Skip to main content

sql_splitter/redactor/
config.rs

1//! Configuration types for the redactor.
2
3use crate::parser::SqlDialect;
4use crate::redactor::StrategyKind;
5use serde::{Deserialize, Serialize};
6use std::path::PathBuf;
7
8/// Runtime configuration for redaction
9#[derive(Debug)]
10pub struct RedactConfig {
11    /// Input SQL file
12    pub input: PathBuf,
13    /// Output SQL file (None for stdout)
14    pub output: Option<PathBuf>,
15    /// SQL dialect
16    pub dialect: SqlDialect,
17    /// Redaction rules
18    pub rules: Vec<Rule>,
19    /// Default strategy for unmatched columns
20    pub default_strategy: StrategyKind,
21    /// Random seed for reproducibility
22    pub seed: Option<u64>,
23    /// Locale for fake data
24    pub locale: String,
25    /// Tables to include (None = all)
26    pub tables_filter: Option<Vec<String>>,
27    /// Tables to exclude
28    pub exclude: Vec<String>,
29    /// Fail on warnings
30    pub strict: bool,
31    /// Show progress
32    pub progress: bool,
33    /// Dry run mode
34    pub dry_run: bool,
35}
36
37impl RedactConfig {
38    /// Create a new builder
39    pub fn builder() -> RedactConfigBuilder {
40        RedactConfigBuilder::default()
41    }
42
43    /// Validate the configuration
44    pub fn validate(&self) -> anyhow::Result<()> {
45        // Check that input file exists
46        if !self.input.exists() {
47            anyhow::bail!("Input file not found: {:?}", self.input);
48        }
49
50        // Validate locale
51        if !is_valid_locale(&self.locale) && self.strict {
52            anyhow::bail!(
53                "Unsupported locale: {}. Use --locale with a supported value.",
54                self.locale
55            );
56        }
57
58        self.default_strategy.validate()?;
59
60        // Validate rules
61        for rule in &self.rules {
62            rule.validate()?;
63        }
64
65        Ok(())
66    }
67}
68
69/// Check if a locale is valid
70fn is_valid_locale(locale: &str) -> bool {
71    matches!(
72        locale.to_lowercase().as_str(),
73        "en" | "en_us" | "de_de" | "fr_fr" | "zh_cn" | "zh_tw" | "ja_jp" | "pt_br" | "ar_sa"
74    )
75}
76
77/// Builder for RedactConfig
78#[derive(Default)]
79pub struct RedactConfigBuilder {
80    input: Option<PathBuf>,
81    output: Option<PathBuf>,
82    dialect: Option<SqlDialect>,
83    config_file: Option<PathBuf>,
84    null_patterns: Vec<String>,
85    hash_patterns: Vec<String>,
86    fake_patterns: Vec<String>,
87    mask_patterns: Vec<String>,
88    constant_patterns: Vec<String>,
89    seed: Option<u64>,
90    locale: String,
91    tables_filter: Option<Vec<String>>,
92    exclude: Vec<String>,
93    strict: bool,
94    progress: bool,
95    dry_run: bool,
96}
97
98impl RedactConfigBuilder {
99    pub fn input(mut self, path: PathBuf) -> Self {
100        self.input = Some(path);
101        self
102    }
103
104    pub fn output(mut self, path: Option<PathBuf>) -> Self {
105        self.output = path;
106        self
107    }
108
109    pub fn dialect(mut self, dialect: SqlDialect) -> Self {
110        self.dialect = Some(dialect);
111        self
112    }
113
114    pub fn config_file(mut self, path: Option<PathBuf>) -> Self {
115        self.config_file = path;
116        self
117    }
118
119    pub fn null_patterns(mut self, patterns: Vec<String>) -> Self {
120        self.null_patterns = patterns;
121        self
122    }
123
124    pub fn hash_patterns(mut self, patterns: Vec<String>) -> Self {
125        self.hash_patterns = patterns;
126        self
127    }
128
129    pub fn fake_patterns(mut self, patterns: Vec<String>) -> Self {
130        self.fake_patterns = patterns;
131        self
132    }
133
134    pub fn mask_patterns(mut self, patterns: Vec<String>) -> Self {
135        self.mask_patterns = patterns;
136        self
137    }
138
139    pub fn constant_patterns(mut self, patterns: Vec<String>) -> Self {
140        self.constant_patterns = patterns;
141        self
142    }
143
144    pub fn seed(mut self, seed: Option<u64>) -> Self {
145        self.seed = seed;
146        self
147    }
148
149    pub fn locale(mut self, locale: String) -> Self {
150        self.locale = locale;
151        self
152    }
153
154    pub fn tables_filter(mut self, tables: Option<Vec<String>>) -> Self {
155        self.tables_filter = tables;
156        self
157    }
158
159    pub fn exclude(mut self, exclude: Vec<String>) -> Self {
160        self.exclude = exclude;
161        self
162    }
163
164    pub fn strict(mut self, strict: bool) -> Self {
165        self.strict = strict;
166        self
167    }
168
169    pub fn progress(mut self, progress: bool) -> Self {
170        self.progress = progress;
171        self
172    }
173
174    pub fn dry_run(mut self, dry_run: bool) -> Self {
175        self.dry_run = dry_run;
176        self
177    }
178
179    /// Build the RedactConfig
180    pub fn build(self) -> anyhow::Result<RedactConfig> {
181        let input = self
182            .input
183            .ok_or_else(|| anyhow::anyhow!("Input file is required"))?;
184        let dialect = self.dialect.unwrap_or(SqlDialect::MySql);
185        let locale = if self.locale.is_empty() {
186            "en".to_string()
187        } else {
188            self.locale
189        };
190
191        // Load YAML config if specified
192        let yaml_config = if let Some(ref path) = self.config_file {
193            Some(RedactYamlConfig::load(path)?)
194        } else {
195            None
196        };
197
198        // Build rules from YAML + CLI patterns
199        let mut rules = Vec::new();
200
201        // Add rules from YAML config
202        if let Some(ref yaml) = yaml_config {
203            rules.extend(yaml.rules.clone());
204        }
205
206        // Add CLI patterns as rules (CLI takes precedence)
207        for pattern in &self.null_patterns {
208            rules.push(Rule {
209                column: pattern.clone(),
210                strategy: StrategyKind::Null,
211            });
212        }
213
214        for pattern in &self.hash_patterns {
215            rules.push(Rule {
216                column: pattern.clone(),
217                strategy: StrategyKind::Hash {
218                    preserve_domain: false,
219                },
220            });
221        }
222
223        for pattern in &self.fake_patterns {
224            rules.push(Rule {
225                column: pattern.clone(),
226                strategy: StrategyKind::Fake {
227                    generator: "name".to_string(),
228                },
229            });
230        }
231
232        for pattern in &self.mask_patterns {
233            // Parse "pattern=column" format
234            if let Some((mask_pattern, column)) = pattern.split_once('=') {
235                rules.push(Rule {
236                    column: column.to_string(),
237                    strategy: StrategyKind::Mask {
238                        pattern: mask_pattern.to_string(),
239                    },
240                });
241            }
242        }
243
244        for pattern in &self.constant_patterns {
245            // Parse "column=value" format
246            if let Some((column, value)) = pattern.split_once('=') {
247                rules.push(Rule {
248                    column: column.to_string(),
249                    strategy: StrategyKind::Constant {
250                        value: value.to_string(),
251                    },
252                });
253            }
254        }
255
256        // Determine default strategy
257        let default_strategy = yaml_config
258            .as_ref()
259            .and_then(|y| y.defaults.as_ref())
260            .map(|d| d.strategy.clone())
261            .unwrap_or(StrategyKind::Skip);
262
263        // Merge seed (CLI overrides YAML)
264        let seed = self
265            .seed
266            .or_else(|| yaml_config.as_ref().and_then(|y| y.seed));
267
268        // Merge locale (CLI overrides YAML)
269        let locale = if locale != "en" {
270            locale
271        } else {
272            yaml_config
273                .as_ref()
274                .and_then(|y| y.locale.clone())
275                .unwrap_or(locale)
276        };
277
278        // Merge skip_tables
279        let mut exclude = self.exclude;
280        if let Some(ref yaml) = yaml_config {
281            if let Some(ref skip) = yaml.skip_tables {
282                exclude.extend(skip.iter().cloned());
283            }
284        }
285
286        Ok(RedactConfig {
287            input,
288            output: self.output,
289            dialect,
290            rules,
291            default_strategy,
292            seed,
293            locale,
294            tables_filter: self.tables_filter,
295            exclude,
296            strict: self.strict,
297            progress: self.progress,
298            dry_run: self.dry_run,
299        })
300    }
301}
302
303/// A redaction rule
304#[derive(Debug, Clone, Serialize, Deserialize)]
305pub struct Rule {
306    /// Column pattern (glob pattern like "*.email" or "users.ssn")
307    pub column: String,
308    /// Redaction strategy
309    #[serde(flatten)]
310    pub strategy: StrategyKind,
311}
312
313impl Rule {
314    /// Validate the rule
315    pub fn validate(&self) -> anyhow::Result<()> {
316        if self.column.is_empty() {
317            anyhow::bail!("Rule column pattern cannot be empty");
318        }
319        self.strategy.validate()
320    }
321}
322
323/// YAML configuration file structure
324#[derive(Debug, Clone, Serialize, Deserialize)]
325pub struct RedactYamlConfig {
326    /// Random seed for reproducibility
327    #[serde(skip_serializing_if = "Option::is_none")]
328    pub seed: Option<u64>,
329
330    /// Locale for fake data
331    #[serde(skip_serializing_if = "Option::is_none")]
332    pub locale: Option<String>,
333
334    /// Default settings
335    #[serde(skip_serializing_if = "Option::is_none")]
336    pub defaults: Option<Defaults>,
337
338    /// Redaction rules
339    #[serde(default)]
340    pub rules: Vec<Rule>,
341
342    /// Tables to skip entirely
343    #[serde(skip_serializing_if = "Option::is_none")]
344    pub skip_tables: Option<Vec<String>>,
345}
346
347impl RedactYamlConfig {
348    /// Load configuration from a YAML file
349    pub fn load(path: &PathBuf) -> anyhow::Result<Self> {
350        let content = std::fs::read_to_string(path)?;
351        let config: Self = serde_yaml_ng::from_str(&content)?;
352        Ok(config)
353    }
354
355    /// Save configuration to a YAML file
356    pub fn save(&self, path: &PathBuf) -> anyhow::Result<()> {
357        let content = serde_yaml_ng::to_string(self)?;
358        std::fs::write(path, content)?;
359        Ok(())
360    }
361}
362
363/// Default settings in YAML config
364#[derive(Debug, Clone, Serialize, Deserialize)]
365pub struct Defaults {
366    /// Default strategy for columns not matching any rule
367    pub strategy: StrategyKind,
368}