fix album_tracks
[id3fs.git] / lib / ID3FS / DB.pm
index af325ba..5217484 100644 (file)
@@ -4,9 +4,9 @@ use strict;
 use warnings;
 use DBI;
 use ID3FS::File;
+use Cwd;
 
 our $SCHEMA_VERSION=1;
-
 my $dbfile=".id3fs";
 
 sub new
@@ -17,14 +17,30 @@ sub new
     bless($self,$class);
 
     my($dir, $init, $me)=@_;
+    $self->{base}=$dir;
+    $self->{absbase}=Cwd::abs_path($dir);
     $self->{dbpath}="$dir/$dbfile";
     $self->{me}=$me;
 
     my $exists=-f $self->{dbpath};
-    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->{dbh}=DBI->connect("dbi:SQLite:dbname=$self->{dbpath}","","",
+    $self->{postgres}=0;
+
+    unless($self->{postgres})
+    {
+       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);
+    }
+
+    my $connectstr="dbi:SQLite:dbname=$self->{dbpath}";
+    my ($user, $pass)=("", "");
+    if($self->{postgres})
+    {
+       $connectstr="dbi:Pg:dbname=id3fs";
+       $user="ianb";
+       $pass="foo";
+    }
+    $self->{dbh}=DBI->connect($connectstr, $user, $pass,
                              { AutoCommit=>1 } );
     unless(defined($self->{dbh}))
     {
@@ -52,6 +68,23 @@ sub create
     {
        $self->{dbh}->do($cmd);
     }
+    if($self->{postgres})
+    {
+       $self->cmd("CREATE SEQUENCE seq");
+    }
+    else
+    {
+       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)");
+       for my $index (keys %indexes)
+       {
+           $self->{dbh}->do("CREATE INDEX $index ON " . $indexes{$index});
+       }
+    }
     $self->cmd("INSERT INTO id3fs (schema_version) VALUES (?)", $SCHEMA_VERSION);
 }
 
@@ -81,9 +114,252 @@ sub cmd_sth
     return $sth;
 }
 
+sub tags
+{
+    my($self, @constraints)=@_;
+    if(!@constraints) # /
+    {
+       my $sql="SELECT DISTINCT name FROM tags;";
+       my $tags=$self->cmd_rows($sql);
+       return(map { $_->[0]; } @$tags);
+    }
+    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 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(@ids, $cid);
+    }
+    @ids = map( { "\"$_\""; } @ids) unless($self->{postgres});
+    my $tagstr=join(", ", @ids);
+    my $sql = ($main_sql_start . $tagstr .
+              $main_sql_mid   . $tagstr .
+              $main_sql_end);
+    print "SQL: $sql\n";
+    my $result=$self->cmd_rows($sql);
+    my @tagnames=map { $_->[0]; } @$result;
+    print "SUBNAMES: ", join(', ', @tagnames), "\n";
+    return(@tagnames);
+}
+
+sub tag_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);
+}
+
+sub artists
+{
+    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();
@@ -94,14 +370,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);
@@ -110,6 +412,7 @@ sub add
            $self->add_tag($file_id, "decade", "${1}0s");
        }
     }
+
     if($self->ok($v1genre))
     {
        $self->add_tag($file_id, "v1genre", $v1genre);
@@ -119,14 +422,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
@@ -152,6 +447,7 @@ sub add_to_table
     unless(defined($id))
     {
        my $sql="INSERT INTO $table (";
+       $sql .= "id, " if($self->{postgres});
        my @fields=qw(name);
        if(defined($extradata))
        {
@@ -159,6 +455,7 @@ 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);
@@ -204,7 +501,7 @@ sub relation_exists
 sub ok
 {
     my($self, $thing)=@_;
-    return(defined($thing) && length($thing));
+    return(defined($thing) && length($thing) && $thing =~ /\S+/);
 }
 
 sub cmd
@@ -221,6 +518,13 @@ sub cmd_onerow
     return($sth->fetchrow_array());
 }
 
+sub cmd_rows
+{
+    my ($self, @args)=@_;
+    my $sth=$self->cmd_sth(@args);
+    return $sth->fetchall_arrayref();
+}
+
 sub cmd_id
 {
     my ($self, @args)=@_;
@@ -231,56 +535,79 @@ sub cmd_id
 sub last_insert_id
 {
     my $self=shift;
-    return $self->{dbh}->last_insert_id("","","","");
+    if($self->{postgres})
+    {
+       return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
+                                           { sequence => "seq" });
+    }
+    else
+    {
+       return $self->{dbh}->last_insert_id("","","","");
+    }
 }
 
 __DATA__
 
 CREATE TABLE id3fs (
-    schema_version
+    schema_version INTEGER
 );
 
 CREATE TABLE files (
     id INTEGER PRIMARY KEY,
-    name
+    name text
+);
+
+CREATE TABLE paths (
+    id INTEGER PRIMARY KEY,
+    name text
 );
 
 CREATE TABLE artists (
     id INTEGER PRIMARY KEY,
-    name
+    name text
 );
 
 CREATE TABLE albums (
     id INTEGER PRIMARY KEY,
-    name
+    name text
 );
 
 CREATE TABLE tags (
     id INTEGER PRIMARY KEY,
-    name
+    name text
 );
 
 CREATE TABLE tagvals (
     id INTEGER PRIMARY KEY,
-    name
+    name text
+);
+
+CREATE TABLE paths_x_files (
+    paths_id INTEGER,
+    files_id INTEGER
 );
 
 CREATE TABLE files_x_tags (
-    files_id,
-    tags_id
+    files_id INTEGER,
+    tags_id INTEGER
 );
 
 CREATE TABLE tags_x_tagvals (
-    tags_id,
-    tagvals_id
+    tags_id INTEGER,
+    tagvals_id INTEGER
 );
 
 CREATE TABLE files_x_artists (
-    files_id,
-    artists_id
+    files_id INTEGER,
+    artists_id INTEGER
+);
+
+CREATE TABLE files_x_albums (
+    files_id INTEGER,
+    albums_id INTEGER
 );
 
 CREATE TABLE artists_x_albums (
-    artists_id,
-    albums_id
+    artists_id INTEGER,
+    albums_id INTEGER
 );