PathElement::*: implement id() method
[id3fs.git] / lib / ID3FS / Path.pm
index 1babe7d..919d28a 100644 (file)
@@ -2,17 +2,23 @@ package ID3FS::Path;
 
 use strict;
 use warnings;
-use feature 'switch';
 use ID3FS::PathElement::Artist;
 use ID3FS::PathElement::Album;
 use ID3FS::PathElement::Boolean;
 use ID3FS::PathElement::File;
 use ID3FS::PathElement::Tag;
 use ID3FS::PathElement::Tagval;
+use ID3FS::Path::Node;
 
 our ($STATE_INVALID, $STATE_ROOT, $STATE_TAG, $STATE_TAGVAL,
-     $STATE_BOOLEAN, $STATE_ARTISTS, $STATE_ALBUMS, $STATE_TRACKLIST,
-     $STATE_FILE)=(0..8);
+     $STATE_BOOLEAN, $STATE_ALBUMS, $STATE_TRACKLIST,
+     $STATE_FILE, $STATE_ALL)=(0..8);
+
+our %priorities=( "OR" => 0, "AND" => 1, "NOT" => 2 );
+
+our $PATH_ALLTRACKS="TRACKS";
+our $PATH_NOARTIST="NOARTIST";
+our $PATH_NOALBUM="NOALBUM";
 
 sub new
 {
@@ -21,24 +27,36 @@ sub new
     my $self={};
     bless($self,$class);
 
+    $self->{elements}=[];
     $self->{db}=shift;
     $self->{path}=shift;
+    $self->{verbose}=shift;
+    $self->{maxtagdepth}=shift;
+    $self->{curtagdepth}=0;
+    $self->{path} =~ s/\/\//\//g; # drop doubled slashes
+
     $self->parse();
-    print "STATE: ", $self->state(), "\n";
+#    print "STATE: ", $self->state(), "\n";
     return $self;
 }
 
 sub isdir
 {
     my($self)=@_;
-    if(($self->state() eq $STATE_FILE) ||
-       ($self->state() eq $STATE_INVALID))
+    if(($self->state() == $STATE_FILE) ||
+       ($self->state() == $STATE_INVALID))
     {
        return 0;
     }
     return 1;
 }
 
+sub isfile
+{
+    my($self)=@_;
+    return($self->state() == $STATE_FILE);
+}
+
 sub isvalid
 {
     my($self)=@_;
@@ -47,10 +65,10 @@ sub isvalid
 
 sub dest
 {
-    my($self)=@_;
+    my($self, $mountpoint)=@_;
     if($self->state() == $STATE_FILE)
     {
-       return $self->{db}->filename(@{$self->{elements}});
+       return $self->filename($mountpoint);
     }
     return "ERROR"; #should never happen?
 }
@@ -59,38 +77,58 @@ sub dirents
 {
     my($self)=@_;
     my @dents=();
-    given($self->state())
+    my @fents=();
+    my $state=$self->state();
+#    print "DIRENTS: STATE: $state\n";
+#    print "DIRENTS: FILE: $self->{path}\n";
+    if($state==$STATE_ALL)
     {
-       when($STATE_TAG)
-       {
-           @dents=qw(AND ARTISTS ALBUMS TRACKS);
-       }
-       when($STATE_BOOLEAN)
-       {
-           @dents=$self->{db}->tags(@{$self->{elements}});
-       }
-       when($STATE_ROOT)
-       {
-           @dents=("ALL", $self->{db}->tags(@{$self->{elements}}));
-       }
-       when($STATE_ARTISTS)
-       {
-           @dents=$self->{db}->artists(@{$self->{elements}});
-       }
-       when($STATE_ALBUMS)
+       @dents=($PATH_ALLTRACKS, $PATH_NOARTIST, $self->artists());
+    }
+    elsif($state==$STATE_TAG || $state==$STATE_TAGVAL)
+    {
+       if($state==$STATE_TAG && $self->at("tag") &&
+          $self->{db}->tag_has_values($self->tail()->id()))
        {
-           @dents=$self->{db}->albums(@{$self->{elements}});
+           @dents=$self->tags();
        }
-       when($STATE_TRACKLIST)
+       else
        {
-           @dents=$self->{db}->tracks(@{$self->{elements}});
+           if($self->{maxtagdepth} && ($self->{curtagdepth} < $self->{maxtagdepth}))
+           {
+               @dents=qw(AND OR);
+           }
+           push(@dents, $self->filter($PATH_ALLTRACKS, $PATH_NOARTIST));
+           push(@dents, $self->artists());
        }
-       default
+    }
+    elsif($state==$STATE_BOOLEAN)
+    {
+       my $parent=$self->tail();
+       unless($self->is("boolean", $parent) &&
+              $parent->{name} eq "NOT")
        {
-           print "DIRENTS: UNHANDLED STATE: $_\n";
+           @dents=("NOT");
        }
+       push(@dents,$self->tags());
+    }
+    elsif($state==$STATE_ROOT)
+    {
+       @dents=(qw(ALL NOT), $self->tags());
+    }
+    elsif($state==$STATE_ALBUMS)
+    {
+       @dents=($self->filter($PATH_ALLTRACKS, $PATH_NOALBUM), $self->albums());
+    }
+    elsif($state==$STATE_TRACKLIST)
+    {
+       @fents=$self->tracks();
     }
-    return(@dents);
+    else
+    {
+       print "DIRENTS: UNHANDLED STATE: $state\n";
+    }
+    return(\@dents, \@fents);
 }
 
 sub parse
@@ -98,148 +136,150 @@ sub parse
     my($self)=@_;
     @{$self->{components}}=split(/\//, $self->{path});
     shift @{$self->{components}}; # drop empty field before leading /
-    print "PATH: $self->{path}\n";
-#    print "COMPONENTS: ", join(' | ', @{$self->{components}}), "\n";
+#    print "PATH: $self->{path}\n";
     $self->state($STATE_ROOT);
     return if($self->{path} eq "/");
     my @parts=@{$self->{components}};
     my($tag, $tagval);
     $self->{elements}=[];
-    while(my $name=shift @parts)
+    $self->{bare_not}=0;
+    $self->{in_all}=0;
+    my $root_not=0;
+    my $tags_seen=0;
+    while(defined(my $name=shift @parts))
     {
-       print "NAME: $name\n";
-       given($self->state())
+#      print "NAME: $name\n";
+       my $state=$self->state();
+       if($state==$STATE_INVALID)
        {
-           when($STATE_INVALID)
+#          print "SM: INVALID: $name\n";
+           return;
+       }
+       elsif($state==$STATE_ROOT)
+       {
+#          print "SM: ROOT: $name\n";
+           if($name eq "ALL")
            {
-               print "SM: INVALID: $name\n";
-               return;
+               $self->{in_all}=1;
+               $self->state($STATE_ALL);
            }
-           when($STATE_ROOT)
+           elsif($name eq "NOT")
            {
-               print "SM: ROOT: $name\n";
-               if($name eq "ALL")
-               {
-                   $self->state($STATE_ARTISTS);
-               }
-               else
-               {
-                   $tag=ID3FS::PathElement::Tag->new($self->{db}, $name);
-                   if($tag)
-                   {
-                       push(@{$self->{elements}}, $tag);
-                       $self->state($STATE_TAG);
-                   }
-                   else
-                   {
-                       $self->state($STATE_INVALID);
-                   }
-               }
+               $root_not=1;
+               push(@{$self->{elements}}, ID3FS::PathElement::Boolean->new($self->{db}, $name));
+               $self->state($STATE_BOOLEAN);
            }
-           when($STATE_TAG)
+           else
            {
-               print "SM: TAG: $name\n";
-               given($name)
-               {
-                   when("AND")
-                   {
-                       $self->state($STATE_BOOLEAN);
-#                      push(@{$self->{elements}}, ID3FS::PathElement::Boolean->new($name));
-                   }
-                   when("ARTISTS")
-                   {
-                       $self->state($STATE_ARTISTS);
-                   }
-                   when("ALBUMS")
-                   {
-                       $self->state($STATE_ALBUMS);
-                   }
-                   when("TRACKS")
-                   {
-                       $self->state($STATE_TRACKLIST);
-                   }
-
-#                  when("OR")  { ; }
-#                  when("NOT") { ; }
-                   default
-                   {
-                       $self->state($STATE_INVALID);
-                   }
-               }
-           }
-
-           when(255) #FIXME - dead code
-           {
-               print "SM: WANTMORE: $name\n";
                $tag=ID3FS::PathElement::Tag->new($self->{db}, $name);
                if($tag)
                {
                    push(@{$self->{elements}}, $tag);
-#                  $self->state($STATE_TAG);
+                   $tags_seen++;
+                   $self->state($STATE_TAG);
                }
                else
                {
                    $self->state($STATE_INVALID);
                }
-               my @valid_tagvals=$self->{db}->tag_values($tag);
-               print "TAGVALUES: $name: ", join(', ', @valid_tagvals), "\n";
-               if(@valid_tagvals)
+           }
+       }
+       elsif($state==$STATE_TAG || $state==$STATE_TAGVAL)
+       {
+           my $tag=$self->tail();
+#          print "SM: TAG/TAGVAL($state): $name\n";
+           if($state==$STATE_TAG && $self->is("tag", $tag) &&
+              $self->{db}->tag_has_values($tag->id()))
+           {
+#              print "Parsing: parent: $tag->id()\n";
+               my $tagval=ID3FS::PathElement::Tag->new($self->{db}, $name, $tag->id());
+               if(defined($tagval))
                {
-                   if(grep { $name eq $_; } @valid_tagvals)
-                   {
-                       print "TAGVAL VALID\n";
-                       $self->state($STATE_TAGVAL);
-                       push(@{$self->{elements}}, ID3FS::PathElement::Tagval($name));
-                   }
-                   else
-                   {
-                       print "ERROR: unknown tagval: $tagval\n";
-                       $self->state($STATE_INVALID);
-                   }
+                   $self->state($STATE_TAGVAL);
+                   # stay in tag state
+                   push(@{$self->{elements}}, $tagval);
                }
                else
                {
                    $self->state($STATE_INVALID);
                }
            }
-           when($STATE_TAGVAL)
+           elsif($name eq $PATH_ALLTRACKS)
            {
-               print "SM: TAGVAL: $name\n";
+               $self->state($STATE_TRACKLIST);
            }
-           when($STATE_BOOLEAN)
+           elsif($name eq $PATH_NOARTIST)
            {
-               print "SM: BOOLEAN: $name\n";
-               my $tag=ID3FS::PathElement::Tag->new($self->{db}, $name);
-               if($tag)
+               $self->state($STATE_TRACKLIST);
+           }
+           elsif($name eq "AND")
+           {
+               $self->state($STATE_BOOLEAN);
+               push(@{$self->{elements}}, ID3FS::PathElement::Boolean->new($self->{db}, $name));
+           }
+           elsif($name eq "OR")
+           {
+               $self->state($STATE_BOOLEAN);
+               push(@{$self->{elements}}, ID3FS::PathElement::Boolean->new($self->{db}, $name));
+           }
+           else
+           {
+               my $artist=ID3FS::PathElement::Artist->new($self->{db}, $name);
+               if($artist)
                {
-                   push(@{$self->{elements}}, $tag);
-                   $self->state($STATE_TAG);
+                   push(@{$self->{elements}}, $artist);
+                   $self->state($STATE_ALBUMS);
                }
                else
                {
                    $self->state($STATE_INVALID);
                }
            }
-           when($STATE_ARTISTS)
+       }
+       elsif($state==$STATE_BOOLEAN)
+       {
+#          print "SM: BOOLEAN: $name\n";
+           my $parent=$self->tail();
+           my $allownot=1;
+           if($self->is("boolean", $parent) &&
+              $parent->{name} eq "NOT")
            {
-               print "SM: ARTIST: $name\n";
-               my $artist=ID3FS::PathElement::Artist->new($self->{db}, $name);
-               push(@{$self->{elements}}, $tag);
-               if($artist)
+               $allownot=0;
+           }
+           if($allownot && $name eq "NOT")
+           {
+               $self->state($STATE_BOOLEAN);
+               push(@{$self->{elements}}, ID3FS::PathElement::Boolean->new($self->{db}, $name));
+           }
+           else
+           {
+               my $tag=ID3FS::PathElement::Tag->new($self->{db}, $name);
+               if($tag)
                {
-                   push(@{$self->{elements}}, $artist);
-                   $self->state($STATE_ALBUMS);
+                   push(@{$self->{elements}}, $tag);
+                   $tags_seen++;
+                   $self->state($STATE_TAG);
                }
                else
                {
                    $self->state($STATE_INVALID);
                }
            }
-           when($STATE_ALBUMS)
+       }
+       elsif($state==$STATE_ALBUMS)
+       {
+#          print "SM: ALBUM: $name\n";
+           if($name eq $PATH_ALLTRACKS)
+           {
+               $self->state($STATE_TRACKLIST);
+           }
+           elsif($name eq $PATH_NOALBUM)
+           {
+               $self->state($STATE_TRACKLIST);
+           }
+           else
            {
-               print "SM: ALBUM: $name\n";
                my $album=ID3FS::PathElement::Album->new($self->{db}, $name);
-               push(@{$self->{elements}}, $album);
                if($album)
                {
                    push(@{$self->{elements}}, $album);
@@ -250,41 +290,600 @@ sub parse
                    $self->state($STATE_INVALID);
                }
            }
-           when($STATE_TRACKLIST)
+       }
+       elsif($state==$STATE_TRACKLIST)
+       {
+#          print "SM: TRACKLIST: $name\n";
+           my $track=ID3FS::PathElement::File->new($self->{db}, $name);
+           if($track)
            {
-               print "SM: TRACKS: $name\n";
-               my $track=ID3FS::PathElement::File->new($self->{db}, $name);
                push(@{$self->{elements}}, $track);
-               if($track)
+               $self->state($STATE_FILE);
+           }
+           else
+           {
+               $self->state($STATE_INVALID);
+           }
+       }
+       elsif($state==$STATE_FILE)
+       {
+#          print "SM: FILE: $name\n";
+           # Can't have anything after a filename
+           $self->state($STATE_INVALID);
+       }
+       elsif($state==$STATE_ALL)
+       {
+           if($name eq $PATH_ALLTRACKS)
+           {
+               $self->state($STATE_TRACKLIST);
+           }
+           elsif($name eq $PATH_NOARTIST)
+           {
+               $self->state($STATE_TRACKLIST);
+           }
+           else
+           {
+               my $artist=ID3FS::PathElement::Artist->new($self->{db}, $name);
+               if($artist)
                {
-                   push(@{$self->{elements}}, $track);
-                   $self->state($STATE_FILE);
+                   push(@{$self->{elements}}, $artist);
+                   $self->state($STATE_ALBUMS);
                }
                else
                {
                    $self->state($STATE_INVALID);
                }
            }
-           when($STATE_FILE)
+       }
+       else
+       {
+           print "SM: ERROR: UNKNOWN STATE: $self->{state}\n";
+           $self->state($STATE_INVALID);
+       }
+    }
+
+    if($root_not && ($tags_seen < 2))
+    {
+       $self->{bare_not}=1;
+    }
+
+    # remove trailing boolean
+    my @elements=@{$self->{elements}};
+    while(@elements && $self->is("boolean", $elements[$#elements]))
+    {
+       pop @elements;
+    }
+    # sort elements by precedence
+    @elements=$self->sort_elements(@elements);
+    $self->{tagtree}=$self->elements_to_tree(\@elements);
+    if($self->{tagtree})
+    {
+       ($self->{sqlconditions},
+        $self->{joins}) = $self->{tagtree}->to_sql();
+#      print "TREE: ",  $self->{tagtree}->print(), "\n";
+#      print("SQL CONDITION(", scalar(@{$self->{joins}}), "): ",
+#            $self->{sqlconditions}, "\n");
+#      use Data::Dumper;
+#      print Dumper $self->{tagtree};
+    }
+}
+
+sub state
+{
+    my($self, $newstate)=@_;
+    if(defined($newstate))
+    {
+       $self->{state}=$newstate;
+       $self->{curtagdepth}++ if($newstate == $STATE_TAG);
+    }
+    return $self->{state};
+}
+
+sub elements_to_tree
+{
+    my($self, $elements)=@_;
+    return undef unless(@$elements);
+    my ($left, $right, $op)=(undef, undef, undef);
+    my $thing=pop @$elements;
+    if($self->is("boolean", $thing))
+    {
+       my $op=$thing;
+       $right=$self->elements_to_tree($elements);
+       if($op->{name} ne "NOT")
+       {
+           $left=$self->elements_to_tree($elements);
+       }
+       return ID3FS::Path::Node->new($left, $op, $right);
+    }
+    else
+    {
+       return ID3FS::Path::Node->new($thing);
+    }
+}
+
+# Dijkstra's shunting-yard algorithm
+sub sort_elements
+{
+    my ($self, @input)=@_;
+    my @opstack=();
+    my @output=();
+#    print "INPUT: ", join(', ', map { $_->{name}; } @input), "\n";
+    while(my $thing = shift @input)
+    {
+       if($self->is("tag", $thing))
+       {
+           # Handle tag values by dropping parent
+           if(@input && $self->is("tag", $input[0]))
            {
-               print "SM: FILE: $name\n";
-               # Can't have anything after a filename
-               $self->state($STATE_INVALID);
+               $thing=shift @input;
            }
-           default
+           push(@output, $thing);
+       }
+       elsif($self->is("boolean", $thing))
+       {
+           # bool
+           while(@opstack &&
+                 ($priorities{$thing->{name}} <= $priorities{$opstack[$#opstack]->{name}}))
            {
-               print "SM: ERROR: UNKNOWN STATE: $self->{state}\n";
-               $self->state($STATE_INVALID);
+               push(@output, pop(@opstack));
            }
+           push(@opstack, $thing);
        }
     }
+    while(@opstack)
+    {
+       push(@output, pop(@opstack));
+    }
+#    print "STACK: ", join(', ', map { $_->{name}; } @output), "\n";
+    return @output;
 }
 
-sub state
+sub used_tags
 {
-    my($self, $newstate)=@_;
-    $self->{state}=$newstate if(defined($newstate));
-    return $self->{state};
+    my($self)=@_;
+    return() unless(defined($self->{tagtree}));
+    return($self->{tagtree}->used_tags());
+}
+
+sub expecting_values
+{
+    my($self)=@_;
+    my $tail=$self->tail();
+    if($self->is("tag", $tail))
+    {
+       return($self->{db}->tag_has_values($tail->id()));
+    }
+}
+
+sub trailing_tag_id
+{
+    my($self)=@_;
+    my $tail=$self->tail();
+    if($self->is("tag", $tail))
+    {
+       return($tail->id());
+    }
+    return undef;
+}
+
+sub trailing_tag_parent
+{
+    my($self)=@_;
+    my $tail=$self->tail();
+    if($self->is("tag", $tail))
+    {
+       return($tail->{parents_id});
+    }
+    return undef;
+}
+
+sub tail
+{
+    my($self)=@_;
+    return($self->{elements}->[$#{$self->{elements}}]);
+}
+
+sub at
+{
+    my($self, $type)=@_;
+    return($self->is($type, $self->tail()));
+}
+
+sub is
+{
+    my($self, $type, $thing)=@_;
+    return 0 unless($thing);
+    my $ref=ref($thing);
+    my $typestr="ID3FS::PathElement::" . ucfirst($type);
+    return 1 if($ref eq $typestr);
+    return 0;
+}
+
+# the one before last
+sub tail_parent
+{
+    my($self)=@_;
+    return($self->{elements}->[($#{$self->{elements}}) - 1]);
+}
+
+######################################################################
+
+sub tags
+{
+    my($self)=@_;
+    if(!$self->{tagtree}) # / or /NOT
+    {
+       my $sql="SELECT DISTINCT name FROM tags WHERE parents_id='';";
+       return($self->{db}->cmd_firstcol($sql));
+    }
+    my $hasvals=$self->expecting_values();
+    my $parent=$self->trailing_tag_parent();
+#    print "THASVALS: $hasvals\n";
+#    print "TPARENT: ", (defined($parent)? $parent : "NO"), "\n";
+    my @ids=();
+    my $sql=("SELECT tags.name FROM (\n" .
+            $self->tags_subselect() .
+            ") AS subselect\n" .
+            "INNER JOIN files_x_tags ON subselect.files_id=files_x_tags.files_id\n" .
+            "INNER JOIN tags ON files_x_tags.tags_id=tags.id\n");
+    my @allused=$self->used_tags();
+    my @used=grep { ref($_) ne "ARRAY"; } @allused;
+    my @used_with_vals=grep { ref($_) eq "ARRAY"; } @allused;
+#    print "tags(): USED: ", join(", ", @used), "\n";
+#    print "tags(): USED_WITH_VALS: ", join(", ", map { "[".$_->[0]. ", ".$_->[1]."]";} @used_with_vals), "\n";
+    my @orclauses=();
+    my @andclauses=();
+    my $id=$self->trailing_tag_id();
+    if($hasvals)
+    {
+#      print "HAS_VALUES\n";
+       my @values=map { "'".$_->[1]."'"; } grep { $_->[0] == $id; } @used_with_vals;
+       my $clause="(tags.parents_id='$id'";
+       if(@values)
+       {
+           $clause .= " AND tags.id NOT IN (" . join(', ', @values) . ")";
+       }
+       $clause .= ")";
+       push(@andclauses, $clause);
+    }
+    else
+    {
+#      print "HASNT VALUES\n";;
+       if(@used)
+       {
+           push(@andclauses, "(NOT (tags.parents_id='' AND tags.id IN (" . join(', ', @used) . ")))");
+       }
+       for my $pair (@used_with_vals)
+       {
+           push(@andclauses, "(NOT (tags.parents_id='" . $pair->[0] . "' AND tags.id='" . $pair->[1] . "'))");
+       }
+    }
+
+    my $parentclause= "(tags.parents_id='";
+    if($hasvals)
+    {
+       $parentclause .= $id;
+    }
+    elsif($parent)
+    {
+       $parentclause .= $parent;
+    }
+    $parentclause .= "')";
+    push(@andclauses, $parentclause);
+
+    if(@orclauses)
+    {
+       push(@andclauses, '( ' . join(' OR ', @orclauses) . ' )');
+    }
+    if(@andclauses)
+    {
+       $sql .= "WHERE " . join(' AND ', @andclauses) . "\n";
+    }
+    $sql .= "GROUP BY tags.name;";
+    print "SQL(TAGS): $sql\n" if($self->{verbose});
+    my @tagnames=$self->{db}->cmd_firstcol($sql);
+    print("SUBNAMES: ", join(', ', @tagnames), "\n") if($self->{verbose});
+    return(@tagnames);
+}
+
+sub artists
+{
+    my($self)=@_;
+    if(!@{$self->{elements}}) # /ALL
+    {
+       my $sql="SELECT DISTINCT name FROM artists WHERE name!='';";
+       return($self->{db}->cmd_firstcol($sql));
+    }
+    my @ids=();
+    my $sql=$self->sql_start("artists.name");
+    $sql .= ("INNER JOIN artists ON files.artists_id=artists.id\n" .
+            "WHERE artists.name != ''\n" .
+            "GROUP BY artists.name;");
+    print "SQL(ARTISTS): $sql\n" if($self->{verbose});
+    my @tagnames=$self->{db}->cmd_firstcol($sql);
+    print("ARTISTS: ", join(', ', @tagnames), "\n") if($self->{verbose});
+    return(@tagnames);
+}
+
+sub albums
+{
+    my($self)=@_;
+    my @ids=();
+    my $tail=$self->tail();
+    # FIXME: rework PathElements
+    if($self->is("artist", $tail))
+    {
+       return $self->artist_albums($tail->id());
+    }
+    my $sql=$self->sql_start("albums.name");
+    $sql .= ("INNER JOIN albums ON files.albums_id=albums.id\n" .
+            "WHERE albums.name != ''\n" .
+            "GROUP BY albums.name;");
+    print "SQL(ALBUMS): \n$sql\n" if($self->{verbose});
+    my @names=$self->{db}->cmd_firstcol($sql);
+    print("ALBUMS: ", join(', ', @names), "\n") if($self->{verbose});
+    return(@names);
+}
+
+sub artist_albums
+{
+    my($self, $artist_id)=@_;
+    my $sql=$self->sql_start("albums.name");
+    $sql .= ("INNER JOIN albums ON albums.id=files.albums_id\n" .
+            "INNER JOIN artists ON artists.id=files.artists_id\n" .
+            "WHERE artists.id=? and albums.name <> ''\n" .
+            "GROUP BY albums.name\n");
+    print "ARTIST_ALBUMS SQL: $sql\n" if($self->{verbose});
+    my @albums=$self->{db}->cmd_firstcol($sql, $artist_id);
+    print("ALBUMS: ", join(', ', @albums), "\n") if($self->{verbose});
+    return(@albums);
+}
+
+sub artist_tracks
+{
+    my($self, $artist_id)=@_;
+    my $sql=$self->sql_start("files.name");
+    $sql .= ("INNER JOIN artists ON artists.id=files.artists_id\n" .
+            "INNER JOIN albums  ON albums.id=files.albums_id\n" .
+            "WHERE artists.id=? AND albums.name=''\n" .
+            "GROUP BY files.name\n");
+    print "ARTIST_TRACKS SQL: $sql\n" if($self->{verbose});
+    my @names=$self->{db}->cmd_firstcol($sql, $artist_id);
+    print("ARTISTTRACKS: ", join(', ', @names), "\n") if($self->{verbose});
+    return(@names);
+}
+
+sub album_tracks
+{
+    my($self, $artist_id, $album_id)=@_;
+    my $sql=("SELECT files.name FROM files\n" .
+            "INNER JOIN albums  ON albums.id=files.albums_id\n" .
+            "INNER JOIN artists ON artists.id=files.artists_id\n" .
+            "WHERE artists.id=? AND albums.id=?\n" .
+            "GROUP BY files.name\n");
+    print "ALBUM_TRACKS SQL($artist_id, $album_id): $sql\n" if($self->{verbose});
+    my @names=$self->{db}->cmd_firstcol($sql, $artist_id, $album_id);
+    print("TRACKS: ", join(', ', @names), "\n") if($self->{verbose});
+    return(@names);
+}
+
+sub tracks
+{
+    my($self)=@_;
+    # FIXME: rework PathElements
+    my $tail=$self->tail();
+    if($self->is("artist", $tail))
+    {
+       return $self->artist_tracks($tail->id());
+    }
+    elsif($self->is("album", $tail))
+    {
+       my $artist_id=0;
+       my $artist=$self->tail_parent();
+       if($self->is("artist", $artist))
+       {
+           # should always happen
+           $artist_id=$artist->id();
+       }
+       return $self->album_tracks($artist_id, $tail->id());
+    }
+    my $sql=$self->sql_start("files.name");
+    $sql .= "INNER JOIN artists ON files.artists_id=artists.id\n";
+    if($self->{components}->[$#{$self->{components}}] eq $PATH_NOARTIST)
+    {
+       $sql .= "WHERE artists.name =''\n";
+    }
+    $sql .= "GROUP BY files.name;";
+    print "TRACKS SQL($self->{path}): $sql\n" if($self->{verbose});
+    my @names=$self->{db}->cmd_firstcol($sql);
+    print("TRACKS: ", join(', ', @names), "\n") if($self->{verbose});
+    return(@names);
+}
+
+sub filename
+{
+    my($self, $mountpoint)=@_;
+    my $tail=$self->tail();
+    if($self->is("file", $tail))
+    {
+       my $id=$tail->id();
+       my $sql=("SELECT paths.name, files.name FROM files\n" .
+                "INNER JOIN paths ON files.paths_id=paths.id\n" .
+                "WHERE files.id=?\n" .
+                "GROUP BY paths.name, files.name");
+       print "FILENAME SQL: $sql\n" if($self->{verbose});
+       my ($path, $name)=$self->{db}->cmd_onerow($sql, $id);
+       my $id3fs_path=join('/', map { $_->{name}; }  @{$self->{elements}});
+       return($self->{db}->relativise($path, $name, $mountpoint));
+    }
+    # should never happen
+    return "ERROR";
+}
+
+sub tags_subselect
+{
+    my($self)=@_;
+    my $hasvals=$self->expecting_values();
+    # we need to specially handle a bare /NOT/tag with no other clauses,
+    # using a simple WHERE id !='tagid' instead of a LEFT JOIN
+    if($self->{bare_not})
+    {
+       return $self->bare_not_subselect();
+    }
+    if($self->{in_all})
+    {
+       return "\tSELECT id FROM files AS files_id\n";
+    }
+    my $tree=$self->{tagtree};
+    my $parent=$self->trailing_tag_parent();
+
+#    print "ELEMENTS: ", join('/', map { $_->{name}; } @{$self->{elements}}), "\n";
+#    print "TREE: ", $tree->print(), "\n";
+    my $tag=undef;
+    if($hasvals)
+    {
+       $tag=$self->trailing_tag_id();
+#      print "Trailing id: $tag\n";
+    }
+    my ($sqlclause, @joins)=(undef, ());
+    ($sqlclause, @joins) = $tree->to_sql($hasvals) if($tree);
+#    print "SQL(" . scalar(@joins) .": $sqlclause\n";
+    my $sql="\tSELECT fxt1.files_id FROM tags t1";
+    my @crosses=();
+    my @inners=();
+#    $joinsneeded++ if($tag);
+    for(my $i=0; $i <= $#joins; $i++)
+    {
+       my $cnt=$i+1;
+       my $join=$joins[$i];
+       my $inner=("\t$join JOIN files_x_tags fxt$cnt ON " .
+                  "t${cnt}.id=fxt${cnt}.tags_id");
+       if($i > 0)
+       {
+           push(@crosses, "CROSS JOIN tags t$cnt");
+           $inner .= " AND fxt1.files_id=fxt${cnt}.files_id";
+       }
+       push(@inners, $inner);
+    }
+    $sql .= ("\n\t" . join(" ", @crosses)) if(@crosses);
+    $sql .= ("\n" . join("\n", @inners)) if(@inners);
+    $sql .= "\n\tWHERE $sqlclause" if($sqlclause);
+#    if($tag)
+#    {
+#      $sql .= " AND t${joinsneeded}.parents_id='$tag'";
+#    }
+    $sql .= "\n\tGROUP BY fxt1.files_id\n";
+    return $sql;
+}
+
+sub bare_not_subselect
+{
+    my($self)=@_;
+    my @tags=grep { $self->is("tag", $_); } @{$self->{elements}};
+    my $sql=("\tSELECT f1.id AS files_id FROM files f1 WHERE f1.id NOT IN (\n" .
+            "\t\tSELECT fxt1.files_id FROM tags t1\n" .
+            "\t\tINNER JOIN files_x_tags fxt1 ON t1.id=fxt1.tags_id\n" .
+            "\t\tWHERE ");
+    if(scalar(@tags) > 1)
+    {
+       $sql .= ("(t1.parents_id='" . $tags[0]->id() . "' AND t1.id='" .
+                $tags[1]->id() . "')");
+    }
+    else
+    {
+       $sql .= ("(t1.parents_id='' AND t1.id='" . $tags[0]->id() . "')");
+    }
+    $sql .= "\n\t\tGROUP BY fxt1.files_id\n\t)\n";
+    return($sql);
+}
+
+sub sql_start
+{
+    my($self, $tables)=@_;
+    my $sql="SELECT $tables FROM ";
+    if($self->{in_all})
+    {
+       $sql .= "files\n";
+    }
+    else
+    {
+       $sql .= ("(\n" .
+                $self->tags_subselect() .
+                ") AS subselect\n" .
+                "INNER JOIN files ON subselect.files_id=files.id\n");
+    }
+    return $sql;
+}
+
+
+sub constraints_tag_list
+{
+    my($self, @constraints)=@_;
+    my $lasttag=undef;
+    my @tags=();
+    my @tags_vals=();
+    for my $constraint (@constraints)
+    {
+#      print ref($constraint), ": ", $constraint->{name}, "\n";
+       if($self->is("tag", $constraint))
+       {
+           if(defined($lasttag))
+           {
+#              print "TAGVAL\n";
+               push(@tags_vals, [$lasttag, $constraint->id()]) if defined($constraint->id());
+               $lasttag=undef;
+           }
+           elsif($self->tag_has_values($constraint->id()))
+           {
+#              print "HASVALUES\n";
+               $lasttag=$constraint->id() if defined($constraint->id());
+           }
+           else
+           {
+#              print "NOVALUES\n";
+               push(@tags, $constraint->id()) if(defined($constraint->id()));
+           }
+       }
+    }
+    @tags=map{ "\"$_\""; } @tags;
+    @tags_vals=map( { [ map({ "\"$_\""; } @$_ ) ] } @tags_vals);
+    $lasttag="\"$lasttag\"" if defined($lasttag);
+    return(\@tags, \@tags_vals, $lasttag);
+}
+
+# we just filter $ALLTRACKS, $NOARTIST and $NOALBUM
+# filtering tags properly requires up to four levels of recursion
+# (tag/tagval/AND/NOT) and is too slow
+sub filter
+{
+    my($self, @dirs)=@_;
+    my $base=$self->{path};
+    my @outdirs=();
+    for my $dir (@dirs)
+    {
+       print "\nFILTER (",$self->state(), "): $base / $dir\n";
+       if($self->empty("$base/$dir"))
+       {
+           print "empty: $base / $dir\n";
+       }
+       else
+       {
+           print "non-empty, accepting: $base / $dir\n";
+           push(@outdirs, $dir);
+       }
+    }
+    return(@outdirs);
+}
+
+sub empty
+{
+    my($self, $dir)=@_;
+    my $path=ID3FS::Path->new($self->{db}, $dir, $self->{verbose},
+                             ($self->{maxtagdepth} - $self->{curtagdepth}));
+    return 1 unless($path->isvalid());
+    my($subdirs,$subfiles)=$path->dirents();
+    return 0 if(@$subfiles || @$subdirs);
+    return 1;
 }
 
 1;