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 bool => '_expand_bool',
143 nest => '_expand_nest',
144 row => '_expand_row',
146 func => '_expand_func',
147 values => '_expand_values',
148 bind => '_expand_noop',
149 literal => '_expand_noop',
152 'between' => '_expand_between',
153 'not_between' => '_expand_between',
154 'in' => '_expand_in',
155 'not_in' => '_expand_in',
156 'nest' => '_expand_nest',
157 (map +($_ => '_expand_op_andor'), ('and', 'or')),
158 (map +($_ => '_expand_op_is'), ('is', 'is_not')),
159 'ident' => '_expand_ident',
160 'value' => '_expand_value',
163 (map +($_, "_render_$_"), qw(op func bind ident literal row values)),
166 (map +($_ => '_render_op_between'), 'between', 'not_between'),
167 (map +($_ => '_render_op_in'), 'in', 'not_in'),
168 (map +($_ => '_render_unop_postfix'),
169 'is_null', 'is_not_null', 'asc', 'desc',
171 (not => '_render_unop_paren'),
172 (map +($_ => '_render_op_andor'), qw(and or)),
173 ',' => '_render_op_multop',
176 delete => [ qw(target where returning) ],
177 update => [ qw(target set where returning) ],
178 insert => [ qw(target fields from returning) ],
179 select => [ qw(select from where order_by) ],
182 'delete.from' => '_expand_delete_clause_target',
183 'update.update' => '_expand_update_clause_target',
184 'insert.into' => '_expand_insert_clause_target',
185 'insert.values' => '_expand_insert_clause_from',
188 'delete.target' => '_render_delete_clause_target',
189 'update.target' => '_render_update_clause_target',
190 'insert.target' => '_render_insert_clause_target',
191 'insert.fields' => '_render_insert_clause_fields',
192 'insert.from' => '_render_insert_clause_from',
196 foreach my $stmt (keys %{$Defaults{clauses_of}}) {
197 $Defaults{expand}{$stmt} = '_expand_statement';
198 $Defaults{render}{$stmt} = '_render_statement';
199 foreach my $clause (@{$Defaults{clauses_of}{$stmt}}) {
200 $Defaults{expand_clause}{"${stmt}.${clause}"}
201 = "_expand_${stmt}_clause_${clause}";
207 my $class = ref($self) || $self;
208 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
210 # choose our case by keeping an option around
211 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
213 # default logic for interpreting arrayrefs
214 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
216 # how to return bind vars
217 $opt{bindtype} ||= 'normal';
219 # default comparison is "=", but can be overridden
222 # try to recognize which are the 'equality' and 'inequality' ops
223 # (temporary quickfix (in 2007), should go through a more seasoned API)
224 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
225 $opt{inequality_op} = qr/^( != | <> )$/ix;
227 $opt{like_op} = qr/^ (is_)?r?like $/xi;
228 $opt{not_like_op} = qr/^ (is_)?not_r?like $/xi;
231 $opt{sqltrue} ||= '1=1';
232 $opt{sqlfalse} ||= '0=1';
235 $opt{special_ops} ||= [];
238 $opt{unary_ops} ||= [];
240 # rudimentary sanity-check for user supplied bits treated as functions/operators
241 # If a purported function matches this regular expression, an exception is thrown.
242 # Literal SQL is *NOT* subject to this check, only functions (and column names
243 # when quoting is not in effect)
246 # need to guard against ()'s in column names too, but this will break tons of
247 # hacks... ideas anyone?
248 $opt{injection_guard} ||= qr/
254 $opt{expand_unary} = {};
256 foreach my $name (sort keys %Defaults) {
257 $opt{$name} = { %{$Defaults{$name}}, %{$opt{$name}||{}} };
260 if ($class ne __PACKAGE__) {
262 # check for overriden methods
264 foreach my $type (qw(insert update delete)) {
265 my $method = "_${type}_returning";
266 if (__PACKAGE__->can($method) ne $class->can($method)) {
267 my $clause = "${type}.returning";
268 $opt{expand_clause}{$clause} = sub { $_[2] },
269 $opt{render_clause}{$clause}
270 = sub { [ $_[0]->$method($_[3]) ] };
273 if (__PACKAGE__->can('_table') ne $class->can('_table')) {
274 $opt{expand_clause}{'select.from'} = sub {
275 return +{ -literal => [ $_[0]->_table($_[2]) ] };
278 if (__PACKAGE__->can('_order_by') ne $class->can('_order_by')) {
279 $opt{expand_clause}{'select.order_by'} = sub { $_[2] };
280 $opt{render_clause}{'select.order_by'} = sub {
281 [ $_[0]->_order_by($_[2]) ];
284 if ($class->isa('DBIx::Class::SQLMaker')) {
285 $opt{warn_once_on_nest} = 1;
286 $opt{disable_old_special_ops} = 1;
287 $opt{render_clause}{'select.where'} = sub {
288 my ($sql, @bind) = $_[0]->where($_[2]);
289 s/\A\s+//, s/\s+\Z// for $sql;
290 return [ $sql, @bind ];
295 if ($opt{lazy_join_sql_parts}) {
296 my $mod = Module::Runtime::use_module('SQL::Abstract::Parts');
297 $opt{join_sql_parts} ||= sub { $mod->new(@_) };
300 $opt{join_sql_parts} ||= sub { join $_[0], @_[1..$#_] };
302 return bless \%opt, $class;
306 my ($self, $name, $key, $value) = @_;
307 return $self->{$name}{$key} unless @_ > 3;
308 $self->{$name}{$key} = $value;
313 foreach my $type (qw(
314 expand op_expand render op_render clause_expand clause_render
316 my $name = join '_', reverse split '_', $type;
317 my $singular = "${type}er";
318 eval qq{sub ${singular} { shift->_ext_rw($name => \@_) }; 1 }
319 or die "Method builder failed for ${singular}: $@";
320 eval qq{sub wrap_${singular} {
321 my (\$self, \$key, \$builder) = \@_;
322 my \$orig = \$self->_ext_rw('${name}', \$key);
325 \$builder->(\$orig, '${name}', \$key)
327 }; 1 } or die "Method builder failed for wrap_${singular}: $@";
328 eval qq{sub ${singular}s {
329 my (\$self, \@args) = \@_;
330 while (my (\$this_key, \$this_value) = splice(\@args, 0, 2)) {
331 \$self->_ext_rw('${name}', \$this_key, \$this_value);
334 }; 1 } or die "Method builder failed for ${singular}s: $@";
335 eval qq{sub wrap_${singular}s {
336 my (\$self, \@args) = \@_;
337 while (my (\$this_key, \$this_builder) = splice(\@args, 0, 2)) {
338 my \$orig = \$self->_ext_rw('${name}', \$this_key);
340 '${name}', \$this_key,
341 \$this_builder->(\$orig, '${name}', \$this_key),
345 }; 1 } or die "Method builder failed for wrap_${singular}s: $@";
346 eval qq{sub ${singular}_list { sort keys %{\$_[0]->{\$name}} }; 1; }
347 or die "Method builder failed for ${singular}_list: $@";
351 sub register_op { $_[0]->{is_op}{$_[1]} = 1; $_[0] }
353 sub statement_list { sort keys %{$_[0]->{clauses_of}} }
356 my ($self, $of, @clauses) = @_;
358 return @{$self->{clauses_of}{$of}||[]};
360 if (ref($clauses[0]) eq 'CODE') {
361 @clauses = $self->${\($clauses[0])}(@{$self->{clauses_of}{$of}||[]});
363 $self->{clauses_of}{$of} = \@clauses;
372 ref($self->{$_}) eq 'HASH'
381 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
382 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
384 sub _assert_pass_injection_guard {
385 if ($_[1] =~ $_[0]->{injection_guard}) {
386 my $class = ref $_[0];
387 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
388 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
389 . "{injection_guard} attribute to ${class}->new()"
394 #======================================================================
396 #======================================================================
399 my ($self, $table, $data, $options) = @_;
402 if (ref($table) eq 'HASH') {
405 my %clauses = (target => $table, values => $data, %{$options||{}});
409 my @rendered = $self->render_statement({ -insert => $stmt });
410 return wantarray ? @rendered : $rendered[0];
413 sub _expand_insert_clause_target {
414 +(target => $_[0]->expand_maybe_list_expr($_[2], -ident));
417 sub _expand_insert_clause_fields {
419 $_[0]->expand_maybe_list_expr($_[2], -ident)
420 ] } if ref($_[2]) eq 'ARRAY';
421 return $_[2]; # should maybe still expand somewhat?
424 sub _expand_insert_clause_from {
425 my ($self, undef, $data) = @_;
426 if (ref($data) eq 'HASH' and (keys(%$data))[0] =~ /^-/) {
427 return $self->expand_expr($data);
429 return $data if ref($data) eq 'HASH' and $data->{-row};
430 my ($f_aqt, $v_aqt) = $self->_expand_insert_values($data);
432 from => { -values => [ $v_aqt ] },
433 ($f_aqt ? (fields => $f_aqt) : ()),
437 sub _expand_insert_clause_returning {
438 +(returning => $_[0]->expand_maybe_list_expr($_[2], -ident));
441 sub _expand_insert_values {
442 my ($self, $data) = @_;
443 if (is_literal_value($data)) {
444 (undef, $self->expand_expr($data));
446 my ($fields, $values) = (
447 ref($data) eq 'HASH' ?
448 ([ sort keys %$data ], [ @{$data}{sort keys %$data} ])
452 # no names (arrayref) means can't generate bindtype
453 !($fields) && $self->{bindtype} eq 'columns'
454 && belch "can't do 'columns' bindtype when called with arrayref";
458 ? $self->expand_expr({ -row => $fields }, -ident)
463 local our $Cur_Col_Meta = $fields->[$_];
464 $self->_expand_insert_value($values->[$_])
471 sub _render_insert_clause_fields {
472 return $_[0]->render_aqt($_[2]);
475 sub _render_insert_clause_target {
476 my ($self, undef, $from) = @_;
477 $self->join_query_parts(' ', $self->format_keyword('insert into'), $from);
480 sub _render_insert_clause_from {
481 return $_[0]->render_aqt($_[2], 1);
484 # So that subclasses can override INSERT ... RETURNING separately from
485 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
486 sub _insert_returning { shift->_returning(@_) }
488 sub _redispatch_returning {
489 my ($self, $type, undef, $returning) = @_;
490 [ $self->${\"_${type}_returning"}({ returning => $returning }) ];
494 my ($self, $options) = @_;
496 my $f = $options->{returning};
498 my ($sql, @bind) = @{ $self->render_aqt(
499 $self->expand_maybe_list_expr($f, -ident)
501 return ($self->_sqlcase(' returning ').$sql, @bind);
504 sub _expand_insert_value {
507 my $k = our $Cur_Col_Meta;
509 if (ref($v) eq 'ARRAY') {
510 if ($self->{array_datatypes}) {
511 return +{ -bind => [ $k, $v ] };
513 my ($sql, @bind) = @$v;
514 $self->_assert_bindval_matches_bindtype(@bind);
515 return +{ -literal => $v };
517 if (ref($v) eq 'HASH') {
518 if (grep !/^-/, keys %$v) {
519 belch "HASH ref as bind value in insert is not supported";
520 return +{ -bind => [ $k, $v ] };
524 return +{ -bind => [ $k, undef ] };
526 return $self->expand_expr($v);
531 #======================================================================
533 #======================================================================
536 my ($self, $table, $set, $where, $options) = @_;
539 if (ref($table) eq 'HASH') {
543 @clauses{qw(target set where)} = ($table, $set, $where);
544 puke "Unsupported data type specified to \$sql->update"
545 unless ref($clauses{set}) eq 'HASH';
546 @clauses{keys %$options} = values %$options;
550 my @rendered = $self->render_statement({ -update => $stmt });
551 return wantarray ? @rendered : $rendered[0];
554 sub _render_update_clause_target {
555 my ($self, undef, $target) = @_;
556 $self->join_query_parts(' ', $self->format_keyword('update'), $target);
559 sub _update_set_values {
560 my ($self, $data) = @_;
562 return @{ $self->render_aqt(
563 $self->_expand_update_set_values(undef, $data),
567 sub _expand_update_set_values {
568 my ($self, undef, $data) = @_;
569 $self->expand_maybe_list_expr( [
572 $set = { -bind => $_ } unless defined $set;
573 +{ -op => [ '=', { -ident => $k }, $set ] };
579 ? ($self->{array_datatypes}
580 ? [ $k, +{ -bind => [ $k, $v ] } ]
581 : [ $k, +{ -literal => $v } ])
583 local our $Cur_Col_Meta = $k;
584 [ $k, $self->_expand_expr($v) ]
591 sub _expand_update_clause_target {
592 my ($self, undef, $target) = @_;
593 +(target => $self->expand_maybe_list_expr($target, -ident));
596 sub _expand_update_clause_set {
597 return $_[2] if ref($_[2]) eq 'HASH' and ($_[2]->{-op}||[''])->[0] eq ',';
598 +(set => $_[0]->_expand_update_set_values($_[1], $_[2]));
601 sub _expand_update_clause_where {
602 +(where => $_[0]->expand_expr($_[2]));
605 sub _expand_update_clause_returning {
606 +(returning => $_[0]->expand_maybe_list_expr($_[2], -ident));
609 # So that subclasses can override UPDATE ... RETURNING separately from
611 sub _update_returning { shift->_returning(@_) }
615 #======================================================================
617 #======================================================================
620 my ($self, @args) = @_;
622 if (ref(my $sel = $args[0]) eq 'HASH') {
626 @clauses{qw(from select where order_by)} = @args;
628 # This oddity is to literalify since historically SQLA doesn't quote
629 # a single identifier argument, so we convert it into a literal
631 $clauses{select} = { -literal => [ $clauses{select}||'*' ] }
632 unless ref($clauses{select});
637 my @rendered = $self->render_statement({ -select => $stmt });
638 return wantarray ? @rendered : $rendered[0];
641 sub _expand_select_clause_select {
642 my ($self, undef, $select) = @_;
643 +(select => $self->expand_maybe_list_expr($select, -ident));
646 sub _expand_select_clause_from {
647 my ($self, undef, $from) = @_;
648 +(from => $self->expand_maybe_list_expr($from, -ident));
651 sub _expand_select_clause_where {
652 my ($self, undef, $where) = @_;
655 if (my $conv = $self->{convert}) {
667 ->wrap_expander(bind => $_wrap)
668 ->wrap_op_expanders(map +($_ => $_wrap), qw(ident value))
669 ->wrap_expander(func => sub {
672 my ($self, $type, $thing) = @_;
673 if (ref($thing) eq 'ARRAY' and $thing->[0] eq $conv
674 and @$thing == 2 and ref($thing->[1]) eq 'HASH'
677 or $thing->[1]{-value}
678 or $thing->[1]{-bind})
680 return { -func => $thing }; # already went through our expander
682 return $self->$orig($type, $thing);
690 return +(where => $sqla->expand_expr($where));
693 sub _expand_select_clause_order_by {
694 my ($self, undef, $order_by) = @_;
695 +(order_by => $self->_expand_order_by($order_by));
699 my ($self, $fields) = @_;
700 return $fields unless ref($fields);
701 return @{ $self->render_aqt(
702 $self->expand_maybe_list_expr($fields, '-ident')
706 #======================================================================
708 #======================================================================
711 my ($self, $table, $where, $options) = @_;
714 if (ref($table) eq 'HASH') {
717 my %clauses = (target => $table, where => $where, %{$options||{}});
721 my @rendered = $self->render_statement({ -delete => $stmt });
722 return wantarray ? @rendered : $rendered[0];
725 # So that subclasses can override DELETE ... RETURNING separately from
727 sub _delete_returning { shift->_returning(@_) }
729 sub _expand_delete_clause_target {
730 +(target => $_[0]->expand_maybe_list_expr($_[2], -ident));
733 sub _expand_delete_clause_where { +(where => $_[0]->expand_expr($_[2])); }
735 sub _expand_delete_clause_returning {
736 +(returning => $_[0]->expand_maybe_list_expr($_[2], -ident));
739 sub _render_delete_clause_target {
740 my ($self, undef, $from) = @_;
741 $self->join_query_parts(' ', $self->format_keyword('delete from'), $from);
744 #======================================================================
746 #======================================================================
750 # Finally, a separate routine just to handle WHERE clauses
752 my ($self, $where, $order) = @_;
754 local $self->{convert_where} = $self->{convert};
757 my ($sql, @bind) = defined($where)
758 ? $self->_recurse_where($where)
760 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
764 my ($order_sql, @order_bind) = $self->_order_by($order);
766 push @bind, @order_bind;
769 return wantarray ? ($sql, @bind) : $sql;
772 { our $Default_Scalar_To = -value }
775 my ($self, $expr, $default_scalar_to) = @_;
776 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
777 $self->_expand_expr($expr);
781 my ($self, $aqt, $top_level) = @_;
782 my ($k, $v, @rest) = %$aqt;
784 die "Not a node type: $k" unless $k =~ s/^-//;
785 if (my $meth = $self->{render}{$k}) {
786 local our $Render_Top_Level = $top_level;
787 return $self->$meth($k, $v);
789 die "notreached: $k";
793 my ($self, $expr, $default_scalar_to) = @_;
794 return @{ $self->render_aqt(
795 $self->expand_expr($expr, $default_scalar_to)
799 sub render_statement {
800 my ($self, $expr, $default_scalar_to) = @_;
802 $self->expand_expr($expr, $default_scalar_to), 1
806 sub _expand_statement {
807 my ($self, $type, $args) = @_;
808 my $ec = $self->{expand_clause};
811 $args->{$type} = delete $args->{_}
813 my %has_clause = map +($_ => 1), @{$self->{clauses_of}{$type}};
814 return +{ "-${type}" => +{
816 my $val = $args->{$_};
817 if (defined($val) and my $exp = $ec->{"${type}.$_"}) {
818 if ((my (@exp) = $self->$exp($_ => $val)) == 1) {
823 } elsif ($has_clause{$_}) {
824 ($_ => $self->expand_expr($val))
832 sub _render_statement {
833 my ($self, $type, $args) = @_;
835 foreach my $clause (@{$self->{clauses_of}{$type}}) {
836 next unless my $clause_expr = $args->{$clause};
838 if (my $rdr = $self->{render_clause}{"${type}.${clause}"}) {
839 $self->$rdr($clause, $clause_expr, $args);
841 my $r = $self->render_aqt($clause_expr, 1);
842 next unless defined $r->[0] and length $r->[0];
843 $self->join_query_parts(' ',
844 $self->format_keyword($clause),
851 my $q = $self->join_query_parts(' ', @parts);
852 return $self->join_query_parts('',
853 (our $Render_Top_Level ? $q : ('(', $q, ')'))
858 my ($self, $raw) = @_;
860 return $op if grep $_->{$op}, @{$self}{qw(is_op expand_op render_op)};
861 s/^-(?=.)//, s/\s+/_/g for $op;
866 my ($self, $expr) = @_;
867 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
868 return undef unless defined($expr);
869 if (ref($expr) eq 'HASH') {
870 return undef unless my $kc = keys %$expr;
872 return $self->_expand_op_andor(and => $expr);
874 my ($key, $value) = %$expr;
875 if ($key =~ /^-/ and $key =~ s/ [_\s]? \d+ $//x ) {
876 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
877 . "You probably wanted ...-and => [ $key => COND1, $key => COND2 ... ]";
879 return $self->_expand_hashpair($key, $value);
881 if (ref($expr) eq 'ARRAY') {
882 return $self->_expand_op_andor(lc($self->{logic}), $expr);
884 if (my $literal = is_literal_value($expr)) {
885 return +{ -literal => $literal };
887 if (!ref($expr) or Scalar::Util::blessed($expr)) {
888 return $self->_expand_scalar($expr);
893 sub _expand_hashpair {
894 my ($self, $k, $v) = @_;
895 unless (defined($k) and length($k)) {
896 if (defined($k) and my $literal = is_literal_value($v)) {
897 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
898 return { -literal => $literal };
900 puke "Supplying an empty left hand side argument is not supported";
903 return $self->_expand_hashpair_op($k, $v);
904 } elsif ($k =~ /^[^\w]/i) {
905 my ($lhs, @rhs) = ref($v) eq 'ARRAY' ? @$v : $v;
906 return $self->_expand_op(
907 -op, [ $k, $self->expand_expr($lhs, -ident), @rhs ]
910 return $self->_expand_hashpair_ident($k, $v);
913 sub _expand_hashpair_ident {
914 my ($self, $k, $v) = @_;
916 local our $Cur_Col_Meta = $k;
918 # hash with multiple or no elements is andor
920 if (ref($v) eq 'HASH' and keys %$v != 1) {
921 return $self->_expand_op_andor(and => $v, $k);
924 # undef needs to be re-sent with cmp to achieve IS/IS NOT NULL
926 if (is_undef_value($v)) {
927 return $self->_expand_hashpair_cmp($k => undef);
930 # scalars and objects get expanded as whatever requested or values
932 if (!ref($v) or Scalar::Util::blessed($v)) {
933 return $self->_expand_hashpair_scalar($k, $v);
936 # single key hashref is a hashtriple
938 if (ref($v) eq 'HASH') {
939 return $self->_expand_hashtriple($k, %$v);
942 # arrayref needs re-engineering over the elements
944 if (ref($v) eq 'ARRAY') {
945 return $self->sqlfalse unless @$v;
946 $self->_debug("ARRAY($k) means distribute over elements");
948 $v->[0] =~ /^-(and|or)$/i
949 ? (shift(@{$v = [ @$v ]}), $1)
950 : lc($self->{logic} || 'OR')
952 return $self->_expand_op_andor(
957 if (my $literal = is_literal_value($v)) {
959 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
962 my ($sql, @bind) = @$literal;
963 if ($self->{bindtype} eq 'columns') {
965 $self->_assert_bindval_matches_bindtype($_);
968 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
974 my ($self, $expr) = @_;
976 return $self->_expand_expr({ (our $Default_Scalar_To) => $expr });
979 sub _expand_hashpair_scalar {
980 my ($self, $k, $v) = @_;
982 return $self->_expand_hashpair_cmp(
983 $k, $self->_expand_scalar($v),
987 sub _expand_hashpair_op {
988 my ($self, $k, $v) = @_;
990 $self->_assert_pass_injection_guard($k =~ /\A-(.*)\Z/s);
992 my $op = $self->_normalize_op($k);
996 my $op = join(' ', split '_', $op);
998 # the old special op system requires illegality for top-level use
1001 (our $Expand_Depth) == 1
1003 List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}
1005 $self->{disable_old_special_ops}
1006 and List::Util::first { $op =~ $_->{regex} } @BUILTIN_SPECIAL_OPS
1010 puke "Illegal use of top-level '-$op'"
1014 if (my $exp = $self->{expand}{$op}||$self->{expand_op}{$op}) {
1015 return $self->$exp($op, $v);
1018 # Ops prefixed with -not_ get converted
1020 if (my ($rest) = $op =~/^not_(.*)$/) {
1023 $self->_expand_expr({ "-${rest}", $v })
1029 # the old unary op system means we should touch nothing and let it work
1031 my $op = join(' ', split '_', $op);
1033 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1034 return { -op => [ $op, $v ] };
1039 $self->{unknown_unop_always_func} && !$self->{render_op}{$op}
1049 and (keys %$v)[0] =~ /^-/
1053 (List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}})
1054 or $self->{render_op}{$op}
1062 if ($type eq -func and ref($v) eq 'ARRAY') {
1063 return $self->_expand_expr({ -func => [ $op, @$v ] });
1066 return $self->_expand_expr({ $type => [ $op, $v ] });
1069 sub _expand_hashpair_cmp {
1070 my ($self, $k, $v) = @_;
1071 $self->_expand_hashtriple($k, $self->{cmp}, $v);
1074 sub _expand_hashtriple {
1075 my ($self, $k, $vk, $vv) = @_;
1077 my $ik = $self->_expand_expr({ -ident => $k });
1079 my $op = $self->_normalize_op($vk);
1080 $self->_assert_pass_injection_guard($op);
1082 if ($op =~ s/ _? \d+ $//x ) {
1083 return $self->_expand_expr($k, { $vk, $vv });
1085 if (my $x = $self->{expand_op}{$op}) {
1086 local our $Cur_Col_Meta = $k;
1087 return $self->$x($op, $vv, $k);
1091 my $op = join(' ', split '_', $op);
1093 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
1094 return { -op => [ $op, $ik, $vv ] };
1096 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1100 { -op => [ $op, $vv ] }
1104 if (ref($vv) eq 'ARRAY') {
1106 my $logic = (defined($raw[0]) and $raw[0] =~ /^-(and|or)$/i)
1107 ? (shift(@raw), lc $1) : 'or';
1108 my @values = map +{ $vk => $_ }, @raw;
1110 $op =~ $self->{inequality_op}
1111 or $op =~ $self->{not_like_op}
1113 if (lc($logic) eq 'or' and @values > 1) {
1114 belch "A multi-element arrayref as an argument to the inequality op '${\uc(join ' ', split '_', $op)}' "
1115 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
1116 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
1121 # try to DWIM on equality operators
1122 return ($self->_dwim_op_to_is($op,
1123 "Supplying an empty arrayref to '%s' is deprecated",
1124 "operator '%s' applied on an empty array (field '$k')"
1125 ) ? $self->sqlfalse : $self->sqltrue);
1127 return $self->_expand_op_andor($logic => \@values, $k);
1129 if (is_undef_value($vv)) {
1130 my $is = ($self->_dwim_op_to_is($op,
1131 "Supplying an undefined argument to '%s' is deprecated",
1132 "unexpected operator '%s' with undef operand",
1133 ) ? 'is' : 'is not');
1135 return $self->_expand_hashpair($k => { $is, undef });
1137 local our $Cur_Col_Meta = $k;
1141 $self->_expand_expr($vv)
1145 sub _dwim_op_to_is {
1146 my ($self, $raw, $empty, $fail) = @_;
1148 my $op = $self->_normalize_op($raw);
1150 if ($op =~ /^not$/i) {
1153 if ($op =~ $self->{equality_op}) {
1156 if ($op =~ $self->{like_op}) {
1157 belch(sprintf $empty, uc(join ' ', split '_', $op));
1160 if ($op =~ $self->{inequality_op}) {
1163 if ($op =~ $self->{not_like_op}) {
1164 belch(sprintf $empty, uc(join ' ', split '_', $op));
1167 puke(sprintf $fail, $op);
1171 my ($self, undef, $args) = @_;
1172 my ($func, @args) = @$args;
1173 return +{ -func => [ $func, map $self->expand_expr($_), @args ] };
1177 my ($self, undef, $body, $k) = @_;
1178 return $self->_expand_hashpair_cmp(
1179 $k, { -ident => $body }
1181 unless (defined($body) or (ref($body) and ref($body) eq 'ARRAY')) {
1182 puke "-ident requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
1184 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
1185 ref($body) ? @$body : $body;
1186 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
1187 unless ($self->{quote_char}) {
1188 $self->_assert_pass_injection_guard($_) for @parts;
1190 return +{ -ident => \@parts };
1194 return $_[0]->_expand_hashpair_cmp(
1195 $_[3], { -value => $_[2] },
1196 ) if defined($_[3]);
1197 +{ -bind => [ our $Cur_Col_Meta, $_[2] ] };
1201 my ($self, undef, $args) = @_;
1202 +{ -row => [ map $self->expand_expr($_), @$args ] };
1206 my ($self, undef, $args) = @_;
1207 my ($op, @opargs) = @$args;
1208 if (my $exp = $self->{expand_op}{$op}) {
1209 return $self->$exp($op, \@opargs);
1211 +{ -op => [ $op, map $self->expand_expr($_), @opargs ] };
1215 my ($self, undef, $v) = @_;
1217 return $self->_expand_expr($v);
1219 puke "-bool => undef not supported" unless defined($v);
1220 return $self->_expand_expr({ -ident => $v });
1223 sub _expand_op_andor {
1224 my ($self, $logop, $v, $k) = @_;
1226 $v = [ map +{ $k, $_ },
1228 ? (map +{ $_ => $v->{$_} }, sort keys %$v)
1232 if (ref($v) eq 'HASH') {
1233 return undef unless keys %$v;
1236 map $self->_expand_expr({ $_ => $v->{$_} }),
1240 if (ref($v) eq 'ARRAY') {
1241 $logop eq 'and' or $logop eq 'or' or puke "unknown logic: $logop";
1244 (ref($_) eq 'ARRAY' and @$_)
1245 or (ref($_) eq 'HASH' and %$_)
1251 while (my ($el) = splice @expr, 0, 1) {
1252 puke "Supplying an empty left hand side argument is not supported in array-pairs"
1253 unless defined($el) and length($el);
1254 my $elref = ref($el);
1256 local our $Expand_Depth = 0;
1257 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
1258 } elsif ($elref eq 'ARRAY') {
1259 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
1260 } elsif (my $l = is_literal_value($el)) {
1261 push @res, { -literal => $l };
1262 } elsif ($elref eq 'HASH') {
1263 local our $Expand_Depth = 0;
1264 push @res, grep defined, $self->_expand_expr($el) if %$el;
1270 # return $res[0] if @res == 1;
1271 return { -op => [ $logop, @res ] };
1277 my ($self, $op, $vv, $k) = @_;
1278 ($k, $vv) = @$vv unless defined $k;
1279 puke "$op can only take undef as argument"
1283 and exists($vv->{-value})
1284 and !defined($vv->{-value})
1286 return +{ -op => [ $op.'_null', $self->expand_expr($k, -ident) ] };
1289 sub _expand_between {
1290 my ($self, $op, $vv, $k) = @_;
1291 $k = shift @{$vv = [ @$vv ]} unless defined $k;
1292 my @rhs = map $self->_expand_expr($_),
1293 ref($vv) eq 'ARRAY' ? @$vv : $vv;
1295 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
1297 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
1299 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1303 $self->expand_expr(ref($k) ? $k : { -ident => $k }),
1309 my ($self, $op, $vv, $k) = @_;
1310 $k = shift @{$vv = [ @$vv ]} unless defined $k;
1311 if (my $literal = is_literal_value($vv)) {
1312 my ($sql, @bind) = @$literal;
1313 my $opened_sql = $self->_open_outer_paren($sql);
1315 $op, $self->expand_expr($k, -ident),
1316 { -literal => [ $opened_sql, @bind ] }
1320 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1321 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1322 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1323 . 'will emit the logically correct SQL instead of raising this exception)'
1325 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
1327 my @rhs = map $self->expand_expr($_, -value),
1328 map { defined($_) ? $_: puke($undef_err) }
1329 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
1330 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
1334 $self->expand_expr($k, -ident),
1340 my ($self, undef, $v) = @_;
1341 # DBIx::Class requires a nest warning to be emitted once but the private
1342 # method it overrode to do so no longer exists
1343 if ($self->{warn_once_on_nest}) {
1344 unless (our $Nest_Warned) {
1346 "-nest in search conditions is deprecated, you most probably wanted:\n"
1347 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
1352 return $self->_expand_expr($v);
1356 my ($self, $type, $v) = @_;
1357 return { "-${type}" => $v };
1360 sub _expand_values {
1361 my ($self, undef, $values) = @_;
1362 return { -values => [
1365 ? $self->expand_expr($_)
1366 : +{ -row => [ map $self->expand_expr($_), @$_ ] }
1367 ), ref($values) eq 'ARRAY' ? @$values : $values
1371 sub _recurse_where {
1372 my ($self, $where, $logic) = @_;
1374 # Special case: top level simple string treated as literal
1376 my $where_exp = (ref($where)
1377 ? $self->_expand_expr($where, $logic)
1378 : { -literal => [ $where ] });
1380 # dispatch expanded expression
1382 my ($sql, @bind) = defined($where_exp) ? @{ $self->render_aqt($where_exp) || [] } : ();
1383 # DBIx::Class used to call _recurse_where in scalar context
1384 # something else might too...
1386 return ($sql, @bind);
1389 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
1395 my ($self, undef, $ident) = @_;
1397 return [ $self->_convert($self->_quote($ident)) ];
1401 my ($self, undef, $values) = @_;
1402 return $self->join_query_parts('',
1404 $self->_render_op(undef, [ ',', @$values ]),
1410 my ($self, undef, $rest) = @_;
1411 my ($func, @args) = @$rest;
1412 return $self->join_query_parts('',
1413 $self->_sqlcase($func),
1414 $self->join_query_parts('',
1416 $self->join_query_parts(', ', @args),
1423 my ($self, undef, $bind) = @_;
1424 return [ $self->_convert('?'), $self->_bindtype(@$bind) ];
1427 sub _render_literal {
1428 my ($self, undef, $literal) = @_;
1429 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1434 my ($self, undef, $v) = @_;
1435 my ($op, @args) = @$v;
1436 if (my $r = $self->{render_op}{$op}) {
1437 return $self->$r($op, \@args);
1442 my $op = join(' ', split '_', $op);
1444 my $ss = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1445 if ($ss and @args > 1) {
1446 puke "Special op '${op}' requires first value to be identifier"
1447 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1448 my $k = join(($self->{name_sep}||'.'), @$ident);
1449 local our $Expand_Depth = 1;
1450 return [ $self->${\($ss->{handler})}($k, $op, $args[1]) ];
1452 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1453 return [ $self->${\($us->{handler})}($op, $args[0]) ];
1456 return $self->_render_unop_paren($op, \@args);
1460 return $self->_render_unop_prefix($op, \@args);
1462 return $self->_render_op_multop($op, \@args);
1468 sub _render_op_between {
1469 my ($self, $op, $args) = @_;
1470 my ($left, $low, $high) = @$args;
1473 puke "Single arg to between must be a literal"
1474 unless $low->{-literal};
1477 +($low, $self->format_keyword('and'), $high);
1480 return $self->join_query_parts(' ',
1481 '(', $left, $self->format_keyword($op), @rh, ')',
1486 my ($self, $op, $args) = @_;
1487 my ($lhs, @rhs) = @$args;
1489 return $self->join_query_parts(' ',
1491 $self->format_keyword($op),
1492 $self->join_query_parts(' ',
1494 $self->join_query_parts(', ', @rhs),
1500 sub _render_op_andor {
1501 my ($self, $op, $args) = @_;
1502 return undef unless @$args;
1503 return $self->join_query_parts('', $args->[0]) if @$args == 1;
1504 my $inner = $self->_render_op_multop($op, $args);
1505 return undef unless defined($inner->[0]) and length($inner->[0]);
1506 return $self->join_query_parts(' ',
1511 sub _render_op_multop {
1512 my ($self, $op, $args) = @_;
1514 return undef unless @parts;
1515 return $self->render_aqt($parts[0]) if @parts == 1;
1516 my $join = ($op eq ','
1518 : ' '.$self->format_keyword($op).' '
1520 return $self->join_query_parts($join, @parts);
1523 sub _render_values {
1524 my ($self, undef, $values) = @_;
1525 my $inner = $self->join_query_parts(' ',
1526 $self->format_keyword('values'),
1527 $self->join_query_parts(', ',
1528 ref($values) eq 'ARRAY' ? @$values : $values
1531 return $self->join_query_parts('',
1532 (our $Render_Top_Level ? $inner : ('(', $inner, ')'))
1536 sub join_query_parts {
1537 my ($self, $join, @parts) = @_;
1540 ? $self->render_aqt($_)
1541 : ((ref($_) eq 'ARRAY') ? $_ : [ $_ ])
1544 $self->{join_sql_parts}->(
1545 $join, grep defined && length, map $_->[0], @final
1547 (map @{$_}[1..$#$_], @final),
1551 sub _render_unop_paren {
1552 my ($self, $op, $v) = @_;
1553 return $self->join_query_parts('',
1554 '(', $self->_render_unop_prefix($op, $v), ')'
1558 sub _render_unop_prefix {
1559 my ($self, $op, $v) = @_;
1560 return $self->join_query_parts(' ',
1561 $self->_sqlcase($op), $v->[0]
1565 sub _render_unop_postfix {
1566 my ($self, $op, $v) = @_;
1567 return $self->join_query_parts(' ',
1568 $v->[0], $self->format_keyword($op),
1572 # Some databases (SQLite) treat col IN (1, 2) different from
1573 # col IN ( (1, 2) ). Use this to strip all outer parens while
1574 # adding them back in the corresponding method
1575 sub _open_outer_paren {
1576 my ($self, $sql) = @_;
1578 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1580 # there are closing parens inside, need the heavy duty machinery
1581 # to reevaluate the extraction starting from $sql (full reevaluation)
1582 if ($inner =~ /\)/) {
1583 require Text::Balanced;
1585 my (undef, $remainder) = do {
1586 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1588 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1591 # the entire expression needs to be a balanced bracketed thing
1592 # (after an extract no remainder sans trailing space)
1593 last if defined $remainder and $remainder =~ /\S/;
1603 #======================================================================
1605 #======================================================================
1607 sub _expand_order_by {
1608 my ($self, $arg) = @_;
1610 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1612 return $self->expand_maybe_list_expr($arg)
1613 if ref($arg) eq 'HASH' and ($arg->{-op}||[''])->[0] eq ',';
1615 my $expander = sub {
1616 my ($self, $dir, $expr) = @_;
1617 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1618 foreach my $arg (@to_expand) {
1622 and grep /^-(asc|desc)$/, keys %$arg
1624 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1628 defined($dir) ? { -op => [ $dir =~ /^-?(.*)$/ ,=> $_ ] } : $_
1630 map $self->expand_expr($_, -ident),
1631 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
1632 return undef unless @exp;
1633 return undef if @exp == 1 and not defined($exp[0]);
1634 return +{ -op => [ ',', @exp ] };
1637 local @{$self->{expand}}{qw(asc desc)} = (($expander) x 2);
1639 return $self->$expander(undef, $arg);
1643 my ($self, $arg) = @_;
1645 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
1647 my ($sql, @bind) = @{ $self->render_aqt($expanded) };
1649 return '' unless length($sql);
1651 my $final_sql = $self->_sqlcase(' order by ').$sql;
1653 return ($final_sql, @bind);
1656 # _order_by no longer needs to call this so doesn't but DBIC uses it.
1658 sub _order_by_chunks {
1659 my ($self, $arg) = @_;
1661 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1663 my @res = $self->_chunkify_order_by($expanded);
1664 (ref() ? $_->[0] : $_) .= '' for @res;
1668 sub _chunkify_order_by {
1669 my ($self, $expanded) = @_;
1671 return grep length, @{ $self->render_aqt($expanded) }
1672 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1675 if (ref() eq 'HASH' and $_->{-op} and $_->{-op}[0] eq ',') {
1676 my ($comma, @list) = @{$_->{-op}};
1677 return map $self->_chunkify_order_by($_), @list;
1679 return $self->render_aqt($_);
1683 #======================================================================
1684 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1685 #======================================================================
1691 $self->expand_maybe_list_expr($from, -ident)
1696 #======================================================================
1698 #======================================================================
1700 sub expand_maybe_list_expr {
1701 my ($self, $expr, $default) = @_;
1703 ',', map $self->expand_expr($_, $default),
1704 @{$expr->{-op}}[1..$#{$expr->{-op}}]
1705 ] } if ref($expr) eq 'HASH' and ($expr->{-op}||[''])->[0] eq ',';
1706 return +{ -op => [ ',',
1707 map $self->expand_expr($_, $default),
1708 ref($expr) eq 'ARRAY' ? @$expr : $expr
1712 # highly optimized, as it's called way too often
1714 # my ($self, $label) = @_;
1716 return '' unless defined $_[1];
1717 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1718 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1720 unless ($_[0]->{quote_char}) {
1721 if (ref($_[1]) eq 'ARRAY') {
1722 return join($_[0]->{name_sep}||'.', @{$_[1]});
1724 $_[0]->_assert_pass_injection_guard($_[1]);
1729 my $qref = ref $_[0]->{quote_char};
1731 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1732 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1733 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1735 my $esc = $_[0]->{escape_char} || $r;
1737 # parts containing * are naturally unquoted
1739 $_[0]->{name_sep}||'',
1743 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1745 (ref($_[1]) eq 'ARRAY'
1749 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1757 # Conversion, if applicable
1759 #my ($self, $arg) = @_;
1760 if (my $conv = $_[0]->{convert_where}) {
1761 return @{ $_[0]->join_query_parts('',
1762 $_[0]->format_keyword($conv),
1771 #my ($self, $col, @vals) = @_;
1772 # called often - tighten code
1773 return $_[0]->{bindtype} eq 'columns'
1774 ? map {[$_[1], $_]} @_[2 .. $#_]
1779 # Dies if any element of @bind is not in [colname => value] format
1780 # if bindtype is 'columns'.
1781 sub _assert_bindval_matches_bindtype {
1782 # my ($self, @bind) = @_;
1784 if ($self->{bindtype} eq 'columns') {
1786 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1787 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1793 sub _join_sql_clauses {
1794 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1796 if (@$clauses_aref > 1) {
1797 my $join = " " . $self->_sqlcase($logic) . " ";
1798 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1799 return ($sql, @$bind_aref);
1801 elsif (@$clauses_aref) {
1802 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1805 return (); # if no SQL, ignore @$bind_aref
1810 # Fix SQL case, if so requested
1812 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1813 # don't touch the argument ... crooked logic, but let's not change it!
1814 return $_[0]->{case} ? $_[1] : uc($_[1]);
1817 sub format_keyword { $_[0]->_sqlcase(join ' ', split '_', $_[1]) }
1819 #======================================================================
1820 # DISPATCHING FROM REFKIND
1821 #======================================================================
1824 my ($self, $data) = @_;
1826 return 'UNDEF' unless defined $data;
1828 # blessed objects are treated like scalars
1829 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1831 return 'SCALAR' unless $ref;
1834 while ($ref eq 'REF') {
1836 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1840 return ($ref||'SCALAR') . ('REF' x $n_steps);
1844 my ($self, $data) = @_;
1845 my @try = ($self->_refkind($data));
1846 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1847 push @try, 'FALLBACK';
1851 sub _METHOD_FOR_refkind {
1852 my ($self, $meth_prefix, $data) = @_;
1855 for (@{$self->_try_refkind($data)}) {
1856 $method = $self->can($meth_prefix."_".$_)
1860 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1864 sub _SWITCH_refkind {
1865 my ($self, $data, $dispatch_table) = @_;
1868 for (@{$self->_try_refkind($data)}) {
1869 $coderef = $dispatch_table->{$_}
1873 puke "no dispatch entry for ".$self->_refkind($data)
1882 #======================================================================
1883 # VALUES, GENERATE, AUTOLOAD
1884 #======================================================================
1886 # LDNOTE: original code from nwiger, didn't touch code in that section
1887 # I feel the AUTOLOAD stuff should not be the default, it should
1888 # only be activated on explicit demand by user.
1892 my $data = shift || return;
1893 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1894 unless ref $data eq 'HASH';
1897 foreach my $k (sort keys %$data) {
1898 my $v = $data->{$k};
1899 $self->_SWITCH_refkind($v, {
1901 if ($self->{array_datatypes}) { # array datatype
1902 push @all_bind, $self->_bindtype($k, $v);
1904 else { # literal SQL with bind
1905 my ($sql, @bind) = @$v;
1906 $self->_assert_bindval_matches_bindtype(@bind);
1907 push @all_bind, @bind;
1910 ARRAYREFREF => sub { # literal SQL with bind
1911 my ($sql, @bind) = @${$v};
1912 $self->_assert_bindval_matches_bindtype(@bind);
1913 push @all_bind, @bind;
1915 SCALARREF => sub { # literal SQL without bind
1917 SCALAR_or_UNDEF => sub {
1918 push @all_bind, $self->_bindtype($k, $v);
1929 my(@sql, @sqlq, @sqlv);
1933 if ($ref eq 'HASH') {
1934 for my $k (sort keys %$_) {
1937 my $label = $self->_quote($k);
1938 if ($r eq 'ARRAY') {
1939 # literal SQL with bind
1940 my ($sql, @bind) = @$v;
1941 $self->_assert_bindval_matches_bindtype(@bind);
1942 push @sqlq, "$label = $sql";
1944 } elsif ($r eq 'SCALAR') {
1945 # literal SQL without bind
1946 push @sqlq, "$label = $$v";
1948 push @sqlq, "$label = ?";
1949 push @sqlv, $self->_bindtype($k, $v);
1952 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1953 } elsif ($ref eq 'ARRAY') {
1954 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1957 if ($r eq 'ARRAY') { # literal SQL with bind
1958 my ($sql, @bind) = @$v;
1959 $self->_assert_bindval_matches_bindtype(@bind);
1962 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1963 # embedded literal SQL
1970 push @sql, '(' . join(', ', @sqlq) . ')';
1971 } elsif ($ref eq 'SCALAR') {
1975 # strings get case twiddled
1976 push @sql, $self->_sqlcase($_);
1980 my $sql = join ' ', @sql;
1982 # this is pretty tricky
1983 # if ask for an array, return ($stmt, @bind)
1984 # otherwise, s/?/shift @sqlv/ to put it inline
1986 return ($sql, @sqlv);
1988 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1989 ref $d ? $d->[1] : $d/e;
1998 # This allows us to check for a local, then _form, attr
2000 my($name) = $AUTOLOAD =~ /.*::(.+)/;
2001 puke "AUTOLOAD invoked for method name ${name} and allow_autoload option not set" unless $self->{allow_autoload};
2002 return $self->generate($name, @_);
2013 SQL::Abstract - Generate SQL from Perl data structures
2019 my $sql = SQL::Abstract->new;
2021 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
2023 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
2025 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
2027 my($stmt, @bind) = $sql->delete($table, \%where);
2029 # Then, use these in your DBI statements
2030 my $sth = $dbh->prepare($stmt);
2031 $sth->execute(@bind);
2033 # Just generate the WHERE clause
2034 my($stmt, @bind) = $sql->where(\%where, $order);
2036 # Return values in the same order, for hashed queries
2037 # See PERFORMANCE section for more details
2038 my @bind = $sql->values(\%fieldvals);
2042 This module was inspired by the excellent L<DBIx::Abstract>.
2043 However, in using that module I found that what I really wanted
2044 to do was generate SQL, but still retain complete control over my
2045 statement handles and use the DBI interface. So, I set out to
2046 create an abstract SQL generation module.
2048 While based on the concepts used by L<DBIx::Abstract>, there are
2049 several important differences, especially when it comes to WHERE
2050 clauses. I have modified the concepts used to make the SQL easier
2051 to generate from Perl data structures and, IMO, more intuitive.
2052 The underlying idea is for this module to do what you mean, based
2053 on the data structures you provide it. The big advantage is that
2054 you don't have to modify your code every time your data changes,
2055 as this module figures it out.
2057 To begin with, an SQL INSERT is as easy as just specifying a hash
2058 of C<key=value> pairs:
2061 name => 'Jimbo Bobson',
2062 phone => '123-456-7890',
2063 address => '42 Sister Lane',
2064 city => 'St. Louis',
2065 state => 'Louisiana',
2068 The SQL can then be generated with this:
2070 my($stmt, @bind) = $sql->insert('people', \%data);
2072 Which would give you something like this:
2074 $stmt = "INSERT INTO people
2075 (address, city, name, phone, state)
2076 VALUES (?, ?, ?, ?, ?)";
2077 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
2078 '123-456-7890', 'Louisiana');
2080 These are then used directly in your DBI code:
2082 my $sth = $dbh->prepare($stmt);
2083 $sth->execute(@bind);
2085 =head2 Inserting and Updating Arrays
2087 If your database has array types (like for example Postgres),
2088 activate the special option C<< array_datatypes => 1 >>
2089 when creating the C<SQL::Abstract> object.
2090 Then you may use an arrayref to insert and update database array types:
2092 my $sql = SQL::Abstract->new(array_datatypes => 1);
2094 planets => [qw/Mercury Venus Earth Mars/]
2097 my($stmt, @bind) = $sql->insert('solar_system', \%data);
2101 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
2103 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
2106 =head2 Inserting and Updating SQL
2108 In order to apply SQL functions to elements of your C<%data> you may
2109 specify a reference to an arrayref for the given hash value. For example,
2110 if you need to execute the Oracle C<to_date> function on a value, you can
2111 say something like this:
2115 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
2118 The first value in the array is the actual SQL. Any other values are
2119 optional and would be included in the bind values array. This gives
2122 my($stmt, @bind) = $sql->insert('people', \%data);
2124 $stmt = "INSERT INTO people (name, date_entered)
2125 VALUES (?, to_date(?,'MM/DD/YYYY'))";
2126 @bind = ('Bill', '03/02/2003');
2128 An UPDATE is just as easy, all you change is the name of the function:
2130 my($stmt, @bind) = $sql->update('people', \%data);
2132 Notice that your C<%data> isn't touched; the module will generate
2133 the appropriately quirky SQL for you automatically. Usually you'll
2134 want to specify a WHERE clause for your UPDATE, though, which is
2135 where handling C<%where> hashes comes in handy...
2137 =head2 Complex where statements
2139 This module can generate pretty complicated WHERE statements
2140 easily. For example, simple C<key=value> pairs are taken to mean
2141 equality, and if you want to see if a field is within a set
2142 of values, you can use an arrayref. Let's say we wanted to
2143 SELECT some data based on this criteria:
2146 requestor => 'inna',
2147 worker => ['nwiger', 'rcwe', 'sfz'],
2148 status => { '!=', 'completed' }
2151 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
2153 The above would give you something like this:
2155 $stmt = "SELECT * FROM tickets WHERE
2156 ( requestor = ? ) AND ( status != ? )
2157 AND ( worker = ? OR worker = ? OR worker = ? )";
2158 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
2160 Which you could then use in DBI code like so:
2162 my $sth = $dbh->prepare($stmt);
2163 $sth->execute(@bind);
2169 The methods are simple. There's one for every major SQL operation,
2170 and a constructor you use first. The arguments are specified in a
2171 similar order for each method (table, then fields, then a where
2172 clause) to try and simplify things.
2174 =head2 new(option => 'value')
2176 The C<new()> function takes a list of options and values, and returns
2177 a new B<SQL::Abstract> object which can then be used to generate SQL
2178 through the methods below. The options accepted are:
2184 If set to 'lower', then SQL will be generated in all lowercase. By
2185 default SQL is generated in "textbook" case meaning something like:
2187 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
2189 Any setting other than 'lower' is ignored.
2193 This determines what the default comparison operator is. By default
2194 it is C<=>, meaning that a hash like this:
2196 %where = (name => 'nwiger', email => 'nate@wiger.org');
2198 Will generate SQL like this:
2200 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
2202 However, you may want loose comparisons by default, so if you set
2203 C<cmp> to C<like> you would get SQL such as:
2205 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
2207 You can also override the comparison on an individual basis - see
2208 the huge section on L</"WHERE CLAUSES"> at the bottom.
2210 =item sqltrue, sqlfalse
2212 Expressions for inserting boolean values within SQL statements.
2213 By default these are C<1=1> and C<1=0>. They are used
2214 by the special operators C<-in> and C<-not_in> for generating
2215 correct SQL even when the argument is an empty array (see below).
2219 This determines the default logical operator for multiple WHERE
2220 statements in arrays or hashes. If absent, the default logic is "or"
2221 for arrays, and "and" for hashes. This means that a WHERE
2225 event_date => {'>=', '2/13/99'},
2226 event_date => {'<=', '4/24/03'},
2229 will generate SQL like this:
2231 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
2233 This is probably not what you want given this query, though (look
2234 at the dates). To change the "OR" to an "AND", simply specify:
2236 my $sql = SQL::Abstract->new(logic => 'and');
2238 Which will change the above C<WHERE> to:
2240 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
2242 The logic can also be changed locally by inserting
2243 a modifier in front of an arrayref:
2245 @where = (-and => [event_date => {'>=', '2/13/99'},
2246 event_date => {'<=', '4/24/03'} ]);
2248 See the L</"WHERE CLAUSES"> section for explanations.
2252 This will automatically convert comparisons using the specified SQL
2253 function for both column and value. This is mostly used with an argument
2254 of C<upper> or C<lower>, so that the SQL will have the effect of
2255 case-insensitive "searches". For example, this:
2257 $sql = SQL::Abstract->new(convert => 'upper');
2258 %where = (keywords => 'MaKe iT CAse inSeNSItive');
2260 Will turn out the following SQL:
2262 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
2264 The conversion can be C<upper()>, C<lower()>, or any other SQL function
2265 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
2266 not validate this option; it will just pass through what you specify verbatim).
2270 This is a kludge because many databases suck. For example, you can't
2271 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
2272 Instead, you have to use C<bind_param()>:
2274 $sth->bind_param(1, 'reg data');
2275 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
2277 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
2278 which loses track of which field each slot refers to. Fear not.
2280 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
2281 Currently, you can specify either C<normal> (default) or C<columns>. If you
2282 specify C<columns>, you will get an array that looks like this:
2284 my $sql = SQL::Abstract->new(bindtype => 'columns');
2285 my($stmt, @bind) = $sql->insert(...);
2288 [ 'column1', 'value1' ],
2289 [ 'column2', 'value2' ],
2290 [ 'column3', 'value3' ],
2293 You can then iterate through this manually, using DBI's C<bind_param()>.
2295 $sth->prepare($stmt);
2298 my($col, $data) = @$_;
2299 if ($col eq 'details' || $col eq 'comments') {
2300 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
2301 } elsif ($col eq 'image') {
2302 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
2304 $sth->bind_param($i, $data);
2308 $sth->execute; # execute without @bind now
2310 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
2311 Basically, the advantage is still that you don't have to care which fields
2312 are or are not included. You could wrap that above C<for> loop in a simple
2313 sub called C<bind_fields()> or something and reuse it repeatedly. You still
2314 get a layer of abstraction over manual SQL specification.
2316 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
2317 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
2318 will expect the bind values in this format.
2322 This is the character that a table or column name will be quoted
2323 with. By default this is an empty string, but you could set it to
2324 the character C<`>, to generate SQL like this:
2326 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
2328 Alternatively, you can supply an array ref of two items, the first being the left
2329 hand quote character, and the second the right hand quote character. For
2330 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
2331 that generates SQL like this:
2333 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
2335 Quoting is useful if you have tables or columns names that are reserved
2336 words in your database's SQL dialect.
2340 This is the character that will be used to escape L</quote_char>s appearing
2341 in an identifier before it has been quoted.
2343 The parameter default in case of a single L</quote_char> character is the quote
2346 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
2347 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
2348 of the B<opening (left)> L</quote_char> within the identifier are currently left
2349 untouched. The default for opening-closing-style quotes may change in future
2350 versions, thus you are B<strongly encouraged> to specify the escape character
2355 This is the character that separates a table and column name. It is
2356 necessary to specify this when the C<quote_char> option is selected,
2357 so that tables and column names can be individually quoted like this:
2359 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2361 =item injection_guard
2363 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2364 column name specified in a query structure. This is a safety mechanism to avoid
2365 injection attacks when mishandling user input e.g.:
2367 my %condition_as_column_value_pairs = get_values_from_user();
2368 $sqla->select( ... , \%condition_as_column_value_pairs );
2370 If the expression matches an exception is thrown. Note that literal SQL
2371 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2373 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2375 =item array_datatypes
2377 When this option is true, arrayrefs in INSERT or UPDATE are
2378 interpreted as array datatypes and are passed directly
2380 When this option is false, arrayrefs are interpreted
2381 as literal SQL, just like refs to arrayrefs
2382 (but this behavior is for backwards compatibility; when writing
2383 new queries, use the "reference to arrayref" syntax
2389 Takes a reference to a list of "special operators"
2390 to extend the syntax understood by L<SQL::Abstract>.
2391 See section L</"SPECIAL OPERATORS"> for details.
2395 Takes a reference to a list of "unary operators"
2396 to extend the syntax understood by L<SQL::Abstract>.
2397 See section L</"UNARY OPERATORS"> for details.
2403 =head2 insert($table, \@values || \%fieldvals, \%options)
2405 This is the simplest function. You simply give it a table name
2406 and either an arrayref of values or hashref of field/value pairs.
2407 It returns an SQL INSERT statement and a list of bind values.
2408 See the sections on L</"Inserting and Updating Arrays"> and
2409 L</"Inserting and Updating SQL"> for information on how to insert
2410 with those data types.
2412 The optional C<\%options> hash reference may contain additional
2413 options to generate the insert SQL. Currently supported options
2420 Takes either a scalar of raw SQL fields, or an array reference of
2421 field names, and adds on an SQL C<RETURNING> statement at the end.
2422 This allows you to return data generated by the insert statement
2423 (such as row IDs) without performing another C<SELECT> statement.
2424 Note, however, this is not part of the SQL standard and may not
2425 be supported by all database engines.
2429 =head2 update($table, \%fieldvals, \%where, \%options)
2431 This takes a table, hashref of field/value pairs, and an optional
2432 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2434 See the sections on L</"Inserting and Updating Arrays"> and
2435 L</"Inserting and Updating SQL"> for information on how to insert
2436 with those data types.
2438 The optional C<\%options> hash reference may contain additional
2439 options to generate the update SQL. Currently supported options
2446 See the C<returning> option to
2447 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2451 =head2 select($source, $fields, $where, $order)
2453 This returns a SQL SELECT statement and associated list of bind values, as
2454 specified by the arguments:
2460 Specification of the 'FROM' part of the statement.
2461 The argument can be either a plain scalar (interpreted as a table
2462 name, will be quoted), or an arrayref (interpreted as a list
2463 of table names, joined by commas, quoted), or a scalarref
2464 (literal SQL, not quoted).
2468 Specification of the list of fields to retrieve from
2470 The argument can be either an arrayref (interpreted as a list
2471 of field names, will be joined by commas and quoted), or a
2472 plain scalar (literal SQL, not quoted).
2473 Please observe that this API is not as flexible as that of
2474 the first argument C<$source>, for backwards compatibility reasons.
2478 Optional argument to specify the WHERE part of the query.
2479 The argument is most often a hashref, but can also be
2480 an arrayref or plain scalar --
2481 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2485 Optional argument to specify the ORDER BY part of the query.
2486 The argument can be a scalar, a hashref or an arrayref
2487 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2493 =head2 delete($table, \%where, \%options)
2495 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2496 It returns an SQL DELETE statement and list of bind values.
2498 The optional C<\%options> hash reference may contain additional
2499 options to generate the delete SQL. Currently supported options
2506 See the C<returning> option to
2507 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2511 =head2 where(\%where, $order)
2513 This is used to generate just the WHERE clause. For example,
2514 if you have an arbitrary data structure and know what the
2515 rest of your SQL is going to look like, but want an easy way
2516 to produce a WHERE clause, use this. It returns an SQL WHERE
2517 clause and list of bind values.
2520 =head2 values(\%data)
2522 This just returns the values from the hash C<%data>, in the same
2523 order that would be returned from any of the other above queries.
2524 Using this allows you to markedly speed up your queries if you
2525 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2527 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2529 Warning: This is an experimental method and subject to change.
2531 This returns arbitrarily generated SQL. It's a really basic shortcut.
2532 It will return two different things, depending on return context:
2534 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2535 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2537 These would return the following:
2539 # First calling form
2540 $stmt = "CREATE TABLE test (?, ?)";
2541 @bind = (field1, field2);
2543 # Second calling form
2544 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2546 Depending on what you're trying to do, it's up to you to choose the correct
2547 format. In this example, the second form is what you would want.
2551 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2555 ALTER SESSION SET nls_date_format = 'MM/YY'
2557 You get the idea. Strings get their case twiddled, but everything
2558 else remains verbatim.
2560 =head1 EXPORTABLE FUNCTIONS
2562 =head2 is_plain_value
2564 Determines if the supplied argument is a plain value as understood by this
2569 =item * The value is C<undef>
2571 =item * The value is a non-reference
2573 =item * The value is an object with stringification overloading
2575 =item * The value is of the form C<< { -value => $anything } >>
2579 On failure returns C<undef>, on success returns a B<scalar> reference
2580 to the original supplied argument.
2586 The stringification overloading detection is rather advanced: it takes
2587 into consideration not only the presence of a C<""> overload, but if that
2588 fails also checks for enabled
2589 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2590 on either C<0+> or C<bool>.
2592 Unfortunately testing in the field indicates that this
2593 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2594 but only when very large numbers of stringifying objects are involved.
2595 At the time of writing ( Sep 2014 ) there is no clear explanation of
2596 the direct cause, nor is there a manageably small test case that reliably
2597 reproduces the problem.
2599 If you encounter any of the following exceptions in B<random places within
2600 your application stack> - this module may be to blame:
2602 Operation "ne": no method found,
2603 left argument in overloaded package <something>,
2604 right argument in overloaded package <something>
2608 Stub found while resolving method "???" overloading """" in package <something>
2610 If you fall victim to the above - please attempt to reduce the problem
2611 to something that could be sent to the L<SQL::Abstract developers
2612 |DBIx::Class/GETTING HELP/SUPPORT>
2613 (either publicly or privately). As a workaround in the meantime you can
2614 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2615 value, which will most likely eliminate your problem (at the expense of
2616 not being able to properly detect exotic forms of stringification).
2618 This notice and environment variable will be removed in a future version,
2619 as soon as the underlying problem is found and a reliable workaround is
2624 =head2 is_literal_value
2626 Determines if the supplied argument is a literal value as understood by this
2631 =item * C<\$sql_string>
2633 =item * C<\[ $sql_string, @bind_values ]>
2637 On failure returns C<undef>, on success returns an B<array> reference
2638 containing the unpacked version of the supplied literal SQL and bind values.
2640 =head1 WHERE CLAUSES
2644 This module uses a variation on the idea from L<DBIx::Abstract>. It
2645 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2646 module is that things in arrays are OR'ed, and things in hashes
2649 The easiest way to explain is to show lots of examples. After
2650 each C<%where> hash shown, it is assumed you used:
2652 my($stmt, @bind) = $sql->where(\%where);
2654 However, note that the C<%where> hash can be used directly in any
2655 of the other functions as well, as described above.
2657 =head2 Key-value pairs
2659 So, let's get started. To begin, a simple hash:
2663 status => 'completed'
2666 Is converted to SQL C<key = val> statements:
2668 $stmt = "WHERE user = ? AND status = ?";
2669 @bind = ('nwiger', 'completed');
2671 One common thing I end up doing is having a list of values that
2672 a field can be in. To do this, simply specify a list inside of
2677 status => ['assigned', 'in-progress', 'pending'];
2680 This simple code will create the following:
2682 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2683 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2685 A field associated to an empty arrayref will be considered a
2686 logical false and will generate 0=1.
2688 =head2 Tests for NULL values
2690 If the value part is C<undef> then this is converted to SQL <IS NULL>
2699 $stmt = "WHERE user = ? AND status IS NULL";
2702 To test if a column IS NOT NULL:
2706 status => { '!=', undef },
2709 =head2 Specific comparison operators
2711 If you want to specify a different type of operator for your comparison,
2712 you can use a hashref for a given column:
2716 status => { '!=', 'completed' }
2719 Which would generate:
2721 $stmt = "WHERE user = ? AND status != ?";
2722 @bind = ('nwiger', 'completed');
2724 To test against multiple values, just enclose the values in an arrayref:
2726 status => { '=', ['assigned', 'in-progress', 'pending'] };
2728 Which would give you:
2730 "WHERE status = ? OR status = ? OR status = ?"
2733 The hashref can also contain multiple pairs, in which case it is expanded
2734 into an C<AND> of its elements:
2738 status => { '!=', 'completed', -not_like => 'pending%' }
2741 # Or more dynamically, like from a form
2742 $where{user} = 'nwiger';
2743 $where{status}{'!='} = 'completed';
2744 $where{status}{'-not_like'} = 'pending%';
2746 # Both generate this
2747 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2748 @bind = ('nwiger', 'completed', 'pending%');
2751 To get an OR instead, you can combine it with the arrayref idea:
2755 priority => [ { '=', 2 }, { '>', 5 } ]
2758 Which would generate:
2760 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2761 @bind = ('2', '5', 'nwiger');
2763 If you want to include literal SQL (with or without bind values), just use a
2764 scalar reference or reference to an arrayref as the value:
2767 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2768 date_expires => { '<' => \"now()" }
2771 Which would generate:
2773 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2774 @bind = ('11/26/2008');
2777 =head2 Logic and nesting operators
2779 In the example above,
2780 there is a subtle trap if you want to say something like
2781 this (notice the C<AND>):
2783 WHERE priority != ? AND priority != ?
2785 Because, in Perl you I<can't> do this:
2787 priority => { '!=' => 2, '!=' => 1 }
2789 As the second C<!=> key will obliterate the first. The solution
2790 is to use the special C<-modifier> form inside an arrayref:
2792 priority => [ -and => {'!=', 2},
2796 Normally, these would be joined by C<OR>, but the modifier tells it
2797 to use C<AND> instead. (Hint: You can use this in conjunction with the
2798 C<logic> option to C<new()> in order to change the way your queries
2799 work by default.) B<Important:> Note that the C<-modifier> goes
2800 B<INSIDE> the arrayref, as an extra first element. This will
2801 B<NOT> do what you think it might:
2803 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2805 Here is a quick list of equivalencies, since there is some overlap:
2808 status => {'!=', 'completed', 'not like', 'pending%' }
2809 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2812 status => {'=', ['assigned', 'in-progress']}
2813 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2814 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2818 =head2 Special operators: IN, BETWEEN, etc.
2820 You can also use the hashref format to compare a list of fields using the
2821 C<IN> comparison operator, by specifying the list as an arrayref:
2824 status => 'completed',
2825 reportid => { -in => [567, 2335, 2] }
2828 Which would generate:
2830 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2831 @bind = ('completed', '567', '2335', '2');
2833 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2836 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2837 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2838 'sqltrue' (by default: C<1=1>).
2840 In addition to the array you can supply a chunk of literal sql or
2841 literal sql with bind:
2844 customer => { -in => \[
2845 'SELECT cust_id FROM cust WHERE balance > ?',
2848 status => { -in => \'SELECT status_codes FROM states' },
2854 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2855 AND status IN ( SELECT status_codes FROM states )
2859 Finally, if the argument to C<-in> is not a reference, it will be
2860 treated as a single-element array.
2862 Another pair of operators is C<-between> and C<-not_between>,
2863 used with an arrayref of two values:
2867 completion_date => {
2868 -not_between => ['2002-10-01', '2003-02-06']
2874 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2876 Just like with C<-in> all plausible combinations of literal SQL
2880 start0 => { -between => [ 1, 2 ] },
2881 start1 => { -between => \["? AND ?", 1, 2] },
2882 start2 => { -between => \"lower(x) AND upper(y)" },
2883 start3 => { -between => [
2885 \["upper(?)", 'stuff' ],
2892 ( start0 BETWEEN ? AND ? )
2893 AND ( start1 BETWEEN ? AND ? )
2894 AND ( start2 BETWEEN lower(x) AND upper(y) )
2895 AND ( start3 BETWEEN lower(x) AND upper(?) )
2897 @bind = (1, 2, 1, 2, 'stuff');
2900 These are the two builtin "special operators"; but the
2901 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
2903 =head2 Unary operators: bool
2905 If you wish to test against boolean columns or functions within your
2906 database you can use the C<-bool> and C<-not_bool> operators. For
2907 example to test the column C<is_user> being true and the column
2908 C<is_enabled> being false you would use:-
2912 -not_bool => 'is_enabled',
2917 WHERE is_user AND NOT is_enabled
2919 If a more complex combination is required, testing more conditions,
2920 then you should use the and/or operators:-
2925 -not_bool => { two=> { -rlike => 'bar' } },
2926 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
2937 (NOT ( three = ? OR three > ? ))
2940 =head2 Nested conditions, -and/-or prefixes
2942 So far, we've seen how multiple conditions are joined with a top-level
2943 C<AND>. We can change this by putting the different conditions we want in
2944 hashes and then putting those hashes in an array. For example:
2949 status => { -like => ['pending%', 'dispatched'] },
2953 status => 'unassigned',
2957 This data structure would create the following:
2959 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2960 OR ( user = ? AND status = ? ) )";
2961 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2964 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2965 to change the logic inside:
2971 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2972 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2979 $stmt = "WHERE ( user = ?
2980 AND ( ( workhrs > ? AND geo = ? )
2981 OR ( workhrs < ? OR geo = ? ) ) )";
2982 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
2984 =head3 Algebraic inconsistency, for historical reasons
2986 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2987 operator goes C<outside> of the nested structure; whereas when connecting
2988 several constraints on one column, the C<-and> operator goes
2989 C<inside> the arrayref. Here is an example combining both features:
2992 -and => [a => 1, b => 2],
2993 -or => [c => 3, d => 4],
2994 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2999 WHERE ( ( ( a = ? AND b = ? )
3000 OR ( c = ? OR d = ? )
3001 OR ( e LIKE ? AND e LIKE ? ) ) )
3003 This difference in syntax is unfortunate but must be preserved for
3004 historical reasons. So be careful: the two examples below would
3005 seem algebraically equivalent, but they are not
3008 { -like => 'foo%' },
3009 { -like => '%bar' },
3011 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
3014 { col => { -like => 'foo%' } },
3015 { col => { -like => '%bar' } },
3017 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
3020 =head2 Literal SQL and value type operators
3022 The basic premise of SQL::Abstract is that in WHERE specifications the "left
3023 side" is a column name and the "right side" is a value (normally rendered as
3024 a placeholder). This holds true for both hashrefs and arrayref pairs as you
3025 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
3026 alter this behavior. There are several ways of doing so.
3030 This is a virtual operator that signals the string to its right side is an
3031 identifier (a column name) and not a value. For example to compare two
3032 columns you would write:
3035 priority => { '<', 2 },
3036 requestor => { -ident => 'submitter' },
3041 $stmt = "WHERE priority < ? AND requestor = submitter";
3044 If you are maintaining legacy code you may see a different construct as
3045 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
3050 This is a virtual operator that signals that the construct to its right side
3051 is a value to be passed to DBI. This is for example necessary when you want
3052 to write a where clause against an array (for RDBMS that support such
3053 datatypes). For example:
3056 array => { -value => [1, 2, 3] }
3061 $stmt = 'WHERE array = ?';
3062 @bind = ([1, 2, 3]);
3064 Note that if you were to simply say:
3070 the result would probably not be what you wanted:
3072 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
3077 Finally, sometimes only literal SQL will do. To include a random snippet
3078 of SQL verbatim, you specify it as a scalar reference. Consider this only
3079 as a last resort. Usually there is a better way. For example:
3082 priority => { '<', 2 },
3083 requestor => { -in => \'(SELECT name FROM hitmen)' },
3088 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
3091 Note that in this example, you only get one bind parameter back, since
3092 the verbatim SQL is passed as part of the statement.
3096 Never use untrusted input as a literal SQL argument - this is a massive
3097 security risk (there is no way to check literal snippets for SQL
3098 injections and other nastyness). If you need to deal with untrusted input
3099 use literal SQL with placeholders as described next.
3101 =head3 Literal SQL with placeholders and bind values (subqueries)
3103 If the literal SQL to be inserted has placeholders and bind values,
3104 use a reference to an arrayref (yes this is a double reference --
3105 not so common, but perfectly legal Perl). For example, to find a date
3106 in Postgres you can use something like this:
3109 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
3114 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
3117 Note that you must pass the bind values in the same format as they are returned
3118 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
3119 to C<columns>, you must provide the bind values in the
3120 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
3121 scalar value; most commonly the column name, but you can use any scalar value
3122 (including references and blessed references), L<SQL::Abstract> will simply
3123 pass it through intact. So if C<bindtype> is set to C<columns> the above
3124 example will look like:
3127 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
3130 Literal SQL is especially useful for nesting parenthesized clauses in the
3131 main SQL query. Here is a first example:
3133 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
3137 bar => \["IN ($sub_stmt)" => @sub_bind],
3142 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
3143 WHERE c2 < ? AND c3 LIKE ?))";
3144 @bind = (1234, 100, "foo%");
3146 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
3147 are expressed in the same way. Of course the C<$sub_stmt> and
3148 its associated bind values can be generated through a former call
3151 my ($sub_stmt, @sub_bind)
3152 = $sql->select("t1", "c1", {c2 => {"<" => 100},
3153 c3 => {-like => "foo%"}});
3156 bar => \["> ALL ($sub_stmt)" => @sub_bind],
3159 In the examples above, the subquery was used as an operator on a column;
3160 but the same principle also applies for a clause within the main C<%where>
3161 hash, like an EXISTS subquery:
3163 my ($sub_stmt, @sub_bind)
3164 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
3165 my %where = ( -and => [
3167 \["EXISTS ($sub_stmt)" => @sub_bind],
3172 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
3173 WHERE c1 = ? AND c2 > t0.c0))";
3177 Observe that the condition on C<c2> in the subquery refers to
3178 column C<t0.c0> of the main query: this is I<not> a bind
3179 value, so we have to express it through a scalar ref.
3180 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
3181 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
3182 what we wanted here.
3184 Finally, here is an example where a subquery is used
3185 for expressing unary negation:
3187 my ($sub_stmt, @sub_bind)
3188 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
3189 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
3191 lname => {like => '%son%'},
3192 \["NOT ($sub_stmt)" => @sub_bind],
3197 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
3198 @bind = ('%son%', 10, 20)
3200 =head3 Deprecated usage of Literal SQL
3202 Below are some examples of archaic use of literal SQL. It is shown only as
3203 reference for those who deal with legacy code. Each example has a much
3204 better, cleaner and safer alternative that users should opt for in new code.
3210 my %where = ( requestor => \'IS NOT NULL' )
3212 $stmt = "WHERE requestor IS NOT NULL"
3214 This used to be the way of generating NULL comparisons, before the handling
3215 of C<undef> got formalized. For new code please use the superior syntax as
3216 described in L</Tests for NULL values>.
3220 my %where = ( requestor => \'= submitter' )
3222 $stmt = "WHERE requestor = submitter"
3224 This used to be the only way to compare columns. Use the superior L</-ident>
3225 method for all new code. For example an identifier declared in such a way
3226 will be properly quoted if L</quote_char> is properly set, while the legacy
3227 form will remain as supplied.
3231 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
3233 $stmt = "WHERE completed > ? AND is_ready"
3234 @bind = ('2012-12-21')
3236 Using an empty string literal used to be the only way to express a boolean.
3237 For all new code please use the much more readable
3238 L<-bool|/Unary operators: bool> operator.
3244 These pages could go on for a while, since the nesting of the data
3245 structures this module can handle are pretty much unlimited (the
3246 module implements the C<WHERE> expansion as a recursive function
3247 internally). Your best bet is to "play around" with the module a
3248 little to see how the data structures behave, and choose the best
3249 format for your data based on that.
3251 And of course, all the values above will probably be replaced with
3252 variables gotten from forms or the command line. After all, if you
3253 knew everything ahead of time, you wouldn't have to worry about
3254 dynamically-generating SQL and could just hardwire it into your
3257 =head1 ORDER BY CLAUSES
3259 Some functions take an order by clause. This can either be a scalar (just a
3260 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
3261 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
3264 Given | Will Generate
3265 ---------------------------------------------------------------
3267 'colA' | ORDER BY colA
3269 [qw/colA colB/] | ORDER BY colA, colB
3271 {-asc => 'colA'} | ORDER BY colA ASC
3273 {-desc => 'colB'} | ORDER BY colB DESC
3275 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
3277 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
3279 \'colA DESC' | ORDER BY colA DESC
3281 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
3282 | /* ...with $x bound to ? */
3285 { -asc => 'colA' }, | colA ASC,
3286 { -desc => [qw/colB/] }, | colB DESC,
3287 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
3288 \'colE DESC', | colE DESC,
3289 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
3290 ] | /* ...with $x bound to ? */
3291 ===============================================================
3295 =head1 SPECIAL OPERATORS
3297 my $sqlmaker = SQL::Abstract->new(special_ops => [
3301 my ($self, $field, $op, $arg) = @_;
3307 handler => 'method_name',
3311 A "special operator" is a SQL syntactic clause that can be
3312 applied to a field, instead of a usual binary operator.
3315 WHERE field IN (?, ?, ?)
3316 WHERE field BETWEEN ? AND ?
3317 WHERE MATCH(field) AGAINST (?, ?)
3319 Special operators IN and BETWEEN are fairly standard and therefore
3320 are builtin within C<SQL::Abstract> (as the overridable methods
3321 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
3322 like the MATCH .. AGAINST example above which is specific to MySQL,
3323 you can write your own operator handlers - supply a C<special_ops>
3324 argument to the C<new> method. That argument takes an arrayref of
3325 operator definitions; each operator definition is a hashref with two
3332 the regular expression to match the operator
3336 Either a coderef or a plain scalar method name. In both cases
3337 the expected return is C<< ($sql, @bind) >>.
3339 When supplied with a method name, it is simply called on the
3340 L<SQL::Abstract> object as:
3342 $self->$method_name($field, $op, $arg)
3346 $field is the LHS of the operator
3347 $op is the part that matched the handler regex
3350 When supplied with a coderef, it is called as:
3352 $coderef->($self, $field, $op, $arg)
3357 For example, here is an implementation
3358 of the MATCH .. AGAINST syntax for MySQL
3360 my $sqlmaker = SQL::Abstract->new(special_ops => [
3362 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3363 {regex => qr/^match$/i,
3365 my ($self, $field, $op, $arg) = @_;
3366 $arg = [$arg] if not ref $arg;
3367 my $label = $self->_quote($field);
3368 my ($placeholder) = $self->_convert('?');
3369 my $placeholders = join ", ", (($placeholder) x @$arg);
3370 my $sql = $self->_sqlcase('match') . " ($label) "
3371 . $self->_sqlcase('against') . " ($placeholders) ";
3372 my @bind = $self->_bindtype($field, @$arg);
3373 return ($sql, @bind);
3380 =head1 UNARY OPERATORS
3382 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3386 my ($self, $op, $arg) = @_;
3392 handler => 'method_name',
3396 A "unary operator" is a SQL syntactic clause that can be
3397 applied to a field - the operator goes before the field
3399 You can write your own operator handlers - supply a C<unary_ops>
3400 argument to the C<new> method. That argument takes an arrayref of
3401 operator definitions; each operator definition is a hashref with two
3408 the regular expression to match the operator
3412 Either a coderef or a plain scalar method name. In both cases
3413 the expected return is C<< $sql >>.
3415 When supplied with a method name, it is simply called on the
3416 L<SQL::Abstract> object as:
3418 $self->$method_name($op, $arg)
3422 $op is the part that matched the handler regex
3423 $arg is the RHS or argument of the operator
3425 When supplied with a coderef, it is called as:
3427 $coderef->($self, $op, $arg)
3435 Thanks to some benchmarking by Mark Stosberg, it turns out that
3436 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3437 I must admit this wasn't an intentional design issue, but it's a
3438 byproduct of the fact that you get to control your C<DBI> handles
3441 To maximize performance, use a code snippet like the following:
3443 # prepare a statement handle using the first row
3444 # and then reuse it for the rest of the rows
3446 for my $href (@array_of_hashrefs) {
3447 $stmt ||= $sql->insert('table', $href);
3448 $sth ||= $dbh->prepare($stmt);
3449 $sth->execute($sql->values($href));
3452 The reason this works is because the keys in your C<$href> are sorted
3453 internally by B<SQL::Abstract>. Thus, as long as your data retains
3454 the same structure, you only have to generate the SQL the first time
3455 around. On subsequent queries, simply use the C<values> function provided
3456 by this module to return your values in the correct order.
3458 However this depends on the values having the same type - if, for
3459 example, the values of a where clause may either have values
3460 (resulting in sql of the form C<column = ?> with a single bind
3461 value), or alternatively the values might be C<undef> (resulting in
3462 sql of the form C<column IS NULL> with no bind value) then the
3463 caching technique suggested will not work.
3467 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3468 really like this part (I do, at least). Building up a complex query
3469 can be as simple as the following:
3476 use CGI::FormBuilder;
3479 my $form = CGI::FormBuilder->new(...);
3480 my $sql = SQL::Abstract->new;
3482 if ($form->submitted) {
3483 my $field = $form->field;
3484 my $id = delete $field->{id};
3485 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3488 Of course, you would still have to connect using C<DBI> to run the
3489 query, but the point is that if you make your form look like your
3490 table, the actual query script can be extremely simplistic.
3492 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3493 a fast interface to returning and formatting data. I frequently
3494 use these three modules together to write complex database query
3495 apps in under 50 lines.
3497 =head1 HOW TO CONTRIBUTE
3499 Contributions are always welcome, in all usable forms (we especially
3500 welcome documentation improvements). The delivery methods include git-
3501 or unified-diff formatted patches, GitHub pull requests, or plain bug
3502 reports either via RT or the Mailing list. Contributors are generally
3503 granted full access to the official repository after their first several
3504 patches pass successful review.
3506 This project is maintained in a git repository. The code and related tools are
3507 accessible at the following locations:
3511 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3513 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3515 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3517 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3523 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3524 Great care has been taken to preserve the I<published> behavior
3525 documented in previous versions in the 1.* family; however,
3526 some features that were previously undocumented, or behaved
3527 differently from the documentation, had to be changed in order
3528 to clarify the semantics. Hence, client code that was relying
3529 on some dark areas of C<SQL::Abstract> v1.*
3530 B<might behave differently> in v1.50.
3532 The main changes are:
3538 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3542 support for the { operator => \"..." } construct (to embed literal SQL)
3546 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3550 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3554 defensive programming: check arguments
3558 fixed bug with global logic, which was previously implemented
3559 through global variables yielding side-effects. Prior versions would
3560 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3561 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3562 Now this is interpreted
3563 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3568 fixed semantics of _bindtype on array args
3572 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3573 we just avoid shifting arrays within that tree.
3577 dropped the C<_modlogic> function
3581 =head1 ACKNOWLEDGEMENTS
3583 There are a number of individuals that have really helped out with
3584 this module. Unfortunately, most of them submitted bugs via CPAN
3585 so I have no idea who they are! But the people I do know are:
3587 Ash Berlin (order_by hash term support)
3588 Matt Trout (DBIx::Class support)
3589 Mark Stosberg (benchmarking)
3590 Chas Owens (initial "IN" operator support)
3591 Philip Collins (per-field SQL functions)
3592 Eric Kolve (hashref "AND" support)
3593 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3594 Dan Kubb (support for "quote_char" and "name_sep")
3595 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3596 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3597 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3598 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3599 Oliver Charles (support for "RETURNING" after "INSERT")
3605 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3609 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3611 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3613 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3614 While not an official support venue, C<DBIx::Class> makes heavy use of
3615 C<SQL::Abstract>, and as such list members there are very familiar with
3616 how to create queries.
3620 This module is free software; you may copy this under the same
3621 terms as perl itself (either the GNU General Public License or
3622 the Artistic License)