Skip to content

fix: add a duplicate index constraint after CREATE TABLE instead of inline (#446) - #708

Merged
tianzhou merged 1 commit into
pgplex:mainfrom
cmaster11:fix/duplicate-index-constraint
Nov 17, 2026
Merged

tianzhou merged 1 commit into
pgplex:mainfrom
cmaster11:fix/duplicate-index-constraint

Conversation

@cmaster11

@cmaster11 cmaster11 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

A table can have two keys on the same column, for example a primary key and a unique key. When pgschema writes such a table as one CREATE TABLE, PostgreSQL silently keeps only one of the two keys. This PR writes the second key as a separate statement, so that both keys survive.

Problem

PostgreSQL removes a PRIMARY KEY, UNIQUE or EXCLUDE constraint from a CREATE TABLE when its index equals an earlier one in the same statement (transformIndexConstraints in src/backend/parser/parse_utilcmd.c). It keeps the primary key first. ALTER TABLE ... ADD CONSTRAINT does not remove it.

pgschema writes all these constraints inside CREATE TABLE, in dump and in the CREATE TABLE step of plan. Thus such a constraint is lost: a plan of the dump against the source database drops it, and drops and adds again each foreign key that uses its index. The dump does not round trip. This is the case of #446. That issue is closed, but its fix is not on main, and v1.14.1 still has the bug.

Before and after

The database (PostgreSQL 17):

CREATE TABLE p (code text NOT NULL);
ALTER TABLE p ADD CONSTRAINT p_code_key UNIQUE (code);
ALTER TABLE p ADD CONSTRAINT p_pkey PRIMARY KEY (code);
CREATE TABLE c (code text REFERENCES p (code));

Each binary ran pgschema dump against it, and then pgschema plan --file <that dump> against the same database. "main" is a build of main (6377a12), "this PR" a build of this branch. Each command exits with 0 and takes under 1 s with both builds.

pgschema dump:

--- dump (main)
+++ dump (this PR)
@@ -12,9 +12,10 @@
 
 CREATE TABLE IF NOT EXISTS p (
     code text,
-    CONSTRAINT p_pkey PRIMARY KEY (code),
-    CONSTRAINT p_code_key UNIQUE (code)
+    CONSTRAINT p_pkey PRIMARY KEY (code)
 );
+ALTER TABLE p
+ADD CONSTRAINT p_code_key UNIQUE (code);
 
 --
 -- Name: c; Type: TABLE; Schema: -; Owner: -

pgschema plan --file <the dump>:

--- plan of the dump (main)
+++ plan of the dump (this PR)
@@ -1,25 +1 @@
-Plan: 2 to modify.
-
-Summary by type:
-  tables: 2 to modify
-
-Tables:
-  ~ c
-    - c_code_fkey (constraint)
-    + c_code_fkey (constraint)
-  ~ p
-    - p_code_key (constraint)
-
-DDL to be executed:
---------------------------------------------------
-
--- Transaction Group #1
-ALTER TABLE c DROP CONSTRAINT c_code_fkey;
-
-ALTER TABLE p DROP CONSTRAINT p_code_key;
-
-ALTER TABLE c
-ADD CONSTRAINT c_code_fkey FOREIGN KEY (code) REFERENCES p (code) NOT VALID;
-
--- Transaction Group #2
-ALTER TABLE c VALIDATE CONSTRAINT c_code_fkey;
+No changes detected.

Fix

  • The CREATE TABLE step inlines the first constraint of each index key. It adds each later constraint with the same key with ALTER TABLE ... ADD CONSTRAINT in the same step. Thus a multi-file dump writes it in the file of the table, and it runs in the same transaction.
  • The key holds the fields that PostgreSQL compares: the key columns in order (with WITHOUT OVERLAPS), the INCLUDE columns, NULLS NOT DISTINCT, DEFERRABLE and INITIALLY DEFERRED, or the definition of an EXCLUDE constraint without its storage parameters, which PostgreSQL does not compare.
  • The comment of such a constraint follows its ALTER TABLE.
  • Both paths of generateTableSQL (a normal table and PARTITION OF) use one function for the constraints now.

Tests

  • internal/diff/constraint_duplicate_test.go: a round trip over dump, dump with --qualify-schema and a first migration, for a primary key with a duplicate unique (with a comment), two equal uniques, equal deferrable uniques, equal EXCLUDE constraints (also with different storage parameters) and a partition child. It also checks that near matches stay inline: (a, b) against (b, a), INCLUDE, DEFERRABLE against INITIALLY DEFERRED, and NULLS NOT DISTINCT. Each generated script is applied again and must give an empty migration.
  • testdata/diff/create_table/issue_446_duplicate_index_constraint/: a new table with a primary key, a duplicate unique, two equal uniques, and a table with a foreign key to it. Before the fix, the repeated plan of TestPlanAndApply was not empty.
  • testdata/diff/create_table/issue_446_duplicate_index_constraint_unchanged/: the same schema on both sides gives an empty plan.
  • testdata/dump/issue_446_duplicate_index_constraint/ with TestDumpCommand_Issue446DuplicateIndexConstraint.

The expected output of each existing test is unchanged. go test ./... passes.

🤖 Generated with Claude Code

…#446)

PostgreSQL drops a PRIMARY KEY, UNIQUE or EXCLUDE constraint of CREATE
TABLE when its index equals an earlier one (transformIndexConstraints in
parse_utilcmd.c). ALTER TABLE ADD CONSTRAINT keeps it. The dump and the
CREATE TABLE step of a plan inlined such a constraint, so it was lost: a
plan of the dump against the source database dropped the constraint and
recreated each foreign key that used it.

The CREATE TABLE step now inlines the first constraint of each index key
and adds each duplicate with ALTER TABLE in the same step. The key holds
the fields that PostgreSQL compares: the key columns in order (with
WITHOUT OVERLAPS), the INCLUDE columns, NULLS NOT DISTINCT, DEFERRABLE
and INITIALLY DEFERRED, or the EXCLUDE definition without its storage
parameters, which PostgreSQL does not compare. The constraint
comment follows the ALTER TABLE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cmaster11
cmaster11 marked this pull request as ready for review November 17, 2026 04:29
Copilot AI balanced review requested due to automatic review settings November 17, 2026 04:29
@greptile-apps

greptile-apps Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge.

Summary

Preserves duplicate index-backed constraints by adding them after CREATE TABLE instead of placing them inside it.

  • Duplicate index constraints are added after the table is created.

No actionable issues found. Tests were inspected but not run during this review.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Order table constraints] --> B{Same index key already inline?}
  B -->|No| C[Keep inside CREATE TABLE]
  B -->|Yes| D[Queue ALTER TABLE ADD CONSTRAINT]
  C --> E[Emit CREATE TABLE]
  D --> F[Emit queued ALTER TABLE statements]
  E --> F
  F --> G[Emit constraint comments]
Loading

Reviews (1) · Last reviewed commit: "fix: add a duplicate key after CREATE TA..." · Reviewed by Greptile

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues block the change to preserve duplicate index-backed constraints in dumps and initial migrations.

No open issues 🎉

What changed in this PR

This PR addresses #446 by preserving duplicate index-backed constraints in pgschema dumps and initial migrations, preventing PostgreSQL from silently removing them during CREATE TABLE.

Changes:

  • Detects equivalent PRIMARY KEY, UNIQUE, and EXCLUDE index definitions and emits duplicates as subsequent ALTER TABLE statements.
  • Shares constraint generation between regular tables and partitions, preserving constraint comments.
  • Adds round-trip tests and fixtures for duplicate constraints, distinct index definitions, and unchanged schemas.
File Description
testdata/​dump/​issue_446_duplicate_index_constraint/​raw.sql Defines the duplicate-constraint dump fixture.
testdata/​dump/​issue_446_duplicate_index_constraint/​pgschema.sql Records expected dump output with separate constraint additions.
testdata/​dump/​issue_446_duplicate_index_constraint/​pgdump.sql Provides reference PostgreSQL dump output.
testdata/​dump/​issue_446_duplicate_index_constraint/​manifest.json Documents the regression fixture.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint/​plan.txt Records expected human-readable creation plan.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint/​plan.sql Records expected migration SQL.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint/​plan.json Records expected structured plan steps.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint/​old.sql Supplies an empty starting schema.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint/​new.sql Defines desired duplicate constraints and a referencing table.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint/​diff.sql Records expected constraint-preserving diff SQL.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint_unchanged/​plan.txt Expects no changes after round-trip.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint_unchanged/​plan.sql Expects an empty SQL plan.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint_unchanged/​plan.json Expects no execution groups.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint_unchanged/​old.sql Defines the existing duplicate-constraint schema.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint_unchanged/​new.sql Expresses the equivalent schema in dump format.
testdata/​diff/​create_table/​issue_446_duplicate_index_constraint_unchanged/​diff.sql Expects an empty schema diff.
internal/​diff/​table.go Emits duplicate constraints after table creation through shared logic.
internal/​diff/​qualify_schema_test.go Adapts tests to the multi-statement return value.
internal/​diff/​constraint.go Adds index-definition keys for duplicate detection.
internal/​diff/​constraint_duplicate_test.go Tests round-trip preservation and distinct constraint variants.
cmd/​dump/​dump_integration_test.go Registers the dump regression test.

Review effort: Balanced

@tianzhou tianzhou left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks for the contribution.

@tianzhou
tianzhou merged commit 4ff615c into pgplex:main Nov 17, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants