sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

Rounding error with Postgres and DateTime

Open avandecreme opened this issue 3 months ago • 0 comments

I have found these related issues/pull requests

None

Description

Given the following datetime with nano second precision: 2025-01-01T18:06:41.502163654Z

If writing a query within postgres with it, it gets rounded up to the closest millisecond:

$ select '2025-01-01T18:06:41.502163654Z'::TIMESTAMPTZ
+-------------------------------+
| timestamptz                   |
|-------------------------------|
| 2025-01-01 18:06:41.502164+00 |
+-------------------------------+

However, executing the following sqlx code returns the value rounded down: 2025-01-01T18:06:41.502163Z

let datetime = "2025-01-01T18:06:41.502163Z"
    .parse::<DateTime<Utc>>()
    .unwrap();
sqlx::query_scalar!(
    r#"SELECT $1 AS "datetime!: DateTime<Utc>""#,
    datetime as DateTime<Utc>,
)
.fetch_one(&pg_pool)

Looking at the relevant code, it seems that the following change fixes the issue:

-        let micros = (*self - postgres_epoch_datetime())
+        let micros = (self.round_subsecs(6) - postgres_epoch_datetime())
            .num_microseconds()
            .ok_or_else(|| format!("NaiveDateTime out of range for Postgres: {self:?}"))?;

Would you be interested by such a fix?

Reproduction steps

See above

SQLx version

0.8.6

Enabled SQLx features

postgres, chrono

Database server and version

postgres 17

Operating system

macos

Rust version

1.89.0

avandecreme avatar Nov 06 '25 14:11 avandecreme