1#![allow(clippy::expect_used)]
8
9use bytes::{BufMut, BytesMut};
10
11use crate::error::TypeError;
12use crate::value::SqlValue;
13
14pub trait TdsEncode {
16 fn encode(&self, buf: &mut BytesMut) -> Result<(), TypeError>;
18
19 fn type_id(&self) -> u8;
21}
22
23impl TdsEncode for SqlValue {
24 fn encode(&self, buf: &mut BytesMut) -> Result<(), TypeError> {
25 match self {
26 SqlValue::Null => {
27 Ok(())
30 }
31 SqlValue::Bool(v) => {
32 buf.put_u8(if *v { 1 } else { 0 });
33 Ok(())
34 }
35 SqlValue::TinyInt(v) => {
36 buf.put_u8(*v);
37 Ok(())
38 }
39 SqlValue::SmallInt(v) => {
40 buf.put_i16_le(*v);
41 Ok(())
42 }
43 SqlValue::Int(v) => {
44 buf.put_i32_le(*v);
45 Ok(())
46 }
47 SqlValue::BigInt(v) => {
48 buf.put_i64_le(*v);
49 Ok(())
50 }
51 SqlValue::Float(v) => {
52 buf.put_f32_le(*v);
53 Ok(())
54 }
55 SqlValue::Double(v) => {
56 buf.put_f64_le(*v);
57 Ok(())
58 }
59 SqlValue::String(s) => {
60 encode_utf16_string(s, buf);
62 Ok(())
63 }
64 SqlValue::Binary(b) => {
65 if b.len() > u16::MAX as usize {
67 return Err(TypeError::BufferTooSmall {
68 needed: b.len(),
69 available: u16::MAX as usize,
70 });
71 }
72 buf.put_u16_le(b.len() as u16);
73 buf.put_slice(b);
74 Ok(())
75 }
76 #[cfg(feature = "decimal")]
77 SqlValue::Decimal(d) => {
78 encode_decimal(*d, buf);
79 Ok(())
80 }
81 #[cfg(feature = "decimal")]
82 SqlValue::Money(d) => encode_money(*d, buf),
83 #[cfg(feature = "decimal")]
84 SqlValue::SmallMoney(d) => encode_smallmoney(*d, buf),
85 #[cfg(feature = "uuid")]
86 SqlValue::Uuid(u) => {
87 encode_uuid(*u, buf);
88 Ok(())
89 }
90 #[cfg(feature = "chrono")]
91 SqlValue::Date(d) => encode_date(*d, buf),
92 #[cfg(feature = "chrono")]
93 SqlValue::Time(t) => {
94 encode_time(*t, buf);
95 Ok(())
96 }
97 #[cfg(feature = "chrono")]
98 SqlValue::DateTime(dt) => encode_datetime2(*dt, buf),
99 #[cfg(feature = "chrono")]
100 SqlValue::SmallDateTime(dt) => encode_smalldatetime(*dt, buf),
101 #[cfg(feature = "chrono")]
102 SqlValue::DateTimeOffset(dto) => encode_datetimeoffset(*dto, buf),
103 #[cfg(feature = "json")]
104 SqlValue::Json(j) => {
105 let s = j.to_string();
107 encode_utf16_string(&s, buf);
108 Ok(())
109 }
110 SqlValue::Xml(x) => {
111 encode_utf16_string(x, buf);
113 Ok(())
114 }
115 SqlValue::Tvp(_) => {
116 Err(TypeError::UnsupportedConversion {
121 from: "TvpData".to_string(),
122 to: "raw bytes (use RPC parameter encoding)",
123 })
124 }
125 }
126 }
127
128 fn type_id(&self) -> u8 {
129 match self {
130 SqlValue::Null => 0x1F, SqlValue::Bool(_) => 0x32, SqlValue::TinyInt(_) => 0x30, SqlValue::SmallInt(_) => 0x34, SqlValue::Int(_) => 0x38, SqlValue::BigInt(_) => 0x7F, SqlValue::Float(_) => 0x3B, SqlValue::Double(_) => 0x3E, SqlValue::String(_) => 0xE7, SqlValue::Binary(_) => 0xA5, #[cfg(feature = "decimal")]
141 SqlValue::Decimal(_) => 0x6C, #[cfg(feature = "decimal")]
143 SqlValue::Money(_) => 0x6E, #[cfg(feature = "decimal")]
145 SqlValue::SmallMoney(_) => 0x6E, #[cfg(feature = "uuid")]
147 SqlValue::Uuid(_) => 0x24, #[cfg(feature = "chrono")]
149 SqlValue::Date(_) => 0x28, #[cfg(feature = "chrono")]
151 SqlValue::Time(_) => 0x29, #[cfg(feature = "chrono")]
153 SqlValue::DateTime(_) => 0x2A, #[cfg(feature = "chrono")]
155 SqlValue::SmallDateTime(_) => 0x6F, #[cfg(feature = "chrono")]
157 SqlValue::DateTimeOffset(_) => 0x2B, #[cfg(feature = "json")]
159 SqlValue::Json(_) => 0xE7, SqlValue::Xml(_) => 0xF1, SqlValue::Tvp(_) => 0xF3, }
163 }
164}
165
166pub fn encode_utf16_string(s: &str, buf: &mut BytesMut) {
168 let utf16: Vec<u16> = s.encode_utf16().collect();
169 let byte_len = utf16.len() * 2;
170
171 buf.put_u16_le(byte_len as u16);
173
174 for code_unit in utf16 {
176 buf.put_u16_le(code_unit);
177 }
178}
179
180#[cfg(feature = "uuid")]
188pub fn encode_uuid(uuid: uuid::Uuid, buf: &mut BytesMut) {
189 let bytes = uuid.as_bytes();
190
191 buf.put_u8(bytes[3]);
193 buf.put_u8(bytes[2]);
194 buf.put_u8(bytes[1]);
195 buf.put_u8(bytes[0]);
196
197 buf.put_u8(bytes[5]);
199 buf.put_u8(bytes[4]);
200
201 buf.put_u8(bytes[7]);
203 buf.put_u8(bytes[6]);
204
205 buf.put_slice(&bytes[8..16]);
207}
208
209#[cfg(feature = "decimal")]
215pub fn encode_decimal(decimal: rust_decimal::Decimal, buf: &mut BytesMut) {
216 let sign = if decimal.is_sign_negative() { 0u8 } else { 1u8 };
217 buf.put_u8(sign);
218
219 let mantissa = decimal.mantissa().unsigned_abs();
221 buf.put_u128_le(mantissa);
222}
223
224#[cfg(feature = "decimal")]
229fn decimal_to_money_cents(value: rust_decimal::Decimal) -> Result<i128, TypeError> {
230 let mantissa: i128 = value.mantissa();
231 let scale: u32 = value.scale();
232 if scale <= 4 {
233 let factor = 10_i128.pow(4 - scale);
234 mantissa.checked_mul(factor).ok_or(TypeError::OutOfRange {
235 target_type: "MONEY",
236 })
237 } else {
238 let factor = 10_i128.pow(scale - 4);
239 Ok(mantissa / factor)
240 }
241}
242
243#[cfg(feature = "decimal")]
249pub fn decimal_to_money_cents_i64(value: rust_decimal::Decimal) -> Result<i64, TypeError> {
250 let cents_i128 = decimal_to_money_cents(value)?;
251 i64::try_from(cents_i128).map_err(|_| TypeError::OutOfRange {
252 target_type: "MONEY",
253 })
254}
255
256#[cfg(feature = "decimal")]
258pub fn decimal_to_smallmoney_cents_i32(value: rust_decimal::Decimal) -> Result<i32, TypeError> {
259 let cents_i128 = decimal_to_money_cents(value)?;
260 i32::try_from(cents_i128).map_err(|_| TypeError::OutOfRange {
261 target_type: "SMALLMONEY",
262 })
263}
264
265#[cfg(feature = "decimal")]
269pub fn encode_money(value: rust_decimal::Decimal, buf: &mut BytesMut) -> Result<(), TypeError> {
270 let cents = decimal_to_money_cents_i64(value)?;
271 let high = (cents >> 32) as i32;
272 let low = (cents & 0xFFFF_FFFF) as u32;
273 buf.put_i32_le(high);
274 buf.put_u32_le(low);
275 Ok(())
276}
277
278#[cfg(feature = "decimal")]
281pub fn encode_smallmoney(
282 value: rust_decimal::Decimal,
283 buf: &mut BytesMut,
284) -> Result<(), TypeError> {
285 let cents = decimal_to_smallmoney_cents_i32(value)?;
286 buf.put_i32_le(cents);
287 Ok(())
288}
289
290#[cfg(feature = "chrono")]
296pub fn datetime_to_legacy_days_ticks(dt: chrono::NaiveDateTime) -> (i32, u32) {
297 use chrono::Timelike;
298 let epoch = chrono::NaiveDate::from_ymd_opt(1900, 1, 1).expect("epoch 1900-01-01 is valid");
299 let days = (dt.date() - epoch).num_days() as i32;
300
301 let since_midnight = dt.time().num_seconds_from_midnight() as u64 * 1000
302 + u64::from(dt.time().nanosecond()) / 1_000_000;
303 let ticks = ((since_midnight * 3 + 5) / 10) as u32;
305 (days, ticks)
306}
307
308#[cfg(feature = "chrono")]
311pub fn encode_datetime_legacy(dt: chrono::NaiveDateTime, buf: &mut BytesMut) {
312 let (days, ticks) = datetime_to_legacy_days_ticks(dt);
313 buf.put_i32_le(days);
314 buf.put_u32_le(ticks);
315}
316
317#[cfg(feature = "chrono")]
326pub fn datetime_to_smalldatetime_days_minutes(
327 dt: chrono::NaiveDateTime,
328) -> Result<(u16, u16), TypeError> {
329 use chrono::Timelike;
330 let epoch = chrono::NaiveDate::from_ymd_opt(1900, 1, 1).expect("epoch 1900-01-01 is valid");
331
332 let total_seconds = dt.time().hour() * 3600 + dt.time().minute() * 60 + dt.time().second();
333 let minutes_raw = (total_seconds + 30) / 60;
334 let (day_carry, minutes) = if minutes_raw >= 1440 {
340 (1i64, 0u16)
341 } else {
342 (0i64, minutes_raw as u16)
343 };
344
345 let days_i64 = (dt.date() - epoch).num_days() + day_carry;
346 let days: u16 = u16::try_from(days_i64).map_err(|_| {
347 TypeError::InvalidDateTime(format!(
348 "SMALLDATETIME year must be 1900-2079, got date with {days_i64} days since 1900-01-01"
349 ))
350 })?;
351
352 Ok((days, minutes))
353}
354
355#[cfg(feature = "chrono")]
364pub fn encode_smalldatetime(
365 dt: chrono::NaiveDateTime,
366 buf: &mut BytesMut,
367) -> Result<(), TypeError> {
368 let (days, minutes) = datetime_to_smalldatetime_days_minutes(dt)?;
369 buf.put_u16_le(days);
370 buf.put_u16_le(minutes);
371 Ok(())
372}
373
374#[cfg(feature = "chrono")]
384pub fn encode_date(date: chrono::NaiveDate, buf: &mut BytesMut) -> Result<(), TypeError> {
385 const MAX_DAYS: i64 = 3_652_058;
387
388 let base = chrono::NaiveDate::from_ymd_opt(1, 1, 1).expect("valid date");
389 let days = date.signed_duration_since(base).num_days();
390 if !(0..=MAX_DAYS).contains(&days) {
391 return Err(TypeError::InvalidDateTime(format!(
392 "DATE must be between 0001-01-01 and 9999-12-31, got {date}"
393 )));
394 }
395 let days = days as u32;
396
397 buf.put_u8((days & 0xFF) as u8);
399 buf.put_u8(((days >> 8) & 0xFF) as u8);
400 buf.put_u8(((days >> 16) & 0xFF) as u8);
401 Ok(())
402}
403
404#[cfg(feature = "chrono")]
408pub fn encode_time(time: chrono::NaiveTime, buf: &mut BytesMut) {
409 use chrono::Timelike;
410
411 let nanos = time.num_seconds_from_midnight() as u64 * 1_000_000_000 + time.nanosecond() as u64;
414 let intervals = nanos / 100;
415
416 buf.put_u8((intervals & 0xFF) as u8);
418 buf.put_u8(((intervals >> 8) & 0xFF) as u8);
419 buf.put_u8(((intervals >> 16) & 0xFF) as u8);
420 buf.put_u8(((intervals >> 24) & 0xFF) as u8);
421 buf.put_u8(((intervals >> 32) & 0xFF) as u8);
422}
423
424#[cfg(feature = "chrono")]
433pub fn encode_datetime2(
434 datetime: chrono::NaiveDateTime,
435 buf: &mut BytesMut,
436) -> Result<(), TypeError> {
437 encode_time(datetime.time(), buf);
438 encode_date(datetime.date(), buf)
439}
440
441#[cfg(feature = "chrono")]
447pub fn encode_datetimeoffset(
448 datetime: chrono::DateTime<chrono::FixedOffset>,
449 buf: &mut BytesMut,
450) -> Result<(), TypeError> {
451 use chrono::Offset;
452
453 let utc = datetime.naive_utc();
455 encode_time(utc.time(), buf);
456 encode_date(utc.date(), buf)?;
457
458 let offset_seconds = datetime.offset().fix().local_minus_utc();
460 let offset_minutes = (offset_seconds / 60) as i16;
461 buf.put_i16_le(offset_minutes);
462 Ok(())
463}
464
465#[cfg(test)]
466#[allow(clippy::unwrap_used)]
467mod tests {
468 use super::*;
469
470 #[cfg(feature = "json")]
473 #[test]
474 fn test_json_encodes_as_nvarchar() {
475 let value = serde_json::json!({"name": "Ada", "id": 42});
476
477 let mut got = BytesMut::new();
478 SqlValue::Json(value.clone()).encode(&mut got).unwrap();
479
480 let mut want = BytesMut::new();
481 encode_utf16_string(&value.to_string(), &mut want);
482 assert_eq!(got, want);
483 }
484
485 #[cfg(feature = "chrono")]
491 #[test]
492 fn test_datetimeoffset_encodes_utc_instant() {
493 use chrono::TimeZone;
494
495 let offset = chrono::FixedOffset::east_opt(2 * 3600).unwrap();
496 let dto = offset.with_ymd_and_hms(2024, 3, 15, 12, 0, 0).unwrap();
497
498 let mut buf = BytesMut::new();
499 encode_datetimeoffset(dto, &mut buf).unwrap();
500 assert_eq!(buf.len(), 10); let mut intervals: u64 = 0;
504 for i in 0..5 {
505 intervals |= u64::from(buf[i]) << (8 * i);
506 }
507 assert_eq!(intervals, 10 * 3600 * 10_000_000, "time must be 10:00 UTC");
508
509 let days = u32::from(buf[5]) | (u32::from(buf[6]) << 8) | (u32::from(buf[7]) << 16);
511 let base = chrono::NaiveDate::from_ymd_opt(1, 1, 1).unwrap();
512 let expected_days =
513 (chrono::NaiveDate::from_ymd_opt(2024, 3, 15).unwrap() - base).num_days() as u32;
514 assert_eq!(days, expected_days);
515
516 assert_eq!(i16::from_le_bytes([buf[8], buf[9]]), 120);
518 }
519
520 #[test]
521 fn test_encode_int() {
522 let mut buf = BytesMut::new();
523 SqlValue::Int(42).encode(&mut buf).unwrap();
524 assert_eq!(&buf[..], &[42, 0, 0, 0]);
525 }
526
527 #[test]
528 fn test_encode_bigint() {
529 let mut buf = BytesMut::new();
530 SqlValue::BigInt(0x0102030405060708)
531 .encode(&mut buf)
532 .unwrap();
533 assert_eq!(&buf[..], &[0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01]);
534 }
535
536 #[test]
537 fn test_encode_utf16_string() {
538 let mut buf = BytesMut::new();
539 encode_utf16_string("AB", &mut buf);
540 assert_eq!(&buf[..], &[4, 0, 0x41, 0, 0x42, 0]);
542 }
543
544 #[cfg(feature = "uuid")]
545 #[test]
546 fn test_encode_uuid() {
547 let mut buf = BytesMut::new();
548 let uuid = uuid::Uuid::parse_str("12345678-1234-5678-1234-567812345678").unwrap();
549 encode_uuid(uuid, &mut buf);
550 assert_eq!(
552 &buf[..],
553 &[
554 0x78, 0x56, 0x34, 0x12, 0x34, 0x12, 0x78, 0x56, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78 ]
559 );
560 }
561
562 #[cfg(feature = "chrono")]
563 #[test]
567 fn test_encode_date_range_enforced() {
568 let mut buf = BytesMut::new();
569
570 let min = chrono::NaiveDate::from_ymd_opt(1, 1, 1).unwrap();
572 encode_date(min, &mut buf).unwrap();
573 assert_eq!(&buf[buf.len() - 3..], &[0, 0, 0]);
574 let max = chrono::NaiveDate::from_ymd_opt(9999, 12, 31).unwrap();
575 encode_date(max, &mut buf).unwrap();
576 assert_eq!(&buf[buf.len() - 3..], &[0xDA, 0xB9, 0x37]);
578
579 let before = chrono::NaiveDate::from_ymd_opt(0, 12, 31).unwrap();
581 assert!(matches!(
582 encode_date(before, &mut buf),
583 Err(TypeError::InvalidDateTime(_))
584 ));
585 let after = chrono::NaiveDate::from_ymd_opt(10000, 1, 1).unwrap();
586 assert!(matches!(
587 encode_date(after, &mut buf),
588 Err(TypeError::InvalidDateTime(_))
589 ));
590
591 let dt = before.and_hms_opt(12, 0, 0).unwrap();
593 assert!(encode_datetime2(dt, &mut buf).is_err());
594 }
595
596 #[test]
597 fn test_encode_date() {
598 let mut buf = BytesMut::new();
599 let date = chrono::NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();
600 encode_date(date, &mut buf).unwrap();
601 assert_eq!(buf.len(), 3);
603 }
604}