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.
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 the issue. The issue is about
orm.migrator.up()rewriting snapshots incorrectly. Let me first look at the repository structure and understand what we're working with.Assistant
This is the MikroORM repository itself. The issue mentions that
orm.migrator.up()rewrites the snapshot incorrectly. Let me explore the migrations package to understand how snapshots work.Assistant
Let me look at the
Migrator.tsfile since it likely contains theup()method and snapshot-related logic.Assistant
Now let me look at the
storeCurrentSchemamethod more closely. The issue is about the snapshot being rewritten incorrectly afterorm.migrator.up(). Let me also look at theDatabaseSchemaclass to understand how the serialization works.Assistant
Now let me look at the
storeCurrentSchemamethod more closely. I see the issue might be related to how the schema is serialized. Let me check the tests related to migrations to understand the expected behavior:Assistant
Let me look at the sqlite-specific tests and also search for issues related to the snapshot being written incorrectly:
Assistant
Let me look at the
runMigrationsmethod more closely - this is where the snapshot is updated after running migrations:Assistant
Now I see the issue! After running migrations, the snapshot is updated by reading the current schema from the database using
DatabaseSchema.create(). But thestoreCurrentSchemamethod callsJSON.stringify(schema, ...)which usesschema.toJSON(). Let me look at whattoJSON()returns and compare it with how the schema is read back from the snapshot.Assistant
Now let me look at
DatabaseTable.toJSON()to understand how tables are serialized:Assistant
Let me look at the rest of
toJSON():Assistant
Now let me look at the
getSchemaFromSnapshotmethod inMigrator.tsto understand how it reads the snapshot back:Assistant
Now I see a potential issue. When the snapshot is written,
DatabaseSchema.toJSON()returns the tables, which includesnativeEnumsfrom each table. But when reading the snapshot back withgetSchemaFromSnapshot(), the code looks forrest.nativeEnums(schema-level native enums) but the tables are destructured as{ tables, namespaces, ...rest }, meaning thenativeEnumsfromrestwould be the schema-level ones.Let me now look at how the snapshot is created initially and compare with how it's updated after
migrator.up(). Let me check the repro repository linked in the issue:Assistant
Let me search for any related issues or commits about snapshots:
Assistant
"thought: So there have been several related fixes for snapshot serialization. Let me look at the recent ones to understand what might be the issue. Let me also look at the specific commit that fixes MySQL snapshot serialization to understand the pattern: "
Assistant
Let me look at the recent commit that fixes MySQL snapshot serialization to understand the pattern.
Assistant
Now I see the pattern. When
migrator.create()stores the snapshot, it usesgetTargetSchema()(from metadata), but whenmigrator.up()runs, it usesDatabaseSchema.create()(from database introspection). Let me look at howgetTargetSchema()works and compare:Assistant
Let me look at
getTargetSchema()to understand how it creates a schema from metadata, and compare it withDatabaseSchema.create()which creates a schema from database introspection.Assistant
Let me look at what happens when a schema is created from metadata vs from database introspection, specifically how the
nameproperty is handled:Assistant
Let me check the SQLite migration test to understand what the issue might be:
Assistant
Let me run the relevant test to see if it passes:
Assistant
That test passes. Let me look more carefully at the issue description. The user reports that
orm.migrator.up()rewrites the snapshot incorrectly. Let me look at the repro repository mentioned:The bug is that after running
migrator.up(), the snapshot changes. Let me look at the test that checks for this:Assistant
Let me look at the
runMigrationsmethod more carefully. The issue is that the snapshot is recreated from the database after migrations run, which may produce different results than the original metadata-based snapshot.Assistant
Let me look at the
DatabaseSchema.create()method and how thenameis set when reading from the database:Assistant
Now let me check what
getTargetSchema()does when the schema name is set:Assistant
Now I need to understand what exactly is wrong. Let me look at the GitHub issue reproduction. The issue says "the snapshot changes and a bunch of stuff in the snapshot is wrong". Let me try to create a minimal reproduction to understand the issue:
Assistant
Let me look at the issue more closely. The issue is about snapshots being rewritten incorrectly after
migrator.up(). The test "snapshot serialization is stable across metadata and introspection paths" checks thatafterUpequalsafterCreate. Let me see if there might be something specific about the schemanameproperty that differs:Assistant
I see a potential issue! Let me look at the
runMigrationsmethod inMigrator.tsagain. WhenDatabaseSchema.create()is called, it usesschemaNameas a parameter. But I don't see whereschemaNameis passed:Assistant
Let me check what happens when
getTargetSchema()is called vs whenDatabaseSchema.create()is called. The issue may be related to how the schemanamefield is handled:Assistant
Now I can see the issue more clearly. Let me trace through:
-
storeCurrentSchema(line 345): When called without a schema, it usesthis.#schemaGenerator.getTargetSchema()which callsDatabaseSchema.fromMetadata()and passesthis.config.get('schema')as the schema name. -
runMigrations(line 205-216): After running migrations, it callsDatabaseSchema.create()withundefinedfor the schema name. TheDatabaseSchema.create()method then usesschemaName ?? config.get('schema') ?? platform.getDefaultSchemaName(). -
getSchemaFromSnapshot(line 293): When reading from the snapshot, it creates a newDatabaseSchemawiththis.config.get('schema').
Wait, let me look at
getTargetSchema()more closely:-
Assistant
Now let me focus on the issue. The problem could be that when
runMigrationsstores the schema after running migrations, it doesn't pass aschemaparameter or use the same schema configuration. Let me check if there's a specificschemaoption:Assistant
I need to continue investigating the issue. Let me look at the
runMigrationsmethod and understand how the schema is being used when storing the snapshot after running migrations.Assistant
I see that
runMigrationsdoesn't pass a schema parameter toDatabaseSchema.create(). Let me look at the full context to understand the issue better. The bug is that afterorm.migrator.up(), the snapshot is rewritten incorrectly.Let me look at the
prunemethod inDatabaseSchemato understand how schemas are filtered. The issue could be that when storing the schema after running migrations, the schema is not properly pruned based on the schema options.Assistant
Let me look at how the snapshot is stored and if
pruneis called anywhere.Assistant
The
prunemethod is called inSqlSchemaGeneratorwhen comparing schemas, but it's not called when storing the snapshot inrunMigrations. Let me investigate if this is the issue - when the schema is stored after running migrations, it may contain tables/views that shouldn't be in the snapshot because they don't match the schema filter.Let me also look at the
runMigrationsmethod to see if the schema is being pruned before being stored.Assistant
I see! The
prunemethod is called inSqlSchemaGenerator.diffSchemas()but not when storing the snapshot inrunMigrations. Let me check if the schema should be pruned before being stored.Assistant
Let me look at the
runMigrationsmethod and see if the schema should be pruned before being stored.Assistant
Let me look at how the
prunemethod should be called and understand the difference betweengetTargetSchema()andDatabaseSchema.create():Assistant
Assistant
Looking at this more carefully, I can see the issue. In
runMigrations, after migrations complete, the snapshot is updated by reading the schema from the database usingDatabaseSchema.create(). However, unlikediffSchemas()which callsprune()to filter the schema,runMigrations()does NOT callprune(). This means extra tables/views from the database (not in metadata) will be included in the snapshot.Let me verify this by looking at how
diffSchemashandles this vs howrunMigrationshandles it:Assistant
Now I understand the issue. Looking at
runMigrations():const schema = await DatabaseSchema.create( this.em.getConnection(), this.em.getPlatform(), this.config, undefined, // schemaName undefined, // schemas undefined, // takeTables undefined, // skipTables undefined, // skipViews ctx, );The schema is created from the database, but it's not pruned like it is in
diffSchemas(). This means:- Tables/views that should be skipped may be included
- Tables from wildcard schemas may be included when they shouldn't be
But wait - the existing test "snapshot serialization is stable across metadata and introspection paths (GH #7607)" passes. Let me look at what that test actually checks and understand if there's a different issue.
Let me also look at the
storeCurrentSchemamethod when it's called from vs :Assistant
Assistant
Let me continue investigating by examining the
runMigrationsmethod and comparing it with how schemas are handled elsewhere.Assistant
Now I can see the issue clearly. In
SqlSchemaGenerator.diffSchemas(), bothfromSchemaandtoSchemaare pruned usingwildcardSchemaTables. But inMigrator.runMigrations(), the schema is NOT pruned before being stored.Let me check what
wildcardSchemaTablescontains and how it's computed:Assistant
Now I understand the full picture. The fix needs to:
- In
runMigrations, after creating the schema from the database, callprune()on it with the appropriate schema and wildcard schema tables, just likediffSchemas()does.
Let me implement this fix:
- In
Assistant
Now I understand the issue. The
runMigrationsmethod creates a schema from the database but doesn't prune it. This means extra tables from other schemas or wildcard schemas might be included in the snapshot.The fix should be to:
- Compute
wildcardSchemaTablesfrom metadata (entities withschema === '*') - Call
prune()on the schema before storing it
Let me implement this fix:
- Compute
Assistant
Let me make the edit directly to fix the issue. The problem is in the
runMigrationsmethod where the schema is not pruned before being stored.Assistant
Let me try to make the edit properly.
Assistant
Let me use the edit command to replace the runMigrations method in the Migrator.ts file. I need to be careful with the syntax.
Assistant
Let me use sed to make the fix to the Migrator.ts file.
Assistant
Let me try a different approach using a Node.js script file instead of inline code.
Assistant
The fix has been applied successfully. Let me verify the changes by looking at the updated code.
Assistant
Now let me run the existing tests to make sure the fix doesn't break anything. I'll start with the SQLite migration tests since they include snapshot-related tests.
Assistant
All 24 SQLite migration tests pass. Let me also run the general Migrator tests to ensure nothing is broken.
Assistant
The Migrator.test.ts failures appear to be due to MySQL not being available in this test environment (the tests are skipped and the
afterAllhooks fail becauseormis undefined from failedbeforeAllsetup). This is not related to my fix - it's an infrastructure issue.Let me verify the fix is correct by checking the diff and running the SQLite tests again, which is what the issue report mentions.
Assistant
The diff looks correct. My fix makes the following changes:
-
Pass
schemaNametoDatabaseSchema.create()- This ensures the schema name used matches the migrations options. -
Pass
skipTablesandskipViewsfrom schema generator config - This ensures tables and views that should be skipped are not included in the snapshot. -
Call
schema.prune()before storing - This filters tables based on schema and wildcard schema tables, matching the behavior inSqlSchemaGenerator.diffSchemas().
Let me verify that the SQLite tests still pass and also run a quick TypeScript check to make sure there are no type errors.
-
Assistant
TypeScript compilation passes. Now let me run the SQLite migration tests one more time to confirm everything works, and also run some additional migration-related tests to make sure the fix is solid.
Assistant
All 24 tests pass. Let me also look at the specific test that validates snapshot stability to make sure my fix aligns with the expected behavior.
Assistant
The test confirms that
afterUpshould equalafterCreate- meaning the snapshot written aftermigrator.up()should be identical to the snapshot written aftermigrator.create(). My fix ensures this by:- Using the same schema name (
this.options.schema) when creating the schema from the database - Applying the same
skipTablesandskipViewsoptions - Calling
prune()to filter tables based on schema and wildcard schema tables
This ensures consistency between the two snapshot sources (metadata-based vs introspection-based).
Let me also run a broader set of tests related to migrations and schema to make sure nothing is broken:
- Using the same schema name (
Assistant
The test failures are all due to database connection issues (MSSQL, PostgreSQL, MySQL not available in the test environment), not related to my code changes. The SQLite tests all passed (24 tests).
Let me verify by checking which tests passed:
Assistant
All SQLite tests pass (24 tests), and MongoDB tests pass (21 tests). All failures are due to missing database connections (MySQL, MariaDB, MSSQL, PostgreSQL) which are infrastructure issues, not related to my code changes.
Let me verify the fix handles edge cases properly by checking if
schemaGeneratorconfig might be undefined:Assistant
Good -
get('schemaGenerator')returns a configuration object throughout the codebase, andskipTables/skipViewsare optional properties that default toundefined, which is the same behavior as the original code. The fix is consistent with how these options are used elsewhere.Let me also verify my fix by reviewing the final state of the file:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.