pythonpostgresqlpsycopg2psycopg3

Named argument passed as a dict: SyntaxError: syntax error at or near "%" or SyntaxError: type modifiers must be simple constants or identifiers


I'm facing some troubles when trying to execute a PostgreSQL CREATE TABLE query with a dictionary of parameters using psycopg:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov  1 09:32:32 2024

@author: me
"""

import psycopg

pg_uri = "postgres://postgres:******@localhost:5432/mydatabase"
conn_dict = psycopg.conninfo.conninfo_to_dict(pg_uri)
conn = psycopg.connect(**conn_dict)
curs = conn.cursor()

d = {"CRS": 4326}
raw = "CREATE TABLE foo (id INT, geom geometry('Point',%(CRS)s));"

query0 = psycopg.sql.SQL(raw).format(**d)
query1 = psycopg.sql.SQL(raw.format(**d))
query2 = psycopg.sql.SQL(raw)

curs.execute(query0) # SyntaxError: syntax error at or near "%"
curs.execute(query1) # SyntaxError: syntax error at or near "%"
curs.execute(query2,d) # SyntaxError: type modifiers must be simple constants or identifiers

The curs.execute() calls either raise:

Relevant pieces of documentation

https://www.psycopg.org/psycopg3/docs/basic/params.html

Version Info

Python: 3.10
psycopg: 3.2.3
PostgreSQL: 16


Solution

  • As the documentation for SQL.format states, SQL.format uses the same placeholder syntax as str.format, i.e. {CRS} and not %(CRS)s.

    d = {"CRS": 4326}
    raw = "CREATE TABLE foo (id INT, geom geometry('Point',{CRS}));"
    
    query0 = psycopg.sql.SQL(raw).format(**d)