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.90_02';
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 foreach my $type (qw(in between)) {
297 my $meth = "_where_field_".uc($type);
298 if (__PACKAGE__->can($meth) ne $class->can($meth)) {
300 my ($self, $op, $v, $k) = @_;
301 $op = join ' ', split '_', $op;
302 return +{ -literal => [
303 $self->$meth($k, $op, $v)
306 $opt{expand_op}{$_} = $exp for $type, "not_${type}";
309 if ($class->isa('DBIx::Class::SQLMaker')) {
310 $opt{warn_once_on_nest} = 1;
311 $opt{disable_old_special_ops} = 1;
312 $opt{render_clause}{'select.where'} = sub {
313 my ($sql, @bind) = $_[0]->where($_[2]);
314 s/\A\s+//, s/\s+\Z// for $sql;
315 return [ $sql, @bind ];
317 $opt{expand_op}{ident} = $class->make_unop_expander(sub {
318 my ($self, undef, $body) = @_;
319 $body = $body->from if Scalar::Util::blessed($body);
320 $self->_expand_ident(ident => $body);
323 if ($class->isa('SQL::Abstract::More')) {
324 $opt{expand_op}{or} = sub {
325 my ($self, $logop, $v, $k) = @_;
326 if ($k and ref($v) eq 'ARRAY') {
327 my ($type, $val) = @$v;
328 my $op = $self->{cmp};
330 ref($type) eq 'HASH' and ref($val) eq 'HASH'
331 and keys %$type == 1 and keys %$val == 1
332 and (keys %$type)[0] eq (keys %$val)[0]
335 ($type) = values %$type;
336 ($val) = values %$val;
338 if ($self->is_bind_value_with_type(my $v = [ $type, $val ])) {
339 return $self->_expand_hashpair($k, { $op, { -bind => $v } });
342 return $self->_expand_op_andor($logop, $v, $k);
344 $opt{render}{bind} = sub {
345 return [ '?', map +(ref($_->[0]) ? $_ : $_->[1]), $_[2] ]
350 if ($opt{lazy_join_sql_parts}) {
351 my $mod = Module::Runtime::use_module('SQL::Abstract::Parts');
352 $opt{join_sql_parts} ||= sub { $mod->new(@_) };
355 $opt{join_sql_parts} ||= sub { join $_[0], @_[1..$#_] };
357 return bless \%opt, $class;
361 my ($self, $name, $key, $value) = @_;
362 return $self->{$name}{$key} unless @_ > 3;
363 $self->{$name}{$key} = $value;
367 sub make_unop_expander {
368 my (undef, $exp) = @_;
370 my ($self, $name, $body, $k) = @_;
371 return $self->_expand_hashpair_cmp($k, { "-${name}" => $body })
373 return $self->$exp($name, $body);
377 sub make_binop_expander {
378 my (undef, $exp) = @_;
380 my ($self, $name, $body, $k) = @_;
381 $k = shift @{$body = [ @$body ]} unless defined $k;
382 $k = ref($k) ? $k : { -ident => $k };
383 return $self->$exp($name, $body, $k);
388 my ($self, $plugin, @args) = @_;
389 unless (ref $plugin) {
390 $plugin =~ s/\A\+/${\__PACKAGE__}::Plugin::/;
391 require(join('/', split '::', $plugin).'.pm');
393 $plugin->apply_to($self, @args);
398 foreach my $type (qw(
399 expand op_expand render op_render clause_expand clause_render
401 my $name = join '_', reverse split '_', $type;
402 my $singular = "${type}er";
404 eval qq{sub ${singular} {
406 return \$self->_ext_rw('${name}', \@_) if \@_ == 1;
407 return \$self->${singular}s(\@_)
408 }; 1 } or die "Method builder failed for ${singular}: $@";
409 eval qq{sub wrap_${singular} {
410 shift->wrap_${singular}s(\@_)
411 }; 1 } or die "Method builder failed for wrap_${singular}: $@";
413 eval qq{sub ${singular}s {
414 my (\$self, \@args) = \@_;
415 while (my (\$this_key, \$this_value) = splice(\@args, 0, 2)) {
416 \$self->_ext_rw('${name}', \$this_key, \$this_value);
419 }; 1 } or die "Method builder failed for ${singular}s: $@";
420 eval qq{sub wrap_${singular}s {
421 my (\$self, \@args) = \@_;
422 while (my (\$this_key, \$this_builder) = splice(\@args, 0, 2)) {
423 my \$orig = \$self->_ext_rw('${name}', \$this_key);
425 '${name}', \$this_key,
426 \$this_builder->(\$orig, '${name}', \$this_key),
430 }; 1 } or die "Method builder failed for wrap_${singular}s: $@";
431 eval qq{sub ${singular}_list { sort keys %{\$_[0]->{\$name}} }; 1; }
432 or die "Method builder failed for ${singular}_list: $@";
434 foreach my $singular (qw(unop_expander binop_expander)) {
435 eval qq{sub ${singular} { shift->${singular}s(\@_) }; 1 }
436 or die "Method builder failed for ${singular}: $@";
437 eval qq{sub ${singular}s {
438 my (\$self, \@args) = \@_;
439 while (my (\$this_key, \$this_value) = splice(\@args, 0, 2)) {
441 expand_op => \$this_key,
442 \$self->make_${singular}(\$this_value),
446 }; 1 } or die "Method builder failed for ${singular}s: $@";
450 #sub register_op { $_[0]->{is_op}{$_[1]} = 1; $_[0] }
452 sub statement_list { sort keys %{$_[0]->{clauses_of}} }
455 my ($self, $of, @clauses) = @_;
457 return @{$self->{clauses_of}{$of}||[]};
459 if (ref($clauses[0]) eq 'CODE') {
460 @clauses = $self->${\($clauses[0])}(@{$self->{clauses_of}{$of}||[]});
462 $self->{clauses_of}{$of} = \@clauses;
471 ref($self->{$_}) eq 'HASH'
480 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
481 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
483 sub _assert_pass_injection_guard {
484 if ($_[1] =~ $_[0]->{injection_guard}) {
485 my $class = ref $_[0];
486 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
487 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
488 . "{injection_guard} attribute to ${class}->new()"
493 #======================================================================
495 #======================================================================
498 my ($self, $table, $data, $options) = @_;
501 if (ref($table) eq 'HASH') {
504 my %clauses = (target => $table, values => $data, %{$options||{}});
508 my @rendered = $self->render_statement({ -insert => $stmt });
509 return wantarray ? @rendered : $rendered[0];
512 sub _expand_insert_clause_target {
513 +(target => $_[0]->expand_expr($_[2], -ident));
516 sub _expand_insert_clause_fields {
518 $_[0]->expand_expr({ -list => $_[2] }, -ident)
519 ] } if ref($_[2]) eq 'ARRAY';
520 return $_[2]; # should maybe still expand somewhat?
523 sub _expand_insert_clause_from {
524 my ($self, undef, $data) = @_;
525 if (ref($data) eq 'HASH' and (keys(%$data))[0] =~ /^-/) {
526 return $self->expand_expr($data);
528 my ($f_aqt, $v_aqt) = $self->_expand_insert_values($data);
530 from => { -values => [ $v_aqt ] },
531 ($f_aqt ? (fields => $f_aqt) : ()),
535 sub _expand_insert_clause_returning {
536 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
539 sub _expand_insert_values {
540 my ($self, $data) = @_;
541 if (is_literal_value($data)) {
542 (undef, $self->expand_expr($data));
544 my ($fields, $values) = (
545 ref($data) eq 'HASH' ?
546 ([ sort keys %$data ], [ @{$data}{sort keys %$data} ])
550 # no names (arrayref) means can't generate bindtype
551 !($fields) && $self->{bindtype} eq 'columns'
552 && belch "can't do 'columns' bindtype when called with arrayref";
556 ? $self->expand_expr({ -row => $fields }, -ident)
561 local our $Cur_Col_Meta = $fields->[$_];
562 $self->_expand_insert_value($values->[$_])
569 sub _render_insert_clause_fields {
570 return $_[0]->render_aqt($_[2]);
573 sub _render_insert_clause_target {
574 my ($self, undef, $from) = @_;
575 $self->join_query_parts(' ', { -keyword => 'insert into' }, $from);
578 sub _render_insert_clause_from {
579 return $_[0]->render_aqt($_[2], 1);
582 # So that subclasses can override INSERT ... RETURNING separately from
583 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
584 sub _insert_returning { shift->_returning(@_) }
586 sub _redispatch_returning {
587 my ($self, $type, undef, $returning) = @_;
588 [ $self->${\"_${type}_returning"}({ returning => $returning }) ];
592 my ($self, $options) = @_;
594 my $f = $options->{returning};
596 my ($sql, @bind) = @{ $self->render_aqt(
597 $self->expand_expr({ -list => $f }, -ident)
599 my $rsql = $self->_sqlcase(' returning ').$sql;
600 return wantarray ? ($rsql, @bind) : $rsql;
603 sub _expand_insert_value {
606 my $k = our $Cur_Col_Meta;
608 if (ref($v) eq 'ARRAY') {
609 if ($self->{array_datatypes}) {
610 return +{ -bind => [ $k, $v ] };
612 my ($sql, @bind) = @$v;
613 $self->_assert_bindval_matches_bindtype(@bind);
614 return +{ -literal => $v };
616 if (ref($v) eq 'HASH') {
617 if (grep !/^-/, keys %$v) {
618 belch "HASH ref as bind value in insert is not supported";
619 return +{ -bind => [ $k, $v ] };
623 return +{ -bind => [ $k, undef ] };
625 return $self->expand_expr($v);
630 #======================================================================
632 #======================================================================
635 my ($self, $table, $set, $where, $options) = @_;
638 if (ref($table) eq 'HASH') {
642 @clauses{qw(target set where)} = ($table, $set, $where);
643 puke "Unsupported data type specified to \$sql->update"
644 unless ref($clauses{set}) eq 'HASH';
645 @clauses{keys %$options} = values %$options;
649 my @rendered = $self->render_statement({ -update => $stmt });
650 return wantarray ? @rendered : $rendered[0];
653 sub _render_update_clause_target {
654 my ($self, undef, $target) = @_;
655 $self->join_query_parts(' ', { -keyword => 'update' }, $target);
658 sub _update_set_values {
659 my ($self, $data) = @_;
661 return @{ $self->render_aqt(
662 $self->_expand_update_set_values(undef, $data),
666 sub _expand_update_set_values {
667 my ($self, undef, $data) = @_;
668 $self->expand_expr({ -list => [
671 $set = { -bind => $_ } unless defined $set;
672 +{ -op => [ '=', { -ident => $k }, $set ] };
678 ? ($self->{array_datatypes}
679 ? [ $k, +{ -bind => [ $k, $v ] } ]
680 : [ $k, +{ -literal => $v } ])
682 local our $Cur_Col_Meta = $k;
683 [ $k, $self->_expand_expr($v) ]
690 sub _expand_update_clause_target {
691 my ($self, undef, $target) = @_;
692 +(target => $self->expand_expr({ -list => $target }, -ident));
695 sub _expand_update_clause_set {
696 return $_[2] if ref($_[2]) eq 'HASH' and ($_[2]->{-op}||[''])->[0] eq ',';
697 +(set => $_[0]->_expand_update_set_values($_[1], $_[2]));
700 sub _expand_update_clause_where {
701 +(where => $_[0]->expand_expr($_[2]));
704 sub _expand_update_clause_returning {
705 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
708 # So that subclasses can override UPDATE ... RETURNING separately from
710 sub _update_returning { shift->_returning(@_) }
714 #======================================================================
716 #======================================================================
719 my ($self, @args) = @_;
721 if (ref(my $sel = $args[0]) eq 'HASH') {
725 @clauses{qw(from select where order_by)} = @args;
727 # This oddity is to literalify since historically SQLA doesn't quote
728 # a single identifier argument, so we convert it into a literal
730 $clauses{select} = { -literal => [ $clauses{select}||'*' ] }
731 unless ref($clauses{select});
736 my @rendered = $self->render_statement({ -select => $stmt });
737 return wantarray ? @rendered : $rendered[0];
740 sub _expand_select_clause_select {
741 my ($self, undef, $select) = @_;
742 +(select => $self->expand_expr({ -list => $select }, -ident));
745 sub _expand_select_clause_from {
746 my ($self, undef, $from) = @_;
747 +(from => $self->expand_expr({ -list => $from }, -ident));
750 sub _expand_select_clause_where {
751 my ($self, undef, $where) = @_;
754 if (my $conv = $self->{convert}) {
766 ->wrap_expander(bind => $_wrap)
767 ->wrap_op_expanders(map +($_ => $_wrap), qw(ident value))
768 ->wrap_expander(func => sub {
771 my ($self, $type, $thing) = @_;
772 if (ref($thing) eq 'ARRAY' and $thing->[0] eq $conv
773 and @$thing == 2 and ref($thing->[1]) eq 'HASH'
776 or $thing->[1]{-value}
777 or $thing->[1]{-bind})
779 return { -func => $thing }; # already went through our expander
781 return $self->$orig($type, $thing);
789 return +(where => $sqla->expand_expr($where));
792 sub _expand_select_clause_order_by {
793 my ($self, undef, $order_by) = @_;
794 +(order_by => $self->_expand_order_by($order_by));
798 my ($self, $fields) = @_;
799 return $fields unless ref($fields);
800 my ($sql, @bind) = @{ $self->render_aqt(
801 $self->expand_expr({ -list => $fields }, '-ident')
803 return wantarray ? ($sql, @bind) : $sql;
806 #======================================================================
808 #======================================================================
811 my ($self, $table, $where, $options) = @_;
814 if (ref($table) eq 'HASH') {
817 my %clauses = (target => $table, where => $where, %{$options||{}});
821 my @rendered = $self->render_statement({ -delete => $stmt });
822 return wantarray ? @rendered : $rendered[0];
825 # So that subclasses can override DELETE ... RETURNING separately from
827 sub _delete_returning { shift->_returning(@_) }
829 sub _expand_delete_clause_target {
830 +(target => $_[0]->expand_expr({ -list => $_[2] }, -ident));
833 sub _expand_delete_clause_where { +(where => $_[0]->expand_expr($_[2])); }
835 sub _expand_delete_clause_returning {
836 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
839 sub _render_delete_clause_target {
840 my ($self, undef, $from) = @_;
841 $self->join_query_parts(' ', { -keyword => 'delete from' }, $from);
844 #======================================================================
846 #======================================================================
850 # Finally, a separate routine just to handle WHERE clauses
852 my ($self, $where, $order) = @_;
854 local $self->{convert_where} = $self->{convert};
857 my ($sql, @bind) = defined($where)
858 ? $self->_recurse_where($where)
860 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
864 my ($order_sql, @order_bind) = $self->_order_by($order);
866 push @bind, @order_bind;
869 return wantarray ? ($sql, @bind) : $sql;
872 { our $Default_Scalar_To = -value }
875 my ($self, $expr, $default_scalar_to) = @_;
876 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
877 $self->_expand_expr($expr);
881 my ($self, $aqt, $top_level) = @_;
882 my ($k, $v, @rest) = %$aqt;
884 die "Not a node type: $k" unless $k =~ s/^-//;
885 if (my $meth = $self->{render}{$k}) {
886 local our $Render_Top_Level = $top_level;
887 return $self->$meth($k, $v);
889 die "notreached: $k";
893 my ($self, $expr, $default_scalar_to) = @_;
894 return @{ $self->render_aqt(
895 $self->expand_expr($expr, $default_scalar_to)
899 sub render_statement {
900 my ($self, $expr, $default_scalar_to) = @_;
902 $self->expand_expr($expr, $default_scalar_to), 1
906 sub _expand_statement {
907 my ($self, $type, $args) = @_;
908 my $ec = $self->{expand_clause};
911 $args->{$type} = delete $args->{_}
913 my %has_clause = map +($_ => 1), @{$self->{clauses_of}{$type}};
914 return +{ "-${type}" => +{
916 my $val = $args->{$_};
917 if (defined($val) and my $exp = $ec->{"${type}.$_"}) {
918 if ((my (@exp) = $self->$exp($_ => $val)) == 1) {
923 } elsif ($has_clause{$_}) {
924 ($_ => $self->expand_expr($val))
932 sub _render_statement {
933 my ($self, $type, $args) = @_;
935 foreach my $clause (@{$self->{clauses_of}{$type}}) {
936 next unless my $clause_expr = $args->{$clause};
938 if (my $rdr = $self->{render_clause}{"${type}.${clause}"}) {
939 $self->$rdr($clause, $clause_expr, $args);
941 my $r = $self->render_aqt($clause_expr, 1);
942 next unless defined $r->[0] and length $r->[0];
943 $self->join_query_parts(' ',
944 { -keyword => $clause },
951 my $q = $self->join_query_parts(' ', @parts);
952 return $self->join_query_parts('',
953 (our $Render_Top_Level ? $q : ('(', $q, ')'))
958 my ($self, $raw) = @_;
960 return $op if grep $_->{$op}, @{$self}{qw(expand_op render_op)};
961 s/^-(?=.)//, s/\s+/_/g for $op;
966 my ($self, $expr) = @_;
967 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
968 return undef unless defined($expr);
969 if (ref($expr) eq 'HASH') {
970 return undef unless my $kc = keys %$expr;
972 return $self->_expand_logop(and => $expr);
974 my ($key, $value) = %$expr;
975 if ($key =~ /^-/ and $key =~ s/ [_\s]? \d+ $//x ) {
976 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
977 . "You probably wanted ...-and => [ $key => COND1, $key => COND2 ... ]";
979 return $self->_expand_hashpair($key, $value);
981 if (ref($expr) eq 'ARRAY') {
982 return $self->_expand_logop(lc($self->{logic}), $expr);
984 if (my $literal = is_literal_value($expr)) {
985 return +{ -literal => $literal };
987 if (!ref($expr) or Scalar::Util::blessed($expr)) {
988 return $self->_expand_scalar($expr);
993 sub _expand_hashpair {
994 my ($self, $k, $v) = @_;
995 unless (defined($k) and length($k)) {
996 if (defined($k) and my $literal = is_literal_value($v)) {
997 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
998 return { -literal => $literal };
1000 puke "Supplying an empty left hand side argument is not supported";
1003 return $self->_expand_hashpair_op($k, $v);
1004 } elsif ($k =~ /^\W+$/) {
1005 my ($lhs, @rhs) = ref($v) eq 'ARRAY' ? @$v : $v;
1006 return $self->_expand_op(
1007 -op, [ $k, $self->expand_expr($lhs, -ident), @rhs ]
1010 return $self->_expand_hashpair_ident($k, $v);
1013 sub _expand_hashpair_ident {
1014 my ($self, $k, $v) = @_;
1016 local our $Cur_Col_Meta = $k;
1018 # hash with multiple or no elements is andor
1020 if (ref($v) eq 'HASH' and keys %$v != 1) {
1021 return $self->_expand_logop(and => $v, $k);
1024 # undef needs to be re-sent with cmp to achieve IS/IS NOT NULL
1026 if (is_undef_value($v)) {
1027 return $self->_expand_hashpair_cmp($k => undef);
1030 # scalars and objects get expanded as whatever requested or values
1032 if (!ref($v) or Scalar::Util::blessed($v)) {
1033 return $self->_expand_hashpair_scalar($k, $v);
1036 # single key hashref is a hashtriple
1038 if (ref($v) eq 'HASH') {
1039 return $self->_expand_hashtriple($k, %$v);
1042 # arrayref needs re-engineering over the elements
1044 if (ref($v) eq 'ARRAY') {
1045 return $self->sqlfalse unless @$v;
1046 $self->_debug("ARRAY($k) means distribute over elements");
1048 $v->[0] =~ /^-(and|or)$/i
1049 ? (shift(@{$v = [ @$v ]}), $1)
1050 : lc($self->{logic} || 'OR')
1052 return $self->_expand_logop(
1057 if (my $literal = is_literal_value($v)) {
1058 unless (length $k) {
1059 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
1062 my ($sql, @bind) = @$literal;
1063 if ($self->{bindtype} eq 'columns') {
1065 $self->_assert_bindval_matches_bindtype($_);
1068 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
1073 sub _expand_scalar {
1074 my ($self, $expr) = @_;
1076 return $self->_expand_expr({ (our $Default_Scalar_To) => $expr });
1079 sub _expand_hashpair_scalar {
1080 my ($self, $k, $v) = @_;
1082 return $self->_expand_hashpair_cmp(
1083 $k, $self->_expand_scalar($v),
1087 sub _expand_hashpair_op {
1088 my ($self, $k, $v) = @_;
1090 $self->_assert_pass_injection_guard($k =~ /\A-(.*)\Z/s);
1092 my $op = $self->_normalize_op($k);
1094 my $wsop = join(' ', split '_', $op);
1096 my $is_special = List::Util::first { $wsop =~ $_->{regex} }
1097 @{$self->{special_ops}};
1101 # the old special op system requires illegality for top-level use
1104 (our $Expand_Depth) == 1
1108 $self->{disable_old_special_ops}
1109 and List::Util::first { $wsop =~ $_->{regex} } @BUILTIN_SPECIAL_OPS
1113 puke "Illegal use of top-level '-$wsop'"
1117 if (my $exp = $self->{expand}{$op}||$self->{expand_op}{$op}) {
1118 return $self->$exp($op, $v);
1121 if ($self->{render}{$op}) {
1122 return { "-${op}" => $v };
1125 # Ops prefixed with -not_ get converted
1127 if (my ($rest) = $op =~/^not_(.*)$/) {
1130 $self->_expand_expr({ "-${rest}", $v })
1136 # the old unary op system means we should touch nothing and let it work
1138 my $op = join(' ', split '_', $op);
1140 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1141 return { -op => [ $op, $v ] };
1145 my $type = $is_special || $self->{render_op}{$op} ? -op : -func;
1147 if ($self->{restore_old_unop_handling}) {
1154 and (keys %$v)[0] =~ /^-/
1155 and not $self->{render_op}{$op}
1164 if ($type eq -func and ref($v) eq 'ARRAY') {
1165 return $self->_expand_expr({ -func => [ $op, @$v ] });
1168 return $self->_expand_expr({ $type => [ $op, $v ] });
1171 sub _expand_hashpair_cmp {
1172 my ($self, $k, $v) = @_;
1173 $self->_expand_hashtriple($k, $self->{cmp}, $v);
1176 sub _expand_hashtriple {
1177 my ($self, $k, $vk, $vv) = @_;
1179 my $ik = $self->_expand_expr({ -ident => $k });
1181 my $op = $self->_normalize_op($vk);
1182 $self->_assert_pass_injection_guard($op);
1184 if ($op =~ s/ _? \d+ $//x ) {
1185 return $self->_expand_expr($k, { $vk, $vv });
1187 if (my $x = $self->{expand_op}{$op}) {
1188 local our $Cur_Col_Meta = $k;
1189 return $self->$x($op, $vv, $k);
1193 my $op = join(' ', split '_', $op);
1195 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
1196 return { -op => [ $op, $ik, $vv ] };
1198 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1202 { -op => [ $op, $vv ] }
1206 if (ref($vv) eq 'ARRAY') {
1208 my $logic = (defined($raw[0]) and $raw[0] =~ /^-(and|or)$/i)
1209 ? (shift(@raw), lc $1) : 'or';
1210 my @values = map +{ $vk => $_ }, @raw;
1212 $op =~ $self->{inequality_op}
1213 or $op =~ $self->{not_like_op}
1215 if (lc($logic) eq 'or' and @values > 1) {
1216 belch "A multi-element arrayref as an argument to the inequality op '${\uc(join ' ', split '_', $op)}' "
1217 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
1218 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
1223 # try to DWIM on equality operators
1224 return ($self->_dwim_op_to_is($op,
1225 "Supplying an empty arrayref to '%s' is deprecated",
1226 "operator '%s' applied on an empty array (field '$k')"
1227 ) ? $self->sqlfalse : $self->sqltrue);
1229 return $self->_expand_logop($logic => \@values, $k);
1231 if (is_undef_value($vv)) {
1232 my $is = ($self->_dwim_op_to_is($op,
1233 "Supplying an undefined argument to '%s' is deprecated",
1234 "unexpected operator '%s' with undef operand",
1235 ) ? 'is' : 'is not');
1237 return $self->_expand_hashpair($k => { $is, undef });
1239 local our $Cur_Col_Meta = $k;
1243 $self->_expand_expr($vv)
1247 sub _dwim_op_to_is {
1248 my ($self, $raw, $empty, $fail) = @_;
1250 my $op = $self->_normalize_op($raw);
1252 if ($op =~ /^not$/i) {
1255 if ($op =~ $self->{equality_op}) {
1258 if ($op =~ $self->{like_op}) {
1259 belch(sprintf $empty, uc(join ' ', split '_', $op));
1262 if ($op =~ $self->{inequality_op}) {
1265 if ($op =~ $self->{not_like_op}) {
1266 belch(sprintf $empty, uc(join ' ', split '_', $op));
1269 puke(sprintf $fail, $op);
1273 my ($self, undef, $args) = @_;
1274 my ($func, @args) = @$args;
1275 return +{ -func => [ $func, map $self->expand_expr($_), @args ] };
1279 my ($self, undef, $body) = @_;
1280 unless (defined($body) or (ref($body) and ref($body) eq 'ARRAY')) {
1281 puke "-ident requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
1283 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
1284 ref($body) ? @$body : $body;
1285 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
1286 unless ($self->{quote_char}) {
1287 $self->_assert_pass_injection_guard($_) for @parts;
1289 return +{ -ident => \@parts };
1293 +{ -bind => [ our $Cur_Col_Meta, $_[2] ] };
1297 my ($self, undef, $args) = @_;
1298 +{ -row => [ map $self->expand_expr($_), @$args ] };
1302 my ($self, undef, $args) = @_;
1303 my ($op, @opargs) = @$args;
1304 if (my $exp = $self->{expand_op}{$op}) {
1305 return $self->$exp($op, \@opargs);
1307 if (List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1308 return { -op => [ $op, @opargs ] };
1310 +{ -op => [ $op, map $self->expand_expr($_), @opargs ] };
1314 my ($self, undef, $v) = @_;
1316 return $self->_expand_expr($v);
1318 puke "-bool => undef not supported" unless defined($v);
1319 return $self->_expand_expr({ -ident => $v });
1323 my ($self, undef, $expr) = @_;
1325 ',', map $self->expand_expr($_),
1326 @{$expr->{-op}}[1..$#{$expr->{-op}}]
1327 ] } if ref($expr) eq 'HASH' and ($expr->{-op}||[''])->[0] eq ',';
1328 return +{ -op => [ ',',
1329 map $self->expand_expr($_),
1330 ref($expr) eq 'ARRAY' ? @$expr : $expr
1335 my ($self, $logop, $v, $k) = @_;
1336 $self->${\$self->{expand_op}{$logop}}($logop, $v, $k);
1339 sub _expand_op_andor {
1340 my ($self, $logop, $v, $k) = @_;
1342 $v = [ map +{ $k, $_ },
1344 ? (map +{ $_ => $v->{$_} }, sort keys %$v)
1348 if (ref($v) eq 'HASH') {
1349 return undef unless keys %$v;
1352 map $self->_expand_expr({ $_ => $v->{$_} }),
1356 if (ref($v) eq 'ARRAY') {
1357 $logop eq 'and' or $logop eq 'or' or puke "unknown logic: $logop";
1360 (ref($_) eq 'ARRAY' and @$_)
1361 or (ref($_) eq 'HASH' and %$_)
1367 while (my ($el) = splice @expr, 0, 1) {
1368 puke "Supplying an empty left hand side argument is not supported in array-pairs"
1369 unless defined($el) and length($el);
1370 my $elref = ref($el);
1372 local our $Expand_Depth = 0;
1373 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
1374 } elsif ($elref eq 'ARRAY') {
1375 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
1376 } elsif (my $l = is_literal_value($el)) {
1377 push @res, { -literal => $l };
1378 } elsif ($elref eq 'HASH') {
1379 local our $Expand_Depth = 0;
1380 push @res, grep defined, $self->_expand_expr($el) if %$el;
1386 # return $res[0] if @res == 1;
1387 return { -op => [ $logop, @res ] };
1393 my ($self, $op, $vv, $k) = @_;
1394 ($k, $vv) = @$vv unless defined $k;
1395 puke "$op can only take undef as argument"
1399 and exists($vv->{-value})
1400 and !defined($vv->{-value})
1402 return +{ -op => [ $op.'_null', $self->expand_expr($k, -ident) ] };
1405 sub _expand_between {
1406 my ($self, $op, $vv, $k) = @_;
1407 my @rhs = map $self->_expand_expr($_),
1408 ref($vv) eq 'ARRAY' ? @$vv : $vv;
1410 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
1412 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
1414 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1418 $self->expand_expr($k),
1419 map $self->expand_expr($_, -value), @rhs
1424 my ($self, $op, $vv, $k) = @_;
1425 if (my $literal = is_literal_value($vv)) {
1426 my ($sql, @bind) = @$literal;
1427 my $opened_sql = $self->_open_outer_paren($sql);
1429 $op, $self->expand_expr($k, -ident),
1430 { -literal => [ $opened_sql, @bind ] }
1434 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1435 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1436 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1437 . 'will emit the logically correct SQL instead of raising this exception)'
1439 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
1441 my @rhs = map $self->expand_expr($_, -value),
1442 map { defined($_) ? $_: puke($undef_err) }
1443 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
1444 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
1448 $self->expand_expr($k, -ident),
1454 my ($self, undef, $v) = @_;
1455 # DBIx::Class requires a nest warning to be emitted once but the private
1456 # method it overrode to do so no longer exists
1457 if ($self->{warn_once_on_nest}) {
1458 unless (our $Nest_Warned) {
1460 "-nest in search conditions is deprecated, you most probably wanted:\n"
1461 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
1466 return $self->_expand_expr($v);
1469 sub _expand_values {
1470 my ($self, undef, $values) = @_;
1471 return { -values => [
1474 ? $self->expand_expr($_)
1475 : +{ -row => [ map $self->expand_expr($_), @$_ ] }
1476 ), ref($values) eq 'ARRAY' ? @$values : $values
1480 sub _recurse_where {
1481 my ($self, $where) = @_;
1483 # Special case: top level simple string treated as literal
1485 my $where_exp = (ref($where)
1486 ? $self->_expand_select_clause_where(undef, $where)
1487 : { -literal => [ $where ] });
1489 # dispatch expanded expression
1491 my ($sql, @bind) = defined($where_exp) ? @{ $self->render_aqt($where_exp) || [] } : ();
1492 # DBIx::Class used to call _recurse_where in scalar context
1493 # something else might too...
1495 return ($sql, @bind);
1498 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
1504 my ($self, undef, $ident) = @_;
1506 return [ $self->_quote($ident) ];
1510 my ($self, undef, $values) = @_;
1511 return $self->join_query_parts('',
1513 $self->_render_op(undef, [ ',', @$values ]),
1519 my ($self, undef, $rest) = @_;
1520 my ($func, @args) = @$rest;
1521 return $self->join_query_parts('',
1522 $self->_sqlcase($func),
1523 $self->join_query_parts('',
1525 $self->join_query_parts(', ', @args),
1532 my ($self, undef, $bind) = @_;
1533 return [ '?', $self->_bindtype(@$bind) ];
1536 sub _render_literal {
1537 my ($self, undef, $literal) = @_;
1538 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1542 sub _render_keyword {
1543 my ($self, undef, $keyword) = @_;
1544 return [ $self->_sqlcase(
1545 ref($keyword) ? $$keyword : join ' ', split '_', $keyword
1550 my ($self, undef, $v) = @_;
1551 my ($op, @args) = @$v;
1552 if (my $r = $self->{render_op}{$op}) {
1553 return $self->$r($op, \@args);
1558 my $op = join(' ', split '_', $op);
1560 my $ss = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1561 if ($ss and @args > 1) {
1562 puke "Special op '${op}' requires first value to be identifier"
1563 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1564 my $k = join(($self->{name_sep}||'.'), @$ident);
1565 local our $Expand_Depth = 1;
1566 return [ $self->${\($ss->{handler})}($k, $op, $args[1]) ];
1568 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1569 return [ $self->${\($us->{handler})}($op, $args[0]) ];
1572 return $self->_render_unop_paren($op, \@args);
1576 return $self->_render_unop_prefix($op, \@args);
1578 return $self->_render_op_multop($op, \@args);
1584 sub _render_op_between {
1585 my ($self, $op, $args) = @_;
1586 my ($left, $low, $high) = @$args;
1589 puke "Single arg to between must be a literal"
1590 unless $low->{-literal};
1593 +($low, { -keyword => 'and' }, $high);
1596 return $self->join_query_parts(' ',
1597 '(', $left, { -keyword => $op }, @rh, ')',
1602 my ($self, $op, $args) = @_;
1603 my ($lhs, @rhs) = @$args;
1605 return $self->join_query_parts(' ',
1607 { -keyword => $op },
1608 $self->join_query_parts(' ',
1610 $self->join_query_parts(', ', @rhs),
1616 sub _render_op_andor {
1617 my ($self, $op, $args) = @_;
1618 return undef unless @$args;
1619 return $self->join_query_parts('', $args->[0]) if @$args == 1;
1620 my $inner = $self->_render_op_multop($op, $args);
1621 return undef unless defined($inner->[0]) and length($inner->[0]);
1622 return $self->join_query_parts(' ',
1627 sub _render_op_multop {
1628 my ($self, $op, $args) = @_;
1630 return undef unless @parts;
1631 return $self->render_aqt($parts[0]) if @parts == 1;
1632 my $join = ($op eq ','
1634 : { -keyword => " ${op} " }
1636 return $self->join_query_parts($join, @parts);
1639 sub _render_values {
1640 my ($self, undef, $values) = @_;
1641 my $inner = $self->join_query_parts(' ',
1642 { -keyword => 'values' },
1643 $self->join_query_parts(', ',
1644 ref($values) eq 'ARRAY' ? @$values : $values
1647 return $self->join_query_parts('',
1648 (our $Render_Top_Level ? $inner : ('(', $inner, ')'))
1652 sub join_query_parts {
1653 my ($self, $join, @parts) = @_;
1654 if (ref($join) eq 'HASH') {
1655 $join = $self->render_aqt($join)->[0];
1659 ? $self->render_aqt($_)
1660 : ((ref($_) eq 'ARRAY') ? $_ : [ $_ ])
1663 $self->{join_sql_parts}->(
1664 $join, grep defined && length, map $_->[0], @final
1666 (map @{$_}[1..$#$_], @final),
1670 sub _render_unop_paren {
1671 my ($self, $op, $v) = @_;
1672 return $self->join_query_parts('',
1673 '(', $self->_render_unop_prefix($op, $v), ')'
1677 sub _render_unop_prefix {
1678 my ($self, $op, $v) = @_;
1679 my $op_sql = $self->{restore_old_unop_handling}
1680 ? $self->_sqlcase($op)
1681 : { -keyword => $op };
1682 return $self->join_query_parts(' ',
1683 ($self->{restore_old_unop_handling}
1684 ? $self->_sqlcase($op)
1685 : { -keyword => \$op }),
1690 sub _render_unop_postfix {
1691 my ($self, $op, $v) = @_;
1692 return $self->join_query_parts(' ',
1693 $v->[0], { -keyword => $op },
1697 # Some databases (SQLite) treat col IN (1, 2) different from
1698 # col IN ( (1, 2) ). Use this to strip all outer parens while
1699 # adding them back in the corresponding method
1700 sub _open_outer_paren {
1701 my ($self, $sql) = @_;
1703 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1705 # there are closing parens inside, need the heavy duty machinery
1706 # to reevaluate the extraction starting from $sql (full reevaluation)
1707 if ($inner =~ /\)/) {
1708 require Text::Balanced;
1710 my (undef, $remainder) = do {
1711 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1713 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1716 # the entire expression needs to be a balanced bracketed thing
1717 # (after an extract no remainder sans trailing space)
1718 last if defined $remainder and $remainder =~ /\S/;
1727 sub _where_field_IN {
1728 my ($self, $k, $op, $vals) = @_;
1729 @{$self->_render_op_in(
1732 $self->expand_expr($k, -ident),
1733 map $self->expand_expr($_, -value),
1734 ref($vals) eq 'ARRAY' ? @$vals : $vals
1739 sub _where_field_BETWEEN {
1740 my ($self, $k, $op, $vals) = @_;
1741 @{$self->_render_op_between(
1743 [ $self->expand_expr($k, -ident), ref($vals) eq 'ARRAY' ? @$vals : $vals ]
1747 #======================================================================
1749 #======================================================================
1751 sub _expand_order_by {
1752 my ($self, $arg) = @_;
1754 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1756 return $self->expand_expr({ -list => $arg })
1757 if ref($arg) eq 'HASH' and ($arg->{-op}||[''])->[0] eq ',';
1759 my $expander = sub {
1760 my ($self, $dir, $expr) = @_;
1761 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1762 foreach my $arg (@to_expand) {
1766 and grep /^-(asc|desc)$/, keys %$arg
1768 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1772 defined($dir) ? { -op => [ $dir =~ /^-?(.*)$/ ,=> $_ ] } : $_
1774 map $self->expand_expr($_, -ident),
1775 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
1776 return undef unless @exp;
1777 return undef if @exp == 1 and not defined($exp[0]);
1778 return +{ -op => [ ',', @exp ] };
1781 local @{$self->{expand}}{qw(asc desc)} = (($expander) x 2);
1783 return $self->$expander(undef, $arg);
1787 my ($self, $arg) = @_;
1789 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
1791 my ($sql, @bind) = @{ $self->render_aqt($expanded) };
1793 return '' unless length($sql);
1795 my $final_sql = $self->_sqlcase(' order by ').$sql;
1797 return $final_sql unless wantarray;
1799 return ($final_sql, @bind);
1802 # _order_by no longer needs to call this so doesn't but DBIC uses it.
1804 sub _order_by_chunks {
1805 my ($self, $arg) = @_;
1807 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1809 my @res = $self->_chunkify_order_by($expanded);
1810 (ref() ? $_->[0] : $_) .= '' for @res;
1814 sub _chunkify_order_by {
1815 my ($self, $expanded) = @_;
1817 return grep length, @{ $self->render_aqt($expanded) }
1818 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1821 if (ref() eq 'HASH' and $_->{-op} and $_->{-op}[0] eq ',') {
1822 my ($comma, @list) = @{$_->{-op}};
1823 return map $self->_chunkify_order_by($_), @list;
1825 return $self->render_aqt($_);
1829 #======================================================================
1830 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1831 #======================================================================
1837 $self->expand_expr({ -list => $from }, -ident)
1842 #======================================================================
1844 #======================================================================
1846 # highly optimized, as it's called way too often
1848 # my ($self, $label) = @_;
1850 return '' unless defined $_[1];
1851 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1852 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1854 unless ($_[0]->{quote_char}) {
1855 if (ref($_[1]) eq 'ARRAY') {
1856 return join($_[0]->{name_sep}||'.', @{$_[1]});
1858 $_[0]->_assert_pass_injection_guard($_[1]);
1863 my $qref = ref $_[0]->{quote_char};
1865 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1866 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1867 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1869 my $esc = $_[0]->{escape_char} || $r;
1871 # parts containing * are naturally unquoted
1873 $_[0]->{name_sep}||'',
1877 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1879 (ref($_[1]) eq 'ARRAY'
1883 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1891 # Conversion, if applicable
1893 #my ($self, $arg) = @_;
1894 if (my $conv = $_[0]->{convert_where}) {
1895 return @{ $_[0]->join_query_parts('',
1896 $_[0]->_sqlcase($conv),
1905 #my ($self, $col, @vals) = @_;
1906 # called often - tighten code
1907 return $_[0]->{bindtype} eq 'columns'
1908 ? map {[$_[1], $_]} @_[2 .. $#_]
1913 # Dies if any element of @bind is not in [colname => value] format
1914 # if bindtype is 'columns'.
1915 sub _assert_bindval_matches_bindtype {
1916 # my ($self, @bind) = @_;
1918 if ($self->{bindtype} eq 'columns') {
1920 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1921 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1927 # Fix SQL case, if so requested
1929 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1930 # don't touch the argument ... crooked logic, but let's not change it!
1931 return $_[0]->{case} ? $_[1] : uc($_[1]);
1934 #======================================================================
1935 # DISPATCHING FROM REFKIND
1936 #======================================================================
1939 my ($self, $data) = @_;
1941 return 'UNDEF' unless defined $data;
1943 # blessed objects are treated like scalars
1944 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1946 return 'SCALAR' unless $ref;
1949 while ($ref eq 'REF') {
1951 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1955 return ($ref||'SCALAR') . ('REF' x $n_steps);
1959 my ($self, $data) = @_;
1960 my @try = ($self->_refkind($data));
1961 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1962 push @try, 'FALLBACK';
1966 sub _METHOD_FOR_refkind {
1967 my ($self, $meth_prefix, $data) = @_;
1970 for (@{$self->_try_refkind($data)}) {
1971 $method = $self->can($meth_prefix."_".$_)
1975 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1979 sub _SWITCH_refkind {
1980 my ($self, $data, $dispatch_table) = @_;
1983 for (@{$self->_try_refkind($data)}) {
1984 $coderef = $dispatch_table->{$_}
1988 puke "no dispatch entry for ".$self->_refkind($data)
1997 #======================================================================
1998 # VALUES, GENERATE, AUTOLOAD
1999 #======================================================================
2001 # LDNOTE: original code from nwiger, didn't touch code in that section
2002 # I feel the AUTOLOAD stuff should not be the default, it should
2003 # only be activated on explicit demand by user.
2007 my $data = shift || return;
2008 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
2009 unless ref $data eq 'HASH';
2012 foreach my $k (sort keys %$data) {
2013 my $v = $data->{$k};
2014 $self->_SWITCH_refkind($v, {
2016 if ($self->{array_datatypes}) { # array datatype
2017 push @all_bind, $self->_bindtype($k, $v);
2019 else { # literal SQL with bind
2020 my ($sql, @bind) = @$v;
2021 $self->_assert_bindval_matches_bindtype(@bind);
2022 push @all_bind, @bind;
2025 ARRAYREFREF => sub { # literal SQL with bind
2026 my ($sql, @bind) = @${$v};
2027 $self->_assert_bindval_matches_bindtype(@bind);
2028 push @all_bind, @bind;
2030 SCALARREF => sub { # literal SQL without bind
2032 SCALAR_or_UNDEF => sub {
2033 push @all_bind, $self->_bindtype($k, $v);
2044 my(@sql, @sqlq, @sqlv);
2048 if ($ref eq 'HASH') {
2049 for my $k (sort keys %$_) {
2052 my $label = $self->_quote($k);
2053 if ($r eq 'ARRAY') {
2054 # literal SQL with bind
2055 my ($sql, @bind) = @$v;
2056 $self->_assert_bindval_matches_bindtype(@bind);
2057 push @sqlq, "$label = $sql";
2059 } elsif ($r eq 'SCALAR') {
2060 # literal SQL without bind
2061 push @sqlq, "$label = $$v";
2063 push @sqlq, "$label = ?";
2064 push @sqlv, $self->_bindtype($k, $v);
2067 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
2068 } elsif ($ref eq 'ARRAY') {
2069 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
2072 if ($r eq 'ARRAY') { # literal SQL with bind
2073 my ($sql, @bind) = @$v;
2074 $self->_assert_bindval_matches_bindtype(@bind);
2077 } elsif ($r eq 'SCALAR') { # literal SQL without bind
2078 # embedded literal SQL
2085 push @sql, '(' . join(', ', @sqlq) . ')';
2086 } elsif ($ref eq 'SCALAR') {
2090 # strings get case twiddled
2091 push @sql, $self->_sqlcase($_);
2095 my $sql = join ' ', @sql;
2097 # this is pretty tricky
2098 # if ask for an array, return ($stmt, @bind)
2099 # otherwise, s/?/shift @sqlv/ to put it inline
2101 return ($sql, @sqlv);
2103 1 while $sql =~ s/\?/my $d = shift(@sqlv);
2104 ref $d ? $d->[1] : $d/e;
2113 # This allows us to check for a local, then _form, attr
2115 my($name) = $AUTOLOAD =~ /.*::(.+)/;
2116 puke "AUTOLOAD invoked for method name ${name} and allow_autoload option not set" unless $self->{allow_autoload};
2117 return $self->generate($name, @_);
2128 SQL::Abstract - Generate SQL from Perl data structures
2134 my $sql = SQL::Abstract->new;
2136 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
2138 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
2140 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
2142 my($stmt, @bind) = $sql->delete($table, \%where);
2144 # Then, use these in your DBI statements
2145 my $sth = $dbh->prepare($stmt);
2146 $sth->execute(@bind);
2148 # Just generate the WHERE clause
2149 my($stmt, @bind) = $sql->where(\%where, $order);
2151 # Return values in the same order, for hashed queries
2152 # See PERFORMANCE section for more details
2153 my @bind = $sql->values(\%fieldvals);
2157 This module was inspired by the excellent L<DBIx::Abstract>.
2158 However, in using that module I found that what I really wanted
2159 to do was generate SQL, but still retain complete control over my
2160 statement handles and use the DBI interface. So, I set out to
2161 create an abstract SQL generation module.
2163 While based on the concepts used by L<DBIx::Abstract>, there are
2164 several important differences, especially when it comes to WHERE
2165 clauses. I have modified the concepts used to make the SQL easier
2166 to generate from Perl data structures and, IMO, more intuitive.
2167 The underlying idea is for this module to do what you mean, based
2168 on the data structures you provide it. The big advantage is that
2169 you don't have to modify your code every time your data changes,
2170 as this module figures it out.
2172 To begin with, an SQL INSERT is as easy as just specifying a hash
2173 of C<key=value> pairs:
2176 name => 'Jimbo Bobson',
2177 phone => '123-456-7890',
2178 address => '42 Sister Lane',
2179 city => 'St. Louis',
2180 state => 'Louisiana',
2183 The SQL can then be generated with this:
2185 my($stmt, @bind) = $sql->insert('people', \%data);
2187 Which would give you something like this:
2189 $stmt = "INSERT INTO people
2190 (address, city, name, phone, state)
2191 VALUES (?, ?, ?, ?, ?)";
2192 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
2193 '123-456-7890', 'Louisiana');
2195 These are then used directly in your DBI code:
2197 my $sth = $dbh->prepare($stmt);
2198 $sth->execute(@bind);
2200 =head2 Inserting and Updating Arrays
2202 If your database has array types (like for example Postgres),
2203 activate the special option C<< array_datatypes => 1 >>
2204 when creating the C<SQL::Abstract> object.
2205 Then you may use an arrayref to insert and update database array types:
2207 my $sql = SQL::Abstract->new(array_datatypes => 1);
2209 planets => [qw/Mercury Venus Earth Mars/]
2212 my($stmt, @bind) = $sql->insert('solar_system', \%data);
2216 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
2218 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
2221 =head2 Inserting and Updating SQL
2223 In order to apply SQL functions to elements of your C<%data> you may
2224 specify a reference to an arrayref for the given hash value. For example,
2225 if you need to execute the Oracle C<to_date> function on a value, you can
2226 say something like this:
2230 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
2233 The first value in the array is the actual SQL. Any other values are
2234 optional and would be included in the bind values array. This gives
2237 my($stmt, @bind) = $sql->insert('people', \%data);
2239 $stmt = "INSERT INTO people (name, date_entered)
2240 VALUES (?, to_date(?,'MM/DD/YYYY'))";
2241 @bind = ('Bill', '03/02/2003');
2243 An UPDATE is just as easy, all you change is the name of the function:
2245 my($stmt, @bind) = $sql->update('people', \%data);
2247 Notice that your C<%data> isn't touched; the module will generate
2248 the appropriately quirky SQL for you automatically. Usually you'll
2249 want to specify a WHERE clause for your UPDATE, though, which is
2250 where handling C<%where> hashes comes in handy...
2252 =head2 Complex where statements
2254 This module can generate pretty complicated WHERE statements
2255 easily. For example, simple C<key=value> pairs are taken to mean
2256 equality, and if you want to see if a field is within a set
2257 of values, you can use an arrayref. Let's say we wanted to
2258 SELECT some data based on this criteria:
2261 requestor => 'inna',
2262 worker => ['nwiger', 'rcwe', 'sfz'],
2263 status => { '!=', 'completed' }
2266 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
2268 The above would give you something like this:
2270 $stmt = "SELECT * FROM tickets WHERE
2271 ( requestor = ? ) AND ( status != ? )
2272 AND ( worker = ? OR worker = ? OR worker = ? )";
2273 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
2275 Which you could then use in DBI code like so:
2277 my $sth = $dbh->prepare($stmt);
2278 $sth->execute(@bind);
2284 The methods are simple. There's one for every major SQL operation,
2285 and a constructor you use first. The arguments are specified in a
2286 similar order for each method (table, then fields, then a where
2287 clause) to try and simplify things.
2289 =head2 new(option => 'value')
2291 The C<new()> function takes a list of options and values, and returns
2292 a new B<SQL::Abstract> object which can then be used to generate SQL
2293 through the methods below. The options accepted are:
2299 If set to 'lower', then SQL will be generated in all lowercase. By
2300 default SQL is generated in "textbook" case meaning something like:
2302 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
2304 Any setting other than 'lower' is ignored.
2308 This determines what the default comparison operator is. By default
2309 it is C<=>, meaning that a hash like this:
2311 %where = (name => 'nwiger', email => 'nate@wiger.org');
2313 Will generate SQL like this:
2315 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
2317 However, you may want loose comparisons by default, so if you set
2318 C<cmp> to C<like> you would get SQL such as:
2320 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
2322 You can also override the comparison on an individual basis - see
2323 the huge section on L</"WHERE CLAUSES"> at the bottom.
2325 =item sqltrue, sqlfalse
2327 Expressions for inserting boolean values within SQL statements.
2328 By default these are C<1=1> and C<1=0>. They are used
2329 by the special operators C<-in> and C<-not_in> for generating
2330 correct SQL even when the argument is an empty array (see below).
2334 This determines the default logical operator for multiple WHERE
2335 statements in arrays or hashes. If absent, the default logic is "or"
2336 for arrays, and "and" for hashes. This means that a WHERE
2340 event_date => {'>=', '2/13/99'},
2341 event_date => {'<=', '4/24/03'},
2344 will generate SQL like this:
2346 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
2348 This is probably not what you want given this query, though (look
2349 at the dates). To change the "OR" to an "AND", simply specify:
2351 my $sql = SQL::Abstract->new(logic => 'and');
2353 Which will change the above C<WHERE> to:
2355 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
2357 The logic can also be changed locally by inserting
2358 a modifier in front of an arrayref:
2360 @where = (-and => [event_date => {'>=', '2/13/99'},
2361 event_date => {'<=', '4/24/03'} ]);
2363 See the L</"WHERE CLAUSES"> section for explanations.
2367 This will automatically convert comparisons using the specified SQL
2368 function for both column and value. This is mostly used with an argument
2369 of C<upper> or C<lower>, so that the SQL will have the effect of
2370 case-insensitive "searches". For example, this:
2372 $sql = SQL::Abstract->new(convert => 'upper');
2373 %where = (keywords => 'MaKe iT CAse inSeNSItive');
2375 Will turn out the following SQL:
2377 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
2379 The conversion can be C<upper()>, C<lower()>, or any other SQL function
2380 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
2381 not validate this option; it will just pass through what you specify verbatim).
2385 This is a kludge because many databases suck. For example, you can't
2386 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
2387 Instead, you have to use C<bind_param()>:
2389 $sth->bind_param(1, 'reg data');
2390 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
2392 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
2393 which loses track of which field each slot refers to. Fear not.
2395 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
2396 Currently, you can specify either C<normal> (default) or C<columns>. If you
2397 specify C<columns>, you will get an array that looks like this:
2399 my $sql = SQL::Abstract->new(bindtype => 'columns');
2400 my($stmt, @bind) = $sql->insert(...);
2403 [ 'column1', 'value1' ],
2404 [ 'column2', 'value2' ],
2405 [ 'column3', 'value3' ],
2408 You can then iterate through this manually, using DBI's C<bind_param()>.
2410 $sth->prepare($stmt);
2413 my($col, $data) = @$_;
2414 if ($col eq 'details' || $col eq 'comments') {
2415 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
2416 } elsif ($col eq 'image') {
2417 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
2419 $sth->bind_param($i, $data);
2423 $sth->execute; # execute without @bind now
2425 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
2426 Basically, the advantage is still that you don't have to care which fields
2427 are or are not included. You could wrap that above C<for> loop in a simple
2428 sub called C<bind_fields()> or something and reuse it repeatedly. You still
2429 get a layer of abstraction over manual SQL specification.
2431 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
2432 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
2433 will expect the bind values in this format.
2437 This is the character that a table or column name will be quoted
2438 with. By default this is an empty string, but you could set it to
2439 the character C<`>, to generate SQL like this:
2441 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
2443 Alternatively, you can supply an array ref of two items, the first being the left
2444 hand quote character, and the second the right hand quote character. For
2445 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
2446 that generates SQL like this:
2448 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
2450 Quoting is useful if you have tables or columns names that are reserved
2451 words in your database's SQL dialect.
2455 This is the character that will be used to escape L</quote_char>s appearing
2456 in an identifier before it has been quoted.
2458 The parameter default in case of a single L</quote_char> character is the quote
2461 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
2462 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
2463 of the B<opening (left)> L</quote_char> within the identifier are currently left
2464 untouched. The default for opening-closing-style quotes may change in future
2465 versions, thus you are B<strongly encouraged> to specify the escape character
2470 This is the character that separates a table and column name. It is
2471 necessary to specify this when the C<quote_char> option is selected,
2472 so that tables and column names can be individually quoted like this:
2474 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2476 =item injection_guard
2478 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2479 column name specified in a query structure. This is a safety mechanism to avoid
2480 injection attacks when mishandling user input e.g.:
2482 my %condition_as_column_value_pairs = get_values_from_user();
2483 $sqla->select( ... , \%condition_as_column_value_pairs );
2485 If the expression matches an exception is thrown. Note that literal SQL
2486 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2488 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2490 =item array_datatypes
2492 When this option is true, arrayrefs in INSERT or UPDATE are
2493 interpreted as array datatypes and are passed directly
2495 When this option is false, arrayrefs are interpreted
2496 as literal SQL, just like refs to arrayrefs
2497 (but this behavior is for backwards compatibility; when writing
2498 new queries, use the "reference to arrayref" syntax
2504 Takes a reference to a list of "special operators"
2505 to extend the syntax understood by L<SQL::Abstract>.
2506 See section L</"SPECIAL OPERATORS"> for details.
2510 Takes a reference to a list of "unary operators"
2511 to extend the syntax understood by L<SQL::Abstract>.
2512 See section L</"UNARY OPERATORS"> for details.
2518 =head2 insert($table, \@values || \%fieldvals, \%options)
2520 This is the simplest function. You simply give it a table name
2521 and either an arrayref of values or hashref of field/value pairs.
2522 It returns an SQL INSERT statement and a list of bind values.
2523 See the sections on L</"Inserting and Updating Arrays"> and
2524 L</"Inserting and Updating SQL"> for information on how to insert
2525 with those data types.
2527 The optional C<\%options> hash reference may contain additional
2528 options to generate the insert SQL. Currently supported options
2535 Takes either a scalar of raw SQL fields, or an array reference of
2536 field names, and adds on an SQL C<RETURNING> statement at the end.
2537 This allows you to return data generated by the insert statement
2538 (such as row IDs) without performing another C<SELECT> statement.
2539 Note, however, this is not part of the SQL standard and may not
2540 be supported by all database engines.
2544 =head2 update($table, \%fieldvals, \%where, \%options)
2546 This takes a table, hashref of field/value pairs, and an optional
2547 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2549 See the sections on L</"Inserting and Updating Arrays"> and
2550 L</"Inserting and Updating SQL"> for information on how to insert
2551 with those data types.
2553 The optional C<\%options> hash reference may contain additional
2554 options to generate the update SQL. Currently supported options
2561 See the C<returning> option to
2562 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2566 =head2 select($source, $fields, $where, $order)
2568 This returns a SQL SELECT statement and associated list of bind values, as
2569 specified by the arguments:
2575 Specification of the 'FROM' part of the statement.
2576 The argument can be either a plain scalar (interpreted as a table
2577 name, will be quoted), or an arrayref (interpreted as a list
2578 of table names, joined by commas, quoted), or a scalarref
2579 (literal SQL, not quoted).
2583 Specification of the list of fields to retrieve from
2585 The argument can be either an arrayref (interpreted as a list
2586 of field names, will be joined by commas and quoted), or a
2587 plain scalar (literal SQL, not quoted).
2588 Please observe that this API is not as flexible as that of
2589 the first argument C<$source>, for backwards compatibility reasons.
2593 Optional argument to specify the WHERE part of the query.
2594 The argument is most often a hashref, but can also be
2595 an arrayref or plain scalar --
2596 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2600 Optional argument to specify the ORDER BY part of the query.
2601 The argument can be a scalar, a hashref or an arrayref
2602 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2608 =head2 delete($table, \%where, \%options)
2610 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2611 It returns an SQL DELETE statement and list of bind values.
2613 The optional C<\%options> hash reference may contain additional
2614 options to generate the delete SQL. Currently supported options
2621 See the C<returning> option to
2622 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2626 =head2 where(\%where, $order)
2628 This is used to generate just the WHERE clause. For example,
2629 if you have an arbitrary data structure and know what the
2630 rest of your SQL is going to look like, but want an easy way
2631 to produce a WHERE clause, use this. It returns an SQL WHERE
2632 clause and list of bind values.
2635 =head2 values(\%data)
2637 This just returns the values from the hash C<%data>, in the same
2638 order that would be returned from any of the other above queries.
2639 Using this allows you to markedly speed up your queries if you
2640 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2642 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2644 Warning: This is an experimental method and subject to change.
2646 This returns arbitrarily generated SQL. It's a really basic shortcut.
2647 It will return two different things, depending on return context:
2649 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2650 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2652 These would return the following:
2654 # First calling form
2655 $stmt = "CREATE TABLE test (?, ?)";
2656 @bind = (field1, field2);
2658 # Second calling form
2659 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2661 Depending on what you're trying to do, it's up to you to choose the correct
2662 format. In this example, the second form is what you would want.
2666 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2670 ALTER SESSION SET nls_date_format = 'MM/YY'
2672 You get the idea. Strings get their case twiddled, but everything
2673 else remains verbatim.
2675 =head1 EXPORTABLE FUNCTIONS
2677 =head2 is_plain_value
2679 Determines if the supplied argument is a plain value as understood by this
2684 =item * The value is C<undef>
2686 =item * The value is a non-reference
2688 =item * The value is an object with stringification overloading
2690 =item * The value is of the form C<< { -value => $anything } >>
2694 On failure returns C<undef>, on success returns a B<scalar> reference
2695 to the original supplied argument.
2701 The stringification overloading detection is rather advanced: it takes
2702 into consideration not only the presence of a C<""> overload, but if that
2703 fails also checks for enabled
2704 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2705 on either C<0+> or C<bool>.
2707 Unfortunately testing in the field indicates that this
2708 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2709 but only when very large numbers of stringifying objects are involved.
2710 At the time of writing ( Sep 2014 ) there is no clear explanation of
2711 the direct cause, nor is there a manageably small test case that reliably
2712 reproduces the problem.
2714 If you encounter any of the following exceptions in B<random places within
2715 your application stack> - this module may be to blame:
2717 Operation "ne": no method found,
2718 left argument in overloaded package <something>,
2719 right argument in overloaded package <something>
2723 Stub found while resolving method "???" overloading """" in package <something>
2725 If you fall victim to the above - please attempt to reduce the problem
2726 to something that could be sent to the L<SQL::Abstract developers
2727 |DBIx::Class/GETTING HELP/SUPPORT>
2728 (either publicly or privately). As a workaround in the meantime you can
2729 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2730 value, which will most likely eliminate your problem (at the expense of
2731 not being able to properly detect exotic forms of stringification).
2733 This notice and environment variable will be removed in a future version,
2734 as soon as the underlying problem is found and a reliable workaround is
2739 =head2 is_literal_value
2741 Determines if the supplied argument is a literal value as understood by this
2746 =item * C<\$sql_string>
2748 =item * C<\[ $sql_string, @bind_values ]>
2752 On failure returns C<undef>, on success returns an B<array> reference
2753 containing the unpacked version of the supplied literal SQL and bind values.
2755 =head2 is_undef_value
2757 Tests for undef, whether expanded or not.
2759 =head1 WHERE CLAUSES
2763 This module uses a variation on the idea from L<DBIx::Abstract>. It
2764 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2765 module is that things in arrays are OR'ed, and things in hashes
2768 The easiest way to explain is to show lots of examples. After
2769 each C<%where> hash shown, it is assumed you used:
2771 my($stmt, @bind) = $sql->where(\%where);
2773 However, note that the C<%where> hash can be used directly in any
2774 of the other functions as well, as described above.
2776 =head2 Key-value pairs
2778 So, let's get started. To begin, a simple hash:
2782 status => 'completed'
2785 Is converted to SQL C<key = val> statements:
2787 $stmt = "WHERE user = ? AND status = ?";
2788 @bind = ('nwiger', 'completed');
2790 One common thing I end up doing is having a list of values that
2791 a field can be in. To do this, simply specify a list inside of
2796 status => ['assigned', 'in-progress', 'pending'];
2799 This simple code will create the following:
2801 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2802 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2804 A field associated to an empty arrayref will be considered a
2805 logical false and will generate 0=1.
2807 =head2 Tests for NULL values
2809 If the value part is C<undef> then this is converted to SQL <IS NULL>
2818 $stmt = "WHERE user = ? AND status IS NULL";
2821 To test if a column IS NOT NULL:
2825 status => { '!=', undef },
2828 =head2 Specific comparison operators
2830 If you want to specify a different type of operator for your comparison,
2831 you can use a hashref for a given column:
2835 status => { '!=', 'completed' }
2838 Which would generate:
2840 $stmt = "WHERE user = ? AND status != ?";
2841 @bind = ('nwiger', 'completed');
2843 To test against multiple values, just enclose the values in an arrayref:
2845 status => { '=', ['assigned', 'in-progress', 'pending'] };
2847 Which would give you:
2849 "WHERE status = ? OR status = ? OR status = ?"
2852 The hashref can also contain multiple pairs, in which case it is expanded
2853 into an C<AND> of its elements:
2857 status => { '!=', 'completed', -not_like => 'pending%' }
2860 # Or more dynamically, like from a form
2861 $where{user} = 'nwiger';
2862 $where{status}{'!='} = 'completed';
2863 $where{status}{'-not_like'} = 'pending%';
2865 # Both generate this
2866 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2867 @bind = ('nwiger', 'completed', 'pending%');
2870 To get an OR instead, you can combine it with the arrayref idea:
2874 priority => [ { '=', 2 }, { '>', 5 } ]
2877 Which would generate:
2879 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2880 @bind = ('2', '5', 'nwiger');
2882 If you want to include literal SQL (with or without bind values), just use a
2883 scalar reference or reference to an arrayref as the value:
2886 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2887 date_expires => { '<' => \"now()" }
2890 Which would generate:
2892 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2893 @bind = ('11/26/2008');
2896 =head2 Logic and nesting operators
2898 In the example above,
2899 there is a subtle trap if you want to say something like
2900 this (notice the C<AND>):
2902 WHERE priority != ? AND priority != ?
2904 Because, in Perl you I<can't> do this:
2906 priority => { '!=' => 2, '!=' => 1 }
2908 As the second C<!=> key will obliterate the first. The solution
2909 is to use the special C<-modifier> form inside an arrayref:
2911 priority => [ -and => {'!=', 2},
2915 Normally, these would be joined by C<OR>, but the modifier tells it
2916 to use C<AND> instead. (Hint: You can use this in conjunction with the
2917 C<logic> option to C<new()> in order to change the way your queries
2918 work by default.) B<Important:> Note that the C<-modifier> goes
2919 B<INSIDE> the arrayref, as an extra first element. This will
2920 B<NOT> do what you think it might:
2922 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2924 Here is a quick list of equivalencies, since there is some overlap:
2927 status => {'!=', 'completed', 'not like', 'pending%' }
2928 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2931 status => {'=', ['assigned', 'in-progress']}
2932 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2933 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2937 =head2 Special operators: IN, BETWEEN, etc.
2939 You can also use the hashref format to compare a list of fields using the
2940 C<IN> comparison operator, by specifying the list as an arrayref:
2943 status => 'completed',
2944 reportid => { -in => [567, 2335, 2] }
2947 Which would generate:
2949 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2950 @bind = ('completed', '567', '2335', '2');
2952 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2955 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2956 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2957 'sqltrue' (by default: C<1=1>).
2959 In addition to the array you can supply a chunk of literal sql or
2960 literal sql with bind:
2963 customer => { -in => \[
2964 'SELECT cust_id FROM cust WHERE balance > ?',
2967 status => { -in => \'SELECT status_codes FROM states' },
2973 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2974 AND status IN ( SELECT status_codes FROM states )
2978 Finally, if the argument to C<-in> is not a reference, it will be
2979 treated as a single-element array.
2981 Another pair of operators is C<-between> and C<-not_between>,
2982 used with an arrayref of two values:
2986 completion_date => {
2987 -not_between => ['2002-10-01', '2003-02-06']
2993 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2995 Just like with C<-in> all plausible combinations of literal SQL
2999 start0 => { -between => [ 1, 2 ] },
3000 start1 => { -between => \["? AND ?", 1, 2] },
3001 start2 => { -between => \"lower(x) AND upper(y)" },
3002 start3 => { -between => [
3004 \["upper(?)", 'stuff' ],
3011 ( start0 BETWEEN ? AND ? )
3012 AND ( start1 BETWEEN ? AND ? )
3013 AND ( start2 BETWEEN lower(x) AND upper(y) )
3014 AND ( start3 BETWEEN lower(x) AND upper(?) )
3016 @bind = (1, 2, 1, 2, 'stuff');
3019 These are the two builtin "special operators"; but the
3020 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
3022 =head2 Unary operators: bool
3024 If you wish to test against boolean columns or functions within your
3025 database you can use the C<-bool> and C<-not_bool> operators. For
3026 example to test the column C<is_user> being true and the column
3027 C<is_enabled> being false you would use:-
3031 -not_bool => 'is_enabled',
3036 WHERE is_user AND NOT is_enabled
3038 If a more complex combination is required, testing more conditions,
3039 then you should use the and/or operators:-
3044 -not_bool => { two=> { -rlike => 'bar' } },
3045 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
3056 (NOT ( three = ? OR three > ? ))
3059 =head2 Nested conditions, -and/-or prefixes
3061 So far, we've seen how multiple conditions are joined with a top-level
3062 C<AND>. We can change this by putting the different conditions we want in
3063 hashes and then putting those hashes in an array. For example:
3068 status => { -like => ['pending%', 'dispatched'] },
3072 status => 'unassigned',
3076 This data structure would create the following:
3078 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
3079 OR ( user = ? AND status = ? ) )";
3080 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
3083 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
3084 to change the logic inside:
3090 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
3091 -or => { workhrs => {'<', 50}, geo => 'EURO' },
3098 $stmt = "WHERE ( user = ?
3099 AND ( ( workhrs > ? AND geo = ? )
3100 OR ( workhrs < ? OR geo = ? ) ) )";
3101 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
3103 =head3 Algebraic inconsistency, for historical reasons
3105 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
3106 operator goes C<outside> of the nested structure; whereas when connecting
3107 several constraints on one column, the C<-and> operator goes
3108 C<inside> the arrayref. Here is an example combining both features:
3111 -and => [a => 1, b => 2],
3112 -or => [c => 3, d => 4],
3113 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
3118 WHERE ( ( ( a = ? AND b = ? )
3119 OR ( c = ? OR d = ? )
3120 OR ( e LIKE ? AND e LIKE ? ) ) )
3122 This difference in syntax is unfortunate but must be preserved for
3123 historical reasons. So be careful: the two examples below would
3124 seem algebraically equivalent, but they are not
3127 { -like => 'foo%' },
3128 { -like => '%bar' },
3130 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
3133 { col => { -like => 'foo%' } },
3134 { col => { -like => '%bar' } },
3136 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
3139 =head2 Literal SQL and value type operators
3141 The basic premise of SQL::Abstract is that in WHERE specifications the "left
3142 side" is a column name and the "right side" is a value (normally rendered as
3143 a placeholder). This holds true for both hashrefs and arrayref pairs as you
3144 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
3145 alter this behavior. There are several ways of doing so.
3149 This is a virtual operator that signals the string to its right side is an
3150 identifier (a column name) and not a value. For example to compare two
3151 columns you would write:
3154 priority => { '<', 2 },
3155 requestor => { -ident => 'submitter' },
3160 $stmt = "WHERE priority < ? AND requestor = submitter";
3163 If you are maintaining legacy code you may see a different construct as
3164 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
3169 This is a virtual operator that signals that the construct to its right side
3170 is a value to be passed to DBI. This is for example necessary when you want
3171 to write a where clause against an array (for RDBMS that support such
3172 datatypes). For example:
3175 array => { -value => [1, 2, 3] }
3180 $stmt = 'WHERE array = ?';
3181 @bind = ([1, 2, 3]);
3183 Note that if you were to simply say:
3189 the result would probably not be what you wanted:
3191 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
3196 Finally, sometimes only literal SQL will do. To include a random snippet
3197 of SQL verbatim, you specify it as a scalar reference. Consider this only
3198 as a last resort. Usually there is a better way. For example:
3201 priority => { '<', 2 },
3202 requestor => { -in => \'(SELECT name FROM hitmen)' },
3207 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
3210 Note that in this example, you only get one bind parameter back, since
3211 the verbatim SQL is passed as part of the statement.
3215 Never use untrusted input as a literal SQL argument - this is a massive
3216 security risk (there is no way to check literal snippets for SQL
3217 injections and other nastyness). If you need to deal with untrusted input
3218 use literal SQL with placeholders as described next.
3220 =head3 Literal SQL with placeholders and bind values (subqueries)
3222 If the literal SQL to be inserted has placeholders and bind values,
3223 use a reference to an arrayref (yes this is a double reference --
3224 not so common, but perfectly legal Perl). For example, to find a date
3225 in Postgres you can use something like this:
3228 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
3233 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
3236 Note that you must pass the bind values in the same format as they are returned
3237 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
3238 to C<columns>, you must provide the bind values in the
3239 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
3240 scalar value; most commonly the column name, but you can use any scalar value
3241 (including references and blessed references), L<SQL::Abstract> will simply
3242 pass it through intact. So if C<bindtype> is set to C<columns> the above
3243 example will look like:
3246 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
3249 Literal SQL is especially useful for nesting parenthesized clauses in the
3250 main SQL query. Here is a first example:
3252 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
3256 bar => \["IN ($sub_stmt)" => @sub_bind],
3261 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
3262 WHERE c2 < ? AND c3 LIKE ?))";
3263 @bind = (1234, 100, "foo%");
3265 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
3266 are expressed in the same way. Of course the C<$sub_stmt> and
3267 its associated bind values can be generated through a former call
3270 my ($sub_stmt, @sub_bind)
3271 = $sql->select("t1", "c1", {c2 => {"<" => 100},
3272 c3 => {-like => "foo%"}});
3275 bar => \["> ALL ($sub_stmt)" => @sub_bind],
3278 In the examples above, the subquery was used as an operator on a column;
3279 but the same principle also applies for a clause within the main C<%where>
3280 hash, like an EXISTS subquery:
3282 my ($sub_stmt, @sub_bind)
3283 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
3284 my %where = ( -and => [
3286 \["EXISTS ($sub_stmt)" => @sub_bind],
3291 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
3292 WHERE c1 = ? AND c2 > t0.c0))";
3296 Observe that the condition on C<c2> in the subquery refers to
3297 column C<t0.c0> of the main query: this is I<not> a bind
3298 value, so we have to express it through a scalar ref.
3299 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
3300 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
3301 what we wanted here.
3303 Finally, here is an example where a subquery is used
3304 for expressing unary negation:
3306 my ($sub_stmt, @sub_bind)
3307 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
3308 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
3310 lname => {like => '%son%'},
3311 \["NOT ($sub_stmt)" => @sub_bind],
3316 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
3317 @bind = ('%son%', 10, 20)
3319 =head3 Deprecated usage of Literal SQL
3321 Below are some examples of archaic use of literal SQL. It is shown only as
3322 reference for those who deal with legacy code. Each example has a much
3323 better, cleaner and safer alternative that users should opt for in new code.
3329 my %where = ( requestor => \'IS NOT NULL' )
3331 $stmt = "WHERE requestor IS NOT NULL"
3333 This used to be the way of generating NULL comparisons, before the handling
3334 of C<undef> got formalized. For new code please use the superior syntax as
3335 described in L</Tests for NULL values>.
3339 my %where = ( requestor => \'= submitter' )
3341 $stmt = "WHERE requestor = submitter"
3343 This used to be the only way to compare columns. Use the superior L</-ident>
3344 method for all new code. For example an identifier declared in such a way
3345 will be properly quoted if L</quote_char> is properly set, while the legacy
3346 form will remain as supplied.
3350 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
3352 $stmt = "WHERE completed > ? AND is_ready"
3353 @bind = ('2012-12-21')
3355 Using an empty string literal used to be the only way to express a boolean.
3356 For all new code please use the much more readable
3357 L<-bool|/Unary operators: bool> operator.
3363 These pages could go on for a while, since the nesting of the data
3364 structures this module can handle are pretty much unlimited (the
3365 module implements the C<WHERE> expansion as a recursive function
3366 internally). Your best bet is to "play around" with the module a
3367 little to see how the data structures behave, and choose the best
3368 format for your data based on that.
3370 And of course, all the values above will probably be replaced with
3371 variables gotten from forms or the command line. After all, if you
3372 knew everything ahead of time, you wouldn't have to worry about
3373 dynamically-generating SQL and could just hardwire it into your
3376 =head1 ORDER BY CLAUSES
3378 Some functions take an order by clause. This can either be a scalar (just a
3379 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
3380 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
3383 Given | Will Generate
3384 ---------------------------------------------------------------
3386 'colA' | ORDER BY colA
3388 [qw/colA colB/] | ORDER BY colA, colB
3390 {-asc => 'colA'} | ORDER BY colA ASC
3392 {-desc => 'colB'} | ORDER BY colB DESC
3394 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
3396 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
3398 \'colA DESC' | ORDER BY colA DESC
3400 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
3401 | /* ...with $x bound to ? */
3404 { -asc => 'colA' }, | colA ASC,
3405 { -desc => [qw/colB/] }, | colB DESC,
3406 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
3407 \'colE DESC', | colE DESC,
3408 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
3409 ] | /* ...with $x bound to ? */
3410 ===============================================================
3414 =head1 OLD EXTENSION SYSTEM
3416 =head2 SPECIAL OPERATORS
3418 my $sqlmaker = SQL::Abstract->new(special_ops => [
3422 my ($self, $field, $op, $arg) = @_;
3428 handler => 'method_name',
3432 A "special operator" is a SQL syntactic clause that can be
3433 applied to a field, instead of a usual binary operator.
3436 WHERE field IN (?, ?, ?)
3437 WHERE field BETWEEN ? AND ?
3438 WHERE MATCH(field) AGAINST (?, ?)
3440 Special operators IN and BETWEEN are fairly standard and therefore
3441 are builtin within C<SQL::Abstract> (as the overridable methods
3442 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
3443 like the MATCH .. AGAINST example above which is specific to MySQL,
3444 you can write your own operator handlers - supply a C<special_ops>
3445 argument to the C<new> method. That argument takes an arrayref of
3446 operator definitions; each operator definition is a hashref with two
3453 the regular expression to match the operator
3457 Either a coderef or a plain scalar method name. In both cases
3458 the expected return is C<< ($sql, @bind) >>.
3460 When supplied with a method name, it is simply called on the
3461 L<SQL::Abstract> object as:
3463 $self->$method_name($field, $op, $arg)
3467 $field is the LHS of the operator
3468 $op is the part that matched the handler regex
3471 When supplied with a coderef, it is called as:
3473 $coderef->($self, $field, $op, $arg)
3478 For example, here is an implementation
3479 of the MATCH .. AGAINST syntax for MySQL
3481 my $sqlmaker = SQL::Abstract->new(special_ops => [
3483 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3484 {regex => qr/^match$/i,
3486 my ($self, $field, $op, $arg) = @_;
3487 $arg = [$arg] if not ref $arg;
3488 my $label = $self->_quote($field);
3489 my ($placeholder) = $self->_convert('?');
3490 my $placeholders = join ", ", (($placeholder) x @$arg);
3491 my $sql = $self->_sqlcase('match') . " ($label) "
3492 . $self->_sqlcase('against') . " ($placeholders) ";
3493 my @bind = $self->_bindtype($field, @$arg);
3494 return ($sql, @bind);
3501 =head2 UNARY OPERATORS
3503 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3507 my ($self, $op, $arg) = @_;
3513 handler => 'method_name',
3517 A "unary operator" is a SQL syntactic clause that can be
3518 applied to a field - the operator goes before the field
3520 You can write your own operator handlers - supply a C<unary_ops>
3521 argument to the C<new> method. That argument takes an arrayref of
3522 operator definitions; each operator definition is a hashref with two
3529 the regular expression to match the operator
3533 Either a coderef or a plain scalar method name. In both cases
3534 the expected return is C<< $sql >>.
3536 When supplied with a method name, it is simply called on the
3537 L<SQL::Abstract> object as:
3539 $self->$method_name($op, $arg)
3543 $op is the part that matched the handler regex
3544 $arg is the RHS or argument of the operator
3546 When supplied with a coderef, it is called as:
3548 $coderef->($self, $op, $arg)
3553 =head1 NEW METHODS (EXPERIMENTAL)
3555 See L<SQL::Abstract::Reference> for the C<expr> versus C<aqt> concept and
3556 an explanation of what the below extensions are extending.
3560 $sqla->plugin('+Foo');
3562 Enables plugin SQL::Abstract::Plugin::Foo.
3566 my ($sql, @bind) = $sqla->render_expr($expr);
3568 =head2 render_statement
3570 Use this if you may be rendering a top level statement so e.g. a SELECT
3571 query doesn't get wrapped in parens
3573 my ($sql, @bind) = $sqla->render_statement($expr);
3577 Expression expansion with optional default for scalars.
3579 my $aqt = $self->expand_expr($expr);
3580 my $aqt = $self->expand_expr($expr, -ident);
3584 Top level means avoid parens on statement AQT.
3586 my $res = $self->render_aqt($aqt, $top_level);
3587 my ($sql, @bind) = @$res;
3589 =head2 join_query_parts
3591 Similar to join() but will render hashrefs as nodes for both join and parts,
3592 and treats arrayref as a nested C<[ $join, @parts ]> structure.
3594 my $part = $self->join_query_parts($join, @parts);
3596 =head1 NEW EXTENSION SYSTEM
3600 my $sqla2 = $sqla->clone;
3602 Performs a semi-shallow copy such that extension methods won't leak state
3603 but excessive depth is avoided.
3613 =head2 clause_expander
3615 =head2 clause_expanders
3617 $sqla->expander('name' => sub { ... });
3618 $sqla->expanders('name1' => sub { ... }, 'name2' => sub { ... });
3620 =head2 expander_list
3622 =head2 op_expander_list
3624 =head2 clause_expander_list
3626 my @names = $sqla->expander_list;
3628 =head2 wrap_expander
3630 =head2 wrap_expanders
3632 =head2 wrap_op_expander
3634 =head2 wrap_op_expanders
3636 =head2 wrap_clause_expander
3638 =head2 wrap_clause_expanders
3640 $sqla->wrap_expander('name' => sub { my ($orig) = @_; sub { ... } });
3641 $sqla->wrap_expanders(
3642 'name1' => sub { my ($orig1) = @_; sub { ... } },
3643 'name2' => sub { my ($orig2) = @_; sub { ... } },
3654 =head2 clause_renderer
3656 =head2 clause_renderers
3658 $sqla->renderer('name' => sub { ... });
3659 $sqla->renderers('name1' => sub { ... }, 'name2' => sub { ... });
3661 =head2 renderer_list
3663 =head2 op_renderer_list
3665 =head2 clause_renderer_list
3667 my @names = $sqla->renderer_list;
3669 =head2 wrap_renderer
3671 =head2 wrap_renderers
3673 =head2 wrap_op_renderer
3675 =head2 wrap_op_renderers
3677 =head2 wrap_clause_renderer
3679 =head2 wrap_clause_renderers
3681 $sqla->wrap_renderer('name' => sub { my ($orig) = @_; sub { ... } });
3682 $sqla->wrap_renderers(
3683 'name1' => sub { my ($orig1) = @_; sub { ... } },
3684 'name2' => sub { my ($orig2) = @_; sub { ... } },
3689 my @clauses = $sqla->clauses_of('select');
3690 $sqla->clauses_of(select => \@new_clauses);
3691 $sqla->clauses_of(select => sub {
3692 my (undef, @old_clauses) = @_;
3694 return @new_clauses;
3697 =head2 statement_list
3699 my @list = $sqla->statement_list;
3701 =head2 make_unop_expander
3703 my $exp = $sqla->make_unop_expander(sub { ... });
3705 If the op is found as a binop, assumes it wants a default comparison, so
3706 the inner expander sub can reliably operate as
3708 sub { my ($self, $name, $body) = @_; ... }
3710 =head2 make_binop_expander
3712 my $exp = $sqla->make_binop_expander(sub { ... });
3714 If the op is found as a unop, assumes the value will be an arrayref with the
3715 LHS as the first entry, and converts that to an ident node if it's a simple
3716 scalar. So the inner expander sub looks like
3719 my ($self, $name, $body, $k) = @_;
3720 { -blah => [ map $self->expand_expr($_), $k, $body ] }
3723 =head2 unop_expander
3725 =head2 unop_expanders
3727 =head2 binop_expander
3729 =head2 binop_expanders
3731 The above methods operate exactly like the op_ versions but wrap the coderef
3732 using the appropriate make_ method first.
3736 Thanks to some benchmarking by Mark Stosberg, it turns out that
3737 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3738 I must admit this wasn't an intentional design issue, but it's a
3739 byproduct of the fact that you get to control your C<DBI> handles
3742 To maximize performance, use a code snippet like the following:
3744 # prepare a statement handle using the first row
3745 # and then reuse it for the rest of the rows
3747 for my $href (@array_of_hashrefs) {
3748 $stmt ||= $sql->insert('table', $href);
3749 $sth ||= $dbh->prepare($stmt);
3750 $sth->execute($sql->values($href));
3753 The reason this works is because the keys in your C<$href> are sorted
3754 internally by B<SQL::Abstract>. Thus, as long as your data retains
3755 the same structure, you only have to generate the SQL the first time
3756 around. On subsequent queries, simply use the C<values> function provided
3757 by this module to return your values in the correct order.
3759 However this depends on the values having the same type - if, for
3760 example, the values of a where clause may either have values
3761 (resulting in sql of the form C<column = ?> with a single bind
3762 value), or alternatively the values might be C<undef> (resulting in
3763 sql of the form C<column IS NULL> with no bind value) then the
3764 caching technique suggested will not work.
3768 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3769 really like this part (I do, at least). Building up a complex query
3770 can be as simple as the following:
3777 use CGI::FormBuilder;
3780 my $form = CGI::FormBuilder->new(...);
3781 my $sql = SQL::Abstract->new;
3783 if ($form->submitted) {
3784 my $field = $form->field;
3785 my $id = delete $field->{id};
3786 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3789 Of course, you would still have to connect using C<DBI> to run the
3790 query, but the point is that if you make your form look like your
3791 table, the actual query script can be extremely simplistic.
3793 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3794 a fast interface to returning and formatting data. I frequently
3795 use these three modules together to write complex database query
3796 apps in under 50 lines.
3798 =head1 HOW TO CONTRIBUTE
3800 Contributions are always welcome, in all usable forms (we especially
3801 welcome documentation improvements). The delivery methods include git-
3802 or unified-diff formatted patches, GitHub pull requests, or plain bug
3803 reports either via RT or the Mailing list. Contributors are generally
3804 granted full access to the official repository after their first several
3805 patches pass successful review.
3807 This project is maintained in a git repository. The code and related tools are
3808 accessible at the following locations:
3812 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3814 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3816 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3818 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3824 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3825 Great care has been taken to preserve the I<published> behavior
3826 documented in previous versions in the 1.* family; however,
3827 some features that were previously undocumented, or behaved
3828 differently from the documentation, had to be changed in order
3829 to clarify the semantics. Hence, client code that was relying
3830 on some dark areas of C<SQL::Abstract> v1.*
3831 B<might behave differently> in v1.50.
3833 The main changes are:
3839 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3843 support for the { operator => \"..." } construct (to embed literal SQL)
3847 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3851 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3855 defensive programming: check arguments
3859 fixed bug with global logic, which was previously implemented
3860 through global variables yielding side-effects. Prior versions would
3861 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3862 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3863 Now this is interpreted
3864 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3869 fixed semantics of _bindtype on array args
3873 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3874 we just avoid shifting arrays within that tree.
3878 dropped the C<_modlogic> function
3882 =head1 ACKNOWLEDGEMENTS
3884 There are a number of individuals that have really helped out with
3885 this module. Unfortunately, most of them submitted bugs via CPAN
3886 so I have no idea who they are! But the people I do know are:
3888 Ash Berlin (order_by hash term support)
3889 Matt Trout (DBIx::Class support)
3890 Mark Stosberg (benchmarking)
3891 Chas Owens (initial "IN" operator support)
3892 Philip Collins (per-field SQL functions)
3893 Eric Kolve (hashref "AND" support)
3894 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3895 Dan Kubb (support for "quote_char" and "name_sep")
3896 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3897 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3898 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3899 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3900 Oliver Charles (support for "RETURNING" after "INSERT")
3906 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3910 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3912 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3914 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3915 While not an official support venue, C<DBIx::Class> makes heavy use of
3916 C<SQL::Abstract>, and as such list members there are very familiar with
3917 how to create queries.
3921 This module is free software; you may copy this under the same
3922 terms as perl itself (either the GNU General Public License or
3923 the Artistic License)