所以我有这个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。
答案 0 :(得分:2)
您可以通过使用占位符枚举所有参数来构建您的一个声明,然后您可以明确地将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"})