Skip to content

fix: propagate schema and database to closure junction table - #12110

Merged
gioboa merged 4 commits into
typeorm:masterfrom
nvdnkpr:fix/closure-table-schema-inheritance
Mar 18, 2026
Merged

gioboa merged 4 commits into
typeorm:masterfrom
nvdnkpr:fix/closure-table-schema-inheritance

Conversation

@nvdnkpr

@nvdnkpr nvdnkpr commented Mar 6, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Closure junction tables now inherit schema and database from the parent entity metadata, so they are created in the correct schema
  • TreeRepository queries now use tablePath instead of tableName for closure table joins, producing correctly quoted identifiers ("schema"."table" instead of "schema.table")

Closes #10263

Test plan

  • Added test test/github-issues/10263 verifying closure junction table inherits parent schema
  • All 95 existing tree tests pass (closure-table, nested-set, materialized-path)
  • Tested against PostgreSQL 16

🤖 Generated with Claude Code

Closure tables created for @Tree('closure-table') entities did not
inherit the parent entity's schema or database, causing the junction
table to be created in the wrong schema (e.g. 'public' instead of the
entity's schema). Additionally, TreeRepository queries used tableName
instead of tablePath for innerJoin calls, producing incorrectly quoted
identifiers like "schema.table" instead of "schema"."table".

Closes typeorm#10263

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Review Summary by Qodo

Fix closure table schema and database inheritance

🐞 Bug fix

Grey Divider

Walkthroughs

Description
• Closure junction tables now inherit schema and database from parent entity
• TreeRepository queries use tablePath instead of tableName for correct identifier quoting
• Added test verifying closure table inherits parent entity schema
Diagram
flowchart LR
  A["Parent Entity<br/>with schema"] -->|"inherits schema<br/>and database"| B["Closure Junction<br/>Table Metadata"]
  C["TreeRepository<br/>innerJoin"] -->|"uses tablePath<br/>instead of tableName"| D["Correctly Quoted<br/>Identifiers"]
Loading

Grey Divider

File Changes

1. src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts 🐞 Bug fix +2/-0

Propagate schema and database to closure junction table

• Added schema property propagation from parent entity metadata to closure junction table
• Added database property propagation from parent entity metadata to closure junction table
• Ensures closure tables are created in the correct schema

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts


2. src/repository/TreeRepository.ts 🐞 Bug fix +2/-2

Use tablePath for closure table joins

• Changed innerJoin call to use tablePath instead of tableName in descendants query
• Changed innerJoin call to use tablePath instead of tableName in ancestors query
• Produces correctly quoted identifiers like "schema"."table" instead of "schema.table"

src/repository/TreeRepository.ts


3. test/github-issues/10263/entity/Space.ts 🧪 Tests +22/-0

Add Space entity for closure table schema test

• Created test entity Space with closure-table tree strategy
• Configured entity with custom schema my_schema
• Includes tree parent and children relationships for testing

test/github-issues/10263/entity/Space.ts


View more (1)
4. test/github-issues/10263/issue-10263.test.ts 🧪 Tests +37/-0

Add test for closure table schema inheritance

• Added test suite verifying closure junction table inherits parent entity schema
• Tests that closure table schema matches parent entity schema
• Validates tablePath contains the correct schema name
• Configured for PostgreSQL testing only

test/github-issues/10263/issue-10263.test.ts


Grey Divider

Qodo Logo

@nvdnkpr

nvdnkpr commented Mar 6, 2026

Copy link
Copy Markdown
Contributor Author

Hello created the fix and the PR. Used Claude Code but tried to stay as minimal invasive as possible. Reviewed the diffs myself but hope that it will pass by two other reviewers with write access.

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

qodo-free-for-open-source-projects Bot commented Mar 6, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (2) 📎 Requirement gaps (0) 📐 Spec deviations (0)

Grey Divider


Action required

1. Dotted join string crashes 🐞 Bug ✓ Correctness
Description
TreeRepository now passes closureJunctionTable.tablePath (e.g. my_schema.space_closure) into
innerJoin, and TypeORM interprets any dotted string as alias.property, causing it to resolve a
non-existent alias (e.g. my_schema) and throw. As a result, closure-table
findDescendants/findAncestors queries can fail whenever the closure junction table is
schema/database-qualified.
Code

src/repository/TreeRepository.ts[178]

+                    this.metadata.closureJunctionTable.tablePath,
Evidence
innerJoin() stores the provided string in JoinAttribute.entityOrProperty. Since tablePath
contains a dot when schema/database is set, QueryBuilderUtils.isAliasProperty() classifies it as
alias.property, making JoinAttribute.relation call findAliasByName(parentAlias) which throws.
SelectQueryBuilder.getQuery() always calls createJoinExpression(), and createJoinExpression()
evaluates joinAttr.relation unconditionally, so the throw happens during SQL generation/execution
of TreeRepository queries. This PR also makes closure junction tables inherit schema/database,
which makes closureJunctionTable.tablePath schema-qualified (dotted) for drivers like Postgres,
triggering the problematic parsing path.

src/repository/TreeRepository.ts[176-181]
src/query-builder/QueryBuilderUtils.ts[10-26]
src/query-builder/JoinAttribute.ts[126-134]
src/query-builder/JoinAttribute.ts[160-168]
src/query-builder/QueryExpressionMap.ts[435-443]
src/query-builder/SelectQueryBuilder.ts[80-86]
src/query-builder/SelectQueryBuilder.ts[2356-2360]
src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[28-43]
src/metadata/EntityMetadata.ts[1047-1051]
src/driver/postgres/PostgresDriver.ts[1043-1050]

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

## Issue description
`TreeRepository` now uses `closureJunctionTable.tablePath` as the first argument to `innerJoin`. When the closure junction table has a schema/database, `tablePath` contains dots (e.g. `my_schema.space_closure`). TypeORM’s join parsing treats *any* dotted string as `alias.property` syntax, which makes join building attempt to resolve an alias named `my_schema` and throw (`alias was not found`).
### Issue Context
The PR also propagates `schema`/`database` to the closure junction table metadata, which makes `closureJunctionTable.tablePath` schema-qualified for drivers like Postgres. Combined with the `innerJoin(tablePath, ...)` change, closure-table queries can fail at runtime.
### Fix Focus Areas
- src/repository/TreeRepository.ts[175-182]
- src/repository/TreeRepository.ts[354-360]
- test/github-issues/10263/issue-10263.test.ts[1-37]
### Suggested implementation notes
- In both closure-table query builder branches, change the join target from `this.metadata.closureJunctionTable.tablePath` back to a non-dotted identifier that still resolves metadata, e.g. `this.metadata.closureJunctionTable.tableName` (or `this.metadata.closureJunctionTable.target`).
- Rely on `JoinAttribute.tablePath` to emit `metadata.tablePath` (which will now include schema due to the metadata-builder change).
- Extend the #10263 test to actually run a query that exercises the join (e.g. initialize, synchronize or insert minimal rows, then call `getTreeRepository(Space).findAncestors(...)` or `findDescendants(...)`) to ensure schema-qualified closure joins work end-to-end.

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


2. Issue test added under github-issues 📘 Rule violation ⛯ Reliability
Description
The fix adds coverage only under test/github-issues/10263 without an explicit reason for not
placing it in the functional test suite. This violates the requirement to keep issue fixes in
test/functional with an issue reference comment when applicable.
Code

test/github-issues/10263/issue-10263.test.ts[R1-37]

+import { expect } from "chai"
+import type { DataSource } from "../../../src"
+import {
+    closeTestingConnections,
+    createTestingConnections,
+} from "../../utils/test-utils"
+import { Space } from "./entity/Space"
+
+describe("github issues > #10263 closure table should inherit entity schema", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [Space],
+            enabledDrivers: ["postgres"],
+            schemaCreate: false,
+            dropSchema: false,
+        })
+    })
+
+    after(() => closeTestingConnections(dataSources))
+
+    it("should set the same schema on the closure junction table as the parent entity", () => {
+        dataSources.forEach((dataSource) => {
+            const spaceMetadata = dataSource.getMetadata(Space)
+
+            expect(spaceMetadata.schema).to.equal("my_schema")
+            expect(spaceMetadata.closureJunctionTable).to.not.be.undefined
+            expect(spaceMetadata.closureJunctionTable.schema).to.equal(
+                "my_schema",
+            )
+            expect(spaceMetadata.closureJunctionTable.tablePath).to.contain(
+                "my_schema",
+            )
+        })
+    })
+})
Evidence
Compliance ID 3 requires issue-fix tests to be added/updated in test/functional; this PR adds a
new per-issue test under test/github-issues/10263 and provides no clear justification in the PR
content for not using the functional suite.

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

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

## Issue description
A new test was added under `test/github-issues/10263`, but compliance requires issue fixes to live in `test/functional` unless there is a clear reason.
## Issue Context
This PR adds `test/github-issues/10263/issue-10263.test.ts` to cover schema inheritance for closure junction tables.
## Fix Focus Areas
- test/github-issues/10263/issue-10263.test.ts[1-37]

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



Remediation recommended

3. Schema inheritance change undocumented 📘 Rule violation ✓ Correctness
Description
The PR changes user-visible behavior by making closure junction tables inherit schema and
database and by joining via tablePath, but no documentation updates are included. Users relying
on schema-qualified naming/creation may need updated docs or examples to reflect the new behavior.
Code

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[R40-41]

+                schema: parentClosureEntityMetadata.schema,
+                database: parentClosureEntityMetadata.database,
Evidence
The checklist requires docs to be updated for user-facing changes. The PR description and code
changes indicate a behavioral change in where/how closure tables are created and referenced, but no
doc changes are present in the diff.

Rule 2: Docs updated for user-facing changes
src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[40-41]

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 PR changes behavior for closure junction table schema/database inheritance and join identifier quoting, but no documentation updates are included.
## Issue Context
This change can affect users configuring schemas and expecting closure tables to be created/queried in a specific schema; docs or examples should reflect the new behavior.
## Fix Focus Areas
- src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[40-41]
- src/repository/TreeRepository.ts[178-178]
- src/repository/TreeRepository.ts[357-357]

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


4. Qualified closureTableName breaks 🐞 Bug ✓ Correctness
Description
Closure junction tables now always inherit parent schema/database, but if
treeOptions.closureTableName is already qualified (contains "."), EntityMetadata will prepend parent
schema/database on top of that qualified name, producing invalid 3-part identifiers for engines that
expect at most schema.table (or db.table). This is a regression vs previous behavior where the
qualified name could work because no additional schema/database was prepended.
Code

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[R40-41]

+                schema: parentClosureEntityMetadata.schema,
+                database: parentClosureEntityMetadata.database,
Evidence
The closure junction metadata now unconditionally copies parent schema/database while still allowing
an arbitrary closureTableName string. EntityMetadata.build constructs tableName/tablePath without
stripping existing qualifiers from the provided name; namingStrategy.closureJunctionTableName also
preserves dots. Drivers then build tablePath by joining parts with '.', and QueryBuilder later
splits on '.' and escapes each segment—so a qualified name plus inherited schema/database can become
a 3-part escaped identifier, which is invalid on e.g. Postgres/MySQL.

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[26-43]
src/metadata/EntityMetadata.ts[1041-1089]
src/naming-strategy/DefaultNamingStrategy.ts[10-35]
src/driver/postgres/PostgresDriver.ts[1047-1055]
src/driver/mysql/MysqlDriver.ts[524-536]
src/query-builder/QueryBuilder.ts[641-650]

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

## Issue description
`ClosureJunctionEntityMetadataBuilder` now always copies `schema`/`database` from the parent entity, but it still accepts a raw `closureTableName` string that may already be qualified (e.g. `&amp;amp;amp;quot;schema.table&amp;amp;amp;quot;` or `&amp;amp;amp;quot;db.table&amp;amp;amp;quot;`). Because `EntityMetadata.build()` and driver `buildTableName()` do not strip qualifiers embedded in `name`, this can produce invalid multi-part identifiers (e.g. `parentSchema.schema.table_closure`).
### Issue Context
We want closure junction tables to inherit the parent entity’s schema/database, but we must avoid *double-qualifying* when users supply a qualified `closureTableName`.
### Fix Focus Areas
- src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[26-43]
Suggested approach:
- Compute `rawName = treeOptions.closureTableName ?? parent.tableNameWithoutPrefix`.
- `const parsed = this.dataSource.driver.parseTableName(rawName)`
- Set `args.name = parsed.tableName` (unqualified)
- Set `args.schema = parent.schema ?? parsed.schema`
- Set `args.database = parent.database ?? parsed.database`
(Consider adding a regression test where `closureTableName` includes a schema/database qualifier.)

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


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Grey Divider

Previous review results

Review updated until commit 0430555

Results up to commit 4964e0d


🐞 Bugs (2) 📘 Rule violations (2) 📎 Requirement gaps (0)

Grey Divider
Action required
1. Dotted join string crashes 🐞 Bug ✓ Correctness
Description
TreeRepository now passes closureJunctionTable.tablePath (e.g. my_schema.space_closure) into
innerJoin, and TypeORM interprets any dotted string as alias.property, causing it to resolve a
non-existent alias (e.g. my_schema) and throw. As a result, closure-table
findDescendants/findAncestors queries can fail whenever the closure junction table is
schema/database-qualified.
Code

src/repository/TreeRepository.ts[178]

+                    this.metadata.closureJunctionTable.tablePath,
Evidence
innerJoin() stores the provided string in JoinAttribute.entityOrProperty. Since tablePath
contains a dot when schema/database is set, QueryBuilderUtils.isAliasProperty() classifies it as
alias.property, making JoinAttribute.relation call findAliasByName(parentAlias) which throws.
SelectQueryBuilder.getQuery() always calls createJoinExpression(), and createJoinExpression()
evaluates joinAttr.relation unconditionally, so the throw happens during SQL generation/execution
of TreeRepository queries. This PR also makes closure junction tables inherit schema/database,
which makes closureJunctionTable.tablePath schema-qualified (dotted) for drivers like Postgres,
triggering the problematic parsing path.

src/repository/TreeRepository.ts[176-181]
src/query-builder/QueryBuilderUtils.ts[10-26]
src/query-builder/JoinAttribute.ts[126-134]
src/query-builder/JoinAttribute.ts[160-168]
src/query-builder/QueryExpressionMap.ts[435-443]
src/query-builder/SelectQueryBuilder.ts[80-86]
src/query-builder/SelectQueryBuilder.ts[2356-2360]
src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[28-43]
src/metadata/EntityMetadata.ts[1047-1051]
src/driver/postgres/PostgresDriver.ts[1043-1050]

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

## Issue description
`TreeRepository` now uses `closureJunctionTable.tablePath` as the first argument to `innerJoin`. When the closure junction table has a schema/database, `tablePath` contains dots (e.g. `my_schema.space_closure`). TypeORM’s join parsing treats *any* dotted string as `alias.property` syntax, which makes join building attempt to resolve an alias named `my_schema` and throw (`alias was not found`).
### Issue Context
The PR also propagates `schema`/`database` to the closure junction table metadata, which makes `closureJunctionTable.tablePath` schema-qualified for drivers like Postgres. Combined with the `innerJoin(tablePath, ...)` change, closure-table queries can fail at runtime.
### Fix Focus Areas
- src/repository/TreeRepository.ts[175-182]
- src/repository/TreeRepository.ts[354-360]
- test/github-issues/10263/issue-10263.test.ts[1-37]
### Suggested implementation notes
- In both closure-table query builder branches, change the join target from `this.metadata.closureJunctionTable.tablePath` back to a non-dotted identifier that still resolves metadata, e.g. `this.metadata.closureJunctionTable.tableName` (or `this.metadata.closureJunctionTable.target`).
- Rely on `JoinAttribute.tablePath` to emit `metadata.tablePath` (which will now include schema due to the metadata-builder change).
- Extend the #10263 test to actually run a query that exercises the join (e.g. initialize, synchronize or insert minimal rows, then call `getTreeRepository(Space).findAncestors(...)` or `findDescendants(...)`) to ensure schema-qualified closure joins work end-to-end.

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


2. Issue test added under github-issues 📘 Rule violation ⛯ Reliability
Description
The fix adds coverage only under test/github-issues/10263 without an explicit reason for not
placing it in the functional test suite. This violates the requirement to keep issue fixes in
test/functional with an issue reference comment when applicable.
Code

test/github-issues/10263/issue-10263.test.ts[R1-37]

+import { expect } from "chai"
+import type { DataSource } from "../../../src"
+import {
+    closeTestingConnections,
+    createTestingConnections,
+} from "../../utils/test-utils"
+import { Space } from "./entity/Space"
+
+describe("github issues > #10263 closure table should inherit entity schema", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [Space],
+            enabledDrivers: ["postgres"],
+            schemaCreate: false,
+            dropSchema: false,
+        })
+    })
+
+    after(() => closeTestingConnections(dataSources))
+
+    it("should set the same schema on the closure junction table as the parent entity", () => {
+        dataSources.forEach((dataSource) => {
+            const spaceMetadata = dataSource.getMetadata(Space)
+
+            expect(spaceMetadata.schema).to.equal("my_schema")
+            expect(spaceMetadata.closureJunctionTable).to.not.be.undefined
+            expect(spaceMetadata.closureJunctionTable.schema).to.equal(
+                "my_schema",
+            )
+            expect(spaceMetadata.closureJunctionTable.tablePath).to.contain(
+                "my_schema",
+            )
+        })
+    })
+})
Evidence
Compliance ID 3 requires issue-fix tests to be added/updated in test/functional; this PR adds a
new per-issue test under test/github-issues/10263 and provides no clear justification in the PR
content for not using the functional suite.

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

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

## Issue description
A new test was added under `test/github-issues/10263`, but compliance requires issue fixes to live in `test/functional` unless there is a clear reason.
## Issue Context
This PR adds `test/github-issues/10263/issue-10263.test.ts` to cover schema inheritance for closure junction tables.
## Fix Focus Areas
- test/github-issues/10263/issue-10263.test.ts[1-37]

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



Remediation recommended
3. Schema inheritance change undocumented 📘 Rule violation ✓ Correctness
Description
The PR changes user-visible behavior by making closure junction tables inherit schema and
database and by joining via tablePath, but no documentation updates are included. Users relying
on schema-qualified naming/creation may need updated docs or examples to reflect the new behavior.
Code

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[R40-41]

+                schema: parentClosureEntityMetadata.schema,
+                database: parentClosureEntityMetadata.database,
Evidence
The checklist requires docs to be updated for user-facing changes. The PR description and code
changes indicate a behavioral change in where/how closure tables are created and referenced, but no
doc changes are present in the diff.

Rule 2: Docs updated for user-facing changes
src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[40-41]

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 PR changes behavior for closure junction table schema/database inheritance and join identifier quoting, but no documentation updates are included.
## Issue Context
This change can affect users configuring schemas and expecting closure tables to be created/queried in a specific schema; docs or examples should reflect the new behavior.
## Fix Focus Areas
- src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[40-41]
- src/repository/TreeRepository.ts[178-178]
- src/repository/TreeRepository.ts[357-357]

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


4. Qualified closureTableName breaks 🐞 Bug ✓ Correctness
Description
Closure junction tables now always inherit parent schema/database, but if
treeOptions.closureTableName is already qualified (contains "."), EntityMetadata will prepend parent
schema/database on top of that qualified name, producing invalid 3-part identifiers for engines that
expect at most schema.table (or db.table). This is a regression vs previous behavior where the
qualified name could work because no additional schema/database was prepended.
Code

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[R40-41]

+                schema: parentClosureEntityMetadata.schema,
+                database: parentClosureEntityMetadata.database,
Evidence
The closure junction metadata now unconditionally copies parent schema/database while still allowing
an arbitrary closureTableName string. EntityMetadata.build constructs tableName/tablePath without
stripping existing qualifiers from the provided name; namingStrategy.closureJunctionTableName also
preserves dots. Drivers then build tablePath by joining parts with '.', and QueryBuilder later
splits on '.' and escapes each segment—so a qualified name plus inherited schema/database can become
a 3-part escaped identifier, which is invalid on e.g. Postgres/MySQL.

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[26-43]
src/metadata/EntityMetadata.ts[1041-1089]
src/naming-strategy/DefaultNamingStrategy.ts[10-35]
src/driver/postgres/PostgresDriver.ts[1047-1055]
src/driver/mysql/MysqlDriver.ts[524-536]
src/query-builder/QueryBuilder.ts[641-650]

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

## Issue description
`ClosureJunctionEntityMetadataBuilder` now always copies `schema`/`database` from the parent entity, but it still accepts a raw `closureTableName` string that may already be qualified (e.g. `&amp;amp;quot;schema.table&amp;amp;quot;` or `&amp;amp;quot;db.table&amp;amp;quot;`). Because `EntityMetadata.build()` and driver `buildTableName()` do not strip qualifiers embedded in `name`, this can produce invalid multi-part identifiers (e.g. `parentSchema.schema.table_closure`).
### Issue Context
We want closure junction tables to inherit the parent entity’s schema/database, but we must avoid *double-qualifying* when users supply a qualified `closureTableName`.
### Fix Focus Areas
- src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[26-43]
Suggested approach:
- Compute `rawName = treeOptions.closureTableName ?? parent.tableNameWithoutPrefix`.
- `const parsed = this.dataSource.driver.parseTableName(rawName)`
- Set `args.name = parsed.tableName` (unqualified)
- Set `args.schema = parent.schema ?? parsed.schema`
- Set `args.database = parent.database ?? parsed.database`
(Consider adding a regression test where `closureTableName` includes a schema/database qualifier.)

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


Grey Divider Grey Divider
Results up to commit 8032f54


🐞 Bugs (2) 📘 Rule violations (2) 📎 Requirement gaps (0)

Grey Divider
Action required
1. Dotted join string crashes 🐞 Bug ✓ Correctness ⭐ New
Description
TreeRepository now passes closureJunctionTable.tablePath (e.g. my_schema.space_closure) into
innerJoin, and TypeORM interprets any dotted string as alias.property, causing it to resolve a
non-existent alias (e.g. my_schema) and throw. As a result, closure-table
findDescendants/findAncestors queries can fail whenever the closure junction table is
schema/database-qualified.
Code

src/repository/TreeRepository.ts[178]

+                    this.metadata.closureJunctionTable.tablePath,
Evidence
innerJoin() stores the provided string in JoinAttribute.entityOrProperty. Since tablePath
contains a dot when schema/database is set, QueryBuilderUtils.isAliasProperty() classifies it as
alias.property, making JoinAttribute.relation call findAliasByName(parentAlias) which throws.
SelectQueryBuilder.getQuery() always calls createJoinExpression(), and createJoinExpression()
evaluates joinAttr.relation unconditionally, so the throw happens during SQL generation/execution
of TreeRepository queries. This PR also makes closure junction tables inherit schema/database,
which makes closureJunctionTable.tablePath schema-qualified (dotted) for drivers like Postgres,
triggering the problematic parsing path.

src/repository/TreeRepository.ts[176-181]
src/query-builder/QueryBuilderUtils.ts[10-26]
src/query-builder/JoinAttribute.ts[126-134]
src/query-builder/JoinAttribute.ts[160-168]
src/query-builder/QueryExpressionMap.ts[435-443]
src/query-builder/SelectQueryBuilder.ts[80-86]
src/query-builder/SelectQueryBuilder.ts[2356-2360]
src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[28-43]
src/metadata/EntityMetadata.ts[1047-1051]
src/driver/postgres/PostgresDriver.ts[1043-1050]

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

### Issue description
`TreeRepository` now uses `closureJunctionTable.tablePath` as the first argument to `innerJoin`. When the closure junction table has a schema/database, `tablePath` contains dots (e.g. `my_schema.space_closure`). TypeORM’s join parsing treats *any* dotted string as `alias.property` syntax, which makes join building attempt to resolve an alias named `my_schema` and throw (`alias was not found`).

### Issue Context
The PR also propagates `schema`/`database` to the closure junction table metadata, which makes `closureJunctionTable.tablePath` schema-qualified for drivers like Postgres. Combined with the `innerJoin(tablePath, ...)` change, closure-table queries can fail at runtime.

### Fix Focus Areas
- src/repository/TreeRepository.ts[175-182]
- src/repository/TreeRepository.ts[354-360]
- test/github-issues/10263/issue-10263.test.ts[1-37]

### Suggested implementation notes
- In both closure-table query builder branches, change the join target from `this.metadata.closureJunctionTable.tablePath` back to a non-dotted identifier that still resolves metadata, e.g. `this.metadata.closureJunctionTable.tableName` (or `this.metadata.closureJunctionTable.target`).
- Rely on `JoinAttribute.tablePath` to emit `metadata.tablePath` (which will now include schema due to the metadata-builder change).
- Extend the #10263 test to actually run a query that exercises the join (e.g. initialize, synchronize or insert minimal rows, then call `getTreeRepository(Space).findAncestors(...)` or `findDescendants(...)`) to ensure schema-qualified closure joins work end-to-end.

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


2. Issue test added under github-issues 📘 Rule violation ⛯ Reliability
Description
The fix adds coverage only under test/github-issues/10263 without an explicit reason for not
placing it in the functional test suite. This violates the requirement to keep issue fixes in
test/functional with an issue reference comment when applicable.
Code

test/github-issues/10263/issue-10263.test.ts[R1-37]

+import { expect } from "chai"
+import type { DataSource } from "../../../src"
+import {
+    closeTestingConnections,
+    createTestingConnections,
+} from "../../utils/test-utils"
+import { Space } from "./entity/Space"
+
+describe("github issues > #10263 closure table should inherit entity schema", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [Space],
+            enabledDrivers: ["postgres"],
+            schemaCreate: false,
+            dropSchema: false,
+        })
+    })
+
+    after(() => closeTestingConnections(dataSources))
+
+    it("should set the same schema on the closure junction table as the parent entity", () => {
+        dataSources.forEach((dataSource) => {
+            const spaceMetadata = dataSource.getMetadata(Space)
+
+            expect(spaceMetadata.schema).to.equal("my_schema")
+            expect(spaceMetadata.closureJunctionTable).to.not.be.undefined
+            expect(spaceMetadata.closureJunctionTable.schema).to.equal(
+                "my_schema",
+            )
+            expect(spaceMetadata.closureJunctionTable.tablePath).to.contain(
+                "my_schema",
+            )
+        })
+    })
+})
Evidence
Compliance ID 3 requires issue-fix tests to be added/updated in test/functional; this PR adds a
new per-issue test under test/github-issues/10263 and provides no clear justification in the PR
content for not using the functional suite.

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

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

## Issue description
A new test was added under `test/github-issues/10263`, but compliance requires issue fixes to live in `test/functional` unless there is a clear reason.
## Issue Context
This PR adds `test/github-issues/10263/issue-10263.test.ts` to cover schema inheritance for closure junction tables.
## Fix Focus Areas
- test/github-issues/10263/issue-10263.test.ts[1-37]

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



Remediation recommended
3. Schema inheritance change undocumented 📘 Rule violation ✓ Correctness ⭐ New
Description
The PR changes user-visible behavior by making closure junction tables inherit schema and
database and by joining via tablePath, but no documentation updates are included. Users relying
on schema-qualified naming/creation may need updated docs or examples to reflect the new behavior.
Code

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[R40-41]

+                schema: parentClosureEntityMetadata.schema,
+                database: parentClosureEntityMetadata.database,
Evidence
The checklist requires docs to be updated for user-facing changes. The PR description and code
changes indicate a behavioral change in where/how closure tables are created and referenced, but no
doc changes are present in the diff.

Rule 2: Docs updated for user-facing changes
src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[40-41]

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 PR changes behavior for closure junction table schema/database inheritance and join identifier quoting, but no documentation updates are included.

## Issue Context
This change can affect users configuring schemas and expecting closure tables to be created/queried in a specific schema; docs or examples should reflect the new behavior.

## Fix Focus Areas
- src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[40-41]
- src/repository/TreeRepository.ts[178-178]
- src/repository/TreeRepository.ts[357-357]

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


4. Qualified closureTableName breaks 🐞 Bug ✓ Correctness
Description
Closure junction tables now always inherit parent schema/database, but if
treeOptions.closureTableName is already qualified (contains "."), EntityMetadata will prepend parent
schema/database on top of that qualified name, producing invalid 3-part identifiers for engines that
expect at most schema.table (or db.table). This is a regression vs previous behavior where the
qualified name could work because no additional schema/database was prepended.
Code

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[R40-41]

+                schema: parentClosureEntityMetadata.schema,
+                database: parentClosureEntityMetadata.database,
Evidence
The closure junction metadata now unconditionally copies parent schema/database while still allowing
an arbitrary closureTableName string. EntityMetadata.build constructs tableName/tablePath without
stripping existing qualifiers from the provided name; namingStrategy.closureJunctionTableName also
preserves dots. Drivers then build tablePath by joining parts with '.', and QueryBuilder later
splits on '.' and escapes each segment—so a qualified name plus inherited schema/database can become
a 3-part escaped identifier, which is invalid on e.g. Postgres/MySQL.

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[26-43]
src/metadata/EntityMetadata.ts[1041-1089]
src/naming-strategy/DefaultNamingStrategy.ts[10-35]
src/driver/postgres/PostgresDriver.ts[1047-1055]
src/driver/mysql/MysqlDriver.ts[524-536]
src/query-builder/QueryBuilder.ts[641-650]

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

## Issue description
`ClosureJunctionEntityMetadataBuilder` now always copies `schema`/`database` from the parent entity, but it still accepts a raw `closureTableName` string that may already be qualified (e.g. `&amp;quot;schema.table&amp;quot;` or `&amp;quot;db.table&amp;quot;`). Because `EntityMetadata.build()` and driver `buildTableName()` do not strip qualifiers embedded in `name`, this can produce invalid multi-part identifiers (e.g. `parentSchema.schema.table_closure`).
### Issue Context
We want closure junction tables to inherit the parent entity’s schema/database, but we must avoid *double-qualifying* when users supply a qualified `closureTableName`.
### Fix Focus Areas
- src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[26-43]
Suggested approach:
- Compute `rawName = treeOptions.closureTableName ?? parent.tableNameWithoutPrefix`.
- `const parsed = this.dataSource.driver.parseTableName(rawName)`
- Set `args.name = parsed.tableName` (unqualified)
- Set `args.schema = parent.schema ?? parsed.schema`
- Set `args.database = parent.database ?? parsed.database`
(Consider adding a regression test where `closureTableName` includes a schema/database qualifier.)

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


Grey Divider Grey Divider
Results up to commit N/A


🐞 Bugs (1) 📘 Rule violations (1) 📎 Requirement gaps (0)

Grey Divider
Action required
1. Issue test added under github-issues 📘 Rule violation ⛯ Reliability
Description
The fix adds coverage only under test/github-issues/10263 without an explicit reason for not
placing it in the functional test suite. This violates the requirement to keep issue fixes in
test/functional with an issue reference comment when applicable.
Code

test/github-issues/10263/issue-10263.test.ts[R1-37]

+import { expect } from "chai"
+import type { DataSource } from "../../../src"
+import {
+    closeTestingConnections,
+    createTestingConnections,
+} from "../../utils/test-utils"
+import { Space } from "./entity/Space"
+
+describe("github issues > #10263 closure table should inherit entity schema", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [Space],
+            enabledDrivers: ["postgres"],
+            schemaCreate: false,
+            dropSchema: false,
+        })
+    })
+
+    after(() => closeTestingConnections(dataSources))
+
+    it("should set the same schema on the closure junction table as the parent entity", () => {
+        dataSources.forEach((dataSource) => {
+            const spaceMetadata = dataSource.getMetadata(Space)
+
+            expect(spaceMetadata.schema).to.equal("my_schema")
+            expect(spaceMetadata.closureJunctionTable).to.not.be.undefined
+            expect(spaceMetadata.closureJunctionTable.schema).to.equal(
+                "my_schema",
+            )
+            expect(spaceMetadata.closureJunctionTable.tablePath).to.contain(
+                "my_schema",
+            )
+        })
+    })
+})
Evidence
Compliance ID 3 requires issue-fix tests to be added/updated in test/functional; this PR adds a
new per-issue test under test/github-issues/10263 and provides no clear justification in the PR
content for not using the functional suite.

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

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

## Issue description
A new test was added under `test/github-issues/10263`, but compliance requires issue fixes to live in `test/functional` unless there is a clear reason.

## Issue Context
This PR adds `test/github-issues/10263/issue-10263.test.ts` to cover schema inheritance for closure junction tables.

## Fix Focus Areas
- test/github-issues/10263/issue-10263.test.ts[1-37]

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



Remediation recommended
2. Qualified closureTableName breaks 🐞 Bug ✓ Correctness
Description
Closure junction tables now always inherit parent schema/database, but if
treeOptions.closureTableName is already qualified (contains "."), EntityMetadata will prepend parent
schema/database on top of that qualified name, producing invalid 3-part identifiers for engines that
expect at most schema.table (or db.table). This is a regression vs previous behavior where the
qualified name could work because no additional schema/database was prepended.
Code

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[R40-41]

+                schema: parentClosureEntityMetadata.schema,
+                database: parentClosureEntityMetadata.database,
Evidence
The closure junction metadata now unconditionally copies parent schema/database while still allowing
an arbitrary closureTableName string. EntityMetadata.build constructs tableName/tablePath without
stripping existing qualifiers from the provided name; namingStrategy.closureJunctionTableName also
preserves dots. Drivers then build tablePath by joining parts with '.', and QueryBuilder later
splits on '.' and escapes each segment—so a qualified name plus inherited schema/database can become
a 3-part escaped identifier, which is invalid on e.g. Postgres/MySQL.

src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[26-43]
src/metadata/EntityMetadata.ts[1041-1089]
src/naming-strategy/DefaultNamingStrategy.ts[10-35]
src/driver/postgres/PostgresDriver.ts[1047-1055]
src/driver/mysql/MysqlDriver.ts[524-536]
src/query-builder/QueryBuilder.ts[641-650]

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

### Issue description
`ClosureJunctionEntityMetadataBuilder` now always copies `schema`/`database` from the parent entity, but it still accepts a raw `closureTableName` string that may already be qualified (e.g. `&quot;schema.table&quot;` or `&quot;db.table&quot;`). Because `EntityMetadata.build()` and driver `buildTableName()` do not strip qualifiers embedded in `name`, this can produce invalid multi-part identifiers (e.g. `parentSchema.schema.table_closure`).

### Issue Context
We want closure junction tables to inherit the parent entity’s schema/database, but we must avoid *double-qualifying* when users supply a qualified `closureTableName`.

### Fix Focus Areas
- src/metadata-builder/ClosureJunctionEntityMetadataBuilder.ts[26-43]

Suggested approach:
- Compute `rawName = treeOptions.closureTableName ?? parent.tableNameWithoutPrefix`.
- `const parsed = this.dataSource.driver.parseTableName(rawName)`
- Set `args.name = parsed.tableName` (unqualified)
- Set `args.schema = parent.schema ?? parsed.schema`
- Set `args.database = parent.database ?? parsed.database`

(Consider adding a regression test where `closureTableName` includes a schema/database qualifier.)

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


Grey Divider Grey Divider
Qodo Logo

@alumni

alumni commented Mar 10, 2026 •

Copy link
Copy Markdown
Collaborator

I could swear I've seen something like this before. See #10743, specifically this: #10743 (comment)

I think a combination of the two PRs would be great to have.

CC @gioboa

@pkg-pr-new

pkg-pr-new Bot commented Mar 10, 2026 •

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

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

commit: 0430555

@coveralls

coveralls commented Mar 10, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 73.219% (-0.03%) from 73.25%
when pulling 0430555 on nvdnkpr:fix/closure-table-schema-inheritance
into b2cba0b on typeorm:master.

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

Copy link
Copy Markdown

Persistent review updated to latest commit 8032f54

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

Copy link
Copy Markdown

Persistent review updated to latest commit 4964e0d

@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 🙏 @nvdnkpr

@gioboa
gioboa enabled auto-merge (squash) March 18, 2026 14:11
@sonarqubecloud

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Persistent review updated to latest commit 0430555

@gioboa
gioboa merged commit 981d601 into typeorm:master Mar 18, 2026
43 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone Mar 18, 2026
pkuczynski pushed a commit that referenced this pull request Mar 21, 2026
Co-authored-by: Navid Nikpour <[email protected]>
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Lucian Mocanu <[email protected]>
Co-authored-by: Giorgio Boa <[email protected]>
xEverth pushed a commit to xEverth/typeorm that referenced this pull request Jun 18, 2026
… the Tree decorator as typeorm#10743

Test locally with multiple database drivers which support the "schema" options
Update tests to remove driver-specific assumptions on closure table metadata's tablePath
Add functional test case for different schema options provided to the parent Entity and the Tree decorator
xEverth pushed a commit to xEverth/typeorm that referenced this pull request Jun 18, 2026
… the Tree decorator as typeorm#10743

Test locally with multiple database drivers which support the "schema" options
Update tests to remove driver-specific assumptions on closure table metadata's tablePath
Add functional test case for different schema options provided to the parent Entity and the Tree decorator
xEverth pushed a commit to xEverth/typeorm that referenced this pull request Jun 19, 2026
… the Tree decorator as typeorm#10743

Test locally with multiple database drivers which support the "schema" options
Update tests to remove driver-specific assumptions on closure table metadata's tablePath
Add functional test case for different schema options provided to the parent Entity and the Tree decorator
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.

Postgres @Tree specify schema for closure tables

4 participants