1

I have a raw SQL statement to be executed using SqlAlchemy. The query contains this:

FROM unnest(array['sku1', 'sku2', 'sku3'])

Building the query manually, I could not find a way to escape each parameter manually.

I tried doing:

session.execute("... FROM unnest(array[:skus]) ...", {'skus': skus})

but:

ProgrammingError: (ProgrammingError) a column definition list is required for functions returning "record"
LINE 21:         FROM unnest(array[('sku1', 'sku2', '...
                      ^

2 Answers 2

2

A Python tuple is adapted to a Postgresql record and a list adapted to an array. That is why in this case a tuple is not valid.

But what you say in your own answer that works does not:

select unnest(['BA007EWCBD43', "KA036'AGHF550", 'KA036ACBK873']);
ERROR:  syntax error at or near "["
LINE 1: select unnest(['BA007EWCBD43', "KA036'AGHF550", 'KA036ACBK87...

Or you mean

FROM unnest(ARRAY['BA007EWCBD43', "KA036'AGHF550", 'KA036ACBK873'])

The parameters should never be manually escaped. Let it to the driver.

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

2 Comments

yes, you're right. that's because I had a custom logger that printed this. Do you know a method to see the real query that goes to the SQL server instead of ... FROM unnest(%(skus)s) ... INFO 2014-09-02 15:21:10,419 sqlalchemy.engine.base.Engine {'skus': ['IN002EWKU161', 'FA003BMAYD09', "NI464E'WFA620", 'NI464EWCI491']}? But not using server logs?
@warvariuc I don't know how to get the final sql query other than reading the server log. But the sqlalchemy people sure know.
0

Ok, if I put a list of skus (not a tuple), everything is fine:

session.execute("... FROM unnest(:skus) ...", {'skus': ['BA007EWCBD43', 'KA036\'AGHF550', 'KA036ACBK873']})

Which generates:

FROM unnest(['BA007EWCBD43', "KA036'AGHF550", 'KA036ACBK873'])

Though a function to manually quote parameters would is still needed for other cases.

Comments

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.