fix pruning tags + only prune files/dirs under @ARGV
[id3fs.git] / lib / ID3FS / DB.pm
1 # id3fs - a FUSE-based filesystem for browsing audio metadata
2 # Copyright (C) 2010  Ian Beckwith <ianb@erislabs.net>
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 package ID3FS::DB;
18
19 use strict;
20 use warnings;
21 use DBI;
22 use ID3FS::AudioFile;
23 use Cwd;
24
25 our $SCHEMA_VERSION=1;
26 my $dbfile=".id3fs"; # default
27
28 sub new
29 {
30     my $proto=shift;
31     my $class=ref($proto) || $proto;
32     my $self={};
33     bless($self,$class);
34
35     $self->{me}=shift;
36     $self->{verbose}=shift;
37     my $init=shift;
38     $self->{base}=shift;
39     $self->{dbpath}=shift || ($self->{base} . "/" . $dbfile);
40     $self->{dbpath}=Cwd::abs_path($self->{dbpath});
41     $self->{absbase}=Cwd::abs_path($self->{base});
42
43     my $connectstr="dbi:SQLite:dbname=$self->{dbpath}";
44     my $exists=-f $self->{dbpath};
45     $self->{dbh}=DBI->connect($connectstr, undef, undef,
46                               { AutoCommit=>1 } );
47     unless(defined($self->{dbh}))
48     {
49         die("$self->{me}: DB Error: " . $DBI::errstr . "\n");
50     }
51
52     if($exists)
53     {
54         $self->checkschema();
55     }
56     else
57     {
58         $self->create();
59     }
60     $self->enable_foreign_keys();
61     return $self;
62 }
63
64 # search parent directories for db
65 sub find_db
66 {
67     # class method
68     shift if(ref($_[0]) eq "ID3FS::DB");
69
70     my($me, $init, @dirs)=@_;
71     my $base=undef;
72     for my $dir (@dirs)
73     {
74 #       my $path=Cwd::abs_path($dir);
75         my $path=$dir;
76         do
77         {
78             $base=$path;
79             $path=~s/(.*)\/.*/$1/;
80         }
81         while(! -f "$base/$dbfile" && length($path) && -d $path);
82         if(-f "$base/$dbfile")
83         {
84             return $base;
85         }
86     }
87     if(!-f "$base/$dbfile")
88     {
89         unless($init)
90         {
91             print "$me: db not found at $base/$dbfile\n";
92             return undef;
93         }
94         $base=$dirs[0];
95
96     }
97     return $base;
98 }
99
100 sub base_dir { return shift->{base}; }
101
102 sub create
103 {
104     my($self,$name)=@_;
105     my @schema=split(/\n\n/,join("", <DATA>));
106     close(DATA);
107     for my $cmd (@schema)
108     {
109         $self->{dbh}->do($cmd);
110     }
111     $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
112                $SCHEMA_VERSION, time());
113 }
114
115 sub checkschema
116 {
117     my $self=shift;
118     my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
119     if(!defined($version) || $version != $SCHEMA_VERSION)
120     {
121         die("$self->{me}: id3fs database version " .
122             defined($version) ? $version : '""' .
123             "not known, current version is $SCHEMA_VERSION.\n");
124     }
125 }
126
127 sub analyze
128 {
129     my $self=shift;
130     $self->cmd("ANALYZE");
131 }
132
133 sub enable_foreign_keys
134 {
135     my $self=shift;
136     $self->cmd("PRAGMA foreign_keys = ON");
137 }
138
139 sub last_update
140 {
141     my($self, $newval)=@_;
142     if(defined($newval))
143     {
144         $self->cmd("UPDATE id3fs SET last_update=?", $newval);
145     }
146     else
147     {
148         ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
149     }
150     return $newval;
151 }
152
153 sub bare_tags
154 {
155     my($self)=@_;
156     my $sql=("SELECT t1.name FROM tags t1\n" .
157              "LEFT JOIN tags t2 on t1.id=t2.parents_id\n" .
158              "WHERE t1.parents_id='' AND t2.id IS NULL\n" .
159              "GROUP BY t1.name\n");
160     my @names=$self->cmd_firstcol($sql);
161     return (@names);
162 }
163
164 sub tags_with_values
165 {
166     my($self)=@_;
167     my $sql=("SELECT p.name, t.name  FROM tags t\n" .
168              "INNER JOIN tags p ON t.parents_id=p.id\n" .
169              "GROUP BY p.name, t.name\n");
170     my $result=$self->cmd_rows($sql);
171     my $tags={};
172     for my $pair (@$result)
173     {
174         push(@{$tags->{$pair->[0]}}, $pair->[1]);
175     }
176     return $tags;
177 }
178
179 sub tag_has_values
180 {
181     my($self, $id)=@_;
182     my $sql=("SELECT COUNT(*) FROM tags\n\t" .
183              "WHERE tags.parents_id=?\n");
184     my ($rows)=$self->cmd_onerow($sql, $id);
185     return $rows;
186 }
187
188 sub relativise
189 {
190     my($self, $path, $name, $mountpoint, $querypath)=@_;
191     my $rpath="$self->{absbase}/$path";
192     my $vpath=$mountpoint . $querypath;
193     my @path=split(/\//,$rpath);
194     my @rel=split(/\//,$vpath);
195     # drop filename from rel
196     pop @rel;
197     # absolute paths have empty first element due to leading /
198     shift(@path) if($path[0] eq "");
199     shift(@rel)  if($rel[0]  eq "");
200     # f: /home/foo/bar/baz.mp3
201     # r: /home/ianb/music/albums
202     while(@path && @rel && ($path[0] eq $rel[0]))
203     {
204         shift(@path);
205         shift(@rel);
206     }
207     my $upcount=scalar(@rel);
208     my $result="../" x $upcount;
209     $result .= join("/",@path);
210     $result .= "/$name";
211     return $result;
212 }
213
214 sub add
215 {
216     my($self,$path)=@_;
217     my $relpath=Cwd::abs_path($path);
218     $relpath =~ s/^\Q$self->{absbase}\E\/?//;
219     my($filepart,$pathpart);
220     if($relpath !~ /\//)
221     {
222         $pathpart='';
223         $filepart=$relpath;
224     }
225     else
226     {
227         ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
228     }
229     my $file=ID3FS::AudioFile->new($path, $self->{me});
230     return unless(defined($file));
231     my $artist=$file->artist();
232     my $album=$file->album();
233     my $v1genre=$file->v1genre();
234     my $year=$file->year();
235     my $audiotype=$file->audiotype();
236     my @tags=$file->tags();
237     my $haspic=$file->haspic();
238     my $channels=$file->channels();
239     my $bitrate=$file->bitrate();
240     my $samplerate=$file->samplerate();
241
242     $artist=undef unless($self->ok($artist));
243     print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
244     my $artist_id=$self->add_to_table("artists",  $artist);
245     my $path_id=$self->add_to_table("paths", $pathpart);
246     $album=undef unless($self->ok($album));
247 #    if($self->{verbose} && !defined($album)) FIXME
248     if(!defined($album))
249     {
250         print "$self->{me}: $path: no album tag defined\n";
251     }
252
253     my $albums_id=$self->add_to_table("albums", $album);
254     my $file_id=$self->add_to_table("files", $filepart,
255                                     { "artists_id" => $artist_id,
256                                       "albums_id"  => $albums_id,
257                                       "paths_id"   => $path_id });
258
259     $self->remove_tag_refs($file_id);
260     if(@tags)
261     {
262         for my $tag (@tags)
263         {
264             $self->add_tag($file_id, @$tag);
265         }
266     }
267     else
268     {
269         $self->add_tag($file_id, "UNTAGGED");
270     }
271
272     $year="UNKNOWN" if(!$self->ok($year) || $year =~ /^0+$/);
273     $year+=1900 if($year=~/^\d\d$/);
274     $self->add_tag($file_id, "year", $year);
275     if($year=~/^(\d\d\d)\d$/)
276     {
277         $self->add_tag($file_id, "decade", "${1}0s");
278     }
279     else
280     {
281         $self->add_tag($file_id, "decade", "UNKNOWN");
282     }
283
284     if($self->ok($v1genre))
285     {
286         $self->add_tag($file_id, "v1genre", $v1genre);
287     }
288
289     if($haspic)
290     {
291         $self->add_tag($file_id, "haspic", undef);
292     }
293
294     if($self->ok($audiotype))
295     {
296         $self->add_tag($file_id, "audiotype", $audiotype);
297     }
298     else
299     {
300         # should never happen
301         $self->add_tag($file_id, "audiotype", "UNKNOWN");
302     }
303
304     if($self->ok($channels))
305     {
306         if    ($channels eq "2") { $channels="stereo";  }
307         elsif ($channels eq "1") { $channels="mono";    }
308         elsif ($channels eq "0") { $channels="UNKNOWN"; }
309         $self->add_tag($file_id, "channels", $channels);
310     }
311
312     if($self->ok($bitrate))
313     {
314         $bitrate="UNKNOWN" if($bitrate=~/^0+$/);
315         $self->add_tag($file_id, "bitrate", $bitrate);
316     }
317
318     if($self->ok($samplerate))
319     {
320         $samplerate="UNKNOWN" if($samplerate=~/^0+$/);
321         $self->add_tag($file_id, "samplerate", $samplerate);
322     }
323
324 }
325
326 sub add_tag
327 {
328     my($self, $file_id, $tag, $value)=@_;
329     my $tag_id=$self->add_to_table("tags",  $tag,
330                                    { "parents_id" => undef });
331     $self->add_relation("files_x_tags",
332                         { "files_id" => $file_id,
333                           "tags_id"  => $tag_id });
334     if(defined($value) && length($value))
335     {
336         my $val_id=$self->add_to_table("tags",  $value,
337                                        { "parents_id" => $tag_id });
338         $self->add_relation("files_x_tags",
339                             { "files_id" => $file_id,
340                               "tags_id"  => $val_id });
341     }
342 }
343
344 sub add_to_table
345 {
346     my($self, $table, $name, $extradata)=@_;
347     my $parent=undef;
348     if($extradata && $extradata->{parents_id})
349     {
350         $parent=$extradata->{parents_id};
351     }
352     my $id=$self->lookup_id($table, $name, $parent);
353     unless(defined($id))
354     {
355         my $sql="INSERT INTO $table (";
356         my @fields=qw(name);
357         if(defined($extradata))
358         {
359             push(@fields, sort keys(%$extradata));
360         }
361         $sql .= join(", ", @fields);
362         $sql .=") VALUES (";
363         $sql .= join(", ", map { "?"; } @fields);
364         $sql .= ");";
365         $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
366     }
367     return $id;
368 }
369
370 sub add_relation
371 {
372     my ($self, $relname, $fields)=@_;
373     return if($self->relation_exists($relname, $fields));
374     my $sql="INSERT INTO $relname (";
375     $sql .= join(", ", sort keys(%$fields));
376     $sql .= ") VALUES (";
377     $sql .= join(", ", map { "?"; } sort keys(%$fields));
378     $sql .= ");";
379     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
380 }
381
382 # remove existing files_x_tags relations before reindexing
383 sub remove_tag_refs
384 {
385     my ($self, $id)=@_;
386     my $sql="DELETE FROM files_x_tags WHERE files_id=?\n";
387     return($self->cmd($sql, $id));
388 }
389
390 sub files_in
391 {
392     my ($self, $dir)=@_;
393     my $sql=("SELECT files.name FROM files\n" .
394              "INNER JOIN paths ON files.paths_id=paths.id\n" .
395              "WHERE paths.name=?\n");
396     return($self->cmd_firstcol($sql, $dir));
397 }
398
399 sub unindex
400 {
401     my($self, $path, $file)=@_;
402     my $sql=("DELETE FROM files WHERE id IN (" .
403              "\tSELECT files.id FROM files\n" .
404              "\tINNER JOIN paths ON paths.id=files.paths_id\n" .
405              "\tWHERE paths.name=? and files.name=? )\n");
406     $self->cmd_rows($sql, $path, $file);
407 }
408
409
410 sub prune_directories
411 {
412     my($self,@includepaths)=@_;
413     my $sql=("SELECT name, id FROM paths\n");
414     my $pathsref=$self->cmd_rows($sql);
415     my @ids=();
416     for my $pathpair (@$pathsref)
417     {
418         my($path, $id)=@$pathpair;
419         my $relpath = $self->{base} . "/" . $path;
420         next unless(grep { $relpath =~ /^$_/; } @includepaths);
421         my $fullpath="$self->{absbase}/$path";
422         unless(-d $fullpath)
423         {
424             push(@ids, $id)
425         }
426     }
427     $self->prune_paths(@ids);
428     return scalar(@ids);
429 }
430
431 sub prune_paths
432 {
433     my($self, @ids)=@_;
434     return unless(@ids);
435     my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
436              join(', ', map { "\"$_\""; } @ids). "\n\t)");
437     $self->cmd($sql);
438 }
439
440 sub remove_unused
441 {
442     my($self)=@_;
443     my $sql=<<'EOT';
444    DELETE FROM artists WHERE id IN (
445        SELECT artists.id FROM artists
446        LEFT JOIN files ON files.artists_id=artists.id
447        WHERE files.id IS NULL);
448
449    DELETE FROM albums WHERE id IN (
450        SELECT albums.id FROM albums
451        LEFT JOIN files ON files.albums_id=albums.id
452        WHERE files.id IS NULL);
453
454    DELETE FROM paths WHERE id IN (
455        SELECT paths.id FROM paths
456        LEFT JOIN files ON files.paths_id=paths.id
457        WHERE files.id IS NULL);
458
459    DELETE FROM files_x_tags WHERE files_id IN (
460        SELECT files_x_tags.files_id FROM files_x_tags
461        LEFT JOIN files ON files.id=files_x_tags.files_id
462        WHERE files.id IS NULL);
463
464    DELETE FROM tags WHERE id IN (
465        SELECT tags.id FROM tags
466        LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
467        WHERE files_x_tags.files_id IS NULL);
468
469     VACUUM
470 EOT
471 #    print "SQL: $sql\n";
472     my @sql=split(/\n\n/, $sql);
473     $self->cmd($_) for (@sql);
474 }
475
476 sub relation_exists
477 {
478     my ($self, $relname, $fields)=@_;
479     my $sql="SELECT count(1) FROM $relname WHERE ";
480     my @exprs=();
481     my @vals=();
482     for my $field (keys %$fields)
483     {
484         push(@exprs,$field);
485         push(@vals,$fields->{$field});
486     }
487     $sql .= join(' AND ', map { "$_=?"; } @exprs);
488     my ($ret)=$self->cmd_onerow($sql, @vals);
489     return $ret;
490 }
491
492 sub ok
493 {
494     my($self, $thing)=@_;
495     return(defined($thing) && length($thing) && $thing =~ /\S+/);
496 }
497
498 # actually call the database
499 sub cmd_sth
500 {
501     my($self, $sql, @params)=@_;
502     my $sth=$self->{dbh}->prepare($sql);
503     my $idx=1;
504     for my $param (@params)
505     {
506         $param="" unless(defined($param));
507         $sth->bind_param($idx++, $param);
508     }
509     $sth->execute();
510     return $sth;
511 }
512
513 # pass cmd to db, ignore response
514 sub cmd
515 {
516     my ($self, @args)=@_;
517     # don't care about retcode
518     $self->cmd_sth(@args);
519 }
520
521 # return one row
522 sub cmd_onerow
523 {
524     my ($self, @args)=@_;
525     my $sth=$self->cmd_sth(@args);
526     return($sth->fetchrow_array());
527 }
528
529 # returns all rows
530 sub cmd_rows
531 {
532     my ($self, @args)=@_;
533     my $sth=$self->cmd_sth(@args);
534     return $sth->fetchall_arrayref();
535 }
536
537 # returns just the first column
538 sub cmd_firstcol
539 {
540     my ($self, @args)=@_;
541     return(map { $_->[0] } @{$self->cmd_rows(@args)});
542 }
543
544 # runs cmd, returns id of last insert
545 sub cmd_id
546 {
547     my ($self, @args)=@_;
548     $self->cmd_sth(@args);
549     return($self->last_insert_id());
550 }
551
552 sub last_insert_id
553 {
554     my $self=shift;
555     return $self->{dbh}->last_insert_id("","","","");
556 }
557
558 # lookup id of $name in $table, also matching on $parent if needed
559 sub lookup_id
560 {
561     my($self, $table, $name, $parent)=@_;
562     my $sql="SELECT id FROM $table where name=?";
563     my @args=($name);
564     if($parent)
565     {
566         $sql .= " AND parents_id=?";
567         push(@args, $parent);
568     }
569     my($id)=$self->cmd_onerow($sql, @args);
570     return $id;
571 }
572
573 __DATA__
574
575 CREATE TABLE id3fs (
576     schema_version INTEGER,
577     last_update
578 );
579
580 CREATE TABLE paths (
581     id INTEGER,
582     name text,
583     PRIMARY KEY(id ASC)
584 );
585
586 CREATE TABLE artists (
587     id INTEGER,
588     name text,
589     PRIMARY KEY(id ASC)
590 );
591
592 CREATE TABLE albums (
593     id INTEGER,
594     name text,
595     PRIMARY KEY(id ASC)
596 );
597
598 CREATE TABLE files (
599     id INTEGER,
600     name text,
601     artists_id,
602     albums_id,
603     paths_id,
604     PRIMARY KEY(id ASC),
605     FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
606     FOREIGN KEY(albums_id)  REFERENCES albums(id)  ON DELETE CASCADE ON UPDATE CASCADE,
607     FOREIGN KEY(paths_id)   REFERENCES paths(id)   ON DELETE CASCADE ON UPDATE CASCADE
608 );
609
610 CREATE TABLE tags (
611     id INTEGER,
612     parents_id INTEGER,
613     name text,
614     PRIMARY KEY(id ASC)
615 );
616
617 CREATE TABLE files_x_tags (
618     files_id INTEGER,
619     tags_id INTEGER,
620     FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
621     FOREIGN KEY(tags_id)  REFERENCES tags(id)  ON DELETE CASCADE ON UPDATE CASCADE
622 );
623
624 CREATE INDEX idx_fxt_both ON files_x_tags (files_id, tags_id)
625
626 CREATE INDEX idx_fxt_tags ON files_x_tags (tags_id)
627
628 CREATE INDEX idx_files_id_name ON files (id, name)
629
630 CREATE INDEX idx_files_name_id ON files (name, id)
631
632 CREATE INDEX idx_tags_id_parent_name ON tags (id, parents_id, name)
633
634 CREATE INDEX idx_tags_parent_id_name ON tags (parents_id, id, name)
635
636 CREATE INDEX idx_tags_name ON tags (name)