set bitrate/samplerate to UNKNOWN when == 0
[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         do
76         {
77             $base=$path;
78             $path=~s/(.*)\/.*/$1/;
79         }
80         while(! -f "$base/$dbfile" && length($path) && -d $path);
81         if(-f "$base/$dbfile")
82         {
83             return $base;
84         }
85     }
86     if(!-f "$base/$dbfile")
87     {
88         unless($init)
89         {
90             print "$me: db not found at $base/$dbfile\n";
91             return undef;
92         }
93         $base=$dirs[0];
94
95     }
96     return $base;
97 }
98
99 sub base_dir { return shift->{base}; }
100
101 sub create
102 {
103     my($self,$name)=@_;
104     my @schema=split(/\n\n/,join("", <DATA>));
105     close(DATA);
106     for my $cmd (@schema)
107     {
108         $self->{dbh}->do($cmd);
109     }
110     $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
111                $SCHEMA_VERSION, time());
112 }
113
114 sub checkschema
115 {
116     my $self=shift;
117     my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
118     if(!defined($version) || $version != $SCHEMA_VERSION)
119     {
120         die("$self->{me}: id3fs database version " .
121             defined($version) ? $version : '""' .
122             "not known, current version is $SCHEMA_VERSION.\n");
123     }
124 }
125
126 sub analyze
127 {
128     my $self=shift;
129     $self->cmd("ANALYZE");
130 }
131
132 sub enable_foreign_keys
133 {
134     my $self=shift;
135     $self->cmd("PRAGMA foreign_keys = ON");
136 }
137
138 sub last_update
139 {
140     my($self, $newval)=@_;
141     if(defined($newval))
142     {
143         $self->cmd("UPDATE id3fs SET last_update=?", $newval);
144     }
145     else
146     {
147         ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
148     }
149     return $newval;
150 }
151
152 sub bare_tags
153 {
154     my($self)=@_;
155     my $sql=("SELECT tags.name FROM tags\n" .
156              "WHERE tags.parents_id=''\n" .
157              "GROUP BY tags.name\n");
158     my @names=$self->cmd_firstcol($sql);
159     return (@names);
160 }
161
162 sub tags_with_values
163 {
164     my($self)=@_;
165     my $sql=("SELECT p.name, t.name  FROM tags t\n" .
166              "INNER JOIN tags p ON t.parents_id=p.id\n" .
167              "GROUP BY p.name, t.name\n");
168     my $result=$self->cmd_rows($sql);
169     my $tags={};
170     for my $pair (@$result)
171     {
172         push(@{$tags->{$pair->[0]}}, $pair->[1]);
173     }
174     return $tags;
175 }
176
177 sub tag_has_values
178 {
179     my($self, $id)=@_;
180     my $sql=("SELECT COUNT(*) FROM tags\n\t" .
181              "WHERE tags.parents_id=?\n");
182     my ($rows)=$self->cmd_onerow($sql, $id);
183     return $rows;
184 }
185
186 sub relativise
187 {
188     my($self, $path, $name, $mountpoint, $querypath)=@_;
189     my $rpath="$self->{absbase}/$path";
190     my $vpath=$mountpoint . $querypath;
191     my @path=split(/\//,$rpath);
192     my @rel=split(/\//,$vpath);
193     # drop filename from rel
194     pop @rel;
195     # absolute paths have empty first element due to leading /
196     shift(@path) if($path[0] eq "");
197     shift(@rel)  if($rel[0]  eq "");
198     # f: /home/foo/bar/baz.mp3
199     # r: /home/ianb/music/albums
200     while(@path && @rel && ($path[0] eq $rel[0]))
201     {
202         shift(@path);
203         shift(@rel);
204     }
205     my $upcount=scalar(@rel);
206     my $result="../" x $upcount;
207     $result .= join("/",@path);
208     $result .= "/$name";
209     return $result;
210 }
211
212 sub add
213 {
214     my($self,$path)=@_;
215     my $relpath=Cwd::abs_path($path);
216     $relpath =~ s/^\Q$self->{absbase}\E\/?//;
217     my($filepart,$pathpart);
218     if($relpath !~ /\//)
219     {
220         $pathpart='';
221         $filepart=$relpath;
222     }
223     else
224     {
225         ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
226     }
227     my $file=ID3FS::AudioFile->new($path, $self->{me});
228     return unless(defined($file));
229     my $artist=$file->artist();
230     my $album=$file->album();
231     my $v1genre=$file->v1genre();
232     my $year=$file->year();
233     my $audiotype=$file->audiotype();
234     my @tags=$file->tags();
235     my $haspic=$file->haspic();
236     my $channels=$file->channels();
237     my $bitrate=$file->bitrate();
238     my $samplerate=$file->samplerate();
239
240     $artist=undef unless($self->ok($artist));
241     print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
242     my $artist_id=$self->add_to_table("artists",  $artist);
243     my $path_id=$self->add_to_table("paths", $pathpart);
244     $album=undef unless($self->ok($album));
245 #    if($self->{verbose} && !defined($album)) FIXME
246     if(!defined($album))
247     {
248         print "$self->{me}: $path: no album tag defined\n";
249     }
250
251     my $albums_id=$self->add_to_table("albums", $album);
252     my $file_id=$self->add_to_table("files", $filepart,
253                                     { "artists_id" => $artist_id,
254                                       "albums_id"  => $albums_id,
255                                       "paths_id"   => $path_id });
256     if(@tags)
257     {
258         for my $tag (@tags)
259         {
260             $self->add_tag($file_id, @$tag);
261         }
262     }
263     else
264     {
265         $self->add_tag($file_id, "UNTAGGED");
266     }
267
268     $year="UNKNOWN" if(!$self->ok($year) || $year =~ /^0+$/);
269     $self->add_tag($file_id, "year", $year);
270     if($year=~/^(\d\d\d)\d$/)
271     {
272         $self->add_tag($file_id, "decade", "${1}0s");
273     }
274     else
275     {
276         $self->add_tag($file_id, "decade", "UNKNOWN");
277     }
278
279     if($self->ok($v1genre))
280     {
281         $self->add_tag($file_id, "v1genre", $v1genre);
282     }
283
284     if($haspic)
285     {
286         $self->add_tag($file_id, "haspic", undef);
287     }
288
289     if($self->ok($audiotype))
290     {
291         $self->add_tag($file_id, "audiotype", $audiotype);
292     }
293
294     if($self->ok($channels))
295     {
296         if    ($channels eq "2") { $channels="stereo";  }
297         elsif ($channels eq "1") { $channels="mono";    }
298         elsif ($channels eq "0") { $channels="UNKNOWN"; }
299         $self->add_tag($file_id, "channels", $channels);
300     }
301
302     if($self->ok($bitrate))
303     {
304         $bitrate="UNKNOWN" if($bitrate=~/^0+$/);
305         $self->add_tag($file_id, "bitrate", $bitrate);
306     }
307
308     if($self->ok($samplerate))
309     {
310         $samplerate="UNKNOWN" if($samplerate=~/^0+$/);
311         $self->add_tag($file_id, "samplerate", $samplerate);
312     }
313
314 }
315
316 sub add_tag
317 {
318     my($self, $file_id, $tag, $value)=@_;
319     my $tag_id=$self->add_to_table("tags",  $tag,
320                                    { "parents_id" => undef });
321     $self->add_relation("files_x_tags",
322                         { "files_id" => $file_id,
323                           "tags_id"  => $tag_id });
324     if(defined($value) && length($value))
325     {
326         my $val_id=$self->add_to_table("tags",  $value,
327                                        { "parents_id" => $tag_id });
328         $self->add_relation("files_x_tags",
329                             { "files_id" => $file_id,
330                               "tags_id"  => $val_id });
331     }
332 }
333
334 sub add_to_table
335 {
336     my($self, $table, $name, $extradata)=@_;
337     my $parent=undef;
338     if($extradata && $extradata->{parents_id})
339     {
340         $parent=$extradata->{parents_id};
341     }
342     my $id=$self->lookup_id($table, $name, $parent);
343     unless(defined($id))
344     {
345         my $sql="INSERT INTO $table (";
346         my @fields=qw(name);
347         if(defined($extradata))
348         {
349             push(@fields, sort keys(%$extradata));
350         }
351         $sql .= join(", ", @fields);
352         $sql .=") VALUES (";
353         $sql .= join(", ", map { "?"; } @fields);
354         $sql .= ");";
355         $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
356     }
357     return $id;
358 }
359
360 sub add_relation
361 {
362     my ($self, $relname, $fields)=@_;
363     return if($self->relation_exists($relname, $fields));
364     my $sql="INSERT INTO $relname (";
365     $sql .= join(", ", sort keys(%$fields));
366     $sql .= ") VALUES (";
367     $sql .= join(", ", map { "?"; } sort keys(%$fields));
368     $sql .= ");";
369     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
370 }
371
372 sub files_in
373 {
374     my ($self, $dir)=@_;
375     my $sql=("SELECT files.name FROM files\n" .
376              "INNER JOIN paths ON files.paths_id=paths.id\n" .
377              "WHERE paths.name=?\n");
378     return($self->cmd_firstcol($sql, $dir));
379 }
380
381 sub unindex
382 {
383     my($self, $path, $file)=@_;
384     my $sql=("DELETE FROM files WHERE id IN (" .
385              "\tSELECT files.id FROM files\n" .
386              "\tINNER JOIN paths ON paths.id=files.paths_id\n" .
387              "\tWHERE paths.name=? and files.name=? )\n");
388     $self->cmd_rows($sql, $path, $file);
389 }
390
391
392 sub prune_directories
393 {
394     my($self)=@_;
395     my $sql=("SELECT name, id FROM paths\n");
396     my $pathsref=$self->cmd_rows($sql);
397     my @ids=();
398     for my $pathpair (@$pathsref)
399     {
400         my($path, $id)=@$pathpair;
401         my $fullpath="$self->{absbase}/$path";
402         unless(-d $fullpath)
403         {
404             push(@ids, $id)
405         }
406     }
407     $self->prune_paths(@ids);
408     return scalar(@ids);
409 }
410
411 sub prune_paths
412 {
413     my($self, @ids)=@_;
414     return unless(@ids);
415     my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
416              join(', ', map { "\"$_\""; } @ids). "\n\t)");
417     $self->cmd($sql);
418 }
419
420 sub remove_unused
421 {
422     my($self)=@_;
423     my $sql=<<'EOT';
424    DELETE FROM artists WHERE id IN (
425        SELECT artists.id FROM artists
426        LEFT JOIN files ON files.artists_id=artists.id
427        WHERE files.id IS NULL);
428
429    DELETE FROM albums WHERE id IN (
430        SELECT albums.id FROM albums
431        LEFT JOIN files ON files.albums_id=albums.id
432        WHERE files.id IS NULL);
433
434    DELETE FROM paths WHERE id IN (
435        SELECT paths.id FROM paths
436        LEFT JOIN files ON files.paths_id=paths.id
437        WHERE files.id IS NULL);
438
439    DELETE FROM files_x_tags WHERE files_id IN (
440        SELECT files_x_tags.files_id FROM files_x_tags
441        LEFT JOIN files ON files.id=files_x_tags.files_id
442        WHERE files.id IS NULL);
443
444    DELETE FROM tags WHERE id IN (
445        SELECT tags.id FROM tags
446        LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
447        WHERE files_x_tags.files_id IS NULL);
448
449     VACUUM
450 EOT
451 #    print "SQL: $sql\n";
452     my @sql=split(/\n\n/, $sql);
453     $self->cmd($_) for (@sql);
454 }
455
456 sub relation_exists
457 {
458     my ($self, $relname, $fields)=@_;
459     my $sql="SELECT count(1) FROM $relname WHERE ";
460     my @exprs=();
461     my @vals=();
462     for my $field (keys %$fields)
463     {
464         push(@exprs,$field);
465         push(@vals,$fields->{$field});
466     }
467     $sql .= join(' AND ', map { "$_=?"; } @exprs);
468     my ($ret)=$self->cmd_onerow($sql, @vals);
469     return $ret;
470 }
471
472 sub ok
473 {
474     my($self, $thing)=@_;
475     return(defined($thing) && length($thing) && $thing =~ /\S+/);
476 }
477
478 # actually call the database
479 sub cmd_sth
480 {
481     my($self, $sql, @params)=@_;
482     my $sth=$self->{dbh}->prepare($sql);
483     my $idx=1;
484     for my $param (@params)
485     {
486         $param="" unless(defined($param));
487         $sth->bind_param($idx++, $param);
488     }
489     $sth->execute();
490     return $sth;
491 }
492
493 # pass cmd to db, ignore response
494 sub cmd
495 {
496     my ($self, @args)=@_;
497     # don't care about retcode
498     $self->cmd_sth(@args);
499 }
500
501 # return one row
502 sub cmd_onerow
503 {
504     my ($self, @args)=@_;
505     my $sth=$self->cmd_sth(@args);
506     return($sth->fetchrow_array());
507 }
508
509 # returns all rows
510 sub cmd_rows
511 {
512     my ($self, @args)=@_;
513     my $sth=$self->cmd_sth(@args);
514     return $sth->fetchall_arrayref();
515 }
516
517 # returns just the first column
518 sub cmd_firstcol
519 {
520     my ($self, @args)=@_;
521     return(map { $_->[0] } @{$self->cmd_rows(@args)});
522 }
523
524 # runs cmd, returns id of last insert
525 sub cmd_id
526 {
527     my ($self, @args)=@_;
528     $self->cmd_sth(@args);
529     return($self->last_insert_id());
530 }
531
532 sub last_insert_id
533 {
534     my $self=shift;
535     return $self->{dbh}->last_insert_id("","","","");
536 }
537
538 # lookup id of $name in $table, also matching on $parent if needed
539 sub lookup_id
540 {
541     my($self, $table, $name, $parent)=@_;
542     my $sql="SELECT id FROM $table where name=?";
543     my @args=($name);
544     if($parent)
545     {
546         $sql .= " AND parents_id=?";
547         push(@args, $parent);
548     }
549     my($id)=$self->cmd_onerow($sql, @args);
550     return $id;
551 }
552
553 __DATA__
554
555 CREATE TABLE id3fs (
556     schema_version INTEGER,
557     last_update
558 );
559
560 CREATE TABLE paths (
561     id INTEGER,
562     name text,
563     PRIMARY KEY(id ASC)
564 );
565
566 CREATE TABLE artists (
567     id INTEGER,
568     name text,
569     PRIMARY KEY(id ASC)
570 );
571
572 CREATE TABLE albums (
573     id INTEGER,
574     name text,
575     PRIMARY KEY(id ASC)
576 );
577
578 CREATE TABLE files (
579     id INTEGER,
580     name text,
581     artists_id,
582     albums_id,
583     paths_id,
584     PRIMARY KEY(id ASC),
585     FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
586     FOREIGN KEY(albums_id)  REFERENCES albums(id)  ON DELETE CASCADE ON UPDATE CASCADE,
587     FOREIGN KEY(paths_id)   REFERENCES paths(id)   ON DELETE CASCADE ON UPDATE CASCADE
588 );
589
590 CREATE TABLE tags (
591     id INTEGER,
592     parents_id INTEGER,
593     name text,
594     PRIMARY KEY(id ASC)
595 );
596
597 CREATE TABLE files_x_tags (
598     files_id INTEGER,
599     tags_id INTEGER,
600     FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
601     FOREIGN KEY(tags_id)  REFERENCES tags(id)  ON DELETE CASCADE ON UPDATE CASCADE
602 );
603
604 CREATE INDEX idx_fxt_both ON files_x_tags (files_id, tags_id)
605
606 CREATE INDEX idx_fxt_tags ON files_x_tags (tags_id)
607
608 CREATE INDEX idx_files_id_name ON files (id, name)
609
610 CREATE INDEX idx_files_name_id ON files (name, id)
611
612 CREATE INDEX idx_tags_id_parent_name ON tags (id, parents_id, name)
613
614 CREATE INDEX idx_tags_parent_id_name ON tags (parents_id, id, name)
615
616 CREATE INDEX idx_tags_name ON tags (name)