more tag fixes
[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     if(defined($parent))
207     {
208         push(@andclauses, "( t2.parents_id=$parent )");
209     }
210     if(@tags)
211     {
212         push(@orclauses, "( t2.parents_id='' AND t2.id NOT IN ( " . join(', ', @tags) ." ) )");
213     }
214     for my $pair (@tags_vals)
215     {
216         my($tag, $val)=@$pair;
217         push(@orclauses, "( NOT (t2.parents_id=$tag AND t2.id=$val ) )");
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, @constraints)=@_;
250     if(!@constraints) # /ALL
251     {
252         my $sql="SELECT DISTINCT name FROM artists;";
253         my $tags=$self->cmd_rows($sql);
254         return(map { $_->[0]; } @$tags);
255     }
256     my @ids=();
257     my $sql=("SELECT artists.name FROM (\n" .
258              $self->tags_subselect(@constraints) .
259              ") AS subselect\n" .
260              "INNER JOIN files ON subselect.files_id=files.id\n" .
261              "INNER JOIN artists ON files.artists_id=artists.id\n" .
262              "GROUP BY artists.name;");
263     print "SQL: $sql\n";
264     my $result=$self->cmd_rows($sql);
265     my @tagnames=map { $_->[0]; } @$result;
266     print "ARTISTS: ", join(', ', @tagnames), "\n";
267     return(@tagnames);
268 }
269
270 sub albums
271 {
272     my($self, @constraints)=@_;
273     my @ids=();
274     # FIXME: rework PathElements
275     if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
276     {
277         return $self->artist_albums($constraints[$#constraints]->{id}, @constraints);
278     }
279     my $sql=("SELECT albums.name\n" .
280              "\tFROM (\n" .
281              $self->tags_subselect(@constraints) .
282              "\t) AS subselect\n" .
283              "INNER JOIN files ON subselect.files_id=files.id\n" .
284              "INNER JOIN albums ON files.albums_id=albums.id\n" .
285              "GROUP BY albums.name;");
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     my($self,@constraints)=@_;
397     my ($tags, $tags_vals, $parent)=$self->constraints_tag_list(@constraints);
398     my @tags=@$tags;
399     my @tags_vals=@$tags_vals;;
400
401     my $sql=("\tSELECT files_x_tags.files_id FROM tags t1\n" .
402              "\tINNER JOIN files_x_tags ON t1.id=files_x_tags.tags_id\n");
403     my @orclauses=();
404     my @andclauses=();
405     if(@tags)
406     {
407         push(@orclauses, "( t1.parents_id='' AND t1.id IN ( " . join(', ', @tags) ." ) )");
408     }
409     for my $pair (@tags_vals)
410     {
411         my($tag, $val)=@$pair;
412         push(@orclauses, "( t1.parents_id=$tag AND t1.id=$val )");
413     }
414     if($parent)
415     {
416         push(@andclauses, "( t1.parents_id=$parent )");
417     }
418     if(@orclauses)
419     {
420         push(@andclauses, join("\n\t\tOR ", @orclauses));
421     }
422     if(@andclauses)
423     {
424         $sql .= "\tWHERE\n\t\t";
425         $sql .= join("\n\t\tAND ", @andclauses) . "\n";
426     }
427     $sql .= "\tGROUP BY files_x_tags.files_id\n";
428     return $sql;
429 }
430
431 sub constraints_tag_list
432 {
433     my($self, @constraints)=@_;
434     my $lasttag=undef;
435     my @tags=();
436     my @tags_vals=();
437     for my $constraint (@constraints)
438     {
439         print ref($constraint), ": ", $constraint->{name}, "\n";
440         if(ref($constraint) eq "ID3FS::PathElement::Tag")
441         {
442             if(defined($lasttag))
443             {
444                 print "TAGVAL\n";
445                 push(@tags_vals, [$lasttag, $constraint->{id}]) if defined($constraint->{id});
446                 $lasttag=undef;
447             }
448             elsif($self->tag_has_values($constraint->{id}))
449             {
450                 print "HASVALUES\n";
451                 $lasttag=$constraint->{id} if defined($constraint->{id});
452             }
453             else
454             {
455                 print "NOVALUES\n";
456                 push(@tags, $constraint->{id}) if(defined($constraint->{id}));
457             }
458         }
459     }
460     unless($self->{postgres})
461     {
462         @tags=map{ "\"$_\""; } @tags;
463         @tags_vals=map( { [ map({ "\"$_\""; } @$_ ) ] } @tags_vals);
464         $lasttag="\"$lasttag\"" if defined($lasttag);
465     }
466     return(\@tags, \@tags_vals, $lasttag);
467 }
468
469
470 sub relativise
471 {
472     my($self, $path, $name, $mountpoint, $id3fs_path)=@_;
473     $id3fs_path=~s/(.*)\/.*/$1/;
474     my $rpath="$self->{absbase}/$path";
475     my $vpath="$mountpoint/$id3fs_path";
476     my @path=split(/\//,$rpath);
477     my @rel=split(/\//,$vpath);
478     #absolute paths have empty first element due to leading /
479     shift(@path) if($path[0] eq "");
480     shift(@rel)  if($rel[0]  eq "");
481     if($path[0] ne $rel[0])
482     {
483         #no path in common, return absolute
484         print "FAIL: NO PATHS IN COMMON\n";
485         return $name;
486     }
487     # f: /home/foo/bar/baz.mp3
488     # r: /home/ianb/music/albums
489     while(@path && @rel && ($path[0] eq $rel[0]))
490     {
491         shift(@path);
492         shift(@rel);
493         print "POP ";
494     }
495     print "\n";
496     my $upcount=scalar(@rel);
497     my $result="../" x $upcount;
498     $result .= join("/",@path);
499     $result .= "/$name";
500     return $result;
501 }
502
503 sub bare_tags
504 {
505     my($self)=@_;
506     my $sql=("SELECT tags.name FROM tags\n" .
507              "WHERE tags.parents_id=''\n" .
508              "GROUP BY tags.name\n");
509     my $result=$self->cmd_rows($sql);
510     my @names=map { $_->[0]; } @$result;
511     return (@names);
512 }
513
514 sub tags_with_values
515 {
516     # FIXME: only shows one level of tag depth
517     my($self)=@_;
518     my $sql=("SELECT p.name, t.name  FROM tags t\n" .
519              "INNER JOIN tags p ON t.parents_id=p.id\n" .
520              "GROUP BY p.name, t.name\n");
521 #    print "SQL: $sql\n";
522     my $result=$self->cmd_rows($sql);
523     my $tags={};
524     for my $pair (@$result)
525     {
526         push(@{$tags->{$pair->[0]}}, $pair->[1]);
527     }
528     return $tags;
529 }
530
531 sub id
532 {
533     my($self, $type, $val)=@_;
534     my $sql="SELECT id FROM $type WHERE name=?";
535     my ($id)=$self->cmd_onerow($sql, $val);
536     return($id);
537 }
538
539 sub add
540 {
541     my($self,$path)=@_;
542     my $relpath=$path;
543     $relpath =~ s/^\Q$self->{base}\E\/?//;
544     my($filepart,$pathpart);
545     if($path !~ /\//)
546     {
547         $pathpart='';
548         $filepart=$relpath;
549     }
550     else
551     {
552         ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
553     }
554     my $file=ID3FS::AudioFile->new($path, $self->{me});
555     return unless(defined($file));
556     my $artist=$file->artist();
557     my $album=$file->album();
558     my $v1genre=$file->v1genre();
559     my $year=$file->year();
560     my $audiotype=$file->audiotype();
561     my @tags=$file->tags();
562     my $haspic=$file->haspic();
563
564     $artist=undef unless($self->ok($artist));
565     print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
566     my $artist_id=$self->add_to_table("artists",  $artist);
567     my $path_id=$self->add_to_table("paths", $pathpart);
568     $album=undef unless($self->ok($album));
569     if($self->{verbose} && !defined($album))
570     {
571         print "$self->{me}: $path: no album tag defined\n";
572     }
573
574     my $albums_id=$self->add_to_table("albums", $album);
575     my $file_id=$self->add_to_table("files", $filepart,
576                                     { "artists_id" => $artist_id,
577                                       "albums_id"  => $albums_id,
578                                       "paths_id"   => $path_id });
579     for my $tag (@tags)
580     {
581         $self->add_tag($file_id, @$tag);
582     }
583
584     if($self->ok($year))
585     {
586         $self->add_tag($file_id, "year", $year);
587         if($year=~/^(\d\d\d)\d$/)
588         {
589             $self->add_tag($file_id, "decade", "${1}0s");
590         }
591     }
592
593     if($self->ok($v1genre))
594     {
595         $self->add_tag($file_id, "v1genre", $v1genre);
596     }
597
598     if($haspic)
599     {
600         $self->add_tag($file_id, "haspic", undef);
601     }
602 }
603
604 sub add_tag
605 {
606     my($self, $file_id, $tag, $value)=@_;
607     my $tag_id=$self->add_to_table("tags",  $tag,
608                                    { "parents_id" => undef });
609     $self->add_relation("files_x_tags",
610                         { "files_id" => $file_id,
611                           "tags_id"  => $tag_id });
612     if(defined($value) && length($value))
613     {
614         my $val_id=$self->add_to_table("tags",  $value,
615                                        { "parents_id" => $tag_id });
616         $self->add_relation("files_x_tags",
617                             { "files_id" => $file_id,
618                               "tags_id"  => $val_id });
619     }
620 }
621
622 sub add_to_table
623 {
624     my($self, $table, $name, $extradata)=@_;
625     my $id=$self->lookup_id($table, $name);
626     unless(defined($id))
627     {
628         my $sql="INSERT INTO $table (";
629         $sql .= "id, " if($self->{postgres});
630         my @fields=qw(name);
631         if(defined($extradata))
632         {
633             push(@fields, sort keys(%$extradata));
634         }
635         $sql .= join(", ", @fields);
636         $sql .=") VALUES (";
637         $sql .=") nextval('seq'), " if($self->{postgres});
638         $sql .= join(", ", map { "?"; } @fields);
639         $sql .= ");";
640         $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
641     }
642     return $id;
643 }
644
645 sub add_relation
646 {
647     my ($self, $relname, $fields)=@_;
648     return if($self->relation_exists($relname, $fields));
649     my $sql="INSERT INTO $relname (";
650     $sql .= join(", ", sort keys(%$fields));
651     $sql .= ") VALUES (";
652     $sql .= join(", ", map { "?"; } sort keys(%$fields));
653     $sql .= ");";
654     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
655 }
656
657 sub lookup_id
658 {
659     my($self, $table, $name)=@_;
660     my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
661     return $id;
662 }
663
664 sub tag_has_values
665 {
666     my($self, $id)=@_;
667     my $sql=("SELECT COUNT(*) FROM tags\n\t" .
668              "WHERE tags.parents_id=?\n");
669     my ($rows)=$self->cmd_onerow($sql, $id);
670     return $rows;
671 }
672
673 sub files_in
674 {
675     my ($self, $dir)=@_;
676     $dir=~s/^$self->{base}\/?//;
677     my $sql=("SELECT files.name FROM files\n" .
678              "INNER JOIN paths ON files.paths_id=paths.id\n" .
679              "WHERE paths.name=?\n");
680     my $files=$self->cmd_rows($sql, $dir);
681     return(map { $_->[0]; } @$files);
682 }
683
684 sub prune_directories
685 {
686     my($self)=@_;
687     my $sql=("SELECT name, id FROM paths ORDER BY name\n");
688     my $pathsref=$self->cmd_rows($sql);
689     my @ids=();
690     for my $pathpair (@$pathsref)
691     {
692         my($path, $id)=@$pathpair;
693         my $fullpath="$self->{absbase}/$path";
694         unless(-d $fullpath)
695         {
696             push(@ids, $id)
697         }
698     }
699     $self->prune_paths(@ids);
700     return scalar(@ids);
701 }
702
703 sub prune_paths
704 {
705     my($self, @ids)=@_;
706     return unless(@ids);
707     my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
708              join(', ', map { "\"$_\""; } @ids). "\n\t)");
709     print "SQL: \n", $sql, "\n";
710     $self->cmd($sql);
711 }
712
713 sub remove_unused
714 {
715     my($self)=@_;
716     my $sql=<<'EOT';
717    DELETE FROM artists WHERE id IN (
718        SELECT artists.id FROM artists
719        LEFT JOIN files ON files.artists_id=artists.id
720        WHERE files.id IS NULL);
721
722    DELETE FROM albums WHERE id IN (
723        SELECT albums.id FROM albums
724        LEFT JOIN files ON files.albums_id=albums.id
725        WHERE files.id IS NULL);
726
727    DELETE FROM paths WHERE id IN (
728        SELECT paths.id FROM paths
729        LEFT JOIN files ON files.paths_id=paths.id
730        WHERE files.id IS NULL);
731
732    DELETE FROM files_x_tags WHERE files_id IN (
733        SELECT files_x_tags.files_id FROM files_x_tags
734        LEFT JOIN files ON files.id=files_x_tags.files_id
735        WHERE files.id IS NULL);
736
737    DELETE FROM tags WHERE id IN (
738        SELECT tags.id FROM tags
739        LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
740        WHERE files_x_tags.files_id IS NULL);
741
742 EOT
743 #    print "SQL: $sql\n";
744     my @sql=split(/\n\n/, $sql);
745     $self->cmd($_) for (@sql);
746 }
747
748 sub relation_exists
749 {
750     my ($self, $relname, $fields)=@_;
751     my $sql="SELECT count(1) FROM $relname WHERE ";
752     my @exprs=();
753     my @vals=();
754     for my $field (keys %$fields)
755     {
756         push(@exprs,$field);
757         push(@vals,$fields->{$field});
758     }
759     $sql .= join(' AND ', map { "$_=?"; } @exprs);
760     my ($ret)=$self->cmd_onerow($sql, @vals);
761     return $ret;
762 }
763
764 sub ok
765 {
766     my($self, $thing)=@_;
767     return(defined($thing) && length($thing) && $thing =~ /\S+/);
768 }
769
770 sub cmd
771 {
772     my ($self, @args)=@_;
773     # don't care about retcode
774     $self->cmd_sth(@args);
775 }
776
777 sub cmd_onerow
778 {
779     my ($self, @args)=@_;
780     my $sth=$self->cmd_sth(@args);
781     return($sth->fetchrow_array());
782 }
783
784 sub cmd_rows
785 {
786     my ($self, @args)=@_;
787     my $sth=$self->cmd_sth(@args);
788     return $sth->fetchall_arrayref();
789 }
790
791 sub cmd_id
792 {
793     my ($self, @args)=@_;
794     $self->cmd_sth(@args);
795     return($self->last_insert_id());
796 }
797
798 sub last_insert_id
799 {
800     my $self=shift;
801     if($self->{postgres})
802     {
803         return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
804                                             { sequence => "seq" });
805     }
806     else
807     {
808         return $self->{dbh}->last_insert_id("","","","");
809     }
810 }
811
812 __DATA__
813
814 CREATE TABLE id3fs (
815     schema_version INTEGER,
816     last_update
817 );
818
819 CREATE TABLE paths (
820     id INTEGER PRIMARY KEY,
821     name text
822 );
823
824 CREATE TABLE artists (
825     id INTEGER PRIMARY KEY,
826     name text
827 );
828
829 CREATE TABLE albums (
830     id INTEGER PRIMARY KEY,
831     name text
832 );
833
834 CREATE TABLE files (
835     id INTEGER PRIMARY KEY,
836     name text,
837     artists_id,
838     albums_id,
839     paths_id,
840     FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
841     FOREIGN KEY(albums_id)  REFERENCES albums(id)  ON DELETE CASCADE ON UPDATE CASCADE,
842     FOREIGN KEY(paths_id)   REFERENCES paths(id)   ON DELETE CASCADE ON UPDATE CASCADE
843 );
844
845 CREATE TABLE tags (
846     id INTEGER PRIMARY KEY,
847     parents_id INTEGER,
848     name text
849 );
850
851 CREATE TABLE files_x_tags (
852     files_id INTEGER,
853     tags_id INTEGER,
854     FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
855     FOREIGN KEY(tags_id)  REFERENCES tags(id)  ON DELETE CASCADE ON UPDATE CASCADE
856 );
857