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