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 (__PACKAGE__->can('_select_fields') ne $class->can('_select_fields')) {
283 $opt{expand_clause}{'select.select'} = sub { $_[2] };
284 $opt{render_clause}{'select.select'} = sub {
285 my @super = $_[0]->_select_fields($_[2]);
287 ref($super[0]) eq 'HASH'
288 ? $_[0]->render_expr($super[0])
291 return $_[0]->join_query_parts(
292 ' ', { -keyword => 'select' }, $effort
296 if ($class->isa('DBIx::Class::SQLMaker')) {
297 $opt{warn_once_on_nest} = 1;
298 $opt{disable_old_special_ops} = 1;
299 $opt{render_clause}{'select.where'} = sub {
300 my ($sql, @bind) = $_[0]->where($_[2]);
301 s/\A\s+//, s/\s+\Z// for $sql;
302 return [ $sql, @bind ];
304 $opt{expand_op}{ident} = sub {
305 my ($self, undef, $body) = @_;
306 $body = $body->from if Scalar::Util::blessed($body);
307 $self->_expand_ident(ident => $body);
312 if ($opt{lazy_join_sql_parts}) {
313 my $mod = Module::Runtime::use_module('SQL::Abstract::Parts');
314 $opt{join_sql_parts} ||= sub { $mod->new(@_) };
317 $opt{join_sql_parts} ||= sub { join $_[0], @_[1..$#_] };
319 return bless \%opt, $class;
323 my ($self, $name, $key, $value) = @_;
324 return $self->{$name}{$key} unless @_ > 3;
325 $self->{$name}{$key} = $value;
329 sub make_unop_expander {
330 my (undef, $exp) = @_;
332 my ($self, $name, $body, $k) = @_;
333 return $self->_expand_hashpair_cmp($k, { "-${name}" => $body })
335 return $self->$exp($name, $body);
339 sub make_binop_expander {
340 my (undef, $exp) = @_;
342 my ($self, $name, $body, $k) = @_;
343 $k = shift @{$body = [ @$body ]} unless defined $k;
344 $k = ref($k) ? $k : { -ident => $k };
345 return $self->$exp($name, $body, $k);
350 my ($self, $plugin, @args) = @_;
351 unless (ref $plugin) {
352 $plugin =~ s/\A\+/${\__PACKAGE__}::Plugin::/;
353 require(join('/', split '::', $plugin).'.pm');
355 $plugin->apply_to($self, @args);
360 foreach my $type (qw(
361 expand op_expand render op_render clause_expand clause_render
363 my $name = join '_', reverse split '_', $type;
364 my $singular = "${type}er";
366 eval qq{sub ${singular} { shift->${singular}s(\@_) }; 1 }
367 or die "Method builder failed for ${singular}: $@";
368 eval qq{sub wrap_${singular} {
369 shift->wrap_${singular}s(\@_)
370 }; 1 } or die "Method builder failed for wrap_${singular}: $@";
372 eval qq{sub ${singular}s {
373 my (\$self, \@args) = \@_;
374 while (my (\$this_key, \$this_value) = splice(\@args, 0, 2)) {
375 \$self->_ext_rw('${name}', \$this_key, \$this_value);
378 }; 1 } or die "Method builder failed for ${singular}s: $@";
379 eval qq{sub wrap_${singular}s {
380 my (\$self, \@args) = \@_;
381 while (my (\$this_key, \$this_builder) = splice(\@args, 0, 2)) {
382 my \$orig = \$self->_ext_rw('${name}', \$this_key);
384 '${name}', \$this_key,
385 \$this_builder->(\$orig, '${name}', \$this_key),
389 }; 1 } or die "Method builder failed for wrap_${singular}s: $@";
390 eval qq{sub ${singular}_list { sort keys %{\$_[0]->{\$name}} }; 1; }
391 or die "Method builder failed for ${singular}_list: $@";
393 foreach my $singular (qw(unop_expander binop_expander)) {
394 eval qq{sub ${singular} { shift->${singular}s(\@_) }; 1 }
395 or die "Method builder failed for ${singular}: $@";
396 eval qq{sub ${singular}s {
397 my (\$self, \@args) = \@_;
398 while (my (\$this_key, \$this_value) = splice(\@args, 0, 2)) {
400 expand_op => \$this_key,
401 \$self->make_${singular}(\$this_value),
405 }; 1 } or die "Method builder failed for ${singular}s: $@";
409 #sub register_op { $_[0]->{is_op}{$_[1]} = 1; $_[0] }
411 sub statement_list { sort keys %{$_[0]->{clauses_of}} }
414 my ($self, $of, @clauses) = @_;
416 return @{$self->{clauses_of}{$of}||[]};
418 if (ref($clauses[0]) eq 'CODE') {
419 @clauses = $self->${\($clauses[0])}(@{$self->{clauses_of}{$of}||[]});
421 $self->{clauses_of}{$of} = \@clauses;
430 ref($self->{$_}) eq 'HASH'
439 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
440 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
442 sub _assert_pass_injection_guard {
443 if ($_[1] =~ $_[0]->{injection_guard}) {
444 my $class = ref $_[0];
445 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
446 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
447 . "{injection_guard} attribute to ${class}->new()"
452 #======================================================================
454 #======================================================================
457 my ($self, $table, $data, $options) = @_;
460 if (ref($table) eq 'HASH') {
463 my %clauses = (target => $table, values => $data, %{$options||{}});
467 my @rendered = $self->render_statement({ -insert => $stmt });
468 return wantarray ? @rendered : $rendered[0];
471 sub _expand_insert_clause_target {
472 +(target => $_[0]->expand_expr($_[2], -ident));
475 sub _expand_insert_clause_fields {
477 $_[0]->expand_expr({ -list => $_[2] }, -ident)
478 ] } if ref($_[2]) eq 'ARRAY';
479 return $_[2]; # should maybe still expand somewhat?
482 sub _expand_insert_clause_from {
483 my ($self, undef, $data) = @_;
484 if (ref($data) eq 'HASH' and (keys(%$data))[0] =~ /^-/) {
485 return $self->expand_expr($data);
487 my ($f_aqt, $v_aqt) = $self->_expand_insert_values($data);
489 from => { -values => [ $v_aqt ] },
490 ($f_aqt ? (fields => $f_aqt) : ()),
494 sub _expand_insert_clause_returning {
495 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
498 sub _expand_insert_values {
499 my ($self, $data) = @_;
500 if (is_literal_value($data)) {
501 (undef, $self->expand_expr($data));
503 my ($fields, $values) = (
504 ref($data) eq 'HASH' ?
505 ([ sort keys %$data ], [ @{$data}{sort keys %$data} ])
509 # no names (arrayref) means can't generate bindtype
510 !($fields) && $self->{bindtype} eq 'columns'
511 && belch "can't do 'columns' bindtype when called with arrayref";
515 ? $self->expand_expr({ -row => $fields }, -ident)
520 local our $Cur_Col_Meta = $fields->[$_];
521 $self->_expand_insert_value($values->[$_])
528 sub _render_insert_clause_fields {
529 return $_[0]->render_aqt($_[2]);
532 sub _render_insert_clause_target {
533 my ($self, undef, $from) = @_;
534 $self->join_query_parts(' ', { -keyword => 'insert into' }, $from);
537 sub _render_insert_clause_from {
538 return $_[0]->render_aqt($_[2], 1);
541 # So that subclasses can override INSERT ... RETURNING separately from
542 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
543 sub _insert_returning { shift->_returning(@_) }
545 sub _redispatch_returning {
546 my ($self, $type, undef, $returning) = @_;
547 [ $self->${\"_${type}_returning"}({ returning => $returning }) ];
551 my ($self, $options) = @_;
553 my $f = $options->{returning};
555 my ($sql, @bind) = @{ $self->render_aqt(
556 $self->expand_expr({ -list => $f }, -ident)
558 my $rsql = $self->_sqlcase(' returning ').$sql;
559 return wantarray ? ($rsql, @bind) : $rsql;
562 sub _expand_insert_value {
565 my $k = our $Cur_Col_Meta;
567 if (ref($v) eq 'ARRAY') {
568 if ($self->{array_datatypes}) {
569 return +{ -bind => [ $k, $v ] };
571 my ($sql, @bind) = @$v;
572 $self->_assert_bindval_matches_bindtype(@bind);
573 return +{ -literal => $v };
575 if (ref($v) eq 'HASH') {
576 if (grep !/^-/, keys %$v) {
577 belch "HASH ref as bind value in insert is not supported";
578 return +{ -bind => [ $k, $v ] };
582 return +{ -bind => [ $k, undef ] };
584 return $self->expand_expr($v);
589 #======================================================================
591 #======================================================================
594 my ($self, $table, $set, $where, $options) = @_;
597 if (ref($table) eq 'HASH') {
601 @clauses{qw(target set where)} = ($table, $set, $where);
602 puke "Unsupported data type specified to \$sql->update"
603 unless ref($clauses{set}) eq 'HASH';
604 @clauses{keys %$options} = values %$options;
608 my @rendered = $self->render_statement({ -update => $stmt });
609 return wantarray ? @rendered : $rendered[0];
612 sub _render_update_clause_target {
613 my ($self, undef, $target) = @_;
614 $self->join_query_parts(' ', { -keyword => 'update' }, $target);
617 sub _update_set_values {
618 my ($self, $data) = @_;
620 return @{ $self->render_aqt(
621 $self->_expand_update_set_values(undef, $data),
625 sub _expand_update_set_values {
626 my ($self, undef, $data) = @_;
627 $self->expand_expr({ -list => [
630 $set = { -bind => $_ } unless defined $set;
631 +{ -op => [ '=', { -ident => $k }, $set ] };
637 ? ($self->{array_datatypes}
638 ? [ $k, +{ -bind => [ $k, $v ] } ]
639 : [ $k, +{ -literal => $v } ])
641 local our $Cur_Col_Meta = $k;
642 [ $k, $self->_expand_expr($v) ]
649 sub _expand_update_clause_target {
650 my ($self, undef, $target) = @_;
651 +(target => $self->expand_expr({ -list => $target }, -ident));
654 sub _expand_update_clause_set {
655 return $_[2] if ref($_[2]) eq 'HASH' and ($_[2]->{-op}||[''])->[0] eq ',';
656 +(set => $_[0]->_expand_update_set_values($_[1], $_[2]));
659 sub _expand_update_clause_where {
660 +(where => $_[0]->expand_expr($_[2]));
663 sub _expand_update_clause_returning {
664 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
667 # So that subclasses can override UPDATE ... RETURNING separately from
669 sub _update_returning { shift->_returning(@_) }
673 #======================================================================
675 #======================================================================
678 my ($self, @args) = @_;
680 if (ref(my $sel = $args[0]) eq 'HASH') {
684 @clauses{qw(from select where order_by)} = @args;
686 # This oddity is to literalify since historically SQLA doesn't quote
687 # a single identifier argument, so we convert it into a literal
689 $clauses{select} = { -literal => [ $clauses{select}||'*' ] }
690 unless ref($clauses{select});
695 my @rendered = $self->render_statement({ -select => $stmt });
696 return wantarray ? @rendered : $rendered[0];
699 sub _expand_select_clause_select {
700 my ($self, undef, $select) = @_;
701 +(select => $self->expand_expr({ -list => $select }, -ident));
704 sub _expand_select_clause_from {
705 my ($self, undef, $from) = @_;
706 +(from => $self->expand_expr({ -list => $from }, -ident));
709 sub _expand_select_clause_where {
710 my ($self, undef, $where) = @_;
713 if (my $conv = $self->{convert}) {
725 ->wrap_expander(bind => $_wrap)
726 ->wrap_op_expanders(map +($_ => $_wrap), qw(ident value))
727 ->wrap_expander(func => sub {
730 my ($self, $type, $thing) = @_;
731 if (ref($thing) eq 'ARRAY' and $thing->[0] eq $conv
732 and @$thing == 2 and ref($thing->[1]) eq 'HASH'
735 or $thing->[1]{-value}
736 or $thing->[1]{-bind})
738 return { -func => $thing }; # already went through our expander
740 return $self->$orig($type, $thing);
748 return +(where => $sqla->expand_expr($where));
751 sub _expand_select_clause_order_by {
752 my ($self, undef, $order_by) = @_;
753 +(order_by => $self->_expand_order_by($order_by));
757 my ($self, $fields) = @_;
758 return $fields unless ref($fields);
759 my ($sql, @bind) = @{ $self->render_aqt(
760 $self->expand_expr({ -list => $fields }, '-ident')
762 return wantarray ? ($sql, @bind) : $sql;
765 #======================================================================
767 #======================================================================
770 my ($self, $table, $where, $options) = @_;
773 if (ref($table) eq 'HASH') {
776 my %clauses = (target => $table, where => $where, %{$options||{}});
780 my @rendered = $self->render_statement({ -delete => $stmt });
781 return wantarray ? @rendered : $rendered[0];
784 # So that subclasses can override DELETE ... RETURNING separately from
786 sub _delete_returning { shift->_returning(@_) }
788 sub _expand_delete_clause_target {
789 +(target => $_[0]->expand_expr({ -list => $_[2] }, -ident));
792 sub _expand_delete_clause_where { +(where => $_[0]->expand_expr($_[2])); }
794 sub _expand_delete_clause_returning {
795 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
798 sub _render_delete_clause_target {
799 my ($self, undef, $from) = @_;
800 $self->join_query_parts(' ', { -keyword => 'delete from' }, $from);
803 #======================================================================
805 #======================================================================
809 # Finally, a separate routine just to handle WHERE clauses
811 my ($self, $where, $order) = @_;
813 local $self->{convert_where} = $self->{convert};
816 my ($sql, @bind) = defined($where)
817 ? $self->_recurse_where($where)
819 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
823 my ($order_sql, @order_bind) = $self->_order_by($order);
825 push @bind, @order_bind;
828 return wantarray ? ($sql, @bind) : $sql;
831 { our $Default_Scalar_To = -value }
834 my ($self, $expr, $default_scalar_to) = @_;
835 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
836 $self->_expand_expr($expr);
840 my ($self, $aqt, $top_level) = @_;
841 my ($k, $v, @rest) = %$aqt;
843 die "Not a node type: $k" unless $k =~ s/^-//;
844 if (my $meth = $self->{render}{$k}) {
845 local our $Render_Top_Level = $top_level;
846 return $self->$meth($k, $v);
848 die "notreached: $k";
852 my ($self, $expr, $default_scalar_to) = @_;
853 return @{ $self->render_aqt(
854 $self->expand_expr($expr, $default_scalar_to)
858 sub render_statement {
859 my ($self, $expr, $default_scalar_to) = @_;
861 $self->expand_expr($expr, $default_scalar_to), 1
865 sub _expand_statement {
866 my ($self, $type, $args) = @_;
867 my $ec = $self->{expand_clause};
870 $args->{$type} = delete $args->{_}
872 my %has_clause = map +($_ => 1), @{$self->{clauses_of}{$type}};
873 return +{ "-${type}" => +{
875 my $val = $args->{$_};
876 if (defined($val) and my $exp = $ec->{"${type}.$_"}) {
877 if ((my (@exp) = $self->$exp($_ => $val)) == 1) {
882 } elsif ($has_clause{$_}) {
883 ($_ => $self->expand_expr($val))
891 sub _render_statement {
892 my ($self, $type, $args) = @_;
894 foreach my $clause (@{$self->{clauses_of}{$type}}) {
895 next unless my $clause_expr = $args->{$clause};
897 if (my $rdr = $self->{render_clause}{"${type}.${clause}"}) {
898 $self->$rdr($clause, $clause_expr, $args);
900 my $r = $self->render_aqt($clause_expr, 1);
901 next unless defined $r->[0] and length $r->[0];
902 $self->join_query_parts(' ',
903 { -keyword => $clause },
910 my $q = $self->join_query_parts(' ', @parts);
911 return $self->join_query_parts('',
912 (our $Render_Top_Level ? $q : ('(', $q, ')'))
917 my ($self, $raw) = @_;
919 return $op if grep $_->{$op}, @{$self}{qw(expand_op render_op)};
920 s/^-(?=.)//, s/\s+/_/g for $op;
925 my ($self, $expr) = @_;
926 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
927 return undef unless defined($expr);
928 if (ref($expr) eq 'HASH') {
929 return undef unless my $kc = keys %$expr;
931 return $self->_expand_op_andor(and => $expr);
933 my ($key, $value) = %$expr;
934 if ($key =~ /^-/ and $key =~ s/ [_\s]? \d+ $//x ) {
935 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
936 . "You probably wanted ...-and => [ $key => COND1, $key => COND2 ... ]";
938 return $self->_expand_hashpair($key, $value);
940 if (ref($expr) eq 'ARRAY') {
941 return $self->_expand_op_andor(lc($self->{logic}), $expr);
943 if (my $literal = is_literal_value($expr)) {
944 return +{ -literal => $literal };
946 if (!ref($expr) or Scalar::Util::blessed($expr)) {
947 return $self->_expand_scalar($expr);
952 sub _expand_hashpair {
953 my ($self, $k, $v) = @_;
954 unless (defined($k) and length($k)) {
955 if (defined($k) and my $literal = is_literal_value($v)) {
956 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
957 return { -literal => $literal };
959 puke "Supplying an empty left hand side argument is not supported";
962 return $self->_expand_hashpair_op($k, $v);
963 } elsif ($k =~ /^[^\w]/i) {
964 my ($lhs, @rhs) = ref($v) eq 'ARRAY' ? @$v : $v;
965 return $self->_expand_op(
966 -op, [ $k, $self->expand_expr($lhs, -ident), @rhs ]
969 return $self->_expand_hashpair_ident($k, $v);
972 sub _expand_hashpair_ident {
973 my ($self, $k, $v) = @_;
975 local our $Cur_Col_Meta = $k;
977 # hash with multiple or no elements is andor
979 if (ref($v) eq 'HASH' and keys %$v != 1) {
980 return $self->_expand_op_andor(and => $v, $k);
983 # undef needs to be re-sent with cmp to achieve IS/IS NOT NULL
985 if (is_undef_value($v)) {
986 return $self->_expand_hashpair_cmp($k => undef);
989 # scalars and objects get expanded as whatever requested or values
991 if (!ref($v) or Scalar::Util::blessed($v)) {
992 return $self->_expand_hashpair_scalar($k, $v);
995 # single key hashref is a hashtriple
997 if (ref($v) eq 'HASH') {
998 return $self->_expand_hashtriple($k, %$v);
1001 # arrayref needs re-engineering over the elements
1003 if (ref($v) eq 'ARRAY') {
1004 return $self->sqlfalse unless @$v;
1005 $self->_debug("ARRAY($k) means distribute over elements");
1007 $v->[0] =~ /^-(and|or)$/i
1008 ? (shift(@{$v = [ @$v ]}), $1)
1009 : lc($self->{logic} || 'OR')
1011 return $self->_expand_op_andor(
1016 if (my $literal = is_literal_value($v)) {
1017 unless (length $k) {
1018 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
1021 my ($sql, @bind) = @$literal;
1022 if ($self->{bindtype} eq 'columns') {
1024 $self->_assert_bindval_matches_bindtype($_);
1027 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
1032 sub _expand_scalar {
1033 my ($self, $expr) = @_;
1035 return $self->_expand_expr({ (our $Default_Scalar_To) => $expr });
1038 sub _expand_hashpair_scalar {
1039 my ($self, $k, $v) = @_;
1041 return $self->_expand_hashpair_cmp(
1042 $k, $self->_expand_scalar($v),
1046 sub _expand_hashpair_op {
1047 my ($self, $k, $v) = @_;
1049 $self->_assert_pass_injection_guard($k =~ /\A-(.*)\Z/s);
1051 my $op = $self->_normalize_op($k);
1053 my $wsop = join(' ', split '_', $op);
1055 my $is_special = List::Util::first { $wsop =~ $_->{regex} }
1056 @{$self->{special_ops}};
1060 # the old special op system requires illegality for top-level use
1063 (our $Expand_Depth) == 1
1067 $self->{disable_old_special_ops}
1068 and List::Util::first { $wsop =~ $_->{regex} } @BUILTIN_SPECIAL_OPS
1072 puke "Illegal use of top-level '-$wsop'"
1076 if (my $exp = $self->{expand}{$op}||$self->{expand_op}{$op}) {
1077 return $self->$exp($op, $v);
1080 if ($self->{render}{$op}) {
1081 return { "-${op}" => $v };
1084 # Ops prefixed with -not_ get converted
1086 if (my ($rest) = $op =~/^not_(.*)$/) {
1089 $self->_expand_expr({ "-${rest}", $v })
1095 # the old unary op system means we should touch nothing and let it work
1097 my $op = join(' ', split '_', $op);
1099 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1100 return { -op => [ $op, $v ] };
1104 my $type = $is_special || $self->{render_op}{$op} ? -op : -func;
1106 if ($self->{restore_old_unop_handling}) {
1113 and (keys %$v)[0] =~ /^-/
1114 and not $self->{render_op}{$op}
1123 if ($type eq -func and ref($v) eq 'ARRAY') {
1124 return $self->_expand_expr({ -func => [ $op, @$v ] });
1127 return $self->_expand_expr({ $type => [ $op, $v ] });
1130 sub _expand_hashpair_cmp {
1131 my ($self, $k, $v) = @_;
1132 $self->_expand_hashtriple($k, $self->{cmp}, $v);
1135 sub _expand_hashtriple {
1136 my ($self, $k, $vk, $vv) = @_;
1138 my $ik = $self->_expand_expr({ -ident => $k });
1140 my $op = $self->_normalize_op($vk);
1141 $self->_assert_pass_injection_guard($op);
1143 if ($op =~ s/ _? \d+ $//x ) {
1144 return $self->_expand_expr($k, { $vk, $vv });
1146 if (my $x = $self->{expand_op}{$op}) {
1147 local our $Cur_Col_Meta = $k;
1148 return $self->$x($op, $vv, $k);
1152 my $op = join(' ', split '_', $op);
1154 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
1155 return { -op => [ $op, $ik, $vv ] };
1157 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1161 { -op => [ $op, $vv ] }
1165 if (ref($vv) eq 'ARRAY') {
1167 my $logic = (defined($raw[0]) and $raw[0] =~ /^-(and|or)$/i)
1168 ? (shift(@raw), lc $1) : 'or';
1169 my @values = map +{ $vk => $_ }, @raw;
1171 $op =~ $self->{inequality_op}
1172 or $op =~ $self->{not_like_op}
1174 if (lc($logic) eq 'or' and @values > 1) {
1175 belch "A multi-element arrayref as an argument to the inequality op '${\uc(join ' ', split '_', $op)}' "
1176 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
1177 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
1182 # try to DWIM on equality operators
1183 return ($self->_dwim_op_to_is($op,
1184 "Supplying an empty arrayref to '%s' is deprecated",
1185 "operator '%s' applied on an empty array (field '$k')"
1186 ) ? $self->sqlfalse : $self->sqltrue);
1188 return $self->_expand_op_andor($logic => \@values, $k);
1190 if (is_undef_value($vv)) {
1191 my $is = ($self->_dwim_op_to_is($op,
1192 "Supplying an undefined argument to '%s' is deprecated",
1193 "unexpected operator '%s' with undef operand",
1194 ) ? 'is' : 'is not');
1196 return $self->_expand_hashpair($k => { $is, undef });
1198 local our $Cur_Col_Meta = $k;
1202 $self->_expand_expr($vv)
1206 sub _dwim_op_to_is {
1207 my ($self, $raw, $empty, $fail) = @_;
1209 my $op = $self->_normalize_op($raw);
1211 if ($op =~ /^not$/i) {
1214 if ($op =~ $self->{equality_op}) {
1217 if ($op =~ $self->{like_op}) {
1218 belch(sprintf $empty, uc(join ' ', split '_', $op));
1221 if ($op =~ $self->{inequality_op}) {
1224 if ($op =~ $self->{not_like_op}) {
1225 belch(sprintf $empty, uc(join ' ', split '_', $op));
1228 puke(sprintf $fail, $op);
1232 my ($self, undef, $args) = @_;
1233 my ($func, @args) = @$args;
1234 return +{ -func => [ $func, map $self->expand_expr($_), @args ] };
1238 my ($self, undef, $body) = @_;
1239 unless (defined($body) or (ref($body) and ref($body) eq 'ARRAY')) {
1240 puke "-ident requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
1242 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
1243 ref($body) ? @$body : $body;
1244 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
1245 unless ($self->{quote_char}) {
1246 $self->_assert_pass_injection_guard($_) for @parts;
1248 return +{ -ident => \@parts };
1252 +{ -bind => [ our $Cur_Col_Meta, $_[2] ] };
1256 my ($self, undef, $args) = @_;
1257 +{ -row => [ map $self->expand_expr($_), @$args ] };
1261 my ($self, undef, $args) = @_;
1262 my ($op, @opargs) = @$args;
1263 if (my $exp = $self->{expand_op}{$op}) {
1264 return $self->$exp($op, \@opargs);
1266 if (List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1267 return { -op => [ $op, @opargs ] };
1269 +{ -op => [ $op, map $self->expand_expr($_), @opargs ] };
1273 my ($self, undef, $v) = @_;
1275 return $self->_expand_expr($v);
1277 puke "-bool => undef not supported" unless defined($v);
1278 return $self->_expand_expr({ -ident => $v });
1282 my ($self, undef, $expr) = @_;
1284 ',', map $self->expand_expr($_),
1285 @{$expr->{-op}}[1..$#{$expr->{-op}}]
1286 ] } if ref($expr) eq 'HASH' and ($expr->{-op}||[''])->[0] eq ',';
1287 return +{ -op => [ ',',
1288 map $self->expand_expr($_),
1289 ref($expr) eq 'ARRAY' ? @$expr : $expr
1293 sub _expand_op_andor {
1294 my ($self, $logop, $v, $k) = @_;
1296 $v = [ map +{ $k, $_ },
1298 ? (map +{ $_ => $v->{$_} }, sort keys %$v)
1302 if (ref($v) eq 'HASH') {
1303 return undef unless keys %$v;
1306 map $self->_expand_expr({ $_ => $v->{$_} }),
1310 if (ref($v) eq 'ARRAY') {
1311 $logop eq 'and' or $logop eq 'or' or puke "unknown logic: $logop";
1314 (ref($_) eq 'ARRAY' and @$_)
1315 or (ref($_) eq 'HASH' and %$_)
1321 while (my ($el) = splice @expr, 0, 1) {
1322 puke "Supplying an empty left hand side argument is not supported in array-pairs"
1323 unless defined($el) and length($el);
1324 my $elref = ref($el);
1326 local our $Expand_Depth = 0;
1327 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
1328 } elsif ($elref eq 'ARRAY') {
1329 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
1330 } elsif (my $l = is_literal_value($el)) {
1331 push @res, { -literal => $l };
1332 } elsif ($elref eq 'HASH') {
1333 local our $Expand_Depth = 0;
1334 push @res, grep defined, $self->_expand_expr($el) if %$el;
1340 # return $res[0] if @res == 1;
1341 return { -op => [ $logop, @res ] };
1347 my ($self, $op, $vv, $k) = @_;
1348 ($k, $vv) = @$vv unless defined $k;
1349 puke "$op can only take undef as argument"
1353 and exists($vv->{-value})
1354 and !defined($vv->{-value})
1356 return +{ -op => [ $op.'_null', $self->expand_expr($k, -ident) ] };
1359 sub _expand_between {
1360 my ($self, $op, $vv, $k) = @_;
1361 my @rhs = map $self->_expand_expr($_),
1362 ref($vv) eq 'ARRAY' ? @$vv : $vv;
1364 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
1366 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
1368 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1372 $self->expand_expr($k),
1373 map $self->expand_expr($_, -value), @rhs
1378 my ($self, $op, $vv, $k) = @_;
1379 if (my $literal = is_literal_value($vv)) {
1380 my ($sql, @bind) = @$literal;
1381 my $opened_sql = $self->_open_outer_paren($sql);
1383 $op, $self->expand_expr($k, -ident),
1384 { -literal => [ $opened_sql, @bind ] }
1388 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1389 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1390 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1391 . 'will emit the logically correct SQL instead of raising this exception)'
1393 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
1395 my @rhs = map $self->expand_expr($_, -value),
1396 map { defined($_) ? $_: puke($undef_err) }
1397 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
1398 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
1402 $self->expand_expr($k, -ident),
1408 my ($self, undef, $v) = @_;
1409 # DBIx::Class requires a nest warning to be emitted once but the private
1410 # method it overrode to do so no longer exists
1411 if ($self->{warn_once_on_nest}) {
1412 unless (our $Nest_Warned) {
1414 "-nest in search conditions is deprecated, you most probably wanted:\n"
1415 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
1420 return $self->_expand_expr($v);
1423 sub _expand_values {
1424 my ($self, undef, $values) = @_;
1425 return { -values => [
1428 ? $self->expand_expr($_)
1429 : +{ -row => [ map $self->expand_expr($_), @$_ ] }
1430 ), ref($values) eq 'ARRAY' ? @$values : $values
1434 sub _recurse_where {
1435 my ($self, $where) = @_;
1437 # Special case: top level simple string treated as literal
1439 my $where_exp = (ref($where)
1440 ? $self->_expand_select_clause_where(undef, $where)
1441 : { -literal => [ $where ] });
1443 # dispatch expanded expression
1445 my ($sql, @bind) = defined($where_exp) ? @{ $self->render_aqt($where_exp) || [] } : ();
1446 # DBIx::Class used to call _recurse_where in scalar context
1447 # something else might too...
1449 return ($sql, @bind);
1452 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
1458 my ($self, undef, $ident) = @_;
1460 return [ $self->_quote($ident) ];
1464 my ($self, undef, $values) = @_;
1465 return $self->join_query_parts('',
1467 $self->_render_op(undef, [ ',', @$values ]),
1473 my ($self, undef, $rest) = @_;
1474 my ($func, @args) = @$rest;
1475 return $self->join_query_parts('',
1476 $self->_sqlcase($func),
1477 $self->join_query_parts('',
1479 $self->join_query_parts(', ', @args),
1486 my ($self, undef, $bind) = @_;
1487 return [ '?', $self->_bindtype(@$bind) ];
1490 sub _render_literal {
1491 my ($self, undef, $literal) = @_;
1492 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1496 sub _render_keyword {
1497 my ($self, undef, $keyword) = @_;
1498 return [ $self->_sqlcase(
1499 ref($keyword) ? $$keyword : join ' ', split '_', $keyword
1504 my ($self, undef, $v) = @_;
1505 my ($op, @args) = @$v;
1506 if (my $r = $self->{render_op}{$op}) {
1507 return $self->$r($op, \@args);
1512 my $op = join(' ', split '_', $op);
1514 my $ss = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1515 if ($ss and @args > 1) {
1516 puke "Special op '${op}' requires first value to be identifier"
1517 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1518 my $k = join(($self->{name_sep}||'.'), @$ident);
1519 local our $Expand_Depth = 1;
1520 return [ $self->${\($ss->{handler})}($k, $op, $args[1]) ];
1522 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1523 return [ $self->${\($us->{handler})}($op, $args[0]) ];
1526 return $self->_render_unop_paren($op, \@args);
1530 return $self->_render_unop_prefix($op, \@args);
1532 return $self->_render_op_multop($op, \@args);
1538 sub _render_op_between {
1539 my ($self, $op, $args) = @_;
1540 my ($left, $low, $high) = @$args;
1543 puke "Single arg to between must be a literal"
1544 unless $low->{-literal};
1547 +($low, { -keyword => 'and' }, $high);
1550 return $self->join_query_parts(' ',
1551 '(', $left, { -keyword => $op }, @rh, ')',
1556 my ($self, $op, $args) = @_;
1557 my ($lhs, @rhs) = @$args;
1559 return $self->join_query_parts(' ',
1561 { -keyword => $op },
1562 $self->join_query_parts(' ',
1564 $self->join_query_parts(', ', @rhs),
1570 sub _render_op_andor {
1571 my ($self, $op, $args) = @_;
1572 return undef unless @$args;
1573 return $self->join_query_parts('', $args->[0]) if @$args == 1;
1574 my $inner = $self->_render_op_multop($op, $args);
1575 return undef unless defined($inner->[0]) and length($inner->[0]);
1576 return $self->join_query_parts(' ',
1581 sub _render_op_multop {
1582 my ($self, $op, $args) = @_;
1584 return undef unless @parts;
1585 return $self->render_aqt($parts[0]) if @parts == 1;
1586 my $join = ($op eq ','
1588 : { -keyword => " ${op} " }
1590 return $self->join_query_parts($join, @parts);
1593 sub _render_values {
1594 my ($self, undef, $values) = @_;
1595 my $inner = $self->join_query_parts(' ',
1596 { -keyword => 'values' },
1597 $self->join_query_parts(', ',
1598 ref($values) eq 'ARRAY' ? @$values : $values
1601 return $self->join_query_parts('',
1602 (our $Render_Top_Level ? $inner : ('(', $inner, ')'))
1606 sub join_query_parts {
1607 my ($self, $join, @parts) = @_;
1608 if (ref($join) eq 'HASH') {
1609 $join = $self->render_aqt($join)->[0];
1613 ? $self->render_aqt($_)
1614 : ((ref($_) eq 'ARRAY') ? $_ : [ $_ ])
1617 $self->{join_sql_parts}->(
1618 $join, grep defined && length, map $_->[0], @final
1620 (map @{$_}[1..$#$_], @final),
1624 sub _render_unop_paren {
1625 my ($self, $op, $v) = @_;
1626 return $self->join_query_parts('',
1627 '(', $self->_render_unop_prefix($op, $v), ')'
1631 sub _render_unop_prefix {
1632 my ($self, $op, $v) = @_;
1633 my $op_sql = $self->{restore_old_unop_handling}
1634 ? $self->_sqlcase($op)
1635 : { -keyword => $op };
1636 return $self->join_query_parts(' ',
1637 ($self->{restore_old_unop_handling}
1638 ? $self->_sqlcase($op)
1639 : { -keyword => \$op }),
1644 sub _render_unop_postfix {
1645 my ($self, $op, $v) = @_;
1646 return $self->join_query_parts(' ',
1647 $v->[0], { -keyword => $op },
1651 # Some databases (SQLite) treat col IN (1, 2) different from
1652 # col IN ( (1, 2) ). Use this to strip all outer parens while
1653 # adding them back in the corresponding method
1654 sub _open_outer_paren {
1655 my ($self, $sql) = @_;
1657 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1659 # there are closing parens inside, need the heavy duty machinery
1660 # to reevaluate the extraction starting from $sql (full reevaluation)
1661 if ($inner =~ /\)/) {
1662 require Text::Balanced;
1664 my (undef, $remainder) = do {
1665 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1667 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1670 # the entire expression needs to be a balanced bracketed thing
1671 # (after an extract no remainder sans trailing space)
1672 last if defined $remainder and $remainder =~ /\S/;
1682 #======================================================================
1684 #======================================================================
1686 sub _expand_order_by {
1687 my ($self, $arg) = @_;
1689 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1691 return $self->expand_expr({ -list => $arg })
1692 if ref($arg) eq 'HASH' and ($arg->{-op}||[''])->[0] eq ',';
1694 my $expander = sub {
1695 my ($self, $dir, $expr) = @_;
1696 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1697 foreach my $arg (@to_expand) {
1701 and grep /^-(asc|desc)$/, keys %$arg
1703 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1707 defined($dir) ? { -op => [ $dir =~ /^-?(.*)$/ ,=> $_ ] } : $_
1709 map $self->expand_expr($_, -ident),
1710 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
1711 return undef unless @exp;
1712 return undef if @exp == 1 and not defined($exp[0]);
1713 return +{ -op => [ ',', @exp ] };
1716 local @{$self->{expand}}{qw(asc desc)} = (($expander) x 2);
1718 return $self->$expander(undef, $arg);
1722 my ($self, $arg) = @_;
1724 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
1726 my ($sql, @bind) = @{ $self->render_aqt($expanded) };
1728 return '' unless length($sql);
1730 my $final_sql = $self->_sqlcase(' order by ').$sql;
1732 return $final_sql unless wantarray;
1734 return ($final_sql, @bind);
1737 # _order_by no longer needs to call this so doesn't but DBIC uses it.
1739 sub _order_by_chunks {
1740 my ($self, $arg) = @_;
1742 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1744 my @res = $self->_chunkify_order_by($expanded);
1745 (ref() ? $_->[0] : $_) .= '' for @res;
1749 sub _chunkify_order_by {
1750 my ($self, $expanded) = @_;
1752 return grep length, @{ $self->render_aqt($expanded) }
1753 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1756 if (ref() eq 'HASH' and $_->{-op} and $_->{-op}[0] eq ',') {
1757 my ($comma, @list) = @{$_->{-op}};
1758 return map $self->_chunkify_order_by($_), @list;
1760 return $self->render_aqt($_);
1764 #======================================================================
1765 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1766 #======================================================================
1772 $self->expand_expr({ -list => $from }, -ident)
1777 #======================================================================
1779 #======================================================================
1781 # highly optimized, as it's called way too often
1783 # my ($self, $label) = @_;
1785 return '' unless defined $_[1];
1786 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1787 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1789 unless ($_[0]->{quote_char}) {
1790 if (ref($_[1]) eq 'ARRAY') {
1791 return join($_[0]->{name_sep}||'.', @{$_[1]});
1793 $_[0]->_assert_pass_injection_guard($_[1]);
1798 my $qref = ref $_[0]->{quote_char};
1800 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1801 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1802 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1804 my $esc = $_[0]->{escape_char} || $r;
1806 # parts containing * are naturally unquoted
1808 $_[0]->{name_sep}||'',
1812 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1814 (ref($_[1]) eq 'ARRAY'
1818 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1826 # Conversion, if applicable
1828 #my ($self, $arg) = @_;
1829 if (my $conv = $_[0]->{convert_where}) {
1830 return @{ $_[0]->join_query_parts('',
1831 $_[0]->_sqlcase($conv),
1840 #my ($self, $col, @vals) = @_;
1841 # called often - tighten code
1842 return $_[0]->{bindtype} eq 'columns'
1843 ? map {[$_[1], $_]} @_[2 .. $#_]
1848 # Dies if any element of @bind is not in [colname => value] format
1849 # if bindtype is 'columns'.
1850 sub _assert_bindval_matches_bindtype {
1851 # my ($self, @bind) = @_;
1853 if ($self->{bindtype} eq 'columns') {
1855 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1856 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1862 # Fix SQL case, if so requested
1864 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1865 # don't touch the argument ... crooked logic, but let's not change it!
1866 return $_[0]->{case} ? $_[1] : uc($_[1]);
1869 #======================================================================
1870 # DISPATCHING FROM REFKIND
1871 #======================================================================
1874 my ($self, $data) = @_;
1876 return 'UNDEF' unless defined $data;
1878 # blessed objects are treated like scalars
1879 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1881 return 'SCALAR' unless $ref;
1884 while ($ref eq 'REF') {
1886 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1890 return ($ref||'SCALAR') . ('REF' x $n_steps);
1894 my ($self, $data) = @_;
1895 my @try = ($self->_refkind($data));
1896 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1897 push @try, 'FALLBACK';
1901 sub _METHOD_FOR_refkind {
1902 my ($self, $meth_prefix, $data) = @_;
1905 for (@{$self->_try_refkind($data)}) {
1906 $method = $self->can($meth_prefix."_".$_)
1910 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1914 sub _SWITCH_refkind {
1915 my ($self, $data, $dispatch_table) = @_;
1918 for (@{$self->_try_refkind($data)}) {
1919 $coderef = $dispatch_table->{$_}
1923 puke "no dispatch entry for ".$self->_refkind($data)
1932 #======================================================================
1933 # VALUES, GENERATE, AUTOLOAD
1934 #======================================================================
1936 # LDNOTE: original code from nwiger, didn't touch code in that section
1937 # I feel the AUTOLOAD stuff should not be the default, it should
1938 # only be activated on explicit demand by user.
1942 my $data = shift || return;
1943 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1944 unless ref $data eq 'HASH';
1947 foreach my $k (sort keys %$data) {
1948 my $v = $data->{$k};
1949 $self->_SWITCH_refkind($v, {
1951 if ($self->{array_datatypes}) { # array datatype
1952 push @all_bind, $self->_bindtype($k, $v);
1954 else { # literal SQL with bind
1955 my ($sql, @bind) = @$v;
1956 $self->_assert_bindval_matches_bindtype(@bind);
1957 push @all_bind, @bind;
1960 ARRAYREFREF => sub { # literal SQL with bind
1961 my ($sql, @bind) = @${$v};
1962 $self->_assert_bindval_matches_bindtype(@bind);
1963 push @all_bind, @bind;
1965 SCALARREF => sub { # literal SQL without bind
1967 SCALAR_or_UNDEF => sub {
1968 push @all_bind, $self->_bindtype($k, $v);
1979 my(@sql, @sqlq, @sqlv);
1983 if ($ref eq 'HASH') {
1984 for my $k (sort keys %$_) {
1987 my $label = $self->_quote($k);
1988 if ($r eq 'ARRAY') {
1989 # literal SQL with bind
1990 my ($sql, @bind) = @$v;
1991 $self->_assert_bindval_matches_bindtype(@bind);
1992 push @sqlq, "$label = $sql";
1994 } elsif ($r eq 'SCALAR') {
1995 # literal SQL without bind
1996 push @sqlq, "$label = $$v";
1998 push @sqlq, "$label = ?";
1999 push @sqlv, $self->_bindtype($k, $v);
2002 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
2003 } elsif ($ref eq 'ARRAY') {
2004 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
2007 if ($r eq 'ARRAY') { # literal SQL with bind
2008 my ($sql, @bind) = @$v;
2009 $self->_assert_bindval_matches_bindtype(@bind);
2012 } elsif ($r eq 'SCALAR') { # literal SQL without bind
2013 # embedded literal SQL
2020 push @sql, '(' . join(', ', @sqlq) . ')';
2021 } elsif ($ref eq 'SCALAR') {
2025 # strings get case twiddled
2026 push @sql, $self->_sqlcase($_);
2030 my $sql = join ' ', @sql;
2032 # this is pretty tricky
2033 # if ask for an array, return ($stmt, @bind)
2034 # otherwise, s/?/shift @sqlv/ to put it inline
2036 return ($sql, @sqlv);
2038 1 while $sql =~ s/\?/my $d = shift(@sqlv);
2039 ref $d ? $d->[1] : $d/e;
2048 # This allows us to check for a local, then _form, attr
2050 my($name) = $AUTOLOAD =~ /.*::(.+)/;
2051 puke "AUTOLOAD invoked for method name ${name} and allow_autoload option not set" unless $self->{allow_autoload};
2052 return $self->generate($name, @_);
2063 SQL::Abstract - Generate SQL from Perl data structures
2069 my $sql = SQL::Abstract->new;
2071 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
2073 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
2075 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
2077 my($stmt, @bind) = $sql->delete($table, \%where);
2079 # Then, use these in your DBI statements
2080 my $sth = $dbh->prepare($stmt);
2081 $sth->execute(@bind);
2083 # Just generate the WHERE clause
2084 my($stmt, @bind) = $sql->where(\%where, $order);
2086 # Return values in the same order, for hashed queries
2087 # See PERFORMANCE section for more details
2088 my @bind = $sql->values(\%fieldvals);
2092 This module was inspired by the excellent L<DBIx::Abstract>.
2093 However, in using that module I found that what I really wanted
2094 to do was generate SQL, but still retain complete control over my
2095 statement handles and use the DBI interface. So, I set out to
2096 create an abstract SQL generation module.
2098 While based on the concepts used by L<DBIx::Abstract>, there are
2099 several important differences, especially when it comes to WHERE
2100 clauses. I have modified the concepts used to make the SQL easier
2101 to generate from Perl data structures and, IMO, more intuitive.
2102 The underlying idea is for this module to do what you mean, based
2103 on the data structures you provide it. The big advantage is that
2104 you don't have to modify your code every time your data changes,
2105 as this module figures it out.
2107 To begin with, an SQL INSERT is as easy as just specifying a hash
2108 of C<key=value> pairs:
2111 name => 'Jimbo Bobson',
2112 phone => '123-456-7890',
2113 address => '42 Sister Lane',
2114 city => 'St. Louis',
2115 state => 'Louisiana',
2118 The SQL can then be generated with this:
2120 my($stmt, @bind) = $sql->insert('people', \%data);
2122 Which would give you something like this:
2124 $stmt = "INSERT INTO people
2125 (address, city, name, phone, state)
2126 VALUES (?, ?, ?, ?, ?)";
2127 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
2128 '123-456-7890', 'Louisiana');
2130 These are then used directly in your DBI code:
2132 my $sth = $dbh->prepare($stmt);
2133 $sth->execute(@bind);
2135 =head2 Inserting and Updating Arrays
2137 If your database has array types (like for example Postgres),
2138 activate the special option C<< array_datatypes => 1 >>
2139 when creating the C<SQL::Abstract> object.
2140 Then you may use an arrayref to insert and update database array types:
2142 my $sql = SQL::Abstract->new(array_datatypes => 1);
2144 planets => [qw/Mercury Venus Earth Mars/]
2147 my($stmt, @bind) = $sql->insert('solar_system', \%data);
2151 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
2153 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
2156 =head2 Inserting and Updating SQL
2158 In order to apply SQL functions to elements of your C<%data> you may
2159 specify a reference to an arrayref for the given hash value. For example,
2160 if you need to execute the Oracle C<to_date> function on a value, you can
2161 say something like this:
2165 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
2168 The first value in the array is the actual SQL. Any other values are
2169 optional and would be included in the bind values array. This gives
2172 my($stmt, @bind) = $sql->insert('people', \%data);
2174 $stmt = "INSERT INTO people (name, date_entered)
2175 VALUES (?, to_date(?,'MM/DD/YYYY'))";
2176 @bind = ('Bill', '03/02/2003');
2178 An UPDATE is just as easy, all you change is the name of the function:
2180 my($stmt, @bind) = $sql->update('people', \%data);
2182 Notice that your C<%data> isn't touched; the module will generate
2183 the appropriately quirky SQL for you automatically. Usually you'll
2184 want to specify a WHERE clause for your UPDATE, though, which is
2185 where handling C<%where> hashes comes in handy...
2187 =head2 Complex where statements
2189 This module can generate pretty complicated WHERE statements
2190 easily. For example, simple C<key=value> pairs are taken to mean
2191 equality, and if you want to see if a field is within a set
2192 of values, you can use an arrayref. Let's say we wanted to
2193 SELECT some data based on this criteria:
2196 requestor => 'inna',
2197 worker => ['nwiger', 'rcwe', 'sfz'],
2198 status => { '!=', 'completed' }
2201 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
2203 The above would give you something like this:
2205 $stmt = "SELECT * FROM tickets WHERE
2206 ( requestor = ? ) AND ( status != ? )
2207 AND ( worker = ? OR worker = ? OR worker = ? )";
2208 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
2210 Which you could then use in DBI code like so:
2212 my $sth = $dbh->prepare($stmt);
2213 $sth->execute(@bind);
2219 The methods are simple. There's one for every major SQL operation,
2220 and a constructor you use first. The arguments are specified in a
2221 similar order for each method (table, then fields, then a where
2222 clause) to try and simplify things.
2224 =head2 new(option => 'value')
2226 The C<new()> function takes a list of options and values, and returns
2227 a new B<SQL::Abstract> object which can then be used to generate SQL
2228 through the methods below. The options accepted are:
2234 If set to 'lower', then SQL will be generated in all lowercase. By
2235 default SQL is generated in "textbook" case meaning something like:
2237 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
2239 Any setting other than 'lower' is ignored.
2243 This determines what the default comparison operator is. By default
2244 it is C<=>, meaning that a hash like this:
2246 %where = (name => 'nwiger', email => 'nate@wiger.org');
2248 Will generate SQL like this:
2250 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
2252 However, you may want loose comparisons by default, so if you set
2253 C<cmp> to C<like> you would get SQL such as:
2255 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
2257 You can also override the comparison on an individual basis - see
2258 the huge section on L</"WHERE CLAUSES"> at the bottom.
2260 =item sqltrue, sqlfalse
2262 Expressions for inserting boolean values within SQL statements.
2263 By default these are C<1=1> and C<1=0>. They are used
2264 by the special operators C<-in> and C<-not_in> for generating
2265 correct SQL even when the argument is an empty array (see below).
2269 This determines the default logical operator for multiple WHERE
2270 statements in arrays or hashes. If absent, the default logic is "or"
2271 for arrays, and "and" for hashes. This means that a WHERE
2275 event_date => {'>=', '2/13/99'},
2276 event_date => {'<=', '4/24/03'},
2279 will generate SQL like this:
2281 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
2283 This is probably not what you want given this query, though (look
2284 at the dates). To change the "OR" to an "AND", simply specify:
2286 my $sql = SQL::Abstract->new(logic => 'and');
2288 Which will change the above C<WHERE> to:
2290 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
2292 The logic can also be changed locally by inserting
2293 a modifier in front of an arrayref:
2295 @where = (-and => [event_date => {'>=', '2/13/99'},
2296 event_date => {'<=', '4/24/03'} ]);
2298 See the L</"WHERE CLAUSES"> section for explanations.
2302 This will automatically convert comparisons using the specified SQL
2303 function for both column and value. This is mostly used with an argument
2304 of C<upper> or C<lower>, so that the SQL will have the effect of
2305 case-insensitive "searches". For example, this:
2307 $sql = SQL::Abstract->new(convert => 'upper');
2308 %where = (keywords => 'MaKe iT CAse inSeNSItive');
2310 Will turn out the following SQL:
2312 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
2314 The conversion can be C<upper()>, C<lower()>, or any other SQL function
2315 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
2316 not validate this option; it will just pass through what you specify verbatim).
2320 This is a kludge because many databases suck. For example, you can't
2321 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
2322 Instead, you have to use C<bind_param()>:
2324 $sth->bind_param(1, 'reg data');
2325 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
2327 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
2328 which loses track of which field each slot refers to. Fear not.
2330 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
2331 Currently, you can specify either C<normal> (default) or C<columns>. If you
2332 specify C<columns>, you will get an array that looks like this:
2334 my $sql = SQL::Abstract->new(bindtype => 'columns');
2335 my($stmt, @bind) = $sql->insert(...);
2338 [ 'column1', 'value1' ],
2339 [ 'column2', 'value2' ],
2340 [ 'column3', 'value3' ],
2343 You can then iterate through this manually, using DBI's C<bind_param()>.
2345 $sth->prepare($stmt);
2348 my($col, $data) = @$_;
2349 if ($col eq 'details' || $col eq 'comments') {
2350 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
2351 } elsif ($col eq 'image') {
2352 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
2354 $sth->bind_param($i, $data);
2358 $sth->execute; # execute without @bind now
2360 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
2361 Basically, the advantage is still that you don't have to care which fields
2362 are or are not included. You could wrap that above C<for> loop in a simple
2363 sub called C<bind_fields()> or something and reuse it repeatedly. You still
2364 get a layer of abstraction over manual SQL specification.
2366 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
2367 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
2368 will expect the bind values in this format.
2372 This is the character that a table or column name will be quoted
2373 with. By default this is an empty string, but you could set it to
2374 the character C<`>, to generate SQL like this:
2376 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
2378 Alternatively, you can supply an array ref of two items, the first being the left
2379 hand quote character, and the second the right hand quote character. For
2380 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
2381 that generates SQL like this:
2383 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
2385 Quoting is useful if you have tables or columns names that are reserved
2386 words in your database's SQL dialect.
2390 This is the character that will be used to escape L</quote_char>s appearing
2391 in an identifier before it has been quoted.
2393 The parameter default in case of a single L</quote_char> character is the quote
2396 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
2397 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
2398 of the B<opening (left)> L</quote_char> within the identifier are currently left
2399 untouched. The default for opening-closing-style quotes may change in future
2400 versions, thus you are B<strongly encouraged> to specify the escape character
2405 This is the character that separates a table and column name. It is
2406 necessary to specify this when the C<quote_char> option is selected,
2407 so that tables and column names can be individually quoted like this:
2409 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2411 =item injection_guard
2413 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2414 column name specified in a query structure. This is a safety mechanism to avoid
2415 injection attacks when mishandling user input e.g.:
2417 my %condition_as_column_value_pairs = get_values_from_user();
2418 $sqla->select( ... , \%condition_as_column_value_pairs );
2420 If the expression matches an exception is thrown. Note that literal SQL
2421 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2423 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2425 =item array_datatypes
2427 When this option is true, arrayrefs in INSERT or UPDATE are
2428 interpreted as array datatypes and are passed directly
2430 When this option is false, arrayrefs are interpreted
2431 as literal SQL, just like refs to arrayrefs
2432 (but this behavior is for backwards compatibility; when writing
2433 new queries, use the "reference to arrayref" syntax
2439 Takes a reference to a list of "special operators"
2440 to extend the syntax understood by L<SQL::Abstract>.
2441 See section L</"SPECIAL OPERATORS"> for details.
2445 Takes a reference to a list of "unary operators"
2446 to extend the syntax understood by L<SQL::Abstract>.
2447 See section L</"UNARY OPERATORS"> for details.
2453 =head2 insert($table, \@values || \%fieldvals, \%options)
2455 This is the simplest function. You simply give it a table name
2456 and either an arrayref of values or hashref of field/value pairs.
2457 It returns an SQL INSERT statement and a list of bind values.
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 insert SQL. Currently supported options
2470 Takes either a scalar of raw SQL fields, or an array reference of
2471 field names, and adds on an SQL C<RETURNING> statement at the end.
2472 This allows you to return data generated by the insert statement
2473 (such as row IDs) without performing another C<SELECT> statement.
2474 Note, however, this is not part of the SQL standard and may not
2475 be supported by all database engines.
2479 =head2 update($table, \%fieldvals, \%where, \%options)
2481 This takes a table, hashref of field/value pairs, and an optional
2482 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2484 See the sections on L</"Inserting and Updating Arrays"> and
2485 L</"Inserting and Updating SQL"> for information on how to insert
2486 with those data types.
2488 The optional C<\%options> hash reference may contain additional
2489 options to generate the update SQL. Currently supported options
2496 See the C<returning> option to
2497 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2501 =head2 select($source, $fields, $where, $order)
2503 This returns a SQL SELECT statement and associated list of bind values, as
2504 specified by the arguments:
2510 Specification of the 'FROM' part of the statement.
2511 The argument can be either a plain scalar (interpreted as a table
2512 name, will be quoted), or an arrayref (interpreted as a list
2513 of table names, joined by commas, quoted), or a scalarref
2514 (literal SQL, not quoted).
2518 Specification of the list of fields to retrieve from
2520 The argument can be either an arrayref (interpreted as a list
2521 of field names, will be joined by commas and quoted), or a
2522 plain scalar (literal SQL, not quoted).
2523 Please observe that this API is not as flexible as that of
2524 the first argument C<$source>, for backwards compatibility reasons.
2528 Optional argument to specify the WHERE part of the query.
2529 The argument is most often a hashref, but can also be
2530 an arrayref or plain scalar --
2531 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2535 Optional argument to specify the ORDER BY part of the query.
2536 The argument can be a scalar, a hashref or an arrayref
2537 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2543 =head2 delete($table, \%where, \%options)
2545 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2546 It returns an SQL DELETE statement and list of bind values.
2548 The optional C<\%options> hash reference may contain additional
2549 options to generate the delete SQL. Currently supported options
2556 See the C<returning> option to
2557 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2561 =head2 where(\%where, $order)
2563 This is used to generate just the WHERE clause. For example,
2564 if you have an arbitrary data structure and know what the
2565 rest of your SQL is going to look like, but want an easy way
2566 to produce a WHERE clause, use this. It returns an SQL WHERE
2567 clause and list of bind values.
2570 =head2 values(\%data)
2572 This just returns the values from the hash C<%data>, in the same
2573 order that would be returned from any of the other above queries.
2574 Using this allows you to markedly speed up your queries if you
2575 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2577 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2579 Warning: This is an experimental method and subject to change.
2581 This returns arbitrarily generated SQL. It's a really basic shortcut.
2582 It will return two different things, depending on return context:
2584 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2585 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2587 These would return the following:
2589 # First calling form
2590 $stmt = "CREATE TABLE test (?, ?)";
2591 @bind = (field1, field2);
2593 # Second calling form
2594 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2596 Depending on what you're trying to do, it's up to you to choose the correct
2597 format. In this example, the second form is what you would want.
2601 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2605 ALTER SESSION SET nls_date_format = 'MM/YY'
2607 You get the idea. Strings get their case twiddled, but everything
2608 else remains verbatim.
2610 =head1 EXPORTABLE FUNCTIONS
2612 =head2 is_plain_value
2614 Determines if the supplied argument is a plain value as understood by this
2619 =item * The value is C<undef>
2621 =item * The value is a non-reference
2623 =item * The value is an object with stringification overloading
2625 =item * The value is of the form C<< { -value => $anything } >>
2629 On failure returns C<undef>, on success returns a B<scalar> reference
2630 to the original supplied argument.
2636 The stringification overloading detection is rather advanced: it takes
2637 into consideration not only the presence of a C<""> overload, but if that
2638 fails also checks for enabled
2639 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2640 on either C<0+> or C<bool>.
2642 Unfortunately testing in the field indicates that this
2643 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2644 but only when very large numbers of stringifying objects are involved.
2645 At the time of writing ( Sep 2014 ) there is no clear explanation of
2646 the direct cause, nor is there a manageably small test case that reliably
2647 reproduces the problem.
2649 If you encounter any of the following exceptions in B<random places within
2650 your application stack> - this module may be to blame:
2652 Operation "ne": no method found,
2653 left argument in overloaded package <something>,
2654 right argument in overloaded package <something>
2658 Stub found while resolving method "???" overloading """" in package <something>
2660 If you fall victim to the above - please attempt to reduce the problem
2661 to something that could be sent to the L<SQL::Abstract developers
2662 |DBIx::Class/GETTING HELP/SUPPORT>
2663 (either publicly or privately). As a workaround in the meantime you can
2664 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2665 value, which will most likely eliminate your problem (at the expense of
2666 not being able to properly detect exotic forms of stringification).
2668 This notice and environment variable will be removed in a future version,
2669 as soon as the underlying problem is found and a reliable workaround is
2674 =head2 is_literal_value
2676 Determines if the supplied argument is a literal value as understood by this
2681 =item * C<\$sql_string>
2683 =item * C<\[ $sql_string, @bind_values ]>
2687 On failure returns C<undef>, on success returns an B<array> reference
2688 containing the unpacked version of the supplied literal SQL and bind values.
2690 =head2 is_undef_value
2692 Tests for undef, whether expanded or not.
2694 =head1 WHERE CLAUSES
2698 This module uses a variation on the idea from L<DBIx::Abstract>. It
2699 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2700 module is that things in arrays are OR'ed, and things in hashes
2703 The easiest way to explain is to show lots of examples. After
2704 each C<%where> hash shown, it is assumed you used:
2706 my($stmt, @bind) = $sql->where(\%where);
2708 However, note that the C<%where> hash can be used directly in any
2709 of the other functions as well, as described above.
2711 =head2 Key-value pairs
2713 So, let's get started. To begin, a simple hash:
2717 status => 'completed'
2720 Is converted to SQL C<key = val> statements:
2722 $stmt = "WHERE user = ? AND status = ?";
2723 @bind = ('nwiger', 'completed');
2725 One common thing I end up doing is having a list of values that
2726 a field can be in. To do this, simply specify a list inside of
2731 status => ['assigned', 'in-progress', 'pending'];
2734 This simple code will create the following:
2736 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2737 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2739 A field associated to an empty arrayref will be considered a
2740 logical false and will generate 0=1.
2742 =head2 Tests for NULL values
2744 If the value part is C<undef> then this is converted to SQL <IS NULL>
2753 $stmt = "WHERE user = ? AND status IS NULL";
2756 To test if a column IS NOT NULL:
2760 status => { '!=', undef },
2763 =head2 Specific comparison operators
2765 If you want to specify a different type of operator for your comparison,
2766 you can use a hashref for a given column:
2770 status => { '!=', 'completed' }
2773 Which would generate:
2775 $stmt = "WHERE user = ? AND status != ?";
2776 @bind = ('nwiger', 'completed');
2778 To test against multiple values, just enclose the values in an arrayref:
2780 status => { '=', ['assigned', 'in-progress', 'pending'] };
2782 Which would give you:
2784 "WHERE status = ? OR status = ? OR status = ?"
2787 The hashref can also contain multiple pairs, in which case it is expanded
2788 into an C<AND> of its elements:
2792 status => { '!=', 'completed', -not_like => 'pending%' }
2795 # Or more dynamically, like from a form
2796 $where{user} = 'nwiger';
2797 $where{status}{'!='} = 'completed';
2798 $where{status}{'-not_like'} = 'pending%';
2800 # Both generate this
2801 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2802 @bind = ('nwiger', 'completed', 'pending%');
2805 To get an OR instead, you can combine it with the arrayref idea:
2809 priority => [ { '=', 2 }, { '>', 5 } ]
2812 Which would generate:
2814 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2815 @bind = ('2', '5', 'nwiger');
2817 If you want to include literal SQL (with or without bind values), just use a
2818 scalar reference or reference to an arrayref as the value:
2821 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2822 date_expires => { '<' => \"now()" }
2825 Which would generate:
2827 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2828 @bind = ('11/26/2008');
2831 =head2 Logic and nesting operators
2833 In the example above,
2834 there is a subtle trap if you want to say something like
2835 this (notice the C<AND>):
2837 WHERE priority != ? AND priority != ?
2839 Because, in Perl you I<can't> do this:
2841 priority => { '!=' => 2, '!=' => 1 }
2843 As the second C<!=> key will obliterate the first. The solution
2844 is to use the special C<-modifier> form inside an arrayref:
2846 priority => [ -and => {'!=', 2},
2850 Normally, these would be joined by C<OR>, but the modifier tells it
2851 to use C<AND> instead. (Hint: You can use this in conjunction with the
2852 C<logic> option to C<new()> in order to change the way your queries
2853 work by default.) B<Important:> Note that the C<-modifier> goes
2854 B<INSIDE> the arrayref, as an extra first element. This will
2855 B<NOT> do what you think it might:
2857 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2859 Here is a quick list of equivalencies, since there is some overlap:
2862 status => {'!=', 'completed', 'not like', 'pending%' }
2863 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2866 status => {'=', ['assigned', 'in-progress']}
2867 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2868 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2872 =head2 Special operators: IN, BETWEEN, etc.
2874 You can also use the hashref format to compare a list of fields using the
2875 C<IN> comparison operator, by specifying the list as an arrayref:
2878 status => 'completed',
2879 reportid => { -in => [567, 2335, 2] }
2882 Which would generate:
2884 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2885 @bind = ('completed', '567', '2335', '2');
2887 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2890 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2891 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2892 'sqltrue' (by default: C<1=1>).
2894 In addition to the array you can supply a chunk of literal sql or
2895 literal sql with bind:
2898 customer => { -in => \[
2899 'SELECT cust_id FROM cust WHERE balance > ?',
2902 status => { -in => \'SELECT status_codes FROM states' },
2908 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2909 AND status IN ( SELECT status_codes FROM states )
2913 Finally, if the argument to C<-in> is not a reference, it will be
2914 treated as a single-element array.
2916 Another pair of operators is C<-between> and C<-not_between>,
2917 used with an arrayref of two values:
2921 completion_date => {
2922 -not_between => ['2002-10-01', '2003-02-06']
2928 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2930 Just like with C<-in> all plausible combinations of literal SQL
2934 start0 => { -between => [ 1, 2 ] },
2935 start1 => { -between => \["? AND ?", 1, 2] },
2936 start2 => { -between => \"lower(x) AND upper(y)" },
2937 start3 => { -between => [
2939 \["upper(?)", 'stuff' ],
2946 ( start0 BETWEEN ? AND ? )
2947 AND ( start1 BETWEEN ? AND ? )
2948 AND ( start2 BETWEEN lower(x) AND upper(y) )
2949 AND ( start3 BETWEEN lower(x) AND upper(?) )
2951 @bind = (1, 2, 1, 2, 'stuff');
2954 These are the two builtin "special operators"; but the
2955 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
2957 =head2 Unary operators: bool
2959 If you wish to test against boolean columns or functions within your
2960 database you can use the C<-bool> and C<-not_bool> operators. For
2961 example to test the column C<is_user> being true and the column
2962 C<is_enabled> being false you would use:-
2966 -not_bool => 'is_enabled',
2971 WHERE is_user AND NOT is_enabled
2973 If a more complex combination is required, testing more conditions,
2974 then you should use the and/or operators:-
2979 -not_bool => { two=> { -rlike => 'bar' } },
2980 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
2991 (NOT ( three = ? OR three > ? ))
2994 =head2 Nested conditions, -and/-or prefixes
2996 So far, we've seen how multiple conditions are joined with a top-level
2997 C<AND>. We can change this by putting the different conditions we want in
2998 hashes and then putting those hashes in an array. For example:
3003 status => { -like => ['pending%', 'dispatched'] },
3007 status => 'unassigned',
3011 This data structure would create the following:
3013 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
3014 OR ( user = ? AND status = ? ) )";
3015 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
3018 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
3019 to change the logic inside:
3025 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
3026 -or => { workhrs => {'<', 50}, geo => 'EURO' },
3033 $stmt = "WHERE ( user = ?
3034 AND ( ( workhrs > ? AND geo = ? )
3035 OR ( workhrs < ? OR geo = ? ) ) )";
3036 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
3038 =head3 Algebraic inconsistency, for historical reasons
3040 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
3041 operator goes C<outside> of the nested structure; whereas when connecting
3042 several constraints on one column, the C<-and> operator goes
3043 C<inside> the arrayref. Here is an example combining both features:
3046 -and => [a => 1, b => 2],
3047 -or => [c => 3, d => 4],
3048 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
3053 WHERE ( ( ( a = ? AND b = ? )
3054 OR ( c = ? OR d = ? )
3055 OR ( e LIKE ? AND e LIKE ? ) ) )
3057 This difference in syntax is unfortunate but must be preserved for
3058 historical reasons. So be careful: the two examples below would
3059 seem algebraically equivalent, but they are not
3062 { -like => 'foo%' },
3063 { -like => '%bar' },
3065 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
3068 { col => { -like => 'foo%' } },
3069 { col => { -like => '%bar' } },
3071 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
3074 =head2 Literal SQL and value type operators
3076 The basic premise of SQL::Abstract is that in WHERE specifications the "left
3077 side" is a column name and the "right side" is a value (normally rendered as
3078 a placeholder). This holds true for both hashrefs and arrayref pairs as you
3079 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
3080 alter this behavior. There are several ways of doing so.
3084 This is a virtual operator that signals the string to its right side is an
3085 identifier (a column name) and not a value. For example to compare two
3086 columns you would write:
3089 priority => { '<', 2 },
3090 requestor => { -ident => 'submitter' },
3095 $stmt = "WHERE priority < ? AND requestor = submitter";
3098 If you are maintaining legacy code you may see a different construct as
3099 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
3104 This is a virtual operator that signals that the construct to its right side
3105 is a value to be passed to DBI. This is for example necessary when you want
3106 to write a where clause against an array (for RDBMS that support such
3107 datatypes). For example:
3110 array => { -value => [1, 2, 3] }
3115 $stmt = 'WHERE array = ?';
3116 @bind = ([1, 2, 3]);
3118 Note that if you were to simply say:
3124 the result would probably not be what you wanted:
3126 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
3131 Finally, sometimes only literal SQL will do. To include a random snippet
3132 of SQL verbatim, you specify it as a scalar reference. Consider this only
3133 as a last resort. Usually there is a better way. For example:
3136 priority => { '<', 2 },
3137 requestor => { -in => \'(SELECT name FROM hitmen)' },
3142 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
3145 Note that in this example, you only get one bind parameter back, since
3146 the verbatim SQL is passed as part of the statement.
3150 Never use untrusted input as a literal SQL argument - this is a massive
3151 security risk (there is no way to check literal snippets for SQL
3152 injections and other nastyness). If you need to deal with untrusted input
3153 use literal SQL with placeholders as described next.
3155 =head3 Literal SQL with placeholders and bind values (subqueries)
3157 If the literal SQL to be inserted has placeholders and bind values,
3158 use a reference to an arrayref (yes this is a double reference --
3159 not so common, but perfectly legal Perl). For example, to find a date
3160 in Postgres you can use something like this:
3163 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
3168 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
3171 Note that you must pass the bind values in the same format as they are returned
3172 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
3173 to C<columns>, you must provide the bind values in the
3174 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
3175 scalar value; most commonly the column name, but you can use any scalar value
3176 (including references and blessed references), L<SQL::Abstract> will simply
3177 pass it through intact. So if C<bindtype> is set to C<columns> the above
3178 example will look like:
3181 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
3184 Literal SQL is especially useful for nesting parenthesized clauses in the
3185 main SQL query. Here is a first example:
3187 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
3191 bar => \["IN ($sub_stmt)" => @sub_bind],
3196 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
3197 WHERE c2 < ? AND c3 LIKE ?))";
3198 @bind = (1234, 100, "foo%");
3200 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
3201 are expressed in the same way. Of course the C<$sub_stmt> and
3202 its associated bind values can be generated through a former call
3205 my ($sub_stmt, @sub_bind)
3206 = $sql->select("t1", "c1", {c2 => {"<" => 100},
3207 c3 => {-like => "foo%"}});
3210 bar => \["> ALL ($sub_stmt)" => @sub_bind],
3213 In the examples above, the subquery was used as an operator on a column;
3214 but the same principle also applies for a clause within the main C<%where>
3215 hash, like an EXISTS subquery:
3217 my ($sub_stmt, @sub_bind)
3218 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
3219 my %where = ( -and => [
3221 \["EXISTS ($sub_stmt)" => @sub_bind],
3226 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
3227 WHERE c1 = ? AND c2 > t0.c0))";
3231 Observe that the condition on C<c2> in the subquery refers to
3232 column C<t0.c0> of the main query: this is I<not> a bind
3233 value, so we have to express it through a scalar ref.
3234 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
3235 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
3236 what we wanted here.
3238 Finally, here is an example where a subquery is used
3239 for expressing unary negation:
3241 my ($sub_stmt, @sub_bind)
3242 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
3243 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
3245 lname => {like => '%son%'},
3246 \["NOT ($sub_stmt)" => @sub_bind],
3251 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
3252 @bind = ('%son%', 10, 20)
3254 =head3 Deprecated usage of Literal SQL
3256 Below are some examples of archaic use of literal SQL. It is shown only as
3257 reference for those who deal with legacy code. Each example has a much
3258 better, cleaner and safer alternative that users should opt for in new code.
3264 my %where = ( requestor => \'IS NOT NULL' )
3266 $stmt = "WHERE requestor IS NOT NULL"
3268 This used to be the way of generating NULL comparisons, before the handling
3269 of C<undef> got formalized. For new code please use the superior syntax as
3270 described in L</Tests for NULL values>.
3274 my %where = ( requestor => \'= submitter' )
3276 $stmt = "WHERE requestor = submitter"
3278 This used to be the only way to compare columns. Use the superior L</-ident>
3279 method for all new code. For example an identifier declared in such a way
3280 will be properly quoted if L</quote_char> is properly set, while the legacy
3281 form will remain as supplied.
3285 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
3287 $stmt = "WHERE completed > ? AND is_ready"
3288 @bind = ('2012-12-21')
3290 Using an empty string literal used to be the only way to express a boolean.
3291 For all new code please use the much more readable
3292 L<-bool|/Unary operators: bool> operator.
3298 These pages could go on for a while, since the nesting of the data
3299 structures this module can handle are pretty much unlimited (the
3300 module implements the C<WHERE> expansion as a recursive function
3301 internally). Your best bet is to "play around" with the module a
3302 little to see how the data structures behave, and choose the best
3303 format for your data based on that.
3305 And of course, all the values above will probably be replaced with
3306 variables gotten from forms or the command line. After all, if you
3307 knew everything ahead of time, you wouldn't have to worry about
3308 dynamically-generating SQL and could just hardwire it into your
3311 =head1 ORDER BY CLAUSES
3313 Some functions take an order by clause. This can either be a scalar (just a
3314 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
3315 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
3318 Given | Will Generate
3319 ---------------------------------------------------------------
3321 'colA' | ORDER BY colA
3323 [qw/colA colB/] | ORDER BY colA, colB
3325 {-asc => 'colA'} | ORDER BY colA ASC
3327 {-desc => 'colB'} | ORDER BY colB DESC
3329 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
3331 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
3333 \'colA DESC' | ORDER BY colA DESC
3335 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
3336 | /* ...with $x bound to ? */
3339 { -asc => 'colA' }, | colA ASC,
3340 { -desc => [qw/colB/] }, | colB DESC,
3341 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
3342 \'colE DESC', | colE DESC,
3343 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
3344 ] | /* ...with $x bound to ? */
3345 ===============================================================
3349 =head1 OLD EXTENSION SYSTEM
3351 =head2 SPECIAL OPERATORS
3353 my $sqlmaker = SQL::Abstract->new(special_ops => [
3357 my ($self, $field, $op, $arg) = @_;
3363 handler => 'method_name',
3367 A "special operator" is a SQL syntactic clause that can be
3368 applied to a field, instead of a usual binary operator.
3371 WHERE field IN (?, ?, ?)
3372 WHERE field BETWEEN ? AND ?
3373 WHERE MATCH(field) AGAINST (?, ?)
3375 Special operators IN and BETWEEN are fairly standard and therefore
3376 are builtin within C<SQL::Abstract> (as the overridable methods
3377 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
3378 like the MATCH .. AGAINST example above which is specific to MySQL,
3379 you can write your own operator handlers - supply a C<special_ops>
3380 argument to the C<new> method. That argument takes an arrayref of
3381 operator definitions; each operator definition is a hashref with two
3388 the regular expression to match the operator
3392 Either a coderef or a plain scalar method name. In both cases
3393 the expected return is C<< ($sql, @bind) >>.
3395 When supplied with a method name, it is simply called on the
3396 L<SQL::Abstract> object as:
3398 $self->$method_name($field, $op, $arg)
3402 $field is the LHS of the operator
3403 $op is the part that matched the handler regex
3406 When supplied with a coderef, it is called as:
3408 $coderef->($self, $field, $op, $arg)
3413 For example, here is an implementation
3414 of the MATCH .. AGAINST syntax for MySQL
3416 my $sqlmaker = SQL::Abstract->new(special_ops => [
3418 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3419 {regex => qr/^match$/i,
3421 my ($self, $field, $op, $arg) = @_;
3422 $arg = [$arg] if not ref $arg;
3423 my $label = $self->_quote($field);
3424 my ($placeholder) = $self->_convert('?');
3425 my $placeholders = join ", ", (($placeholder) x @$arg);
3426 my $sql = $self->_sqlcase('match') . " ($label) "
3427 . $self->_sqlcase('against') . " ($placeholders) ";
3428 my @bind = $self->_bindtype($field, @$arg);
3429 return ($sql, @bind);
3436 =head2 UNARY OPERATORS
3438 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3442 my ($self, $op, $arg) = @_;
3448 handler => 'method_name',
3452 A "unary operator" is a SQL syntactic clause that can be
3453 applied to a field - the operator goes before the field
3455 You can write your own operator handlers - supply a C<unary_ops>
3456 argument to the C<new> method. That argument takes an arrayref of
3457 operator definitions; each operator definition is a hashref with two
3464 the regular expression to match the operator
3468 Either a coderef or a plain scalar method name. In both cases
3469 the expected return is C<< $sql >>.
3471 When supplied with a method name, it is simply called on the
3472 L<SQL::Abstract> object as:
3474 $self->$method_name($op, $arg)
3478 $op is the part that matched the handler regex
3479 $arg is the RHS or argument of the operator
3481 When supplied with a coderef, it is called as:
3483 $coderef->($self, $op, $arg)
3488 =head1 NEW METHODS (EXPERIMENTAL)
3490 See L<SQL::Abstract::Reference> for the C<expr> versus C<aqt> concept and
3491 an explanation of what the below extensions are extending.
3495 $sqla->plugin('+Foo');
3497 Enables plugin SQL::Abstract::Plugin::Foo.
3501 my ($sql, @bind) = $sqla->render_expr($expr);
3503 =head2 render_statement
3505 Use this if you may be rendering a top level statement so e.g. a SELECT
3506 query doesn't get wrapped in parens
3508 my ($sql, @bind) = $sqla->render_statement($expr);
3512 Expression expansion with optional default for scalars.
3514 my $aqt = $self->expand_expr($expr);
3515 my $aqt = $self->expand_expr($expr, -ident);
3519 Top level means avoid parens on statement AQT.
3521 my $res = $self->render_aqt($aqt, $top_level);
3522 my ($sql, @bind) = @$res;
3524 =head2 join_query_parts
3526 Similar to join() but will render hashrefs as nodes for both join and parts,
3527 and treats arrayref as a nested C<[ $join, @parts ]> structure.
3529 my $part = $self->join_query_parts($join, @parts);
3531 =head1 NEW EXTENSION SYSTEM
3535 my $sqla2 = $sqla->clone;
3537 Performs a semi-shallow copy such that extension methods won't leak state
3538 but excessive depth is avoided.
3548 =head2 clause_expander
3550 =head2 clause_expanders
3552 $sqla->expander('name' => sub { ... });
3553 $sqla->expanders('name1' => sub { ... }, 'name2' => sub { ... });
3555 =head2 expander_list
3557 =head2 op_expander_list
3559 =head2 clause_expander_list
3561 my @names = $sqla->expander_list;
3563 =head2 wrap_expander
3565 =head2 wrap_expanders
3567 =head2 wrap_op_expander
3569 =head2 wrap_op_expanders
3571 =head2 wrap_clause_expander
3573 =head2 wrap_clause_expanders
3575 $sqla->wrap_expander('name' => sub { my ($orig) = @_; sub { ... } });
3576 $sqla->wrap_expanders(
3577 'name1' => sub { my ($orig1) = @_; sub { ... } },
3578 'name2' => sub { my ($orig2) = @_; sub { ... } },
3589 =head2 clause_renderer
3591 =head2 clause_renderers
3593 $sqla->renderer('name' => sub { ... });
3594 $sqla->renderers('name1' => sub { ... }, 'name2' => sub { ... });
3596 =head2 renderer_list
3598 =head2 op_renderer_list
3600 =head2 clause_renderer_list
3602 my @names = $sqla->renderer_list;
3604 =head2 wrap_renderer
3606 =head2 wrap_renderers
3608 =head2 wrap_op_renderer
3610 =head2 wrap_op_renderers
3612 =head2 wrap_clause_renderer
3614 =head2 wrap_clause_renderers
3616 $sqla->wrap_renderer('name' => sub { my ($orig) = @_; sub { ... } });
3617 $sqla->wrap_renderers(
3618 'name1' => sub { my ($orig1) = @_; sub { ... } },
3619 'name2' => sub { my ($orig2) = @_; sub { ... } },
3624 my @clauses = $sqla->clauses_of('select');
3625 $sqla->clauses_of(select => \@new_clauses);
3626 $sqla->clauses_of(select => sub {
3627 my (undef, @old_clauses) = @_;
3629 return @new_clauses;
3632 =head2 statement_list
3634 my @list = $sqla->statement_list;
3636 =head2 make_unop_expander
3638 my $exp = $sqla->make_unop_expander(sub { ... });
3640 If the op is found as a binop, assumes it wants a default comparison, so
3641 the inner expander sub can reliably operate as
3643 sub { my ($self, $name, $body) = @_; ... }
3645 =head2 make_binop_expander
3647 my $exp = $sqla->make_binop_expander(sub { ... });
3649 If the op is found as a unop, assumes the value will be an arrayref with the
3650 LHS as the first entry, and converts that to an ident node if it's a simple
3651 scalar. So the inner expander sub looks like
3654 my ($self, $name, $body, $k) = @_;
3655 { -blah => [ map $self->expand_expr($_), $k, $body ] }
3658 =head2 unop_expander
3660 =head2 unop_expanders
3662 =head2 binop_expander
3664 =head2 binop_expanders
3666 The above methods operate exactly like the op_ versions but wrap the coderef
3667 using the appropriate make_ method first.
3671 Thanks to some benchmarking by Mark Stosberg, it turns out that
3672 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3673 I must admit this wasn't an intentional design issue, but it's a
3674 byproduct of the fact that you get to control your C<DBI> handles
3677 To maximize performance, use a code snippet like the following:
3679 # prepare a statement handle using the first row
3680 # and then reuse it for the rest of the rows
3682 for my $href (@array_of_hashrefs) {
3683 $stmt ||= $sql->insert('table', $href);
3684 $sth ||= $dbh->prepare($stmt);
3685 $sth->execute($sql->values($href));
3688 The reason this works is because the keys in your C<$href> are sorted
3689 internally by B<SQL::Abstract>. Thus, as long as your data retains
3690 the same structure, you only have to generate the SQL the first time
3691 around. On subsequent queries, simply use the C<values> function provided
3692 by this module to return your values in the correct order.
3694 However this depends on the values having the same type - if, for
3695 example, the values of a where clause may either have values
3696 (resulting in sql of the form C<column = ?> with a single bind
3697 value), or alternatively the values might be C<undef> (resulting in
3698 sql of the form C<column IS NULL> with no bind value) then the
3699 caching technique suggested will not work.
3703 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3704 really like this part (I do, at least). Building up a complex query
3705 can be as simple as the following:
3712 use CGI::FormBuilder;
3715 my $form = CGI::FormBuilder->new(...);
3716 my $sql = SQL::Abstract->new;
3718 if ($form->submitted) {
3719 my $field = $form->field;
3720 my $id = delete $field->{id};
3721 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3724 Of course, you would still have to connect using C<DBI> to run the
3725 query, but the point is that if you make your form look like your
3726 table, the actual query script can be extremely simplistic.
3728 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3729 a fast interface to returning and formatting data. I frequently
3730 use these three modules together to write complex database query
3731 apps in under 50 lines.
3733 =head1 HOW TO CONTRIBUTE
3735 Contributions are always welcome, in all usable forms (we especially
3736 welcome documentation improvements). The delivery methods include git-
3737 or unified-diff formatted patches, GitHub pull requests, or plain bug
3738 reports either via RT or the Mailing list. Contributors are generally
3739 granted full access to the official repository after their first several
3740 patches pass successful review.
3742 This project is maintained in a git repository. The code and related tools are
3743 accessible at the following locations:
3747 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3749 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3751 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3753 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3759 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3760 Great care has been taken to preserve the I<published> behavior
3761 documented in previous versions in the 1.* family; however,
3762 some features that were previously undocumented, or behaved
3763 differently from the documentation, had to be changed in order
3764 to clarify the semantics. Hence, client code that was relying
3765 on some dark areas of C<SQL::Abstract> v1.*
3766 B<might behave differently> in v1.50.
3768 The main changes are:
3774 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3778 support for the { operator => \"..." } construct (to embed literal SQL)
3782 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3786 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3790 defensive programming: check arguments
3794 fixed bug with global logic, which was previously implemented
3795 through global variables yielding side-effects. Prior versions would
3796 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3797 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3798 Now this is interpreted
3799 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3804 fixed semantics of _bindtype on array args
3808 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3809 we just avoid shifting arrays within that tree.
3813 dropped the C<_modlogic> function
3817 =head1 ACKNOWLEDGEMENTS
3819 There are a number of individuals that have really helped out with
3820 this module. Unfortunately, most of them submitted bugs via CPAN
3821 so I have no idea who they are! But the people I do know are:
3823 Ash Berlin (order_by hash term support)
3824 Matt Trout (DBIx::Class support)
3825 Mark Stosberg (benchmarking)
3826 Chas Owens (initial "IN" operator support)
3827 Philip Collins (per-field SQL functions)
3828 Eric Kolve (hashref "AND" support)
3829 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3830 Dan Kubb (support for "quote_char" and "name_sep")
3831 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3832 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3833 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3834 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3835 Oliver Charles (support for "RETURNING" after "INSERT")
3841 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3845 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3847 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3849 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3850 While not an official support venue, C<DBIx::Class> makes heavy use of
3851 C<SQL::Abstract>, and as such list members there are very familiar with
3852 how to create queries.
3856 This module is free software; you may copy this under the same
3857 terms as perl itself (either the GNU General Public License or
3858 the Artistic License)