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 understanding the issue. The user is reporting that
orm.migrator.up()rewrites snapshots incorrectly in MikroORM. I need to:- First, explore the repository structure to understand the codebase
- Try to reproduce the issue
- Find the root cause
- Fix the issue
- Verify the fix
Let me start by exploring the repository.
Assistant
Let me explore more about the repository structure and look for migration-related files.
Assistant
This is the main MikroORM repository. The issue is about
orm.migrator.up()rewriting snapshots incorrectly. Let me look at the packages directory and find the migration-related code.Assistant
There's a
migrationspackage. Let me explore it.Assistant
Let me look at the
Migrator.tsfile since it's the main file that handlesup()operations.Assistant
Now I need to understand the issue better. The bug is in
runMigrationswhere after running migrations, it updates the snapshot. Let me look at thestoreCurrentSchemamethod. It gets the schema usingthis.#schemaGenerator.getTargetSchema()when no schema is passed. But wait, looking at therunMigrationsmethod:typescriptconst schema = await DatabaseSchema.create( this.em.getConnection(), this.em.getPlatform(), this.config, undefined, undefined, undefined, undefined, ctx, );It's creating a schema from the database, but looking at the
DatabaseSchema.createsignature, I need to understand what parameters it takes and if there's an issue with how the schema is being captured.Let me check the tests and see if there's existing tests for this functionality.
Assistant
Let me look at the SQLite migrator test since the issue mentions using SQLite driver.
Assistant
I see there's a test called
snapshot serialization is stable across metadata and introspection paths (GH #7607)andsnapshot from create and up have identical column fields and consistent primary flag (GH #7234). Let me look at theDatabaseSchema.createmethod to understand the issue.Assistant
Now let me look at the
DatabaseTable.toJSON()method to understand how the schema is serialized. Let me also check thegetTargetSchemamethod in the schema generator.Assistant
Now let me look at the
SqlSchemaGeneratorto understand howgetTargetSchema()works:Assistant
Now let me understand the issue better. When
orm.migrator.up()runs, it callsrunMigrationswhich:- Runs the migrations
- Creates a new schema from the database using
DatabaseSchema.create() - Stores that schema to the snapshot file
The issue is that the schema read from the database might have different serialization than the schema created from metadata. Let me check the existing test for this issue and look at the referenced GitHub issue.
Assistant
I see recent commits related to snapshot serialization issues. Let me look at the most recent fix related to MySQL snapshot serialization:
Assistant
Let me look at the reproduction repository link mentioned in the issue description. It references a specific GitHub repo, but since this is the MikroORM repository itself, I should look for what the issue might be. Let me look at the recent issues and tests to understand what's happening.
Assistant
This is very helpful! The issue is that after
migration:createwrites a snapshot from entity metadata,migration:uprewrites it from the database (MySQL information_schema), and the two serializations can diverge. The test verifies that both should produce the same snapshot.Let me check if there's already a similar test for SQLite and run it to see if there are any issues:
Assistant
Let me look at the test for GH7607 (snapshot serialization stability) more closely:
Assistant
Let me run the existing tests to see if they pass and understand the current state:
Assistant
The test is timing out. Let me try a different approach - let me first check if there are any build artifacts and understand the project better:
Assistant
Let me check what tools are available to run tests:
Assistant
Let me look more carefully at the issue. The bug is that
orm.migrator.up()rewrites the snapshot incorrectly. Based on my analysis so far, I see that whenup()runs, it reads the current database schema and writes it to the snapshot file. Let me trace through the code path more carefully.Assistant
Let me look at the
runMigrationsmethod more closely:Assistant
Now I see the issue! When
runMigrationsstores the current schema after running migrations, it callsDatabaseSchema.create()with manyundefinedparameters. Let me look at what parametersDatabaseSchema.create()takes:Assistant
Now let me check how the snapshot is created during
storeCurrentSchemawhen called fromcreatevsup(). Whencreateis called, it usesgetTargetSchema()(from metadata), but whenup()is called, it usesDatabaseSchema.create()(from DB introspection).The issue is that
DatabaseSchema.toJSON()serializes the schema, andstoreCurrentSchemawrites it as JSON. The problem is likely thatDatabaseSchema.toJSON()doesn't include thenameproperty properly, or something else in the serialization differs.Let me look at the
toJSONmethod and compare with how the snapshot is loaded:Assistant
Now I see that
toJSON()returns{ name, namespaces, tables, views, nativeEnums }. Let me check how the schema is serialized to JSON instoreCurrentSchema:Assistant
I see! In
getSchemaFromSnapshot, the schema is reconstructed from the JSON data, and the constructor usesthis.config.get('schema')for the name, not thenamefield from the snapshot. But when creating the snapshot,toJSON()includesname: this.name.Let me check
storeCurrentSchema:Assistant
Now let me look for the actual issue. When
storeCurrentSchemais called with a schema object, it callsJSON.stringify(schema, null, 2). This usestoJSON()method for serialization.The key issue could be that when the schema is created from metadata (
getTargetSchema) vs. from database introspection (DatabaseSchema.create), they might have different values for the same fields. Let me check if there's a schema option being passed differently.Let me look more at what happens when running
up()with a specific schema parameter:Assistant
Let me look at the issue more carefully. The problem is that in
runMigrations, after running migrations, the code creates a new schema from the database usingDatabaseSchema.create(). This introspects the actual database state.The issue could be that when calling
DatabaseSchema.create(), it's not passing the same schema options that were used when creating the snapshot from metadata. Let me check the options being used:Assistant
Now I need to understand what the actual bug is. Looking at the code, the
runMigrationsmethod passes allundefinedforschemaName,schemas,takeTables,skipTables, andskipViewsparameters.Let me compare this to what happens in
checkSchemaand other places where the schema generator is used:Assistant
Now let me check what options are available in
this.optionsand if there's aschemaoption that should be passed:Assistant
Let me look at the AbstractMigrator more closely to understand how
schemaoption is used:Assistant
Now I understand the structure better. Let me look at what happens when the snapshot is stored and compare it with how it should be stored. The key issue is that when
runMigrationsstores the schema after running migrations, it usesDatabaseSchema.create()which introspects the database.Let me check the reproduction repository mentioned in the issue. Since I don't have direct access to it, let me search for any recent changes related to this issue:
Assistant
Let me look at the most recent commits related to snapshot serialization:
Assistant
Let me look at what changed in the Migrator.ts file in that commit to understand the issue better.
Assistant
Now let me check if there are any newer issues related to this. Let me look at what the reproduction repository might contain:
Assistant
The issue is about
orm.migrator.up()rewriting the snapshot incorrectly. Looking at the code, I need to understand the problem better. Let me look at the options that are being passed when creating the schema inrunMigrationsvs when creating from metadata.The issue might be related to the schema options not being passed correctly when creating the schema from the database. Let me check if the
schemaoption should be passed.Assistant
I think I found the issue! In
runMigrations, when creating the schema from the database to store in the snapshot, it's not passing theschemaoption or theincludeWildcardSchemaoption. This could cause the snapshot to include different tables/columns than what was intended.Let me also check if there's a schema option that should be used:
Assistant
Now let me check what happens in
storeCurrentSchemawhen called without a schema (fromcreate):Assistant
Now I understand the issue better. The problem is that:
- When
storeCurrentSchemais called fromcreate(), it usesgetTargetSchema()which creates a schema from metadata - When
storeCurrentSchemais called fromrunMigrations()(afterup()ordown()), it usesDatabaseSchema.create()which introspects the database
The issue is that when
DatabaseSchema.create()is called inrunMigrations, it doesn't pass theschemaNameparameter, so the schema name might be different. Let me look at howgetTargetSchemahandles the schema name:- When
Assistant
Now I see that
getTargetSchemausesschema ?? this.config.get('schema') ?? this.platform.getDefaultSchemaName(). InDatabaseSchema.create(), it also usesschemaName ?? config.get('schema') ?? platform.getDefaultSchemaName().So the schema name should be the same. Let me look at what else might be different. Let me check if the issue is that when the schema is serialized, there might be extra tables like the migrations table being included.
Actually, looking at
DatabaseSchema.create()more carefully:Assistant
Wait, I notice the issue now. The
DatabaseSchema.create()method filters out the migrations table, but it uses a different logic than what might be expected. Let me trace through this more carefully.Let me also look at what might be different between the target schema from metadata and the introspected schema. The key insight is that
runMigrationscreates a schema from the database, but this schema might include things that weren't in the original metadata-based snapshot.Let me write a simple test script to reproduce the issue:
Assistant
Let me fix the import statement. The
Entity,PrimaryKey, andPropertydecorators come from the@mikro-orm/decoratorspackage, not from@mikro-orm/core.Assistant
Let me look at how the existing tests import things and use a similar approach.
Assistant
I see that the existing tests use
ReflectMetadataProviderand import from@mikro-orm/decorators/legacy. Let me check if I can run the existing tests instead to understand the issue better.Let me look more carefully at the code to understand what might be the issue. Looking at the issue description, it says "the snapshot changes and a bunch of stuff in the snapshot is wrong". Let me look for recent changes or patterns in the code.
Assistant
Now I see that when calling
DatabaseSchema.create()inrunMigrations, the code doesn't pass theschemaoption fromthis.options.schema. Let me check if this is the issue. TherunMigrationsmethod extractsctxfrom options but doesn't usethis.options.schema.Let me also check how the schema is used elsewhere in the codebase when creating a target schema:
Assistant
Now I'm starting to understand the issue better. Let me check if
storeCurrentSchemapasses the schema name correctly when called fromrunMigrations:When
storeCurrentSchemais called without a schema argument, it defaults tothis.#schemaGenerator.getTargetSchema(). This uses the metadata to create the schema, which includesthis.config.get('schema')for the schema name.However, when
storeCurrentSchemais called fromrunMigrations, it passes a schema created byDatabaseSchema.create()withundefinedforschemaName. TheDatabaseSchema.createmethod will also useconfig.get('schema')for the schema name, so that should be consistent.Let me look at the actual problem more carefully. Let me check the
DatabaseSchema.createmethod again and trace through what happens with the schema name:Assistant
The shell is available, let me continue exploring the codebase.
Assistant
Assistant
I accidentally sent an empty message. Let me continue with the investigation by looking at the
DatabaseSchema.fromMetadatamethod.Assistant
Let me continue looking at the
fromMetadatamethod and also check the key differences between how schemas are created from metadata vs. from database introspection. The issue seems to be that after runningmigrator.up(), the snapshot is rewritten with database introspection data, which may differ from the metadata-based snapshot.Let me look at what options might be missing when calling
DatabaseSchema.create()inrunMigrations.Assistant
Let me look at the
runMigrationsmethod more closely to understand what's happening:Assistant
Assistant
I need to check the SqliteSchemaHelper to understand how views are loaded.
Assistant
Let me look at the loadViews method more closely.
Assistant
Let me check the
extractViewDefinitionmethod to understand how view definitions are extracted from the database.Assistant
Let me check the
extractViewDefinitionmethod to understand how view definitions are normalized.Assistant
I've been analyzing the code and I think I've identified the issue. The problem is in the
runMigrationsmethod ofMigrator.ts. When it runs migrations and updates the snapshot, it creates a schema from database introspection (DatabaseSchema.create()) instead of using the target schema from entity metadata (getTargetSchema()).This causes the snapshot to include all tables in the database (except the migrations table), while the original snapshot created by
create()only includes tables defined by entities. This inconsistency causes the snapshot to "change" and have "wrong" content after runningup().Let me verify my understanding and implement the fix.
Assistant
Looking at this issue more carefully, I now understand the problem. In
runMigrations, after running migrations, the snapshot is updated usingDatabaseSchema.create()which introspects the database. This can include tables/views that weren't defined by entity metadata, and the field values might differ from the metadata-based schema.The fix should be to use
getTargetSchema()forup()since after runningup(), the database should match the target schema. Fordown(), we should still use introspection to capture the actual database state after reverting the migration.Let me implement this fix:
Assistant
The patch failed because the line numbers or context didn't match exactly. Let me look at the actual content of the file more carefully and use the edit command to make the changes directly.
Assistant
Now I can see the exact code. Let me apply the fix using the edit command:
Assistant
The patch failed. Let me edit the file directly using the edit command.
The issue is in the
runMigrationsmethod. Whenup()is called, the snapshot is updated usingDatabaseSchema.create()which introspects the database. This can cause inconsistencies because:- The introspected schema may include tables/views not defined in entity metadata
- Field values from introspection may differ from metadata (types, defaults, etc.)
The fix is to use
getTargetSchema()forup()since after running migrations, the database should match the target schema. Fordown(), we should still use introspection.Let me apply the fix by editing the file directly.
Assistant
The patch failed earlier. Let me use the
editcommand to replace the code in the Migrator.ts file. I need to replace lines 197-223 (the runMigrations method).The fix is:
- For 'up' method: use
getTargetSchema()from metadata (consistent with whatcreate()uses) - For 'down' method: use
DatabaseSchema.create()from database introspection (to capture actual state)
Let me use the edit command properly.
- For 'up' method: use
Assistant
Let me first open the Migrator.ts file, then use the edit command to replace the relevant code.
Assistant
I need to edit the Migrator.ts file to fix the issue. Let me use the edit command to replace the runMigrations method. The key change is:
- For 'up' method: use
getTargetSchema()from metadata (consistent with whatcreate()uses) - For 'down' method: use
DatabaseSchema.create()from database introspection (to capture actual state)
Let me replace lines 205-216 (the schema creation part) with the new logic.
- For 'up' method: use
Assistant
The user's shell is available and I was in the middle of fixing the issue. Let me continue by applying the fix to the runMigrations method in Migrator.ts. I need to replace the code that creates a schema from database introspection with code that uses getTargetSchema() for 'up' operations (to maintain consistency with what create() produces) while still using introspection for 'down' operations.
Let me apply the edit now.
Assistant
The user wants me to continue. I was in the middle of fixing the bug. I need to:
- Replace the runMigrations method in Migrator.ts with the fix
- The fix should use getTargetSchema() for 'up' operations instead of DatabaseSchema.create()
Let me apply the fix properly.
Assistant
I need to provide the replacement text for the edit command. Let me first check the current state of the file and then apply the fix properly.
Assistant
The previous edit corrupted the file. Let me restore it first and then apply the correct fix.
Assistant
Good, the file is restored. Now let me apply the fix correctly. The issue is that
runMigrationsusesDatabaseSchema.create()(database introspection) to update the snapshot after running migrations. This causes the snapshot to differ from what was created bycreate()which usesgetTargetSchema()(metadata-based).The fix should use
getTargetSchema()for 'up' operations to maintain consistency with whatcreate()produces.Assistant
I need to apply the fix to the runMigrations method. The issue is that it uses
DatabaseSchema.create()(database introspection) which can produce different results thangetTargetSchema()(metadata-based) used bycreate().The fix should use
getTargetSchema()for 'up' operations to maintain consistency.Let me use the edit command properly with the replacement text.
Assistant
The user's shell is available and I was in the middle of fixing the bug. The issue is that
runMigrationsinMigrator.tsusesDatabaseSchema.create()(database introspection) to update the snapshot after running migrations, butcreate()usesgetTargetSchema()(metadata-based). This causes the snapshot to differ afterup()is run.My fix is to use
getTargetSchema()for 'up' operations to maintain consistency with whatcreate()produces. For 'down' operations, I'll keep usingDatabaseSchema.create()to capture the actual database state after reverting.I need to replace lines 197-225 in the Migrator.ts file with my fixed version. Let me use sed to do this properly.
Assistant
Let me verify the fix was applied correctly by checking the modified file.
Assistant
The fix has been applied to the
runMigrationsmethod. The change ensures that forupoperations, we usegetTargetSchema()(metadata-based) to maintain consistency with whatcreate()produces, while fordownoperations we continue to useDatabaseSchema.create()(database introspection) to capture the actual database state after reverting.Let me verify the TypeScript code compiles correctly and run the relevant tests.
Assistant
The TypeScript compilation passed without errors. Now let me run the relevant migrator tests to verify the fix doesn't break existing functionality.
Assistant
All 24 SQLite migrator tests passed! Let me run a few more related test suites to ensure the fix is solid.
Assistant
The test failures are infrastructure-related (MongoDB, MySQL, etc. connections refused) - these databases aren't running in this environment. The SQLite tests passed successfully.
Let me run a quick check to verify the fix logic is correct and review the diff:
Assistant
The fix looks good. Let me verify the changes are correct:
-
For 'up' operations: We now use
getTargetSchema()which creates the schema from entity metadata. This is the same source used bycreate()when storing the snapshot, so the snapshot afterup()will match the snapshot aftercreate(). -
For 'down' operations: We continue to use
DatabaseSchema.create()which introspects the database. This makes sense because after reverting a migration, the database state may not exactly match any target schema from metadata.
The key insight is that
migrator.create()usesgetTargetSchema()to store the snapshot, butmigrator.up()was usingDatabaseSchema.create()(database introspection), causing the snapshot to differ. This fix alignsup()withcreate().Let me run the snapshot-specific tests one more time to confirm everything works:
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.