乐闻世界logo
搜索文章和话题

How to call postgres stored procedure from golang using gorm package

1个答案

1

Calling PostgreSQL stored procedures from Go using the gorm package is a relatively straightforward process. First, ensure that you have correctly installed and imported the gorm package in your Go project. The following are the steps to call PostgreSQL stored procedures from Go:

Step 1: Installation and Importing the gorm Package

Ensure that your Go project has the gorm package and the PostgreSQL driver installed, typically pgx or pq. You can install them with the following commands:

bash
go get -u gorm.io/gorm go get -u gorm.io/driver/postgres

Import them into your Go file:

go
import ( "gorm.io/gorm" "gorm.io/driver/postgres" )

Step 2: Connecting to the PostgreSQL Database

First, configure the database connection. Here is an example of a connection string:

go
dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable" db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil { panic("failed to connect database") }

Step 3: Defining the Stored Procedure

Assume that you have already defined a stored procedure in the PostgreSQL database. For example, a simple stored procedure for querying user information by a specific ID:

sql
CREATE OR REPLACE FUNCTION get_user_info(userId INT) RETURNS TABLE(name VARCHAR, age INT) AS $$ BEGIN RETURN QUERY SELECT name, age FROM users WHERE id = userId; END; $$ LANGUAGE plpgsql;

Step 4: Calling the Stored Procedure from Go

Now, use gorm's native SQL execution capability to call this stored procedure. Execute the stored procedure with the Raw method and scan the results:

go
var result []struct { Name string Age int } db.Raw("SELECT * FROM get_user_info(?)", 1).Scan(&result) for _, user := range result { fmt.Printf("Name: %s, Age: %d\n", user.Name, user.Age) }

Here, get_user_info(?) is the stored procedure, and 1 is the parameter passed to it, representing the user ID. Using the Scan method, we map the results to a slice of structs, where each struct represents user information.

Summary

Using gorm to call PostgreSQL stored procedures involves combining the Raw and Scan methods to execute native SQL and handle returned results. This approach is not only suitable for calling stored procedures but also for executing any custom SQL queries. Adjust the code according to the specific logic and return types of the stored procedure in practical applications.

2024年8月12日 17:42 回复

你的答案