Skip to main content

sqlx_sqlserver/
value.rs

1use std::borrow::Cow;
2
3use bytes::Bytes;
4use sqlx_core::decode::Decode;
5use sqlx_core::encode::{Encode, IsNull};
6use sqlx_core::error::BoxDynError;
7use sqlx_core::types::Type;
8use sqlx_core::value::{Value, ValueRef};
9
10use crate::decimal_tools::{decode_money_bytes, decode_numeric_bytes};
11use crate::{Mssql, MssqlType, MssqlTypeInfo};
12
13/// Owned SQL Server value skeleton.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct MssqlValue {
16    type_info: MssqlTypeInfo,
17    data: Option<Bytes>,
18}
19
20impl MssqlValue {
21    /// Creates an owned value from type information and raw little-endian TDS bytes.
22    pub(crate) fn new(type_info: MssqlTypeInfo, data: Option<Bytes>) -> Self {
23        Self { type_info, data }
24    }
25
26    /// Creates a `NULL` value with the supplied type information.
27    pub fn null(type_info: MssqlTypeInfo) -> Self {
28        Self {
29            type_info,
30            data: None,
31        }
32    }
33}
34
35impl Value for MssqlValue {
36    type Database = Mssql;
37
38    fn as_ref(&self) -> MssqlValueRef<'_> {
39        MssqlValueRef {
40            type_info: &self.type_info,
41            data: self.data.as_ref().map(Bytes::as_ref),
42        }
43    }
44
45    fn type_info(&self) -> Cow<'_, MssqlTypeInfo> {
46        Cow::Borrowed(&self.type_info)
47    }
48
49    fn is_null(&self) -> bool {
50        self.data.is_none()
51    }
52}
53
54/// Borrowed SQL Server value skeleton.
55#[derive(Debug, Clone, Copy)]
56pub struct MssqlValueRef<'r> {
57    type_info: &'r MssqlTypeInfo,
58    data: Option<&'r [u8]>,
59}
60
61impl<'r> ValueRef<'r> for MssqlValueRef<'r> {
62    type Database = Mssql;
63
64    fn to_owned(&self) -> MssqlValue {
65        MssqlValue {
66            type_info: self.type_info.clone(),
67            data: self.data.map(Bytes::copy_from_slice),
68        }
69    }
70
71    fn type_info(&self) -> Cow<'_, MssqlTypeInfo> {
72        Cow::Borrowed(self.type_info)
73    }
74
75    fn is_null(&self) -> bool {
76        self.data.is_none()
77    }
78}
79
80impl<'r> MssqlValueRef<'r> {
81    pub(crate) fn as_bytes(&self) -> Option<&'r [u8]> {
82        self.data
83    }
84
85    #[cfg(any(
86        feature = "bigdecimal",
87        feature = "chrono",
88        feature = "decimal",
89        feature = "time"
90    ))]
91    pub(crate) fn mssql_type_info(&self) -> &'r MssqlTypeInfo {
92        self.type_info
93    }
94}
95
96fn non_null_bytes<'r>(value: MssqlValueRef<'r>, rust_type: &str) -> Result<&'r [u8], BoxDynError> {
97    value
98        .as_bytes()
99        .ok_or_else(|| format!("cannot decode SQL Server NULL as {rust_type}").into())
100}
101
102fn decode_integer(value: MssqlValueRef<'_>, rust_type: &str) -> Result<i64, BoxDynError> {
103    let bytes = non_null_bytes(value, rust_type)?;
104
105    if matches!(value.type_info.kind(), MssqlType::Decimal) {
106        return decode_numeric_integer(bytes, value.type_info.scale());
107    }
108
109    match bytes.len() {
110        1 => Ok(i64::from(bytes[0])),
111        2 => Ok(i64::from(i16::from_le_bytes([bytes[0], bytes[1]]))),
112        4 => Ok(i64::from(i32::from_le_bytes([
113            bytes[0], bytes[1], bytes[2], bytes[3],
114        ]))),
115        8 => Ok(i64::from_le_bytes([
116            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
117        ])),
118        len => Err(format!("cannot decode {len}-byte SQL Server integer as {rust_type}").into()),
119    }
120}
121
122fn decode_numeric_integer(bytes: &[u8], mut scale: u8) -> Result<i64, BoxDynError> {
123    let (sign, mut numerator) = decode_numeric_bytes(bytes)?;
124
125    while numerator % 10 == 0 && scale > 0 {
126        numerator /= 10;
127        scale -= 1;
128    }
129
130    if scale > 0 {
131        numerator /= 10_u128.pow(u32::from(scale));
132    }
133
134    let value = i64::try_from(numerator)?;
135    Ok(value * i64::from(sign))
136}
137
138#[allow(clippy::cast_precision_loss)]
139fn decode_numeric_f64(bytes: &[u8], mut scale: u8) -> Result<f64, BoxDynError> {
140    let (sign, mut numerator) = decode_numeric_bytes(bytes)?;
141
142    while numerator % 10 == 0 && scale > 0 {
143        numerator /= 10;
144        scale -= 1;
145    }
146
147    let denominator = 10_u128.pow(u32::from(scale));
148    let integer_part = (numerator / denominator) as f64;
149    let fractional_part = (numerator % denominator) as f64 / denominator as f64;
150    let absolute = integer_part + fractional_part;
151
152    Ok(if sign == 1 { absolute } else { -absolute })
153}
154
155#[allow(clippy::cast_precision_loss)]
156fn decode_money_f64(bytes: &[u8]) -> Result<f64, BoxDynError> {
157    let numerator = decode_money_bytes(bytes)?;
158    let denominator = 10_000;
159    let integer_part = (numerator / denominator) as f64;
160    let fractional_part = (numerator % denominator) as f64 / denominator as f64;
161
162    Ok(integer_part + fractional_part)
163}
164
165fn is_integer_compatible(ty: &MssqlTypeInfo) -> bool {
166    matches!(
167        ty.kind(),
168        MssqlType::TinyInt
169            | MssqlType::SmallInt
170            | MssqlType::Int
171            | MssqlType::BigInt
172            | MssqlType::Decimal
173    )
174}
175
176impl Type<Mssql> for i8 {
177    fn type_info() -> MssqlTypeInfo {
178        MssqlTypeInfo::SMALLINT
179    }
180
181    fn compatible(ty: &MssqlTypeInfo) -> bool {
182        is_integer_compatible(ty)
183    }
184}
185
186impl Encode<'_, Mssql> for i8 {
187    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
188        <i16 as Encode<Mssql>>::encode_by_ref(&i16::from(*self), buf)
189    }
190}
191
192impl Decode<'_, Mssql> for i8 {
193    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
194        Ok(i8::try_from(decode_integer(value, "i8")?)?)
195    }
196}
197
198impl Type<Mssql> for u8 {
199    fn type_info() -> MssqlTypeInfo {
200        MssqlTypeInfo::TINYINT
201    }
202
203    fn compatible(ty: &MssqlTypeInfo) -> bool {
204        is_integer_compatible(ty)
205    }
206}
207
208impl Encode<'_, Mssql> for u8 {
209    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
210        buf.push(*self);
211        Ok(IsNull::No)
212    }
213}
214
215impl Decode<'_, Mssql> for u8 {
216    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
217        Ok(u8::try_from(decode_integer(value, "u8")?)?)
218    }
219}
220
221impl Type<Mssql> for i32 {
222    fn type_info() -> MssqlTypeInfo {
223        MssqlTypeInfo::INT
224    }
225
226    fn compatible(ty: &MssqlTypeInfo) -> bool {
227        is_integer_compatible(ty)
228    }
229}
230
231impl Encode<'_, Mssql> for i32 {
232    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
233        buf.extend_from_slice(&self.to_le_bytes());
234        Ok(IsNull::No)
235    }
236}
237
238impl Type<Mssql> for bool {
239    fn type_info() -> MssqlTypeInfo {
240        MssqlTypeInfo::BIT
241    }
242
243    fn compatible(ty: &MssqlTypeInfo) -> bool {
244        matches!(ty.kind(), MssqlType::Bit)
245    }
246}
247
248impl Encode<'_, Mssql> for bool {
249    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
250        buf.push(u8::from(*self));
251        Ok(IsNull::No)
252    }
253}
254
255impl Decode<'_, Mssql> for bool {
256    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
257        let bytes = value
258            .as_bytes()
259            .ok_or_else(|| "cannot decode SQL Server NULL as bool".to_owned())?;
260
261        match bytes {
262            [0] => Ok(false),
263            [1] => Ok(true),
264            _ => Err("cannot decode SQL Server bit as bool".into()),
265        }
266    }
267}
268
269impl Type<Mssql> for i16 {
270    fn type_info() -> MssqlTypeInfo {
271        MssqlTypeInfo::SMALLINT
272    }
273
274    fn compatible(ty: &MssqlTypeInfo) -> bool {
275        is_integer_compatible(ty)
276    }
277}
278
279impl Encode<'_, Mssql> for i16 {
280    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
281        buf.extend_from_slice(&self.to_le_bytes());
282        Ok(IsNull::No)
283    }
284}
285
286impl Decode<'_, Mssql> for i16 {
287    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
288        Ok(i16::try_from(decode_integer(value, "i16")?)?)
289    }
290}
291
292impl Type<Mssql> for u16 {
293    fn type_info() -> MssqlTypeInfo {
294        MssqlTypeInfo::INT
295    }
296
297    fn compatible(ty: &MssqlTypeInfo) -> bool {
298        is_integer_compatible(ty)
299    }
300}
301
302impl Encode<'_, Mssql> for u16 {
303    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
304        <i32 as Encode<Mssql>>::encode_by_ref(&i32::from(*self), buf)
305    }
306}
307
308impl Decode<'_, Mssql> for u16 {
309    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
310        Ok(u16::try_from(decode_integer(value, "u16")?)?)
311    }
312}
313
314impl Decode<'_, Mssql> for i32 {
315    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
316        Ok(i32::try_from(decode_integer(value, "i32")?)?)
317    }
318}
319
320impl Type<Mssql> for u32 {
321    fn type_info() -> MssqlTypeInfo {
322        MssqlTypeInfo::BIGINT
323    }
324
325    fn compatible(ty: &MssqlTypeInfo) -> bool {
326        is_integer_compatible(ty)
327    }
328}
329
330impl Encode<'_, Mssql> for u32 {
331    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
332        <i64 as Encode<Mssql>>::encode_by_ref(&i64::from(*self), buf)
333    }
334}
335
336impl Decode<'_, Mssql> for u32 {
337    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
338        Ok(u32::try_from(decode_integer(value, "u32")?)?)
339    }
340}
341
342impl Type<Mssql> for u64 {
343    fn type_info() -> MssqlTypeInfo {
344        MssqlTypeInfo::BIGINT
345    }
346
347    fn compatible(ty: &MssqlTypeInfo) -> bool {
348        is_integer_compatible(ty)
349    }
350}
351
352impl Encode<'_, Mssql> for u64 {
353    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
354        let value = i64::try_from(*self)?;
355        <i64 as Encode<Mssql>>::encode_by_ref(&value, buf)
356    }
357}
358
359impl Decode<'_, Mssql> for u64 {
360    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
361        Ok(u64::try_from(decode_integer(value, "u64")?)?)
362    }
363}
364
365impl Type<Mssql> for i64 {
366    fn type_info() -> MssqlTypeInfo {
367        MssqlTypeInfo::BIGINT
368    }
369
370    fn compatible(ty: &MssqlTypeInfo) -> bool {
371        is_integer_compatible(ty)
372    }
373}
374
375impl Encode<'_, Mssql> for i64 {
376    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
377        buf.extend_from_slice(&self.to_le_bytes());
378        Ok(IsNull::No)
379    }
380}
381
382impl Decode<'_, Mssql> for i64 {
383    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
384        decode_integer(value, "i64")
385    }
386}
387
388impl Type<Mssql> for f32 {
389    fn type_info() -> MssqlTypeInfo {
390        MssqlTypeInfo::REAL
391    }
392
393    fn compatible(ty: &MssqlTypeInfo) -> bool {
394        <f64 as Type<Mssql>>::compatible(ty)
395    }
396}
397
398impl Encode<'_, Mssql> for f32 {
399    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
400        buf.extend_from_slice(&self.to_le_bytes());
401        Ok(IsNull::No)
402    }
403}
404
405impl Decode<'_, Mssql> for f32 {
406    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
407        if !matches!(value.type_info.kind(), MssqlType::Real) {
408            return Ok(<f64 as Decode<Mssql>>::decode(value)? as f32);
409        }
410
411        let bytes = value
412            .as_bytes()
413            .ok_or_else(|| "cannot decode SQL Server NULL as f32".to_owned())?;
414
415        match bytes {
416            [a, b, c, d] => Ok(f32::from_le_bytes([*a, *b, *c, *d])),
417            _ => Err("cannot decode SQL Server real as f32".into()),
418        }
419    }
420}
421
422impl Type<Mssql> for f64 {
423    fn type_info() -> MssqlTypeInfo {
424        MssqlTypeInfo::FLOAT
425    }
426
427    fn compatible(ty: &MssqlTypeInfo) -> bool {
428        matches!(
429            ty.kind(),
430            MssqlType::Real | MssqlType::Float | MssqlType::Decimal | MssqlType::Money
431        )
432    }
433}
434
435impl Decode<'_, Mssql> for f64 {
436    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
437        if matches!(value.type_info.kind(), MssqlType::Decimal) {
438            return decode_numeric_f64(non_null_bytes(value, "f64")?, value.type_info.scale());
439        }
440
441        if matches!(value.type_info.kind(), MssqlType::Money) {
442            return decode_money_f64(non_null_bytes(value, "f64")?);
443        }
444
445        match value
446            .as_bytes()
447            .ok_or_else(|| "cannot decode SQL Server NULL as f64".to_owned())?
448        {
449            [a, b, c, d] => Ok(f64::from(f32::from_le_bytes([*a, *b, *c, *d]))),
450            [a, b, c, d, e, f, g, h] => Ok(f64::from_le_bytes([*a, *b, *c, *d, *e, *f, *g, *h])),
451            _ => Err("cannot decode SQL Server float as f64".into()),
452        }
453    }
454}
455
456impl Encode<'_, Mssql> for f64 {
457    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
458        buf.extend_from_slice(&self.to_le_bytes());
459        Ok(IsNull::No)
460    }
461}
462
463impl Type<Mssql> for str {
464    fn type_info() -> MssqlTypeInfo {
465        // NULL strings have no value from which to infer length. ISNULL uses
466        // the first operand's type and length, so use NVARCHAR(MAX).
467        MssqlTypeInfo::with_size(MssqlType::NVarChar, u16::MAX)
468    }
469
470    fn compatible(ty: &MssqlTypeInfo) -> bool {
471        matches!(ty.kind(), MssqlType::NVarChar | MssqlType::VarChar)
472    }
473}
474
475impl Type<Mssql> for String {
476    fn type_info() -> MssqlTypeInfo {
477        <str as Type<Mssql>>::type_info()
478    }
479
480    fn compatible(ty: &MssqlTypeInfo) -> bool {
481        <str as Type<Mssql>>::compatible(ty)
482    }
483}
484
485impl Encode<'_, Mssql> for str {
486    fn produces(&self) -> Option<MssqlTypeInfo> {
487        Some(MssqlTypeInfo::with_size(
488            MssqlType::NVarChar,
489            nvarchar_parameter_size(self),
490        ))
491    }
492
493    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
494        for unit in self.encode_utf16() {
495            buf.extend_from_slice(&unit.to_le_bytes());
496        }
497
498        Ok(IsNull::No)
499    }
500}
501
502impl<'q> Encode<'q, Mssql> for &'q str {
503    fn produces(&self) -> Option<MssqlTypeInfo> {
504        <str as Encode<Mssql>>::produces(*self)
505    }
506
507    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
508        <str as Encode<Mssql>>::encode_by_ref(*self, buf)
509    }
510}
511
512impl Encode<'_, Mssql> for String {
513    fn produces(&self) -> Option<MssqlTypeInfo> {
514        <str as Encode<Mssql>>::produces(self.as_str())
515    }
516
517    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
518        <str as Encode<Mssql>>::encode_by_ref(self.as_str(), buf)
519    }
520}
521
522impl Decode<'_, Mssql> for String {
523    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
524        let bytes = value
525            .as_bytes()
526            .ok_or_else(|| "cannot decode SQL Server NULL as String".to_owned())?;
527
528        if matches!(value.type_info.kind(), MssqlType::VarChar) {
529            let encoding = varchar_encoding(value.type_info);
530            let text = encoding
531                .decode_without_bom_handling_and_without_replacement(bytes)
532                .ok_or("invalid SQL Server VARCHAR text for its collation")?;
533            return Ok(text.into_owned());
534        }
535
536        if bytes.len() % 2 != 0 {
537            return Err("cannot decode odd-length SQL Server UTF-16 text".into());
538        }
539
540        let units = bytes
541            .as_chunks::<2>()
542            .0
543            .iter()
544            .copied()
545            .map(u16::from_le_bytes)
546            .collect::<Vec<_>>();
547        Ok(String::from_utf16(&units)?)
548    }
549}
550
551impl<'r> Decode<'r, Mssql> for &'r str {
552    fn decode(value: MssqlValueRef<'r>) -> Result<Self, BoxDynError> {
553        if !matches!(value.type_info.kind(), MssqlType::VarChar) {
554            return Err("borrowed SQL Server &str decoding is only supported for VARCHAR; NVARCHAR requires UTF-16 allocation".into());
555        }
556
557        let encoding = varchar_encoding(value.type_info);
558        let bytes = non_null_bytes(value, "&str")?;
559        if encoding != encoding_rs::UTF_8 && !bytes.is_ascii() {
560            return Err("borrowed SQL Server &str requires UTF-8 or ASCII text; use String to decode this collation".into());
561        }
562        Ok(std::str::from_utf8(bytes)?)
563    }
564}
565
566fn varchar_encoding(type_info: &MssqlTypeInfo) -> &'static encoding_rs::Encoding {
567    type_info
568        .protocol_type_info()
569        .and_then(|info| info.collation)
570        .map_or(encoding_rs::UTF_8, |collation| collation.encoding())
571}
572
573impl Type<Mssql> for [u8] {
574    fn type_info() -> MssqlTypeInfo {
575        MssqlTypeInfo::VARBINARY
576    }
577
578    fn compatible(ty: &MssqlTypeInfo) -> bool {
579        matches!(ty.kind(), MssqlType::VarBinary)
580    }
581}
582
583impl Type<Mssql> for Vec<u8> {
584    fn type_info() -> MssqlTypeInfo {
585        <[u8] as Type<Mssql>>::type_info()
586    }
587
588    fn compatible(ty: &MssqlTypeInfo) -> bool {
589        <[u8] as Type<Mssql>>::compatible(ty)
590    }
591}
592
593impl Encode<'_, Mssql> for [u8] {
594    fn produces(&self) -> Option<MssqlTypeInfo> {
595        Some(MssqlTypeInfo::with_size(
596            MssqlType::VarBinary,
597            varbinary_parameter_size(self.len()),
598        ))
599    }
600
601    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
602        buf.extend_from_slice(self);
603        Ok(IsNull::No)
604    }
605}
606
607impl<'q> Encode<'q, Mssql> for &'q [u8] {
608    fn produces(&self) -> Option<MssqlTypeInfo> {
609        <[u8] as Encode<Mssql>>::produces(*self)
610    }
611
612    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
613        <[u8] as Encode<Mssql>>::encode_by_ref(*self, buf)
614    }
615}
616
617impl Encode<'_, Mssql> for Vec<u8> {
618    fn produces(&self) -> Option<MssqlTypeInfo> {
619        <[u8] as Encode<Mssql>>::produces(self.as_slice())
620    }
621
622    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
623        <[u8] as Encode<Mssql>>::encode_by_ref(self.as_slice(), buf)
624    }
625}
626
627impl Decode<'_, Mssql> for Vec<u8> {
628    fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> {
629        Ok(<&[u8] as Decode<Mssql>>::decode(value)?.to_vec())
630    }
631}
632
633impl<'r> Decode<'r, Mssql> for &'r [u8] {
634    fn decode(value: MssqlValueRef<'r>) -> Result<Self, BoxDynError> {
635        non_null_bytes(value, "bytes")
636    }
637}
638
639fn nvarchar_parameter_size(value: &str) -> u16 {
640    let bytes = value.encode_utf16().count().saturating_mul(2);
641    if bytes > 8000 {
642        u16::MAX
643    } else {
644        u16::try_from(std::cmp::max(2, bytes)).unwrap_or(u16::MAX)
645    }
646}
647
648fn varbinary_parameter_size(len: usize) -> u16 {
649    if len > 8000 {
650        u16::MAX
651    } else {
652        u16::try_from(std::cmp::max(1, len)).unwrap_or(u16::MAX)
653    }
654}
655
656#[cfg(test)]
657mod tests {
658    use super::*;
659
660    #[test]
661    fn integer_scalars_use_lossless_parameter_types() {
662        assert_eq!(MssqlTypeInfo::SMALLINT, <i8 as Type<Mssql>>::type_info());
663        assert_eq!(MssqlTypeInfo::TINYINT, <u8 as Type<Mssql>>::type_info());
664        assert_eq!(MssqlTypeInfo::INT, <u16 as Type<Mssql>>::type_info());
665        assert_eq!(MssqlTypeInfo::BIGINT, <u32 as Type<Mssql>>::type_info());
666    }
667
668    #[test]
669    fn encodes_unsigned_integer_scalars_without_saturation() {
670        let mut buf = Vec::new();
671        let _ = <u32 as Encode<Mssql>>::encode_by_ref(&u32::MAX, &mut buf).unwrap();
672        assert_eq!(i64::from(u32::MAX).to_le_bytes(), buf.as_slice());
673
674        buf.clear();
675        let _ = <u16 as Encode<Mssql>>::encode_by_ref(&u16::MAX, &mut buf).unwrap();
676        assert_eq!(i32::from(u16::MAX).to_le_bytes(), buf.as_slice());
677    }
678
679    #[test]
680    fn decodes_integer_scalars_with_range_checks() {
681        let value = MssqlValue::new(
682            MssqlTypeInfo::INT,
683            Some(Bytes::from(65_535_i32.to_le_bytes().to_vec())),
684        );
685        assert_eq!(
686            65_535_u16,
687            <u16 as Decode<Mssql>>::decode(value.as_ref()).unwrap()
688        );
689
690        let negative = MssqlValue::new(
691            MssqlTypeInfo::INT,
692            Some(Bytes::from((-1_i32).to_le_bytes().to_vec())),
693        );
694        assert!(<u16 as Decode<Mssql>>::decode(negative.as_ref()).is_err());
695
696        let too_large = MssqlValue::new(
697            MssqlTypeInfo::INT,
698            Some(Bytes::from(128_i32.to_le_bytes().to_vec())),
699        );
700        assert!(<i8 as Decode<Mssql>>::decode(too_large.as_ref()).is_err());
701    }
702
703    #[test]
704    fn integer_scalars_are_compatible_with_decimal() {
705        let mut numeric = vec![1_u8];
706        numeric.extend_from_slice(&42_u128.to_le_bytes());
707        let value = MssqlValue::new(MssqlTypeInfo::DECIMAL, Some(Bytes::from(numeric)));
708
709        assert!(<i64 as Type<Mssql>>::compatible(&MssqlTypeInfo::DECIMAL));
710        assert_eq!(
711            42_i64,
712            <i64 as Decode<Mssql>>::decode(value.as_ref()).unwrap()
713        );
714    }
715
716    #[test]
717    fn decodes_borrowed_bytes() {
718        let value = MssqlValue::new(
719            MssqlTypeInfo::VARBINARY,
720            Some(Bytes::from(vec![1, 2, 3, 4])),
721        );
722        let bytes = <&[u8] as Decode<Mssql>>::decode(value.as_ref()).unwrap();
723
724        assert_eq!(&[1, 2, 3, 4], bytes);
725    }
726
727    #[test]
728    fn decodes_ascii_varchar_as_utf8() {
729        let value = MssqlValue::new(MssqlTypeInfo::VARCHAR, Some(Bytes::from_static(b"hello")));
730
731        assert_eq!(
732            "hello",
733            <String as Decode<Mssql>>::decode(value.as_ref()).unwrap()
734        );
735        assert_eq!(
736            "hello",
737            <&str as Decode<Mssql>>::decode(value.as_ref()).unwrap()
738        );
739    }
740
741    #[test]
742    fn decodes_nvarchar_as_utf16() {
743        let mut data = Vec::new();
744        for unit in "hello".encode_utf16() {
745            data.extend_from_slice(&unit.to_le_bytes());
746        }
747
748        let value = MssqlValue::new(MssqlTypeInfo::NVARCHAR, Some(Bytes::from(data)));
749
750        assert_eq!(
751            "hello",
752            <String as Decode<Mssql>>::decode(value.as_ref()).unwrap()
753        );
754        assert!(<&str as Decode<Mssql>>::decode(value.as_ref()).is_err());
755    }
756}