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