mssql-types 0.16.0

SQL Server to Rust type mappings and conversions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! Trait for converting Rust types to SQL values.

// Allow expect() for chrono date construction with known-valid constant dates
#![allow(clippy::expect_used)]

use crate::error::TypeError;
use crate::value::SqlValue;

/// Trait for types that can be converted to SQL values.
///
/// This trait is implemented for common Rust types to enable
/// type-safe parameter binding in queries.
pub trait ToSql {
    /// Convert this value to a SQL value.
    fn to_sql(&self) -> Result<SqlValue, TypeError>;

    /// Get the SQL type name for this value.
    fn sql_type(&self) -> &'static str;

    /// Explicit decimal precision and scale, when the value alone cannot convey
    /// it. `None` for every type except [`Numeric`] (created with [`numeric`]),
    /// which uses it to declare `decimal(precision, scale)` for an Always
    /// Encrypted column whose declared precision must match exactly.
    fn decimal_param_info(&self) -> Option<DecimalParamInfo> {
        None
    }
}

/// Explicit precision and scale for a `decimal`/`numeric` parameter (see
/// [`numeric`]).
#[derive(Debug, Clone, Copy)]
pub struct DecimalParamInfo {
    /// Total number of significant digits (1–38).
    pub precision: u8,
    /// Number of digits to the right of the decimal point.
    pub scale: u8,
}

impl ToSql for bool {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Bool(*self))
    }

    fn sql_type(&self) -> &'static str {
        "BIT"
    }
}

impl ToSql for u8 {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::TinyInt(*self))
    }

    fn sql_type(&self) -> &'static str {
        "TINYINT"
    }
}

impl ToSql for i16 {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::SmallInt(*self))
    }

    fn sql_type(&self) -> &'static str {
        "SMALLINT"
    }
}

impl ToSql for i32 {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Int(*self))
    }

    fn sql_type(&self) -> &'static str {
        "INT"
    }
}

impl ToSql for i64 {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::BigInt(*self))
    }

    fn sql_type(&self) -> &'static str {
        "BIGINT"
    }
}

impl ToSql for f32 {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Float(*self))
    }

    fn sql_type(&self) -> &'static str {
        "REAL"
    }
}

impl ToSql for f64 {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Double(*self))
    }

    fn sql_type(&self) -> &'static str {
        "FLOAT"
    }
}

impl ToSql for str {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::String(self.to_owned()))
    }

    fn sql_type(&self) -> &'static str {
        "NVARCHAR"
    }
}

impl ToSql for String {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::String(self.clone()))
    }

    fn sql_type(&self) -> &'static str {
        "NVARCHAR"
    }
}

impl ToSql for [u8] {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Binary(bytes::Bytes::copy_from_slice(self)))
    }

    fn sql_type(&self) -> &'static str {
        "VARBINARY"
    }
}

impl ToSql for Vec<u8> {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Binary(bytes::Bytes::copy_from_slice(self)))
    }

    fn sql_type(&self) -> &'static str {
        "VARBINARY"
    }
}

/// Associates a Rust type with its SQL type name so a typed NULL can be
/// declared without a value (see [`null`]).
///
/// `SQL_TYPE` must match what [`ToSql::sql_type`] returns for a value of the
/// same type.
pub trait SqlTyped {
    /// The SQL type name for this Rust type.
    const SQL_TYPE: &'static str;
}

impl SqlTyped for bool {
    const SQL_TYPE: &'static str = "BIT";
}
impl SqlTyped for u8 {
    const SQL_TYPE: &'static str = "TINYINT";
}
impl SqlTyped for i16 {
    const SQL_TYPE: &'static str = "SMALLINT";
}
impl SqlTyped for i32 {
    const SQL_TYPE: &'static str = "INT";
}
impl SqlTyped for i64 {
    const SQL_TYPE: &'static str = "BIGINT";
}
impl SqlTyped for f32 {
    const SQL_TYPE: &'static str = "REAL";
}
impl SqlTyped for f64 {
    const SQL_TYPE: &'static str = "FLOAT";
}
impl SqlTyped for String {
    const SQL_TYPE: &'static str = "NVARCHAR";
}
impl SqlTyped for Vec<u8> {
    const SQL_TYPE: &'static str = "VARBINARY";
}
#[cfg(feature = "uuid")]
impl SqlTyped for uuid::Uuid {
    const SQL_TYPE: &'static str = "UNIQUEIDENTIFIER";
}
#[cfg(feature = "chrono")]
impl SqlTyped for chrono::NaiveDate {
    const SQL_TYPE: &'static str = "DATE";
}

/// A typed NULL parameter, created with [`null`].
///
/// Unlike `Option::<T>::None`, which produces an untyped NULL declared as
/// `nvarchar(1)`, this carries its SQL type. That matters for Always Encrypted
/// columns, whose strict typing rejects an untyped NULL bound to, for example,
/// an `int` or `varbinary` column.
#[derive(Debug, Clone, Copy)]
pub struct TypedNull {
    sql_type: &'static str,
}

impl ToSql for TypedNull {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Null)
    }

    fn sql_type(&self) -> &'static str {
        self.sql_type
    }
}

/// Create a typed NULL parameter for SQL type `T`, e.g. `null::<i32>()`.
///
/// Use this in place of `Option::<T>::None` when binding NULL to a strongly
/// typed column — required for an Always Encrypted column of a non-string type.
#[must_use]
pub fn null<T: SqlTyped>() -> TypedNull {
    TypedNull {
        sql_type: T::SQL_TYPE,
    }
}

impl<T: ToSql> ToSql for Option<T> {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        match self {
            Some(v) => v.to_sql(),
            None => Ok(SqlValue::Null),
        }
    }

    fn sql_type(&self) -> &'static str {
        match self {
            Some(v) => v.sql_type(),
            None => "NULL",
        }
    }

    fn decimal_param_info(&self) -> Option<DecimalParamInfo> {
        self.as_ref().and_then(ToSql::decimal_param_info)
    }
}

impl<T: ToSql + ?Sized> ToSql for &T {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        (*self).to_sql()
    }

    fn sql_type(&self) -> &'static str {
        (*self).sql_type()
    }

    fn decimal_param_info(&self) -> Option<DecimalParamInfo> {
        (*self).decimal_param_info()
    }
}

#[cfg(feature = "uuid")]
impl ToSql for uuid::Uuid {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Uuid(*self))
    }

    fn sql_type(&self) -> &'static str {
        "UNIQUEIDENTIFIER"
    }
}

#[cfg(feature = "decimal")]
impl ToSql for rust_decimal::Decimal {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Decimal(*self))
    }

    fn sql_type(&self) -> &'static str {
        "DECIMAL"
    }
}

/// A `decimal`/`numeric` parameter with explicit precision and scale.
///
/// A plain [`rust_decimal::Decimal`] carries scale but not precision, so it
/// cannot be matched against an Always Encrypted `decimal` column, whose
/// declared `decimal(precision, scale)` must match the column exactly.
/// Construct one with [`numeric`].
#[cfg(feature = "decimal")]
#[derive(Debug, Clone, Copy)]
pub struct Numeric {
    value: rust_decimal::Decimal,
    precision: u8,
    scale: u8,
}

/// Create a `decimal`/`numeric` parameter with explicit precision and scale.
///
/// Required when binding to an Always Encrypted `decimal` column, whose declared
/// `decimal(precision, scale)` must match the column exactly. The value is
/// rescaled to `scale`.
#[cfg(feature = "decimal")]
#[must_use]
pub fn numeric(value: rust_decimal::Decimal, precision: u8, scale: u8) -> Numeric {
    Numeric {
        value,
        precision,
        scale,
    }
}

#[cfg(feature = "decimal")]
impl ToSql for Numeric {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        let mut value = self.value;
        value.rescale(u32::from(self.scale));
        Ok(SqlValue::Decimal(value))
    }

    fn sql_type(&self) -> &'static str {
        "DECIMAL"
    }

    fn decimal_param_info(&self) -> Option<DecimalParamInfo> {
        Some(DecimalParamInfo {
            precision: self.precision,
            scale: self.scale,
        })
    }
}

#[cfg(feature = "decimal")]
impl ToSql for crate::value::Money {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Money(self.0))
    }

    fn sql_type(&self) -> &'static str {
        "MONEY"
    }
}

#[cfg(feature = "decimal")]
impl ToSql for crate::value::SmallMoney {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::SmallMoney(self.0))
    }

    fn sql_type(&self) -> &'static str {
        "SMALLMONEY"
    }
}

#[cfg(feature = "chrono")]
impl ToSql for chrono::NaiveDate {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Date(*self))
    }

    fn sql_type(&self) -> &'static str {
        "DATE"
    }
}

#[cfg(feature = "chrono")]
impl ToSql for chrono::NaiveTime {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Time(*self))
    }

    fn sql_type(&self) -> &'static str {
        "TIME"
    }
}

#[cfg(feature = "chrono")]
impl ToSql for chrono::NaiveDateTime {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::DateTime(*self))
    }

    fn sql_type(&self) -> &'static str {
        "DATETIME2"
    }
}

#[cfg(feature = "chrono")]
impl ToSql for crate::value::SmallDateTime {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::SmallDateTime(self.0))
    }

    fn sql_type(&self) -> &'static str {
        "SMALLDATETIME"
    }
}

#[cfg(feature = "chrono")]
impl ToSql for chrono::DateTime<chrono::FixedOffset> {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::DateTimeOffset(*self))
    }

    fn sql_type(&self) -> &'static str {
        "DATETIMEOFFSET"
    }
}

#[cfg(feature = "chrono")]
impl ToSql for chrono::DateTime<chrono::Utc> {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        // Convert UTC to FixedOffset with +00:00 offset
        let fixed = self.with_timezone(&chrono::FixedOffset::east_opt(0).expect("valid offset"));
        Ok(SqlValue::DateTimeOffset(fixed))
    }

    fn sql_type(&self) -> &'static str {
        "DATETIMEOFFSET"
    }
}

#[cfg(feature = "json")]
impl ToSql for serde_json::Value {
    fn to_sql(&self) -> Result<SqlValue, TypeError> {
        Ok(SqlValue::Json(self.clone()))
    }

    fn sql_type(&self) -> &'static str {
        "NVARCHAR(MAX)"
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn test_to_sql_i32() {
        let value: i32 = 42;
        assert_eq!(value.to_sql().unwrap(), SqlValue::Int(42));
        assert_eq!(value.sql_type(), "INT");
    }

    #[test]
    fn test_typed_null_carries_type() {
        // A typed NULL is a NULL value that still reports its SQL type, and that
        // type matches what a value of the same Rust type reports.
        assert_eq!(null::<i32>().to_sql().unwrap(), SqlValue::Null);
        assert_eq!(null::<i32>().sql_type(), 42i32.sql_type());
        assert_eq!(null::<i64>().sql_type(), "BIGINT");
        assert_eq!(null::<Vec<u8>>().sql_type(), "VARBINARY");
        assert_eq!(null::<String>().sql_type(), "NVARCHAR");
    }

    #[test]
    fn test_to_sql_string() {
        let value = "hello".to_string();
        assert_eq!(
            value.to_sql().unwrap(),
            SqlValue::String("hello".to_string())
        );
        assert_eq!(value.sql_type(), "NVARCHAR");
    }

    #[test]
    fn test_to_sql_option() {
        let some: Option<i32> = Some(42);
        assert_eq!(some.to_sql().unwrap(), SqlValue::Int(42));

        let none: Option<i32> = None;
        assert_eq!(none.to_sql().unwrap(), SqlValue::Null);
    }
}