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