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