gpt4 book ai didi

sql - Postgres : function accepting a hashmap or similar type as argument

转载 作者:搜寻专家 更新时间:2023-10-30 23:47:42 25 4
gpt4 key购买 nike

有没有办法将 hashmap(或类似数据类型)作为参数传递给 postgres 函数?

我正在尝试获得一个可以接受不同编号的函数。不同情况下的论据。我不想为那些与特定调用者无关的参数传递空值或 0。

我正在尝试实现的示例(请原谅伪代码)

function(hashmap map) {
condition = 'where ';
for (entry : map) {
condtion = condition || map.key || '=' || map.value;
}
sql := sql || condition;
//execute sql
}

有没有办法在 postgres 中实现这一点?

最佳答案

对于您的用例,您可以使用一个 hstore 或两个数组,或二维数组。您的示例很好地演示了 SQL 注入(inject),因此您不应忘记必要的转义。

CREATE OR REPLACE FUNCTION hstore_params(filters hstore)
RETURNS text AS $$
BEGIN
RETURN 'SELECT * FROM some_table ' ||
coalesce ('WHERE ' ||
( SELECT string_agg(quote_ident(key) || ' = ' || quote_literal(value), ' and ')
FROM each('c1 => Ahoj, c2 => Nazdar'::hstore). '') );
END;
$$ LANGUAGE plpgsql;
postgres=# SELECT hstore_params('c1 => Ahoj, c2 => Nazdar');                        hstore_params                         -------------------------------------------------------------- SELECT * FROM some_table WHERE c1 = 'Ahoj' and c2 = 'Nazdar'(1 row)

Next possibility is usage of function default parameters. It is my personal favorite:

CREATE OR REPLACE FUNCTION hstore_params(c1 text DEFAULT NULL, c2 text DEFAULT NULL)
RETURNS text AS $$
BEGIN
EXECUTE 'SELECT *
FROM xx
WHERE (c1 = $1 OR c1 IS NULL)
AND (c2 = $2 OR c2 IS NULL)'
USING c1, c2;
RETURN 'ok';
END;
$$ LANGUAGE plpgsql;
postgres=# SELECT hstore_params(); hstore_params --------------- ok(1 row)postgres=# SELECT hstore_params('Ahoj','Nazdar'); hstore_params --------------- ok(1 row)postgres=# SELECT hstore_params('Ahoj'); hstore_params --------------- ok(1 row)postgres=# SELECT hstore_params(c2 := 'Ahoj'); hstore_params --------------- ok(1 row)

关于sql - Postgres : function accepting a hashmap or similar type as argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26241785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com