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