Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Golang中使用可变数量的命名参数执行SQL查询_Sql_Database_Postgresql_Go - Fatal编程技术网

在Golang中使用可变数量的命名参数执行SQL查询

在Golang中使用可变数量的命名参数执行SQL查询,sql,database,postgresql,go,Sql,Database,Postgresql,Go,所以我有一个PostgreSQL函数,它接受不同数量的命名参数,并返回相应项的列表: CREATE OR REPLACE FUNCTION read_user( _id BIGINT DEFAULT NULL, _phone VARCHAR(30) DEFAULT NULL, _type VARCHAR(15) DEFAULT NULL, _last VARCHAR(50) DEFAULT NULL, _first VARCHAR(50) DEFAULT NULL ) RE

所以我有一个PostgreSQL函数,它接受不同数量的命名参数,并返回相应项的列表:

CREATE OR REPLACE FUNCTION read_user(
  _id BIGINT DEFAULT NULL,
  _phone VARCHAR(30) DEFAULT NULL,
  _type VARCHAR(15) DEFAULT NULL,
  _last VARCHAR(50) DEFAULT NULL,
  _first VARCHAR(50) DEFAULT NULL
) 
RETURNS setof T_USERS
AS $$ 
BEGIN
  RETURN QUERY
  SELECT * FROM T_USERS
  WHERE ( id = _id OR _id IS NULL )
    AND ( phone = _phone OR _phone IS NULL )
    AND ( type = _type OR _type IS NULL )
    AND ( last = _last OR _last IS NULL )
    AND ( first = _first OR _first IS NULL );
    EXCEPTION WHEN others THEN
      RAISE WARNING 'Transaction failed and was rolled back';
      RAISE NOTICE '% %', SQLERRM, SQLSTATE;
END
$$ LANGUAGE plpgsql;
因此,我可以运行以下多态查询:

SELECT read_user(_id := 2);
SELECT read_user(_first := 'John', _last := 'Doe');
在Golang,我可以制作如下内容:

stmt, err := db.Prepare("SELECT read_user(_id = ?)")

但是我如何才能做同样的事情,但是要使用不同数量的
read\u user
参数?我使用的是
pq
驱动程序。

您可以通过枚举所有带有占位符的参数来构造一条语句,然后可以在没有参数值的地方显式传递
nil

stmt, err := db.Prepare("SELECT read_user(_id := $1, _phone := $2, _type := $3, _last := $4, _first := $5)")
if err != nil {
    // ...
}
stmt.Query(2, nil, nil, nil, nil) // result should be equivalent to `SELECT read_user(_id := 2)`
stmt.Query(nil, nil, nil, "Doe", "John") // result should be equivalent to `SELECT read_user(_first := 'John', _last := 'Doe')`
如果还希望在Go中包含命名参数,可以创建一个结构类型来表示参数,并创建一个包装函数,将该参数类型的字段映射到查询中:

type readUserParams struct {
    Id    interface{}
    Phone interface{}
    Type  interface{}
    Last  interface{}
    First interface{}
}

func readUser(p *readUserParams) {
    stmt.Query(p.Id, p.Phone, p.Type, p.Last, p.First)
    // ...
}

readUser(&readUserParams{Id: 2})
readUser(&readUserParams{First: "John", Last:"Doe"})

您使用什么db驱动程序与postgres对话?@mkopriva pqIt可以工作,但您能否解释一下
nil
如何转换为postgres中的命名参数?考虑到将参数分配给类型,我希望postgres会抛出某种错误,这是不期望的。我相信
nil
会被转换为
NULL
,并像这样调用postgres函数
SELECT read\u user(\u id:=2,\u phone:=NULL,\u type:=NULL…)
有效。此解决方案也适用于go的雪花实现:)