Skip to content

perf(postgres,cockroachdb): stop rescanning the catalog for each table - #13050

Open
samuelmbabhazi wants to merge 4 commits into
typeorm:masterfrom
samuelmbabhazi:fix/load-tables-linear
Open

samuelmbabhazi wants to merge 4 commits into
typeorm:masterfrom
samuelmbabhazi:fix/load-tables-linear

Conversation

@samuelmbabhazi

@samuelmbabhazi samuelmbabhazi commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Description of change

Fixes #12745.

loadTables() scanned the column, constraint, index and foreign key arrays once per table, and the constraints again once per column, so schema loading grew with tables times rows. The rows are now grouped once before the loop, by table, by column and by constraint name. OrmUtils.uniq still compares within one table's constraints, which I left alone because it is shared code. CockroachDB had the same loop, so it gets the same change.

This is meant to change speed only. Lookups that were global by constraint name stay global, so the loaded tables are the same.

Measured against real databases, running the old and new loadTables on the same schema (19 columns per table, composite primary key, two unique constraints, a check, a foreign key and an index), and comparing the loaded tables with isDeepStrictEqual:

Database Tables Before After Same result
PostgreSQL 17.9 1,600 about 6.3 s about 1.8 s yes
CockroachDB v24.3.8 120 about 0.85 s about 0.7 s yes

A second comparison covered a harder schema on both databases: enums, arrays, generated columns, a partial unique index, a composite foreign key, a table with no constraints, same-named constraints across schemas, and an exclusion constraint on PostgreSQL. The loaded tables were identical there too.

The new test creates a same-named table in two schemas and checks that each one gets only its own columns, foreign key and index. It fails if the grouping key leaves out the schema.

Test runs: the full suite on PostgreSQL 17.9 has 3154 passing and one failure, RedisQueryResultCache Integration, because testcontainers can't reach Docker on my machine. On CockroachDB v24.3.8 the schema builder, query runner, database schema and migration suites have 541 passing.

Most of the diff is indentation, because the column mapping lost a level of nesting. It's easier to read with whitespace hidden (?w=1).

This overlaps #12916, which rewrites the same loop to run sequentially. Whichever lands second needs a rebase. I'm happy to do it if this one goes second.

One thing I left alone on purpose: unique, check and foreign key constraints are looked up by name across all tables. Two tables with a constraint of the same name, for example the same table in two schemas, each get the columns of both. I can open a separate issue for it.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links a relevant issue using a closing keyword: Fixes #12745
  • 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, no behaviour change

… size

loadTables scanned every catalog array once per table, and the constraints
once per column, so schema loading grew with tables times rows. The rows are
now grouped once by table and by constraint name. Lookups that were global by
constraint name stay global, so the loaded tables do not change.
@github-actions github-actions Bot added the linked-issue PR references an issue label Nov 9, 2026
@pkg-pr-new

pkg-pr-new Bot commented Nov 9, 2026 •

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

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

commit: 18c638c

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

qodo-free-for-open-source-projects Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Added explanatory comment repeats the code's purpose 📘 Rule violation ⚙ Maintainability
Description
The new comment // Group the catalog rows once, so loading stays linear in the schema size.
restates what the grouping block below it already shows, and the same comment is pasted into both
the PostgreSQL and CockroachDB loadTables paths. The compliance item treats extra comments as a
failure, and a later reader gets a second copy of the same explanation to keep in sync if the
grouping changes.
Code

packages/typeorm/src/driver/postgres/PostgresQueryRunner.ts[3792]

+        // Group the catalog rows once, so loading stays linear in the schema size.
Evidence
The compliance item lists 'No extra comments' as a success criterion. The PR adds this same one-line
comment in both drivers, directly above the grouping constants it describes, so it adds no
information beyond the code.

Rule 4: Remove AI-generated noise
packages/typeorm/src/driver/cockroachdb/CockroachQueryRunner.ts[3341-3341]

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 adds the comment `// Group the catalog rows once, so loading stays linear in the schema size.` above the row-grouping constants in `loadTables` in both drivers. It restates the code and is duplicated, which the PR-Compliance rule 'Remove AI-generated noise' discourages.
## Fix Focus Areas
- packages/typeorm/src/driver/postgres/PostgresQueryRunner.ts[3792-3792]
- packages/typeorm/src/driver/cockroachdb/CockroachQueryRunner.ts[3341-3341]
## Recommended Fix
Delete the added comment line in both files. Keep the code unchanged. The grouping constants are self-explanatory from their names and the `OrmUtils.groupInMap` calls.

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


2. Large tables still load quadratically ✓ Resolved
Description
loadTables still scans every table constraint for each column in both drivers, and PostgreSQL
scans every table index row again for each distinct index. A table with proportional numbers of
columns and constraint rows, or many distinct indexes, therefore incurs quadratic work even when its
catalog rows and loaded objects grow linearly.

Grey Divider

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

Grey Divider

Context sources
Review mode: Auto: ⚖️ Balanced: Downgraded extended -> standard: change is below the extended eligibility bar (hunks 14/18, lines 1721/200; both must reach the floor). Router rationale: Large cross-driver refactor with many independent, subtle schema-loading behavior paths.

Grey Divider

Tip of the day
💡 Did you know, you can reply 'qodo' on any finding to push back, ask questions, or dig deeper

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit 18c638c ⚖️ Balanced

Results up to commit 46a4c83


🐞 Bugs (0) 📘 Rule violations (1) 📜 Skill insights (0)


Remediation recommended
1. Added explanatory comment repeats the code's purpose 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The new comment // Group the catalog rows once, so loading stays linear in the schema size.
restates what the grouping block below it already shows, and the same comment is pasted into both
the PostgreSQL and CockroachDB loadTables paths. The compliance item treats extra comments as a
failure, and a later reader gets a second copy of the same explanation to keep in sync if the
grouping changes.
Code

packages/typeorm/src/driver/postgres/PostgresQueryRunner.ts[3792]

+        // Group the catalog rows once, so loading stays linear in the schema size.
Evidence
The compliance item lists 'No extra comments' as a success criterion. The PR adds this same one-line
comment in both drivers, directly above the grouping constants it describes, so it adds no
information beyond the code.

Rule 4: Remove AI-generated noise
packages/typeorm/src/driver/cockroachdb/CockroachQueryRunner.ts[3341-3341]

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 adds the comment `// Group the catalog rows once, so loading stays linear in the schema size.` above the row-grouping constants in `loadTables` in both drivers. It restates the code and is duplicated, which the PR-Compliance rule 'Remove AI-generated noise' discourages.

## Fix Focus Areas
- packages/typeorm/src/driver/postgres/PostgresQueryRunner.ts[3792-3792]
- packages/typeorm/src/driver/cockroachdb/CockroachQueryRunner.ts[3341-3341]

## Recommended Fix
Delete the added comment line in both files. Keep the code unchanged. The grouping constants are self-explanatory from their names and the `OrmUtils.groupInMap` calls.

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


2. Large tables still load quadratically ✓ Resolved
Description
loadTables still scans every table constraint for each column in both drivers, and PostgreSQL
scans every table index row again for each distinct index. A table with proportional numbers of
columns and constraint rows, or many distinct indexes, therefore incurs quadratic work even when its
catalog rows and loaded objects grow linearly.

Context sources
Review mode: Auto: ⚖️ Balanced: Downgraded extended -> standard: change is below the extended eligibility bar (hunks 14/18, lines 1723/200; both must reach the floor). Router rationale: Large cross-driver refactor with substantial logic and multiple independent regression risks.
Results up to commit d60801b


🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)


Remediation recommended
1. Large tables still load quadratically ✓ Resolved
Description
loadTables still scans every table constraint for each column in both drivers, and PostgreSQL
scans every table index row again for each distinct index. A table with proportional numbers of
columns and constraint rows, or many distinct indexes, therefore incurs quadratic work even when its
catalog rows and loaded objects grow linearly.

Context sources
Review mode: Auto: ⚖️ Balanced: Refactors core schema loading in two drivers; equivalence matters, but logic is contained.
Results up to commit 492ae0d


🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)


Remediation recommended
1. Large tables still load quadratically 🐞 Bug ➹ Performance
Description
loadTables still scans every table constraint for each column in both drivers, and PostgreSQL
scans every table index row again for each distinct index. A table with proportional numbers of
columns and constraint rows, or many distinct indexes, therefore incurs quadratic work even when its
catalog rows and loaded objects grow linearly.
Code

packages/typeorm/src/driver/postgres/PostgresQueryRunner.ts[R3839-3842]

+                        const columnConstraints = tableConstraints.filter(
+                            (dbConstraint) =>
+                                dbConstraint["column_name"] ===
+                                dbColumn["column_name"],
Evidence
The new groups stop at table granularity. Each column filters its table's entire constraint array,
and each PostgreSQL index filters its table's entire index array; the catalog queries can return one
row per constrained column or index. The existing uniq helper also scans previously accepted
items, so replacing just the two filters would not complete the stated linear-time goal.

packages/typeorm/src/driver/postgres/PostgresQueryRunner.ts[3792-3817]
packages/typeorm/src/driver/postgres/PostgresQueryRunner.ts[3838-3843]
packages/typeorm/src/driver/postgres/PostgresQueryRunner.ts[4333-4343]
packages/typeorm/src/driver/cockroachdb/CockroachQueryRunner.ts[3388-3394]
packages/typeorm/src/driver/postgres/PostgresQueryRunner.ts[3731-3752]
packages/typeorm/src/util/OrmUtils.ts[83-108]

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 table-level maps remove cross-table scans, but repeated scans within a large table prevent `loadTables` from being linear in catalog size.

## Fix Focus Areas
- packages/typeorm/src/driver/postgres/PostgresQueryRunner.ts[3838-3843]
- packages/typeorm/src/driver/postgres/PostgresQueryRunner.ts[4333-4343]
- packages/typeorm/src/driver/cockroachdb/CockroachQueryRunner.ts[3389-3394]
- packages/typeorm/src/util/OrmUtils.ts[83-108]

## Recommended Fix
Group each table's constraints by column before mapping its columns. Group PostgreSQL index rows by name before building indexes. Account for the remaining quadratic `OrmUtils.uniq` calls when processing many distinct constraints or indexes, while preserving catalog row order and the existing global-by-name lookups.

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


Context sources
Review mode: Auto: ⚖️ Balanced: Real logic changes in two schema loaders; mostly re-indentation, so not extended.

Grey Divider

Qodo Logo

@samuelmbabhazi samuelmbabhazi changed the title perf(postgres,cockroachdb): load tables in time linear to the catalog size perf(postgres,cockroachdb): stop rescanning the catalog for each table Nov 9, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

linked-issue PR references an issue

Development

Successfully merging this pull request may close these issues.

Postgres loadTables() re-scans the whole catalog per table (quadratic schema loading)

2 participants