From: Denis Laxalde Date: Tue, 20 May 2025 13:55:44 +0000 (+0200) Subject: Use pg_index's indnatts when indnkeyatts is not available X-Git-Url: http://git.ipfire.org/gitweb/gitweb.cgi?a=commitdiff_plain;h=refs%2Fpull%2F12611%2Fhead;p=thirdparty%2Fsqlalchemy%2Fsqlalchemy.git Use pg_index's indnatts when indnkeyatts is not available Using NULL when this column is not available does not work with old PostgreSQL (tested on version 9.6, as reported in #12600). Instead, use `indnatts` which should be equal to what `indnkeyatts` would be as there is no "included attributes" in the index on these old versions (but only "key columns"). From https://www.postgresql.org/docs/17/catalog-pg-index.html: * `indnatts`, "The total number of columns in the index [...]; this number includes both key and included attributes" * `indnkeyatts`, "The number of key columns in the index, not counting any included columns [...]" Fixes #12600. --- diff --git a/doc/build/changelog/unreleased_20/12600.rst b/doc/build/changelog/unreleased_20/12600.rst new file mode 100644 index 0000000000..99d8b6bba1 --- /dev/null +++ b/doc/build/changelog/unreleased_20/12600.rst @@ -0,0 +1,6 @@ +.. change:: + :tags: bug, postgresql + :tickets: 12600 + + Fix query for unique and primary key constraints reflection on PostgreSQL 10 + and below. diff --git a/lib/sqlalchemy/dialects/postgresql/base.py b/lib/sqlalchemy/dialects/postgresql/base.py index ee4a168e37..3d0fff2890 100644 --- a/lib/sqlalchemy/dialects/postgresql/base.py +++ b/lib/sqlalchemy/dialects/postgresql/base.py @@ -4110,7 +4110,7 @@ class PGDialect(default.DefaultDialect): if self.server_version_info >= (11, 0): indnkeyatts = pg_catalog.pg_index.c.indnkeyatts else: - indnkeyatts = sql.null().label("indnkeyatts") + indnkeyatts = pg_catalog.pg_index.c.indnatts.label("indnkeyatts") if self.server_version_info >= (15,): indnullsnotdistinct = pg_catalog.pg_index.c.indnullsnotdistinct @@ -4585,7 +4585,7 @@ class PGDialect(default.DefaultDialect): if self.server_version_info >= (11, 0): indnkeyatts = pg_catalog.pg_index.c.indnkeyatts else: - indnkeyatts = sql.null().label("indnkeyatts") + indnkeyatts = pg_catalog.pg_index.c.indnatts.label("indnkeyatts") if self.server_version_info >= (15,): nulls_not_distinct = pg_catalog.pg_index.c.indnullsnotdistinct