简体   繁体   English

POSTGRES:函数接受哈希图或类似类型作为参数

[英]POSTGRES: function accepting a hashmap or similar type as argument

Is there a way to pass hashmap (or similar data type) to a postgres function as an argument? 有没有一种方法可以将哈希图(或类似的数据类型)作为参数传递给Postgres函数?

I am trying to get a function that can accept different no. 我正在尝试获得可以接受不同编号的函数。 of arguments in different cases. 在不同情况下的论点。 And I dont want to pass nulls or 0's for those arguments that are not relevant to a particular caller. 而且我不想为那些与特定调用者无关的参数传递null或0。

Example of what I am trying to achieve (excuse the pseudocode) 我尝试实现的示例(对不起,伪代码)

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

Is there a way to achieve this in postgres? 有没有办法在postgres中实现这一目标?

For your use case, you can use a hstore or two arrays, or 2D array. 对于您的用例,可以使用一个hstore或两个数组或2D数组。 Your example is nice demonstration of SQL injection, so you should not to forget on necessary escaping. 您的示例很好地演示了SQL注入,因此您不要忘记必要的转义。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM