Dynamic columns in asyncpg fetch query

54 Views Asked by At

I want to execute a select query with asyncpg where the columns to be selected depends on some variable. For example:

        columns=["some_col_12", "another_col_51"]  # Set from outside
        result = await connection.fetch(
            rf"""
            SELECT 
                a_fixed_column,
                { ','.join(columns) }
            FROM table
            """
        )

This feels VERY unsafe, since the passed columns are vulnerable of injection.

I tried something with prepared statements, but doing i.e. fetch("SELECT $1","sample_col") returns the constant string 'sample_col' and not that column.

Any recommendation about how to achieve this?

0

There are 0 best solutions below