I have some problem to design a good algorithm which use specification of psycopg2 library described here
I want to build a dynamic query equal to this string :
The proper way is to use psycopg2 2.7's new sql module which includes an Identifier object. This allows you to dynamically specify SQL identifiers in a safe way.
Unfortunately 2.7 is not on PyPi yet (2.6.2 as of writing).
Until then, psycopg2 cover this under the heading "How can I pass field/table names to a query?" http://initd.org/psycopg/docs/faq.html#problems-with-type-conversions
You can pass SQL identifiers in along with data values to the execute function by using the AsIs function.
Note: this provides NO security. It is as good as using a format string, which is not recommended.
The only real advantage of this is you encourage future code to follow the execute + data style. You can also easily search for AsIs in future.
from psycopg2.extensions import AsIs
with transaction() as cur:
# WARNING: not secure
cur.execute('SELECT * from %(table)s', {'table': AsIs('mytable')})