sqlalchemy icon indicating copy to clipboard operation
sqlalchemy copied to clipboard

Using unique in a returning with sentinel looses the sentinel filter

Open CaselIT opened this issue 2 years ago • 5 comments

This is likely an edge case, but it's still a bug

import sqlalchemy as sa

metadata = sa.MetaData()
t = sa.Table(
    "t",
    metadata,
    sa.Column("id", sa.Integer, primary_key=True),
    sa.Column("data", sa.String(20)),
)

e = sa.create_engine(
    "postgresql+psycopg2://scott:[email protected]:5432/test"  # , echo=True
)
with e.connect() as c:
    metadata.create_all(c)

    r = c.execute(
        t.insert().returning(t.c.data, sort_by_parameter_order=True),
        [{"data": "a"}, {"data": "b"}],
    )
    print(r.all())
    r = c.execute(
        t.insert().returning(t.c.data, sort_by_parameter_order=True),
        [{"data": "a"}, {"data": "b"}],
    )
    print(r.unique().all())

the above prints

[('a',), ('b',)]
[('a', 3), ('b', 4)]

while it should print [('a',), ('b',)] twice.

The issue is likely that CursorResult does not set sentinel_filter as the tuple filter of the metadata

CaselIT avatar Dec 29 '23 12:12 CaselIT

This happens in any case where "generative" is used, so also if using yield_per(1) instead of unique()

CaselIT avatar Dec 29 '23 12:12 CaselIT

seems simple to fix

nobody would notice this if it requires sort_by_parameter_order to happen because nobody is using that parameter directly

zzzeek avatar Dec 29 '23 14:12 zzzeek

interestingly the processors already take into consideration the _num_sentinel_cols so if at least a column defines one the result is correct (since at the moment the length of the processors is used to define the length of the data)

CaselIT avatar Dec 29 '23 18:12 CaselIT

Federico Caselli has proposed a fix for this issue in the main branch:

Improve handling of sentinel columns https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/5039

sqla-tester avatar Dec 29 '23 21:12 sqla-tester

Federico Caselli has proposed a fix for this issue in the rel_2_0 branch:

Improve handling of sentinel columns https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/5040

sqla-tester avatar Dec 31 '23 11:12 sqla-tester