Fix: Failed migration incorrectly marked as applied #4509
+135
−38
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Closes: #4521
🐛 Issue Summary
In certain cases, a migration that should fail inside a transaction (e.g., due to violating a newly-added constraint) is still being:
Applied to the database, and
Recorded inside schema_migrations,
While the Supabase dashboard reports it as “Failed”.
This results in partial / inconsistent application of the migration file and breaks Supabase’s migration safety guarantees.
The issue appears to stem from the migration executor not correctly propagating SQL transactional errors in some edge cases involving ALTER TABLE ... ADD CONSTRAINT, generated columns, or multi-statement migration files.
✅ What This PR Changes
Ensures that any SQL error inside a migration file is:
Correctly captured
Causes a full transaction rollback
Prevents the migration from being marked as applied
Errors now bubble up reliably from the Postgres wire protocol layer.
CLI and API will no longer falsely report:
“Migration failed”
While still committing parts of the migration.
Ensures the schema_migrations insert only happens after a successful transaction commit.
Ensures executor failure paths never call the migration-completed hook.
Test cases that verify:
Constraint violation → rollback → file NOT applied
Multi-statement migration rollback behavior
Generated column + check constraint edge case
🧪 How the Bug Was Reproduced (Based on User Report)
A migration containing:
new table creation
generated columns
multiple ALTER TABLE operations
new CHECK constraints
…would partially apply, even though a constraint violation should have caused a rollback.
This PR addresses exactly this scenario.
🛠️ Implementation Notes
Updated migration execution wrapper to treat all SQLSTATE codes ≥ 40000 as rollback-worthy.
Removed early return conditions that ran before transaction abort detection.
Ensured error logs do not trigger a false “migration applied” completion flow.
📎 Linked Issue
https: //github.com/supabase/supabase/issues/40761