user2990084
user2990084

Reputation: 2840

Preserve data in migrations

With this setup:

-Development environment
-Flask
-SQLAlchemy
-Postgres
-Possibility Alembic

If I have a database with some tables populated with random data. As far as I know the Flask-Migrate, that will use Alembic, will not preserve the data, only keep the models and database synchronized.

But what is the difference between the use of Alembic or just delete > create all tables?

Something like:

db.create_all()

The second question:

What happens to the data when something change in models? The data will be lost? Or the Alembic can preserve the previous populated data?

Well, my idea is just populate the database with some data, and then avoid any lost of data when the models change. Alembic is the solution?

Or I need to import the data, from a .sql file, for example, when I change the models and database?

Upvotes: 3

Views: 3197

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67479

I am the Flask-Migrate author.

You are not correct. Flask-Migrate (through Alembic) will always preserve the data that you have in your database. That is the whole point of working with database migrations, you do not want to lose your data.

It seems you already have a database with data in it and you want to start using migrations. You have two options to incorporate Flask-Migrate into your project:

  1. Only track migrations going forward, i.e. leave your initial database schema outside of migration tracking.

    For this you really have nothing special to do. Just do manage.py db init to create the migrations repository and when you need to migrate your database do so normally with manage.py db migrate. The disadvantage of this method is that Flask-Migrate/Alembic do not have the initial schema of the database, so it is not possible to recreate a database from scratch.

  2. Implement an initial migration that brings your database to your current state, then continue tracking future migrations normally.

    This requires a little bit of trick. Here you want Alembic to record an initial migration that defines your current schema. Since Alembic creates migrations by comparing your models to your database, the trick is to replace your real database with an empty database and then generate a migration. After the initial migration is recorded, you restore your database, and from then on you can continue migrating your database normally.

I hope this helps. Let me know if you have any more questions.

Upvotes: 17

Related Questions