【问题标题】:Executing SQL query with variable number of named parameters in Golang在 Golang 中使用可变数量的命名参数执行 SQL 查询
【发布时间】:2017-09-27 18:37:33
【问题描述】:

所以我有这个 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

【问题讨论】:

  • 您使用什么数据库驱动程序与 postgres 对话?
  • @mkopriva linkpq

标签: sql database postgresql go


【解决方案1】:

您可以通过枚举所有参数及其占位符来构造您的一个语句,然后您可以在没有参数值的地方显式传递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"})

【讨论】:

  • 它可以工作,但你能解释一下nil是如何在postgres中翻译成命名参数的吗?考虑到将参数分配给类型,我预计 postgres 会抛出某种错误,这是意料之中的。
  • 我相信nil 被翻译成NULL 并且像SELECT read_user(_id := 2, _phone := NULL, _type := NULL...) 这样调用postgres 函数是有效的。
  • 这个解决方案也适用于 go 的雪花实现 :) godoc.org/github.com/snowflakedb/gosnowflake
  • @Pat - 您的评论在 7 小时后解决了我的问题。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多