I'm using psycopg2.sql to generate query strings dynamically.
I want to be able to pass either a list of columns or an * (for all columns) to the same SELECT query string dynamically.
This works for a list of columns:
qry = sql.SQL('SELECT {} FROM {}.{}').format(
sql.SQL(",").join(map(sql.Identifier, ["col1","col2"])),
sql.Identifier('schema'),
sql.Identifier('table'))
But this doesn't work when trying to select all columns:
qry = sql.SQL('SELECT {} FROM {}.{}').format(
sql.Identifier('*')),
sql.Identifier('schema'),
sql.Identifier('table'))
The error I receive is "DatabaseError: Execution failed on sql … column "*" does not exist"
sql.Identifier('*')
generates "*"
:
SELECT "*" FROM "schema"."table"
Use the basic SQL Composable:
qry = sql.SQL('SELECT {} FROM {}.{}').format(
sql.SQL('*'),
sql.Identifier('schema'),
sql.Identifier('table'))
to get
SELECT * FROM "schema"."table"