pgsql: Fix ADD PRIMARY KEY after dropping and re-adding a column

From: Fujii Masao <fujii(at)postgresql(dot)org>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Fix ADD PRIMARY KEY after dropping and re-adding a column
Date: 2026-10-06 04:15:10
Message-ID: E1xDwa6-00000000V33-41x9@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Fix ADD PRIMARY KEY after dropping and re-adding a column

Previously, dropping a NOT NULL column, adding a new column with the same
name, and making it a primary key in a single ALTER TABLE command could
fail with "primary key column ... is not marked NOT NULL". This happened
because ALTER TABLE checked for an existing NOT NULL constraint before
dropping the old column. Finding the constraint caused it to skip adding
one for the new column, even though the old constraint would be removed
with the old column.

Defer this check until after column drops and additions have been
executed, so that it examines the columns that will actually form the
primary key. Add any required NOT NULL constraints before creating the
primary-key index.

Backpatch to v18, where this issue was introduced by commit a379061a22a.

Reported-by: Ludvig Janiuk <ludvig(dot)janiuk(at)proton(dot)me>
Author: Fujii Masao <masao(dot)fujii(at)gmail(dot)com>
Co-authored-by: Manuel Reyes Bravo <manuelreyesbravo(at)gmail(dot)com>
Discussion: https://postgr.es/m/0a9b4c44-cdff-4ec8-a8fb-b3a8b59e9ba9@proton.me
Backpatch-through: 18

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/dd97e0c8e3823690653cd555090e01fafbb33a85

Modified Files
--------------
src/backend/commands/tablecmds.c | 35 +++++++++++++++++++++----------
src/test/regress/expected/alter_table.out | 25 ++++++++++++++++++++++
src/test/regress/sql/alter_table.sql | 26 +++++++++++++++++++++++
3 files changed, 75 insertions(+), 11 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Fujii Masao 2026-10-06 04:15:27 pgsql: Fix ADD PRIMARY KEY after dropping and re-adding a column
Previous Message Richard Guo 2026-10-06 02:00:27 pgsql: Don't reprocess PHV copies within outer aggregates' arguments