Skip to content

feat: support dynamic timestamp ScanLocation via DSN timezone #311

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

almas1992
Copy link

@almas1992 almas1992 commented May 21, 2025

  • Do only one thing
  • Non breaking API changes
  • Tested

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?

  • Parses the timezone value from the DSN, if provided
  • Loads the corresponding Go *time.Location
  • Registers a custom TimestampCodec with ScanLocation set to the parsed location

This 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 as Asia/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 as 2024-01-01 08:00:00 UTC instead of Asia/Shanghai.

This becomes problematic when:

  • Displaying times to end-users expecting local time
  • Comparing or calculating time ranges across services
  • Debugging issues where time shifts are hard to trace

To solve this, the DSN now accepts a timezone parameter (e.g., timezone=Asia/Shanghai), which is used to configure pgx’s TimestampCodec.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.

@almas1992 almas1992 force-pushed the master branch 3 times, most recently from 0c899b2 to c901b0e Compare May 21, 2025 07:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant