Expanded IN parameter overwrites a bind named <name>_1 in the same query
Describe the bug
When a statement has an expanding IN parameter and another bind parameter whose name equals one of the generated element names (<name>_1, <name>_2, ...), the IN element value silently replaces the other parameter's value. Anonymous bind names are predictable, so two columns named a and a_1 are enough: a IN (...) expands to a_1_1, a_1_2 and the anonymous bind for a_1 = 5 is also a_1_1. The query returns wrong rows with no error.
Optional link from https://docs.sqlalchemy.org which documents the behavior that is expected
No response
SQLAlchemy Version in Use
2.1.5
DBAPI (i.e. the database driver)
pysqlite (also shown compiling for psycopg2)
Database Vendor and Major Version
SQLite
Python Version
3.12
Operating system
Linux
To Reproduce
import sys
import sqlalchemy as sa
from sqlalchemy import Column, Integer, MetaData, Table, bindparam, select
from sqlalchemy.dialects import postgresql
print("python:", sys.version.split()[0])
print("SQLAlchemy:", sa.__version__)
m = MetaData()
t = Table(
"t",
m,
Column("id", Integer, primary_key=True),
Column("a", Integer),
Column("a_1", Integer),
)
e = sa.create_engine("sqlite://")
m.create_all(e)
with e.begin() as conn:
conn.execute(t.insert(), [dict(id=1, a=1, a_1=5), dict(id=2, a=2, a_1=7)])
stmt = select(t.c.id).where(t.c.a.in_([1, 2]), t.c.a_1 == 5)
with e.connect() as conn:
print("observed:", conn.execute(stmt).all())
print("expected: [(1,)]")
# the same statement on PostgreSQL, before and after expansion
c = stmt.compile(dialect=postgresql.dialect())
print(c, c.params)
st = c.construct_expanded_state()
print(st.statement, st.parameters)
# explicit names collide the same way
stmt2 = select(t.c.id).where(
t.c.a.in_(bindparam("x", [1, 2], expanding=True)),
t.c.a_1 == bindparam("x_1", 5),
)
with e.connect() as conn:
print("observed:", conn.execute(stmt2).all())
print("expected: [(1,)]")
Error
python: 3.12.3
SQLAlchemy: 2.1.5
observed: []
expected: [(1,)]
SELECT t.id
FROM t
WHERE t.a IN (__[POSTCOMPILE_a_1]) AND t.a_1 = %(a_1_1)s::INTEGER {'a_1': [1, 2], 'a_1_1': 5}
SELECT t.id
FROM t
WHERE t.a IN (%(a_1_1)s::INTEGER, %(a_1_2)s::INTEGER) AND t.a_1 = %(a_1_1)s::INTEGER {'a_1_1': 1, 'a_1_2': 2}
observed: []
expected: [(1,)]
No exception is raised. After expansion t.a_1 is compared against 1 (the first IN element) instead of 5, so the query returns no rows. Swapping the order of the two criteria gives the same result.
Additional context
Expected: both queries return [(1,)], and a_1_1 keeps the value 5 after expansion.
I traced it at main (f26a7c27e). _literal_execute_expanding_parameter in lib/sqlalchemy/sql/compiler.py (lines 3625-3629) names the expanded elements "%s_%s" % (name, i), and _process_parameters_for_postcompile merges them into the parameter dict with parameters.update(to_update) at line 2250 without checking for names the statement already uses. Positional paramstyles are affected too: on SQLite (qmark) the expanded positiontup is ['a_1_1', 'a_1_2', 'a_1_1'], so both slots resolve to the same key. The naming goes back to 1.4.0.
A possible fix is to generate the expansion names so they cannot collide with any existing bind name in the compiled statement, for example by uniquifying them against self.binds and the escaped names the same way _escaped_bind_name does, or by using a separator that bind name sanitizing never produces. A regression test with columns a and a_1 would cover it.
If this is accepted I can send a PR once the issue is open for pull requests.
Hi, I'd like to work on this one. The root cause is in SQLCompiler._literal_execute_expanding_parameter: expanding IN element bind names (<name>_1, <name>_2, ...) are generated without checking against other bind names in the statement, so parameters.update(to_update) in _process_parameters_for_postcompile silently overwrites the colliding parameter. My planned fix threads the set of taken bind names through and disambiguates generated element names on collision (appending _1, _2, ... until free), keeping to_update and the replacement expression consistent. I've verified it locally against current main (the issue's repro now returns the expected rows, and the full test/sql/ suite passes). Would you consider adding the open for pull requests label? Thanks!
Mike Bayer has proposed a fix for this issue in the main branch:
uniquify expanded IN element names against other bind names https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/7088
Mike Bayer has proposed a fix for this issue in the rel_2_0 branch:
uniquify expanded IN element names against other bind names https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/7090