Skip to main content

sql_splitter/redactor/
matcher.rs

1//! Column pattern matching for redaction rules.
2
3use crate::redactor::config::{RedactConfig, Rule};
4use crate::redactor::StrategyKind;
5use crate::schema::TableSchema;
6use glob::Pattern;
7
8/// Compiled column matcher for efficient pattern matching
9#[derive(Debug)]
10pub struct ColumnMatcher {
11    /// Compiled rules with glob patterns
12    rules: Vec<CompiledRule>,
13    /// Default strategy for unmatched columns
14    default_strategy: StrategyKind,
15}
16
17/// A rule with pre-compiled glob patterns
18#[derive(Debug)]
19struct CompiledRule {
20    /// Table pattern (None = match all tables)
21    table_pattern: Option<Pattern>,
22    /// Column pattern
23    column_pattern: Pattern,
24    /// The strategy to apply
25    strategy: StrategyKind,
26}
27
28impl ColumnMatcher {
29    /// Create a new matcher from configuration
30    pub fn from_config(config: &RedactConfig) -> anyhow::Result<Self> {
31        let mut rules = Vec::with_capacity(config.rules.len());
32
33        for rule in &config.rules {
34            let compiled = Self::compile_rule(rule)?;
35            rules.push(compiled);
36        }
37
38        Ok(Self {
39            rules,
40            default_strategy: config.default_strategy.clone(),
41        })
42    }
43
44    /// Compile a rule into table and column patterns
45    fn compile_rule(rule: &Rule) -> anyhow::Result<CompiledRule> {
46        let pattern = &rule.column;
47
48        // Check if pattern contains a table qualifier (table.column)
49        let (table_pattern, column_pattern) = if let Some(dot_pos) = pattern.find('.') {
50            let table_part = &pattern[..dot_pos];
51            let column_part = &pattern[dot_pos + 1..];
52
53            // Compile table pattern (might be * for all tables)
54            let table_pat = if table_part == "*" {
55                None
56            } else {
57                Some(Pattern::new(table_part).map_err(|e| {
58                    anyhow::anyhow!("Invalid table pattern '{}': {}", table_part, e)
59                })?)
60            };
61
62            let col_pat = Pattern::new(column_part)
63                .map_err(|e| anyhow::anyhow!("Invalid column pattern '{}': {}", column_part, e))?;
64
65            (table_pat, col_pat)
66        } else {
67            // No table qualifier - match all tables
68            let col_pat = Pattern::new(pattern)
69                .map_err(|e| anyhow::anyhow!("Invalid column pattern '{}': {}", pattern, e))?;
70            (None, col_pat)
71        };
72
73        Ok(CompiledRule {
74            table_pattern,
75            column_pattern,
76            strategy: rule.strategy.clone(),
77        })
78    }
79
80    /// Get the strategy for a specific column
81    pub fn get_strategy(&self, table_name: &str, column_name: &str) -> StrategyKind {
82        // Find first matching rule (rules are processed in order)
83        for rule in &self.rules {
84            if self.rule_matches(rule, table_name, column_name) {
85                return rule.strategy.clone();
86            }
87        }
88
89        // No match - return default
90        self.default_strategy.clone()
91    }
92
93    /// Get strategies for all columns in a table
94    pub fn get_strategies(&self, table_name: &str, table: &TableSchema) -> Vec<StrategyKind> {
95        table
96            .columns
97            .iter()
98            .map(|col| self.get_strategy(table_name, &col.name))
99            .collect()
100    }
101
102    /// Count how many columns match any redaction rule
103    pub fn count_matches(&self, table_name: &str, table: &TableSchema) -> usize {
104        table
105            .columns
106            .iter()
107            .filter(|col| {
108                let strategy = self.get_strategy(table_name, &col.name);
109                !matches!(strategy, StrategyKind::Skip)
110            })
111            .count()
112    }
113
114    /// Check if a rule matches a table/column pair
115    fn rule_matches(&self, rule: &CompiledRule, table_name: &str, column_name: &str) -> bool {
116        // Check table pattern (if specified)
117        if let Some(ref table_pat) = rule.table_pattern {
118            if !table_pat.matches(table_name) && !table_pat.matches(&table_name.to_lowercase()) {
119                return false;
120            }
121        }
122
123        // Check column pattern
124        rule.column_pattern.matches(column_name)
125            || rule.column_pattern.matches(&column_name.to_lowercase())
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    fn create_test_schema() -> TableSchema {
134        use crate::schema::{Column, ColumnId, ColumnType, TableId};
135
136        TableSchema {
137            name: "users".to_string(),
138            id: TableId(0),
139            columns: vec![
140                Column {
141                    name: "id".to_string(),
142                    col_type: ColumnType::Int,
143                    source_type: "INT".to_string(),
144                    ordinal: ColumnId(0),
145                    is_primary_key: true,
146                    is_nullable: false,
147                    is_unique: false,
148                    default_sql: None,
149                    is_generated: false,
150                    is_identity: false,
151                    collation: None,
152                },
153                Column {
154                    name: "email".to_string(),
155                    col_type: ColumnType::Text,
156                    source_type: "VARCHAR(255)".to_string(),
157                    ordinal: ColumnId(1),
158                    is_primary_key: false,
159                    is_nullable: false,
160                    is_unique: false,
161                    default_sql: None,
162                    is_generated: false,
163                    is_identity: false,
164                    collation: None,
165                },
166                Column {
167                    name: "name".to_string(),
168                    col_type: ColumnType::Text,
169                    source_type: "VARCHAR(255)".to_string(),
170                    ordinal: ColumnId(2),
171                    is_primary_key: false,
172                    is_nullable: true,
173                    is_unique: false,
174                    default_sql: None,
175                    is_generated: false,
176                    is_identity: false,
177                    collation: None,
178                },
179                Column {
180                    name: "ssn".to_string(),
181                    col_type: ColumnType::Text,
182                    source_type: "VARCHAR(255)".to_string(),
183                    ordinal: ColumnId(3),
184                    is_primary_key: false,
185                    is_nullable: true,
186                    is_unique: false,
187                    default_sql: None,
188                    is_generated: false,
189                    is_identity: false,
190                    collation: None,
191                },
192            ],
193            primary_key: vec![ColumnId(0)],
194            foreign_keys: vec![],
195            unique_constraints: vec![],
196            check_constraints: vec![],
197            indexes: vec![],
198            create_statement: None,
199        }
200    }
201
202    #[test]
203    fn test_wildcard_column_match() {
204        let config = RedactConfig {
205            input: std::path::PathBuf::new(),
206            output: None,
207            dialect: crate::parser::SqlDialect::MySql,
208            rules: vec![Rule {
209                column: "*.email".to_string(),
210                strategy: StrategyKind::Hash {
211                    preserve_domain: true,
212                },
213            }],
214            default_strategy: StrategyKind::Skip,
215            seed: None,
216            locale: "en".to_string(),
217            tables_filter: None,
218            exclude: vec![],
219            strict: false,
220            progress: false,
221            dry_run: false,
222        };
223
224        let matcher = ColumnMatcher::from_config(&config).unwrap();
225        let schema = create_test_schema();
226
227        let strategies = matcher.get_strategies("users", &schema);
228
229        // id: skip, email: hash, name: skip, ssn: skip
230        assert!(matches!(strategies[0], StrategyKind::Skip));
231        assert!(matches!(strategies[1], StrategyKind::Hash { .. }));
232        assert!(matches!(strategies[2], StrategyKind::Skip));
233        assert!(matches!(strategies[3], StrategyKind::Skip));
234    }
235
236    #[test]
237    fn test_exact_column_match() {
238        let config = RedactConfig {
239            input: std::path::PathBuf::new(),
240            output: None,
241            dialect: crate::parser::SqlDialect::MySql,
242            rules: vec![Rule {
243                column: "users.ssn".to_string(),
244                strategy: StrategyKind::Null,
245            }],
246            default_strategy: StrategyKind::Skip,
247            seed: None,
248            locale: "en".to_string(),
249            tables_filter: None,
250            exclude: vec![],
251            strict: false,
252            progress: false,
253            dry_run: false,
254        };
255
256        let matcher = ColumnMatcher::from_config(&config).unwrap();
257
258        // Should match users.ssn
259        let strategy = matcher.get_strategy("users", "ssn");
260        assert!(matches!(strategy, StrategyKind::Null));
261
262        // Should NOT match other_table.ssn
263        let strategy = matcher.get_strategy("other_table", "ssn");
264        assert!(matches!(strategy, StrategyKind::Skip));
265    }
266
267    #[test]
268    fn test_rule_priority() {
269        let config = RedactConfig {
270            input: std::path::PathBuf::new(),
271            output: None,
272            dialect: crate::parser::SqlDialect::MySql,
273            rules: vec![
274                // More specific rule first
275                Rule {
276                    column: "admins.email".to_string(),
277                    strategy: StrategyKind::Skip,
278                },
279                // General rule second
280                Rule {
281                    column: "*.email".to_string(),
282                    strategy: StrategyKind::Hash {
283                        preserve_domain: false,
284                    },
285                },
286            ],
287            default_strategy: StrategyKind::Skip,
288            seed: None,
289            locale: "en".to_string(),
290            tables_filter: None,
291            exclude: vec![],
292            strict: false,
293            progress: false,
294            dry_run: false,
295        };
296
297        let matcher = ColumnMatcher::from_config(&config).unwrap();
298
299        // admins.email should skip (first rule)
300        let strategy = matcher.get_strategy("admins", "email");
301        assert!(matches!(strategy, StrategyKind::Skip));
302
303        // users.email should hash (second rule)
304        let strategy = matcher.get_strategy("users", "email");
305        assert!(matches!(strategy, StrategyKind::Hash { .. }));
306    }
307
308    #[test]
309    fn test_count_matches() {
310        let config = RedactConfig {
311            input: std::path::PathBuf::new(),
312            output: None,
313            dialect: crate::parser::SqlDialect::MySql,
314            rules: vec![
315                Rule {
316                    column: "*.email".to_string(),
317                    strategy: StrategyKind::Hash {
318                        preserve_domain: false,
319                    },
320                },
321                Rule {
322                    column: "*.ssn".to_string(),
323                    strategy: StrategyKind::Null,
324                },
325            ],
326            default_strategy: StrategyKind::Skip,
327            seed: None,
328            locale: "en".to_string(),
329            tables_filter: None,
330            exclude: vec![],
331            strict: false,
332            progress: false,
333            dry_run: false,
334        };
335
336        let matcher = ColumnMatcher::from_config(&config).unwrap();
337        let schema = create_test_schema();
338
339        // Should match email and ssn (2 columns)
340        assert_eq!(matcher.count_matches("users", &schema), 2);
341    }
342}