sqlarfs 0.1.1

A file archive format and virtual filesystem backed by a SQLite database
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use std::path::PathBuf;
use std::time::{self, Duration, SystemTime, UNIX_EPOCH};

use rusqlite::blob::Blob;
use rusqlite::{OptionalExtension, Savepoint};

use crate::list::SortDirection;
use crate::metadata::SYMLINK_MODE;

use super::list::{ListEntries, ListEntry, ListMapFunc, ListOptions, ListSort};
use super::metadata::{FileMetadata, FileMode, FileType, DIR_MODE, FILE_MODE, TYPE_MASK};
use super::util::u64_from_usize;

#[derive(Debug)]
enum InnerTransaction<'conn> {
    Transaction(rusqlite::Transaction<'conn>),
    Savepoint(rusqlite::Savepoint<'conn>),
}

pub struct FileBlob<'conn> {
    blob: Blob<'conn>,
    original_size: u64,
}

impl<'conn> FileBlob<'conn> {
    pub fn is_compressed(&self) -> bool {
        u64_from_usize(self.blob.len()) != self.original_size
    }

    pub fn into_blob(self) -> Blob<'conn> {
        self.blob
    }
}

#[derive(Debug)]
pub struct BlobSize {
    // The original size of the blob (the `sz` column).
    pub original: u64,

    // The actual size of the blob (the compressed size, if it's compressed).
    pub actual: u64,
}

impl BlobSize {
    pub fn is_compressed(&self) -> bool {
        self.actual != self.original
    }
}

// Methods on this type map 1:1 to SQL queries. rusqlite errors are handled and converted to
// sqlarfs errors.
#[derive(Debug)]
pub struct Store<'conn> {
    inner: InnerTransaction<'conn>,
}

impl<'conn> Store<'conn> {
    pub fn new(tx: rusqlite::Transaction<'conn>) -> Self {
        Self {
            inner: InnerTransaction::Transaction(tx),
        }
    }

    pub fn into_tx(self) -> rusqlite::Transaction<'conn> {
        match self.inner {
            InnerTransaction::Transaction(tx) => tx,
            // This will only ever be the case in the middle of a [`Store::exec`] block, where it's
            // not possible call this method.
            InnerTransaction::Savepoint(_) => unreachable!(),
        }
    }

    fn tx(&self) -> &rusqlite::Connection {
        match &self.inner {
            InnerTransaction::Transaction(transaction) => transaction,
            InnerTransaction::Savepoint(savepoint) => savepoint,
        }
    }

    fn savepoint(&mut self) -> crate::Result<Savepoint> {
        Ok(match &mut self.inner {
            InnerTransaction::Transaction(transaction) => transaction.savepoint()?,
            InnerTransaction::Savepoint(savepoint) => savepoint.savepoint()?,
        })
    }

    // Execute the given function inside of a savepoint.
    //
    // Operations that perform multiple writes to the database should wrap them with this method to
    // ensure atomicity and consistency.
    pub fn exec<T, F>(&mut self, f: F) -> crate::Result<T>
    where
        F: FnOnce(&mut Store) -> crate::Result<T>,
    {
        let savepoint = self.savepoint()?;

        let mut store = Store {
            inner: InnerTransaction::Savepoint(savepoint),
        };

        let result = f(&mut store)?;

        let savepoint = match store.inner {
            InnerTransaction::Savepoint(savepoint) => savepoint,
            InnerTransaction::Transaction(_) => unreachable!(),
        };

        savepoint.commit()?;

        Ok(result)
    }

    pub fn create_table(&self, fail_if_exists: bool) -> crate::Result<()> {
        self.tx()
            .execute(
                if fail_if_exists {
                    "
                CREATE TABLE sqlar(
                    name TEXT PRIMARY KEY,
                    mode INT,
                    mtime INT,
                    sz INT,
                    data BLOB
                );
                "
                } else {
                    "
                CREATE TABLE IF NOT EXISTS sqlar(
                    name TEXT PRIMARY KEY,
                    mode INT,
                    mtime INT,
                    sz INT,
                    data BLOB
                );
                "
                },
                (),
            )
            .map_err(|err| {
                if fail_if_exists && matches!(err, rusqlite::Error::SqlInputError { .. }) {
                    crate::Error::SqlarAlreadyExists
                } else {
                    err.into()
                }
            })?;

        Ok(())
    }

    // The file mode is mandatory even though the column in the database is nullable because we
    // need a reliable way to determine whether the file is a directory or not, and we can't set
    // the file type bits in the mode without also setting the permissions bits because we wouldn't
    // have a way to distinguish a file with undefined permissions from a file with `0o000`
    // permissions.
    pub fn create_file(
        &self,
        path: &str,
        kind: FileType,
        mode: FileMode,
        mtime: Option<SystemTime>,
        symlink_target: Option<&str>,
    ) -> crate::Result<()> {
        if symlink_target.is_some() && kind != FileType::Symlink {
            panic!("Tried to create a non-symlink with a symlink target. This is a bug.");
        }

        let unix_mtime = mtime
            .map(|mtime| -> crate::Result<_> {
                Ok(mtime
                    .duration_since(time::UNIX_EPOCH)
                    .map_err(|err| crate::Error::InvalidArgs {
                        reason: err.to_string(),
                    })?
                    .as_secs())
            })
            .transpose()?;

        // While we don't rely on this information to determine the file type, we set the correct
        // file mode bits when we create a file, because that's what the reference implementation
        // does.
        let mode_bits = match kind {
            FileType::File => mode.to_file_mode(),
            FileType::Dir => mode.to_dir_mode(),
            FileType::Symlink => mode.to_symlink_mode(),
        };

        let initial_size = match kind {
            FileType::File | FileType::Dir => 0,
            // The negative size indicates that the file is a symlink.
            FileType::Symlink => -1,
        };

        let initial_data: Option<Box<dyn rusqlite::ToSql>> = match kind {
            FileType::File => Some(Box::<Vec<u8>>::default()),
            // A NULL value in the `data` column indicates that the file is a directory.
            FileType::Dir => None,
            FileType::Symlink => Some(Box::new(
                symlink_target.expect("Tried to create a symlink without a target. This is a bug."),
            )),
        };

        let result = self.tx().execute(
            "INSERT INTO sqlar (name, mode, mtime, sz, data) VALUES (?1, ?2, ?3, ?4, ?5)",
            (path, mode_bits, unix_mtime, initial_size, initial_data),
        );

        match result {
            Ok(_) => Ok(()),
            Err(err)
                if err.sqlite_error_code() == Some(rusqlite::ErrorCode::ConstraintViolation) =>
            {
                Err(crate::Error::FileAlreadyExists { path: path.into() })
            }
            Err(err) => Err(err.into()),
        }
    }

    pub fn delete_file(&self, path: &str) -> crate::Result<()> {
        // Deleting files must be recursive so that the archive doesn't end up with orphan files.
        let num_updated = self.tx().execute(
            "DELETE FROM sqlar WHERE name = ?1 OR name GLOB ?1 || '/?*'",
            (path,),
        )?;

        if num_updated == 0 {
            return Err(crate::Error::FileNotFound { path: path.into() });
        }

        Ok(())
    }

    pub fn open_blob(&self, path: &str, read_only: bool) -> crate::Result<FileBlob> {
        let row = self
            .tx()
            .query_row(
                "SELECT rowid, sz FROM sqlar WHERE name = ?1;",
                (path,),
                |row| Ok((row.get(0)?, row.get(1)?)),
            )
            .optional()?;

        match row {
            Some((row_id, original_size)) => Ok(FileBlob {
                blob: self.tx().blob_open(
                    rusqlite::DatabaseName::Main,
                    "sqlar",
                    "data",
                    row_id,
                    read_only,
                )?,
                original_size,
            }),
            None => Err(crate::Error::FileNotFound { path: path.into() }),
        }
    }

    pub fn allocate_blob(&self, path: &str, len: u64) -> crate::Result<()> {
        let num_updated = self.tx().execute(
            "UPDATE sqlar SET data = zeroblob(?1) WHERE name = ?2",
            (len, path),
        )?;

        if num_updated == 0 {
            return Err(crate::Error::FileNotFound { path: path.into() });
        }

        Ok(())
    }

    pub fn store_blob(&self, path: &str, bytes: &[u8]) -> crate::Result<()> {
        let num_updated = self
            .tx()
            .execute("UPDATE sqlar SET data = ?1 WHERE name = ?2", (bytes, path))?;

        if num_updated == 0 {
            return Err(crate::Error::FileNotFound { path: path.into() });
        }

        Ok(())
    }

    pub fn read_metadata(&self, path: &str) -> crate::Result<FileMetadata> {
        self.tx()
            .query_row(
                "
                SELECT
                    mode,
                    mtime,
                    sz,
                    iif(sz < 0, data, NULL) AS target,
                    data IS NULL AS is_dir
                FROM
                    sqlar
                WHERE
                    name = ?1;
                ",
                (path,),
                |row| {
                    let mode = row.get::<_, Option<u32>>(0)?.map(FileMode::from_mode);
                    let mtime = row
                        .get::<_, Option<u64>>(1)?
                        .map(|mtime_secs| UNIX_EPOCH + Duration::from_secs(mtime_secs));
                    let size: i64 = row.get(2)?;
                    // When the `data` column contains a symlink target, its type is `TEXT`, not
                    // `BLOB`. Remember that columns in SQLite are dynamically typed.
                    let symlink_target: Option<String> = row.get(3)?;
                    let is_dir: bool = row.get(4)?;

                    // We ignore the file mode in the database when determining the file type.
                    Ok(if let Some(target) = symlink_target {
                        FileMetadata::Symlink {
                            mtime,
                            target: PathBuf::from(target),
                        }
                    } else if is_dir {
                        FileMetadata::Dir { mode, mtime }
                    } else {
                        FileMetadata::File {
                            mode,
                            mtime,
                            size: size.try_into().expect("The file size in the database was negative, but we should have already checked for this. This is a bug."),
                        }
                    })
                },
            )
            .optional()?
            .ok_or(crate::Error::FileNotFound { path: path.into() })
    }

    pub fn set_mode(&self, path: &str, mode: Option<FileMode>) -> crate::Result<()> {
        // If the file is a symlink, this is a no-op. Symlinks always have 777 permissions.
        let num_updated = self.tx().execute(
            "UPDATE sqlar SET mode = iif(mode & ?1 = ?2, mode, mode & ?1 | ?3) WHERE name = ?4",
            (TYPE_MASK, SYMLINK_MODE, mode.map(|mode| mode.bits()), path),
        )?;

        if num_updated == 0 {
            return Err(crate::Error::FileNotFound { path: path.into() });
        }

        Ok(())
    }

    pub fn set_mtime(&self, path: &str, mtime: Option<SystemTime>) -> crate::Result<()> {
        let mtime_secs = mtime
            .map(|mtime| -> crate::Result<_> {
                Ok(mtime
                    .duration_since(time::UNIX_EPOCH)
                    .map_err(|err| crate::Error::InvalidArgs {
                        reason: err.to_string(),
                    })?
                    .as_secs())
            })
            .transpose()?;

        let num_updated = self.tx().execute(
            "UPDATE sqlar SET mtime = ?1 WHERE name = ?2",
            (mtime_secs, path),
        )?;

        if num_updated == 0 {
            return Err(crate::Error::FileNotFound { path: path.into() });
        }

        Ok(())
    }

    pub fn set_size(&self, path: &str, size: u64) -> crate::Result<()> {
        let num_updated = self
            .tx()
            .execute("UPDATE sqlar SET sz = ?1 WHERE name = ?2", (size, path))?;

        if num_updated == 0 {
            return Err(crate::Error::FileNotFound { path: path.into() });
        }

        Ok(())
    }

    pub fn blob_size(&self, path: &str) -> crate::Result<BlobSize> {
        self.tx()
            .query_row(
                "SELECT sz, length(data) FROM sqlar WHERE name = ?1;",
                (path,),
                |row| {
                    Ok(BlobSize {
                        original: row.get(0)?,
                        actual: row.get(1)?,
                    })
                },
            )
            .optional()?
            .ok_or(crate::Error::FileNotFound { path: path.into() })
    }

    pub fn list_files(&self, opts: &ListOptions) -> crate::Result<ListEntries> {
        let order_column = match opts.sort {
            Some(ListSort::Size) => "s.sz",
            Some(ListSort::Mtime) => "s.mtime",
            Some(ListSort::Depth) => "p.segments",
            // The contract of `Archive::list` and `Archive::list_with` is that default sort order
            // is unspecified.
            None => "s.rowid",
        };

        let direction = match opts.direction {
            Some(SortDirection::Asc) | None => "ASC",
            Some(SortDirection::Desc) => "DESC",
        };

        let stmt = self.tx().prepare(&format!(
            "
            WITH path_segments AS (
                SELECT
                    name,
                    length(name) - length(replace(name, '/', '')) AS segments
                FROM
                    sqlar
            )
            SELECT
                s.name,
                s.mode,
                s.mtime,
                s.sz,
                iif(s.sz = -1, s.data, NULL) AS target,
                s.data IS NULL AS is_dir
            FROM
                sqlar AS s
            JOIN
                path_segments AS p ON s.name = p.name
            WHERE
                iif(?1 IS NULL OR ?1 = '', true, s.name GLOB ?1 || '/?*')
                AND iif(?3 IS NULL, true, (s.mode & ?2) = ?3)
                AND iif(?4 IS NULL, true, (s.mode & ?2) = ?4)
                AND CASE
                    WHEN ?5 IS NULL THEN true
                    WHEN ?5 = '' THEN NOT s.name GLOB '*/*'
                    ELSE s.name GLOB ?5 || '/?*' AND NOT s.name GLOB ?5 || '/?*/*'
                END
            ORDER BY
                {order_column} {direction}
        "
        ))?;

        let params: Vec<Box<dyn rusqlite::ToSql>> = vec![
            Box::new(opts.ancestor.as_ref().map(|ancestor| {
                ancestor
                    .to_string_lossy()
                    .trim_end_matches(std::path::MAIN_SEPARATOR)
                    .to_string()
            })),
            Box::new(TYPE_MASK),
            Box::new(if let Some(ListSort::Size) = opts.sort {
                Some(FILE_MODE)
            } else {
                None
            }),
            Box::new(match opts.file_type {
                Some(FileType::File) => Some(FILE_MODE),
                Some(FileType::Dir) => Some(DIR_MODE),
                Some(FileType::Symlink) => Some(SYMLINK_MODE),
                None => None,
            }),
            Box::new(opts.parent.as_ref().map(|parent| {
                parent
                    .to_string_lossy()
                    .trim_end_matches(std::path::MAIN_SEPARATOR)
                    .to_string()
            })),
        ];

        let map_func: ListMapFunc = Box::new(|row| {
            let mode = row.get::<_, Option<u32>>(1)?.map(FileMode::from_mode);
            let mtime = row
                .get::<_, Option<u64>>(2)?
                .map(|mtime_secs| UNIX_EPOCH + Duration::from_secs(mtime_secs));
            let size: i64 = row.get(3)?;
            // When the `data` column contains a symlink target, its type is `TEXT`, not `BLOB`.
            // Remember that columns in SQLite are dynamically typed.
            let symlink_target: Option<String> = row.get(4)?;
            let is_dir: bool = row.get(5)?;

            let metadata = if let Some(target) = symlink_target {
                FileMetadata::Symlink {
                    mtime,
                    target: PathBuf::from(target),
                }
            } else if is_dir {
                FileMetadata::Dir { mode, mtime }
            } else {
                FileMetadata::File {
                    mode,
                    mtime,
                    size: size.try_into().expect("The file size in the database was negative, but we should have already checked for this. This is a bug."),
                }
            };

            Ok(ListEntry {
                path: PathBuf::from(row.get::<_, String>(0)?),
                metadata,
            })
        });

        ListEntries::new(stmt, params, map_func)
    }
}