1use async_trait::async_trait;
2use rust_decimal::Decimal;
3use sqlx::{sqlite::SqliteConnectOptions, Column, Row as SqlxRow, SqlitePool};
4use std::path::PathBuf;
5
6use crate::{
7 connectors::{Source, Target},
8 schema::{Column as SchemaColumn, DataType, Row, Schema, Value},
9 Result, TinyEtlError,
10};
11
12pub struct SqliteSource {
13 connection_string: String,
14 pool: Option<SqlitePool>,
15 table_name: String,
16 query: Option<String>,
17 current_offset: usize,
18 total_rows: Option<usize>,
19}
20
21impl SqliteSource {
22 pub fn new(connection_string: &str) -> Result<Self> {
23 let (db_path, table) = if connection_string.contains('#') {
25 let parts: Vec<&str> = connection_string.split('#').collect();
26 if parts.len() != 2 {
27 return Err(TinyEtlError::Configuration(
28 "SQLite connection string format: file.db#table".to_string(),
29 ));
30 }
31 (parts[0].trim_start_matches("sqlite:"), parts[1])
32 } else {
33 return Err(TinyEtlError::Configuration(
34 "SQLite source requires table specification: file.db#table".to_string(),
35 ));
36 };
37
38 Ok(Self {
39 connection_string: format!("sqlite:{}", db_path),
40 pool: None,
41 table_name: table.to_string(),
42 query: None,
43 current_offset: 0,
44 total_rows: None,
45 })
46 }
47}
48
49#[async_trait]
50impl Source for SqliteSource {
51 async fn connect(&mut self) -> Result<()> {
52 match SqlitePool::connect(&self.connection_string).await {
53 Ok(pool) => {
54 self.pool = Some(pool);
55 Ok(())
56 }
57 Err(e) => {
58 let db_path = self.connection_string.trim_start_matches("sqlite:");
59 Err(TinyEtlError::Connection(format!(
60 "Failed to connect to SQLite database '{}': {}. Make sure the file exists and is readable.",
61 db_path,
62 e
63 )))
64 }
65 }
66 }
67
68 async fn infer_schema(&mut self, _sample_size: usize) -> Result<Schema> {
69 if self.pool.is_none() {
70 self.connect().await?;
71 }
72
73 let pool = self.pool.as_ref().unwrap();
74
75 let table_info = sqlx::query(&format!("PRAGMA table_info(\"{}\")", self.table_name))
77 .fetch_all(pool)
78 .await?;
79
80 let mut columns = Vec::new();
81 for row in table_info {
82 let name: String = row.get(1);
83 let sql_type: String = row.get(2);
84 let not_null: bool = row.get(3);
85
86 let data_type = match sql_type.to_uppercase().as_str() {
87 "INTEGER" | "INT" => DataType::Integer,
88 "REAL" | "FLOAT" | "DOUBLE" | "NUMERIC" | "DECIMAL" => DataType::Decimal,
89 "TEXT" | "VARCHAR" => DataType::String,
90 "BOOLEAN" | "BOOL" => DataType::Boolean,
91 "DATE" => DataType::Date,
92 "DATETIME" | "TIMESTAMP" => DataType::DateTime,
93 _ => DataType::String,
94 };
95
96 columns.push(SchemaColumn {
97 name,
98 data_type,
99 nullable: !not_null,
100 });
101 }
102
103 let count_result = sqlx::query(&format!(
105 "SELECT COUNT(*) as count FROM \"{}\"",
106 self.table_name
107 ))
108 .fetch_one(pool)
109 .await?;
110 let estimated_rows: i64 = count_result.get("count");
111
112 self.total_rows = Some(estimated_rows as usize);
114
115 Ok(Schema {
116 columns,
117 estimated_rows: Some(estimated_rows as usize),
118 primary_key_candidate: None,
119 })
120 }
121
122 async fn read_batch(&mut self, batch_size: usize) -> Result<Vec<Row>> {
123 if self.pool.is_none() {
124 self.connect().await?;
125 }
126
127 let pool = self.pool.as_ref().unwrap();
128
129 let query = format!(
131 "SELECT * FROM \"{}\" LIMIT {} OFFSET {}",
132 self.table_name, batch_size, self.current_offset
133 );
134 let rows = sqlx::query(&query).fetch_all(pool).await?;
135
136 self.current_offset += rows.len();
138
139 let mut result_rows = Vec::new();
140 for row in rows {
141 let mut data_row = Row::new();
142
143 for (i, column) in row.columns().iter().enumerate() {
145 let column_name = column.name();
146
147 let value = if let Ok(val) = row.try_get::<Option<String>, _>(i) {
149 match val {
150 Some(s) => Value::String(s),
151 None => Value::Null,
152 }
153 } else if let Ok(val) = row.try_get::<Option<i64>, _>(i) {
154 match val {
155 Some(i) => Value::Integer(i),
156 None => Value::Null,
157 }
158 } else if let Ok(val) = row.try_get::<Option<f64>, _>(i) {
159 match val {
160 Some(f) => {
161 match Decimal::try_from(f) {
163 Ok(d) => Value::Decimal(d),
164 Err(_) => Value::String(f.to_string()),
165 }
166 }
167 None => Value::Null,
168 }
169 } else {
170 Value::Null
171 };
172
173 data_row.insert(column_name.to_string(), value);
174 }
175
176 result_rows.push(data_row);
177 }
178
179 Ok(result_rows)
180 }
181
182 async fn estimated_row_count(&self) -> Result<Option<usize>> {
183 if let Some(pool) = &self.pool {
184 let count_result = sqlx::query(&format!(
185 "SELECT COUNT(*) as count FROM {}",
186 self.table_name
187 ))
188 .fetch_one(pool)
189 .await?;
190 let count: i64 = count_result.get("count");
191 Ok(Some(count as usize))
192 } else {
193 Ok(None)
194 }
195 }
196
197 async fn reset(&mut self) -> Result<()> {
198 self.current_offset = 0;
200 self.query = None;
201 Ok(())
202 }
203
204 fn has_more(&self) -> bool {
205 if let Some(total) = self.total_rows {
207 self.current_offset < total
208 } else {
209 false
210 }
211 }
212}
213
214pub struct SqliteTarget {
215 connection_string: String,
216 pool: Option<SqlitePool>,
217 table_name: String,
218}
219
220impl SqliteTarget {
221 pub fn new(connection_string: &str) -> Result<Self> {
222 let normalized = connection_string
227 .trim_start_matches("sqlite://")
228 .trim_start_matches("sqlite:");
229
230 let (db_path, table) = if normalized.contains('#') {
231 let parts: Vec<&str> = normalized.split('#').collect();
232 if parts.len() != 2 {
233 return Err(TinyEtlError::Configuration(
234 "SQLite connection string format: file.db#table or sqlite://file.db#table"
235 .to_string(),
236 ));
237 }
238 (parts[0], parts[1])
239 } else {
240 (normalized, "data")
242 };
243
244 Ok(Self {
245 connection_string: format!("sqlite:{}", db_path),
246 pool: None,
247 table_name: table.to_string(),
248 })
249 }
250
251 fn get_db_path(&self) -> Result<PathBuf> {
252 let path_str = self.connection_string.trim_start_matches("sqlite:");
253 Ok(PathBuf::from(path_str))
254 }
255
256 fn map_data_type_to_sqlite(&self, data_type: &DataType) -> &'static str {
257 match data_type {
258 DataType::Integer => "INTEGER",
259 DataType::Decimal => "REAL",
260 DataType::String => "TEXT",
261 DataType::Boolean => "INTEGER", DataType::Date => "TEXT",
263 DataType::DateTime => "TEXT",
264 DataType::Json => "TEXT", DataType::Null => "TEXT",
266 }
267 }
268}
269
270#[async_trait]
271impl Target for SqliteTarget {
272 async fn connect(&mut self) -> Result<()> {
273 let db_path = self.get_db_path()?;
275 if let Some(parent) = db_path.parent() {
276 std::fs::create_dir_all(parent)?;
277 }
278
279 let connect_options = SqliteConnectOptions::new()
282 .filename(&db_path)
283 .create_if_missing(true);
284
285 match SqlitePool::connect_with(connect_options).await {
286 Ok(pool) => {
287 self.pool = Some(pool);
288 Ok(())
289 }
290 Err(e) => Err(TinyEtlError::Connection(format!(
291 "Failed to connect to SQLite database '{}': {}. Check file path and permissions.",
292 db_path.display(),
293 e
294 ))),
295 }
296 }
297
298 async fn create_table(&mut self, table_name: &str, schema: &Schema) -> Result<()> {
299 if self.pool.is_none() {
300 self.connect().await?;
301 }
302
303 let pool = self.pool.as_ref().unwrap();
304
305 let actual_table_name = if table_name.is_empty() {
307 self.table_name.clone()
308 } else {
309 table_name.to_string()
310 };
311
312 self.table_name = actual_table_name.clone();
314
315 let column_definitions: Vec<String> = schema
317 .columns
318 .iter()
319 .map(|col| {
320 let sqlite_type = self.map_data_type_to_sqlite(&col.data_type);
321 let nullable = if col.nullable { "" } else { " NOT NULL" };
322 format!("\"{}\" {}{}", col.name, sqlite_type, nullable)
323 })
324 .collect();
325
326 let create_sql = format!(
328 "CREATE TABLE IF NOT EXISTS \"{}\" ({})",
329 actual_table_name,
330 column_definitions.join(", ")
331 );
332
333 sqlx::query(&create_sql).execute(pool).await?;
334 Ok(())
335 }
336
337 async fn write_batch(&mut self, rows: &[Row]) -> Result<usize> {
338 if self.pool.is_none() {
339 return Err(TinyEtlError::Connection("Pool not connected".to_string()));
340 }
341
342 if rows.is_empty() {
343 return Ok(0);
344 }
345
346 let pool = self.pool.as_ref().unwrap();
347
348 let columns: Vec<String> = rows[0].keys().cloned().collect();
350
351 let quoted_columns: Vec<String> =
353 columns.iter().map(|col| format!("\"{}\"", col)).collect();
354
355 let max_variables = 900; let max_rows_per_chunk = max_variables / columns.len();
359
360 let mut total_written = 0;
361
362 for chunk in rows.chunks(max_rows_per_chunk) {
364 let placeholders_per_row = vec!["?"; columns.len()].join(", ");
366 let value_groups: Vec<String> = (0..chunk.len())
367 .map(|_| format!("({})", placeholders_per_row))
368 .collect();
369
370 let insert_sql = format!(
371 "INSERT INTO \"{}\" ({}) VALUES {}",
372 self.table_name,
373 quoted_columns.join(", "),
374 value_groups.join(", ")
375 );
376
377 let mut query = sqlx::query(&insert_sql);
378
379 for row in chunk {
381 for column in &columns {
382 let value = row.get(column).unwrap_or(&Value::Null);
383 query = match value {
384 Value::String(s) => query.bind(s),
385 Value::Integer(i) => query.bind(*i),
386 Value::Decimal(d) => {
387 let f: f64 = (*d).try_into().unwrap_or(0.0);
389 query.bind(f)
390 }
391 Value::Boolean(b) => query.bind(*b),
392 Value::Date(dt) => query.bind(dt.to_rfc3339()),
393 Value::Json(j) => query
394 .bind(serde_json::to_string(j).unwrap_or_else(|_| "{}".to_string())),
395 Value::Null => query.bind(None::<String>),
396 };
397 }
398 }
399
400 let result = query.execute(pool).await?;
401 total_written += result.rows_affected() as usize;
402 }
403
404 Ok(total_written)
405 }
406
407 async fn finalize(&mut self) -> Result<()> {
408 Ok(())
410 }
411
412 async fn exists(&self, table_name: &str) -> Result<bool> {
413 if let Some(pool) = &self.pool {
414 let actual_table_name = if table_name.is_empty() {
415 &self.table_name
416 } else {
417 table_name
418 };
419
420 let result =
421 sqlx::query("SELECT name FROM sqlite_master WHERE type='table' AND name=?")
422 .bind(actual_table_name)
423 .fetch_optional(pool)
424 .await?;
425
426 Ok(result.is_some())
427 } else {
428 Ok(false)
429 }
430 }
431
432 async fn truncate(&mut self, table_name: &str) -> Result<()> {
433 if let Some(pool) = &self.pool {
434 let actual_table_name = if table_name.is_empty() {
435 &self.table_name
436 } else {
437 table_name
438 };
439
440 sqlx::query(&format!("DELETE FROM \"{}\"", actual_table_name))
441 .execute(pool)
442 .await?;
443 }
444 Ok(())
445 }
446
447 fn supports_append(&self) -> bool {
448 true
450 }
451}
452
453#[cfg(test)]
454mod tests {
455 use super::*;
456
457 #[tokio::test]
458 async fn test_sqlite_source_new() {
459 let source = SqliteSource::new("test.db#users");
460 assert!(source.is_ok());
461 }
462
463 #[tokio::test]
464 async fn test_sqlite_source_invalid_format() {
465 let source = SqliteSource::new("test.db");
466 assert!(source.is_err());
467 }
468
469 #[tokio::test]
470 async fn test_sqlite_target_new() {
471 let target = SqliteTarget::new("test.db#users");
472 assert!(target.is_ok());
473
474 let target2 = SqliteTarget::new("test.db");
475 assert!(target2.is_ok());
476 }
477}