1 package SQL::Abstract; # see doc at end of file
5 use Module::Runtime ();
10 use Exporter 'import';
11 our @EXPORT_OK = qw(is_plain_value is_literal_value);
21 *SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION = $ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}
27 #======================================================================
29 #======================================================================
31 our $VERSION = '1.87';
33 # This would confuse some packagers
34 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
38 # special operators (-in, -between). May be extended/overridden by user.
39 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
40 my @BUILTIN_SPECIAL_OPS = (
41 {regex => qr/^ (?: not \s )? between $/ix, handler => sub { die "NOPE" }},
42 {regex => qr/^ is (?: \s+ not )? $/ix, handler => sub { die "NOPE" }},
43 {regex => qr/^ (?: not \s )? in $/ix, handler => sub { die "NOPE" }},
44 {regex => qr/^ ident $/ix, handler => sub { die "NOPE" }},
45 {regex => qr/^ value $/ix, handler => sub { die "NOPE" }},
48 #======================================================================
49 # DEBUGGING AND ERROR REPORTING
50 #======================================================================
53 return unless $_[0]->{debug}; shift; # a little faster
54 my $func = (caller(1))[3];
55 warn "[$func] ", @_, "\n";
59 my($func) = (caller(1))[3];
60 Carp::carp "[$func] Warning: ", @_;
64 my($func) = (caller(1))[3];
65 Carp::croak "[$func] Fatal: ", @_;
68 sub is_literal_value ($) {
69 ref $_[0] eq 'SCALAR' ? [ ${$_[0]} ]
70 : ( ref $_[0] eq 'REF' and ref ${$_[0]} eq 'ARRAY' ) ? [ @${ $_[0] } ]
74 sub is_undef_value ($) {
78 and exists $_[0]->{-value}
79 and not defined $_[0]->{-value}
83 # FIXME XSify - this can be done so much more efficiently
84 sub is_plain_value ($) {
86 ! length ref $_[0] ? \($_[0])
88 ref $_[0] eq 'HASH' and keys %{$_[0]} == 1
90 exists $_[0]->{-value}
91 ) ? \($_[0]->{-value})
93 # reuse @_ for even moar speedz
94 defined ( $_[1] = Scalar::Util::blessed $_[0] )
96 # deliberately not using Devel::OverloadInfo - the checks we are
97 # intersted in are much more limited than the fullblown thing, and
98 # this is a very hot piece of code
100 # simply using ->can('(""') can leave behind stub methods that
101 # break actually using the overload later (see L<perldiag/Stub
102 # found while resolving method "%s" overloading "%s" in package
103 # "%s"> and the source of overload::mycan())
105 # either has stringification which DBI SHOULD prefer out of the box
106 grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
108 # has nummification or boolification, AND fallback is *not* disabled
110 SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION
113 grep { *{"${_}::(0+"}{CODE} } @{$_[2]}
115 grep { *{"${_}::(bool"}{CODE} } @{$_[2]}
119 # no fallback specified at all
120 ! ( ($_[3]) = grep { *{"${_}::()"}{CODE} } @{$_[2]} )
122 # fallback explicitly undef
123 ! defined ${"$_[3]::()"}
136 #======================================================================
138 #======================================================================
142 not => '_expand_not',
143 bool => '_expand_bool',
144 and => '_expand_op_andor',
145 or => '_expand_op_andor',
146 nest => '_expand_nest',
147 bind => '_expand_bind',
149 not_in => '_expand_in',
150 row => '_expand_row',
151 between => '_expand_between',
152 not_between => '_expand_between',
154 (map +($_ => '_expand_op_is'), ('is', 'is_not')),
155 ident => '_expand_ident',
156 value => '_expand_value',
157 func => '_expand_func',
158 values => '_expand_values',
161 'between' => '_expand_between',
162 'not_between' => '_expand_between',
163 'in' => '_expand_in',
164 'not_in' => '_expand_in',
165 'nest' => '_expand_nest',
166 (map +($_ => '_expand_op_andor'), ('and', 'or')),
167 (map +($_ => '_expand_op_is'), ('is', 'is_not')),
168 'ident' => '_expand_ident',
169 'value' => '_expand_value',
172 (map +($_, "_render_$_"), qw(op func bind ident literal row values)),
175 (map +($_ => '_render_op_between'), 'between', 'not_between'),
176 (map +($_ => '_render_op_in'), 'in', 'not_in'),
177 (map +($_ => '_render_unop_postfix'),
178 'is_null', 'is_not_null', 'asc', 'desc',
180 (not => '_render_unop_paren'),
181 (map +($_ => '_render_op_andor'), qw(and or)),
182 ',' => '_render_op_multop',
185 delete => [ qw(target where returning) ],
186 update => [ qw(target set where returning) ],
187 insert => [ qw(target fields from returning) ],
188 select => [ qw(select from where order_by) ],
191 'delete.from' => '_expand_delete_clause_target',
192 'update.update' => '_expand_update_clause_target',
193 'insert.into' => '_expand_insert_clause_target',
194 'insert.values' => '_expand_insert_clause_from',
197 'delete.target' => '_render_delete_clause_target',
198 'update.target' => '_render_update_clause_target',
199 'insert.target' => '_render_insert_clause_target',
200 'insert.fields' => '_render_insert_clause_fields',
201 'insert.from' => '_render_insert_clause_from',
205 foreach my $stmt (keys %{$Defaults{clauses_of}}) {
206 $Defaults{expand}{$stmt} = '_expand_statement';
207 $Defaults{render}{$stmt} = '_render_statement';
208 foreach my $clause (@{$Defaults{clauses_of}{$stmt}}) {
209 $Defaults{expand_clause}{"${stmt}.${clause}"}
210 = "_expand_${stmt}_clause_${clause}";
216 my $class = ref($self) || $self;
217 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
219 # choose our case by keeping an option around
220 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
222 # default logic for interpreting arrayrefs
223 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
225 # how to return bind vars
226 $opt{bindtype} ||= 'normal';
228 # default comparison is "=", but can be overridden
231 # try to recognize which are the 'equality' and 'inequality' ops
232 # (temporary quickfix (in 2007), should go through a more seasoned API)
233 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
234 $opt{inequality_op} = qr/^( != | <> )$/ix;
236 $opt{like_op} = qr/^ (is_)?r?like $/xi;
237 $opt{not_like_op} = qr/^ (is_)?not_r?like $/xi;
240 $opt{sqltrue} ||= '1=1';
241 $opt{sqlfalse} ||= '0=1';
244 $opt{special_ops} ||= [];
247 $opt{unary_ops} ||= [];
249 # rudimentary sanity-check for user supplied bits treated as functions/operators
250 # If a purported function matches this regular expression, an exception is thrown.
251 # Literal SQL is *NOT* subject to this check, only functions (and column names
252 # when quoting is not in effect)
255 # need to guard against ()'s in column names too, but this will break tons of
256 # hacks... ideas anyone?
257 $opt{injection_guard} ||= qr/
263 $opt{expand_unary} = {};
265 foreach my $name (sort keys %Defaults) {
266 $opt{$name} = { %{$Defaults{$name}}, %{$opt{$name}||{}} };
269 if ($class ne __PACKAGE__) {
271 # check for overriden methods
273 foreach my $type (qw(insert update delete)) {
274 my $method = "_${type}_returning";
275 if (__PACKAGE__->can($method) ne $class->can($method)) {
276 my $clause = "${type}.returning";
277 $opt{expand_clause}{$clause} = sub { $_[2] },
278 $opt{render_clause}{$clause}
279 = sub { [ $_[0]->$method($_[3]) ] };
282 if (__PACKAGE__->can('_table') ne $class->can('_table')) {
283 $opt{expand_clause}{'select.from'} = sub {
284 return +{ -literal => [ $_[0]->_table($_[2]) ] };
287 if (__PACKAGE__->can('_order_by') ne $class->can('_order_by')) {
288 $opt{expand_clause}{'select.order_by'} = sub { $_[2] };
289 $opt{render_clause}{'select.order_by'} = sub {
290 [ $_[0]->_order_by($_[2]) ];
293 if ($class->isa('DBIx::Class::SQLMaker')) {
294 $opt{warn_once_on_nest} = 1;
295 $opt{disable_old_special_ops} = 1;
296 $opt{render_clause}{'select.where'} = sub {
297 my ($sql, @bind) = $_[0]->where($_[2]);
298 s/\A\s+//, s/\s+\Z// for $sql;
299 return [ $sql, @bind ];
304 if ($opt{lazy_join_sql_parts}) {
305 my $mod = Module::Runtime::use_module('SQL::Abstract::Parts');
306 $opt{join_sql_parts} ||= sub { $mod->new(@_) };
309 $opt{join_sql_parts} ||= sub { join $_[0], @_[1..$#_] };
311 return bless \%opt, $class;
315 my ($self, $name, $key, $value) = @_;
316 return $self->{$name}{$key} unless @_ > 3;
317 $self->{$name}{$key} = $value;
322 foreach my $type (qw(
323 expand op_expand render op_render clause_expand clause_render
325 my $name = join '_', reverse split '_', $type;
326 my $singular = "${type}er";
327 eval qq{sub ${singular} { shift->_ext_rw($name => \@_) }; 1 }
328 or die "Method builder failed for ${singular}: $@";
329 eval qq{sub wrap_${singular} {
330 my (\$self, \$key, \$builder) = \@_;
331 my \$orig = \$self->_ext_rw('${name}', \$key);
334 \$builder->(\$orig, '${name}', \$key)
336 }; 1 } or die "Method builder failed for wrap_${singular}: $@";
337 eval qq{sub ${singular}s {
338 my (\$self, \@args) = \@_;
339 while (my (\$this_key, \$this_value) = splice(\@args, 0, 2)) {
340 \$self->_ext_rw('${name}', \$this_key, \$this_value);
343 }; 1 } or die "Method builder failed for ${singular}s: $@";
344 eval qq{sub wrap_${singular}s {
345 my (\$self, \@args) = \@_;
346 while (my (\$this_key, \$this_builder) = splice(\@args, 0, 2)) {
347 my \$orig = \$self->_ext_rw('${name}', \$this_key);
349 '${name}', \$this_key,
350 \$this_builder->(\$orig, '${name}', \$this_key),
354 }; 1 } or die "Method builder failed for wrap_${singular}s: $@";
355 eval qq{sub ${singular}_list { sort keys %{\$_[0]->{\$name}} }; 1; }
356 or die "Method builder failed for ${singular}_list: $@";
360 sub register_op { $_[0]->{is_op}{$_[1]} = 1; $_[0] }
362 sub statement_list { sort keys %{$_[0]->{clauses_of}} }
365 my ($self, $of, @clauses) = @_;
367 return @{$self->{clauses_of}{$of}||[]};
369 if (ref($clauses[0]) eq 'CODE') {
370 @clauses = $self->${\($clauses[0])}(@{$self->{clauses_of}{$of}||[]});
372 $self->{clauses_of}{$of} = \@clauses;
381 ref($self->{$_}) eq 'HASH'
390 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
391 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
393 sub _assert_pass_injection_guard {
394 if ($_[1] =~ $_[0]->{injection_guard}) {
395 my $class = ref $_[0];
396 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
397 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
398 . "{injection_guard} attribute to ${class}->new()"
403 #======================================================================
405 #======================================================================
408 my ($self, $table, $data, $options) = @_;
411 if (ref($table) eq 'HASH') {
414 my %clauses = (target => $table, values => $data, %{$options||{}});
418 my @rendered = $self->render_statement({ -insert => $stmt });
419 return wantarray ? @rendered : $rendered[0];
422 sub _expand_insert_clause_target {
423 +(target => $_[0]->expand_maybe_list_expr($_[2], -ident));
426 sub _expand_insert_clause_fields {
428 $_[0]->expand_maybe_list_expr($_[2], -ident)
429 ] } if ref($_[2]) eq 'ARRAY';
430 return $_[2]; # should maybe still expand somewhat?
433 sub _expand_insert_clause_from {
434 my ($self, undef, $data) = @_;
435 if (ref($data) eq 'HASH' and (keys(%$data))[0] =~ /^-/) {
436 return $self->expand_expr($data);
438 return $data if ref($data) eq 'HASH' and $data->{-row};
439 my ($f_aqt, $v_aqt) = $self->_expand_insert_values($data);
441 from => { -values => [ $v_aqt ] },
442 ($f_aqt ? (fields => $f_aqt) : ()),
446 sub _expand_insert_clause_returning {
447 +(returning => $_[0]->expand_maybe_list_expr($_[2], -ident));
450 sub _expand_insert_values {
451 my ($self, $data) = @_;
452 if (is_literal_value($data)) {
453 (undef, $self->expand_expr($data));
455 my ($fields, $values) = (
456 ref($data) eq 'HASH' ?
457 ([ sort keys %$data ], [ @{$data}{sort keys %$data} ])
461 # no names (arrayref) means can't generate bindtype
462 !($fields) && $self->{bindtype} eq 'columns'
463 && belch "can't do 'columns' bindtype when called with arrayref";
467 ? $self->expand_expr({ -row => $fields }, -ident)
472 local our $Cur_Col_Meta = $fields->[$_];
473 $self->_expand_insert_value($values->[$_])
480 sub _render_insert_clause_fields {
481 return $_[0]->render_aqt($_[2]);
484 sub _render_insert_clause_target {
485 my ($self, undef, $from) = @_;
486 $self->join_query_parts(' ', $self->format_keyword('insert into'), $from);
489 sub _render_insert_clause_from {
490 return $_[0]->render_aqt($_[2], 1);
493 # So that subclasses can override INSERT ... RETURNING separately from
494 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
495 sub _insert_returning { shift->_returning(@_) }
497 sub _redispatch_returning {
498 my ($self, $type, undef, $returning) = @_;
499 [ $self->${\"_${type}_returning"}({ returning => $returning }) ];
503 my ($self, $options) = @_;
505 my $f = $options->{returning};
507 my ($sql, @bind) = @{ $self->render_aqt(
508 $self->expand_maybe_list_expr($f, -ident)
510 return ($self->_sqlcase(' returning ').$sql, @bind);
513 sub _expand_insert_value {
516 my $k = our $Cur_Col_Meta;
518 if (ref($v) eq 'ARRAY') {
519 if ($self->{array_datatypes}) {
520 return +{ -bind => [ $k, $v ] };
522 my ($sql, @bind) = @$v;
523 $self->_assert_bindval_matches_bindtype(@bind);
524 return +{ -literal => $v };
526 if (ref($v) eq 'HASH') {
527 if (grep !/^-/, keys %$v) {
528 belch "HASH ref as bind value in insert is not supported";
529 return +{ -bind => [ $k, $v ] };
533 return +{ -bind => [ $k, undef ] };
535 return $self->expand_expr($v);
540 #======================================================================
542 #======================================================================
545 my ($self, $table, $set, $where, $options) = @_;
548 if (ref($table) eq 'HASH') {
552 @clauses{qw(target set where)} = ($table, $set, $where);
553 puke "Unsupported data type specified to \$sql->update"
554 unless ref($clauses{set}) eq 'HASH';
555 @clauses{keys %$options} = values %$options;
559 my @rendered = $self->render_statement({ -update => $stmt });
560 return wantarray ? @rendered : $rendered[0];
563 sub _render_update_clause_target {
564 my ($self, undef, $target) = @_;
565 $self->join_query_parts(' ', $self->format_keyword('update'), $target);
568 sub _update_set_values {
569 my ($self, $data) = @_;
571 return @{ $self->render_aqt(
572 $self->_expand_update_set_values(undef, $data),
576 sub _expand_update_set_values {
577 my ($self, undef, $data) = @_;
578 $self->expand_maybe_list_expr( [
581 $set = { -bind => $_ } unless defined $set;
582 +{ -op => [ '=', { -ident => $k }, $set ] };
588 ? ($self->{array_datatypes}
589 ? [ $k, +{ -bind => [ $k, $v ] } ]
590 : [ $k, +{ -literal => $v } ])
592 local our $Cur_Col_Meta = $k;
593 [ $k, $self->_expand_expr($v) ]
600 sub _expand_update_clause_target {
601 my ($self, undef, $target) = @_;
602 +(target => $self->expand_maybe_list_expr($target, -ident));
605 sub _expand_update_clause_set {
606 return $_[2] if ref($_[2]) eq 'HASH' and ($_[2]->{-op}||[''])->[0] eq ',';
607 +(set => $_[0]->_expand_update_set_values($_[1], $_[2]));
610 sub _expand_update_clause_where {
611 +(where => $_[0]->expand_expr($_[2]));
614 sub _expand_update_clause_returning {
615 +(returning => $_[0]->expand_maybe_list_expr($_[2], -ident));
618 # So that subclasses can override UPDATE ... RETURNING separately from
620 sub _update_returning { shift->_returning(@_) }
624 #======================================================================
626 #======================================================================
629 my ($self, @args) = @_;
631 if (ref(my $sel = $args[0]) eq 'HASH') {
635 @clauses{qw(from select where order_by)} = @args;
637 # This oddity is to literalify since historically SQLA doesn't quote
638 # a single identifier argument, so we convert it into a literal
640 $clauses{select} = { -literal => [ $clauses{select}||'*' ] }
641 unless ref($clauses{select});
646 my @rendered = $self->render_statement({ -select => $stmt });
647 return wantarray ? @rendered : $rendered[0];
650 sub _expand_select_clause_select {
651 my ($self, undef, $select) = @_;
652 +(select => $self->expand_maybe_list_expr($select, -ident));
655 sub _expand_select_clause_from {
656 my ($self, undef, $from) = @_;
657 +(from => $self->expand_maybe_list_expr($from, -ident));
660 sub _expand_select_clause_where {
661 my ($self, undef, $where) = @_;
664 if (my $conv = $self->{convert}) {
676 ->wrap_expanders(map +($_ => $_wrap), qw(ident value bind))
677 ->wrap_op_expanders(map +($_ => $_wrap), qw(ident value bind))
678 ->wrap_expander(func => sub {
681 my ($self, $type, $thing) = @_;
682 if (ref($thing) eq 'ARRAY' and $thing->[0] eq $conv
683 and @$thing == 2 and ref($thing->[1]) eq 'HASH'
686 or $thing->[1]{-value}
687 or $thing->[1]{-bind})
689 return { -func => $thing }; # already went through our expander
691 return $self->$orig($type, $thing);
699 return +(where => $sqla->expand_expr($where));
702 sub _expand_select_clause_order_by {
703 my ($self, undef, $order_by) = @_;
704 +(order_by => $self->_expand_order_by($order_by));
708 my ($self, $fields) = @_;
709 return $fields unless ref($fields);
710 return @{ $self->render_aqt(
711 $self->expand_maybe_list_expr($fields, '-ident')
715 #======================================================================
717 #======================================================================
720 my ($self, $table, $where, $options) = @_;
723 if (ref($table) eq 'HASH') {
726 my %clauses = (target => $table, where => $where, %{$options||{}});
730 my @rendered = $self->render_statement({ -delete => $stmt });
731 return wantarray ? @rendered : $rendered[0];
734 # So that subclasses can override DELETE ... RETURNING separately from
736 sub _delete_returning { shift->_returning(@_) }
738 sub _expand_delete_clause_target {
739 +(target => $_[0]->expand_maybe_list_expr($_[2], -ident));
742 sub _expand_delete_clause_where { +(where => $_[0]->expand_expr($_[2])); }
744 sub _expand_delete_clause_returning {
745 +(returning => $_[0]->expand_maybe_list_expr($_[2], -ident));
748 sub _render_delete_clause_target {
749 my ($self, undef, $from) = @_;
750 $self->join_query_parts(' ', $self->format_keyword('delete from'), $from);
753 #======================================================================
755 #======================================================================
759 # Finally, a separate routine just to handle WHERE clauses
761 my ($self, $where, $order) = @_;
763 local $self->{convert_where} = $self->{convert};
766 my ($sql, @bind) = defined($where)
767 ? $self->_recurse_where($where)
769 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
773 my ($order_sql, @order_bind) = $self->_order_by($order);
775 push @bind, @order_bind;
778 return wantarray ? ($sql, @bind) : $sql;
781 { our $Default_Scalar_To = -value }
784 my ($self, $expr, $default_scalar_to) = @_;
785 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
786 $self->_expand_expr($expr);
790 my ($self, $aqt, $top_level) = @_;
791 my ($k, $v, @rest) = %$aqt;
793 die "Not a node type: $k" unless $k =~ s/^-//;
794 if (my $meth = $self->{render}{$k}) {
795 local our $Render_Top_Level = $top_level;
796 return $self->$meth($k, $v);
798 die "notreached: $k";
802 my ($self, $expr, $default_scalar_to) = @_;
803 return @{ $self->render_aqt(
804 $self->expand_expr($expr, $default_scalar_to)
808 sub render_statement {
809 my ($self, $expr, $default_scalar_to) = @_;
811 $self->expand_expr($expr, $default_scalar_to), 1
815 sub _expand_statement {
816 my ($self, $type, $args) = @_;
817 my $ec = $self->{expand_clause};
820 $args->{$type} = delete $args->{_}
822 my %has_clause = map +($_ => 1), @{$self->{clauses_of}{$type}};
823 return +{ "-${type}" => +{
825 my $val = $args->{$_};
826 if (defined($val) and my $exp = $ec->{"${type}.$_"}) {
827 if ((my (@exp) = $self->$exp($_ => $val)) == 1) {
832 } elsif ($has_clause{$_}) {
833 ($_ => $self->expand_expr($val))
841 sub _render_statement {
842 my ($self, $type, $args) = @_;
844 foreach my $clause (@{$self->{clauses_of}{$type}}) {
845 next unless my $clause_expr = $args->{$clause};
847 if (my $rdr = $self->{render_clause}{"${type}.${clause}"}) {
848 $self->$rdr($clause, $clause_expr, $args);
850 my $r = $self->render_aqt($clause_expr, 1);
851 next unless defined $r->[0] and length $r->[0];
852 $self->join_query_parts(' ',
853 $self->format_keyword($clause),
860 my $q = $self->join_query_parts(' ', @parts);
861 return $self->join_query_parts('',
862 (our $Render_Top_Level ? $q : ('(', $q, ')'))
867 my ($self, $raw) = @_;
869 return $op if grep $_->{$op}, @{$self}{qw(is_op expand_op render_op)};
870 s/^-(?=.)//, s/\s+/_/g for $op;
875 my ($self, $expr) = @_;
876 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
877 return undef unless defined($expr);
878 if (ref($expr) eq 'HASH') {
879 return undef unless my $kc = keys %$expr;
881 return $self->_expand_op_andor(and => $expr);
883 my ($key, $value) = %$expr;
884 if ($key =~ /^-/ and $key =~ s/ [_\s]? \d+ $//x ) {
885 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
886 . "You probably wanted ...-and => [ $key => COND1, $key => COND2 ... ]";
888 return $self->_expand_hashpair($key, $value);
890 if (ref($expr) eq 'ARRAY') {
891 return $self->_expand_op_andor(lc($self->{logic}), $expr);
893 if (my $literal = is_literal_value($expr)) {
894 return +{ -literal => $literal };
896 if (!ref($expr) or Scalar::Util::blessed($expr)) {
897 return $self->_expand_scalar($expr);
902 sub _expand_hashpair {
903 my ($self, $k, $v) = @_;
904 unless (defined($k) and length($k)) {
905 if (defined($k) and my $literal = is_literal_value($v)) {
906 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
907 return { -literal => $literal };
909 puke "Supplying an empty left hand side argument is not supported";
912 return $self->_expand_hashpair_op($k, $v);
913 } elsif ($k =~ /^[^\w]/i) {
914 my ($lhs, @rhs) = ref($v) eq 'ARRAY' ? @$v : $v;
915 return $self->_expand_op(
916 -op, [ $k, $self->expand_expr($lhs, -ident), @rhs ]
919 return $self->_expand_hashpair_ident($k, $v);
922 sub _expand_hashpair_ident {
923 my ($self, $k, $v) = @_;
925 local our $Cur_Col_Meta = $k;
927 # hash with multiple or no elements is andor
929 if (ref($v) eq 'HASH' and keys %$v != 1) {
930 return $self->_expand_op_andor(and => $v, $k);
933 # undef needs to be re-sent with cmp to achieve IS/IS NOT NULL
935 if (is_undef_value($v)) {
936 return $self->_expand_hashpair_cmp($k => undef);
939 # scalars and objects get expanded as whatever requested or values
941 if (!ref($v) or Scalar::Util::blessed($v)) {
942 return $self->_expand_hashpair_scalar($k, $v);
945 # single key hashref is a hashtriple
947 if (ref($v) eq 'HASH') {
948 return $self->_expand_hashtriple($k, %$v);
951 # arrayref needs re-engineering over the elements
953 if (ref($v) eq 'ARRAY') {
954 return $self->sqlfalse unless @$v;
955 $self->_debug("ARRAY($k) means distribute over elements");
957 $v->[0] =~ /^-(and|or)$/i
958 ? (shift(@{$v = [ @$v ]}), $1)
959 : lc($self->{logic} || 'OR')
961 return $self->_expand_op_andor(
966 if (my $literal = is_literal_value($v)) {
968 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
971 my ($sql, @bind) = @$literal;
972 if ($self->{bindtype} eq 'columns') {
974 $self->_assert_bindval_matches_bindtype($_);
977 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
983 my ($self, $expr) = @_;
985 return $self->_expand_expr({ (our $Default_Scalar_To) => $expr });
988 sub _expand_hashpair_scalar {
989 my ($self, $k, $v) = @_;
991 return $self->_expand_hashpair_cmp(
992 $k, $self->_expand_scalar($v),
996 sub _expand_hashpair_op {
997 my ($self, $k, $v) = @_;
999 $self->_assert_pass_injection_guard($k =~ /\A-(.*)\Z/s);
1001 my $op = $self->_normalize_op($k);
1005 my $op = join(' ', split '_', $op);
1007 # the old special op system requires illegality for top-level use
1010 (our $Expand_Depth) == 1
1012 List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}
1014 $self->{disable_old_special_ops}
1015 and List::Util::first { $op =~ $_->{regex} } @BUILTIN_SPECIAL_OPS
1019 puke "Illegal use of top-level '-$op'"
1023 if (my $exp = $self->{expand}{$op}) {
1024 return $self->$exp($op, $v);
1027 # Ops prefixed with -not_ get converted
1029 if (my ($rest) = $op =~/^not_(.*)$/) {
1032 $self->_expand_expr({ "-${rest}", $v })
1038 # the old unary op system means we should touch nothing and let it work
1040 my $op = join(' ', split '_', $op);
1042 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1043 return { -op => [ $op, $v ] };
1047 # an explicit node type is currently assumed to be expanded (this is almost
1048 # certainly wrong and there should be expansion anyway)
1050 if ($self->{render}{$op}) {
1051 return { $k => $v };
1054 my $type = $self->{unknown_unop_always_func} ? -func : -op;
1061 and (keys %$v)[0] =~ /^-/
1064 (List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}})
1071 return +{ $type => [
1073 ($type eq -func and ref($v) eq 'ARRAY')
1074 ? map $self->_expand_expr($_), @$v
1075 : $self->_expand_expr($v)
1079 sub _expand_hashpair_cmp {
1080 my ($self, $k, $v) = @_;
1081 $self->_expand_hashtriple($k, $self->{cmp}, $v);
1084 sub _expand_hashtriple {
1085 my ($self, $k, $vk, $vv) = @_;
1087 my $ik = $self->_expand_expr({ -ident => $k });
1089 my $op = $self->_normalize_op($vk);
1090 $self->_assert_pass_injection_guard($op);
1092 if ($op =~ s/ _? \d+ $//x ) {
1093 return $self->_expand_expr($k, { $vk, $vv });
1095 if (my $x = $self->{expand_op}{$op}) {
1096 local our $Cur_Col_Meta = $k;
1097 return $self->$x($op, $vv, $k);
1101 my $op = join(' ', split '_', $op);
1103 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
1104 return { -op => [ $op, $ik, $vv ] };
1106 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1110 { -op => [ $op, $vv ] }
1114 if (ref($vv) eq 'ARRAY') {
1116 my $logic = (defined($raw[0]) and $raw[0] =~ /^-(and|or)$/i)
1117 ? (shift(@raw), lc $1) : 'or';
1118 my @values = map +{ $vk => $_ }, @raw;
1120 $op =~ $self->{inequality_op}
1121 or $op =~ $self->{not_like_op}
1123 if (lc($logic) eq 'or' and @values > 1) {
1124 belch "A multi-element arrayref as an argument to the inequality op '${\uc(join ' ', split '_', $op)}' "
1125 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
1126 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
1131 # try to DWIM on equality operators
1132 return ($self->_dwim_op_to_is($op,
1133 "Supplying an empty arrayref to '%s' is deprecated",
1134 "operator '%s' applied on an empty array (field '$k')"
1135 ) ? $self->sqlfalse : $self->sqltrue);
1137 return $self->_expand_op_andor($logic => \@values, $k);
1139 if (is_undef_value($vv)) {
1140 my $is = ($self->_dwim_op_to_is($op,
1141 "Supplying an undefined argument to '%s' is deprecated",
1142 "unexpected operator '%s' with undef operand",
1143 ) ? 'is' : 'is not');
1145 return $self->_expand_hashpair($k => { $is, undef });
1147 local our $Cur_Col_Meta = $k;
1151 $self->_expand_expr($vv)
1155 sub _dwim_op_to_is {
1156 my ($self, $raw, $empty, $fail) = @_;
1158 my $op = $self->_normalize_op($raw);
1160 if ($op =~ /^not$/i) {
1163 if ($op =~ $self->{equality_op}) {
1166 if ($op =~ $self->{like_op}) {
1167 belch(sprintf $empty, uc(join ' ', split '_', $op));
1170 if ($op =~ $self->{inequality_op}) {
1173 if ($op =~ $self->{not_like_op}) {
1174 belch(sprintf $empty, uc(join ' ', split '_', $op));
1177 puke(sprintf $fail, $op);
1181 my ($self, undef, $args) = @_;
1182 my ($func, @args) = @$args;
1183 return +{ -func => [ $func, map $self->expand_expr($_), @args ] };
1187 my ($self, undef, $body, $k) = @_;
1188 return $self->_expand_hashpair_cmp(
1189 $k, { -ident => $body }
1191 unless (defined($body) or (ref($body) and ref($body) eq 'ARRAY')) {
1192 puke "-ident requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
1194 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
1195 ref($body) ? @$body : $body;
1196 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
1197 unless ($self->{quote_char}) {
1198 $self->_assert_pass_injection_guard($_) for @parts;
1200 return +{ -ident => \@parts };
1204 return $_[0]->_expand_hashpair_cmp(
1205 $_[3], { -value => $_[2] },
1206 ) if defined($_[3]);
1207 +{ -bind => [ our $Cur_Col_Meta, $_[2] ] };
1211 +{ -op => [ 'not', $_[0]->_expand_expr($_[2]) ] };
1215 my ($self, undef, $args) = @_;
1216 +{ -row => [ map $self->expand_expr($_), @$args ] };
1220 my ($self, undef, $args) = @_;
1221 my ($op, @opargs) = @$args;
1222 if (my $exp = $self->{expand_op}{$op}) {
1223 return $self->$exp($op, \@opargs);
1225 +{ -op => [ $op, map $self->expand_expr($_), @opargs ] };
1229 my ($self, undef, $v) = @_;
1231 return $self->_expand_expr($v);
1233 puke "-bool => undef not supported" unless defined($v);
1234 return $self->_expand_expr({ -ident => $v });
1237 sub _expand_op_andor {
1238 my ($self, $logop, $v, $k) = @_;
1240 $v = [ map +{ $k, $_ },
1242 ? (map +{ $_ => $v->{$_} }, sort keys %$v)
1246 if (ref($v) eq 'HASH') {
1247 return undef unless keys %$v;
1250 map $self->_expand_expr({ $_ => $v->{$_} }),
1254 if (ref($v) eq 'ARRAY') {
1255 $logop eq 'and' or $logop eq 'or' or puke "unknown logic: $logop";
1258 (ref($_) eq 'ARRAY' and @$_)
1259 or (ref($_) eq 'HASH' and %$_)
1265 while (my ($el) = splice @expr, 0, 1) {
1266 puke "Supplying an empty left hand side argument is not supported in array-pairs"
1267 unless defined($el) and length($el);
1268 my $elref = ref($el);
1270 local our $Expand_Depth = 0;
1271 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
1272 } elsif ($elref eq 'ARRAY') {
1273 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
1274 } elsif (my $l = is_literal_value($el)) {
1275 push @res, { -literal => $l };
1276 } elsif ($elref eq 'HASH') {
1277 local our $Expand_Depth = 0;
1278 push @res, grep defined, $self->_expand_expr($el) if %$el;
1284 # return $res[0] if @res == 1;
1285 return { -op => [ $logop, @res ] };
1291 my ($self, $op, $vv, $k) = @_;
1292 ($k, $vv) = @$vv unless defined $k;
1293 puke "$op can only take undef as argument"
1297 and exists($vv->{-value})
1298 and !defined($vv->{-value})
1300 return +{ -op => [ $op.'_null', $self->expand_expr($k, -ident) ] };
1303 sub _expand_between {
1304 my ($self, $op, $vv, $k) = @_;
1305 $k = shift @{$vv = [ @$vv ]} unless defined $k;
1306 my @rhs = map $self->_expand_expr($_),
1307 ref($vv) eq 'ARRAY' ? @$vv : $vv;
1309 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
1311 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
1313 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1317 $self->expand_expr(ref($k) ? $k : { -ident => $k }),
1323 my ($self, $op, $vv, $k) = @_;
1324 $k = shift @{$vv = [ @$vv ]} unless defined $k;
1325 if (my $literal = is_literal_value($vv)) {
1326 my ($sql, @bind) = @$literal;
1327 my $opened_sql = $self->_open_outer_paren($sql);
1329 $op, $self->expand_expr($k, -ident),
1330 { -literal => [ $opened_sql, @bind ] }
1334 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1335 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1336 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1337 . 'will emit the logically correct SQL instead of raising this exception)'
1339 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
1341 my @rhs = map $self->expand_expr($_, -value),
1342 map { defined($_) ? $_: puke($undef_err) }
1343 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
1344 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
1348 $self->expand_expr($k, -ident),
1354 my ($self, undef, $v) = @_;
1355 # DBIx::Class requires a nest warning to be emitted once but the private
1356 # method it overrode to do so no longer exists
1357 if ($self->{warn_once_on_nest}) {
1358 unless (our $Nest_Warned) {
1360 "-nest in search conditions is deprecated, you most probably wanted:\n"
1361 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
1366 return $self->_expand_expr($v);
1370 my ($self, undef, $bind) = @_;
1371 return { -bind => $bind };
1374 sub _expand_values {
1375 my ($self, undef, $values) = @_;
1376 return { -values => [
1379 ? $self->expand_expr($_)
1380 : +{ -row => [ map $self->expand_expr($_), @$_ ] }
1381 ), ref($values) eq 'ARRAY' ? @$values : $values
1385 sub _recurse_where {
1386 my ($self, $where, $logic) = @_;
1388 # Special case: top level simple string treated as literal
1390 my $where_exp = (ref($where)
1391 ? $self->_expand_expr($where, $logic)
1392 : { -literal => [ $where ] });
1394 # dispatch expanded expression
1396 my ($sql, @bind) = defined($where_exp) ? @{ $self->render_aqt($where_exp) || [] } : ();
1397 # DBIx::Class used to call _recurse_where in scalar context
1398 # something else might too...
1400 return ($sql, @bind);
1403 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
1409 my ($self, undef, $ident) = @_;
1411 return [ $self->_convert($self->_quote($ident)) ];
1415 my ($self, undef, $values) = @_;
1416 return $self->join_query_parts('',
1418 $self->_render_op(undef, [ ',', @$values ]),
1424 my ($self, undef, $rest) = @_;
1425 my ($func, @args) = @$rest;
1426 return $self->join_query_parts('',
1427 $self->_sqlcase($func),
1428 $self->join_query_parts('',
1430 $self->join_query_parts(', ', @args),
1437 my ($self, undef, $bind) = @_;
1438 return [ $self->_convert('?'), $self->_bindtype(@$bind) ];
1441 sub _render_literal {
1442 my ($self, undef, $literal) = @_;
1443 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1448 my ($self, undef, $v) = @_;
1449 my ($op, @args) = @$v;
1450 if (my $r = $self->{render_op}{$op}) {
1451 return $self->$r($op, \@args);
1456 my $op = join(' ', split '_', $op);
1458 my $ss = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1459 if ($ss and @args > 1) {
1460 puke "Special op '${op}' requires first value to be identifier"
1461 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1462 my $k = join(($self->{name_sep}||'.'), @$ident);
1463 local our $Expand_Depth = 1;
1464 return [ $self->${\($ss->{handler})}($k, $op, $args[1]) ];
1466 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1467 return [ $self->${\($us->{handler})}($op, $args[0]) ];
1470 return $self->_render_unop_paren($op, \@args);
1474 return $self->_render_unop_prefix($op, \@args);
1476 return $self->_render_op_multop($op, \@args);
1482 sub _render_op_between {
1483 my ($self, $op, $args) = @_;
1484 my ($left, $low, $high) = @$args;
1487 puke "Single arg to between must be a literal"
1488 unless $low->{-literal};
1491 +($low, $self->format_keyword('and'), $high);
1494 return $self->join_query_parts(' ',
1495 '(', $left, $self->format_keyword($op), @rh, ')',
1500 my ($self, $op, $args) = @_;
1501 my ($lhs, @rhs) = @$args;
1503 return $self->join_query_parts(' ',
1505 $self->format_keyword($op),
1506 $self->join_query_parts(' ',
1508 $self->join_query_parts(', ', @rhs),
1514 sub _render_op_andor {
1515 my ($self, $op, $args) = @_;
1516 return undef unless @$args;
1517 return $self->join_query_parts('', $args->[0]) if @$args == 1;
1518 my $inner = $self->_render_op_multop($op, $args);
1519 return undef unless defined($inner->[0]) and length($inner->[0]);
1520 return $self->join_query_parts(' ',
1525 sub _render_op_multop {
1526 my ($self, $op, $args) = @_;
1528 return undef unless @parts;
1529 return $self->render_aqt($parts[0]) if @parts == 1;
1530 my $join = ($op eq ','
1532 : ' '.$self->format_keyword($op).' '
1534 return $self->join_query_parts($join, @parts);
1537 sub _render_values {
1538 my ($self, undef, $values) = @_;
1539 my $inner = $self->join_query_parts(' ',
1540 $self->format_keyword('values'),
1541 $self->join_query_parts(', ',
1542 ref($values) eq 'ARRAY' ? @$values : $values
1545 return $self->join_query_parts('',
1546 (our $Render_Top_Level ? $inner : ('(', $inner, ')'))
1550 sub join_query_parts {
1551 my ($self, $join, @parts) = @_;
1554 ? $self->render_aqt($_)
1555 : ((ref($_) eq 'ARRAY') ? $_ : [ $_ ])
1558 $self->{join_sql_parts}->(
1559 $join, grep defined && length, map $_->[0], @final
1561 (map @{$_}[1..$#$_], @final),
1565 sub _render_unop_paren {
1566 my ($self, $op, $v) = @_;
1567 return $self->join_query_parts('',
1568 '(', $self->_render_unop_prefix($op, $v), ')'
1572 sub _render_unop_prefix {
1573 my ($self, $op, $v) = @_;
1574 return $self->join_query_parts(' ',
1575 $self->_sqlcase($op), $v->[0]
1579 sub _render_unop_postfix {
1580 my ($self, $op, $v) = @_;
1581 return $self->join_query_parts(' ',
1582 $v->[0], $self->format_keyword($op),
1586 # Some databases (SQLite) treat col IN (1, 2) different from
1587 # col IN ( (1, 2) ). Use this to strip all outer parens while
1588 # adding them back in the corresponding method
1589 sub _open_outer_paren {
1590 my ($self, $sql) = @_;
1592 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1594 # there are closing parens inside, need the heavy duty machinery
1595 # to reevaluate the extraction starting from $sql (full reevaluation)
1596 if ($inner =~ /\)/) {
1597 require Text::Balanced;
1599 my (undef, $remainder) = do {
1600 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1602 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1605 # the entire expression needs to be a balanced bracketed thing
1606 # (after an extract no remainder sans trailing space)
1607 last if defined $remainder and $remainder =~ /\S/;
1617 #======================================================================
1619 #======================================================================
1621 sub _expand_order_by {
1622 my ($self, $arg) = @_;
1624 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1626 return $self->expand_maybe_list_expr($arg)
1627 if ref($arg) eq 'HASH' and ($arg->{-op}||[''])->[0] eq ',';
1629 my $expander = sub {
1630 my ($self, $dir, $expr) = @_;
1631 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1632 foreach my $arg (@to_expand) {
1636 and grep /^-(asc|desc)$/, keys %$arg
1638 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1642 defined($dir) ? { -op => [ $dir =~ /^-?(.*)$/ ,=> $_ ] } : $_
1644 map $self->expand_expr($_, -ident),
1645 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
1646 return undef unless @exp;
1647 return undef if @exp == 1 and not defined($exp[0]);
1648 return +{ -op => [ ',', @exp ] };
1651 local @{$self->{expand}}{qw(asc desc)} = (($expander) x 2);
1653 return $self->$expander(undef, $arg);
1657 my ($self, $arg) = @_;
1659 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
1661 my ($sql, @bind) = @{ $self->render_aqt($expanded) };
1663 return '' unless length($sql);
1665 my $final_sql = $self->_sqlcase(' order by ').$sql;
1667 return ($final_sql, @bind);
1670 # _order_by no longer needs to call this so doesn't but DBIC uses it.
1672 sub _order_by_chunks {
1673 my ($self, $arg) = @_;
1675 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1677 my @res = $self->_chunkify_order_by($expanded);
1678 (ref() ? $_->[0] : $_) .= '' for @res;
1682 sub _chunkify_order_by {
1683 my ($self, $expanded) = @_;
1685 return grep length, @{ $self->render_aqt($expanded) }
1686 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1689 if (ref() eq 'HASH' and $_->{-op} and $_->{-op}[0] eq ',') {
1690 my ($comma, @list) = @{$_->{-op}};
1691 return map $self->_chunkify_order_by($_), @list;
1693 return $self->render_aqt($_);
1697 #======================================================================
1698 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1699 #======================================================================
1705 $self->expand_maybe_list_expr($from, -ident)
1710 #======================================================================
1712 #======================================================================
1714 sub expand_maybe_list_expr {
1715 my ($self, $expr, $default) = @_;
1717 ',', map $self->expand_expr($_, $default),
1718 @{$expr->{-op}}[1..$#{$expr->{-op}}]
1719 ] } if ref($expr) eq 'HASH' and ($expr->{-op}||[''])->[0] eq ',';
1720 return +{ -op => [ ',',
1721 map $self->expand_expr($_, $default),
1722 ref($expr) eq 'ARRAY' ? @$expr : $expr
1726 # highly optimized, as it's called way too often
1728 # my ($self, $label) = @_;
1730 return '' unless defined $_[1];
1731 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1732 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1734 unless ($_[0]->{quote_char}) {
1735 if (ref($_[1]) eq 'ARRAY') {
1736 return join($_[0]->{name_sep}||'.', @{$_[1]});
1738 $_[0]->_assert_pass_injection_guard($_[1]);
1743 my $qref = ref $_[0]->{quote_char};
1745 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1746 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1747 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1749 my $esc = $_[0]->{escape_char} || $r;
1751 # parts containing * are naturally unquoted
1753 $_[0]->{name_sep}||'',
1757 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1759 (ref($_[1]) eq 'ARRAY'
1763 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1771 # Conversion, if applicable
1773 #my ($self, $arg) = @_;
1774 if (my $conv = $_[0]->{convert_where}) {
1775 return @{ $_[0]->join_query_parts('',
1776 $_[0]->format_keyword($conv),
1785 #my ($self, $col, @vals) = @_;
1786 # called often - tighten code
1787 return $_[0]->{bindtype} eq 'columns'
1788 ? map {[$_[1], $_]} @_[2 .. $#_]
1793 # Dies if any element of @bind is not in [colname => value] format
1794 # if bindtype is 'columns'.
1795 sub _assert_bindval_matches_bindtype {
1796 # my ($self, @bind) = @_;
1798 if ($self->{bindtype} eq 'columns') {
1800 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1801 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1807 sub _join_sql_clauses {
1808 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1810 if (@$clauses_aref > 1) {
1811 my $join = " " . $self->_sqlcase($logic) . " ";
1812 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1813 return ($sql, @$bind_aref);
1815 elsif (@$clauses_aref) {
1816 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1819 return (); # if no SQL, ignore @$bind_aref
1824 # Fix SQL case, if so requested
1826 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1827 # don't touch the argument ... crooked logic, but let's not change it!
1828 return $_[0]->{case} ? $_[1] : uc($_[1]);
1831 sub format_keyword { $_[0]->_sqlcase(join ' ', split '_', $_[1]) }
1833 #======================================================================
1834 # DISPATCHING FROM REFKIND
1835 #======================================================================
1838 my ($self, $data) = @_;
1840 return 'UNDEF' unless defined $data;
1842 # blessed objects are treated like scalars
1843 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1845 return 'SCALAR' unless $ref;
1848 while ($ref eq 'REF') {
1850 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1854 return ($ref||'SCALAR') . ('REF' x $n_steps);
1858 my ($self, $data) = @_;
1859 my @try = ($self->_refkind($data));
1860 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1861 push @try, 'FALLBACK';
1865 sub _METHOD_FOR_refkind {
1866 my ($self, $meth_prefix, $data) = @_;
1869 for (@{$self->_try_refkind($data)}) {
1870 $method = $self->can($meth_prefix."_".$_)
1874 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1878 sub _SWITCH_refkind {
1879 my ($self, $data, $dispatch_table) = @_;
1882 for (@{$self->_try_refkind($data)}) {
1883 $coderef = $dispatch_table->{$_}
1887 puke "no dispatch entry for ".$self->_refkind($data)
1896 #======================================================================
1897 # VALUES, GENERATE, AUTOLOAD
1898 #======================================================================
1900 # LDNOTE: original code from nwiger, didn't touch code in that section
1901 # I feel the AUTOLOAD stuff should not be the default, it should
1902 # only be activated on explicit demand by user.
1906 my $data = shift || return;
1907 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1908 unless ref $data eq 'HASH';
1911 foreach my $k (sort keys %$data) {
1912 my $v = $data->{$k};
1913 $self->_SWITCH_refkind($v, {
1915 if ($self->{array_datatypes}) { # array datatype
1916 push @all_bind, $self->_bindtype($k, $v);
1918 else { # literal SQL with bind
1919 my ($sql, @bind) = @$v;
1920 $self->_assert_bindval_matches_bindtype(@bind);
1921 push @all_bind, @bind;
1924 ARRAYREFREF => sub { # literal SQL with bind
1925 my ($sql, @bind) = @${$v};
1926 $self->_assert_bindval_matches_bindtype(@bind);
1927 push @all_bind, @bind;
1929 SCALARREF => sub { # literal SQL without bind
1931 SCALAR_or_UNDEF => sub {
1932 push @all_bind, $self->_bindtype($k, $v);
1943 my(@sql, @sqlq, @sqlv);
1947 if ($ref eq 'HASH') {
1948 for my $k (sort keys %$_) {
1951 my $label = $self->_quote($k);
1952 if ($r eq 'ARRAY') {
1953 # literal SQL with bind
1954 my ($sql, @bind) = @$v;
1955 $self->_assert_bindval_matches_bindtype(@bind);
1956 push @sqlq, "$label = $sql";
1958 } elsif ($r eq 'SCALAR') {
1959 # literal SQL without bind
1960 push @sqlq, "$label = $$v";
1962 push @sqlq, "$label = ?";
1963 push @sqlv, $self->_bindtype($k, $v);
1966 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1967 } elsif ($ref eq 'ARRAY') {
1968 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1971 if ($r eq 'ARRAY') { # literal SQL with bind
1972 my ($sql, @bind) = @$v;
1973 $self->_assert_bindval_matches_bindtype(@bind);
1976 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1977 # embedded literal SQL
1984 push @sql, '(' . join(', ', @sqlq) . ')';
1985 } elsif ($ref eq 'SCALAR') {
1989 # strings get case twiddled
1990 push @sql, $self->_sqlcase($_);
1994 my $sql = join ' ', @sql;
1996 # this is pretty tricky
1997 # if ask for an array, return ($stmt, @bind)
1998 # otherwise, s/?/shift @sqlv/ to put it inline
2000 return ($sql, @sqlv);
2002 1 while $sql =~ s/\?/my $d = shift(@sqlv);
2003 ref $d ? $d->[1] : $d/e;
2012 # This allows us to check for a local, then _form, attr
2014 my($name) = $AUTOLOAD =~ /.*::(.+)/;
2015 puke "AUTOLOAD invoked for method name ${name} and allow_autoload option not set" unless $self->{allow_autoload};
2016 return $self->generate($name, @_);
2027 SQL::Abstract - Generate SQL from Perl data structures
2033 my $sql = SQL::Abstract->new;
2035 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
2037 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
2039 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
2041 my($stmt, @bind) = $sql->delete($table, \%where);
2043 # Then, use these in your DBI statements
2044 my $sth = $dbh->prepare($stmt);
2045 $sth->execute(@bind);
2047 # Just generate the WHERE clause
2048 my($stmt, @bind) = $sql->where(\%where, $order);
2050 # Return values in the same order, for hashed queries
2051 # See PERFORMANCE section for more details
2052 my @bind = $sql->values(\%fieldvals);
2056 This module was inspired by the excellent L<DBIx::Abstract>.
2057 However, in using that module I found that what I really wanted
2058 to do was generate SQL, but still retain complete control over my
2059 statement handles and use the DBI interface. So, I set out to
2060 create an abstract SQL generation module.
2062 While based on the concepts used by L<DBIx::Abstract>, there are
2063 several important differences, especially when it comes to WHERE
2064 clauses. I have modified the concepts used to make the SQL easier
2065 to generate from Perl data structures and, IMO, more intuitive.
2066 The underlying idea is for this module to do what you mean, based
2067 on the data structures you provide it. The big advantage is that
2068 you don't have to modify your code every time your data changes,
2069 as this module figures it out.
2071 To begin with, an SQL INSERT is as easy as just specifying a hash
2072 of C<key=value> pairs:
2075 name => 'Jimbo Bobson',
2076 phone => '123-456-7890',
2077 address => '42 Sister Lane',
2078 city => 'St. Louis',
2079 state => 'Louisiana',
2082 The SQL can then be generated with this:
2084 my($stmt, @bind) = $sql->insert('people', \%data);
2086 Which would give you something like this:
2088 $stmt = "INSERT INTO people
2089 (address, city, name, phone, state)
2090 VALUES (?, ?, ?, ?, ?)";
2091 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
2092 '123-456-7890', 'Louisiana');
2094 These are then used directly in your DBI code:
2096 my $sth = $dbh->prepare($stmt);
2097 $sth->execute(@bind);
2099 =head2 Inserting and Updating Arrays
2101 If your database has array types (like for example Postgres),
2102 activate the special option C<< array_datatypes => 1 >>
2103 when creating the C<SQL::Abstract> object.
2104 Then you may use an arrayref to insert and update database array types:
2106 my $sql = SQL::Abstract->new(array_datatypes => 1);
2108 planets => [qw/Mercury Venus Earth Mars/]
2111 my($stmt, @bind) = $sql->insert('solar_system', \%data);
2115 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
2117 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
2120 =head2 Inserting and Updating SQL
2122 In order to apply SQL functions to elements of your C<%data> you may
2123 specify a reference to an arrayref for the given hash value. For example,
2124 if you need to execute the Oracle C<to_date> function on a value, you can
2125 say something like this:
2129 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
2132 The first value in the array is the actual SQL. Any other values are
2133 optional and would be included in the bind values array. This gives
2136 my($stmt, @bind) = $sql->insert('people', \%data);
2138 $stmt = "INSERT INTO people (name, date_entered)
2139 VALUES (?, to_date(?,'MM/DD/YYYY'))";
2140 @bind = ('Bill', '03/02/2003');
2142 An UPDATE is just as easy, all you change is the name of the function:
2144 my($stmt, @bind) = $sql->update('people', \%data);
2146 Notice that your C<%data> isn't touched; the module will generate
2147 the appropriately quirky SQL for you automatically. Usually you'll
2148 want to specify a WHERE clause for your UPDATE, though, which is
2149 where handling C<%where> hashes comes in handy...
2151 =head2 Complex where statements
2153 This module can generate pretty complicated WHERE statements
2154 easily. For example, simple C<key=value> pairs are taken to mean
2155 equality, and if you want to see if a field is within a set
2156 of values, you can use an arrayref. Let's say we wanted to
2157 SELECT some data based on this criteria:
2160 requestor => 'inna',
2161 worker => ['nwiger', 'rcwe', 'sfz'],
2162 status => { '!=', 'completed' }
2165 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
2167 The above would give you something like this:
2169 $stmt = "SELECT * FROM tickets WHERE
2170 ( requestor = ? ) AND ( status != ? )
2171 AND ( worker = ? OR worker = ? OR worker = ? )";
2172 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
2174 Which you could then use in DBI code like so:
2176 my $sth = $dbh->prepare($stmt);
2177 $sth->execute(@bind);
2183 The methods are simple. There's one for every major SQL operation,
2184 and a constructor you use first. The arguments are specified in a
2185 similar order for each method (table, then fields, then a where
2186 clause) to try and simplify things.
2188 =head2 new(option => 'value')
2190 The C<new()> function takes a list of options and values, and returns
2191 a new B<SQL::Abstract> object which can then be used to generate SQL
2192 through the methods below. The options accepted are:
2198 If set to 'lower', then SQL will be generated in all lowercase. By
2199 default SQL is generated in "textbook" case meaning something like:
2201 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
2203 Any setting other than 'lower' is ignored.
2207 This determines what the default comparison operator is. By default
2208 it is C<=>, meaning that a hash like this:
2210 %where = (name => 'nwiger', email => 'nate@wiger.org');
2212 Will generate SQL like this:
2214 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
2216 However, you may want loose comparisons by default, so if you set
2217 C<cmp> to C<like> you would get SQL such as:
2219 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
2221 You can also override the comparison on an individual basis - see
2222 the huge section on L</"WHERE CLAUSES"> at the bottom.
2224 =item sqltrue, sqlfalse
2226 Expressions for inserting boolean values within SQL statements.
2227 By default these are C<1=1> and C<1=0>. They are used
2228 by the special operators C<-in> and C<-not_in> for generating
2229 correct SQL even when the argument is an empty array (see below).
2233 This determines the default logical operator for multiple WHERE
2234 statements in arrays or hashes. If absent, the default logic is "or"
2235 for arrays, and "and" for hashes. This means that a WHERE
2239 event_date => {'>=', '2/13/99'},
2240 event_date => {'<=', '4/24/03'},
2243 will generate SQL like this:
2245 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
2247 This is probably not what you want given this query, though (look
2248 at the dates). To change the "OR" to an "AND", simply specify:
2250 my $sql = SQL::Abstract->new(logic => 'and');
2252 Which will change the above C<WHERE> to:
2254 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
2256 The logic can also be changed locally by inserting
2257 a modifier in front of an arrayref:
2259 @where = (-and => [event_date => {'>=', '2/13/99'},
2260 event_date => {'<=', '4/24/03'} ]);
2262 See the L</"WHERE CLAUSES"> section for explanations.
2266 This will automatically convert comparisons using the specified SQL
2267 function for both column and value. This is mostly used with an argument
2268 of C<upper> or C<lower>, so that the SQL will have the effect of
2269 case-insensitive "searches". For example, this:
2271 $sql = SQL::Abstract->new(convert => 'upper');
2272 %where = (keywords => 'MaKe iT CAse inSeNSItive');
2274 Will turn out the following SQL:
2276 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
2278 The conversion can be C<upper()>, C<lower()>, or any other SQL function
2279 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
2280 not validate this option; it will just pass through what you specify verbatim).
2284 This is a kludge because many databases suck. For example, you can't
2285 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
2286 Instead, you have to use C<bind_param()>:
2288 $sth->bind_param(1, 'reg data');
2289 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
2291 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
2292 which loses track of which field each slot refers to. Fear not.
2294 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
2295 Currently, you can specify either C<normal> (default) or C<columns>. If you
2296 specify C<columns>, you will get an array that looks like this:
2298 my $sql = SQL::Abstract->new(bindtype => 'columns');
2299 my($stmt, @bind) = $sql->insert(...);
2302 [ 'column1', 'value1' ],
2303 [ 'column2', 'value2' ],
2304 [ 'column3', 'value3' ],
2307 You can then iterate through this manually, using DBI's C<bind_param()>.
2309 $sth->prepare($stmt);
2312 my($col, $data) = @$_;
2313 if ($col eq 'details' || $col eq 'comments') {
2314 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
2315 } elsif ($col eq 'image') {
2316 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
2318 $sth->bind_param($i, $data);
2322 $sth->execute; # execute without @bind now
2324 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
2325 Basically, the advantage is still that you don't have to care which fields
2326 are or are not included. You could wrap that above C<for> loop in a simple
2327 sub called C<bind_fields()> or something and reuse it repeatedly. You still
2328 get a layer of abstraction over manual SQL specification.
2330 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
2331 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
2332 will expect the bind values in this format.
2336 This is the character that a table or column name will be quoted
2337 with. By default this is an empty string, but you could set it to
2338 the character C<`>, to generate SQL like this:
2340 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
2342 Alternatively, you can supply an array ref of two items, the first being the left
2343 hand quote character, and the second the right hand quote character. For
2344 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
2345 that generates SQL like this:
2347 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
2349 Quoting is useful if you have tables or columns names that are reserved
2350 words in your database's SQL dialect.
2354 This is the character that will be used to escape L</quote_char>s appearing
2355 in an identifier before it has been quoted.
2357 The parameter default in case of a single L</quote_char> character is the quote
2360 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
2361 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
2362 of the B<opening (left)> L</quote_char> within the identifier are currently left
2363 untouched. The default for opening-closing-style quotes may change in future
2364 versions, thus you are B<strongly encouraged> to specify the escape character
2369 This is the character that separates a table and column name. It is
2370 necessary to specify this when the C<quote_char> option is selected,
2371 so that tables and column names can be individually quoted like this:
2373 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2375 =item injection_guard
2377 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2378 column name specified in a query structure. This is a safety mechanism to avoid
2379 injection attacks when mishandling user input e.g.:
2381 my %condition_as_column_value_pairs = get_values_from_user();
2382 $sqla->select( ... , \%condition_as_column_value_pairs );
2384 If the expression matches an exception is thrown. Note that literal SQL
2385 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2387 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2389 =item array_datatypes
2391 When this option is true, arrayrefs in INSERT or UPDATE are
2392 interpreted as array datatypes and are passed directly
2394 When this option is false, arrayrefs are interpreted
2395 as literal SQL, just like refs to arrayrefs
2396 (but this behavior is for backwards compatibility; when writing
2397 new queries, use the "reference to arrayref" syntax
2403 Takes a reference to a list of "special operators"
2404 to extend the syntax understood by L<SQL::Abstract>.
2405 See section L</"SPECIAL OPERATORS"> for details.
2409 Takes a reference to a list of "unary operators"
2410 to extend the syntax understood by L<SQL::Abstract>.
2411 See section L</"UNARY OPERATORS"> for details.
2417 =head2 insert($table, \@values || \%fieldvals, \%options)
2419 This is the simplest function. You simply give it a table name
2420 and either an arrayref of values or hashref of field/value pairs.
2421 It returns an SQL INSERT statement and a list of bind values.
2422 See the sections on L</"Inserting and Updating Arrays"> and
2423 L</"Inserting and Updating SQL"> for information on how to insert
2424 with those data types.
2426 The optional C<\%options> hash reference may contain additional
2427 options to generate the insert SQL. Currently supported options
2434 Takes either a scalar of raw SQL fields, or an array reference of
2435 field names, and adds on an SQL C<RETURNING> statement at the end.
2436 This allows you to return data generated by the insert statement
2437 (such as row IDs) without performing another C<SELECT> statement.
2438 Note, however, this is not part of the SQL standard and may not
2439 be supported by all database engines.
2443 =head2 update($table, \%fieldvals, \%where, \%options)
2445 This takes a table, hashref of field/value pairs, and an optional
2446 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2448 See the sections on L</"Inserting and Updating Arrays"> and
2449 L</"Inserting and Updating SQL"> for information on how to insert
2450 with those data types.
2452 The optional C<\%options> hash reference may contain additional
2453 options to generate the update SQL. Currently supported options
2460 See the C<returning> option to
2461 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2465 =head2 select($source, $fields, $where, $order)
2467 This returns a SQL SELECT statement and associated list of bind values, as
2468 specified by the arguments:
2474 Specification of the 'FROM' part of the statement.
2475 The argument can be either a plain scalar (interpreted as a table
2476 name, will be quoted), or an arrayref (interpreted as a list
2477 of table names, joined by commas, quoted), or a scalarref
2478 (literal SQL, not quoted).
2482 Specification of the list of fields to retrieve from
2484 The argument can be either an arrayref (interpreted as a list
2485 of field names, will be joined by commas and quoted), or a
2486 plain scalar (literal SQL, not quoted).
2487 Please observe that this API is not as flexible as that of
2488 the first argument C<$source>, for backwards compatibility reasons.
2492 Optional argument to specify the WHERE part of the query.
2493 The argument is most often a hashref, but can also be
2494 an arrayref or plain scalar --
2495 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2499 Optional argument to specify the ORDER BY part of the query.
2500 The argument can be a scalar, a hashref or an arrayref
2501 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2507 =head2 delete($table, \%where, \%options)
2509 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2510 It returns an SQL DELETE statement and list of bind values.
2512 The optional C<\%options> hash reference may contain additional
2513 options to generate the delete SQL. Currently supported options
2520 See the C<returning> option to
2521 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2525 =head2 where(\%where, $order)
2527 This is used to generate just the WHERE clause. For example,
2528 if you have an arbitrary data structure and know what the
2529 rest of your SQL is going to look like, but want an easy way
2530 to produce a WHERE clause, use this. It returns an SQL WHERE
2531 clause and list of bind values.
2534 =head2 values(\%data)
2536 This just returns the values from the hash C<%data>, in the same
2537 order that would be returned from any of the other above queries.
2538 Using this allows you to markedly speed up your queries if you
2539 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2541 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2543 Warning: This is an experimental method and subject to change.
2545 This returns arbitrarily generated SQL. It's a really basic shortcut.
2546 It will return two different things, depending on return context:
2548 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2549 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2551 These would return the following:
2553 # First calling form
2554 $stmt = "CREATE TABLE test (?, ?)";
2555 @bind = (field1, field2);
2557 # Second calling form
2558 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2560 Depending on what you're trying to do, it's up to you to choose the correct
2561 format. In this example, the second form is what you would want.
2565 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2569 ALTER SESSION SET nls_date_format = 'MM/YY'
2571 You get the idea. Strings get their case twiddled, but everything
2572 else remains verbatim.
2574 =head1 EXPORTABLE FUNCTIONS
2576 =head2 is_plain_value
2578 Determines if the supplied argument is a plain value as understood by this
2583 =item * The value is C<undef>
2585 =item * The value is a non-reference
2587 =item * The value is an object with stringification overloading
2589 =item * The value is of the form C<< { -value => $anything } >>
2593 On failure returns C<undef>, on success returns a B<scalar> reference
2594 to the original supplied argument.
2600 The stringification overloading detection is rather advanced: it takes
2601 into consideration not only the presence of a C<""> overload, but if that
2602 fails also checks for enabled
2603 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2604 on either C<0+> or C<bool>.
2606 Unfortunately testing in the field indicates that this
2607 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2608 but only when very large numbers of stringifying objects are involved.
2609 At the time of writing ( Sep 2014 ) there is no clear explanation of
2610 the direct cause, nor is there a manageably small test case that reliably
2611 reproduces the problem.
2613 If you encounter any of the following exceptions in B<random places within
2614 your application stack> - this module may be to blame:
2616 Operation "ne": no method found,
2617 left argument in overloaded package <something>,
2618 right argument in overloaded package <something>
2622 Stub found while resolving method "???" overloading """" in package <something>
2624 If you fall victim to the above - please attempt to reduce the problem
2625 to something that could be sent to the L<SQL::Abstract developers
2626 |DBIx::Class/GETTING HELP/SUPPORT>
2627 (either publicly or privately). As a workaround in the meantime you can
2628 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2629 value, which will most likely eliminate your problem (at the expense of
2630 not being able to properly detect exotic forms of stringification).
2632 This notice and environment variable will be removed in a future version,
2633 as soon as the underlying problem is found and a reliable workaround is
2638 =head2 is_literal_value
2640 Determines if the supplied argument is a literal value as understood by this
2645 =item * C<\$sql_string>
2647 =item * C<\[ $sql_string, @bind_values ]>
2651 On failure returns C<undef>, on success returns an B<array> reference
2652 containing the unpacked version of the supplied literal SQL and bind values.
2654 =head1 WHERE CLAUSES
2658 This module uses a variation on the idea from L<DBIx::Abstract>. It
2659 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2660 module is that things in arrays are OR'ed, and things in hashes
2663 The easiest way to explain is to show lots of examples. After
2664 each C<%where> hash shown, it is assumed you used:
2666 my($stmt, @bind) = $sql->where(\%where);
2668 However, note that the C<%where> hash can be used directly in any
2669 of the other functions as well, as described above.
2671 =head2 Key-value pairs
2673 So, let's get started. To begin, a simple hash:
2677 status => 'completed'
2680 Is converted to SQL C<key = val> statements:
2682 $stmt = "WHERE user = ? AND status = ?";
2683 @bind = ('nwiger', 'completed');
2685 One common thing I end up doing is having a list of values that
2686 a field can be in. To do this, simply specify a list inside of
2691 status => ['assigned', 'in-progress', 'pending'];
2694 This simple code will create the following:
2696 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2697 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2699 A field associated to an empty arrayref will be considered a
2700 logical false and will generate 0=1.
2702 =head2 Tests for NULL values
2704 If the value part is C<undef> then this is converted to SQL <IS NULL>
2713 $stmt = "WHERE user = ? AND status IS NULL";
2716 To test if a column IS NOT NULL:
2720 status => { '!=', undef },
2723 =head2 Specific comparison operators
2725 If you want to specify a different type of operator for your comparison,
2726 you can use a hashref for a given column:
2730 status => { '!=', 'completed' }
2733 Which would generate:
2735 $stmt = "WHERE user = ? AND status != ?";
2736 @bind = ('nwiger', 'completed');
2738 To test against multiple values, just enclose the values in an arrayref:
2740 status => { '=', ['assigned', 'in-progress', 'pending'] };
2742 Which would give you:
2744 "WHERE status = ? OR status = ? OR status = ?"
2747 The hashref can also contain multiple pairs, in which case it is expanded
2748 into an C<AND> of its elements:
2752 status => { '!=', 'completed', -not_like => 'pending%' }
2755 # Or more dynamically, like from a form
2756 $where{user} = 'nwiger';
2757 $where{status}{'!='} = 'completed';
2758 $where{status}{'-not_like'} = 'pending%';
2760 # Both generate this
2761 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2762 @bind = ('nwiger', 'completed', 'pending%');
2765 To get an OR instead, you can combine it with the arrayref idea:
2769 priority => [ { '=', 2 }, { '>', 5 } ]
2772 Which would generate:
2774 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2775 @bind = ('2', '5', 'nwiger');
2777 If you want to include literal SQL (with or without bind values), just use a
2778 scalar reference or reference to an arrayref as the value:
2781 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2782 date_expires => { '<' => \"now()" }
2785 Which would generate:
2787 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2788 @bind = ('11/26/2008');
2791 =head2 Logic and nesting operators
2793 In the example above,
2794 there is a subtle trap if you want to say something like
2795 this (notice the C<AND>):
2797 WHERE priority != ? AND priority != ?
2799 Because, in Perl you I<can't> do this:
2801 priority => { '!=' => 2, '!=' => 1 }
2803 As the second C<!=> key will obliterate the first. The solution
2804 is to use the special C<-modifier> form inside an arrayref:
2806 priority => [ -and => {'!=', 2},
2810 Normally, these would be joined by C<OR>, but the modifier tells it
2811 to use C<AND> instead. (Hint: You can use this in conjunction with the
2812 C<logic> option to C<new()> in order to change the way your queries
2813 work by default.) B<Important:> Note that the C<-modifier> goes
2814 B<INSIDE> the arrayref, as an extra first element. This will
2815 B<NOT> do what you think it might:
2817 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2819 Here is a quick list of equivalencies, since there is some overlap:
2822 status => {'!=', 'completed', 'not like', 'pending%' }
2823 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2826 status => {'=', ['assigned', 'in-progress']}
2827 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2828 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2832 =head2 Special operators: IN, BETWEEN, etc.
2834 You can also use the hashref format to compare a list of fields using the
2835 C<IN> comparison operator, by specifying the list as an arrayref:
2838 status => 'completed',
2839 reportid => { -in => [567, 2335, 2] }
2842 Which would generate:
2844 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2845 @bind = ('completed', '567', '2335', '2');
2847 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2850 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2851 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2852 'sqltrue' (by default: C<1=1>).
2854 In addition to the array you can supply a chunk of literal sql or
2855 literal sql with bind:
2858 customer => { -in => \[
2859 'SELECT cust_id FROM cust WHERE balance > ?',
2862 status => { -in => \'SELECT status_codes FROM states' },
2868 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2869 AND status IN ( SELECT status_codes FROM states )
2873 Finally, if the argument to C<-in> is not a reference, it will be
2874 treated as a single-element array.
2876 Another pair of operators is C<-between> and C<-not_between>,
2877 used with an arrayref of two values:
2881 completion_date => {
2882 -not_between => ['2002-10-01', '2003-02-06']
2888 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2890 Just like with C<-in> all plausible combinations of literal SQL
2894 start0 => { -between => [ 1, 2 ] },
2895 start1 => { -between => \["? AND ?", 1, 2] },
2896 start2 => { -between => \"lower(x) AND upper(y)" },
2897 start3 => { -between => [
2899 \["upper(?)", 'stuff' ],
2906 ( start0 BETWEEN ? AND ? )
2907 AND ( start1 BETWEEN ? AND ? )
2908 AND ( start2 BETWEEN lower(x) AND upper(y) )
2909 AND ( start3 BETWEEN lower(x) AND upper(?) )
2911 @bind = (1, 2, 1, 2, 'stuff');
2914 These are the two builtin "special operators"; but the
2915 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
2917 =head2 Unary operators: bool
2919 If you wish to test against boolean columns or functions within your
2920 database you can use the C<-bool> and C<-not_bool> operators. For
2921 example to test the column C<is_user> being true and the column
2922 C<is_enabled> being false you would use:-
2926 -not_bool => 'is_enabled',
2931 WHERE is_user AND NOT is_enabled
2933 If a more complex combination is required, testing more conditions,
2934 then you should use the and/or operators:-
2939 -not_bool => { two=> { -rlike => 'bar' } },
2940 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
2951 (NOT ( three = ? OR three > ? ))
2954 =head2 Nested conditions, -and/-or prefixes
2956 So far, we've seen how multiple conditions are joined with a top-level
2957 C<AND>. We can change this by putting the different conditions we want in
2958 hashes and then putting those hashes in an array. For example:
2963 status => { -like => ['pending%', 'dispatched'] },
2967 status => 'unassigned',
2971 This data structure would create the following:
2973 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2974 OR ( user = ? AND status = ? ) )";
2975 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2978 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2979 to change the logic inside:
2985 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2986 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2993 $stmt = "WHERE ( user = ?
2994 AND ( ( workhrs > ? AND geo = ? )
2995 OR ( workhrs < ? OR geo = ? ) ) )";
2996 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
2998 =head3 Algebraic inconsistency, for historical reasons
3000 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
3001 operator goes C<outside> of the nested structure; whereas when connecting
3002 several constraints on one column, the C<-and> operator goes
3003 C<inside> the arrayref. Here is an example combining both features:
3006 -and => [a => 1, b => 2],
3007 -or => [c => 3, d => 4],
3008 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
3013 WHERE ( ( ( a = ? AND b = ? )
3014 OR ( c = ? OR d = ? )
3015 OR ( e LIKE ? AND e LIKE ? ) ) )
3017 This difference in syntax is unfortunate but must be preserved for
3018 historical reasons. So be careful: the two examples below would
3019 seem algebraically equivalent, but they are not
3022 { -like => 'foo%' },
3023 { -like => '%bar' },
3025 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
3028 { col => { -like => 'foo%' } },
3029 { col => { -like => '%bar' } },
3031 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
3034 =head2 Literal SQL and value type operators
3036 The basic premise of SQL::Abstract is that in WHERE specifications the "left
3037 side" is a column name and the "right side" is a value (normally rendered as
3038 a placeholder). This holds true for both hashrefs and arrayref pairs as you
3039 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
3040 alter this behavior. There are several ways of doing so.
3044 This is a virtual operator that signals the string to its right side is an
3045 identifier (a column name) and not a value. For example to compare two
3046 columns you would write:
3049 priority => { '<', 2 },
3050 requestor => { -ident => 'submitter' },
3055 $stmt = "WHERE priority < ? AND requestor = submitter";
3058 If you are maintaining legacy code you may see a different construct as
3059 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
3064 This is a virtual operator that signals that the construct to its right side
3065 is a value to be passed to DBI. This is for example necessary when you want
3066 to write a where clause against an array (for RDBMS that support such
3067 datatypes). For example:
3070 array => { -value => [1, 2, 3] }
3075 $stmt = 'WHERE array = ?';
3076 @bind = ([1, 2, 3]);
3078 Note that if you were to simply say:
3084 the result would probably not be what you wanted:
3086 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
3091 Finally, sometimes only literal SQL will do. To include a random snippet
3092 of SQL verbatim, you specify it as a scalar reference. Consider this only
3093 as a last resort. Usually there is a better way. For example:
3096 priority => { '<', 2 },
3097 requestor => { -in => \'(SELECT name FROM hitmen)' },
3102 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
3105 Note that in this example, you only get one bind parameter back, since
3106 the verbatim SQL is passed as part of the statement.
3110 Never use untrusted input as a literal SQL argument - this is a massive
3111 security risk (there is no way to check literal snippets for SQL
3112 injections and other nastyness). If you need to deal with untrusted input
3113 use literal SQL with placeholders as described next.
3115 =head3 Literal SQL with placeholders and bind values (subqueries)
3117 If the literal SQL to be inserted has placeholders and bind values,
3118 use a reference to an arrayref (yes this is a double reference --
3119 not so common, but perfectly legal Perl). For example, to find a date
3120 in Postgres you can use something like this:
3123 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
3128 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
3131 Note that you must pass the bind values in the same format as they are returned
3132 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
3133 to C<columns>, you must provide the bind values in the
3134 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
3135 scalar value; most commonly the column name, but you can use any scalar value
3136 (including references and blessed references), L<SQL::Abstract> will simply
3137 pass it through intact. So if C<bindtype> is set to C<columns> the above
3138 example will look like:
3141 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
3144 Literal SQL is especially useful for nesting parenthesized clauses in the
3145 main SQL query. Here is a first example:
3147 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
3151 bar => \["IN ($sub_stmt)" => @sub_bind],
3156 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
3157 WHERE c2 < ? AND c3 LIKE ?))";
3158 @bind = (1234, 100, "foo%");
3160 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
3161 are expressed in the same way. Of course the C<$sub_stmt> and
3162 its associated bind values can be generated through a former call
3165 my ($sub_stmt, @sub_bind)
3166 = $sql->select("t1", "c1", {c2 => {"<" => 100},
3167 c3 => {-like => "foo%"}});
3170 bar => \["> ALL ($sub_stmt)" => @sub_bind],
3173 In the examples above, the subquery was used as an operator on a column;
3174 but the same principle also applies for a clause within the main C<%where>
3175 hash, like an EXISTS subquery:
3177 my ($sub_stmt, @sub_bind)
3178 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
3179 my %where = ( -and => [
3181 \["EXISTS ($sub_stmt)" => @sub_bind],
3186 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
3187 WHERE c1 = ? AND c2 > t0.c0))";
3191 Observe that the condition on C<c2> in the subquery refers to
3192 column C<t0.c0> of the main query: this is I<not> a bind
3193 value, so we have to express it through a scalar ref.
3194 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
3195 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
3196 what we wanted here.
3198 Finally, here is an example where a subquery is used
3199 for expressing unary negation:
3201 my ($sub_stmt, @sub_bind)
3202 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
3203 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
3205 lname => {like => '%son%'},
3206 \["NOT ($sub_stmt)" => @sub_bind],
3211 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
3212 @bind = ('%son%', 10, 20)
3214 =head3 Deprecated usage of Literal SQL
3216 Below are some examples of archaic use of literal SQL. It is shown only as
3217 reference for those who deal with legacy code. Each example has a much
3218 better, cleaner and safer alternative that users should opt for in new code.
3224 my %where = ( requestor => \'IS NOT NULL' )
3226 $stmt = "WHERE requestor IS NOT NULL"
3228 This used to be the way of generating NULL comparisons, before the handling
3229 of C<undef> got formalized. For new code please use the superior syntax as
3230 described in L</Tests for NULL values>.
3234 my %where = ( requestor => \'= submitter' )
3236 $stmt = "WHERE requestor = submitter"
3238 This used to be the only way to compare columns. Use the superior L</-ident>
3239 method for all new code. For example an identifier declared in such a way
3240 will be properly quoted if L</quote_char> is properly set, while the legacy
3241 form will remain as supplied.
3245 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
3247 $stmt = "WHERE completed > ? AND is_ready"
3248 @bind = ('2012-12-21')
3250 Using an empty string literal used to be the only way to express a boolean.
3251 For all new code please use the much more readable
3252 L<-bool|/Unary operators: bool> operator.
3258 These pages could go on for a while, since the nesting of the data
3259 structures this module can handle are pretty much unlimited (the
3260 module implements the C<WHERE> expansion as a recursive function
3261 internally). Your best bet is to "play around" with the module a
3262 little to see how the data structures behave, and choose the best
3263 format for your data based on that.
3265 And of course, all the values above will probably be replaced with
3266 variables gotten from forms or the command line. After all, if you
3267 knew everything ahead of time, you wouldn't have to worry about
3268 dynamically-generating SQL and could just hardwire it into your
3271 =head1 ORDER BY CLAUSES
3273 Some functions take an order by clause. This can either be a scalar (just a
3274 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
3275 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
3278 Given | Will Generate
3279 ---------------------------------------------------------------
3281 'colA' | ORDER BY colA
3283 [qw/colA colB/] | ORDER BY colA, colB
3285 {-asc => 'colA'} | ORDER BY colA ASC
3287 {-desc => 'colB'} | ORDER BY colB DESC
3289 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
3291 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
3293 \'colA DESC' | ORDER BY colA DESC
3295 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
3296 | /* ...with $x bound to ? */
3299 { -asc => 'colA' }, | colA ASC,
3300 { -desc => [qw/colB/] }, | colB DESC,
3301 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
3302 \'colE DESC', | colE DESC,
3303 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
3304 ] | /* ...with $x bound to ? */
3305 ===============================================================
3309 =head1 SPECIAL OPERATORS
3311 my $sqlmaker = SQL::Abstract->new(special_ops => [
3315 my ($self, $field, $op, $arg) = @_;
3321 handler => 'method_name',
3325 A "special operator" is a SQL syntactic clause that can be
3326 applied to a field, instead of a usual binary operator.
3329 WHERE field IN (?, ?, ?)
3330 WHERE field BETWEEN ? AND ?
3331 WHERE MATCH(field) AGAINST (?, ?)
3333 Special operators IN and BETWEEN are fairly standard and therefore
3334 are builtin within C<SQL::Abstract> (as the overridable methods
3335 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
3336 like the MATCH .. AGAINST example above which is specific to MySQL,
3337 you can write your own operator handlers - supply a C<special_ops>
3338 argument to the C<new> method. That argument takes an arrayref of
3339 operator definitions; each operator definition is a hashref with two
3346 the regular expression to match the operator
3350 Either a coderef or a plain scalar method name. In both cases
3351 the expected return is C<< ($sql, @bind) >>.
3353 When supplied with a method name, it is simply called on the
3354 L<SQL::Abstract> object as:
3356 $self->$method_name($field, $op, $arg)
3360 $field is the LHS of the operator
3361 $op is the part that matched the handler regex
3364 When supplied with a coderef, it is called as:
3366 $coderef->($self, $field, $op, $arg)
3371 For example, here is an implementation
3372 of the MATCH .. AGAINST syntax for MySQL
3374 my $sqlmaker = SQL::Abstract->new(special_ops => [
3376 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3377 {regex => qr/^match$/i,
3379 my ($self, $field, $op, $arg) = @_;
3380 $arg = [$arg] if not ref $arg;
3381 my $label = $self->_quote($field);
3382 my ($placeholder) = $self->_convert('?');
3383 my $placeholders = join ", ", (($placeholder) x @$arg);
3384 my $sql = $self->_sqlcase('match') . " ($label) "
3385 . $self->_sqlcase('against') . " ($placeholders) ";
3386 my @bind = $self->_bindtype($field, @$arg);
3387 return ($sql, @bind);
3394 =head1 UNARY OPERATORS
3396 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3400 my ($self, $op, $arg) = @_;
3406 handler => 'method_name',
3410 A "unary operator" is a SQL syntactic clause that can be
3411 applied to a field - the operator goes before the field
3413 You can write your own operator handlers - supply a C<unary_ops>
3414 argument to the C<new> method. That argument takes an arrayref of
3415 operator definitions; each operator definition is a hashref with two
3422 the regular expression to match the operator
3426 Either a coderef or a plain scalar method name. In both cases
3427 the expected return is C<< $sql >>.
3429 When supplied with a method name, it is simply called on the
3430 L<SQL::Abstract> object as:
3432 $self->$method_name($op, $arg)
3436 $op is the part that matched the handler regex
3437 $arg is the RHS or argument of the operator
3439 When supplied with a coderef, it is called as:
3441 $coderef->($self, $op, $arg)
3449 Thanks to some benchmarking by Mark Stosberg, it turns out that
3450 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3451 I must admit this wasn't an intentional design issue, but it's a
3452 byproduct of the fact that you get to control your C<DBI> handles
3455 To maximize performance, use a code snippet like the following:
3457 # prepare a statement handle using the first row
3458 # and then reuse it for the rest of the rows
3460 for my $href (@array_of_hashrefs) {
3461 $stmt ||= $sql->insert('table', $href);
3462 $sth ||= $dbh->prepare($stmt);
3463 $sth->execute($sql->values($href));
3466 The reason this works is because the keys in your C<$href> are sorted
3467 internally by B<SQL::Abstract>. Thus, as long as your data retains
3468 the same structure, you only have to generate the SQL the first time
3469 around. On subsequent queries, simply use the C<values> function provided
3470 by this module to return your values in the correct order.
3472 However this depends on the values having the same type - if, for
3473 example, the values of a where clause may either have values
3474 (resulting in sql of the form C<column = ?> with a single bind
3475 value), or alternatively the values might be C<undef> (resulting in
3476 sql of the form C<column IS NULL> with no bind value) then the
3477 caching technique suggested will not work.
3481 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3482 really like this part (I do, at least). Building up a complex query
3483 can be as simple as the following:
3490 use CGI::FormBuilder;
3493 my $form = CGI::FormBuilder->new(...);
3494 my $sql = SQL::Abstract->new;
3496 if ($form->submitted) {
3497 my $field = $form->field;
3498 my $id = delete $field->{id};
3499 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3502 Of course, you would still have to connect using C<DBI> to run the
3503 query, but the point is that if you make your form look like your
3504 table, the actual query script can be extremely simplistic.
3506 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3507 a fast interface to returning and formatting data. I frequently
3508 use these three modules together to write complex database query
3509 apps in under 50 lines.
3511 =head1 HOW TO CONTRIBUTE
3513 Contributions are always welcome, in all usable forms (we especially
3514 welcome documentation improvements). The delivery methods include git-
3515 or unified-diff formatted patches, GitHub pull requests, or plain bug
3516 reports either via RT or the Mailing list. Contributors are generally
3517 granted full access to the official repository after their first several
3518 patches pass successful review.
3520 This project is maintained in a git repository. The code and related tools are
3521 accessible at the following locations:
3525 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3527 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3529 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3531 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3537 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3538 Great care has been taken to preserve the I<published> behavior
3539 documented in previous versions in the 1.* family; however,
3540 some features that were previously undocumented, or behaved
3541 differently from the documentation, had to be changed in order
3542 to clarify the semantics. Hence, client code that was relying
3543 on some dark areas of C<SQL::Abstract> v1.*
3544 B<might behave differently> in v1.50.
3546 The main changes are:
3552 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3556 support for the { operator => \"..." } construct (to embed literal SQL)
3560 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3564 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3568 defensive programming: check arguments
3572 fixed bug with global logic, which was previously implemented
3573 through global variables yielding side-effects. Prior versions would
3574 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3575 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3576 Now this is interpreted
3577 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3582 fixed semantics of _bindtype on array args
3586 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3587 we just avoid shifting arrays within that tree.
3591 dropped the C<_modlogic> function
3595 =head1 ACKNOWLEDGEMENTS
3597 There are a number of individuals that have really helped out with
3598 this module. Unfortunately, most of them submitted bugs via CPAN
3599 so I have no idea who they are! But the people I do know are:
3601 Ash Berlin (order_by hash term support)
3602 Matt Trout (DBIx::Class support)
3603 Mark Stosberg (benchmarking)
3604 Chas Owens (initial "IN" operator support)
3605 Philip Collins (per-field SQL functions)
3606 Eric Kolve (hashref "AND" support)
3607 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3608 Dan Kubb (support for "quote_char" and "name_sep")
3609 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3610 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3611 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3612 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3613 Oliver Charles (support for "RETURNING" after "INSERT")
3619 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3623 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3625 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3627 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3628 While not an official support venue, C<DBIx::Class> makes heavy use of
3629 C<SQL::Abstract>, and as such list members there are very familiar with
3630 how to create queries.
3634 This module is free software; you may copy this under the same
3635 terms as perl itself (either the GNU General Public License or
3636 the Artistic License)