Skip to content

fix(cockroachdb): adjust join in loadTables to load correct table columns - #12413

Merged
alumni merged 7 commits into
typeorm:masterfrom
Cprakhar:fix/cockroachdb-loadTables
May 18, 2026
Merged

alumni merged 7 commits into
typeorm:masterfrom
Cprakhar:fix/cockroachdb-loadTables

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Apr 25, 2026 •

Copy link
Copy Markdown
Collaborator

Description of change

  • Removed debug log from database-schema/enums/enums.test.ts.
  • Added a test description in persistence/persistence-order/persistence-order.test.ts.
  • Fix typo in SELECT * FROM "${database}"."sys"."schema" - "sys"."schema" -> "sys"."schemas". (SqlServerQueryRunner.ts)
  • Updated columnsSql query in CockroachDB loadTables to query correct columns from the schema and table.
    Why: Let's say we have two tables, public.post and custom.post, both having name as a column. With columnsSql, it was returning two columns name for the table public.post.
  • Added CockroachDB and SAP HANA in the multi-schema-and-database test suite.

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)

@pkg-pr-new

pkg-pr-new Bot commented Apr 25, 2026 •

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

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

commit: d6cdb93

@Cprakhar
Cprakhar marked this pull request as ready for review April 25, 2026 07:20
@Cprakhar Cprakhar self-assigned this Apr 25, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Apr 25, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. WHERE precedence bug ✓ Resolved 🐞 Bug ≡ Correctness
Description
In CockroachQueryRunner.loadTables, columnsSql is constructed as `WHERE "is_hidden" = 'NO' AND
<cond1> OR <cond2> ... (no parentheses), so is_hidden` filtering only applies to the first OR
clause when multiple tables are loaded. This can return hidden columns for other tables and corrupt
table metadata returned by getTables/schema sync.
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R3222-3224]

`LEFT JOIN "pg_attribute" AS "attr" ON "attr"."attrelid" = "cls"."oid" AND "attr"."attname" = "column_name" AND "attr"."attnum" = "ordinal_position" ` +
`WHERE "is_hidden" = 'NO' AND ` +
columnsCondiiton
Evidence
When tableNames is not provided, loadTables queries *all* tables into dbTables, meaning the
generated columnsCondiiton is typically an OR-joined list of multiple table predicates. Because
columnsSql concatenates WHERE "is_hidden" = 'NO' AND  directly with that OR string (without
wrapping it in parentheses), SQL precedence rules make the filter equivalent to `(is_hidden='NO' AND
cond1) OR cond2 OR cond3..., allowing rows matching cond2/cond3 regardless of is_hidden`.

src/driver/cockroachdb/CockroachQueryRunner.ts[3188-3205]
src/driver/cockroachdb/CockroachQueryRunner.ts[3211-3225]

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

## Issue description
`columnsSql` in `CockroachQueryRunner.loadTables` appends an OR-joined `columnsCondiiton` directly after `WHERE "is_hidden" = 'NO' AND `. Because `AND` binds tighter than `OR`, `is_hidden='NO'` only applies to the first OR term when multiple tables are present.
### Issue Context
This runs when loading multiple tables (e.g., `getTables()` during schema sync). The intended semantics are to apply `is_hidden='NO'` to *all* table predicates.
### Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[3211-3225]
### Suggested change
Update the SQL construction to wrap the OR condition:
- `... WHERE "is_hidden" = 'NO' AND (${columnsCondiiton})`
This preserves the intended filtering for every table condition.

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



Remediation recommended

2. Unescaped schema/table literals 🐞 Bug ⛨ Security
Description
CockroachQueryRunner.loadTables interpolates schema/table names into SQL string literals when
building the WHERE clause. If a schema or table name contains a single-quote, the generated SQL
becomes invalid (and with untrusted identifiers, this can become an injection vector), causing
getTable/getTables introspection to fail.
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R3212-3214]

.map(({ table_name, table_schema }) => {
return `("table_schema" = '${table_schema}' AND "table_name" = '${table_name}')`
})
Evidence
The WHERE clause is assembled by string-interpolating table_schema/table_name values inside
single-quoted literals, with no escaping/parameter binding before executing the query.

src/driver/cockroachdb/CockroachQueryRunner.ts[3192-3224]

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

## Issue description
`CockroachQueryRunner.loadTables` builds `tablesCondition`/`columnsCondition` by embedding schema/table names directly into SQL string literals (e.g., `... = '${table_schema}'`). This can break introspection when identifiers contain `'`, and it’s an avoidable injection surface if identifiers are not fully trusted.
### Issue Context
This affects metadata loading queries (e.g., `columnsSql`) used by `getTable/getTables` and schema sync.
### Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[3192-3224]
### Implementation guidance
- Replace string interpolation with positional parameters.
- Generate `("table_schema" = $1 AND "table_name" = $2) OR (...)` with a flat `parameters: any[]` array, and call `this.query(columnsSql, parameters)`.
- Apply the same approach to `tablesCondition` when `tableNames` is provided.

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


3. SQL assertion can be skipped ✓ Resolved 🐞 Bug ☼ Reliability
Description
The new expectSqlByDriver helper only asserts when it can derive an expected SQL string; otherwise
it silently performs no check. This can let tests pass without validating generated SQL when new
drivers are added or when an expected mapping is accidentally omitted.
Code

test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/multi-schema-and-database-basic-functionality.test.ts[R63-88]

+function expectSqlByDriver(
+    dataSource: DataSource,
+    sql: string,
+    expected: {
+        parameterized?: string
+        postgres?: string
+        mssql?: string
+        sap?: string
+        mysql?: string
+    },
+) {
+    const parameterPlaceholder = getParameterPlaceholder(dataSource)
+
+    if (
+        expected.parameterized !== undefined &&
+        parameterPlaceholder !== undefined
+    ) {
+        sql.should.be.equal(
+            expected.parameterized.replaceAll(":param", parameterPlaceholder),
+        )
+        return
+    }
+
+    const expectedSql = getExpectedSqlByDriver(dataSource, expected)
+    if (expectedSql !== undefined) sql.should.be.equal(expectedSql)
+}
Evidence
If neither the parameterized path matches nor getExpectedSqlByDriver returns a string, the
function completes without any assertion/failure.

test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/multi-schema-and-database-basic-functionality.test.ts[63-88]

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

## Issue description
`expectSqlByDriver` can complete without asserting anything when `expectedSql` is `undefined` (and `parameterized` isn’t asserted). This weakens the test suite by allowing silent passes.
### Issue Context
This helper is intended to verify SQL generation across drivers; missing assertions reduce regression detection.
### Fix Focus Areas
- test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/multi-schema-and-database-basic-functionality.test.ts[63-88]
### Implementation guidance
- After computing `expectedSql`, if it is `undefined`, explicitly fail the test, e.g.:
- `throw new Error(`No expected SQL configured for driver: ${driverType}`)`
- or `expect.fail(...)`
- Optionally include `sql` in the error message to aid debugging.

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


4. columnsCondiiton typo variable name ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The modified query string still references columnsCondiiton, a misspelled identifier that deviates
from consistent naming conventions and reduces code readability/maintainability. This should be
corrected to a properly spelled camelCase name (e.g., columnsCondition).
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[3224]

+            `(${columnsCondiiton})`
Evidence
PR Compliance ID 1 requires consistent naming conventions; the changed line uses the misspelled
identifier columnsCondiiton, which is inconsistent and error-prone.

Rule 1: Consistent Naming Conventions
src/driver/cockroachdb/CockroachQueryRunner.ts[3224-3224]

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 CockroachDB query-building code uses a misspelled identifier `columnsCondiiton`, which violates naming consistency expectations and reduces readability.
## Issue Context
This identifier is used to build the `columnsSql` WHERE clause; rename it to a correctly spelled camelCase name and update all references in the same scope.
## Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[3211-3224]

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


View more (1)
5. Test misses join regression ✓ Resolved 🐞 Bug ≡ Correctness
Description
In the multi-schema basic-functionality suite, Post and PostWithSchema both map to the same
physical table when the connection schema is set to "custom", so the test does not create two
schemas containing a post table and cannot exercise the Cockroach loadTables join fix described
in the PR.
Code

test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/multi-schema-and-database-basic-functionality.test.ts[R248-263]

+    describe("custom-table-schema", () => {
+        const drivers: DatabaseType[][] = [
+            // SAP throws error during connection if schema specified in connection options does not exist.
+            // only testing custom schema specified in Entity decorator
+            ["sap"],
+            ["mssql", "postgres", "cockroachdb"],
+        ]
+        for (const driver of drivers) {
+            describe(`${driver.join("|")}`, () => {
+                let dataSources: DataSource[]
+                before(async () => {
+                    dataSources = await createTestingConnections({
+                        entities: [User, Category, Post, PostWithSchema],
+                        enabledDrivers: driver,
+                        schema: driver.includes("sap") ? undefined : "custom",
+                    })
Evidence
The test config sets schema: "custom" (for the postgres/mssql/cockroachdb driver set) while
registering both Post (default table name post) and PostWithSchema (`schema: "custom", name:
"post"), causing both entities to resolve to custom.post instead of creating two post` tables in
different schemas (the scenario needed to reproduce the Cockroach duplicate-column bug).

test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/multi-schema-and-database-basic-functionality.test.ts[248-264]
test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/entity/Post.ts[1-12]
test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/entity/PostWithSchema.ts[1-10]

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 updated test suite intends to validate CockroachDB column loading when two schemas contain the same table name, but the current setup maps both `Post` and `PostWithSchema` to `custom.post` when `schema: "custom"` is set on the connection. This prevents the test from reproducing the reported regression scenario.
### Issue Context
The PR description explains the bug happens with e.g. `public.post` and `custom.post` both having a `name` column, leading to duplicated columns being returned for one table. The test should therefore ensure **two distinct schemas** each contain a **`post`** table.
### Fix Focus Areas
- test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/multi-schema-and-database-basic-functionality.test.ts[248-264]
- test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/entity/PostWithSchema.ts[1-10]
- test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/entity/Post.ts[1-12]
### Concrete fix options (pick one)
1) **For cockroachdb (and possibly postgres), don’t set connection `schema: "custom"`**, so `Post` creates `public.post` (or the DB default), and keep `PostWithSchema` as `custom.post`.
2) Keep connection `schema: "custom"`, but change `PostWithSchema` to use a **different schema** (e.g. `schema: "other"`) while still keeping `name: "post"`, ensuring two schemas contain `post`.
After the change, add/assert a check that both schema-qualified tables exist (e.g., queryRunner.getTable("post") + queryRunner.getTable("custom.post") or two explicit schema-qualified paths depending on driver) and that `table.columns` for each is not duplicated.

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



Advisory comments

6. Mixed Chai assertion styles 🐞 Bug ⚙ Maintainability
Description
multi-schema-and-database-basic-functionality.test.ts uses expect(...).should..., mixing Chai’s
expect and should interfaces in one chain, which is inconsistent with the surrounding tests and
makes the assertion intent harder to follow. This should be rewritten to a single style
(expect(...).to... or (value).should...) for clarity and maintainability.
Code

test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/multi-schema-and-database-basic-functionality.test.ts[185]

+                    expect(await query.getRawOne()).should.be.not.empty
Evidence
The changed line uses expect(...).should... while the same file elsewhere uses standard
expect(...).to... style; additionally, the repo globally enables should via chai.should(), so
both styles are available—making consistency especially important to avoid confusion.

test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/multi-schema-and-database-basic-functionality.test.ts[176-202]
test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/multi-schema-and-database-basic-functionality.test.ts[320-333]
test/utils/test-setup.ts[5-14]

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 test assertion mixes Chai `expect` and `should` styles in the same expression (`expect(...).should...`), which is inconsistent with the rest of the file and reduces readability/maintainability.
### Issue Context
The repo enables Chai's `should` interface globally, but tests in this file largely use `expect(...).to...`.
### Fix Focus Areas
- test/functional/multi-schema-and-database/multi-schema-and-database-basic-functionality/multi-schema-and-database-basic-functionality.test.ts[176-202]
### Suggested change
Replace:
- `expect(await query.getRawOne()).should.be.not.empty`
With either:
- `expect(await query.getRawOne()).to.be.not.empty`
or:
- `;(await query.getRawOne())!.should.be.not.empty`

ⓘ 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

@Cprakhar Cprakhar changed the title fix(cockroachdb): adjust SQL join order for column retrieval and enhance test coverage for custom schemas fix(cockroachdb): adjust join in loadTables to load correct table columns Apr 25, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit cd9c44a

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

Copy link
Copy Markdown

Persistent review updated to latest commit 59132d0

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

Copy link
Copy Markdown

Persistent review updated to latest commit 6e87dfd

Comment on lines 98 to 99
sqlInMemory.upQueries.length.should.be.equal(0)
sqlInMemory.downQueries.length.should.be.equal(0)

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.

Whenever we have console.log in tests, we are trying to figure out why an assertion is not working. This can always be solved by introducing better assertions, e.g.: expect(array).to.have.length(0) (or lengthOf?) would also log the array values if the expectation is not met ;)

@@ -24,25 +24,30 @@ describe("multi-schema-and-database > custom-junction-schema", () => {
Promise.all(
dataSources.map(async (dataSource) => {
const queryRunner = dataSource.createQueryRunner()

@alumni alumni Apr 26, 2026 •

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.

Instead of adding try-finally and introducing another level of indentation:

Suggested change
const queryRunner = dataSource.createQueryRunner()
await using queryRunner = dataSource.createQueryRunner()

Same can be done in the other tests.

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

Copy link
Copy Markdown

Persistent review updated to latest commit 95b1aa9

expect(table.database).to.be.equal("testDB")
expect(table.schema).to.be.equal("questions")
expect(table.name).to.be.equal("testDB.questions.question")
expect(table!.database).to.equal("testDB")

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.

nit (no need to change unless there's another change): this is an unnecessary change. we are now making this assertion 3 times instead of only one (before). In tests, we often know that the table exists, so we place the assertion when we read the table.

Comment on lines +184 to +191
describe("custom-table-schema", () => {
const drivers: DatabaseType[][] = [
// SAP throws error during connection if schema specified in connection options does not exist.
// only testing custom schema specified in Entity decorator
["sap"],
["mssql", "postgres", "cockroachdb"],
]
for (const driver of drivers) {

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 not sure what are we trying to test here, but we don't have this test structure usually. Additionally, the schema should exist before connecting to the database.

These new tests could be simplified a lot

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

SAP HANA has a currentSchema option in the @sap-client package, which is passed if defined in DataSourceOptions.schema, which throws errors. Other drivers in the tests don't have this. Schemas are created beforehand using the logic in test-utils.ts

I will try to simplify this.

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.

Yeah, we pass DataSourceOptions.schema to the client, which is fine, because the schema that you pass to the client should exist. It's simpler than executing a query to change the schema every time you create a QueryRunner. I only changed it like that for the SAP driver since I'm more familiar with it, but you can make that assumption for all drivers.

@Cprakhar
Cprakhar force-pushed the fix/cockroachdb-loadTables branch from 95b1aa9 to 9837a59 Compare May 2, 2026 19:30
@Cprakhar
Cprakhar force-pushed the fix/cockroachdb-loadTables branch from 9298386 to 8b74705 Compare May 2, 2026 20:08
@alumni alumni added the backport This fix should be backported to a previous version label May 16, 2026
@alumni

alumni commented May 18, 2026

Copy link
Copy Markdown
Collaborator

@Cprakhar FYI cherry picking to 0.3 would not be possible for tests (since they use await using which was added in 1.0 only)

@alumni
alumni merged commit df09802 into typeorm:master May 18, 2026
46 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone May 18, 2026
alumni added a commit that referenced this pull request May 18, 2026
…umns (#12413)

Co-authored-by: Lucian Mocanu <[email protected]>
(cherry picked from commit df09802)
alumni added a commit that referenced this pull request May 18, 2026
…umns (#12413)

Co-authored-by: Lucian Mocanu <[email protected]>
(cherry picked from commit df09802)
@alumni alumni removed the backport This fix should be backported to a previous version label May 18, 2026
alumni added a commit that referenced this pull request May 18, 2026
…umns (#12413)

Co-authored-by: Lucian Mocanu <[email protected]>
(cherry picked from commit df09802)
@Cprakhar
Cprakhar deleted the fix/cockroachdb-loadTables branch June 13, 2026 21:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

3 participants