How to pass list of columns or * (all columns) to dynamic SQL query with psycopg2.sql

Question:

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”

Asked By: bjk

||

Answers:

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"
Answered By: klin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.