Skip to main content

vlorql_core/compile/
dialect_config.rs

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