From 9d932c6d94da46ce23973d7d2ea6065d0f02c99c Mon Sep 17 00:00:00 2001 From: lovasoa Date: Thu, 19 Nov 2026 01:47:17 +0100 Subject: [PATCH 1/3] Store local chrono timestamps using UTC --- README.md | 6 ++++++ src/types/chrono.rs | 33 ++++++++++++++++++++++++--------- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 98e6cd0..89a5d84 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,12 @@ let mut conn = sqlx_core::any::AnyConnection::connect( .await?; ``` +## Local timestamps + +With the `chrono` feature, a `DateTime` bound to an ODBC timestamp uses +UTC. Earlier versions wrote local wall-clock time. Check existing data before +mixing old and new writers for the same timestamp column. + ## ODBC Setup ODBC uses two native pieces outside this crate: diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 641b9ae..d48c160 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -127,7 +127,7 @@ impl<'q> Encode<'q, Odbc> for DateTime { impl<'q> Encode<'q, Odbc> for DateTime { fn encode_by_ref(&self, buf: &mut Vec) -> Result { buf.push(OdbcArgumentValue::Timestamp(timestamp_from_naive( - self.naive_local(), + self.naive_utc(), ))); Ok(IsNull::No) } @@ -345,14 +345,6 @@ impl<'r> Decode<'r, Odbc> for DateTime { impl<'r> Decode<'r, Odbc> for DateTime { fn decode(value: OdbcValueRef<'r>) -> Result { - if let Some(timestamp) = raw_timestamp(value) { - return Ok(DateTime::::from_naive_utc_and_offset( - naive_from_timestamp(timestamp)?, - Utc, - ) - .with_timezone(&Local)); - } - Ok( as Decode>::decode(value)?.with_timezone(&Local)) } } @@ -492,6 +484,29 @@ mod tests { Ok(()) } + #[test] + fn local_datetime_preserves_the_instant_in_a_timestamp() -> Result<(), BoxDynError> { + let utc = NaiveDate::from_ymd_opt(2020, 1, 2) + .unwrap() + .and_hms_opt(23, 30, 0) + .unwrap(); + let local = + DateTime::::from_naive_utc_and_offset(utc, FixedOffset::east_opt(3600).unwrap()); + + let mut buf = Vec::new(); + let _ = as Encode>::encode(local, &mut buf)?; + let [OdbcArgumentValue::Timestamp(timestamp)] = buf.as_slice() else { + panic!("expected an ODBC timestamp"); + }; + let value = OdbcValue::new(OdbcValueKind::Timestamp(*timestamp)); + assert_eq!( + as Decode>::decode(value.as_ref())?, + local + ); + + Ok(()) + } + #[test] fn chrono_type_info_names_match_old_odbc() { assert_eq!(>::type_info().name(), "DATE"); From 11c22905cb9fd2d80c932e308ad346cbab2007b3 Mon Sep 17 00:00:00 2001 From: Ophir Lojkine Date: Fri, 27 Nov 2026 16:12:08 +0000 Subject: [PATCH 2/3] Verify local timestamps against real ODBC drivers --- README.md | 6 ++++-- tests/odbc/optional_types.rs | 23 ++++++++++++++++------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 89a5d84..9a8054d 100644 --- a/README.md +++ b/README.md @@ -73,8 +73,10 @@ let mut conn = sqlx_core::any::AnyConnection::connect( ## Local timestamps With the `chrono` feature, a `DateTime` bound to an ODBC timestamp uses -UTC. Earlier versions wrote local wall-clock time. Check existing data before -mixing old and new writers for the same timestamp column. +UTC. Earlier versions wrote local wall-clock time. To keep writing wall-clock +values, bind `value.naive_local()` as a `NaiveDateTime`. If the column stores +instants, review existing values written by non-UTC clients before upgrading +and migrate them using the time zone of the original writer. ## ODBC Setup diff --git a/tests/odbc/optional_types.rs b/tests/odbc/optional_types.rs index 4a30d3b..80575d3 100644 --- a/tests/odbc/optional_types.rs +++ b/tests/odbc/optional_types.rs @@ -44,7 +44,7 @@ async fn rust_decimal_round_trip() -> Result<(), Box> { #[cfg(feature = "chrono")] #[tokio::test] async fn chrono_round_trip() -> Result<(), Box> { - use chrono::{NaiveDate, NaiveDateTime, NaiveTime}; + use chrono::{DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime}; let Some(mut conn) = get_test_conn("chrono round trip").await? else { return Ok(()); @@ -54,16 +54,25 @@ async fn chrono_round_trip() -> Result<(), Box> { let time = NaiveTime::from_hms_opt(15, 30, 45).unwrap(); // The DuckDB ODBC driver does not round-trip timestamp fractions. let timestamp = date.and_time(time); - let row = query("SELECT CAST(? AS DATE), CAST(? AS TIME), CAST(? AS TIMESTAMP)") - .bind(date) - .bind(time) - .bind(timestamp) - .fetch_one(&mut conn) - .await?; + let local = DateTime::::from_naive_utc_and_offset( + timestamp, + FixedOffset::east_opt(7200).unwrap(), + ); + let row = query( + "SELECT CAST(? AS DATE), CAST(? AS TIME), CAST(? AS TIMESTAMP), CAST(? AS TIMESTAMP)", + ) + .bind(date) + .bind(time) + .bind(timestamp) + .bind(local) + .fetch_one(&mut conn) + .await?; assert_eq!(row.try_get::(0)?, date); assert_eq!(row.try_get::(1)?, time); assert_eq!(row.try_get::(2)?, timestamp); + assert_eq!(row.try_get::(3)?, local.naive_utc()); + assert_eq!(row.try_get::, _>(3)?, local); conn.close().await?; Ok(()) } From a4162326ee73746b71de370bb7f2bbc512c9089e Mon Sep 17 00:00:00 2001 From: Ophir Lojkine Date: Sat, 28 Nov 2026 16:28:00 +0000 Subject: [PATCH 3/3] Bind local chrono datetimes as offset-aware text --- README.md | 19 +++++++----- src/types/chrono.rs | 37 ++++++++++------------- tests/odbc/optional_types.rs | 58 +++++++++++++++++++++++++++--------- 3 files changed, 71 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 9a8054d..d45b2f8 100644 --- a/README.md +++ b/README.md @@ -70,13 +70,18 @@ let mut conn = sqlx_core::any::AnyConnection::connect( .await?; ``` -## Local timestamps - -With the `chrono` feature, a `DateTime` bound to an ODBC timestamp uses -UTC. Earlier versions wrote local wall-clock time. To keep writing wall-clock -values, bind `value.naive_local()` as a `NaiveDateTime`. If the column stores -instants, review existing values written by non-UTC clients before upgrading -and migrate them using the time zone of the original writer. +## Chrono timestamps + +With the `chrono` feature, `DateTime` now binds as RFC 3339 text with its +offset, like `DateTime` and `DateTime`. Previously it bound as +a plain ODBC timestamp containing the local clock time. The database decides +how to convert the text. For example, PostgreSQL and DuckDB use the offset when +casting to `TIMESTAMP WITH TIME ZONE` and discard it when casting to `TIMESTAMP`. + +To keep binding a plain timestamp, use `value.naive_local()` for the previous +wall-clock behavior or `value.naive_utc()` for a column that stores UTC by +convention. If you change what a column stores, review existing values before +mixing them with new writes. ## ODBC Setup diff --git a/src/types/chrono.rs b/src/types/chrono.rs index d48c160..26a65cc 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -1,7 +1,8 @@ use crate::value::OdbcValueRef; use crate::{DataTypeExt, Odbc, OdbcArgumentValue, OdbcTypeInfo, OdbcValueKind}; use ::chrono::{ - DateTime, Datelike, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Utc, + DateTime, Datelike, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, + Timelike, Utc, }; use odbc_api::DataType; use sqlx_core::decode::Decode; @@ -110,29 +111,16 @@ impl<'q> Encode<'q, Odbc> for NaiveDateTime { } } -impl<'q> Encode<'q, Odbc> for DateTime { +impl<'q, Tz: TimeZone> Encode<'q, Odbc> for DateTime +where + Tz::Offset: std::fmt::Display, +{ fn encode_by_ref(&self, buf: &mut Vec) -> Result { buf.push(OdbcArgumentValue::Text(self.to_rfc3339())); Ok(IsNull::No) } } -impl<'q> Encode<'q, Odbc> for DateTime { - fn encode_by_ref(&self, buf: &mut Vec) -> Result { - buf.push(OdbcArgumentValue::Text(self.to_rfc3339())); - Ok(IsNull::No) - } -} - -impl<'q> Encode<'q, Odbc> for DateTime { - fn encode_by_ref(&self, buf: &mut Vec) -> Result { - buf.push(OdbcArgumentValue::Timestamp(timestamp_from_naive( - self.naive_utc(), - ))); - Ok(IsNull::No) - } -} - fn timestamp_from_naive(value: NaiveDateTime) -> odbc_api::sys::Timestamp { odbc_api::sys::Timestamp { year: value.year() as i16, @@ -485,7 +473,7 @@ mod tests { } #[test] - fn local_datetime_preserves_the_instant_in_a_timestamp() -> Result<(), BoxDynError> { + fn local_and_fixed_offset_datetime_encode_as_the_same_text() -> Result<(), BoxDynError> { let utc = NaiveDate::from_ymd_opt(2020, 1, 2) .unwrap() .and_hms_opt(23, 30, 0) @@ -495,10 +483,15 @@ mod tests { let mut buf = Vec::new(); let _ = as Encode>::encode(local, &mut buf)?; - let [OdbcArgumentValue::Timestamp(timestamp)] = buf.as_slice() else { - panic!("expected an ODBC timestamp"); + let _ = as Encode>::encode(local.fixed_offset(), &mut buf)?; + let [OdbcArgumentValue::Text(local_text), OdbcArgumentValue::Text(fixed_text)] = + buf.as_slice() + else { + panic!("expected two text parameters"); }; - let value = OdbcValue::new(OdbcValueKind::Timestamp(*timestamp)); + assert_eq!(local_text, "2020-01-03T00:30:00+01:00"); + assert_eq!(local_text, fixed_text); + let value = OdbcValue::new(OdbcValueKind::Text(local_text.clone())); assert_eq!( as Decode>::decode(value.as_ref())?, local diff --git a/tests/odbc/optional_types.rs b/tests/odbc/optional_types.rs index 80575d3..266c9fe 100644 --- a/tests/odbc/optional_types.rs +++ b/tests/odbc/optional_types.rs @@ -44,7 +44,7 @@ async fn rust_decimal_round_trip() -> Result<(), Box> { #[cfg(feature = "chrono")] #[tokio::test] async fn chrono_round_trip() -> Result<(), Box> { - use chrono::{DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime}; + use chrono::{NaiveDate, NaiveDateTime, NaiveTime}; let Some(mut conn) = get_test_conn("chrono round trip").await? else { return Ok(()); @@ -54,25 +54,55 @@ async fn chrono_round_trip() -> Result<(), Box> { let time = NaiveTime::from_hms_opt(15, 30, 45).unwrap(); // The DuckDB ODBC driver does not round-trip timestamp fractions. let timestamp = date.and_time(time); - let local = DateTime::::from_naive_utc_and_offset( - timestamp, - FixedOffset::east_opt(7200).unwrap(), - ); + let row = query("SELECT CAST(? AS DATE), CAST(? AS TIME), CAST(? AS TIMESTAMP)") + .bind(date) + .bind(time) + .bind(timestamp) + .fetch_one(&mut conn) + .await?; + + assert_eq!(row.try_get::(0)?, date); + assert_eq!(row.try_get::(1)?, time); + assert_eq!(row.try_get::(2)?, timestamp); + conn.close().await?; + Ok(()) +} + +#[cfg(feature = "chrono")] +#[tokio::test] +async fn chrono_local_timestamp_casts() -> Result<(), Box> { + use chrono::{DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime}; + + let Some(mut conn) = get_test_conn("chrono local timestamp casts").await? else { + return Ok(()); + }; + let dbms = conn.dbms_name()?; + if !dbms.eq_ignore_ascii_case("PostgreSQL") && !dbms.eq_ignore_ascii_case("DuckDB") { + conn.close().await?; + return Ok(()); + } + + let utc = NaiveDate::from_ymd_opt(2024, 2, 29) + .unwrap() + .and_hms_opt(23, 30, 45) + .unwrap(); + let local = + DateTime::::from_naive_utc_and_offset(utc, FixedOffset::east_opt(7200).unwrap()); let row = query( - "SELECT CAST(? AS DATE), CAST(? AS TIME), CAST(? AS TIMESTAMP), CAST(? AS TIMESTAMP)", + "SELECT CAST(? AS TIMESTAMP), + CAST(? AS TIMESTAMP WITH TIME ZONE) AT TIME ZONE 'UTC', + CAST(? AS TIMESTAMP WITH TIME ZONE) AT TIME ZONE 'UTC'", ) - .bind(date) - .bind(time) - .bind(timestamp) .bind(local) + .bind(local) + .bind(local.fixed_offset()) .fetch_one(&mut conn) .await?; - assert_eq!(row.try_get::(0)?, date); - assert_eq!(row.try_get::(1)?, time); - assert_eq!(row.try_get::(2)?, timestamp); - assert_eq!(row.try_get::(3)?, local.naive_utc()); - assert_eq!(row.try_get::, _>(3)?, local); + // A plain timestamp cast discards the offset; the timezone-aware casts use it. + assert_eq!(row.try_get::(0)?, local.naive_local()); + assert_eq!(row.try_get::, _>(1)?, local); + assert_eq!(row.try_get::(2)?, utc); conn.close().await?; Ok(()) }