Skip to main content

datasources_sqlserver/
sql_generate.rs

1use datasources::{
2    DecimalRule, DefaultValueConverter, DefaultValueOptions, DeterministicTypeConverter, SpecFieldRules,
3};
4use regex::Regex;
5use std::collections::HashMap;
6use std::sync::LazyLock;
7
8pub const QUOTE_LEFT: &str = "[";
9pub const QUOTE_RIGHT: &str = "]";
10
11fn string_sized(n: i32) -> String {
12    format!("NVARCHAR({n})")
13}
14
15fn binary_sized(n: i32) -> String {
16    format!("VARBINARY({n})")
17}
18
19pub static TYPES: LazyLock<DeterministicTypeConverter> = LazyLock::new(|| {
20    DeterministicTypeConverter::new(
21        HashMap::from([
22            ("string".into(), "NVARCHAR(MAX)".into()),
23            ("character".into(), "NCHAR(1)".into()),
24            ("number".into(), "INT".into()),
25            ("integer".into(), "INT".into()),
26            ("unsignedinteger".into(), "BIGINT".into()),
27            ("smallinteger".into(), "SMALLINT".into()),
28            ("unsignedsmallinteger".into(), "INT".into()),
29            ("biginteger".into(), "BIGINT".into()),
30            ("unsignedbiginteger".into(), "DECIMAL(20)".into()),
31            ("float".into(), "FLOAT".into()),
32            ("decimal".into(), "DECIMAL".into()),
33            ("boolean".into(), "BIT".into()),
34            ("datetime".into(), "DATETIME2".into()),
35            ("binary".into(), "VARBINARY(MAX)".into()),
36            ("uuid".into(), "UNIQUEIDENTIFIER".into()),
37            ("reference".into(), "INT".into()),
38        ]),
39        SpecFieldRules {
40            dialect_name: Some("sqlserver".into()),
41            string_unlimited: "NVARCHAR(MAX)".into(),
42            string_sized,
43            character: Some("NCHAR".into()),
44            decimal: Some(DecimalRule::Required {
45                type_name: "DECIMAL".into(),
46            }),
47            binary_unlimited: Some("VARBINARY(MAX)".into()),
48            binary_sized: Some(binary_sized),
49        },
50    )
51});
52
53pub static DEFAULTS: LazyLock<DefaultValueConverter> = LazyLock::new(|| {
54    DefaultValueConverter::new(DefaultValueOptions {
55        new_id: || "NEWID()".into(),
56        now: || "GETDATE()".into(),
57        utc_now: || "GETUTCDATE()".into(),
58        boolean_on: "1".into(),
59        boolean_off: "0".into(),
60        hex: |arg| format!("0x{arg}"),
61        hex_reverse: Regex::new(r"^0x(.*)$").expect("hex"),
62    })
63});