문제

I have a table with below schema :

CREATE TABLE tbl_name (
id bigserial primary key,
phone_info json
);

Sample json data for phone_info column is given below .

 {  
   "STATUS":{"1010101010":"1","2020202020":"1"},
   "1010101010":"OK", 
   "2020202020":"OK"  
 }

Now I need to add a check constraint on phone_info column so that all key for "STATUS" ie(1010101010,2020202020) should exist as a (key,value) pair of phone_info column where value would be "OK". So above sample data would satisfy the check constraint as there are following key value pair exists in phone_info column.

"1010101010":"OK"
"2020202020,":"OK" 

I have tried below solution but this has not worked because array_agg function is not supported with check constraints.

ALTER TABLE tbl_name
ADD CONSTRAINT validate_info CHECK ('OK' = ALL(array_agg(phone_info->json_object_keys(phone_info->'STATUS'))) ); 

Can someone please help me out , Can I write a SQL function and use the function in check constraint?

도움이 되었습니까?

해결책

With something like this I think you'll want an SQL function.

CREATE TABLE tjson AS SELECT '{  
   "STATUS":{"1010101010":"1","2020202020":"1"},
   "1010101010":"OK", 
   "2020202020":"OK"  
 }'::json AS col;

perhaps something like:

CREATE OR REPLACE FUNCTION my_json_valid(json) RETURNS boolean AS $$
SELECT bool_and(coalesce($1->>k = 'OK','f'))
FROM json_object_keys($1->'STATUS') k;
$$ LANGUAGE sql IMMUTABLE;

... but remember that while PostgreSQL will let you modify that function, doing so can cause previously valid rows to become invalid in the table. Never modify this function without dropping the constraint then adding it back again.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top