Skip to content

Commit

Permalink
allow converting from DateTime2 to Datetimen in 'tds73'
Browse files Browse the repository at this point in the history
  • Loading branch information
Geo-W committed Jun 3, 2023
1 parent 98943b2 commit b888b9d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/tds/codec/column_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ mod xml;
use super::{Encode, FixedLenType, TypeInfo, VarLenType};
#[cfg(feature = "tds73")]
use crate::tds::time::{Date, DateTime2, DateTimeOffset, Time};
use crate::time::chrono::from_days;
use crate::{
tds::{time::DateTime, time::SmallDateTime, xml::XmlData, Numeric},
SqlReadBytes,
Expand Down Expand Up @@ -594,6 +595,22 @@ 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 days = dt2.date().days().checked_sub(693595).ok_or_else(|| crate::Error::Conversion(
format!("invalid datetime, expecting datetime not earlier than 1900-01-01 but got {:?}",
from_days(dt2.date().days() as i64,1)).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(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 @@ -18,7 +18,7 @@ pub use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime};
use std::ops::Sub;

#[inline]
fn from_days(days: i64, start_year: i32) -> NaiveDate {
pub fn from_days(days: i64, start_year: i32) -> NaiveDate {
NaiveDate::from_ymd_opt(start_year, 1, 1).unwrap() + chrono::Duration::days(days)
}

Expand Down

0 comments on commit b888b9d

Please sign in to comment.