Skip to content
Sarj Code Standards

psycopg-sql-format-field-mismatch

Give psycopg SQL.format an argument for every replacement field.

Why

psycopg SQL.format reads every unescaped brace in the template as a replacement field and raises on the first field it cannot fill: IndexError for a missing positional argument, KeyError for a missing keyword, and ValueError for unmatched braces, format specs, conversions, or mixed automatic and numbered fields. The call fails every time it runs. Braces that belong to the SQL text, such as an empty JSON object '{}', are the usual cause. Ruff F521-F525 check str.format literals only.

Fix

Write braces that belong to the SQL text as {{ and }}. For a real field, pass the missing positional or keyword argument, use one numbering style, and drop format specs and conversions.

Examples

Before — flagged An empty JSON object in SQL text is read as a positional field
app/report.py
from psycopg.sql import SQL
def report_query(where):
return SQL("SELECT COALESCE(data, '{}') FROM calls {where}").format(where=where)
After — preferred Escaped braces stay SQL text
app/report.py
from psycopg.sql import SQL
def report_query(where):
return SQL("SELECT COALESCE(data, '{{}}') FROM calls {where}").format(where=where)
Before — flagged A named field has no keyword argument
app/report.py
from psycopg import sql
def report_query(table):
return sql.SQL("SELECT * FROM {table} {where}").format(table=table)
After — preferred Every named field has a keyword argument
app/report.py
from psycopg import sql
def report_query(table, where):
return sql.SQL("SELECT * FROM {table} {where}").format(table=table, where=where)