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        // Split at the final dot so a schema-qualified table identity remains
49        // intact: `tenant_a.users.email` targets the `email` column on
50        // `tenant_a.users`, not a fictitious `users.email` column on
51        // `tenant_a`.
52        let (table_pattern, column_pattern) = if let Some(dot_pos) = pattern.rfind('.') {
53            let table_part = &pattern[..dot_pos];
54            let column_part = &pattern[dot_pos + 1..];
55
56            // Compile table pattern (might be * for all tables)
57            let table_pat = if table_part == "*" {
58                None
59            } else {
60                Some(Pattern::new(table_part).map_err(|e| {
61                    anyhow::anyhow!("Invalid table pattern '{}': {}", table_part, e)
62                })?)
63            };
64
65            let col_pat = Pattern::new(column_part)
66                .map_err(|e| anyhow::anyhow!("Invalid column pattern '{}': {}", column_part, e))?;
67
68            (table_pat, col_pat)
69        } else {
70            // No table qualifier - match all tables
71            let col_pat = Pattern::new(pattern)
72                .map_err(|e| anyhow::anyhow!("Invalid column pattern '{}': {}", pattern, e))?;
73            (None, col_pat)
74        };
75
76        Ok(CompiledRule {
77            table_pattern,
78            column_pattern,
79            strategy: rule.strategy.clone(),
80        })
81    }
82
83    /// Get the strategy for a specific column
84    pub fn get_strategy(&self, table_name: &str, column_name: &str) -> StrategyKind {
85        // Find first matching rule (rules are processed in order)
86        for rule in &self.rules {
87            if self.rule_matches(rule, table_name, column_name) {
88                return rule.strategy.clone();
89            }
90        }
91
92        // No match - return default
93        self.default_strategy.clone()
94    }
95
96    /// Get strategies for all columns in a table
97    pub fn get_strategies(&self, table_name: &str, table: &TableSchema) -> Vec<StrategyKind> {
98        table
99            .columns
100            .iter()
101            .map(|col| self.get_strategy(table_name, &col.name))
102            .collect()
103    }
104
105    /// Count how many columns match any redaction rule
106    pub fn count_matches(&self, table_name: &str, table: &TableSchema) -> usize {
107        table
108            .columns
109            .iter()
110            .filter(|col| {
111                let strategy = self.get_strategy(table_name, &col.name);
112                !matches!(strategy, StrategyKind::Skip)
113            })
114            .count()
115    }
116
117    /// Check if a rule matches a table/column pair
118    fn rule_matches(&self, rule: &CompiledRule, table_name: &str, column_name: &str) -> bool {
119        // Check table pattern (if specified)
120        if let Some(ref table_pat) = rule.table_pattern {
121            if !table_pat.matches(table_name) && !table_pat.matches(&table_name.to_lowercase()) {
122                return false;
123            }
124        }
125
126        // Check column pattern
127        rule.column_pattern.matches(column_name)
128            || rule.column_pattern.matches(&column_name.to_lowercase())
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    fn create_test_schema() -> TableSchema {
137        use crate::schema::{Column, ColumnId, ColumnType, TableId};
138
139        TableSchema {
140            name: "users".to_string(),
141            id: TableId(0),
142            columns: vec![
143                Column {
144                    name: "id".to_string(),
145                    col_type: ColumnType::Int,
146                    source_type: "INT".to_string(),
147                    ordinal: ColumnId(0),
148                    is_primary_key: true,
149                    is_nullable: false,
150                    is_unique: false,
151                    default_sql: None,
152                    is_generated: false,
153                    is_identity: false,
154                    collation: None,
155                },
156                Column {
157                    name: "email".to_string(),
158                    col_type: ColumnType::Text,
159                    source_type: "VARCHAR(255)".to_string(),
160                    ordinal: ColumnId(1),
161                    is_primary_key: false,
162                    is_nullable: false,
163                    is_unique: false,
164                    default_sql: None,
165                    is_generated: false,
166                    is_identity: false,
167                    collation: None,
168                },
169                Column {
170                    name: "name".to_string(),
171                    col_type: ColumnType::Text,
172                    source_type: "VARCHAR(255)".to_string(),
173                    ordinal: ColumnId(2),
174                    is_primary_key: false,
175                    is_nullable: true,
176                    is_unique: false,
177                    default_sql: None,
178                    is_generated: false,
179                    is_identity: false,
180                    collation: None,
181                },
182                Column {
183                    name: "ssn".to_string(),
184                    col_type: ColumnType::Text,
185                    source_type: "VARCHAR(255)".to_string(),
186                    ordinal: ColumnId(3),
187                    is_primary_key: false,
188                    is_nullable: true,
189                    is_unique: false,
190                    default_sql: None,
191                    is_generated: false,
192                    is_identity: false,
193                    collation: None,
194                },
195            ],
196            primary_key: vec![ColumnId(0)],
197            foreign_keys: vec![],
198            unique_constraints: vec![],
199            check_constraints: vec![],
200            indexes: vec![],
201            create_statement: None,
202        }
203    }
204
205    #[test]
206    fn test_wildcard_column_match() {
207        let config = RedactConfig {
208            input: std::path::PathBuf::new(),
209            output: None,
210            dialect: crate::parser::SqlDialect::MySql,
211            rules: vec![Rule {
212                column: "*.email".to_string(),
213                strategy: StrategyKind::Hash {
214                    preserve_domain: true,
215                },
216            }],
217            default_strategy: StrategyKind::Skip,
218            seed: None,
219            locale: "en".to_string(),
220            tables_filter: None,
221            exclude: vec![],
222            strict: false,
223            progress: false,
224            dry_run: false,
225        };
226
227        let matcher = ColumnMatcher::from_config(&config).unwrap();
228        let schema = create_test_schema();
229
230        let strategies = matcher.get_strategies("users", &schema);
231
232        // id: skip, email: hash, name: skip, ssn: skip
233        assert!(matches!(strategies[0], StrategyKind::Skip));
234        assert!(matches!(strategies[1], StrategyKind::Hash { .. }));
235        assert!(matches!(strategies[2], StrategyKind::Skip));
236        assert!(matches!(strategies[3], StrategyKind::Skip));
237    }
238
239    #[test]
240    fn test_exact_column_match() {
241        let config = RedactConfig {
242            input: std::path::PathBuf::new(),
243            output: None,
244            dialect: crate::parser::SqlDialect::MySql,
245            rules: vec![Rule {
246                column: "users.ssn".to_string(),
247                strategy: StrategyKind::Null,
248            }],
249            default_strategy: StrategyKind::Skip,
250            seed: None,
251            locale: "en".to_string(),
252            tables_filter: None,
253            exclude: vec![],
254            strict: false,
255            progress: false,
256            dry_run: false,
257        };
258
259        let matcher = ColumnMatcher::from_config(&config).unwrap();
260
261        // Should match users.ssn
262        let strategy = matcher.get_strategy("users", "ssn");
263        assert!(matches!(strategy, StrategyKind::Null));
264
265        // Should NOT match other_table.ssn
266        let strategy = matcher.get_strategy("other_table", "ssn");
267        assert!(matches!(strategy, StrategyKind::Skip));
268    }
269
270    #[test]
271    fn qualified_table_rule_matches_the_complete_table_identity() {
272        let config = RedactConfig {
273            input: std::path::PathBuf::new(),
274            output: None,
275            dialect: crate::parser::SqlDialect::Postgres,
276            rules: vec![Rule {
277                column: "tenant_a.users.email".to_string(),
278                strategy: StrategyKind::Null,
279            }],
280            default_strategy: StrategyKind::Skip,
281            seed: None,
282            locale: "en".to_string(),
283            tables_filter: None,
284            exclude: vec![],
285            strict: false,
286            progress: false,
287            dry_run: false,
288        };
289        let matcher = ColumnMatcher::from_config(&config).unwrap();
290
291        assert!(matches!(
292            matcher.get_strategy("tenant_a.users", "email"),
293            StrategyKind::Null
294        ));
295        assert!(matches!(
296            matcher.get_strategy("tenant_b.users", "email"),
297            StrategyKind::Skip
298        ));
299    }
300
301    #[test]
302    fn test_rule_priority() {
303        let config = RedactConfig {
304            input: std::path::PathBuf::new(),
305            output: None,
306            dialect: crate::parser::SqlDialect::MySql,
307            rules: vec![
308                // More specific rule first
309                Rule {
310                    column: "admins.email".to_string(),
311                    strategy: StrategyKind::Skip,
312                },
313                // General rule second
314                Rule {
315                    column: "*.email".to_string(),
316                    strategy: StrategyKind::Hash {
317                        preserve_domain: false,
318                    },
319                },
320            ],
321            default_strategy: StrategyKind::Skip,
322            seed: None,
323            locale: "en".to_string(),
324            tables_filter: None,
325            exclude: vec![],
326            strict: false,
327            progress: false,
328            dry_run: false,
329        };
330
331        let matcher = ColumnMatcher::from_config(&config).unwrap();
332
333        // admins.email should skip (first rule)
334        let strategy = matcher.get_strategy("admins", "email");
335        assert!(matches!(strategy, StrategyKind::Skip));
336
337        // users.email should hash (second rule)
338        let strategy = matcher.get_strategy("users", "email");
339        assert!(matches!(strategy, StrategyKind::Hash { .. }));
340    }
341
342    #[test]
343    fn test_count_matches() {
344        let config = RedactConfig {
345            input: std::path::PathBuf::new(),
346            output: None,
347            dialect: crate::parser::SqlDialect::MySql,
348            rules: vec![
349                Rule {
350                    column: "*.email".to_string(),
351                    strategy: StrategyKind::Hash {
352                        preserve_domain: false,
353                    },
354                },
355                Rule {
356                    column: "*.ssn".to_string(),
357                    strategy: StrategyKind::Null,
358                },
359            ],
360            default_strategy: StrategyKind::Skip,
361            seed: None,
362            locale: "en".to_string(),
363            tables_filter: None,
364            exclude: vec![],
365            strict: false,
366            progress: false,
367            dry_run: false,
368        };
369
370        let matcher = ColumnMatcher::from_config(&config).unwrap();
371        let schema = create_test_schema();
372
373        // Should match email and ssn (2 columns)
374        assert_eq!(matcher.count_matches("users", &schema), 2);
375    }
376}