Skip to content

Rounding error with Postgres and DateTime #4089

@avandecreme

Description

@avandecreme

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions