literal_binds: a string literal containing %(name)s is rendered as '?' (qmark) or '%%s' (format) in 2.x
Describe the bug
When a statement is compiled with literal_binds=True for a dialect whose paramstyle is qmark or format, a string literal whose text contains %(name)s is rewritten: '%(k)s' becomes '?' (qmark, e.g. SQLite) or '%%s' (format, e.g. MySQL). The rendered SQL then compares against a different value and silently returns the wrong rows. pyformat (PostgreSQL) is not affected, and SQLAlchemy 1.4.54 renders all three correctly.
It looks like SQLCompiler._process_positional applies _positional_pattern to the whole compiled string, including the text of string literals rendered inline.
Optional link from https://docs.sqlalchemy.org which documents the behavior that is expected
No response
SQLAlchemy Version in Use
2.0.52 and 2.1.1 (1.4.54 is not affected)
DBAPI (i.e. the database driver)
sqlite3 (stdlib)
Database Vendor and Major Version
SQLite 3.50.4
Python Version
3.11
Operating system
Linux
To Reproduce
import sqlalchemy as sa
from sqlalchemy.dialects import mysql, postgresql
engine = sa.create_engine("sqlite://")
t = sa.Table("t", sa.MetaData(), sa.Column("x", sa.String))
t.create(engine)
with engine.begin() as c:
c.execute(t.insert(), [{"x": "%(k)s"}, {"x": "?"}])
stmt = sa.select(t.c.x).where(t.c.x == "%(k)s")
sql = str(stmt.compile(engine, compile_kwargs={"literal_binds": True}))
print(sql)
with engine.connect() as c:
print(c.exec_driver_sql(sql).fetchall())
for d in (mysql.dialect(), postgresql.dialect()):
print(stmt.compile(dialect=d, compile_kwargs={"literal_binds": True}))Error
No exception. Output on 2.0.52 and 2.1.1 (whitespace collapsed):
SELECT t.x FROM t WHERE t.x = '?'
[('?',)]
SELECT t.x FROM t WHERE t.x = '%%s' -- mysql
SELECT t.x FROM t WHERE t.x = '%%(k)s' -- postgresqlThe same script on 1.4.54:
SELECT t.x FROM t WHERE t.x = '%(k)s'
[('%(k)s',)]
SELECT t.x FROM t WHERE t.x = '%%(k)s'
SELECT t.x FROM t WHERE t.x = '%%(k)s'Additional context
Applications that render SQL with literal_binds and execute it (for example BI tools that show and run the generated query) are affected for any user-supplied filter value containing %(...)s.
Source: sqlalchemy/sqlalchemy