Skip to main content

sql_splitter/duckdb/
mod.rs

1//! DuckDB query engine for SQL dump analytics.
2//!
3//! This module provides the ability to load SQL dumps into an embedded DuckDB
4//! database and execute analytical queries on them.
5//!
6//! # Features
7//!
8//! - **Bundled engine**: DuckDB is embedded via the optional `duckdb-query` feature
9//! - **Multi-dialect support**: MySQL, PostgreSQL, and SQLite dumps
10//! - **Memory management**: Auto-switches to disk mode for large dumps
11//! - **Caching**: Optional persistent cache for repeated queries
12//!
13//! # Example
14//!
15//! ```text
16//! use sql_splitter::duckdb::{QueryEngine, QueryConfig, QueryResultFormatter, OutputFormat};
17//! use std::path::Path;
18//!
19//! let config = QueryConfig::default();
20//! let mut engine = QueryEngine::new(&config).unwrap();
21//! engine.import_dump(Path::new("dump.sql")).unwrap();
22//!
23//! let result = engine.query("SELECT COUNT(*) FROM users").unwrap();
24//! println!("{}", QueryResultFormatter::format(&result, OutputFormat::Table));
25//! ```
26
27mod batch;
28mod cache;
29mod loader;
30mod output;
31mod types;
32
33// BatchManager is used internally by DumpLoader
34#[allow(unused_imports)]
35pub use batch::{flush_batch, BatchManager, InsertBatch, MAX_ROWS_PER_BATCH};
36pub use cache::CacheManager;
37pub use loader::DumpLoader;
38pub use output::{OutputFormat, QueryResultFormatter};
39#[allow(unused_imports)] // Used in tests
40pub use types::TypeConverter;
41
42use crate::parser::SqlDialect;
43use anyhow::{Context, Result};
44use duckdb::Connection;
45use std::path::{Path, PathBuf};
46
47/// Configuration for the query engine
48#[derive(Debug, Clone, Default)]
49pub struct QueryConfig {
50    /// Source SQL dialect (auto-detected if None)
51    pub dialect: Option<SqlDialect>,
52    /// Use disk-based storage instead of in-memory
53    pub disk_mode: bool,
54    /// Enable persistent caching
55    pub cache_enabled: bool,
56    /// Only import specific tables
57    pub tables: Option<Vec<String>>,
58    /// Memory limit for DuckDB (e.g., "4GB")
59    pub memory_limit: Option<String>,
60    /// Show progress during import
61    pub progress: bool,
62}
63
64/// Statistics from dump import
65#[derive(Debug, Default, Clone)]
66pub struct ImportStats {
67    /// Number of tables created
68    pub tables_created: usize,
69    /// Number of INSERT statements processed
70    pub insert_statements: usize,
71    /// Total rows inserted
72    pub rows_inserted: u64,
73    /// Statements skipped (unsupported)
74    pub statements_skipped: usize,
75    /// Warnings generated
76    pub warnings: Vec<String>,
77    /// Import duration in seconds
78    pub duration_secs: f64,
79}
80
81impl std::fmt::Display for ImportStats {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        write!(
84            f,
85            "{} tables, {} rows imported in {:.2}s",
86            self.tables_created, self.rows_inserted, self.duration_secs
87        )
88    }
89}
90
91/// Result of a query execution
92#[derive(Debug, Clone)]
93pub struct QueryResult {
94    /// Column names
95    pub columns: Vec<String>,
96    /// Column types (as strings)
97    pub column_types: Vec<String>,
98    /// Rows of data (each row is a vector of string values)
99    pub rows: Vec<Vec<String>>,
100    /// Query execution time in seconds
101    pub execution_time_secs: f64,
102}
103
104impl QueryResult {
105    /// Check if the result is empty
106    pub fn is_empty(&self) -> bool {
107        self.rows.is_empty()
108    }
109
110    /// Get the number of rows
111    pub fn row_count(&self) -> usize {
112        self.rows.len()
113    }
114
115    /// Get the number of columns
116    pub fn column_count(&self) -> usize {
117        self.columns.len()
118    }
119}
120
121/// The main query engine that wraps DuckDB
122pub struct QueryEngine {
123    conn: Connection,
124    config: QueryConfig,
125    import_stats: Option<ImportStats>,
126    temp_db_path: Option<PathBuf>,
127}
128
129impl QueryEngine {
130    /// Create a new query engine with the given configuration
131    pub fn new(config: &QueryConfig) -> Result<Self> {
132        let (conn, temp_db_path) = if config.disk_mode {
133            let temp_dir = std::env::temp_dir();
134            let temp_path = temp_dir.join(format!("sql-splitter-{}.duckdb", std::process::id()));
135            let conn = Connection::open(&temp_path)
136                .context("Failed to create disk-based DuckDB database")?;
137            // An import is one long run of writes, and every statement
138            // autocommits. At the 16MB default the WAL crosses the threshold
139            // constantly, so each commit checkpoints row groups back to disk --
140            // profiling a 620MB table put ~45% of samples in
141            // execute -> Commit -> CreateCheckpoint. Raising the threshold lets
142            // the import write once; the caller checkpoints explicitly when it
143            // wants the file durable.
144            conn.execute("SET checkpoint_threshold = '1GB'", [])
145                .context("Failed to raise checkpoint threshold")?;
146            (conn, Some(temp_path))
147        } else {
148            let conn = Connection::open_in_memory()
149                .context("Failed to create in-memory DuckDB database")?;
150            (conn, None)
151        };
152
153        // Configure memory limit if specified
154        if let Some(ref limit) = config.memory_limit {
155            conn.execute(&format!("SET memory_limit = '{}'", limit), [])
156                .context("Failed to set memory limit")?;
157        }
158
159        Ok(Self {
160            conn,
161            config: config.clone(),
162            import_stats: None,
163            temp_db_path,
164        })
165    }
166
167    /// Create a query engine from a cached database file
168    pub fn from_cache(cache_path: &Path, config: &QueryConfig) -> Result<Self> {
169        let conn = Connection::open(cache_path).context("Failed to open cached DuckDB database")?;
170
171        if let Some(ref limit) = config.memory_limit {
172            conn.execute(&format!("SET memory_limit = '{}'", limit), [])
173                .context("Failed to set memory limit")?;
174        }
175
176        Ok(Self {
177            conn,
178            config: config.clone(),
179            import_stats: None,
180            temp_db_path: None,
181        })
182    }
183
184    /// Import a SQL dump file into the DuckDB database
185    pub fn import_dump(&mut self, dump_path: &Path) -> Result<&ImportStats> {
186        let loader = DumpLoader::new(&self.conn, &self.config);
187        let stats = loader.load(dump_path)?;
188        self.import_stats = Some(stats);
189        // Safe: we just set import_stats to Some above
190        Ok(self
191            .import_stats
192            .as_ref()
193            .expect("import_stats was just set"))
194    }
195
196    /// Execute a query and return the results
197    pub fn query(&self, sql: &str) -> Result<QueryResult> {
198        let start = std::time::Instant::now();
199
200        let mut stmt = self
201            .conn
202            .prepare(sql)
203            .with_context(|| format!("Failed to prepare query: {}", sql))?;
204
205        // Execute the query and collect rows
206        let mut rows_result = stmt
207            .query([])
208            .with_context(|| format!("Failed to execute query: {}", sql))?;
209
210        // Collect all rows first
211        let mut rows: Vec<Vec<String>> = Vec::new();
212        let mut column_count = 0;
213
214        while let Some(row) = rows_result.next()? {
215            // Get column count from first row
216            if column_count == 0 {
217                column_count = row.as_ref().column_count();
218            }
219
220            let mut values = Vec::with_capacity(column_count);
221            for i in 0..column_count {
222                let value: String = match row.get_ref(i) {
223                    Ok(duckdb::types::ValueRef::Null) => "NULL".to_string(),
224                    Ok(duckdb::types::ValueRef::Boolean(b)) => b.to_string(),
225                    Ok(duckdb::types::ValueRef::TinyInt(n)) => n.to_string(),
226                    Ok(duckdb::types::ValueRef::SmallInt(n)) => n.to_string(),
227                    Ok(duckdb::types::ValueRef::Int(n)) => n.to_string(),
228                    Ok(duckdb::types::ValueRef::BigInt(n)) => n.to_string(),
229                    Ok(duckdb::types::ValueRef::HugeInt(n)) => n.to_string(),
230                    Ok(duckdb::types::ValueRef::UTinyInt(n)) => n.to_string(),
231                    Ok(duckdb::types::ValueRef::USmallInt(n)) => n.to_string(),
232                    Ok(duckdb::types::ValueRef::UInt(n)) => n.to_string(),
233                    Ok(duckdb::types::ValueRef::UBigInt(n)) => n.to_string(),
234                    Ok(duckdb::types::ValueRef::Float(f)) => f.to_string(),
235                    Ok(duckdb::types::ValueRef::Double(f)) => f.to_string(),
236                    Ok(duckdb::types::ValueRef::Text(s)) => String::from_utf8_lossy(s).to_string(),
237                    Ok(duckdb::types::ValueRef::Blob(b)) => {
238                        format!("<blob {} bytes>", b.len())
239                    }
240                    Ok(duckdb::types::ValueRef::Decimal(d)) => d.to_string(),
241                    Ok(duckdb::types::ValueRef::Timestamp(_, ts)) => {
242                        // Convert timestamp to readable format
243                        // DuckDB timestamps are microseconds since epoch
244                        let secs = ts / 1_000_000;
245                        let nanos = ((ts % 1_000_000) * 1000) as u32;
246                        if let Some(dt) = chrono::DateTime::from_timestamp(secs, nanos) {
247                            dt.format("%Y-%m-%d %H:%M:%S").to_string()
248                        } else {
249                            ts.to_string()
250                        }
251                    }
252                    Ok(duckdb::types::ValueRef::Date32(days)) => {
253                        // Days since epoch (1970-01-01)
254                        if let Some(date) = chrono::NaiveDate::from_num_days_from_ce_opt(
255                            719163 + days, // 719163 = days from 0001-01-01 to 1970-01-01
256                        ) {
257                            date.format("%Y-%m-%d").to_string()
258                        } else {
259                            days.to_string()
260                        }
261                    }
262                    Ok(duckdb::types::ValueRef::Time64(_, micros)) => {
263                        let secs = (micros / 1_000_000) as u32;
264                        let nanos = ((micros % 1_000_000) * 1000) as u32;
265                        if let Some(time) =
266                            chrono::NaiveTime::from_num_seconds_from_midnight_opt(secs, nanos)
267                        {
268                            time.format("%H:%M:%S").to_string()
269                        } else {
270                            micros.to_string()
271                        }
272                    }
273                    Ok(other) => format!("{:?}", other),
274                    Err(_) => "ERROR".to_string(),
275                };
276                values.push(value);
277            }
278            rows.push(values);
279        }
280
281        // Drop the rows iterator to release the mutable borrow
282        drop(rows_result);
283
284        // Now get column info from the statement
285        let column_count = stmt.column_count();
286        let columns: Vec<String> = (0..column_count)
287            .map(|i| {
288                stmt.column_name(i)
289                    .map(|s| s.to_string())
290                    .unwrap_or_else(|_| format!("col{}", i))
291            })
292            .collect();
293
294        // Get column types
295        let column_types: Vec<String> = (0..column_count)
296            .map(|i| format!("{:?}", stmt.column_type(i)))
297            .collect();
298
299        Ok(QueryResult {
300            columns,
301            column_types,
302            rows,
303            execution_time_secs: start.elapsed().as_secs_f64(),
304        })
305    }
306
307    /// Execute a statement that doesn't return results (e.g., CREATE, INSERT)
308    pub fn execute(&self, sql: &str) -> Result<usize> {
309        self.conn
310            .execute(sql, [])
311            .with_context(|| format!("Failed to execute: {}", sql))
312    }
313
314    /// Get list of tables in the database
315    pub fn list_tables(&self) -> Result<Vec<String>> {
316        let result = self.query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'main' ORDER BY table_name")?;
317        Ok(result.rows.into_iter().map(|r| r[0].clone()).collect())
318    }
319
320    /// Get schema for a specific table
321    pub fn describe_table(&self, table: &str) -> Result<QueryResult> {
322        self.query(&format!("DESCRIBE \"{}\"", table))
323    }
324
325    /// Get import statistics (if a dump was imported)
326    pub fn import_stats(&self) -> Option<&ImportStats> {
327        self.import_stats.as_ref()
328    }
329
330    /// Get the underlying DuckDB connection (for advanced use)
331    pub fn connection(&self) -> &Connection {
332        &self.conn
333    }
334}
335
336impl Drop for QueryEngine {
337    fn drop(&mut self) {
338        // Clean up temporary database file if we created one
339        if let Some(ref path) = self.temp_db_path {
340            let _ = std::fs::remove_file(path);
341            // Also try to remove the .wal file if it exists
342            let wal_path = path.with_extension("duckdb.wal");
343            let _ = std::fs::remove_file(wal_path);
344        }
345    }
346}
347
348/// Threshold for automatic disk mode (2 GB)
349pub const DISK_MODE_THRESHOLD: u64 = 2 * 1024 * 1024 * 1024;
350
351/// Determine if disk mode should be used based on file size
352pub fn should_use_disk_mode(file_size: u64) -> bool {
353    file_size > DISK_MODE_THRESHOLD
354}