better override handling, handle defined-but-empty sql parts
[scpubgit/Q-Branch.git] / lib / SQL / Abstract.pm
index 3016bc1..7a03936 100644 (file)
@@ -185,6 +185,7 @@ our %Defaults = (
     delete => [ qw(target where returning) ],
     update => [ qw(target set where returning) ],
     insert => [ qw(target fields from returning) ],
+    select => [ qw(select from where order_by) ],
   },
   expand_clause => {
     'delete.from' => '_expand_delete_clause_target',
@@ -242,11 +243,6 @@ sub new {
   # special operators
   $opt{special_ops} ||= [];
 
-  if ($class->isa('DBIx::Class::SQLMaker')) {
-    $opt{warn_once_on_nest} = 1;
-    $opt{disable_old_special_ops} = 1;
-  }
-
   # unary operators
   $opt{unary_ops} ||= [];
 
@@ -267,7 +263,42 @@ sub new {
   $opt{expand_unary} = {};
 
   foreach my $name (sort keys %Defaults) {
-    $opt{$name} = { %{$Defaults{$name}} };
+    $opt{$name} = { %{$Defaults{$name}}, %{$opt{$name}||{}} };
+  }
+
+  if ($class ne __PACKAGE__) {
+
+    # check for overriden methods
+
+    foreach my $type (qw(insert update delete)) {
+      my $method = "_${type}_returning";
+      if (__PACKAGE__->can($method) ne $class->can($method)) {
+        my $clause = "${type}.returning";
+        $opt{expand_clause}{$clause} = sub { $_[2] },
+        $opt{render_clause}{$clause}
+          = sub { [ $_[0]->$method($_[3]) ] };
+      }
+    }
+    if (__PACKAGE__->can('_table') ne $class->can('_table')) {
+      $opt{expand_clause}{'select.from'} = sub {
+        return +{ -literal => [ $_[0]->_table($_[2]) ] };
+      };
+    }
+    if (__PACKAGE__->can('_order_by') ne $class->can('_order_by')) {
+      $opt{expand_clause}{'select.order_by'} = sub { $_[2] };
+      $opt{render_clause}{'select.order_by'} = sub {
+        [ $_[0]->_order_by($_[2]) ];
+      };
+    }
+    if ($class->isa('DBIx::Class::SQLMaker')) {
+      $opt{warn_once_on_nest} = 1;
+      $opt{disable_old_special_ops} = 1;
+      $opt{render_clause}{'select.where'} = sub {
+        my ($sql, @bind) = $_[0]->where($_[2]);
+        s/\A\s+//, s/\s+\Z// for $sql;
+        return [ $sql, @bind ];
+      };
+    }
   }
 
   if ($opt{lazy_join_sql_parts}) {
@@ -280,6 +311,82 @@ sub new {
   return bless \%opt, $class;
 }
 
+sub _ext_rw {
+  my ($self, $name, $key, $value) = @_;
+  return $self->{$name}{$key} unless @_ > 3;
+  $self->{$name}{$key} = $value;
+  return $self;
+}
+
+BEGIN {
+  foreach my $type (qw(
+    expand op_expand render op_render clause_expand clause_render
+  )) {
+    my $name = join '_', reverse split '_', $type;
+    my $singular = "${type}er";
+    eval qq{sub ${singular} { shift->_ext_rw($name => \@_) }; 1 }
+      or die "Method builder failed for ${singular}: $@";
+    eval qq{sub wrap_${singular} {
+      my (\$self, \$key, \$builder) = \@_;
+      my \$orig = \$self->_ext_rw('${name}', \$key);
+      \$self->_ext_rw(
+        '${name}', \$key,
+        \$builder->(\$orig, '${name}', \$key)
+      );
+    }; 1 } or die "Method builder failed for wrap_${singular}: $@";
+    eval qq{sub ${singular}s {
+      my (\$self, \@args) = \@_;
+      while (my (\$this_key, \$this_value) = splice(\@args, 0, 2)) {
+        \$self->_ext_rw('${name}', \$this_key, \$this_value);
+      }
+      return \$self;
+    }; 1 } or die "Method builder failed for ${singular}s: $@";
+    eval qq{sub wrap_${singular}s {
+      my (\$self, \@args) = \@_;
+      while (my (\$this_key, \$this_builder) = splice(\@args, 0, 2)) {
+        my \$orig = \$self->_ext_rw('${name}', \$this_key);
+        \$self->_ext_rw(
+          '${name}', \$this_key,
+           \$this_builder->(\$orig, '${name}', \$this_key),
+        );
+      }
+      return \$self;
+    }; 1 } or die "Method builder failed for wrap_${singular}s: $@";
+    eval qq{sub ${singular}_list { sort keys %{\$_[0]->{\$name}} }; 1; }
+     or die "Method builder failed for ${singular}_list: $@";
+  }
+}
+
+sub register_op { $_[0]->{is_op}{$_[1]} = 1; $_[0] }
+
+sub statement_list { sort keys %{$_[0]->{clauses_of}} }
+
+sub clauses_of {
+  my ($self, $of, @clauses) = @_;
+  unless (@clauses) {
+    return @{$self->{clauses_of}{$of}||[]};
+  }
+  if (ref($clauses[0]) eq 'CODE') {
+    @clauses = $self->${\($clauses[0])}(@{$self->{clauses_of}{$of}||[]});
+  }
+  $self->{clauses_of}{$of} = \@clauses;
+  return $self;
+}
+
+sub clone {
+  my ($self) = @_;
+  bless(
+    {
+      (map +($_ => (
+        ref($self->{$_}) eq 'HASH'
+          ? { %{$self->{$_}} }
+          : $self->{$_}
+      )), keys %$self),
+    },
+    ref($self)
+  );
+}
+
 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
 
@@ -518,24 +625,83 @@ sub _update_returning { shift->_returning(@_) }
 # SELECT
 #======================================================================
 
-
 sub select {
-  my $self   = shift;
-  my $table  = $self->_table(shift);
-  my $fields = shift || '*';
-  my $where  = shift;
-  my $order  = shift;
+  my ($self, @args) = @_;
+  my $stmt = do {
+    if (ref(my $sel = $args[0]) eq 'HASH') {
+      $sel
+    } else {
+      my %clauses;
+      @clauses{qw(from select where order_by)} = @args;
+
+      # This oddity is to literalify since historically SQLA doesn't quote
+      # a single identifier argument, so we convert it into a literal
+
+      $clauses{select} = { -literal => [ $clauses{select}||'*' ] }
+        unless ref($clauses{select});
+      \%clauses;
+    }
+  };
 
-  my ($fields_sql, @bind) = $self->_select_fields($fields);
+  my @rendered = $self->render_statement({ -select => $stmt });
+  return wantarray ? @rendered : $rendered[0];
+}
+
+sub _expand_select_clause_select {
+  my ($self, undef, $select) = @_;
+  +(select => $self->_expand_maybe_list_expr($select, -ident));
+}
 
-  my ($where_sql, @where_bind) = $self->where($where, $order);
-  push @bind, @where_bind;
+sub _expand_select_clause_from {
+  my ($self, undef, $from) = @_;
+  +(from => $self->_expand_maybe_list_expr($from, -ident));
+}
+
+sub _expand_select_clause_where {
+  my ($self, undef, $where) = @_;
+
+  my $sqla = do {
+    if (my $conv = $self->{convert}) {
+      my $_wrap = sub {
+        my $orig = shift;
+        sub {
+          my $self = shift;
+          +{ -func => [
+            $conv,
+            $self->$orig(@_)
+          ] };
+        };
+      };
+      $self->clone
+           ->wrap_expanders(map +($_ => $_wrap), qw(ident value bind))
+           ->wrap_op_expanders(map +($_ => $_wrap), qw(ident value bind))
+           ->wrap_expander(func => sub {
+               my $orig = shift;
+               sub {
+                 my ($self, $type, $thing) = @_;
+                 if (ref($thing) eq 'ARRAY' and $thing->[0] eq $conv
+                     and @$thing == 2 and ref($thing->[1]) eq 'HASH'
+                     and (
+                       $thing->[1]{-ident}
+                       or $thing->[1]{-value}
+                       or $thing->[1]{-bind})
+                     ) {
+                   return { -func => $thing }; # already went through our expander
+                 }
+                 return $self->$orig($type, $thing);
+               }
+             });
+    } else {
+      $self;
+    }
+  };
 
-  my $sql = join(' ', $self->_sqlcase('select'), $fields_sql,
-                      $self->_sqlcase('from'),   $table)
-          . $where_sql;
+  return +(where => $sqla->expand_expr($where));
+}
 
-  return wantarray ? ($sql, @bind) : $sql;
+sub _expand_select_clause_order_by {
+  my ($self, undef, $order_by) = @_;
+  +(order_by => $self->_expand_order_by($order_by));
 }
 
 sub _select_fields {
@@ -653,6 +819,7 @@ sub _expand_statement {
     $args = { %$args };
     $args->{$type} = delete $args->{_}
   }
+  my %has_clause = map +($_ => 1), @{$self->{clauses_of}{$type}};
   return +{ "-${type}" => +{
     map {
       my $val = $args->{$_};
@@ -662,8 +829,10 @@ sub _expand_statement {
         } else {
           @exp
         }
-      } else {
+      } elsif ($has_clause{$_}) {
         ($_ => $self->expand_expr($val))
+      } else {
+        ($_ => $val)
       }
     } sort keys %$args
   } };
@@ -676,7 +845,7 @@ sub _render_statement {
     next unless my $clause_expr = $args->{$clause};
     my $part = do {
       if (my $rdr = $self->{render_clause}{"${type}.${clause}"}) {
-        $self->$rdr($clause, $clause_expr);
+        $self->$rdr($clause, $clause_expr, $args);
       } else {
         my $r = $self->render_aqt($clause_expr, 1);
         next unless defined $r->[0] and length $r->[0];
@@ -1386,7 +1555,9 @@ sub join_query_parts {
       : ((ref($_) eq 'ARRAY') ? $_ : [ $_ ])
   ), @parts;
   return [
-    $self->{join_sql_parts}->($join, grep defined, map $_->[0], @final),
+    $self->{join_sql_parts}->(
+      $join, grep defined && length, map $_->[0], @final
+    ),
     (map @{$_}[1..$#$_], @final),
   ];
 }