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        self.reject_unsupported_strategies(strategies)?;
50
51        // Parse the INSERT statement (dialect governs backslash unescaping so
52        // non-MySQL strings aren't corrupted on re-serialization, bug #3)
53        let mut parser = InsertParser::new(stmt)
54            .with_schema(table)
55            .with_dialect(self.dialect)
56            .with_extraction(RowExtraction::ValuesOnly);
57        let rows = parser.parse_rows()?;
58
59        if rows.is_empty() {
60            return Ok((stmt.to_vec(), 0, 0));
61        }
62
63        // Get the column list (if any) from the statement, locating VALUES as a
64        // keyword so a table named like `*values*` doesn't misplace it (bug #2).
65        let column_list = crate::parser::mysql_insert::find_values_keyword_pos(stmt, self.dialect)
66            .and_then(|pos| crate::parser::mysql_insert::extract_column_list_before(stmt, pos));
67
68        // Build the header: INSERT INTO table_name (columns) VALUES
69        let mut result = self.build_insert_header(table_name, &column_list);
70
71        let mut rows_redacted = 0u64;
72        let mut columns_redacted = 0u64;
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 = self.strategy_for_value_column(
87                    table,
88                    column_list.as_deref(),
89                    col_idx,
90                    strategies,
91                );
92
93                // Apply redaction
94                let (redacted_sql, was_redacted) = self.redact_value(value, strategy);
95                result.extend_from_slice(redacted_sql.as_bytes());
96
97                if was_redacted {
98                    columns_redacted += 1;
99                    row_had_redaction = true;
100                }
101            }
102
103            result.extend_from_slice(b")");
104            if row_had_redaction {
105                rows_redacted += 1;
106            }
107        }
108
109        result.extend_from_slice(b";\n");
110
111        Ok((result, rows_redacted, columns_redacted))
112    }
113
114    /// Rewrite a COPY statement with redacted values (PostgreSQL)
115    ///
116    /// Splits the statement into header line and data block, then delegates
117    /// the row redaction loop to [`Self::rewrite_copy_data`].
118    pub fn rewrite_copy(
119        &mut self,
120        stmt: &[u8],
121        _table_name: &str,
122        table: &TableSchema,
123        strategies: &[StrategyKind],
124    ) -> anyhow::Result<(Vec<u8>, u64, u64)> {
125        // COPY statements include the header and data block
126        // Format: COPY table (cols) FROM stdin;\ndata\n\.\n
127
128        // Find the header line (ends with "FROM stdin;" or similar)
129        let header_end = stmt
130            .iter()
131            .position(|&b| b == b'\n')
132            .ok_or_else(|| anyhow::anyhow!("Invalid COPY statement: no newline"))?;
133        let header = &stmt[..header_end];
134        let data_block = &stmt[header_end + 1..];
135
136        // Parse column list from header
137        let columns = parse_copy_columns(&String::from_utf8_lossy(header));
138
139        let (redacted_data, rows_redacted, columns_redacted) =
140            self.rewrite_copy_data(data_block, table, strategies, &columns)?;
141
142        // Build result: header + redacted data (including terminator)
143        let mut result = Vec::with_capacity(header.len() + 1 + redacted_data.len());
144        result.extend_from_slice(header);
145        result.push(b'\n');
146        result.extend_from_slice(&redacted_data);
147
148        Ok((result, rows_redacted, columns_redacted))
149    }
150
151    /// Rewrite just the COPY data block (header handled separately)
152    pub fn rewrite_copy_data(
153        &mut self,
154        data_block: &[u8],
155        table: &TableSchema,
156        strategies: &[StrategyKind],
157        columns: &[String],
158    ) -> anyhow::Result<(Vec<u8>, u64, u64)> {
159        self.reject_unsupported_strategies(strategies)?;
160
161        // Parse data rows
162        let mut parser = CopyParser::new(data_block)
163            .with_schema(table)
164            .with_column_order(columns.to_vec())
165            .with_extraction(RowExtraction::ValuesOnly);
166        let rows = parser.parse_rows()?;
167
168        if rows.is_empty() {
169            return Ok((data_block.to_vec(), 0, 0));
170        }
171
172        // Build result: redacted data + terminator
173        let mut result = Vec::with_capacity(data_block.len());
174
175        let mut rows_redacted = 0u64;
176        let mut columns_redacted = 0u64;
177
178        for row in &rows {
179            let mut row_had_redaction = false;
180            let mut first = true;
181
182            // Parse the raw values from the row
183            let values = self.parse_copy_row_values(&row.raw);
184
185            for (col_idx, value) in values.iter().enumerate() {
186                if !first {
187                    result.push(b'\t');
188                }
189                first = false;
190
191                let strategy =
192                    self.strategy_for_value_column(table, Some(columns), col_idx, strategies);
193                let (redacted, was_redacted) = self.redact_copy_value(value, strategy);
194                result.extend_from_slice(&redacted);
195
196                if was_redacted {
197                    columns_redacted += 1;
198                    row_had_redaction = true;
199                }
200            }
201
202            result.push(b'\n');
203            if row_had_redaction {
204                rows_redacted += 1;
205            }
206        }
207
208        // Add terminator
209        result.extend_from_slice(b"\\.\n");
210
211        Ok((result, rows_redacted, columns_redacted))
212    }
213
214    /// Parse tab-separated values from a COPY row
215    fn parse_copy_row_values(&self, raw: &[u8]) -> Vec<CopyValueRef> {
216        let mut values = Vec::new();
217        let mut start = 0;
218
219        for (i, &b) in raw.iter().enumerate() {
220            if b == b'\t' {
221                values.push(self.parse_single_copy_value(&raw[start..i]));
222                start = i + 1;
223            }
224        }
225        // Last value
226        if start <= raw.len() {
227            values.push(self.parse_single_copy_value(&raw[start..]));
228        }
229
230        values
231    }
232
233    /// Parse a single COPY value
234    fn parse_single_copy_value(&self, raw: &[u8]) -> CopyValueRef {
235        if raw == b"\\N" {
236            CopyValueRef::Null
237        } else {
238            CopyValueRef::Text(raw.to_vec())
239        }
240    }
241
242    /// Redact a COPY value and return the redacted bytes
243    fn redact_copy_value(
244        &mut self,
245        value: &CopyValueRef,
246        strategy: &StrategyKind,
247    ) -> (Vec<u8>, bool) {
248        if matches!(strategy, StrategyKind::Skip) {
249            let bytes = match value {
250                CopyValueRef::Null => b"\\N".to_vec(),
251                CopyValueRef::Text(t) => t.clone(),
252            };
253            return (bytes, false);
254        }
255
256        // Convert to RedactValue
257        let redact_value = match value {
258            CopyValueRef::Null => RedactValue::Null,
259            CopyValueRef::Text(t) => {
260                // Decode escape sequences first (canonical COPY decoder lives
261                // in the parser module)
262                let decoded = decode_copy_escapes(t);
263                RedactValue::String(String::from_utf8_lossy(&decoded).into_owned())
264            }
265        };
266
267        // Apply strategy
268        let result = self.apply_strategy(&redact_value, strategy);
269
270        // Convert back to COPY format
271        let bytes = match result {
272            RedactValue::Null => b"\\N".to_vec(),
273            RedactValue::String(s) => self.encode_copy_escapes(&s),
274            RedactValue::Integer(i) => i.to_string().into_bytes(),
275            RedactValue::Bytes(b) => self.encode_copy_escapes(&String::from_utf8_lossy(&b)),
276        };
277
278        (bytes, true)
279    }
280
281    /// Encode string for COPY format (escape special characters)
282    fn encode_copy_escapes(&self, value: &str) -> Vec<u8> {
283        let mut result = Vec::with_capacity(value.len());
284
285        for b in value.bytes() {
286            match b {
287                b'\n' => result.extend_from_slice(b"\\n"),
288                b'\r' => result.extend_from_slice(b"\\r"),
289                b'\t' => result.extend_from_slice(b"\\t"),
290                b'\\' => result.extend_from_slice(b"\\\\"),
291                _ => result.push(b),
292            }
293        }
294
295        result
296    }
297
298    /// Build INSERT statement header
299    fn build_insert_header(&self, table_name: &str, columns: &Option<Vec<String>>) -> Vec<u8> {
300        let mut result = Vec::new();
301
302        // INSERT INTO table_name
303        result.extend_from_slice(b"INSERT INTO ");
304        result.extend_from_slice(
305            crate::transform_common::quote_ident(self.dialect, table_name).as_bytes(),
306        );
307
308        // Optional column list
309        if let Some(cols) = columns {
310            result.extend_from_slice(b" (");
311            for (i, col) in cols.iter().enumerate() {
312                if i > 0 {
313                    result.extend_from_slice(b", ");
314                }
315                result.extend_from_slice(self.quote_identifier(col).as_bytes());
316            }
317            result.extend_from_slice(b")");
318        }
319
320        result.extend_from_slice(b" VALUES");
321        result
322    }
323
324    /// Quote an identifier based on dialect
325    fn quote_identifier(&self, name: &str) -> String {
326        crate::transform_common::quote_identifier(self.dialect, name)
327    }
328
329    /// Reject strategies that require a whole-input rewrite before any output
330    /// is emitted. This protects direct library callers in addition to config
331    /// validation performed by the CLI.
332    fn reject_unsupported_strategies(&self, strategies: &[StrategyKind]) -> anyhow::Result<()> {
333        if strategies
334            .iter()
335            .any(|strategy| matches!(strategy, StrategyKind::Shuffle))
336        {
337            anyhow::bail!(
338                "The shuffle redaction strategy is not supported because it requires a two-pass rewrite"
339            );
340        }
341        Ok(())
342    }
343
344    /// Resolve the strategy for a value position to its schema column.
345    ///
346    /// Redaction rules are compiled in schema order. INSERT and COPY statements
347    /// can provide a partial or reordered column list, so value position alone
348    /// is not a valid schema-column index.
349    fn strategy_for_value_column<'a>(
350        &self,
351        table: &TableSchema,
352        column_order: Option<&[String]>,
353        value_index: usize,
354        strategies: &'a [StrategyKind],
355    ) -> &'a StrategyKind {
356        let column_name = column_order
357            .and_then(|columns| columns.get(value_index).map(String::as_str))
358            .or_else(|| {
359                table
360                    .columns
361                    .get(value_index)
362                    .map(|column| column.name.as_str())
363            });
364
365        column_name
366            .and_then(|name| table.get_column_id(name))
367            .and_then(|column_id| strategies.get(column_id.0 as usize))
368            .unwrap_or(&StrategyKind::Skip)
369    }
370
371    /// Redact a parsed value and format it for SQL output
372    fn redact_value(&mut self, value: &ParsedValue, strategy: &StrategyKind) -> (String, bool) {
373        // Skip strategy means no redaction
374        if matches!(strategy, StrategyKind::Skip) {
375            return (self.format_value(value), false);
376        }
377
378        // Convert ParsedValue to RedactValue
379        let redact_value = self.parsed_to_redact(value);
380
381        // Apply the strategy
382        let result = self.apply_strategy(&redact_value, strategy);
383
384        // Format the result for SQL
385        (self.format_redact_value(&result), true)
386    }
387
388    /// Convert ParsedValue to RedactValue
389    fn parsed_to_redact(&self, value: &ParsedValue) -> RedactValue {
390        match value {
391            ParsedValue::Null => RedactValue::Null,
392            ParsedValue::Integer(n) => RedactValue::Integer(*n),
393            ParsedValue::BigInteger(n) => RedactValue::Integer(*n as i64), // Potential truncation
394            ParsedValue::String { value } => RedactValue::String(value.clone()),
395            ParsedValue::Hex(bytes) => RedactValue::Bytes(bytes.clone()),
396            ParsedValue::Other(bytes) => {
397                RedactValue::String(String::from_utf8_lossy(bytes).into_owned())
398            }
399        }
400    }
401
402    /// Apply a redaction strategy to a value
403    fn apply_strategy(&mut self, value: &RedactValue, strategy: &StrategyKind) -> RedactValue {
404        match strategy {
405            StrategyKind::Null => NullStrategy::new().apply(value, &mut self.rng),
406            StrategyKind::Constant { value: constant } => {
407                ConstantStrategy::new(constant.clone()).apply(value, &mut self.rng)
408            }
409            StrategyKind::Hash { preserve_domain } => {
410                HashStrategy::new(*preserve_domain).apply(value, &mut self.rng)
411            }
412            StrategyKind::Mask { pattern } => {
413                MaskStrategy::new(pattern.clone()).apply(value, &mut self.rng)
414            }
415            StrategyKind::Fake { generator } => {
416                FakeStrategy::new(generator.clone(), self.locale.clone())
417                    .apply(value, &mut self.rng)
418            }
419            StrategyKind::Shuffle => {
420                // Shuffle is special - needs column-level state
421                // For now, treat as skip (shuffle implemented at higher level)
422                value.clone()
423            }
424            StrategyKind::Skip => value.clone(),
425        }
426    }
427
428    /// Format a ParsedValue for SQL output
429    fn format_value(&self, value: &ParsedValue) -> String {
430        match value {
431            ParsedValue::Null => "NULL".to_string(),
432            ParsedValue::Integer(n) => n.to_string(),
433            ParsedValue::BigInteger(n) => n.to_string(),
434            ParsedValue::String { value } => self.format_sql_string(value),
435            ParsedValue::Hex(bytes) => String::from_utf8_lossy(bytes).into_owned(),
436            ParsedValue::Other(bytes) => String::from_utf8_lossy(bytes).into_owned(),
437        }
438    }
439
440    /// Format a RedactValue for SQL output
441    fn format_redact_value(&self, value: &RedactValue) -> String {
442        match value {
443            RedactValue::Null => "NULL".to_string(),
444            RedactValue::Integer(n) => n.to_string(),
445            RedactValue::String(s) => self.format_sql_string(s),
446            RedactValue::Bytes(b) => {
447                // Format as hex literal
448                format!("0x{}", hex::encode(b))
449            }
450        }
451    }
452
453    /// Format a string for SQL with proper escaping based on dialect
454    fn format_sql_string(&self, value: &str) -> String {
455        match self.dialect {
456            SqlDialect::MySql => {
457                // MySQL uses backslash escaping
458                let escaped = value
459                    .replace('\\', "\\\\")
460                    .replace('\'', "\\'")
461                    .replace('\n', "\\n")
462                    .replace('\r', "\\r")
463                    .replace('\t', "\\t")
464                    .replace('\0', "\\0");
465                format!("'{}'", escaped)
466            }
467            SqlDialect::Postgres | SqlDialect::Sqlite => {
468                // PostgreSQL/SQLite use doubled single quotes
469                let escaped = value.replace('\'', "''");
470                format!("'{}'", escaped)
471            }
472            SqlDialect::Mssql => {
473                // MSSQL uses N'...' for Unicode strings with doubled quotes
474                let escaped = value.replace('\'', "''");
475                // Use N'...' for non-ASCII or always for safety
476                if value.bytes().any(|b| b > 127) {
477                    format!("N'{}'", escaped)
478                } else {
479                    format!("'{}'", escaped)
480                }
481            }
482        }
483    }
484}
485
486/// Internal COPY value representation
487enum CopyValueRef {
488    Null,
489    Text(Vec<u8>),
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495    use crate::schema::{Column, ColumnId, ColumnType, TableId, TableSchema};
496
497    fn create_test_schema() -> TableSchema {
498        TableSchema {
499            name: "users".to_string(),
500            id: TableId(0),
501            columns: vec![
502                Column {
503                    name: "id".to_string(),
504                    col_type: ColumnType::Int,
505                    source_type: "INT".to_string(),
506                    ordinal: ColumnId(0),
507                    is_primary_key: true,
508                    is_nullable: false,
509                    is_unique: false,
510                    default_sql: None,
511                    is_generated: false,
512                    is_identity: false,
513                    collation: None,
514                },
515                Column {
516                    name: "email".to_string(),
517                    col_type: ColumnType::Text,
518                    source_type: "VARCHAR(255)".to_string(),
519                    ordinal: ColumnId(1),
520                    is_primary_key: false,
521                    is_nullable: false,
522                    is_unique: false,
523                    default_sql: None,
524                    is_generated: false,
525                    is_identity: false,
526                    collation: None,
527                },
528                Column {
529                    name: "name".to_string(),
530                    col_type: ColumnType::Text,
531                    source_type: "VARCHAR(255)".to_string(),
532                    ordinal: ColumnId(2),
533                    is_primary_key: false,
534                    is_nullable: true,
535                    is_unique: false,
536                    default_sql: None,
537                    is_generated: false,
538                    is_identity: false,
539                    collation: None,
540                },
541            ],
542            primary_key: vec![ColumnId(0)],
543            foreign_keys: vec![],
544            unique_constraints: vec![],
545            check_constraints: vec![],
546            indexes: vec![],
547            create_statement: None,
548        }
549    }
550
551    #[test]
552    fn test_rewrite_insert_table_name_with_values() {
553        // A table named `product_values` must not have its column list dropped
554        // by matching the "values" substring inside the name (bug #2).
555        let mut schema = create_test_schema();
556        schema.name = "product_values".to_string();
557
558        let mut rewriter = ValueRewriter::new(Some(1), SqlDialect::MySql, "en".to_string());
559        let stmt = b"INSERT INTO `product_values` (`id`, `email`, `name`) VALUES (1, 'a@b.com', 'Al'), (2, 'c@d.com', 'Bo');";
560        let strategies = vec![StrategyKind::Skip, StrategyKind::Skip, StrategyKind::Skip];
561
562        let (result, _rows, _cols) = rewriter
563            .rewrite_insert(stmt, "product_values", &schema, &strategies)
564            .unwrap();
565        let s = String::from_utf8_lossy(&result);
566
567        assert!(
568            s.contains("(`id`, `email`, `name`)"),
569            "column list dropped: {s}"
570        );
571        // Two data rows, no phantom third row.
572        assert_eq!(s.matches("@").count(), 2, "wrong row count: {s}");
573    }
574
575    #[test]
576    fn rewrite_insert_keeps_qualified_table_components_separate() {
577        let mut rewriter = ValueRewriter::new(Some(42), SqlDialect::Postgres, "en".to_string());
578        let schema = create_test_schema();
579        let (result, _, _) = rewriter
580            .rewrite_insert(
581                b"INSERT INTO users (id, email, name) VALUES (1, 'a@example.com', 'Alice');",
582                "tenant_a.users",
583                &schema,
584                &[StrategyKind::Skip, StrategyKind::Skip, StrategyKind::Skip],
585            )
586            .unwrap();
587
588        assert!(String::from_utf8(result)
589            .unwrap()
590            .starts_with("INSERT INTO \"tenant_a\".\"users\""));
591    }
592
593    #[test]
594    fn test_rewrite_insert_mysql() {
595        let mut rewriter = ValueRewriter::new(Some(42), SqlDialect::MySql, "en".to_string());
596        let schema = create_test_schema();
597
598        let stmt = b"INSERT INTO `users` (`id`, `email`, `name`) VALUES (1, 'alice@example.com', 'Alice');";
599        let strategies = vec![
600            StrategyKind::Skip, // id
601            StrategyKind::Hash {
602                preserve_domain: true,
603            }, // email
604            StrategyKind::Fake {
605                generator: "name".to_string(),
606            }, // name
607        ];
608
609        let (result, rows, cols) = rewriter
610            .rewrite_insert(stmt, "users", &schema, &strategies)
611            .unwrap();
612        let result_str = String::from_utf8_lossy(&result);
613
614        assert!(result_str.contains("INSERT INTO `users`"));
615        assert!(result_str.contains("VALUES"));
616        assert_eq!(rows, 1);
617        assert_eq!(cols, 2); // email and name were redacted
618    }
619
620    #[test]
621    fn reordered_insert_columns_use_schema_strategies() {
622        let mut rewriter = ValueRewriter::new(Some(42), SqlDialect::MySql, "en".to_string());
623        let schema = create_test_schema();
624        let stmt = b"INSERT INTO `users` (`name`, `email`, `id`) VALUES ('Alice', 'alice@example.com', 1);";
625        let strategies = vec![StrategyKind::Skip, StrategyKind::Null, StrategyKind::Skip];
626
627        let (result, rows, columns) = rewriter
628            .rewrite_insert(stmt, "users", &schema, &strategies)
629            .unwrap();
630        let result = String::from_utf8(result).unwrap();
631
632        assert!(
633            result.contains("('Alice', NULL, 1)"),
634            "unexpected output: {result}"
635        );
636        assert!(!result.contains("alice@example.com"));
637        assert_eq!(rows, 1);
638        assert_eq!(columns, 1);
639    }
640
641    #[test]
642    fn reordered_copy_columns_use_schema_strategies() {
643        let mut rewriter = ValueRewriter::new(Some(42), SqlDialect::Postgres, "en".to_string());
644        let schema = create_test_schema();
645        let strategies = vec![StrategyKind::Skip, StrategyKind::Null, StrategyKind::Skip];
646
647        let (result, rows, columns) = rewriter
648            .rewrite_copy_data(
649                b"Alice\talice@example.com\t1\n\\.\n",
650                &schema,
651                &strategies,
652                &["name".to_string(), "email".to_string(), "id".to_string()],
653            )
654            .unwrap();
655        let result = String::from_utf8(result).unwrap();
656
657        assert_eq!(result, "Alice\t\\N\t1\n\\.\n");
658        assert_eq!(rows, 1);
659        assert_eq!(columns, 1);
660    }
661
662    #[test]
663    fn shuffle_is_rejected_for_direct_library_calls() {
664        let mut rewriter = ValueRewriter::new(Some(42), SqlDialect::MySql, "en".to_string());
665        let schema = create_test_schema();
666
667        let error = rewriter
668            .rewrite_insert(
669                b"INSERT INTO users VALUES (1, 'alice@example.com', 'Alice');",
670                "users",
671                &schema,
672                &[
673                    StrategyKind::Skip,
674                    StrategyKind::Shuffle,
675                    StrategyKind::Skip,
676                ],
677            )
678            .expect_err("shuffle must not silently preserve a direct caller's source value");
679
680        assert_eq!(
681            error.to_string(),
682            "The shuffle redaction strategy is not supported because it requires a two-pass rewrite"
683        );
684    }
685
686    #[test]
687    fn test_rewrite_insert_mssql() {
688        let mut rewriter = ValueRewriter::new(Some(42), SqlDialect::Mssql, "en".to_string());
689        let schema = create_test_schema();
690
691        let stmt = b"INSERT INTO [users] ([id], [email], [name]) VALUES (1, N'alice@example.com', N'Alice');";
692        let strategies = vec![
693            StrategyKind::Skip, // id
694            StrategyKind::Null, // email
695            StrategyKind::Skip, // name
696        ];
697
698        let (result, rows, cols) = rewriter
699            .rewrite_insert(stmt, "users", &schema, &strategies)
700            .unwrap();
701        let result_str = String::from_utf8_lossy(&result);
702
703        assert!(result_str.contains("INSERT INTO [users]"));
704        assert!(result_str.contains("NULL")); // email redacted to NULL
705        assert_eq!(rows, 1);
706        assert_eq!(cols, 1);
707    }
708
709    #[test]
710    fn test_format_sql_string_mysql() {
711        let rewriter = ValueRewriter::new(Some(42), SqlDialect::MySql, "en".to_string());
712        assert_eq!(rewriter.format_sql_string("hello"), "'hello'");
713        assert_eq!(rewriter.format_sql_string("it's"), "'it\\'s'");
714        assert_eq!(rewriter.format_sql_string("line\nbreak"), "'line\\nbreak'");
715    }
716
717    #[test]
718    fn test_format_sql_string_postgres() {
719        let rewriter = ValueRewriter::new(Some(42), SqlDialect::Postgres, "en".to_string());
720        assert_eq!(rewriter.format_sql_string("hello"), "'hello'");
721        assert_eq!(rewriter.format_sql_string("it's"), "'it''s'");
722    }
723
724    #[test]
725    fn test_format_sql_string_mssql() {
726        let rewriter = ValueRewriter::new(Some(42), SqlDialect::Mssql, "en".to_string());
727        assert_eq!(rewriter.format_sql_string("hello"), "'hello'");
728        assert_eq!(rewriter.format_sql_string("café"), "N'café'");
729    }
730
731    #[test]
732    fn test_quote_identifier() {
733        let mysql = ValueRewriter::new(None, SqlDialect::MySql, "en".to_string());
734        assert_eq!(mysql.quote_identifier("users"), "`users`");
735
736        let pg = ValueRewriter::new(None, SqlDialect::Postgres, "en".to_string());
737        assert_eq!(pg.quote_identifier("users"), "\"users\"");
738
739        let mssql = ValueRewriter::new(None, SqlDialect::Mssql, "en".to_string());
740        assert_eq!(mssql.quote_identifier("users"), "[users]");
741    }
742}