liteboxfs 0.2.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
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
use std::os::unix::ffi::OsStringExt;
use std::{ffi::OsString, time::SystemTime};

use super::exclusive::ExclusiveFileId;
use super::store::SqlStore;
use crate::util::system_time_to_nanos;
use crate::{
    RootId,
    block::FileId as StoreFileId,
    errors::InternalError,
    file_metadata::{FileMode, Gid, RawMetadata, Uid, Xattrs},
    user::UserMetadata,
};

impl<'conn> SqlStore<'conn> {
    pub fn get_file_metadata_by_id(&self, file_id: StoreFileId) -> crate::Result<RawMetadata> {
        let mut stmt = self.db.prepare_cached(
            r#"
            SELECT
                liteboxfs_files.kind, liteboxfs_files.mode, liteboxfs_files.atime, liteboxfs_files.mtime,
                liteboxfs_files.ctime, liteboxfs_files.btime, liteboxfs_files.uid, liteboxfs_files.gid
            FROM
                liteboxfs_files
            WHERE
                liteboxfs_files.id = ?;
            "#,
        )?;

        let result = stmt.query_row(rusqlite::params![file_id], |row| {
            Ok(RawMetadata {
                discriminant: row.get(0)?,
                mode: FileMode::from_bits_truncate(row.get(1)?),
                atime: row.get(2)?,
                mtime: row.get(3)?,
                ctime: row.get(4)?,
                btime: row.get(5)?,
                uid: Uid::from_raw(row.get(6)?),
                gid: Gid::from_raw(row.get(7)?),
            })
        });

        match result {
            Ok(data) => Ok(data),
            Err(rusqlite::Error::QueryReturnedNoRows) => {
                Err(InternalError::FileNotFound { id: file_id }.into())
            }
            Err(err) => Err(err.into()),
        }
    }

    pub fn update_file_mode(&self, file_id: ExclusiveFileId, mode: FileMode) -> crate::Result<()> {
        let rows_updated = self.db.execute(
            r#"
            UPDATE
                liteboxfs_files
            SET
                mode = ?
            WHERE
                id = ?;
            "#,
            rusqlite::params![mode.bits(), file_id],
        )?;

        if rows_updated == 0 {
            return Err(InternalError::FileNotFound {
                id: file_id.file_id(),
            }
            .into());
        }

        Ok(())
    }

    pub fn update_file_uid(&self, file_id: ExclusiveFileId, uid: Uid) -> crate::Result<()> {
        let rows_updated = self.db.execute(
            r#"
            UPDATE
                liteboxfs_files
            SET
                uid = ?
            WHERE
                id = ?;
            "#,
            rusqlite::params![uid.as_raw(), file_id],
        )?;

        if rows_updated == 0 {
            return Err(InternalError::FileNotFound {
                id: file_id.file_id(),
            }
            .into());
        }

        Ok(())
    }

    pub fn update_file_gid(&self, file_id: ExclusiveFileId, gid: Gid) -> crate::Result<()> {
        let rows_updated = self.db.execute(
            r#"
            UPDATE
                liteboxfs_files
            SET
                gid = ?
            WHERE
                id = ?;
            "#,
            rusqlite::params![gid.as_raw(), file_id],
        )?;

        if rows_updated == 0 {
            return Err(InternalError::FileNotFound {
                id: file_id.file_id(),
            }
            .into());
        }

        Ok(())
    }

    pub fn update_file_atime(
        &self,
        file_id: ExclusiveFileId,
        atime: SystemTime,
    ) -> crate::Result<()> {
        let rows_updated = self.db.execute(
            r#"
            UPDATE
                liteboxfs_files
            SET
                atime = ?
            WHERE
                id = ?;
            "#,
            rusqlite::params![system_time_to_nanos(atime)?, file_id],
        )?;

        if rows_updated == 0 {
            return Err(InternalError::FileNotFound {
                id: file_id.file_id(),
            }
            .into());
        }

        Ok(())
    }

    pub fn update_file_mtime(
        &self,
        file_id: ExclusiveFileId,
        mtime: SystemTime,
    ) -> crate::Result<()> {
        let rows_updated = self.db.execute(
            r#"
            UPDATE
                liteboxfs_files
            SET
                mtime = ?
            WHERE
                id = ?;
            "#,
            rusqlite::params![system_time_to_nanos(mtime)?, file_id],
        )?;

        if rows_updated == 0 {
            return Err(InternalError::FileNotFound {
                id: file_id.file_id(),
            }
            .into());
        }

        Ok(())
    }

    pub fn update_file_ctime(
        &self,
        file_id: ExclusiveFileId,
        ctime: SystemTime,
    ) -> crate::Result<()> {
        let rows_updated = self.db.execute(
            r#"
            UPDATE
                liteboxfs_files
            SET
                ctime = ?
            WHERE
                id = ?;
            "#,
            rusqlite::params![system_time_to_nanos(ctime)?, file_id],
        )?;

        if rows_updated == 0 {
            return Err(InternalError::FileNotFound {
                id: file_id.file_id(),
            }
            .into());
        }

        Ok(())
    }

    pub fn update_file_btime(
        &self,
        file_id: ExclusiveFileId,
        btime: Option<SystemTime>,
    ) -> crate::Result<()> {
        let rows_updated = self.db.execute(
            r#"
            UPDATE
                liteboxfs_files
            SET
                btime = ?
            WHERE
                id = ?;
            "#,
            rusqlite::params![btime.map(system_time_to_nanos).transpose()?, file_id],
        )?;

        if rows_updated == 0 {
            return Err(InternalError::FileNotFound {
                id: file_id.file_id(),
            }
            .into());
        }

        Ok(())
    }

    pub fn get_file_xattrs(&self, file_id: StoreFileId) -> crate::Result<Xattrs> {
        let mut stmt = self.db.prepare_cached(
            r#"
            SELECT
                name,
                value
            FROM
                liteboxfs_xattrs
            WHERE
                file = ?;
            "#,
        )?;

        let rows = stmt.query_map(rusqlite::params![file_id], |row| {
            Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, Vec<u8>>(1)?))
        })?;

        let mut xattrs = Xattrs::new();
        for row in rows {
            let (name, value) = row?;
            let name = OsString::from_vec(name);
            xattrs.set(name, value);
        }

        Ok(xattrs)
    }

    pub fn set_file_xattrs(&self, file_id: ExclusiveFileId, xattrs: &Xattrs) -> crate::Result<()> {
        // Delete all existing xattrs for this file.
        self.db.execute(
            r#"
            DELETE FROM
                liteboxfs_xattrs
            WHERE
                file = ?;
            "#,
            rusqlite::params![file_id],
        )?;

        // Insert the new xattrs.
        let mut stmt = self.db.prepare_cached(
            r#"
            INSERT INTO
                liteboxfs_xattrs (file, name, value)
            VALUES
                (?, ?, ?);
            "#,
        )?;

        for (name, value) in xattrs {
            stmt.execute(rusqlite::params![file_id, name.as_encoded_bytes(), value])?;
        }

        Ok(())
    }

    pub fn get_file_xattr(
        &self,
        file_id: StoreFileId,
        name: &[u8],
    ) -> crate::Result<Option<Vec<u8>>> {
        let mut stmt = self.db.prepare_cached(
            r#"
            SELECT
                value
            FROM
                liteboxfs_xattrs
            WHERE
                file = ?
                AND name = ?;
            "#,
        )?;

        let result = stmt.query_row(rusqlite::params![file_id, name], |row| {
            row.get::<_, Vec<u8>>(0)
        });

        match result {
            Ok(value) => Ok(Some(value)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(err) => Err(err.into()),
        }
    }

    pub fn set_file_xattr(
        &self,
        file_id: ExclusiveFileId,
        name: &[u8],
        value: &[u8],
    ) -> crate::Result<()> {
        self.db.execute(
            r#"
            INSERT OR REPLACE INTO
                liteboxfs_xattrs (file, name, value)
            VALUES
                (?, ?, ?);
            "#,
            rusqlite::params![file_id, name, value],
        )?;

        Ok(())
    }

    /// Get all global filesystem metadata.
    pub fn get_filesystem_metadata(&self) -> crate::Result<UserMetadata> {
        let mut stmt = self.db.prepare_cached(
            r#"
            SELECT
                key,
                value
            FROM
                liteboxfs_metadata;
            "#,
        )?;

        let rows = stmt.query_map([], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?))
        })?;

        let mut metadata = UserMetadata::new();
        for row in rows {
            let (key, value) = row?;
            metadata.set(key, value)?;
        }

        Ok(metadata)
    }

    /// Set all global filesystem metadata, replacing any existing metadata.
    pub fn set_filesystem_metadata(&self, metadata: &UserMetadata) -> crate::Result<()> {
        self.db.execute(
            r#"
            DELETE FROM
                liteboxfs_metadata;
            "#,
            [],
        )?;

        let mut stmt = self.db.prepare_cached(
            r#"
            INSERT INTO
                liteboxfs_metadata (key, value)
            VALUES
                (?, ?);
            "#,
        )?;

        for (key, value) in metadata {
            stmt.execute(rusqlite::params![key, value])?;
        }

        Ok(())
    }

    /// Get all metadata for a specific root.
    pub fn get_root_metadata(&self, root_id: RootId) -> crate::Result<UserMetadata> {
        let mut stmt = self.db.prepare_cached(
            r#"
            SELECT
                key,
                value
            FROM
                liteboxfs_root_metadata
            WHERE
                root = (
                    SELECT
                        id
                    FROM
                        liteboxfs_roots
                    WHERE
                        uuid = ?
                );
            "#,
        )?;

        let rows = stmt.query_map(rusqlite::params![root_id.to_string()], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?))
        })?;

        let mut metadata = UserMetadata::new();
        for row in rows {
            let (key, value) = row?;
            metadata.set(key, value)?;
        }

        Ok(metadata)
    }

    /// Set all metadata for a specific root, replacing any existing metadata.
    pub fn set_root_metadata(&self, root_id: RootId, metadata: &UserMetadata) -> crate::Result<()> {
        self.db.execute(
            r#"
            DELETE FROM
                liteboxfs_root_metadata
            WHERE
                root = (
                    SELECT
                        id
                    FROM
                        liteboxfs_roots
                    WHERE
                        uuid = ?
                );
            "#,
            rusqlite::params![root_id.to_string()],
        )?;

        let mut stmt = self.db.prepare_cached(
            r#"
            INSERT INTO
                liteboxfs_root_metadata (root, key, value)
            VALUES
                (
                    (
                        SELECT
                            id
                        FROM
                            liteboxfs_roots
                        WHERE
                            uuid = ?
                    ),
                    ?,
                    ?
                );
            "#,
        )?;

        for (key, value) in metadata {
            stmt.execute(rusqlite::params![root_id.to_string(), key, value])?;
        }

        Ok(())
    }
}