aboutsummaryrefslogtreecommitdiff
path: root/lib/App/MediaControl/DB.rakumod
blob: 7ce562eb72d3022227ee07f55e903157761e170e (plain)
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
use v6.d;
use DB::SQLite;
 
class App::MediaControl::DB {
    has DB::SQLite $.pool is required;
 
    method !db(Callable $code{
        my $conn = self.pool.db;
        # we need an explicit LEAVE block because on 2021.10, `will 
        # leave { .finish }` kills precomp 
        LEAVE { .finish with $conn };
        $conn.begin;
        $conn.execute('PRAGMA foreign_keys=true');
        my $result = $code($connwith $conn;
        $conn.commit;
        return $result;
    }
 
    method ensure-schema() {
        return if self!db: { .query(
            'SELECT 1 FROM sqlite_schema WHERE type=? AND tbl_name=?',
            'table''files',
        ).value.defined };
 
        self!db: {
            .query(q:to/END/); 
            CREATE TABLE files (
                id INTEGER PRIMARY KEY,
                parent_id INTEGER NULL REFERENCES files(id),
                matpath TEXT NOT NULL,
                name TEXT NOT NULL,
                is_dir BOOLEAN NOT NULL,
                watched_time INTEGER NULL,
                UNIQUE (matpath, name)
            )
            END
        }
    }
 
    method add-entry(Str :$path! is copyStr :$name!Bool :$is-dir!{
        $path ~~ s{<!after '/'>$} = '/';
        $path ~~ s{<!before '/'>^} = '/';
 
        note "add-entry($path,$name)";
        self!db: {
            .query(q:to/END/:$path, :$name:is_dir($is-dir)); 
            WITH parent(id,path) AS (
                SELECT id, matpath || name || '/' FROM files
            ),
            newrow(path,name,is_dir) AS (
                VALUES($path, $name, $is_dir)
            )
            INSERT INTO files(parent_id,matpath,name,is_dir)
            SELECT id, newrow.path, name, is_dir
            FROM newrow
            LEFT JOIN parent ON parent.path=newrow.path
            WHERE true
            ON CONFLICT (matpath,name) DO NOTHING
            END
        }
    }
}