2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much :) . I added the function and it is working fine with check constraint .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.