Faking database migrations in Alembic
Originally posted 2016-10-06
This is a short post documenting a workaround for faking initial migrations in Alembic.
Alembic and other database schema migration tools offer ways to automatically generate and apply schema migrations in series. When beginning to use Alembic on an existing database, you’ll want to create an initial migration that reproduces the existing state of the database. But you’ll also want to fast-forward past that migration - since the database table already exists. Django’s South accomplishes this with a flag
I could not find an analogous method in Alembic, so I got around it by having Alembic dump the SQL it would have executed to run the initial migration. At the very end of this long SQL dump, it had a SQL query I could execute to set the migration state.
$ python manage.py db upgrade 9c1e52a780a7 --sql BEGIN; CREATE TABLE alembic_version ( version_num VARCHAR(32) NOT NULL ); CREATE TABLE go_server ( ) ... # more CREATE TABLE statements ... ... INSERT INTO alembic_version (version_num) VALUES ('9c1e52a780a7'); COMMIT;
I copied the query
INSERT INTO alembic_version (version_num) VALUES ('9c1e52a780a7');, opened a psql shell, and manually ran just that line. After that, Alembic will think that it has already applied the initial migration.