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            // Convert to hex string for DuckDB
159            let hex: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
160            format!("x'{}'", hex)
161        }
162        ParsedValue::Other(raw) => {
163            let s = String::from_utf8_lossy(raw);
164            // Try to parse as float
165            if s.parse::<f64>().is_ok() {
166                s.to_string()
167            } else {
168                // Treat as text
169                let escaped = s.replace('\'', "''");
170                format!("'{}'", escaped)
171            }
172        }
173    }
174}
175
176/// Generate a batched INSERT statement from parsed values
177fn generate_batch_insert(
178    table: &str,
179    columns: &Option<Vec<String>>,
180    rows: &[Vec<ParsedValue>],
181    dialect: SqlDialect,
182) -> String {
183    if rows.is_empty() {
184        return String::new();
185    }
186
187    // DuckDB loads PostgreSQL's `public` and SQL Server's standard system
188    // schemas into its default schema. Match the DDL and direct-INSERT paths.
189    let duckdb_table = match dialect {
190        SqlDialect::Postgres => table.strip_prefix("public.").unwrap_or(table),
191        SqlDialect::Mssql => ["dbo.", "master.", "tempdb.", "model.", "msdb."]
192            .iter()
193            .find_map(|prefix| table.strip_prefix(prefix))
194            .unwrap_or(table),
195        SqlDialect::MySql | SqlDialect::Sqlite => table,
196    };
197    let mut sql = format!(
198        "INSERT INTO {}",
199        quote_ident(SqlDialect::Postgres, duckdb_table)
200    );
201
202    // Add column list if specified
203    if let Some(cols) = columns {
204        sql.push_str(" (");
205        for (i, col) in cols.iter().enumerate() {
206            if i > 0 {
207                sql.push_str(", ");
208            }
209            sql.push('"');
210            sql.push_str(col);
211            sql.push('"');
212        }
213        sql.push(')');
214    }
215
216    sql.push_str(" VALUES\n");
217
218    for (i, row) in rows.iter().enumerate() {
219        if i > 0 {
220            sql.push_str(",\n");
221        }
222        sql.push('(');
223        for (j, value) in row.iter().enumerate() {
224            if j > 0 {
225                sql.push_str(", ");
226            }
227            sql.push_str(&format_value_for_sql(value));
228        }
229        sql.push(')');
230    }
231    sql.push(';');
232
233    sql
234}
235
236/// Flush a batch using DuckDB's Appender API with transactional fallback
237pub fn flush_batch(
238    conn: &Connection,
239    batch: &mut InsertBatch,
240    stats: &mut ImportStats,
241    failed_tables: &mut std::collections::HashSet<String>,
242) -> Result<()> {
243    if batch.rows.is_empty() {
244        return Ok(());
245    }
246
247    // Skip tables we know don't exist
248    if failed_tables.contains(&batch.table) {
249        batch.clear();
250        return Ok(());
251    }
252
253    // Try the fast path with batched INSERT
254    match try_batch_insert(conn, batch, stats) {
255        Ok(true) => {
256            // Success via batched INSERT
257            batch.clear();
258            Ok(())
259        }
260        Ok(false) => {
261            // Table doesn't exist or other non-recoverable error
262            failed_tables.insert(batch.table.clone());
263            batch.clear();
264            Ok(())
265        }
266        Err(_) => {
267            // Batched INSERT failed (constraint violation, type mismatch, etc.)
268            // Fall back to per-statement execution
269            fallback_execute(conn, batch, stats)?;
270            batch.clear();
271            Ok(())
272        }
273    }
274}
275
276/// Try to insert using batched SQL execution, returns Ok(true) on success,
277/// Ok(false) if table doesn't exist, Err on constraint/type errors
278fn try_batch_insert(
279    conn: &Connection,
280    batch: &InsertBatch,
281    stats: &mut ImportStats,
282) -> Result<bool> {
283    // Generate a single batched INSERT statement
284    let batch_sql = generate_batch_insert(&batch.table, &batch.columns, &batch.rows, batch.dialect);
285    if batch_sql.is_empty() {
286        return Ok(true);
287    }
288
289    // Execute the batched INSERT (within the loader's transaction context)
290    match conn.execute(&batch_sql, []) {
291        Ok(_) => {
292            stats.insert_statements += batch.statements.len();
293            stats.rows_inserted += batch.rows.len() as u64;
294            Ok(true)
295        }
296        Err(e) => {
297            // Check if it's a "table not found" error
298            if is_missing_table_error(&e) {
299                return Ok(false);
300            }
301            Err(e.into())
302        }
303    }
304}
305
306/// FK violations also say that a key "does not exist", so only a catalog
307/// missing-table error can tell the loader to skip future rows for a table.
308fn is_missing_table_error(error: &duckdb::Error) -> bool {
309    matches!(
310        error,
311        duckdb::Error::DuckDBFailure(_, Some(message))
312            if message.starts_with("Catalog Error: Table with name ")
313    )
314}
315
316/// Fallback: execute original SQL statements one by one
317fn fallback_execute(conn: &Connection, batch: &InsertBatch, stats: &mut ImportStats) -> Result<()> {
318    for stmt in &batch.statements {
319        match conn.execute(stmt, []) {
320            Ok(_) => {
321                stats.insert_statements += 1;
322                stats.rows_inserted += count_insert_rows(stmt);
323            }
324            Err(e) => {
325                if stats.warnings.len() < 100 {
326                    stats.warnings.push(format!(
327                        "Failed INSERT for {} in fallback: {}",
328                        batch.table, e
329                    ));
330                }
331                stats.statements_skipped += 1;
332            }
333        }
334    }
335    Ok(())
336}
337
338/// Count rows in an INSERT statement (simple heuristic)
339fn count_insert_rows(sql: &str) -> u64 {
340    if let Some(values_pos) = sql.to_uppercase().find("VALUES") {
341        let after_values = &sql[values_pos + 6..];
342        let mut count = 0u64;
343        let mut depth: i32 = 0;
344        let mut in_string = false;
345        let mut prev_char = ' ';
346
347        for c in after_values.chars() {
348            if c == '\'' && prev_char != '\\' {
349                in_string = !in_string;
350            }
351            if !in_string {
352                if c == '(' {
353                    if depth == 0 {
354                        count += 1;
355                    }
356                    depth += 1;
357                } else if c == ')' {
358                    depth = depth.saturating_sub(1);
359                }
360            }
361            prev_char = c;
362        }
363        count
364    } else {
365        1
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    #[test]
374    fn test_batch_manager_queue() {
375        let mut mgr = BatchManager::new(100);
376
377        let rows = vec![vec![
378            ParsedValue::Integer(1),
379            ParsedValue::String {
380                value: "test".to_string(),
381            },
382        ]];
383
384        let result = mgr.queue_insert(
385            "users",
386            None,
387            rows,
388            "INSERT INTO users VALUES (1, 'test')".to_string(),
389            SqlDialect::MySql,
390        );
391        assert!(result.is_none()); // Not ready yet
392        assert!(mgr.has_pending());
393    }
394
395    #[test]
396    fn test_batch_manager_flush_threshold() {
397        let mut mgr = BatchManager::new(2);
398
399        let rows1 = vec![vec![ParsedValue::Integer(1)]];
400        let rows2 = vec![vec![ParsedValue::Integer(2)], vec![ParsedValue::Integer(3)]];
401
402        mgr.queue_insert("test", None, rows1, "SQL1".to_string(), SqlDialect::MySql);
403        let result = mgr.queue_insert("test", None, rows2, "SQL2".to_string(), SqlDialect::MySql);
404
405        assert!(result.is_some());
406        let batch = result.unwrap();
407        assert_eq!(batch.row_count(), 3);
408    }
409
410    #[test]
411    fn test_count_insert_rows() {
412        assert_eq!(count_insert_rows("INSERT INTO t VALUES (1)"), 1);
413        assert_eq!(count_insert_rows("INSERT INTO t VALUES (1), (2), (3)"), 3);
414        assert_eq!(
415            count_insert_rows("INSERT INTO t VALUES (1, 'a(b)'), (2, 'c')"),
416            2
417        );
418    }
419
420    #[test]
421    fn test_generate_batch_insert_with_columns() {
422        let rows = vec![
423            vec![
424                ParsedValue::String {
425                    value: "alice".to_string(),
426                },
427                ParsedValue::Integer(1),
428            ],
429            vec![
430                ParsedValue::String {
431                    value: "bob".to_string(),
432                },
433                ParsedValue::Integer(2),
434            ],
435        ];
436        let columns = Some(vec!["name".to_string(), "id".to_string()]);
437        let sql = generate_batch_insert("users", &columns, &rows, SqlDialect::MySql);
438        assert!(sql.contains("INSERT INTO \"users\" (\"name\", \"id\") VALUES"));
439        assert!(sql.contains("'alice'"));
440        assert!(sql.contains("'bob'"));
441    }
442
443    #[test]
444    fn test_generate_batch_insert_without_columns() {
445        let rows = vec![vec![
446            ParsedValue::Integer(1),
447            ParsedValue::String {
448                value: "test".to_string(),
449            },
450        ]];
451        let sql = generate_batch_insert("test", &None, &rows, SqlDialect::MySql);
452        assert_eq!(sql, "INSERT INTO \"test\" VALUES\n(1, 'test');");
453    }
454
455    #[test]
456    fn batch_insert_quotes_qualified_table_components_separately() {
457        let rows = vec![vec![ParsedValue::Integer(1)]];
458        let sql = generate_batch_insert("tenant_a.users", &None, &rows, SqlDialect::Postgres);
459
460        assert_eq!(sql, "INSERT INTO \"tenant_a\".\"users\" VALUES\n(1);");
461    }
462
463    #[test]
464    fn batch_insert_maps_postgres_public_to_duckdb_default_schema() {
465        let rows = vec![vec![ParsedValue::Integer(1)]];
466        let sql = generate_batch_insert("public.users", &None, &rows, SqlDialect::Postgres);
467
468        assert_eq!(sql, "INSERT INTO \"users\" VALUES\n(1);");
469    }
470
471    #[test]
472    fn batch_insert_maps_mssql_dbo_to_duckdb_default_schema() {
473        let rows = vec![vec![ParsedValue::Integer(1)]];
474        let sql = generate_batch_insert("dbo.users", &None, &rows, SqlDialect::Mssql);
475
476        assert_eq!(sql, "INSERT INTO \"users\" VALUES\n(1);");
477    }
478}