feat: support dynamic timestamp ScanLocation via DSN timezone #311
+32
−13
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Background
By default, pgx parses PostgreSQL timestamp (without time zone) fields as UTC.
However, in many real-world scenarios, timestamps are stored in local time (e.g., Asia/Shanghai).
To address this, the timezone parameter is now extracted from the DSN and used to set
the ScanLocation of the pgtype.TimestampCodec, ensuring correct interpretation of timestamp values.
What did this pull request do?
timezone
value from the DSN, if provided*time.Location
TimestampCodec
withScanLocation
set to the parsed locationThis ensures that timestamp parsing behavior is aligned with the configured session time zone.
User Case Description
In many PostgreSQL schemas,
timestamp
fields (without time zone) are used to store datetime values in local time, such asAsia/Shanghai
.However, by default, the pgx driver parses these values as UTC, which can lead to incorrect time interpretation in applications — for example, an event saved as
2024-01-01 08:00:00
may be misinterpreted as2024-01-01 08:00:00 UTC
instead ofAsia/Shanghai
.This becomes problematic when:
To solve this, the DSN now accepts a
timezone
parameter (e.g.,timezone=Asia/Shanghai
), which is used to configure pgx’sTimestampCodec.ScanLocation
.This ensures that timestamp values are interpreted in the correct local time zone, aligning with how the data was originally stored.
This change improves consistency, prevents subtle bugs, and reduces the need for manual
.In(time.Local)
conversions in application code.