1use crate::parser::mysql_insert::{InsertParser, ParsedValue, RowExtraction};
7use crate::parser::postgres_copy::{parse_copy_columns, CopyParser};
8use crate::parser::SqlDialect;
9use crate::redactor::strategy::{
10 ConstantStrategy, FakeStrategy, HashStrategy, MaskStrategy, NullStrategy, RedactValue,
11 Strategy, StrategyKind,
12};
13use crate::schema::TableSchema;
14use rand::rngs::StdRng;
15use rand::SeedableRng;
16
17pub struct ValueRewriter {
19 rng: StdRng,
21 dialect: SqlDialect,
23 locale: String,
25}
26
27impl ValueRewriter {
28 pub fn new(seed: Option<u64>, dialect: SqlDialect, locale: String) -> Self {
30 let rng = match seed {
31 Some(s) => StdRng::seed_from_u64(s),
32 None => rand::make_rng(),
33 };
34 Self {
35 rng,
36 dialect,
37 locale,
38 }
39 }
40
41 pub fn rewrite_insert(
43 &mut self,
44 stmt: &[u8],
45 table_name: &str,
46 table: &TableSchema,
47 strategies: &[StrategyKind],
48 ) -> anyhow::Result<(Vec<u8>, u64, u64)> {
49 let mut parser = InsertParser::new(stmt)
52 .with_schema(table)
53 .with_dialect(self.dialect)
54 .with_extraction(RowExtraction::ValuesOnly);
55 let rows = parser.parse_rows()?;
56
57 if rows.is_empty() {
58 return Ok((stmt.to_vec(), 0, 0));
59 }
60
61 let column_list = crate::parser::mysql_insert::find_values_keyword_pos(stmt)
64 .and_then(|pos| crate::parser::mysql_insert::extract_column_list_before(stmt, pos));
65
66 let mut result = self.build_insert_header(table_name, &column_list);
68
69 let mut rows_redacted = 0u64;
70 let mut columns_redacted = 0u64;
71 let num_strategies = strategies.len();
72
73 for (row_idx, row) in rows.iter().enumerate() {
74 if row_idx > 0 {
75 result.extend_from_slice(b",");
76 }
77 result.extend_from_slice(b"\n(");
78
79 let mut row_had_redaction = false;
80
81 for (col_idx, value) in row.values.iter().enumerate() {
82 if col_idx > 0 {
83 result.extend_from_slice(b", ");
84 }
85
86 let strategy = strategies.get(col_idx).unwrap_or(&StrategyKind::Skip);
88
89 let (redacted_sql, was_redacted) =
91 self.redact_value(value, strategy, col_idx < num_strategies);
92 result.extend_from_slice(redacted_sql.as_bytes());
93
94 if was_redacted {
95 columns_redacted += 1;
96 row_had_redaction = true;
97 }
98 }
99
100 result.extend_from_slice(b")");
101 if row_had_redaction {
102 rows_redacted += 1;
103 }
104 }
105
106 result.extend_from_slice(b";\n");
107
108 Ok((result, rows_redacted, columns_redacted))
109 }
110
111 pub fn rewrite_copy(
113 &mut self,
114 stmt: &[u8],
115 _table_name: &str,
116 table: &TableSchema,
117 strategies: &[StrategyKind],
118 ) -> anyhow::Result<(Vec<u8>, u64, u64)> {
119 let stmt_str = String::from_utf8_lossy(stmt);
123
124 let header_end = stmt_str
126 .find('\n')
127 .ok_or_else(|| anyhow::anyhow!("Invalid COPY statement: no newline"))?;
128 let header = &stmt_str[..header_end];
129 let data_block = &stmt[header_end + 1..];
130
131 let columns = parse_copy_columns(header);
133
134 let mut parser = CopyParser::new(data_block)
136 .with_schema(table)
137 .with_column_order(columns.clone())
138 .with_extraction(RowExtraction::ValuesOnly);
139 let rows = parser.parse_rows()?;
140
141 if rows.is_empty() {
142 return Ok((stmt.to_vec(), 0, 0));
143 }
144
145 let mut result = Vec::with_capacity(stmt.len());
147 result.extend_from_slice(header.as_bytes());
148 result.push(b'\n');
149
150 let mut rows_redacted = 0u64;
151 let mut columns_redacted = 0u64;
152
153 for row in &rows {
154 let mut row_had_redaction = false;
155 let mut first = true;
156
157 let values = self.parse_copy_row_values(&row.raw);
159
160 for (col_idx, value) in values.iter().enumerate() {
161 if !first {
162 result.push(b'\t');
163 }
164 first = false;
165
166 let strategy = strategies.get(col_idx).unwrap_or(&StrategyKind::Skip);
167 let (redacted, was_redacted) = self.redact_copy_value(value, strategy);
168 result.extend_from_slice(&redacted);
169
170 if was_redacted {
171 columns_redacted += 1;
172 row_had_redaction = true;
173 }
174 }
175
176 result.push(b'\n');
177 if row_had_redaction {
178 rows_redacted += 1;
179 }
180 }
181
182 result.extend_from_slice(b"\\.\n");
184
185 Ok((result, rows_redacted, columns_redacted))
186 }
187
188 pub fn rewrite_copy_data(
190 &mut self,
191 data_block: &[u8],
192 table: &TableSchema,
193 strategies: &[StrategyKind],
194 columns: &[String],
195 ) -> anyhow::Result<(Vec<u8>, u64, u64)> {
196 let mut parser = CopyParser::new(data_block)
198 .with_schema(table)
199 .with_column_order(columns.to_vec())
200 .with_extraction(RowExtraction::ValuesOnly);
201 let rows = parser.parse_rows()?;
202
203 if rows.is_empty() {
204 return Ok((data_block.to_vec(), 0, 0));
205 }
206
207 let mut result = Vec::with_capacity(data_block.len());
209
210 let mut rows_redacted = 0u64;
211 let mut columns_redacted = 0u64;
212
213 for row in &rows {
214 let mut row_had_redaction = false;
215 let mut first = true;
216
217 let values = self.parse_copy_row_values(&row.raw);
219
220 for (col_idx, value) in values.iter().enumerate() {
221 if !first {
222 result.push(b'\t');
223 }
224 first = false;
225
226 let strategy = strategies.get(col_idx).unwrap_or(&StrategyKind::Skip);
227 let (redacted, was_redacted) = self.redact_copy_value(value, strategy);
228 result.extend_from_slice(&redacted);
229
230 if was_redacted {
231 columns_redacted += 1;
232 row_had_redaction = true;
233 }
234 }
235
236 result.push(b'\n');
237 if row_had_redaction {
238 rows_redacted += 1;
239 }
240 }
241
242 result.extend_from_slice(b"\\.\n");
244
245 Ok((result, rows_redacted, columns_redacted))
246 }
247
248 fn parse_copy_row_values(&self, raw: &[u8]) -> Vec<CopyValueRef> {
250 let mut values = Vec::new();
251 let mut start = 0;
252
253 for (i, &b) in raw.iter().enumerate() {
254 if b == b'\t' {
255 values.push(self.parse_single_copy_value(&raw[start..i]));
256 start = i + 1;
257 }
258 }
259 if start <= raw.len() {
261 values.push(self.parse_single_copy_value(&raw[start..]));
262 }
263
264 values
265 }
266
267 fn parse_single_copy_value(&self, raw: &[u8]) -> CopyValueRef {
269 if raw == b"\\N" {
270 CopyValueRef::Null
271 } else {
272 CopyValueRef::Text(raw.to_vec())
273 }
274 }
275
276 fn redact_copy_value(
278 &mut self,
279 value: &CopyValueRef,
280 strategy: &StrategyKind,
281 ) -> (Vec<u8>, bool) {
282 if matches!(strategy, StrategyKind::Skip) {
283 let bytes = match value {
284 CopyValueRef::Null => b"\\N".to_vec(),
285 CopyValueRef::Text(t) => t.clone(),
286 };
287 return (bytes, false);
288 }
289
290 let redact_value = match value {
292 CopyValueRef::Null => RedactValue::Null,
293 CopyValueRef::Text(t) => {
294 let decoded = self.decode_copy_escapes(t);
296 RedactValue::String(String::from_utf8_lossy(&decoded).into_owned())
297 }
298 };
299
300 let result = self.apply_strategy(&redact_value, strategy);
302
303 let bytes = match result {
305 RedactValue::Null => b"\\N".to_vec(),
306 RedactValue::String(s) => self.encode_copy_escapes(&s),
307 RedactValue::Integer(i) => i.to_string().into_bytes(),
308 RedactValue::Bytes(b) => self.encode_copy_escapes(&String::from_utf8_lossy(&b)),
309 };
310
311 (bytes, true)
312 }
313
314 fn decode_copy_escapes(&self, value: &[u8]) -> Vec<u8> {
316 let mut result = Vec::with_capacity(value.len());
317 let mut i = 0;
318
319 while i < value.len() {
320 if value[i] == b'\\' && i + 1 < value.len() {
321 let next = value[i + 1];
322 let decoded = match next {
323 b'n' => b'\n',
324 b'r' => b'\r',
325 b't' => b'\t',
326 b'\\' => b'\\',
327 _ => {
328 result.push(b'\\');
329 result.push(next);
330 i += 2;
331 continue;
332 }
333 };
334 result.push(decoded);
335 i += 2;
336 } else {
337 result.push(value[i]);
338 i += 1;
339 }
340 }
341
342 result
343 }
344
345 fn encode_copy_escapes(&self, value: &str) -> Vec<u8> {
347 let mut result = Vec::with_capacity(value.len());
348
349 for b in value.bytes() {
350 match b {
351 b'\n' => result.extend_from_slice(b"\\n"),
352 b'\r' => result.extend_from_slice(b"\\r"),
353 b'\t' => result.extend_from_slice(b"\\t"),
354 b'\\' => result.extend_from_slice(b"\\\\"),
355 _ => result.push(b),
356 }
357 }
358
359 result
360 }
361
362 fn build_insert_header(&self, table_name: &str, columns: &Option<Vec<String>>) -> Vec<u8> {
364 let mut result = Vec::new();
365
366 result.extend_from_slice(b"INSERT INTO ");
368 result.extend_from_slice(self.quote_identifier(table_name).as_bytes());
369
370 if let Some(cols) = columns {
372 result.extend_from_slice(b" (");
373 for (i, col) in cols.iter().enumerate() {
374 if i > 0 {
375 result.extend_from_slice(b", ");
376 }
377 result.extend_from_slice(self.quote_identifier(col).as_bytes());
378 }
379 result.extend_from_slice(b")");
380 }
381
382 result.extend_from_slice(b" VALUES");
383 result
384 }
385
386 fn quote_identifier(&self, name: &str) -> String {
388 match self.dialect {
389 SqlDialect::MySql => format!("`{}`", name),
390 SqlDialect::Postgres | SqlDialect::Sqlite => format!("\"{}\"", name),
391 SqlDialect::Mssql => format!("[{}]", name),
392 }
393 }
394
395 fn redact_value(
397 &mut self,
398 value: &ParsedValue,
399 strategy: &StrategyKind,
400 has_strategy: bool,
401 ) -> (String, bool) {
402 if !has_strategy || matches!(strategy, StrategyKind::Skip) {
404 return (self.format_value(value), false);
405 }
406
407 let redact_value = self.parsed_to_redact(value);
409
410 let result = self.apply_strategy(&redact_value, strategy);
412
413 (self.format_redact_value(&result), true)
415 }
416
417 fn parsed_to_redact(&self, value: &ParsedValue) -> RedactValue {
419 match value {
420 ParsedValue::Null => RedactValue::Null,
421 ParsedValue::Integer(n) => RedactValue::Integer(*n),
422 ParsedValue::BigInteger(n) => RedactValue::Integer(*n as i64), ParsedValue::String { value } => RedactValue::String(value.clone()),
424 ParsedValue::Hex(bytes) => RedactValue::Bytes(bytes.clone()),
425 ParsedValue::Other(bytes) => {
426 RedactValue::String(String::from_utf8_lossy(bytes).into_owned())
427 }
428 }
429 }
430
431 fn apply_strategy(&mut self, value: &RedactValue, strategy: &StrategyKind) -> RedactValue {
433 match strategy {
434 StrategyKind::Null => NullStrategy::new().apply(value, &mut self.rng),
435 StrategyKind::Constant { value: constant } => {
436 ConstantStrategy::new(constant.clone()).apply(value, &mut self.rng)
437 }
438 StrategyKind::Hash { preserve_domain } => {
439 HashStrategy::new(*preserve_domain).apply(value, &mut self.rng)
440 }
441 StrategyKind::Mask { pattern } => {
442 MaskStrategy::new(pattern.clone()).apply(value, &mut self.rng)
443 }
444 StrategyKind::Fake { generator } => {
445 FakeStrategy::new(generator.clone(), self.locale.clone())
446 .apply(value, &mut self.rng)
447 }
448 StrategyKind::Shuffle => {
449 value.clone()
452 }
453 StrategyKind::Skip => value.clone(),
454 }
455 }
456
457 fn format_value(&self, value: &ParsedValue) -> String {
459 match value {
460 ParsedValue::Null => "NULL".to_string(),
461 ParsedValue::Integer(n) => n.to_string(),
462 ParsedValue::BigInteger(n) => n.to_string(),
463 ParsedValue::String { value } => self.format_sql_string(value),
464 ParsedValue::Hex(bytes) => String::from_utf8_lossy(bytes).into_owned(),
465 ParsedValue::Other(bytes) => String::from_utf8_lossy(bytes).into_owned(),
466 }
467 }
468
469 fn format_redact_value(&self, value: &RedactValue) -> String {
471 match value {
472 RedactValue::Null => "NULL".to_string(),
473 RedactValue::Integer(n) => n.to_string(),
474 RedactValue::String(s) => self.format_sql_string(s),
475 RedactValue::Bytes(b) => {
476 format!("0x{}", hex::encode(b))
478 }
479 }
480 }
481
482 fn format_sql_string(&self, value: &str) -> String {
484 match self.dialect {
485 SqlDialect::MySql => {
486 let escaped = value
488 .replace('\\', "\\\\")
489 .replace('\'', "\\'")
490 .replace('\n', "\\n")
491 .replace('\r', "\\r")
492 .replace('\t', "\\t")
493 .replace('\0', "\\0");
494 format!("'{}'", escaped)
495 }
496 SqlDialect::Postgres | SqlDialect::Sqlite => {
497 let escaped = value.replace('\'', "''");
499 format!("'{}'", escaped)
500 }
501 SqlDialect::Mssql => {
502 let escaped = value.replace('\'', "''");
504 if value.bytes().any(|b| b > 127) {
506 format!("N'{}'", escaped)
507 } else {
508 format!("'{}'", escaped)
509 }
510 }
511 }
512 }
513}
514
515enum CopyValueRef {
517 Null,
518 Text(Vec<u8>),
519}
520
521#[cfg(test)]
522mod tests {
523 use super::*;
524 use crate::schema::{Column, ColumnId, ColumnType, TableId, TableSchema};
525
526 fn create_test_schema() -> TableSchema {
527 TableSchema {
528 name: "users".to_string(),
529 id: TableId(0),
530 columns: vec![
531 Column {
532 name: "id".to_string(),
533 col_type: ColumnType::Int,
534 ordinal: ColumnId(0),
535 is_primary_key: true,
536 is_nullable: false,
537 },
538 Column {
539 name: "email".to_string(),
540 col_type: ColumnType::Text,
541 ordinal: ColumnId(1),
542 is_primary_key: false,
543 is_nullable: false,
544 },
545 Column {
546 name: "name".to_string(),
547 col_type: ColumnType::Text,
548 ordinal: ColumnId(2),
549 is_primary_key: false,
550 is_nullable: true,
551 },
552 ],
553 primary_key: vec![ColumnId(0)],
554 foreign_keys: vec![],
555 indexes: vec![],
556 create_statement: None,
557 }
558 }
559
560 #[test]
561 fn test_rewrite_insert_table_name_with_values() {
562 let mut schema = create_test_schema();
565 schema.name = "product_values".to_string();
566
567 let mut rewriter = ValueRewriter::new(Some(1), SqlDialect::MySql, "en".to_string());
568 let stmt = b"INSERT INTO `product_values` (`id`, `email`, `name`) VALUES (1, 'a@b.com', 'Al'), (2, 'c@d.com', 'Bo');";
569 let strategies = vec![StrategyKind::Skip, StrategyKind::Skip, StrategyKind::Skip];
570
571 let (result, _rows, _cols) = rewriter
572 .rewrite_insert(stmt, "product_values", &schema, &strategies)
573 .unwrap();
574 let s = String::from_utf8_lossy(&result);
575
576 assert!(
577 s.contains("(`id`, `email`, `name`)"),
578 "column list dropped: {s}"
579 );
580 assert_eq!(s.matches("@").count(), 2, "wrong row count: {s}");
582 }
583
584 #[test]
585 fn test_rewrite_insert_mysql() {
586 let mut rewriter = ValueRewriter::new(Some(42), SqlDialect::MySql, "en".to_string());
587 let schema = create_test_schema();
588
589 let stmt = b"INSERT INTO `users` (`id`, `email`, `name`) VALUES (1, 'alice@example.com', 'Alice');";
590 let strategies = vec![
591 StrategyKind::Skip, StrategyKind::Hash {
593 preserve_domain: true,
594 }, StrategyKind::Fake {
596 generator: "name".to_string(),
597 }, ];
599
600 let (result, rows, cols) = rewriter
601 .rewrite_insert(stmt, "users", &schema, &strategies)
602 .unwrap();
603 let result_str = String::from_utf8_lossy(&result);
604
605 assert!(result_str.contains("INSERT INTO `users`"));
606 assert!(result_str.contains("VALUES"));
607 assert_eq!(rows, 1);
608 assert_eq!(cols, 2); }
610
611 #[test]
612 fn test_rewrite_insert_mssql() {
613 let mut rewriter = ValueRewriter::new(Some(42), SqlDialect::Mssql, "en".to_string());
614 let schema = create_test_schema();
615
616 let stmt = b"INSERT INTO [users] ([id], [email], [name]) VALUES (1, N'alice@example.com', N'Alice');";
617 let strategies = vec![
618 StrategyKind::Skip, StrategyKind::Null, StrategyKind::Skip, ];
622
623 let (result, rows, cols) = rewriter
624 .rewrite_insert(stmt, "users", &schema, &strategies)
625 .unwrap();
626 let result_str = String::from_utf8_lossy(&result);
627
628 assert!(result_str.contains("INSERT INTO [users]"));
629 assert!(result_str.contains("NULL")); assert_eq!(rows, 1);
631 assert_eq!(cols, 1);
632 }
633
634 #[test]
635 fn test_format_sql_string_mysql() {
636 let rewriter = ValueRewriter::new(Some(42), SqlDialect::MySql, "en".to_string());
637 assert_eq!(rewriter.format_sql_string("hello"), "'hello'");
638 assert_eq!(rewriter.format_sql_string("it's"), "'it\\'s'");
639 assert_eq!(rewriter.format_sql_string("line\nbreak"), "'line\\nbreak'");
640 }
641
642 #[test]
643 fn test_format_sql_string_postgres() {
644 let rewriter = ValueRewriter::new(Some(42), SqlDialect::Postgres, "en".to_string());
645 assert_eq!(rewriter.format_sql_string("hello"), "'hello'");
646 assert_eq!(rewriter.format_sql_string("it's"), "'it''s'");
647 }
648
649 #[test]
650 fn test_format_sql_string_mssql() {
651 let rewriter = ValueRewriter::new(Some(42), SqlDialect::Mssql, "en".to_string());
652 assert_eq!(rewriter.format_sql_string("hello"), "'hello'");
653 assert_eq!(rewriter.format_sql_string("café"), "N'café'");
654 }
655
656 #[test]
657 fn test_quote_identifier() {
658 let mysql = ValueRewriter::new(None, SqlDialect::MySql, "en".to_string());
659 assert_eq!(mysql.quote_identifier("users"), "`users`");
660
661 let pg = ValueRewriter::new(None, SqlDialect::Postgres, "en".to_string());
662 assert_eq!(pg.quote_identifier("users"), "\"users\"");
663
664 let mssql = ValueRewriter::new(None, SqlDialect::Mssql, "en".to_string());
665 assert_eq!(mssql.quote_identifier("users"), "[users]");
666 }
667}