Skip to main content

sqlx_sqlserver/
arguments.rs

1use std::fmt::{self, Write};
2
3use sqlx_core::arguments::Arguments;
4use sqlx_core::encode::{Encode, IsNull};
5use sqlx_core::error::BoxDynError;
6use sqlx_core::types::Type;
7
8use crate::{Mssql, MssqlType, MssqlTypeInfo};
9
10const DATA_TYPE_INTN: u8 = 0x26;
11const DATA_TYPE_BITN: u8 = 0x68;
12const DATA_TYPE_FLOATN: u8 = 0x6d;
13const DATA_TYPE_GUID: u8 = 0x24;
14const DATA_TYPE_NUMERICN: u8 = 0x6c;
15const DATA_TYPE_DATEN: u8 = 0x28;
16const DATA_TYPE_TIMEN: u8 = 0x29;
17const DATA_TYPE_DATETIME2N: u8 = 0x2a;
18const DATA_TYPE_DATETIMEOFFSETN: u8 = 0x2b;
19const DATA_TYPE_BIGVARBINARY: u8 = 0xa5;
20const DATA_TYPE_BIGVARCHAR: u8 = 0xa7;
21const DATA_TYPE_NVARCHAR: u8 = 0xe7;
22const DEFAULT_COLLATION: [u8; 5] = [0x81, 0x04, 0xd0, 0x00, 0x34];
23const PLP_NULL: u64 = 0xffff_ffff_ffff_ffff;
24const PLP_CHUNK_SIZE: usize = 8192;
25const STATUS_BY_REF_VALUE: u8 = 0x01;
26
27/// SQL Server argument buffer.
28#[derive(Debug, Default, Clone)]
29pub struct MssqlArguments {
30    len: usize,
31    data: Vec<u8>,
32    declarations: String,
33}
34
35impl MssqlArguments {
36    /// Returns `true` when no arguments were added.
37    pub const fn is_empty(&self) -> bool {
38        self.len == 0
39    }
40
41    pub(crate) fn data(&self) -> &[u8] {
42        &self.data
43    }
44
45    pub(crate) fn declarations(&self) -> &str {
46        &self.declarations
47    }
48
49    fn add_parameter(
50        &mut self,
51        type_info: MssqlTypeInfo,
52        encoded: Vec<u8>,
53        is_null: bool,
54    ) -> Result<(), BoxDynError> {
55        let name = format!("@p{}", self.len + 1);
56        let declaration = declaration(&type_info, encoded.len(), is_null)?;
57        let data_len = self.data.len();
58
59        if let Err(error) = write_parameter(&mut self.data, &name, &type_info, &encoded, is_null) {
60            self.data.truncate(data_len);
61            return Err(error);
62        }
63
64        if !self.declarations.is_empty() {
65            self.declarations.push(',');
66        }
67
68        self.declarations.push_str(&name);
69        self.declarations.push(' ');
70        self.declarations.push_str(&declaration);
71        self.len += 1;
72        Ok(())
73    }
74}
75
76impl Arguments for MssqlArguments {
77    type Database = Mssql;
78
79    fn reserve(&mut self, _additional: usize, _size: usize) {}
80
81    fn add<'t, T>(&mut self, value: T) -> Result<(), BoxDynError>
82    where
83        T: Encode<'t, Self::Database> + Type<Self::Database>,
84    {
85        let type_info = value.produces().unwrap_or_else(T::type_info);
86        let mut encoded = Vec::with_capacity(value.size_hint());
87        let is_null = matches!(value.encode(&mut encoded)?, IsNull::Yes);
88        self.add_parameter(type_info, encoded, is_null)?;
89        Ok(())
90    }
91
92    fn len(&self) -> usize {
93        self.len
94    }
95
96    fn format_placeholder<W: Write>(&self, writer: &mut W) -> fmt::Result {
97        write!(writer, "@p{}", self.len)
98    }
99}
100
101pub(crate) fn write_parameter(
102    out: &mut Vec<u8>,
103    name: &str,
104    type_info: &MssqlTypeInfo,
105    encoded: &[u8],
106    is_null: bool,
107) -> Result<(), BoxDynError> {
108    write_parameter_with_status(out, name, 0, type_info, encoded, is_null)
109}
110
111pub(crate) fn write_output_i32_parameter(
112    out: &mut Vec<u8>,
113    name: &str,
114    value: i32,
115) -> Result<(), BoxDynError> {
116    write_parameter_with_status(
117        out,
118        name,
119        STATUS_BY_REF_VALUE,
120        &MssqlTypeInfo::INT,
121        &value.to_le_bytes(),
122        false,
123    )
124}
125
126fn write_parameter_with_status(
127    out: &mut Vec<u8>,
128    name: &str,
129    status: u8,
130    type_info: &MssqlTypeInfo,
131    encoded: &[u8],
132    is_null: bool,
133) -> Result<(), BoxDynError> {
134    write_b_varchar(out, name)?;
135    out.push(status);
136    write_type_info(out, type_info, encoded.len(), is_null)?;
137    write_param_len_data(out, type_info, encoded, is_null)?;
138    Ok(())
139}
140
141pub(crate) fn write_nvarchar_parameter(
142    out: &mut Vec<u8>,
143    name: &str,
144    value: &str,
145) -> Result<(), BoxDynError> {
146    let mut encoded = Vec::with_capacity(value.len() * 2);
147    write_utf16(&mut encoded, value);
148    write_parameter(out, name, &MssqlTypeInfo::NVARCHAR, &encoded, false)
149}
150
151pub(crate) fn write_null_nvarchar_parameter(
152    out: &mut Vec<u8>,
153    name: &str,
154) -> Result<(), BoxDynError> {
155    write_parameter(out, name, &MssqlTypeInfo::NVARCHAR, &[], true)
156}
157
158pub(crate) fn type_declaration(type_info: &MssqlTypeInfo) -> Result<&'static str, BoxDynError> {
159    Ok(match type_info.kind() {
160        MssqlType::Bit => "bit",
161        MssqlType::TinyInt => "tinyint",
162        MssqlType::SmallInt => "smallint",
163        MssqlType::Int => "int",
164        MssqlType::BigInt => "bigint",
165        MssqlType::Real => "real",
166        MssqlType::Float => "float",
167        MssqlType::NVarChar => "nvarchar(max)",
168        MssqlType::VarChar => "varchar(max)",
169        MssqlType::VarBinary => "varbinary(max)",
170        MssqlType::Decimal => "decimal(38, 0)",
171        MssqlType::Date => "date",
172        MssqlType::Time => "time(7)",
173        MssqlType::DateTime2 => "datetime2(7)",
174        MssqlType::DateTimeOffset => "datetimeoffset(7)",
175        MssqlType::UniqueIdentifier => "uniqueidentifier",
176        other => return Err(format!("SQL Server arguments do not support type {other:?}").into()),
177    })
178}
179
180fn write_type_info(
181    out: &mut Vec<u8>,
182    type_info: &MssqlTypeInfo,
183    encoded_len: usize,
184    is_null: bool,
185) -> Result<(), BoxDynError> {
186    match type_info.kind() {
187        MssqlType::Bit => {
188            out.push(DATA_TYPE_BITN);
189            out.push(1);
190        }
191        MssqlType::TinyInt => {
192            out.push(DATA_TYPE_INTN);
193            out.push(1);
194        }
195        MssqlType::SmallInt => {
196            out.push(DATA_TYPE_INTN);
197            out.push(2);
198        }
199        MssqlType::Int => {
200            out.push(DATA_TYPE_INTN);
201            out.push(4);
202        }
203        MssqlType::BigInt => {
204            out.push(DATA_TYPE_INTN);
205            out.push(8);
206        }
207        MssqlType::Real => {
208            out.push(DATA_TYPE_FLOATN);
209            out.push(4);
210        }
211        MssqlType::Float => {
212            out.push(DATA_TYPE_FLOATN);
213            out.push(8);
214        }
215        MssqlType::NVarChar => {
216            out.push(DATA_TYPE_NVARCHAR);
217            out.extend_from_slice(
218                &nvarchar_type_size(type_info, encoded_len, is_null)?.to_le_bytes(),
219            );
220            out.extend_from_slice(&DEFAULT_COLLATION);
221        }
222        MssqlType::VarChar => {
223            out.push(DATA_TYPE_BIGVARCHAR);
224            out.extend_from_slice(
225                &bounded_short_len(type_info, encoded_len, is_null)?.to_le_bytes(),
226            );
227            out.extend_from_slice(&DEFAULT_COLLATION);
228        }
229        MssqlType::VarBinary => {
230            out.push(DATA_TYPE_BIGVARBINARY);
231            out.extend_from_slice(
232                &bounded_short_len(type_info, encoded_len, is_null)?.to_le_bytes(),
233            );
234        }
235        MssqlType::Decimal => {
236            out.push(DATA_TYPE_NUMERICN);
237            out.push(u8::try_from(type_info.size().unwrap_or(17))?);
238            out.push(type_info.precision().max(1));
239            out.push(type_info.scale());
240        }
241        MssqlType::Date => {
242            out.push(DATA_TYPE_DATEN);
243        }
244        MssqlType::Time => {
245            out.push(DATA_TYPE_TIMEN);
246            out.push(type_info.scale());
247        }
248        MssqlType::DateTime2 => {
249            out.push(DATA_TYPE_DATETIME2N);
250            out.push(type_info.scale());
251        }
252        MssqlType::DateTimeOffset => {
253            out.push(DATA_TYPE_DATETIMEOFFSETN);
254            out.push(type_info.scale());
255        }
256        MssqlType::UniqueIdentifier => {
257            out.push(DATA_TYPE_GUID);
258            out.push(16);
259        }
260        other => return Err(format!("SQL Server arguments do not support type {other:?}").into()),
261    }
262
263    Ok(())
264}
265
266fn write_param_len_data(
267    out: &mut Vec<u8>,
268    type_info: &MssqlTypeInfo,
269    encoded: &[u8],
270    is_null: bool,
271) -> Result<(), BoxDynError> {
272    match type_info.kind() {
273        MssqlType::Bit
274        | MssqlType::TinyInt
275        | MssqlType::SmallInt
276        | MssqlType::Int
277        | MssqlType::BigInt
278        | MssqlType::Real
279        | MssqlType::Float
280        | MssqlType::Decimal
281        | MssqlType::Date
282        | MssqlType::Time
283        | MssqlType::DateTime2
284        | MssqlType::DateTimeOffset
285        | MssqlType::UniqueIdentifier => {
286            out.push(if is_null {
287                0
288            } else {
289                u8::try_from(encoded.len())?
290            });
291        }
292        MssqlType::NVarChar | MssqlType::VarChar | MssqlType::VarBinary => {
293            if type_info.size() == Some(u16::MAX) {
294                write_plp_value(out, encoded, is_null)?;
295            } else {
296                let len = if is_null {
297                    u16::MAX
298                } else {
299                    u16::try_from(encoded.len())?
300                };
301                out.extend_from_slice(&len.to_le_bytes());
302            }
303        }
304        other => return Err(format!("SQL Server arguments do not support type {other:?}").into()),
305    }
306
307    if !is_null && type_info.size() != Some(u16::MAX) {
308        out.extend_from_slice(encoded);
309    }
310
311    Ok(())
312}
313
314fn declaration(
315    type_info: &MssqlTypeInfo,
316    encoded_len: usize,
317    is_null: bool,
318) -> Result<String, BoxDynError> {
319    Ok(match type_info.kind() {
320        MssqlType::Bit => "bit".to_owned(),
321        MssqlType::TinyInt => "tinyint".to_owned(),
322        MssqlType::SmallInt => "smallint".to_owned(),
323        MssqlType::Int => "int".to_owned(),
324        MssqlType::BigInt => "bigint".to_owned(),
325        MssqlType::Real => "real".to_owned(),
326        MssqlType::Float => "float".to_owned(),
327        MssqlType::NVarChar => nvarchar_declaration(type_info, encoded_len, is_null)?,
328        MssqlType::VarChar => varchar_declaration(type_info, encoded_len, is_null)?,
329        MssqlType::VarBinary => varbinary_declaration(type_info, encoded_len, is_null)?,
330        MssqlType::Decimal => format!(
331            "decimal({},{})",
332            type_info.precision().max(1),
333            type_info.scale()
334        ),
335        MssqlType::Date => "date".to_owned(),
336        MssqlType::Time => format!("time({})", type_info.scale()),
337        MssqlType::DateTime2 => format!("datetime2({})", type_info.scale()),
338        MssqlType::DateTimeOffset => format!("datetimeoffset({})", type_info.scale()),
339        MssqlType::UniqueIdentifier => "uniqueidentifier".to_owned(),
340        other => return Err(format!("SQL Server arguments do not support type {other:?}").into()),
341    })
342}
343
344fn nvarchar_declaration(
345    type_info: &MssqlTypeInfo,
346    encoded_len: usize,
347    is_null: bool,
348) -> Result<String, BoxDynError> {
349    let size = nvarchar_type_size(type_info, encoded_len, is_null)?;
350    if size == u16::MAX {
351        Ok("nvarchar(max)".to_owned())
352    } else {
353        Ok(format!("nvarchar({})", size / 2))
354    }
355}
356
357fn varchar_declaration(
358    type_info: &MssqlTypeInfo,
359    encoded_len: usize,
360    is_null: bool,
361) -> Result<String, BoxDynError> {
362    let size = bounded_short_len(type_info, encoded_len, is_null)?;
363    if size == u16::MAX {
364        Ok("varchar(max)".to_owned())
365    } else {
366        Ok(format!("varchar({size})"))
367    }
368}
369
370fn varbinary_declaration(
371    type_info: &MssqlTypeInfo,
372    encoded_len: usize,
373    is_null: bool,
374) -> Result<String, BoxDynError> {
375    let size = bounded_short_len(type_info, encoded_len, is_null)?;
376    if size == u16::MAX {
377        Ok("varbinary(max)".to_owned())
378    } else {
379        Ok(format!("varbinary({size})"))
380    }
381}
382
383fn nvarchar_type_size(
384    type_info: &MssqlTypeInfo,
385    encoded_len: usize,
386    is_null: bool,
387) -> Result<u16, BoxDynError> {
388    if let Some(size) = type_info.size() {
389        return Ok(size);
390    }
391
392    let len = if is_null {
393        2
394    } else {
395        std::cmp::max(2, encoded_len)
396    };
397    Ok(u16::try_from(len)?)
398}
399
400fn bounded_short_len(
401    type_info: &MssqlTypeInfo,
402    encoded_len: usize,
403    is_null: bool,
404) -> Result<u16, BoxDynError> {
405    if let Some(size) = type_info.size() {
406        return Ok(size);
407    }
408
409    let len = if is_null {
410        1
411    } else {
412        std::cmp::max(1, encoded_len)
413    };
414    Ok(u16::try_from(len)?)
415}
416
417fn write_plp_value(out: &mut Vec<u8>, encoded: &[u8], is_null: bool) -> Result<(), BoxDynError> {
418    if is_null {
419        out.extend_from_slice(&PLP_NULL.to_le_bytes());
420        return Ok(());
421    }
422
423    out.extend_from_slice(&u64::try_from(encoded.len())?.to_le_bytes());
424
425    for chunk in encoded.chunks(PLP_CHUNK_SIZE) {
426        out.extend_from_slice(&u32::try_from(chunk.len())?.to_le_bytes());
427        out.extend_from_slice(chunk);
428    }
429
430    out.extend_from_slice(&0_u32.to_le_bytes());
431    Ok(())
432}
433
434fn write_b_varchar(out: &mut Vec<u8>, value: &str) -> Result<(), BoxDynError> {
435    let char_len = value.encode_utf16().count();
436    out.push(u8::try_from(char_len)?);
437    write_utf16(out, value);
438    Ok(())
439}
440
441fn write_utf16(out: &mut Vec<u8>, value: &str) {
442    for unit in value.encode_utf16() {
443        out.extend_from_slice(&unit.to_le_bytes());
444    }
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450
451    #[test]
452    fn null_strings_use_nvarchar_max_in_declarations_and_rpc_values() {
453        let mut args = MssqlArguments::default();
454        args.add(None::<String>).unwrap();
455
456        assert_eq!("@p1 nvarchar(max)", args.declarations());
457        assert!(args
458            .data
459            .windows(3)
460            .any(|bytes| bytes == [DATA_TYPE_NVARCHAR, 0xff, 0xff]));
461        assert!(args.data.ends_with(&PLP_NULL.to_le_bytes()));
462    }
463
464    #[test]
465    fn failed_parameter_encoding_leaves_existing_arguments_intact() {
466        let mut args = MssqlArguments::default();
467        args.add(7_i32).unwrap();
468        let mut expected = args.clone();
469
470        assert!(args
471            .add_parameter(MssqlTypeInfo::INT, vec![0; 256], false)
472            .is_err());
473
474        args.add(8_i32).unwrap();
475        expected.add(8_i32).unwrap();
476
477        assert_eq!(args.len(), expected.len());
478        assert_eq!(args.declarations(), expected.declarations());
479        assert_eq!(args.data(), expected.data());
480    }
481
482    #[test]
483    fn formats_sql_server_style_placeholders() {
484        let args = MssqlArguments {
485            len: 3,
486            data: Vec::new(),
487            declarations: String::new(),
488        };
489        let mut out = String::new();
490
491        args.format_placeholder(&mut out).unwrap();
492
493        assert_eq!("@p3", out);
494    }
495
496    #[test]
497    fn records_declarations_and_rpc_argument_data() {
498        let mut args = MssqlArguments::default();
499
500        args.add(7_i32).unwrap();
501        args.add("hi").unwrap();
502
503        assert_eq!("@p1 int,@p2 nvarchar(2)", args.declarations());
504        assert!(args
505            .data()
506            .windows(2)
507            .any(|bytes| bytes == [DATA_TYPE_INTN, 4]));
508        assert!(args
509            .data()
510            .windows(8)
511            .any(|bytes| bytes == [DATA_TYPE_NVARCHAR, 4, 0, 0x81, 0x04, 0xd0, 0x00, 0x34]));
512    }
513
514    #[test]
515    fn declares_lossless_integer_parameter_types() {
516        let mut args = MssqlArguments::default();
517
518        args.add(-5_i8).unwrap();
519        args.add(255_u8).unwrap();
520        args.add(65_535_u16).unwrap();
521        args.add(u32::MAX).unwrap();
522
523        assert_eq!(
524            "@p1 smallint,@p2 tinyint,@p3 int,@p4 bigint",
525            args.declarations()
526        );
527        assert!(args
528            .data()
529            .windows(2)
530            .any(|bytes| bytes == [DATA_TYPE_INTN, 1]));
531        assert!(args
532            .data()
533            .windows(2)
534            .any(|bytes| bytes == [DATA_TYPE_INTN, 8]));
535    }
536
537    #[test]
538    fn declares_large_text_and_binary_parameters_as_max() {
539        let mut args = MssqlArguments::default();
540        let text = "x".repeat(4001);
541        let bytes = vec![0x5a; 8001];
542
543        args.add(text.as_str()).unwrap();
544        args.add(bytes.as_slice()).unwrap();
545
546        assert_eq!("@p1 nvarchar(max),@p2 varbinary(max)", args.declarations());
547        assert!(args
548            .data()
549            .windows(3)
550            .any(|bytes| bytes == [DATA_TYPE_NVARCHAR, 0xff, 0xff]));
551        assert!(args
552            .data()
553            .windows(3)
554            .any(|bytes| bytes == [DATA_TYPE_BIGVARBINARY, 0xff, 0xff]));
555        assert!(args
556            .data()
557            .windows(8)
558            .any(|bytes| bytes == 8002_u64.to_le_bytes()));
559        assert!(args
560            .data()
561            .windows(8)
562            .any(|bytes| bytes == 8001_u64.to_le_bytes()));
563    }
564}