We have tables like this:
people_people (
"id" integer...
"attributes" HSTORE
)
object_permission (
"permissions" JSON
)
An example of an object_permission.permissions
is:
{"matricule":{"authorized_keys": ["12"],
"unauthorized_keys": ["1", "2", "20"]},
"departement":{"authorized_keys": ["it"],
"unauthorized_keys": ["finance", "account"]},
"access":{"authorized_keys": ["superuser", "user", "login"],
"unauthorized_keys": ["web"]}}
From these data, I'd like to generate the query:
SELECT * FROM people_people
WHERE
(attributes->'matricule' IN ["12"]) AND
(attributes->'departement' IN ["it"]) AND
(attributes->'access' IN ["superuser", "user", "login"]);
How to generate dynamic WHERE
clause based on a JSON field?
I don't want to use dynamic SQL because of the possible SQL injection.
Best Answer
Here is a small example to prove my point:
Now taking your JSON as an example, we can do something like this:
The actual output is to describe what to expect from above:
If we move the necessary part to a condition, it will work nicely:
Notes:
CREATE TABLE
statements, a syntactically correct JSON snippet and a query that actually can run.