Skip to main content

sql_splitter/duckdb/
batch.rs

1//! Batch manager for DuckDB Appender-based bulk loading.
2//!
3//! This module provides efficient batched insertion of rows into DuckDB
4//! using the Appender API instead of individual INSERT statement execution.
5
6use crate::parser::{ParsedValue, SqlDialect};
7use crate::transform_common::quote_ident;
8use ahash::AHashMap;
9use anyhow::Result;
10use duckdb::Connection;
11
12use super::ImportStats;
13
14/// Maximum rows to accumulate per batch before flushing
15pub const MAX_ROWS_PER_BATCH: usize = 10_000;
16
17/// A batch of rows for a single table
18#[derive(Debug)]
19pub struct InsertBatch {
20    /// Target table name
21    pub table: String,
22    /// Source SQL dialect, used to map source-default schemas to DuckDB's
23    /// default schema in generated batch inserts.
24    pub dialect: SqlDialect,
25    /// Column list if explicitly specified
26    pub columns: Option<Vec<String>>,
27    /// Accumulated rows (each row is a Vec of ParsedValue)
28    pub rows: Vec<Vec<ParsedValue>>,
29    /// Original SQL statements for fallback execution
30    pub statements: Vec<String>,
31    /// Number of rows contributed by each statement
32    pub rows_per_statement: Vec<usize>,
33}
34
35impl InsertBatch {
36    /// Create a new batch for a table
37    pub fn new(table: String, columns: Option<Vec<String>>, dialect: SqlDialect) -> Self {
38        Self {
39            table,
40            dialect,
41            columns,
42            rows: Vec::new(),
43            statements: Vec::new(),
44            rows_per_statement: Vec::new(),
45        }
46    }
47
48    /// Total number of rows in batch
49    pub fn row_count(&self) -> usize {
50        self.rows.len()
51    }
52
53    /// Clear the batch
54    pub fn clear(&mut self) {
55        self.rows.clear();
56        self.statements.clear();
57        self.rows_per_statement.clear();
58    }
59}
60
61/// Batch key: (table_name, column_layout, source dialect).
62/// Using Option<Vec<String>> for columns allows distinguishing between
63/// different column orderings for the same table. The source dialect is part
64/// of the key because it determines the DuckDB table-name mapping.
65type BatchKey = (String, Option<Vec<String>>, SqlDialect);
66
67/// Manages batched INSERT operations for multiple tables
68pub struct BatchManager {
69    /// Active batches keyed by (table, columns)
70    batches: AHashMap<BatchKey, InsertBatch>,
71    /// Maximum rows per batch
72    max_rows_per_batch: usize,
73}
74
75impl BatchManager {
76    /// Create a new batch manager
77    pub fn new(max_rows_per_batch: usize) -> Self {
78        Self {
79            batches: AHashMap::new(),
80            max_rows_per_batch,
81        }
82    }
83
84    /// Queue rows for insertion, returning a batch if it's ready to flush
85    pub fn queue_insert(
86        &mut self,
87        table: &str,
88        columns: Option<Vec<String>>,
89        rows: Vec<Vec<ParsedValue>>,
90        original_sql: String,
91        dialect: SqlDialect,
92    ) -> Option<InsertBatch> {
93        let row_count = rows.len();
94        let key = (table.to_string(), columns.clone(), dialect);
95
96        let batch = self
97            .batches
98            .entry(key)
99            .or_insert_with(|| InsertBatch::new(table.to_string(), columns, dialect));
100
101        batch.rows.extend(rows);
102        batch.statements.push(original_sql);
103        batch.rows_per_statement.push(row_count);
104
105        // Check if we need to flush
106        if batch.rows.len() >= self.max_rows_per_batch {
107            // Take the batch out and return it
108            let key = (table.to_string(), batch.columns.clone(), dialect);
109            self.batches.remove(&key)
110        } else {
111            None
112        }
113    }
114
115    /// Get any batches that are ready to flush
116    pub fn get_ready_batches(&mut self) -> Vec<InsertBatch> {
117        let mut ready = Vec::new();
118        let mut to_remove = Vec::new();
119
120        for (key, batch) in &self.batches {
121            if batch.rows.len() >= self.max_rows_per_batch {
122                to_remove.push(key.clone());
123            }
124        }
125
126        for key in to_remove {
127            if let Some(batch) = self.batches.remove(&key) {
128                ready.push(batch);
129            }
130        }
131
132        ready
133    }
134
135    /// Flush all remaining batches
136    pub fn drain_all(&mut self) -> Vec<InsertBatch> {
137        self.batches.drain().map(|(_, batch)| batch).collect()
138    }
139
140    /// Check if there are any pending batches
141    pub fn has_pending(&self) -> bool {
142        !self.batches.is_empty()
143    }
144}
145
146/// Format a ParsedValue for SQL insertion
147fn format_value_for_sql(value: &ParsedValue) -> String {
148    match value {
149        ParsedValue::Null => "NULL".to_string(),
150        ParsedValue::Integer(n) => n.to_string(),
151        ParsedValue::BigInteger(n) => n.to_string(),
152        ParsedValue::String { value } => {
153            // Escape single quotes by doubling them (SQL standard)
154            let escaped = value.replace('\'', "''");
155            format!("'{}'", escaped)
156        }
157        ParsedValue::Hex(bytes) => {
158            // `ParsedValue::Hex` carries the literal as written, `0x` prefix
159            // included, so the digits are already hex -- re-encoding the bytes
160            // would hex-encode the ASCII characters and turn 0x30 into
161            // x'30783330'.
162            format!("x'{}'", hex_digits(bytes))
163        }
164        ParsedValue::Other(raw) => {
165            let s = String::from_utf8_lossy(raw);
166            // Try to parse as float
167            if s.parse::<f64>().is_ok() {
168                s.to_string()
169            } else {
170                // Treat as text
171                let escaped = s.replace('\'', "''");
172                format!("'{}'", escaped)
173            }
174        }
175    }
176}
177
178/// Generate a batched INSERT statement from parsed values
179fn generate_batch_insert(
180    table: &str,
181    columns: &Option<Vec<String>>,
182    rows: &[Vec<ParsedValue>],
183    dialect: SqlDialect,
184) -> String {
185    if rows.is_empty() {
186        return String::new();
187    }
188
189    // DuckDB loads PostgreSQL's `public` and SQL Server's standard system
190    // schemas into its default schema. Match the DDL and direct-INSERT paths.
191    let duckdb_table = match dialect {
192        SqlDialect::Postgres => table.strip_prefix("public.").unwrap_or(table),
193        SqlDialect::Mssql => ["dbo.", "master.", "tempdb.", "model.", "msdb."]
194            .iter()
195            .find_map(|prefix| table.strip_prefix(prefix))
196            .unwrap_or(table),
197        SqlDialect::MySql | SqlDialect::Sqlite => table,
198    };
199    let mut sql = format!(
200        "INSERT INTO {}",
201        quote_ident(SqlDialect::Postgres, duckdb_table)
202    );
203
204    // Add column list if specified
205    if let Some(cols) = columns {
206        sql.push_str(" (");
207        for (i, col) in cols.iter().enumerate() {
208            if i > 0 {
209                sql.push_str(", ");
210            }
211            sql.push('"');
212            sql.push_str(col);
213            sql.push('"');
214        }
215        sql.push(')');
216    }
217
218    sql.push_str(" VALUES\n");
219
220    for (i, row) in rows.iter().enumerate() {
221        if i > 0 {
222            sql.push_str(",\n");
223        }
224        sql.push('(');
225        for (j, value) in row.iter().enumerate() {
226            if j > 0 {
227                sql.push_str(", ");
228            }
229            sql.push_str(&format_value_for_sql(value));
230        }
231        sql.push(')');
232    }
233    sql.push(';');
234
235    sql
236}
237
238/// Flush a batch using DuckDB's Appender API with transactional fallback
239pub fn flush_batch(
240    conn: &Connection,
241    batch: &mut InsertBatch,
242    stats: &mut ImportStats,
243    failed_tables: &mut std::collections::HashSet<String>,
244) -> Result<()> {
245    if batch.rows.is_empty() {
246        return Ok(());
247    }
248
249    // Skip tables we know don't exist
250    if failed_tables.contains(&batch.table) {
251        batch.clear();
252        return Ok(());
253    }
254
255    // Fastest path: hand the parsed values straight to DuckDB's Appender. The
256    // batched-INSERT path below has to serialize every value back into SQL text
257    // that DuckDB then re-parses -- profiling put ~75% of import time in
258    // duckdb::ClientContext::CreatePreparedStatement doing exactly that. The
259    // Appender skips the parser entirely. It is not always applicable, so it
260    // reports false and leaves the batch untouched when it bails.
261    match try_appender_insert(conn, batch, stats) {
262        Ok(true) => {
263            batch.clear();
264            return Ok(());
265        }
266        Ok(false) => {} // not eligible, fall through to SQL
267        Err(e) => {
268            // The append was rolled back, so falling through cannot double-insert.
269            if stats.warnings.len() < 100 {
270                stats.warnings.push(format!(
271                    "Appender failed for {}, using SQL: {}",
272                    batch.table, e
273                ));
274            }
275        }
276    }
277
278    // Try the fast path with batched INSERT
279    match try_batch_insert(conn, batch, stats) {
280        Ok(true) => {
281            // Success via batched INSERT
282            batch.clear();
283            Ok(())
284        }
285        Ok(false) => {
286            // Table doesn't exist or other non-recoverable error
287            failed_tables.insert(batch.table.clone());
288            batch.clear();
289            Ok(())
290        }
291        Err(_) => {
292            // Batched INSERT failed (constraint violation, type mismatch, etc.)
293            // Fall back to per-statement execution
294            fallback_execute(conn, batch, stats)?;
295            batch.clear();
296            Ok(())
297        }
298    }
299}
300
301/// Map the DuckDB table name the way the SQL path does, so both agree on which
302/// table a batch targets.
303fn duckdb_table_name(table: &str, dialect: SqlDialect) -> &str {
304    match dialect {
305        SqlDialect::Postgres => table.strip_prefix("public.").unwrap_or(table),
306        SqlDialect::Mssql => ["dbo.", "master.", "tempdb.", "model.", "msdb."]
307            .iter()
308            .find_map(|prefix| table.strip_prefix(prefix))
309            .unwrap_or(table),
310        SqlDialect::MySql | SqlDialect::Sqlite => table,
311    }
312}
313
314/// Convert a parsed value for the Appender. `Other` holds raw bytes for
315/// decimals, floats and expressions like `NOW()`; binding those as text would
316/// either lose exactness or be flatly wrong, so those batches take the SQL path
317/// where DuckDB parses them into the column's own type.
318fn appender_value(v: &ParsedValue) -> Option<duckdb::types::Value> {
319    use duckdb::types::Value as V;
320    Some(match v {
321        ParsedValue::Null => V::Null,
322        ParsedValue::Integer(i) => V::BigInt(*i),
323        ParsedValue::BigInteger(i) => V::HugeInt(*i),
324        ParsedValue::String { value } => V::Text(value.clone()),
325        ParsedValue::Hex(b) => V::Blob(decode_hex_literal(b)?),
326        ParsedValue::Other(_) => return None,
327    })
328}
329
330/// The hex digits of a `0xABCD` literal, without the prefix.
331fn hex_digits(raw: &[u8]) -> std::borrow::Cow<'_, str> {
332    let digits = raw
333        .strip_prefix(b"0x")
334        .or_else(|| raw.strip_prefix(b"0X"))
335        .unwrap_or(raw);
336    String::from_utf8_lossy(digits)
337}
338
339/// Decode a `0xABCD` literal into the bytes it denotes. MySQL left-pads an odd
340/// digit count, so `0xABC` is the two bytes `0x0A 0xBC`.
341fn decode_hex_literal(raw: &[u8]) -> Option<Vec<u8>> {
342    let digits = hex_digits(raw);
343    let d = digits.as_bytes();
344    if d.is_empty() || !d.iter().all(u8::is_ascii_hexdigit) {
345        return None;
346    }
347    let mut out = Vec::with_capacity(d.len().div_ceil(2));
348    let mut idx = 0;
349    if d.len() % 2 == 1 {
350        out.push((d[0] as char).to_digit(16)? as u8);
351        idx = 1;
352    }
353    while idx < d.len() {
354        let hi = (d[idx] as char).to_digit(16)? as u8;
355        let lo = (d[idx + 1] as char).to_digit(16)? as u8;
356        out.push((hi << 4) | lo);
357        idx += 2;
358    }
359    Some(out)
360}
361
362/// Append a batch with DuckDB's Appender, bypassing SQL parsing entirely.
363///
364/// `Ok(false)` means the batch is not eligible and nothing was written, so the
365/// caller should use the SQL path. `Err` means the append failed *and was rolled
366/// back*, so the caller can also fall through without double-inserting.
367///
368/// Eligibility is deliberately strict. The Appender binds positionally across
369/// every column of the table, so a batch whose column list differs from the
370/// table's own order -- or omits a column -- would silently write values into
371/// the wrong columns. That is worse than being slow, so anything short of an
372/// exact match declines.
373fn try_appender_insert(
374    conn: &Connection,
375    batch: &InsertBatch,
376    stats: &mut ImportStats,
377) -> Result<bool> {
378    let table = duckdb_table_name(&batch.table, batch.dialect);
379
380    // The table's real column order, straight from the catalog.
381    let mut stmt = conn.prepare(
382        "SELECT column_name FROM information_schema.columns \
383         WHERE table_name = ? ORDER BY ordinal_position",
384    )?;
385    let table_cols: Vec<String> = stmt
386        .query_map([table], |r| r.get::<_, String>(0))?
387        .collect::<std::result::Result<_, _>>()?;
388    if table_cols.is_empty() {
389        return Ok(false); // unknown table; let the SQL path produce the error
390    }
391
392    // An explicit column list must match the catalog exactly, in order.
393    if let Some(cols) = &batch.columns {
394        if cols.len() != table_cols.len()
395            || !cols
396                .iter()
397                .zip(&table_cols)
398                .all(|(a, b)| a.eq_ignore_ascii_case(b))
399        {
400            return Ok(false);
401        }
402    }
403
404    // Every row must be full width and hold only bindable values.
405    let width = table_cols.len();
406    let mut values: Vec<duckdb::types::Value> = Vec::with_capacity(batch.rows.len() * width);
407    for row in &batch.rows {
408        if row.len() != width {
409            return Ok(false);
410        }
411        for v in row {
412            match appender_value(v) {
413                Some(val) => values.push(val),
414                None => return Ok(false),
415            }
416        }
417    }
418
419    // Wrap in a transaction so a type-cast failure part-way through leaves no
420    // partially appended rows behind for the SQL fallback to duplicate.
421    conn.execute_batch("BEGIN TRANSACTION")?;
422    let appended = (|| -> duckdb::Result<()> {
423        let mut app = conn.appender(table)?;
424        let mut refs: Vec<&dyn duckdb::ToSql> = Vec::with_capacity(width);
425        for chunk in values.chunks(width) {
426            refs.clear();
427            refs.extend(chunk.iter().map(|v| v as &dyn duckdb::ToSql));
428            app.append_row(refs.as_slice())?;
429        }
430        app.flush()
431    })();
432
433    match appended {
434        Ok(()) => {
435            conn.execute_batch("COMMIT")?;
436            stats.insert_statements += batch.statements.len();
437            stats.rows_inserted += batch.rows.len() as u64;
438            Ok(true)
439        }
440        Err(e) => {
441            conn.execute_batch("ROLLBACK")?;
442            Err(e.into())
443        }
444    }
445}
446
447/// Try to insert using batched SQL execution, returns Ok(true) on success,
448/// Ok(false) if table doesn't exist, Err on constraint/type errors
449fn try_batch_insert(
450    conn: &Connection,
451    batch: &InsertBatch,
452    stats: &mut ImportStats,
453) -> Result<bool> {
454    // Generate a single batched INSERT statement
455    let batch_sql = generate_batch_insert(&batch.table, &batch.columns, &batch.rows, batch.dialect);
456    if batch_sql.is_empty() {
457        return Ok(true);
458    }
459
460    // Execute the batched INSERT (within the loader's transaction context)
461    match conn.execute(&batch_sql, []) {
462        Ok(_) => {
463            stats.insert_statements += batch.statements.len();
464            stats.rows_inserted += batch.rows.len() as u64;
465            Ok(true)
466        }
467        Err(e) => {
468            // Check if it's a "table not found" error
469            if is_missing_table_error(&e) {
470                return Ok(false);
471            }
472            Err(e.into())
473        }
474    }
475}
476
477/// FK violations also say that a key "does not exist", so only a catalog
478/// missing-table error can tell the loader to skip future rows for a table.
479fn is_missing_table_error(error: &duckdb::Error) -> bool {
480    matches!(
481        error,
482        duckdb::Error::DuckDBFailure(_, Some(message))
483            if message.starts_with("Catalog Error: Table with name ")
484    )
485}
486
487/// Fallback: execute original SQL statements one by one
488fn fallback_execute(conn: &Connection, batch: &InsertBatch, stats: &mut ImportStats) -> Result<()> {
489    for stmt in &batch.statements {
490        match conn.execute(stmt, []) {
491            Ok(_) => {
492                stats.insert_statements += 1;
493                stats.rows_inserted += count_insert_rows(stmt);
494            }
495            Err(e) => {
496                if stats.warnings.len() < 100 {
497                    stats.warnings.push(format!(
498                        "Failed INSERT for {} in fallback: {}",
499                        batch.table, e
500                    ));
501                }
502                stats.statements_skipped += 1;
503            }
504        }
505    }
506    Ok(())
507}
508
509/// Count rows in an INSERT statement (simple heuristic)
510fn count_insert_rows(sql: &str) -> u64 {
511    if let Some(values_pos) = sql.to_uppercase().find("VALUES") {
512        let after_values = &sql[values_pos + 6..];
513        let mut count = 0u64;
514        let mut depth: i32 = 0;
515        let mut in_string = false;
516        let mut prev_char = ' ';
517
518        for c in after_values.chars() {
519            if c == '\'' && prev_char != '\\' {
520                in_string = !in_string;
521            }
522            if !in_string {
523                if c == '(' {
524                    if depth == 0 {
525                        count += 1;
526                    }
527                    depth += 1;
528                } else if c == ')' {
529                    depth = depth.saturating_sub(1);
530                }
531            }
532            prev_char = c;
533        }
534        count
535    } else {
536        1
537    }
538}
539
540#[cfg(test)]
541mod tests {
542    use super::*;
543
544    #[test]
545    fn hex_literal_decodes_to_the_bytes_it_denotes() {
546        // `ParsedValue::Hex` keeps the `0x` prefix, so a naive re-encode of the
547        // payload turns 0x30 into the four ASCII bytes "0x30".
548        assert_eq!(decode_hex_literal(b"0x30").unwrap(), vec![0x30]);
549        assert_eq!(decode_hex_literal(b"0x623a303b").unwrap(), b"b:0;".to_vec());
550        assert_eq!(decode_hex_literal(b"0XFF").unwrap(), vec![0xff]);
551        // MySQL left-pads an odd digit count: 0xABC is 0x0A 0xBC.
552        assert_eq!(decode_hex_literal(b"0xABC").unwrap(), vec![0x0a, 0xbc]);
553        assert!(decode_hex_literal(b"0x").is_none());
554        assert!(decode_hex_literal(b"0xZZ").is_none());
555    }
556
557    #[test]
558    fn hex_literal_renders_as_sql_blob_without_double_encoding() {
559        let v = ParsedValue::Hex(b"0x623a303b".to_vec());
560        assert_eq!(format_value_for_sql(&v), "x'623a303b'");
561    }
562
563    #[test]
564    fn test_batch_manager_queue() {
565        let mut mgr = BatchManager::new(100);
566
567        let rows = vec![vec![
568            ParsedValue::Integer(1),
569            ParsedValue::String {
570                value: "test".to_string(),
571            },
572        ]];
573
574        let result = mgr.queue_insert(
575            "users",
576            None,
577            rows,
578            "INSERT INTO users VALUES (1, 'test')".to_string(),
579            SqlDialect::MySql,
580        );
581        assert!(result.is_none()); // Not ready yet
582        assert!(mgr.has_pending());
583    }
584
585    #[test]
586    fn test_batch_manager_flush_threshold() {
587        let mut mgr = BatchManager::new(2);
588
589        let rows1 = vec![vec![ParsedValue::Integer(1)]];
590        let rows2 = vec![vec![ParsedValue::Integer(2)], vec![ParsedValue::Integer(3)]];
591
592        mgr.queue_insert("test", None, rows1, "SQL1".to_string(), SqlDialect::MySql);
593        let result = mgr.queue_insert("test", None, rows2, "SQL2".to_string(), SqlDialect::MySql);
594
595        assert!(result.is_some());
596        let batch = result.unwrap();
597        assert_eq!(batch.row_count(), 3);
598    }
599
600    #[test]
601    fn test_count_insert_rows() {
602        assert_eq!(count_insert_rows("INSERT INTO t VALUES (1)"), 1);
603        assert_eq!(count_insert_rows("INSERT INTO t VALUES (1), (2), (3)"), 3);
604        assert_eq!(
605            count_insert_rows("INSERT INTO t VALUES (1, 'a(b)'), (2, 'c')"),
606            2
607        );
608    }
609
610    #[test]
611    fn test_generate_batch_insert_with_columns() {
612        let rows = vec![
613            vec![
614                ParsedValue::String {
615                    value: "alice".to_string(),
616                },
617                ParsedValue::Integer(1),
618            ],
619            vec![
620                ParsedValue::String {
621                    value: "bob".to_string(),
622                },
623                ParsedValue::Integer(2),
624            ],
625        ];
626        let columns = Some(vec!["name".to_string(), "id".to_string()]);
627        let sql = generate_batch_insert("users", &columns, &rows, SqlDialect::MySql);
628        assert!(sql.contains("INSERT INTO \"users\" (\"name\", \"id\") VALUES"));
629        assert!(sql.contains("'alice'"));
630        assert!(sql.contains("'bob'"));
631    }
632
633    #[test]
634    fn test_generate_batch_insert_without_columns() {
635        let rows = vec![vec![
636            ParsedValue::Integer(1),
637            ParsedValue::String {
638                value: "test".to_string(),
639            },
640        ]];
641        let sql = generate_batch_insert("test", &None, &rows, SqlDialect::MySql);
642        assert_eq!(sql, "INSERT INTO \"test\" VALUES\n(1, 'test');");
643    }
644
645    #[test]
646    fn batch_insert_quotes_qualified_table_components_separately() {
647        let rows = vec![vec![ParsedValue::Integer(1)]];
648        let sql = generate_batch_insert("tenant_a.users", &None, &rows, SqlDialect::Postgres);
649
650        assert_eq!(sql, "INSERT INTO \"tenant_a\".\"users\" VALUES\n(1);");
651    }
652
653    #[test]
654    fn batch_insert_maps_postgres_public_to_duckdb_default_schema() {
655        let rows = vec![vec![ParsedValue::Integer(1)]];
656        let sql = generate_batch_insert("public.users", &None, &rows, SqlDialect::Postgres);
657
658        assert_eq!(sql, "INSERT INTO \"users\" VALUES\n(1);");
659    }
660
661    #[test]
662    fn batch_insert_maps_mssql_dbo_to_duckdb_default_schema() {
663        let rows = vec![vec![ParsedValue::Integer(1)]];
664        let sql = generate_batch_insert("dbo.users", &None, &rows, SqlDialect::Mssql);
665
666        assert_eq!(sql, "INSERT INTO \"users\" VALUES\n(1);");
667    }
668}