partial (broken) support for tagvals
[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 cmd_sth
168 {
169     my($self, $sql, @params)=@_;
170     my $sth=$self->{dbh}->prepare($sql);
171     my $idx=1;
172     for my $param (@params)
173     {
174         $param="" unless(defined($param));
175         $sth->bind_param($idx++, $param);
176     }
177     $sth->execute();
178     return $sth;
179 }
180
181 sub tags
182 {
183     my($self, $path)=@_;
184     my @constraints=@{$path->{elements}};
185     if(!@constraints) # /
186     {
187         # FIXME: add ALL?
188         my $sql="SELECT DISTINCT name FROM tags WHERE parents_id='';";
189         my $tags=$self->cmd_rows($sql);
190         return(map { $_->[0]; } @$tags);
191     }
192     my @ids=();
193     my $sql=("SELECT tags.name FROM (\n" .
194              $self->tags_subselect($path) .
195              ") AS subselect\n" .
196              "INNER JOIN files_x_tags ON subselect.files_id=files_x_tags.files_id\n" .
197              "INNER JOIN tags ON files_x_tags.tags_id=tags.id\n");
198     my (@allused)=$path->used_tags();
199     my @used=grep { ref($_) ne "ARRAY"; } @allused;
200     my @used_with_vals=grep { ref($_) eq "ARRAY"; } @allused;
201     print "tags(): USED: ", join(", ", @used), "\n";
202     print "tags(): USED_WITH_VALS: ", join(", ", map { "[".$_->[0]. ", ".$_->[1]."]";} @used_with_vals), "\n";
203     my @orclauses=();
204     if($path->tag_has_values())
205     {
206         print "HAS_VALUES\n";
207         my $parent=$path->trailing_tag_id();
208         print "parent: $parent\n";
209         my @values=map { "'".$_->[1]."'"; } grep { $_->[0] == $parent; } @used_with_vals;
210         my $clause="(tags.parents_id='$parent'";
211         if(@values)
212         {
213             $clause .= " AND tags.id NOT IN (" . join(', ', @values) . ")";
214         }
215         $clause .= ")";
216         push(@orclauses, $clause);
217     }
218     else
219     {
220         print "HASNT VALUES\n";;
221         if(@used)
222         {
223             push(@orclauses, "(tags.parents_id='' AND tags.id NOT IN (" . join(', ', @used) . "))");
224         }
225         for my $pair (@used_with_vals)
226         {
227             push(@orclauses, "(tags.parents_id='" . $pair->[0] . "' AND tags.id!='" . $pair->[1] . "')");
228         }
229     }
230     if(@orclauses)
231     {
232         $sql .= "WHERE " . join(' OR ', @orclauses) . "\n";
233     }
234     $sql .= "GROUP BY tags.name;";
235     print "SQL: $sql\n";
236     my $result=$self->cmd_rows($sql);
237     my @tagnames=map { $_->[0]; } @$result;
238     print "SUBNAMES: ", join(', ', @tagnames), "\n";
239     return(@tagnames);
240 }
241
242 sub tag_values
243 {
244     my($self, $tagid)=@_;
245     my $sql=("SELECT DISTINCT name FROM tags\n" .
246              "WHERE parents_id=?");
247     my $tags=$self->cmd_rows($sql, $tagid);
248     my @tags=map { $_->[0]; } @$tags;
249     @tags=map { length($_) ? $_ : "NOVALUE"; } @tags;
250     return @tags;
251 }
252
253 sub artists
254 {
255     my($self, $path)=@_;
256     my @constraints=@{$path->{elements}};
257     if(!@constraints) # /ALL
258     {
259         my $sql="SELECT DISTINCT name FROM artists;";
260         my $tags=$self->cmd_rows($sql);
261         return(map { $_->[0]; } @$tags);
262     }
263     my @ids=();
264     my $sql=("SELECT artists.name FROM (\n" .
265              $self->tags_subselect($path) .
266              ") AS subselect\n" .
267              "INNER JOIN files ON subselect.files_id=files.id\n" .
268              "INNER JOIN artists ON files.artists_id=artists.id\n" .
269              "GROUP BY artists.name;");
270     print "SQL: $sql\n";
271     my $result=$self->cmd_rows($sql);
272     my @tagnames=map { $_->[0]; } @$result;
273     print "ARTISTS: ", join(', ', @tagnames), "\n";
274     return(@tagnames);
275 }
276
277 sub albums
278 {
279     my($self, $path)=@_;
280     my @constraints=@{$path->{elements}};
281     my @ids=();
282     # FIXME: rework PathElements
283     if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
284     {
285         return $self->artist_albums($constraints[$#constraints]->{id}, $path);
286     }
287     my $sql=("SELECT albums.name\n" .
288              "\tFROM (\n" .
289              $self->tags_subselect($path) .
290              "\t) AS subselect\n" .
291              "INNER JOIN files ON subselect.files_id=files.id\n" .
292              "INNER JOIN albums ON files.albums_id=albums.id\n" .
293              "GROUP BY albums.name;");
294     print "SQL(ALBUMS): \n$sql\n";
295     my $result=$self->cmd_rows($sql);
296     my @names=map { $_->[0]; } @$result;
297     print "ALBUMS: ", join(', ', @names), "\n";
298     return(@names);
299 }
300
301 sub artist_albums
302 {
303     my($self, $artist_id, $path)=@_;
304     my @constraints=@{$path->{elements}};
305     my $sql=("SELECT albums.name FROM (\n" .
306              $self->tags_subselect($path) .
307              "\t) AS subselect\n" .
308              "INNER JOIN files ON subselect.files_id=files.id\n" .
309              "INNER JOIN albums ON albums.id=files.albums_id\n\t" .
310              "INNER JOIN artists ON artists.id=files.artists_id\n\t" .
311              "WHERE artists.id=? and albums.name <> ''\n\t" .
312              "GROUP BY albums.name\n");
313     print "ARTIST_ALBUMS SQL: $sql\n";
314     my $result=$self->cmd_rows($sql, $artist_id);
315     my @albums=map { $_->[0]; } @$result;
316     print "ALBUMS: ", join(', ', @albums), "\n";
317     return(@albums);
318 }
319
320 sub artist_tracks
321 {
322     my($self, $artist_id, $path)=@_;
323     my @constraints=@{$path->{elements}};
324     my $sql=("SELECT files.name FROM (\n" .
325              $self->tags_subselect($path) .
326              "\t) AS subselect\n" .
327              "INNER JOIN files ON subselect.files_id=files.id\n" .
328              "INNER JOIN artists ON artists.id=files.artists_id\n\t" .
329              "INNER JOIN albums  ON albums.id=files.albums_id\n\t" .
330              "WHERE artists.id=? AND albums.name=''\n\t" .
331              "GROUP BY files.name\n");
332     print "ARTIST_TRACKS SQL: $sql\n";
333     my $result=$self->cmd_rows($sql, $artist_id);
334     my @names=map { $_->[0]; } @$result;
335     print "ARTISTTRACKS: ", join(', ', @names), "\n";
336     return(@names);
337 }
338
339 sub album_tracks
340 {
341     my($self, $artist_id, $album_id)=@_;
342     my $sql=("SELECT files.name FROM files\n\t" .
343              "INNER JOIN albums  ON albums.id=files.albums_id\n\t" .
344              "INNER JOIN artists ON artists.id=files.artists_id\n\t" .
345              "WHERE artists.id=? AND albums.id=?\n\t" .
346              "GROUP BY files.name\n");
347     print "ALBUM_TRACKS SQL($artist_id, $album_id): $sql\n";
348     my $result=$self->cmd_rows($sql, $artist_id, $album_id);
349     my @names=map { $_->[0]; } @$result;
350     print "TRACKS: ", join(', ', @names), "\n";
351     return(@names);
352 }
353
354 sub tracks
355 {
356     my($self, $path)=@_;
357     my @constraints=@{$path->{elements}};
358     # FIXME: rework PathElements
359     if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
360     {
361         return $self->artist_tracks($constraints[$#constraints]->{id}, @constraints);
362     }
363     elsif(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Album")
364     {
365         my $artist_id=0;
366         my $artist=$constraints[($#constraints)-1];
367         if(defined($artist) && (ref($artist) eq "ID3FS::PathElement::Artist"))
368         {
369             # should always happen
370             $artist_id=$artist->{id};
371         }
372         return $self->album_tracks($artist_id, $constraints[$#constraints]->{id});
373     }
374
375     my $sql=("SELECT files.name\n" .
376              "\tFROM (\n" .
377              $self->tags_subselect($path) .
378              "\t) AS subselect\n" .
379              "INNER JOIN files ON files.id=subselect.files_id\n" .
380              "GROUP BY files.name;");
381     print "SQL: $sql\n";
382     my $result=$self->cmd_rows($sql);
383     my @names=map { $_->[0]; } @$result;
384     print "TRACKS: ", join(', ', @names), "\n";
385     return(@names);
386 }
387
388 sub filename
389 {
390     my($self, $mountpoint, $path)=@_;
391     my @constraints=@{$path->{elements}};
392     if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::File")
393     {
394         my $id=$constraints[$#constraints]->{id};
395         my $sql=("SELECT paths.name, files.name FROM files\n" .
396                  "INNER JOIN paths ON files.paths_id=paths.id\n" .
397                  "WHERE files.id=?\n" .
398                  "GROUP BY paths.name, files.name");
399         print "FILENAME SQL: $sql\n";
400         my ($path, $name)=$self->cmd_onerow($sql, $id);
401         my $id3fs_path=join('/', map { $_->{name}; }  @constraints);
402         return($self->relativise($path, $name, $mountpoint, $id3fs_path));
403     }
404     die("DB::filename: unhandled case\n"); #FIXME
405 }
406
407 sub tags_subselect
408 {
409     my($self, $path)=@_;
410     my $tree=$path->{tagtree};
411     my $tag=undef;
412     if($path->tag_has_values())
413     {
414         $tag=$path->trailing_tag_id();
415         print "Trailing id: $tag\n";
416     }
417     my ($sqlclause, $joinsneeded)=$tree->to_sql($tag);
418     print "SQL($joinsneeded): $sqlclause\n";
419     my $sql="\tSELECT fxt1.files_id FROM tags t1";
420     my @crosses=();
421     my @inners=();
422 #    $joinsneeded++ if($tag);
423     for(my $i=1; $i <= $joinsneeded; $i++)
424     {
425         if($i > 1)
426         {
427             push(@crosses, "CROSS JOIN tags t$i");
428         }
429         my $inner=("\tINNER JOIN files_x_tags fxt$i ON " .
430                    "t${i}.id=fxt${i}.tags_id");
431         if($i>2)
432         {
433             $inner .= " AND fxt1.files_id=fxt${i}.files_id";
434         }
435         push(@inners, $inner);
436     }
437     $sql .= ("\n\t" . join(" ", @crosses)) if(@crosses);
438     $sql .= ("\n" . join("\n", @inners)) if(@inners);
439     $sql .= "\n\tWHERE $sqlclause";
440 #    if($tag)
441 #    {
442 #       $sql .= " AND t${joinsneeded}.parents_id='$tag'";
443 #    }
444     $sql .= "\n\tGROUP BY fxt1.files_id\n";
445     return $sql;
446 }
447
448 sub tags_subselect_and_not
449 {
450     my($self,@constraints)=@_;
451     my ($tags, $tags_vals, $parent)=$self->constraints_tag_list(@constraints);
452     my @tags=@$tags;
453     my @tags_vals=@$tags_vals;;
454     my $cnt=1;
455     my @andclauses=();
456     my $sql='';
457     for my $tag (@tags)
458     {
459         if($cnt == 1)
460         {
461             $sql="\tSELECT fxt" . scalar(@tags) . ".files_id FROM files_x_tags fxt1\n";
462             push(@andclauses, "\t\tfxt${cnt}.tags_id=$tag");
463         }
464         else
465         {
466             $sql .= ("\tLEFT JOIN files_x_tags fxt$cnt ON fxt" .
467                  ($cnt-1) . ".files_id=fxt${cnt}.files_id\n");
468             push(@andclauses, "\t\tfxt${cnt}.tags_id IS NULL");
469         }
470         print "AND: @andclauses\n";
471         $cnt++;
472     }
473     if(@andclauses)
474     {
475         $sql .= "\tWHERE\n\t\t";
476         $sql .= join(" AND\n\t\t", @andclauses) . "\n";
477     }
478     $sql .= "\tGROUP BY fxt". scalar(@tags).".files_id\n";
479     return $sql;
480 }
481
482
483 sub tags_subselect_and
484 {
485     my($self,@constraints)=@_;
486     my ($tags, $tags_vals, $parent)=$self->constraints_tag_list(@constraints);
487     my @tags=@$tags;
488     my @tags_vals=@$tags_vals;;
489     my $cnt=1;
490     my @andclauses=();
491     my $sql='';
492     for my $tag (@tags)
493     {
494         if($cnt == 1)
495         {
496             $sql="\tSELECT fxt" . scalar(@tags) . ".files_id FROM files_x_tags fxt1\n";
497         }
498         else
499         {
500             $sql .= ("\tINNER JOIN files_x_tags fxt$cnt ON fxt" .
501                  ($cnt-1) . ".files_id=fxt${cnt}.files_id\n");
502         }
503         push(@andclauses, "\t\tfxt${cnt}.tags_id = $tag");
504         print "AND: @andclauses\n";
505         $cnt++;
506     }
507     if(@andclauses)
508     {
509         $sql .= "\tWHERE\n\t\t";
510         $sql .= join(" AND\n\t\t", @andclauses) . "\n";
511     }
512     $sql .= "\tGROUP BY fxt". scalar(@tags).".files_id\n";
513     return $sql;
514 }
515
516 sub tags_subselect_or
517 {
518     my($self,@constraints)=@_;
519     my ($tags, $tags_vals, $parent)=$self->constraints_tag_list(@constraints);
520     my @tags=@$tags;
521     my @tags_vals=@$tags_vals;;
522
523     my $sql=("\tSELECT files_x_tags.files_id FROM tags t1\n" .
524              "\tINNER JOIN files_x_tags ON t1.id=files_x_tags.tags_id\n");
525     my @orclauses=();
526     my @andclauses=();
527     # FIXME: and / or?
528     if(@tags)
529     {
530         push(@andclauses, "( t1.parents_id=" . (defined($parent) ? $parent : "''") . " )");
531         push(@andclauses, "( t1.id IN ( " . join(', ', @tags) ." ) )");
532     }
533     for my $pair (@tags_vals)
534     {
535         my($tag, $val)=@$pair;
536         push(@orclauses, "( t1.parents_id=$tag AND t1.id=$val )");
537     }
538 #    push(@andclauses, "( t1.parents_id=" . (defined($parent) ? $parent : "''") . " )");
539     if(@orclauses)
540     {
541         push(@andclauses, join("\n\t\tOR ", @orclauses));
542     }
543     if(@andclauses)
544     {
545         $sql .= "\tWHERE\n\t\t";
546         $sql .= join("\n\t\tAND ", @andclauses) . "\n";
547     }
548     $sql .= "\tGROUP BY files_x_tags.files_id\n";
549     return $sql;
550 }
551
552 sub constraints_tag_list
553 {
554     my($self, @constraints)=@_;
555     my $lasttag=undef;
556     my @tags=();
557     my @tags_vals=();
558     for my $constraint (@constraints)
559     {
560 #       print ref($constraint), ": ", $constraint->{name}, "\n";
561         if(ref($constraint) eq "ID3FS::PathElement::Tag")
562         {
563             if(defined($lasttag))
564             {
565 #               print "TAGVAL\n";
566                 push(@tags_vals, [$lasttag, $constraint->{id}]) if defined($constraint->{id});
567                 $lasttag=undef;
568             }
569             elsif($self->tag_has_values($constraint->{id}))
570             {
571 #               print "HASVALUES\n";
572                 $lasttag=$constraint->{id} if defined($constraint->{id});
573             }
574             else
575             {
576 #               print "NOVALUES\n";
577                 push(@tags, $constraint->{id}) if(defined($constraint->{id}));
578             }
579         }
580     }
581     unless($self->{postgres})
582     {
583         @tags=map{ "\"$_\""; } @tags;
584         @tags_vals=map( { [ map({ "\"$_\""; } @$_ ) ] } @tags_vals);
585         $lasttag="\"$lasttag\"" if defined($lasttag);
586     }
587     return(\@tags, \@tags_vals, $lasttag);
588 }
589
590
591 sub relativise
592 {
593     my($self, $path, $name, $mountpoint, $id3fs_path)=@_;
594     $id3fs_path=~s/(.*)\/.*/$1/;
595     my $rpath="$self->{absbase}/$path";
596     my $vpath="$mountpoint/$id3fs_path";
597     my @path=split(/\//,$rpath);
598     my @rel=split(/\//,$vpath);
599     #absolute paths have empty first element due to leading /
600     shift(@path) if($path[0] eq "");
601     shift(@rel)  if($rel[0]  eq "");
602     if($path[0] ne $rel[0])
603     {
604         #no path in common, return absolute
605         print "FAIL: NO PATHS IN COMMON\n";
606         return $name;
607     }
608     # f: /home/foo/bar/baz.mp3
609     # r: /home/ianb/music/albums
610     while(@path && @rel && ($path[0] eq $rel[0]))
611     {
612         shift(@path);
613         shift(@rel);
614 #       print "POP ";
615     }
616 #    print "\n";
617     my $upcount=scalar(@rel);
618     my $result="../" x $upcount;
619     $result .= join("/",@path);
620     $result .= "/$name";
621     return $result;
622 }
623
624 sub bare_tags
625 {
626     my($self)=@_;
627     my $sql=("SELECT tags.name FROM tags\n" .
628              "WHERE tags.parents_id=''\n" .
629              "GROUP BY tags.name\n");
630     my $result=$self->cmd_rows($sql);
631     my @names=map { $_->[0]; } @$result;
632     return (@names);
633 }
634
635 sub tags_with_values
636 {
637     # FIXME: only shows one level of tag depth
638     my($self)=@_;
639     my $sql=("SELECT p.name, t.name  FROM tags t\n" .
640              "INNER JOIN tags p ON t.parents_id=p.id\n" .
641              "GROUP BY p.name, t.name\n");
642     print "SQL: $sql\n";
643     my $result=$self->cmd_rows($sql);
644     my $tags={};
645     for my $pair (@$result)
646     {
647         push(@{$tags->{$pair->[0]}}, $pair->[1]);
648     }
649     return $tags;
650 }
651
652 sub id
653 {
654     my($self, $type, $val)=@_;
655     my $sql="SELECT id FROM $type WHERE name=?";
656     my ($id)=$self->cmd_onerow($sql, $val);
657     return($id);
658 }
659
660 sub add
661 {
662     my($self,$path)=@_;
663     my $relpath=$path;
664     $relpath =~ s/^\Q$self->{base}\E\/?//;
665     my($filepart,$pathpart);
666     if($relpath !~ /\//)
667     {
668         $pathpart='';
669         $filepart=$relpath;
670     }
671     else
672     {
673         ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
674     }
675     my $file=ID3FS::AudioFile->new($path, $self->{me});
676     return unless(defined($file));
677     my $artist=$file->artist();
678     my $album=$file->album();
679     my $v1genre=$file->v1genre();
680     my $year=$file->year();
681     my $audiotype=$file->audiotype();
682     my @tags=$file->tags();
683     my $haspic=$file->haspic();
684
685     $artist=undef unless($self->ok($artist));
686     print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
687     my $artist_id=$self->add_to_table("artists",  $artist);
688     my $path_id=$self->add_to_table("paths", $pathpart);
689     $album=undef unless($self->ok($album));
690     if($self->{verbose} && !defined($album))
691     {
692         print "$self->{me}: $path: no album tag defined\n";
693     }
694
695     my $albums_id=$self->add_to_table("albums", $album);
696     my $file_id=$self->add_to_table("files", $filepart,
697                                     { "artists_id" => $artist_id,
698                                       "albums_id"  => $albums_id,
699                                       "paths_id"   => $path_id });
700     for my $tag (@tags)
701     {
702         $self->add_tag($file_id, @$tag);
703     }
704
705     if($self->ok($year))
706     {
707         $self->add_tag($file_id, "year", $year);
708         if($year=~/^(\d\d\d)\d$/)
709         {
710             $self->add_tag($file_id, "decade", "${1}0s");
711         }
712     }
713
714     if($self->ok($v1genre))
715     {
716         $self->add_tag($file_id, "v1genre", $v1genre);
717     }
718
719     if($haspic)
720     {
721         $self->add_tag($file_id, "haspic", undef);
722     }
723 }
724
725 sub add_tag
726 {
727     my($self, $file_id, $tag, $value)=@_;
728     my $tag_id=$self->add_to_table("tags",  $tag,
729                                    { "parents_id" => undef });
730     $self->add_relation("files_x_tags",
731                         { "files_id" => $file_id,
732                           "tags_id"  => $tag_id });
733     if(defined($value) && length($value))
734     {
735         my $val_id=$self->add_to_table("tags",  $value,
736                                        { "parents_id" => $tag_id });
737         $self->add_relation("files_x_tags",
738                             { "files_id" => $file_id,
739                               "tags_id"  => $val_id });
740     }
741 }
742
743 sub add_to_table
744 {
745     my($self, $table, $name, $extradata)=@_;
746     my $id=$self->lookup_id($table, $name);
747     unless(defined($id))
748     {
749         my $sql="INSERT INTO $table (";
750         $sql .= "id, " if($self->{postgres});
751         my @fields=qw(name);
752         if(defined($extradata))
753         {
754             push(@fields, sort keys(%$extradata));
755         }
756         $sql .= join(", ", @fields);
757         $sql .=") VALUES (";
758         $sql .=") nextval('seq'), " if($self->{postgres});
759         $sql .= join(", ", map { "?"; } @fields);
760         $sql .= ");";
761         $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
762     }
763     return $id;
764 }
765
766 sub add_relation
767 {
768     my ($self, $relname, $fields)=@_;
769     return if($self->relation_exists($relname, $fields));
770     my $sql="INSERT INTO $relname (";
771     $sql .= join(", ", sort keys(%$fields));
772     $sql .= ") VALUES (";
773     $sql .= join(", ", map { "?"; } sort keys(%$fields));
774     $sql .= ");";
775     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
776 }
777
778 sub lookup_id
779 {
780     my($self, $table, $name)=@_;
781     my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
782     return $id;
783 }
784
785 sub tag_has_values
786 {
787     my($self, $id)=@_;
788     my $sql=("SELECT COUNT(*) FROM tags\n\t" .
789              "WHERE tags.parents_id=?\n");
790     my ($rows)=$self->cmd_onerow($sql, $id);
791     return $rows;
792 }
793
794 sub files_in
795 {
796     my ($self, $dir)=@_;
797     $dir=~s/^$self->{base}\/?//;
798     my $sql=("SELECT files.name FROM files\n" .
799              "INNER JOIN paths ON files.paths_id=paths.id\n" .
800              "WHERE paths.name=?\n");
801     my $files=$self->cmd_rows($sql, $dir);
802     return(map { $_->[0]; } @$files);
803 }
804
805 sub prune_directories
806 {
807     my($self)=@_;
808     my $sql=("SELECT name, id FROM paths ORDER BY name\n");
809     my $pathsref=$self->cmd_rows($sql);
810     my @ids=();
811     for my $pathpair (@$pathsref)
812     {
813         my($path, $id)=@$pathpair;
814         my $fullpath="$self->{absbase}/$path";
815         unless(-d $fullpath)
816         {
817             push(@ids, $id)
818         }
819     }
820     $self->prune_paths(@ids);
821     return scalar(@ids);
822 }
823
824 sub prune_paths
825 {
826     my($self, @ids)=@_;
827     return unless(@ids);
828     my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
829              join(', ', map { "\"$_\""; } @ids). "\n\t)");
830     print "SQL: \n", $sql, "\n";
831     $self->cmd($sql);
832 }
833
834 sub remove_unused
835 {
836     my($self)=@_;
837     my $sql=<<'EOT';
838    DELETE FROM artists WHERE id IN (
839        SELECT artists.id FROM artists
840        LEFT JOIN files ON files.artists_id=artists.id
841        WHERE files.id IS NULL);
842
843    DELETE FROM albums WHERE id IN (
844        SELECT albums.id FROM albums
845        LEFT JOIN files ON files.albums_id=albums.id
846        WHERE files.id IS NULL);
847
848    DELETE FROM paths WHERE id IN (
849        SELECT paths.id FROM paths
850        LEFT JOIN files ON files.paths_id=paths.id
851        WHERE files.id IS NULL);
852
853    DELETE FROM files_x_tags WHERE files_id IN (
854        SELECT files_x_tags.files_id FROM files_x_tags
855        LEFT JOIN files ON files.id=files_x_tags.files_id
856        WHERE files.id IS NULL);
857
858    DELETE FROM tags WHERE id IN (
859        SELECT tags.id FROM tags
860        LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
861        WHERE files_x_tags.files_id IS NULL);
862
863     VACUUM
864 EOT
865     print "SQL: $sql\n";
866     my @sql=split(/\n\n/, $sql);
867     $self->cmd($_) for (@sql);
868 }
869
870 sub relation_exists
871 {
872     my ($self, $relname, $fields)=@_;
873     my $sql="SELECT count(1) FROM $relname WHERE ";
874     my @exprs=();
875     my @vals=();
876     for my $field (keys %$fields)
877     {
878         push(@exprs,$field);
879         push(@vals,$fields->{$field});
880     }
881     $sql .= join(' AND ', map { "$_=?"; } @exprs);
882     my ($ret)=$self->cmd_onerow($sql, @vals);
883     return $ret;
884 }
885
886 sub ok
887 {
888     my($self, $thing)=@_;
889     return(defined($thing) && length($thing) && $thing =~ /\S+/);
890 }
891
892 sub cmd
893 {
894     my ($self, @args)=@_;
895     # don't care about retcode
896     $self->cmd_sth(@args);
897 }
898
899 sub cmd_onerow
900 {
901     my ($self, @args)=@_;
902     my $sth=$self->cmd_sth(@args);
903     return($sth->fetchrow_array());
904 }
905
906 sub cmd_rows
907 {
908     my ($self, @args)=@_;
909     my $sth=$self->cmd_sth(@args);
910     return $sth->fetchall_arrayref();
911 }
912
913 sub cmd_id
914 {
915     my ($self, @args)=@_;
916     $self->cmd_sth(@args);
917     return($self->last_insert_id());
918 }
919
920 sub last_insert_id
921 {
922     my $self=shift;
923     if($self->{postgres})
924     {
925         return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
926                                             { sequence => "seq" });
927     }
928     else
929     {
930         return $self->{dbh}->last_insert_id("","","","");
931     }
932 }
933
934 __DATA__
935
936 CREATE TABLE id3fs (
937     schema_version INTEGER,
938     last_update
939 );
940
941 CREATE TABLE paths (
942     id INTEGER PRIMARY KEY,
943     name text
944 );
945
946 CREATE TABLE artists (
947     id INTEGER PRIMARY KEY,
948     name text
949 );
950
951 CREATE TABLE albums (
952     id INTEGER PRIMARY KEY,
953     name text
954 );
955
956 CREATE TABLE files (
957     id INTEGER PRIMARY KEY,
958     name text,
959     artists_id,
960     albums_id,
961     paths_id,
962     FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
963     FOREIGN KEY(albums_id)  REFERENCES albums(id)  ON DELETE CASCADE ON UPDATE CASCADE,
964     FOREIGN KEY(paths_id)   REFERENCES paths(id)   ON DELETE CASCADE ON UPDATE CASCADE
965 );
966
967 CREATE TABLE tags (
968     id INTEGER PRIMARY KEY,
969     parents_id INTEGER,
970     name text
971 );
972
973 CREATE TABLE files_x_tags (
974     files_id INTEGER,
975     tags_id INTEGER,
976     FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
977     FOREIGN KEY(tags_id)  REFERENCES tags(id)  ON DELETE CASCADE ON UPDATE CASCADE
978 );
979