In <i>psycopg2</i>, variables can be inserted into queries using <i>%s</i> placeholders and supplying arguments to <i>cursor.execute</i>, but this does not allow for identifier arguments such as table or columns names. The alternative is to use <i>psycopg2.sql.SQL.format</i>, but this requires arguments to be converted into <i>Composable</i> objects such as <i>Literal</i> or <i>Identifier</i>.<p>With <i>TemplateQuery</i>, instead of wrapping arguments with <i>psycopg2.sql</i> classes (e.g. <i>Literal</i>, <i>Identifier</i>) the expected class can be written inside the query:<p><pre><code> >>> TemplateQuery('SELECT * FROM {table@Q} WHERE {@I} {@S} {value@L}').format(
... 'column_name', '>=', table='public.my_table', value=100
... ).as_string(conn)
'SELECT * FROM "public"."my_table" WHERE "column_name" >= 100'
</code></pre>
The character after the at sign <i>@</i> in the placeholder key is the transformation that is applied to the argument before inserting it into the placeholder (<i>S</i> for raw SQL, <i>I</i> for Identifiers and <i>L</i> for literals, among others).<p>I wrote this small library while working on my master's thesis to help run similar analysis queries on different tables and schema configurations, without the mental overhead of wrapping arguments in the proper classes. I'm not sure if it will be useful to anyone, but I thought it was worth releasing. Would appreciate any feedback at all!