summaryrefslogtreecommitdiff
path: root/lib/Ultramarine/Model/DB.pm6
blob: 596da6a1f29c84133ead81c655464f909f624feb (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
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
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;
 
    constant $ROOT-DIR-ID=0;
 
    my @migrations = (
        -> $dbh {
            $dbh.do(q:to/END/); 
            CREATE TABLE directories (
                id INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                parent_id INTEGER NOT NULL,
                FOREIGN KEY (parent_id) REFERENCES directories(id),
                UNIQUE (name,parent_id)
            )
            END
 
            $dbh.do(q:to/END/,$ROOT-DIR-ID,'/',$ROOT-DIR-ID);
            INSERT INTO directories(id,name,parent_id) VALUES (?,?,?)
            END
 
            $dbh.do(q:to/END/);
            CREATE TABLE artists (
                id INTEGER PRIMARY KEY,
                name TEXT UNIQUE NOT NULL
            )
            END
 
            $dbh.do(q:to/END/);
            CREATE TABLE albums (
                id INTEGER PRIMARY KEY,
                title TEXT UNIQUE NOT NULL,
                artist_id INTEGER NOT NULL,
                FOREIGN KEY (artist_id) REFERENCES artists(id),
                UNIQUE (title,artist_id)
            )
            END
 
            $dbh.do(q:to/END/);
            CREATE TABLE songs (
                path TEXT NOT NULL PRIMARY KEY,
                mtime INTEGER NOT NULL,
                directory_id INTEGER,
                album_id INTEGER,
                metadata TEXT DEFAULT '{}',
                FOREIGN KEY (directory_id) REFERENCES directories(id),
                FOREIGN KEY (album_id) REFERENCES albums(id)
            )
            END
        },
    );
 
    has $!dbh = do {
        my $dbh = DBIish.connect($!db-driver, |%!db-args);
        $dbh.do(q{PRAGMA foreign_keys=ON});
        my Ultramarine::Model::DBMigration $migration .= new(:$dbh,:@migrations);
        $migration.ensure-schema;
        $dbh;
    };
 
    method ensure-artist(:$name!) {
        my $sth = $!dbh.prepare(q:to/END/);
        INSERT OR IGNORE INTO artists(name) VALUES (?)
        END
        $sth.execute($name);
        $sth.finish;
        $sth = $!dbh.prepare(q:to/END/);
        SELECT id
        FROM artists
        WHERE name=?
        END
        $sth.execute($name);
        return $sth.row()[0];
 
        LEAVE { .finish with $sth }
    }
 
    method ensure-album(:$title!,:$artist-id!) {
        my $sth = $!dbh.prepare(q:to/END/);
        INSERT OR IGNORE INTO albums(title,artist_id) VALUES (?,?)
        END
        $sth.execute($title,$artist-id);
        $sth.finish;
        $sth = $!dbh.prepare(q:to/END/);
        SELECT id
        FROM albums
        WHERE title=? AND artist_id=?
        END
        $sth.execute($title,$artist-id);
        return $sth.row()[0];
 
        LEAVE { .finish with $sth }
    }
 
    method ensure-one-directory(:$name!,:$parent-id!) {
        my $sth = $!dbh.prepare(q:to/END/);
        INSERT OR IGNORE INTO directories(name,parent_id) VALUES (?,?)
        END
        $sth.execute($name,$parent-id // $ROOT-DIR-ID);
        $sth.finish;
        $sth = $!dbh.prepare(q:to/END/);
        SELECT id
        FROM directories
        WHERE name=? AND parent_id=?
        END
        $sth.execute($name,$parent-id // $ROOT-DIR-ID);
        return $sth.row()[0];
 
        LEAVE { .finish with $sth }
    }
 
    method ensure-directories(IO() :$path! is copy) {
        my @components = gather {
            while $path ne '.'|'/' {
                take $path.basename;
                $path .= parent;
            }
        };
        my $parent-id=Nil;
        while my $name = @components.pop {
            $parent-id = self.ensure-one-directory(:$name,:$parent-id);
        }
        return $parent-id;
    }
 
    method ensure-song(IO() :$path!,:$mtime!,:%metadata!) {
        CATCH { default { .perl.say } }
        my $last-dir-id = self.ensure-directories(:path($path.dirname));
        my $artist-id = self.ensure-artist(:name($_))
           with %metadata<tags><artist>;
        my $album-id = self.ensure-album(:title($_),:$artist-id)
           with %metadata<tags><album>;
        my $sth = $!dbh.prepare(q:to/END/);
        INSERT OR REPLACE INTO songs(path,mtime,directory_id,album_id,metadata)
        VALUES (?,?,?,?,?)
        END
        LEAVE { .finish with $sth }
        $sth.execute($path.Str,$mtime,$last-dir-id,$album-id,to-json(%metadata));
    }
 
    # seen-file
    # * add a row into a "seen" table, fk to songs
    # remove-unseen-files
    # * delete from songs where not in seen
    # remove-empty
    # * delete from directories where not in directories or songs
    # ** repeat until nothing gets deleted
    # * delete from albums where not in songs
    # * delete from artists where not in albums
 
    sub unpack-row(%song is copy) {
        %song<metadata> = from-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;
    }
}