Skip to content

add check against using NOT VALID, VALIDATE in same transaction#97

Merged
kodiakhq[bot] merged 12 commits intomasterfrom
chris/not-valid-validate-in-transaction
Feb 15, 2021
Merged

add check against using NOT VALID, VALIDATE in same transaction#97
kodiakhq[bot] merged 12 commits intomasterfrom
chris/not-valid-validate-in-transaction

Conversation

@chdsbd
Copy link
Collaborator

@chdsbd chdsbd commented Feb 15, 2021

Adding a constraint as NOT VALID and running VALIDATE CONSTRAINT in the same transaction is equivalent to adding the constraint without NOT VALID. Reads will be blocked while the table is scanned to validate the constraint.

The solution is to add the constraint as NOT VALID in one transaction and VALIDATE CONSTRAINT in a separate transaction.

Example bad migration

BEGIN;
ALTER TABLE "app_email" ADD CONSTRAINT "fk_user" FOREIGN KEY (user_id) REFERENCES "app_user" (id) NOT VALID;
ALTER TABLE "app_email" VALIDATE CONSTRAINT "fk_user";
COMMIT;

Example warning

stdin:1:0: warning: constraint-missing-not-valid

   1 | BEGIN;
   2 | ALTER TABLE "app_email" ADD CONSTRAINT "fk_user" FOREIGN KEY (user_id) REFERENCES "app_user" (id) NOT VALID;
   3 | ALTER TABLE "app_email" VALIDATE CONSTRAINT "fk_user";
   4 | COMMIT;

  note: Using NOT VALID and VALIDATE CONSTRAINT in the same transaction will block all reads while the constraint is validated.
  help: Add constraint as NOT VALID in one transaction and VALIDATE CONSTRAINT in a separate transaction.

Fixed SQL

BEGIN;
ALTER TABLE "app_email" ADD CONSTRAINT "fk_user" FOREIGN KEY (user_id) REFERENCES "app_user" (id) NOT VALID;
COMMIT;
BEGIN;
ALTER TABLE "app_email" VALIDATE CONSTRAINT "fk_user";
COMMIT;

Result

Found 0 issues in 1 file 🎉

@chdsbd chdsbd changed the base branch from master to chris/ref-span February 15, 2021 19:54
Base automatically changed from chris/ref-span to master February 15, 2021 20:14
kodiakhq bot pushed a commit that referenced this pull request Feb 15, 2021
This allows us to be more general in how we report errors with statements. I need this refactor for #97.
@chdsbd chdsbd requested a review from sbdchd February 15, 2021 21:30
@chdsbd chdsbd marked this pull request as ready for review February 15, 2021 21:30
@sbdchd sbdchd added the automerge automerge with kodiak label Feb 15, 2021
@kodiakhq kodiakhq bot merged commit 3f1d8b2 into master Feb 15, 2021
@kodiakhq kodiakhq bot deleted the chris/not-valid-validate-in-transaction branch February 15, 2021 22:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

automerge automerge with kodiak

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants