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);
183 my($self, @constraints)=@_;
184 if(!@constraints) # /
187 my $sql="SELECT DISTINCT name FROM tags WHERE parents_id='';";
188 my $tags=$self->cmd_rows($sql);
189 return(map { $_->[0]; } @$tags);
193 my $sql=("SELECT t2.name FROM (\n" .
194 $self->tags_subselect(@constraints) .
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);
200 my @tags_vals=@$tags_vals;;
204 print "TAGS: ", Dumper \@tags;
205 print "VALS: ", Dumper \@tags_vals;
207 push(@andclauses, "( t2.parents_id=" . (defined($parent) ? $parent : "''") . " )");
210 push(@orclauses, "( t2.id NOT IN ( " . join(', ', @tags) ." ) )");
212 for my $pair (@tags_vals)
214 my($tag, $val)=@$pair;
215 # push(@orclauses, "( NOT ( t2.parents_id=$tag AND t2.id=$val ) )");
216 push(@andclauses, "( NOT ( t2.id=$tag ) )");
220 push(@andclauses, join("\n\tOR ", @orclauses));
224 $sql .= "\tWHERE\n\t\t";
225 $sql .= join("\n\tAND ", @andclauses) . "\n";
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";
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;
248 my($self, @constraints)=@_;
249 if(!@constraints) # /ALL
251 my $sql="SELECT DISTINCT name FROM artists;";
252 my $tags=$self->cmd_rows($sql);
253 return(map { $_->[0]; } @$tags);
256 my $sql=("SELECT artists.name FROM (\n" .
257 $self->tags_subselect(@constraints) .
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";
271 my($self, @constraints)=@_;
273 # FIXME: rework PathElements
274 if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
276 return $self->artist_albums($constraints[$#constraints]->{id}, @constraints);
278 my $sql=("SELECT albums.name\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";
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";
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";
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";
344 my($self, @constraints)=@_;
345 # FIXME: rework PathElements
346 if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
348 return $self->artist_tracks($constraints[$#constraints]->{id}, @constraints);
350 elsif(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Album")
353 my $artist=$constraints[($#constraints)-1];
354 if(defined($artist) && (ref($artist) eq "ID3FS::PathElement::Artist"))
356 # should always happen
357 $artist_id=$artist->{id};
359 return $self->album_tracks($artist_id, $constraints[$#constraints]->{id});
362 my $sql=("SELECT files.name\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";
377 my($self, $mountpoint, @constraints)=@_;
378 if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::File")
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));
390 die("DB::filename: unhandled case\n"); #FIXME
395 my($self,@constraints)=@_;
396 my ($tags, $tags_vals, $parent)=$self->constraints_tag_list(@constraints);
398 my @tags_vals=@$tags_vals;;
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");
406 push(@orclauses, "( t1.parents_id=" . (defined($parent) ? $parent : "''") . " )");
407 push(@orclauses, "( t1.id IN ( " . join(', ', @tags) ." ) )");
409 for my $pair (@tags_vals)
411 my($tag, $val)=@$pair;
412 push(@orclauses, "( t1.parents_id=$tag AND t1.id=$val )");
414 # push(@andclauses, "( t1.parents_id=" . (defined($parent) ? $parent : "''") . " )");
417 push(@andclauses, join("\n\t\tOR ", @orclauses));
421 $sql .= "\tWHERE\n\t\t";
422 $sql .= join("\n\t\tAND ", @andclauses) . "\n";
424 $sql .= "\tGROUP BY files_x_tags.files_id\n";
428 sub constraints_tag_list
430 my($self, @constraints)=@_;
434 for my $constraint (@constraints)
436 print ref($constraint), ": ", $constraint->{name}, "\n";
437 if(ref($constraint) eq "ID3FS::PathElement::Tag")
439 if(defined($lasttag))
442 push(@tags_vals, [$lasttag, $constraint->{id}]) if defined($constraint->{id});
445 elsif($self->tag_has_values($constraint->{id}))
448 $lasttag=$constraint->{id} if defined($constraint->{id});
453 push(@tags, $constraint->{id}) if(defined($constraint->{id}));
457 unless($self->{postgres})
459 @tags=map{ "\"$_\""; } @tags;
460 @tags_vals=map( { [ map({ "\"$_\""; } @$_ ) ] } @tags_vals);
461 $lasttag="\"$lasttag\"" if defined($lasttag);
463 return(\@tags, \@tags_vals, $lasttag);
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])
480 #no path in common, return absolute
481 print "FAIL: NO PATHS IN COMMON\n";
484 # f: /home/foo/bar/baz.mp3
485 # r: /home/ianb/music/albums
486 while(@path && @rel && ($path[0] eq $rel[0]))
493 my $upcount=scalar(@rel);
494 my $result="../" x $upcount;
495 $result .= join("/",@path);
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;
513 # FIXME: only shows one level of tag depth
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);
521 for my $pair (@$result)
523 push(@{$tags->{$pair->[0]}}, $pair->[1]);
530 my($self, $type, $val)=@_;
531 my $sql="SELECT id FROM $type WHERE name=?";
532 my ($id)=$self->cmd_onerow($sql, $val);
540 $relpath =~ s/^\Q$self->{base}\E\/?//;
541 my($filepart,$pathpart);
549 ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
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();
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))
568 print "$self->{me}: $path: no album tag defined\n";
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 });
578 $self->add_tag($file_id, @$tag);
583 $self->add_tag($file_id, "year", $year);
584 if($year=~/^(\d\d\d)\d$/)
586 $self->add_tag($file_id, "decade", "${1}0s");
590 if($self->ok($v1genre))
592 $self->add_tag($file_id, "v1genre", $v1genre);
597 $self->add_tag($file_id, "haspic", undef);
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))
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 });
621 my($self, $table, $name, $extradata)=@_;
622 my $id=$self->lookup_id($table, $name);
625 my $sql="INSERT INTO $table (";
626 $sql .= "id, " if($self->{postgres});
628 if(defined($extradata))
630 push(@fields, sort keys(%$extradata));
632 $sql .= join(", ", @fields);
634 $sql .=") nextval('seq'), " if($self->{postgres});
635 $sql .= join(", ", map { "?"; } @fields);
637 $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
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));
651 $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
656 my($self, $table, $name)=@_;
657 my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
664 my $sql=("SELECT COUNT(*) FROM tags\n\t" .
665 "WHERE tags.parents_id=?\n");
666 my ($rows)=$self->cmd_onerow($sql, $id);
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);
681 sub prune_directories
684 my $sql=("SELECT name, id FROM paths ORDER BY name\n");
685 my $pathsref=$self->cmd_rows($sql);
687 for my $pathpair (@$pathsref)
689 my($path, $id)=@$pathpair;
690 my $fullpath="$self->{absbase}/$path";
696 $self->prune_paths(@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";
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);
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);
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);
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);
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);
740 # print "SQL: $sql\n";
741 my @sql=split(/\n\n/, $sql);
742 $self->cmd($_) for (@sql);
747 my ($self, $relname, $fields)=@_;
748 my $sql="SELECT count(1) FROM $relname WHERE ";
751 for my $field (keys %$fields)
754 push(@vals,$fields->{$field});
756 $sql .= join(' AND ', map { "$_=?"; } @exprs);
757 my ($ret)=$self->cmd_onerow($sql, @vals);
763 my($self, $thing)=@_;
764 return(defined($thing) && length($thing) && $thing =~ /\S+/);
769 my ($self, @args)=@_;
770 # don't care about retcode
771 $self->cmd_sth(@args);
776 my ($self, @args)=@_;
777 my $sth=$self->cmd_sth(@args);
778 return($sth->fetchrow_array());
783 my ($self, @args)=@_;
784 my $sth=$self->cmd_sth(@args);
785 return $sth->fetchall_arrayref();
790 my ($self, @args)=@_;
791 $self->cmd_sth(@args);
792 return($self->last_insert_id());
798 if($self->{postgres})
800 return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
801 { sequence => "seq" });
805 return $self->{dbh}->last_insert_id("","","","");
812 schema_version INTEGER,
817 id INTEGER PRIMARY KEY,
821 CREATE TABLE artists (
822 id INTEGER PRIMARY KEY,
826 CREATE TABLE albums (
827 id INTEGER PRIMARY KEY,
832 id INTEGER PRIMARY KEY,
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
843 id INTEGER PRIMARY KEY,
848 CREATE TABLE files_x_tags (
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