Skip to main content

crisol_core/data/
sqlite.rs

1//! SQLite connector.
2
3use std::path::{Path, PathBuf};
4
5use rusqlite::types::ValueRef;
6
7use super::column::{Column, DataValue};
8use super::dataset::Dataset;
9use super::source::{ColumnSchema, DataError, DataSource};
10
11/// Most rows one query may load.
12const MAX_ROWS: usize = 5_000_000;
13
14/// A SQLite query exposed as a paged data source.
15/// # Example
16///
17/// ```
18/// use crisol_core::data::SqliteSource;
19/// ```
20pub struct SqliteSource {
21    path: PathBuf,
22    name: String,
23    query: String,
24    data: Dataset,
25    schema: Vec<ColumnSchema>,
26}
27
28impl SqliteSource {
29    #[cfg(feature = "threads")]
30    /// Open a database and read `query` once.
31    ///
32    /// # Errors
33    /// When the database or query fails.
34    pub fn open(path: impl AsRef<Path>, query: impl Into<String>) -> Result<Self, DataError> {
35        let path = path.as_ref().to_path_buf();
36        let query = query.into();
37        let data = read_sqlite(&path, &query)?;
38        let schema = data.columns().iter().map(ColumnSchema::from_column).collect();
39        Ok(Self {
40            name: path
41                .file_name()
42                .and_then(|name| name.to_str())
43                .unwrap_or("data.sqlite")
44                .to_owned(),
45            path,
46            query,
47            data,
48            schema,
49        })
50    }
51
52    /// The file name.
53    pub fn name(&self) -> &str {
54        &self.name
55    }
56
57    /// The database path.
58    pub fn path(&self) -> &Path {
59        &self.path
60    }
61
62    /// The query.
63    pub fn query(&self) -> &str {
64        &self.query
65    }
66
67    /// The parsed data.
68    pub fn data(&self) -> &Dataset {
69        &self.data
70    }
71
72    /// Re-run the query and replace the data.
73    ///
74    /// # Errors
75    /// When the query fails.
76    #[cfg(feature = "threads")]
77    pub fn refresh(&mut self) -> Result<(), DataError> {
78        self.data = read_sqlite(&self.path, &self.query)?;
79        self.schema = self.data.columns().iter().map(ColumnSchema::from_column).collect();
80        Ok(())
81    }
82}
83
84impl DataSource for SqliteSource {
85    fn schema(&self) -> &[ColumnSchema] {
86        &self.schema
87    }
88
89    fn row_count(&self) -> usize {
90        self.data.row_count()
91    }
92
93    fn read_range(&self, range: std::ops::Range<usize>) -> Result<Dataset, DataError> {
94        super::source::check_range(&range, self.row_count())?;
95        Ok(self.data.slice(range))
96    }
97}
98
99/// Run a query and convert every row to a dataset.
100///
101/// # Errors
102/// When the database or query fails.
103#[cfg(feature = "threads")]
104/// # Example
105///
106/// ```
107/// use crisol_core::data::read_sqlite;
108/// ```
109pub fn read_sqlite(path: impl AsRef<Path>, query: &str) -> Result<Dataset, DataError> {
110    // Read-only and never creating: a viewer must not modify the database, and a typo in
111    // the path must not leave an empty file behind.
112    let connection = rusqlite::Connection::open_with_flags(
113        path,
114        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
115    )
116    .map_err(|error| DataError::Connector(error.to_string()))?;
117    let mut statement = connection
118        .prepare(query)
119        .map_err(|error| DataError::Connector(error.to_string()))?;
120    if !statement.readonly() {
121        return Err(DataError::Connector("only read-only statements are allowed".to_owned()));
122    }
123    let names: Vec<String> = statement.column_names().iter().map(|name| (*name).to_owned()).collect();
124    let mut rows = statement
125        .query([])
126        .map_err(|error| DataError::Connector(error.to_string()))?;
127    let mut values: Vec<Vec<DataValue>> = Vec::new();
128    while let Some(row) = rows.next().map_err(|error| DataError::Connector(error.to_string()))? {
129        let mut record = Vec::with_capacity(names.len());
130        for index in 0..names.len() {
131            let value = row
132                .get_ref(index)
133                .map_err(|error| DataError::Connector(error.to_string()))?;
134            record.push(match value {
135                ValueRef::Null => DataValue::Null,
136                ValueRef::Integer(value) => DataValue::Int(value),
137                ValueRef::Real(value) => DataValue::Float(value),
138                ValueRef::Text(value) => DataValue::Text(String::from_utf8_lossy(value).into_owned()),
139                ValueRef::Blob(value) => DataValue::Text(format!("0x{}", hex(value))),
140            });
141        }
142        values.push(record);
143        // A recursive CTE can produce rows without end.
144        if values.len() > MAX_ROWS {
145            return Err(DataError::Connector(format!(
146                "the query returned more than {MAX_ROWS} rows"
147            )));
148        }
149    }
150    Ok(dataset_from_values(&names, &values))
151}
152
153fn dataset_from_values(names: &[String], rows: &[Vec<DataValue>]) -> Dataset {
154    let columns: Vec<Column> = names
155        .iter()
156        .enumerate()
157        .map(|(index, name)| {
158            let values: Vec<DataValue> = rows
159                .iter()
160                .map(|row| row.get(index).cloned().unwrap_or(DataValue::Null))
161                .collect();
162            column_from_values(name, &values)
163        })
164        .collect();
165    Dataset::from_columns(columns)
166}
167
168fn column_from_values(name: &str, values: &[DataValue]) -> Column {
169    let non_null: Vec<&DataValue> = values
170        .iter()
171        .filter(|value| !matches!(value, DataValue::Null))
172        .collect();
173    let all_int = !non_null.is_empty() && non_null.iter().all(|value| matches!(value, DataValue::Int(_)));
174    let all_float = !non_null.is_empty()
175        && non_null
176            .iter()
177            .all(|value| matches!(value, DataValue::Int(_) | DataValue::Float(_)));
178    let column = if all_int {
179        Column::ints(
180            name,
181            values
182                .iter()
183                .map(|value| if let DataValue::Int(value) = value { *value } else { 0 })
184                .collect::<Vec<_>>(),
185        )
186    } else if all_float {
187        Column::floats(
188            name,
189            values
190                .iter()
191                .map(|value| value.as_f64().unwrap_or(f64::NAN))
192                .collect::<Vec<_>>(),
193        )
194    } else {
195        Column::text(
196            name,
197            values
198                .iter()
199                // `{other:?}` printed `Int(5)` in a mixed column.
200                .map(DataValue::display_text)
201                .collect::<Vec<_>>(),
202        )
203    };
204    with_validity(column, values)
205}
206
207fn with_validity(column: Column, values: &[DataValue]) -> Column {
208    let valid: Vec<bool> = values.iter().map(|value| !matches!(value, DataValue::Null)).collect();
209    if valid.iter().all(|valid| *valid) {
210        column
211    } else {
212        column.with_validity(valid)
213    }
214}
215
216fn hex(bytes: &[u8]) -> String {
217    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223
224    #[cfg(feature = "threads")]
225    #[test]
226    fn sqlite_query_becomes_a_typed_dataset() {
227        let path = std::path::PathBuf::from("/tmp").join("crisol-sqlite-test.db");
228        let _ = std::fs::remove_file(&path);
229        {
230            let connection = rusqlite::Connection::open(&path).expect("open");
231            connection
232                .execute_batch("CREATE TABLE trace (t REAL, cycle INTEGER, state TEXT); INSERT INTO trace VALUES (0.5, 2, 'run'), (0.1, 1, 'idle');")
233                .expect("setup");
234        }
235        let source = SqliteSource::open(&path, "SELECT t, cycle, state FROM trace ORDER BY cycle").expect("source");
236        assert_eq!(source.row_count(), 2);
237        assert_eq!(source.schema()[1].kind, crate::data::ColumnType::Int);
238        assert_eq!(source.data().cell(1, 2), crate::data::CellValue::Text("run"));
239        assert_eq!(source.read_range(0..1).expect("page").row_count(), 1);
240        let _ = std::fs::remove_file(path);
241    }
242}