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

Yak*_*ash 5 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
) 
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;
Run Code Online (Sandbox Code Playgroud)

所以我可以运行这样的多态查询:

SELECT read_user(_id := 2);
SELECT read_user(_first := 'John', _last := 'Doe');
Run Code Online (Sandbox Code Playgroud)

在 Golang 中我可以做类似的事情:

stmt, err := db.Prepare("SELECT read_user(_id = ?)")
Run Code Online (Sandbox Code Playgroud)

但是我怎样才能做同样的事情,但参数数量不同呢read_user?我正在使用pq驱动程序https://github.com/lib/pq

mko*_*iva 4

您可以通过枚举所有参数及其占位符来构建一条语句,然后您可以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')`
Run Code Online (Sandbox Code Playgroud)

如果您也想在 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"})
Run Code Online (Sandbox Code Playgroud)