Skip to content

RFC: New migrations experience #4604

Open

Description

@marcelomendoncasoares
Image

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 existing create-migration command. By default, generate only the JSON definition files.
    • --force to allow destructive operations (same as today).
    • --tag to identify the revision (same as today).
    • --empty to create an empty migration to be manually edited.
    • --dry-run to only show which changes would be generated.
    • --check to exit with non-zero when there are pending updates to create a migration.
    • --generate-sql to 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.
    • --config to specify which database to use (current --mode). Defaults to development.
    • --dry-run to show which changes would be applied.
    • --check to exit with non-zero when there are pending revisions to apply.
  • repair: Replaces the current create-repair-migration command. Create and apply the migration to the database on-the-fly, just like apply (solves Apply DB repair migration via the serverpod CLI command #3120).
    • --config to specify which database to use (current --mode). Defaults to development.
    • --version to target a specific version. Defaults to the latest revision.
    • --force to allow destructive operations (same as today).
    • --dry-run to show which changes would be applied.
    • --check to exit with non-zero when the database is out of sync with the migration system.
    • --create-only to only store the migration to apply later.
      • --tag to identify the revision (same as today).
      • --generate-sql for also generating the SQL files.
    • --from-files to apply a stored repair migration created using --create-only.
    • --prune to remove non-existing versions from the table registry (like after a squash).
  • downgrade [version]: Downgrade to a specific version. Uses repair, 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 repair command.
  • rollback [steps=1]: An alias to downgrade, but operating on N recent migrations.
    • Same options as the repair command.
  • 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.
    • --from to specify the start version of the squash range (when not using --older-than).
    • --to to specify the end version of the squash range (when not using --older-than).
    • --older-than to squash all migrations older than a given version.
    • --tag to identify the generated squash revision (overrides any tag on the latest version).
    • --generate-sql to create the squashed migration with the SQL files.
  • cleanup: Removes all migration folders that are not in the migration_registry.txt.
  • rebase: Convenience command to facilitate resolving merge conflicts. Requires the developer to resolve conflicts on the migration_registry.txt file first. Then, this command will basically call cleanup followed by create.
    • Same options as the create command.
  • show: Show the existing migrations and their apply status (with timestamp) on the target database.
    • --config to specify which database to use (current --mode). Defaults to development.

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:

  • m to create a migration that does not contain destructive actions.
  • f to create a migration that contains destructive actions (similar to create --force).
  • s to squash the latest changes into the last migration.
  • a to apply the migrations to the local database.

Related issues

Activity

  1. added
    enhancement
    rfc
    area: cli
    area: migrations
    on Jan 16, 2026
  2. moved this from Inbox 📫 to Backlog 🗂️ in Serverpod Frameworkson Jan 16, 2026
  3. craiglabenz commented on Jan 17, 2026

    @craiglabenz
    Contributor

    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" 😄)

    1. I think the defintion.{sql|json} files are the bigger source of friction than migration.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 the migration.sql files. 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.sql files might be made ephemeral and generated on-demand.

    2. This is slightly pedantic, but I think downgrade is 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.

    3. 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 no migration_id is supplied, the command moves all of the way forward. If a migration_id is 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.

    4. 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 that 0003 added 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 --dart could potentially create a migration.dart file with a Future<void> migrate(session) function, instead of a migration.sql file, 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.

  4. abdulah1974 commented on Jan 19, 2026

    @abdulah1974

    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.

  5. KristijanZic commented on Jan 20, 2026

    @KristijanZic
    Contributor

    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

  6. spaghettigus commented on Jan 20, 2026

    @spaghettigus

    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!

  7. Errechydy commented on Jan 20, 2026

    @Errechydy

    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.

  8. remonh87 commented on Jan 20, 2026

    @remonh87
    Contributor

    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 001 and 002 naming 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 migration 004_john and 004_laura and a kind of merge migration called 005_merge. If we can achieve this that would be awesome.

    **Definition sql vs migration **

    I want to read what changes are being made, for peace of mind if nothing else.
    Very true that is for me the exact reason I generate it often. I accept for the time being the fact that it will bloat my code base over the convenience of making increment updates that can be easily verified.

    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

    tables:
      users:
        columns:
          id: integer, pk, auto # Dense flags
          email: text, unique, !null
        indexes:
          idx_email: [email]
      posts:
        columns:
          id: integer, pk
          author_id: integer, ref(users.id)
  9. Metaildust commented on Jan 21, 2026

    @Metaildust

    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?

  10. craiglabenz commented on Jan 23, 2026

    @craiglabenz
    Contributor

    @remonh87 wrote:

    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.

    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.sql file 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. Since serverpod create-migration has 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:

    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 migration 004_john and 004_laura and a kind of merge migration called 005_merge. If we can achieve this that would be awesome.

    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_john and 004_laura arrive 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.txt file 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 a migration_a, and at Time-1, Laura creates migration_b; but Laura's work is ready first and is merged first; all John has to do is set his parent migration to migration_b and everything would work; even though his timestamp is earlier.

    Note: This of course assumes that their migrations to do not touch the same part of the schema in incompatible ways. If they do, then of course John must materially alter his migration_a to stop conflicting with Laura's migration_b.


    @Errechydy wrote:

    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).

    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:

    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

    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.

  11. marcelomendoncasoares commented on Feb 26, 2026

    @marcelomendoncasoares
    CollaboratorAuthor

    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.json file 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 the DatabaseDefinition from the database itself and compare with the definition that lives inside the Protocol class, 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 yaml could 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 downgrade command by a version option on the rollback command, but not on apply since they behave differently. While apply simply executes the SQL of the pending migration versions, downgrade would rely on the repair mechanism to generate a diff, create the SQL on-the-fly and apply it to the database. This is similar to the rollback, so it is possible to bundle both in one that accepts steps or version.

    The SQL generation for rollback can be replaced by a pre-generated reverse file, 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 reverse file for rollback, it would not entirely replace the repair command, 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 the repair command 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 reset command 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 the migration_registry.txt, calling cleanup and then create.

    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 withServerpod will apply the migration to the local database and should be used to assert anything that could be problematic before applying to production.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: cliarea: migrationsenhancementrfc

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions