fix handling of unset artist/album; unset years default to UNKNOWN
[id3fs.git] / lib / ID3FS / DB.pm
1 package ID3FS::DB;
2
3 use strict;
4 use warnings;
5 use DBI;
6 use ID3FS::AudioFile;
7 use Cwd;
8
9 our $SCHEMA_VERSION=1;
10 my $dbfile=".id3fs";
11
12 sub new
13 {
14     my $proto=shift;
15     my $class=ref($proto) || $proto;
16     my $self={};
17     bless($self,$class);
18
19     $self->{me}=shift;
20     $self->{verbose}=shift;
21     my $init=shift;
22     my $dbpath=shift;
23     $self->{base}=shift;
24     my $fallbackdir=shift;
25
26     $dbpath=$self->find_db($init, $dbpath, $fallbackdir);
27     return undef unless($dbpath);
28     $self->{absbase}=Cwd::abs_path($self->{base});
29
30     my $connectstr="dbi:SQLite:dbname=$dbpath";
31     my ($user, $pass)=("", "");
32     if($self->{postgres})
33     {
34         $connectstr="dbi:Pg:dbname=id3fs";
35         $user="ianb";
36         $pass="foo";
37     }
38     my $exists=-f $dbpath;
39     $self->{dbh}=DBI->connect($connectstr, $user, $pass,
40                               { AutoCommit=>1 } );
41     unless(defined($self->{dbh}))
42     {
43         die("$self->{me}: DB Error: " . $DBI::errstr . "\n");
44     }
45
46     if($exists)
47     {
48         $self->checkschema();
49     }
50     else
51     {
52         $self->create();
53     }
54     $self->enable_foreign_keys();
55     return $self;
56 }
57
58 sub find_db
59 {
60     my($self, $init, $dbpath, $fallbackdir)=@_;
61     my $file=undef;
62     my $base=undef;
63     if(defined($dbpath))
64     {
65         $file=$dbpath;
66     }
67     if(defined ($self->{base}))
68     {
69         $file="$self->{base}/$dbfile" unless defined($file);
70         $base=$self->{base};
71     }
72     elsif(defined($fallbackdir) && -d $fallbackdir)
73     {
74         my $path=Cwd::abs_path($fallbackdir);
75         do
76         {
77             $file="$path/$dbfile";
78             $base=$path;
79             $path=~s/(.*)\/.*/$1/;
80         }
81         while(! -f $file && length($path) && -d $path);
82         if(! -f $file)
83         {
84             $file="$fallbackdir/$dbfile";
85             $base=$fallbackdir;
86         }
87     }
88     if(!-f $file && !$init)
89     {
90         print "$self->{me}: db not found at $file\n";
91         return undef;
92     }
93     $self->{base}=$base;
94     return $file;
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     if($self->{postgres})
109     {
110         $self->cmd("CREATE SEQUENCE seq");
111     }
112     else
113     {
114         my %indexes=( "idx_files_id"  => "files (id)",
115                       "idx_fxt_both"  => "files_x_tags (files_id, tags_id)",
116                       "idx_fxt_files" => "files_x_tags (files_id)",
117                       "idx_fxt_tags"  => "files_x_tags (tags_id)",
118                       "idx_tags_id"   => "tags (id)",
119                       "idx_tags_name" => "tags (name)");
120         for my $index (keys %indexes)
121         {
122             $self->{dbh}->do("CREATE INDEX $index ON " . $indexes{$index});
123         }
124     }
125     $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
126                $SCHEMA_VERSION, time());
127 }
128
129 sub checkschema
130 {
131     my $self=shift;
132     my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
133     if(!defined($version) || $version != $SCHEMA_VERSION)
134     {
135         die("$self->{me}: id3fs database version " .
136             defined($version) ? $version : '""' .
137             "not known, current version is $SCHEMA_VERSION.\n");
138     }
139 }
140
141 sub analyze
142 {
143     my $self=shift;
144     $self->cmd("ANALYZE");
145 }
146
147 sub enable_foreign_keys
148 {
149     my $self=shift;
150     $self->cmd("PRAGMA foreign_keys = ON");
151 }
152
153 sub last_update
154 {
155     my($self, $newval)=@_;
156     if(defined($newval))
157     {
158         $self->cmd("UPDATE id3fs SET last_update=?", $newval);
159     }
160     else
161     {
162         ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
163     }
164     return $newval;
165 }
166
167 sub id
168 {
169     my($self, $type, $val)=@_;
170     my $sql="SELECT id FROM $type WHERE name=?";
171     my ($id)=$self->cmd_onerow($sql, $val);
172     return($id);
173 }
174
175 sub tag_has_values
176 {
177     my($self, $id)=@_;
178     my $sql=("SELECT COUNT(*) FROM tags\n\t" .
179              "WHERE tags.parents_id=?\n");
180     my ($rows)=$self->cmd_onerow($sql, $id);
181     return $rows;
182 }
183
184 sub relativise
185 {
186     my($self, $path, $name, $mountpoint, $id3fs_path)=@_;
187     $id3fs_path=~s/(.*)\/.*/$1/;
188     my $rpath="$self->{absbase}/$path";
189     my $vpath="$mountpoint/$id3fs_path";
190     my @path=split(/\//,$rpath);
191     my @rel=split(/\//,$vpath);
192     #absolute paths have empty first element due to leading /
193     shift(@path) if($path[0] eq "");
194     shift(@rel)  if($rel[0]  eq "");
195     if($path[0] ne $rel[0])
196     {
197         #no path in common, return absolute
198         print "FAIL: NO PATHS IN COMMON\n";
199         return $name;
200     }
201     # f: /home/foo/bar/baz.mp3
202     # r: /home/ianb/music/albums
203     while(@path && @rel && ($path[0] eq $rel[0]))
204     {
205         shift(@path);
206         shift(@rel);
207 #       print "POP ";
208     }
209 #    print "\n";
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=$path;
221     $relpath =~ s/^\Q$self->{base}\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
269     if($self->ok($v1genre))
270     {
271         $self->add_tag($file_id, "v1genre", $v1genre);
272     }
273
274     if($haspic)
275     {
276         $self->add_tag($file_id, "haspic", undef);
277     }
278 }
279
280 sub add_tag
281 {
282     my($self, $file_id, $tag, $value)=@_;
283     my $tag_id=$self->add_to_table("tags",  $tag,
284                                    { "parents_id" => undef });
285     $self->add_relation("files_x_tags",
286                         { "files_id" => $file_id,
287                           "tags_id"  => $tag_id });
288     if(defined($value) && length($value))
289     {
290         my $val_id=$self->add_to_table("tags",  $value,
291                                        { "parents_id" => $tag_id });
292         $self->add_relation("files_x_tags",
293                             { "files_id" => $file_id,
294                               "tags_id"  => $val_id });
295     }
296 }
297
298 sub add_to_table
299 {
300     my($self, $table, $name, $extradata)=@_;
301     my $id=$self->lookup_id($table, $name);
302     unless(defined($id))
303     {
304         my $sql="INSERT INTO $table (";
305         $sql .= "id, " if($self->{postgres});
306         my @fields=qw(name);
307         if(defined($extradata))
308         {
309             push(@fields, sort keys(%$extradata));
310         }
311         $sql .= join(", ", @fields);
312         $sql .=") VALUES (";
313         $sql .=") nextval('seq'), " if($self->{postgres});
314         $sql .= join(", ", map { "?"; } @fields);
315         $sql .= ");";
316         $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
317     }
318     return $id;
319 }
320
321 sub add_relation
322 {
323     my ($self, $relname, $fields)=@_;
324     return if($self->relation_exists($relname, $fields));
325     my $sql="INSERT INTO $relname (";
326     $sql .= join(", ", sort keys(%$fields));
327     $sql .= ") VALUES (";
328     $sql .= join(", ", map { "?"; } sort keys(%$fields));
329     $sql .= ");";
330     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
331 }
332
333 sub files_in
334 {
335     my ($self, $dir)=@_;
336     $dir=~s/^$self->{base}\/?//;
337     my $sql=("SELECT files.name FROM files\n" .
338              "INNER JOIN paths ON files.paths_id=paths.id\n" .
339              "WHERE paths.name=?\n");
340     my $files=$self->cmd_rows($sql, $dir);
341     return(map { $_->[0]; } @$files);
342 }
343
344 sub prune_directories
345 {
346     my($self)=@_;
347     my $sql=("SELECT name, id FROM paths ORDER BY name\n");
348     my $pathsref=$self->cmd_rows($sql);
349     my @ids=();
350     for my $pathpair (@$pathsref)
351     {
352         my($path, $id)=@$pathpair;
353         my $fullpath="$self->{absbase}/$path";
354         unless(-d $fullpath)
355         {
356             push(@ids, $id)
357         }
358     }
359     $self->prune_paths(@ids);
360     return scalar(@ids);
361 }
362
363 sub prune_paths
364 {
365     my($self, @ids)=@_;
366     return unless(@ids);
367     my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
368              join(', ', map { "\"$_\""; } @ids). "\n\t)");
369     print "SQL: \n", $sql, "\n";
370     $self->cmd($sql);
371 }
372
373 sub remove_unused
374 {
375     my($self)=@_;
376     my $sql=<<'EOT';
377    DELETE FROM artists WHERE id IN (
378        SELECT artists.id FROM artists
379        LEFT JOIN files ON files.artists_id=artists.id
380        WHERE files.id IS NULL);
381
382    DELETE FROM albums WHERE id IN (
383        SELECT albums.id FROM albums
384        LEFT JOIN files ON files.albums_id=albums.id
385        WHERE files.id IS NULL);
386
387    DELETE FROM paths WHERE id IN (
388        SELECT paths.id FROM paths
389        LEFT JOIN files ON files.paths_id=paths.id
390        WHERE files.id IS NULL);
391
392    DELETE FROM files_x_tags WHERE files_id IN (
393        SELECT files_x_tags.files_id FROM files_x_tags
394        LEFT JOIN files ON files.id=files_x_tags.files_id
395        WHERE files.id IS NULL);
396
397    DELETE FROM tags WHERE id IN (
398        SELECT tags.id FROM tags
399        LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
400        WHERE files_x_tags.files_id IS NULL);
401
402     VACUUM
403 EOT
404     print "SQL: $sql\n";
405     my @sql=split(/\n\n/, $sql);
406     $self->cmd($_) for (@sql);
407 }
408
409 sub relation_exists
410 {
411     my ($self, $relname, $fields)=@_;
412     my $sql="SELECT count(1) FROM $relname WHERE ";
413     my @exprs=();
414     my @vals=();
415     for my $field (keys %$fields)
416     {
417         push(@exprs,$field);
418         push(@vals,$fields->{$field});
419     }
420     $sql .= join(' AND ', map { "$_=?"; } @exprs);
421     my ($ret)=$self->cmd_onerow($sql, @vals);
422     return $ret;
423 }
424
425 sub ok
426 {
427     my($self, $thing)=@_;
428     return(defined($thing) && length($thing) && $thing =~ /\S+/);
429 }
430
431 sub cmd_sth
432 {
433     my($self, $sql, @params)=@_;
434     my $sth=$self->{dbh}->prepare($sql);
435     my $idx=1;
436     for my $param (@params)
437     {
438         $param="" unless(defined($param));
439         $sth->bind_param($idx++, $param);
440     }
441     $sth->execute();
442     return $sth;
443 }
444
445 sub cmd
446 {
447     my ($self, @args)=@_;
448     # don't care about retcode
449     $self->cmd_sth(@args);
450 }
451
452 sub cmd_onerow
453 {
454     my ($self, @args)=@_;
455     my $sth=$self->cmd_sth(@args);
456     return($sth->fetchrow_array());
457 }
458
459 sub cmd_rows
460 {
461     my ($self, @args)=@_;
462     my $sth=$self->cmd_sth(@args);
463     return $sth->fetchall_arrayref();
464 }
465
466 sub cmd_firstcol
467 {
468     my ($self, @args)=@_;
469     return(map { $_->[0] } @{$self->cmd_rows(@args)});
470 }
471
472 sub cmd_id
473 {
474     my ($self, @args)=@_;
475     $self->cmd_sth(@args);
476     return($self->last_insert_id());
477 }
478
479 sub last_insert_id
480 {
481     my $self=shift;
482     if($self->{postgres})
483     {
484         return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
485                                             { sequence => "seq" });
486     }
487     else
488     {
489         return $self->{dbh}->last_insert_id("","","","");
490     }
491 }
492
493 sub lookup_id
494 {
495     my($self, $table, $name)=@_;
496     my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
497     return $id;
498 }
499
500 __DATA__
501
502 CREATE TABLE id3fs (
503     schema_version INTEGER,
504     last_update
505 );
506
507 CREATE TABLE paths (
508     id INTEGER PRIMARY KEY,
509     name text
510 );
511
512 CREATE TABLE artists (
513     id INTEGER PRIMARY KEY,
514     name text
515 );
516
517 CREATE TABLE albums (
518     id INTEGER PRIMARY KEY,
519     name text
520 );
521
522 CREATE TABLE files (
523     id INTEGER PRIMARY KEY,
524     name text,
525     artists_id,
526     albums_id,
527     paths_id,
528     FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
529     FOREIGN KEY(albums_id)  REFERENCES albums(id)  ON DELETE CASCADE ON UPDATE CASCADE,
530     FOREIGN KEY(paths_id)   REFERENCES paths(id)   ON DELETE CASCADE ON UPDATE CASCADE
531 );
532
533 CREATE TABLE tags (
534     id INTEGER PRIMARY KEY,
535     parents_id INTEGER,
536     name text
537 );
538
539 CREATE TABLE files_x_tags (
540     files_id INTEGER,
541     tags_id INTEGER,
542     FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
543     FOREIGN KEY(tags_id)  REFERENCES tags(id)  ON DELETE CASCADE ON UPDATE CASCADE
544 );
545