In a Postgres DB I have a table (Users) which defines users. It is like
|ID| meta |
|01| {"email" : "test1@gmail.com","importance" : "High"} |
|02| {"email" : "test2@gmail.com","importance" : "Medium"}|
As you can see the 'meta' column contains json, for a specific reason. (not changeable)
I would like to create a function, which accepts 3 parameters:
- An email (inc_email)
- A Key (inc_key)
- A Value (inc_value)
It would then search for the record which has a meta containing the e-mail, and it would add the new key-values to the json. But! If the value is empty, it would delete the key-values if they are already there.
Example:
function('test1@gmail.com','security','true')
would result:
|ID| meta |
|01| {"email" : "test1@gmail.com","importance" : "High", "security":"true"} |
Then:
function('test1@gmail.com','security','')
would result:
|ID| meta |
|01| {"email" : "test1@gmail.com","importance" : "High"}|
So far I got to the point where I search the specific record, and I give back the json result, but I am not sure what is the best way to implement this json modification.
declare
ret json;
begin
select array_to_json(array_agg(u.meta)) into ret
from Users u
where meta::text LIKE ('%"email" : "' || inc_email || '%');
return ret;
end;