diff --git a/README.md b/README.md index 98e6cd0..d45b2f8 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,19 @@ let mut conn = sqlx_core::any::AnyConnection::connect( .await?; ``` +## 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 ODBC uses two native pieces outside this crate: diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 641b9ae..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_local(), - ))); - Ok(IsNull::No) - } -} - fn timestamp_from_naive(value: NaiveDateTime) -> odbc_api::sys::Timestamp { odbc_api::sys::Timestamp { year: value.year() as i16, @@ -345,14 +333,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 +472,34 @@ mod tests { Ok(()) } + #[test] + 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) + .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 _ = 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"); + }; + 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 + ); + + Ok(()) + } + #[test] fn chrono_type_info_names_match_old_odbc() { assert_eq!(>::type_info().name(), "DATE"); diff --git a/tests/odbc/optional_types.rs b/tests/odbc/optional_types.rs index 4a30d3b..266c9fe 100644 --- a/tests/odbc/optional_types.rs +++ b/tests/odbc/optional_types.rs @@ -68,6 +68,45 @@ async fn chrono_round_trip() -> Result<(), Box> { 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 TIMESTAMP), + CAST(? AS TIMESTAMP WITH TIME ZONE) AT TIME ZONE 'UTC', + CAST(? AS TIMESTAMP WITH TIME ZONE) AT TIME ZONE 'UTC'", + ) + .bind(local) + .bind(local) + .bind(local.fixed_offset()) + .fetch_one(&mut conn) + .await?; + + // 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(()) +} + #[cfg(feature = "time")] #[tokio::test] async fn time_round_trip() -> Result<(), Box> {