Database Migrations in Dart-land
Overview
If there’s one thing my coworkers would say about me, it’s that I’m a little obsessed with figuring out how to make Dart work on the backend; One of my primary focuses has been on finding a solid ORM with migrations.
Why? For me, there are two main reasons:
Writing the same CRUD operations for every entity is tedious, time-consuming, and error-prone
Schema changes should be tracked in VC and be synchronized with your entity models
After a lot of trial-and-error, I finally felt that there wasn’t an ORM available that really suited me. So, fine, I will write the SQL queries and handle serialization/deserialization myself (with the help of codegen, anyway).
However, that still doesn’t address my desire for a migration system. Pair this with my recent inclination to make the tools I need instead of waiting for someone else to do it and, ta-da: dart_migrator!
It’s still in its early phases and hasn’t been published to pub.dev yet, but the idea is that: I will write the SQL queries and maintain the models, I will even write the migration queries, but dart_migrator
will handle running the migrations as needed.
Basic Usage
Installation
Install dart_migrator
to your package’s dev dependencies (for now, directly from GitHub)
Creating a migration
Use the dart_migrator
CLI to create a new migration:
The “n” flag is required and represents the “name” of your new migration.
The result of this command will be a new folder:
In this folder will be empty up.sql
and down.sql
files. Write your changes in the up.sql
file; write the inverse of these changes in down.sql
.
Running migrations
Once you have new migrations, use the CLI tool to run all pending migrations against your database.
The “env” flag signifies that the tool should look for a DATABASE_URL
key in a .env
file in your root directory. If you don’t have a .env
file or would rather pass the URL on the command-line, use the “url” flag.
dart_migrator
will look for new migrations, tracked by the migrations
table (created and maintained by the CLI tool).
Configuration
The tool can be configured using a dart_migrator.yaml
file in the root of your project.
There is still a lot of work to do, but this fills a gap in the Dart ecosystem for me and I hope it helps you, too!