summaryrefslogtreecommitdiff
path: root/lib/Ultramarine/Model/DB.pm6
blob: 57a5f0b835b32a410c1fc648ed665cdcd243ac7b (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use v6.d.PREVIEW;
use DBIish;
use Ultramarine::Model::DBMigration;
use JSON::Fast;
 
class Ultramarine::Model::DB {
    has $.db-driver is required;
    has %.db-args is required;
 
    my @migrations = (
        -> $dbh {
            $dbh.do(q:to/END/); 
            CREATE TABLE songs (
                path TEXT PRIMARY KEY,
                mtime INTEGER NOT NULL,
                metadata TEXT DEFAULT '{}'
            );
            END
        },
    );
 
    has $!dbh = do {
        my $dbh = DBIish.connect($!db-driver|%!db-args);
        my Ultramarine::Model::DBMigration $migration .= new(:$dbh,:@migrations);
        $migration.ensure-schema;
        $dbh;
    };
 
    method set-song(:$path!,:$mtime!,:%metadata!{
        my %song = pack-row(%(:$path,:$mtime,:%metadata));
        my $sth = $!dbh.prepare(q:to/END/); 
        INSERT OR REPLACE INTO songs(path,mtime,metadata)
        VALUES (?,?,?)
        END
        LEAVE { .finish with $sth }
        $sth.execute(%song<path mtime metadata>».Str);
    }
 
    sub unpack-row(%song is copy{
        %song<metadata> = from-json(%song<metadata>);
        return %song;
    }
    sub pack-row(%song is copy{
        %song<metadata> = to-json(%song<metadata>);
        return %song;
    }
 
    method get-song(:$path!{
        my $sth = $!dbh.prepare(q:to/END/); 
        SELECT *
        FROM songs
        WHERE path=?
        END
        LEAVE { .finish with $sth }
        $sth.execute($path.Str);
        return unpack-row($sth.row(:hash));
    }
 
    method all-songs() {
        my $sth = $!dbh.prepare(q:to/END/); 
        SELECT *
        FROM songs
        ORDER BY path ASC
        END
        $sth.execute();
        return gather {
            while $sth.row(:hash-> %song {
                take unpack-row(%song);
            }
            .finish with $sth;
        }
    }
 
    method is-up-to-date(:$path!,:$mtime!{
        my $sth = $!dbh.prepare(q:to/END/); 
        SELECT COUNT(*)
        FROM songs
        WHERE path=?
          AND mtime >= $mtime
        END
        LEAVE { .finish with $sth };
        $sth.execute($path.Str,$mtime);
        return ($sth.row[0]//0).Bool;
    }
}