सरल plpgsql आधारित समाधान नहीं हैं। कुछ संभावित समाधान:
hstoreका इस्तेमाल करना विस्तार।
CREATE TYPE footype AS (a int, b int, c int);
postgres=# select row(10,20,30);
row
------------
(10,20,30)
(1 row)
postgres=# select row(10,20,30)::footype #= 'b=>100';
?column?
-------------
(10,100,30)
(1 row)
hstore आधारित कार्य बहुत सरल हो सकता है:
create or replace function update_fields(r anyelement,
variadic changes text[])
returns anyelement as $$
select $1 #= hstore($2);
$$ language sql;
postgres=# select *
from update_fields(row(10,20,30)::footype,
'b', '1000', 'c', '800');
a | b | c
----+------+-----
10 | 1000 | 800
(1 row)
- कुछ साल पहले मैंने एक एक्सटेंशन pl टूलबॉक्स
लिखा था . एक फ़ंक्शन है
record_set_fields:
pavel=# select * from pst.record_expand(pst.record_set_fields(row(10,20),'f1',33)); name | value | typ ------+-------+--------- f1 | 33 | integer f2 | 20 | integer (2 rows)
शायद आप कुछ plpgsql केवल सिस्टम टेबल और सरणियों के साथ कुछ ट्रिक्स के आधार पर समाधान पा सकते हैं जैसे यह
, लेकिन मैं इसका सुझाव नहीं दे सकता। यह बहुत कम पठनीय है और उन्नत उपयोगकर्ता के लिए केवल काला जादू नहीं है। hstore सरल और लगभग हर जगह है इसलिए इसे प्राथमिकता दी जानी चाहिए।
PostgreSQL 9.4 (शायद 9.3) पर आप JSON जोड़तोड़ के साथ काला जादू करने की कोशिश कर सकते हैं:
postgres=# select json_populate_record(NULL::footype, jo)
from (select json_object(array_agg(key),
array_agg(case key when 'b'
then 1000::text
else value
end)) jo
from json_each_text(row_to_json(row(10,20,30)::footype))) x;
json_populate_record
----------------------
(10,1000,30)
(1 row)
इसलिए मैं फ़ंक्शन लिखने में सक्षम हूं:
CREATE OR REPLACE FUNCTION public.update_field(r anyelement,
fn text, val text,
OUT result anyelement)
RETURNS anyelement
LANGUAGE plpgsql
AS $function$
declare jo json;
begin
jo := (select json_object(array_agg(key),
array_agg(case key when 'b' then val
else value end))
from json_each_text(row_to_json(r)));
result := json_populate_record(r, jo);
end;
$function$
postgres=# select * from update_field(row(10,20,30)::footype, 'b', '1000');
a | b | c
----+------+----
10 | 1000 | 30
(1 row)
JSON आधारित फ़ंक्शन भयानक तेज़ नहीं होना चाहिए। hstore तेज़ होना चाहिए।