liteboxfs 0.1.0

A modern POSIX filesystem in 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
use std::{ffi::OsStr, iter, path::PathBuf};

use rusqlite::OptionalExtension;

use crate::{
    FileOrigin, RootId,
    block::FileId as StoreFileId,
    path::NormalizedPath,
    sql::{FileDiscriminant, SqlStore},
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathInsertResult {
    Inserted,
    AlreadyExists,
}

impl<'conn> SqlStore<'conn> {
    /// Resolve a normalized path to its row ID in `liteboxfs_paths`.
    pub(super) fn resolve_path_id(
        &self,
        root_row_id: i64,
        root_id: RootId,
        path: &NormalizedPath,
    ) -> crate::Result<i64> {
        let root_path_row_id: i64 = self
            .db
            .query_row(
                r#"
                SELECT
                    id
                FROM
                    liteboxfs_paths
                WHERE
                    root = ?
                    AND parent IS NULL
                    AND name = x'2f';
                "#,
                rusqlite::params![root_row_id],
                |row| row.get(0),
            )
            .map_err(|e| match e {
                rusqlite::Error::QueryReturnedNoRows => crate::Error::FileNotFound {
                    file: FileOrigin::Litebox {
                        root: root_id,
                        locator: path.to_path_buf().into(),
                    },
                },
                _ => e.into(),
            })?;

        let mut current_id = root_path_row_id;

        for component in path.components() {
            let next_id: Option<i64> = self
                .db
                .query_row(
                    r#"
                    SELECT
                        id
                    FROM
                        liteboxfs_paths
                    WHERE
                        root = ?
                        AND parent = ?
                        AND name = ?;
                    "#,
                    rusqlite::params![root_row_id, current_id, component.as_encoded_bytes()],
                    |row| row.get(0),
                )
                .optional()?;

            match next_id {
                Some(id) => current_id = id,
                None => {
                    return Err(crate::Error::FileNotFound {
                        file: FileOrigin::Litebox {
                            root: root_id,
                            locator: path.to_path_buf().into(),
                        },
                    });
                }
            }
        }

        Ok(current_id)
    }

    pub fn insert_path(
        &self,
        root_id: RootId,
        path: &NormalizedPath,
        file: StoreFileId,
    ) -> crate::Result<PathInsertResult> {
        let root_row_id: i64 = self.db.query_row(
            r#"
            SELECT
                id
            FROM
                liteboxfs_roots
            WHERE
                uuid = ?;
            "#,
            rusqlite::params![root_id.to_string()],
            |row| row.get(0),
        )?;

        let components = path.components().collect::<Vec<_>>();

        if components.is_empty() {
            let exists = self
                .db
                .query_row(
                    r#"
                    SELECT
                        id
                    FROM
                        liteboxfs_paths
                    WHERE
                        root = ?
                        AND parent IS NULL
                        AND name = x'2f';
                    "#,
                    rusqlite::params![root_row_id],
                    |row| row.get::<_, i64>(0),
                )
                .optional()?;

            if exists.is_some() {
                return Ok(PathInsertResult::AlreadyExists);
            }

            // If there is no root directory, insert one.
            self.db.execute(
                r#"
                INSERT INTO
                    liteboxfs_paths (file, root, name, parent)
                VALUES
                    (?, ?, x'2f', NULL);
                "#,
                rusqlite::params![file, root_row_id],
            )?;

            return Ok(PathInsertResult::Inserted);
        }

        // For non-root paths, start traversal from the root path.
        let root_path_row_id: i64 = self
            .db
            .query_row(
                r#"
                SELECT
                    id
                FROM
                    liteboxfs_paths
                WHERE
                    root = ?
                    AND parent IS NULL
                    AND name = x'2f';
                "#,
                rusqlite::params![root_row_id],
                |row| row.get(0),
            )
            .map_err(|e| match e {
                rusqlite::Error::QueryReturnedNoRows => crate::Error::NoParentDirectory {
                    file: FileOrigin::Litebox {
                        root: root_id,
                        locator: path.to_path_buf().into(),
                    },
                },
                _ => e.into(),
            })?;

        let mut last_parent_id: i64 = root_path_row_id;
        let num_components = components.len();

        for (i, component) in components.into_iter().enumerate() {
            let is_last_component = i == num_components - 1;

            let component_id = if is_last_component {
                self.db
                    .query_one(
                        r#"
                        SELECT
                            liteboxfs_paths.id
                        FROM
                            liteboxfs_paths
                        WHERE
                            liteboxfs_paths.root = ?
                            AND liteboxfs_paths.parent = ?
                            AND liteboxfs_paths.name = ?
                        LIMIT 1;
                        "#,
                        rusqlite::params![
                            root_row_id,
                            last_parent_id,
                            component.as_encoded_bytes(),
                        ],
                        |row| row.get::<_, i64>(0),
                    )
                    .optional()?
            } else {
                self.db
                    .query_one(
                        r#"
                        SELECT
                            liteboxfs_paths.id
                        FROM
                            liteboxfs_paths
                        JOIN
                            liteboxfs_files ON liteboxfs_paths.file = liteboxfs_files.id
                        WHERE
                            liteboxfs_paths.root = ?
                            AND liteboxfs_paths.parent = ?
                            AND liteboxfs_paths.name = ?
                            AND liteboxfs_files.kind = ?
                        LIMIT 1;
                        "#,
                        rusqlite::params![
                            root_row_id,
                            last_parent_id,
                            component.as_encoded_bytes(),
                            FileDiscriminant::Dir
                        ],
                        |row| row.get::<_, i64>(0),
                    )
                    .optional()?
            };

            match component_id {
                Some(_) if is_last_component => {
                    return Ok(PathInsertResult::AlreadyExists);
                }
                Some(component_id) => {
                    last_parent_id = component_id;
                }
                None if is_last_component => {
                    self.db.execute(
                        r#"
                        INSERT INTO
                            liteboxfs_paths (file, root, name, parent)
                        VALUES
                            (?, ?, ?, ?);
                        "#,
                        rusqlite::params![
                            file,
                            root_row_id,
                            component.as_encoded_bytes(),
                            last_parent_id
                        ],
                    )?;

                    return Ok(PathInsertResult::Inserted);
                }
                None => {
                    // Check whether the path segment:
                    // 1. Exists but is not a directory.
                    // 2. Does not exist at all.
                    let exists_as_non_dir: bool = self
                        .db
                        .query_one(
                            r#"
                            SELECT
                                1
                            FROM
                                liteboxfs_paths
                            WHERE
                                liteboxfs_paths.root = ?
                                AND liteboxfs_paths.parent = ?
                                AND liteboxfs_paths.name = ?
                            LIMIT 1;
                            "#,
                            rusqlite::params![
                                root_row_id,
                                last_parent_id,
                                component.as_encoded_bytes(),
                            ],
                            |_row| Ok(()),
                        )
                        .optional()?
                        .is_some();

                    if exists_as_non_dir {
                        // Reconstruct the partial path up to the current component.
                        let partial: PathBuf = iter::once(OsStr::new("/"))
                            .chain(path.components().take(i + 1))
                            .collect();
                        return Err(crate::Error::NotADirectory {
                            file: FileOrigin::Litebox {
                                root: root_id,
                                locator: NormalizedPath::new(&partial).to_path_buf().into(),
                            },
                        });
                    }

                    return Err(crate::Error::NoParentDirectory {
                        file: FileOrigin::Litebox {
                            root: root_id,
                            locator: path.to_path_buf().into(),
                        },
                    });
                }
            }
        }

        unreachable!()
    }

    pub fn rename_path_tree(
        &self,
        root_id: RootId,
        source: &NormalizedPath,
        dest: &NormalizedPath,
    ) -> crate::Result<()> {
        let root_row_id: i64 = self.db.query_row(
            r#"
            SELECT
                id
            FROM
                liteboxfs_roots
            WHERE
                uuid = ?;
            "#,
            rusqlite::params![root_id.to_string()],
            |row| row.get(0),
        )?;

        let source_path_id = self.resolve_path_id(root_row_id, root_id, source)?;

        let dest_exists = match self.resolve_path_id(root_row_id, root_id, dest) {
            Ok(_) => true,
            Err(crate::Error::FileNotFound { .. }) => false,
            Err(e) => return Err(e),
        };

        if dest_exists {
            return Err(crate::Error::FileAlreadyExists {
                path: FileOrigin::Litebox {
                    root: root_id,
                    locator: dest.to_path_buf(),
                },
            });
        }

        let dest_name = dest.file_name().expect("dest path should have a file name");

        let dest_parent = dest
            .parent()
            .map(NormalizedPath::new)
            .expect("dest path should have a parent");

        let dest_parent_id = self
            .resolve_path_id(root_row_id, root_id, &dest_parent)
            .map_err(|e| match e {
                crate::Error::FileNotFound { .. } => crate::Error::NoParentDirectory {
                    file: FileOrigin::Litebox {
                        root: root_id,
                        locator: dest.to_path_buf().into(),
                    },
                },
                _ => e,
            })?;

        let parent_kind: FileDiscriminant = self.db.query_row(
            r#"
            SELECT
                liteboxfs_files.kind
            FROM
                liteboxfs_paths
            JOIN
                liteboxfs_files ON liteboxfs_paths.file = liteboxfs_files.id
            WHERE
                liteboxfs_paths.id = ?;
            "#,
            rusqlite::params![dest_parent_id],
            |row| row.get(0),
        )?;

        if parent_kind != FileDiscriminant::Dir {
            return Err(crate::Error::NotADirectory {
                file: FileOrigin::Litebox {
                    root: root_id,
                    locator: dest.to_path_buf().into(),
                },
            });
        }

        // Updating the parent and name of the source row moves the entire subtree: every
        // descendant already references its parent by ID, so no other rows need updating.
        self.db.execute(
            r#"
            UPDATE
                liteboxfs_paths
            SET
                parent = ?1,
                name = ?2
            WHERE
                id = ?3;
            "#,
            rusqlite::params![dest_parent_id, dest_name.as_encoded_bytes(), source_path_id],
        )?;

        Ok(())
    }

    pub fn count_paths(&self, root_id: RootId, file: StoreFileId) -> crate::Result<u32> {
        let count: i64 = self.db.query_row(
            r#"
            SELECT
                COUNT(*)
            FROM
                liteboxfs_paths
            WHERE
                root = (
                    SELECT
                        id
                    FROM
                        liteboxfs_roots
                    WHERE
                        uuid = ?1
                )
                AND file = ?2;
            "#,
            rusqlite::params![root_id, file],
            |row| row.get(0),
        )?;

        Ok(count as u32)
    }
}