Skip to main content

sqlx_sqlserver/protocol/
type_info.rs

1use std::fmt::Write;
2
3use bytes::Bytes;
4use sqlx_core::encode::{Encode, IsNull};
5use sqlx_core::error::BoxDynError;
6
7use crate::Mssql;
8
9const PLP_NULL: u64 = 0xffff_ffff_ffff_ffff;
10const PLP_UNKNOWN_LENGTH: u64 = 0xffff_ffff_ffff_fffe;
11const PLP_CHUNK_SIZE: usize = 8192;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub(crate) struct CollationFlags(u8);
15
16impl CollationFlags {
17    pub(crate) const IGNORE_CASE: Self = Self(1 << 0);
18    pub(crate) const IGNORE_ACCENT: Self = Self(1 << 1);
19    pub(crate) const IGNORE_WIDTH: Self = Self(1 << 2);
20    pub(crate) const IGNORE_KANA: Self = Self(1 << 3);
21    pub(crate) const BINARY: Self = Self(1 << 4);
22    pub(crate) const BINARY2: Self = Self(1 << 5);
23    const UTF8: Self = Self(1 << 6);
24
25    pub(crate) const fn from_bits_truncate(bits: u8) -> Self {
26        Self(bits & 0x7f)
27    }
28
29    pub(crate) const fn bits(self) -> u8 {
30        self.0
31    }
32}
33
34#[derive(Debug, PartialEq, Eq, Clone, Copy)]
35pub(crate) struct Collation {
36    pub(crate) locale: u32,
37    pub(crate) flags: CollationFlags,
38    pub(crate) sort: u8,
39    pub(crate) version: u8,
40}
41
42#[derive(Debug, PartialEq, Eq, Clone, Copy)]
43#[repr(u8)]
44pub(crate) enum DataType {
45    // fixed-length data types
46    // https://docs.microsoft.com/en-us/openspecs/sql_server_protocols/ms-sstds/d33ef17b-7e53-4380-ad11-2ba42c8dda8d
47    Null = 0x1f,
48    TinyInt = 0x30,
49    Bit = 0x32,
50    SmallInt = 0x34,
51    Int = 0x38,
52    SmallDateTime = 0x3a,
53    Real = 0x3b,
54    Money = 0x3c,
55    DateTime = 0x3d,
56    Float = 0x3e,
57    SmallMoney = 0x7a,
58    BigInt = 0x7f,
59
60    // variable-length data types
61    // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-tds/ce3183a6-9d89-47e8-a02f-de5a1a1303de
62
63    // byte length
64    Guid = 0x24,
65    IntN = 0x26,
66    Decimal = 0x37,
67    Numeric = 0x3f,
68    BitN = 0x68,
69    DecimalN = 0x6a,
70    NumericN = 0x6c,
71    FloatN = 0x6d,
72    MoneyN = 0x6e,
73    DateTimeN = 0x6f,
74    DateN = 0x28,
75    TimeN = 0x29,
76    DateTime2N = 0x2a,
77    DateTimeOffsetN = 0x2b,
78    Char = 0x2f,
79    VarChar = 0x27,
80    Binary = 0x2d,
81    VarBinary = 0x25,
82
83    // short length
84    BigVarBinary = 0xa5,
85    BigVarChar = 0xa7,
86    BigBinary = 0xad,
87    BigChar = 0xaf,
88    NVarChar = 0xe7,
89    NChar = 0xef,
90    Xml = 0xf1,
91    UserDefined = 0xf0,
92
93    // long length
94    Text = 0x23,
95    Image = 0x22,
96    NText = 0x63,
97    Variant = 0x62,
98}
99
100// http://msdn.microsoft.com/en-us/library/dd358284.aspx
101#[derive(Debug, Clone, Eq, PartialEq)]
102pub(crate) struct TypeInfo {
103    pub(crate) ty: DataType,
104    pub(crate) size: u32,
105    pub(crate) scale: u8,
106    pub(crate) precision: u8,
107    pub(crate) collation: Option<Collation>,
108}
109
110impl TypeInfo {
111    pub(crate) const fn new(ty: DataType, size: u32) -> Self {
112        Self {
113            ty,
114            size,
115            scale: 0,
116            precision: 0,
117            collation: None,
118        }
119    }
120
121    // reads a TYPE_INFO from the buffer
122    pub(crate) fn get(input: &mut &[u8]) -> Result<Self, TypeInfoError> {
123        let ty = DataType::get(input)?;
124
125        Ok(match ty {
126            DataType::Null => Self::new(ty, 0),
127
128            DataType::TinyInt | DataType::Bit => Self::new(ty, 1),
129
130            DataType::SmallInt => Self::new(ty, 2),
131
132            DataType::Int | DataType::SmallDateTime | DataType::Real | DataType::SmallMoney => {
133                Self::new(ty, 4)
134            }
135
136            DataType::BigInt | DataType::Money | DataType::DateTime | DataType::Float => {
137                Self::new(ty, 8)
138            }
139
140            DataType::DateN => Self::new(ty, 3),
141
142            DataType::TimeN | DataType::DateTime2N | DataType::DateTimeOffsetN => {
143                let scale = read_u8(input)?;
144
145                let mut size = match scale {
146                    0..=2 => 3,
147                    3..=4 => 4,
148                    5..=7 => 5,
149                    scale => {
150                        return Err(TypeInfoError::InvalidScale { ty, scale });
151                    }
152                };
153
154                match ty {
155                    DataType::DateTime2N => {
156                        size += 3;
157                    }
158                    DataType::DateTimeOffsetN => {
159                        size += 5;
160                    }
161                    _ => {}
162                }
163
164                Self {
165                    scale,
166                    size,
167                    ty,
168                    precision: 0,
169                    collation: None,
170                }
171            }
172
173            DataType::Guid
174            | DataType::IntN
175            | DataType::BitN
176            | DataType::FloatN
177            | DataType::MoneyN
178            | DataType::DateTimeN
179            | DataType::Char
180            | DataType::VarChar
181            | DataType::Binary
182            | DataType::VarBinary => Self::new(ty, u32::from(read_u8(input)?)),
183
184            DataType::Decimal | DataType::Numeric | DataType::DecimalN | DataType::NumericN => {
185                let size = u32::from(read_u8(input)?);
186                let precision = read_u8(input)?;
187                let scale = read_u8(input)?;
188
189                Self {
190                    size,
191                    precision,
192                    scale,
193                    ty,
194                    collation: None,
195                }
196            }
197
198            DataType::BigVarBinary | DataType::BigBinary => {
199                Self::new(ty, u32::from(read_u16_le(input)?))
200            }
201
202            DataType::BigVarChar | DataType::BigChar | DataType::NVarChar | DataType::NChar => {
203                let size = u32::from(read_u16_le(input)?);
204                let collation = Collation::get(input)?;
205
206                Self {
207                    ty,
208                    size,
209                    collation: Some(collation),
210                    scale: 0,
211                    precision: 0,
212                }
213            }
214
215            DataType::Xml
216            | DataType::UserDefined
217            | DataType::Text
218            | DataType::Image
219            | DataType::NText
220            | DataType::Variant => {
221                return Err(TypeInfoError::UnsupportedDataType(ty));
222            }
223        })
224    }
225
226    // writes a TYPE_INFO to the buffer
227    pub(crate) fn put(&self, out: &mut Vec<u8>) -> Result<(), BoxDynError> {
228        out.push(self.ty as u8);
229
230        match self.ty {
231            DataType::Null
232            | DataType::TinyInt
233            | DataType::Bit
234            | DataType::SmallInt
235            | DataType::Int
236            | DataType::SmallDateTime
237            | DataType::Real
238            | DataType::SmallMoney
239            | DataType::BigInt
240            | DataType::Money
241            | DataType::DateTime
242            | DataType::Float => {}
243
244            DataType::TimeN | DataType::DateTime2N | DataType::DateTimeOffsetN => {
245                out.push(self.scale);
246            }
247
248            DataType::Guid
249            | DataType::IntN
250            | DataType::BitN
251            | DataType::FloatN
252            | DataType::MoneyN
253            | DataType::DateTimeN
254            | DataType::DateN
255            | DataType::Char
256            | DataType::VarChar
257            | DataType::Binary
258            | DataType::VarBinary => {
259                out.push(u8::try_from(self.size)?);
260            }
261
262            DataType::Decimal | DataType::Numeric | DataType::DecimalN | DataType::NumericN => {
263                out.push(u8::try_from(self.size)?);
264                out.push(self.precision);
265                out.push(self.scale);
266            }
267
268            DataType::BigVarBinary | DataType::BigBinary => {
269                out.extend_from_slice(&u16::try_from(self.size)?.to_le_bytes());
270            }
271
272            DataType::BigVarChar | DataType::BigChar | DataType::NVarChar | DataType::NChar => {
273                out.extend_from_slice(&u16::try_from(self.size)?.to_le_bytes());
274
275                if let Some(collation) = &self.collation {
276                    collation.put(out);
277                } else {
278                    out.extend_from_slice(&0_u32.to_le_bytes());
279                    out.push(0);
280                }
281            }
282
283            DataType::Xml
284            | DataType::UserDefined
285            | DataType::Text
286            | DataType::Image
287            | DataType::NText
288            | DataType::Variant => {
289                log::error!("Unsupported mssql data type argument writing {:?}", self.ty);
290            }
291        }
292
293        Ok(())
294    }
295
296    pub(crate) fn is_null(&self) -> bool {
297        matches!(self.ty, DataType::Null)
298    }
299
300    pub(crate) fn is_nullable_or_variable_length(&self) -> bool {
301        !matches!(
302            self.ty,
303            DataType::Null
304                | DataType::TinyInt
305                | DataType::Bit
306                | DataType::SmallInt
307                | DataType::Int
308                | DataType::SmallDateTime
309                | DataType::Real
310                | DataType::Money
311                | DataType::DateTime
312                | DataType::Float
313                | DataType::SmallMoney
314                | DataType::BigInt
315        )
316    }
317
318    pub(crate) fn get_value(
319        &self,
320        payload: &Bytes,
321        input: &mut &[u8],
322    ) -> Result<Option<Bytes>, TypeInfoError> {
323        Ok(match self.ty {
324            DataType::Null => None,
325
326            DataType::TinyInt
327            | DataType::Bit
328            | DataType::SmallInt
329            | DataType::Int
330            | DataType::SmallDateTime
331            | DataType::Real
332            | DataType::Money
333            | DataType::DateTime
334            | DataType::Float
335            | DataType::SmallMoney
336            | DataType::BigInt => Some(take_shared(payload, input, self.size as usize)?),
337
338            DataType::Guid
339            | DataType::IntN
340            | DataType::Decimal
341            | DataType::Numeric
342            | DataType::BitN
343            | DataType::DecimalN
344            | DataType::NumericN
345            | DataType::FloatN
346            | DataType::MoneyN
347            | DataType::DateN
348            | DataType::DateTimeN
349            | DataType::TimeN
350            | DataType::DateTime2N
351            | DataType::DateTimeOffsetN => {
352                let size = read_u8(input)?;
353
354                if size == 0 || size == 0xff {
355                    None
356                } else {
357                    Some(take_shared(payload, input, usize::from(size))?)
358                }
359            }
360
361            DataType::Char | DataType::VarChar | DataType::Binary | DataType::VarBinary => {
362                let size = read_u8(input)?;
363                if size == 0xff {
364                    None
365                } else {
366                    Some(take_shared(payload, input, usize::from(size))?)
367                }
368            }
369
370            DataType::BigVarBinary
371            | DataType::BigVarChar
372            | DataType::BigBinary
373            | DataType::BigChar
374            | DataType::NVarChar
375            | DataType::NChar
376            | DataType::Xml
377            | DataType::UserDefined => {
378                if self.size == 0xffff {
379                    self.get_big_blob(input)?
380                } else {
381                    let size = read_u16_le(input)?;
382                    if size == 0xffff {
383                        None
384                    } else {
385                        Some(take_shared(payload, input, usize::from(size))?)
386                    }
387                }
388            }
389
390            DataType::Text | DataType::Image | DataType::NText | DataType::Variant => {
391                let size = read_u32_le(input)?;
392
393                if size == 0xffff_ffff {
394                    None
395                } else {
396                    Some(take_shared(payload, input, usize::try_from(size).unwrap())?)
397                }
398            }
399        })
400    }
401
402    pub(crate) fn get_big_blob(&self, input: &mut &[u8]) -> Result<Option<Bytes>, TypeInfoError> {
403        let len = read_u64_le(input)?;
404        if len == PLP_NULL {
405            return Ok(None);
406        }
407
408        let mut data = Vec::new();
409        loop {
410            let chunk_size = read_u32_le(input)? as usize;
411
412            if chunk_size == 0 {
413                break;
414            }
415
416            data.extend_from_slice(take(input, chunk_size)?);
417        }
418
419        if len != PLP_UNKNOWN_LENGTH && len != data.len() as u64 {
420            return Err(TypeInfoError::InvalidPlpLength {
421                declared: len,
422                actual: data.len(),
423            });
424        }
425
426        Ok(Some(Bytes::from(data)))
427    }
428
429    pub(crate) fn put_value<'q, T: Encode<'q, Mssql>>(
430        &self,
431        out: &mut Vec<u8>,
432        value: T,
433    ) -> Result<(), BoxDynError> {
434        match self.ty {
435            DataType::Null
436            | DataType::TinyInt
437            | DataType::Bit
438            | DataType::SmallInt
439            | DataType::Int
440            | DataType::SmallDateTime
441            | DataType::Real
442            | DataType::Money
443            | DataType::DateTime
444            | DataType::DateN
445            | DataType::Float
446            | DataType::SmallMoney
447            | DataType::BigInt => {
448                self.put_fixed_value(out, value)?;
449            }
450
451            DataType::Guid
452            | DataType::IntN
453            | DataType::Decimal
454            | DataType::Numeric
455            | DataType::BitN
456            | DataType::DecimalN
457            | DataType::NumericN
458            | DataType::FloatN
459            | DataType::MoneyN
460            | DataType::DateTimeN
461            | DataType::TimeN
462            | DataType::DateTime2N
463            | DataType::DateTimeOffsetN
464            | DataType::Char
465            | DataType::VarChar
466            | DataType::Binary
467            | DataType::VarBinary => {
468                self.put_byte_len_value(out, value)?;
469            }
470
471            DataType::BigVarBinary
472            | DataType::BigVarChar
473            | DataType::BigBinary
474            | DataType::BigChar
475            | DataType::NVarChar
476            | DataType::NChar
477            | DataType::Xml
478            | DataType::UserDefined => {
479                if self.size == 0xffff {
480                    self.put_big_blob(out, value)?;
481                } else {
482                    self.put_short_len_value(out, value)?;
483                }
484            }
485
486            DataType::Text | DataType::Image | DataType::NText | DataType::Variant => {
487                self.put_long_len_value(out, value)?;
488            }
489        }
490
491        Ok(())
492    }
493
494    pub(crate) fn put_fixed_value<'q, T: Encode<'q, Mssql>>(
495        &self,
496        out: &mut Vec<u8>,
497        value: T,
498    ) -> Result<(), BoxDynError> {
499        let _ = value.encode(out)?;
500        Ok(())
501    }
502
503    pub(crate) fn put_byte_len_value<'q, T: Encode<'q, Mssql>>(
504        &self,
505        out: &mut Vec<u8>,
506        value: T,
507    ) -> Result<(), BoxDynError> {
508        let offset = out.len();
509        out.push(0);
510
511        let size = if let IsNull::Yes = value.encode(out)? {
512            0xff
513        } else {
514            u8::try_from(out.len() - offset - 1)?
515        };
516
517        out[offset] = size;
518        Ok(())
519    }
520
521    pub(crate) fn put_short_len_value<'q, T: Encode<'q, Mssql>>(
522        &self,
523        out: &mut Vec<u8>,
524        value: T,
525    ) -> Result<(), BoxDynError> {
526        let offset = out.len();
527        out.extend_from_slice(&0_u16.to_le_bytes());
528
529        let size = if let IsNull::Yes = value.encode(out)? {
530            0xffff
531        } else {
532            u16::try_from(out.len() - offset - 2)?
533        };
534
535        out[offset..(offset + 2)].copy_from_slice(&size.to_le_bytes());
536        Ok(())
537    }
538
539    pub(crate) fn put_big_blob<'q, T: Encode<'q, Mssql>>(
540        &self,
541        out: &mut Vec<u8>,
542        value: T,
543    ) -> Result<(), BoxDynError> {
544        let mut value_buf = Vec::new();
545        if let IsNull::Yes = value.encode(&mut value_buf)? {
546            out.extend_from_slice(&PLP_NULL.to_le_bytes());
547            return Ok(());
548        }
549
550        out.extend_from_slice(&u64::try_from(value_buf.len())?.to_le_bytes());
551
552        for chunk in value_buf.chunks(PLP_CHUNK_SIZE) {
553            out.extend_from_slice(&u32::try_from(chunk.len())?.to_le_bytes());
554            out.extend_from_slice(chunk);
555        }
556
557        out.extend_from_slice(&0_u32.to_le_bytes());
558        Ok(())
559    }
560
561    pub(crate) fn put_long_len_value<'q, T: Encode<'q, Mssql>>(
562        &self,
563        out: &mut Vec<u8>,
564        value: T,
565    ) -> Result<(), BoxDynError> {
566        let offset = out.len();
567        out.extend_from_slice(&0_u32.to_le_bytes());
568
569        let size = if let IsNull::Yes = value.encode(out)? {
570            0xffff_ffff
571        } else {
572            u32::try_from(out.len() - offset - 4)?
573        };
574
575        out[offset..(offset + 4)].copy_from_slice(&size.to_le_bytes());
576        Ok(())
577    }
578
579    pub(crate) fn name(&self) -> &'static str {
580        match self.ty {
581            DataType::Null => "NULL",
582            DataType::TinyInt => "TINYINT",
583            DataType::SmallInt => "SMALLINT",
584            DataType::Int => "INT",
585            DataType::BigInt => "BIGINT",
586            DataType::Real => "REAL",
587            DataType::Float => "FLOAT",
588
589            DataType::IntN => match self.size {
590                1 => "TINYINT",
591                2 => "SMALLINT",
592                4 => "INT",
593                8 => "BIGINT",
594                n => unreachable!("invalid size {} for int", n),
595            },
596
597            DataType::FloatN => match self.size {
598                4 => "REAL",
599                8 => "FLOAT",
600                n => unreachable!("invalid size {} for float", n),
601            },
602
603            DataType::VarChar => "VARCHAR",
604            DataType::NVarChar => "NVARCHAR",
605            DataType::BigVarChar => "BIGVARCHAR",
606            DataType::Char => "CHAR",
607            DataType::BigChar => "BIGCHAR",
608            DataType::NChar => "NCHAR",
609            DataType::VarBinary => "VARBINARY",
610            DataType::BigVarBinary => "BIGVARBINARY",
611            DataType::Binary => "BINARY",
612            DataType::BigBinary => "BIGBINARY",
613            DataType::DateN => "DATE",
614            DataType::DateTimeN => "DATETIME",
615            DataType::DateTime2N => "DATETIME2",
616            DataType::DateTimeOffsetN => "DATETIMEOFFSET",
617
618            DataType::Bit => "BIT",
619            DataType::SmallDateTime => "SMALLDATETIME",
620            DataType::Money => "MONEY",
621            DataType::DateTime => "DATETIME",
622            DataType::SmallMoney => "SMALLMONEY",
623            DataType::Guid => "UNIQUEIDENTIFIER",
624            DataType::Decimal => "DECIMAL",
625            DataType::Numeric => "NUMERIC",
626            DataType::BitN => "BIT",
627            DataType::DecimalN => "DECIMAL",
628            DataType::NumericN => "NUMERIC",
629            DataType::MoneyN => "MONEY",
630            DataType::TimeN => "TIME",
631            DataType::Xml => "XML",
632            DataType::UserDefined => "USER_DEFINED_TYPE",
633            DataType::Text => "TEXT",
634            DataType::Image => "IMAGE",
635            DataType::NText => "NTEXT",
636            DataType::Variant => "SQL_VARIANT",
637        }
638    }
639
640    pub(crate) fn fmt(&self, out: &mut String) {
641        match self.ty {
642            DataType::Null => out.push_str("nvarchar(1)"),
643            DataType::TinyInt => out.push_str("tinyint"),
644            DataType::SmallInt => out.push_str("smallint"),
645            DataType::Int => out.push_str("int"),
646            DataType::BigInt => out.push_str("bigint"),
647            DataType::Real => out.push_str("real"),
648            DataType::Float => out.push_str("float"),
649            DataType::Bit => out.push_str("bit"),
650
651            DataType::IntN => out.push_str(match self.size {
652                1 => "tinyint",
653                2 => "smallint",
654                4 => "int",
655                8 => "bigint",
656                n => unreachable!("invalid size {} for int", n),
657            }),
658
659            DataType::FloatN => out.push_str(match self.size {
660                4 => "real",
661                8 => "float",
662                n => unreachable!("invalid size {} for float", n),
663            }),
664
665            DataType::NVarChar | DataType::NChar => {
666                out.push_str(match self.ty {
667                    DataType::NVarChar => "nvarchar",
668                    DataType::NChar => "nchar",
669                    _ => unreachable!(),
670                });
671
672                if self.size == 0xffff {
673                    out.push_str("(max)");
674                } else {
675                    let _ = write!(out, "({})", self.size / 2);
676                }
677            }
678
679            DataType::VarChar
680            | DataType::BigVarChar
681            | DataType::Char
682            | DataType::BigChar
683            | DataType::VarBinary
684            | DataType::BigVarBinary
685            | DataType::Binary
686            | DataType::BigBinary => {
687                out.push_str(match self.ty {
688                    DataType::VarChar => "varchar",
689                    DataType::BigVarChar => "bigvarchar",
690                    DataType::Char => "char",
691                    DataType::BigChar => "bigchar",
692                    DataType::VarBinary => "varbinary",
693                    DataType::BigVarBinary => "varbinary",
694                    DataType::Binary => "binary",
695                    DataType::BigBinary => "binary",
696                    _ => unreachable!(),
697                });
698
699                if self.size == 0xffff {
700                    out.push_str("(max)");
701                } else {
702                    let _ = write!(out, "({})", self.size);
703                }
704            }
705
706            DataType::BitN => {
707                out.push_str("bit");
708            }
709
710            DataType::DateN => {
711                out.push_str("date");
712            }
713
714            DataType::DateTime | DataType::DateTimeN => {
715                out.push_str("datetime");
716            }
717
718            DataType::DateTime2N => {
719                let _ = write!(out, "datetime2({})", self.scale);
720            }
721
722            DataType::DateTimeOffsetN => {
723                let _ = write!(out, "datetimeoffset({})", self.scale);
724            }
725
726            DataType::TimeN => {
727                let _ = write!(out, "time({})", self.scale);
728            }
729            DataType::SmallDateTime => out.push_str("smalldatetime"),
730            DataType::Money => out.push_str("money"),
731            DataType::SmallMoney => out.push_str("smallmoney"),
732            DataType::Guid => out.push_str("uniqueidentifier"),
733            DataType::Decimal => out.push_str("decimal"),
734            DataType::Numeric => out.push_str("numeric"),
735            DataType::DecimalN => {
736                let _ = write!(out, "decimal({},{})", self.precision, self.scale);
737            }
738            DataType::NumericN => {
739                let _ = write!(out, "numeric({},{})", self.precision, self.scale);
740            }
741            DataType::MoneyN => {
742                let _ = write!(out, "money({})", self.scale);
743            }
744            DataType::Xml => out.push_str("xml"),
745            DataType::UserDefined => out.push_str("user_defined_type"),
746            DataType::Text => out.push_str("text"),
747            DataType::Image => out.push_str("image"),
748            DataType::NText => out.push_str("ntext"),
749            DataType::Variant => out.push_str("sql_variant"),
750        }
751    }
752}
753
754fn take_shared(payload: &Bytes, input: &mut &[u8], len: usize) -> Result<Bytes, TypeInfoError> {
755    let start = payload
756        .len()
757        .checked_sub(input.len())
758        .ok_or(TypeInfoError::UnexpectedEof)?;
759    take(input, len)?;
760    let end = payload
761        .len()
762        .checked_sub(input.len())
763        .ok_or(TypeInfoError::UnexpectedEof)?;
764    Ok(payload.slice(start..end))
765}
766
767impl DataType {
768    pub(crate) fn get(input: &mut &[u8]) -> Result<Self, TypeInfoError> {
769        Ok(match read_u8(input)? {
770            0x1f => DataType::Null,
771            0x30 => DataType::TinyInt,
772            0x32 => DataType::Bit,
773            0x34 => DataType::SmallInt,
774            0x38 => DataType::Int,
775            0x3a => DataType::SmallDateTime,
776            0x3b => DataType::Real,
777            0x3c => DataType::Money,
778            0x3d => DataType::DateTime,
779            0x3e => DataType::Float,
780            0x7a => DataType::SmallMoney,
781            0x7f => DataType::BigInt,
782            0x24 => DataType::Guid,
783            0x26 => DataType::IntN,
784            0x37 => DataType::Decimal,
785            0x3f => DataType::Numeric,
786            0x68 => DataType::BitN,
787            0x6a => DataType::DecimalN,
788            0x6c => DataType::NumericN,
789            0x6d => DataType::FloatN,
790            0x6e => DataType::MoneyN,
791            0x6f => DataType::DateTimeN,
792            0x28 => DataType::DateN,
793            0x29 => DataType::TimeN,
794            0x2a => DataType::DateTime2N,
795            0x2b => DataType::DateTimeOffsetN,
796            0x2f => DataType::Char,
797            0x27 => DataType::VarChar,
798            0x2d => DataType::Binary,
799            0x25 => DataType::VarBinary,
800            0xa5 => DataType::BigVarBinary,
801            0xa7 => DataType::BigVarChar,
802            0xad => DataType::BigBinary,
803            0xaf => DataType::BigChar,
804            0xe7 => DataType::NVarChar,
805            0xef => DataType::NChar,
806            0xf1 => DataType::Xml,
807            0xf0 => DataType::UserDefined,
808            0x23 => DataType::Text,
809            0x22 => DataType::Image,
810            0x63 => DataType::NText,
811            0x62 => DataType::Variant,
812            ty => return Err(TypeInfoError::UnknownDataType(ty)),
813        })
814    }
815}
816
817impl Collation {
818    pub(crate) fn encoding(self) -> &'static encoding_rs::Encoding {
819        if self.flags.bits() & CollationFlags::UTF8.bits() != 0 {
820            return encoding_rs::UTF_8;
821        }
822
823        // SQL Server reports a Windows locale identifier in the collation.
824        // Keep the code page mapping used by sqlx-oldapi.
825        match self.locale {
826            // Arabic locales
827            0x0401 | 0x3801 | 0x3C01 | 0x1401 | 0x0C01 | 0x0801 | 0x2C01 | 0x3401 | 0x3001
828            | 0x1001 | 0x1801 | 0x2001 | 0x4001 | 0x2801 | 0x1C01 | 0x2401 | 0x0429 | 0x0492
829            | 0x0846 | 0x048C | 0x0859 | 0x0420 | 0x0820 | 0x045F | 0x0480 => {
830                encoding_rs::WINDOWS_1256
831            }
832
833            // Chinese locales
834            0x0804 | 0x50804 | 0x20804 | 0x1004 | 0x51004 | 0x21004 => encoding_rs::GBK,
835            0x0C04 | 0x40C04 | 0x1404 | 0x41404 | 0x21404 | 0x0404 | 0x30404 | 0x40404 => {
836                encoding_rs::BIG5
837            }
838
839            // Cyrillic locales
840            0x082C | 0x046D | 0x0423 | 0x0402 | 0x201A | 0x0440 | 0x042F | 0x0450 | 0x0419
841            | 0x0819 | 0x0485 | 0x0428 | 0x0444 | 0x0422 | 0x0843 | 0x281A | 0x1C1A | 0x301A => {
842                encoding_rs::WINDOWS_1251
843            }
844
845            // Central European locales
846            0x141A | 0x0405 | 0x041A | 0x101A | 0x040E | 0x1040E | 0x0415 | 0x0418 | 0x0818
847            | 0x041B | 0x0424 | 0x041C | 0x241A | 0x181A | 0x2C1A | 0x0442 => {
848                encoding_rs::WINDOWS_1250
849            }
850
851            // Baltic locales
852            0x0425..=0x0427 => encoding_rs::WINDOWS_1257,
853
854            // Greek
855            0x0408 => encoding_rs::WINDOWS_1253,
856
857            // Hebrew
858            0x040D => encoding_rs::WINDOWS_1255,
859
860            // Japanese
861            0x0411 | 0x40411 => encoding_rs::SHIFT_JIS,
862
863            // Korean
864            0x0412 => encoding_rs::EUC_KR,
865
866            // Thai
867            0x041E => encoding_rs::WINDOWS_874,
868
869            // Turkish
870            0x042C | 0x041F | 0x0443 => encoding_rs::WINDOWS_1254,
871
872            // Vietnamese
873            0x042A => encoding_rs::WINDOWS_1258,
874
875            // Western European/US locales - default for unhandled LCIDs
876            _ => encoding_rs::WINDOWS_1252,
877        }
878    }
879
880    pub(crate) fn get(input: &mut &[u8]) -> Result<Collation, TypeInfoError> {
881        let locale_sort_version = read_u32_le(input)?;
882        let locale = locale_sort_version & 0xfffff;
883        let flags = CollationFlags::from_bits_truncate(((locale_sort_version >> 20) & 0xff) as u8);
884        let version = (locale_sort_version >> 28) as u8;
885        let sort = read_u8(input)?;
886
887        Ok(Collation {
888            locale,
889            flags,
890            sort,
891            version,
892        })
893    }
894
895    pub(crate) fn put(&self, out: &mut Vec<u8>) {
896        let locale_sort_version =
897            self.locale | ((u32::from(self.flags.bits())) << 20) | ((self.version as u32) << 28);
898
899        out.extend_from_slice(&locale_sort_version.to_le_bytes());
900        out.push(self.sort);
901    }
902}
903
904#[derive(Debug, thiserror::Error, PartialEq, Eq)]
905pub(crate) enum TypeInfoError {
906    #[error("TDS TYPE_INFO ended unexpectedly")]
907    UnexpectedEof,
908    #[error("unknown TDS data type 0x{0:02x}")]
909    UnknownDataType(u8),
910    #[error("unsupported TDS data type {0:?}")]
911    UnsupportedDataType(DataType),
912    #[error("invalid scale {scale} for type {ty:?}")]
913    InvalidScale { ty: DataType, scale: u8 },
914    #[error("TDS value declared {declared} bytes but contained {actual} bytes")]
915    InvalidPlpLength { declared: u64, actual: usize },
916}
917
918fn read_u8(input: &mut &[u8]) -> Result<u8, TypeInfoError> {
919    let bytes = take(input, 1)?;
920    Ok(bytes[0])
921}
922
923fn read_u16_le(input: &mut &[u8]) -> Result<u16, TypeInfoError> {
924    let bytes = take(input, 2)?;
925    Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
926}
927
928fn read_u32_le(input: &mut &[u8]) -> Result<u32, TypeInfoError> {
929    let bytes = take(input, 4)?;
930    Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
931}
932
933fn read_u64_le(input: &mut &[u8]) -> Result<u64, TypeInfoError> {
934    let bytes = take(input, 8)?;
935    Ok(u64::from_le_bytes([
936        bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
937    ]))
938}
939
940fn take<'a>(input: &mut &'a [u8], len: usize) -> Result<&'a [u8], TypeInfoError> {
941    let bytes = input.get(..len).ok_or(TypeInfoError::UnexpectedEof)?;
942    *input = &input[len..];
943    Ok(bytes)
944}
945
946#[cfg(test)]
947mod tests {
948    use super::*;
949
950    #[test]
951    fn parses_type_info_and_value_with_old_wire_constants() {
952        let payload = Bytes::copy_from_slice(&[
953            DataType::IntN as u8,
954            4,
955            4,
956            1,
957            0,
958            0,
959            0,
960            0xfe,
961            0,
962            0,
963            0xe0,
964            0,
965            0,
966            0,
967            0,
968            0,
969            0,
970            0,
971            0,
972            0,
973        ]);
974        let mut input = payload.as_ref();
975
976        let type_info = TypeInfo::get(&mut input).unwrap();
977
978        assert_eq!(type_info, TypeInfo::new(DataType::IntN, 4));
979        assert_eq!(
980            Some(Bytes::from_static(&[1, 0, 0, 0])),
981            type_info.get_value(&payload, &mut input).unwrap()
982        );
983    }
984
985    #[test]
986    fn put_round_trips_collation_for_nvarchar_type_info() {
987        let type_info = TypeInfo {
988            ty: DataType::NVarChar,
989            size: 8,
990            scale: 0,
991            precision: 0,
992            collation: Some(Collation {
993                locale: 0x0409,
994                flags: CollationFlags::IGNORE_CASE,
995                sort: 52,
996                version: 0,
997            }),
998        };
999
1000        let mut out = Vec::new();
1001        type_info.put(&mut out).unwrap();
1002        let mut input = out.as_slice();
1003
1004        assert_eq!(type_info, TypeInfo::get(&mut input).unwrap());
1005        assert!(input.is_empty());
1006    }
1007
1008    #[test]
1009    fn put_value_uses_old_byte_length_null_sentinel() {
1010        let type_info = TypeInfo::new(DataType::IntN, 4);
1011        let mut out = Vec::new();
1012
1013        type_info.put_value(&mut out, Option::<i32>::None).unwrap();
1014
1015        assert_eq!([0xff], out.as_slice());
1016    }
1017
1018    #[test]
1019    fn put_value_and_get_value_round_trip_max_nvarchar_blob() {
1020        let type_info = TypeInfo::new(DataType::NVarChar, 0xffff);
1021        let mut out = Vec::new();
1022
1023        type_info.put_value(&mut out, "hi").unwrap();
1024
1025        assert_eq!(&[4, 0, 0, 0, 0, 0, 0, 0], &out[..8]);
1026        assert_eq!(&[4, 0, 0, 0], &out[8..12]);
1027        assert_eq!(&[0, 0, 0, 0], &out[out.len() - 4..]);
1028
1029        let payload = Bytes::copy_from_slice(&out);
1030        let mut input = payload.as_ref();
1031        assert_eq!(
1032            Some(Bytes::from_static(&[b'h', 0, b'i', 0])),
1033            type_info.get_value(&payload, &mut input).unwrap()
1034        );
1035        assert!(input.is_empty());
1036    }
1037
1038    #[test]
1039    fn rejects_blob_with_mismatched_length() {
1040        let type_info = TypeInfo::new(DataType::BigVarBinary, 0xffff);
1041        let payload = Bytes::from_static(&[2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, b'a', 0, 0, 0, 0]);
1042        assert_eq!(
1043            Err(TypeInfoError::InvalidPlpLength {
1044                declared: 2,
1045                actual: 1,
1046            }),
1047            type_info.get_value(&payload, &mut payload.as_ref()),
1048        );
1049    }
1050
1051    #[test]
1052    fn put_value_chunks_large_max_nvarchar_blob() {
1053        let type_info = TypeInfo::new(DataType::NVarChar, 0xffff);
1054        let value = "x".repeat(PLP_CHUNK_SIZE + 1);
1055        let expected_len = value.encode_utf16().count() * 2;
1056        let mut out = Vec::new();
1057
1058        type_info.put_value(&mut out, value.as_str()).unwrap();
1059
1060        let mut input = out.as_slice();
1061        assert_eq!(expected_len as u64, read_u64_le(&mut input).unwrap());
1062        let mut chunk_sizes = Vec::new();
1063        loop {
1064            let chunk_size = read_u32_le(&mut input).unwrap() as usize;
1065            if chunk_size == 0 {
1066                break;
1067            }
1068
1069            chunk_sizes.push(chunk_size);
1070            let _ = take(&mut input, chunk_size).unwrap();
1071        }
1072
1073        assert_eq!(vec![PLP_CHUNK_SIZE, PLP_CHUNK_SIZE, 2], chunk_sizes);
1074        assert!(input.is_empty());
1075
1076        let payload = Bytes::copy_from_slice(&out);
1077        let mut input = payload.as_ref();
1078        assert_eq!(
1079            expected_len,
1080            type_info
1081                .get_value(&payload, &mut input)
1082                .unwrap()
1083                .unwrap()
1084                .len()
1085        );
1086        assert!(input.is_empty());
1087    }
1088
1089    #[test]
1090    fn put_value_encodes_null_max_nvarchar_blob() {
1091        let type_info = TypeInfo::new(DataType::NVarChar, 0xffff);
1092        let mut out = Vec::new();
1093
1094        type_info
1095            .put_value(&mut out, Option::<String>::None)
1096            .unwrap();
1097
1098        assert_eq!(PLP_NULL.to_le_bytes(), out.as_slice());
1099
1100        let payload = Bytes::copy_from_slice(&out);
1101        let mut input = payload.as_ref();
1102        assert_eq!(None, type_info.get_value(&payload, &mut input).unwrap());
1103        assert!(input.is_empty());
1104    }
1105
1106    #[test]
1107    fn formats_tds_type_declarations_like_old_protocol_module() {
1108        let mut out = String::new();
1109        TypeInfo::new(DataType::NVarChar, 12).fmt(&mut out);
1110
1111        assert_eq!("nvarchar(6)", out);
1112        assert_eq!("NVARCHAR", TypeInfo::new(DataType::NVarChar, 12).name());
1113    }
1114}