Skip to content

Fix spurious DROP TABLE in stamp --sql to base - #1836

Closed
Gooh456 wants to merge 1 commit into
sqlalchemy:mainfrom
Gooh456:fix-stamp-sql-drop-table
Closed

Fix spurious DROP TABLE in stamp --sql to base#1836
Gooh456 wants to merge 1 commit into
sqlalchemy:mainfrom
Gooh456:fix-stamp-sql-drop-table

Conversation

@Gooh456

@Gooh456 Gooh456 commented Jul 24, 2026

Copy link
Copy Markdown

Fixes #1822.

alembic stamp --sql base emits a bare DROP TABLE alembic_version with no matching CREATE TABLE anywhere in the output. Real (non-sql) stamp never drops the version table, it only ever gets created, never dropped.

Root cause is in MigrationContext.run_migrations() (alembic/runtime/migration.py). At the end of the method there's an unconditional if self.as_sql and not head_maintainer.heads: self._version.drop(...). This fires whenever an offline SQL script ends with zero heads, whether that's from stamp or from downgrade/upgrade steps that walk down to base. zzzeek confirmed on the issue this was a coding mistake from way back, added for --sql mode without checking that non-sql mode never does this.

Fix just removes that block so --sql output matches what actually happens against a real database.

This also changes downgrade --sql <rev>:base output, since it shares the same code path and had the same bug (there was an existing test, test_version_to_none, that was actually asserting the buggy DROP was present). Updated that test to assert no DROP, and added test_sql_stamp_to_base_no_drop for the stamp scenario from the issue.

Ran the full tests/test_command.py (116 tests) plus test_version_traversal.py, test_environment.py, test_offline_environment.py locally, all green.

MigrationContext.run_migrations() dropped the alembic_version table
whenever --sql mode ended with zero heads, including for the stamp
command going to "base". Non-sql operation never drops the version
table, only the --sql code path did. That mismatch produced a bare
DROP TABLE statement with no matching CREATE for a plain
"alembic stamp --sql base" that starts from no assumed heads.

Remove the DROP. This also affects downgrade --sql to base which
had the same unconditional drop; updated the existing test for that
to match and added a regression test for the stamp case.

Fixes: sqlalchemy#1822
Signed-off-by: Kyue <164024549+Gooh456@users.noreply.github.com>
@zzzeek

zzzeek commented Jul 24, 2026

Copy link
Copy Markdown
Member

dupe of #1823

@zzzeek zzzeek closed this Jul 24, 2026
@Gooh456

Gooh456 commented Jul 24, 2026

Copy link
Copy Markdown
Author

ah, missed #1823. same fix basically, no worries, all good closing this one.

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.

Stamp command with "base" emits a DROP if --sql mode is present and no head revisions are present

2 participants