id3fs-index -l: bare tags: don't display tags with children (eg year)
[id3fs.git] / lib / ID3FS / DB.pm
index ac84aa0..5821b53 100644 (file)
@@ -1,12 +1,29 @@
+# id3fs - a FUSE-based filesystem for browsing audio metadata
+# Copyright (C) 2010  Ian Beckwith <ianb@erislabs.net>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
 package ID3FS::DB;
 
 use strict;
 use warnings;
 use DBI;
-use ID3FS::File;
+use ID3FS::AudioFile;
+use Cwd;
 
 our $SCHEMA_VERSION=1;
-my $dbfile=".id3fs";
+my $dbfile=".id3fs"; # default
 
 sub new
 {
@@ -15,47 +32,72 @@ sub new
     my $self={};
     bless($self,$class);
 
-    my($dir, $init, $me)=@_;
-    $self->{dbpath}="$dir/$dbfile";
-    $self->{me}=$me;
+    $self->{me}=shift;
+    $self->{verbose}=shift;
+    my $init=shift;
+    $self->{base}=shift;
+    $self->{dbpath}=shift || ($self->{base} . "/" . $dbfile);
+    $self->{dbpath}=Cwd::abs_path($self->{dbpath});
+    $self->{absbase}=Cwd::abs_path($self->{base});
 
+    my $connectstr="dbi:SQLite:dbname=$self->{dbpath}";
     my $exists=-f $self->{dbpath};
-
-    $self->{postgres}=0;
-
-    unless($self->{postgres})
+    $self->{dbh}=DBI->connect($connectstr, undef, undef,
+                             { AutoCommit=>1 } );
+    unless(defined($self->{dbh}))
     {
-       die("$me: $self->{dbpath}: not found. use --init to create.\n") if(!$exists && !$init);
-       die("$me: --init used but $self->{dbpath} exists.\n")           if($exists && $init);
+       die("$self->{me}: DB Error: " . $DBI::errstr . "\n");
     }
 
-    my $connectstr="dbi:SQLite:dbname=$self->{dbpath}";
-    my ($user, $pass)=("", "");
-    if($self->{postgres})
+    if($exists)
     {
-       $connectstr="dbi:Pg:dbname=id3fs";
-       $user="ianb";
-       $pass="foo";
+       $self->checkschema();
     }
-    $self->{dbh}=DBI->connect($connectstr, $user, $pass,
-                             { AutoCommit=>1 } );
-    unless(defined($self->{dbh}))
+    else
     {
-       die("$me: DB Error: " . $DBI::errstr . "\n");
+       $self->create();
     }
+    $self->enable_foreign_keys();
+    return $self;
+}
 
-    if($init)
+# search parent directories for db
+sub find_db
+{
+    # class method
+    shift if(ref($_[0]) eq "ID3FS::DB");
+
+    my($me, $init, @dirs)=@_;
+    my $base=undef;
+    for my $dir (@dirs)
     {
-       $self->create();
+       my $path=Cwd::abs_path($dir);
+       do
+       {
+           $base=$path;
+           $path=~s/(.*)\/.*/$1/;
+       }
+       while(! -f "$base/$dbfile" && length($path) && -d $path);
+       if(-f "$base/$dbfile")
+       {
+           return $base;
+       }
     }
-    else
+    if(!-f "$base/$dbfile")
     {
-       $self->checkschema();
-    }
+       unless($init)
+       {
+           print "$me: db not found at $base/$dbfile\n";
+           return undef;
+       }
+       $base=$dirs[0];
 
-    return $self;
+    }
+    return $base;
 }
 
+sub base_dir { return shift->{base}; }
+
 sub create
 {
     my($self,$name)=@_;
@@ -65,11 +107,8 @@ sub create
     {
        $self->{dbh}->do($cmd);
     }
-    if($self->{postgres})
-    {
-       $self->cmd("CREATE SEQUENCE seq");
-    }
-    $self->cmd("INSERT INTO id3fs (schema_version) VALUES (?)", $SCHEMA_VERSION);
+    $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
+              $SCHEMA_VERSION, time());
 }
 
 sub checkschema
@@ -84,104 +123,161 @@ sub checkschema
     }
 }
 
-sub cmd_sth
+sub analyze
 {
-    my($self, $sql, @params)=@_;
-    my $sth=$self->{dbh}->prepare($sql);
-    my $idx=1;
-    for my $param (@params)
+    my $self=shift;
+    $self->cmd("ANALYZE");
+}
+
+sub enable_foreign_keys
+{
+    my $self=shift;
+    $self->cmd("PRAGMA foreign_keys = ON");
+}
+
+sub last_update
+{
+    my($self, $newval)=@_;
+    if(defined($newval))
     {
-       $param="" unless(defined($param));
-       $sth->bind_param($idx++, $param);
+       $self->cmd("UPDATE id3fs SET last_update=?", $newval);
     }
-    $sth->execute();
-    return $sth;
+    else
+    {
+       ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
+    }
+    return $newval;
 }
 
-sub tags
+sub bare_tags
 {
-    my($self, @constraints)=@_;
-    if(!@constraints) # /
-    {
-       my $sql="SELECT DISTINCT name FROM tags;";
-       my $tags=$self->cmd_rows($sql);
-       return(map { $_->[0]; } @$tags);
-    }
-    my @file_ids=();
-    my @tag_ids=();
-    my $main_sql_start=("SELECT tags.name FROM files\n" .
-                       "  INNER JOIN files_x_tags fxt1 ON files.id=fxt1.files_id\n" .
-                       "  INNER JOIN files_x_tags fxt2 ON files.id=fxt2.files_id\n" .
-                       "  INNER JOIN tags ON tags.id=fxt2.tags_id\n" .
-                       "  WHERE fxt1.tags_id IN \n\t(");
-    my $main_sql_mid=")\n\tAND fxt2.tags_id NOT IN \n\t(";
-    my $main_sql_end=")\n  GROUP BY tags.name;";
-    while(my $constraint=shift @constraints)
-    {
-       print "CONSTRAINT: $constraint->{name}\n";
-       my $cid=$constraint->{id};
-       push(@tag_ids, $cid);
-    }
-    @tag_ids = map( { "\"$_\""; } @tag_ids) unless($self->{postgres});
-    my $tagstr=join(", ", @tag_ids);
-    my $sql = ($main_sql_start . $tagstr .
-              $main_sql_mid   . $tagstr .
-              $main_sql_end);
-    print "SQL: $sql\n";
+    my($self)=@_;
+    my $sql=("SELECT t1.name FROM tags t1\n" .
+            "LEFT JOIN tags t2 on t1.id=t2.parents_id\n" .
+            "WHERE t1.parents_id='' AND t2.id IS NULL\n" .
+            "GROUP BY t1.name\n");
+    my @names=$self->cmd_firstcol($sql);
+    return (@names);
+}
+
+sub tags_with_values
+{
+    my($self)=@_;
+    my $sql=("SELECT p.name, t.name  FROM tags t\n" .
+            "INNER JOIN tags p ON t.parents_id=p.id\n" .
+            "GROUP BY p.name, t.name\n");
     my $result=$self->cmd_rows($sql);
-    my @tagnames=map { $_->[0]; } @$result;
-    print "SUBNAMES: ", join(', ', @tagnames), "\n";
-    return(@tagnames);
+    my $tags={};
+    for my $pair (@$result)
+    {
+       push(@{$tags->{$pair->[0]}}, $pair->[1]);
+    }
+    return $tags;
 }
 
-sub tag_values
+sub tag_has_values
 {
-    my($self, $tag)=@_;
-    my $sql=("SELECT DISTINCT tagvals.name FROM tags\n" .
-            "INNER JOIN tags_x_tagvals ON tags.id=tags_x_tagvals.tags_id\n" .
-            "INNER JOIN tagvals ON tagvals.id=tags_x_tagvals.tagvals_id\n" .
-            "WHERE tags.name=?");
-    my $tags=$self->cmd_rows($sql, $tag);
-    return(map { $_->[0]; } @$tags);
+    my($self, $id)=@_;
+    my $sql=("SELECT COUNT(*) FROM tags\n\t" .
+            "WHERE tags.parents_id=?\n");
+    my ($rows)=$self->cmd_onerow($sql, $id);
+    return $rows;
 }
 
-sub tag_id
+sub relativise
 {
-    my($self, $tag)=@_;
-    my $sql='SELECT id FROM tags WHERE name=?';
-    my ($id)=$self->cmd_onerow($sql, $tag);
-    return($id);
+    my($self, $path, $name, $mountpoint, $querypath)=@_;
+    my $rpath="$self->{absbase}/$path";
+    my $vpath=$mountpoint . $querypath;
+    my @path=split(/\//,$rpath);
+    my @rel=split(/\//,$vpath);
+    # drop filename from rel
+    pop @rel;
+    # absolute paths have empty first element due to leading /
+    shift(@path) if($path[0] eq "");
+    shift(@rel)  if($rel[0]  eq "");
+    # f: /home/foo/bar/baz.mp3
+    # r: /home/ianb/music/albums
+    while(@path && @rel && ($path[0] eq $rel[0]))
+    {
+       shift(@path);
+       shift(@rel);
+    }
+    my $upcount=scalar(@rel);
+    my $result="../" x $upcount;
+    $result .= join("/",@path);
+    $result .= "/$name";
+    return $result;
 }
 
 sub add
 {
     my($self,$path)=@_;
-    my $file=ID3FS::File->new($path);
+    my $relpath=Cwd::abs_path($path);
+    $relpath =~ s/^\Q$self->{absbase}\E\/?//;
+    my($filepart,$pathpart);
+    if($relpath !~ /\//)
+    {
+       $pathpart='';
+       $filepart=$relpath;
+    }
+    else
+    {
+       ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
+    }
+    my $file=ID3FS::AudioFile->new($path, $self->{me});
     return unless(defined($file));
     my $artist=$file->artist();
     my $album=$file->album();
     my $v1genre=$file->v1genre();
     my $year=$file->year();
-    my $audiotype=$file->album();
-    my $tags=$file->tags();
+    my $audiotype=$file->audiotype();
+    my @tags=$file->tags();
     my $haspic=$file->haspic();
-
-    my $file_id=$self->add_to_table("files", $path);
-    my $artists_id=$self->add_to_table("artists",  $artist);
-    my $albums_id=$self->add_to_table("albums",  $album);
-    for my $tag (keys %$tags)
+    my $channels=$file->channels();
+    my $bitrate=$file->bitrate();
+    my $samplerate=$file->samplerate();
+
+    $artist=undef unless($self->ok($artist));
+    print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
+    my $artist_id=$self->add_to_table("artists",  $artist);
+    my $path_id=$self->add_to_table("paths", $pathpart);
+    $album=undef unless($self->ok($album));
+#    if($self->{verbose} && !defined($album)) FIXME
+    if(!defined($album))
     {
-       $self->add_tag($file_id, $tag, $tags->{$tag});
+       print "$self->{me}: $path: no album tag defined\n";
     }
 
-    if($self->ok($year))
+    my $albums_id=$self->add_to_table("albums", $album);
+    my $file_id=$self->add_to_table("files", $filepart,
+                                   { "artists_id" => $artist_id,
+                                     "albums_id"  => $albums_id,
+                                     "paths_id"   => $path_id });
+    if(@tags)
     {
-       $self->add_tag($file_id, "year", $year);
-       if($year=~/^(\d\d\d)\d$/)
+       for my $tag (@tags)
        {
-           $self->add_tag($file_id, "decade", "${1}0s");
+           $self->add_tag($file_id, @$tag);
        }
     }
+    else
+    {
+       $self->add_tag($file_id, "UNTAGGED");
+    }
+
+    $year="UNKNOWN" if(!$self->ok($year) || $year =~ /^0+$/);
+    $year+=1900 if($year=~/^\d\d$/);
+    $self->add_tag($file_id, "year", $year);
+    if($year=~/^(\d\d\d)\d$/)
+    {
+       $self->add_tag($file_id, "decade", "${1}0s");
+    }
+    else
+    {
+       $self->add_tag($file_id, "decade", "UNKNOWN");
+    }
+
     if($self->ok($v1genre))
     {
        $self->add_tag($file_id, "v1genre", $v1genre);
@@ -192,39 +288,68 @@ sub add
        $self->add_tag($file_id, "haspic", undef);
     }
 
-    $self->add_relation("files_x_artists",
-                       { "files_id" => $file_id,
-                         "artists_id" => $artists_id });
+    if($self->ok($audiotype))
+    {
+       $self->add_tag($file_id, "audiotype", $audiotype);
+    }
+    else
+    {
+       # should never happen
+       $self->add_tag($file_id, "audiotype", "UNKNOWN");
+    }
+
+    if($self->ok($channels))
+    {
+       if    ($channels eq "2") { $channels="stereo";  }
+       elsif ($channels eq "1") { $channels="mono";    }
+       elsif ($channels eq "0") { $channels="UNKNOWN"; }
+       $self->add_tag($file_id, "channels", $channels);
+    }
+
+    if($self->ok($bitrate))
+    {
+       $bitrate="UNKNOWN" if($bitrate=~/^0+$/);
+       $self->add_tag($file_id, "bitrate", $bitrate);
+    }
+
+    if($self->ok($samplerate))
+    {
+       $samplerate="UNKNOWN" if($samplerate=~/^0+$/);
+       $self->add_tag($file_id, "samplerate", $samplerate);
+    }
 
-    $self->add_relation("artists_x_albums",
-                     { "artists_id" => $artists_id,
-                       "albums_id" => $albums_id});
 }
 
 sub add_tag
 {
-    my($self, $file_id, $tag, $val)=@_;
-    my $tag_id=$self->add_to_table("tags",  $tag);
+    my($self, $file_id, $tag, $value)=@_;
+    my $tag_id=$self->add_to_table("tags",  $tag,
+                                  { "parents_id" => undef });
     $self->add_relation("files_x_tags",
                        { "files_id" => $file_id,
                          "tags_id"  => $tag_id });
-    if(defined($val))
+    if(defined($value) && length($value))
     {
-       my $val_id=$self->add_to_table("tagvals", $val);
-       $self->add_relation("tags_x_tagvals",
-                           { "tags_id"     => $tag_id,
-                             "tagvals_id"  => $val_id });
+       my $val_id=$self->add_to_table("tags",  $value,
+                                      { "parents_id" => $tag_id });
+       $self->add_relation("files_x_tags",
+                           { "files_id" => $file_id,
+                             "tags_id"  => $val_id });
     }
 }
 
 sub add_to_table
 {
     my($self, $table, $name, $extradata)=@_;
-    my $id=$self->lookup_id($table, $name);
+    my $parent=undef;
+    if($extradata && $extradata->{parents_id})
+    {
+       $parent=$extradata->{parents_id};
+    }
+    my $id=$self->lookup_id($table, $name, $parent);
     unless(defined($id))
     {
        my $sql="INSERT INTO $table (";
-       $sql .= "id, " if($self->{postgres});
        my @fields=qw(name);
        if(defined($extradata))
        {
@@ -232,7 +357,6 @@ sub add_to_table
        }
        $sql .= join(", ", @fields);
        $sql .=") VALUES (";
-       $sql .=") nextval('seq'), " if($self->{postgres});
        $sql .= join(", ", map { "?"; } @fields);
        $sql .= ");";
        $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
@@ -252,11 +376,88 @@ sub add_relation
     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
 }
 
-sub lookup_id
+sub files_in
 {
-    my($self, $table, $name)=@_;
-    my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
-    return $id;
+    my ($self, $dir)=@_;
+    my $sql=("SELECT files.name FROM files\n" .
+            "INNER JOIN paths ON files.paths_id=paths.id\n" .
+            "WHERE paths.name=?\n");
+    return($self->cmd_firstcol($sql, $dir));
+}
+
+sub unindex
+{
+    my($self, $path, $file)=@_;
+    my $sql=("DELETE FROM files WHERE id IN (" .
+            "\tSELECT files.id FROM files\n" .
+            "\tINNER JOIN paths ON paths.id=files.paths_id\n" .
+            "\tWHERE paths.name=? and files.name=? )\n");
+    $self->cmd_rows($sql, $path, $file);
+}
+
+
+sub prune_directories
+{
+    my($self)=@_;
+    my $sql=("SELECT name, id FROM paths\n");
+    my $pathsref=$self->cmd_rows($sql);
+    my @ids=();
+    for my $pathpair (@$pathsref)
+    {
+       my($path, $id)=@$pathpair;
+       my $fullpath="$self->{absbase}/$path";
+       unless(-d $fullpath)
+       {
+           push(@ids, $id)
+       }
+    }
+    $self->prune_paths(@ids);
+    return scalar(@ids);
+}
+
+sub prune_paths
+{
+    my($self, @ids)=@_;
+    return unless(@ids);
+    my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
+            join(', ', map { "\"$_\""; } @ids). "\n\t)");
+    $self->cmd($sql);
+}
+
+sub remove_unused
+{
+    my($self)=@_;
+    my $sql=<<'EOT';
+   DELETE FROM artists WHERE id IN (
+       SELECT artists.id FROM artists
+       LEFT JOIN files ON files.artists_id=artists.id
+       WHERE files.id IS NULL);
+
+   DELETE FROM albums WHERE id IN (
+       SELECT albums.id FROM albums
+       LEFT JOIN files ON files.albums_id=albums.id
+       WHERE files.id IS NULL);
+
+   DELETE FROM paths WHERE id IN (
+       SELECT paths.id FROM paths
+       LEFT JOIN files ON files.paths_id=paths.id
+       WHERE files.id IS NULL);
+
+   DELETE FROM files_x_tags WHERE files_id IN (
+       SELECT files_x_tags.files_id FROM files_x_tags
+       LEFT JOIN files ON files.id=files_x_tags.files_id
+       WHERE files.id IS NULL);
+
+   DELETE FROM tags WHERE id IN (
+       SELECT tags.id FROM tags
+       LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
+       WHERE files_x_tags.files_id IS NULL);
+
+    VACUUM
+EOT
+#    print "SQL: $sql\n";
+    my @sql=split(/\n\n/, $sql);
+    $self->cmd($_) for (@sql);
 }
 
 sub relation_exists
@@ -278,9 +479,25 @@ sub relation_exists
 sub ok
 {
     my($self, $thing)=@_;
-    return(defined($thing) && length($thing));
+    return(defined($thing) && length($thing) && $thing =~ /\S+/);
 }
 
+# actually call the database
+sub cmd_sth
+{
+    my($self, $sql, @params)=@_;
+    my $sth=$self->{dbh}->prepare($sql);
+    my $idx=1;
+    for my $param (@params)
+    {
+       $param="" unless(defined($param));
+       $sth->bind_param($idx++, $param);
+    }
+    $sth->execute();
+    return $sth;
+}
+
+# pass cmd to db, ignore response
 sub cmd
 {
     my ($self, @args)=@_;
@@ -288,6 +505,7 @@ sub cmd
     $self->cmd_sth(@args);
 }
 
+# return one row
 sub cmd_onerow
 {
     my ($self, @args)=@_;
@@ -295,6 +513,7 @@ sub cmd_onerow
     return($sth->fetchrow_array());
 }
 
+# returns all rows
 sub cmd_rows
 {
     my ($self, @args)=@_;
@@ -302,6 +521,14 @@ sub cmd_rows
     return $sth->fetchall_arrayref();
 }
 
+# returns just the first column
+sub cmd_firstcol
+{
+    my ($self, @args)=@_;
+    return(map { $_->[0] } @{$self->cmd_rows(@args)});
+}
+
+# runs cmd, returns id of last insert
 sub cmd_id
 {
     my ($self, @args)=@_;
@@ -312,64 +539,85 @@ sub cmd_id
 sub last_insert_id
 {
     my $self=shift;
-    if($self->{postgres})
-    {
-       return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
-                                           { sequence => "seq" });
-    }
-    else
+    return $self->{dbh}->last_insert_id("","","","");
+}
+
+# lookup id of $name in $table, also matching on $parent if needed
+sub lookup_id
+{
+    my($self, $table, $name, $parent)=@_;
+    my $sql="SELECT id FROM $table where name=?";
+    my @args=($name);
+    if($parent)
     {
-       return $self->{dbh}->last_insert_id("","","","");
+       $sql .= " AND parents_id=?";
+       push(@args, $parent);
     }
+    my($id)=$self->cmd_onerow($sql, @args);
+    return $id;
 }
 
 __DATA__
 
 CREATE TABLE id3fs (
-    schema_version INTEGER
+    schema_version INTEGER,
+    last_update
 );
 
-CREATE TABLE files (
-    id INTEGER PRIMARY KEY,
-    name text
+CREATE TABLE paths (
+    id INTEGER,
+    name text,
+    PRIMARY KEY(id ASC)
 );
 
 CREATE TABLE artists (
-    id INTEGER PRIMARY KEY,
-    name text
+    id INTEGER,
+    name text,
+    PRIMARY KEY(id ASC)
 );
 
 CREATE TABLE albums (
-    id INTEGER PRIMARY KEY,
-    name text
+    id INTEGER,
+    name text,
+    PRIMARY KEY(id ASC)
 );
 
-CREATE TABLE tags (
-    id INTEGER PRIMARY KEY,
-    name text
+CREATE TABLE files (
+    id INTEGER,
+    name text,
+    artists_id,
+    albums_id,
+    paths_id,
+    PRIMARY KEY(id ASC),
+    FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
+    FOREIGN KEY(albums_id)  REFERENCES albums(id)  ON DELETE CASCADE ON UPDATE CASCADE,
+    FOREIGN KEY(paths_id)   REFERENCES paths(id)   ON DELETE CASCADE ON UPDATE CASCADE
 );
 
-CREATE TABLE tagvals (
-    id INTEGER PRIMARY KEY,
-    name text
+CREATE TABLE tags (
+    id INTEGER,
+    parents_id INTEGER,
+    name text,
+    PRIMARY KEY(id ASC)
 );
 
 CREATE TABLE files_x_tags (
     files_id INTEGER,
-    tags_id INTEGER
-);
-
-CREATE TABLE tags_x_tagvals (
     tags_id INTEGER,
-    tagvals_id INTEGER
+    FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
+    FOREIGN KEY(tags_id)  REFERENCES tags(id)  ON DELETE CASCADE ON UPDATE CASCADE
 );
 
-CREATE TABLE files_x_artists (
-    files_id INTEGER,
-    artists_id INTEGER
-);
+CREATE INDEX idx_fxt_both ON files_x_tags (files_id, tags_id)
 
-CREATE TABLE artists_x_albums (
-    artists_id INTEGER,
-    albums_id INTEGER
-);
+CREATE INDEX idx_fxt_tags ON files_x_tags (tags_id)
+
+CREATE INDEX idx_files_id_name ON files (id, name)
+
+CREATE INDEX idx_files_name_id ON files (name, id)
+
+CREATE INDEX idx_tags_id_parent_name ON tags (id, parents_id, name)
+
+CREATE INDEX idx_tags_parent_id_name ON tags (parents_id, id, name)
+
+CREATE INDEX idx_tags_name ON tags (name)