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