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