Skip to content

fix: release query runner when there is no migration to revert - #11232

Merged
gioboa merged 5 commits into
typeorm:masterfrom
mjr128:fix-revert-when-empty-migration
Dec 6, 2025
Merged

gioboa merged 5 commits into
typeorm:masterfrom
mjr128:fix-revert-when-empty-migration

Conversation

@mjr128

@mjr128 mjr128 commented Jan 9, 2025 •

Copy link
Copy Markdown
Contributor

avoid error when there is nothing to revert because datasource is destroyed and query runner is not released

fix: Error trying to revert last migration when there is none on Oracle
Closes: #11231

Description of change

Update MigrationExectuor.undoLastMigration() to release the query runner when there is no migration to run. The query runner is released the same way it is done when there is a migration to revert.

This fixes #11231 and avoid an error message on oracle database when reverting without migration to revert.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • npm run format to apply prettier formatting
  • npm run test passes with this change
  • This pull request links relevant issues as Fixes #11231
  • There are new or updated unit tests validating the change
  • [N/A] Documentation has been updated to reflect this change
  • The new commits follow conventions explained in CONTRIBUTING.md

Summary by CodeRabbit

  • Bug Fixes
    • Fixed a resource cleanup issue when reverting the last migration with no migrations present, preventing potential connection leaks and improving stability, including on Oracle.
  • Tests
    • Added automated tests to verify that reverting the last migration with an empty migration list completes without errors and releases resources properly.

avoid error when there is nothing to revert because datasource is destroyed and query runner
is not released

fix: Error trying to revert last migration when there is none on Oracle
Closes: typeorm#11231

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @mjr128 for your help
I added this PR in our release board

@gioboa gioboa added the size-s label Jan 24, 2025
@jovanadjuric jovanadjuric added this to the 0.3.23 milestone Apr 17, 2025
@jovanadjuric jovanadjuric moved this from Proposed to In Progress in TypeORM Roadmap Apr 17, 2025

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering why pipeline tests didn't run 🤔

@gioboa
gioboa self-requested a review April 18, 2025 00:57
@coveralls

coveralls commented Apr 18, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.796% (+0.02%) from 80.773%
when pulling aec9f47 on mjr128:fix-revert-when-empty-migration
into 2d8c515 on typeorm:master.

Comment thread test/github-issues/11231/issue-11231.ts Resolved
@coderabbitai

coderabbitai Bot commented Sep 21, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds an early-release of an internally created queryRunner in MigrationExecutor.undoLastMigration when no migrations exist, and introduces a test validating Oracle behavior for reverting with an empty migrations list.

Changes

Cohort / File(s) Summary
Migration executor cleanup
src/migration/MigrationExecutor.ts
Adds conditional release of an internally created queryRunner on early return when no migrations are found during undoLastMigration.
Oracle regression test
test/github-issues/11231/issue-11231.ts
New test for issue #11231: ensures undoLastMigration with empty migrations on Oracle does not throw and allows clean DataSource destruction.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller
  participant MigrationExecutor
  participant QueryRunner

  Caller->>MigrationExecutor: undoLastMigration()
  alt No external queryRunner provided
    MigrationExecutor->>QueryRunner: create()
  end
  MigrationExecutor->>QueryRunner: getExecutedMigrations()
  alt No migrations found
    MigrationExecutor->>MigrationExecutor: log "Nothing to revert"
    opt Executor created QueryRunner
      MigrationExecutor->>QueryRunner: release()
    end
    MigrationExecutor-->>Caller: return
  else Migrations exist
    MigrationExecutor->>QueryRunner: revert last migration
    opt Executor created QueryRunner
      MigrationExecutor->>QueryRunner: release()
    end
    MigrationExecutor-->>Caller: return
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • naorpeled
  • OSA413

Poem

A bunny peeks at Oracle’s pool,
“No hops to undo? Keep calm, stay cool.”
It sets the runner gently free,
Then closes burrows gracefully.
Thump-thump logs, no errors chime—
Clean paws, clean code, in tidy time. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "fix: release query runner when there is no migration to revert" is a concise, single-sentence summary that directly reflects the primary change in MigrationExecutor.undoLastMigration (ensuring the query runner is released on the early-return path). It is specific to the behavioral fix without extraneous detail and will be clear to reviewers scanning history. The phrasing follows conventional commit style and accurately represents the changeset.
Linked Issues Check ✅ Passed The changes modify MigrationExecutor.undoLastMigration to release the queryRunner when no migrations are found and add a focused test under test/github-issues/11231 that calls undoLastMigration on Oracle-connected data sources with an empty migrations list and then destroys the data source, asserting no throw. This directly addresses the root cause described in #11231 (unreleased query runner causing Oracle NJS-104 during DataSource.destroy) and provides automated verification. Based on the provided summaries, the implementation and test meet the linked issue's objective of exiting cleanly with the "No migrations..." message and avoiding the Oracle error.
Out of Scope Changes Check ✅ Passed The diff and summaries show only a change in src/migration/MigrationExecutor.ts (early-return queryRunner release) and a new test file for the GitHub issue; both are directly related to the reported Oracle revert bug and its verification. No other source files or unrelated features are listed in the provided summary, so there is no evidence of out-of-scope changes. The changes appear focused and limited to the issue being fixed.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Sep 21, 2025 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm/typeorm@11232
    

commit: aec9f47

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/migration/MigrationExecutor.ts (1)

433-437: Leak on early-throw path: release QueryRunner before throwing.

If the last executed migration isn’t found in source, we throw before the try/finally and leak the QueryRunner (same symptom on Oracle). Release it here too.

Apply this minimal patch:

-        // if no migrations found in the database then nothing to revert
-        if (!migrationToRevert)
-            throw new TypeORMError(
-                `No migration ${lastTimeExecutedMigration.name} was found in the source code. Make sure you have this migration in your codebase and its included in the connection options.`,
-            )
+        // if migration is missing in source, release and throw
+        if (!migrationToRevert) {
+            if (!this.queryRunner) await queryRunner.release()
+            throw new TypeORMError(
+                `No migration ${lastTimeExecutedMigration.name} was found in the source code. Make sure you have this migration in your codebase and its included in the connection options.`,
+            )
+        }
🧹 Nitpick comments (2)
src/migration/MigrationExecutor.ts (1)

731-744: Optional: centralize lifecycle with withQueryRunner.

Consider wrapping undoLastMigration in withQueryRunner instead of manual releases to eliminate future early-exit leaks.

test/github-issues/11231/issue-11231.ts (1)

23-29: Chai misuse: to.not.throw on an awaited promise is a no-op.

Either assert the promise is fulfilled (chai-as-promised) or just await destroy.

Apply one of the following:

Option A (no chai-as-promised):

-                await dataSource.undoLastMigration()
-                expect(await dataSource.destroy()).to.not.throw
+                await dataSource.undoLastMigration()
+                await dataSource.destroy()

If you take Option A, also remove the unused import:

- import { expect } from "chai"
+ // import removed – no assertions used

Option B (with chai-as-promised):

                 await dataSource.undoLastMigration()
-                expect(await dataSource.destroy()).to.not.throw
+                await expect(dataSource.destroy()).to.be.fulfilled
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d4f7b44 and 2ad458a.

📒 Files selected for processing (2)
  • src/migration/MigrationExecutor.ts (1 hunks)
  • test/github-issues/11231/issue-11231.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
test/github-issues/11231/issue-11231.ts (1)
test/utils/test-utils.ts (2)
  • createTestingConnections (388-482)
  • closeTestingConnections (487-499)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (14)
  • GitHub Check: tests-linux (20) / sap
  • GitHub Check: tests-linux (18) / postgres (14)
  • GitHub Check: tests-linux (18) / postgres (17)
  • GitHub Check: tests-linux (20) / cockroachdb
  • GitHub Check: tests-linux (20) / mssql
  • GitHub Check: tests-linux (18) / mysql_mariadb_latest
  • GitHub Check: tests-linux (18) / mssql
  • GitHub Check: tests-linux (18) / mysql_mariadb
  • GitHub Check: tests-linux (18) / mongodb
  • GitHub Check: tests-linux (18) / better-sqlite3
  • GitHub Check: tests-windows / sqljs
  • GitHub Check: tests-windows / sqlite
  • GitHub Check: tests-windows / better-sqlite3
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
src/migration/MigrationExecutor.ts (1)

416-422: Good fix: release QueryRunner on early return.

This closes the resource leak when there’s nothing to revert and prevents Oracle’s NJS-104. Looks correct and consistent with other early-exit paths.

test/github-issues/11231/issue-11231.ts (1)

9-9: Move test to functional suite; avoid GitHub-issue-specific path/name.

Per project guidance, place this under the migrations test suite and rename the describe accordingly.

Suggested describe string:

  • migrations > undoLastMigration > does not leave busy connections when no migrations (oracle)

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Dec 1, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to aec9f47

CategorySuggestion                                                                                                                                    Impact
Possible issue
Ensure query runner cleanup on errors

Wrap the migration logic in a try...finally block to ensure the queryRunner is
always released, preventing potential resource leaks on error.

src/migration/MigrationExecutor.ts [415-423]

-// if no migrations found in the database then nothing to revert
-if (!lastTimeExecutedMigration) {
-    this.connection.logger.logSchemaBuild(
-        `No migrations were found in the database. Nothing to revert!`,
+try {
+    // create migrations table if it's not created yet
+    await this.createMigrationsTableIfNotExist(queryRunner)
+
+    // create typeorm_metadata table if it's not created yet
+    const schemaBuilder = this.connection.driver.createSchemaBuilder()
+    if (InstanceChecker.isRdbmsSchemaBuilder(schemaBuilder)) {
+        await schemaBuilder.createMetadataTableIfNecessary(queryRunner)
+    }
+
+    // get all migrations that are executed and saved in the database
+    const executedMigrations = await this.loadExecutedMigrations(
+        queryRunner,
     )
+
+    // get the time when last migration was executed
+    const lastTimeExecutedMigration =
+        this.getLatestExecutedMigration(executedMigrations)
+
+    // if no migrations found in the database then nothing to revert
+    if (!lastTimeExecutedMigration) {
+        this.connection.logger.logSchemaBuild(
+            `No migrations were found in the database. Nothing to revert!`,
+        )
+        return
+    }
+    // ... rest of the migration logic
+} finally {
     // if query runner was created by us then release it
     if (!this.queryRunner) await queryRunner.release()
-    return
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential resource leak. If an error occurs after the queryRunner is created but before the function returns, the runner would not be released. Using a try...finally block is the standard and robust way to ensure resource cleanup, which is a significant improvement to the method's reliability.

Medium
  • More

Previous suggestions

Suggestions up to commit 685afba
CategorySuggestion                                                                                                                                    Impact
Possible issue
Ensure query runner cleanup

Wrap the logic in undoLastMigration within a try...finally block to ensure the
queryRunner is always released, even if errors occur.

src/migration/MigrationExecutor.ts [415-423]

-// if no migrations found in the database then nothing to revert
-if (!lastTimeExecutedMigration) {
-    this.connection.logger.logSchemaBuild(
-        `No migrations were found in the database. Nothing to revert!`,
+try {
+    // create migrations table if it's not created yet
+    await this.createMigrationsTableIfNotExist(queryRunner)
+
+    // create typeorm_metadata table if it's not created yet
+    const schemaBuilder = this.connection.driver.createSchemaBuilder()
+    if (InstanceChecker.isRdbmsSchemaBuilder(schemaBuilder)) {
+        await schemaBuilder.createMetadataTableIfNecessary(queryRunner)
+    }
+
+    // get all migrations that are executed and saved in the database
+    const executedMigrations = await this.loadExecutedMigrations(
+        queryRunner,
     )
+
+    // get the time when last migration was executed
+    const lastTimeExecutedMigration =
+        this.getLatestExecutedMigration(executedMigrations)
+
+    // if no migrations found in the database then nothing to revert
+    if (!lastTimeExecutedMigration) {
+        this.connection.logger.logSchemaBuild(
+            `No migrations were found in the database. Nothing to revert!`,
+        )
+        return
+    }
+    // ... rest of the migration logic
+} finally {
     // if query runner was created by us then release it
     if (!this.queryRunner) await queryRunner.release()
-    return
 }
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a potential resource leak if an error occurs before the query runner is released, proposing a robust try...finally block which is a best practice for ensuring resource cleanup.

High

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your amazing help @mjr128

@gioboa
gioboa merged commit a46eb0a into typeorm:master Dec 6, 2025
mgohin pushed a commit to mgohin/typeorm that referenced this pull request Jan 15, 2026
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Error trying to revert last migration when there is none on Oracle

5 participants