Skip to main content

sqlx_sqlserver/
type_info.rs

1use std::fmt::{self, Display, Formatter};
2
3use sqlx_core::type_info::TypeInfo;
4
5use crate::protocol::type_info as protocol;
6
7/// SQL Server scalar type families known by the skeleton driver.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum MssqlType {
10    /// SQL `NULL`.
11    Null,
12    /// SQL Server `bit`.
13    Bit,
14    /// SQL Server `tinyint`.
15    TinyInt,
16    /// SQL Server `smallint`.
17    SmallInt,
18    /// SQL Server `int`.
19    Int,
20    /// SQL Server `bigint`.
21    BigInt,
22    /// SQL Server `real`.
23    Real,
24    /// SQL Server `float`.
25    Float,
26    /// Unicode text such as `nvarchar`.
27    NVarChar,
28    /// Non-Unicode text such as `varchar`.
29    VarChar,
30    /// Binary data such as `varbinary`.
31    VarBinary,
32    /// SQL Server `decimal`/`numeric`.
33    Decimal,
34    /// SQL Server `money`/`smallmoney`.
35    Money,
36    /// SQL Server `date`.
37    Date,
38    /// SQL Server `time`.
39    Time,
40    /// SQL Server legacy `datetime`/`smalldatetime`.
41    DateTime,
42    /// SQL Server `datetime2`.
43    DateTime2,
44    /// SQL Server `datetimeoffset`.
45    DateTimeOffset,
46    /// SQL Server `uniqueidentifier`.
47    UniqueIdentifier,
48    /// A type not yet mapped by this skeleton.
49    Other(String),
50}
51
52/// SQL Server type information.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct MssqlTypeInfo {
55    kind: MssqlType,
56    variable_length: bool,
57    size: Option<u16>,
58    protocol_type_info: Option<protocol::TypeInfo>,
59}
60
61impl MssqlTypeInfo {
62    /// Creates type information from a known SQL Server type family.
63    pub const fn new(kind: MssqlType) -> Self {
64        Self {
65            kind,
66            variable_length: false,
67            size: None,
68            protocol_type_info: None,
69        }
70    }
71
72    pub(crate) const fn with_size(kind: MssqlType, size: u16) -> Self {
73        Self {
74            kind,
75            variable_length: true,
76            size: Some(size),
77            protocol_type_info: None,
78        }
79    }
80
81    pub(crate) const fn with_protocol(
82        kind: MssqlType,
83        protocol_type_info: protocol::TypeInfo,
84    ) -> Self {
85        Self {
86            kind,
87            variable_length: true,
88            size: Some(protocol_type_info.size as u16),
89            protocol_type_info: Some(protocol_type_info),
90        }
91    }
92
93    /// Returns the known SQL Server type family.
94    pub fn kind(&self) -> &MssqlType {
95        &self.kind
96    }
97
98    pub(crate) const fn size(&self) -> Option<u16> {
99        self.size
100    }
101
102    pub(crate) const fn protocol_type_info(&self) -> Option<&protocol::TypeInfo> {
103        self.protocol_type_info.as_ref()
104    }
105
106    pub(crate) const fn scale(&self) -> u8 {
107        match &self.protocol_type_info {
108            Some(protocol_type_info) => protocol_type_info.scale,
109            None => 0,
110        }
111    }
112
113    pub(crate) const fn precision(&self) -> u8 {
114        match &self.protocol_type_info {
115            Some(protocol_type_info) => protocol_type_info.precision,
116            None => 0,
117        }
118    }
119
120    /// Returns the canonical SQL Server type family name.
121    pub fn name(&self) -> &str {
122        <Self as TypeInfo>::name(self)
123    }
124
125    /// SQL `NULL` type information.
126    pub const NULL: Self = Self::new(MssqlType::Null);
127    /// SQL Server `bit` type information.
128    pub const BIT: Self = Self::new(MssqlType::Bit);
129    /// SQL Server `tinyint` type information.
130    pub const TINYINT: Self = Self::new(MssqlType::TinyInt);
131    /// SQL Server `smallint` type information.
132    pub const SMALLINT: Self = Self::new(MssqlType::SmallInt);
133    /// SQL Server `int` type information.
134    pub const INT: Self = Self::new(MssqlType::Int);
135    /// SQL Server `bigint` type information.
136    pub const BIGINT: Self = Self::new(MssqlType::BigInt);
137    /// SQL Server `real` type information.
138    pub const REAL: Self = Self::new(MssqlType::Real);
139    /// SQL Server `float` type information.
140    pub const FLOAT: Self = Self::new(MssqlType::Float);
141    /// SQL Server Unicode text type information.
142    pub const NVARCHAR: Self = Self::new(MssqlType::NVarChar);
143    /// SQL Server non-Unicode text type information.
144    pub const VARCHAR: Self = Self::new(MssqlType::VarChar);
145    /// SQL Server binary type information.
146    pub const VARBINARY: Self = Self::new(MssqlType::VarBinary);
147    /// SQL Server decimal/numeric type information.
148    pub const DECIMAL: Self = Self::with_protocol(
149        MssqlType::Decimal,
150        protocol::TypeInfo {
151            ty: protocol::DataType::NumericN,
152            size: 17,
153            scale: 0,
154            precision: 38,
155            collation: None,
156        },
157    );
158    /// SQL Server money type information.
159    pub const MONEY: Self = Self::new(MssqlType::Money);
160    /// SQL Server date type information.
161    pub const DATE: Self = Self::with_protocol(
162        MssqlType::Date,
163        protocol::TypeInfo {
164            ty: protocol::DataType::DateN,
165            size: 3,
166            scale: 0,
167            precision: 10,
168            collation: None,
169        },
170    );
171    /// SQL Server time type information.
172    pub const TIME: Self = Self::with_protocol(
173        MssqlType::Time,
174        protocol::TypeInfo {
175            ty: protocol::DataType::TimeN,
176            size: 5,
177            scale: 7,
178            precision: 0,
179            collation: None,
180        },
181    );
182    /// SQL Server datetime2 type information.
183    pub const DATETIME2: Self = Self::with_protocol(
184        MssqlType::DateTime2,
185        protocol::TypeInfo {
186            ty: protocol::DataType::DateTime2N,
187            size: 8,
188            scale: 7,
189            precision: 0,
190            collation: None,
191        },
192    );
193    /// SQL Server datetimeoffset type information.
194    pub const DATETIMEOFFSET: Self = Self::with_protocol(
195        MssqlType::DateTimeOffset,
196        protocol::TypeInfo {
197            ty: protocol::DataType::DateTimeOffsetN,
198            size: 10,
199            scale: 7,
200            precision: 34,
201            collation: None,
202        },
203    );
204    /// SQL Server uniqueidentifier type information.
205    pub const UNIQUEIDENTIFIER: Self = Self::with_protocol(
206        MssqlType::UniqueIdentifier,
207        protocol::TypeInfo {
208            ty: protocol::DataType::Guid,
209            size: 16,
210            scale: 0,
211            precision: 0,
212            collation: None,
213        },
214    );
215
216    #[cfg(any(feature = "bigdecimal", feature = "decimal"))]
217    pub(crate) const fn decimal_with_scale(scale: u8) -> Self {
218        Self::with_protocol(
219            MssqlType::Decimal,
220            protocol::TypeInfo {
221                ty: protocol::DataType::NumericN,
222                size: 17,
223                scale,
224                precision: 38,
225                collation: None,
226            },
227        )
228    }
229
230    pub(crate) fn from_protocol(type_info: &protocol::TypeInfo) -> Self {
231        let kind = match type_info.ty {
232            protocol::DataType::Null => MssqlType::Null,
233            protocol::DataType::Bit | protocol::DataType::BitN => MssqlType::Bit,
234            protocol::DataType::TinyInt => MssqlType::TinyInt,
235            protocol::DataType::SmallInt => MssqlType::SmallInt,
236            protocol::DataType::Int => MssqlType::Int,
237            protocol::DataType::BigInt => MssqlType::BigInt,
238            protocol::DataType::Real => MssqlType::Real,
239            protocol::DataType::Float => MssqlType::Float,
240            protocol::DataType::IntN => match type_info.size {
241                1 => MssqlType::TinyInt,
242                2 => MssqlType::SmallInt,
243                4 => MssqlType::Int,
244                8 => MssqlType::BigInt,
245                _ => MssqlType::Other(type_info.name().to_owned()),
246            },
247            protocol::DataType::FloatN => match type_info.size {
248                4 => MssqlType::Real,
249                8 => MssqlType::Float,
250                _ => MssqlType::Other(type_info.name().to_owned()),
251            },
252            protocol::DataType::NVarChar | protocol::DataType::NChar => MssqlType::NVarChar,
253            protocol::DataType::VarChar
254            | protocol::DataType::Char
255            | protocol::DataType::BigVarChar
256            | protocol::DataType::BigChar => MssqlType::VarChar,
257            protocol::DataType::VarBinary
258            | protocol::DataType::Binary
259            | protocol::DataType::BigVarBinary
260            | protocol::DataType::BigBinary => MssqlType::VarBinary,
261            protocol::DataType::Decimal
262            | protocol::DataType::DecimalN
263            | protocol::DataType::Numeric
264            | protocol::DataType::NumericN => MssqlType::Decimal,
265            protocol::DataType::Money
266            | protocol::DataType::MoneyN
267            | protocol::DataType::SmallMoney => MssqlType::Money,
268            protocol::DataType::DateN => MssqlType::Date,
269            protocol::DataType::TimeN => MssqlType::Time,
270            protocol::DataType::DateTime
271            | protocol::DataType::DateTimeN
272            | protocol::DataType::SmallDateTime => MssqlType::DateTime,
273            protocol::DataType::DateTime2N => MssqlType::DateTime2,
274            protocol::DataType::DateTimeOffsetN => MssqlType::DateTimeOffset,
275            protocol::DataType::Guid => MssqlType::UniqueIdentifier,
276            _ => MssqlType::Other(type_info.name().to_owned()),
277        };
278
279        Self {
280            kind,
281            variable_length: type_info.is_nullable_or_variable_length(),
282            size: u16::try_from(type_info.size).ok(),
283            protocol_type_info: Some(type_info.clone()),
284        }
285    }
286}
287
288impl TypeInfo for MssqlTypeInfo {
289    fn is_null(&self) -> bool {
290        matches!(self.kind, MssqlType::Null)
291    }
292
293    fn name(&self) -> &str {
294        match &self.kind {
295            MssqlType::Null => "NULL",
296            MssqlType::Bit => "BIT",
297            MssqlType::TinyInt => "TINYINT",
298            MssqlType::SmallInt => "SMALLINT",
299            MssqlType::Int => "INT",
300            MssqlType::BigInt => "BIGINT",
301            MssqlType::Real => "REAL",
302            MssqlType::Float => "FLOAT",
303            MssqlType::NVarChar => "NVARCHAR",
304            MssqlType::VarChar => "VARCHAR",
305            MssqlType::VarBinary => "VARBINARY",
306            MssqlType::Decimal => "DECIMAL",
307            MssqlType::Money => "MONEY",
308            MssqlType::Date => "DATE",
309            MssqlType::Time => "TIME",
310            MssqlType::DateTime => "DATETIME",
311            MssqlType::DateTime2 => "DATETIME2",
312            MssqlType::DateTimeOffset => "DATETIMEOFFSET",
313            MssqlType::UniqueIdentifier => "UNIQUEIDENTIFIER",
314            MssqlType::Other(name) => name,
315        }
316    }
317
318    fn type_compatible(&self, other: &Self) -> bool {
319        self.kind == other.kind || self.is_null() || other.is_null()
320    }
321}
322
323impl Display for MssqlTypeInfo {
324    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
325        f.write_str(self.name())
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    #[test]
334    fn exposes_sql_server_type_names() {
335        assert_eq!("INT", MssqlTypeInfo::INT.name());
336        assert_eq!("NVARCHAR", MssqlTypeInfo::NVARCHAR.to_string());
337        assert_eq!("VARCHAR", MssqlTypeInfo::VARCHAR.to_string());
338    }
339
340    #[test]
341    fn null_is_compatible_with_known_types() {
342        assert!(MssqlTypeInfo::NULL.type_compatible(&MssqlTypeInfo::INT));
343        assert!(MssqlTypeInfo::NVARCHAR.type_compatible(&MssqlTypeInfo::NULL));
344        assert!(!MssqlTypeInfo::INT.type_compatible(&MssqlTypeInfo::BIGINT));
345    }
346
347    #[test]
348    fn maps_unicode_and_non_unicode_protocol_text_separately() {
349        assert_eq!(
350            MssqlType::NVarChar,
351            MssqlTypeInfo::from_protocol(&protocol::TypeInfo::new(protocol::DataType::NVarChar, 8))
352                .kind
353        );
354        assert_eq!(
355            MssqlType::VarChar,
356            MssqlTypeInfo::from_protocol(&protocol::TypeInfo::new(protocol::DataType::VarChar, 8))
357                .kind
358        );
359        assert_eq!(
360            MssqlType::VarChar,
361            MssqlTypeInfo::from_protocol(&protocol::TypeInfo::new(
362                protocol::DataType::BigVarChar,
363                8,
364            ))
365            .kind
366        );
367    }
368}