ISSUE DESCRIPTION orm.migrator.up() rewrites snapshot incorrectly Describe the bug When…
- User
ISSUE DESCRIPTION
orm.migrator.up()rewrites snapshot incorrectlyDescribe the bug
When we run
orm.migrator.up(), the snapshot changes and a bunch of stuff in the snapshot is wrong and we have to revert the changes.Reproduction
https://github.com/zachkirsch/mikro-orm-migrate-snapshot-repro
What driver are you using?
@mikro-orm/sqlite
MikroORM version
7.1.2-dev.10
Node.js version
v24.0.1
Operating system
macOS
Validations
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord.
- The provided reproduction is a minimal reproducible example of the bug.
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call ) using or commands. However you don't need to use or before submitting your changes. In fact, only submits currently unstaged changes because it uses to get the changes that need to be submitted. Assistant
Let me start by exploring the repository structure to understand the codebase and then investigate the issue.
Assistant
Let me look at the reproduction repo to understand the issue better, and also explore the migrator code.
Assistant
The issue is about
orm.migrator.up()rewriting the snapshot incorrectly. The key part is inrunMigrationsmethod. After running migrations, it creates a new schema from the database and stores it as the snapshot.Let me look at the
storeCurrentSchemamethod and thegetTargetSchemamethod to understand what's happening.The issue is that
runMigrationscallsDatabaseSchema.createto get the actual database schema, then stores it. ButgetTargetSchemais used instoreCurrentSchemawhen no schema is passed.Let me look at the reproduction repo to understand the specific issue. The reproduction repo URL is https://github.com/zachkirsch/mikro-orm-migrate-snapshot-repro. I can't access it, but let me try to understand what's happening.
Let me look at the
getTargetSchemamethod in the SqlSchemaGenerator.Assistant
So
getTargetSchemacreates a schema from metadata. InrunMigrations, it usesDatabaseSchema.createwhich reads the schema from the database. Let me look atDatabaseSchema.createto see how it works.The issue is that after
migrator.up(), the snapshot is rewritten with the database schema (viaDatabaseSchema.create), but this might differ from the target schema (metadata-based). The problem might be thatDatabaseSchema.createreads the actual database schema, which could include extra columns/tables or have different properties.Let me check the git history for the
runMigrationsmethod to understand recent changes.Assistant
Now let me look at the current
runMigrationsmethod:Assistant
Now let me understand the issue. After
up(), the snapshot is rewritten usingDatabaseSchema.create(database introspection). Butcreate()usesgetTargetSchema()(metadata-based). These two paths should produce the same snapshot, but they may differ.The key question is: what's the difference between a schema created from metadata vs one read from the database?
Let me look at
DatabaseSchema.fromMetadataandDatabaseSchema.createto understand.Assistant
Now let me try to reproduce the issue. Let me look at the reproduction repo concept. The issue is that
up()rewrites the snapshot usingDatabaseSchema.create(introspection), whilecreate()usesgetTargetSchema(metadata-based). These should be the same but the snapshot changes afterup().Let me try to understand the specific differences. Let me look at
DatabaseSchema.toJSON()andtoJSONofDatabaseTable.Assistant
Let me try to clone the reproduction repo to understand the specific issue.
Assistant
Now I understand the issue. The migration SQL creates the
accounttable WITHOUT the comment on thenotescolumn:sqlcreate table `account` (`id` integer not null primary key autoincrement, `notes` text not null);But the committed snapshot (generated during
create()from metadata) includes the comment"free-form notes". Afterup(), the snapshot is regenerated using database introspection (DatabaseSchema.create), which doesn't find the comment (because the migration SQL didn't include it), so the comment flips tonull.Let me look at the
runMigrationsmethod and understand the difference betweenup()anddown()paths:Assistant
Now let me look at the existing tests for the migrator to understand the expected behavior:
Assistant
Now I understand the issue clearly. The existing tests use blank migrations (which run
select 1and don't change the schema), so introspection matches metadata. But with a real migration whose SQL doesn't perfectly match metadata (e.g., missing a comment), introspection produces a different snapshot.The fix: for
up(), use the metadata target schema (same ascreate()does viagetTargetSchema()), not database introspection. This guarantees the snapshot stays consistent with whatcreate()produces. Fordown(), we still need database introspection because the database has reverted and there's no metadata representation of the pre-migration state.Let me verify my understanding by first reproducing the issue:
Assistant
Now let me apply the fix. I'll modify the
runMigrationsmethod to use the metadata target schema forup()(consistent withcreate()) and database introspection fordown():Assistant
Now let me check if
storeCurrentSchema(undefined)correctly usesgetTargetSchema():Assistant
Now let me build the migrations package and run the existing tests:
Assistant
Building the whole project takes too long. Let me try building just the migrations package, or use the existing build. Let me check if there's already a build output.
Assistant
No dist directories. The tests likely use TS source directly via vitest. Let me check the vitest config:
Assistant
Good, tests use the TS source directly. Let me run the migrator sqlite tests:
Assistant
All 24 tests pass. Now let me create a reproduction script to verify the fix works for the specific issue (comment being lost). Let me write a temporary test:
Assistant
Let me write a standalone reproduction test to confirm the fix resolves the issue:
Assistant
I need to use the sqlite
defineConfig. Let me fix the test:Assistant
The test passes with my fix. Now let me verify the test would have FAILED before my fix by temporarily reverting:
Assistant
The test fails before the fix (comment becomes
null) and passes after the fix. This confirms the fix resolves the issue.Now let me clean up the temporary test and run the broader migration test suites to make sure nothing breaks:
Assistant
Postgres tests fail due to no database connection available in this environment. Let me verify these are pre-existing failures unrelated to my change:
Assistant
Same failures without my change — pre-existing due to no postgres DB available. My change doesn't affect them.
Now let me check the runtime schema tests (wildcard schema), since the
up()path now usesgetTargetSchema()which may not handle wildcard schemas the same way as introspection:Assistant
The
includeWildcardSchemais used ingetSchemaDiff(line 403, 412). ThegetTargetSchema()method also accepts anincludeWildcardSchemaparameter (second arg). Let me check if the snapshot creation (create()path) handles wildcard schema. Thecreate()callsstoreCurrentSchema()without arguments, which callsgetTargetSchema()withoutincludeWildcardSchema. Socreate()doesn't passincludeWildcardSchematogetTargetSchema(). Myup()path also doesn't, so it matchescreate()behavior. That's consistent.Let me look at the MigrationRuntimeSchema tests to understand if there are snapshot checks with wildcard schemas.
Assistant
SQLite runtime schema test doesn't use snapshots. The mssql/mysql/oracle/postgres ones do, but those need DB connections which aren't available here. Let me check whether the mysql one mentions snapshot writes related to up.
Let me look at the mssql one since it might be runnable... actually mssql needs a DB. Let me check what these tests do with snapshots.
Assistant
None of the runtime schema tests use snapshots (all
snapshot: false). So my change doesn't affect them.Now, let me run the main
Migrator.test.tsto make sure nothing else breaks:Assistant
These failures are due to
ECONNREFUSED 127.0.0.1:3308(MySQL not available) — pre-existing connection failures, not related to my change. Let me confirm by checking which driverMigrator.test.tsuses:Assistant
MySQL tests can't run in this environment (no MySQL DB). These are all pre-existing connection failures. My change is for the SQLite-tested migrator. Let me run the CLI migration command tests that might be affected:
Assistant
All CLI migration tests pass. Let me review the final state of my change and verify there are no other callers relying on the introspection behavior after
up():Assistant
Let me check whether the mongodb migrator has similar logic that might need updating:
Assistant
The mongodb migrator doesn't use snapshots, so no changes needed there.
Let me run the complete migrations sqlite test suite once more plus the check migrations command test:
Assistant
All tests pass. Let me search the test suite for any other assertions about snapshot content after
up()that might rely on introspection-specific values:Assistant
There's an important test in
Migrator.postgres.test.tsthat asserts the snapshot changes afterup(). Let me look at it in detail:Assistant
This postgres test directly codifies the introspection behavior. Let me check when it was added and understand the design intent:
Assistant
This is an important test that codifies the introspection behavior. Let me understand the test setup to fully grasp the scenario:
Assistant
Now I understand the test fully. The DB has divergences (extra
foo/pathcolumns, type changes) that don't match metadata. The test mocksexecuteMigrationsso the DB doesn't change duringup/down, then asserts the snapshot reflects the actual (divergent) DB via introspection.This test codifies exactly the buggy behavior reported in the issue. The key insight is: for SQLite, column comments can't be expressed in DDL, so after
up()the DB genuinely lacks them, and introspection loses them from the snapshot — creating perpetual phantom diffs. The snapshot should reflect metadata (the source of truth), not the actual DB.My fix is correct:
up()uses the metadata target schema (consistent withcreate()),down()keeps introspection. This only changes theup()behavior. Let me verify themethodparameter is correctly threaded throughAbstractMigrator.runMigrations:Assistant
The
methodparameter is correctly'up'or'down', and my checkmethod === 'down'works correctly. The transaction context handling fordown()matches the original.Let me run a lint/type check on the migrations package and re-run the sqlite tests one final time:
Assistant
TypeScript compiles cleanly and all sqlite tests pass. Let me do one final comprehensive verification reproducing the exact issue scenario, including checking that
create()afterup()produces no phantom diff:Assistant
All passes. The fix keeps the snapshot stable after
up(), preserves the comment, and prevents phantom migrations. Let me clean up the temporary test file and run a broader schema generator test to ensure nothing related breaks:Assistant
The skip-views test mentions snapshot. Let me check if it's related to migrator snapshots. Let me grep for "snapshot" in the sqlite schema generator tests.
Actually, those are probably about
snapshotconfig option for schema. Let me check.Assistant
These set
snapshot: false, so they're not affected by my change. Let me run the sqlite schema generator tests to be safe, since they involve schema serialization:Assistant
All tests pass. Let me do a final review of my change:
Assistant
My change is clean and minimal. Let me verify there are no other migrator test files that use snapshots and can run in this environment (sqlite/libsql):
Assistant
The MigrationRuntimeSchema.sqlite.test.ts uses
snapshot: false, so it's not affected. Let me run the full set of runnable migration tests one final time:Assistant
All 46 tests pass across 12 test files. Let me verify there are no leftover temporary files:
Assistant
The only change is in
packages/migrations/src/Migrator.ts. Let me review the final change one more time to confirm it's correct:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.