I’m trying to create a query using Pycopg2
‘s SQL String Composition which in I need to use a curly brackets inside my query to update a key value in a jsonb column. Something like this:
update myschema.users set data = jsonb_set(data, '{someId}', '100')
This is how I’m trying to write this query using Sql Composition string in Python:
statement = SQL(
"UPDATE {schema}.{table} set data = jsonb_set(data, '{{key}}', '{value}') {where};"
).format(
schema=Identifier(schema_var),
table=Identifier(table_var),
key=SQL(id_key),
value=SQL(id_value),
where=SQL(where),
)
But by running this, a new key called key
will be added in the jsonb value. and if I try to run it with just one pair of curly brackets like this:
statement = SQL(
"UPDATE {schema}.{table} set data = jsonb_set(data, '{key}' ...." # The rest is the same
I get this error:
Array value must start with "{" or dimension information
How can I fix this?
2
Answers
To solve this issue I needed to use three nested curly brackets like this:
This way, the
someId
key will actually gets updated in the database.You are over thinking this.
Load data into table:
The values for the
jsonb_set()
should be passed in as parameters not as part of the composition process.UPDATE
Using same
sql_str
and assigning the values to variables.