Skip to main content

sql_splitter/
transform_common.rs

1//! Shared plumbing for the row-level transform commands (`sample`, `shard`).
2//!
3//! Both commands follow the same pipeline: split the dump into per-table temp
4//! files, build a schema graph, walk each table's data rows, spill selected
5//! rows to disk, then synthesize a single SQL output file. This module owns
6//! the pieces that were previously duplicated between the two commands:
7//!
8//! - [`UnifiedRow`] / [`RowFormat`]: dialect-agnostic row representation
9//! - [`for_each_data_row`]: the INSERT/COPY statement walker
10//! - [`RowSpillWriter`] / [`RowSpillReader`]: bounded-memory row spilling
11//! - [`split_to_temp_tables`] / [`build_schema_graph`]: pipeline phases 0-1
12//! - [`write_dialect_header`] / [`write_dialect_footer`] / [`quote_ident`]:
13//!   session preamble and identifier quoting
14//! - [`convert_copy_to_insert_values`]: COPY-row to INSERT-VALUES conversion
15
16use crate::parser::mysql_insert::{
17    parse_insert_tuple, FkRef, InsertRowContext, ParsedRow, PkTuple, PkValue, RowExtraction,
18};
19use crate::parser::postgres_copy::{parse_copy_columns, CopyParser, ParsedCopyRow};
20use crate::parser::{ContentFilter, Parser, ParserEvent, SqlDialect};
21use crate::schema::{SchemaBuilder, SchemaGraph, TableSchema};
22use crate::splitter::{Splitter, Stats as SplitStats};
23use indicatif::{ProgressBar, ProgressStyle};
24use std::fs::{self, File};
25use std::io::{self, BufReader, BufWriter, Read, Write};
26use std::path::{Path, PathBuf};
27use tempfile::TempDir;
28
29/// Row format indicator for spilled/converted rows.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum RowFormat {
32    /// MySQL-style `(v1, v2, ...)` value list from an INSERT statement.
33    Insert,
34    /// PostgreSQL COPY tab-separated row.
35    Copy,
36}
37
38impl RowFormat {
39    fn tag(self) -> u8 {
40        match self {
41            RowFormat::Insert => 0,
42            RowFormat::Copy => 1,
43        }
44    }
45
46    fn from_tag(tag: u8) -> Self {
47        if tag == 0 {
48            RowFormat::Insert
49        } else {
50            RowFormat::Copy
51        }
52    }
53}
54
55/// Combined row representation for both MySQL INSERT and PostgreSQL COPY.
56pub enum UnifiedRow {
57    Insert(ParsedRow),
58    Copy(ParsedCopyRow),
59}
60
61impl UnifiedRow {
62    pub fn pk(&self) -> Option<&PkTuple> {
63        match self {
64            UnifiedRow::Insert(r) => r.pk.as_ref(),
65            UnifiedRow::Copy(r) => r.pk.as_ref(),
66        }
67    }
68
69    pub fn fk_values(&self) -> &[(FkRef, PkTuple)] {
70        match self {
71            UnifiedRow::Insert(r) => &r.fk_values,
72            UnifiedRow::Copy(r) => &r.fk_values,
73        }
74    }
75
76    /// Get the value for a specific schema column index (requires
77    /// [`RowExtraction::Full`] parsing).
78    pub fn get_column_value(&self, idx: usize) -> Option<&PkValue> {
79        match self {
80            UnifiedRow::Insert(r) => r.get_column_value(idx),
81            UnifiedRow::Copy(r) => r.get_column_value(idx),
82        }
83    }
84
85    pub fn format(&self) -> RowFormat {
86        match self {
87            UnifiedRow::Insert(_) => RowFormat::Insert,
88            UnifiedRow::Copy(_) => RowFormat::Copy,
89        }
90    }
91
92    pub fn raw(&self) -> &[u8] {
93        match self {
94            UnifiedRow::Insert(r) => &r.raw,
95            UnifiedRow::Copy(r) => &r.raw,
96        }
97    }
98}
99
100// The row/event control-flow signal now lives in the parser layer so the
101// streaming row visitors and `Parser::visit_events` can share it; re-exported
102// here so the sample/shard consumers keep their existing import path.
103pub use crate::parser::RowFlow;
104
105/// Returns true if `stmt` is a PostgreSQL COPY data block (ends with the
106/// `\.` terminator).
107pub fn is_copy_data_block(stmt: &[u8]) -> bool {
108    stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n")
109}
110
111/// Walk every data row of a per-table SQL file, invoking `f` for each row.
112///
113/// Handles the INSERT/COPY-header/COPY-data statement dispatch (including
114/// tracking the COPY column order across statements) that was previously
115/// hand-rolled in every sampling/sharding loop.
116pub fn for_each_data_row<F>(
117    table_file: &Path,
118    table_schema: &TableSchema,
119    dialect: SqlDialect,
120    extraction: RowExtraction,
121    mut f: F,
122) -> anyhow::Result<()>
123where
124    F: FnMut(UnifiedRow) -> anyhow::Result<RowFlow>,
125{
126    let file = File::open(table_file)?;
127    let mut parser = Parser::with_dialect(file, 64 * 1024, dialect);
128
129    // Per-statement/block context, rebuilt lazily as headers arrive so each
130    // streamed row is parsed with the same column mapping the collecting parser
131    // would have used — but only the current row is ever materialized.
132    let mut insert_ctx: Option<InsertRowContext> = None;
133    let mut copy_ctx: Option<(CopyParser<'_>, bool)> = None;
134
135    parser.visit_events(|event| match event {
136        // DDL/control statements carry no data rows here.
137        ParserEvent::Statement(_) => Ok(RowFlow::Continue),
138        ParserEvent::InsertRow {
139            header,
140            row,
141            first_in_statement,
142        } => {
143            if first_in_statement || insert_ctx.is_none() {
144                insert_ctx = Some(InsertRowContext::from_header(header, table_schema, dialect));
145            }
146            let ctx = insert_ctx.as_ref().expect("insert_ctx set above");
147            match parse_insert_tuple(row, table_schema, ctx, dialect, extraction) {
148                Some(parsed) => f(UnifiedRow::Insert(parsed)),
149                None => Ok(RowFlow::Continue),
150            }
151        }
152        ParserEvent::CopyStart(header) => {
153            let columns = parse_copy_columns(&String::from_utf8_lossy(header));
154            let (parser, empty_line_is_row) = CopyParser::new(&[])
155                .with_schema(table_schema)
156                .with_column_order(columns)
157                .with_extraction(extraction)
158                .prepared();
159            copy_ctx = Some((parser, empty_line_is_row));
160            Ok(RowFlow::Continue)
161        }
162        ParserEvent::CopyRow(line) => match copy_ctx.as_ref() {
163            Some((cp, empty_line_is_row)) => match cp.parse_line(line, *empty_line_is_row) {
164                Some(parsed) => f(UnifiedRow::Copy(parsed)),
165                None => Ok(RowFlow::Continue),
166            },
167            None => Ok(RowFlow::Continue),
168        },
169        ParserEvent::CopyEnd => Ok(RowFlow::Continue),
170    })
171}
172
173/// Writer for spilling selected rows to a temp file with bounded memory.
174///
175/// Record format: 1-byte format tag, 4-byte little-endian length, raw row
176/// bytes. Length-prefixed so rows containing newlines or non-UTF-8 bytes
177/// round-trip exactly.
178pub struct RowSpillWriter {
179    writer: BufWriter<File>,
180}
181
182impl RowSpillWriter {
183    pub fn create(path: &Path) -> io::Result<Self> {
184        Ok(Self {
185            writer: BufWriter::new(File::create(path)?),
186        })
187    }
188
189    pub fn write_row(&mut self, format: RowFormat, raw: &[u8]) -> io::Result<()> {
190        self.writer.write_all(&[format.tag()])?;
191        self.writer.write_all(&(raw.len() as u32).to_le_bytes())?;
192        self.writer.write_all(raw)
193    }
194
195    pub fn finish(mut self) -> io::Result<()> {
196        self.writer.flush()
197    }
198}
199
200/// Reader for row spill files written by [`RowSpillWriter`].
201pub struct RowSpillReader {
202    reader: BufReader<File>,
203}
204
205impl RowSpillReader {
206    pub fn open(path: &Path) -> io::Result<Self> {
207        Ok(Self {
208            reader: BufReader::new(File::open(path)?),
209        })
210    }
211
212    /// Read the next spilled row, or `None` at end of file.
213    pub fn next_row(&mut self) -> io::Result<Option<(RowFormat, Vec<u8>)>> {
214        let mut tag = [0u8; 1];
215        match self.reader.read_exact(&mut tag) {
216            Ok(()) => {}
217            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
218            Err(e) => return Err(e),
219        }
220        let mut len_buf = [0u8; 4];
221        self.reader.read_exact(&mut len_buf)?;
222        let len = u32::from_le_bytes(len_buf) as usize;
223        let mut raw = vec![0u8; len];
224        self.reader.read_exact(&mut raw)?;
225        Ok(Some((RowFormat::from_tag(tag[0]), raw)))
226    }
227}
228
229/// Result of the phase-0 split into per-table temp files.
230pub struct SplitPhase {
231    /// Owns the temp directory; dropped when the pipeline finishes.
232    pub temp_dir: TempDir,
233    /// Directory containing the per-table `.sql` files.
234    pub tables_dir: PathBuf,
235    /// Statistics from the split.
236    pub stats: SplitStats,
237}
238
239/// Phase 0 shared by sample/shard: split the input dump into per-table temp
240/// files, with an optional byte-based progress bar.
241pub fn split_to_temp_tables(
242    input: &Path,
243    dialect: SqlDialect,
244    progress: bool,
245) -> anyhow::Result<SplitPhase> {
246    // Get file size for progress tracking
247    let file_size = std::fs::metadata(input)?.len();
248
249    // Progress bar setup - byte-based for the split phase
250    let progress_bar = if progress {
251        let pb = ProgressBar::new(file_size);
252        pb.set_style(
253            ProgressStyle::with_template(
254                "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
255            )
256            .unwrap()
257            .progress_chars("█▓▒░  ")
258            .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
259        );
260        pb.enable_steady_tick(std::time::Duration::from_millis(100));
261        pb.set_message("Splitting dump...");
262        Some(pb)
263    } else {
264        None
265    };
266
267    let temp_dir = TempDir::new()?;
268    let tables_dir = temp_dir.path().join("tables");
269
270    let mut splitter = Splitter::new(input.to_path_buf(), tables_dir.clone())
271        .with_dialect(dialect)
272        .with_content_filter(ContentFilter::All);
273
274    if let Some(ref pb) = progress_bar {
275        let pb_clone = pb.clone();
276        splitter = splitter.with_progress(move |bytes| {
277            pb_clone.set_position(bytes);
278        });
279    }
280
281    let stats = splitter.split()?;
282
283    // Finish byte-based progress, switch to milestone messages
284    if let Some(ref pb) = progress_bar {
285        pb.finish_and_clear();
286    }
287
288    if progress {
289        eprintln!(
290            "Split complete: {} tables, {} statements",
291            stats.tables_found, stats.statements_processed
292        );
293    }
294
295    Ok(SplitPhase {
296        temp_dir,
297        tables_dir,
298        stats,
299    })
300}
301
302/// Build a schema graph from a directory of split per-table files.
303pub fn build_schema_graph(tables_dir: &Path, dialect: SqlDialect) -> anyhow::Result<SchemaGraph> {
304    let mut builder = SchemaBuilder::new();
305
306    for entry in fs::read_dir(tables_dir)? {
307        let entry = entry?;
308        let path = entry.path();
309
310        if path.extension().is_some_and(|e| e == "sql") {
311            let file = File::open(&path)?;
312            let mut parser = Parser::with_dialect(file, 64 * 1024, dialect);
313
314            while let Some(stmt) = parser.read_statement()? {
315                builder.ingest_statement(&stmt, dialect);
316            }
317        }
318    }
319
320    Ok(SchemaGraph::from_schema(builder.build()))
321}
322
323/// Quote a possibly schema-qualified table identifier for the given dialect.
324pub fn quote_ident(dialect: SqlDialect, name: &str) -> String {
325    // Table identities are canonical dotted names. Quote each identifier part
326    // separately: quoting `tenant.users` as one identifier changes it from a
327    // schema-qualified table reference into a table literally named
328    // `tenant.users`.
329    split_qualified_identifier(name)
330        .unwrap_or_else(|| vec![name.to_string()])
331        .iter()
332        .map(|part| quote_identifier_part(dialect, part))
333        .collect::<Vec<_>>()
334        .join(".")
335}
336
337/// Quote exactly one identifier component for the given dialect.
338///
339/// Use this for column, index, and constraint names. In contrast to
340/// [`quote_ident`], dots are literal characters here rather than schema
341/// separators.
342pub fn quote_identifier(dialect: SqlDialect, name: &str) -> String {
343    quote_identifier_part(dialect, name)
344}
345
346/// Split the dotted table identity while preserving a quoted component that
347/// contains a literal dot, such as `public."user.log"`.
348fn split_qualified_identifier(name: &str) -> Option<Vec<String>> {
349    let bytes = name.as_bytes();
350    let mut i = 0;
351    let mut parts = Vec::new();
352
353    while i < bytes.len() {
354        let mut part = Vec::new();
355        if bytes[i] == b'"' {
356            i += 1;
357            let mut terminated = false;
358            while i < bytes.len() {
359                if bytes[i] == b'"' {
360                    if bytes.get(i + 1) == Some(&b'"') {
361                        part.push(b'"');
362                        i += 2;
363                        continue;
364                    }
365                    i += 1;
366                    terminated = true;
367                    break;
368                }
369                part.push(bytes[i]);
370                i += 1;
371            }
372            if !terminated {
373                return None;
374            }
375        } else {
376            while i < bytes.len() && bytes[i] != b'.' {
377                part.push(bytes[i]);
378                i += 1;
379            }
380        }
381
382        if part.is_empty() {
383            return None;
384        }
385        parts.push(String::from_utf8_lossy(&part).into_owned());
386
387        if i == bytes.len() {
388            return Some(parts);
389        }
390        if bytes[i] != b'.' {
391            return None;
392        }
393        i += 1;
394    }
395
396    None
397}
398
399fn quote_identifier_part(dialect: SqlDialect, name: &str) -> String {
400    // Double any occurrence of the closing delimiter so an identifier can never
401    // terminate its own quoting early (malformed / injectable SQL otherwise).
402    match dialect {
403        SqlDialect::MySql => format!("`{}`", name.replace('`', "``")),
404        SqlDialect::Postgres | SqlDialect::Sqlite => {
405            format!("\"{}\"", name.replace('"', "\"\""))
406        }
407        SqlDialect::Mssql => format!("[{}]", name.replace(']', "]]")),
408    }
409}
410
411/// Write the dialect-specific session header (FK checks off, encoding, etc.).
412pub fn write_dialect_header<W: Write>(writer: &mut W, dialect: SqlDialect) -> io::Result<()> {
413    match dialect {
414        SqlDialect::MySql => {
415            writeln!(writer, "SET NAMES utf8mb4;")?;
416            writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
417        }
418        SqlDialect::Postgres => {
419            writeln!(writer, "SET client_encoding = 'UTF8';")?;
420            writeln!(writer, "SET session_replication_role = replica;")?;
421        }
422        SqlDialect::Sqlite => {
423            writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
424        }
425        SqlDialect::Mssql => {
426            writeln!(writer, "SET ANSI_NULLS ON;")?;
427            writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
428            writeln!(writer, "SET NOCOUNT ON;")?;
429        }
430    }
431    writeln!(writer)?;
432    Ok(())
433}
434
435/// Write the dialect-specific session footer (restores header settings).
436pub fn write_dialect_footer<W: Write>(writer: &mut W, dialect: SqlDialect) -> io::Result<()> {
437    writeln!(writer)?;
438    match dialect {
439        SqlDialect::MySql => {
440            writeln!(writer, "SET FOREIGN_KEY_CHECKS = 1;")?;
441        }
442        SqlDialect::Postgres => {
443            writeln!(writer, "SET session_replication_role = DEFAULT;")?;
444        }
445        SqlDialect::Sqlite => {
446            writeln!(writer, "PRAGMA foreign_keys = ON;")?;
447        }
448        SqlDialect::Mssql => {
449            // No footer needed
450        }
451    }
452    Ok(())
453}
454
455/// Write a chunk of spilled rows as a single multi-row INSERT statement.
456pub fn write_insert_chunk<W: Write>(
457    writer: &mut W,
458    quoted_name: &str,
459    chunk: &[(RowFormat, Vec<u8>)],
460    dialect: SqlDialect,
461) -> io::Result<()> {
462    writeln!(writer, "INSERT INTO {} VALUES", quoted_name)?;
463
464    for (i, (format, row_bytes)) in chunk.iter().enumerate() {
465        if i > 0 {
466            writer.write_all(b",\n")?;
467        }
468
469        let values = match format {
470            // A RowFormat::Insert row was captured verbatim from an input
471            // INSERT in this same dialect (sample/shard never cross-convert
472            // dialects), so it is re-emitted as-is. Rewriting escapes here — e.g.
473            // \' -> '' — corrupts native literals such as a value ending in a
474            // backslash.
475            RowFormat::Insert => row_bytes.clone(),
476            RowFormat::Copy => convert_copy_to_insert_values(row_bytes, dialect),
477        };
478        writer.write_all(&values)?;
479    }
480
481    writer.write_all(b";\n")?;
482    Ok(())
483}
484
485/// Convert PostgreSQL COPY format (tab-separated) to INSERT VALUES format.
486pub fn convert_copy_to_insert_values(row: &[u8], dialect: SqlDialect) -> Vec<u8> {
487    let mut result = Vec::with_capacity(row.len() + 20);
488    result.push(b'(');
489
490    let fields: Vec<&[u8]> = row.split(|&b| b == b'\t').collect();
491
492    for (i, field) in fields.iter().enumerate() {
493        if i > 0 {
494            result.extend_from_slice(b", ");
495        }
496
497        // Check for NULL marker
498        if *field == b"\\N" {
499            result.extend_from_slice(b"NULL");
500        } else if field.is_empty() {
501            result.extend_from_slice(b"''");
502        } else if is_numeric(field) {
503            // Numeric value - no quotes needed
504            result.extend_from_slice(field);
505        } else {
506            // Decode the COPY text-format escapes (\n \t \\ …) to the real
507            // bytes first, then re-escape for the target dialect's string
508            // literal. Emitting the raw COPY bytes here would leave `\n` as the
509            // two characters backslash+n (and MySQL would double the backslash
510            // into `\\n`), corrupting embedded newlines/tabs/backslashes.
511            let decoded = decode_copy_escapes(field);
512            result.push(b'\'');
513            for &b in &decoded {
514                match b {
515                    b'\'' => {
516                        // Escape single quote
517                        match dialect {
518                            SqlDialect::MySql => result.extend_from_slice(b"\\'"),
519                            SqlDialect::Postgres | SqlDialect::Sqlite | SqlDialect::Mssql => {
520                                result.extend_from_slice(b"''")
521                            }
522                        }
523                    }
524                    b'\\' if dialect == SqlDialect::MySql => {
525                        // Escape backslash in MySQL
526                        result.extend_from_slice(b"\\\\");
527                    }
528                    _ => result.push(b),
529                }
530            }
531            result.push(b'\'');
532        }
533    }
534
535    result.push(b')');
536    result
537}
538
539/// Decode PostgreSQL COPY text-format escape sequences in one field to the
540/// bytes they represent. Mirrors the decoder in `convert::copy_to_insert` but
541/// stays byte-oriented so binary/`bytea` data survives the round-trip.
542fn decode_copy_escapes(field: &[u8]) -> Vec<u8> {
543    // Fast path: no escapes at all -> the field is already the raw bytes.
544    if !field.contains(&b'\\') {
545        return field.to_vec();
546    }
547
548    let mut out = Vec::with_capacity(field.len());
549    let mut i = 0;
550    while i < field.len() {
551        if field[i] == b'\\' && i + 1 < field.len() {
552            let next = field[i + 1];
553            match next {
554                b'n' => out.push(b'\n'),
555                b'r' => out.push(b'\r'),
556                b't' => out.push(b'\t'),
557                b'\\' => out.push(b'\\'),
558                b'b' => out.push(0x08),
559                b'f' => out.push(0x0C),
560                b'v' => out.push(0x0B),
561                _ if next.is_ascii_digit() => {
562                    // Octal escape (\NNN, up to 3 digits).
563                    let mut val = 0u8;
564                    let mut consumed = 0;
565                    for j in 0..3 {
566                        match field.get(i + 1 + j) {
567                            Some(&d @ b'0'..=b'7') => {
568                                val = val.wrapping_mul(8).wrapping_add(d - b'0');
569                                consumed += 1;
570                            }
571                            _ => break,
572                        }
573                    }
574                    if consumed > 0 {
575                        out.push(val);
576                        i += 1 + consumed;
577                        continue;
578                    }
579                    // Not actually octal: keep the backslash and the byte.
580                    out.push(b'\\');
581                    out.push(next);
582                }
583                // Unknown escape: keep the backslash and the following byte.
584                _ => {
585                    out.push(b'\\');
586                    out.push(next);
587                }
588            }
589            i += 2;
590        } else {
591            out.push(field[i]);
592            i += 1;
593        }
594    }
595    out
596}
597
598/// Check if a byte slice represents a numeric value.
599pub fn is_numeric(s: &[u8]) -> bool {
600    if s.is_empty() {
601        return false;
602    }
603
604    let mut has_digit = false;
605    let mut has_dot = false;
606    let mut start = 0;
607
608    // Handle leading sign
609    if s[0] == b'-' || s[0] == b'+' {
610        start = 1;
611    }
612
613    for &b in &s[start..] {
614        match b {
615            b'0'..=b'9' => has_digit = true,
616            b'.' if !has_dot => has_dot = true,
617            b'e' | b'E' => {
618                // Scientific notation - just check rest is digits
619                continue;
620            }
621            _ => return false,
622        }
623    }
624
625    has_digit
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631
632    #[test]
633    fn spill_roundtrip_preserves_newlines_and_binary() {
634        let dir = tempfile::tempdir().unwrap();
635        let path = dir.path().join("t.rows");
636
637        let rows: Vec<(RowFormat, Vec<u8>)> = vec![
638            (RowFormat::Insert, b"(1, 'a\nb')".to_vec()),
639            (RowFormat::Copy, vec![0xFF, 0xFE, b'\t', b'x', b'\n']),
640            (RowFormat::Insert, Vec::new()),
641        ];
642
643        let mut w = RowSpillWriter::create(&path).unwrap();
644        for (f, raw) in &rows {
645            w.write_row(*f, raw).unwrap();
646        }
647        w.finish().unwrap();
648
649        let mut r = RowSpillReader::open(&path).unwrap();
650        for (f, raw) in &rows {
651            let (rf, rraw) = r.next_row().unwrap().unwrap();
652            assert_eq!(rf, *f);
653            assert_eq!(&rraw, raw);
654        }
655        assert!(r.next_row().unwrap().is_none());
656    }
657
658    #[test]
659    fn quote_ident_per_dialect() {
660        assert_eq!(quote_ident(SqlDialect::MySql, "t"), "`t`");
661        assert_eq!(quote_ident(SqlDialect::Postgres, "t"), "\"t\"");
662        assert_eq!(quote_ident(SqlDialect::Sqlite, "t"), "\"t\"");
663        assert_eq!(quote_ident(SqlDialect::Mssql, "t"), "[t]");
664    }
665
666    #[test]
667    fn quote_ident_keeps_qualified_table_parts_separate() {
668        assert_eq!(
669            quote_ident(SqlDialect::Postgres, "tenant_a.users"),
670            "\"tenant_a\".\"users\""
671        );
672        assert_eq!(
673            quote_ident(SqlDialect::MySql, "tenant_a.users"),
674            "`tenant_a`.`users`"
675        );
676        assert_eq!(quote_ident(SqlDialect::Mssql, "dbo.users"), "[dbo].[users]");
677        assert_eq!(
678            quote_ident(SqlDialect::Postgres, "public.\"user.log\""),
679            "\"public\".\"user.log\""
680        );
681    }
682
683    #[test]
684    fn quote_ident_escapes_the_closing_delimiter() {
685        // A delimiter character inside an identifier must be doubled so it cannot
686        // terminate the quoted identifier early (malformed / injectable SQL).
687        assert_eq!(quote_ident(SqlDialect::MySql, "a`b"), "`a``b`");
688        assert_eq!(quote_ident(SqlDialect::Postgres, "a\"b"), "\"a\"\"b\"");
689        assert_eq!(quote_ident(SqlDialect::Sqlite, "a\"b"), "\"a\"\"b\"");
690        assert_eq!(quote_ident(SqlDialect::Mssql, "a]b"), "[a]]b]");
691    }
692
693    #[test]
694    fn quote_identifier_keeps_literal_dots_in_one_component() {
695        assert_eq!(
696            quote_identifier(SqlDialect::Postgres, "settings.theme"),
697            "\"settings.theme\""
698        );
699    }
700
701    #[test]
702    fn is_numeric_basics() {
703        assert!(is_numeric(b"123"));
704        assert!(is_numeric(b"-1.5"));
705        assert!(is_numeric(b"1e10"));
706        assert!(!is_numeric(b""));
707        assert!(!is_numeric(b"abc"));
708        assert!(!is_numeric(b"1.2.3"));
709    }
710}