Skip to content

fix(postgres): improve normalizeDatetimeFunction for tstzrange data type - #12182

Merged
alumni merged 8 commits into
typeorm:masterfrom
Cprakhar:fix/normalizeDatetimeFunction-postgres
Jun 15, 2026
Merged

alumni merged 8 commits into
typeorm:masterfrom
Cprakhar:fix/normalizeDatetimeFunction-postgres

Conversation

@Cprakhar

Copy link
Copy Markdown
Collaborator

Description of change

This PR fixes #11990

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #11990
  • 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 Mar 10, 2026 •

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

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

commit: 57be3f6

@Cprakhar
Cprakhar marked this pull request as ready for review March 10, 2026 19:11
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Review Summary by Qodo

Fix normalizeDatetimeFunction to prevent false matches in tstzrange

🐞 Bug fix

Grey Divider

Walkthroughs

Description
• Refactored normalizeDatetimeFunction to use regex patterns for exact matching
• Prevents false positives when datetime functions appear within larger strings
• Added .trim() to handle whitespace in input values
• Added test case validating tstzrange default value handling
Diagram
flowchart LR
  A["normalizeDatetimeFunction<br/>with indexOf checks"] -->|"Replace with<br/>regex patterns"| B["Exact matching<br/>using /^pattern$/ regex"]
  B -->|"Prevents false<br/>positives"| C["Correct handling<br/>of tstzrange defaults"]
  D["New test case"] -->|"Validates"| C
Loading

Grey Divider

File Changes

1. src/driver/postgres/PostgresDriver.ts 🐞 Bug fix +24/-32

Refactor datetime function detection with regex patterns

• Replaced indexOf() substring checks with regex patterns for exact matching
• Added .trim() call to normalize input whitespace
• Simplified logic by extracting precision once before conditionals
• Prevents false positives when datetime functions appear within larger strings like
 tstzrange(CURRENT_TIMESTAMP, NULL)

src/driver/postgres/PostgresDriver.ts


2. test/functional/columns/default-columns/column-default.test.ts 🧪 Tests +32/-0

Add test for tstzrange default column values

• New test file validating default column values in schema
• Tests that tstzrange column with current_timestamp function has correct default value
• Uses PostgreSQL driver with test database setup and cleanup

test/functional/columns/default-columns/column-default.test.ts


3. test/functional/columns/default-columns/entity/Event.ts 🧪 Tests +15/-0

Add Event entity for default column testing

• New entity class for testing default column behavior
• Defines Event table with sysPeriod column of type tstzrange
• Uses current_timestamp function as default value with null end bound

test/functional/columns/default-columns/entity/Event.ts


Grey Divider

Qodo Logo

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

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (6) 📘 Rule violations (5)

Grey Divider


Action required

1. funcName case breaks switch 📘 Rule violation ≡ Correctness
Description
normalizeDatetimeFunction captures funcName using a case-insensitive regex but then switches on
case-sensitive uppercase literals, so lowercase inputs like current_timestamp/now can bypass
normalization. Additionally, the regex only permits parentheses when they contain digits, so common
defaults like NOW() / CURRENT_TIMESTAMP() may no longer normalize, leading to unexpected schema
default comparisons and repeated schema diffs.
Code

src/driver/mysql/MysqlDriver.ts[R1292-1306]

+        const match = value.trim().match(/^(CURRENT_TIMESTAMP|NOW)(\(\d+\))?$/i)
+
+        if (!match) return value
+
+        const [, funcName, precision = ""] = match
+
+        switch (funcName) {
+            case "CURRENT_TIMESTAMP":
+            case "NOW":
+                if (this.dataSource.options.type === "mariadb" && !precision) {
+                    return "CURRENT_TIMESTAMP()"
+                }
+                return `CURRENT_TIMESTAMP${precision}`
+            default:
+                return value
Evidence
The implementation matches datetime function defaults with a /i (case-insensitive) regex, which
means the captured funcName can retain whatever casing appears in the input; however, the
subsequent switch (funcName) only contains exact uppercase case labels, so lowercase forms fall
through to default and skip normalization. Because normalizeDefault() delegates function
defaults to normalizeDatetimeFunction(), any missed normalization propagates directly into default
comparison and changed-column detection, and the current regex behavior (only allowing parenthesized
precision like (3)) implies that empty-parentheses variants such as NOW() /
CURRENT_TIMESTAMP() are also missed, which can produce noisy, non-idempotent schema diffs.

Rule 4: Remove AI-generated noise
src/driver/mysql/MysqlDriver.ts[1292-1306]
src/driver/mysql/MysqlDriver.ts[821-853]
src/driver/mysql/MysqlDriver.ts[1289-1307]
test/functional/schema-builder/column-type/datetime/create-update-date/entity/mysql/Post.ts[14-39]
test/functional/schema-builder/column-type/datetime/create-update-date/create-update-date.test.ts[159-193]

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

## Issue description
`MysqlDriver.normalizeDatetimeFunction()` currently uses a case-insensitive regex to capture a datetime function name but then performs a case-sensitive `switch` against uppercase literals, so inputs like `current_timestamp`/`now(3)` can bypass normalization. The regex also only accepts parentheses when they contain digits, causing common defaults like `NOW()` / `CURRENT_TIMESTAMP()` (empty parentheses) to stop normalizing, which in turn can make schema default comparison and diff detection non-idempotent.
## Issue Context
This logic exists to normalize MySQL/MariaDB datetime default function strings across equivalent forms and casing (e.g. `CURRENT_TIMESTAMP`, `current_timestamp`, `Now(3)`, `CURRENT_TIMESTAMP()`), and the prior behavior uppercased the input before checking. `normalizeDefault()` routes function defaults through `normalizeDatetimeFunction()`, so any missed normalization directly affects default comparisons and changed-column detection, potentially leading to repeated schema diffs.
## Fix Focus Areas
- src/driver/mysql/MysqlDriver.ts[1289-1307]

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


2. Postgres funcName switch mismatch 📘 Rule violation ≡ Correctness
Description
PostgresDriver.normalizeDatetimeFunction uses a case-insensitive regex but then switches on the
captured function name with case-sensitive, uppercase labels, so inputs like current_date or
localtimestamp(3) match yet fall through and are returned unnormalized. This can introduce
inconsistent/buggy normalization behavior and lead to persistent schema diff/update churn for
entities using lowercase datetime defaults.
Code

src/driver/postgres/PostgresDriver.ts[R1850-1877]

+        const match = value
+            .trim()
+            .match(
+                /^(CURRENT_TIMESTAMP|CURRENT_DATE|CURRENT_TIME|LOCALTIMESTAMP|LOCALTIME)(\(\d+\))?$/i,
+            )
+
+        if (!match) return value
+
+        const [, funcName, precision = ""] = match
+
+        const prefix = "('now'::text)"
+
+        switch (funcName) {
+            case "CURRENT_TIMESTAMP":
              return precision
-                    ? `('now'::text)::timestamp${precision[0]} with time zone`
+                    ? `${prefix}::timestamp${precision} with time zone`
                  : "now()"
-            } else if (upperCaseValue === "CURRENT_DATE") {
-                return "('now'::text)::date"
-            } else if (upperCaseValue.indexOf("CURRENT_TIME") !== -1) {
-                return precision
-                    ? `('now'::text)::time${precision[0]} with time zone`
-                    : "('now'::text)::time with time zone"
-            } else if (upperCaseValue.indexOf("LOCALTIMESTAMP") !== -1) {
-                return precision
-                    ? `('now'::text)::timestamp${precision[0]} without time zone`
-                    : "('now'::text)::timestamp without time zone"
-            } else if (upperCaseValue.indexOf("LOCALTIME") !== -1) {
-                return precision
-                    ? `('now'::text)::time${precision[0]} without time zone`
-                    : "('now'::text)::time without time zone"
-            }
+            case "CURRENT_DATE":
+                return `${prefix}::date`
+            case "CURRENT_TIME":
+                return `${prefix}::time${precision} with time zone`
+            case "LOCALTIMESTAMP":
+                return `${prefix}::timestamp${precision} without time zone`
+            case "LOCALTIME":
+                return `${prefix}::time${precision} without time zone`
+            default:
+                return value
      }
-
-        return value
Evidence
The implementation matches datetime-default expressions using a regex with the /i flag, meaning
lowercase function names will be captured successfully, but the subsequent switch compares that
captured funcName against exact uppercase case labels; because the capture preserves the original
casing and is not normalized (e.g., via toUpperCase()), non-uppercase inputs will hit the
default branch and be returned unchanged. Since the Postgres default-normalization path
(normalizeDefault()) relies on normalizeDatetimeFunction() for function defaults, any existing
entities/tests that define lowercase datetime defaults will now bypass normalization, resulting in
noisy/incorrect behavior and recurring schema diff churn.

Rule 4: Remove AI-generated noise
src/driver/postgres/PostgresDriver.ts[1850-1877]
src/driver/postgres/PostgresDriver.ts[1204-1233]
src/driver/postgres/PostgresDriver.ts[1849-1877]
test/functional/schema-builder/column-type/datetime/create-update-date/entity/postgres/Post.ts[14-57]
test/functional/schema-builder/column-type/datetime/create-update-date/create-update-date.test.ts[15-48]

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

## Issue description
`normalizeDatetimeFunction()` matches Postgres datetime functions using a case-insensitive regex, but then switches on the captured function name without normalizing its case. Because the capture preserves the input casing, lowercase defaults (e.g., `current_date`, `localtimestamp(3)`) will match the regex but fail the case-sensitive `switch`, skipping normalization and potentially causing persistent schema diff/update churn.
## Issue Context
This method is responsible for normalizing Postgres datetime default expressions, and `normalizeDefault()` calls `normalizeDatetimeFunction()` for function defaults. The previous behavior compared in a case-insensitive way (e.g., via `toUpperCase()`), and the test suite/entities already include lowercase datetime defaults that should normalize equivalently to uppercase forms.
## Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[1849-1877]

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


3. Skipped assertions via optional chaining 🐞 Bug ≡ Correctness
Description
column-default.test.ts uses optional chaining before chai "should" assertions, so the assertions are
not executed when sysPeriodColumn/loadedEvent are undefined. This can let the test pass without
actually validating the column default or that the saved row was loaded.
Code

test/functional/columns/default-columns/column-default.test.ts[R28-42]

Evidence
The new test guards both the column lookup and the assertion with optional chaining, which
short-circuits the assertion chain when the value is null/undefined. The test harness already
enables chai's should-style assertions globally, and existing tests typically assert existence
explicitly (e.g., table!.should.exist) rather than skipping checks.

test/functional/columns/default-columns/column-default.test.ts[21-42]
test/utils/test-setup.ts[1-14]
test/functional/query-runner/create-table.test.ts[105-116]

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 regression test uses optional chaining (`?.`) before chai `should` assertions, which can skip the assertions entirely if an intermediate value is `null`/`undefined`, allowing the test to pass without validating the behavior.
### Issue Context
Chai's `should` is registered globally in the test setup, and other tests typically assert existence explicitly (e.g., `table!.should.exist`) so that missing data fails the test.
### Fix Focus Areas
- test/functional/columns/default-columns/column-default.test.ts[21-42]
- test/utils/test-setup.ts[1-14]
- test/functional/query-runner/create-table.test.ts[105-116]
### Suggested change
- Replace `table?.findColumnByName(...)` with an explicit existence assertion (`table!.should.exist` / `expect(table).to.exist`).
- Replace `sysPeriodColumn?.default.should...` with `sysPeriodColumn!.default.should...` (or `expect(sysPeriodColumn).to.exist` then assert on `.default`).
- Replace `findOneBy` + `loadedEvent?.should...` with `findOneByOrFail` (or assert `loadedEvent` is not null before comparing).

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


View more (2)
4. Case-sensitive default compare 🐞 Bug ≡ Correctness
Description
PostgresDriver.defaultEqual lowercases only the metadata default and then compares it with strict
string equality to the schema default, so defaults like tstzrange(current_timestamp, null) vs
tstzrange(CURRENT_TIMESTAMP, NULL) will be treated as different and keep generating ALTER COLUMN ...
SET DEFAULT diffs. This is now triggered by the stricter normalizeDatetimeFunction which correctly
leaves composite expressions unchanged.
Code

src/driver/postgres/PostgresDriver.ts[R1850-1874]

Evidence
The new Event entity uses a functional default that returns a composite expression
(tstzrange(current_timestamp, null)). With the anchored-regex change, normalizeDatetimeFunction
returns that composite expression unchanged, so normalizeDefault returns it as-is; defaultEqual then
lowercases only the metadata side via lowerDefaultValueIfNecessary and compares it to the
introspected tableColumn.default, which PostgresQueryRunner does not lowercase (it only strips
casts). The new functional test asserts the introspected schema default is
"tstzrange(CURRENT_TIMESTAMP, NULL)" (uppercase keywords), which will not be strictly equal to the
lowercased metadata expression, causing the column to be flagged as changed on every schema diff
run.

src/driver/postgres/PostgresDriver.ts[1849-1877]
src/driver/postgres/PostgresDriver.ts[1204-1233]
src/driver/postgres/PostgresDriver.ts[1248-1271]
src/driver/postgres/PostgresDriver.ts[1623-1634]
src/driver/postgres/PostgresQueryRunner.ts[4075-4129]
test/functional/columns/default-columns/entity/Event.ts[1-13]
test/functional/columns/default-columns/column-default.test.ts[20-31]

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

## Issue description
`PostgresDriver.defaultEqual()` lowercases only the *metadata* default via `lowerDefaultValueIfNecessary(...)` and then compares it to `tableColumn.default` without applying the same normalization. With the new `normalizeDatetimeFunction` behavior (correctly returning composite expressions unchanged), composite defaults like `tstzrange(current_timestamp, null)` can be stored/introspected as `tstzrange(CURRENT_TIMESTAMP, NULL)`, making schema diff think the column is always changed.
### Issue Context
- `normalizeDefault()` returns the raw function string when it’s not an exact datetime function.
- `lowerDefaultValueIfNecessary()` lowercases outside quoted literals.
- `PostgresQueryRunner` strips casts but does not lowercase default expressions.
### Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[1248-1271]
- src/driver/postgres/PostgresDriver.ts[1623-1634]
### Suggested fix
In `defaultEqual()`, apply the same normalization to the table default before comparing, e.g.:
- `const normalizedMetadata = this.lowerDefaultValueIfNecessary(this.normalizeDefault(columnMetadata))`
- `const normalizedTable = this.lowerDefaultValueIfNecessary(tableColumn.default)`
- compare `normalizedMetadata === normalizedTable`
### Test reinforcement (optional but recommended)
Extend the newly added postgres test to run schema sync/log twice and assert no further diff is generated for the `sysPeriod` default.

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


5. Brittle default assertion 🐞 Bug ≡ Correctness
Description
The new Postgres functional test asserts an exact introspected default string
"tstzrange(CURRENT_TIMESTAMP, NULL)", but Postgres/TypeORM commonly canonicalize CURRENT_TIMESTAMP
to now(), so the database may report "tstzrange(now(), NULL)" and fail the test.
Code

test/functional/columns/default-columns/column-default.test.ts[R26-29]

Evidence
The test hard-codes CURRENT_TIMESTAMP inside the range default, but the Postgres driver itself
normalizes CURRENT_TIMESTAMP to "now()" (showing that now() is treated as the canonical
representation), and the Postgres schema introspection preserves "now()" defaults verbatim—so a DB
that emits now() inside the expression will not match the asserted string.

test/functional/columns/default-columns/column-default.test.ts[19-30]
src/driver/postgres/PostgresDriver.ts[1768-1795]
src/driver/postgres/PostgresQueryRunner.ts[4055-4062]

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 functional test asserts a single exact string for the introspected default of a `tstzrange` column. Postgres may canonicalize `CURRENT_TIMESTAMP` to `now()` (including when nested in expressions), causing CI failures depending on how the database formats stored defaults.
### Issue Context
TypeORM’s Postgres driver treats `CURRENT_TIMESTAMP` as equivalent to `now()` (see `normalizeDatetimeFunction`), and the query runner preserves `now()` defaults verbatim during schema introspection.
### Fix Focus Areas
- test/functional/columns/default-columns/column-default.test.ts[19-30]

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



Remediation recommended

6. Test missing #11990 reference 📘 Rule violation ⚙ Maintainability
Description
The new functional test validates the fix but does not include an issue-reference comment (e.g.,
Fixes #11990) near the test, which reduces traceability to the reported issue. This violates the
guideline to keep issue fixes in functional tests with an issue reference when applicable.
Code

test/functional/columns/default-columns/column-default.test.ts[R10-23]

+describe("columns > default columns", () => {
+    let dataSources: DataSource[]
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [__dirname + "/entity/*{.js,.ts}"],
+            enabledDrivers: ["postgres"],
+        })
+    })
+    beforeEach(() => reloadTestingDatabases(dataSources))
+    after(() => closeTestingConnections(dataSources))
+
+    it("should have correct default value in schema", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
Evidence
PR Compliance ID 3 requires issue fixes to live in the functional test suite with an issue reference
comment when applicable. The added test file contains no comment referencing #11990 in the new
describe/it block area.

Rule 3: Prefer functional tests over per-issue tests
test/functional/columns/default-columns/column-default.test.ts[10-23]

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 functional test added for this fix does not include an issue-reference comment (e.g., `Fixes #11990`), reducing traceability from the test back to the motivating bug report.
## Issue Context
PR description indicates this change fixes `#11990`. The compliance checklist requests issue-reference comments in functional tests when applicable.
## Fix Focus Areas
- test/functional/columns/default-columns/column-default.test.ts[10-23]

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


7. Redundant new RegExp wrapper 📘 Rule violation ⚙ Maintainability
Description
new RegExp(/\(\d+\)/).exec(value) is redundant and inconsistent with typical regex usage in this
file, adding unnecessary noise. This hurts readability and suggests style inconsistency.
Code

src/driver/postgres/PostgresDriver.ts[R1857-1859]

Evidence
PR Compliance ID 4 requires avoiding AI-like slop and inconsistent style; wrapping a regex literal
in new RegExp(...) is unnecessary and inconsistent with standard patterns.

Rule 4: Remove AI-generated noise
src/driver/postgres/PostgresDriver.ts[1857-1859]

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 code constructs a RegExp from a regex literal (`new RegExp(/.../)`) which is redundant and inconsistent style.
## Issue Context
This is minor but adds unnecessary noise to the change and can be simplified without changing behavior.
## Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[1857-1859]

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


8. QueryRunner leak on error 🐞 Bug ☼ Reliability
Description
The test releases the QueryRunner only after getTable resolves; if getTable throws, the
QueryRunner is never released. This can leak a connection and make the overall test suite flaky.
Code

test/functional/columns/default-columns/column-default.test.ts[R24-27]

Evidence
release() is not in a finally block, so exceptions from getTable (or any awaited call before
release) prevent cleanup.

test/functional/columns/default-columns/column-default.test.ts[24-27]

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

## Issue description
If `getTable('event')` throws, `queryRunner.release()` won’t execute, potentially leaking a connection.
### Issue Context
Tests should always release query runners even on failure to avoid cascading flakiness.
### Fix Focus Areas
- test/functional/columns/default-columns/column-default.test.ts[24-27]
### Suggested fix
Wrap QueryRunner usage in try/finally:

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


View more (1)
9. normalizeDatetimeFunction undocumented change 📘 Rule violation ≡ Correctness
Description
The PR changes how Postgres datetime default expressions are normalized (now only exact function
strings match), which can affect generated schema defaults (e.g., `tstzrange(CURRENT_TIMESTAMP,
NULL)`). No documentation update is included for this user-facing behavior change.
Code

src/driver/postgres/PostgresDriver.ts[R1769-1793]

Evidence
Compliance ID 2 requires docs updates for user-facing changes; the PR changes default-value
normalization logic in normalizeDatetimeFunction and the PR description explicitly marks
documentation as not updated.

Rule 2: Docs updated for user-facing changes
src/driver/postgres/PostgresDriver.ts[1769-1793]

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 Postgres driver behavior for normalizing datetime defaults changed (only exact `CURRENT_TIMESTAMP`, `CURRENT_DATE`, etc. are normalized). This can affect how users should write `default: () =&amp;gt; ...` expressions (notably `tstzrange(CURRENT_TIMESTAMP, NULL)`), but no documentation was updated.
## Issue Context
`normalizeDatetimeFunction` now matches exact datetime-function strings via regexes, preventing unintended normalization inside larger SQL expressions.
## Fix Focus Areas
- docs/docs/drivers/postgres.md[61-66]

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



Informational

10. CURRENT_DATE precision dropped 🐞 Bug ≡ Correctness ⭐ New
Description
PostgresDriver.normalizeDatetimeFunction now accepts inputs like "CURRENT_DATE(3)" but ignores the
precision and rewrites them to a plain date expression, silently changing a malformed/typo’d default
instead of leaving it unchanged. Because normalizeDefault routes all function defaults through
normalizeDatetimeFunction, this can hide user mistakes by producing an unintended default
expression.
Code

src/driver/postgres/PostgresDriver.ts[R1850-1875]

+        const match = value
+            .trim()
+            .toUpperCase()
+            .match(
+                /^(CURRENT_TIMESTAMP|CURRENT_DATE|CURRENT_TIME|LOCALTIMESTAMP|LOCALTIME)(\(\d+\))?$/,
+            )
+
+        if (!match) return value
+
+        const [, funcName, precision = ""] = match
+
+        const prefix = "('now'::text)"
+
+        switch (funcName) {
+            case "CURRENT_TIMESTAMP":
                return precision
-                    ? `('now'::text)::timestamp${precision[0]} with time zone`
+                    ? `${prefix}::timestamp${precision} with time zone`
                    : "now()"
-            } else if (upperCaseValue === "CURRENT_DATE") {
-                return "('now'::text)::date"
-            } else if (upperCaseValue.indexOf("CURRENT_TIME") !== -1) {
-                return precision
-                    ? `('now'::text)::time${precision[0]} with time zone`
-                    : "('now'::text)::time with time zone"
-            } else if (upperCaseValue.indexOf("LOCALTIMESTAMP") !== -1) {
-                return precision
-                    ? `('now'::text)::timestamp${precision[0]} without time zone`
-                    : "('now'::text)::timestamp without time zone"
-            } else if (upperCaseValue.indexOf("LOCALTIME") !== -1) {
-                return precision
-                    ? `('now'::text)::time${precision[0]} without time zone`
-                    : "('now'::text)::time without time zone"
-            }
+            case "CURRENT_DATE":
+                return `${prefix}::date`
+            case "CURRENT_TIME":
+                return `${prefix}::time${precision} with time zone`
+            case "LOCALTIMESTAMP":
+                return `${prefix}::timestamp${precision} without time zone`
+            case "LOCALTIME":
+                return `${prefix}::time${precision} without time zone`
Evidence
normalizeDefault() forwards all function defaults into normalizeDatetimeFunction(), so any broadened
matching there directly affects default normalization. The updated regex allows an optional
precision group for CURRENT_DATE, but the CURRENT_DATE switch branch discards it, causing silent
rewriting of malformed inputs.

src/driver/postgres/PostgresDriver.ts[1229-1233]
src/driver/postgres/PostgresDriver.ts[1849-1877]

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

### Issue description
`PostgresDriver.normalizeDatetimeFunction()` currently matches `CURRENT_DATE` with an optional precision group `(...)(\(\d+\))?`, but the `CURRENT_DATE` branch ignores that precision and returns a precision-less `::date` expression. This means a malformed default like `CURRENT_DATE(3)` gets silently rewritten rather than remaining unchanged.

### Issue Context
`normalizeDefault()` calls `normalizeDatetimeFunction()` for all function defaults, so this normalization can affect schema generation/migrations and default comparisons.

### Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[1204-1234]
- src/driver/postgres/PostgresDriver.ts[1849-1879]

### Suggested fix
Update the matcher/logic so `CURRENT_DATE` is only accepted without precision, e.g.:
- Adjust the regex to not allow precision for `CURRENT_DATE`, or
- Add a guard: if `funcName === "CURRENT_DATE"` and `precision !== ""`, return the original `value` unchanged.

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


11. Quoted default drift masked 🐞 Bug ≡ Correctness
Description
defaultEqual now lowercases both metadata and table defaults, and the lowercasing logic only
protects single-quoted strings; text inside double quotes is also lowercased. This can cause
defaults that differ only by case inside double-quoted identifiers (case-sensitive in Postgres) to
compare equal and avoid needed schema updates.
Code

src/driver/postgres/PostgresDriver.ts[R1267-1274]

Evidence
defaultEqual now normalizes the table default via lowerDefaultValueIfNecessary; that helper
lowercases everything not inside single quotes, which includes double-quoted identifier content.
PostgresQueryRunner can preserve double quotes in column defaults (it primarily strips casts), so
case-only differences inside quoted identifiers can reach comparison and now be normalized away.

src/driver/postgres/PostgresDriver.ts[1260-1275]
src/driver/postgres/PostgresDriver.ts[1627-1638]
src/driver/postgres/PostgresQueryRunner.ts[4121-4128]

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

## Issue description
`lowerDefaultValueIfNecessary` lowercases segments outside single quotes, which also lowercases inside double-quoted identifiers. With the PR change applying this to `tableColumn.default` too, case-only differences inside quoted identifiers can be hidden.
### Issue Context
In PostgreSQL, double-quoted identifiers are case-sensitive. Masking differences can prevent schema updates when metadata and DB defaults are not actually equivalent.
### Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[1267-1274]
- src/driver/postgres/PostgresDriver.ts[1627-1638]
### Suggested fix
Update `lowerDefaultValueIfNecessary` to avoid lowercasing content inside double quotes as well as inside single quotes (e.g., a small state-machine scan over the string tracking `'` and `"` contexts). A simpler mitigation is: if the default contains `"`, skip lowercasing entirely or only lowercase outside both quote types.

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

Previous review results

Review updated until commit 57be3f6

Results up to commit b9edaa1


🐞 Bugs (5) 📘 Rule violations (5)


Action required
1. funcName case breaks switch 📘 Rule violation ≡ Correctness
Description
normalizeDatetimeFunction captures funcName using a case-insensitive regex but then switches on
case-sensitive uppercase literals, so lowercase inputs like current_timestamp/now can bypass
normalization. Additionally, the regex only permits parentheses when they contain digits, so common
defaults like NOW() / CURRENT_TIMESTAMP() may no longer normalize, leading to unexpected schema
default comparisons and repeated schema diffs.
Code

src/driver/mysql/MysqlDriver.ts[R1292-1306]

+        const match = value.trim().match(/^(CURRENT_TIMESTAMP|NOW)(\(\d+\))?$/i)
+
+        if (!match) return value
+
+        const [, funcName, precision = ""] = match
+
+        switch (funcName) {
+            case "CURRENT_TIMESTAMP":
+            case "NOW":
+                if (this.dataSource.options.type === "mariadb" && !precision) {
+                    return "CURRENT_TIMESTAMP()"
+                }
+                return `CURRENT_TIMESTAMP${precision}`
+            default:
+                return value
Evidence
The implementation matches datetime function defaults with a /i (case-insensitive) regex, which
means the captured funcName can retain whatever casing appears in the input; however, the
subsequent switch (funcName) only contains exact uppercase case labels, so lowercase forms fall
through to default and skip normalization. Because normalizeDefault() delegates function
defaults to normalizeDatetimeFunction(), any missed normalization propagates directly into default
comparison and changed-column detection, and the current regex behavior (only allowing parenthesized
precision like (3)) implies that empty-parentheses variants such as NOW() /
CURRENT_TIMESTAMP() are also missed, which can produce noisy, non-idempotent schema diffs.

Rule 4: Remove AI-generated noise
src/driver/mysql/MysqlDriver.ts[1292-1306]
src/driver/mysql/MysqlDriver.ts[821-853]
src/driver/mysql/MysqlDriver.ts[1289-1307]
test/functional/schema-builder/column-type/datetime/create-update-date/entity/mysql/Post.ts[14-39]
test/functional/schema-builder/column-type/datetime/create-update-date/create-update-date.test.ts[159-193]

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

## Issue description
`MysqlDriver.normalizeDatetimeFunction()` currently uses a case-insensitive regex to capture a datetime function name but then performs a case-sensitive `switch` against uppercase literals, so inputs like `current_timestamp`/`now(3)` can bypass normalization. The regex also only accepts parentheses when they contain digits, causing common defaults like `NOW()` / `CURRENT_TIMESTAMP()` (empty parentheses) to stop normalizing, which in turn can make schema default comparison and diff detection non-idempotent.
## Issue Context
This logic exists to normalize MySQL/MariaDB datetime default function strings across equivalent forms and casing (e.g. `CURRENT_TIMESTAMP`, `current_timestamp`, `Now(3)`, `CURRENT_TIMESTAMP()`), and the prior behavior uppercased the input before checking. `normalizeDefault()` routes function defaults through `normalizeDatetimeFunction()`, so any missed normalization directly affects default comparisons and changed-column detection, potentially leading to repeated schema diffs.
## Fix Focus Areas
- src/driver/mysql/MysqlDriver.ts[1289-1307]

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


2. Postgres funcName switch mismatch 📘 Rule violation ≡ Correctness
Description
PostgresDriver.normalizeDatetimeFunction uses a case-insensitive regex but then switches on the
captured function name with case-sensitive, uppercase labels, so inputs like current_date or
localtimestamp(3) match yet fall through and are returned unnormalized. This can introduce
inconsistent/buggy normalization behavior and lead to persistent schema diff/update churn for
entities using lowercase datetime defaults.
Code

src/driver/postgres/PostgresDriver.ts[R1850-1877]

+        const match = value
+            .trim()
+            .match(
+                /^(CURRENT_TIMESTAMP|CURRENT_DATE|CURRENT_TIME|LOCALTIMESTAMP|LOCALTIME)(\(\d+\))?$/i,
+            )
+
+        if (!match) return value
+
+        const [, funcName, precision = ""] = match
+
+        const prefix = "('now'::text)"
+
+        switch (funcName) {
+            case "CURRENT_TIMESTAMP":
               return precision
-                    ? `('now'::text)::timestamp${precision[0]} with time zone`
+                    ? `${prefix}::timestamp${precision} with time zone`
                   : "now()"
-            } else if (upperCaseValue === "CURRENT_DATE") {
-                return "('now'::text)::date"
-            } else if (upperCaseValue.indexOf("CURRENT_TIME") !== -1) {
-                return precision
-                    ? `('now'::text)::time${precision[0]} with time zone`
-                    : "('now'::text)::time with time zone"
-            } else if (upperCaseValue.indexOf("LOCALTIMESTAMP") !== -1) {
-                return precision
-                    ? `('now'::text)::timestamp${precision[0]} without time zone`
-                    : "('now'::text)::timestamp without time zone"
-            } else if (upperCaseValue.indexOf("LOCALTIME") !== -1) {
-                return precision
-                    ? `('now'::text)::time${precision[0]} without time zone`
-                    : "('now'::text)::time without time zone"
-            }
+            case "CURRENT_DATE":
+                return `${prefix}::date`
+            case "CURRENT_TIME":
+                return `${prefix}::time${precision} with time zone`
+            case "LOCALTIMESTAMP":
+                return `${prefix}::timestamp${precision} without time zone`
+            case "LOCALTIME":
+                return `${prefix}::time${precision} without time zone`
+            default:
+                return value
       }
-
-        return value
Evidence
The implementation matches datetime-default expressions using a regex with the /i flag, meaning
lowercase function names will be captured successfully, but the subsequent switch compares that
captured funcName against exact uppercase case labels; because the capture preserves the original
casing and is not normalized (e.g., via toUpperCase()), non-uppercase inputs will hit the
default branch and be returned unchanged. Since the Postgres default-normalization path
(normalizeDefault()) relies on normalizeDatetimeFunction() for function defaults, any existing
entities/tests that define lowercase datetime defaults will now bypass normalization, resulting in
noisy/incorrect behavior and recurring schema diff churn.

Rule 4: Remove AI-generated noise
src/driver/postgres/PostgresDriver.ts[1850-1877]
src/driver/postgres/PostgresDriver.ts[1204-1233]
src/driver/postgres/PostgresDriver.ts[1849-1877]
test/functional/schema-builder/column-type/datetime/create-update-date/entity/postgres/Post.ts[14-57]
test/functional/schema-builder/column-type/datetime/create-update-date/create-update-date.test.ts[15-48]

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

## Issue description
`normalizeDatetimeFunction()` matches Postgres datetime functions using a case-insensitive regex, but then switches on the captured function name without normalizing its case. Because the capture preserves the input casing, lowercase defaults (e.g., `current_date`, `localtimestamp(3)`) will match the regex but fail the case-sensitive `switch`, skipping normalization and potentially causing persistent schema diff/update churn.
## Issue Context
This method is responsible for normalizing Postgres datetime default expressions, and `normalizeDefault()` calls `normalizeDatetimeFunction()` for function defaults. The previous behavior compared in a case-insensitive way (e.g., via `toUpperCase()`), and the test suite/entities already include lowercase datetime defaults that should normalize equivalently to uppercase forms.
## Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[1849-1877]

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


3. Skipped assertions via optional chaining 🐞 Bug ≡ Correctness
Description
column-default.test.ts uses optional chaining before chai "should" assertions, so the assertions are
not executed when sysPeriodColumn/loadedEvent are undefined. This can let the test pass without
actually validating the column default or that the saved row was loaded.
Code

test/functional/columns/default-columns/column-default.test.ts[R28-42]

Evidence
The new test guards both the column lookup and the assertion with optional chaining, which
short-circuits the assertion chain when the value is null/undefined. The test harness already
enables chai's should-style assertions globally, and existing tests typically assert existence
explicitly (e.g., table!.should.exist) rather than skipping checks.

test/functional/columns/default-columns/column-default.test.ts[21-42]
test/utils/test-setup.ts[1-14]
test/functional/query-runner/create-table.test.ts[105-116]

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 regression test uses optional chaining (`?.`) before chai `should` assertions, which can skip the assertions entirely if an intermediate value is `null`/`undefined`, allowing the test to pass without validating the behavior.
### Issue Context
Chai's `should` is registered globally in the test setup, and other tests typically assert existence explicitly (e.g., `table!.should.exist`) so that missing data fails the test.
### Fix Focus Areas
- test/functional/columns/default-columns/column-default.test.ts[21-42]
- test/utils/test-setup.ts[1-14]
- test/functional/query-runner/create-table.test.ts[105-116]
### Suggested change
- Replace `table?.findColumnByName(...)` with an explicit existence assertion (`table!.should.exist` / `expect(table).to.exist`).
- Replace `sysPeriodColumn?.default.should...` with `sysPeriodColumn!.default.should...` (or `expect(sysPeriodColumn).to.exist` then assert on `.default`).
- Replace `findOneBy` + `loadedEvent?.should...` with `findOneByOrFail` (or assert `loadedEvent` is not null before comparing).

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


View more (2)
4. Case-sensitive default compare 🐞 Bug ≡ Correctness
Description
PostgresDriver.defaultEqual lowercases only the metadata default and then compares it with strict
string equality to the schema default, so defaults like tstzrange(current_timestamp, null) vs
tstzrange(CURRENT_TIMESTAMP, NULL) will be treated as different and keep generating ALTER COLUMN ...
SET DEFAULT diffs. This is now triggered by the stricter normalizeDatetimeFunction which correctly
leaves composite expressions unchanged.
Code

src/driver/postgres/PostgresDriver.ts[R1850-1874]

Evidence
The new Event entity uses a functional default that returns a composite expression
(tstzrange(current_timestamp, null)). With the anchored-regex change, normalizeDatetimeFunction
returns that composite expression unchanged, so normalizeDefault returns it as-is; defaultEqual then
lowercases only the metadata side via lowerDefaultValueIfNecessary and compares it to the
introspected tableColumn.default, which PostgresQueryRunner does not lowercase (it only strips
casts). The new functional test asserts the introspected schema default is
"tstzrange(CURRENT_TIMESTAMP, NULL)" (uppercase keywords), which will not be strictly equal to the
lowercased metadata expression, causing the column to be flagged as changed on every schema diff
run.

src/driver/postgres/PostgresDriver.ts[1849-1877]
src/driver/postgres/PostgresDriver.ts[1204-1233]
src/driver/postgres/PostgresDriver.ts[1248-1271]
src/driver/postgres/PostgresDriver.ts[1623-1634]
src/driver/postgres/PostgresQueryRunner.ts[4075-4129]
test/functional/columns/default-columns/entity/Event.ts[1-13]
test/functional/columns/default-columns/column-default.test.ts[20-31]

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

## Issue description
`PostgresDriver.defaultEqual()` lowercases only the *metadata* default via `lowerDefaultValueIfNecessary(...)` and then compares it to `tableColumn.default` without applying the same normalization. With the new `normalizeDatetimeFunction` behavior (correctly returning composite expressions unchanged), composite defaults like `tstzrange(current_timestamp, null)` can be stored/introspected as `tstzrange(CURRENT_TIMESTAMP, NULL)`, making schema diff think the column is always changed.
### Issue Context
- `normalizeDefault()` returns the raw function string when it’s not an exact datetime function.
- `lowerDefaultValueIfNecessary()` lowercases outside quoted literals.
- `PostgresQueryRunner` strips casts but does not lowercase default expressions.
### Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[1248-1271]
- src/driver/postgres/PostgresDriver.ts[1623-1634]
### Suggested fix
In `defaultEqual()`, apply the same normalization to the table default before comparing, e.g.:
- `const normalizedMetadata = this.lowerDefaultValueIfNecessary(this.normalizeDefault(columnMetadata))`
- `const normalizedTable = this.lowerDefaultValueIfNecessary(tableColumn.default)`
- compare `normalizedMetadata === normalizedTable`
### Test reinforcement (optional but recommended)
Extend the newly added postgres test to run schema sync/log twice and assert no further diff is generated for the `sysPeriod` default.

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


5. Brittle default assertion 🐞 Bug ≡ Correctness
Description
The new Postgres functional test asserts an exact introspected default string
"tstzrange(CURRENT_TIMESTAMP, NULL)", but Postgres/TypeORM commonly canonicalize CURRENT_TIMESTAMP
to now(), so the database may report "tstzrange(now(), NULL)" and fail the test.
Code

test/functional/columns/default-columns/column-default.test.ts[R26-29]

Evidence
The test hard-codes CURRENT_TIMESTAMP inside the range default, but the Postgres driver itself
normalizes CURRENT_TIMESTAMP to "now()" (showing that now() is treated as the canonical
representation), and the Postgres schema introspection preserves "now()" defaults verbatim—so a DB
that emits now() inside the expression will not match the asserted string.

test/functional/columns/default-columns/column-default.test.ts[19-30]
src/driver/postgres/PostgresDriver.ts[1768-1795]
src/driver/postgres/PostgresQueryRunner.ts[4055-4062]

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 functional test asserts a single exact string for the introspected default of a `tstzrange` column. Postgres may canonicalize `CURRENT_TIMESTAMP` to `now()` (including when nested in expressions), causing CI failures depending on how the database formats stored defaults.
### Issue Context
TypeORM’s Postgres driver treats `CURRENT_TIMESTAMP` as equivalent to `now()` (see `normalizeDatetimeFunction`), and the query runner preserves `now()` defaults verbatim during schema introspection.
### Fix Focus Areas
- test/functional/columns/default-columns/column-default.test.ts[19-30]

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



Remediation recommended
6. Test missing #11990 reference 📘 Rule violation ⚙ Maintainability
Description
The new functional test validates the fix but does not include an issue-reference comment (e.g.,
Fixes #11990) near the test, which reduces traceability to the reported issue. This violates the
guideline to keep issue fixes in functional tests with an issue reference when applicable.
Code

test/functional/columns/default-columns/column-default.test.ts[R10-23]

+describe("columns > default columns", () => {
+    let dataSources: DataSource[]
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [__dirname...

@Cprakhar
Cprakhar force-pushed the fix/normalizeDatetimeFunction-postgres branch from 7bf5d73 to 69d74a8 Compare March 10, 2026 19:25
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 69d74a8

@coveralls

coveralls commented Mar 10, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 73.709% (-0.04%) from 73.745% — Cprakhar:fix/normalizeDatetimeFunction-postgres into typeorm:master

@Cprakhar
Cprakhar force-pushed the fix/normalizeDatetimeFunction-postgres branch from 69d74a8 to 2d8d6f6 Compare April 2, 2026 15:25
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 92fe1f9

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

Copy link
Copy Markdown

Persistent review updated to latest commit 4c2978f

@Cprakhar
Cprakhar force-pushed the fix/normalizeDatetimeFunction-postgres branch from 4c2978f to c179d4e Compare April 15, 2026 11:32
@sonarqubecloud

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Persistent review updated to latest commit c179d4e

@Cprakhar
Cprakhar force-pushed the fix/normalizeDatetimeFunction-postgres branch from c179d4e to 2ccabcc Compare May 8, 2026 13:08
@Cprakhar Cprakhar self-assigned this May 8, 2026

@smith-xyz smith-xyz 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.

Fix looks accurate to me.

Just a code style suggestion to help with readability.

curious if you could profile this function to see if the regex is slower versus the index and short circuit from before?

Comment thread src/driver/postgres/PostgresDriver.ts Resolved
@Cprakhar

Cprakhar commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

@smith-xyz Checkout the profiling result:

import { performance } from "perf_hooks";

const samples = [
  "CURRENT_TIMESTAMP",
  "CURRENT_TIMESTAMP(3)",
  "CURRENT_DATE",
  "LOCALTIME(6)",
  "random_string",
];

const ITERATIONS = 10_000_000;
for (let i = 0; i < 10; i++) {
console.log(`Run ${i + 1}:`);
const start = performance.now();
for (let i = 0; i < ITERATIONS; i++) {
  regexVersion(samples[i % samples.length]);
}
console.log("regex:", performance.now() - start);

const start2 = performance.now();
for (let i = 0; i < ITERATIONS; i++) {
  indexOfVersion(samples[i % samples.length]);
}
console.log("indexOf:", performance.now() - start2);
}

function indexOfVersion(value: string): string {
    const upperCaseValue = value.toUpperCase()
        const isDatetimeFunction =
            upperCaseValue.indexOf("CURRENT_TIMESTAMP") !== -1 ||
            upperCaseValue.indexOf("CURRENT_DATE") !== -1 ||
            upperCaseValue.indexOf("CURRENT_TIME") !== -1 ||
            upperCaseValue.indexOf("LOCALTIMESTAMP") !== -1 ||
            upperCaseValue.indexOf("LOCALTIME") !== -1

        if (isDatetimeFunction) {
            // extract precision, e.g. "(3)"
            const precision = value.match(/\(\d+\)/)

            if (upperCaseValue.indexOf("CURRENT_TIMESTAMP") !== -1) {
                return precision
                    ? `('now'::text)::timestamp${precision[0]} with time zone`
                    : "now()"
            } else if (upperCaseValue === "CURRENT_DATE") {
                return "('now'::text)::date"
            } else if (upperCaseValue.indexOf("CURRENT_TIME") !== -1) {
                return precision
                    ? `('now'::text)::time${precision[0]} with time zone`
                    : "('now'::text)::time with time zone"
            } else if (upperCaseValue.indexOf("LOCALTIMESTAMP") !== -1) {
                return precision
                    ? `('now'::text)::timestamp${precision[0]} without time zone`
                    : "('now'::text)::timestamp without time zone"
            } else if (upperCaseValue.indexOf("LOCALTIME") !== -1) {
                return precision
                    ? `('now'::text)::time${precision[0]} without time zone`
                    : "('now'::text)::time without time zone"
            }
        }

        return value
}

function regexVersion(value: string): string {
    const match = value.trim().toUpperCase().match(
        /^(CURRENT_TIMESTAMP|CURRENT_DATE|CURRENT_TIME|LOCALTIMESTAMP|LOCALTIME)(\(\d+\))?$/
    );

    if (!match) return value; 

    const [, funcName, precision = ''] = match;
    
    const prefix = "('now'::text)";

    switch (funcName) {
        case 'CURRENT_TIMESTAMP':
            return precision ? `${prefix}::timestamp${precision} with time zone` : "now()";
        case 'CURRENT_DATE':
            return `${prefix}::date`;
        case 'CURRENT_TIME':
            return `${prefix}::time${precision} with time zone`;
        case 'LOCALTIMESTAMP':
            return `${prefix}::timestamp${precision} without time zone`;
        case 'LOCALTIME':
            return `${prefix}::time${precision} without time zone`;
        default:
            return value;
    }
}

Result:

Run 1:
regex: 1176.771129
indexOf: 1117.945966
Run 2:
regex: 1217.647798
indexOf: 1187.8481549999997
Run 3:
regex: 1129.9035020000001
indexOf: 1155.3527999999997
Run 4:
regex: 1215.7293090000003
indexOf: 1151.0026039999993
Run 5:
regex: 1120.7011899999998
indexOf: 1150.800566
Run 6:
regex: 1120.8268100000005
indexOf: 1156.0653789999997
Run 7:
regex: 1127.973967
indexOf: 1152.8068390000008
Run 8:
regex: 1124.5077210000018
indexOf: 1170.899688999998
Run 9:
regex: 1123.7420980000024
indexOf: 1161.5906480000012
Run 10:
regex: 1131.932510999999
indexOf: 1160.9226649999982

Comment thread src/driver/postgres/PostgresDriver.ts Resolved
@alumni

alumni commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

Nice! I noticed indexOf is used in MysqlDriver, could we handle it similarly there?

BTW, I think the reason why indexOf was used instead of RegExp in the past is because you can do: "CURRENT_TIMESTAMP"(6) - function names are SQL identifiers so they can be quoted (like table names). You can also specify their schema, e.g.: SYS.CURRENT_TIMESTAMP in SAP HANA. I think it is highly unlikely though that someone would bother do that.

Another thing: the SpannerDriver also has this method, but it's unused (probably it was copy-pasted from MysqlDriver). Could we remove it? Thanks! :)

Comment thread src/driver/mysql/MysqlDriver.ts Resolved
@Cprakhar
Cprakhar force-pushed the fix/normalizeDatetimeFunction-postgres branch 2 times, most recently from b9edaa1 to ebc3fc2 Compare June 15, 2026 10:31
- remove unused normalizeDatetimeFunction method from spanner driver
- apply the regex logic in MySQL driver
@Cprakhar
Cprakhar force-pushed the fix/normalizeDatetimeFunction-postgres branch from ebc3fc2 to 57be3f6 Compare June 15, 2026 10:32
@alumni
alumni merged commit bf47c9f into typeorm:master Jun 15, 2026
46 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone Jun 15, 2026
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.

Defaults not respected for tstzrange columns

6 participants