Search code examples
symfonydoctrinedatabase-migration

Doctrine migrations start in the middle of the project


I am working with Symfony and Doctrine. In the middle of the project I need to implement the Doctrine migrations, because the DB changes were too much and I need a better way to handle it. How is the best way to start with the migrations, when there is already data on prod and it need to stay there and not to be touched?

My plan will be:

On my test system

  • drop all tables
  • run php bin/console doctrine:migrations:diff
  • The new automatic migration file, which I become holds all the table structures of my current state
  • go live to the table "migration_versions" and add the ID of this migration, so it will be skipped by the first run of the migrations
  • run the migration php bin/console doctrine:migrations:migrate

In this way, I have all the structures from my entities, but I will not destroy my live data.

What do you thing?


Solution

  • If there is already some data on production, then your best take is to do a make:migration or doc:mig:diff from the current schema state. That will generate only the necessary sql that will update the new changes, but nothing else. Your first migration version will countain only the sql to update from the current state, and not from the beginning of times.

    And also, once you have adopted this, you have to do every database modification under migrations. For example, if you need to add a non-nullable field, you usually add the new field with not null, then fill all the rows of that field with a default or calculated one, and then alter the table to make the field not nullable. Migrations will generate some boilerplate code to make your life easier, but it also requires a lot of care from the development team. Always test them first in a database that you can get rid of. And you will run into FK constraints and lots of other issues, but basically you have to solve them doing SQL.