Database Migrations
2 min read ยท last updated at- Laravel (https://laravel.com/docs/migrations)
- Symfony (https://symfony.com/bundles/DoctrineMigrationsBundle)
- Rails (https://guides.rubyonrails.org/active_record_migrations.html)
- Django (https://docs.djangoproject.com/en/4.2/topics/migrations/)
- Phoenix (https://hexdocs.pm/phoenix/ecto.html#using-the-schema-and-migration-generator)
- FastAPI (https://alembic.sqlalchemy.org/en/latest/tutorial.html)
- DotNet (https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations)
- Vapor (https://docs.vapor.codes/fluent/migration/)
- Play (https://www.playframework.com/documentation/3.0.x/Evolutions)
- Spring (third party? Either flyway or liquibase)
- Several Go Libs?
Relational databases define a schema for the data they persist. Database migrations helps with deterministically creating and editing of this schema.
Manually Editing The Schema
A user
in your app might have an email
, a password
and an id
used for internal references.
Imagine you already have a local, staging and production database with the described user
table.
Now due to a new feature, users also need to have a name
that they can be referred to, since it is more personal than using their email
.
One could simply use a database GUI, edit the table, which would generate something like the query below.
Nice, now your local database has the new column and you can develop the code relying on that new column. When deploying your new code, you now need to rember to also apply those changes to stagig and later to production. Annoying, but maybe doable if you are the only one developing changes and you deploy frequently. Nearly impossible in the context of a team that develops multiple features simultaneously, many of which require changes to the schema. Luckily, many frameworks include database migration tools out of the box that helps you automate all of this.
Working With Migrations
When using a tool for database migrations, you usually create a file representing your changes and check that into version control. The tool then applies the changes in the file and stores an entry somewhere stating that these changes were successfully applied to the schema. When we tell the tool again to execute all migrations, it knows that it does not need to run the migration we created again.
This was just a high-level overview of how migrations work. The next sections dive into more detail and provide examples for each framework.
Creating The File
Most frameworks have a designated folder containing timestamped files representing the migrations.
Files in these folders often contain classes or functions
Note that we do not explicitly create the id
column here.
Rails does that by default.
- Writing the files by hand
- Link ORMs and create a concept
Listing The Migration Status
Applying The Migrations
Advanced topics
- Conflict resolution (alembic has the merge stuff)
- Seed data