1mod config;
11mod config_generator;
12mod matcher;
13mod rewriter;
14pub mod strategy;
15
16pub use config::RedactConfig;
17#[allow(unused_imports)] pub use config::{RedactConfigBuilder, RedactYamlConfig, Rule};
19pub use config_generator::generate_config;
20pub use matcher::ColumnMatcher;
21pub use rewriter::ValueRewriter;
22pub use strategy::StrategyKind;
23
24use crate::parser::postgres_copy::parse_copy_columns;
25use crate::parser::{Parser, SqlDialect, StatementType};
26use crate::schema::Schema;
27use ahash::AHashMap;
28use schemars::JsonSchema;
29use std::fs::File;
30use std::io::{BufWriter, Write};
31use std::path::Path;
32
33#[derive(Debug, Default, serde::Serialize, JsonSchema)]
35pub struct RedactStats {
36 pub tables_processed: usize,
38 pub rows_redacted: u64,
40 pub columns_redacted: u64,
42 pub table_stats: Vec<TableRedactStats>,
44 pub warnings: Vec<String>,
46}
47
48#[derive(Debug, Clone, serde::Serialize, JsonSchema)]
50pub struct TableRedactStats {
51 pub name: String,
52 pub rows_processed: u64,
53 pub columns_redacted: u64,
54}
55
56pub struct Redactor {
58 config: RedactConfig,
59 schema: Schema,
60 matcher: ColumnMatcher,
61 rewriter: ValueRewriter,
62 stats: RedactStats,
63 pending_copy: Option<PendingCopy>,
65}
66
67struct PendingCopy {
69 header: Vec<u8>,
70 table_name: String,
71 columns: Vec<String>,
72}
73
74impl Redactor {
75 pub fn new(config: RedactConfig) -> anyhow::Result<Self> {
77 let schema = Self::build_schema(&config.input, config.dialect)?;
79
80 let matcher = ColumnMatcher::from_config(&config)?;
82
83 let rewriter = ValueRewriter::new(config.seed, config.dialect, config.locale.clone());
85
86 Ok(Self {
87 config,
88 schema,
89 matcher,
90 rewriter,
91 stats: RedactStats::default(),
92 pending_copy: None,
93 })
94 }
95
96 fn build_schema(input: &Path, dialect: SqlDialect) -> anyhow::Result<Schema> {
98 Schema::from_sql_file(input, dialect, None)
99 }
100
101 pub fn run(&mut self) -> anyhow::Result<RedactStats> {
103 if self.config.dry_run {
104 return self.dry_run();
105 }
106
107 let output: Box<dyn Write> = if let Some(ref path) = self.config.output {
110 Box::new(BufWriter::new(File::create(path)?))
111 } else {
112 Box::new(BufWriter::new(std::io::stdout()))
113 };
114
115 self.process_file(output)?;
116
117 Ok(std::mem::take(&mut self.stats))
118 }
119
120 fn dry_run(&mut self) -> anyhow::Result<RedactStats> {
122 let reader = crate::splitter::open_input(&self.config.input)?;
123 let mut parser = Parser::with_dialect(reader, 64 * 1024, self.config.dialect);
124
125 let mut tables_seen: AHashMap<String, u64> = AHashMap::new();
126
127 while let Some(stmt) = parser.read_statement()? {
128 let (stmt_type, table_name) =
129 Parser::<&[u8]>::parse_statement_with_dialect(&stmt, self.config.dialect);
130
131 if !table_name.is_empty()
132 && (stmt_type == StatementType::Insert || stmt_type == StatementType::Copy)
133 {
134 *tables_seen.entry(table_name).or_insert(0) += 1;
135 }
136 }
137
138 for (name, count) in tables_seen {
140 if let Some(table) = self.schema.get_table(&name) {
141 let columns_matched = self.matcher.count_matches(&name, table);
142 if columns_matched > 0 {
143 self.stats.tables_processed += 1;
144 self.stats.rows_redacted += count;
145 self.stats.columns_redacted += columns_matched as u64 * count;
146 self.stats.table_stats.push(TableRedactStats {
147 name,
148 rows_processed: count,
149 columns_redacted: columns_matched as u64,
150 });
151 }
152 }
153 }
154
155 Ok(std::mem::take(&mut self.stats))
156 }
157
158 fn process_file(&mut self, mut output: Box<dyn Write>) -> anyhow::Result<()> {
160 let reader = crate::splitter::open_input(&self.config.input)?;
161 let mut parser = Parser::with_dialect(reader, 64 * 1024, self.config.dialect);
162
163 while let Some(stmt) = parser.read_statement()? {
164 let (stmt_type, table_name) =
165 Parser::<&[u8]>::parse_statement_with_dialect(&stmt, self.config.dialect);
166
167 let redacted = match stmt_type {
168 StatementType::Insert if !table_name.is_empty() => {
169 self.redact_insert(&stmt, &table_name)?
170 }
171 StatementType::Copy if !table_name.is_empty() => {
172 if self.config.dialect == SqlDialect::Postgres {
174 let header_str = String::from_utf8_lossy(&stmt);
175 let columns = parse_copy_columns(&header_str);
176 self.pending_copy = Some(PendingCopy {
177 header: stmt.clone(),
178 table_name: table_name.clone(),
179 columns,
180 });
181 continue;
183 }
184 self.redact_copy(&stmt, &table_name)?
185 }
186 StatementType::Unknown
187 if self.config.dialect == SqlDialect::Postgres
188 && self.pending_copy.is_some()
189 && (stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n")) =>
190 {
191 self.redact_copy_data(&stmt)?
193 }
194 _ => {
195 if let Some(pending) = self.pending_copy.take() {
198 output.write_all(&pending.header)?;
199 }
200 stmt
201 }
202 };
203
204 output.write_all(&redacted)?;
205 }
206
207 if let Some(pending) = self.pending_copy.take() {
209 output.write_all(&pending.header)?;
210 }
211
212 output.flush()?;
213 Ok(())
214 }
215
216 fn record_stats(&mut self, table_name: &str, rows_redacted: u64, cols_redacted: u64) {
218 if rows_redacted == 0 {
219 return;
220 }
221
222 self.stats.rows_redacted += rows_redacted;
223 self.stats.columns_redacted += cols_redacted;
224
225 if let Some(ts) = self
227 .stats
228 .table_stats
229 .iter_mut()
230 .find(|t| t.name == table_name)
231 {
232 ts.rows_processed += rows_redacted;
233 ts.columns_redacted += cols_redacted;
234 } else {
235 self.stats.tables_processed += 1;
236 self.stats.table_stats.push(TableRedactStats {
237 name: table_name.to_string(),
238 rows_processed: rows_redacted,
239 columns_redacted: cols_redacted,
240 });
241 }
242 }
243
244 fn redact_insert(&mut self, stmt: &[u8], table_name: &str) -> anyhow::Result<Vec<u8>> {
246 if self.should_skip_table(table_name) {
248 return Ok(stmt.to_vec());
249 }
250
251 let Some(table) = self.schema.get_table(table_name) else {
253 self.stats.warnings.push(format!(
254 "No schema for table '{}', passing through unchanged",
255 table_name
256 ));
257 return Ok(stmt.to_vec());
258 };
259
260 let strategies = self.matcher.get_strategies(table_name, table);
262
263 if strategies.iter().all(|s| matches!(s, StrategyKind::Skip)) {
265 return Ok(stmt.to_vec());
266 }
267
268 let (redacted, rows_redacted, cols_redacted) =
270 self.rewriter
271 .rewrite_insert(stmt, table_name, table, &strategies)?;
272
273 self.record_stats(table_name, rows_redacted, cols_redacted);
274
275 Ok(redacted)
276 }
277
278 fn redact_copy(&mut self, stmt: &[u8], table_name: &str) -> anyhow::Result<Vec<u8>> {
280 if self.should_skip_table(table_name) {
282 return Ok(stmt.to_vec());
283 }
284
285 let Some(table) = self.schema.get_table(table_name) else {
287 self.stats.warnings.push(format!(
288 "No schema for table '{}', passing through unchanged",
289 table_name
290 ));
291 return Ok(stmt.to_vec());
292 };
293
294 let strategies = self.matcher.get_strategies(table_name, table);
296
297 if strategies.iter().all(|s| matches!(s, StrategyKind::Skip)) {
299 return Ok(stmt.to_vec());
300 }
301
302 let (redacted, rows_redacted, cols_redacted) =
304 self.rewriter
305 .rewrite_copy(stmt, table_name, table, &strategies)?;
306
307 self.record_stats(table_name, rows_redacted, cols_redacted);
308
309 Ok(redacted)
310 }
311
312 fn redact_copy_data(&mut self, data_block: &[u8]) -> anyhow::Result<Vec<u8>> {
314 let pending = self
315 .pending_copy
316 .take()
317 .ok_or_else(|| anyhow::anyhow!("COPY data block without pending header"))?;
318
319 let table_name = &pending.table_name;
320
321 if self.should_skip_table(table_name) {
323 let mut result = pending.header;
325 result.extend_from_slice(data_block);
326 return Ok(result);
327 }
328
329 let Some(table) = self.schema.get_table(table_name) else {
331 self.stats.warnings.push(format!(
332 "No schema for table '{}', passing through unchanged",
333 table_name
334 ));
335 let mut result = pending.header;
336 result.extend_from_slice(data_block);
337 return Ok(result);
338 };
339
340 let strategies = self.matcher.get_strategies(table_name, table);
342
343 if strategies.iter().all(|s| matches!(s, StrategyKind::Skip)) {
345 let mut result = pending.header;
346 result.extend_from_slice(data_block);
347 return Ok(result);
348 }
349
350 let (redacted_data, rows_redacted, cols_redacted) =
352 self.rewriter
353 .rewrite_copy_data(data_block, table, &strategies, &pending.columns)?;
354
355 self.record_stats(&pending.table_name, rows_redacted, cols_redacted);
356
357 let mut result = pending.header;
360 if !result.ends_with(b"\n") {
361 result.push(b'\n');
362 }
363 result.extend_from_slice(&redacted_data);
364 Ok(result)
365 }
366
367 fn should_skip_table(&self, name: &str) -> bool {
369 if self
371 .config
372 .exclude
373 .iter()
374 .any(|e| e.eq_ignore_ascii_case(name))
375 {
376 return true;
377 }
378
379 if let Some(ref tables) = self.config.tables_filter {
381 if !tables.iter().any(|t| t.eq_ignore_ascii_case(name)) {
382 return true;
383 }
384 }
385
386 false
387 }
388}