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 is_undef_value);
21 *SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION = $ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}
27 #======================================================================
29 #======================================================================
31 our $VERSION = '1.86';
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 row => '_expand_row',
145 func => '_expand_func',
146 values => '_expand_values',
147 list => '_expand_list',
150 (map +($_ => __PACKAGE__->make_binop_expander('_expand_between')),
151 qw(between not_between)),
152 (map +($_ => __PACKAGE__->make_binop_expander('_expand_in')),
154 (map +($_ => '_expand_op_andor'), ('and', 'or')),
155 (map +($_ => '_expand_op_is'), ('is', 'is_not')),
156 (map +($_ => __PACKAGE__->make_unop_expander("_expand_${_}")),
157 qw(ident value nest)),
160 (map +($_, "_render_$_"),
161 qw(op func bind ident literal row values keyword)),
164 (map +($_ => '_render_op_between'), 'between', 'not_between'),
165 (map +($_ => '_render_op_in'), 'in', 'not_in'),
166 (map +($_ => '_render_unop_postfix'),
167 'is_null', 'is_not_null', 'asc', 'desc',
169 (not => '_render_unop_paren'),
170 (map +($_ => '_render_op_andor'), qw(and or)),
171 ',' => '_render_op_multop',
174 delete => [ qw(target where returning) ],
175 update => [ qw(target set where returning) ],
176 insert => [ qw(target fields from returning) ],
177 select => [ qw(select from where order_by) ],
180 'delete.from' => '_expand_delete_clause_target',
181 'update.update' => '_expand_update_clause_target',
182 'insert.into' => '_expand_insert_clause_target',
183 'insert.values' => '_expand_insert_clause_from',
186 'delete.target' => '_render_delete_clause_target',
187 'update.target' => '_render_update_clause_target',
188 'insert.target' => '_render_insert_clause_target',
189 'insert.fields' => '_render_insert_clause_fields',
190 'insert.from' => '_render_insert_clause_from',
194 foreach my $stmt (keys %{$Defaults{clauses_of}}) {
195 $Defaults{expand}{$stmt} = '_expand_statement';
196 $Defaults{render}{$stmt} = '_render_statement';
197 foreach my $clause (@{$Defaults{clauses_of}{$stmt}}) {
198 $Defaults{expand_clause}{"${stmt}.${clause}"}
199 = "_expand_${stmt}_clause_${clause}";
205 my $class = ref($self) || $self;
206 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
208 # choose our case by keeping an option around
209 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
211 # default logic for interpreting arrayrefs
212 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
214 # how to return bind vars
215 $opt{bindtype} ||= 'normal';
217 # default comparison is "=", but can be overridden
220 # try to recognize which are the 'equality' and 'inequality' ops
221 # (temporary quickfix (in 2007), should go through a more seasoned API)
222 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
223 $opt{inequality_op} = qr/^( != | <> )$/ix;
225 $opt{like_op} = qr/^ (is_)?r?like $/xi;
226 $opt{not_like_op} = qr/^ (is_)?not_r?like $/xi;
229 $opt{sqltrue} ||= '1=1';
230 $opt{sqlfalse} ||= '0=1';
233 $opt{special_ops} ||= [];
236 $opt{unary_ops} ||= [];
238 # rudimentary sanity-check for user supplied bits treated as functions/operators
239 # If a purported function matches this regular expression, an exception is thrown.
240 # Literal SQL is *NOT* subject to this check, only functions (and column names
241 # when quoting is not in effect)
244 # need to guard against ()'s in column names too, but this will break tons of
245 # hacks... ideas anyone?
246 $opt{injection_guard} ||= qr/
252 $opt{expand_unary} = {};
254 foreach my $name (sort keys %Defaults) {
255 $opt{$name} = { %{$Defaults{$name}}, %{$opt{$name}||{}} };
258 if ($class ne __PACKAGE__) {
260 # check for overriden methods
262 foreach my $type (qw(insert update delete)) {
263 my $method = "_${type}_returning";
264 if (__PACKAGE__->can($method) ne $class->can($method)) {
265 my $clause = "${type}.returning";
266 $opt{expand_clause}{$clause} = sub { $_[2] },
267 $opt{render_clause}{$clause}
268 = sub { [ $_[0]->$method($_[3]) ] };
271 if (__PACKAGE__->can('_table') ne $class->can('_table')) {
272 $opt{expand_clause}{'select.from'} = sub {
273 return +{ -literal => [ $_[0]->_table($_[2]) ] };
276 if (__PACKAGE__->can('_order_by') ne $class->can('_order_by')) {
277 $opt{expand_clause}{'select.order_by'} = sub { $_[2] };
278 $opt{render_clause}{'select.order_by'} = sub {
279 [ $_[0]->_order_by($_[2]) ];
282 if ($class->isa('DBIx::Class::SQLMaker')) {
283 $opt{warn_once_on_nest} = 1;
284 $opt{disable_old_special_ops} = 1;
285 $opt{render_clause}{'select.where'} = sub {
286 my ($sql, @bind) = $_[0]->where($_[2]);
287 s/\A\s+//, s/\s+\Z// for $sql;
288 return [ $sql, @bind ];
293 if ($opt{lazy_join_sql_parts}) {
294 my $mod = Module::Runtime::use_module('SQL::Abstract::Parts');
295 $opt{join_sql_parts} ||= sub { $mod->new(@_) };
298 $opt{join_sql_parts} ||= sub { join $_[0], @_[1..$#_] };
300 return bless \%opt, $class;
304 my ($self, $name, $key, $value) = @_;
305 return $self->{$name}{$key} unless @_ > 3;
306 $self->{$name}{$key} = $value;
310 sub make_unop_expander {
311 my (undef, $exp) = @_;
313 my ($self, $name, $body, $k) = @_;
314 return $self->_expand_hashpair_cmp($k, { "-${name}" => $body })
316 return $self->$exp($name, $body);
320 sub make_binop_expander {
321 my (undef, $exp) = @_;
323 my ($self, $name, $body, $k) = @_;
324 $k = shift @{$body = [ @$body ]} unless defined $k;
325 $k = ref($k) ? $k : { -ident => $k };
326 return $self->$exp($name, $body, $k);
331 my ($self, $plugin, @args) = @_;
332 unless (ref $plugin) {
333 $plugin =~ s/\A\+/${\ref($self)}::Plugin::/;
334 require(join('/', split '::', $plugin).'.pm');
336 $plugin->apply_to($self, @args);
341 foreach my $type (qw(
342 expand op_expand render op_render clause_expand clause_render
344 my $name = join '_', reverse split '_', $type;
345 my $singular = "${type}er";
347 eval qq{sub ${singular} { shift->${singular}s(\@_) }; 1 }
348 or die "Method builder failed for ${singular}: $@";
349 eval qq{sub wrap_${singular} {
350 shift->wrap_${singular}s(\@_)
351 }; 1 } or die "Method builder failed for wrap_${singular}: $@";
353 eval qq{sub ${singular}s {
354 my (\$self, \@args) = \@_;
355 while (my (\$this_key, \$this_value) = splice(\@args, 0, 2)) {
356 \$self->_ext_rw('${name}', \$this_key, \$this_value);
359 }; 1 } or die "Method builder failed for ${singular}s: $@";
360 eval qq{sub wrap_${singular}s {
361 my (\$self, \@args) = \@_;
362 while (my (\$this_key, \$this_builder) = splice(\@args, 0, 2)) {
363 my \$orig = \$self->_ext_rw('${name}', \$this_key);
365 '${name}', \$this_key,
366 \$this_builder->(\$orig, '${name}', \$this_key),
370 }; 1 } or die "Method builder failed for wrap_${singular}s: $@";
371 eval qq{sub ${singular}_list { sort keys %{\$_[0]->{\$name}} }; 1; }
372 or die "Method builder failed for ${singular}_list: $@";
374 foreach my $singular (qw(unop_expander binop_expander)) {
375 eval qq{sub ${singular} { shift->${singular}s(\@_) }; 1 }
376 or die "Method builder failed for ${singular}: $@";
377 eval qq{sub ${singular}s {
378 my (\$self, \@args) = \@_;
379 while (my (\$this_key, \$this_value) = splice(\@args, 0, 2)) {
381 expand_op => \$this_key,
382 \$self->make_${singular}(\$this_value),
386 }; 1 } or die "Method builder failed for ${singular}s: $@";
390 #sub register_op { $_[0]->{is_op}{$_[1]} = 1; $_[0] }
392 sub statement_list { sort keys %{$_[0]->{clauses_of}} }
395 my ($self, $of, @clauses) = @_;
397 return @{$self->{clauses_of}{$of}||[]};
399 if (ref($clauses[0]) eq 'CODE') {
400 @clauses = $self->${\($clauses[0])}(@{$self->{clauses_of}{$of}||[]});
402 $self->{clauses_of}{$of} = \@clauses;
411 ref($self->{$_}) eq 'HASH'
420 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
421 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
423 sub _assert_pass_injection_guard {
424 if ($_[1] =~ $_[0]->{injection_guard}) {
425 my $class = ref $_[0];
426 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
427 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
428 . "{injection_guard} attribute to ${class}->new()"
433 #======================================================================
435 #======================================================================
438 my ($self, $table, $data, $options) = @_;
441 if (ref($table) eq 'HASH') {
444 my %clauses = (target => $table, values => $data, %{$options||{}});
448 my @rendered = $self->render_statement({ -insert => $stmt });
449 return wantarray ? @rendered : $rendered[0];
452 sub _expand_insert_clause_target {
453 +(target => $_[0]->expand_expr($_[2], -ident));
456 sub _expand_insert_clause_fields {
458 $_[0]->expand_expr({ -list => $_[2] }, -ident)
459 ] } if ref($_[2]) eq 'ARRAY';
460 return $_[2]; # should maybe still expand somewhat?
463 sub _expand_insert_clause_from {
464 my ($self, undef, $data) = @_;
465 if (ref($data) eq 'HASH' and (keys(%$data))[0] =~ /^-/) {
466 return $self->expand_expr($data);
468 my ($f_aqt, $v_aqt) = $self->_expand_insert_values($data);
470 from => { -values => [ $v_aqt ] },
471 ($f_aqt ? (fields => $f_aqt) : ()),
475 sub _expand_insert_clause_returning {
476 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
479 sub _expand_insert_values {
480 my ($self, $data) = @_;
481 if (is_literal_value($data)) {
482 (undef, $self->expand_expr($data));
484 my ($fields, $values) = (
485 ref($data) eq 'HASH' ?
486 ([ sort keys %$data ], [ @{$data}{sort keys %$data} ])
490 # no names (arrayref) means can't generate bindtype
491 !($fields) && $self->{bindtype} eq 'columns'
492 && belch "can't do 'columns' bindtype when called with arrayref";
496 ? $self->expand_expr({ -row => $fields }, -ident)
501 local our $Cur_Col_Meta = $fields->[$_];
502 $self->_expand_insert_value($values->[$_])
509 sub _render_insert_clause_fields {
510 return $_[0]->render_aqt($_[2]);
513 sub _render_insert_clause_target {
514 my ($self, undef, $from) = @_;
515 $self->join_query_parts(' ', { -keyword => 'insert into' }, $from);
518 sub _render_insert_clause_from {
519 return $_[0]->render_aqt($_[2], 1);
522 # So that subclasses can override INSERT ... RETURNING separately from
523 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
524 sub _insert_returning { shift->_returning(@_) }
526 sub _redispatch_returning {
527 my ($self, $type, undef, $returning) = @_;
528 [ $self->${\"_${type}_returning"}({ returning => $returning }) ];
532 my ($self, $options) = @_;
534 my $f = $options->{returning};
536 my ($sql, @bind) = @{ $self->render_aqt(
537 $self->expand_expr({ -list => $f }, -ident)
539 return ($self->_sqlcase(' returning ').$sql, @bind);
542 sub _expand_insert_value {
545 my $k = our $Cur_Col_Meta;
547 if (ref($v) eq 'ARRAY') {
548 if ($self->{array_datatypes}) {
549 return +{ -bind => [ $k, $v ] };
551 my ($sql, @bind) = @$v;
552 $self->_assert_bindval_matches_bindtype(@bind);
553 return +{ -literal => $v };
555 if (ref($v) eq 'HASH') {
556 if (grep !/^-/, keys %$v) {
557 belch "HASH ref as bind value in insert is not supported";
558 return +{ -bind => [ $k, $v ] };
562 return +{ -bind => [ $k, undef ] };
564 return $self->expand_expr($v);
569 #======================================================================
571 #======================================================================
574 my ($self, $table, $set, $where, $options) = @_;
577 if (ref($table) eq 'HASH') {
581 @clauses{qw(target set where)} = ($table, $set, $where);
582 puke "Unsupported data type specified to \$sql->update"
583 unless ref($clauses{set}) eq 'HASH';
584 @clauses{keys %$options} = values %$options;
588 my @rendered = $self->render_statement({ -update => $stmt });
589 return wantarray ? @rendered : $rendered[0];
592 sub _render_update_clause_target {
593 my ($self, undef, $target) = @_;
594 $self->join_query_parts(' ', { -keyword => 'update' }, $target);
597 sub _update_set_values {
598 my ($self, $data) = @_;
600 return @{ $self->render_aqt(
601 $self->_expand_update_set_values(undef, $data),
605 sub _expand_update_set_values {
606 my ($self, undef, $data) = @_;
607 $self->expand_expr({ -list => [
610 $set = { -bind => $_ } unless defined $set;
611 +{ -op => [ '=', { -ident => $k }, $set ] };
617 ? ($self->{array_datatypes}
618 ? [ $k, +{ -bind => [ $k, $v ] } ]
619 : [ $k, +{ -literal => $v } ])
621 local our $Cur_Col_Meta = $k;
622 [ $k, $self->_expand_expr($v) ]
629 sub _expand_update_clause_target {
630 my ($self, undef, $target) = @_;
631 +(target => $self->expand_expr({ -list => $target }, -ident));
634 sub _expand_update_clause_set {
635 return $_[2] if ref($_[2]) eq 'HASH' and ($_[2]->{-op}||[''])->[0] eq ',';
636 +(set => $_[0]->_expand_update_set_values($_[1], $_[2]));
639 sub _expand_update_clause_where {
640 +(where => $_[0]->expand_expr($_[2]));
643 sub _expand_update_clause_returning {
644 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
647 # So that subclasses can override UPDATE ... RETURNING separately from
649 sub _update_returning { shift->_returning(@_) }
653 #======================================================================
655 #======================================================================
658 my ($self, @args) = @_;
660 if (ref(my $sel = $args[0]) eq 'HASH') {
664 @clauses{qw(from select where order_by)} = @args;
666 # This oddity is to literalify since historically SQLA doesn't quote
667 # a single identifier argument, so we convert it into a literal
669 $clauses{select} = { -literal => [ $clauses{select}||'*' ] }
670 unless ref($clauses{select});
675 my @rendered = $self->render_statement({ -select => $stmt });
676 return wantarray ? @rendered : $rendered[0];
679 sub _expand_select_clause_select {
680 my ($self, undef, $select) = @_;
681 +(select => $self->expand_expr({ -list => $select }, -ident));
684 sub _expand_select_clause_from {
685 my ($self, undef, $from) = @_;
686 +(from => $self->expand_expr({ -list => $from }, -ident));
689 sub _expand_select_clause_where {
690 my ($self, undef, $where) = @_;
693 if (my $conv = $self->{convert}) {
705 ->wrap_expander(bind => $_wrap)
706 ->wrap_op_expanders(map +($_ => $_wrap), qw(ident value))
707 ->wrap_expander(func => sub {
710 my ($self, $type, $thing) = @_;
711 if (ref($thing) eq 'ARRAY' and $thing->[0] eq $conv
712 and @$thing == 2 and ref($thing->[1]) eq 'HASH'
715 or $thing->[1]{-value}
716 or $thing->[1]{-bind})
718 return { -func => $thing }; # already went through our expander
720 return $self->$orig($type, $thing);
728 return +(where => $sqla->expand_expr($where));
731 sub _expand_select_clause_order_by {
732 my ($self, undef, $order_by) = @_;
733 +(order_by => $self->_expand_order_by($order_by));
737 my ($self, $fields) = @_;
738 return $fields unless ref($fields);
739 return @{ $self->render_aqt(
740 $self->expand_expr({ -list => $fields }, '-ident')
744 #======================================================================
746 #======================================================================
749 my ($self, $table, $where, $options) = @_;
752 if (ref($table) eq 'HASH') {
755 my %clauses = (target => $table, where => $where, %{$options||{}});
759 my @rendered = $self->render_statement({ -delete => $stmt });
760 return wantarray ? @rendered : $rendered[0];
763 # So that subclasses can override DELETE ... RETURNING separately from
765 sub _delete_returning { shift->_returning(@_) }
767 sub _expand_delete_clause_target {
768 +(target => $_[0]->expand_expr({ -list => $_[2] }, -ident));
771 sub _expand_delete_clause_where { +(where => $_[0]->expand_expr($_[2])); }
773 sub _expand_delete_clause_returning {
774 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
777 sub _render_delete_clause_target {
778 my ($self, undef, $from) = @_;
779 $self->join_query_parts(' ', { -keyword => 'delete from' }, $from);
782 #======================================================================
784 #======================================================================
788 # Finally, a separate routine just to handle WHERE clauses
790 my ($self, $where, $order) = @_;
792 local $self->{convert_where} = $self->{convert};
795 my ($sql, @bind) = defined($where)
796 ? $self->_recurse_where($where)
798 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
802 my ($order_sql, @order_bind) = $self->_order_by($order);
804 push @bind, @order_bind;
807 return wantarray ? ($sql, @bind) : $sql;
810 { our $Default_Scalar_To = -value }
813 my ($self, $expr, $default_scalar_to) = @_;
814 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
815 $self->_expand_expr($expr);
819 my ($self, $aqt, $top_level) = @_;
820 my ($k, $v, @rest) = %$aqt;
822 die "Not a node type: $k" unless $k =~ s/^-//;
823 if (my $meth = $self->{render}{$k}) {
824 local our $Render_Top_Level = $top_level;
825 return $self->$meth($k, $v);
827 die "notreached: $k";
831 my ($self, $expr, $default_scalar_to) = @_;
832 return @{ $self->render_aqt(
833 $self->expand_expr($expr, $default_scalar_to)
837 sub render_statement {
838 my ($self, $expr, $default_scalar_to) = @_;
840 $self->expand_expr($expr, $default_scalar_to), 1
844 sub _expand_statement {
845 my ($self, $type, $args) = @_;
846 my $ec = $self->{expand_clause};
849 $args->{$type} = delete $args->{_}
851 my %has_clause = map +($_ => 1), @{$self->{clauses_of}{$type}};
852 return +{ "-${type}" => +{
854 my $val = $args->{$_};
855 if (defined($val) and my $exp = $ec->{"${type}.$_"}) {
856 if ((my (@exp) = $self->$exp($_ => $val)) == 1) {
861 } elsif ($has_clause{$_}) {
862 ($_ => $self->expand_expr($val))
870 sub _render_statement {
871 my ($self, $type, $args) = @_;
873 foreach my $clause (@{$self->{clauses_of}{$type}}) {
874 next unless my $clause_expr = $args->{$clause};
876 if (my $rdr = $self->{render_clause}{"${type}.${clause}"}) {
877 $self->$rdr($clause, $clause_expr, $args);
879 my $r = $self->render_aqt($clause_expr, 1);
880 next unless defined $r->[0] and length $r->[0];
881 $self->join_query_parts(' ',
882 { -keyword => $clause },
889 my $q = $self->join_query_parts(' ', @parts);
890 return $self->join_query_parts('',
891 (our $Render_Top_Level ? $q : ('(', $q, ')'))
896 my ($self, $raw) = @_;
898 return $op if grep $_->{$op}, @{$self}{qw(expand_op render_op)};
899 s/^-(?=.)//, s/\s+/_/g for $op;
904 my ($self, $expr) = @_;
905 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
906 return undef unless defined($expr);
907 if (ref($expr) eq 'HASH') {
908 return undef unless my $kc = keys %$expr;
910 return $self->_expand_op_andor(and => $expr);
912 my ($key, $value) = %$expr;
913 if ($key =~ /^-/ and $key =~ s/ [_\s]? \d+ $//x ) {
914 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
915 . "You probably wanted ...-and => [ $key => COND1, $key => COND2 ... ]";
917 return $self->_expand_hashpair($key, $value);
919 if (ref($expr) eq 'ARRAY') {
920 return $self->_expand_op_andor(lc($self->{logic}), $expr);
922 if (my $literal = is_literal_value($expr)) {
923 return +{ -literal => $literal };
925 if (!ref($expr) or Scalar::Util::blessed($expr)) {
926 return $self->_expand_scalar($expr);
931 sub _expand_hashpair {
932 my ($self, $k, $v) = @_;
933 unless (defined($k) and length($k)) {
934 if (defined($k) and my $literal = is_literal_value($v)) {
935 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
936 return { -literal => $literal };
938 puke "Supplying an empty left hand side argument is not supported";
941 return $self->_expand_hashpair_op($k, $v);
942 } elsif ($k =~ /^[^\w]/i) {
943 my ($lhs, @rhs) = ref($v) eq 'ARRAY' ? @$v : $v;
944 return $self->_expand_op(
945 -op, [ $k, $self->expand_expr($lhs, -ident), @rhs ]
948 return $self->_expand_hashpair_ident($k, $v);
951 sub _expand_hashpair_ident {
952 my ($self, $k, $v) = @_;
954 local our $Cur_Col_Meta = $k;
956 # hash with multiple or no elements is andor
958 if (ref($v) eq 'HASH' and keys %$v != 1) {
959 return $self->_expand_op_andor(and => $v, $k);
962 # undef needs to be re-sent with cmp to achieve IS/IS NOT NULL
964 if (is_undef_value($v)) {
965 return $self->_expand_hashpair_cmp($k => undef);
968 # scalars and objects get expanded as whatever requested or values
970 if (!ref($v) or Scalar::Util::blessed($v)) {
971 return $self->_expand_hashpair_scalar($k, $v);
974 # single key hashref is a hashtriple
976 if (ref($v) eq 'HASH') {
977 return $self->_expand_hashtriple($k, %$v);
980 # arrayref needs re-engineering over the elements
982 if (ref($v) eq 'ARRAY') {
983 return $self->sqlfalse unless @$v;
984 $self->_debug("ARRAY($k) means distribute over elements");
986 $v->[0] =~ /^-(and|or)$/i
987 ? (shift(@{$v = [ @$v ]}), $1)
988 : lc($self->{logic} || 'OR')
990 return $self->_expand_op_andor(
995 if (my $literal = is_literal_value($v)) {
997 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
1000 my ($sql, @bind) = @$literal;
1001 if ($self->{bindtype} eq 'columns') {
1003 $self->_assert_bindval_matches_bindtype($_);
1006 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
1011 sub _expand_scalar {
1012 my ($self, $expr) = @_;
1014 return $self->_expand_expr({ (our $Default_Scalar_To) => $expr });
1017 sub _expand_hashpair_scalar {
1018 my ($self, $k, $v) = @_;
1020 return $self->_expand_hashpair_cmp(
1021 $k, $self->_expand_scalar($v),
1025 sub _expand_hashpair_op {
1026 my ($self, $k, $v) = @_;
1028 $self->_assert_pass_injection_guard($k =~ /\A-(.*)\Z/s);
1030 my $op = $self->_normalize_op($k);
1032 my $wsop = join(' ', split '_', $op);
1034 my $is_special = List::Util::first { $wsop =~ $_->{regex} }
1035 @{$self->{special_ops}};
1039 # the old special op system requires illegality for top-level use
1042 (our $Expand_Depth) == 1
1046 $self->{disable_old_special_ops}
1047 and List::Util::first { $wsop =~ $_->{regex} } @BUILTIN_SPECIAL_OPS
1051 puke "Illegal use of top-level '-$wsop'"
1055 if (my $exp = $self->{expand}{$op}||$self->{expand_op}{$op}) {
1056 return $self->$exp($op, $v);
1059 if ($self->{render}{$op}) {
1060 return { "-${op}" => $v };
1063 # Ops prefixed with -not_ get converted
1065 if (my ($rest) = $op =~/^not_(.*)$/) {
1068 $self->_expand_expr({ "-${rest}", $v })
1074 # the old unary op system means we should touch nothing and let it work
1076 my $op = join(' ', split '_', $op);
1078 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1079 return { -op => [ $op, $v ] };
1083 my $type = $is_special || $self->{render_op}{$op} ? -op : -func;
1085 if ($self->{restore_old_unop_handling}) {
1092 and (keys %$v)[0] =~ /^-/
1093 and not $self->{render_op}{$op}
1102 if ($type eq -func and ref($v) eq 'ARRAY') {
1103 return $self->_expand_expr({ -func => [ $op, @$v ] });
1106 return $self->_expand_expr({ $type => [ $op, $v ] });
1109 sub _expand_hashpair_cmp {
1110 my ($self, $k, $v) = @_;
1111 $self->_expand_hashtriple($k, $self->{cmp}, $v);
1114 sub _expand_hashtriple {
1115 my ($self, $k, $vk, $vv) = @_;
1117 my $ik = $self->_expand_expr({ -ident => $k });
1119 my $op = $self->_normalize_op($vk);
1120 $self->_assert_pass_injection_guard($op);
1122 if ($op =~ s/ _? \d+ $//x ) {
1123 return $self->_expand_expr($k, { $vk, $vv });
1125 if (my $x = $self->{expand_op}{$op}) {
1126 local our $Cur_Col_Meta = $k;
1127 return $self->$x($op, $vv, $k);
1131 my $op = join(' ', split '_', $op);
1133 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
1134 return { -op => [ $op, $ik, $vv ] };
1136 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1140 { -op => [ $op, $vv ] }
1144 if (ref($vv) eq 'ARRAY') {
1146 my $logic = (defined($raw[0]) and $raw[0] =~ /^-(and|or)$/i)
1147 ? (shift(@raw), lc $1) : 'or';
1148 my @values = map +{ $vk => $_ }, @raw;
1150 $op =~ $self->{inequality_op}
1151 or $op =~ $self->{not_like_op}
1153 if (lc($logic) eq 'or' and @values > 1) {
1154 belch "A multi-element arrayref as an argument to the inequality op '${\uc(join ' ', split '_', $op)}' "
1155 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
1156 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
1161 # try to DWIM on equality operators
1162 return ($self->_dwim_op_to_is($op,
1163 "Supplying an empty arrayref to '%s' is deprecated",
1164 "operator '%s' applied on an empty array (field '$k')"
1165 ) ? $self->sqlfalse : $self->sqltrue);
1167 return $self->_expand_op_andor($logic => \@values, $k);
1169 if (is_undef_value($vv)) {
1170 my $is = ($self->_dwim_op_to_is($op,
1171 "Supplying an undefined argument to '%s' is deprecated",
1172 "unexpected operator '%s' with undef operand",
1173 ) ? 'is' : 'is not');
1175 return $self->_expand_hashpair($k => { $is, undef });
1177 local our $Cur_Col_Meta = $k;
1181 $self->_expand_expr($vv)
1185 sub _dwim_op_to_is {
1186 my ($self, $raw, $empty, $fail) = @_;
1188 my $op = $self->_normalize_op($raw);
1190 if ($op =~ /^not$/i) {
1193 if ($op =~ $self->{equality_op}) {
1196 if ($op =~ $self->{like_op}) {
1197 belch(sprintf $empty, uc(join ' ', split '_', $op));
1200 if ($op =~ $self->{inequality_op}) {
1203 if ($op =~ $self->{not_like_op}) {
1204 belch(sprintf $empty, uc(join ' ', split '_', $op));
1207 puke(sprintf $fail, $op);
1211 my ($self, undef, $args) = @_;
1212 my ($func, @args) = @$args;
1213 return +{ -func => [ $func, map $self->expand_expr($_), @args ] };
1217 my ($self, undef, $body) = @_;
1218 unless (defined($body) or (ref($body) and ref($body) eq 'ARRAY')) {
1219 puke "-ident requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
1221 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
1222 ref($body) ? @$body : $body;
1223 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
1224 unless ($self->{quote_char}) {
1225 $self->_assert_pass_injection_guard($_) for @parts;
1227 return +{ -ident => \@parts };
1231 +{ -bind => [ our $Cur_Col_Meta, $_[2] ] };
1235 my ($self, undef, $args) = @_;
1236 +{ -row => [ map $self->expand_expr($_), @$args ] };
1240 my ($self, undef, $args) = @_;
1241 my ($op, @opargs) = @$args;
1242 if (my $exp = $self->{expand_op}{$op}) {
1243 return $self->$exp($op, \@opargs);
1245 +{ -op => [ $op, map $self->expand_expr($_), @opargs ] };
1249 my ($self, undef, $v) = @_;
1251 return $self->_expand_expr($v);
1253 puke "-bool => undef not supported" unless defined($v);
1254 return $self->_expand_expr({ -ident => $v });
1258 my ($self, undef, $expr) = @_;
1260 ',', map $self->expand_expr($_),
1261 @{$expr->{-op}}[1..$#{$expr->{-op}}]
1262 ] } if ref($expr) eq 'HASH' and ($expr->{-op}||[''])->[0] eq ',';
1263 return +{ -op => [ ',',
1264 map $self->expand_expr($_),
1265 ref($expr) eq 'ARRAY' ? @$expr : $expr
1269 sub _expand_op_andor {
1270 my ($self, $logop, $v, $k) = @_;
1272 $v = [ map +{ $k, $_ },
1274 ? (map +{ $_ => $v->{$_} }, sort keys %$v)
1278 if (ref($v) eq 'HASH') {
1279 return undef unless keys %$v;
1282 map $self->_expand_expr({ $_ => $v->{$_} }),
1286 if (ref($v) eq 'ARRAY') {
1287 $logop eq 'and' or $logop eq 'or' or puke "unknown logic: $logop";
1290 (ref($_) eq 'ARRAY' and @$_)
1291 or (ref($_) eq 'HASH' and %$_)
1297 while (my ($el) = splice @expr, 0, 1) {
1298 puke "Supplying an empty left hand side argument is not supported in array-pairs"
1299 unless defined($el) and length($el);
1300 my $elref = ref($el);
1302 local our $Expand_Depth = 0;
1303 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
1304 } elsif ($elref eq 'ARRAY') {
1305 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
1306 } elsif (my $l = is_literal_value($el)) {
1307 push @res, { -literal => $l };
1308 } elsif ($elref eq 'HASH') {
1309 local our $Expand_Depth = 0;
1310 push @res, grep defined, $self->_expand_expr($el) if %$el;
1316 # return $res[0] if @res == 1;
1317 return { -op => [ $logop, @res ] };
1323 my ($self, $op, $vv, $k) = @_;
1324 ($k, $vv) = @$vv unless defined $k;
1325 puke "$op can only take undef as argument"
1329 and exists($vv->{-value})
1330 and !defined($vv->{-value})
1332 return +{ -op => [ $op.'_null', $self->expand_expr($k, -ident) ] };
1335 sub _expand_between {
1336 my ($self, $op, $vv, $k) = @_;
1337 my @rhs = map $self->_expand_expr($_),
1338 ref($vv) eq 'ARRAY' ? @$vv : $vv;
1340 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
1342 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
1344 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1348 $self->expand_expr($k),
1349 map $self->expand_expr($_, -value), @rhs
1354 my ($self, $op, $vv, $k) = @_;
1355 if (my $literal = is_literal_value($vv)) {
1356 my ($sql, @bind) = @$literal;
1357 my $opened_sql = $self->_open_outer_paren($sql);
1359 $op, $self->expand_expr($k, -ident),
1360 { -literal => [ $opened_sql, @bind ] }
1364 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1365 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1366 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1367 . 'will emit the logically correct SQL instead of raising this exception)'
1369 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
1371 my @rhs = map $self->expand_expr($_, -value),
1372 map { defined($_) ? $_: puke($undef_err) }
1373 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
1374 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
1378 $self->expand_expr($k, -ident),
1384 my ($self, undef, $v) = @_;
1385 # DBIx::Class requires a nest warning to be emitted once but the private
1386 # method it overrode to do so no longer exists
1387 if ($self->{warn_once_on_nest}) {
1388 unless (our $Nest_Warned) {
1390 "-nest in search conditions is deprecated, you most probably wanted:\n"
1391 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
1396 return $self->_expand_expr($v);
1399 sub _expand_values {
1400 my ($self, undef, $values) = @_;
1401 return { -values => [
1404 ? $self->expand_expr($_)
1405 : +{ -row => [ map $self->expand_expr($_), @$_ ] }
1406 ), ref($values) eq 'ARRAY' ? @$values : $values
1410 sub _recurse_where {
1411 my ($self, $where) = @_;
1413 # Special case: top level simple string treated as literal
1415 my $where_exp = (ref($where)
1416 ? $self->_expand_select_clause_where(undef, $where)
1417 : { -literal => [ $where ] });
1419 # dispatch expanded expression
1421 my ($sql, @bind) = defined($where_exp) ? @{ $self->render_aqt($where_exp) || [] } : ();
1422 # DBIx::Class used to call _recurse_where in scalar context
1423 # something else might too...
1425 return ($sql, @bind);
1428 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
1434 my ($self, undef, $ident) = @_;
1436 return [ $self->_quote($ident) ];
1440 my ($self, undef, $values) = @_;
1441 return $self->join_query_parts('',
1443 $self->_render_op(undef, [ ',', @$values ]),
1449 my ($self, undef, $rest) = @_;
1450 my ($func, @args) = @$rest;
1451 return $self->join_query_parts('',
1452 $self->_sqlcase($func),
1453 $self->join_query_parts('',
1455 $self->join_query_parts(', ', @args),
1462 my ($self, undef, $bind) = @_;
1463 return [ '?', $self->_bindtype(@$bind) ];
1466 sub _render_literal {
1467 my ($self, undef, $literal) = @_;
1468 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1472 sub _render_keyword {
1473 my ($self, undef, $keyword) = @_;
1474 return [ $self->_sqlcase(
1475 ref($keyword) ? $$keyword : join ' ', split '_', $keyword
1480 my ($self, undef, $v) = @_;
1481 my ($op, @args) = @$v;
1482 if (my $r = $self->{render_op}{$op}) {
1483 return $self->$r($op, \@args);
1488 my $op = join(' ', split '_', $op);
1490 my $ss = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1491 if ($ss and @args > 1) {
1492 puke "Special op '${op}' requires first value to be identifier"
1493 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1494 my $k = join(($self->{name_sep}||'.'), @$ident);
1495 local our $Expand_Depth = 1;
1496 return [ $self->${\($ss->{handler})}($k, $op, $args[1]) ];
1498 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1499 return [ $self->${\($us->{handler})}($op, $args[0]) ];
1502 return $self->_render_unop_paren($op, \@args);
1506 return $self->_render_unop_prefix($op, \@args);
1508 return $self->_render_op_multop($op, \@args);
1514 sub _render_op_between {
1515 my ($self, $op, $args) = @_;
1516 my ($left, $low, $high) = @$args;
1519 puke "Single arg to between must be a literal"
1520 unless $low->{-literal};
1523 +($low, { -keyword => 'and' }, $high);
1526 return $self->join_query_parts(' ',
1527 '(', $left, { -keyword => $op }, @rh, ')',
1532 my ($self, $op, $args) = @_;
1533 my ($lhs, @rhs) = @$args;
1535 return $self->join_query_parts(' ',
1537 { -keyword => $op },
1538 $self->join_query_parts(' ',
1540 $self->join_query_parts(', ', @rhs),
1546 sub _render_op_andor {
1547 my ($self, $op, $args) = @_;
1548 return undef unless @$args;
1549 return $self->join_query_parts('', $args->[0]) if @$args == 1;
1550 my $inner = $self->_render_op_multop($op, $args);
1551 return undef unless defined($inner->[0]) and length($inner->[0]);
1552 return $self->join_query_parts(' ',
1557 sub _render_op_multop {
1558 my ($self, $op, $args) = @_;
1560 return undef unless @parts;
1561 return $self->render_aqt($parts[0]) if @parts == 1;
1562 my $join = ($op eq ','
1564 : { -keyword => " ${op} " }
1566 return $self->join_query_parts($join, @parts);
1569 sub _render_values {
1570 my ($self, undef, $values) = @_;
1571 my $inner = $self->join_query_parts(' ',
1572 { -keyword => 'values' },
1573 $self->join_query_parts(', ',
1574 ref($values) eq 'ARRAY' ? @$values : $values
1577 return $self->join_query_parts('',
1578 (our $Render_Top_Level ? $inner : ('(', $inner, ')'))
1582 sub join_query_parts {
1583 my ($self, $join, @parts) = @_;
1584 if (ref($join) eq 'HASH') {
1585 $join = $self->render_aqt($join)->[0];
1589 ? $self->render_aqt($_)
1590 : ((ref($_) eq 'ARRAY') ? $_ : [ $_ ])
1593 $self->{join_sql_parts}->(
1594 $join, grep defined && length, map $_->[0], @final
1596 (map @{$_}[1..$#$_], @final),
1600 sub _render_unop_paren {
1601 my ($self, $op, $v) = @_;
1602 return $self->join_query_parts('',
1603 '(', $self->_render_unop_prefix($op, $v), ')'
1607 sub _render_unop_prefix {
1608 my ($self, $op, $v) = @_;
1609 my $op_sql = $self->{restore_old_unop_handling}
1610 ? $self->_sqlcase($op)
1611 : { -keyword => $op };
1612 return $self->join_query_parts(' ',
1613 ($self->{restore_old_unop_handling}
1614 ? $self->_sqlcase($op)
1615 : { -keyword => \$op }),
1620 sub _render_unop_postfix {
1621 my ($self, $op, $v) = @_;
1622 return $self->join_query_parts(' ',
1623 $v->[0], { -keyword => $op },
1627 # Some databases (SQLite) treat col IN (1, 2) different from
1628 # col IN ( (1, 2) ). Use this to strip all outer parens while
1629 # adding them back in the corresponding method
1630 sub _open_outer_paren {
1631 my ($self, $sql) = @_;
1633 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1635 # there are closing parens inside, need the heavy duty machinery
1636 # to reevaluate the extraction starting from $sql (full reevaluation)
1637 if ($inner =~ /\)/) {
1638 require Text::Balanced;
1640 my (undef, $remainder) = do {
1641 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1643 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1646 # the entire expression needs to be a balanced bracketed thing
1647 # (after an extract no remainder sans trailing space)
1648 last if defined $remainder and $remainder =~ /\S/;
1658 #======================================================================
1660 #======================================================================
1662 sub _expand_order_by {
1663 my ($self, $arg) = @_;
1665 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1667 return $self->expand_expr({ -list => $arg })
1668 if ref($arg) eq 'HASH' and ($arg->{-op}||[''])->[0] eq ',';
1670 my $expander = sub {
1671 my ($self, $dir, $expr) = @_;
1672 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1673 foreach my $arg (@to_expand) {
1677 and grep /^-(asc|desc)$/, keys %$arg
1679 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1683 defined($dir) ? { -op => [ $dir =~ /^-?(.*)$/ ,=> $_ ] } : $_
1685 map $self->expand_expr($_, -ident),
1686 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
1687 return undef unless @exp;
1688 return undef if @exp == 1 and not defined($exp[0]);
1689 return +{ -op => [ ',', @exp ] };
1692 local @{$self->{expand}}{qw(asc desc)} = (($expander) x 2);
1694 return $self->$expander(undef, $arg);
1698 my ($self, $arg) = @_;
1700 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
1702 my ($sql, @bind) = @{ $self->render_aqt($expanded) };
1704 return '' unless length($sql);
1706 my $final_sql = $self->_sqlcase(' order by ').$sql;
1708 return ($final_sql, @bind);
1711 # _order_by no longer needs to call this so doesn't but DBIC uses it.
1713 sub _order_by_chunks {
1714 my ($self, $arg) = @_;
1716 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1718 my @res = $self->_chunkify_order_by($expanded);
1719 (ref() ? $_->[0] : $_) .= '' for @res;
1723 sub _chunkify_order_by {
1724 my ($self, $expanded) = @_;
1726 return grep length, @{ $self->render_aqt($expanded) }
1727 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1730 if (ref() eq 'HASH' and $_->{-op} and $_->{-op}[0] eq ',') {
1731 my ($comma, @list) = @{$_->{-op}};
1732 return map $self->_chunkify_order_by($_), @list;
1734 return $self->render_aqt($_);
1738 #======================================================================
1739 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1740 #======================================================================
1746 $self->expand_expr({ -list => $from }, -ident)
1751 #======================================================================
1753 #======================================================================
1755 # highly optimized, as it's called way too often
1757 # my ($self, $label) = @_;
1759 return '' unless defined $_[1];
1760 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1761 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1763 unless ($_[0]->{quote_char}) {
1764 if (ref($_[1]) eq 'ARRAY') {
1765 return join($_[0]->{name_sep}||'.', @{$_[1]});
1767 $_[0]->_assert_pass_injection_guard($_[1]);
1772 my $qref = ref $_[0]->{quote_char};
1774 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1775 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1776 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1778 my $esc = $_[0]->{escape_char} || $r;
1780 # parts containing * are naturally unquoted
1782 $_[0]->{name_sep}||'',
1786 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1788 (ref($_[1]) eq 'ARRAY'
1792 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1800 # Conversion, if applicable
1802 #my ($self, $arg) = @_;
1803 if (my $conv = $_[0]->{convert_where}) {
1804 return @{ $_[0]->join_query_parts('',
1805 $_[0]->_sqlcase($conv),
1814 #my ($self, $col, @vals) = @_;
1815 # called often - tighten code
1816 return $_[0]->{bindtype} eq 'columns'
1817 ? map {[$_[1], $_]} @_[2 .. $#_]
1822 # Dies if any element of @bind is not in [colname => value] format
1823 # if bindtype is 'columns'.
1824 sub _assert_bindval_matches_bindtype {
1825 # my ($self, @bind) = @_;
1827 if ($self->{bindtype} eq 'columns') {
1829 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1830 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1836 # Fix SQL case, if so requested
1838 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1839 # don't touch the argument ... crooked logic, but let's not change it!
1840 return $_[0]->{case} ? $_[1] : uc($_[1]);
1843 #======================================================================
1844 # DISPATCHING FROM REFKIND
1845 #======================================================================
1848 my ($self, $data) = @_;
1850 return 'UNDEF' unless defined $data;
1852 # blessed objects are treated like scalars
1853 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1855 return 'SCALAR' unless $ref;
1858 while ($ref eq 'REF') {
1860 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1864 return ($ref||'SCALAR') . ('REF' x $n_steps);
1868 my ($self, $data) = @_;
1869 my @try = ($self->_refkind($data));
1870 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1871 push @try, 'FALLBACK';
1875 sub _METHOD_FOR_refkind {
1876 my ($self, $meth_prefix, $data) = @_;
1879 for (@{$self->_try_refkind($data)}) {
1880 $method = $self->can($meth_prefix."_".$_)
1884 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1888 sub _SWITCH_refkind {
1889 my ($self, $data, $dispatch_table) = @_;
1892 for (@{$self->_try_refkind($data)}) {
1893 $coderef = $dispatch_table->{$_}
1897 puke "no dispatch entry for ".$self->_refkind($data)
1906 #======================================================================
1907 # VALUES, GENERATE, AUTOLOAD
1908 #======================================================================
1910 # LDNOTE: original code from nwiger, didn't touch code in that section
1911 # I feel the AUTOLOAD stuff should not be the default, it should
1912 # only be activated on explicit demand by user.
1916 my $data = shift || return;
1917 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1918 unless ref $data eq 'HASH';
1921 foreach my $k (sort keys %$data) {
1922 my $v = $data->{$k};
1923 $self->_SWITCH_refkind($v, {
1925 if ($self->{array_datatypes}) { # array datatype
1926 push @all_bind, $self->_bindtype($k, $v);
1928 else { # literal SQL with bind
1929 my ($sql, @bind) = @$v;
1930 $self->_assert_bindval_matches_bindtype(@bind);
1931 push @all_bind, @bind;
1934 ARRAYREFREF => sub { # literal SQL with bind
1935 my ($sql, @bind) = @${$v};
1936 $self->_assert_bindval_matches_bindtype(@bind);
1937 push @all_bind, @bind;
1939 SCALARREF => sub { # literal SQL without bind
1941 SCALAR_or_UNDEF => sub {
1942 push @all_bind, $self->_bindtype($k, $v);
1953 my(@sql, @sqlq, @sqlv);
1957 if ($ref eq 'HASH') {
1958 for my $k (sort keys %$_) {
1961 my $label = $self->_quote($k);
1962 if ($r eq 'ARRAY') {
1963 # literal SQL with bind
1964 my ($sql, @bind) = @$v;
1965 $self->_assert_bindval_matches_bindtype(@bind);
1966 push @sqlq, "$label = $sql";
1968 } elsif ($r eq 'SCALAR') {
1969 # literal SQL without bind
1970 push @sqlq, "$label = $$v";
1972 push @sqlq, "$label = ?";
1973 push @sqlv, $self->_bindtype($k, $v);
1976 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1977 } elsif ($ref eq 'ARRAY') {
1978 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1981 if ($r eq 'ARRAY') { # literal SQL with bind
1982 my ($sql, @bind) = @$v;
1983 $self->_assert_bindval_matches_bindtype(@bind);
1986 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1987 # embedded literal SQL
1994 push @sql, '(' . join(', ', @sqlq) . ')';
1995 } elsif ($ref eq 'SCALAR') {
1999 # strings get case twiddled
2000 push @sql, $self->_sqlcase($_);
2004 my $sql = join ' ', @sql;
2006 # this is pretty tricky
2007 # if ask for an array, return ($stmt, @bind)
2008 # otherwise, s/?/shift @sqlv/ to put it inline
2010 return ($sql, @sqlv);
2012 1 while $sql =~ s/\?/my $d = shift(@sqlv);
2013 ref $d ? $d->[1] : $d/e;
2022 # This allows us to check for a local, then _form, attr
2024 my($name) = $AUTOLOAD =~ /.*::(.+)/;
2025 puke "AUTOLOAD invoked for method name ${name} and allow_autoload option not set" unless $self->{allow_autoload};
2026 return $self->generate($name, @_);
2037 SQL::Abstract - Generate SQL from Perl data structures
2043 my $sql = SQL::Abstract->new;
2045 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
2047 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
2049 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
2051 my($stmt, @bind) = $sql->delete($table, \%where);
2053 # Then, use these in your DBI statements
2054 my $sth = $dbh->prepare($stmt);
2055 $sth->execute(@bind);
2057 # Just generate the WHERE clause
2058 my($stmt, @bind) = $sql->where(\%where, $order);
2060 # Return values in the same order, for hashed queries
2061 # See PERFORMANCE section for more details
2062 my @bind = $sql->values(\%fieldvals);
2066 This module was inspired by the excellent L<DBIx::Abstract>.
2067 However, in using that module I found that what I really wanted
2068 to do was generate SQL, but still retain complete control over my
2069 statement handles and use the DBI interface. So, I set out to
2070 create an abstract SQL generation module.
2072 While based on the concepts used by L<DBIx::Abstract>, there are
2073 several important differences, especially when it comes to WHERE
2074 clauses. I have modified the concepts used to make the SQL easier
2075 to generate from Perl data structures and, IMO, more intuitive.
2076 The underlying idea is for this module to do what you mean, based
2077 on the data structures you provide it. The big advantage is that
2078 you don't have to modify your code every time your data changes,
2079 as this module figures it out.
2081 To begin with, an SQL INSERT is as easy as just specifying a hash
2082 of C<key=value> pairs:
2085 name => 'Jimbo Bobson',
2086 phone => '123-456-7890',
2087 address => '42 Sister Lane',
2088 city => 'St. Louis',
2089 state => 'Louisiana',
2092 The SQL can then be generated with this:
2094 my($stmt, @bind) = $sql->insert('people', \%data);
2096 Which would give you something like this:
2098 $stmt = "INSERT INTO people
2099 (address, city, name, phone, state)
2100 VALUES (?, ?, ?, ?, ?)";
2101 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
2102 '123-456-7890', 'Louisiana');
2104 These are then used directly in your DBI code:
2106 my $sth = $dbh->prepare($stmt);
2107 $sth->execute(@bind);
2109 =head2 Inserting and Updating Arrays
2111 If your database has array types (like for example Postgres),
2112 activate the special option C<< array_datatypes => 1 >>
2113 when creating the C<SQL::Abstract> object.
2114 Then you may use an arrayref to insert and update database array types:
2116 my $sql = SQL::Abstract->new(array_datatypes => 1);
2118 planets => [qw/Mercury Venus Earth Mars/]
2121 my($stmt, @bind) = $sql->insert('solar_system', \%data);
2125 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
2127 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
2130 =head2 Inserting and Updating SQL
2132 In order to apply SQL functions to elements of your C<%data> you may
2133 specify a reference to an arrayref for the given hash value. For example,
2134 if you need to execute the Oracle C<to_date> function on a value, you can
2135 say something like this:
2139 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
2142 The first value in the array is the actual SQL. Any other values are
2143 optional and would be included in the bind values array. This gives
2146 my($stmt, @bind) = $sql->insert('people', \%data);
2148 $stmt = "INSERT INTO people (name, date_entered)
2149 VALUES (?, to_date(?,'MM/DD/YYYY'))";
2150 @bind = ('Bill', '03/02/2003');
2152 An UPDATE is just as easy, all you change is the name of the function:
2154 my($stmt, @bind) = $sql->update('people', \%data);
2156 Notice that your C<%data> isn't touched; the module will generate
2157 the appropriately quirky SQL for you automatically. Usually you'll
2158 want to specify a WHERE clause for your UPDATE, though, which is
2159 where handling C<%where> hashes comes in handy...
2161 =head2 Complex where statements
2163 This module can generate pretty complicated WHERE statements
2164 easily. For example, simple C<key=value> pairs are taken to mean
2165 equality, and if you want to see if a field is within a set
2166 of values, you can use an arrayref. Let's say we wanted to
2167 SELECT some data based on this criteria:
2170 requestor => 'inna',
2171 worker => ['nwiger', 'rcwe', 'sfz'],
2172 status => { '!=', 'completed' }
2175 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
2177 The above would give you something like this:
2179 $stmt = "SELECT * FROM tickets WHERE
2180 ( requestor = ? ) AND ( status != ? )
2181 AND ( worker = ? OR worker = ? OR worker = ? )";
2182 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
2184 Which you could then use in DBI code like so:
2186 my $sth = $dbh->prepare($stmt);
2187 $sth->execute(@bind);
2193 The methods are simple. There's one for every major SQL operation,
2194 and a constructor you use first. The arguments are specified in a
2195 similar order for each method (table, then fields, then a where
2196 clause) to try and simplify things.
2198 =head2 new(option => 'value')
2200 The C<new()> function takes a list of options and values, and returns
2201 a new B<SQL::Abstract> object which can then be used to generate SQL
2202 through the methods below. The options accepted are:
2208 If set to 'lower', then SQL will be generated in all lowercase. By
2209 default SQL is generated in "textbook" case meaning something like:
2211 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
2213 Any setting other than 'lower' is ignored.
2217 This determines what the default comparison operator is. By default
2218 it is C<=>, meaning that a hash like this:
2220 %where = (name => 'nwiger', email => 'nate@wiger.org');
2222 Will generate SQL like this:
2224 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
2226 However, you may want loose comparisons by default, so if you set
2227 C<cmp> to C<like> you would get SQL such as:
2229 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
2231 You can also override the comparison on an individual basis - see
2232 the huge section on L</"WHERE CLAUSES"> at the bottom.
2234 =item sqltrue, sqlfalse
2236 Expressions for inserting boolean values within SQL statements.
2237 By default these are C<1=1> and C<1=0>. They are used
2238 by the special operators C<-in> and C<-not_in> for generating
2239 correct SQL even when the argument is an empty array (see below).
2243 This determines the default logical operator for multiple WHERE
2244 statements in arrays or hashes. If absent, the default logic is "or"
2245 for arrays, and "and" for hashes. This means that a WHERE
2249 event_date => {'>=', '2/13/99'},
2250 event_date => {'<=', '4/24/03'},
2253 will generate SQL like this:
2255 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
2257 This is probably not what you want given this query, though (look
2258 at the dates). To change the "OR" to an "AND", simply specify:
2260 my $sql = SQL::Abstract->new(logic => 'and');
2262 Which will change the above C<WHERE> to:
2264 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
2266 The logic can also be changed locally by inserting
2267 a modifier in front of an arrayref:
2269 @where = (-and => [event_date => {'>=', '2/13/99'},
2270 event_date => {'<=', '4/24/03'} ]);
2272 See the L</"WHERE CLAUSES"> section for explanations.
2276 This will automatically convert comparisons using the specified SQL
2277 function for both column and value. This is mostly used with an argument
2278 of C<upper> or C<lower>, so that the SQL will have the effect of
2279 case-insensitive "searches". For example, this:
2281 $sql = SQL::Abstract->new(convert => 'upper');
2282 %where = (keywords => 'MaKe iT CAse inSeNSItive');
2284 Will turn out the following SQL:
2286 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
2288 The conversion can be C<upper()>, C<lower()>, or any other SQL function
2289 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
2290 not validate this option; it will just pass through what you specify verbatim).
2294 This is a kludge because many databases suck. For example, you can't
2295 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
2296 Instead, you have to use C<bind_param()>:
2298 $sth->bind_param(1, 'reg data');
2299 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
2301 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
2302 which loses track of which field each slot refers to. Fear not.
2304 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
2305 Currently, you can specify either C<normal> (default) or C<columns>. If you
2306 specify C<columns>, you will get an array that looks like this:
2308 my $sql = SQL::Abstract->new(bindtype => 'columns');
2309 my($stmt, @bind) = $sql->insert(...);
2312 [ 'column1', 'value1' ],
2313 [ 'column2', 'value2' ],
2314 [ 'column3', 'value3' ],
2317 You can then iterate through this manually, using DBI's C<bind_param()>.
2319 $sth->prepare($stmt);
2322 my($col, $data) = @$_;
2323 if ($col eq 'details' || $col eq 'comments') {
2324 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
2325 } elsif ($col eq 'image') {
2326 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
2328 $sth->bind_param($i, $data);
2332 $sth->execute; # execute without @bind now
2334 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
2335 Basically, the advantage is still that you don't have to care which fields
2336 are or are not included. You could wrap that above C<for> loop in a simple
2337 sub called C<bind_fields()> or something and reuse it repeatedly. You still
2338 get a layer of abstraction over manual SQL specification.
2340 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
2341 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
2342 will expect the bind values in this format.
2346 This is the character that a table or column name will be quoted
2347 with. By default this is an empty string, but you could set it to
2348 the character C<`>, to generate SQL like this:
2350 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
2352 Alternatively, you can supply an array ref of two items, the first being the left
2353 hand quote character, and the second the right hand quote character. For
2354 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
2355 that generates SQL like this:
2357 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
2359 Quoting is useful if you have tables or columns names that are reserved
2360 words in your database's SQL dialect.
2364 This is the character that will be used to escape L</quote_char>s appearing
2365 in an identifier before it has been quoted.
2367 The parameter default in case of a single L</quote_char> character is the quote
2370 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
2371 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
2372 of the B<opening (left)> L</quote_char> within the identifier are currently left
2373 untouched. The default for opening-closing-style quotes may change in future
2374 versions, thus you are B<strongly encouraged> to specify the escape character
2379 This is the character that separates a table and column name. It is
2380 necessary to specify this when the C<quote_char> option is selected,
2381 so that tables and column names can be individually quoted like this:
2383 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2385 =item injection_guard
2387 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2388 column name specified in a query structure. This is a safety mechanism to avoid
2389 injection attacks when mishandling user input e.g.:
2391 my %condition_as_column_value_pairs = get_values_from_user();
2392 $sqla->select( ... , \%condition_as_column_value_pairs );
2394 If the expression matches an exception is thrown. Note that literal SQL
2395 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2397 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2399 =item array_datatypes
2401 When this option is true, arrayrefs in INSERT or UPDATE are
2402 interpreted as array datatypes and are passed directly
2404 When this option is false, arrayrefs are interpreted
2405 as literal SQL, just like refs to arrayrefs
2406 (but this behavior is for backwards compatibility; when writing
2407 new queries, use the "reference to arrayref" syntax
2413 Takes a reference to a list of "special operators"
2414 to extend the syntax understood by L<SQL::Abstract>.
2415 See section L</"SPECIAL OPERATORS"> for details.
2419 Takes a reference to a list of "unary operators"
2420 to extend the syntax understood by L<SQL::Abstract>.
2421 See section L</"UNARY OPERATORS"> for details.
2427 =head2 insert($table, \@values || \%fieldvals, \%options)
2429 This is the simplest function. You simply give it a table name
2430 and either an arrayref of values or hashref of field/value pairs.
2431 It returns an SQL INSERT statement and a list of bind values.
2432 See the sections on L</"Inserting and Updating Arrays"> and
2433 L</"Inserting and Updating SQL"> for information on how to insert
2434 with those data types.
2436 The optional C<\%options> hash reference may contain additional
2437 options to generate the insert SQL. Currently supported options
2444 Takes either a scalar of raw SQL fields, or an array reference of
2445 field names, and adds on an SQL C<RETURNING> statement at the end.
2446 This allows you to return data generated by the insert statement
2447 (such as row IDs) without performing another C<SELECT> statement.
2448 Note, however, this is not part of the SQL standard and may not
2449 be supported by all database engines.
2453 =head2 update($table, \%fieldvals, \%where, \%options)
2455 This takes a table, hashref of field/value pairs, and an optional
2456 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2458 See the sections on L</"Inserting and Updating Arrays"> and
2459 L</"Inserting and Updating SQL"> for information on how to insert
2460 with those data types.
2462 The optional C<\%options> hash reference may contain additional
2463 options to generate the update SQL. Currently supported options
2470 See the C<returning> option to
2471 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2475 =head2 select($source, $fields, $where, $order)
2477 This returns a SQL SELECT statement and associated list of bind values, as
2478 specified by the arguments:
2484 Specification of the 'FROM' part of the statement.
2485 The argument can be either a plain scalar (interpreted as a table
2486 name, will be quoted), or an arrayref (interpreted as a list
2487 of table names, joined by commas, quoted), or a scalarref
2488 (literal SQL, not quoted).
2492 Specification of the list of fields to retrieve from
2494 The argument can be either an arrayref (interpreted as a list
2495 of field names, will be joined by commas and quoted), or a
2496 plain scalar (literal SQL, not quoted).
2497 Please observe that this API is not as flexible as that of
2498 the first argument C<$source>, for backwards compatibility reasons.
2502 Optional argument to specify the WHERE part of the query.
2503 The argument is most often a hashref, but can also be
2504 an arrayref or plain scalar --
2505 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2509 Optional argument to specify the ORDER BY part of the query.
2510 The argument can be a scalar, a hashref or an arrayref
2511 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2517 =head2 delete($table, \%where, \%options)
2519 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2520 It returns an SQL DELETE statement and list of bind values.
2522 The optional C<\%options> hash reference may contain additional
2523 options to generate the delete SQL. Currently supported options
2530 See the C<returning> option to
2531 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2535 =head2 where(\%where, $order)
2537 This is used to generate just the WHERE clause. For example,
2538 if you have an arbitrary data structure and know what the
2539 rest of your SQL is going to look like, but want an easy way
2540 to produce a WHERE clause, use this. It returns an SQL WHERE
2541 clause and list of bind values.
2544 =head2 values(\%data)
2546 This just returns the values from the hash C<%data>, in the same
2547 order that would be returned from any of the other above queries.
2548 Using this allows you to markedly speed up your queries if you
2549 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2551 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2553 Warning: This is an experimental method and subject to change.
2555 This returns arbitrarily generated SQL. It's a really basic shortcut.
2556 It will return two different things, depending on return context:
2558 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2559 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2561 These would return the following:
2563 # First calling form
2564 $stmt = "CREATE TABLE test (?, ?)";
2565 @bind = (field1, field2);
2567 # Second calling form
2568 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2570 Depending on what you're trying to do, it's up to you to choose the correct
2571 format. In this example, the second form is what you would want.
2575 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2579 ALTER SESSION SET nls_date_format = 'MM/YY'
2581 You get the idea. Strings get their case twiddled, but everything
2582 else remains verbatim.
2584 =head1 EXPORTABLE FUNCTIONS
2586 =head2 is_plain_value
2588 Determines if the supplied argument is a plain value as understood by this
2593 =item * The value is C<undef>
2595 =item * The value is a non-reference
2597 =item * The value is an object with stringification overloading
2599 =item * The value is of the form C<< { -value => $anything } >>
2603 On failure returns C<undef>, on success returns a B<scalar> reference
2604 to the original supplied argument.
2610 The stringification overloading detection is rather advanced: it takes
2611 into consideration not only the presence of a C<""> overload, but if that
2612 fails also checks for enabled
2613 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2614 on either C<0+> or C<bool>.
2616 Unfortunately testing in the field indicates that this
2617 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2618 but only when very large numbers of stringifying objects are involved.
2619 At the time of writing ( Sep 2014 ) there is no clear explanation of
2620 the direct cause, nor is there a manageably small test case that reliably
2621 reproduces the problem.
2623 If you encounter any of the following exceptions in B<random places within
2624 your application stack> - this module may be to blame:
2626 Operation "ne": no method found,
2627 left argument in overloaded package <something>,
2628 right argument in overloaded package <something>
2632 Stub found while resolving method "???" overloading """" in package <something>
2634 If you fall victim to the above - please attempt to reduce the problem
2635 to something that could be sent to the L<SQL::Abstract developers
2636 |DBIx::Class/GETTING HELP/SUPPORT>
2637 (either publicly or privately). As a workaround in the meantime you can
2638 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2639 value, which will most likely eliminate your problem (at the expense of
2640 not being able to properly detect exotic forms of stringification).
2642 This notice and environment variable will be removed in a future version,
2643 as soon as the underlying problem is found and a reliable workaround is
2648 =head2 is_literal_value
2650 Determines if the supplied argument is a literal value as understood by this
2655 =item * C<\$sql_string>
2657 =item * C<\[ $sql_string, @bind_values ]>
2661 On failure returns C<undef>, on success returns an B<array> reference
2662 containing the unpacked version of the supplied literal SQL and bind values.
2664 =head2 is_undef_value
2666 Tests for undef, whether expanded or not.
2668 =head1 WHERE CLAUSES
2672 This module uses a variation on the idea from L<DBIx::Abstract>. It
2673 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2674 module is that things in arrays are OR'ed, and things in hashes
2677 The easiest way to explain is to show lots of examples. After
2678 each C<%where> hash shown, it is assumed you used:
2680 my($stmt, @bind) = $sql->where(\%where);
2682 However, note that the C<%where> hash can be used directly in any
2683 of the other functions as well, as described above.
2685 =head2 Key-value pairs
2687 So, let's get started. To begin, a simple hash:
2691 status => 'completed'
2694 Is converted to SQL C<key = val> statements:
2696 $stmt = "WHERE user = ? AND status = ?";
2697 @bind = ('nwiger', 'completed');
2699 One common thing I end up doing is having a list of values that
2700 a field can be in. To do this, simply specify a list inside of
2705 status => ['assigned', 'in-progress', 'pending'];
2708 This simple code will create the following:
2710 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2711 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2713 A field associated to an empty arrayref will be considered a
2714 logical false and will generate 0=1.
2716 =head2 Tests for NULL values
2718 If the value part is C<undef> then this is converted to SQL <IS NULL>
2727 $stmt = "WHERE user = ? AND status IS NULL";
2730 To test if a column IS NOT NULL:
2734 status => { '!=', undef },
2737 =head2 Specific comparison operators
2739 If you want to specify a different type of operator for your comparison,
2740 you can use a hashref for a given column:
2744 status => { '!=', 'completed' }
2747 Which would generate:
2749 $stmt = "WHERE user = ? AND status != ?";
2750 @bind = ('nwiger', 'completed');
2752 To test against multiple values, just enclose the values in an arrayref:
2754 status => { '=', ['assigned', 'in-progress', 'pending'] };
2756 Which would give you:
2758 "WHERE status = ? OR status = ? OR status = ?"
2761 The hashref can also contain multiple pairs, in which case it is expanded
2762 into an C<AND> of its elements:
2766 status => { '!=', 'completed', -not_like => 'pending%' }
2769 # Or more dynamically, like from a form
2770 $where{user} = 'nwiger';
2771 $where{status}{'!='} = 'completed';
2772 $where{status}{'-not_like'} = 'pending%';
2774 # Both generate this
2775 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2776 @bind = ('nwiger', 'completed', 'pending%');
2779 To get an OR instead, you can combine it with the arrayref idea:
2783 priority => [ { '=', 2 }, { '>', 5 } ]
2786 Which would generate:
2788 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2789 @bind = ('2', '5', 'nwiger');
2791 If you want to include literal SQL (with or without bind values), just use a
2792 scalar reference or reference to an arrayref as the value:
2795 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2796 date_expires => { '<' => \"now()" }
2799 Which would generate:
2801 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2802 @bind = ('11/26/2008');
2805 =head2 Logic and nesting operators
2807 In the example above,
2808 there is a subtle trap if you want to say something like
2809 this (notice the C<AND>):
2811 WHERE priority != ? AND priority != ?
2813 Because, in Perl you I<can't> do this:
2815 priority => { '!=' => 2, '!=' => 1 }
2817 As the second C<!=> key will obliterate the first. The solution
2818 is to use the special C<-modifier> form inside an arrayref:
2820 priority => [ -and => {'!=', 2},
2824 Normally, these would be joined by C<OR>, but the modifier tells it
2825 to use C<AND> instead. (Hint: You can use this in conjunction with the
2826 C<logic> option to C<new()> in order to change the way your queries
2827 work by default.) B<Important:> Note that the C<-modifier> goes
2828 B<INSIDE> the arrayref, as an extra first element. This will
2829 B<NOT> do what you think it might:
2831 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2833 Here is a quick list of equivalencies, since there is some overlap:
2836 status => {'!=', 'completed', 'not like', 'pending%' }
2837 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2840 status => {'=', ['assigned', 'in-progress']}
2841 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2842 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2846 =head2 Special operators: IN, BETWEEN, etc.
2848 You can also use the hashref format to compare a list of fields using the
2849 C<IN> comparison operator, by specifying the list as an arrayref:
2852 status => 'completed',
2853 reportid => { -in => [567, 2335, 2] }
2856 Which would generate:
2858 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2859 @bind = ('completed', '567', '2335', '2');
2861 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2864 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2865 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2866 'sqltrue' (by default: C<1=1>).
2868 In addition to the array you can supply a chunk of literal sql or
2869 literal sql with bind:
2872 customer => { -in => \[
2873 'SELECT cust_id FROM cust WHERE balance > ?',
2876 status => { -in => \'SELECT status_codes FROM states' },
2882 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2883 AND status IN ( SELECT status_codes FROM states )
2887 Finally, if the argument to C<-in> is not a reference, it will be
2888 treated as a single-element array.
2890 Another pair of operators is C<-between> and C<-not_between>,
2891 used with an arrayref of two values:
2895 completion_date => {
2896 -not_between => ['2002-10-01', '2003-02-06']
2902 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2904 Just like with C<-in> all plausible combinations of literal SQL
2908 start0 => { -between => [ 1, 2 ] },
2909 start1 => { -between => \["? AND ?", 1, 2] },
2910 start2 => { -between => \"lower(x) AND upper(y)" },
2911 start3 => { -between => [
2913 \["upper(?)", 'stuff' ],
2920 ( start0 BETWEEN ? AND ? )
2921 AND ( start1 BETWEEN ? AND ? )
2922 AND ( start2 BETWEEN lower(x) AND upper(y) )
2923 AND ( start3 BETWEEN lower(x) AND upper(?) )
2925 @bind = (1, 2, 1, 2, 'stuff');
2928 These are the two builtin "special operators"; but the
2929 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
2931 =head2 Unary operators: bool
2933 If you wish to test against boolean columns or functions within your
2934 database you can use the C<-bool> and C<-not_bool> operators. For
2935 example to test the column C<is_user> being true and the column
2936 C<is_enabled> being false you would use:-
2940 -not_bool => 'is_enabled',
2945 WHERE is_user AND NOT is_enabled
2947 If a more complex combination is required, testing more conditions,
2948 then you should use the and/or operators:-
2953 -not_bool => { two=> { -rlike => 'bar' } },
2954 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
2965 (NOT ( three = ? OR three > ? ))
2968 =head2 Nested conditions, -and/-or prefixes
2970 So far, we've seen how multiple conditions are joined with a top-level
2971 C<AND>. We can change this by putting the different conditions we want in
2972 hashes and then putting those hashes in an array. For example:
2977 status => { -like => ['pending%', 'dispatched'] },
2981 status => 'unassigned',
2985 This data structure would create the following:
2987 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2988 OR ( user = ? AND status = ? ) )";
2989 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2992 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2993 to change the logic inside:
2999 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
3000 -or => { workhrs => {'<', 50}, geo => 'EURO' },
3007 $stmt = "WHERE ( user = ?
3008 AND ( ( workhrs > ? AND geo = ? )
3009 OR ( workhrs < ? OR geo = ? ) ) )";
3010 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
3012 =head3 Algebraic inconsistency, for historical reasons
3014 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
3015 operator goes C<outside> of the nested structure; whereas when connecting
3016 several constraints on one column, the C<-and> operator goes
3017 C<inside> the arrayref. Here is an example combining both features:
3020 -and => [a => 1, b => 2],
3021 -or => [c => 3, d => 4],
3022 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
3027 WHERE ( ( ( a = ? AND b = ? )
3028 OR ( c = ? OR d = ? )
3029 OR ( e LIKE ? AND e LIKE ? ) ) )
3031 This difference in syntax is unfortunate but must be preserved for
3032 historical reasons. So be careful: the two examples below would
3033 seem algebraically equivalent, but they are not
3036 { -like => 'foo%' },
3037 { -like => '%bar' },
3039 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
3042 { col => { -like => 'foo%' } },
3043 { col => { -like => '%bar' } },
3045 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
3048 =head2 Literal SQL and value type operators
3050 The basic premise of SQL::Abstract is that in WHERE specifications the "left
3051 side" is a column name and the "right side" is a value (normally rendered as
3052 a placeholder). This holds true for both hashrefs and arrayref pairs as you
3053 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
3054 alter this behavior. There are several ways of doing so.
3058 This is a virtual operator that signals the string to its right side is an
3059 identifier (a column name) and not a value. For example to compare two
3060 columns you would write:
3063 priority => { '<', 2 },
3064 requestor => { -ident => 'submitter' },
3069 $stmt = "WHERE priority < ? AND requestor = submitter";
3072 If you are maintaining legacy code you may see a different construct as
3073 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
3078 This is a virtual operator that signals that the construct to its right side
3079 is a value to be passed to DBI. This is for example necessary when you want
3080 to write a where clause against an array (for RDBMS that support such
3081 datatypes). For example:
3084 array => { -value => [1, 2, 3] }
3089 $stmt = 'WHERE array = ?';
3090 @bind = ([1, 2, 3]);
3092 Note that if you were to simply say:
3098 the result would probably not be what you wanted:
3100 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
3105 Finally, sometimes only literal SQL will do. To include a random snippet
3106 of SQL verbatim, you specify it as a scalar reference. Consider this only
3107 as a last resort. Usually there is a better way. For example:
3110 priority => { '<', 2 },
3111 requestor => { -in => \'(SELECT name FROM hitmen)' },
3116 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
3119 Note that in this example, you only get one bind parameter back, since
3120 the verbatim SQL is passed as part of the statement.
3124 Never use untrusted input as a literal SQL argument - this is a massive
3125 security risk (there is no way to check literal snippets for SQL
3126 injections and other nastyness). If you need to deal with untrusted input
3127 use literal SQL with placeholders as described next.
3129 =head3 Literal SQL with placeholders and bind values (subqueries)
3131 If the literal SQL to be inserted has placeholders and bind values,
3132 use a reference to an arrayref (yes this is a double reference --
3133 not so common, but perfectly legal Perl). For example, to find a date
3134 in Postgres you can use something like this:
3137 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
3142 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
3145 Note that you must pass the bind values in the same format as they are returned
3146 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
3147 to C<columns>, you must provide the bind values in the
3148 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
3149 scalar value; most commonly the column name, but you can use any scalar value
3150 (including references and blessed references), L<SQL::Abstract> will simply
3151 pass it through intact. So if C<bindtype> is set to C<columns> the above
3152 example will look like:
3155 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
3158 Literal SQL is especially useful for nesting parenthesized clauses in the
3159 main SQL query. Here is a first example:
3161 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
3165 bar => \["IN ($sub_stmt)" => @sub_bind],
3170 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
3171 WHERE c2 < ? AND c3 LIKE ?))";
3172 @bind = (1234, 100, "foo%");
3174 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
3175 are expressed in the same way. Of course the C<$sub_stmt> and
3176 its associated bind values can be generated through a former call
3179 my ($sub_stmt, @sub_bind)
3180 = $sql->select("t1", "c1", {c2 => {"<" => 100},
3181 c3 => {-like => "foo%"}});
3184 bar => \["> ALL ($sub_stmt)" => @sub_bind],
3187 In the examples above, the subquery was used as an operator on a column;
3188 but the same principle also applies for a clause within the main C<%where>
3189 hash, like an EXISTS subquery:
3191 my ($sub_stmt, @sub_bind)
3192 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
3193 my %where = ( -and => [
3195 \["EXISTS ($sub_stmt)" => @sub_bind],
3200 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
3201 WHERE c1 = ? AND c2 > t0.c0))";
3205 Observe that the condition on C<c2> in the subquery refers to
3206 column C<t0.c0> of the main query: this is I<not> a bind
3207 value, so we have to express it through a scalar ref.
3208 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
3209 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
3210 what we wanted here.
3212 Finally, here is an example where a subquery is used
3213 for expressing unary negation:
3215 my ($sub_stmt, @sub_bind)
3216 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
3217 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
3219 lname => {like => '%son%'},
3220 \["NOT ($sub_stmt)" => @sub_bind],
3225 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
3226 @bind = ('%son%', 10, 20)
3228 =head3 Deprecated usage of Literal SQL
3230 Below are some examples of archaic use of literal SQL. It is shown only as
3231 reference for those who deal with legacy code. Each example has a much
3232 better, cleaner and safer alternative that users should opt for in new code.
3238 my %where = ( requestor => \'IS NOT NULL' )
3240 $stmt = "WHERE requestor IS NOT NULL"
3242 This used to be the way of generating NULL comparisons, before the handling
3243 of C<undef> got formalized. For new code please use the superior syntax as
3244 described in L</Tests for NULL values>.
3248 my %where = ( requestor => \'= submitter' )
3250 $stmt = "WHERE requestor = submitter"
3252 This used to be the only way to compare columns. Use the superior L</-ident>
3253 method for all new code. For example an identifier declared in such a way
3254 will be properly quoted if L</quote_char> is properly set, while the legacy
3255 form will remain as supplied.
3259 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
3261 $stmt = "WHERE completed > ? AND is_ready"
3262 @bind = ('2012-12-21')
3264 Using an empty string literal used to be the only way to express a boolean.
3265 For all new code please use the much more readable
3266 L<-bool|/Unary operators: bool> operator.
3272 These pages could go on for a while, since the nesting of the data
3273 structures this module can handle are pretty much unlimited (the
3274 module implements the C<WHERE> expansion as a recursive function
3275 internally). Your best bet is to "play around" with the module a
3276 little to see how the data structures behave, and choose the best
3277 format for your data based on that.
3279 And of course, all the values above will probably be replaced with
3280 variables gotten from forms or the command line. After all, if you
3281 knew everything ahead of time, you wouldn't have to worry about
3282 dynamically-generating SQL and could just hardwire it into your
3285 =head1 ORDER BY CLAUSES
3287 Some functions take an order by clause. This can either be a scalar (just a
3288 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
3289 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
3292 Given | Will Generate
3293 ---------------------------------------------------------------
3295 'colA' | ORDER BY colA
3297 [qw/colA colB/] | ORDER BY colA, colB
3299 {-asc => 'colA'} | ORDER BY colA ASC
3301 {-desc => 'colB'} | ORDER BY colB DESC
3303 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
3305 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
3307 \'colA DESC' | ORDER BY colA DESC
3309 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
3310 | /* ...with $x bound to ? */
3313 { -asc => 'colA' }, | colA ASC,
3314 { -desc => [qw/colB/] }, | colB DESC,
3315 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
3316 \'colE DESC', | colE DESC,
3317 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
3318 ] | /* ...with $x bound to ? */
3319 ===============================================================
3323 =head1 OLD EXTENSION SYSTEM
3325 =head2 SPECIAL OPERATORS
3327 my $sqlmaker = SQL::Abstract->new(special_ops => [
3331 my ($self, $field, $op, $arg) = @_;
3337 handler => 'method_name',
3341 A "special operator" is a SQL syntactic clause that can be
3342 applied to a field, instead of a usual binary operator.
3345 WHERE field IN (?, ?, ?)
3346 WHERE field BETWEEN ? AND ?
3347 WHERE MATCH(field) AGAINST (?, ?)
3349 Special operators IN and BETWEEN are fairly standard and therefore
3350 are builtin within C<SQL::Abstract> (as the overridable methods
3351 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
3352 like the MATCH .. AGAINST example above which is specific to MySQL,
3353 you can write your own operator handlers - supply a C<special_ops>
3354 argument to the C<new> method. That argument takes an arrayref of
3355 operator definitions; each operator definition is a hashref with two
3362 the regular expression to match the operator
3366 Either a coderef or a plain scalar method name. In both cases
3367 the expected return is C<< ($sql, @bind) >>.
3369 When supplied with a method name, it is simply called on the
3370 L<SQL::Abstract> object as:
3372 $self->$method_name($field, $op, $arg)
3376 $field is the LHS of the operator
3377 $op is the part that matched the handler regex
3380 When supplied with a coderef, it is called as:
3382 $coderef->($self, $field, $op, $arg)
3387 For example, here is an implementation
3388 of the MATCH .. AGAINST syntax for MySQL
3390 my $sqlmaker = SQL::Abstract->new(special_ops => [
3392 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3393 {regex => qr/^match$/i,
3395 my ($self, $field, $op, $arg) = @_;
3396 $arg = [$arg] if not ref $arg;
3397 my $label = $self->_quote($field);
3398 my ($placeholder) = $self->_convert('?');
3399 my $placeholders = join ", ", (($placeholder) x @$arg);
3400 my $sql = $self->_sqlcase('match') . " ($label) "
3401 . $self->_sqlcase('against') . " ($placeholders) ";
3402 my @bind = $self->_bindtype($field, @$arg);
3403 return ($sql, @bind);
3410 =head2 UNARY OPERATORS
3412 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3416 my ($self, $op, $arg) = @_;
3422 handler => 'method_name',
3426 A "unary operator" is a SQL syntactic clause that can be
3427 applied to a field - the operator goes before the field
3429 You can write your own operator handlers - supply a C<unary_ops>
3430 argument to the C<new> method. That argument takes an arrayref of
3431 operator definitions; each operator definition is a hashref with two
3438 the regular expression to match the operator
3442 Either a coderef or a plain scalar method name. In both cases
3443 the expected return is C<< $sql >>.
3445 When supplied with a method name, it is simply called on the
3446 L<SQL::Abstract> object as:
3448 $self->$method_name($op, $arg)
3452 $op is the part that matched the handler regex
3453 $arg is the RHS or argument of the operator
3455 When supplied with a coderef, it is called as:
3457 $coderef->($self, $op, $arg)
3462 =head1 NEW METHODS (EXPERIMENTAL)
3464 See L<SQL::Abstract::Reference> for the C<expr> versus C<aqt> concept and
3465 an explanation of what the below extensions are extending.
3469 $sqla->plugin('+Foo');
3471 Enables plugin SQL::Abstract::Plugin::Foo.
3475 my ($sql, @bind) = $sqla->render_expr($expr);
3477 =head2 render_statement
3479 Use this if you may be rendering a top level statement so e.g. a SELECT
3480 query doesn't get wrapped in parens
3482 my ($sql, @bind) = $sqla->render_statement($expr);
3486 Expression expansion with optional default for scalars.
3488 my $aqt = $self->expand_expr($expr);
3489 my $aqt = $self->expand_expr($expr, -ident);
3493 Top level means avoid parens on statement AQT.
3495 my $res = $self->render_aqt($aqt, $top_level);
3496 my ($sql, @bind) = @$res;
3498 =head2 join_query_parts
3500 Similar to join() but will render hashrefs as nodes for both join and parts,
3501 and treats arrayref as a nested C<[ $join, @parts ]> structure.
3503 my $part = $self->join_query_parts($join, @parts);
3505 =head1 NEW EXTENSION SYSTEM
3509 my $sqla2 = $sqla->clone;
3511 Performs a semi-shallow copy such that extension methods won't leak state
3512 but excessive depth is avoided.
3522 =head2 clause_expander
3524 =head2 clause_expanders
3526 $sqla->expander('name' => sub { ... });
3527 $sqla->expanders('name1' => sub { ... }, 'name2' => sub { ... });
3529 =head2 expander_list
3531 =head2 op_expander_list
3533 =head2 clause_expander_list
3535 my @names = $sqla->expander_list;
3537 =head2 wrap_expander
3539 =head2 wrap_expanders
3541 =head2 wrap_op_expander
3543 =head2 wrap_op_expanders
3545 =head2 wrap_clause_expander
3547 =head2 wrap_clause_expanders
3549 $sqla->wrap_expander('name' => sub { my ($orig) = @_; sub { ... } });
3550 $sqla->wrap_expanders(
3551 'name1' => sub { my ($orig1) = @_; sub { ... } },
3552 'name2' => sub { my ($orig2) = @_; sub { ... } },
3563 =head2 clause_renderer
3565 =head2 clause_renderers
3567 $sqla->renderer('name' => sub { ... });
3568 $sqla->renderers('name1' => sub { ... }, 'name2' => sub { ... });
3570 =head2 renderer_list
3572 =head2 op_renderer_list
3574 =head2 clause_renderer_list
3576 my @names = $sqla->renderer_list;
3578 =head2 wrap_renderer
3580 =head2 wrap_renderers
3582 =head2 wrap_op_renderer
3584 =head2 wrap_op_renderers
3586 =head2 wrap_clause_renderer
3588 =head2 wrap_clause_renderers
3590 $sqla->wrap_renderer('name' => sub { my ($orig) = @_; sub { ... } });
3591 $sqla->wrap_renderers(
3592 'name1' => sub { my ($orig1) = @_; sub { ... } },
3593 'name2' => sub { my ($orig2) = @_; sub { ... } },
3598 my @clauses = $sqla->clauses_of('select');
3599 $sqla->clauses_of(select => \@new_clauses);
3600 $sqla->clauses_of(select => sub {
3601 my (undef, @old_clauses) = @_;
3603 return @new_clauses;
3606 =head2 statement_list
3608 my @list = $sqla->statement_list;
3610 =head2 make_unop_expander
3612 my $exp = $sqla->make_unop_expander(sub { ... });
3614 If the op is found as a binop, assumes it wants a default comparison, so
3615 the inner expander sub can reliably operate as
3617 sub { my ($self, $name, $body) = @_; ... }
3619 =head2 make_binop_expander
3621 my $exp = $sqla->make_binop_expander(sub { ... });
3623 If the op is found as a unop, assumes the value will be an arrayref with the
3624 LHS as the first entry, and converts that to an ident node if it's a simple
3625 scalar. So the inner expander sub looks like
3628 my ($self, $name, $body, $k) = @_;
3629 { -blah => [ map $self->expand_expr($_), $k, $body ] }
3632 =head2 unop_expander
3634 =head2 unop_expanders
3636 =head2 binop_expander
3638 =head2 binop_expanders
3640 The above methods operate exactly like the op_ versions but wrap the coderef
3641 using the appropriate make_ method first.
3645 Thanks to some benchmarking by Mark Stosberg, it turns out that
3646 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3647 I must admit this wasn't an intentional design issue, but it's a
3648 byproduct of the fact that you get to control your C<DBI> handles
3651 To maximize performance, use a code snippet like the following:
3653 # prepare a statement handle using the first row
3654 # and then reuse it for the rest of the rows
3656 for my $href (@array_of_hashrefs) {
3657 $stmt ||= $sql->insert('table', $href);
3658 $sth ||= $dbh->prepare($stmt);
3659 $sth->execute($sql->values($href));
3662 The reason this works is because the keys in your C<$href> are sorted
3663 internally by B<SQL::Abstract>. Thus, as long as your data retains
3664 the same structure, you only have to generate the SQL the first time
3665 around. On subsequent queries, simply use the C<values> function provided
3666 by this module to return your values in the correct order.
3668 However this depends on the values having the same type - if, for
3669 example, the values of a where clause may either have values
3670 (resulting in sql of the form C<column = ?> with a single bind
3671 value), or alternatively the values might be C<undef> (resulting in
3672 sql of the form C<column IS NULL> with no bind value) then the
3673 caching technique suggested will not work.
3677 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3678 really like this part (I do, at least). Building up a complex query
3679 can be as simple as the following:
3686 use CGI::FormBuilder;
3689 my $form = CGI::FormBuilder->new(...);
3690 my $sql = SQL::Abstract->new;
3692 if ($form->submitted) {
3693 my $field = $form->field;
3694 my $id = delete $field->{id};
3695 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3698 Of course, you would still have to connect using C<DBI> to run the
3699 query, but the point is that if you make your form look like your
3700 table, the actual query script can be extremely simplistic.
3702 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3703 a fast interface to returning and formatting data. I frequently
3704 use these three modules together to write complex database query
3705 apps in under 50 lines.
3707 =head1 HOW TO CONTRIBUTE
3709 Contributions are always welcome, in all usable forms (we especially
3710 welcome documentation improvements). The delivery methods include git-
3711 or unified-diff formatted patches, GitHub pull requests, or plain bug
3712 reports either via RT or the Mailing list. Contributors are generally
3713 granted full access to the official repository after their first several
3714 patches pass successful review.
3716 This project is maintained in a git repository. The code and related tools are
3717 accessible at the following locations:
3721 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3723 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3725 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3727 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3733 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3734 Great care has been taken to preserve the I<published> behavior
3735 documented in previous versions in the 1.* family; however,
3736 some features that were previously undocumented, or behaved
3737 differently from the documentation, had to be changed in order
3738 to clarify the semantics. Hence, client code that was relying
3739 on some dark areas of C<SQL::Abstract> v1.*
3740 B<might behave differently> in v1.50.
3742 The main changes are:
3748 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3752 support for the { operator => \"..." } construct (to embed literal SQL)
3756 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3760 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3764 defensive programming: check arguments
3768 fixed bug with global logic, which was previously implemented
3769 through global variables yielding side-effects. Prior versions would
3770 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3771 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3772 Now this is interpreted
3773 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3778 fixed semantics of _bindtype on array args
3782 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3783 we just avoid shifting arrays within that tree.
3787 dropped the C<_modlogic> function
3791 =head1 ACKNOWLEDGEMENTS
3793 There are a number of individuals that have really helped out with
3794 this module. Unfortunately, most of them submitted bugs via CPAN
3795 so I have no idea who they are! But the people I do know are:
3797 Ash Berlin (order_by hash term support)
3798 Matt Trout (DBIx::Class support)
3799 Mark Stosberg (benchmarking)
3800 Chas Owens (initial "IN" operator support)
3801 Philip Collins (per-field SQL functions)
3802 Eric Kolve (hashref "AND" support)
3803 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3804 Dan Kubb (support for "quote_char" and "name_sep")
3805 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3806 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3807 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3808 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3809 Oliver Charles (support for "RETURNING" after "INSERT")
3815 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3819 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3821 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3823 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3824 While not an official support venue, C<DBIx::Class> makes heavy use of
3825 C<SQL::Abstract>, and as such list members there are very familiar with
3826 how to create queries.
3830 This module is free software; you may copy this under the same
3831 terms as perl itself (either the GNU General Public License or
3832 the Artistic License)