filemanager 0.1.1

Unified file abstraction for local and cloud files with caching options and support for multiple formats.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::marker::PhantomData;
use std::path::PathBuf;

use rusqlite::{Connection, OpenFlags};

use crate::{CacheError, Uri, UriError};

/// Errors from SQL read operations.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum SqlError {
    /// An I/O error occurred.
    #[error(transparent)]
    Io(#[from] std::io::Error),
    /// A SQLite error occurred.
    #[error("sql error: {0}")]
    Sql(#[source] Box<dyn std::error::Error + Send + Sync>),
    /// The requested table was not found.
    #[error("table not found: {0}")]
    TableNotFound(String),
    /// A deserialization error occurred.
    #[error("deserialize error: {0}")]
    Deserialize(#[source] Box<dyn std::error::Error + Send + Sync>),
    /// The requested row range is out of bounds.
    #[error("out of bounds: {start}..{end} (rows {rows})")]
    OutOfBounds {
        start: usize,
        end: usize,
        rows: usize,
    },
    /// Binary read error occurred while reading the underlying file.
    #[error(transparent)]
    Uri(#[from] UriError),
    #[error(transparent)]
    Cache(#[from] CacheError),
}

/// Reads SQLite databases from a [`ManagedFile`].
///
/// # Examples
///
/// ```
/// use filemanager::formats::sql::SqlReader;
///
/// let dir = tempfile::tempdir().unwrap();
/// let path = dir.path().join("test.db");
/// {
///     let conn = rusqlite::Connection::open(&path).unwrap();
///     conn.execute_batch("CREATE TABLE items (id INTEGER, name TEXT);").unwrap();
/// }
/// let reader = SqlReader::from(&path).unwrap();
/// let tables = reader.tables().unwrap();
/// assert!(tables.contains(&"items".to_string()));
/// ```
#[derive(Debug)]
pub struct SqlReader {
    path: PathBuf,
    original_uri: Uri,
    effective_uri: Uri,
}

impl SqlReader {
    /// Creates a `SqlReader` from a [`ManagedFile`].
    ///
    /// # Examples
    ///
    /// ```
    /// use filemanager::formats::sql::SqlReader;
    ///
    /// let dir = tempfile::tempdir().unwrap();
    /// let path = dir.path().join("test.db");
    /// {
    ///     let conn = rusqlite::Connection::open(&path).unwrap();
    ///     conn.execute_batch("CREATE TABLE t (x INTEGER);").unwrap();
    /// }
    /// let _reader = SqlReader::from(&path).unwrap();
    /// ```
    pub fn from(uri: impl Into<Uri>) -> Result<Self, SqlError> {
        let original_uri = uri.into();
        let effective_uri = original_uri.force_cache()?;
        let path = effective_uri.as_path().ok_or_else(|| {
            SqlError::Uri(crate::UriError::InvalidUri(effective_uri.clone()))
        })?;
        // Verify the file is readable
        let _conn = Connection::open_with_flags(
            &path,
            OpenFlags::SQLITE_OPEN_READ_ONLY,
        )
        .map_err(|e| SqlError::Sql(Box::new(e)))?;
        Ok(SqlReader {
            path,
            original_uri,
            effective_uri,
        })
    }

    /// Returns the names of all tables in the database.
    ///
    /// # Examples
    ///
    /// ```
    /// use filemanager::formats::sql::SqlReader;
    ///
    /// let dir = tempfile::tempdir().unwrap();
    /// let path = dir.path().join("test.db");
    /// {
    ///     let conn = rusqlite::Connection::open(&path).unwrap();
    ///     conn.execute_batch("CREATE TABLE foo (x INTEGER); CREATE TABLE bar (y TEXT);").unwrap();
    /// }
    /// let reader = SqlReader::from(&path).unwrap();
    /// let mut tables = reader.tables().unwrap();
    /// tables.sort();
    /// assert_eq!(tables, vec!["bar", "foo"]);
    /// ```
    pub fn tables(&self) -> Result<Vec<String>, SqlError> {
        let conn = Connection::open_with_flags(
            &self.path,
            OpenFlags::SQLITE_OPEN_READ_ONLY,
        )
        .map_err(|e| SqlError::Sql(Box::new(e)))?;
        let mut stmt = conn
            .prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
            .map_err(|e| SqlError::Sql(Box::new(e)))?;
        let names = stmt
            .query_map([], |row| row.get::<_, String>(0))
            .map_err(|e| SqlError::Sql(Box::new(e)))?
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| SqlError::Sql(Box::new(e)))?;
        Ok(names)
    }

    /// Returns a typed [`SqlTable`] for the given table name.
    ///
    /// # Examples
    ///
    /// ```
    /// use filemanager::formats::sql::SqlReader;
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize, Debug)]
    /// struct Item { id: i64, name: String }
    ///
    /// let dir = tempfile::tempdir().unwrap();
    /// let path = dir.path().join("test.db");
    /// {
    ///     let conn = rusqlite::Connection::open(&path).unwrap();
    ///     conn.execute_batch(
    ///         "CREATE TABLE items (id INTEGER, name TEXT); INSERT INTO items VALUES (1, 'Alice');"
    ///     ).unwrap();
    /// }
    /// let reader = SqlReader::from(&path).unwrap();
    /// let table = reader.from_table::<Item>("items").unwrap();
    /// assert_eq!(table.shape(), (1, 2));
    /// ```
    pub fn from_table<T>(&self, name: &str) -> Result<SqlTable<T>, SqlError> {
        let conn = Connection::open_with_flags(
            &self.path,
            OpenFlags::SQLITE_OPEN_READ_ONLY,
        )
        .map_err(|e| SqlError::Sql(Box::new(e)))?;

        // Check table exists
        let exists: bool = conn
            .query_row(
                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?1",
                rusqlite::params![name],
                |row| row.get::<_, i64>(0),
            )
            .map_err(|e| SqlError::Sql(Box::new(e)))?
            > 0;

        if !exists {
            return Err(SqlError::TableNotFound(name.to_string()));
        }

        let rows: usize =
            conn.query_row(
                &format!("SELECT COUNT(*) FROM \"{}\"", name),
                [],
                |row| row.get::<_, i64>(0),
            )
            .map_err(|e| SqlError::Sql(Box::new(e)))? as usize;

        let mut pragma_stmt = conn
            .prepare(&format!("PRAGMA table_info(\"{}\")", name))
            .map_err(|e| SqlError::Sql(Box::new(e)))?;
        let cols = pragma_stmt
            .query_map([], |_| Ok(()))
            .map_err(|e| SqlError::Sql(Box::new(e)))?
            .count();

        Ok(SqlTable {
            db_path: self.path.clone(),
            table_name: name.to_string(),
            rows,
            cols,
            _marker: PhantomData,
        })
    }

    pub fn original_uri(&self) -> &Uri {
        &self.original_uri
    }

    pub fn effective_uri(&self) -> &Uri {
        &self.effective_uri
    }
}

/// A typed view of a SQLite table.
///
/// # Examples
///
/// ```
/// use filemanager::formats::sql::SqlReader;
/// use serde::Deserialize;
///
/// #[derive(Deserialize, Debug, PartialEq)]
/// struct Item { id: i64, name: String }
///
/// let dir = tempfile::tempdir().unwrap();
/// let path = dir.path().join("test.db");
/// {
///     let conn = rusqlite::Connection::open(&path).unwrap();
///     conn.execute_batch(
///         "CREATE TABLE items (id INTEGER, name TEXT); INSERT INTO items VALUES (1, 'Alice');"
///     ).unwrap();
/// }
/// let reader = SqlReader::from(&path).unwrap();
/// let table = reader.from_table::<Item>("items").unwrap();
/// let items = table.read_all().unwrap();
/// assert_eq!(items[0], Item { id: 1, name: "Alice".into() });
/// ```
#[derive(Debug)]
pub struct SqlTable<T> {
    db_path: PathBuf,
    table_name: String,
    rows: usize,
    cols: usize,
    _marker: PhantomData<T>,
}

impl<T: for<'de> serde::Deserialize<'de>> SqlTable<T> {
    /// Returns the `(rows, cols)` shape of the table.
    ///
    /// # Examples
    ///
    /// ```
    /// use filemanager::formats::sql::SqlReader;
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct Row { id: i64 }
    ///
    /// let dir = tempfile::tempdir().unwrap();
    /// let path = dir.path().join("test.db");
    /// {
    ///     let conn = rusqlite::Connection::open(&path).unwrap();
    ///     conn.execute_batch("CREATE TABLE t (id INTEGER); INSERT INTO t VALUES (1);").unwrap();
    /// }
    /// let reader = SqlReader::from(&path).unwrap();
    /// let table = reader.from_table::<Row>("t").unwrap();
    /// assert_eq!(table.shape(), (1, 1));
    /// ```
    #[must_use]
    pub fn shape(&self) -> (usize, usize) {
        (self.rows, self.cols)
    }

    /// Returns `true` if the table has no rows.
    ///
    /// # Examples
    ///
    /// ```
    /// use filemanager::formats::sql::SqlReader;
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct Row { id: i64 }
    ///
    /// let dir = tempfile::tempdir().unwrap();
    /// let path = dir.path().join("test.db");
    /// {
    ///     let conn = rusqlite::Connection::open(&path).unwrap();
    ///     conn.execute_batch("CREATE TABLE empty_table (id INTEGER);").unwrap();
    /// }
    /// let reader = SqlReader::from(&path).unwrap();
    /// let table = reader.from_table::<Row>("empty_table").unwrap();
    /// assert!(table.is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.rows == 0
    }

    /// Reads all rows from the table.
    ///
    /// # Examples
    ///
    /// ```
    /// use filemanager::formats::sql::SqlReader;
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize, Debug, PartialEq)]
    /// struct Row { val: i64 }
    ///
    /// let dir = tempfile::tempdir().unwrap();
    /// let path = dir.path().join("test.db");
    /// {
    ///     let conn = rusqlite::Connection::open(&path).unwrap();
    ///     conn.execute_batch(
    ///         "CREATE TABLE t (val INTEGER); INSERT INTO t VALUES (10); INSERT INTO t VALUES (20);"
    ///     ).unwrap();
    /// }
    /// let reader = SqlReader::from(&path).unwrap();
    /// let table = reader.from_table::<Row>("t").unwrap();
    /// assert_eq!(table.read_all().unwrap(), vec![Row { val: 10 }, Row { val: 20 }]);
    /// ```
    pub fn read_all(&self) -> Result<Vec<T>, SqlError> {
        self.query(self.rows, 0)
    }

    /// Reads a row range from the table.
    ///
    /// # Examples
    ///
    /// ```
    /// use filemanager::formats::sql::SqlReader;
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize, Debug, PartialEq)]
    /// struct Row { val: i64 }
    ///
    /// let dir = tempfile::tempdir().unwrap();
    /// let path = dir.path().join("test.db");
    /// {
    ///     let conn = rusqlite::Connection::open(&path).unwrap();
    ///     conn.execute_batch(
    ///         "CREATE TABLE t (val INTEGER); INSERT INTO t VALUES (1); INSERT INTO t VALUES (2); INSERT INTO t VALUES (3);"
    ///     ).unwrap();
    /// }
    /// let reader = SqlReader::from(&path).unwrap();
    /// let table = reader.from_table::<Row>("t").unwrap();
    /// assert_eq!(table.read_range(1..3).unwrap(), vec![Row { val: 2 }, Row { val: 3 }]);
    /// ```
    pub fn read_range(
        &self,
        range: std::ops::Range<usize>,
    ) -> Result<Vec<T>, SqlError> {
        if range.end > self.rows {
            return Err(SqlError::OutOfBounds {
                start: range.start,
                end: range.end,
                rows: self.rows,
            });
        }
        let limit = range.end - range.start;
        let offset = range.start;
        self.query(limit, offset)
    }

    fn query(&self, limit: usize, offset: usize) -> Result<Vec<T>, SqlError> {
        let conn = Connection::open_with_flags(
            &self.db_path,
            OpenFlags::SQLITE_OPEN_READ_ONLY,
        )
        .map_err(|e| SqlError::Sql(Box::new(e)))?;

        let sql = format!(
            "SELECT * FROM \"{}\" LIMIT {} OFFSET {}",
            self.table_name, limit, offset
        );
        let mut stmt =
            conn.prepare(&sql).map_err(|e| SqlError::Sql(Box::new(e)))?;

        let col_names: Vec<String> = stmt
            .column_names()
            .into_iter()
            .map(|s| s.to_string())
            .collect();

        let rows = stmt
            .query_map([], |row| {
                let mut map = serde_json::Map::new();
                for (i, col) in col_names.iter().enumerate() {
                    let val: rusqlite::types::Value = row.get(i)?;
                    map.insert(col.clone(), rusqlite_value_to_json(val));
                }
                Ok(map)
            })
            .map_err(|e| SqlError::Sql(Box::new(e)))?;

        let mut result = Vec::with_capacity(limit);
        for row_result in rows {
            let map = row_result.map_err(|e| SqlError::Sql(Box::new(e)))?;
            let value = serde_json::Value::Object(map);
            // if let Ok(item) = serde_json::from_value::<T>(value) {
            //     result.push(item);
            // }
            let item = serde_json::from_value::<T>(value)
                .map_err(|e| SqlError::Deserialize(Box::new(e)))?;
            result.push(item);
        }
        Ok(result)
    }
}

fn rusqlite_value_to_json(v: rusqlite::types::Value) -> serde_json::Value {
    match v {
        rusqlite::types::Value::Null => serde_json::Value::Null,
        rusqlite::types::Value::Integer(i) => serde_json::json!(i),
        rusqlite::types::Value::Real(f) => serde_json::Number::from_f64(f)
            .map(serde_json::Value::Number)
            .unwrap_or(serde_json::Value::Null),
        rusqlite::types::Value::Text(s) => serde_json::Value::String(s),
        rusqlite::types::Value::Blob(_) => serde_json::Value::Null,
    }
}