15 my $class=ref($proto) || $proto;
20 $self->{verbose}=shift;
24 my $fallbackdir=shift;
26 $dbpath=$self->find_db($init, $dbpath, $fallbackdir);
27 return undef unless($dbpath);
28 $self->{absbase}=Cwd::abs_path($self->{base});
30 my $connectstr="dbi:SQLite:dbname=$dbpath";
31 my ($user, $pass)=("", "");
34 $connectstr="dbi:Pg:dbname=id3fs";
38 my $exists=-f $dbpath;
39 $self->{dbh}=DBI->connect($connectstr, $user, $pass,
41 unless(defined($self->{dbh}))
43 die("$self->{me}: DB Error: " . $DBI::errstr . "\n");
54 $self->enable_foreign_keys();
60 my($self, $init, $dbpath, $fallbackdir)=@_;
67 if(defined ($self->{base}))
69 $file="$self->{base}/$dbfile" unless defined($file);
72 elsif(defined($fallbackdir) && -d $fallbackdir)
74 my $path=Cwd::abs_path($fallbackdir);
77 $file="$path/$dbfile";
79 $path=~s/(.*)\/.*/$1/;
81 while(! -f $file && length($path) && -d $path);
84 $file="$fallbackdir/$dbfile";
88 if(!-f $file && !$init)
90 print "$self->{me}: db not found at $file\n";
97 sub base_dir { return shift->{base}; }
102 my @schema=split(/\n\n/,join("", <DATA>));
104 for my $cmd (@schema)
106 $self->{dbh}->do($cmd);
108 if($self->{postgres})
110 $self->cmd("CREATE SEQUENCE seq");
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)
122 $self->{dbh}->do("CREATE INDEX $index ON " . $indexes{$index});
125 $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
126 $SCHEMA_VERSION, time());
132 my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
133 if(!defined($version) || $version != $SCHEMA_VERSION)
135 die("$self->{me}: id3fs database version " .
136 defined($version) ? $version : '""' .
137 "not known, current version is $SCHEMA_VERSION.\n");
144 $self->cmd("ANALYZE");
147 sub enable_foreign_keys
150 $self->cmd("PRAGMA foreign_keys = ON");
155 my($self, $newval)=@_;
158 $self->cmd("UPDATE id3fs SET last_update=?", $newval);
162 ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
169 my($self, $sql, @params)=@_;
170 my $sth=$self->{dbh}->prepare($sql);
172 for my $param (@params)
174 $param="" unless(defined($param));
175 $sth->bind_param($idx++, $param);
184 my @constraints=@{$path->{elements}};
185 if(!@constraints) # /
188 my $sql="SELECT DISTINCT name FROM tags WHERE parents_id='';";
189 my $tags=$self->cmd_rows($sql);
190 return(map { $_->[0]; } @$tags);
194 my $sql=("SELECT t2.name FROM (\n" .
195 $self->tags_subselect($path) .
197 "INNER JOIN files_x_tags ON subselect.files_id=files_x_tags.files_id\n" .
198 "INNER JOIN tags t2 ON files_x_tags.tags_id=t2.id\n");
199 my @used=$path->used_tags();
200 print "tags(): USED: ", join(", ", @used), "\n";
203 $sql .= "WHERE t2.id NOT IN (";
204 $sql .= join(', ', @used);
207 $sql .= "GROUP BY t2.name;";
209 my $result=$self->cmd_rows($sql);
210 my @tagnames=map { $_->[0]; } @$result;
211 print "SUBNAMES: ", join(', ', @tagnames), "\n";
217 my($self, $tagid)=@_;
218 my $sql=("SELECT DISTINCT name FROM tags\n" .
219 "WHERE parents_id=?");
220 my $tags=$self->cmd_rows($sql, $tagid);
221 my @tags=map { $_->[0]; } @$tags;
222 @tags=map { length($_) ? $_ : "NOVALUE"; } @tags;
229 my @constraints=@{$path->{elements}};
230 if(!@constraints) # /ALL
232 my $sql="SELECT DISTINCT name FROM artists;";
233 my $tags=$self->cmd_rows($sql);
234 return(map { $_->[0]; } @$tags);
237 my $sql=("SELECT artists.name FROM (\n" .
238 $self->tags_subselect($path) .
240 "INNER JOIN files ON subselect.files_id=files.id\n" .
241 "INNER JOIN artists ON files.artists_id=artists.id\n" .
242 "GROUP BY artists.name;");
244 my $result=$self->cmd_rows($sql);
245 my @tagnames=map { $_->[0]; } @$result;
246 print "ARTISTS: ", join(', ', @tagnames), "\n";
253 my @constraints=@{$path->{elements}};
255 # FIXME: rework PathElements
256 if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
258 return $self->artist_albums($constraints[$#constraints]->{id}, $path);
260 my $sql=("SELECT albums.name\n" .
262 $self->tags_subselect($path) .
263 "\t) AS subselect\n" .
264 "INNER JOIN files ON subselect.files_id=files.id\n" .
265 "INNER JOIN albums ON files.albums_id=albums.id\n" .
266 "GROUP BY albums.name;");
267 print "SQL(ALBUMS): \n$sql\n";
268 my $result=$self->cmd_rows($sql);
269 my @names=map { $_->[0]; } @$result;
270 print "ALBUMS: ", join(', ', @names), "\n";
276 my($self, $artist_id, $path)=@_;
277 my @constraints=@{$path->{elements}};
278 my $sql=("SELECT albums.name FROM (\n" .
279 $self->tags_subselect($path) .
280 "\t) AS subselect\n" .
281 "INNER JOIN files ON subselect.files_id=files.id\n" .
282 "INNER JOIN albums ON albums.id=files.albums_id\n\t" .
283 "INNER JOIN artists ON artists.id=files.artists_id\n\t" .
284 "WHERE artists.id=? and albums.name <> ''\n\t" .
285 "GROUP BY albums.name\n");
286 print "ARTIST_ALBUMS SQL: $sql\n";
287 my $result=$self->cmd_rows($sql, $artist_id);
288 my @albums=map { $_->[0]; } @$result;
289 print "ALBUMS: ", join(', ', @albums), "\n";
295 my($self, $artist_id, $path)=@_;
296 my @constraints=@{$path->{elements}};
297 my $sql=("SELECT files.name FROM (\n" .
298 $self->tags_subselect($path) .
299 "\t) AS subselect\n" .
300 "INNER JOIN files ON subselect.files_id=files.id\n" .
301 "INNER JOIN artists ON artists.id=files.artists_id\n\t" .
302 "INNER JOIN albums ON albums.id=files.albums_id\n\t" .
303 "WHERE artists.id=? AND albums.name=''\n\t" .
304 "GROUP BY files.name\n");
305 print "ARTIST_TRACKS SQL: $sql\n";
306 my $result=$self->cmd_rows($sql, $artist_id);
307 my @names=map { $_->[0]; } @$result;
308 print "ARTISTTRACKS: ", join(', ', @names), "\n";
314 my($self, $artist_id, $album_id)=@_;
315 my $sql=("SELECT files.name FROM files\n\t" .
316 "INNER JOIN albums ON albums.id=files.albums_id\n\t" .
317 "INNER JOIN artists ON artists.id=files.artists_id\n\t" .
318 "WHERE artists.id=? AND albums.id=?\n\t" .
319 "GROUP BY files.name\n");
320 print "ALBUM_TRACKS SQL($artist_id, $album_id): $sql\n";
321 my $result=$self->cmd_rows($sql, $artist_id, $album_id);
322 my @names=map { $_->[0]; } @$result;
323 print "TRACKS: ", join(', ', @names), "\n";
330 my @constraints=@{$path->{elements}};
331 # FIXME: rework PathElements
332 if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
334 return $self->artist_tracks($constraints[$#constraints]->{id}, @constraints);
336 elsif(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Album")
339 my $artist=$constraints[($#constraints)-1];
340 if(defined($artist) && (ref($artist) eq "ID3FS::PathElement::Artist"))
342 # should always happen
343 $artist_id=$artist->{id};
345 return $self->album_tracks($artist_id, $constraints[$#constraints]->{id});
348 my $sql=("SELECT files.name\n" .
350 $self->tags_subselect($path) .
351 "\t) AS subselect\n" .
352 "INNER JOIN files ON files.id=subselect.files_id\n" .
353 "GROUP BY files.name;");
355 my $result=$self->cmd_rows($sql);
356 my @names=map { $_->[0]; } @$result;
357 print "TRACKS: ", join(', ', @names), "\n";
363 my($self, $mountpoint, $path)=@_;
364 my @constraints=@{$path->{elements}};
365 if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::File")
367 my $id=$constraints[$#constraints]->{id};
368 my $sql=("SELECT paths.name, files.name FROM files\n" .
369 "INNER JOIN paths ON files.paths_id=paths.id\n" .
370 "WHERE files.id=?\n" .
371 "GROUP BY paths.name, files.name");
372 print "FILENAME SQL: $sql\n";
373 my ($path, $name)=$self->cmd_onerow($sql, $id);
374 my $id3fs_path=join('/', map { $_->{name}; } @constraints);
375 return($self->relativise($path, $name, $mountpoint, $id3fs_path));
377 die("DB::filename: unhandled case\n"); #FIXME
383 my $tree=$path->{tagtree};
384 my ($sqlclause, $joinsneeded)=$tree->to_sql();
385 print "SQL($joinsneeded): $sqlclause\n";
386 my $sql="\tSELECT fxt1.files_id FROM files_x_tags fxt1\n";
387 for(my $i=2; $i <= $joinsneeded; $i++)
389 $sql .= ("\tINNER JOIN files_x_tags fxt$i ON " .
390 "fxt1.files_id=fxt${i}.files_id\n");
392 $sql .= "\tWHERE $sqlclause\n";
393 $sql .= "\tGROUP BY fxt${joinsneeded}.files_id\n";
397 sub tags_subselect_and_not
399 my($self,@constraints)=@_;
400 my ($tags, $tags_vals, $parent)=$self->constraints_tag_list(@constraints);
402 my @tags_vals=@$tags_vals;;
410 $sql="\tSELECT fxt" . scalar(@tags) . ".files_id FROM files_x_tags fxt1\n";
411 push(@andclauses, "\t\tfxt${cnt}.tags_id=$tag");
415 $sql .= ("\tLEFT JOIN files_x_tags fxt$cnt ON fxt" .
416 ($cnt-1) . ".files_id=fxt${cnt}.files_id\n");
417 push(@andclauses, "\t\tfxt${cnt}.tags_id IS NULL");
419 print "AND: @andclauses\n";
424 $sql .= "\tWHERE\n\t\t";
425 $sql .= join(" AND\n\t\t", @andclauses) . "\n";
427 $sql .= "\tGROUP BY fxt". scalar(@tags).".files_id\n";
432 sub tags_subselect_and
434 my($self,@constraints)=@_;
435 my ($tags, $tags_vals, $parent)=$self->constraints_tag_list(@constraints);
437 my @tags_vals=@$tags_vals;;
445 $sql="\tSELECT fxt" . scalar(@tags) . ".files_id FROM files_x_tags fxt1\n";
449 $sql .= ("\tINNER JOIN files_x_tags fxt$cnt ON fxt" .
450 ($cnt-1) . ".files_id=fxt${cnt}.files_id\n");
452 push(@andclauses, "\t\tfxt${cnt}.tags_id = $tag");
453 print "AND: @andclauses\n";
458 $sql .= "\tWHERE\n\t\t";
459 $sql .= join(" AND\n\t\t", @andclauses) . "\n";
461 $sql .= "\tGROUP BY fxt". scalar(@tags).".files_id\n";
465 sub tags_subselect_or
467 my($self,@constraints)=@_;
468 my ($tags, $tags_vals, $parent)=$self->constraints_tag_list(@constraints);
470 my @tags_vals=@$tags_vals;;
472 my $sql=("\tSELECT files_x_tags.files_id FROM tags t1\n" .
473 "\tINNER JOIN files_x_tags ON t1.id=files_x_tags.tags_id\n");
479 push(@andclauses, "( t1.parents_id=" . (defined($parent) ? $parent : "''") . " )");
480 push(@andclauses, "( t1.id IN ( " . join(', ', @tags) ." ) )");
482 for my $pair (@tags_vals)
484 my($tag, $val)=@$pair;
485 push(@orclauses, "( t1.parents_id=$tag AND t1.id=$val )");
487 # push(@andclauses, "( t1.parents_id=" . (defined($parent) ? $parent : "''") . " )");
490 push(@andclauses, join("\n\t\tOR ", @orclauses));
494 $sql .= "\tWHERE\n\t\t";
495 $sql .= join("\n\t\tAND ", @andclauses) . "\n";
497 $sql .= "\tGROUP BY files_x_tags.files_id\n";
501 sub constraints_tag_list
503 my($self, @constraints)=@_;
507 for my $constraint (@constraints)
509 # print ref($constraint), ": ", $constraint->{name}, "\n";
510 if(ref($constraint) eq "ID3FS::PathElement::Tag")
512 if(defined($lasttag))
515 push(@tags_vals, [$lasttag, $constraint->{id}]) if defined($constraint->{id});
518 elsif($self->tag_has_values($constraint->{id}))
520 # print "HASVALUES\n";
521 $lasttag=$constraint->{id} if defined($constraint->{id});
525 # print "NOVALUES\n";
526 push(@tags, $constraint->{id}) if(defined($constraint->{id}));
530 unless($self->{postgres})
532 @tags=map{ "\"$_\""; } @tags;
533 @tags_vals=map( { [ map({ "\"$_\""; } @$_ ) ] } @tags_vals);
534 $lasttag="\"$lasttag\"" if defined($lasttag);
536 return(\@tags, \@tags_vals, $lasttag);
542 my($self, $path, $name, $mountpoint, $id3fs_path)=@_;
543 $id3fs_path=~s/(.*)\/.*/$1/;
544 my $rpath="$self->{absbase}/$path";
545 my $vpath="$mountpoint/$id3fs_path";
546 my @path=split(/\//,$rpath);
547 my @rel=split(/\//,$vpath);
548 #absolute paths have empty first element due to leading /
549 shift(@path) if($path[0] eq "");
550 shift(@rel) if($rel[0] eq "");
551 if($path[0] ne $rel[0])
553 #no path in common, return absolute
554 print "FAIL: NO PATHS IN COMMON\n";
557 # f: /home/foo/bar/baz.mp3
558 # r: /home/ianb/music/albums
559 while(@path && @rel && ($path[0] eq $rel[0]))
566 my $upcount=scalar(@rel);
567 my $result="../" x $upcount;
568 $result .= join("/",@path);
576 my $sql=("SELECT tags.name FROM tags\n" .
577 "WHERE tags.parents_id=''\n" .
578 "GROUP BY tags.name\n");
579 my $result=$self->cmd_rows($sql);
580 my @names=map { $_->[0]; } @$result;
586 # FIXME: only shows one level of tag depth
588 my $sql=("SELECT p.name, t.name FROM tags t\n" .
589 "INNER JOIN tags p ON t.parents_id=p.id\n" .
590 "GROUP BY p.name, t.name\n");
592 my $result=$self->cmd_rows($sql);
594 for my $pair (@$result)
596 push(@{$tags->{$pair->[0]}}, $pair->[1]);
603 my($self, $type, $val)=@_;
604 my $sql="SELECT id FROM $type WHERE name=?";
605 my ($id)=$self->cmd_onerow($sql, $val);
613 $relpath =~ s/^\Q$self->{base}\E\/?//;
614 my($filepart,$pathpart);
622 ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
624 my $file=ID3FS::AudioFile->new($path, $self->{me});
625 return unless(defined($file));
626 my $artist=$file->artist();
627 my $album=$file->album();
628 my $v1genre=$file->v1genre();
629 my $year=$file->year();
630 my $audiotype=$file->audiotype();
631 my @tags=$file->tags();
632 my $haspic=$file->haspic();
634 $artist=undef unless($self->ok($artist));
635 print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
636 my $artist_id=$self->add_to_table("artists", $artist);
637 my $path_id=$self->add_to_table("paths", $pathpart);
638 $album=undef unless($self->ok($album));
639 if($self->{verbose} && !defined($album))
641 print "$self->{me}: $path: no album tag defined\n";
644 my $albums_id=$self->add_to_table("albums", $album);
645 my $file_id=$self->add_to_table("files", $filepart,
646 { "artists_id" => $artist_id,
647 "albums_id" => $albums_id,
648 "paths_id" => $path_id });
651 $self->add_tag($file_id, @$tag);
656 $self->add_tag($file_id, "year", $year);
657 if($year=~/^(\d\d\d)\d$/)
659 $self->add_tag($file_id, "decade", "${1}0s");
663 if($self->ok($v1genre))
665 $self->add_tag($file_id, "v1genre", $v1genre);
670 $self->add_tag($file_id, "haspic", undef);
676 my($self, $file_id, $tag, $value)=@_;
677 my $tag_id=$self->add_to_table("tags", $tag,
678 { "parents_id" => undef });
679 $self->add_relation("files_x_tags",
680 { "files_id" => $file_id,
681 "tags_id" => $tag_id });
682 if(defined($value) && length($value))
684 my $val_id=$self->add_to_table("tags", $value,
685 { "parents_id" => $tag_id });
686 $self->add_relation("files_x_tags",
687 { "files_id" => $file_id,
688 "tags_id" => $val_id });
694 my($self, $table, $name, $extradata)=@_;
695 my $id=$self->lookup_id($table, $name);
698 my $sql="INSERT INTO $table (";
699 $sql .= "id, " if($self->{postgres});
701 if(defined($extradata))
703 push(@fields, sort keys(%$extradata));
705 $sql .= join(", ", @fields);
707 $sql .=") nextval('seq'), " if($self->{postgres});
708 $sql .= join(", ", map { "?"; } @fields);
710 $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
717 my ($self, $relname, $fields)=@_;
718 return if($self->relation_exists($relname, $fields));
719 my $sql="INSERT INTO $relname (";
720 $sql .= join(", ", sort keys(%$fields));
721 $sql .= ") VALUES (";
722 $sql .= join(", ", map { "?"; } sort keys(%$fields));
724 $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
729 my($self, $table, $name)=@_;
730 my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
737 my $sql=("SELECT COUNT(*) FROM tags\n\t" .
738 "WHERE tags.parents_id=?\n");
739 my ($rows)=$self->cmd_onerow($sql, $id);
746 $dir=~s/^$self->{base}\/?//;
747 my $sql=("SELECT files.name FROM files\n" .
748 "INNER JOIN paths ON files.paths_id=paths.id\n" .
749 "WHERE paths.name=?\n");
750 my $files=$self->cmd_rows($sql, $dir);
751 return(map { $_->[0]; } @$files);
754 sub prune_directories
757 my $sql=("SELECT name, id FROM paths ORDER BY name\n");
758 my $pathsref=$self->cmd_rows($sql);
760 for my $pathpair (@$pathsref)
762 my($path, $id)=@$pathpair;
763 my $fullpath="$self->{absbase}/$path";
769 $self->prune_paths(@ids);
777 my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
778 join(', ', map { "\"$_\""; } @ids). "\n\t)");
779 print "SQL: \n", $sql, "\n";
787 DELETE FROM artists WHERE id IN (
788 SELECT artists.id FROM artists
789 LEFT JOIN files ON files.artists_id=artists.id
790 WHERE files.id IS NULL);
792 DELETE FROM albums WHERE id IN (
793 SELECT albums.id FROM albums
794 LEFT JOIN files ON files.albums_id=albums.id
795 WHERE files.id IS NULL);
797 DELETE FROM paths WHERE id IN (
798 SELECT paths.id FROM paths
799 LEFT JOIN files ON files.paths_id=paths.id
800 WHERE files.id IS NULL);
802 DELETE FROM files_x_tags WHERE files_id IN (
803 SELECT files_x_tags.files_id FROM files_x_tags
804 LEFT JOIN files ON files.id=files_x_tags.files_id
805 WHERE files.id IS NULL);
807 DELETE FROM tags WHERE id IN (
808 SELECT tags.id FROM tags
809 LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
810 WHERE files_x_tags.files_id IS NULL);
815 my @sql=split(/\n\n/, $sql);
816 $self->cmd($_) for (@sql);
821 my ($self, $relname, $fields)=@_;
822 my $sql="SELECT count(1) FROM $relname WHERE ";
825 for my $field (keys %$fields)
828 push(@vals,$fields->{$field});
830 $sql .= join(' AND ', map { "$_=?"; } @exprs);
831 my ($ret)=$self->cmd_onerow($sql, @vals);
837 my($self, $thing)=@_;
838 return(defined($thing) && length($thing) && $thing =~ /\S+/);
843 my ($self, @args)=@_;
844 # don't care about retcode
845 $self->cmd_sth(@args);
850 my ($self, @args)=@_;
851 my $sth=$self->cmd_sth(@args);
852 return($sth->fetchrow_array());
857 my ($self, @args)=@_;
858 my $sth=$self->cmd_sth(@args);
859 return $sth->fetchall_arrayref();
864 my ($self, @args)=@_;
865 $self->cmd_sth(@args);
866 return($self->last_insert_id());
872 if($self->{postgres})
874 return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
875 { sequence => "seq" });
879 return $self->{dbh}->last_insert_id("","","","");
886 schema_version INTEGER,
891 id INTEGER PRIMARY KEY,
895 CREATE TABLE artists (
896 id INTEGER PRIMARY KEY,
900 CREATE TABLE albums (
901 id INTEGER PRIMARY KEY,
906 id INTEGER PRIMARY KEY,
911 FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
912 FOREIGN KEY(albums_id) REFERENCES albums(id) ON DELETE CASCADE ON UPDATE CASCADE,
913 FOREIGN KEY(paths_id) REFERENCES paths(id) ON DELETE CASCADE ON UPDATE CASCADE
917 id INTEGER PRIMARY KEY,
922 CREATE TABLE files_x_tags (
925 FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
926 FOREIGN KEY(tags_id) REFERENCES tags(id) ON DELETE CASCADE ON UPDATE CASCADE