Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow converting from DateTime2 to Datetimen in 'tds73' #298

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
20 changes: 20 additions & 0 deletions src/tds/codec/column_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ use crate::{
};
use bytes::BufMut;
pub(crate) use bytes_mut_with_type_info::BytesMutWithTypeInfo;
use chrono::{Duration, NaiveDate};
use std::borrow::{BorrowMut, Cow};
use uuid::Uuid;

Expand Down Expand Up @@ -594,6 +595,25 @@ impl<'a> Encode<BytesMutWithTypeInfo<'a>> for ColumnData<'a> {
time.encode(&mut *dst)?;
}
#[cfg(feature = "tds73")]
(ColumnData::DateTime2(opt), Some(TypeInfo::VarLenSized(vlc)))
if vlc.r#type() == VarLenType::Datetimen =>
{
if let Some(dt2) = opt {
dst.put_u8(8);
let dt2_days = dt2.date().days();
let dt2_date =
NaiveDate::from_ymd_opt(1, 1, 1).unwrap() + Duration::days(dt2_days.into());
let dt1_days = dt2_days.checked_sub(693595).ok_or_else(|| crate::Error::Conversion(
format!("invalid datetime, expecting datetime not earlier than 1900-01-01 but got {:?}", dt2_date)
.into()))?; // minus days gap between year 1 and year 1900
let seconds_fragments = dt2.time().increments() * 100 * 300 / 1e9 as u64; // degrade second's precision
dst.put_u32_le(dt1_days as u32);
dst.put_u32_le(seconds_fragments as u32);
} else {
dst.put_u8(0);
}
}
#[cfg(feature = "tds73")]
(ColumnData::DateTime2(opt), Some(TypeInfo::VarLenSized(vlc)))
if vlc.r#type() == VarLenType::Datetime2 =>
{
Expand Down
2 changes: 1 addition & 1 deletion src/tds/time/chrono.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::tds::codec::ColumnData;
#[cfg(feature = "tds73")]
#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]
pub use chrono::offset::{FixedOffset, Utc};
pub use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime};
pub use chrono::{Duration, DateTime, NaiveDate, NaiveDateTime, NaiveTime};
#[cfg(feature = "tds73")]
use std::ops::Sub;

Expand Down