Search code examples
pythonpostgresqlpsycopg2

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


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"


Solution

  • 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"