1 # id3fs - a FUSE-based filesystem for browsing audio metadata
2 # Copyright (C) 2010 Ian Beckwith <ianb@erislabs.net>
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25 our $SCHEMA_VERSION=1;
26 my $dbfile=".id3fs"; # default
31 my $class=ref($proto) || $proto;
36 $self->{verbose}=shift;
39 $self->{dbpath}=shift || ($self->{base} . "/" . $dbfile);
40 $self->{dbpath}=Cwd::abs_path($self->{dbpath});
41 $self->{absbase}=Cwd::abs_path($self->{base});
43 my $connectstr="dbi:SQLite:dbname=$self->{dbpath}";
44 my $exists=-f $self->{dbpath};
45 $self->{dbh}=DBI->connect($connectstr, undef, undef,
47 unless(defined($self->{dbh}))
49 die("$self->{me}: DB Error: " . $DBI::errstr . "\n");
60 $self->enable_foreign_keys();
64 # search parent directories for db
68 shift if(ref($_[0]) eq "ID3FS::DB");
70 my($me, $init, @dirs)=@_;
74 my $path=Cwd::abs_path($dir);
78 $path=~s/(.*)\/.*/$1/;
80 while(! -f "$base/$dbfile" && length($path) && -d $path);
81 if(-f "$base/$dbfile")
86 if(!-f "$base/$dbfile")
90 print "$me: db not found at $base/$dbfile\n";
99 sub base_dir { return shift->{base}; }
104 my @schema=split(/\n\n/,join("", <DATA>));
106 for my $cmd (@schema)
108 $self->{dbh}->do($cmd);
110 $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
111 $SCHEMA_VERSION, time());
117 my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
118 if(!defined($version) || $version != $SCHEMA_VERSION)
120 die("$self->{me}: id3fs database version " .
121 defined($version) ? $version : '""' .
122 "not known, current version is $SCHEMA_VERSION.\n");
129 $self->cmd("ANALYZE");
132 sub enable_foreign_keys
135 $self->cmd("PRAGMA foreign_keys = ON");
140 my($self, $newval)=@_;
143 $self->cmd("UPDATE id3fs SET last_update=?", $newval);
147 ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
155 my $sql=("SELECT tags.name FROM tags\n" .
156 "WHERE tags.parents_id=''\n" .
157 "GROUP BY tags.name\n");
158 my @names=$self->cmd_firstcol($sql);
165 my $sql=("SELECT p.name, t.name FROM tags t\n" .
166 "INNER JOIN tags p ON t.parents_id=p.id\n" .
167 "GROUP BY p.name, t.name\n");
168 my $result=$self->cmd_rows($sql);
170 for my $pair (@$result)
172 push(@{$tags->{$pair->[0]}}, $pair->[1]);
180 my $sql=("SELECT COUNT(*) FROM tags\n\t" .
181 "WHERE tags.parents_id=?\n");
182 my ($rows)=$self->cmd_onerow($sql, $id);
188 my($self, $path, $name, $mountpoint, $querypath)=@_;
189 my $rpath="$self->{absbase}/$path";
190 my $vpath=$mountpoint . $querypath;
191 my @path=split(/\//,$rpath);
192 my @rel=split(/\//,$vpath);
193 # drop filename from rel
195 # absolute paths have empty first element due to leading /
196 shift(@path) if($path[0] eq "");
197 shift(@rel) if($rel[0] eq "");
198 # f: /home/foo/bar/baz.mp3
199 # r: /home/ianb/music/albums
200 while(@path && @rel && ($path[0] eq $rel[0]))
205 my $upcount=scalar(@rel);
206 my $result="../" x $upcount;
207 $result .= join("/",@path);
215 my $relpath=Cwd::abs_path($path);
216 $relpath =~ s/^\Q$self->{absbase}\E\/?//;
217 my($filepart,$pathpart);
225 ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
227 my $file=ID3FS::AudioFile->new($path, $self->{me});
228 return unless(defined($file));
229 my $artist=$file->artist();
230 my $album=$file->album();
231 my $v1genre=$file->v1genre();
232 my $year=$file->year();
233 my $audiotype=$file->audiotype();
234 my @tags=$file->tags();
235 my $haspic=$file->haspic();
236 my $channels=$file->channels();
237 my $bitrate=$file->bitrate();
238 my $samplerate=$file->samplerate();
240 $artist=undef unless($self->ok($artist));
241 print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
242 my $artist_id=$self->add_to_table("artists", $artist);
243 my $path_id=$self->add_to_table("paths", $pathpart);
244 $album=undef unless($self->ok($album));
245 # if($self->{verbose} && !defined($album)) FIXME
248 print "$self->{me}: $path: no album tag defined\n";
251 my $albums_id=$self->add_to_table("albums", $album);
252 my $file_id=$self->add_to_table("files", $filepart,
253 { "artists_id" => $artist_id,
254 "albums_id" => $albums_id,
255 "paths_id" => $path_id });
260 $self->add_tag($file_id, @$tag);
265 $self->add_tag($file_id, "UNTAGGED");
268 $year="UNKNOWN" if(!$self->ok($year) || $year =~ /^0+$/);
269 $self->add_tag($file_id, "year", $year);
270 if($year=~/^(\d\d\d)\d$/)
272 $self->add_tag($file_id, "decade", "${1}0s");
276 $self->add_tag($file_id, "decade", "UNKNOWN");
279 if($self->ok($v1genre))
281 $self->add_tag($file_id, "v1genre", $v1genre);
286 $self->add_tag($file_id, "haspic", undef);
289 if($self->ok($audiotype))
291 $self->add_tag($file_id, "audiotype", $audiotype);
294 if($self->ok($channels))
298 $self->add_tag($file_id, "channels", "stereo");
300 elsif($channels eq "1")
302 $self->add_tag($file_id, "channels", "mono");
306 $self->add_tag($file_id, "channels", $channels);
310 if($self->ok($bitrate))
312 $self->add_tag($file_id, "bitrate", $bitrate);
315 if($self->ok($samplerate))
317 $self->add_tag($file_id, "samplerate", $samplerate);
324 my($self, $file_id, $tag, $value)=@_;
325 my $tag_id=$self->add_to_table("tags", $tag,
326 { "parents_id" => undef });
327 $self->add_relation("files_x_tags",
328 { "files_id" => $file_id,
329 "tags_id" => $tag_id });
330 if(defined($value) && length($value))
332 my $val_id=$self->add_to_table("tags", $value,
333 { "parents_id" => $tag_id });
334 $self->add_relation("files_x_tags",
335 { "files_id" => $file_id,
336 "tags_id" => $val_id });
342 my($self, $table, $name, $extradata)=@_;
344 if($extradata && $extradata->{parents_id})
346 $parent=$extradata->{parents_id};
348 my $id=$self->lookup_id($table, $name, $parent);
351 my $sql="INSERT INTO $table (";
353 if(defined($extradata))
355 push(@fields, sort keys(%$extradata));
357 $sql .= join(", ", @fields);
359 $sql .= join(", ", map { "?"; } @fields);
361 $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
368 my ($self, $relname, $fields)=@_;
369 return if($self->relation_exists($relname, $fields));
370 my $sql="INSERT INTO $relname (";
371 $sql .= join(", ", sort keys(%$fields));
372 $sql .= ") VALUES (";
373 $sql .= join(", ", map { "?"; } sort keys(%$fields));
375 $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
381 my $sql=("SELECT files.name FROM files\n" .
382 "INNER JOIN paths ON files.paths_id=paths.id\n" .
383 "WHERE paths.name=?\n");
384 return($self->cmd_firstcol($sql, $dir));
389 my($self, $path, $file)=@_;
390 my $sql=("DELETE FROM files WHERE id IN (" .
391 "\tSELECT files.id FROM files\n" .
392 "\tINNER JOIN paths ON paths.id=files.paths_id\n" .
393 "\tWHERE paths.name=? and files.name=? )\n");
394 $self->cmd_rows($sql, $path, $file);
398 sub prune_directories
401 my $sql=("SELECT name, id FROM paths\n");
402 my $pathsref=$self->cmd_rows($sql);
404 for my $pathpair (@$pathsref)
406 my($path, $id)=@$pathpair;
407 my $fullpath="$self->{absbase}/$path";
413 $self->prune_paths(@ids);
421 my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
422 join(', ', map { "\"$_\""; } @ids). "\n\t)");
430 DELETE FROM artists WHERE id IN (
431 SELECT artists.id FROM artists
432 LEFT JOIN files ON files.artists_id=artists.id
433 WHERE files.id IS NULL);
435 DELETE FROM albums WHERE id IN (
436 SELECT albums.id FROM albums
437 LEFT JOIN files ON files.albums_id=albums.id
438 WHERE files.id IS NULL);
440 DELETE FROM paths WHERE id IN (
441 SELECT paths.id FROM paths
442 LEFT JOIN files ON files.paths_id=paths.id
443 WHERE files.id IS NULL);
445 DELETE FROM files_x_tags WHERE files_id IN (
446 SELECT files_x_tags.files_id FROM files_x_tags
447 LEFT JOIN files ON files.id=files_x_tags.files_id
448 WHERE files.id IS NULL);
450 DELETE FROM tags WHERE id IN (
451 SELECT tags.id FROM tags
452 LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
453 WHERE files_x_tags.files_id IS NULL);
457 # print "SQL: $sql\n";
458 my @sql=split(/\n\n/, $sql);
459 $self->cmd($_) for (@sql);
464 my ($self, $relname, $fields)=@_;
465 my $sql="SELECT count(1) FROM $relname WHERE ";
468 for my $field (keys %$fields)
471 push(@vals,$fields->{$field});
473 $sql .= join(' AND ', map { "$_=?"; } @exprs);
474 my ($ret)=$self->cmd_onerow($sql, @vals);
480 my($self, $thing)=@_;
481 return(defined($thing) && length($thing) && $thing =~ /\S+/);
484 # actually call the database
487 my($self, $sql, @params)=@_;
488 my $sth=$self->{dbh}->prepare($sql);
490 for my $param (@params)
492 $param="" unless(defined($param));
493 $sth->bind_param($idx++, $param);
499 # pass cmd to db, ignore response
502 my ($self, @args)=@_;
503 # don't care about retcode
504 $self->cmd_sth(@args);
510 my ($self, @args)=@_;
511 my $sth=$self->cmd_sth(@args);
512 return($sth->fetchrow_array());
518 my ($self, @args)=@_;
519 my $sth=$self->cmd_sth(@args);
520 return $sth->fetchall_arrayref();
523 # returns just the first column
526 my ($self, @args)=@_;
527 return(map { $_->[0] } @{$self->cmd_rows(@args)});
530 # runs cmd, returns id of last insert
533 my ($self, @args)=@_;
534 $self->cmd_sth(@args);
535 return($self->last_insert_id());
541 return $self->{dbh}->last_insert_id("","","","");
544 # lookup id of $name in $table, also matching on $parent if needed
547 my($self, $table, $name, $parent)=@_;
548 my $sql="SELECT id FROM $table where name=?";
552 $sql .= " AND parents_id=?";
553 push(@args, $parent);
555 my($id)=$self->cmd_onerow($sql, @args);
562 schema_version INTEGER,
572 CREATE TABLE artists (
578 CREATE TABLE albums (
591 FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
592 FOREIGN KEY(albums_id) REFERENCES albums(id) ON DELETE CASCADE ON UPDATE CASCADE,
593 FOREIGN KEY(paths_id) REFERENCES paths(id) ON DELETE CASCADE ON UPDATE CASCADE
603 CREATE TABLE files_x_tags (
606 FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
607 FOREIGN KEY(tags_id) REFERENCES tags(id) ON DELETE CASCADE ON UPDATE CASCADE
610 CREATE INDEX idx_fxt_both ON files_x_tags (files_id, tags_id)
612 CREATE INDEX idx_fxt_tags ON files_x_tags (tags_id)
614 CREATE INDEX idx_files_id_name ON files (id, name)
616 CREATE INDEX idx_files_name_id ON files (name, id)
618 CREATE INDEX idx_tags_id_parent_name ON tags (id, parents_id, name)
620 CREATE INDEX idx_tags_parent_id_name ON tags (parents_id, id, name)
622 CREATE INDEX idx_tags_name ON tags (name)