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



因此,我拥有此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_user参数?我正在使用pq驱动程序https://github.com/lib/pq。

您可以通过枚举 asl 及其占位符的参数来构建一个语句,然后您可以在没有参数值的地方明确传递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中命名参数,则可以创建一个结构类型来表示参数和包装器func,该函数将映射该参数类型的字段中的concor:

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"})

最新更新