Skip to main content

sql_splitter/redactor/
rewriter.rs

1//! Value rewriter for INSERT and COPY statement redaction.
2//!
3//! Handles parsing values, applying redaction strategies, and formatting
4//! the redacted values back to SQL with proper dialect-aware escaping.
5
6use crate::parser::mysql_insert::{InsertParser, ParsedValue, RowExtraction};
7use crate::parser::postgres_copy::{decode_copy_escapes, 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
17/// Rewriter for INSERT and COPY statements
18pub struct ValueRewriter {
19    /// RNG for reproducible redaction
20    rng: StdRng,
21    /// Dialect for output formatting
22    dialect: SqlDialect,
23    /// Locale for fake data generation
24    locale: String,
25}
26
27impl ValueRewriter {
28    /// Create a new rewriter with optional seed for reproducibility
29    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    /// Rewrite an INSERT statement with redacted values
42    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        // Parse the INSERT statement (dialect governs backslash unescaping so
50        // non-MySQL strings aren't corrupted on re-serialization, bug #3)
51        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        // Get the column list (if any) from the statement, locating VALUES as a
62        // keyword so a table named like `*values*` doesn't misplace it (bug #2).
63        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        // Build the header: INSERT INTO table_name (columns) VALUES
67        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                // Get strategy for this column (may be Skip if index out of bounds)
87                let strategy = strategies.get(col_idx).unwrap_or(&StrategyKind::Skip);
88
89                // Apply redaction
90                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    /// Rewrite a COPY statement with redacted values (PostgreSQL)
112    ///
113    /// Splits the statement into header line and data block, then delegates
114    /// the row redaction loop to [`Self::rewrite_copy_data`].
115    pub fn rewrite_copy(
116        &mut self,
117        stmt: &[u8],
118        _table_name: &str,
119        table: &TableSchema,
120        strategies: &[StrategyKind],
121    ) -> anyhow::Result<(Vec<u8>, u64, u64)> {
122        // COPY statements include the header and data block
123        // Format: COPY table (cols) FROM stdin;\ndata\n\.\n
124
125        // Find the header line (ends with "FROM stdin;" or similar)
126        let header_end = stmt
127            .iter()
128            .position(|&b| b == b'\n')
129            .ok_or_else(|| anyhow::anyhow!("Invalid COPY statement: no newline"))?;
130        let header = &stmt[..header_end];
131        let data_block = &stmt[header_end + 1..];
132
133        // Parse column list from header
134        let columns = parse_copy_columns(&String::from_utf8_lossy(header));
135
136        let (redacted_data, rows_redacted, columns_redacted) =
137            self.rewrite_copy_data(data_block, table, strategies, &columns)?;
138
139        // Build result: header + redacted data (including terminator)
140        let mut result = Vec::with_capacity(header.len() + 1 + redacted_data.len());
141        result.extend_from_slice(header);
142        result.push(b'\n');
143        result.extend_from_slice(&redacted_data);
144
145        Ok((result, rows_redacted, columns_redacted))
146    }
147
148    /// Rewrite just the COPY data block (header handled separately)
149    pub fn rewrite_copy_data(
150        &mut self,
151        data_block: &[u8],
152        table: &TableSchema,
153        strategies: &[StrategyKind],
154        columns: &[String],
155    ) -> anyhow::Result<(Vec<u8>, u64, u64)> {
156        // Parse data rows
157        let mut parser = CopyParser::new(data_block)
158            .with_schema(table)
159            .with_column_order(columns.to_vec())
160            .with_extraction(RowExtraction::ValuesOnly);
161        let rows = parser.parse_rows()?;
162
163        if rows.is_empty() {
164            return Ok((data_block.to_vec(), 0, 0));
165        }
166
167        // Build result: redacted data + terminator
168        let mut result = Vec::with_capacity(data_block.len());
169
170        let mut rows_redacted = 0u64;
171        let mut columns_redacted = 0u64;
172
173        for row in &rows {
174            let mut row_had_redaction = false;
175            let mut first = true;
176
177            // Parse the raw values from the row
178            let values = self.parse_copy_row_values(&row.raw);
179
180            for (col_idx, value) in values.iter().enumerate() {
181                if !first {
182                    result.push(b'\t');
183                }
184                first = false;
185
186                let strategy = strategies.get(col_idx).unwrap_or(&StrategyKind::Skip);
187                let (redacted, was_redacted) = self.redact_copy_value(value, strategy);
188                result.extend_from_slice(&redacted);
189
190                if was_redacted {
191                    columns_redacted += 1;
192                    row_had_redaction = true;
193                }
194            }
195
196            result.push(b'\n');
197            if row_had_redaction {
198                rows_redacted += 1;
199            }
200        }
201
202        // Add terminator
203        result.extend_from_slice(b"\\.\n");
204
205        Ok((result, rows_redacted, columns_redacted))
206    }
207
208    /// Parse tab-separated values from a COPY row
209    fn parse_copy_row_values(&self, raw: &[u8]) -> Vec<CopyValueRef> {
210        let mut values = Vec::new();
211        let mut start = 0;
212
213        for (i, &b) in raw.iter().enumerate() {
214            if b == b'\t' {
215                values.push(self.parse_single_copy_value(&raw[start..i]));
216                start = i + 1;
217            }
218        }
219        // Last value
220        if start <= raw.len() {
221            values.push(self.parse_single_copy_value(&raw[start..]));
222        }
223
224        values
225    }
226
227    /// Parse a single COPY value
228    fn parse_single_copy_value(&self, raw: &[u8]) -> CopyValueRef {
229        if raw == b"\\N" {
230            CopyValueRef::Null
231        } else {
232            CopyValueRef::Text(raw.to_vec())
233        }
234    }
235
236    /// Redact a COPY value and return the redacted bytes
237    fn redact_copy_value(
238        &mut self,
239        value: &CopyValueRef,
240        strategy: &StrategyKind,
241    ) -> (Vec<u8>, bool) {
242        if matches!(strategy, StrategyKind::Skip) {
243            let bytes = match value {
244                CopyValueRef::Null => b"\\N".to_vec(),
245                CopyValueRef::Text(t) => t.clone(),
246            };
247            return (bytes, false);
248        }
249
250        // Convert to RedactValue
251        let redact_value = match value {
252            CopyValueRef::Null => RedactValue::Null,
253            CopyValueRef::Text(t) => {
254                // Decode escape sequences first (canonical COPY decoder lives
255                // in the parser module)
256                let decoded = decode_copy_escapes(t);
257                RedactValue::String(String::from_utf8_lossy(&decoded).into_owned())
258            }
259        };
260
261        // Apply strategy
262        let result = self.apply_strategy(&redact_value, strategy);
263
264        // Convert back to COPY format
265        let bytes = match result {
266            RedactValue::Null => b"\\N".to_vec(),
267            RedactValue::String(s) => self.encode_copy_escapes(&s),
268            RedactValue::Integer(i) => i.to_string().into_bytes(),
269            RedactValue::Bytes(b) => self.encode_copy_escapes(&String::from_utf8_lossy(&b)),
270        };
271
272        (bytes, true)
273    }
274
275    /// Encode string for COPY format (escape special characters)
276    fn encode_copy_escapes(&self, value: &str) -> Vec<u8> {
277        let mut result = Vec::with_capacity(value.len());
278
279        for b in value.bytes() {
280            match b {
281                b'\n' => result.extend_from_slice(b"\\n"),
282                b'\r' => result.extend_from_slice(b"\\r"),
283                b'\t' => result.extend_from_slice(b"\\t"),
284                b'\\' => result.extend_from_slice(b"\\\\"),
285                _ => result.push(b),
286            }
287        }
288
289        result
290    }
291
292    /// Build INSERT statement header
293    fn build_insert_header(&self, table_name: &str, columns: &Option<Vec<String>>) -> Vec<u8> {
294        let mut result = Vec::new();
295
296        // INSERT INTO table_name
297        result.extend_from_slice(b"INSERT INTO ");
298        result.extend_from_slice(self.quote_identifier(table_name).as_bytes());
299
300        // Optional column list
301        if let Some(cols) = columns {
302            result.extend_from_slice(b" (");
303            for (i, col) in cols.iter().enumerate() {
304                if i > 0 {
305                    result.extend_from_slice(b", ");
306                }
307                result.extend_from_slice(self.quote_identifier(col).as_bytes());
308            }
309            result.extend_from_slice(b")");
310        }
311
312        result.extend_from_slice(b" VALUES");
313        result
314    }
315
316    /// Quote an identifier based on dialect
317    fn quote_identifier(&self, name: &str) -> String {
318        crate::transform_common::quote_ident(self.dialect, name)
319    }
320
321    /// Redact a parsed value and format it for SQL output
322    fn redact_value(
323        &mut self,
324        value: &ParsedValue,
325        strategy: &StrategyKind,
326        has_strategy: bool,
327    ) -> (String, bool) {
328        // Skip strategy means no redaction
329        if !has_strategy || matches!(strategy, StrategyKind::Skip) {
330            return (self.format_value(value), false);
331        }
332
333        // Convert ParsedValue to RedactValue
334        let redact_value = self.parsed_to_redact(value);
335
336        // Apply the strategy
337        let result = self.apply_strategy(&redact_value, strategy);
338
339        // Format the result for SQL
340        (self.format_redact_value(&result), true)
341    }
342
343    /// Convert ParsedValue to RedactValue
344    fn parsed_to_redact(&self, value: &ParsedValue) -> RedactValue {
345        match value {
346            ParsedValue::Null => RedactValue::Null,
347            ParsedValue::Integer(n) => RedactValue::Integer(*n),
348            ParsedValue::BigInteger(n) => RedactValue::Integer(*n as i64), // Potential truncation
349            ParsedValue::String { value } => RedactValue::String(value.clone()),
350            ParsedValue::Hex(bytes) => RedactValue::Bytes(bytes.clone()),
351            ParsedValue::Other(bytes) => {
352                RedactValue::String(String::from_utf8_lossy(bytes).into_owned())
353            }
354        }
355    }
356
357    /// Apply a redaction strategy to a value
358    fn apply_strategy(&mut self, value: &RedactValue, strategy: &StrategyKind) -> RedactValue {
359        match strategy {
360            StrategyKind::Null => NullStrategy::new().apply(value, &mut self.rng),
361            StrategyKind::Constant { value: constant } => {
362                ConstantStrategy::new(constant.clone()).apply(value, &mut self.rng)
363            }
364            StrategyKind::Hash { preserve_domain } => {
365                HashStrategy::new(*preserve_domain).apply(value, &mut self.rng)
366            }
367            StrategyKind::Mask { pattern } => {
368                MaskStrategy::new(pattern.clone()).apply(value, &mut self.rng)
369            }
370            StrategyKind::Fake { generator } => {
371                FakeStrategy::new(generator.clone(), self.locale.clone())
372                    .apply(value, &mut self.rng)
373            }
374            StrategyKind::Shuffle => {
375                // Shuffle is special - needs column-level state
376                // For now, treat as skip (shuffle implemented at higher level)
377                value.clone()
378            }
379            StrategyKind::Skip => value.clone(),
380        }
381    }
382
383    /// Format a ParsedValue for SQL output
384    fn format_value(&self, value: &ParsedValue) -> String {
385        match value {
386            ParsedValue::Null => "NULL".to_string(),
387            ParsedValue::Integer(n) => n.to_string(),
388            ParsedValue::BigInteger(n) => n.to_string(),
389            ParsedValue::String { value } => self.format_sql_string(value),
390            ParsedValue::Hex(bytes) => String::from_utf8_lossy(bytes).into_owned(),
391            ParsedValue::Other(bytes) => String::from_utf8_lossy(bytes).into_owned(),
392        }
393    }
394
395    /// Format a RedactValue for SQL output
396    fn format_redact_value(&self, value: &RedactValue) -> String {
397        match value {
398            RedactValue::Null => "NULL".to_string(),
399            RedactValue::Integer(n) => n.to_string(),
400            RedactValue::String(s) => self.format_sql_string(s),
401            RedactValue::Bytes(b) => {
402                // Format as hex literal
403                format!("0x{}", hex::encode(b))
404            }
405        }
406    }
407
408    /// Format a string for SQL with proper escaping based on dialect
409    fn format_sql_string(&self, value: &str) -> String {
410        match self.dialect {
411            SqlDialect::MySql => {
412                // MySQL uses backslash escaping
413                let escaped = value
414                    .replace('\\', "\\\\")
415                    .replace('\'', "\\'")
416                    .replace('\n', "\\n")
417                    .replace('\r', "\\r")
418                    .replace('\t', "\\t")
419                    .replace('\0', "\\0");
420                format!("'{}'", escaped)
421            }
422            SqlDialect::Postgres | SqlDialect::Sqlite => {
423                // PostgreSQL/SQLite use doubled single quotes
424                let escaped = value.replace('\'', "''");
425                format!("'{}'", escaped)
426            }
427            SqlDialect::Mssql => {
428                // MSSQL uses N'...' for Unicode strings with doubled quotes
429                let escaped = value.replace('\'', "''");
430                // Use N'...' for non-ASCII or always for safety
431                if value.bytes().any(|b| b > 127) {
432                    format!("N'{}'", escaped)
433                } else {
434                    format!("'{}'", escaped)
435                }
436            }
437        }
438    }
439}
440
441/// Internal COPY value representation
442enum CopyValueRef {
443    Null,
444    Text(Vec<u8>),
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450    use crate::schema::{Column, ColumnId, ColumnType, TableId, TableSchema};
451
452    fn create_test_schema() -> TableSchema {
453        TableSchema {
454            name: "users".to_string(),
455            id: TableId(0),
456            columns: vec![
457                Column {
458                    name: "id".to_string(),
459                    col_type: ColumnType::Int,
460                    source_type: "INT".to_string(),
461                    ordinal: ColumnId(0),
462                    is_primary_key: true,
463                    is_nullable: false,
464                    is_unique: false,
465                    default_sql: None,
466                    is_generated: false,
467                    is_identity: false,
468                    collation: None,
469                },
470                Column {
471                    name: "email".to_string(),
472                    col_type: ColumnType::Text,
473                    source_type: "VARCHAR(255)".to_string(),
474                    ordinal: ColumnId(1),
475                    is_primary_key: false,
476                    is_nullable: false,
477                    is_unique: false,
478                    default_sql: None,
479                    is_generated: false,
480                    is_identity: false,
481                    collation: None,
482                },
483                Column {
484                    name: "name".to_string(),
485                    col_type: ColumnType::Text,
486                    source_type: "VARCHAR(255)".to_string(),
487                    ordinal: ColumnId(2),
488                    is_primary_key: false,
489                    is_nullable: true,
490                    is_unique: false,
491                    default_sql: None,
492                    is_generated: false,
493                    is_identity: false,
494                    collation: None,
495                },
496            ],
497            primary_key: vec![ColumnId(0)],
498            foreign_keys: vec![],
499            unique_constraints: vec![],
500            check_constraints: vec![],
501            indexes: vec![],
502            create_statement: None,
503        }
504    }
505
506    #[test]
507    fn test_rewrite_insert_table_name_with_values() {
508        // A table named `product_values` must not have its column list dropped
509        // by matching the "values" substring inside the name (bug #2).
510        let mut schema = create_test_schema();
511        schema.name = "product_values".to_string();
512
513        let mut rewriter = ValueRewriter::new(Some(1), SqlDialect::MySql, "en".to_string());
514        let stmt = b"INSERT INTO `product_values` (`id`, `email`, `name`) VALUES (1, 'a@b.com', 'Al'), (2, 'c@d.com', 'Bo');";
515        let strategies = vec![StrategyKind::Skip, StrategyKind::Skip, StrategyKind::Skip];
516
517        let (result, _rows, _cols) = rewriter
518            .rewrite_insert(stmt, "product_values", &schema, &strategies)
519            .unwrap();
520        let s = String::from_utf8_lossy(&result);
521
522        assert!(
523            s.contains("(`id`, `email`, `name`)"),
524            "column list dropped: {s}"
525        );
526        // Two data rows, no phantom third row.
527        assert_eq!(s.matches("@").count(), 2, "wrong row count: {s}");
528    }
529
530    #[test]
531    fn test_rewrite_insert_mysql() {
532        let mut rewriter = ValueRewriter::new(Some(42), SqlDialect::MySql, "en".to_string());
533        let schema = create_test_schema();
534
535        let stmt = b"INSERT INTO `users` (`id`, `email`, `name`) VALUES (1, 'alice@example.com', 'Alice');";
536        let strategies = vec![
537            StrategyKind::Skip, // id
538            StrategyKind::Hash {
539                preserve_domain: true,
540            }, // email
541            StrategyKind::Fake {
542                generator: "name".to_string(),
543            }, // name
544        ];
545
546        let (result, rows, cols) = rewriter
547            .rewrite_insert(stmt, "users", &schema, &strategies)
548            .unwrap();
549        let result_str = String::from_utf8_lossy(&result);
550
551        assert!(result_str.contains("INSERT INTO `users`"));
552        assert!(result_str.contains("VALUES"));
553        assert_eq!(rows, 1);
554        assert_eq!(cols, 2); // email and name were redacted
555    }
556
557    #[test]
558    fn test_rewrite_insert_mssql() {
559        let mut rewriter = ValueRewriter::new(Some(42), SqlDialect::Mssql, "en".to_string());
560        let schema = create_test_schema();
561
562        let stmt = b"INSERT INTO [users] ([id], [email], [name]) VALUES (1, N'alice@example.com', N'Alice');";
563        let strategies = vec![
564            StrategyKind::Skip, // id
565            StrategyKind::Null, // email
566            StrategyKind::Skip, // name
567        ];
568
569        let (result, rows, cols) = rewriter
570            .rewrite_insert(stmt, "users", &schema, &strategies)
571            .unwrap();
572        let result_str = String::from_utf8_lossy(&result);
573
574        assert!(result_str.contains("INSERT INTO [users]"));
575        assert!(result_str.contains("NULL")); // email redacted to NULL
576        assert_eq!(rows, 1);
577        assert_eq!(cols, 1);
578    }
579
580    #[test]
581    fn test_format_sql_string_mysql() {
582        let rewriter = ValueRewriter::new(Some(42), SqlDialect::MySql, "en".to_string());
583        assert_eq!(rewriter.format_sql_string("hello"), "'hello'");
584        assert_eq!(rewriter.format_sql_string("it's"), "'it\\'s'");
585        assert_eq!(rewriter.format_sql_string("line\nbreak"), "'line\\nbreak'");
586    }
587
588    #[test]
589    fn test_format_sql_string_postgres() {
590        let rewriter = ValueRewriter::new(Some(42), SqlDialect::Postgres, "en".to_string());
591        assert_eq!(rewriter.format_sql_string("hello"), "'hello'");
592        assert_eq!(rewriter.format_sql_string("it's"), "'it''s'");
593    }
594
595    #[test]
596    fn test_format_sql_string_mssql() {
597        let rewriter = ValueRewriter::new(Some(42), SqlDialect::Mssql, "en".to_string());
598        assert_eq!(rewriter.format_sql_string("hello"), "'hello'");
599        assert_eq!(rewriter.format_sql_string("café"), "N'café'");
600    }
601
602    #[test]
603    fn test_quote_identifier() {
604        let mysql = ValueRewriter::new(None, SqlDialect::MySql, "en".to_string());
605        assert_eq!(mysql.quote_identifier("users"), "`users`");
606
607        let pg = ValueRewriter::new(None, SqlDialect::Postgres, "en".to_string());
608        assert_eq!(pg.quote_identifier("users"), "\"users\"");
609
610        let mssql = ValueRewriter::new(None, SqlDialect::Mssql, "en".to_string());
611        assert_eq!(mssql.quote_identifier("users"), "[users]");
612    }
613}