问题
When deploying an application to a fresh server (i.e. the database is empty) how do I sync the database properly with Flask-Migrate?
I've added Flask-Migrate to the project when I already had some schema in place so I don't have "initial" migrations with all create_table()
. Now when I do manage.py db upgrade
in my deployment script I get relation "..." does not exist
.
Is there any built-in way to detect empty database and run 'create_all()' instead of migrations? This is what the Alembic's Cookbook suggests. Since I'm using Flask-Migrate already I'm looking for some unified way of dealing with migrations.
回答1:
The ideal solution is that you generate an initial migration for your db schema as it was the day you started tracking migrations with Flask-Migrate and Alembic.
Doing this is simple if you remember to do it at the time. Just create a separate empty database (leave your real db alone), configure your app to use the empty database, and then generate a migration. This migration will have the entire schema. Once you have that migration generated, get rid of the empty database and restore your configuration back to the real db.
If you already have additional migrations then it gets a little bit more complicated. You will have to go back to the version of your code where you want to generate the initial migration, then follow the above procedure to generate it. Finally, you will need to insert the initial migration in the migration list as the first one. Look at a few of the migration scripts to figure out how each migration references the previous one. A couple of small edits should get you up and running.
If this seems like too much work, then the other alternative is that you use db.create_all()
to generate the database up to the latest migration, and then ./manage.py db stamp head
to tell Alembic that it should consider the database updated.
来源:https://stackoverflow.com/questions/36069353/how-to-sync-db-with-flask-migrate-in-a-fresh-application-deployment