tweak relativise
[id3fs.git] / lib / ID3FS / DB.pm
index 25ef83b..955e117 100644 (file)
@@ -3,10 +3,10 @@ package ID3FS::DB;
 use strict;
 use warnings;
 use DBI;
-use ID3FS::File;
+use ID3FS::AudioFile;
+use Cwd;
 
 our $SCHEMA_VERSION=1;
-
 my $dbfile=".id3fs";
 
 sub new
@@ -16,33 +16,91 @@ 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;
+    my $dbpath=shift;
+    $self->{base}=shift;
+    my $fallbackdir=shift;
 
-    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->{dbpath}=$self->find_db($init, $dbpath, $fallbackdir);
+    return undef unless($self->{dbpath});
+    $self->{absbase}=Cwd::abs_path($self->{base});
 
-    $self->{dbh}=DBI->connect("dbi:SQLite:dbname=$self->{dbpath}","","",
+    my $connectstr="dbi:SQLite:dbname=$self->{dbpath}";
+    my ($user, $pass)=("", "");
+    if($self->{postgres})
+    {
+       $connectstr="dbi:Pg:dbname=id3fs";
+       $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();
     }
-
+    $self->enable_foreign_keys();
     return $self;
 }
 
+sub find_db
+{
+    my($self, $init, $dbpath, $fallbackdir)=@_;
+    my $file=undef;
+    my $base=undef;
+    if(defined($dbpath))
+    {
+       $file=$dbpath;
+    }
+    if(defined ($self->{base}))
+    {
+       $file="$self->{base}/$dbfile" unless defined($file);
+       $base=$self->{base};
+    }
+    elsif(defined($fallbackdir) && -d $fallbackdir)
+    {
+       my $path=Cwd::abs_path($fallbackdir);
+       do
+       {
+           $file="$path/$dbfile";
+           $base=$path;
+           $path=~s/(.*)\/.*/$1/;
+       }
+       while(! -f $file && length($path) && -d $path);
+       if(! -f $file)
+       {
+           $file="$fallbackdir/$dbfile";
+           $base=$fallbackdir;
+       }
+    }
+    else
+    {
+       print "$self->{me}: $fallbackdir: not a directory\n";
+       return undef;
+    }
+    if(!-f $file && !$init)
+    {
+       print "$self->{me}: db not found at $file\n";
+       return undef;
+    }
+    $self->{base}=$base;
+    return $file;
+}
+
+sub base_dir { return shift->{base}; }
+
 sub create
 {
     my($self,$name)=@_;
@@ -52,7 +110,25 @@ sub create
     {
        $self->{dbh}->do($cmd);
     }
-    $self->cmd("INSERT INTO id3fs (schema_version) VALUES (?)", $SCHEMA_VERSION);
+    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, last_update) VALUES (?, ?)",
+              $SCHEMA_VERSION, time());
 }
 
 sub checkschema
@@ -67,43 +143,349 @@ 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 bare_tags
+{
+    my($self)=@_;
+    my $sql=("SELECT tags.name FROM tags\n" .
+            "WHERE tags.parents_id=''\n" .
+            "GROUP BY tags.name\n");
+    my @names=$self->cmd_firstcol($sql);
+    return (@names);
+}
+
+sub tags_with_values
+{
+    # FIXME: only shows one level of tag depth
+    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");
+#    print "SQL: $sql\n";
+    my $result=$self->cmd_rows($sql);
+    my $tags={};
+    for my $pair (@$result)
+    {
+       push(@{$tags->{$pair->[0]}}, $pair->[1]);
+    }
+    return $tags;
+}
+
+sub tag_has_values
+{
+    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 relativise
+{
+    my($self, $path, $name, $mountpoint)=@_;
+    my $id3fs_path=$self->{dbpath};
+    $id3fs_path=~s/(.*)\/.*/$1/;
+    my $rpath="$self->{absbase}/$path";
+    my $vpath="$mountpoint/$id3fs_path";
+    my @path=split(/\//,$rpath);
+    my @rel=split(/\//,$vpath);
+    #absolute paths have empty first element due to leading /
+    shift(@path) if($path[0] eq "");
+    shift(@rel)  if($rel[0]  eq "");
+    if($path[0] ne $rel[0])
+    {
+       #no path in common, return absolute
+       print "FAIL: NO PATHS IN COMMON\n";
+       return $name;
+    }
+    # f: /home/foo/bar/baz.mp3
+    # r: /home/ianb/music/albums
+    while(@path && @rel && ($path[0] eq $rel[0]))
+    {
+       shift(@path);
+       shift(@rel);
+#      print "POP ";
+    }
+#    print "\n";
+    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();
-#FIXME
-#    my $haspic=$file->haspic();
-    my $tags=$file->tags();
-    print "$path:\n";
-    for my $thing  (qw(artist album v1genre year audiotype))
+    my $audiotype=$file->audiotype();
+    my @tags=$file->tags();
+    my $haspic=$file->haspic();
+
+    $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))
+    {
+       print "$self->{me}: $path: no album tag defined\n";
+    }
+
+    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 });
+    for my $tag (@tags)
+    {
+       $self->add_tag($file_id, @$tag);
+    }
+
+    $year="UNKNOWN" unless($self->ok($year));
+    $self->add_tag($file_id, "year", $year);
+    if($year=~/^(\d\d\d)\d$/)
     {
-       no strict 'refs';
-       my $thingval=$file->$thing();
-       use strict 'refs';
-       print("\t$thing: ", $thingval, "\n") if(defined($thingval));
+       $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);
+    }
+
+    if($haspic)
+    {
+       $self->add_tag($file_id, "haspic", undef);
     }
 }
 
+sub add_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($value) && length($value))
+    {
+       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 $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))
+       {
+           push(@fields, sort keys(%$extradata));
+       }
+       $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);
+    }
+    return $id;
+}
+
+sub add_relation
+{
+    my ($self, $relname, $fields)=@_;
+    return if($self->relation_exists($relname, $fields));
+    my $sql="INSERT INTO $relname (";
+    $sql .= join(", ", sort keys(%$fields));
+    $sql .= ") VALUES (";
+    $sql .= join(", ", map { "?"; } sort keys(%$fields));
+    $sql .= ");";
+    $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
+}
+
+sub files_in
+{
+    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");
+#    print "files_in: SQL: $sql\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 ORDER BY name\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)");
+#    print "SQL: \n", $sql, "\n";
+    $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
+{
+    my ($self, $relname, $fields)=@_;
+    my $sql="SELECT count(1) FROM $relname WHERE ";
+    my @exprs=();
+    my @vals=();
+    for my $field (keys %$fields)
+    {
+       push(@exprs,$field);
+       push(@vals,$fields->{$field});
+    }
+    $sql .= join(' AND ', map { "$_=?"; } @exprs);
+    my ($ret)=$self->cmd_onerow($sql, @vals);
+    return $ret;
+}
+
+sub ok
+{
+    my($self, $thing)=@_;
+    return(defined($thing) && length($thing) && $thing =~ /\S+/);
+}
+
+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;
+}
+
 sub cmd
 {
     my ($self, @args)=@_;
@@ -118,34 +500,102 @@ 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_firstcol
+{
+    my ($self, @args)=@_;
+    return(map { $_->[0] } @{$self->cmd_rows(@args)});
+}
+
+sub cmd_id
+{
+    my ($self, @args)=@_;
+    $self->cmd_sth(@args);
+    return($self->last_insert_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("","","","");
+    }
+}
+
+sub lookup_id
+{
+    my($self, $table, $name, $parent)=@_;
+    my $sql="SELECT id FROM $table where name=?";
+    my @args=($name);
+    if($parent)
+    {
+       $sql .= " AND parents_id=?";
+       push(@args, $parent);
+    }
+    my($id)=$self->cmd_onerow($sql, @args);
+    return $id;
+}
+
 __DATA__
 
 CREATE TABLE id3fs (
-    schema_version
+    schema_version INTEGER,
+    last_update
 );
 
-CREATE TABLE files (
-    id INTEGER PRIMARY KEY,
-    path
+CREATE TABLE paths (
+    id INTEGER,
+    name text,
+    PRIMARY KEY(id DESC)
 );
 
-CREATE TABLE tags (
-    id INTEGER PRIMARY KEY,
-    name
+CREATE TABLE artists (
+    id INTEGER,
+    name text,
+    PRIMARY KEY(id DESC)
 );
 
-CREATE TABLE tagvalues (
-    id INTEGER PRIMARY KEY,
-    name
+CREATE TABLE albums (
+    id INTEGER,
+    name text,
+    PRIMARY KEY(id DESC)
 );
 
-CREATE TABLE files_x_tags (
-    files_id,
-    tags_id
+CREATE TABLE files (
+    id INTEGER,
+    name text,
+    artists_id,
+    albums_id,
+    paths_id,
+    PRIMARY KEY(id DESC),
+    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 tags_x_tagvalues (
-    tags_id,
-    tagvalues_id
+CREATE TABLE tags (
+    id INTEGER,
+    parents_id INTEGER,
+    name text,
+    PRIMARY KEY(id DESC)
+);
+
+CREATE TABLE files_x_tags (
+    files_id INTEGER,
+    tags_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
 );