Skip to content

perf(cockroachdb): batch DROP statements in clearDatabase() - #12159

Merged
pkuczynski merged 4 commits into
masterfrom
perf/batch-cockroachdb-drop-statements
Mar 11, 2026
Merged

pkuczynski merged 4 commits into
masterfrom
perf/batch-cockroachdb-drop-statements

Conversation

@pkuczynski

@pkuczynski pkuczynski commented Mar 9, 2026 •

Copy link
Copy Markdown
Member

CockroachDB tests take 20+ minutes while other databases complete in 2–3 minutes. A major contributor is clearDatabase(), which is called via synchronize(true) in every test's beforeEach. Previously, it executed each DROP as a separate query — for N tables, that meant N+1 round-trips (1 SELECT + N individual DROPs), repeated for views, tables, sequences, and enum types.

This batches all DROP operations into single statements:

-- Before: N individual queries
DROP TABLE IF EXISTS "public"."users" CASCADE;
DROP TABLE IF EXISTS "public"."posts" CASCADE;
DROP TABLE IF EXISTS "public"."comments" CASCADE;

-- After: 1 batched query
DROP TABLE IF EXISTS "public"."users", "public"."posts", "public"."comments" CASCADE

Applied to all four object types (views, tables, sequences, enums), reducing the total from 4×(N+1) queries down to 4×2 queries per clearDatabase() call.

Additionally hardens the DROP statements:

  • Use quote_ident() for enum type names instead of manual double-quote concatenation
  • Add IF EXISTS to DROP SEQUENCE for resilience to concurrent cleanup
  • Filter information_schema.tables by table_type = 'BASE TABLE' to avoid dropping views as tables

@pkuczynski pkuczynski self-assigned this Mar 9, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Review Summary by Qodo

Batch DROP statements in CockroachDB clearDatabase()

✨ Enhancement

Grey Divider

Walkthroughs

Description
• Batch DROP statements for views, tables, sequences, and enums
• Reduce database round-trips from 4×(N+1) to 4×2 per clearDatabase() call
• Refactor query generation to collect object names then execute single batched DROP
• Significantly improve CockroachDB test performance (20+ minutes to 2-3 minutes)
Diagram
flowchart LR
  A["SELECT object names<br/>views, tables, sequences, enums"] -->|"Collect names"| B["Build batched<br/>DROP statements"]
  B -->|"Single query per type"| C["Execute DROP<br/>with all objects"]
  C -->|"Reduce round-trips"| D["Improved test<br/>performance"]
Loading

Grey Divider

File Changes

1. src/driver/cockroachdb/CockroachQueryRunner.ts ✨ Enhancement +42/-25

Batch DROP statements for database objects

• Refactored clearDatabase() to batch DROP statements for views, tables, and sequences
• Changed from executing individual DROP queries to collecting object names and executing single
 batched DROP per type
• Refactored dropEnumTypes() method to use same batching pattern for enum types
• Added conditional checks to only execute DROP statements when objects exist

src/driver/cockroachdb/CockroachQueryRunner.ts


Grey Divider

Qodo Logo

@pkg-pr-new

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

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

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

commit: 7af618e

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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Views dropped as tables 🐞 Bug ✓ Correctness
Description
CockroachQueryRunner.clearDatabase() selects drop targets from information_schema.tables without
restricting to BASE TABLE and then issues a DROP TABLE for every returned name. This can attempt to
drop views as tables and abort clearDatabase(), breaking test cleanup via synchronize(true).
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R3026-3034]

+            const tables: ObjectLiteral[] = await this.query(
+                `SELECT quote_ident(table_schema) || '.' || quote_ident(table_name) as "name" ` +
+                    `FROM "information_schema"."tables" WHERE "table_schema" IN (${schemaNamesString})`,
+            )
+
+            if (tables.length > 0) {
+                await this.query(
+                    `DROP TABLE IF EXISTS ${tables.map(({ name }) => name).join(", ")} CASCADE`,
+                )
Evidence
The PR’s new batching still relies on information_schema.tables without a TABLE_TYPE filter, then
constructs a single DROP TABLE over all returned names. Elsewhere in this repo, drivers that use
INFORMATION_SCHEMA.TABLES explicitly filter TABLE_TYPE='BASE TABLE' before dropping tables,
indicating that the unfiltered catalog can contain non-table entries that must be excluded.

src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3035]
src/driver/sqlserver/SqlServerQueryRunner.ts[2816-2820]
src/driver/spanner/SpannerQueryRunner.ts[1624-1629]

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

## Issue description
`clearDatabase()` builds its batched `DROP TABLE` list from `information_schema.tables` without filtering by table type, which can include non-table relations (e.g., views). This can cause `DROP TABLE` to fail and abort database cleanup.
### Issue Context
Other drivers in this repo filter `INFORMATION_SCHEMA.TABLES` with `TABLE_TYPE = &amp;#x27;BASE TABLE&amp;#x27;` before dropping tables.
### Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[3026-3034]

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


2. Missing IF EXISTS sequence 🐞 Bug ⛯ Reliability
Description
clearDatabase() batches sequence drops but uses DROP SEQUENCE without IF EXISTS, so if any
selected sequence is gone by execution time the statement throws and aborts the cleanup. This can
make test database resets flaky under concurrent or re-entrant cleanup scenarios.
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R3043-3046]

+            if (sequences.length > 0) {
+                await this.query(
+                    `DROP SEQUENCE ${sequences.map(({ name }) => name).join(", ")}`,
+                )
Evidence
The new batched sequence drop statement is issued without IF EXISTS, unlike the batched
view/table/type drops in the same method which are idempotent via IF EXISTS guards.

src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3035]
src/driver/cockroachdb/CockroachQueryRunner.ts[3037-3047]
src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4018]

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

## Issue description
`clearDatabase()` batches sequence drops but executes `DROP SEQUENCE ...` without `IF EXISTS`. If any sequence disappears between the catalog query and the DROP (e.g., concurrent cleanup), the statement throws and aborts the reset.
### Issue Context
Views/tables/types in the same method are dropped using `IF EXISTS`, making them resilient to missing objects; sequences should follow the same idempotent pattern.
### Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[3037-3047]

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



Remediation recommended

3. Redundant // drop ... comments 📘 Rule violation ✓ Correctness ⭐ New
Description
The PR adds several new inline comments that restate the immediately-following code, which conflicts
with the compliance requirement to avoid extra comments/noise. This increases churn and can be
considered AI-like “slop” per the checklist even though functionality is unchanged.
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R3013-3038]

+            // drop views
+            const views: ObjectLiteral[] = await this.query(
+                `SELECT quote_ident(schemaname) || '.' || quote_ident(viewname) as "name" ` +
+                    `FROM "pg_views" WHERE "schemaname" IN (${schemaNamesString})`,
+            )
+
+            if (views.length > 0) {
+                await this.query(
+                    `DROP VIEW IF EXISTS ${views.map(({ name }) => name).join(", ")} CASCADE`,
+                )
            }

-            const selectDropsQuery = `SELECT 'DROP TABLE IF EXISTS ' || quote_ident(table_schema) || '.' || quote_ident(table_name) || ' CASCADE;' as "query" FROM "information_schema"."tables" WHERE "table_schema" IN (${schemaNamesString})`
-            const dropQueries: ObjectLiteral[] =
-                await this.query(selectDropsQuery)
-            for (const q of dropQueries) {
-                await this.query(q["query"])
+            // drop tables
+            const tables: ObjectLiteral[] = await this.query(
+                `SELECT quote_ident(table_schema) || '.' || quote_ident(table_name) as "name" ` +
+                    `FROM "information_schema"."tables" WHERE "table_schema" IN (${schemaNamesString}) AND "table_type" = 'BASE TABLE'`,
+            )
+
+            if (tables.length > 0) {
+                await this.query(
+                    `DROP TABLE IF EXISTS ${tables.map(({ name }) => name).join(", ")} CASCADE`,
+                )
            }

-            const selectSequenceDropsQuery = `SELECT 'DROP SEQUENCE ' || quote_ident(sequence_schema) || '.' || quote_ident(sequence_name) || ';' as "query" FROM "information_schema"."sequences" WHERE "sequence_schema" IN (${schemaNamesString})`
-            const sequenceDropQueries: ObjectLiteral[] = await this.query(
-                selectSequenceDropsQuery,
+            // drop sequences
+            const sequences: ObjectLiteral[] = await this.query(
Evidence
Compliance ID 4 requires avoiding extra comments/noise. The changed hunk introduces new comments
(// drop views, // drop tables, // drop sequences) that are redundant with the code directly
below them.

Rule 4: Remove AI-generated noise
src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3038]

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

## Issue description
New inline comments were added that restate the immediately-following code (e.g., `// drop views`). Compliance requires avoiding extra comments/noise.

## Issue Context
This change is primarily a performance refactor; the added comments do not add meaningful context and may be considered unnecessary churn.

## Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3038]

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


4. Unbounded DROP statement size 🐞 Bug ⛯ Reliability ⭐ New
Description
CockroachQueryRunner.clearDatabase() now concatenates all discovered object names into a single DROP
statement string with no chunking, so on sufficiently large schemas the generated SQL can exceed
server/driver statement size limits and fail, leaving the database uncleared.
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R3031-3034]

+            if (tables.length > 0) {
+                await this.query(
+                    `DROP TABLE IF EXISTS ${tables.map(({ name }) => name).join(", ")} CASCADE`,
+                )
Evidence
The new implementation builds one DROP TABLE statement by joining all table names returned from the
catalog into a single SQL string, with no bounds/chunking. Since clearDatabase() is invoked by
DataSource.dropDatabase() and commonly by synchronize(true) test flows, a failure here prevents full
cleanup.

src/driver/cockroachdb/CockroachQueryRunner.ts[3025-3035]
src/data-source/DataSource.ts[308-341]

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

### Issue description
`clearDatabase()` builds a single `DROP ... ${names.join(&#x27;, &#x27;)}` statement per object type. This can create arbitrarily large SQL strings, which may exceed server/driver statement size limits on large schemas and cause `clearDatabase()` to fail.

### Issue Context
This code path is used during database reset flows (e.g., `dropDatabase()` and commonly `synchronize(true)` in tests). A failure prevents cleanup and can break subsequent schema setup.

### Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3047]
- src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4018]

### Implementation notes
- Introduce a small helper (e.g., `dropInBatches(kind, names, suffixSql, batchSizeOrMaxLen)`)
- Apply it to VIEW/TABLE/SEQUENCE/TYPE drops
- Prefer chunking by **max SQL length** (most robust) or a conservative **max identifiers per statement** (simpler)

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


5. Enum names not escaped 🐞 Bug ✓ Correctness
Description
dropEnumTypes() manually wraps pg_namespace/pg_type names in double quotes instead of using
quote_ident(), so enum type names containing embedded '"' characters can produce malformed SQL and
cause clearDatabase() to fail during DROP TYPE.
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R4007-4017]

+        const enums: ObjectLiteral[] = await this.query(
+            `SELECT '"' || n.nspname || '"."' || t.typname || '"' as "name" FROM "pg_type" "t" ` +
+                `INNER JOIN "pg_enum" "e" ON "e"."enumtypid" = "t"."oid" ` +
+                `INNER JOIN "pg_namespace" "n" ON "n"."oid" = "t"."typnamespace" ` +
+                `WHERE "n"."nspname" IN (${schemaNames}) GROUP BY "n"."nspname", "t"."typname"`,
+        )
+
+        if (enums.length > 0) {
+            await this.query(
+                `DROP TYPE IF EXISTS ${enums.map(({ name }) => name).join(", ")}`,
+            )
Evidence
In clearDatabase(), views/tables/sequences are selected using quote_ident() to ensure identifiers
are safely escaped before being interpolated into batched DROP statements. In contrast,
dropEnumTypes() constructs the fully-qualified type name with raw catalog fields concatenated inside
quotes, which does not escape embedded quotes and can yield invalid identifiers in the generated
DROP TYPE statement.

src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3046]
src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4017]

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

## Issue description
`dropEnumTypes()` constructs qualified enum type names using manual string concatenation with embedded double quotes. This does not escape embedded quotes within identifiers and can generate invalid SQL for certain enum/type names, causing `clearDatabase()` to fail when dropping enums.
## Issue Context
Within `clearDatabase()`, other object types (views/tables/sequences) already use `quote_ident()` when selecting names for batched DROP statements. Enum types should follow the same pattern.
## Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4017]
- src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3046]
## Suggested change
Update the enum-name SELECT to use `quote_ident(n.nspname) || &amp;amp;amp;#x27;.&amp;amp;amp;#x27; || quote_ident(t.typname)` (aliased as `name`) and keep the batched `DROP TYPE IF EXISTS ${...}` logic unchanged.

ⓘ 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 7af618e

Results up to commit 8b3a977


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

Grey Divider
Action required
1. Views dropped as tables 🐞 Bug ✓ Correctness ⭐ New
Description
CockroachQueryRunner.clearDatabase() selects drop targets from information_schema.tables without
restricting to BASE TABLE and then issues a DROP TABLE for every returned name. This can attempt to
drop views as tables and abort clearDatabase(), breaking test cleanup via synchronize(true).
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R3026-3034]

+            const tables: ObjectLiteral[] = await this.query(
+                `SELECT quote_ident(table_schema) || '.' || quote_ident(table_name) as "name" ` +
+                    `FROM "information_schema"."tables" WHERE "table_schema" IN (${schemaNamesString})`,
+            )
+
+            if (tables.length > 0) {
+                await this.query(
+                    `DROP TABLE IF EXISTS ${tables.map(({ name }) => name).join(", ")} CASCADE`,
+                )
Evidence
The PR’s new batching still relies on information_schema.tables without a TABLE_TYPE filter, then
constructs a single DROP TABLE over all returned names. Elsewhere in this repo, drivers that use
INFORMATION_SCHEMA.TABLES explicitly filter TABLE_TYPE='BASE TABLE' before dropping tables,
indicating that the unfiltered catalog can contain non-table entries that must be excluded.

src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3035]
src/driver/sqlserver/SqlServerQueryRunner.ts[2816-2820]
src/driver/spanner/SpannerQueryRunner.ts[1624-1629]

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

### Issue description
`clearDatabase()` builds its batched `DROP TABLE` list from `information_schema.tables` without filtering by table type, which can include non-table relations (e.g., views). This can cause `DROP TABLE` to fail and abort database cleanup.

### Issue Context
Other drivers in this repo filter `INFORMATION_SCHEMA.TABLES` with `TABLE_TYPE = &#x27;BASE TABLE&#x27;` before dropping tables.

### Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[3026-3034]

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


2. Missing IF EXISTS sequence 🐞 Bug ⛯ Reliability
Description
clearDatabase() batches sequence drops but uses DROP SEQUENCE without IF EXISTS, so if any
selected sequence is gone by execution time the statement throws and aborts the cleanup. This can
make test database resets flaky under concurrent or re-entrant cleanup scenarios.
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R3043-3046]

+            if (sequences.length > 0) {
+                await this.query(
+                    `DROP SEQUENCE ${sequences.map(({ name }) => name).join(", ")}`,
+                )
Evidence
The new batched sequence drop statement is issued without IF EXISTS, unlike the batched
view/table/type drops in the same method which are idempotent via IF EXISTS guards.

src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3035]
src/driver/cockroachdb/CockroachQueryRunner.ts[3037-3047]
src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4018]

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

## Issue description
`clearDatabase()` batches sequence drops but executes `DROP SEQUENCE ...` without `IF EXISTS`. If any sequence disappears between the catalog query and the DROP (e.g., concurrent cleanup), the statement throws and aborts the reset.
### Issue Context
Views/tables/types in the same method are dropped using `IF EXISTS`, making them resilient to missing objects; sequences should follow the same idempotent pattern.
### Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[3037-3047]

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



Remediation recommended
3. Enum names not escaped 🐞 Bug ✓ Correctness
Description
dropEnumTypes() manually wraps pg_namespace/pg_type names in double quotes instead of using
quote_ident(), so enum type names containing embedded '"' characters can produce malformed SQL and
cause clearDatabase() to fail during DROP TYPE.
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R4007-4017]

+        const enums: ObjectLiteral[] = await this.query(
+            `SELECT '"' || n.nspname || '"."' || t.typname || '"' as "name" FROM "pg_type" "t" ` +
+                `INNER JOIN "pg_enum" "e" ON "e"."enumtypid" = "t"."oid" ` +
+                `INNER JOIN "pg_namespace" "n" ON "n"."oid" = "t"."typnamespace" ` +
+                `WHERE "n"."nspname" IN (${schemaNames}) GROUP BY "n"."nspname", "t"."typname"`,
+        )
+
+        if (enums.length > 0) {
+            await this.query(
+                `DROP TYPE IF EXISTS ${enums.map(({ name }) => name).join(", ")}`,
+            )
Evidence
In clearDatabase(), views/tables/sequences are selected using quote_ident() to ensure identifiers
are safely escaped before being interpolated into batched DROP statements. In contrast,
dropEnumTypes() constructs the fully-qualified type name with raw catalog fields concatenated inside
quotes, which does not escape embedded quotes and can yield invalid identifiers in the generated
DROP TYPE statement.

src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3046]
src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4017]

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

## Issue description
`dropEnumTypes()` constructs qualified enum type names using manual string concatenation with embedded double quotes. This does not escape embedded quotes within identifiers and can generate invalid SQL for certain enum/type names, causing `clearDatabase()` to fail when dropping enums.
## Issue Context
Within `clearDatabase()`, other object types (views/tables/sequences) already use `quote_ident()` when selecting names for batched DROP statements. Enum types should follow the same pattern.
## Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4017]
- src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3046]
## Suggested change
Update the enum-name SELECT to use `quote_ident(n.nspname) || &amp;amp;#x27;.&amp;amp;#x27; || quote_ident(t.typname)` (aliased as `name`) and keep the batched `DROP TYPE IF EXISTS ${...}` logic unchanged.

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


Grey Divider Grey Divider
Results up to commit cb8267f


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

Grey Divider
Action required
1. Missing IF EXISTS sequence 🐞 Bug ⛯ Reliability ⭐ New
Description
clearDatabase() batches sequence drops but uses DROP SEQUENCE without IF EXISTS, so if any
selected sequence is gone by execution time the statement throws and aborts the cleanup. This can
make test database resets flaky under concurrent or re-entrant cleanup scenarios.
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R3043-3046]

+            if (sequences.length > 0) {
+                await this.query(
+                    `DROP SEQUENCE ${sequences.map(({ name }) => name).join(", ")}`,
+                )
Evidence
The new batched sequence drop statement is issued without IF EXISTS, unlike the batched
view/table/type drops in the same method which are idempotent via IF EXISTS guards.

src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3035]
src/driver/cockroachdb/CockroachQueryRunner.ts[3037-3047]
src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4018]

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

### Issue description
`clearDatabase()` batches sequence drops but executes `DROP SEQUENCE ...` without `IF EXISTS`. If any sequence disappears between the catalog query and the DROP (e.g., concurrent cleanup), the statement throws and aborts the reset.

### Issue Context
Views/tables/types in the same method are dropped using `IF EXISTS`, making them resilient to missing objects; sequences should follow the same idempotent pattern.

### Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[3037-3047]

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



Remediation recommended
2. Enum names not escaped 🐞 Bug ✓ Correctness
Description
dropEnumTypes() manually wraps pg_namespace/pg_type names in double quotes instead of using
quote_ident(), so enum type names containing embedded '"' characters can produce malformed SQL and
cause clearDatabase() to fail during DROP TYPE.
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R4007-4017]

+        const enums: ObjectLiteral[] = await this.query(
+            `SELECT '"' || n.nspname || '"."' || t.typname || '"' as "name" FROM "pg_type" "t" ` +
+                `INNER JOIN "pg_enum" "e" ON "e"."enumtypid" = "t"."oid" ` +
+                `INNER JOIN "pg_namespace" "n" ON "n"."oid" = "t"."typnamespace" ` +
+                `WHERE "n"."nspname" IN (${schemaNames}) GROUP BY "n"."nspname", "t"."typname"`,
+        )
+
+        if (enums.length > 0) {
+            await this.query(
+                `DROP TYPE IF EXISTS ${enums.map(({ name }) => name).join(", ")}`,
+            )
Evidence
In clearDatabase(), views/tables/sequences are selected using quote_ident() to ensure identifiers
are safely escaped before being interpolated into batched DROP statements. In contrast,
dropEnumTypes() constructs the fully-qualified type name with raw catalog fields concatenated inside
quotes, which does not escape embedded quotes and can yield invalid identifiers in the generated
DROP TYPE statement.

src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3046]
src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4017]

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

## Issue description
`dropEnumTypes()` constructs qualified enum type names using manual string concatenation with embedded double quotes. This does not escape embedded quotes within identifiers and can generate invalid SQL for certain enum/type names, causing `clearDatabase()` to fail when dropping enums.
## Issue Context
Within `clearDatabase()`, other object types (views/tables/sequences) already use `quote_ident()` when selecting names for batched DROP statements. Enum types should follow the same pattern.
## Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4017]
- src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3046]
## Suggested change
Update the enum-name SELECT to use `quote_ident(n.nspname) || &amp;#x27;.&amp;#x27; || quote_ident(t.typname)` (aliased as `name`) and keep the batched `DROP TYPE IF EXISTS ${...}` logic unchanged.

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


Grey Divider Grey Divider
Results up to commit 14d3ffe


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

Grey Divider
Remediation recommended
1. Enum names not escaped 🐞 Bug ✓ Correctness
Description
dropEnumTypes() manually wraps pg_namespace/pg_type names in double quotes instead of using
quote_ident(), so enum type names containing embedded '"' characters can produce malformed SQL and
cause clearDatabase() to fail during DROP TYPE.
Code

src/driver/cockroachdb/CockroachQueryRunner.ts[R4007-4017]

+        const enums: ObjectLiteral[] = await this.query(
+            `SELECT '"' || n.nspname || '"."' || t.typname || '"' as "name" FROM "pg_type" "t" ` +
+                `INNER JOIN "pg_enum" "e" ON "e"."enumtypid" = "t"."oid" ` +
+                `INNER JOIN "pg_namespace" "n" ON "n"."oid" = "t"."typnamespace" ` +
+                `WHERE "n"."nspname" IN (${schemaNames}) GROUP BY "n"."nspname", "t"."typname"`,
+        )
+
+        if (enums.length > 0) {
+            await this.query(
+                `DROP TYPE IF EXISTS ${enums.map(({ name }) => name).join(", ")}`,
+            )
Evidence
In clearDatabase(), views/tables/sequences are selected using quote_ident() to ensure identifiers
are safely escaped before being interpolated into batched DROP statements. In contrast,
dropEnumTypes() constructs the fully-qualified type name with raw catalog fields concatenated inside
quotes, which does not escape embedded quotes and can yield invalid identifiers in the generated
DROP TYPE statement.

src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3046]
src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4017]

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

## Issue description
`dropEnumTypes()` constructs qualified enum type names using manual string concatenation with embedded double quotes. This does not escape embedded quotes within identifiers and can generate invalid SQL for certain enum/type names, causing `clearDatabase()` to fail when dropping enums.

## Issue Context
Within `clearDatabase()`, other object types (views/tables/sequences) already use `quote_ident()` when selecting names for batched DROP statements. Enum types should follow the same pattern.

## Fix Focus Areas
- src/driver/cockroachdb/CockroachQueryRunner.ts[4006-4017]
- src/driver/cockroachdb/CockroachQueryRunner.ts[3013-3046]

## Suggested change
Update the enum-name SELECT to use `quote_ident(n.nspname) || &#x27;.&#x27; || quote_ident(t.typname)` (aliased as `name`) and keep the batched `DROP TYPE IF EXISTS ${...}` logic unchanged.

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


Grey Divider Grey Divider
Qodo Logo

@pkuczynski
pkuczynski force-pushed the perf/batch-cockroachdb-drop-statements branch from 14d3ffe to cb8267f Compare March 9, 2026 17:44
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit cb8267f

@coveralls

coveralls commented Mar 9, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 74.899%. remained the same
when pulling 7af618e on perf/batch-cockroachdb-drop-statements
into c4dc431 on master.

@pkuczynski
pkuczynski requested a review from alumni March 9, 2026 18:23
@pkuczynski
pkuczynski added this pull request to the merge queue Mar 9, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Mar 9, 2026
@gioboa
gioboa added this pull request to the merge queue Mar 10, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Mar 10, 2026
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

Deploying typeorm with  Cloudflare Pages  Cloudflare Pages

Latest commit: 8b3a977
Status: ✅  Deploy successful!
Preview URL: https://d5310218.typeorm.pages.dev
Branch Preview URL: https://perf-batch-cockroachdb-drop.typeorm.pages.dev

View logs

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

Copy link
Copy Markdown

Persistent review updated to latest commit 8b3a977

- use quote_ident() for enum type names instead of manual quoting
- add IF EXISTS to DROP SEQUENCE for resilience to concurrent cleanup
- filter information_schema.tables by table_type = 'BASE TABLE'
@sonarqubecloud

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Persistent review updated to latest commit 7af618e

@pkuczynski
pkuczynski enabled auto-merge (squash) March 11, 2026 14:43
@pkuczynski
pkuczynski merged commit d494489 into master Mar 11, 2026
68 of 70 checks passed
@pkuczynski
pkuczynski deleted the perf/batch-cockroachdb-drop-statements branch March 11, 2026 15:10
@github-actions github-actions Bot added this to the 1.0 milestone Mar 11, 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.

5 participants