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