2014-10-07 87 views
1

有沒有辦法將hashmap(或類似的數據類型)作爲參數傳遞給postgres函數?POSTGRES:函數接受一個hashmap或類似的參數作爲參數

我想獲得一個函數,可以接受不同的號碼。在不同情況下的論點。我不想傳遞與特定調用者無關的參數的零或0。

什麼,我想實現示例(原諒的僞代碼)

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

有沒有辦法在Postgres而言,要實現這一目標?

+2

退房'hstore' http://www.postgresql.org/docs/current/static/hstore.html – 2014-10-07 17:34:43

回答

1

對於您的用例,您可以使用hstore或兩個數組或二維數組。你的例子很好地演示了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) 

接着可能性的函數默認參數使用。這是我個人最喜歡的:

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) 
相關問題