#13615·sqlalchemy

PostgreSQL reflection drops columns from composite primary keys when a constraint and a commented object share an OID

Author: zzzeekCreated Sep 28, 2026Updated Sep 28, 2026
Labelsbugpostgresqlreflectionregressioncode review in progress

Discussed in https://github.com/sqlalchemy/sqlalchemy/discussions/13614

Originally posted by Elaskinok September 28, 2026

Describe the bug

On PostgreSQL, _constraint_query, _foreing_key_query and _check_constraint_query outer-join pg_description on objoid = pg_constraint.oid alone. OIDs are only unique within one catalog, so a comment on another object with the same OID as a constraint joins too, and the constraint's rows are repeated once per matching comment. #11961 fixed this for _comment_query only.

Since 2.0.41 (#10665), _reflect_constraint takes the first indnkeyatts entries of the aggregated column list as the key and the rest as INCLUDE columns. With repeated rows, composite primary keys and unique constraints lose their trailing columns to postgresql_include. Foreign key and check constraints are returned once per matching comment, so the reflected table gets duplicate constraints.

SQLAlchemy Version in Use

2.0.52 and 2.1.1

DBAPI (i.e. the database driver)

psycopg2 2.9.12

Database Vendor and Major Version

PostgreSQL 17 and 18

Python Version

3.13

Operating system

macOS, PostgreSQL in Docker

To Reproduce

python
import sqlalchemy as sa

engine = sa.create_engine("postgresql+psycopg2://scott:tiger@localhost/test")

with engine.begin() as conn:
    conn.exec_driver_sql("DROP TABLE IF EXISTS t")
    conn.exec_driver_sql("CREATE TABLE t (a INTEGER, b INTEGER, CONSTRAINT t_pkey PRIMARY KEY (a, b))")
    conn.exec_driver_sql("COMMENT ON CONSTRAINT t_pkey ON t IS 'primary key of t'")

    # Force an OID collision: a commented large object with the same OID as t_pkey.
    oid = conn.exec_driver_sql("SELECT oid FROM pg_constraint WHERE conname = 't_pkey'").scalar()
    conn.exec_driver_sql(f"SELECT lo_create({oid})")
    conn.exec_driver_sql(f"COMMENT ON LARGE OBJECT {oid} IS 'unrelated large object'")

print(sa.__version__)
print(sa.inspect(engine).get_pk_constraint("t"))
print([c.name for c in sa.Table("t", sa.MetaData(), autoload_with=engine).primary_key])

Error

No exception, but the primary key is wrong (2.1.1 prints the same):

2.0.52
{'constrained_columns': ['a', 'a'], 'name': 't_pkey', 'comment': 'primary key of t', 'dialect_options': {'postgresql_include': ['b', 'b']}}
['a']

Expected ['a', 'b'] for both constrained_columns and Table.primary_key, with no INCLUDE columns. 2.0.40 also returns duplicates, but its Table.primary_key is right:

2.0.40
{'constrained_columns': ['a', 'a', 'b', 'b'], 'name': 't_pkey', 'comment': 'primary key of t'}
['a', 'b']

Additional context

No large object is needed in practice: pg_upgrade keeps table OIDs but gives the recreated constraints new, low OIDs, so a constraint can end up with the OID of a table that has column comments. Code relying on Table.primary_key then silently gets a truncated key. I can share a script that reproduces this through pg_upgrade.

A possible fix is the condition #11961 added to _comment_query, applied to the three constraint queries:

python
.outerjoin(
    pg_catalog.pg_description,
    sql.and_(
        pg_catalog.pg_description.c.objoid == pg_catalog.pg_constraint.c.oid,
        pg_catalog.pg_description.c.classoid
        == sql.func.cast("pg_catalog.pg_constraint", REGCLASS),
    ),
)

With this applied locally, primary keys, unique constraints, foreign keys and check constraints all reflect correctly under collisions. _columns_query is not affected: it also matches objsubid = attnum, and only column comments have a nonzero objsubid.

Alternatively, selecting pg_catalog.obj_description(pg_constraint.oid, 'pg_constraint') instead of joining avoids the repeated rows and needs no REGCLASS cast, which DuckDB lacks (#12011).

The reproduction needs no superuser, so it could double as a test. I can open a PR if that helps.