Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,19 @@ let mut conn = sqlx_core::any::AnyConnection::connect(
.await?;
```

## Chrono timestamps

With the `chrono` feature, `DateTime<Local>` now binds as RFC 3339 text with its
offset, like `DateTime<FixedOffset>` and `DateTime<Utc>`. 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:
Expand Down
60 changes: 34 additions & 26 deletions src/types/chrono.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -110,29 +111,16 @@ impl<'q> Encode<'q, Odbc> for NaiveDateTime {
}
}

impl<'q> Encode<'q, Odbc> for DateTime<Utc> {
impl<'q, Tz: TimeZone> Encode<'q, Odbc> for DateTime<Tz>
where
Tz::Offset: std::fmt::Display,
{
fn encode_by_ref(&self, buf: &mut Vec<OdbcArgumentValue>) -> Result<IsNull, BoxDynError> {
buf.push(OdbcArgumentValue::Text(self.to_rfc3339()));
Ok(IsNull::No)
}
}

impl<'q> Encode<'q, Odbc> for DateTime<FixedOffset> {
fn encode_by_ref(&self, buf: &mut Vec<OdbcArgumentValue>) -> Result<IsNull, BoxDynError> {
buf.push(OdbcArgumentValue::Text(self.to_rfc3339()));
Ok(IsNull::No)
}
}

impl<'q> Encode<'q, Odbc> for DateTime<Local> {
fn encode_by_ref(&self, buf: &mut Vec<OdbcArgumentValue>) -> Result<IsNull, BoxDynError> {
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,
Expand Down Expand Up @@ -345,14 +333,6 @@ impl<'r> Decode<'r, Odbc> for DateTime<FixedOffset> {

impl<'r> Decode<'r, Odbc> for DateTime<Local> {
fn decode(value: OdbcValueRef<'r>) -> Result<Self, BoxDynError> {
if let Some(timestamp) = raw_timestamp(value) {
return Ok(DateTime::<Utc>::from_naive_utc_and_offset(
naive_from_timestamp(timestamp)?,
Utc,
)
.with_timezone(&Local));
}

Ok(<DateTime<Utc> as Decode<Odbc>>::decode(value)?.with_timezone(&Local))
}
}
Expand Down Expand Up @@ -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::<Local>::from_naive_utc_and_offset(utc, FixedOffset::east_opt(3600).unwrap());

let mut buf = Vec::new();
let _ = <DateTime<Local> as Encode<Odbc>>::encode(local, &mut buf)?;
let _ = <DateTime<FixedOffset> as Encode<Odbc>>::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!(
<DateTime<Local> as Decode<Odbc>>::decode(value.as_ref())?,
local
);

Ok(())
}

#[test]
fn chrono_type_info_names_match_old_odbc() {
assert_eq!(<NaiveDate as Type<Odbc>>::type_info().name(), "DATE");
Expand Down
39 changes: 39 additions & 0 deletions tests/odbc/optional_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,45 @@ async fn chrono_round_trip() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}

#[cfg(feature = "chrono")]
#[tokio::test]
async fn chrono_local_timestamp_casts() -> Result<(), Box<dyn std::error::Error>> {
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::<Local>::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::<NaiveDateTime, _>(0)?, local.naive_local());
assert_eq!(row.try_get::<DateTime<Local>, _>(1)?, local);
assert_eq!(row.try_get::<NaiveDateTime, _>(2)?, utc);
conn.close().await?;
Ok(())
}

#[cfg(feature = "time")]
#[tokio::test]
async fn time_round_trip() -> Result<(), Box<dyn std::error::Error>> {
Expand Down