Repository navigation
Description
Summary
One of the core routines of the development experience when using Serverpod is creating and applying migrations to the database. It is also where users face most common conflicts, like local state that diverges from the database and merge conflicts on migrations of different branches. Our tooling in this area is currently very limited and pushes a lot of manual work to developers when such conflicts occur.
The purpose of this RFC is to outline a new set of tools to provide a smooth developer experience when dealing with migrations.
Current pain points
- Merge conflicts are frequent and require the developer to manually delete everything.
- Empty folders left by discarding git changes break the create command.
- Applying migrations requires starting the server.
- Too many generated SQL files that bloat the repository.
- Migration folders pile over time, and cleaning up is manual.
- Lack of a way to abort a pipeline with an error if a migration is missing on a given project.
- The command to apply migrations is not easily discoverable from the tools for newcomers.
- Rolling migrations back is done by creating a repair migration, which is not intuitive.
- No easy way to inspect which migrations were applied to the database (and when).
> Not all of the above pain points will be addressed with the effort we’re going to dedicate now, but this RFC will also serve to collect feedback and suggestions on how to improve every aspect regarding migrations on Serverpod.
Out of scope
The current RFC focuses on the experience when interacting with migrations from the user perspective, but does not aim to change how they are executed when applying. This means that changing the definition files, the migration registry, or the migration SQL generator is out of scope. It is open for improvement on when to generate and how to store them, but without changing their formats.
For reference, a few pain points that are not covered in this RFC are:
- Hooking custom transformation into migrations requires manually editing generated SQL files.
- No way to attach custom Dart scripts/logic to run before/after specific migrations.
- Migrations being registered as a linear history creates frequent conflicts on branch merges.
Proposal
To provide a complete - and centralized - experience with migrations, we could introduce a new migration subcommand on the Serverpod CLI that would contain all commands related to this area. The goal would be to create, apply, rollback, and squash migrations as a part of the same experience. Discovery also improves a lot, since users can always call --help and see all available commands.
Generating SQL
A first fundamental change in the new migration system would be to no longer require generating the SQL previously and to allow generating the SQL on-the-fly when applying the migration. This could be configurable on the generator.yaml for those that prefer always seeing the SQL, but the default would be to only generate the SQL files if the create command is invoked with a --generate-sql flag. The behavior would be:
- If the SQL files exist in the migration folder, applying the migration will use them.
- Otherwise, the required SQL will be generated on the fly from the definition files.
Having the option to generate the SQL files would still allow users to manually edit them when needed. This has several benefits:
- Drastically reduce the bloat in repositories, as migrations tend to grow fast.
- Reduce the complexity of the migration system for newcomers (fewer files to understand).
- Eliminate the need for the already ephemeral repair-migration files (except when requested).
- Get closer to supporting other databases with a migrations folder that is mostly SQL dialect-agnostic.
CLI commands
The following commands would be introduced:
create: Similar to the existingcreate-migrationcommand. By default, generate only the JSON definition files.--forceto allow destructive operations (same as today).--tagto identify the revision (same as today).--emptyto create an empty migration to be manually edited.--dry-runto only show which changes would be generated.--checkto exit with non-zero when there are pending updates to create a migration.--generate-sqlto create the migration with the SQL files.
apply: Applies pending migrations to the database. Solves Apply DB migration via the serverpod CLI command #3119 by decoupling applying the migration from starting the server.--configto specify which database to use (current--mode). Defaults todevelopment.--dry-runto show which changes would be applied.--checkto exit with non-zero when there are pending revisions to apply.
repair: Replaces the currentcreate-repair-migrationcommand. Create and apply the migration to the database on-the-fly, just likeapply(solves Apply DB repair migration via the serverpod CLI command #3120).--configto specify which database to use (current--mode). Defaults todevelopment.--versionto target a specific version. Defaults to the latest revision.--forceto allow destructive operations (same as today).--dry-runto show which changes would be applied.--checkto exit with non-zero when the database is out of sync with the migration system.--create-onlyto only store the migration to apply later.--tagto identify the revision (same as today).--generate-sqlfor also generating the SQL files.
--from-filesto apply a stored repair migration created using--create-only.--pruneto remove non-existing versions from the table registry (like after a squash).
downgrade [version]: Downgrade to a specific version. Usesrepair, as shown in the docs.- If the version is not specified, iteratively list the existing ones for the user to choose.
- Same options as the
repaircommand.
rollback [steps=1]: An alias todowngrade, but operating on N recent migrations.- Same options as the
repaircommand.
- Same options as the
squash: Convenience command to squash migrations into the latest of the range (to preserve the order). If the latest migration has a tag and no tag is specified, the original tag is kept.--fromto specify the start version of the squash range (when not using--older-than).--toto specify the end version of the squash range (when not using--older-than).--older-thanto squash all migrations older than a given version.--tagto identify the generated squash revision (overrides any tag on the latest version).--generate-sqlto create the squashed migration with the SQL files.
cleanup: Removes all migration folders that are not in themigration_registry.txt.rebase: Convenience command to facilitate resolving merge conflicts. Requires the developer to resolve conflicts on themigration_registry.txtfile first. Then, this command will basically callcleanupfollowed bycreate.- Same options as the
createcommand.
- Same options as the
show: Show the existing migrations and their apply status (with timestamp) on the target database.--configto specify which database to use (current--mode). Defaults todevelopment.
Migrations watch
A more seamless experience could be implemented by augmenting the generate --watch command to allow creating and applying migrations locally very quickly while developing. It would be done by support listening to the following keys while the watch mode is running:
mto create a migration that does not contain destructive actions.fto create a migration that contains destructive actions (similar tocreate --force).sto squash the latest changes into the last migration.ato apply the migrations to the local database.
Related issues
- Apply DB migration via the serverpod CLI command #3119
- Apply DB repair migration via the serverpod CLI command #3120
- Allow configuration of output directory for generated migrations #3368
- Add ability to rollback migrations #2207
- Add a default tag of "initial" to the first migration #2208
- Server Folder Naming Restriction Migration Issue (Not a server package) #1846
- Do not explicitly exit the serverpod process after applying migrations #3959
- Create migration should not throw error when the latest migration folder is empty #3985
- Append migration command #4503
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsBacklog 🗂️
Activity
craiglabenz commentedon Jan 17, 2026
Stream of consciousness thoughts, aside from general, wide-ranging excitement. (Also, instead of writing IMO everywhere, know that my level of epistemic certainty on all the following claims is: "in my opinion" 😄)
I think the
defintion.{sql|json}files are the bigger source of friction thanmigration.sql. The current RFC moves in the right direction by making more files be generated on the fly than before, but I think developers would enjoy a bigger win if those files were the definition files; and not the migration files. Interestingly, a brief UX survey of your power users might reveal how often Serverpod developers would still go out of their way to generate themigration.sqlfiles. I know I would every time -- I want to read what changes are being made, for peace of mind if nothing else.My worry about continuing to build around an assumption of concrete definition files is that they will remain forever entrenched in Serverpod's architecture. As the system can generate them quite quickly and they are not used at runtime (thus, that cost is only paid during commands and start up / schema verification), and because developers never modify them (is this correct?), I would vote for a second look at how the
definition.sqlfiles might be made ephemeral and generated on-demand.This is slightly pedantic, but I think
downgradeis a confusing word choice for its current command / role. It means something significantly different from "rollback" as to be a misleading alias. "Downgrading" is more like reverting to an earlier (and presumably worse) version of something; but applying migrations is not "upgrading"; it is merely proceeding and keeping pace with the project's development.Related to the previous point, I don't think that 3 commands to apply migrations are necessary. I believe
serverpod apply [migration_id]should suffice. If nomigration_idis supplied, the command moves all of the way forward. If amigration_idis supplied, the system moves to that point in time; rolling back already applied migrations if necessary.This would come at the DX cost of forcing a developer to lookup their desired
migration_id, but would alleviate navigating 3 separate commands.I would love to see a more human-friendly order identifier than the current timestamps system. Django uses a simple
0001,0002, etc etc progression system which is much easier to scan at a glance; and even remember. I might know off the top of my head that0003added that one important index, but it's very hard to keep that straight when the identifying numbers in question are all 17 digits long.--
Looking to the future, do you have any plans for data migrations / fixtures? I understand why this is not included in the current RFC, because data migrations are deceptively complicated. Other languages with runtime introspection solve this versioning headache by synthetically producing a version of all the database models as they were defined at that point in time, so future people joining the project will still be able to execute them successfully even if the relevant models and classes have since evolved.
However, Dart has no such introspection, meaning to achieve something similar, Serverpod would have to write to disc a snapshot every model for every migration and then pass that version of the database schema into each data migration Dart file. As someone who's trying to do away with definition files, no one should be surprised that I hate that idea.
Another option is that these migration Dart scripts simply have to be updated along with the rest of the codebase as a project advances. For example, if I add a data migration to populate a new column with derived data from other tables and columns, then later modify the new column again; I may have to revisit the original data migration and reason about what it should do for future developers who join the project. (Maybe I soft-delete it by turning it into a no-op, or maybe its logic needs to be updated, etc.)
These updates to old data migrations would be very error-prone; rendering this idea also only okay. However, as the third and only remaining option may be to simply not have data migrations, I think it is still preferable.
If Serverpod were to embrace this thinking and allow developers to write data migrations in Dart and then live with the consequences (aka, update them later as project advancement dictates), then it may not be much scope creep to include them in this RFC.
serverpod migration create --dartcould potentially create amigration.dartfile with aFuture<void> migrate(session)function, instead of amigration.sqlfile, wherein developers could access their models and read/write data as necessary. Of course, schema migrations in these Dart migration files would be a very, very bad idea.abdulah1974 commentedon Jan 19, 2026
I believe it would be very beneficial to add a feature to Serverpod that allows creating a backend-only project without relying on Flutter. This would help Serverpod gain wider adoption and be used in larger projects, as developers could choose any frontend technology they prefer, whether web, mobile, or another framework.
Thank you.
KristijanZic commentedon Jan 20, 2026
A quite a large pain point is that Serverpod doesn't have a separate migration directory for each run mode.
Custom and separate migration directories would greatly simplify development and testing
spaghettigus commentedon Jan 20, 2026
The biggest feature I would like (likely out of scope) would be a way to generate repair migrations without a running server. I use Cloud Run in a vpc, and the only method I can get to work is manual sql scripts and manual changes to migration files.
I don't mind extra commands if it helps isolate concerns (I feel like I have to keep a list of commands anyway).
Appreciate the improvements you all have made lately!
Errechydy commentedon Jan 20, 2026
One thing that i hated when i was playing with Serverpod a while back is when somehow you did a mess with your database migration, you end up in a dead end, no way to do anything, any commend i run i get tons of errors, the only solution that worked is the make a new project and copy past all the files and start over, that happened like more than 6 times.
It will be great if you add "RESET" command that cleans up the project, like delete all the migrations files and only keep the current database schema one (alternative of creating a new project and moving files to it).
Why this is important, flutter devs are not experts in backend or databases management like migrations, they need a reset button kind of command to start over when they mess something up and want a short cut to just make things work again.
remonh87 commentedon Jan 20, 2026
First of all I really like the proposal you have written as it matures the current migration solutions. Also I like the additions that @craiglabenz added to it as this would drastically improve the developer experience. I have a few notes/additions:
Repair and downgrade
Personally I find the repair mechanism tricky. It is often hard for me to review if the repair migration is what I want and the only way to test it is grab a copy of prod run the migration and test everything. I really like how Django does migrations. Every change that you make has also a
reverse()operation. I do know that Django handles migrations in Python and Serverpod in SQL but it could be an approach to explore.**Versioning / merge conflicts in large projects ***
I am a bit doubting about @craiglabenz proposal of
001and002naming for migrations. On one hand I like the simplicity but it can possibly lead to more merge conflicts. Yes Django uses this convention but also the Dependency Graph handles merge conflicts. For example: we have 3 migrations John and Laura are developing on the backend and both create a migration called 4. How Django works is that it creates a migration004_johnand004_lauraand a kind of merge migration called005_merge. If we can achieve this that would be awesome.**Definition sql vs migration **
I like @craiglabenz proposal for generating it more on the fly as it is something that I sometimes forget. Normally running the serverpod tests save me.
Last but not least: the biggest file and inconvenience to me is the defintion.json file as it easily goes to the 1000sLOC and technically you pollute the userspace with internal tooling. If we want to be radical we should go for standard SQL DDL as this is the go to in the market. However less radical solution could be using a more dense file format for your defintions (like yaml):
Before json
{ "tables": [ { "name": "users", "columns": [ { "name": "id", "type": "integer", "isNullable": false, "autoIncrement": true }, { "name": "email", "type": "text", "isNullable": false } ], "indexes": [] } ] }After yaml
Metaildust commentedon Jan 21, 2026
I'm with 'serverpod migration create --dart', and if not in this rfc, i still think it should be included after the current idea is done. Because if we use this, we can immediately check if there's something wrong instead of check it when we are implementing the SQL migration, And spend another whole night to roll back.
why don't we just use this chance of adoption?
craiglabenz commentedon Jan 23, 2026
@remonh87 wrote:
To be clear, I am not proposing that the actual migration logic be generated on the fly. IMO, that is too critical and must be manually reviewed by developers. Even in Django, the migrations are reviewable by the team; it's just that they are fully abstracted away to Python. In Serverpod, I think a concrete
migration.sqlfile should always be created for each migration.What I DO think should move to on-demand generation are all of the
definition.*files used to verify that the codebase and database still agree on the schema. Sinceserverpod create-migrationhas the ability to generate those files in the first place, my proposal is that that same mechanism be used to generate a synthetic definition at verification time. This would remove the need for any definition files to ever be written to disc and committed to version control.@remonh87 wrote:
Django's real secret to migration ordering is that, because each migration is actually Python and not raw SQL, they each designate which migration they follow. Thus, if
004_johnand004_lauraarrive somewhat in rapid succession, whoever merges last can merely declare the other migration as being its predecessor, and the system will work just fine. The numbers are pure convenience; the only thing that actually matters is the in-migration declaration of which migration the given migration follows.Serverpod could technically do something similar by adding a
parent_migration.txtfile which merely shows the unique ID of the preceding migration. Then, all the migration names would be conveniences for the developer and not actually matter. Migrations can even be out of order according to timestamp. For example, at Time-0, John creates amigration_a, and at Time-1, Laura createsmigration_b; but Laura's work is ready first and is merged first; all John has to do is set his parent migration tomigration_band everything would work; even though his timestamp is earlier.@Errechydy wrote:
In my mind,
serverpod migrations apply zero("zero" is a special migration in Django that means even unapply the initial migration) would constitute this RESET command. The developer would then nuke their entire migrations folder, create a new, clean, initial migration, apply it, and continue. This is, of course, only a development phase operation. Once a project is deployed, doing this would cause incredible chaos.@KristijanZic wrote:
I'm curious about this use case. Can you say more about your development setup that this would simplify? I'd like to know more.
marcelomendoncasoares commentedon Feb 26, 2026
Very happy to see all the discussion! Took me a bit to get back here, but I'll try to answer on all topics at once:
The definition files
@craiglabenz The
definition.jsonfile is hard to get rid of because it is generated from the CLI by analyzing the models in that point-in-time. The server can only derive theDatabaseDefinitionfrom the database itself and compare with the definition that lives inside theProtocolclass, but it is not capable of analyzing the models to generate the definition in runtime. And this file is crucial on the migration system to generate the diff between versions and the migration actions.@remonh87 A
yamlcould be an idea to reduce the LOC, but not with dense flags. Because dense flags would eliminate the possibility of adding extra optional fields without breaking the parse of previously existing definition files.Apply, downgrade and rollback commands
@craiglabenz We can replace the
downgradecommand by aversionoption on therollbackcommand, but not onapplysince they behave differently. Whileapplysimply executes the SQL of the pending migration versions,downgradewould rely on therepairmechanism to generate a diff, create the SQL on-the-fly and apply it to the database. This is similar to therollback, so it is possible to bundle both in one that acceptsstepsorversion.The SQL generation for rollback can be replaced by a pre-generated
reversefile, as @remonh87 suggested, but it would mean adding more files to the migration folder instead of reducing the bloat. On the other hand, it does have the advantage of making the rollback process editable and coupled with the migration - which does not occur with using repair migrations.Repair migrations
@remonh87 Although we can generate the
reversefile forrollback, it would not entirely replace therepaircommand, because it also serves the purpose of restoring the migration system once the database is in an inconsistent state. If applied migrations are removed from the codebase, for example, only therepaircommand can bring it back on track.@studioaugustus Creating repair migrations without need for a running server is actually in scope of this RFC. Once we are able to run migrations from the CLI as this RFC proposes, we'll also be able to analyze the database directly instead of depending on an Insights endpoint as we do today - which is the reason for the running server requirement. The #4748 PR was already a step towards the decoupling of the database from the server.
Reset command
@Errechydy The reason why we did not include a
resetcommand is due to the risk of it being misused against a production database and resulting in a catastrophe. But we can evaluate implementing it for development. Technically, it would only be an alias to deleting all entries from themigration_registry.txt, callingcleanupand thencreate.Migration names and versioning
@craiglabenz I agree that a timestamp is not the most human-friendly identifier, but it is semantic with the linear way we store migrations. It also helps spot easily when a migration from another branch lands "in the past" while merging. But you can always create your migrations with a tag if you want to easily know what they introduce.
The graph system that Django uses is more sophisticated, but it is also a lot more complex to comprehend and to solve eventual conflicts. Since migrations are already a hard topic and many developers on the Flutter community come from the app development world - not server development -, we prefer to keep the system as simple and easy to work with as possible.
Data migrations support
@craiglabenz Currently, data migrations are possible through manual SQL modification on the migration files, which makes them correctly coupled with the schema that they operate on. It also allows full granular control, since data can be moved around between delete and create steps. But it has several cons, such as changing a generated file (which is not nice), stepping out from the ORM abstraction with the models, and having to write raw SQL.
But, as you wrote, this is a deceptively complicated topic. It does not seem to make much sense without the snapshot, as breaking old migration Dart files with new migrations would be a very poor UX - and runtime errors. But the bloat would be too much with snapshots, and even more if we expose both pre/post hooks. Even with all this, it would still not solve common cases of moving data mid-migration (like between a create and a drop).
Given that we don't yet have a good design for solving this problem in a reasonable way, we have no plans to work on it for now.
@Metaildust The approach that exists today to properly check if something goes wrong after a migration is using the test framework, as @remonh87 also pointed out. Tests that run using
withServerpodwill apply the migration to the local database and should be used to assert anything that could be problematic before applying to production.