datafusion_remote_table/connection/
sqlite.rs

1use crate::connection::{RemoteDbType, projections_contains};
2use crate::{
3    Connection, ConnectionOptions, DFResult, Pool, RemoteField, RemoteSchema, RemoteSchemaRef,
4    RemoteType, SqliteType,
5};
6use datafusion::arrow::array::{
7    ArrayBuilder, ArrayRef, BinaryBuilder, Float64Builder, Int32Builder, Int64Builder, NullBuilder,
8    RecordBatch, RecordBatchOptions, StringBuilder, make_builder,
9};
10use datafusion::arrow::datatypes::{DataType, SchemaRef};
11use datafusion::common::{DataFusionError, project_schema};
12use datafusion::execution::SendableRecordBatchStream;
13use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
14use derive_getters::Getters;
15use derive_with::With;
16use itertools::Itertools;
17use log::{debug, error};
18use rusqlite::types::ValueRef;
19use rusqlite::{Column, Row, Rows};
20use std::any::Any;
21use std::collections::HashMap;
22use std::path::PathBuf;
23use std::sync::Arc;
24
25#[derive(Debug, Clone, With, Getters)]
26pub struct SqliteConnectionOptions {
27    pub path: PathBuf,
28    pub stream_chunk_size: usize,
29}
30
31impl SqliteConnectionOptions {
32    pub fn new(path: PathBuf) -> Self {
33        Self {
34            path,
35            stream_chunk_size: 2048,
36        }
37    }
38}
39
40impl From<SqliteConnectionOptions> for ConnectionOptions {
41    fn from(options: SqliteConnectionOptions) -> Self {
42        ConnectionOptions::Sqlite(options)
43    }
44}
45
46#[derive(Debug)]
47pub struct SqlitePool {
48    path: PathBuf,
49}
50
51pub async fn connect_sqlite(options: &SqliteConnectionOptions) -> DFResult<SqlitePool> {
52    let _ = rusqlite::Connection::open(&options.path).map_err(|e| {
53        DataFusionError::Execution(format!("Failed to open sqlite connection: {e:?}"))
54    })?;
55    Ok(SqlitePool {
56        path: options.path.clone(),
57    })
58}
59
60#[async_trait::async_trait]
61impl Pool for SqlitePool {
62    async fn get(&self) -> DFResult<Arc<dyn Connection>> {
63        Ok(Arc::new(SqliteConnection {
64            path: self.path.clone(),
65        }))
66    }
67}
68
69#[derive(Debug)]
70pub struct SqliteConnection {
71    path: PathBuf,
72}
73
74#[async_trait::async_trait]
75impl Connection for SqliteConnection {
76    fn as_any(&self) -> &dyn Any {
77        self
78    }
79
80    async fn infer_schema(&self, sql: &str) -> DFResult<RemoteSchemaRef> {
81        let sql = RemoteDbType::Sqlite.query_limit_1(sql);
82        let conn = rusqlite::Connection::open(&self.path).map_err(|e| {
83            DataFusionError::Execution(format!("Failed to open sqlite connection: {e:?}"))
84        })?;
85        let mut stmt = conn.prepare(&sql).map_err(|e| {
86            DataFusionError::Execution(format!("Failed to prepare sqlite statement: {e:?}"))
87        })?;
88        let columns: Vec<OwnedColumn> =
89            stmt.columns().iter().map(sqlite_col_to_owned_col).collect();
90        let rows = stmt.query([]).map_err(|e| {
91            DataFusionError::Execution(format!("Failed to query sqlite statement: {e:?}"))
92        })?;
93
94        let remote_schema = Arc::new(build_remote_schema(columns.as_slice(), rows)?);
95        Ok(remote_schema)
96    }
97
98    async fn query(
99        &self,
100        conn_options: &ConnectionOptions,
101        sql: &str,
102        table_schema: SchemaRef,
103        projection: Option<&Vec<usize>>,
104        unparsed_filters: &[String],
105        limit: Option<usize>,
106    ) -> DFResult<SendableRecordBatchStream> {
107        let projected_schema = project_schema(&table_schema, projection)?;
108        let sql = RemoteDbType::Sqlite.rewrite_query(sql, unparsed_filters, limit);
109        debug!("[remote-table] executing sqlite query: {sql}");
110
111        let (tx, mut rx) = tokio::sync::mpsc::channel::<DFResult<RecordBatch>>(1);
112        let conn = rusqlite::Connection::open(&self.path).map_err(|e| {
113            DataFusionError::Execution(format!("Failed to open sqlite connection: {e:?}"))
114        })?;
115
116        let projection = projection.cloned();
117        let chunk_size = conn_options.stream_chunk_size();
118
119        spawn_background_task(tx, conn, sql, table_schema, projection, chunk_size);
120
121        let stream = async_stream::stream! {
122            while let Some(batch) = rx.recv().await {
123                yield batch;
124            }
125        };
126        Ok(Box::pin(RecordBatchStreamAdapter::new(
127            projected_schema,
128            stream,
129        )))
130    }
131}
132
133#[derive(Debug)]
134struct OwnedColumn {
135    name: String,
136    decl_type: Option<String>,
137}
138
139fn sqlite_col_to_owned_col(sqlite_col: &Column) -> OwnedColumn {
140    OwnedColumn {
141        name: sqlite_col.name().to_string(),
142        decl_type: sqlite_col.decl_type().map(|x| x.to_string()),
143    }
144}
145
146fn decl_type_to_remote_type(decl_type: &str) -> DFResult<SqliteType> {
147    if ["tinyint", "smallint", "int", "integer", "bigint"].contains(&decl_type) {
148        return Ok(SqliteType::Integer);
149    }
150    if ["real", "float", "double"].contains(&decl_type) {
151        return Ok(SqliteType::Real);
152    }
153    if decl_type.starts_with("real") {
154        return Ok(SqliteType::Real);
155    }
156    if ["text", "varchar", "char", "string"].contains(&decl_type) {
157        return Ok(SqliteType::Text);
158    }
159    if decl_type.starts_with("char")
160        || decl_type.starts_with("varchar")
161        || decl_type.starts_with("text")
162    {
163        return Ok(SqliteType::Text);
164    }
165    if ["binary", "varbinary", "tinyblob", "blob"].contains(&decl_type) {
166        return Ok(SqliteType::Blob);
167    }
168    if decl_type.starts_with("binary") || decl_type.starts_with("varbinary") {
169        return Ok(SqliteType::Blob);
170    }
171    Err(DataFusionError::NotImplemented(format!(
172        "Unsupported sqlite decl type: {decl_type}",
173    )))
174}
175
176fn build_remote_schema(columns: &[OwnedColumn], mut rows: Rows) -> DFResult<RemoteSchema> {
177    let mut remote_field_map = HashMap::with_capacity(columns.len());
178    let mut unknown_cols = vec![];
179    for (col_idx, col) in columns.iter().enumerate() {
180        if let Some(decl_type) = &col.decl_type {
181            let remote_type =
182                RemoteType::Sqlite(decl_type_to_remote_type(&decl_type.to_ascii_lowercase())?);
183            remote_field_map.insert(col_idx, RemoteField::new(&col.name, remote_type, true));
184        } else {
185            // None for expressions
186            unknown_cols.push(col_idx);
187        }
188    }
189
190    if !unknown_cols.is_empty() {
191        while let Some(row) = rows.next().map_err(|e| {
192            DataFusionError::Execution(format!("Failed to get next row from sqlite: {e:?}"))
193        })? {
194            let mut to_be_removed = vec![];
195            for col_idx in unknown_cols.iter() {
196                let value_ref = row.get_ref(*col_idx).map_err(|e| {
197                    DataFusionError::Execution(format!(
198                        "Failed to get value ref for column {col_idx}: {e:?}"
199                    ))
200                })?;
201                match value_ref {
202                    ValueRef::Null => {}
203                    ValueRef::Integer(_) => {
204                        remote_field_map.insert(
205                            *col_idx,
206                            RemoteField::new(
207                                columns[*col_idx].name.clone(),
208                                RemoteType::Sqlite(SqliteType::Integer),
209                                true,
210                            ),
211                        );
212                        to_be_removed.push(*col_idx);
213                    }
214                    ValueRef::Real(_) => {
215                        remote_field_map.insert(
216                            *col_idx,
217                            RemoteField::new(
218                                columns[*col_idx].name.clone(),
219                                RemoteType::Sqlite(SqliteType::Real),
220                                true,
221                            ),
222                        );
223                        to_be_removed.push(*col_idx);
224                    }
225                    ValueRef::Text(_) => {
226                        remote_field_map.insert(
227                            *col_idx,
228                            RemoteField::new(
229                                columns[*col_idx].name.clone(),
230                                RemoteType::Sqlite(SqliteType::Text),
231                                true,
232                            ),
233                        );
234                        to_be_removed.push(*col_idx);
235                    }
236                    ValueRef::Blob(_) => {
237                        remote_field_map.insert(
238                            *col_idx,
239                            RemoteField::new(
240                                columns[*col_idx].name.clone(),
241                                RemoteType::Sqlite(SqliteType::Blob),
242                                true,
243                            ),
244                        );
245                        to_be_removed.push(*col_idx);
246                    }
247                }
248            }
249            for col_idx in to_be_removed.iter() {
250                unknown_cols.retain(|&x| x != *col_idx);
251            }
252            if unknown_cols.is_empty() {
253                break;
254            }
255        }
256    }
257
258    if !unknown_cols.is_empty() {
259        return Err(DataFusionError::NotImplemented(format!(
260            "Failed to infer sqlite decl type for columns: {unknown_cols:?}"
261        )));
262    }
263    let remote_fields = remote_field_map
264        .into_iter()
265        .sorted_by_key(|entry| entry.0)
266        .map(|entry| entry.1)
267        .collect::<Vec<_>>();
268    Ok(RemoteSchema::new(remote_fields))
269}
270
271fn spawn_background_task(
272    tx: tokio::sync::mpsc::Sender<DFResult<RecordBatch>>,
273    conn: rusqlite::Connection,
274    sql: String,
275    table_schema: SchemaRef,
276    projection: Option<Vec<usize>>,
277    chunk_size: usize,
278) {
279    std::thread::spawn(move || {
280        let runtime = match tokio::runtime::Builder::new_current_thread().build() {
281            Ok(runtime) => runtime,
282            Err(e) => {
283                error!("Failed to create tokio runtime to run sqlite query: {e:?}");
284                return;
285            }
286        };
287        let local_set = tokio::task::LocalSet::new();
288        local_set.block_on(&runtime, async move {
289            let mut stmt = match conn.prepare(&sql) {
290                Ok(stmt) => stmt,
291                Err(e) => {
292                    let _ = tx
293                        .send(Err(DataFusionError::Execution(format!(
294                            "Failed to prepare sqlite statement: {e:?}"
295                        ))))
296                        .await;
297                    return;
298                }
299            };
300            let columns: Vec<OwnedColumn> =
301                stmt.columns().iter().map(sqlite_col_to_owned_col).collect();
302            let mut rows = match stmt.query([]) {
303                Ok(rows) => rows,
304                Err(e) => {
305                    let _ = tx
306                        .send(Err(DataFusionError::Execution(format!(
307                            "Failed to query sqlite statement: {e:?}"
308                        ))))
309                        .await;
310                    return;
311                }
312            };
313
314            loop {
315                let (batch, is_empty) = match rows_to_batch(
316                    &mut rows,
317                    &table_schema,
318                    &columns,
319                    projection.as_ref(),
320                    chunk_size,
321                ) {
322                    Ok((batch, is_empty)) => (batch, is_empty),
323                    Err(e) => {
324                        let _ = tx
325                            .send(Err(DataFusionError::Execution(format!(
326                                "Failed to convert rows to batch: {e:?}"
327                            ))))
328                            .await;
329                        return;
330                    }
331                };
332                if is_empty {
333                    break;
334                }
335                if tx.send(Ok(batch)).await.is_err() {
336                    return;
337                }
338            }
339        });
340    });
341}
342
343fn rows_to_batch(
344    rows: &mut Rows,
345    table_schema: &SchemaRef,
346    columns: &[OwnedColumn],
347    projection: Option<&Vec<usize>>,
348    chunk_size: usize,
349) -> DFResult<(RecordBatch, bool)> {
350    let projected_schema = project_schema(table_schema, projection)?;
351    let mut array_builders = vec![];
352    for field in table_schema.fields() {
353        let builder = make_builder(field.data_type(), 1000);
354        array_builders.push(builder);
355    }
356
357    let mut is_empty = true;
358    let mut row_count = 0;
359    while let Some(row) = rows.next().map_err(|e| {
360        DataFusionError::Execution(format!("Failed to get next row from sqlite: {e:?}"))
361    })? {
362        is_empty = false;
363        row_count += 1;
364        append_rows_to_array_builders(
365            row,
366            table_schema,
367            columns,
368            projection,
369            array_builders.as_mut_slice(),
370        )?;
371        if row_count >= chunk_size {
372            break;
373        }
374    }
375
376    let projected_columns = array_builders
377        .into_iter()
378        .enumerate()
379        .filter(|(idx, _)| projections_contains(projection, *idx))
380        .map(|(_, mut builder)| builder.finish())
381        .collect::<Vec<ArrayRef>>();
382    let options = RecordBatchOptions::new().with_row_count(Some(row_count));
383    Ok((
384        RecordBatch::try_new_with_options(projected_schema, projected_columns, &options)?,
385        is_empty,
386    ))
387}
388
389macro_rules! handle_primitive_type {
390    ($builder:expr, $field:expr, $col:expr, $builder_ty:ty, $value_ty:ty, $row:expr, $index:expr) => {{
391        let builder = $builder
392            .as_any_mut()
393            .downcast_mut::<$builder_ty>()
394            .unwrap_or_else(|| {
395                panic!(
396                    "Failed to downcast builder to {} for {:?} and {:?}",
397                    stringify!($builder_ty),
398                    $field,
399                    $col
400                )
401            });
402
403        let v: Option<$value_ty> = $row.get($index).map_err(|e| {
404            DataFusionError::Execution(format!(
405                "Failed to get optional {} value for {:?} and {:?}: {e:?}",
406                stringify!($value_ty),
407                $field,
408                $col
409            ))
410        })?;
411
412        match v {
413            Some(v) => builder.append_value(v),
414            None => builder.append_null(),
415        }
416    }};
417}
418
419fn append_rows_to_array_builders(
420    row: &Row,
421    table_schema: &SchemaRef,
422    columns: &[OwnedColumn],
423    projection: Option<&Vec<usize>>,
424    array_builders: &mut [Box<dyn ArrayBuilder>],
425) -> DFResult<()> {
426    for (idx, field) in table_schema.fields.iter().enumerate() {
427        if !projections_contains(projection, idx) {
428            continue;
429        }
430        let builder = &mut array_builders[idx];
431        let col = columns.get(idx);
432        match field.data_type() {
433            DataType::Null => {
434                let builder = builder
435                    .as_any_mut()
436                    .downcast_mut::<NullBuilder>()
437                    .expect("Failed to downcast builder to NullBuilder");
438                builder.append_null();
439            }
440            DataType::Int32 => {
441                handle_primitive_type!(builder, field, col, Int32Builder, i32, row, idx);
442            }
443            DataType::Int64 => {
444                handle_primitive_type!(builder, field, col, Int64Builder, i64, row, idx);
445            }
446            DataType::Float64 => {
447                handle_primitive_type!(builder, field, col, Float64Builder, f64, row, idx);
448            }
449            DataType::Utf8 => {
450                handle_primitive_type!(builder, field, col, StringBuilder, String, row, idx);
451            }
452            DataType::Binary => {
453                handle_primitive_type!(builder, field, col, BinaryBuilder, Vec<u8>, row, idx);
454            }
455            _ => {
456                return Err(DataFusionError::NotImplemented(format!(
457                    "Unsupported data type {:?} for col: {:?}",
458                    field.data_type(),
459                    col
460                )));
461            }
462        }
463    }
464    Ok(())
465}