Repository navigation
fix(postgres): handle timestamptz persistence/hydration correctly - #11774
Conversation
WalkthroughAdds support for Postgres Changes
Sequence Diagram(s)sequenceDiagram
participant App as Application / Tests
participant Driver as PostgresDriver
participant DB as Postgres
Note over App,Driver: Persisting entity with timestamptz
App->>Driver: preparePersistentValue(value, columnMetadata)
alt column.type == "timestamptz"
Driver-->>Driver: convert Date -> DB string (ISO)
else other timestamp types
Driver-->>Driver: existing timestamp handling
end
Driver->>DB: execute INSERT/UPDATE with converted value
Note over DB,Driver: Hydration path
DB-->>Driver: returns timestamptz string
Driver->>Driver: prepareHydratedValue(dbValue, columnMetadata)
alt column.type == "timestamptz"
Driver-->>Driver: convert string -> Date object
else other timestamp types
Driver-->>Driver: existing timestamp handling
end
Driver->>App: returns hydrated entity with Date in `timestampTz`
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
commit: |
gioboa
left a comment
There was a problem hiding this comment.
Thanks for your help, can you add a test to cover this case please?
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
test/functional/database-schema/column-types/postgres/column-types-postgres.ts (1)
408-419: Consider adding a comment to clarify the cache-testing pattern.The double
findOnecalls test cache behavior: the first populates the cache from the database, and the second retrieves from the cache to verify proper serialization/deserialization of Date objects. While the pattern is clear to those familiar with cache testing, a brief comment would improve readability.Apply this diff to add a clarifying comment:
await postRepository.save(post) + // First query populates the cache from database await postRepository.findOne({ where: { id: 1, }, cache: true, }) + // Second query loads from cache to verify serialization/deserialization const loadedPost = (await postRepository.findOne({ where: { id: 1, }, cache: true, }))!
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
test/functional/database-schema/column-types/postgres/column-types-postgres.ts(3 hunks)test/functional/database-schema/column-types/postgres/entity/PostWithOptions.ts(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-07-27T20:50:10.364Z
Learnt from: alumni
Repo: typeorm/typeorm PR: 11581
File: docs/docs/drivers/postgres.md:23-23
Timestamp: 2025-07-27T20:50:10.364Z
Learning: The correct data source type for Aurora PostgreSQL in TypeORM is `aurora-postgres`, not `aurora-data-api-pg`. The `aurora-data-api-pg` driver was renamed to `aurora-postgres` according to the CHANGELOG.md. This is defined in the DatabaseType union type and AuroraPostgresConnectionOptions interface.
Applied to files:
test/functional/database-schema/column-types/postgres/entity/PostWithOptions.ts
🧬 Code graph analysis (1)
test/functional/database-schema/column-types/postgres/entity/PostWithOptions.ts (1)
src/decorator/columns/Column.ts (1)
Column(134-220)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (20)
- GitHub Check: tests-linux (20) / mysql_mariadb
- GitHub Check: tests-linux (20) / mssql
- GitHub Check: tests-linux (20) / mongodb
- GitHub Check: tests-linux (20) / oracle
- GitHub Check: tests-linux (18) / postgres (17)
- GitHub Check: tests-linux (18) / sap
- GitHub Check: tests-linux (18) / mysql_mariadb_latest
- GitHub Check: tests-linux (18) / postgres (14)
- GitHub Check: tests-linux (18) / sqljs
- GitHub Check: tests-linux (18) / mongodb
- GitHub Check: tests-linux (18) / oracle
- GitHub Check: tests-linux (18) / sqlite
- GitHub Check: tests-linux (18) / better-sqlite3
- GitHub Check: tests-linux (18) / mysql_mariadb
- GitHub Check: tests-linux (18) / mssql
- GitHub Check: tests-windows / sqljs
- GitHub Check: tests-windows / sqlite
- GitHub Check: tests-windows / better-sqlite3
- GitHub Check: formatting
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
test/functional/database-schema/column-types/postgres/entity/PostWithOptions.ts (1)
46-47: LGTM! Clean addition of timestamptz column.The new
timestampTzcolumn follows the same pattern as existing timestamp columns and correctly uses thetimestamptztype (PostgreSQL alias fortimestamp with time zone).test/functional/database-schema/column-types/postgres/column-types-postgres.ts (3)
18-18: Good addition to test cache behavior.Enabling caching is essential for testing the timestamptz persistence/hydration through the cache layer, which is the focus of this PR.
403-403: LGTM!The initialization of
timestampTzfollows the same pattern as other timestamp fields.
429-440: Excellent addition of instanceof Date assertions!The
instanceof Datechecks at lines 432, 436, and 440 are crucial for verifying that timestamp values are properly hydrated as Date objects when loaded from cache, not just as strings or plain objects. This directly validates the core objective of this PR—ensuringtimestamptz(and other timestamp types) are correctly serialized/deserialized through the cache layer.The assertions for the new
timestampTzfield (lines 437-440) properly test both value equality and type correctness.
|
Sure, I added a specific test for timestamptz and fixed the existing test case which was not really testing persistence/hydration since the data was not fetched from the cache |
gioboa
left a comment
There was a problem hiding this comment.
Thanks @Minishlink it looks great 👏
There was a problem hiding this comment.
Hello @Minishlink, could you update the branch?
| connections = await createTestingConnections({ | ||
| entities: [__dirname + "/entity/*{.js,.ts}"], | ||
| enabledDrivers: ["postgres"], | ||
| cache: true, |
There was a problem hiding this comment.
I'll assume two things, so correct me if I'm wrong.
timestamptzcolumn types were not cached correctly as the type was not inpreparePersistentValueandprepareHydrateValue, so this PR fixes that.- The
cache: trueis to verify caching works for said column type.
If both assumptions are true then I'd prefer if caching was enabled separately in another test, since this particular file tests column types, not caching.
I've looked at other column-types-x.ts files to see if they have caching enabled and they don't.
See:
https://github.com/typeorm/typeorm/blob/master/test/functional/database-schema/column-types/mysql/column-types-mysql.ts#L16-L19
https://github.com/typeorm/typeorm/blob/master/test/functional/database-schema/column-types/cockroachdb/column-types-cockroach.ts#L23-L27
There was a problem hiding this comment.
Yes you're right. I assumed that persistence/hydration was linked to cache?
There was a problem hiding this comment.
I'm confused too 🤔
I am assuming that persistence/hydration works regardless of caching. i.e. data serialization/deserialization form/to database/ORM.
But then, why does timestamptz work without caching and fails when caching? i.e. if the issue is serialization/deserialization it should fail in both cases.
It might be that this logic here is executed somewhere which fixes the issue when caching is not used.
There was a problem hiding this comment.
I've made a small sample here, should fail if you enable caching, should success if you disable caching.
There was a problem hiding this comment.
Yes you're right. I assumed that persistence/hydration was linked to cache?
Nope. Cache has nothing do to with hydration.
Could we undo this line and merge master to see that the tests are still passing?
It should affect anything now, but we don't want any additional functionality affecting the result of the test in the future.
Without cache we don't test much here since we don't persist/hydrate
PR Code Suggestions ✨Latest suggestions up to f4e0706
Previous suggestionsSuggestions
|
||||||||||||||||||
Removed caching from testing column types in PostgreSQL.
PR Code Suggestions ✨
|
|||||||||
alumni
left a comment
There was a problem hiding this comment.
The PostWithOptions entity is reserved for data types that have parameters.
We already had Post.timestamptz and similar tests in test/functional/database-schema/column-types/postgres/column-types-postgres.ts lines 167-169 and 291-293 ("all types should work correctly - persist and hydrate").
So unless I'm missing something, the new test doesn't seem to be testing the change in this PR.
I would add the necessary assertions to the test above (for Post.timestamptz)
|
Hello @Minishlink, you could check my reproduction at https://github.com/G0maa/typeorm-bug-reproduce/blob/43407c7eb6feda7300846e566ec65aab11fc09d0/src/app.ts for this PR, If you uncomment the |
gioboa
left a comment
There was a problem hiding this comment.
@Minishlink thanks for opening this PR.
I'm closing this for now because it's stale and with conflicts, feel free to create a new PR with your improvements. 💪
User descriptionDescription of changeThis includes 'timestamptz' as type for values which are Date and should be serialized/deserialized in/from the cache. Pull-Request Checklist
Summary by CodeRabbit
PR TypeBug fix, Tests Description
Diagram Walkthroughflowchart LR
A["PostgreSQL timestamptz column"] -->|"serialize/deserialize"| B["DateUtils functions"]
B -->|"mixedDateToDate"| C["Date persistence"]
B -->|"normalizeHydratedDate"| D["Date hydration"]
E["Test with cache enabled"] -->|"validates"| C
E -->|"validates"| D
|
| Relevant files | |||||
|---|---|---|---|---|---|
| Bug fix |
| ||||
| Tests |
|
PR Code Suggestions ✨Explore these optional code suggestions:
|
|||||||||
Code Review by Qodo
1. Missing timestamptz in withPrecisionColumnTypes array
|
| columnMetadata.type === "datetime" || | ||
| columnMetadata.type === Date || | ||
| columnMetadata.type === "timestamp" || | ||
| columnMetadata.type === "timestamptz" || |
There was a problem hiding this comment.
1. Missing timestamptz in withprecisioncolumntypes array 🐞 Bug ✓ Correctness
• The withPrecisionColumnTypes array in PostgresDriver.ts lists column types that support precision, but timestamptz is not included despite being added to other timestamp type checks • This array is used by the framework to determine which column types can have precision specified, and its absence will cause the framework to reject or ignore precision values for timestamptz columns • This creates inconsistent type handling where timestamptz is recognized in some code paths but not in precision-related operations, leading to schema validation failures
Agent prompt
## Issue Description
The `withPrecisionColumnTypes` array in PostgresDriver.ts is missing the 'timestamptz' type, which prevents the framework from recognizing that timestamptz columns can have precision specified. This causes schema validation failures and inconsistent type handling.
## Issue Context
The PR adds `timestamptz` support in timestamp type checks (lines 661, 749) but doesn't update the `withPrecisionColumnTypes` array. Since `timestamptz` is PostgreSQL's alias for 'timestamp with time zone' and supports precision (0-6), it should be included in this array alongside the other timestamp types.
## Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[226-234]
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| columnMetadata.type === "datetime" || | ||
| columnMetadata.type === Date || | ||
| columnMetadata.type === "timestamp" || | ||
| columnMetadata.type === "timestamptz" || |
There was a problem hiding this comment.
2. Missing timestamptz in datatypedefaults object 🐞 Bug ✓ Correctness
• The dataTypeDefaults object in PostgresDriver.ts specifies default precision values for timestamp types but doesn't include timestamptz • This object is used by BaseQueryRunner to determine if a column's precision is the default value (6 for PostgreSQL timestamps) • Without this entry, the framework cannot correctly identify when a timestamptz column uses default precision, causing unnecessary schema synchronization operations and potential data integrity issues
Agent prompt
## Issue Description
The `dataTypeDefaults` object in PostgresDriver.ts is missing the 'timestamptz' type with its default precision value. This prevents the framework from correctly identifying when a timestamptz column uses the default precision, causing schema synchronization issues.
## Issue Context
PostgreSQL's `timestamptz` type has a default precision of 6, same as 'timestamp with time zone'. The BaseQueryRunner's `isDefaultColumnPrecision` method relies on this object to determine if a column's precision is the default value. Without this entry, the method will always return false for timestamptz columns, triggering unnecessary schema updates.
## Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[280-288]
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
Code Review by Qodo🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)
Great, no issues found!Qodo reviewed your code and found no material issues that require reviewⓘ The new review experience is currently in Beta. Learn more |
timestamptz persistence/hydration correctly
|
Later edit: Never mind, we already convert it to the actual column type in |
Description of change
This includes 'timestamptz' as type for values which are Date and should be serialized/deserialized in/from the cache.
Pull-Request Checklist
masterbranchFixes #00000(searched for timestamptz)Summary by CodeRabbit
New Features
Tests