Skip to main content

vlorql_core/compile/
dialect_config.rs

1//! Config-driven SQL dialect definitions.
2
3use crate::errors::{ConfigErrorKind, VlorQLError};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use serde_json::json;
7use std::collections::HashMap;
8use std::path::Path;
9
10/// A configurable SQL dialect definition loaded from TOML/YAML.
11#[allow(missing_docs)]
12#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
13#[serde(default)]
14pub struct DialectConfig {
15    pub name: String,
16    pub identifier_quote: String,
17    pub placeholder: String,
18    pub limit_offset: String,
19    pub top_syntax: Option<String>,
20    pub supports_cte: bool,
21    pub supports_window_functions: bool,
22    pub supports_json_operations: bool,
23    pub supports_offset: bool,
24    pub supports_fetch: bool,
25    pub allow_distinct: bool,
26    pub allow_select_distinct: bool,
27    pub max_joins: Option<usize>,
28    pub allowed_join_types: Vec<String>,
29    pub allowed_functions: Vec<String>,
30    pub denied_functions: Vec<String>,
31    pub max_group_by_columns: Option<usize>,
32    pub type_mappings: HashMap<String, String>,
33    pub function_name_mappings: HashMap<String, String>,
34}
35
36impl Default for DialectConfig {
37    fn default() -> Self {
38        Self::default_postgres()
39    }
40}
41
42impl DialectConfig {
43    pub fn placeholder_str(&self, index: usize) -> String {
44        if self.placeholder.contains("{index}") {
45            self.placeholder.replace("{index}", &index.to_string())
46        } else {
47            self.placeholder.clone()
48        }
49    }
50
51    pub fn quote_identifier(&self, ident: &str) -> String {
52        match self.identifier_quote.as_str() {
53            "double_quote" => format!("\"{}\"", ident.replace('"', "\"\"")),
54            "backtick" => format!("`{}`", ident.replace('`', "``")),
55            "bracket" => format!("[{}]", ident),
56            "never" => ident.to_string(),
57            _ => format!("\"{}\"", ident.replace('"', "\"\"")),
58        }
59    }
60
61    pub fn render_limit_offset(&self, limit: Option<u64>, offset: Option<u64>) -> Option<String> {
62        if limit.is_none() && offset.is_none() {
63            return None;
64        }
65        let template = &self.limit_offset;
66        let result = template
67            .replace("{limit}", &limit.map(|v| v.to_string()).unwrap_or_default())
68            .replace("{offset}", &offset.map(|v| v.to_string()).unwrap_or_default());
69        if result.trim().is_empty() {
70            return None;
71        }
72        Some(result)
73    }
74
75    pub fn render_top(&self, limit: u64) -> Option<String> {
76        self.top_syntax
77            .as_ref()
78            .map(|s| s.replace("{limit}", &limit.to_string()))
79    }
80
81    pub fn default_postgres() -> Self {
82        Self {
83            name: "postgres".into(),
84            identifier_quote: "double_quote".into(),
85            placeholder: "${index}".into(),
86            limit_offset: "LIMIT {limit} OFFSET {offset}".into(),
87            top_syntax: None,
88            supports_cte: true,
89            supports_window_functions: true,
90            supports_json_operations: true,
91            supports_offset: true,
92            supports_fetch: true,
93            allow_distinct: true,
94            allow_select_distinct: true,
95            max_joins: None,
96            allowed_join_types: vec![],
97            allowed_functions: vec![],
98            denied_functions: vec![],
99            max_group_by_columns: None,
100            type_mappings: HashMap::new(),
101            function_name_mappings: HashMap::new(),
102        }
103    }
104
105    pub fn default_sqlite() -> Self {
106        let mut cfg = Self::default_postgres();
107        cfg.name = "sqlite".into();
108        cfg.placeholder = "?".into();
109        cfg.limit_offset = "LIMIT {limit} OFFSET {offset}".into();
110        cfg
111    }
112
113    pub fn default_mysql() -> Self {
114        let mut type_mappings = HashMap::new();
115        type_mappings.insert("ilike".into(), "LIKE".into());
116        Self {
117            name: "mysql".into(),
118            identifier_quote: "backtick".into(),
119            placeholder: "?".into(),
120            limit_offset: "LIMIT {offset}, {limit}".into(),
121            top_syntax: None,
122            supports_cte: true,
123            supports_window_functions: true,
124            supports_json_operations: false,
125            supports_offset: true,
126            supports_fetch: false,
127            allow_distinct: true,
128            allow_select_distinct: true,
129            max_joins: None,
130            allowed_join_types: vec![],
131            allowed_functions: vec![],
132            denied_functions: vec![],
133            max_group_by_columns: None,
134            type_mappings,
135            function_name_mappings: HashMap::new(),
136        }
137    }
138
139    pub fn from_toml(path: impl AsRef<Path>) -> Result<Self, VlorQLError> {
140        let path = path.as_ref();
141        let content = std::fs::read_to_string(path).map_err(|e| {
142            VlorQLError::config(
143                ConfigErrorKind::ConfigFileError {
144                    path: path.display().to_string(),
145                    reason: e.to_string(),
146                },
147                json!({"path": path.display().to_string()}),
148            )
149        })?;
150        toml::from_str(&content).map_err(|e| {
151            VlorQLError::config(
152                ConfigErrorKind::ConfigFileError {
153                    path: path.display().to_string(),
154                    reason: e.to_string(),
155                },
156                json!({"path": path.display().to_string(), "parse_error": e.to_string()}),
157            )
158        })
159    }
160
161    pub fn from_yaml(path: impl AsRef<Path>) -> Result<Self, VlorQLError> {
162        let path = path.as_ref();
163        let content = std::fs::read_to_string(path).map_err(|e| {
164            VlorQLError::config(
165                ConfigErrorKind::ConfigFileError {
166                    path: path.display().to_string(),
167                    reason: e.to_string(),
168                },
169                json!({"path": path.display().to_string()}),
170            )
171        })?;
172        serde_yaml::from_str(&content).map_err(|e| {
173            VlorQLError::config(
174                ConfigErrorKind::ConfigFileError {
175                    path: path.display().to_string(),
176                    reason: e.to_string(),
177                },
178                json!({"path": path.display().to_string(), "parse_error": e.to_string()}),
179            )
180        })
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    #[test]
189    fn placeholder_postgres_style() {
190        let cfg = DialectConfig::default_postgres();
191        assert_eq!(cfg.placeholder_str(1), "$1");
192        assert_eq!(cfg.placeholder_str(3), "$3");
193    }
194
195    #[test]
196    fn placeholder_mysql_style() {
197        let cfg = DialectConfig::default_mysql();
198        assert_eq!(cfg.placeholder_str(1), "?");
199        assert_eq!(cfg.placeholder_str(5), "?");
200    }
201
202    #[test]
203    fn placeholder_custom_style() {
204        let cfg = DialectConfig {
205            placeholder: "@p{index}".into(),
206            ..DialectConfig::default_postgres()
207        };
208        assert_eq!(cfg.placeholder_str(1), "@p1");
209        assert_eq!(cfg.placeholder_str(42), "@p42");
210    }
211
212    #[test]
213    fn quote_identifier_double_quote() {
214        let cfg = DialectConfig::default_postgres();
215        assert_eq!(cfg.quote_identifier("users"), r#""users""#);
216        assert_eq!(cfg.quote_identifier(r#"he"llo"#), r#""he""llo""#);
217    }
218
219    #[test]
220    fn quote_identifier_backtick() {
221        let cfg = DialectConfig::default_mysql();
222        assert_eq!(cfg.quote_identifier("users"), "`users`");
223        assert_eq!(cfg.quote_identifier("order"), "`order`");
224    }
225
226    #[test]
227    fn quote_identifier_bracket() {
228        let cfg = DialectConfig {
229            identifier_quote: "bracket".into(),
230            ..DialectConfig::default_postgres()
231        };
232        assert_eq!(cfg.quote_identifier("users"), "[users]");
233    }
234
235    #[test]
236    fn quote_identifier_never() {
237        let cfg = DialectConfig {
238            identifier_quote: "never".into(),
239            ..DialectConfig::default_postgres()
240        };
241        assert_eq!(cfg.quote_identifier("users"), "users");
242    }
243
244    #[test]
245    fn render_limit_offset_both() {
246        let cfg = DialectConfig::default_postgres();
247        let result = cfg.render_limit_offset(Some(10), Some(20));
248        assert_eq!(result.as_deref(), Some("LIMIT 10 OFFSET 20"));
249    }
250
251    #[test]
252    fn render_limit_offset_limit_only() {
253        let cfg = DialectConfig::default_postgres();
254        let result = cfg.render_limit_offset(Some(10), None);
255        assert_eq!(result.as_deref(), Some("LIMIT 10 OFFSET "));
256    }
257
258    #[test]
259    fn render_limit_offset_mysql() {
260        let cfg = DialectConfig::default_mysql();
261        let result = cfg.render_limit_offset(Some(10), Some(20));
262        assert_eq!(result.as_deref(), Some("LIMIT 20, 10"));
263    }
264
265    #[test]
266    fn render_limit_offset_fetch() {
267        let cfg = DialectConfig {
268            limit_offset: "OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY".into(),
269            ..DialectConfig::default_postgres()
270        };
271        let result = cfg.render_limit_offset(Some(10), Some(0));
272        assert_eq!(
273            result.as_deref(),
274            Some("OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY")
275        );
276    }
277
278    #[test]
279    fn render_top_syntax() {
280        let cfg = DialectConfig {
281            top_syntax: Some("SELECT TOP {limit}".into()),
282            ..DialectConfig::default_postgres()
283        };
284        assert_eq!(cfg.render_top(5).as_deref(), Some("SELECT TOP 5"));
285    }
286
287    #[test]
288    fn default_postgres_values() {
289        let cfg = DialectConfig::default_postgres();
290        assert_eq!(cfg.name, "postgres");
291        assert!(cfg.supports_cte);
292        assert!(cfg.supports_window_functions);
293        assert!(cfg.allow_distinct);
294    }
295
296    #[test]
297    fn default_mysql_values() {
298        let cfg = DialectConfig::default_mysql();
299        assert_eq!(cfg.name, "mysql");
300        assert_eq!(cfg.identifier_quote, "backtick");
301        assert_eq!(cfg.placeholder, "?");
302        assert!(!cfg.supports_json_operations);
303    }
304
305    #[test]
306    fn default_sqlite_values() {
307        let cfg = DialectConfig::default_sqlite();
308        assert_eq!(cfg.name, "sqlite");
309        assert_eq!(cfg.placeholder, "?");
310    }
311
312    #[test]
313    fn from_toml_loads_config() {
314        let toml_str = r#"
315name = "testdb"
316identifier_quote = "double_quote"
317placeholder = "${index}"
318limit_offset = "LIMIT {limit} OFFSET {offset}"
319supports_cte = true
320supports_window_functions = false
321supports_json_operations = false
322supports_offset = true
323supports_fetch = false
324allow_distinct = true
325allow_select_distinct = true
326allowed_join_types = ["inner", "left"]
327
328[type_mappings]
329ilike = "LIKE"
330
331[function_name_mappings]
332"now" = "GETDATE"
333"#;
334        let cfg: DialectConfig = toml::from_str(toml_str).expect("should parse");
335        assert_eq!(cfg.name, "testdb");
336        assert!(!cfg.supports_window_functions);
337        assert_eq!(cfg.allowed_join_types, vec!["inner", "left"]);
338        assert_eq!(cfg.type_mappings.get("ilike").unwrap(), "LIKE");
339        assert_eq!(cfg.function_name_mappings.get("now").unwrap(), "GETDATE");
340    }
341}