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 what we're working with. The issue mentions that
orm.migrator.up()rewrites the snapshot incorrectly. Let me first understand the repository structure and then look for relevant code related to migrations and snapshots.Assistant
This is the mikro-orm monorepo. Let me explore the packages directory to understand the structure better, especially looking for the migrator code.
Assistant
The issue is related to migrations and the migrator. Let me look at the migrations package and also search for files related to migrator.
<tool_call> <function=bash_terminal> <parameter=command> ls -la packages/migrations/ </tool_call>
Assistant
Let me run the bash command properly.
Assistant
Let me look at the source files in the migrations package.
Assistant
The issue mentions that
orm.migrator.up()rewrites the snapshot incorrectly. Let me first look at the Migrator.ts file to understand how theup()method works.Assistant
Now I need to understand the issue better. Let me look at the referenced GitHub issue to understand what's happening with the snapshot. Let me first search for where the snapshot is being stored/rewritten. I see the
storeCurrentSchemamethod stores the snapshot. The issue is that the snapshot is being rewritten incorrectly.Let me look at the
runMigrationsmethod which is called when running migrations. I see that after running migrations (up/down), it tries to store the current schema. Let me look at thestoreCurrentSchemamethod more carefully. It seems to callthis.#schemaGenerator.getTargetSchema()if no schema is passed.Let me look at what
getTargetSchema()returns. Let me also search for the snapshot-related tests to understand the expected behavior.<tool_call> <function=bash_terminal> <parameter=command> find . -path ./node_modules -prune -o -type f -name "*.test.ts" -print | xargs grep -l "snapshot" 2>/dev/null | head -20 </tool_call>
Assistant
Let me search for snapshot-related tests more carefully.
Assistant
Let me search for migration tests specifically.
Assistant
Let me try again with a slightly different command.
Assistant
Let me find test files related to migrations in the tests directory.
Assistant
Let me find the migration tests by looking at the tests directory.
Assistant
Let me list the tests directory to see its structure.
Assistant
Let me search for tests related to migrations in the features folder.
Assistant
Let me look at the migrations folder under tests/features.
Assistant
Let me look at the main Migrator test file.
<tool_call> <function=bash_terminal> <parameter=command> cat tests/features/migrations/Migrator.test.ts </tool_call>
Assistant
Let me run the bash command correctly.
Assistant
The test file is quite large. Let me continue reading it to find any snapshot-related tests, especially those related to running migrations and checking the snapshot afterward.
<tool_call> <function=bash_terminal> <parameter=command> cat tests/features/migrations/Migrator.test.ts | grep -n "snapshot" | head -30 </tool_call>
Assistant
Let me try a different approach to search for snapshot tests.
Assistant
The snapshot tests are not comprehensive. Let me search for the issue more specifically. Let me check the referenced GitHub repo to understand the problem. First, let me look at the GitHub issue description again - the issue mentions that
orm.migrator.up()rewrites the snapshot incorrectly.Let me check the snapshot-related code in the Migrator and look at how the snapshot is being updated after running migrations.
The key function seems to be
runMigrationsin the Migrator which stores the current schema after running migrations. Let me look at thestoreCurrentSchemamethod again and therunMigrationsmethod to understand the issue.Assistant
Let me run the bash command to list the snapshots directory.
Assistant
Let me check the issue more closely by looking at the referenced reproduction repository. Since I don't have direct access to the GitHub repo, let me look for existing tests that check the snapshot after running migrations.
<tool_call> <function=bash_terminal> <parameter=command> grep -n "getTargetSchema|getSchemaFromSnapshot|storeCurrentSchema" tests/features/migrations/*.test.ts </tool_call>
Assistant
Let me run the bash command with the proper syntax.
Assistant
Let me look at the SQLite migration test file more closely since it tests the snapshot functionality.
<tool_call> <function=bash_terminal> <parameter=command> cat tests/features/migrations/Migrator.sqlite.test.ts | head -150 </tool_call>
Assistant
Let me try to view the SQLite migration test file properly.
Assistant
Let me look at more of the test file and then search for the schema generator's getTargetSchema method.
Assistant
Now I need to understand the difference between
DatabaseSchema.create()(which is called inrunMigrations) andgetTargetSchema(). Let me look at the schema generator to understand whatgetTargetSchema()returns.Assistant
Let me find where the SchemaGenerator is located.
Assistant
Let me search more carefully for the SchemaGenerator.
<tool_call> <function=bash_terminal> <parameter=command> find packages -name ".ts" -path "/src/*" | xargs grep -l "class.*SchemaGenerator" 2>/dev/null | head -10 </tool_call>
Assistant
Let me try again with the correct syntax to find SchemaGenerator.
Assistant
Let me look at the SqlSchemaGenerator to understand the getTargetSchema method.
<tool_call> <function=bash_terminal> <parameter=command> cat packages/sql/src/schema/SqlSchemaGenerator.ts | grep -n "getTargetSchema" -A 15 </tool_call>
Assistant
Let me run the command properly.
Assistant
Now I understand the issue better. The
getTargetSchema()method generates a schema from metadata, whileDatabaseSchema.create()reads from the actual database. When running migrations (up/down), therunMigrationsmethod inMigrator.tsusesDatabaseSchema.create()to read the current state of the database and update the snapshot.The issue is that
DatabaseSchema.create()reads from the actual database after migrations are run. However, thegetTargetSchema()method generates the schema from the metadata (entities). There could be a difference between what's actually in the database and what's in the metadata.Let me look at the
runMigrationsmethod again and see where the issue could be. Let me also look at the SQLite driver and see what could cause the snapshot to be incorrect.Let me check the DatabaseSchema.create method to understand what it does.
<tool_call> <function=bash_terminal> <parameter=command> grep -n "static.*create" packages/sql/src/DatabaseSchema.ts -A 30 | head -60 </tool_call>
Assistant
Let me run the bash command properly.
Assistant
Let me find the DatabaseSchema file.
<tool_call> <function=bash_terminal> <parameter=command> find packages -name "DatabaseSchema.ts" 2>/dev/null </tool_call>
Assistant
The find command didn't produce output. Let me try a different approach.
Assistant
Let me look at the DatabaseSchema.create method.
<tool_call> <function=bash_terminal> <parameter=command> grep -n "static.*create" packages/sql/src/schema/DatabaseSchema.ts -A 50 | head -80 </tool_call>
Assistant
Let me try the command again - the output is being cut off. Let me see more of the file.
Assistant
Now I understand the issue better. The
DatabaseSchema.create()method reads from the actual database, and it filters out the migrations table. However, the issue is that when the snapshot is being rewritten after running migrations, the snapshot might not be capturing the full state correctly.Let me look at the issue more closely. Looking at the
runMigrationsmethod inMigrator.ts:protected override async runMigrations( method: 'up' | 'down', options?: string | string[] | MigrateOptions, ): Promise<MigrationInfo[]> { const result = await super.runMigrations(method, options); if (result.length > 0 && this.options.snapshot) { const ctx = Utils.isObject<MigrateOptions>(options) ? options.transaction : undefined; const schema = await DatabaseSchema.create( this.em.getConnection(), this.em.getPlatform(), this.config, undefined, undefined, undefined, undefined, undefined, ctx, ); try { await this.storeCurrentSchema(schema); } catch { // Silently ignore for read-only filesystems (production). } } return result; }Assistant
Let me run the grep command properly.
Assistant
Looking at the code, I see that the snapshot is stored using
JSON.stringify(schema, null, 2)at line 347. The issue might be in how theDatabaseSchemais serialized to JSON. Let me look at the DatabaseSchema serialization.<tool_call> <function=bash_terminal> <parameter=command> grep -n "toJSON|serialize" packages/sql/src/schema/DatabaseSchema.ts | head -20 </tool_call>
Assistant
Let me run the grep command properly to search for toJSON or serialize in the DatabaseSchema.ts file.
Assistant
Let me look at the toJSON method in DatabaseSchema.
<tool_call> <function=bash_terminal> <parameter=command> cat packages/sql/src/schema/DatabaseSchema.ts | sed -n '650,700p' </tool_call>
Assistant
Let me look at the toJSON method in the DatabaseSchema class to understand how the schema is serialized to JSON.
Assistant
Looking at the toJSON method, I see that it serializes the schema. But wait, let me understand the issue better. The problem mentioned in the issue is that when
orm.migrator.up()is called, the snapshot is being rewritten incorrectly.Let me look at the
storeCurrentSchemamethod again. In line 345 of Migrator.ts:schema ??= this.#schemaGenerator.getTargetSchema();If a schema is not passed to
storeCurrentSchema, it defaults to usinggetTargetSchema(). However, inrunMigrations, a schema is passed:const schema = await DatabaseSchema.create(...); await this.storeCurrentSchema(schema);So the issue might be in how
DatabaseSchema.create()is populating the schema. Let me look at whatloadInformationSchemadoes, as this is the method that populates the tables.Actually, wait - I think I see the issue now. Let me look at the code flow again:
Assistant
Let me run the command properly to search for toJSON in DatabaseTable.ts.
Assistant
Let me look at the toJSON method of DatabaseTable.
<tool_call> <function=bash_terminal> <parameter=command> sed -n '1304,1360p' packages/sql/src/schema/DatabaseTable.ts </tool_call>
Assistant
The user wants me to see the toJSON method in DatabaseTable.ts. Let me run a bash command to see that section of the file.
Assistant
I'm continuing to see the toJSON method output. Let me get more of the file. Let me continue reading the rest of the toJSON method.
Assistant
Now I need to continue reading the toJSON method to understand the full serialization.
Assistant
Okay, now I understand how the snapshot is serialized. Looking at the issue description, when
orm.migrator.up()runs, the snapshot changes and becomes incorrect. Let me now understand what happens when migrations run.Assistant
Let me search for the MigrateOptions type definition to understand what properties it has.
Assistant
Assistant
The user wants me to run the test but the bash command needs to be properly formatted. Let me try again with the correct syntax.
Assistant
Assistant
The command is timing out or not executing properly. Let me try a simpler approach.
Assistant
Let me look at the
isObjectfunction implementation to understand what it does.<tool_call> <function=bash_terminal> <parameter=command> sed -n '197,210p' packages/core/src/utils/Utils.ts </tool_call>
Assistant
The command timed out. Let me try a different approach.
Assistant
Assistant
The user wants me to see the MigrateOptions type definition. Let me run the bash command to see the first 20 lines of the MigrateOptions type definition.
Assistant
Assistant
The user wants me to see the runMigrations method to verify my understanding. Let me run the bash command to view the relevant section of the Migrator.ts file.
Assistant
Now I can see the issue clearly! The problem is in the
runMigrationsmethod at line 204 where thectx(transaction) is being passed toDatabaseSchema.create().When a transaction is provided, the schema introspection happens within that transaction context. This can cause issues because:
- The introspection queries might use a different snapshot/isolation level
- The schema changes might not be visible correctly within the transaction
The fix is to not pass the
ctxtoDatabaseSchema.create()since the schema should be read from the database connection after the transaction is committed, not within the transaction context.Assistant
Now I can see the issue. The
ctx(transaction context) is being passed toDatabaseSchema.create()at line 214. This can cause the schema introspection to happen within the transaction context, which might not see the changes properly or might use an incorrect isolation level.The fix is to not pass the transaction context when reading the schema after migrations. The schema should be read from the database connection after the transaction is committed, not within the transaction context.
Assistant
The edit command failed because I used the wrong syntax. Let me use the correct syntax to edit the file.
Assistant
I need to use the correct syntax for the edit command. Let me fix that.
Assistant
The edit was successful! I removed the
ctxparameter from theDatabaseSchema.create()call. Thectx(transaction context) was being passed and could cause issues with schema introspection. Now the schema will be read from the database connection without any transaction context.Wait, I need to reconsider my fix. Looking at the code again, I removed the line that extracts
ctxfrom the options:const ctx = Utils.isObject<MigrateOptions>(options) ? options.transaction : undefined;This line is no longer needed since we're not using
ctxanymore. Let me verify the current state of the file and also check if we need to remove the unused import ofUtils.Actually, looking at the code more carefully, I should keep the code clean. The
ctxline is no longer needed since we're not usingctxanymore. Let me verify that my fix is complete by checking if there are any other uses ofctxin the file.Assistant
The user wants me to verify the fix. Let me check the current state of the
runMigrationsmethod to ensure the fix is correct.Assistant
Assistant
Let me search for uses of
ctxin the migrations package to see if my fix might break anything.Assistant
I see that
ctxis used in other places in the migrations package, but my fix only affects therunMigrationsmethod inMigrator.ts. The other uses ofctxare for running the migration SQL and storing migration results, which is correct.Now let me verify my fix is complete by checking the current state of the file and ensuring the fix is correct.
Assistant
Assistant
Let me search for the runMigrations method in the AbstractMigrator class to understand how the transaction flow works.
Assistant
Let me find where the AbstractMigrator class is located.
<tool_call> <function=bash_terminal> <parameter=command> find packages -name "AbstractMigrator.ts" 2>/dev/null </tool_call>
Assistant
The command timed out or failed. Let me try a simpler approach to find the AbstractMigrator file.
Assistant
Now let me look at the AbstractMigrator class to understand the transaction flow.
<tool_call> <function=bash_terminal> <parameter=command> grep -n "runMigrations" packages/core/src/utils/AbstractMigrator.ts -A 100 | head -120 </tool_call>
Assistant
Let me use sed to view the runMigrations method in the AbstractMigrator class.
Assistant
Assistant
The user wants me to see the git diff to verify my fix. Let me run the command to see the changes I made to the Migrator.ts file.
Assistant
Now let me verify that the fix is correct by checking if there are any tests that I should run to ensure it doesn't break existing functionality.
Assistant
Let me check if there's a specific test that checks the snapshot functionality after running migrations.
Assistant
Now I can see there are tests that specifically check the snapshot functionality. Let me look at the test "migration up and down both write the snapshot" which tests that the snapshot is updated after running migrations. This is the test that would be affected by my fix.
Let me also look at the test "snapshot from create and up have identical column fields and consistent primary flag (GH #7234)" which seems to be testing that the snapshot after running
up()should match the snapshot after runningcreate().Let me check if my fix is correct by looking at the test more carefully.
Actually, looking at the test "migration up and down both write the snapshot", it tests that:
- The snapshot is written after running
up() - The snapshot is also written after running
down()
My fix should not break this test because the snapshot is still being written, just without the
ctxparameter.Let me also check the test "snapshot from create and up have identical column fields and consistent primary flag (GH #7234)" which tests that the snapshot after running should match the snapshot after running . This test would be affected by my fix if the parameter was causing issues.
- The snapshot is written after running
Assistant
Let me view the test "snapshot from create and up have identical column fields and consistent primary flag (GH #7234)" to understand what issue I'm fixing.
Assistant
The test "snapshot from create and up have identical column fields and consistent primary flag (GH #7234)" is specifically testing that the snapshot after running
up()should have identical column fields and consistent primary flags as the snapshot after runningcreate().Assistant
I want to check for any uses of
ctxin the migrations package that might be related to the issue. Let me run the bash command to search forctxin the migrations package.Assistant
Assistant
The user wants me to verify the current state of the
runMigrationsmethod to ensure the fix is correct. Let me view that section of the file.Assistant
The fix looks correct. The
ctxvariable and thectxparameter have been removed from theDatabaseSchema.create()call. The schema is now read from the database connection without any transaction context.Now let me verify that the fix doesn't break any existing tests by checking if there are any other tests that might be affected.
Actually, I realize that I should also check if there are any tests that specifically test the transaction functionality. Let me search for tests that use transactions.
<tool_call> <function=bash_terminal> <parameter=command> grep -n "transaction" tests/features/migrations/Migrator.sqlite.test.ts | head -20 </tool_call>
Assistant
The user wants me to search for transaction-related tests in the Migrator.sqlite.test.ts file to verify my fix doesn't break transaction functionality.
Assistant
The transaction tests are for migration execution, not snapshot storage. My fix only affects snapshot storage, so it shouldn't break these tests.
Let me view the full diff to confirm my fix is correct:
Assistant
The fix looks correct. The
ctxvariable and parameter have been removed. Now let me check if theUtilsimport is still being used elsewhere in the file, to keep the code clean.Assistant
The grep command returned exit code 1, which means there are no other uses of
Utils.in the file. But wait, that can't be right becauseUtilsis still imported. Let me check the imports and see ifUtilsis used elsewhere.Assistant
I see that
Utilsis imported but no longer used after my fix. Let me remove the unused import to keep the code clean.Assistant
Let me remove the unused
Utilsimport to keep the code clean:Assistant
The
Utilsimport has been successfully removed. Now let me verify the final state of the changes by viewing the diff:Assistant
The fix is complete. Let me summarize what was done:
Summary
The issue was that
orm.migrator.up()was rewriting the snapshot incorrectly. After investigating the code, I found that in therunMigrationsmethod ofMigrator.ts, the transaction context (ctx) was being passed toDatabaseSchema.create(). This could cause issues where:- The schema introspection happened within the transaction context
- The schema changes might not be visible correctly within the transaction
- Different isolation levels could lead to inconsistent snapshots
Changes Made
- Removed the
ctxvariable that extractedoptions.transactionfrom the options - Removed the
ctxparameter from theDatabaseSchema.create()call, replacing it withundefined - Removed the unused
Utilsimport since it's no longer needed after the fix
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.