Creating “zero state” migration for existing db with sqlalchemy/alembic and “faking” zero migration for that existing db

alembic revision --autogenerate inspects the state of the connected database and the state of the target metadata and then creates a migration that brings the database in line with metadata.

If you are introducing alembic/sqlalchemy to an existing database, and you want a migration file that given an empty, fresh database would reproduce the current state- follow these steps.

  1. Ensure that your metadata is truly in line with your current database(i.e. ensure that running alembic revision --autogenerate creates a migration with zero operations).

  2. Create a new temp_db that is empty and point your sqlalchemy.url in alembic.ini to this new temp_db.

  3. Run alembic revision --autogenerate. This will create your desired bulk migration that brings a fresh db in line with the current one.

  4. Remove temp_db and re-point sqlalchemy.url to your existing database.

  5. Run alembic stamp head. This tells sqlalchemy that the current migration represents the state of the database- so next time you run alembic upgrade head it will begin from this migration.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)