pgschema icon indicating copy to clipboard operation
pgschema copied to clipboard

Failure dropping a table and a related constraint, when the constraint is included in the cascading drop of the table

Open cysp opened this issue 8 months ago • 1 comments

To reproduce, apply these two schema documents in sequence:

CREATE TABLE a (id bigint PRIMARY KEY, b_id bigint);

CREATE TABLE b (id bigint PRIMARY KEY);

ALTER TABLE a ADD CONSTRAINT "a_b_id_fkey" FOREIGN KEY ("b_id") REFERENCES "b" ("id");
CREATE TABLE a (id bigint PRIMARY KEY);

Applying the second schema plans correctly but fails with this output:

Plan: 1 to modify, 1 to drop.

Summary by type:
  tables: 1 to modify, 1 to drop

Tables:
  ~ a
    - b_id (column)
    - a_b_id_fkey (constraint)
  - b

DDL to be executed:
--------------------------------------------------

DROP TABLE IF EXISTS b CASCADE;

ALTER TABLE a DROP CONSTRAINT a_b_id_fkey;

ALTER TABLE a DROP COLUMN b_id;

Do you want to apply these changes? (yes/no): yes

Applying changes...

Executing group 1/1...
  Executing 3 statements in implicit transaction
Error: failed to execute concatenated statements in group 1: ERROR: constraint "a_b_id_fkey" of relation "a" does not exist (SQLSTATE 42704)

(The cascading drop of table b has already dropped constraint a_b_id_fkey by the time that drop is executed.)

cysp avatar Mar 29 '26 11:03 cysp

Potentially related but also potentially not if it's a significantly different cause: a constraint that needs to be reconfigured due to its source column being dropped is planned for an explicit drop after its column has implicitly dropped it. This change plans correctly if the constraint is renamed.

CREATE TABLE a (id bigint PRIMARY KEY, revision bigint);

CREATE TABLE b (id bigint PRIMARY KEY);

ALTER TABLE a ADD CONSTRAINT "a_revision_fkey" FOREIGN KEY ("revision") REFERENCES "b" ("id");
CREATE TABLE a (id bigint PRIMARY KEY, current_revision bigint);

CREATE TABLE b (id bigint PRIMARY KEY);

ALTER TABLE a ADD CONSTRAINT "a_revision_fkey" FOREIGN KEY ("current_revision") REFERENCES "b" ("id");
Plan: 1 to modify.

Summary by type:
  tables: 1 to modify

Tables:
  ~ a
    + current_revision (column)
    - revision (column)
    - a_revision_fkey (constraint)
    + a_revision_fkey (constraint)

DDL to be executed:
--------------------------------------------------

ALTER TABLE a DROP COLUMN revision;

ALTER TABLE a ADD COLUMN current_revision bigint;

ALTER TABLE a DROP CONSTRAINT a_revision_fkey;

ALTER TABLE a
ADD CONSTRAINT a_revision_fkey FOREIGN KEY (current_revision) REFERENCES b (id) NOT VALID;

ALTER TABLE a VALIDATE CONSTRAINT a_revision_fkey;

Do you want to apply these changes? (yes/no): yes

Applying changes...

Executing group 1/1...
  Executing 5 statements in implicit transaction
Error: failed to execute concatenated statements in group 1: ERROR: constraint "a_revision_fkey" of relation "a" does not exist (SQLSTATE 42704)

cysp avatar Mar 29 '26 21:03 cysp