X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FSQL%2FAbstract.pm;h=77917336a6d3c9920032a8515725258ff199305c;hb=ff96fdd4393f62c96b87602b3923eac4d55f80ec;hp=0c33b4b8fbbff824322dcc230574e81b8fbf55cd;hpb=9de2bd8632d56f3752470253a925d9fde3cdd51c;p=scpubgit%2FQ-Branch.git diff --git a/lib/SQL/Abstract.pm b/lib/SQL/Abstract.pm index 0c33b4b..7791733 100644 --- a/lib/SQL/Abstract.pm +++ b/lib/SQL/Abstract.pm @@ -27,7 +27,7 @@ BEGIN { # GLOBALS #====================================================================== -our $VERSION = '1.84'; +our $VERSION = '1.86'; # This would confuse some packagers $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases @@ -37,22 +37,9 @@ our $AUTOLOAD; # special operators (-in, -between). May be extended/overridden by user. # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation my @BUILTIN_SPECIAL_OPS = ( - {regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'}, - {regex => qr/^ (?: not \s )? in $/ix, handler => '_where_field_IN'}, - {regex => qr/^ ident $/ix, handler => '_where_op_IDENT'}, - {regex => qr/^ value $/ix, handler => '_where_op_VALUE'}, - {regex => qr/^ is (?: \s+ not )? $/ix, handler => '_where_field_IS'}, -); - -# unaryish operators - key maps to handler -my @BUILTIN_UNARY_OPS = ( - # the digits are backcompat stuff - { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' }, - { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' }, - { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' }, - { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' }, - { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' }, - { regex => qr/^ value $/xi, handler => '_where_op_VALUE' }, + {regex => qr/^ (?: not \s )? between $/ix, handler => sub { die "NOPE" }}, + {regex => qr/^ (?: not \s )? in $/ix, handler => sub { die "NOPE" }}, + {regex => qr/^ is (?: \s+ not )? $/ix, handler => sub { die "NOPE" }}, ); #====================================================================== @@ -168,13 +155,12 @@ sub new { $opt{sqlfalse} ||= '0=1'; # special operators - $opt{special_ops} ||= []; + $opt{user_special_ops} = [ @{$opt{special_ops} ||= []} ]; # regexes are applied in order, thus push after user-defines push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS; # unary operators $opt{unary_ops} ||= []; - push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS; # rudimentary sanity-check for user supplied bits treated as functions/operators # If a purported function matches this regular expression, an exception is thrown. @@ -193,6 +179,8 @@ sub new { return bless \%opt, $class; } +sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } } +sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } } sub _assert_pass_injection_guard { if ($_[1] =~ $_[0]->{injection_guard}) { @@ -236,12 +224,12 @@ sub _returning { my $f = $options->{returning}; - my $fieldlist = $self->_SWITCH_refkind($f, { - ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;}, - SCALAR => sub {$self->_quote($f)}, - SCALARREF => sub {$$f}, - }); - return $self->_sqlcase(' returning ') . $fieldlist; + my ($sql, @bind) = $self->_render_expr( + $self->_expand_maybe_list_expr($f, undef, -ident) + ); + return wantarray + ? $self->_sqlcase(' returning ') . $sql + : ($self->_sqlcase(' returning ').$sql, @bind); } sub _insert_HASHREF { # explicit list of fields and then values @@ -330,7 +318,7 @@ sub _insert_value { push @all_bind, @bind; }, - # THINK : anything useful to do with a HASHREF ? + # THINK: anything useful to do with a HASHREF ? HASHREF => sub { # (nothing, but old SQLA passed it through) #TODO in SQLA >= 2.0 it will die instead belch "HASH ref as bind value in insert is not supported"; @@ -368,10 +356,32 @@ sub update { my $options = shift; # first build the 'SET' part of the sql statement - my (@set, @all_bind); puke "Unsupported data type specified to \$sql->update" unless ref $data eq 'HASH'; + my ($sql, @all_bind) = $self->_update_set_values($data); + $sql = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ') + . $sql; + + if ($where) { + my($where_sql, @where_bind) = $self->where($where); + $sql .= $where_sql; + push @all_bind, @where_bind; + } + + if ($options->{returning}) { + my ($returning_sql, @returning_bind) = $self->_update_returning($options); + $sql .= $returning_sql; + push @all_bind, @returning_bind; + } + + return wantarray ? ($sql, @all_bind) : $sql; +} + +sub _update_set_values { + my ($self, $data) = @_; + + my (@set, @all_bind); for my $k (sort keys %$data) { my $v = $data->{$k}; my $r = ref $v; @@ -405,8 +415,10 @@ sub update { puke 'Operator calls in update must be in the form { -op => $arg }' if (@rest or not $op =~ /^\-(.+)/); - local $self->{_nested_func_lhs} = $k; - my ($sql, @bind) = $self->_where_unary_op($1, $arg); + local our $Cur_Col_Meta = $k; + my ($sql, @bind) = $self->_render_expr( + $self->_expand_expr_hashpair($op, $arg) + ); push @set, "$label = $sql"; push @all_bind, @bind; @@ -419,22 +431,9 @@ sub update { } # generate sql - my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ') - . join ', ', @set; + my $sql = join ', ', @set; - if ($where) { - my($where_sql, @where_bind) = $self->where($where); - $sql .= $where_sql; - push @all_bind, @where_bind; - } - - if ($options->{returning}) { - my ($returning_sql, @returning_bind) = $self->_update_returning($options); - $sql .= $returning_sql; - push @all_bind, @returning_bind; - } - - return wantarray ? ($sql, @all_bind) : $sql; + return ($sql, @all_bind); } # So that subclasses can override UPDATE ... RETURNING separately from @@ -455,17 +454,25 @@ sub select { my $where = shift; my $order = shift; - my($where_sql, @bind) = $self->where($where, $order); + my ($fields_sql, @bind) = $self->_select_fields($fields); + + my ($where_sql, @where_bind) = $self->where($where, $order); + push @bind, @where_bind; - my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields - : $fields; - my $sql = join(' ', $self->_sqlcase('select'), $f, + my $sql = join(' ', $self->_sqlcase('select'), $fields_sql, $self->_sqlcase('from'), $table) . $where_sql; return wantarray ? ($sql, @bind) : $sql; } +sub _select_fields { + my ($self, $fields) = @_; + return $self->_render_expr( + $self->_expand_maybe_list_expr($fields, undef, '-ident') + ); +} + #====================================================================== # DELETE #====================================================================== @@ -478,7 +485,7 @@ sub delete { my $options = shift; my($where_sql, @bind) = $self->where($where); - my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql; + my $sql = $self->_sqlcase('delete from ') . $table . $where_sql; if ($options->{returning}) { my ($returning_sql, @returning_bind) = $self->_delete_returning($options); @@ -505,9 +512,13 @@ sub _delete_returning { shift->_returning(@_) } sub where { my ($self, $where, $order) = @_; + local $self->{convert_where} = $self->{convert}; + # where ? - my ($sql, @bind) = $self->_recurse_where($where); - $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : ''; + my ($sql, @bind) = defined($where) + ? $self->_recurse_where($where) + : (undef); + $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : ''; # order by? if ($order) { @@ -519,758 +530,506 @@ sub where { return wantarray ? ($sql, @bind) : $sql; } - -sub _recurse_where { - my ($self, $where, $logic) = @_; - - # dispatch on appropriate method according to refkind of $where - my $method = $self->_METHOD_FOR_refkind("_where", $where); - - my ($sql, @bind) = $self->$method($where, $logic); - - # DBIx::Class used to call _recurse_where in scalar context - # something else might too... - if (wantarray) { - return ($sql, @bind); +sub _expand_expr { + my ($self, $expr, $logic, $default_scalar_to) = @_; + local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to; + return undef unless defined($expr); + if (ref($expr) eq 'HASH') { + if (keys %$expr > 1) { + $logic ||= 'and'; + return +{ -op => [ + $logic, + map $self->_expand_expr_hashpair($_ => $expr->{$_}, $logic), + sort keys %$expr + ] }; + } + return unless %$expr; + return $self->_expand_expr_hashpair(%$expr, $logic); } - else { - belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0"; - return $sql; + if (ref($expr) eq 'ARRAY') { + my $logic = lc($logic || $self->{logic}); + $logic eq 'and' or $logic eq 'or' or puke "unknown logic: $logic"; + + my @expr = @$expr; + + my @res; + + while (my ($el) = splice @expr, 0, 1) { + puke "Supplying an empty left hand side argument is not supported in array-pairs" + unless defined($el) and length($el); + my $elref = ref($el); + if (!$elref) { + push(@res, $self->_expand_expr({ $el, shift(@expr) })); + } elsif ($elref eq 'ARRAY') { + push(@res, $self->_expand_expr($el)) if @$el; + } elsif (my $l = is_literal_value($el)) { + push @res, { -literal => $l }; + } elsif ($elref eq 'HASH') { + push @res, $self->_expand_expr($el); + } else { + die "notreached"; + } + } + return { -op => [ $logic, @res ] }; } -} - - - -#====================================================================== -# WHERE: top-level ARRAYREF -#====================================================================== - - -sub _where_ARRAYREF { - my ($self, $where, $logic) = @_; - - $logic = uc($logic || $self->{logic}); - $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic"; - - my @clauses = @$where; - - my (@sql_clauses, @all_bind); - # need to use while() so can shift() for pairs - while (@clauses) { - my $el = shift @clauses; - - $el = undef if (defined $el and ! length $el); - - # switch according to kind of $el and get corresponding ($sql, @bind) - my ($sql, @bind) = $self->_SWITCH_refkind($el, { - - # skip empty elements, otherwise get invalid trailing AND stuff - ARRAYREF => sub {$self->_recurse_where($el) if @$el}, - - ARRAYREFREF => sub { - my ($s, @b) = @$$el; - $self->_assert_bindval_matches_bindtype(@b); - ($s, @b); - }, - - HASHREF => sub {$self->_recurse_where($el, 'and') if %$el}, - - SCALARREF => sub { ($$el); }, - - SCALAR => sub { - # top-level arrayref with scalars, recurse in pairs - $self->_recurse_where({$el => shift(@clauses)}) - }, - - UNDEF => sub {puke "Supplying an empty left hand side argument is not supported in array-pairs" }, - }); - - if ($sql) { - push @sql_clauses, $sql; - push @all_bind, @bind; + if (my $literal = is_literal_value($expr)) { + return +{ -literal => $literal }; + } + if (!ref($expr) or Scalar::Util::blessed($expr)) { + if (my $d = $Default_Scalar_To) { + return +{ $d => $expr }; + } + if (my $m = our $Cur_Col_Meta) { + return +{ -bind => [ $m, $expr ] }; } + return +{ -value => $expr }; } - - return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind); -} - -#====================================================================== -# WHERE: top-level ARRAYREFREF -#====================================================================== - -sub _where_ARRAYREFREF { - my ($self, $where) = @_; - my ($sql, @bind) = @$$where; - $self->_assert_bindval_matches_bindtype(@bind); - return ($sql, @bind); + die "notreached"; } -#====================================================================== -# WHERE: top-level HASHREF -#====================================================================== - -sub _where_HASHREF { - my ($self, $where) = @_; - my (@sql_clauses, @all_bind); - - for my $k (sort keys %$where) { - my $v = $where->{$k}; - - # ($k => $v) is either a special unary op or a regular hashpair - my ($sql, @bind) = do { - if ($k =~ /^-./) { - # put the operator in canonical form - my $op = $k; - $op = substr $op, 1; # remove initial dash - $op =~ s/^\s+|\s+$//g;# remove leading/trailing space - $op =~ s/\s+/ /g; # compress whitespace - - # so that -not_foo works correctly - $op =~ s/^not_/NOT /i; - - $self->_debug("Unary OP(-$op) within hashref, recursing..."); - my ($s, @b) = $self->_where_unary_op($op, $v); - - # top level vs nested - # we assume that handled unary ops will take care of their ()s - $s = "($s)" unless ( - List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}} - or - ( defined $self->{_nested_func_lhs} and $self->{_nested_func_lhs} eq $k ) - ); - ($s, @b); - } - else { - if (! length $k) { - if (is_literal_value ($v) ) { - belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead'; - } - else { - puke "Supplying an empty left hand side argument is not supported in hash-pairs"; - } - } - - my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v); - $self->$method($k, $v); - } - }; - - push @sql_clauses, $sql; - push @all_bind, @bind; +sub _expand_expr_hashpair { + my ($self, $k, $v, $logic) = @_; + unless (defined($k) and length($k)) { + if (defined($k) and my $literal = is_literal_value($v)) { + belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead'; + return { -literal => $literal }; + } + puke "Supplying an empty left hand side argument is not supported"; } - - return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind); -} - -sub _where_unary_op { - my ($self, $op, $rhs) = @_; - - # top level special ops are illegal in general - # this includes the -ident/-value ops (dual purpose unary and special) - puke "Illegal use of top-level '-$op'" - if ! defined $self->{_nested_func_lhs} and List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}; - - if (my $op_entry = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) { - my $handler = $op_entry->{handler}; - - if (not ref $handler) { - if ($op =~ s/ [_\s]? \d+ $//x ) { - belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. ' - . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]"; + if ($k =~ /^-/) { + $self->_assert_pass_injection_guard($k =~ /^-(.*)$/s); + if ($k =~ s/ [_\s]? \d+ $//x ) { + belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. ' + . "You probably wanted ...-and => [ $k => COND1, $k => COND2 ... ]"; + } + if ($k eq '-nest') { + return $self->_expand_expr($v); + } + if ($k eq '-bool') { + if (ref($v)) { + return $self->_expand_expr($v); } - return $self->$handler($op, $rhs); + puke "-bool => undef not supported" unless defined($v); + return { -ident => $v }; } - elsif (ref $handler eq 'CODE') { - return $handler->($self, $op, $rhs); + if ($k eq '-not') { + return { -op => [ 'not', $self->_expand_expr($v) ] }; } - else { - puke "Illegal handler for operator $op - expecting a method name or a coderef"; + if (my ($rest) = $k =~/^-not[_ ](.*)$/) { + return +{ -op => [ + 'not', + $self->_expand_expr_hashpair("-${rest}", $v, $logic) + ] }; } - } - - $self->_debug("Generic unary OP: $op - recursing as function"); - - $self->_assert_pass_injection_guard($op); - - my ($sql, @bind) = $self->_SWITCH_refkind($rhs, { - SCALAR => sub { + if (my ($logic) = $k =~ /^-(and|or)$/i) { + if (ref($v) eq 'HASH') { + return $self->_expand_expr($v, $logic); + } + if (ref($v) eq 'ARRAY') { + return $self->_expand_expr($v, $logic); + } + } + { + my $op = $k; + $op =~ s/^-// if length($op) > 1; + + # top level special ops are illegal in general puke "Illegal use of top-level '-$op'" - unless defined $self->{_nested_func_lhs}; - - return ( - $self->_convert('?'), - $self->_bindtype($self->{_nested_func_lhs}, $rhs) - ); - }, - FALLBACK => sub { - $self->_recurse_where($rhs) - }, - }); - - $sql = sprintf('%s %s', - $self->_sqlcase($op), - $sql, - ); - - return ($sql, @bind); -} - -sub _where_op_ANDOR { - my ($self, $op, $v) = @_; - - $self->_SWITCH_refkind($v, { - ARRAYREF => sub { - return $self->_where_ARRAYREF($v, $op); - }, - - HASHREF => sub { - return ($op =~ /^or/i) - ? $self->_where_ARRAYREF([ map { $_ => $v->{$_} } (sort keys %$v) ], $op) - : $self->_where_HASHREF($v); - }, - - SCALARREF => sub { - puke "-$op => \\\$scalar makes little sense, use " . - ($op =~ /^or/i - ? '[ \$scalar, \%rest_of_conditions ] instead' - : '-and => [ \$scalar, \%rest_of_conditions ] instead' - ); - }, - - ARRAYREFREF => sub { - puke "-$op => \\[...] makes little sense, use " . - ($op =~ /^or/i - ? '[ \[...], \%rest_of_conditions ] instead' - : '-and => [ \[...], \%rest_of_conditions ] instead' - ); - }, - - SCALAR => sub { # permissively interpreted as SQL - puke "-$op => \$value makes little sense, use -bool => \$value instead"; - }, - - UNDEF => sub { - puke "-$op => undef not supported"; - }, - }); -} - -sub _where_op_NEST { - my ($self, $op, $v) = @_; - - $self->_SWITCH_refkind($v, { - - SCALAR => sub { # permissively interpreted as SQL - belch "literal SQL should be -nest => \\'scalar' " - . "instead of -nest => 'scalar' "; - return ($v); - }, - - UNDEF => sub { - puke "-$op => undef not supported"; - }, - - FALLBACK => sub { - $self->_recurse_where($v); - }, - - }); -} - - -sub _where_op_BOOL { - my ($self, $op, $v) = @_; - - my ($s, @b) = $self->_SWITCH_refkind($v, { - SCALAR => sub { # interpreted as SQL column - $self->_convert($self->_quote($v)); - }, - - UNDEF => sub { - puke "-$op => undef not supported"; - }, - - FALLBACK => sub { - $self->_recurse_where($v); - }, - }); - - $s = "(NOT $s)" if $op =~ /^not/i; - ($s, @b); -} - - -sub _where_op_IDENT { - my $self = shift; - my ($op, $rhs) = splice @_, -2; - if (! defined $rhs or length ref $rhs) { - puke "-$op requires a single plain scalar argument (a quotable identifier)"; - } - - # in case we are called as a top level special op (no '=') - my $lhs = shift; - - $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs); - - return $lhs - ? "$lhs = $rhs" - : $rhs - ; -} - -sub _where_op_VALUE { - my $self = shift; - my ($op, $rhs) = splice @_, -2; - - # in case we are called as a top level special op (no '=') - my $lhs = shift; - - # special-case NULL - if (! defined $rhs) { - return defined $lhs - ? $self->_convert($self->_quote($lhs)) . ' IS NULL' - : undef - ; + if List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}; + } + if ($k eq '-value' and my $m = our $Cur_Col_Meta) { + return +{ -bind => [ $m, $v ] }; + } + if ($k eq '-op' or $k eq '-ident' or $k eq '-value' or $k eq '-bind' or $k eq '-literal' or $k eq '-func') { + return { $k => $v }; + } + if (my $custom = $self->{custom_expansions}{($k =~ /^-(.*)$/)[0]}) { + return $self->$custom($v); + } + if ( + ref($v) eq 'HASH' + and keys %$v == 1 + and (keys %$v)[0] =~ /^-/ + ) { + my ($func) = $k =~ /^-(.*)$/; + return +{ -func => [ $func, $self->_expand_expr($v) ] }; + } + if (!ref($v) or is_literal_value($v)) { + return +{ -op => [ $k =~ /^-(.*)$/, $self->_expand_expr($v) ] }; + } } - - my @bind = - $self->_bindtype( - (defined $lhs ? $lhs : $self->{_nested_func_lhs}), - $rhs, + if ( + !defined($v) + or ( + ref($v) eq 'HASH' + and exists $v->{-value} + and not defined $v->{-value} ) - ; - - return $lhs - ? ( - $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'), - @bind - ) - : ( - $self->_convert('?'), - @bind, - ) - ; -} - -sub _where_hashpair_ARRAYREF { - my ($self, $k, $v) = @_; - - if (@$v) { - my @v = @$v; # need copy because of shift below - $self->_debug("ARRAY($k) means distribute over elements"); - - # put apart first element if it is an operator (-and, -or) - my $op = ( - (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix) - ? shift @v - : '' - ); - my @distributed = map { {$k => $_} } @v; - - if ($op) { - $self->_debug("OP($op) reinjected into the distributed array"); - unshift @distributed, $op; - } - - my $logic = $op ? substr($op, 1) : ''; - - return $self->_recurse_where(\@distributed, $logic); + ) { + return $self->_expand_expr_hashpair($k => { $self->{cmp} => undef }); } - else { - $self->_debug("empty ARRAY($k) means 0=1"); - return ($self->{sqlfalse}); + if (!ref($v) or Scalar::Util::blessed($v)) { + return +{ + -op => [ + $self->{cmp}, + { -ident => $k }, + { -bind => [ $k, $v ] } + ] + }; } -} - -sub _where_hashpair_HASHREF { - my ($self, $k, $v, $logic) = @_; - $logic ||= 'and'; - - local $self->{_nested_func_lhs} = defined $self->{_nested_func_lhs} - ? $self->{_nested_func_lhs} - : $k - ; - - my ($all_sql, @all_bind); - - for my $orig_op (sort keys %$v) { - my $val = $v->{$orig_op}; - - # put the operator in canonical form - my $op = $orig_op; - - # FIXME - we need to phase out dash-less ops - $op =~ s/^-//; # remove possible initial dash - $op =~ s/^\s+|\s+$//g;# remove leading/trailing space - $op =~ s/\s+/ /g; # compress whitespace - - $self->_assert_pass_injection_guard($op); - - # fixup is_not - $op =~ s/^is_not/IS NOT/i; - - # so that -not_foo works correctly - $op =~ s/^not_/NOT /i; - - # another retarded special case: foo => { $op => { -value => undef } } - if (ref $val eq 'HASH' and keys %$val == 1 and exists $val->{-value} and ! defined $val->{-value} ) { - $val = undef; + if (ref($v) eq 'HASH') { + if (keys %$v > 1) { + return { -op => [ + 'and', + map $self->_expand_expr_hashpair($k => { $_ => $v->{$_} }), + sort keys %$v + ] }; } - - my ($sql, @bind); - - # CASE: col-value logic modifiers - if ($orig_op =~ /^ \- (and|or) $/xi) { - ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1); + my ($vk, $vv) = %$v; + $vk =~ s/^-//; + $vk = lc($vk); + $self->_assert_pass_injection_guard($vk); + if ($vk =~ s/ [_\s]? \d+ $//x ) { + belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. ' + . "You probably wanted ...-and => [ -$vk => COND1, -$vk => COND2 ... ]"; } - # CASE: special operators like -in or -between - elsif (my $special_op = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) { - my $handler = $special_op->{handler}; - if (! $handler) { - puke "No handler supplied for special operator $orig_op"; + if ($vk =~ /^(?:not[ _])?between$/) { + local our $Cur_Col_Meta = $k; + my @rhs = map $self->_expand_expr($_), + ref($vv) eq 'ARRAY' ? @$vv : $vv; + unless ( + (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal}) + or + (@rhs == 2 and defined($rhs[0]) and defined($rhs[1])) + ) { + puke "Operator '${\uc($vk)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref"; } - elsif (not ref $handler) { - ($sql, @bind) = $self->$handler($k, $op, $val); + return +{ -op => [ + join(' ', split '_', $vk), + { -ident => $k }, + @rhs + ] } + } + if ($vk =~ /^(?:not[ _])?in$/) { + if (my $literal = is_literal_value($vv)) { + my ($sql, @bind) = @$literal; + my $opened_sql = $self->_open_outer_paren($sql); + return +{ -op => [ + $vk, { -ident => $k }, + [ { -literal => [ $opened_sql, @bind ] } ] + ] }; } - elsif (ref $handler eq 'CODE') { - ($sql, @bind) = $handler->($self, $k, $op, $val); + my $undef_err = + 'SQL::Abstract before v1.75 used to generate incorrect SQL when the ' + . "-${\uc($vk)} operator was given an undef-containing list: !!!AUDIT YOUR CODE " + . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract ' + . 'will emit the logically correct SQL instead of raising this exception)' + ; + puke("Argument passed to the '${\uc($vk)}' operator can not be undefined") + if !defined($vv); + my @rhs = map $self->_expand_expr($_), + map { ref($_) ? $_ : { -bind => [ $k, $_ ] } } + map { defined($_) ? $_: puke($undef_err) } + (ref($vv) eq 'ARRAY' ? @$vv : $vv); + return $self->${\($vk =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs; + + return +{ -op => [ + join(' ', split '_', $vk), + { -ident => $k }, + \@rhs + ] }; + } + if ($vk eq 'ident') { + if (! defined $vv or ref $vv) { + puke "-$vk requires a single plain scalar argument (a quotable identifier)"; } - else { - puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef"; + return +{ -op => [ + $self->{cmp}, + { -ident => $k }, + { -ident => $vv } + ] }; + } + if ($vk eq 'value') { + return $self->_expand_expr_hashpair($k, undef) unless defined($vv); + return +{ -op => [ + $self->{cmp}, + { -ident => $k }, + { -bind => [ $k, $vv ] } + ] }; + } + if ($vk =~ /^is(?:[ _]not)?$/) { + puke "$vk can only take undef as argument" + if defined($vv) + and not ( + ref($vv) eq 'HASH' + and exists($vv->{-value}) + and !defined($vv->{-value}) + ); + $vk =~ s/_/ /g; + return +{ -op => [ $vk.' null', { -ident => $k } ] }; + } + if ($vk =~ /^(and|or)$/) { + if (ref($vv) eq 'HASH') { + return +{ -op => [ + $vk, + map $self->_expand_expr_hashpair($k, { $_ => $vv->{$_} }), + sort keys %$vv + ] }; } } - else { - $self->_SWITCH_refkind($val, { - - ARRAYREF => sub { # CASE: col => {op => \@vals} - ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val); - }, - - ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind) - my ($sub_sql, @sub_bind) = @$$val; - $self->_assert_bindval_matches_bindtype(@sub_bind); - $sql = join ' ', $self->_convert($self->_quote($k)), - $self->_sqlcase($op), - $sub_sql; - @bind = @sub_bind; - }, - - UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL" - my $is = - $op =~ /^not$/i ? 'is not' # legacy - : $op =~ $self->{equality_op} ? 'is' - : $op =~ $self->{like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is' - : $op =~ $self->{inequality_op} ? 'is not' - : $op =~ $self->{not_like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is not' - : puke "unexpected operator '$orig_op' with undef operand"; - - $sql = $self->_quote($k) . $self->_sqlcase(" $is null"); - }, - - FALLBACK => sub { # CASE: col => {op/func => $stuff} - ($sql, @bind) = $self->_where_unary_op($op, $val); - - $sql = join(' ', - $self->_convert($self->_quote($k)), - $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested - ); - }, - }); + if (my $us = List::Util::first { $vk =~ $_->{regex} } @{$self->{user_special_ops}}) { + return { -op => [ $vk, { -ident => $k }, $vv ] }; } - - ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql; - push @all_bind, @bind; - } - return ($all_sql, @all_bind); -} - -sub _where_field_IS { - my ($self, $k, $op, $v) = @_; - - my ($s) = $self->_SWITCH_refkind($v, { - UNDEF => sub { - join ' ', - $self->_convert($self->_quote($k)), - map { $self->_sqlcase($_)} ($op, 'null') - }, - FALLBACK => sub { - puke "$op can only take undef as argument"; - }, - }); - - $s; -} - -sub _where_field_op_ARRAYREF { - my ($self, $k, $op, $vals) = @_; - - my @vals = @$vals; #always work on a copy - - if (@vals) { - $self->_debug(sprintf '%s means multiple elements: [ %s ]', - $vals, - join(', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ), - ); - - # see if the first element is an -and/-or op - my $logic; - if (defined $vals[0] && $vals[0] =~ /^ - (AND|OR) $/ix) { - $logic = uc $1; - shift @vals; + if (ref($vv) eq 'ARRAY') { + my ($logic, @values) = ( + (defined($vv->[0]) and $vv->[0] =~ /^-(and|or)$/i) + ? @$vv + : (-or => @$vv) + ); + if ( + $vk =~ $self->{inequality_op} + or join(' ', split '_', $vk) =~ $self->{not_like_op} + ) { + if (lc($logic) eq '-or' and @values > 1) { + my $op = uc join ' ', split '_', $vk; + belch "A multi-element arrayref as an argument to the inequality op '$op' " + . 'is technically equivalent to an always-true 1=1 (you probably wanted ' + . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)" + ; + } + } + unless (@values) { + # try to DWIM on equality operators + my $op = join ' ', split '_', $vk; + return + $op =~ $self->{equality_op} ? $self->sqlfalse + : $op =~ $self->{like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->sqlfalse + : $op =~ $self->{inequality_op} ? $self->sqltrue + : $op =~ $self->{not_like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->sqltrue + : puke "operator '$op' applied on an empty array (field '$k')"; + } + return +{ -op => [ + $logic =~ /^-(.*)$/, + map $self->_expand_expr_hashpair($k => { $vk => $_ }), + @values + ] }; } - - # a long standing API wart - an attempt to change this behavior during - # the 1.50 series failed *spectacularly*. Warn instead and leave the - # behavior as is if ( - @vals > 1 - and - (!$logic or $logic eq 'OR') - and - ($op =~ $self->{inequality_op} or $op =~ $self->{not_like_op}) + !defined($vv) + or ( + ref($vv) eq 'HASH' + and exists $vv->{-value} + and not defined $vv->{-value} + ) ) { - my $o = uc($op); - belch "A multi-element arrayref as an argument to the inequality op '$o' " - . 'is technically equivalent to an always-true 1=1 (you probably wanted ' - . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)" - ; + my $op = join ' ', split '_', $vk; + my $is = + $op =~ /^not$/i ? 'is not' # legacy + : $op =~ $self->{equality_op} ? 'is' + : $op =~ $self->{like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is' + : $op =~ $self->{inequality_op} ? 'is not' + : $op =~ $self->{not_like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is not' + : puke "unexpected operator '$op' with undef operand"; + return +{ -op => [ $is.' null', { -ident => $k } ] }; } - - # distribute $op over each remaining member of @vals, append logic if exists - return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic); - + local our $Cur_Col_Meta = $k; + return +{ -op => [ + $vk, + { -ident => $k }, + $self->_expand_expr($vv) + ] }; } - else { - # try to DWIM on equality operators - return - $op =~ $self->{equality_op} ? $self->{sqlfalse} - : $op =~ $self->{like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->{sqlfalse} - : $op =~ $self->{inequality_op} ? $self->{sqltrue} - : $op =~ $self->{not_like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->{sqltrue} - : puke "operator '$op' applied on an empty array (field '$k')"; + if (ref($v) eq 'ARRAY') { + return $self->sqlfalse unless @$v; + $self->_debug("ARRAY($k) means distribute over elements"); + my $this_logic = ( + $v->[0] =~ /^-((?:and|or))$/i + ? ($v = [ @{$v}[1..$#$v] ], $1) + : ($self->{logic} || 'or') + ); + return +{ -op => [ + $this_logic, + map $self->_expand_expr({ $k => $_ }, $this_logic), @$v + ] }; + } + if (my $literal = is_literal_value($v)) { + unless (length $k) { + belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead'; + return \$literal; + } + my ($sql, @bind) = @$literal; + if ($self->{bindtype} eq 'columns') { + for (@bind) { + if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) { + puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]" + } + } + } + return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] }; } + die "notreached"; } - -sub _where_hashpair_SCALARREF { - my ($self, $k, $v) = @_; - $self->_debug("SCALAR($k) means literal SQL: $$v"); - my $sql = $self->_quote($k) . " " . $$v; - return ($sql); +sub _render_expr { + my ($self, $expr) = @_; + my ($k, $v, @rest) = %$expr; + die "No" if @rest; + my %op = map +("-$_" => '_render_'.$_), + qw(op func value bind ident literal); + if (my $meth = $op{$k}) { + return $self->$meth($v); + } + die "notreached: $k"; } -# literal SQL with bind -sub _where_hashpair_ARRAYREFREF { - my ($self, $k, $v) = @_; - $self->_debug("REF($k) means literal SQL: @${$v}"); - my ($sql, @bind) = @$$v; - $self->_assert_bindval_matches_bindtype(@bind); - $sql = $self->_quote($k) . " " . $sql; - return ($sql, @bind ); -} +sub _recurse_where { + my ($self, $where, $logic) = @_; -# literal SQL without bind -sub _where_hashpair_SCALAR { - my ($self, $k, $v) = @_; - $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v"); - my $sql = join ' ', $self->_convert($self->_quote($k)), - $self->_sqlcase($self->{cmp}), - $self->_convert('?'); - my @bind = $self->_bindtype($k, $v); - return ($sql, @bind); -} +#print STDERR Data::Dumper::Concise::Dumper([ $where, $logic ]); + my $where_exp = $self->_expand_expr($where, $logic); -sub _where_hashpair_UNDEF { - my ($self, $k, $v) = @_; - $self->_debug("UNDEF($k) means IS NULL"); - my $sql = $self->_quote($k) . $self->_sqlcase(' is null'); - return ($sql); -} +#print STDERR Data::Dumper::Concise::Dumper([ EXP => $where_exp ]); -#====================================================================== -# WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF) -#====================================================================== + # dispatch on appropriate method according to refkind of $where +# my $method = $self->_METHOD_FOR_refkind("_where", $where_exp); +# my ($sql, @bind) = $self->$method($where_exp, $logic); -sub _where_SCALARREF { - my ($self, $where) = @_; + my ($sql, @bind) = defined($where_exp) ? $self->_render_expr($where_exp) : (undef); - # literal sql - $self->_debug("SCALAR(*top) means literal SQL: $$where"); - return ($$where); + # DBIx::Class used to call _recurse_where in scalar context + # something else might too... + if (wantarray) { + return ($sql, @bind); + } + else { + belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0"; + return $sql; + } } +sub _render_ident { + my ($self, $ident) = @_; -sub _where_SCALAR { - my ($self, $where) = @_; - - # literal sql - $self->_debug("NOREF(*top) means literal SQL: $where"); - return ($where); + return $self->_convert($self->_quote($ident)); } +sub _render_value { + my ($self, $value) = @_; -sub _where_UNDEF { - my ($self) = @_; - return (); + return ($self->_convert('?'), $self->_bindtype(undef, $value)); } - -#====================================================================== -# WHERE: BUILTIN SPECIAL OPERATORS (-in, -between) -#====================================================================== - - -sub _where_field_BETWEEN { - my ($self, $k, $op, $vals) = @_; - - my ($label, $and, $placeholder); - $label = $self->_convert($self->_quote($k)); - $and = ' ' . $self->_sqlcase('and') . ' '; - $placeholder = $self->_convert('?'); - $op = $self->_sqlcase($op); - - my $invalid_args = "Operator '$op' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref"; - - my ($clause, @bind) = $self->_SWITCH_refkind($vals, { - ARRAYREFREF => sub { - my ($s, @b) = @$$vals; - $self->_assert_bindval_matches_bindtype(@b); - ($s, @b); - }, - SCALARREF => sub { - return $$vals; - }, - ARRAYREF => sub { - puke $invalid_args if @$vals != 2; - - my (@all_sql, @all_bind); - foreach my $val (@$vals) { - my ($sql, @bind) = $self->_SWITCH_refkind($val, { - SCALAR => sub { - return ($placeholder, $self->_bindtype($k, $val) ); - }, - SCALARREF => sub { - return $$val; - }, - ARRAYREFREF => sub { - my ($sql, @bind) = @$$val; - $self->_assert_bindval_matches_bindtype(@bind); - return ($sql, @bind); - }, - HASHREF => sub { - my ($func, $arg, @rest) = %$val; - puke "Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN" - if (@rest or $func !~ /^ \- (.+)/x); - $self->_where_unary_op($1 => $arg); - }, - FALLBACK => sub { - puke $invalid_args, - }, - }); - push @all_sql, $sql; - push @all_bind, @bind; - } - +my %unop_postfix = map +($_ => 1), + 'is null', 'is not null', + 'asc', 'desc', +; + +my %special = ( + (map +($_ => do { + my $op = $_; + sub { + my ($self, $args) = @_; + my ($left, $low, $high) = @$args; + my ($rhsql, @rhbind) = do { + if (@$args == 2) { + puke "Single arg to between must be a literal" + unless $low->{-literal}; + @{$low->{-literal}} + } else { + my ($l, $h) = map [ $self->_render_expr($_) ], $low, $high; + (join(' ', $l->[0], $self->_sqlcase('and'), $h->[0]), + @{$l}[1..$#$l], @{$h}[1..$#$h]) + } + }; + my ($lhsql, @lhbind) = $self->_render_expr($left); return ( - (join $and, @all_sql), - @all_bind + join(' ', '(', $lhsql, $self->_sqlcase($op), $rhsql, ')'), + @lhbind, @rhbind ); - }, - FALLBACK => sub { - puke $invalid_args, - }, - }); + } + }), 'between', 'not between'), + (map +($_ => do { + my $op = $_; + sub { + my ($self, $args) = @_; + my ($lhs, $rhs) = @$args; + my @in_bind; + my @in_sql = map { + my ($sql, @bind) = $self->_render_expr($_); + push @in_bind, @bind; + $sql; + } @$rhs; + my ($lhsql, @lbind) = $self->_render_expr($lhs); + return ( + $lhsql.' '.$self->_sqlcase($op).' ( ' + .join(', ', @in_sql) + .' )', + @lbind, @in_bind + ); + } + }), 'in', 'not in'), +); - my $sql = "( $label $op $clause )"; - return ($sql, @bind) +sub _render_op { + my ($self, $v) = @_; + my ($op, @args) = @$v; + $op =~ s/^-// if length($op) > 1; + $op = lc($op); + if (my $h = $special{$op}) { + return $self->$h(\@args); + } + if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{user_special_ops}}) { + puke "Special op '${op}' requires first value to be identifier" + unless my ($k) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0]; + return $self->${\($us->{handler})}($k, $op, $args[1]); + } + my $final_op = $op =~ /^(?:is|not)_/ ? join(' ', split '_', $op) : $op; + if (@args == 1 and $op !~ /^(and|or)$/) { + my ($expr_sql, @bind) = $self->_render_expr($args[0]); + my $op_sql = $self->_sqlcase($final_op); + my $final_sql = ( + $unop_postfix{lc($final_op)} + ? "${expr_sql} ${op_sql}" + : "${op_sql} ${expr_sql}" + ); + return (($op eq 'not' ? '('.$final_sql.')' : $final_sql), @bind); + } else { + my @parts = map [ $self->_render_expr($_) ], @args; + my ($final_sql) = map +($op =~ /^(and|or)$/ ? "(${_})" : $_), join( + ($final_op eq ',' ? '' : ' ').$self->_sqlcase($final_op).' ', + map $_->[0], @parts + ); + return ( + $final_sql, + map @{$_}[1..$#$_], @parts + ); + } + die "unhandled"; } +sub _render_func { + my ($self, $rest) = @_; + my ($func, @args) = @$rest; + my @arg_sql; + my @bind = map { + my @x = @$_; + push @arg_sql, shift @x; + @x + } map [ $self->_render_expr($_) ], @args; + return ($self->_sqlcase($func).'('.join(', ', @arg_sql).')', @bind); +} -sub _where_field_IN { - my ($self, $k, $op, $vals) = @_; - - # backwards compatibility : if scalar, force into an arrayref - $vals = [$vals] if defined $vals && ! ref $vals; - - my ($label) = $self->_convert($self->_quote($k)); - my ($placeholder) = $self->_convert('?'); - $op = $self->_sqlcase($op); - - my ($sql, @bind) = $self->_SWITCH_refkind($vals, { - ARRAYREF => sub { # list of choices - if (@$vals) { # nonempty list - my (@all_sql, @all_bind); - - for my $val (@$vals) { - my ($sql, @bind) = $self->_SWITCH_refkind($val, { - SCALAR => sub { - return ($placeholder, $val); - }, - SCALARREF => sub { - return $$val; - }, - ARRAYREFREF => sub { - my ($sql, @bind) = @$$val; - $self->_assert_bindval_matches_bindtype(@bind); - return ($sql, @bind); - }, - HASHREF => sub { - my ($func, $arg, @rest) = %$val; - puke "Only simple { -func => arg } functions accepted as sub-arguments to IN" - if (@rest or $func !~ /^ \- (.+)/x); - $self->_where_unary_op($1 => $arg); - }, - UNDEF => sub { - puke( - 'SQL::Abstract before v1.75 used to generate incorrect SQL when the ' - . "-$op operator was given an undef-containing list: !!!AUDIT YOUR CODE " - . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract ' - . 'will emit the logically correct SQL instead of raising this exception)' - ); - }, - }); - push @all_sql, $sql; - push @all_bind, @bind; - } - - return ( - sprintf('%s %s ( %s )', - $label, - $op, - join(', ', @all_sql) - ), - $self->_bindtype($k, @all_bind), - ); - } - else { # empty list : some databases won't understand "IN ()", so DWIM - my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse}; - return ($sql); - } - }, - - SCALARREF => sub { # literal SQL - my $sql = $self->_open_outer_paren($$vals); - return ("$label $op ( $sql )"); - }, - ARRAYREFREF => sub { # literal SQL with bind - my ($sql, @bind) = @$$vals; - $self->_assert_bindval_matches_bindtype(@bind); - $sql = $self->_open_outer_paren($sql); - return ("$label $op ( $sql )", @bind); - }, - - UNDEF => sub { - puke "Argument passed to the '$op' operator can not be undefined"; - }, - - FALLBACK => sub { - puke "special op $op requires an arrayref (or scalarref/arrayref-ref)"; - }, - }); +sub _render_bind { + my ($self, $bind) = @_; + return ($self->_convert('?'), $self->_bindtype(@$bind)); +} - return ($sql, @bind); +sub _render_literal { + my ($self, $literal) = @_; + $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]); + return @$literal; } # Some databases (SQLite) treat col IN (1, 2) different from @@ -1311,82 +1070,30 @@ sub _open_outer_paren { sub _order_by { my ($self, $arg) = @_; - my (@sql, @bind); - for my $c ($self->_order_by_chunks($arg) ) { - $self->_SWITCH_refkind($c, { - SCALAR => sub { push @sql, $c }, - ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c }, - }); - } - - my $sql = @sql - ? sprintf('%s %s', - $self->_sqlcase(' order by'), - join(', ', @sql) - ) - : '' - ; - - return wantarray ? ($sql, @bind) : $sql; -} - -sub _order_by_chunks { - my ($self, $arg) = @_; - - return $self->_SWITCH_refkind($arg, { - - ARRAYREF => sub { - map { $self->_order_by_chunks($_ ) } @$arg; - }, - - ARRAYREFREF => sub { - my ($s, @b) = @$$arg; - $self->_assert_bindval_matches_bindtype(@b); - [ $s, @b ]; - }, - - SCALAR => sub {$self->_quote($arg)}, - - UNDEF => sub {return () }, + return '' unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg); - SCALARREF => sub {$$arg}, # literal SQL, no quoting + my $expander = sub { + my ($self, $dir, $expr) = @_; + my @exp = map +(defined($dir) ? { -op => [ $dir => $_ ] } : $_), + map $self->_expand_expr($_, undef, -ident), + ref($expr) eq 'ARRAY' ? @$expr : $expr; + return (@exp > 1 ? { -op => [ ',', @exp ] } : $exp[0]); + }; - HASHREF => sub { - # get first pair in hash - my ($key, $val, @rest) = %$arg; + local $self->{custom_expansions} = { + asc => sub { shift->$expander(asc => @_) }, + desc => sub { shift->$expander(desc => @_) }, + }; - return () unless $key; - - if (@rest or not $key =~ /^-(desc|asc)/i) { - puke "hash passed to _order_by must have exactly one key (-desc or -asc)"; - } - - my $direction = $1; - - my @ret; - for my $c ($self->_order_by_chunks($val)) { - my ($sql, @bind); - - $self->_SWITCH_refkind($c, { - SCALAR => sub { - $sql = $c; - }, - ARRAYREF => sub { - ($sql, @bind) = @$c; - }, - }); + my $expanded = $self->$expander(undef, $arg); - $sql = $sql . ' ' . $self->_sqlcase($direction); + my ($sql, @bind) = $self->_render_expr($expanded); - push @ret, [ $sql, @bind]; - } + my $final_sql = $self->_sqlcase(' order by ').$sql; - return @ret; - }, - }); + return wantarray ? ($final_sql, @bind) : $final_sql; } - #====================================================================== # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES) #====================================================================== @@ -1394,11 +1101,9 @@ sub _order_by_chunks { sub _table { my $self = shift; my $from = shift; - $self->_SWITCH_refkind($from, { - ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;}, - SCALAR => sub {$self->_quote($from)}, - SCALARREF => sub {$$from}, - }); + ($self->_render_expr( + $self->_expand_maybe_list_expr($from, undef, -ident) + ))[0]; } @@ -1406,6 +1111,21 @@ sub _table { # UTILITY FUNCTIONS #====================================================================== +sub _expand_maybe_list_expr { + my ($self, $expr, $logic, $default) = @_; + my $e = do { + if (ref($expr) eq 'ARRAY') { + return { -op => [ + ',', map $self->_expand_expr($_, $logic, $default), @$expr + ] } if @$expr > 1; + $expr->[0] + } else { + $expr + } + }; + return $self->_expand_expr($e, $logic, $default); +} + # highly optimized, as it's called way too often sub _quote { # my ($self, $label) = @_; @@ -1435,8 +1155,8 @@ sub _quote { # Conversion, if applicable sub _convert { #my ($self, $arg) = @_; - if ($_[0]->{convert}) { - return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')'; + if ($_[0]->{convert_where}) { + return $_[0]->_sqlcase($_[0]->{convert_where}) .'(' . $_[1] . ')'; } return $_[1]; } @@ -1913,7 +1633,7 @@ Which will change the above C to: WHERE event_date >= '2/13/99' AND event_date <= '4/24/03' The logic can also be changed locally by inserting -a modifier in front of an arrayref : +a modifier in front of an arrayref: @where = (-and => [event_date => {'>=', '2/13/99'}, event_date => {'<=', '4/24/03'} ]); @@ -2124,7 +1844,7 @@ L. =head2 select($source, $fields, $where, $order) This returns a SQL SELECT statement and associated list of bind values, as -specified by the arguments : +specified by the arguments: =over @@ -2134,8 +1854,7 @@ Specification of the 'FROM' part of the statement. The argument can be either a plain scalar (interpreted as a table name, will be quoted), or an arrayref (interpreted as a list of table names, joined by commas, quoted), or a scalarref -(literal table name, not quoted), or a ref to an arrayref -(list of literal table names, joined by commas, not quoted). +(literal SQL, not quoted). =item $fields @@ -2489,7 +2208,7 @@ Here is a quick list of equivalencies, since there is some overlap: -=head2 Special operators : IN, BETWEEN, etc. +=head2 Special operators: IN, BETWEEN, etc. You can also use the hashref format to compare a list of fields using the C comparison operator, by specifying the list as an arrayref: @@ -2508,8 +2227,8 @@ The reverse operator C<-not_in> generates SQL C and is used in the same way. If the argument to C<-in> is an empty array, 'sqlfalse' is generated -(by default : C<1=0>). Similarly, C<< -not_in => [] >> generates -'sqltrue' (by default : C<1=1>). +(by default: C<1=0>). Similarly, C<< -not_in => [] >> generates +'sqltrue' (by default: C<1=1>). In addition to the array you can supply a chunk of literal sql or literal sql with bind: @@ -2572,7 +2291,7 @@ Would give you: These are the two builtin "special operators"; but the -list can be expanded : see section L below. +list can be expanded: see section L below. =head2 Unary operators: bool @@ -2636,7 +2355,7 @@ This data structure would create the following: Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or> -to change the logic inside : +to change the logic inside: my @where = ( -and => [ @@ -2660,7 +2379,7 @@ That would yield: C: when connecting several conditions, the C<-and->|C<-or> operator goes C of the nested structure; whereas when connecting several constraints on one column, the C<-and> operator goes -C the arrayref. Here is an example combining both features : +C the arrayref. Here is an example combining both features: my @where = ( -and => [a => 1, b => 2], @@ -2675,20 +2394,20 @@ yielding OR ( e LIKE ? AND e LIKE ? ) ) ) This difference in syntax is unfortunate but must be preserved for -historical reasons. So be careful : the two examples below would +historical reasons. So be careful: the two examples below would seem algebraically equivalent, but they are not { col => [ -and => { -like => 'foo%' }, { -like => '%bar' }, ] } - # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) ) + # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) ) [ -and => { col => { -like => 'foo%' } }, { col => { -like => '%bar' } }, ] - # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) ) + # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) ) =head2 Literal SQL and value type operators @@ -2802,7 +2521,7 @@ example will look like: ) Literal SQL is especially useful for nesting parenthesized clauses in the -main SQL query. Here is a first example : +main SQL query. Here is a first example: my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?", 100, "foo%"); @@ -2811,7 +2530,7 @@ main SQL query. Here is a first example : bar => \["IN ($sub_stmt)" => @sub_bind], ); -This yields : +This yields: $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?))"; @@ -2832,7 +2551,7 @@ to C : In the examples above, the subquery was used as an operator on a column; but the same principle also applies for a clause within the main C<%where> -hash, like an EXISTS subquery : +hash, like an EXISTS subquery: my ($sub_stmt, @sub_bind) = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"}); @@ -2849,7 +2568,7 @@ which yields Observe that the condition on C in the subquery refers to -column C of the main query : this is I a bind +column C of the main query: this is I a bind value, so we have to express it through a scalar ref. Writing C<< c2 => {">" => "t0.c0"} >> would have generated C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly @@ -2984,7 +2703,7 @@ forms. Examples: A "special operator" is a SQL syntactic clause that can be applied to a field, instead of a usual binary operator. -For example : +For example: WHERE field IN (?, ?, ?) WHERE field BETWEEN ? AND ? @@ -3203,7 +2922,7 @@ to clarify the semantics. Hence, client code that was relying on some dark areas of C v1.* B in v1.50. -The main changes are : +The main changes are: =over @@ -3225,7 +2944,7 @@ optional support for L =item * -defensive programming : check arguments +defensive programming: check arguments =item *