ensure tags with different parents have different entries; tweak schema
[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     else
89     {
90         print "$self->{me}: $fallbackdir: not a directory\n";
91         return undef;
92     }
93     if(!-f $file && !$init)
94     {
95         print "$self->{me}: db not found at $file\n";
96         return undef;
97     }
98     $self->{base}=$base;
99     return $file;
100 }
101
102 sub base_dir { return shift->{base}; }
103
104 sub create
105 {
106     my($self,$name)=@_;
107     my @schema=split(/\n\n/,join("", <DATA>));
108     close(DATA);
109     for my $cmd (@schema)
110     {
111         $self->{dbh}->do($cmd);
112     }
113     if($self->{postgres})
114     {
115         $self->cmd("CREATE SEQUENCE seq");
116     }
117     else
118     {
119         my %indexes=( "idx_files_id"  => "files (id)",
120                       "idx_fxt_both"  => "files_x_tags (files_id, tags_id)",
121                       "idx_fxt_files" => "files_x_tags (files_id)",
122                       "idx_fxt_tags"  => "files_x_tags (tags_id)",
123                       "idx_tags_id"   => "tags (id)",
124                       "idx_tags_name" => "tags (name)");
125         for my $index (keys %indexes)
126         {
127             $self->{dbh}->do("CREATE INDEX $index ON " . $indexes{$index});
128         }
129     }
130     $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
131                $SCHEMA_VERSION, time());
132 }
133
134 sub checkschema
135 {
136     my $self=shift;
137     my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
138     if(!defined($version) || $version != $SCHEMA_VERSION)
139     {
140         die("$self->{me}: id3fs database version " .
141             defined($version) ? $version : '""' .
142             "not known, current version is $SCHEMA_VERSION.\n");
143     }
144 }
145
146 sub analyze
147 {
148     my $self=shift;
149     $self->cmd("ANALYZE");
150 }
151
152 sub enable_foreign_keys
153 {
154     my $self=shift;
155     $self->cmd("PRAGMA foreign_keys = ON");
156 }
157
158 sub last_update
159 {
160     my($self, $newval)=@_;
161     if(defined($newval))
162     {
163         $self->cmd("UPDATE id3fs SET last_update=?", $newval);
164     }
165     else
166     {
167         ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
168     }
169     return $newval;
170 }
171
172 sub id
173 {
174     my($self, $type, $val)=@_;
175     my $sql="SELECT id FROM $type WHERE name=?";
176     my ($id)=$self->cmd_onerow($sql, $val);
177     return($id);
178 }
179
180 sub tag_has_values
181 {
182     my($self, $id)=@_;
183     my $sql=("SELECT COUNT(*) FROM tags\n\t" .
184              "WHERE tags.parents_id=?\n");
185     my ($rows)=$self->cmd_onerow($sql, $id);
186     return $rows;
187 }
188
189 sub relativise
190 {
191     my($self, $path, $name, $mountpoint, $id3fs_path)=@_;
192     $id3fs_path=~s/(.*)\/.*/$1/;
193     my $rpath="$self->{absbase}/$path";
194     my $vpath="$mountpoint/$id3fs_path";
195     my @path=split(/\//,$rpath);
196     my @rel=split(/\//,$vpath);
197     #absolute paths have empty first element due to leading /
198     shift(@path) if($path[0] eq "");
199     shift(@rel)  if($rel[0]  eq "");
200     if($path[0] ne $rel[0])
201     {
202         #no path in common, return absolute
203         print "FAIL: NO PATHS IN COMMON\n";
204         return $name;
205     }
206     # f: /home/foo/bar/baz.mp3
207     # r: /home/ianb/music/albums
208     while(@path && @rel && ($path[0] eq $rel[0]))
209     {
210         shift(@path);
211         shift(@rel);
212 #       print "POP ";
213     }
214 #    print "\n";
215     my $upcount=scalar(@rel);
216     my $result="../" x $upcount;
217     $result .= join("/",@path);
218     $result .= "/$name";
219     return $result;
220 }
221
222 sub add
223 {
224     my($self,$path)=@_;
225     my $relpath=Cwd::abs_path($path);
226     $relpath =~ s/^\Q$self->{absbase}\E\/?//;
227     my($filepart,$pathpart);
228     if($relpath !~ /\//)
229     {
230         $pathpart='';
231         $filepart=$relpath;
232     }
233     else
234     {
235         ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
236     }
237     my $file=ID3FS::AudioFile->new($path, $self->{me});
238     return unless(defined($file));
239     my $artist=$file->artist();
240     my $album=$file->album();
241     my $v1genre=$file->v1genre();
242     my $year=$file->year();
243     my $audiotype=$file->audiotype();
244     my @tags=$file->tags();
245     my $haspic=$file->haspic();
246
247     $artist=undef unless($self->ok($artist));
248     print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
249     my $artist_id=$self->add_to_table("artists",  $artist);
250     my $path_id=$self->add_to_table("paths", $pathpart);
251     $album=undef unless($self->ok($album));
252     if($self->{verbose} && !defined($album))
253     {
254         print "$self->{me}: $path: no album tag defined\n";
255     }
256
257     my $albums_id=$self->add_to_table("albums", $album);
258     my $file_id=$self->add_to_table("files", $filepart,
259                                     { "artists_id" => $artist_id,
260                                       "albums_id"  => $albums_id,
261                                       "paths_id"   => $path_id });
262     for my $tag (@tags)
263     {
264         $self->add_tag($file_id, @$tag);
265     }
266
267     $year="UNKNOWN" unless($self->ok($year));
268     $self->add_tag($file_id, "year", $year);
269     if($year=~/^(\d\d\d)\d$/)
270     {
271         $self->add_tag($file_id, "decade", "${1}0s");
272     }
273     else
274     {
275         $self->add_tag($file_id, "decade", "UNKNOWN");
276     }
277
278     if($self->ok($v1genre))
279     {
280         $self->add_tag($file_id, "v1genre", $v1genre);
281     }
282
283     if($haspic)
284     {
285         $self->add_tag($file_id, "haspic", undef);
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         $sql .= "id, " if($self->{postgres});
320         my @fields=qw(name);
321         if(defined($extradata))
322         {
323             push(@fields, sort keys(%$extradata));
324         }
325         $sql .= join(", ", @fields);
326         $sql .=") VALUES (";
327         $sql .=") nextval('seq'), " if($self->{postgres});
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 ORDER BY name\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     if($self->{postgres})
507     {
508         return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
509                                             { sequence => "seq" });
510     }
511     else
512     {
513         return $self->{dbh}->last_insert_id("","","","");
514     }
515 }
516
517 sub lookup_id
518 {
519     my($self, $table, $name, $parent)=@_;
520     my $sql="SELECT id FROM $table where name=?";
521     my @args=($name);
522     if($parent)
523     {
524         $sql .= " AND parents_id=?";
525         push(@args, $parent);
526     }
527     my($id)=$self->cmd_onerow($sql, @args);
528     return $id;
529 }
530
531 __DATA__
532
533 CREATE TABLE id3fs (
534     schema_version INTEGER,
535     last_update
536 );
537
538 CREATE TABLE paths (
539     id INTEGER,
540     name text,
541     PRIMARY KEY(id DESC)
542 );
543
544 CREATE TABLE artists (
545     id INTEGER,
546     name text,
547     PRIMARY KEY(id DESC)
548 );
549
550 CREATE TABLE albums (
551     id INTEGER,
552     name text,
553     PRIMARY KEY(id DESC)
554 );
555
556 CREATE TABLE files (
557     id INTEGER,
558     name text,
559     artists_id,
560     albums_id,
561     paths_id,
562     PRIMARY KEY(id DESC),
563     FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
564     FOREIGN KEY(albums_id)  REFERENCES albums(id)  ON DELETE CASCADE ON UPDATE CASCADE,
565     FOREIGN KEY(paths_id)   REFERENCES paths(id)   ON DELETE CASCADE ON UPDATE CASCADE
566 );
567
568 CREATE TABLE tags (
569     id INTEGER,
570     parents_id INTEGER,
571     name text,
572     PRIMARY KEY(id DESC)
573 );
574
575 CREATE TABLE files_x_tags (
576     files_id INTEGER,
577     tags_id INTEGER,
578     FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
579     FOREIGN KEY(tags_id)  REFERENCES tags(id)  ON DELETE CASCADE ON UPDATE CASCADE
580 );
581