I had a requirement like, I need to form a query based on JSONB object parameter and returns its output.
JSONB parameter contains Table name, where clause details, Column value to be returned form a table.
Below is the sample format of JSONB where getjsontesterabledata is the function which takes JSONB as parameter.
select getjsontesterabledata('{"MODULE": "TEST",
"TEST_INFO": {
"AGGREGATE_OP": "",
"RESULT_ATTRIB_NAME": "TESTER_VALUE",
"CONDITIONAL_ATTRIBS": [
{"VALUE": "98842", "ATTRIBUTE": "TEST_ID", "CONDITION_OP": "="},
{"VALUE": "DRIVE", "ATTRIBUTE": "TEST_NAME", "CONDITION_OP": "="}]
}}');
In above JSONB param, MODULE is table name , AGGREGATE_OP is like SUM, AVG … , CONDITIONAL_ATTRIBS are like where clause.
From the above JSONB parameter, Query formation should be like
select TESTER_VALUE
from test
where TEST_ID = 98842 and TEST_NAME = 'DRIVE';
and this query output should be returned.
Here i am stuck at forming a Query from JSONB Parameter specifically in forming a where clause. I need help on this.
Please note that PostgreSQL version is 12.15.
2
Answers
Basically here it is. Pls. note the formation of the
where
clause andcoalesce
-ing the text totrue
if there is no data for "CONDITIONAL_ATTRIBS".Please also note that this looks very much like a SQL injection nightmare and only makes sense if the input parameter data do not come from user input.
The result is
You can make a loop using
jsonb_array_elements(data_json->'TEST_INFO'->'CONDITIONAL_ATTRIBS')
.You can see this function working in dbfiddle.
Some resources used:
Postgresql looping through query results
Postgresql json functions documentation
Postgresql create function documentation
Postgresql concat documentation