Skip to main content

vlorql_core/compile/
rewrite.rs

1//! SQL rewrite engine for post-compilation transformations.
2
3use crate::errors::{ConfigErrorKind, VlorQLError};
4use regex::Regex;
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use serde_json::json;
8use std::path::Path;
9
10/// One rewrite rule: match with regex, replace with template.
11#[allow(missing_docs)]
12#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
13pub struct RewriteRule {
14    pub name: String,
15    pub description: Option<String>,
16    pub match_pattern: String,
17    pub replace_template: String,
18    pub dialect_filter: Option<Vec<String>>,
19}
20
21/// Applies a set of rewrite rules to generated SQL.
22#[allow(missing_docs)]
23#[derive(Debug, Default)]
24pub struct RewriteEngine {
25    rules: Vec<RewriteRule>,
26}
27
28impl RewriteEngine {
29    pub fn new(rules: Vec<RewriteRule>) -> Self {
30        Self { rules }
31    }
32
33    pub fn apply(&self, sql: &str, dialect: &str) -> Result<String, VlorQLError> {
34        let mut result = sql.to_string();
35        for rule in &self.rules {
36            if let Some(filter) = &rule.dialect_filter {
37                if !filter.iter().any(|d| d.eq_ignore_ascii_case(dialect)) {
38                    continue;
39                }
40            }
41            let re = Regex::new(&rule.match_pattern).map_err(|e| {
42                VlorQLError::config(
43                    ConfigErrorKind::ConfigFileError {
44                        path: format!("rule:{}", rule.name),
45                        reason: format!("invalid regex: {e}"),
46                    },
47                    json!({"rule": rule.name, "pattern": &rule.match_pattern}),
48                )
49            })?;
50            result = re
51                .replace_all(&result, rule.replace_template.as_str())
52                .to_string();
53        }
54        Ok(result)
55    }
56
57    pub fn load_toml(path: impl AsRef<Path>) -> Result<Self, VlorQLError> {
58        let path = path.as_ref();
59        let content = std::fs::read_to_string(path).map_err(|e| {
60            VlorQLError::config(
61                ConfigErrorKind::ConfigFileError {
62                    path: path.display().to_string(),
63                    reason: e.to_string(),
64                },
65                json!({"path": path.display().to_string()}),
66            )
67        })?;
68        #[derive(Deserialize)]
69        struct RulesFile {
70            rules: Vec<RewriteRule>,
71        }
72        let parsed: RulesFile = toml::from_str(&content).map_err(|e| {
73            VlorQLError::config(
74                ConfigErrorKind::ConfigFileError {
75                    path: path.display().to_string(),
76                    reason: e.to_string(),
77                },
78                json!({"path": path.display().to_string(), "parse_error": e.to_string()}),
79            )
80        })?;
81        Ok(Self::new(parsed.rules))
82    }
83
84    pub fn load_yaml(path: impl AsRef<Path>) -> Result<Self, VlorQLError> {
85        let path = path.as_ref();
86        let content = std::fs::read_to_string(path).map_err(|e| {
87            VlorQLError::config(
88                ConfigErrorKind::ConfigFileError {
89                    path: path.display().to_string(),
90                    reason: e.to_string(),
91                },
92                json!({"path": path.display().to_string()}),
93            )
94        })?;
95        #[derive(Deserialize)]
96        struct RulesFile {
97            rules: Vec<RewriteRule>,
98        }
99        let parsed: RulesFile = serde_yaml::from_str(&content).map_err(|e| {
100            VlorQLError::config(
101                ConfigErrorKind::ConfigFileError {
102                    path: path.display().to_string(),
103                    reason: e.to_string(),
104                },
105                json!({"path": path.display().to_string(), "parse_error": e.to_string()}),
106            )
107        })?;
108        Ok(Self::new(parsed.rules))
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn rewrite_ilike_to_lower() {
118        let engine = RewriteEngine::new(vec![RewriteRule {
119            name: "ilike_to_lower".into(),
120            description: None,
121            match_pattern: r"(?P<left>\S+)\s+ILIKE\s+(?P<right>\S+)".into(),
122            replace_template: "LOWER(${left}) LIKE LOWER(${right})".into(),
123            dialect_filter: Some(vec!["mysql".into()]),
124        }]);
125        let sql = engine
126            .apply("WHERE name ILIKE '%foo%'", "mysql")
127            .unwrap();
128        assert_eq!(sql, "WHERE LOWER(name) LIKE LOWER('%foo%')");
129    }
130
131    #[test]
132    fn rewrite_skipped_for_wrong_dialect() {
133        let engine = RewriteEngine::new(vec![RewriteRule {
134            name: "ilike_to_lower".into(),
135            description: None,
136            match_pattern: "ILIKE".into(),
137            replace_template: "LIKE".into(),
138            dialect_filter: Some(vec!["mysql".into()]),
139        }]);
140        let sql = engine
141            .apply("WHERE name ILIKE '%foo%'", "postgres")
142            .unwrap();
143        assert_eq!(sql, "WHERE name ILIKE '%foo%'");
144    }
145
146    #[test]
147    fn rewrite_multiple_rules() {
148        let engine = RewriteEngine::new(vec![
149            RewriteRule {
150                name: "ilike".into(),
151                description: None,
152                match_pattern: "ILIKE".into(),
153                replace_template: "LIKE".into(),
154                dialect_filter: None,
155            },
156            RewriteRule {
157                name: "now".into(),
158                description: None,
159                match_pattern: r"\bNOW\(\)".into(),
160                replace_template: "GETDATE()".into(),
161                dialect_filter: None,
162            },
163        ]);
164        let sql = engine
165            .apply("WHERE name ILIKE '%foo%' AND date = NOW()", "mssql")
166            .unwrap();
167        assert_eq!(sql, "WHERE name LIKE '%foo%' AND date = GETDATE()");
168    }
169
170    #[test]
171    fn rewrite_no_rules_passthrough() {
172        let engine = RewriteEngine::new(vec![]);
173        let sql = engine.apply("SELECT 1", "postgres").unwrap();
174        assert_eq!(sql, "SELECT 1");
175    }
176
177    #[test]
178    fn rewrite_invalid_regex_returns_error() {
179        let engine = RewriteEngine::new(vec![RewriteRule {
180            name: "bad".into(),
181            description: None,
182            match_pattern: r"[invalid".into(),
183            replace_template: "x".into(),
184            dialect_filter: None,
185        }]);
186        assert!(engine.apply("test", "postgres").is_err());
187    }
188}