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;";
188 my $tags=$self->cmd_rows($sql);
189 return(map { $_->[0]; } @$tags);
193 my $main_sql_start=("SELECT t2.name\n" .
195 $self->tags_subselect(@constraints) .
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 "WHERE t2.id NOT IN (");
200 my $main_sql_end=")\nGROUP BY t2.name;";
201 # FIXME: generalise more?
203 while(my $constraint=shift @constraints)
205 my $cid=$constraint->{id};
208 @ids = map( { "\"$_\""; } grep { defined; } @ids) unless($self->{postgres});
209 my $tagstr=join(", ", @ids);
210 my $sql = ($main_sql_start . $tagstr .
213 my $result=$self->cmd_rows($sql);
214 my @tagnames=map { $_->[0]; } @$result;
215 print "SUBNAMES: ", join(', ', @tagnames), "\n";
221 my($self, $tagid)=@_;
222 my $sql=("SELECT DISTINCT name FROM tags\n" .
223 "WHERE parents_id=?");
224 my $tags=$self->cmd_rows($sql, $tagid);
225 my @tags=map { $_->[0]; } @$tags;
226 @tags=map { length($_) ? $_ : "NOVALUE"; } @tags;
232 my($self, @constraints)=@_;
233 if(!@constraints) # /ALL
235 my $sql="SELECT DISTINCT name FROM artists;";
236 my $tags=$self->cmd_rows($sql);
237 return(map { $_->[0]; } @$tags);
240 my $sql=("SELECT artists.name FROM (\n" .
241 $self->tags_subselect(@constraints) .
243 "INNER JOIN files ON subselect.files_id=files.id\n" .
244 "INNER JOIN artists ON files.artists_id=artists.id\n" .
245 "GROUP BY artists.name;");
247 my $result=$self->cmd_rows($sql);
248 my @tagnames=map { $_->[0]; } @$result;
249 print "ARTISTS: ", join(', ', @tagnames), "\n";
255 my($self, @constraints)=@_;
257 # FIXME: rework PathElements
258 if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
260 return $self->artist_albums($constraints[$#constraints]->{id}, @constraints);
262 my $sql=("SELECT albums.name\n" .
264 $self->tags_subselect(@constraints) .
265 "\t) AS subselect\n" .
266 "INNER JOIN files ON subselect.files_id=files.id\n" .
267 "INNER JOIN albums ON files.albums_id=albums.id\n" .
268 "GROUP BY albums.name;");
269 my $result=$self->cmd_rows($sql);
270 my @names=map { $_->[0]; } @$result;
271 print "ALBUMS: ", join(', ', @names), "\n";
277 my($self, $artist_id, @constraints)=@_;
278 my $sql=("SELECT albums.name FROM (\n" .
279 $self->tags_subselect(@constraints) .
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, @constraints)=@_;
296 my $sql=("SELECT files.name FROM (\n" .
297 $self->tags_subselect(@constraints) .
298 "\t) AS subselect\n" .
299 "INNER JOIN files ON subselect.files_id=files.id\n" .
300 "INNER JOIN artists ON artists.id=files.artists_id\n\t" .
301 "INNER JOIN albums ON albums.id=files.albums_id\n\t" .
302 "WHERE artists.id=? AND albums.name=''\n\t" .
303 "GROUP BY files.name\n");
304 print "ARTIST_TRACKS SQL: $sql\n";
305 my $result=$self->cmd_rows($sql, $artist_id);
306 my @names=map { $_->[0]; } @$result;
307 print "ARTISTTRACKS: ", join(', ', @names), "\n";
313 my($self, $artist_id, $album_id)=@_;
314 my $sql=("SELECT files.name FROM files\n\t" .
315 "INNER JOIN albums ON albums.id=files.albums_id\n\t" .
316 "INNER JOIN artists ON artists.id=files.artists_id\n\t" .
317 "WHERE artists.id=? AND albums.id=?\n\t" .
318 "GROUP BY files.name\n");
319 print "ALBUM_TRACKS SQL($artist_id, $album_id): $sql\n";
320 my $result=$self->cmd_rows($sql, $artist_id, $album_id);
321 my @names=map { $_->[0]; } @$result;
322 print "TRACKS: ", join(', ', @names), "\n";
328 my($self, @constraints)=@_;
329 # FIXME: rework PathElements
330 if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
332 return $self->artist_tracks($constraints[$#constraints]->{id}, @constraints);
334 elsif(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Album")
337 my $artist=$constraints[($#constraints)-1];
338 if(defined($artist) && (ref($artist) eq "ID3FS::PathElement::Artist"))
340 # should always happen
341 $artist_id=$artist->{id};
343 return $self->album_tracks($artist_id, $constraints[$#constraints]->{id});
346 my $sql=("SELECT files.name\n" .
348 $self->tags_subselect(@constraints) .
349 "\t) AS subselect\n" .
350 "INNER JOIN files ON files.id=subselect.files_id\n" .
351 "GROUP BY files.name;");
353 my $result=$self->cmd_rows($sql);
354 my @names=map { $_->[0]; } @$result;
355 print "TRACKS: ", join(', ', @names), "\n";
361 my($self, $mountpoint, @constraints)=@_;
362 if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::File")
364 my $id=$constraints[$#constraints]->{id};
365 my $sql=("SELECT paths.name, files.name FROM files\n" .
366 "INNER JOIN paths ON files.paths_id=paths.id\n" .
367 "WHERE files.id=?\n" .
368 "GROUP BY paths.name, files.name");
369 print "FILENAME SQL: $sql\n";
370 my ($path, $name)=$self->cmd_onerow($sql, $id);
371 my $id3fs_path=join('/', map { $_->{name}; } @constraints);
372 return($self->relativise($path, $name, $mountpoint, $id3fs_path));
374 die("DB::filename: unhandled case\n"); #FIXME
379 my($self,@constraints)=@_;
384 # print "CONSTRAINTS: \n", Dumper \@constraints;
385 for my $constraint (@constraints)
387 # print ref($constraint),"\n";
388 if(ref($constraint) eq "ID3FS::PathElement::Tag")
390 if($self->tag_has_values($constraint->{id}))
392 # print "HASVALUES\n";
393 $lasttag=$constraint->{id} if defined($constraint->{id});
397 # print "NOVALUES\n";
398 push(@tags, $constraint->{id}) if(defined($constraint->{id}));
401 elsif(ref($constraint) eq "ID3FS::PathElement::Tagval")
404 push(@tags_vals, [$lasttag, $constraint->{id}]) if defined($constraint->{id});
407 unless($self->{postgres})
409 @tags=map{ "\"$_\""; } @tags;
410 @tags_vals=map( { [ map({ "\"$_\""; } @$_ ) ] } @tags_vals);
412 # print "TAGS\n", Dumper \@tags;
413 # print "\nVALS\n", Dumper(\@tags_vals), "\n";
414 my $sql=("\tSELECT files_x_tags.files_id FROM tags t1\n" .
415 "\tINNER JOIN files_x_tags ON t1.id=files_x_tags.tags_id\n");
419 push(@clauses, "(t1.id IN ( " . join(', ', @tags) ." ) )");
421 for my $pair (@tags_vals)
423 my($tag, $val)=@$pair;
424 push(@clauses, "( t1.parents_id=$tag AND t1.id=$val )");
428 $sql .= "\tWHERE\n\t\t" . join("\n\t\tOR ", @clauses) . "\n";
436 my($self, $path, $name, $mountpoint, $id3fs_path)=@_;
437 $id3fs_path=~s/(.*)\/.*/$1/;
438 my $rpath="$self->{absbase}/$path";
439 my $vpath="$mountpoint/$id3fs_path";
440 my @path=split(/\//,$rpath);
441 my @rel=split(/\//,$vpath);
442 #absolute paths have empty first element due to leading /
443 shift(@path) if($path[0] eq "");
444 shift(@rel) if($rel[0] eq "");
445 if($path[0] ne $rel[0])
447 #no path in common, return absolute
448 print "FAIL: NO PATHS IN COMMON\n";
451 # f: /home/foo/bar/baz.mp3
452 # r: /home/ianb/music/albums
453 while(@path && @rel && ($path[0] eq $rel[0]))
460 my $upcount=scalar(@rel);
461 my $result="../" x $upcount;
462 $result .= join("/",@path);
470 my $sql=("SELECT tags.name FROM tags\n" .
471 "WHERE tags.parents_id=''\n" .
472 "GROUP BY tags.name\n");
473 my $result=$self->cmd_rows($sql);
474 my @names=map { $_->[0]; } @$result;
480 # FIXME: only shows one level of tag depth
482 my $sql=("SELECT p.name, t.name FROM tags t\n" .
483 "INNER JOIN tags p ON t.parents_id=p.id\n" .
484 "GROUP BY p.name, t.name\n");
485 # print "SQL: $sql\n";
486 my $result=$self->cmd_rows($sql);
488 for my $pair (@$result)
490 push(@{$tags->{$pair->[0]}}, $pair->[1]);
497 my($self, $type, $val)=@_;
498 my $sql="SELECT id FROM $type WHERE name=?";
499 my ($id)=$self->cmd_onerow($sql, $val);
507 $relpath =~ s/^\Q$self->{base}\E\/?//;
508 my($filepart,$pathpart);
516 ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
518 my $file=ID3FS::AudioFile->new($path, $self->{me});
519 return unless(defined($file));
520 my $artist=$file->artist();
521 my $album=$file->album();
522 my $v1genre=$file->v1genre();
523 my $year=$file->year();
524 my $audiotype=$file->audiotype();
525 my @tags=$file->tags();
526 my $haspic=$file->haspic();
528 $artist=undef unless($self->ok($artist));
529 print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
530 my $artist_id=$self->add_to_table("artists", $artist);
531 my $path_id=$self->add_to_table("paths", $pathpart);
532 $album=undef unless($self->ok($album));
533 if($self->{verbose} && !defined($album))
535 print "$self->{me}: $path: no album tag defined\n";
538 my $albums_id=$self->add_to_table("albums", $album);
539 my $file_id=$self->add_to_table("files", $filepart,
540 { "artists_id" => $artist_id,
541 "albums_id" => $albums_id,
542 "paths_id" => $path_id });
545 $self->add_tag($file_id, @$tag);
550 $self->add_tag($file_id, "year", $year);
551 if($year=~/^(\d\d\d)\d$/)
553 $self->add_tag($file_id, "decade", "${1}0s");
557 if($self->ok($v1genre))
559 $self->add_tag($file_id, "v1genre", $v1genre);
564 $self->add_tag($file_id, "haspic", undef);
570 my($self, $file_id, @tags)=@_;
574 my $tag_id=$self->add_to_table("tags", $tag,
575 { "parents_id" => $parent_id });
576 $self->add_relation("files_x_tags",
577 { "files_id" => $file_id,
578 "tags_id" => $tag_id });
585 my($self, $table, $name, $extradata)=@_;
586 my $id=$self->lookup_id($table, $name);
589 my $sql="INSERT INTO $table (";
590 $sql .= "id, " if($self->{postgres});
592 if(defined($extradata))
594 push(@fields, sort keys(%$extradata));
596 $sql .= join(", ", @fields);
598 $sql .=") nextval('seq'), " if($self->{postgres});
599 $sql .= join(", ", map { "?"; } @fields);
601 $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
608 my ($self, $relname, $fields)=@_;
609 return if($self->relation_exists($relname, $fields));
610 my $sql="INSERT INTO $relname (";
611 $sql .= join(", ", sort keys(%$fields));
612 $sql .= ") VALUES (";
613 $sql .= join(", ", map { "?"; } sort keys(%$fields));
615 $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
620 my($self, $table, $name)=@_;
621 my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
628 my $sql=("SELECT COUNT(*) FROM tags\n\t" .
629 "WHERE tags.parents_id=?\n");
630 my ($rows)=$self->cmd_onerow($sql, $id);
637 $dir=~s/^$self->{base}\/?//;
638 my $sql=("SELECT files.name FROM files\n" .
639 "INNER JOIN paths ON files.paths_id=paths.id\n" .
640 "WHERE paths.name=?\n");
641 my $files=$self->cmd_rows($sql, $dir);
642 return(map { $_->[0]; } @$files);
645 sub prune_directories
648 my $sql=("SELECT name, id FROM paths ORDER BY name\n");
649 my $pathsref=$self->cmd_rows($sql);
651 for my $pathpair (@$pathsref)
653 my($path, $id)=@$pathpair;
654 my $fullpath="$self->{absbase}/$path";
660 $self->prune_paths(@ids);
668 my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
669 join(', ', map { "\"$_\""; } @ids). "\n\t)");
670 print "SQL: \n", $sql, "\n";
678 DELETE FROM artists WHERE id IN (
679 SELECT artists.id FROM artists
680 LEFT JOIN files ON files.artists_id=artists.id
681 WHERE files.id IS NULL);
683 DELETE FROM albums WHERE id IN (
684 SELECT albums.id FROM albums
685 LEFT JOIN files ON files.albums_id=albums.id
686 WHERE files.id IS NULL);
688 DELETE FROM paths WHERE id IN (
689 SELECT paths.id FROM paths
690 LEFT JOIN files ON files.paths_id=paths.id
691 WHERE files.id IS NULL);
693 DELETE FROM files_x_tags WHERE files_id IN (
694 SELECT files_x_tags.files_id FROM files_x_tags
695 LEFT JOIN files ON files.id=files_x_tags.files_id
696 WHERE files.id IS NULL);
698 DELETE FROM tags WHERE id IN (
699 SELECT tags.id FROM tags
700 LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
701 WHERE files_x_tags.files_id IS NULL);
705 my @sql=split(/\n\n/, $sql);
706 $self->cmd($_) for (@sql);
711 my ($self, $relname, $fields)=@_;
712 my $sql="SELECT count(1) FROM $relname WHERE ";
715 for my $field (keys %$fields)
718 push(@vals,$fields->{$field});
720 $sql .= join(' AND ', map { "$_=?"; } @exprs);
721 my ($ret)=$self->cmd_onerow($sql, @vals);
727 my($self, $thing)=@_;
728 return(defined($thing) && length($thing) && $thing =~ /\S+/);
733 my ($self, @args)=@_;
734 # don't care about retcode
735 $self->cmd_sth(@args);
740 my ($self, @args)=@_;
741 my $sth=$self->cmd_sth(@args);
742 return($sth->fetchrow_array());
747 my ($self, @args)=@_;
748 my $sth=$self->cmd_sth(@args);
749 return $sth->fetchall_arrayref();
754 my ($self, @args)=@_;
755 $self->cmd_sth(@args);
756 return($self->last_insert_id());
762 if($self->{postgres})
764 return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
765 { sequence => "seq" });
769 return $self->{dbh}->last_insert_id("","","","");
776 schema_version INTEGER,
781 id INTEGER PRIMARY KEY,
785 CREATE TABLE artists (
786 id INTEGER PRIMARY KEY,
790 CREATE TABLE albums (
791 id INTEGER PRIMARY KEY,
796 id INTEGER PRIMARY KEY,
801 FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
802 FOREIGN KEY(albums_id) REFERENCES albums(id) ON DELETE CASCADE ON UPDATE CASCADE,
803 FOREIGN KEY(paths_id) REFERENCES paths(id) ON DELETE CASCADE ON UPDATE CASCADE
807 id INTEGER PRIMARY KEY,
812 CREATE TABLE files_x_tags (
815 FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
816 FOREIGN KEY(tags_id) REFERENCES tags(id) ON DELETE CASCADE ON UPDATE CASCADE