Skip to main content

sqlx_sqlserver/protocol/
type_info.rs

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