last_update: store in id3fs table, update when index is updated,
[id3fs.git] / lib / ID3FS / DB.pm
index 01b41d8..b6570ce 100644 (file)
@@ -4,6 +4,7 @@ use strict;
 use warnings;
 use DBI;
 use ID3FS::File;
+use Cwd;
 
 our $SCHEMA_VERSION=1;
 my $dbfile=".id3fs";
@@ -15,19 +16,19 @@ sub new
     my $self={};
     bless($self,$class);
 
-    my($dir, $init, $me)=@_;
-    $self->{dbpath}="$dir/$dbfile";
-    $self->{me}=$me;
+    $self->{me}=shift;
+    $self->{dbpath}=shift;
+    $self->{base}=shift;
+    $self->{fallbackdir}=shift;
 
-    my $exists=-f $self->{dbpath};
-
-    $self->{postgres}=0;
-
-    unless($self->{postgres})
+    if(!defined($self->{base}) &&
+       defined($self->{fallbackdir}) &&
+       -d $self->{fallbackdir})
     {
-       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);
+       $self->{base}=$self->{fallbackdir};
     }
+    $self->{dbpath}="$self->{base}/$dbfile" unless(defined($self->{dbpath}));
+    $self->{absbase}=Cwd::abs_path($self->{base});
 
     my $connectstr="dbi:SQLite:dbname=$self->{dbpath}";
     my ($user, $pass)=("", "");
@@ -37,20 +38,21 @@ sub new
        $user="ianb";
        $pass="foo";
     }
+    my $exists=-f $self->{dbpath};
     $self->{dbh}=DBI->connect($connectstr, $user, $pass,
                              { AutoCommit=>1 } );
     unless(defined($self->{dbh}))
     {
-       die("$me: DB Error: " . $DBI::errstr . "\n");
+       die("$self->{me}: DB Error: " . $DBI::errstr . "\n");
     }
 
-    if($init)
+    if($exists)
     {
-       $self->create();
+       $self->checkschema();
     }
     else
     {
-       $self->checkschema();
+       $self->create();
     }
 
     return $self;
@@ -71,18 +73,19 @@ sub create
     }
     else
     {
-       my %indexes=( "idx_files_id"  => "files(id)",
-                     "idx_fxt_both"  => "files_x_tags(files_id, tags_id)",
+       my %indexes=( "idx_files_id"  => "files (id)",
+                     "idx_fxt_both"  => "files_x_tags (files_id, tags_id)",
                      "idx_fxt_files" => "files_x_tags (files_id)",
                      "idx_fxt_tags"  => "files_x_tags (tags_id)",
                      "idx_tags_id"   => "tags (id)",
-                     "idx_tags_name" => "tags(name)" );
+                     "idx_tags_name" => "tags (name)");
        for my $index (keys %indexes)
        {
            $self->{dbh}->do("CREATE INDEX $index ON " . $indexes{$index});
        }
     }
-    $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
@@ -97,6 +100,20 @@ sub checkschema
     }
 }
 
+sub last_update
+{
+    my($self, $newval)=@_;
+    if(defined($newval))
+    {
+       $self->cmd("UPDATE id3fs SET last_update=?", $newval);
+    }
+    else
+    {
+       ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
+    }
+    return $newval;
+}
+
 sub cmd_sth
 {
     my($self, $sql, @params)=@_;
@@ -120,26 +137,25 @@ sub tags
        my $tags=$self->cmd_rows($sql);
        return(map { $_->[0]; } @$tags);
     }
-    my @file_ids=();
-    my @tag_ids=();
+    my @ids=();
 
     my $main_sql_start=("SELECT t2.name\n" .
                        "\tFROM (SELECT files_id FROM tags t1\n" .
                        "\t\tINNER JOIN files_x_tags ON t1.id=files_x_tags.tags_id\n" .
-                       "\t\tWHERE t1.id in \n\t\t\t(");
-    my $main_sql_mid=(")\n\t\t) AS fxt1\n" .
-                     "\tINNER JOIN files_x_tags fxt2 ON fxt1.files_id=fxt2.files_id\n" .
-                     "\tINNER JOIN tags t2 ON fxt2.tags_id=t2.id\n" .
+                       "\t\tWHERE t1.id in\n\t\t\t(");
+    my $main_sql_mid=(")\n\t\t) AS subselect\n" .
+                     "\tINNER JOIN files_x_tags ON subselect.files_id=files_x_tags.files_id\n" .
+                     "\tINNER JOIN tags t2 ON files_x_tags.tags_id=t2.id\n" .
                      "\tWHERE t2.id NOT IN (");
     my $main_sql_end=")\n\tGROUP BY t2.name;";
     while(my $constraint=shift @constraints)
     {
        print "CONSTRAINT: $constraint->{name}\n";
        my $cid=$constraint->{id};
-       push(@tag_ids, $cid);
+       push(@ids, $cid);
     }
-    @tag_ids = map( { "\"$_\""; } @tag_ids) unless($self->{postgres});
-    my $tagstr=join(", ", @tag_ids);
+    @ids = map( { "\"$_\""; } @ids) unless($self->{postgres});
+    my $tagstr=join(", ", @ids);
     my $sql = ($main_sql_start . $tagstr .
               $main_sql_mid   . $tagstr .
               $main_sql_end);
@@ -161,17 +177,203 @@ sub tag_values
     return(map { $_->[0]; } @$tags);
 }
 
-sub tag_id
+sub artists
 {
-    my($self, $tag)=@_;
-    my $sql='SELECT id FROM tags WHERE name=?';
-    my ($id)=$self->cmd_onerow($sql, $tag);
+    my($self, @constraints)=@_;
+    if(!@constraints) # /ALL
+    {
+       my $sql="SELECT DISTINCT name FROM artists;";
+       my $tags=$self->cmd_rows($sql);
+       return(map { $_->[0]; } @$tags);
+    }
+    my @ids=();
+    my $main_sql_start=("SELECT artists.name\n" .
+                       "\tFROM (SELECT files_id FROM tags\n" .
+                       "\t\tINNER JOIN files_x_tags ON tags.id=files_x_tags.tags_id\n" .
+                       "\t\tWHERE tags.id in\n\t\t\t(");
+    my $main_sql_end=(")\n\t\t) AS subselect\n" .
+                     "\tINNER JOIN files_x_artists ON subselect.files_id=files_x_artists.files_id\n" .
+                     "\tINNER JOIN artists ON artists.id=files_x_artists.artists_id\n" .
+                     "\n\tGROUP BY artists.name;");
+    while(my $constraint=shift @constraints)
+    {
+       print "CONSTRAINT: $constraint->{name}\n";
+       my $cid=$constraint->{id};
+       push(@ids, $cid);
+    }
+    @ids = map( { "\"$_\""; } @ids) unless($self->{postgres});
+    my $tagstr=join(", ", @ids);
+    my $sql = ($main_sql_start . $tagstr .
+              $main_sql_end);
+    print "SQL: $sql\n";
+    my $result=$self->cmd_rows($sql);
+    my @tagnames=map { $_->[0]; } @$result;
+    print "ARTISTS: ", join(', ', @tagnames), "\n";
+    return(@tagnames);
+}
+
+sub albums
+{
+    my($self, @constraints)=@_;
+    my @ids=();
+    # FIXME: rework PathElements
+    if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
+    {
+       return $self->artist_albums($constraints[$#constraints]->{id});
+    }
+    my $main_sql_start=("SELECT albums.name\n" .
+                       "\tFROM (SELECT files_id FROM tags\n" .
+                       "\t\tINNER JOIN files_x_tags ON tags.id=files_x_tags.tags_id\n" .
+                       "\t\tWHERE tags.id in\n\t\t\t(");
+    my $main_sql_end=(")\n\t\t) AS subselect\n" .
+                     "\tINNER JOIN files_x_albums ON subselect.files_id=files_x_albums.files_id\n" .
+                     "\tINNER JOIN albums ON albums.id=files_x_albums.albums_id\n" .
+                     "\n\tGROUP BY albums.name;");
+    while(my $constraint=shift @constraints)
+    {
+       print "CONSTRAINT: $constraint->{name}\n";
+       my $cid=$constraint->{id};
+       push(@ids, $cid);
+    }
+    @ids = map( { "\"$_\""; } @ids) unless($self->{postgres});
+    my $str=join(", ", @ids);
+    my $sql = ($main_sql_start . $str .
+              $main_sql_end);
+    print "SQL: $sql\n";
+    my $result=$self->cmd_rows($sql);
+    my @names=map { $_->[0]; } @$result;
+    print "ALBUMS: ", join(', ', @names), "\n";
+    return(@names);
+}
+
+sub artist_albums
+{
+    my($self, $artist_id)=@_;
+    my $sql=("SELECT albums.name FROM artists\n\t" .
+            "INNER JOIN artists_x_albums ON artists.id=artists_x_albums.artists_id\n\t" .
+            "INNER JOIN albums ON albums.id=artists_x_albums.albums_id\n\t" .
+            "WHERE artists.id=?\n\t" .
+            "GROUP BY albums.name\n");
+    print "ARTIST_ALBUMS SQL: $sql\n";
+    my $result=$self->cmd_rows($sql, $artist_id);
+    my @albums=map { $_->[0]; } @$result;
+    print "ALBUMS: ", join(', ', @albums), "\n";
+    return(@albums);
+}
+
+sub artist_tracks
+{
+    my($self, $artist_id)=@_;
+    my $sql=("SELECT files.name FROM artists\n\t" .
+            "INNER JOIN artists_x_files ON artists.id=files_x_artists.artists_id\n\t" .
+            "INNER JOIN files ON files.id=files_x_artists.files_id\n\t" .
+            "WHERE artists.id=?\n\t" .
+            "GROUP BY files.name\n");
+    print "ARTIST_TRACKS SQL: $sql\n";
+    my $result=$self->cmd_rows($sql, $artist_id);
+    my @names=map { $_->[0]; } @$result;
+    @names = map { s/.*\///; } @names;
+    print "ARTISTTRACKS: ", join(', ', @names), "\n";
+    return(@names);
+}
+
+sub album_tracks
+{
+    my($self, $album_id)=@_;
+    my $sql=("SELECT files.name FROM files\n\t" .
+            "INNER JOIN files_x_albums ON files.id=files_x_albums.files_id\n\t" .
+            "INNER JOIN albums ON albums.id=files_x_albums.albums_id\n\t" .
+            "WHERE albums.id=?\n\t" .
+            "GROUP BY files.name\n");
+    print "ALBUM_TRACKS SQL($album_id): $sql\n";
+    my $result=$self->cmd_rows($sql, $album_id);
+    my @names=map { $_->[0]; } @$result;
+    @names = map { s/.*\///; $_;} @names;
+    print "TRACKS: ", join(', ', @names), "\n";
+    return(@names);
+}
+
+sub tracks
+{
+    my($self, @constraints)=@_;
+    # FIXME: rework PathElements
+    if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Artist")
+    {
+       return $self->artist_tracks($constraints[$#constraints]->{id});
+    }
+    elsif(ref($constraints[$#constraints]) eq "ID3FS::PathElement::Album")
+    {
+       return $self->album_tracks($constraints[$#constraints]->{id});
+    }
+
+    my $main_sql_start=("SELECT files.name\n" .
+                       "\tFROM (SELECT files_id FROM tags\n" .
+                       "\t\tINNER JOIN files_x_tags ON tags.id=files_x_tags.tags_id\n" .
+                       "\t\tWHERE tags.id in\n\t\t\t(");
+    my $main_sql_end=(")\n\t\t) AS subselect\n" .
+                     "\tINNER JOIN files ON files.id=subselect.files_id" .
+                     "\tGROUP BY files.name;");
+    my @ids;
+    while(my $constraint=shift @constraints)
+    {
+       print "CONSTRAINT: $constraint->{name}\n";
+       my $cid=$constraint->{id};
+       push(@ids, $cid);
+    }
+    @ids = map( { "\"$_\""; } @ids) unless($self->{postgres});
+    my $str=join(", ", @ids);
+    my $sql = ($main_sql_start . $str .
+              $main_sql_end);
+    print "SQL: $sql\n";
+    my $result=$self->cmd_rows($sql);
+    my @names=map { $_->[0]; } @$result;
+    @names = map { s/.*\///; $_; } @names;
+    print "TRACKS: ", join(', ', @names), "\n";
+    return(@names);
+}
+
+sub filename
+{
+    my($self, @constraints)=@_;
+    if(ref($constraints[$#constraints]) eq "ID3FS::PathElement::File")
+    {
+       my $id=$constraints[$#constraints]->{id};
+       my $sql=("SELECT paths.name, files.name FROM files\n" .
+                "INNER JOIN paths_x_files ON files.id=paths_x_files.files_id\n" .
+                "INNER JOIN paths ON paths_x_files.paths_id=paths.id\n" .
+                "WHERE files.id=?\n" .
+                "GROUP BY paths.name, files.name");
+       print "FILENAME SQL: $sql\n";
+       my ($path, $name)=$self->cmd_onerow($sql, $id);
+       return($self->{absbase} . "/$path/$name");
+    }
+    die("DB::filename: unhandled case\n"); #FIXME
+}
+
+sub id
+{
+    my($self, $type, $val)=@_;
+    print "ID: $type $val\n";
+    my $sql="SELECT id FROM $type WHERE name=?";
+    my ($id)=$self->cmd_onerow($sql, $val);
     return($id);
 }
 
 sub add
 {
     my($self,$path)=@_;
+    my $relpath=$path;
+    $relpath =~ s/^\Q$self->{base}\E\/?//;
+    my($filepart,$pathpart);
+    if($path !~ /\//)
+    {
+       $pathpart='';
+       $filepart=$relpath;
+    }
+    else
+    {
+       ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
+    }
     my $file=ID3FS::File->new($path);
     return unless(defined($file));
     my $artist=$file->artist();
@@ -182,14 +384,40 @@ sub add
     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);
+    my $file_id=$self->add_to_table("files", $filepart);
+    my $path_id=$self->add_to_table("paths", $pathpart);
+    $self->add_relation("paths_x_files",
+                       { "paths_id" => $path_id,
+                         "files_id" => $file_id});
+
     for my $tag (keys %$tags)
     {
        $self->add_tag($file_id, $tag, $tags->{$tag});
     }
 
+    my $artist_id;
+    if($self->ok($artist))
+    {
+       $artist_id=$self->add_to_table("artists",  $artist);
+       $self->add_relation("files_x_artists",
+                           { "files_id" => $file_id,
+                             "artists_id" => $artist_id });
+    }
+
+    if($self->ok($album))
+    {
+       my $albums_id=$self->add_to_table("albums", $album);
+       $self->add_relation("files_x_albums",
+                           { "files_id" => $file_id,
+                             "albums_id" => $albums_id});
+       if($self->ok($artist))
+       {
+           $self->add_relation("artists_x_albums",
+                               { "artists_id" => $artist_id,
+                                 "albums_id" => $albums_id});
+       }
+    }
+
     if($self->ok($year))
     {
        $self->add_tag($file_id, "year", $year);
@@ -198,6 +426,7 @@ sub add
            $self->add_tag($file_id, "decade", "${1}0s");
        }
     }
+
     if($self->ok($v1genre))
     {
        $self->add_tag($file_id, "v1genre", $v1genre);
@@ -207,14 +436,6 @@ sub add
     {
        $self->add_tag($file_id, "haspic", undef);
     }
-
-    $self->add_relation("files_x_artists",
-                       { "files_id" => $file_id,
-                         "artists_id" => $artists_id });
-
-    $self->add_relation("artists_x_albums",
-                     { "artists_id" => $artists_id,
-                       "albums_id" => $albums_id});
 }
 
 sub add_tag
@@ -294,7 +515,7 @@ sub relation_exists
 sub ok
 {
     my($self, $thing)=@_;
-    return(defined($thing) && length($thing));
+    return(defined($thing) && length($thing) && $thing =~ /\S+/);
 }
 
 sub cmd
@@ -342,7 +563,8 @@ sub last_insert_id
 __DATA__
 
 CREATE TABLE id3fs (
-    schema_version INTEGER
+    schema_version INTEGER,
+    last_update
 );
 
 CREATE TABLE files (
@@ -350,6 +572,11 @@ CREATE TABLE files (
     name text
 );
 
+CREATE TABLE paths (
+    id INTEGER PRIMARY KEY,
+    name text
+);
+
 CREATE TABLE artists (
     id INTEGER PRIMARY KEY,
     name text
@@ -370,6 +597,11 @@ CREATE TABLE tagvals (
     name text
 );
 
+CREATE TABLE paths_x_files (
+    paths_id INTEGER,
+    files_id INTEGER
+);
+
 CREATE TABLE files_x_tags (
     files_id INTEGER,
     tags_id INTEGER
@@ -385,6 +617,11 @@ CREATE TABLE files_x_artists (
     artists_id INTEGER
 );
 
+CREATE TABLE files_x_albums (
+    files_id INTEGER,
+    albums_id INTEGER
+);
+
 CREATE TABLE artists_x_albums (
     artists_id INTEGER,
     albums_id INTEGER