Skip to content

fix: multiple recursive cte problems - #12490

Merged
Cprakhar merged 7 commits into
typeorm:masterfrom
twooster:twooster/fix-12489
Jun 10, 2026
Merged

Cprakhar merged 7 commits into
typeorm:masterfrom
twooster:twooster/fix-12489

Conversation

@twooster

@twooster twooster commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Description of change

Fixes #12489. See that issue for a complete description. In short: you couldn't have more than one recursive CTE, and the single recursive CTE needed to be the first CTE added. Otherwise, you'd get invalid SQL. This fixes that.

I've only tested against Postgres because some of the other docker images failed to pull, but the theory here is sound. I added the Oracle tests as best I know, but I'm not an Oracle dev.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #00000
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md) N/A

@twooster twooster changed the title fix #12489: multiple recursive cte problems fix[#12489]: multiple recursive cte problems May 14, 2026
@twooster twooster changed the title fix[#12489]: multiple recursive cte problems fix: #12489 multiple recursive cte problems May 14, 2026
@twooster twooster changed the title fix: #12489 multiple recursive cte problems fix: multiple recursive cte problems May 14, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented May 14, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (2) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0)

Grey Divider


Action required

1. databaseRequireRecusiveHint misspelled ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
New code references databaseRequireRecusiveHint, which contains a spelling error and violates the
project's naming conventions. This reduces readability and increases the chance of repeated typos in
future changes.
Code

src/query-builder/QueryBuilder.ts[R1244-1245]

+        const recursiveClause =
+            anyRecursive && databaseRequireRecusiveHint ? "RECURSIVE " : ""
Evidence
PR Compliance ID 1 requires consistent naming conventions. The newly added recursive clause logic
uses the misspelled identifier databaseRequireRecusiveHint, introducing/propagating inconsistent
naming in modified code.

Rule 1: Consistent Naming Conventions
src/query-builder/QueryBuilder.ts[1244-1245]
src/query-builder/QueryBuilder.ts[1175-1177]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The identifier `databaseRequireRecusiveHint` is misspelled (`Recusive` vs `Recursive`) and is used in newly added logic.
## Issue Context
This violates naming convention expectations and makes the surrounding CTE logic harder to read/maintain.
## Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1175-1177]
- src/query-builder/QueryBuilder.ts[1244-1247]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Oracle .addSelect() misquoted identifier 📘 Rule violation ≡ Correctness
Description
The Oracle branch of the new mixed-recursive CTE functional test selects "cte1.foo", which Oracle
treats as a single quoted identifier (including the dot) rather than a qualified alias/column
reference. This is inconsistent with the file’s existing Oracle style and is likely to produce
invalid SQL and flaky or failing tests, adding unnecessary noise to the suite.
Code

test/functional/query-builder/cte/recursive-cte.test.ts[126]

+                            .addSelect(`"cte1.foo"`, "foo")
Evidence
The cited change adds an Oracle-specific select expression using "cte1.foo", and in Oracle quoted
identifiers preserve the dot as part of the identifier name, so it is not parsed as alias cte1
with column foo. In the same test file, the existing Oracle recursive CTE test uses the correct
qualification style of "alias"."column" (e.g., "cte"."foo"), demonstrating that the new line
deviates from established patterns and supporting the conclusion that it will generate invalid
Oracle SQL and create avoidable churn.

Rule 4: Remove AI-generated noise
test/functional/query-builder/cte/recursive-cte.test.ts[124-127]
test/functional/query-builder/cte/recursive-cte.test.ts[35-52]
test/functional/query-builder/cte/recursive-cte.test.ts[88-128]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The Oracle branch of the new mixed-recursive CTE functional test uses an incorrectly quoted select expression `"cte1.foo"`, which Oracle interprets as a single identifier (dot inside quotes) rather than a qualified column reference. Update the test to use Oracle’s correct quoted qualification form (e.g., `"cte1"."foo"`) and match the file’s existing Oracle style to avoid invalid SQL and test instability.
## Issue Context
In Oracle, `"cte1.foo"` is one identifier containing a dot, not `cte1` (alias) + `foo` (column). The same file already demonstrates the correct Oracle pattern in the existing recursive CTE test (e.g., `"cte"."foo"`), and the new test should follow that same approach.
## Fix Focus Areas
- test/functional/query-builder/cte/recursive-cte.test.ts[88-128]
- test/functional/query-builder/cte/recursive-cte.test.ts[124-127]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Non-portable join quoting 🐞 Bug ≡ Correctness
Description
The new mixed-recursive CTE tests hard-code join predicates using double-quoted identifiers (e.g.,
"cte1"."foo"), which will generate invalid SQL on drivers like MySQL that escape identifiers with
backticks, causing cross-DB test failures.
Code

test/functional/query-builder/cte/recursive-cte.test.ts[R93-97]

+                            .innerJoin(
+                                "cte2",
+                                "cte2",
+                                `"cte1"."foo" = "cte2"."foo"`,
+                            )
Evidence
The new test hard-codes "..." quoting in join conditions, but the MySQL driver’s escape()
clearly uses backticks, and existing CTE tests demonstrate using driver.escape for portability.

test/functional/query-builder/cte/recursive-cte.test.ts[88-103]
test/functional/query-builder/cte/recursive-cte.test.ts[129-143]
src/driver/mysql/MysqlDriver.ts[534-536]
test/functional/query-builder/cte/simple-cte.test.ts[82-115]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new mixed-recursive CTE tests use hard-coded double-quoted identifiers in join conditions (e.g., `"cte1"."foo" = "cte2"."foo"`). This is not portable: for example, the MySQL driver escapes identifiers using backticks, not double quotes, so these predicates can break on MySQL.
### Issue Context
Other CTE tests construct join/selection SQL with `dataSource.driver.escape(...)` to stay portable across drivers.
### Fix Focus Areas
- test/functional/query-builder/cte/recursive-cte.test.ts[92-102]
- test/functional/query-builder/cte/recursive-cte.test.ts[132-142]
- test/functional/query-builder/cte/simple-cte.test.ts[82-115]
- src/driver/mysql/MysqlDriver.ts[534-536]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (1)
4. New test under test/github-issues ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
This PR adds an issue-specific test file under test/github-issues/12489, but the checklist
requires issue fixes to be covered by the functional test suite. Keeping the fix validation only in
test/github-issues violates the testing placement requirement and increases long-term maintenance
burden.
Code

test/github-issues/12489/issue-12489.test.ts[R1-28]

+import { expect } from "chai"
+import type { DataSource } from "../../../src"
+import {
+    closeTestingConnections,
+    createTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import type { CteCapabilities } from "../../../src/driver/types/CteCapabilities"
+
+function filterByCteCapabilities(
+    capability: keyof CteCapabilities,
+    equalsTo: boolean = true,
+): (dataSource: DataSource) => boolean {
+    return (dataSource: DataSource) =>
+        dataSource.driver.cteCapabilities[capability] === equalsTo
+}
+
+describe("github issues > #12489 Recursive CTEs order dependent, can't have more than one", () => {
+    let dataSources: DataSource[]
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [],
+        })
+    })
+    beforeEach(() => reloadTestingDatabases(dataSources))
+    after(() => closeTestingConnections(dataSources))
+
+    it("should support multiple mixed-recursive CTEs", () =>
Evidence
PR Compliance ID 3 requires issue fixes to add/update tests in test/functional and considers it a
failure if tests are added only under test/github-issues without a clear reason. The PR introduces
a new test file located at test/github-issues/12489/issue-12489.test.ts, indicating the coverage
is in the per-issue test area rather than the functional suite.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/12489/issue-12489.test.ts[1-28]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The fix for #12489 is validated only by a test added under `test/github-issues/12489`, but compliance requires issue fixes to be covered in `test/functional` (with an issue reference comment when applicable).
## Issue Context
Per the checklist, `test/github-issues` should not be the only place where regression coverage lives unless there is a clear, documented reason.
## Fix Focus Areas
- test/github-issues/12489/issue-12489.test.ts[1-127]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

5. mixed-recursive CTE lacks issue ref 📘 Rule violation ⚙ Maintainability
Description
The new functional test for mixed recursive CTEs does not include a GitHub issue #12489 reference
comment, even though it is an issue-driven fix. This makes it harder to trace the regression
coverage back to the reported issue.
Code

test/functional/query-builder/cte/recursive-cte.test.ts[R74-75]

+    it("should support multiple mixed-recursive CTEs", () =>
+        Promise.all(
Evidence
PR Compliance ID 3 requires issue-fix functional tests to include an issue reference comment when
applicable. The added test case should support multiple mixed-recursive CTEs has no comment
referencing #12489 near the new test declaration.

Rule 3: Prefer functional tests over per-issue tests
test/functional/query-builder/cte/recursive-cte.test.ts[74-75]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The newly added functional test does not include an issue reference comment for the issue it fixes (`#12489`).
## Issue Context
Compliance requires issue-driven fixes to be represented in the functional test suite, and to include an issue reference comment when applicable for traceability.
## Fix Focus Areas
- test/functional/query-builder/cte/recursive-cte.test.ts[74-75]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Oracle CTE test SQL ✓ Resolved 🐞 Bug ≡ Correctness
Description
The new issue-12489 regression test uses Oracle-specific CTE SQL that is inconsistent with how
Oracle CTEs are referenced elsewhere in the test suite (quoted identifiers) and also uses a
sys.odcinumberlist(...) FROM-clause form that is not used anywhere else in the repo, making the
Oracle variant likely to fail or be unreliable in CI.
Code

test/github-issues/12489/issue-12489.test.ts[R57-80]

+                            .addCommonTableExpression(
+                                `SELECT * AS foo FROM sys.odcinumberlist(1,2,3,4,5,6,7,8,9,10)`,
+                                "cte1",
+                                { recursive: false, columnNames: ["foo"] },
+                            )
+                            .addCommonTableExpression(
+                                `SELECT 1 FROM "DUAL"` +
+                                    ` UNION ALL` +
+                                    ` SELECT cte2.foo + 1` +
+                                    ` FROM cte2` +
+                                    ` WHERE cte2.foo < 10`,
+                                "cte2",
+                                { recursive: true, columnNames: ["foo"] },
+                            )
+                            .addCommonTableExpression(
+                                `SELECT 1 FROM "DUAL"` +
+                                    ` UNION ALL` +
+                                    ` SELECT cte3.foo + 1` +
+                                    ` FROM cte3` +
+                                    ` WHERE cte3.foo < 10`,
+                                "cte3",
+                                { recursive: true, columnNames: ["foo"] },
+                            )
+                            .addSelect("cte1.foo", "foo")
Evidence
The new test’s Oracle branch uses raw SQL referencing cte2/cte3 without quotes and uses a
sys.odcinumberlist(...) row source; meanwhile, QueryBuilder escapes CTE aliases/columns and
Oracle’s driver escape is double-quote based. The existing Oracle recursive-CTE functional test
demonstrates the established pattern of quoting the recursive self-reference (e.g., FROM "cte",
"cte"."foo").

test/github-issues/12489/issue-12489.test.ts[42-81]
src/query-builder/QueryBuilder.ts[1170-1248]
src/driver/oracle/OracleDriver.ts[456-458]
test/functional/query-builder/cte/recursive-cte.test.ts[35-51]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The Oracle-specific branch of `test/github-issues/12489/issue-12489.test.ts` builds the CTE bodies as raw SQL strings. It currently references recursive CTEs using unquoted identifiers (e.g., `FROM cte2`, `cte2.foo`) and uses `sys.odcinumberlist(...)` directly in the FROM clause. This differs from the repo’s existing Oracle recursive CTE test style, which consistently uses quoted identifiers inside the raw SQL passed to `addCommonTableExpression`.
## Issue Context
TypeORM’s CTE header generation escapes CTE aliases/column names via `QueryBuilder.escape(...)`, and Oracle escaping uses double-quotes. Existing Oracle recursive-CTE tests quote the recursive self-reference accordingly.
## Fix Focus Areas
- test/github-issues/12489/issue-12489.test.ts[42-81]
- test/functional/query-builder/cte/recursive-cte.test.ts[35-51]
- src/query-builder/QueryBuilder.ts[1170-1248]
- src/driver/oracle/OracleDriver.ts[456-458]
## Suggested fix
- Update the Oracle CTE SQL strings to use quoted identifiers consistently (e.g., `FROM "cte2"`, `SELECT "cte2"."foo" + 1`, etc.), following the pattern in `test/functional/query-builder/cte/recursive-cte.test.ts`.
- Replace the non-recursive `cte1` generator query with an Oracle-safe row-source that is known to work in this repo’s Oracle tests (e.g., a `SELECT ... FROM "DUAL" UNION ALL ...` sequence or another Oracle-compatible set generator), and keep it consistent with the `columnNames: ["foo"]` header.
- Consider building identifier references via `dataSource.driver.escape(...)` to keep the test portable and consistent with per-driver quoting rules.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Qodo Logo

@twooster

Copy link
Copy Markdown
Contributor Author

Fixed review comments, but qodo hasn't updated.

@pkg-pr-new

pkg-pr-new Bot commented Jun 7, 2026 •

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

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

commit: e54bda2

@Cprakhar
Cprakhar requested review from alumni and smith-xyz June 7, 2026 09:04
Comment thread src/query-builder/QueryBuilder.ts Resolved

@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 help @twooster

@gioboa
gioboa enabled auto-merge (squash) June 9, 2026 11:10
@gioboa
gioboa disabled auto-merge June 9, 2026 11:10
@Cprakhar
Cprakhar merged commit 7c26654 into typeorm:master Jun 10, 2026
46 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone Jun 10, 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.

Recursive CTEs order dependent, can't have more than one

4 participants