Repository navigation
Closed
Labels
Description
Issue description
Recursive CTE must come first, adding more than one causes invalid SQL generation
Expected Behavior
As a user, I should be able to run,
queryBuilder
.addCommonTableExpression("SELECT 1", "cte1", { recursive: false })
.addCommonTableExpression("SELECT 2", "cte2", { recursive: true })
.addCommonTableExpression("SELECT 3", "cte3", { recursive: true })
And have this generate the correct SQL, something like:
WITH RECURSIVE cte1 AS (SELECT 1), cte2 AS (SELECT 2), cte3 AS (SELECT 3)
...
Actual Behavior
The generated SQL is actually:
WITH cte1 AS (SELECT 1), RECURSIVE cte2 AS (SELECT 2), RECURSIVE cte3 AS (SELECT 3)
...
This does not match the SQL grammar for Postgres or MySQL, or SQLite. (I haven't checked further.)
Steps to reproduce
it("should work with multiple mixed-recursive CTEs", () =>
Promise.all(
dataSources
.filter(filterByCteCapabilities("enabled"))
.map(async (dataSource) => {
if (
dataSource.options.type === "sap" ||
dataSource.options.type === "spanner"
) {
// CTE cannot reference itself in SAP HANA / Spanner
return
}
let qb: { foo: number }[]
if (dataSource.options.type === "oracle") {
qb = await dataSource
.createQueryBuilder()
.select([])
.from("cte", "cte")
.addCommonTableExpression(
`SELECT 1 FROM "DUAL"` +
` UNION ALL` +
` SELECT "cte"."foo" + 1` +
` FROM "cte"` +
` WHERE "cte"."foo" < 10`,
"cte",
{ recursive: true, columnNames: ["foo"] },
)
.addSelect(`"cte"."foo"`, "foo")
.getRawMany<{ foo: number }>()
} else {
qb = await dataSource
.createQueryBuilder()
.select([])
.from("cte1", "cte1")
.innerJoin("cte2", "cte2", `"cte1"."foo" = "cte2"."foo"`)
.innerJoin("cte3", "cte3", `"cte1"."foo" = "cte3"."foo"`)
.addCommonTableExpression(
`SELECT foo FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) AS t(foo)`,
"cte1",
{ recursive: false, columnNames: ["foo"] },
)
.addCommonTableExpression(
`SELECT 1` +
` UNION ALL` +
` SELECT cte2.foo + 1` +
` FROM cte2` +
` WHERE cte2.foo < 10`,
"cte2",
{ recursive: true, columnNames: ["foo"] },
)
.addCommonTableExpression(
`SELECT 1` +
` UNION ALL` +
` SELECT cte3.foo + 1` +
` FROM cte3` +
` WHERE cte3.foo < 10`,
"cte3",
{ recursive: true, columnNames: ["foo"] },
)
.addSelect("cte1.foo", "foo")
.getRawMany<{ foo: number }>()
}
expect(qb).to.have.length(10)
}),
))
})
My Environment
| Dependency | Version |
|---|---|
| Operating System | macOS |
| Node.js version | 22.22.0 |
| Typescript version | 5.9.3 |
| TypeORM version | master |
Additional Context
No response
Relevant Database Driver(s)
- aurora-mysql
- aurora-postgres
- better-sqlite3
- capacitor
- cockroachdb
- cordova
- expo
- mongodb
- mysql
- nativescript
- oracle
- postgres
- react-native
- sap
- spanner
- sqlite
- sqljs
- sqlserver
Are you willing to resolve this issue by submitting a Pull Request?
Yes, I have the time, and I know how to start.
Activity