sort_elements: ignore everything except tags and booleans
[id3fs.git] / lib / ID3FS / DB.pm
1 package ID3FS::DB;
2
3 use strict;
4 use warnings;
5 use DBI;
6 use ID3FS::AudioFile;
7 use Cwd;
8
9 our $SCHEMA_VERSION=1;
10 my $dbfile=".id3fs";
11
12 sub new
13 {
14     my $proto=shift;
15     my $class=ref($proto) || $proto;
16     my $self={};
17     bless($self,$class);
18
19     $self->{me}=shift;
20     $self->{verbose}=shift;
21     my $init=shift;
22     my $dbpath=shift;
23     $self->{base}=shift;
24     my $fallbackdir=shift;
25
26     $dbpath=$self->find_db($init, $dbpath, $fallbackdir);
27     return undef unless($dbpath);
28     $self->{absbase}=Cwd::abs_path($self->{base});
29
30     my $connectstr="dbi:SQLite:dbname=$dbpath";
31     my ($user, $pass)=("", "");
32     if($self->{postgres})
33     {
34         $connectstr="dbi:Pg:dbname=id3fs";
35         $user="ianb";
36         $pass="foo";
37     }
38     my $exists=-f $dbpath;
39     $self->{dbh}=DBI->connect($connectstr, $user, $pass,
40                               { AutoCommit=>1 } );
41     unless(defined($self->{dbh}))
42     {
43         die("$self->{me}: DB Error: " . $DBI::errstr . "\n");
44     }
45
46     if($exists)
47     {
48         $self->checkschema();
49     }
50     else
51     {
52         $self->create();
53     }
54     $self->enable_foreign_keys();
55     return $self;
56 }
57
58 sub find_db
59 {
60     my($self, $init, $dbpath, $fallbackdir)=@_;
61     my $file=undef;
62     my $base=undef;
63     if(defined($dbpath))
64     {
65         $file=$dbpath;
66     }
67     if(defined ($self->{base}))
68     {
69         $file="$self->{base}/$dbfile" unless defined($file);
70         $base=$self->{base};
71     }
72     elsif(defined($fallbackdir) && -d $fallbackdir)
73     {
74         my $path=Cwd::abs_path($fallbackdir);
75         do
76         {
77             $file="$path/$dbfile";
78             $base=$path;
79             $path=~s/(.*)\/.*/$1/;
80         }
81         while(! -f $file && length($path) && -d $path);
82         if(! -f $file)
83         {
84             $file="$fallbackdir/$dbfile";
85             $base=$fallbackdir;
86         }
87     }
88     if(!-f $file && !$init)
89     {
90         print "$self->{me}: db not found at $file\n";
91         return undef;
92     }
93     $self->{base}=$base;
94     return $file;
95 }
96
97 sub base_dir { return shift->{base}; }
98
99 sub create
100 {
101     my($self,$name)=@_;
102     my @schema=split(/\n\n/,join("", <DATA>));
103     close(DATA);
104     for my $cmd (@schema)
105     {
106         $self->{dbh}->do($cmd);
107     }
108     if($self->{postgres})
109     {
110         $self->cmd("CREATE SEQUENCE seq");
111     }
112     else
113     {
114         my %indexes=( "idx_files_id"  => "files (id)",
115                       "idx_fxt_both"  => "files_x_tags (files_id, tags_id)",
116                       "idx_fxt_files" => "files_x_tags (files_id)",
117                       "idx_fxt_tags"  => "files_x_tags (tags_id)",
118                       "idx_tags_id"   => "tags (id)",
119                       "idx_tags_name" => "tags (name)");
120         for my $index (keys %indexes)
121         {
122             $self->{dbh}->do("CREATE INDEX $index ON " . $indexes{$index});
123         }
124     }
125     $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
126                $SCHEMA_VERSION, time());
127 }
128
129 sub checkschema
130 {
131     my $self=shift;
132     my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
133     if(!defined($version) || $version != $SCHEMA_VERSION)
134     {
135         die("$self->{me}: id3fs database version " .
136             defined($version) ? $version : '""' .
137             "not known, current version is $SCHEMA_VERSION.\n");
138     }
139 }
140
141 sub analyze
142 {
143     my $self=shift;
144     $self->cmd("ANALYZE");
145 }
146
147 sub enable_foreign_keys
148 {
149     my $self=shift;
150     $self->cmd("PRAGMA foreign_keys = ON");
151 }
152
153 sub last_update
154 {
155     my($self, $newval)=@_;
156     if(defined($newval))
157     {
158         $self->cmd("UPDATE id3fs SET last_update=?", $newval);
159     }
160     else
161     {
162         ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
163     }
164     return $newval;
165 }
166
167 sub cmd_sth
168 {
169     my($self, $sql, @params)=@_;
170     my $sth=$self->{dbh}->prepare($sql);
171     my $idx=1;
172     for my $param (@params)
173     {
174         $param="" unless(defined($param));
175         $sth->bind_param($idx++, $param);
176     }
177     $sth->execute();
178     return $sth;
179 }
180
181 sub tags
182 {
183     my($self, @constraints)=@_;
184     if(!@constraints) # /
185     {
186         # FIXME: add ALL?
187         my $sql="SELECT DISTINCT name FROM tags WHERE parents_id='';";
188         my $tags=$self->cmd_rows($sql);
189         return(map { $_->[0]; } @$tags);
190     }
191     my @ids=();
192
193     my $sql=("SELECT t2.name FROM (\n" .
194              $self->tags_subselect(@constraints) .
195              ") AS subselect\n" .
196              "INNER JOIN files_x_tags ON subselect.files_id=files_x_tags.files_id\n" .
197              "INNER JOIN tags t2 ON files_x_tags.tags_id=t2.id\n");
198     my ($tags, $tags_vals, $parent)=$self->constraints_tag_list(@constraints);
199     my @tags=@$tags;
200     my @tags_vals=@$tags_vals;;
201     my @orclauses=();
202     my @andclauses=();
203     use Data::Dumper;
204 #    print "TAGS: ", Dumper \@tags;
205 #    print "VALS: ", Dumper \@tags_vals;
206
207     push(@andclauses, "( t2.parents_id=" . (defined($parent) ? $parent : "''") . " )");
208     if(@tags)
209     {
210         push(@orclauses, "( t2.id NOT IN ( " . join(', ', @tags) ." ) )");
211     }
212     for my $pair (@tags_vals)
213     {
214         my($tag, $val)=@$pair;
215 #       push(@orclauses, "( NOT ( t2.parents_id=$tag AND t2.id=$val ) )");
216         push(@andclauses, "( NOT ( t2.id=$tag ) )");
217     }
218     if(@orclauses)
219     {
220         push(@andclauses, join("\n\tOR ", @orclauses));
221     }
222     if(@andclauses)
223     {
224         $sql .= "\tWHERE\n\t\t";
225         $sql .= join("\n\tAND ", @andclauses) . "\n";
226     }
227     $sql .= "GROUP BY t2.name;";
228     print "SQL: $sql\n";
229     my $result=$self->cmd_rows($sql);
230     my @tagnames=map { $_->[0]; } @$result;
231     print "SUBNAMES: ", join(', ', @tagnames), "\n";
232     return(@tagnames);
233 }
234
235 sub tag_values
236 {
237     my($self, $tagid)=@_;
238     my $sql=("SELECT DISTINCT name FROM tags\n" .
239              "WHERE parents_id=?");
240     my $tags=$self->cmd_rows($sql, $tagid);
241     my @tags=map { $_->[0]; } @$tags;
242     @tags=map { length($_) ? $_ : "NOVALUE"; } @tags;
243     return @tags;
244 }
245
246 sub artists
247 {
248     my($self, @constraints)=@_;
249     if(!@constraints) # /ALL
250     {
251         my $sql="SELECT DISTINCT name FROM artists;";
252         my $tags=$self->cmd_rows($sql);
253         return(map { $_->[0]; } @$tags);
254     }
255     my @ids=();
256     my $sql=("SELECT artists.name FROM (\n" .
257              $self->tags_subselect(@constraints) .
258              ") AS subselect\n" .
259              "INNER JOIN files ON subselect.files_id=files.id\n" .
260              "INNER JOIN artists ON files.artists_id=artists.id\n" .
261              "GROUP BY artists.name;");
262     print "SQL: $sql\n";
263     my $result=$self->cmd_rows($sql);
264     my @tagnames=map { $_->[0]; } @$result;
265     print "ARTISTS: ", join(', ', @tagnames), "\n";
266     return(@tagnames);
267 }
268
269 sub albums
270 {
271     my($self, @constraints)=@_;
272     my @ids=();
273     # FIXME: rework PathElements
274     if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
275     {
276         return $self->artist_albums($constraints[$#constraints]->{id}, @constraints);
277     }
278     my $sql=("SELECT albums.name\n" .
279              "\tFROM (\n" .
280              $self->tags_subselect(@constraints) .
281              "\t) AS subselect\n" .
282              "INNER JOIN files ON subselect.files_id=files.id\n" .
283              "INNER JOIN albums ON files.albums_id=albums.id\n" .
284              "GROUP BY albums.name;");
285     print "SQL(ALBUMS): \n$sql\n";
286     my $result=$self->cmd_rows($sql);
287     my @names=map { $_->[0]; } @$result;
288     print "ALBUMS: ", join(', ', @names), "\n";
289     return(@names);
290 }
291
292 sub artist_albums
293 {
294     my($self, $artist_id, @constraints)=@_;
295     my $sql=("SELECT albums.name FROM (\n" .
296              $self->tags_subselect(@constraints) .
297              "\t) AS subselect\n" .
298              "INNER JOIN files ON subselect.files_id=files.id\n" .
299              "INNER JOIN albums ON albums.id=files.albums_id\n\t" .
300              "INNER JOIN artists ON artists.id=files.artists_id\n\t" .
301              "WHERE artists.id=? and albums.name <> ''\n\t" .
302              "GROUP BY albums.name\n");
303     print "ARTIST_ALBUMS SQL: $sql\n";
304     my $result=$self->cmd_rows($sql, $artist_id);
305     my @albums=map { $_->[0]; } @$result;
306     print "ALBUMS: ", join(', ', @albums), "\n";
307     return(@albums);
308 }
309
310 sub artist_tracks
311 {
312     my($self, $artist_id, @constraints)=@_;
313     my $sql=("SELECT files.name FROM (\n" .
314              $self->tags_subselect(@constraints) .
315              "\t) AS subselect\n" .
316              "INNER JOIN files ON subselect.files_id=files.id\n" .
317              "INNER JOIN artists ON artists.id=files.artists_id\n\t" .
318              "INNER JOIN albums  ON albums.id=files.albums_id\n\t" .
319              "WHERE artists.id=? AND albums.name=''\n\t" .
320              "GROUP BY files.name\n");
321     print "ARTIST_TRACKS SQL: $sql\n";
322     my $result=$self->cmd_rows($sql, $artist_id);
323     my @names=map { $_->[0]; } @$result;
324     print "ARTISTTRACKS: ", join(', ', @names), "\n";
325     return(@names);
326 }
327
328 sub album_tracks
329 {
330     my($self, $artist_id, $album_id)=@_;
331     my $sql=("SELECT files.name FROM files\n\t" .
332              "INNER JOIN albums  ON albums.id=files.albums_id\n\t" .
333              "INNER JOIN artists ON artists.id=files.artists_id\n\t" .
334              "WHERE artists.id=? AND albums.id=?\n\t" .
335              "GROUP BY files.name\n");
336     print "ALBUM_TRACKS SQL($artist_id, $album_id): $sql\n";
337     my $result=$self->cmd_rows($sql, $artist_id, $album_id);
338     my @names=map { $_->[0]; } @$result;
339     print "TRACKS: ", join(', ', @names), "\n";
340     return(@names);
341 }
342
343 sub tracks
344 {
345     my($self, @constraints)=@_;
346     # FIXME: rework PathElements
347     if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
348     {
349         return $self->artist_tracks($constraints[$#constraints]->{id}, @constraints);
350     }
351     elsif(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Album")
352     {
353         my $artist_id=0;
354         my $artist=$constraints[($#constraints)-1];
355         if(defined($artist) && (ref($artist) eq "ID3FS::PathElement::Artist"))
356         {
357             # should always happen
358             $artist_id=$artist->{id};
359         }
360         return $self->album_tracks($artist_id, $constraints[$#constraints]->{id});
361     }
362
363     my $sql=("SELECT files.name\n" .
364              "\tFROM (\n" .
365              $self->tags_subselect(@constraints) .
366              "\t) AS subselect\n" .
367              "INNER JOIN files ON files.id=subselect.files_id\n" .
368              "GROUP BY files.name;");
369     print "SQL: $sql\n";
370     my $result=$self->cmd_rows($sql);
371     my @names=map { $_->[0]; } @$result;
372     print "TRACKS: ", join(', ', @names), "\n";
373     return(@names);
374 }
375
376 sub filename
377 {
378     my($self, $mountpoint, @constraints)=@_;
379     if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::File")
380     {
381         my $id=$constraints[$#constraints]->{id};
382         my $sql=("SELECT paths.name, files.name FROM files\n" .
383                  "INNER JOIN paths ON files.paths_id=paths.id\n" .
384                  "WHERE files.id=?\n" .
385                  "GROUP BY paths.name, files.name");
386         print "FILENAME SQL: $sql\n";
387         my ($path, $name)=$self->cmd_onerow($sql, $id);
388         my $id3fs_path=join('/', map { $_->{name}; }  @constraints);
389         return($self->relativise($path, $name, $mountpoint, $id3fs_path));
390     }
391     die("DB::filename: unhandled case\n"); #FIXME
392 }
393
394 sub tags_subselect
395 {
396     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=" . (defined($parent) ? $parent : "''") . " )");
408         push(@orclauses, "( t1.id IN ( " . join(', ', @tags) ." ) )");
409     }
410     for my $pair (@tags_vals)
411     {
412         my($tag, $val)=@$pair;
413         push(@orclauses, "( t1.parents_id=$tag AND t1.id=$val )");
414     }
415 #    push(@andclauses, "( t1.parents_id=" . (defined($parent) ? $parent : "''") . " )");
416     if(@orclauses)
417     {
418         push(@andclauses, join("\n\t\tOR ", @orclauses));
419     }
420     if(@andclauses)
421     {
422         $sql .= "\tWHERE\n\t\t";
423         $sql .= join("\n\t\tAND ", @andclauses) . "\n";
424     }
425     $sql .= "\tGROUP BY files_x_tags.files_id\n";
426     return $sql;
427 }
428
429 sub constraints_tag_list
430 {
431     my($self, @constraints)=@_;
432     my $lasttag=undef;
433     my @tags=();
434     my @tags_vals=();
435     for my $constraint (@constraints)
436     {
437 #       print ref($constraint), ": ", $constraint->{name}, "\n";
438         if(ref($constraint) eq "ID3FS::PathElement::Tag")
439         {
440             if(defined($lasttag))
441             {
442 #               print "TAGVAL\n";
443                 push(@tags_vals, [$lasttag, $constraint->{id}]) if defined($constraint->{id});
444                 $lasttag=undef;
445             }
446             elsif($self->tag_has_values($constraint->{id}))
447             {
448 #               print "HASVALUES\n";
449                 $lasttag=$constraint->{id} if defined($constraint->{id});
450             }
451             else
452             {
453 #               print "NOVALUES\n";
454                 push(@tags, $constraint->{id}) if(defined($constraint->{id}));
455             }
456         }
457     }
458     unless($self->{postgres})
459     {
460         @tags=map{ "\"$_\""; } @tags;
461         @tags_vals=map( { [ map({ "\"$_\""; } @$_ ) ] } @tags_vals);
462         $lasttag="\"$lasttag\"" if defined($lasttag);
463     }
464     return(\@tags, \@tags_vals, $lasttag);
465 }
466
467
468 sub relativise
469 {
470     my($self, $path, $name, $mountpoint, $id3fs_path)=@_;
471     $id3fs_path=~s/(.*)\/.*/$1/;
472     my $rpath="$self->{absbase}/$path";
473     my $vpath="$mountpoint/$id3fs_path";
474     my @path=split(/\//,$rpath);
475     my @rel=split(/\//,$vpath);
476     #absolute paths have empty first element due to leading /
477     shift(@path) if($path[0] eq "");
478     shift(@rel)  if($rel[0]  eq "");
479     if($path[0] ne $rel[0])
480     {
481         #no path in common, return absolute
482         print "FAIL: NO PATHS IN COMMON\n";
483         return $name;
484     }
485     # f: /home/foo/bar/baz.mp3
486     # r: /home/ianb/music/albums
487     while(@path && @rel && ($path[0] eq $rel[0]))
488     {
489         shift(@path);
490         shift(@rel);
491 #       print "POP ";
492     }
493 #    print "\n";
494     my $upcount=scalar(@rel);
495     my $result="../" x $upcount;
496     $result .= join("/",@path);
497     $result .= "/$name";
498     return $result;
499 }
500
501 sub bare_tags
502 {
503     my($self)=@_;
504     my $sql=("SELECT tags.name FROM tags\n" .
505              "WHERE tags.parents_id=''\n" .
506              "GROUP BY tags.name\n");
507     my $result=$self->cmd_rows($sql);
508     my @names=map { $_->[0]; } @$result;
509     return (@names);
510 }
511
512 sub tags_with_values
513 {
514     # FIXME: only shows one level of tag depth
515     my($self)=@_;
516     my $sql=("SELECT p.name, t.name  FROM tags t\n" .
517              "INNER JOIN tags p ON t.parents_id=p.id\n" .
518              "GROUP BY p.name, t.name\n");
519     print "SQL: $sql\n";
520     my $result=$self->cmd_rows($sql);
521     my $tags={};
522     for my $pair (@$result)
523     {
524         push(@{$tags->{$pair->[0]}}, $pair->[1]);
525     }
526     return $tags;
527 }
528
529 sub id
530 {
531     my($self, $type, $val)=@_;
532     my $sql="SELECT id FROM $type WHERE name=?";
533     my ($id)=$self->cmd_onerow($sql, $val);
534     return($id);
535 }
536
537 sub add
538 {
539     my($self,$path)=@_;
540     my $relpath=$path;
541     $relpath =~ s/^\Q$self->{base}\E\/?//;
542     my($filepart,$pathpart);
543     if($relpath !~ /\//)
544     {
545         $pathpart='';
546         $filepart=$relpath;
547     }
548     else
549     {
550         ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
551     }
552     my $file=ID3FS::AudioFile->new($path, $self->{me});
553     return unless(defined($file));
554     my $artist=$file->artist();
555     my $album=$file->album();
556     my $v1genre=$file->v1genre();
557     my $year=$file->year();
558     my $audiotype=$file->audiotype();
559     my @tags=$file->tags();
560     my $haspic=$file->haspic();
561
562     $artist=undef unless($self->ok($artist));
563     print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
564     my $artist_id=$self->add_to_table("artists",  $artist);
565     my $path_id=$self->add_to_table("paths", $pathpart);
566     $album=undef unless($self->ok($album));
567     if($self->{verbose} && !defined($album))
568     {
569         print "$self->{me}: $path: no album tag defined\n";
570     }
571
572     my $albums_id=$self->add_to_table("albums", $album);
573     my $file_id=$self->add_to_table("files", $filepart,
574                                     { "artists_id" => $artist_id,
575                                       "albums_id"  => $albums_id,
576                                       "paths_id"   => $path_id });
577     for my $tag (@tags)
578     {
579         $self->add_tag($file_id, @$tag);
580     }
581
582     if($self->ok($year))
583     {
584         $self->add_tag($file_id, "year", $year);
585         if($year=~/^(\d\d\d)\d$/)
586         {
587             $self->add_tag($file_id, "decade", "${1}0s");
588         }
589     }
590
591     if($self->ok($v1genre))
592     {
593         $self->add_tag($file_id, "v1genre", $v1genre);
594     }
595
596     if($haspic)
597     {
598         $self->add_tag($file_id, "haspic", undef);
599     }
600 }
601
602 sub add_tag
603 {
604     my($self, $file_id, $tag, $value)=@_;
605     my $tag_id=$self->add_to_table("tags",  $tag,
606                                    { "parents_id" => undef });
607     $self->add_relation("files_x_tags",
608                         { "files_id" => $file_id,
609                           "tags_id"  => $tag_id });
610     if(defined($value) && length($value))
611     {
612         my $val_id=$self->add_to_table("tags",  $value,
613                                        { "parents_id" => $tag_id });
614         $self->add_relation("files_x_tags",
615                             { "files_id" => $file_id,
616                               "tags_id"  => $val_id });
617     }
618 }
619
620 sub add_to_table
621 {
622     my($self, $table, $name, $extradata)=@_;
623     my $id=$self->lookup_id($table, $name);
624     unless(defined($id))
625     {
626         my $sql="INSERT INTO $table (";
627         $sql .= "id, " if($self->{postgres});
628         my @fields=qw(name);
629         if(defined($extradata))
630         {
631             push(@fields, sort keys(%$extradata));
632         }
633         $sql .= join(", ", @fields);
634         $sql .=") VALUES (";
635         $sql .=") nextval('seq'), " if($self->{postgres});
636         $sql .= join(", ", map { "?"; } @fields);
637         $sql .= ");";
638         $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
639     }
640     return $id;
641 }
642
643 sub add_relation
644 {
645     my ($self, $relname, $fields)=@_;
646     return if($self->relation_exists($relname, $fields));
647     my $sql="INSERT INTO $relname (";
648     $sql .= join(", ", sort keys(%$fields));
649     $sql .= ") VALUES (";
650     $sql .= join(", ", map { "?"; } sort keys(%$fields));
651     $sql .= ");";
652     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
653 }
654
655 sub lookup_id
656 {
657     my($self, $table, $name)=@_;
658     my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
659     return $id;
660 }
661
662 sub tag_has_values
663 {
664     my($self, $id)=@_;
665     my $sql=("SELECT COUNT(*) FROM tags\n\t" .
666              "WHERE tags.parents_id=?\n");
667     my ($rows)=$self->cmd_onerow($sql, $id);
668     return $rows;
669 }
670
671 sub files_in
672 {
673     my ($self, $dir)=@_;
674     $dir=~s/^$self->{base}\/?//;
675     my $sql=("SELECT files.name FROM files\n" .
676              "INNER JOIN paths ON files.paths_id=paths.id\n" .
677              "WHERE paths.name=?\n");
678     my $files=$self->cmd_rows($sql, $dir);
679     return(map { $_->[0]; } @$files);
680 }
681
682 sub prune_directories
683 {
684     my($self)=@_;
685     my $sql=("SELECT name, id FROM paths ORDER BY name\n");
686     my $pathsref=$self->cmd_rows($sql);
687     my @ids=();
688     for my $pathpair (@$pathsref)
689     {
690         my($path, $id)=@$pathpair;
691         my $fullpath="$self->{absbase}/$path";
692         unless(-d $fullpath)
693         {
694             push(@ids, $id)
695         }
696     }
697     $self->prune_paths(@ids);
698     return scalar(@ids);
699 }
700
701 sub prune_paths
702 {
703     my($self, @ids)=@_;
704     return unless(@ids);
705     my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
706              join(', ', map { "\"$_\""; } @ids). "\n\t)");
707     print "SQL: \n", $sql, "\n";
708     $self->cmd($sql);
709 }
710
711 sub remove_unused
712 {
713     my($self)=@_;
714     my $sql=<<'EOT';
715    DELETE FROM artists WHERE id IN (
716        SELECT artists.id FROM artists
717        LEFT JOIN files ON files.artists_id=artists.id
718        WHERE files.id IS NULL);
719
720    DELETE FROM albums WHERE id IN (
721        SELECT albums.id FROM albums
722        LEFT JOIN files ON files.albums_id=albums.id
723        WHERE files.id IS NULL);
724
725    DELETE FROM paths WHERE id IN (
726        SELECT paths.id FROM paths
727        LEFT JOIN files ON files.paths_id=paths.id
728        WHERE files.id IS NULL);
729
730    DELETE FROM files_x_tags WHERE files_id IN (
731        SELECT files_x_tags.files_id FROM files_x_tags
732        LEFT JOIN files ON files.id=files_x_tags.files_id
733        WHERE files.id IS NULL);
734
735    DELETE FROM tags WHERE id IN (
736        SELECT tags.id FROM tags
737        LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
738        WHERE files_x_tags.files_id IS NULL);
739
740 EOT
741     print "SQL: $sql\n";
742     my @sql=split(/\n\n/, $sql);
743     $self->cmd($_) for (@sql);
744 }
745
746 sub relation_exists
747 {
748     my ($self, $relname, $fields)=@_;
749     my $sql="SELECT count(1) FROM $relname WHERE ";
750     my @exprs=();
751     my @vals=();
752     for my $field (keys %$fields)
753     {
754         push(@exprs,$field);
755         push(@vals,$fields->{$field});
756     }
757     $sql .= join(' AND ', map { "$_=?"; } @exprs);
758     my ($ret)=$self->cmd_onerow($sql, @vals);
759     return $ret;
760 }
761
762 sub ok
763 {
764     my($self, $thing)=@_;
765     return(defined($thing) && length($thing) && $thing =~ /\S+/);
766 }
767
768 sub cmd
769 {
770     my ($self, @args)=@_;
771     # don't care about retcode
772     $self->cmd_sth(@args);
773 }
774
775 sub cmd_onerow
776 {
777     my ($self, @args)=@_;
778     my $sth=$self->cmd_sth(@args);
779     return($sth->fetchrow_array());
780 }
781
782 sub cmd_rows
783 {
784     my ($self, @args)=@_;
785     my $sth=$self->cmd_sth(@args);
786     return $sth->fetchall_arrayref();
787 }
788
789 sub cmd_id
790 {
791     my ($self, @args)=@_;
792     $self->cmd_sth(@args);
793     return($self->last_insert_id());
794 }
795
796 sub last_insert_id
797 {
798     my $self=shift;
799     if($self->{postgres})
800     {
801         return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
802                                             { sequence => "seq" });
803     }
804     else
805     {
806         return $self->{dbh}->last_insert_id("","","","");
807     }
808 }
809
810 __DATA__
811
812 CREATE TABLE id3fs (
813     schema_version INTEGER,
814     last_update
815 );
816
817 CREATE TABLE paths (
818     id INTEGER PRIMARY KEY,
819     name text
820 );
821
822 CREATE TABLE artists (
823     id INTEGER PRIMARY KEY,
824     name text
825 );
826
827 CREATE TABLE albums (
828     id INTEGER PRIMARY KEY,
829     name text
830 );
831
832 CREATE TABLE files (
833     id INTEGER PRIMARY KEY,
834     name text,
835     artists_id,
836     albums_id,
837     paths_id,
838     FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
839     FOREIGN KEY(albums_id)  REFERENCES albums(id)  ON DELETE CASCADE ON UPDATE CASCADE,
840     FOREIGN KEY(paths_id)   REFERENCES paths(id)   ON DELETE CASCADE ON UPDATE CASCADE
841 );
842
843 CREATE TABLE tags (
844     id INTEGER PRIMARY KEY,
845     parents_id INTEGER,
846     name text
847 );
848
849 CREATE TABLE files_x_tags (
850     files_id INTEGER,
851     tags_id INTEGER,
852     FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
853     FOREIGN KEY(tags_id)  REFERENCES tags(id)  ON DELETE CASCADE ON UPDATE CASCADE
854 );
855