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)),
158 bind => __PACKAGE__->make_unop_expander(sub { +{ -bind => $_[2] } }),
161 (map +($_, "_render_$_"),
162 qw(op func bind ident literal row values keyword)),
165 (map +($_ => '_render_op_between'), 'between', 'not_between'),
166 (map +($_ => '_render_op_in'), 'in', 'not_in'),
167 (map +($_ => '_render_unop_postfix'),
168 'is_null', 'is_not_null', 'asc', 'desc',
170 (not => '_render_unop_paren'),
171 (map +($_ => '_render_op_andor'), qw(and or)),
172 ',' => '_render_op_multop',
175 delete => [ qw(target where returning) ],
176 update => [ qw(target set where returning) ],
177 insert => [ qw(target fields from returning) ],
178 select => [ qw(select from where order_by) ],
181 'delete.from' => '_expand_delete_clause_target',
182 'update.update' => '_expand_update_clause_target',
183 'insert.into' => '_expand_insert_clause_target',
184 'insert.values' => '_expand_insert_clause_from',
187 'delete.target' => '_render_delete_clause_target',
188 'update.target' => '_render_update_clause_target',
189 'insert.target' => '_render_insert_clause_target',
190 'insert.fields' => '_render_insert_clause_fields',
191 'insert.from' => '_render_insert_clause_from',
195 foreach my $stmt (keys %{$Defaults{clauses_of}}) {
196 $Defaults{expand}{$stmt} = '_expand_statement';
197 $Defaults{render}{$stmt} = '_render_statement';
198 foreach my $clause (@{$Defaults{clauses_of}{$stmt}}) {
199 $Defaults{expand_clause}{"${stmt}.${clause}"}
200 = "_expand_${stmt}_clause_${clause}";
206 my $class = ref($self) || $self;
207 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
209 # choose our case by keeping an option around
210 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
212 # default logic for interpreting arrayrefs
213 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
215 # how to return bind vars
216 $opt{bindtype} ||= 'normal';
218 # default comparison is "=", but can be overridden
221 # try to recognize which are the 'equality' and 'inequality' ops
222 # (temporary quickfix (in 2007), should go through a more seasoned API)
223 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
224 $opt{inequality_op} = qr/^( != | <> )$/ix;
226 $opt{like_op} = qr/^ (is_)?r?like $/xi;
227 $opt{not_like_op} = qr/^ (is_)?not_r?like $/xi;
230 $opt{sqltrue} ||= '1=1';
231 $opt{sqlfalse} ||= '0=1';
234 $opt{special_ops} ||= [];
237 $opt{unary_ops} ||= [];
239 # rudimentary sanity-check for user supplied bits treated as functions/operators
240 # If a purported function matches this regular expression, an exception is thrown.
241 # Literal SQL is *NOT* subject to this check, only functions (and column names
242 # when quoting is not in effect)
245 # need to guard against ()'s in column names too, but this will break tons of
246 # hacks... ideas anyone?
247 $opt{injection_guard} ||= qr/
253 $opt{expand_unary} = {};
255 foreach my $name (sort keys %Defaults) {
256 $opt{$name} = { %{$Defaults{$name}}, %{$opt{$name}||{}} };
259 if ($class ne __PACKAGE__) {
261 # check for overriden methods
263 foreach my $type (qw(insert update delete)) {
264 my $method = "_${type}_returning";
265 if (__PACKAGE__->can($method) ne $class->can($method)) {
266 my $clause = "${type}.returning";
267 $opt{expand_clause}{$clause} = sub { $_[2] },
268 $opt{render_clause}{$clause}
269 = sub { [ $_[0]->$method($_[3]) ] };
272 if (__PACKAGE__->can('_table') ne $class->can('_table')) {
273 $opt{expand_clause}{'select.from'} = sub {
274 return +{ -literal => [ $_[0]->_table($_[2]) ] };
277 if (__PACKAGE__->can('_order_by') ne $class->can('_order_by')) {
278 $opt{expand_clause}{'select.order_by'} = sub { $_[2] };
279 $opt{render_clause}{'select.order_by'} = sub {
280 [ $_[0]->_order_by($_[2]) ];
283 if (__PACKAGE__->can('_select_fields') ne $class->can('_select_fields')) {
284 $opt{expand_clause}{'select.select'} = sub { $_[2] };
285 $opt{render_clause}{'select.select'} = sub {
286 my @super = $_[0]->_select_fields($_[2]);
288 ref($super[0]) eq 'HASH'
289 ? $_[0]->render_expr($super[0])
292 return $_[0]->join_query_parts(
293 ' ', { -keyword => 'select' }, $effort
297 foreach my $type (qw(in between)) {
298 my $meth = "_where_field_".uc($type);
299 if (__PACKAGE__->can($meth) ne $class->can($meth)) {
301 my ($self, $op, $v, $k) = @_;
302 $op = join ' ', split '_', $op;
303 return +{ -literal => [
304 $self->$meth($k, $op, $v)
307 $opt{expand_op}{$_} = $exp for $type, "not_${type}";
310 if ($class->isa('DBIx::Class::SQLMaker')) {
311 $opt{warn_once_on_nest} = 1;
312 $opt{disable_old_special_ops} = 1;
313 $opt{render_clause}{'select.where'} = sub {
314 my ($sql, @bind) = $_[0]->where($_[2]);
315 s/\A\s+//, s/\s+\Z// for $sql;
316 return [ $sql, @bind ];
318 $opt{expand_op}{ident} = $class->make_unop_expander(sub {
319 my ($self, undef, $body) = @_;
320 $body = $body->from if Scalar::Util::blessed($body);
321 $self->_expand_ident(ident => $body);
324 if ($class->isa('SQL::Abstract::More')) {
325 my $orig = $opt{expand_op}{or};
326 $opt{expand_op}{or} = sub {
327 my ($self, $logop, $v, $k) = @_;
328 if ($k and ref($v) eq 'ARRAY') {
329 my ($type, $val) = @$v;
332 ref($type) eq 'HASH' and ref($val) eq 'HASH'
333 and keys %$type == 1 and keys %$val == 1
334 and (keys %$type)[0] eq (keys %$val)[0]
337 ($type) = values %$type;
338 ($val) = values %$val;
340 if ($self->is_bind_value_with_type(my $v = [ $type, $val ])) {
341 return $self->expand_expr(
342 { $k, map +($op ? { $op => $_ } : $_), { -bind => $v } }
346 return $self->$orig($logop, $v, $k);
348 $opt{render}{bind} = sub {
349 return [ '?', map +(ref($_->[0]) ? $_ : $_->[1]), $_[2] ]
354 if ($opt{lazy_join_sql_parts}) {
355 my $mod = Module::Runtime::use_module('SQL::Abstract::Parts');
356 $opt{join_sql_parts} ||= sub { $mod->new(@_) };
359 $opt{join_sql_parts} ||= sub { join $_[0], @_[1..$#_] };
361 return bless \%opt, $class;
365 my ($self, $name, $key, $value) = @_;
366 return $self->{$name}{$key} unless @_ > 3;
367 $self->{$name}{$key} = $value;
371 sub make_unop_expander {
372 my (undef, $exp) = @_;
374 my ($self, $name, $body, $k) = @_;
375 return $self->_expand_hashpair_cmp($k, { "-${name}" => $body })
377 return $self->$exp($name, $body);
381 sub make_binop_expander {
382 my (undef, $exp) = @_;
384 my ($self, $name, $body, $k) = @_;
385 $k = shift @{$body = [ @$body ]} unless defined $k;
386 $k = ref($k) ? $k : { -ident => $k };
387 return $self->$exp($name, $body, $k);
392 my ($self, $plugin, @args) = @_;
393 unless (ref $plugin) {
394 $plugin =~ s/\A\+/${\__PACKAGE__}::Plugin::/;
395 require(join('/', split '::', $plugin).'.pm');
397 $plugin->apply_to($self, @args);
402 foreach my $type (qw(
403 expand op_expand render op_render clause_expand clause_render
405 my $name = join '_', reverse split '_', $type;
406 my $singular = "${type}er";
408 eval qq{sub ${singular} {
410 return \$self->_ext_rw('${name}', \@_) if \@_ == 1;
411 return \$self->${singular}s(\@_)
412 }; 1 } or die "Method builder failed for ${singular}: $@";
413 eval qq{sub wrap_${singular} {
414 shift->wrap_${singular}s(\@_)
415 }; 1 } or die "Method builder failed for wrap_${singular}: $@";
417 eval qq{sub ${singular}s {
418 my (\$self, \@args) = \@_;
419 while (my (\$this_key, \$this_value) = splice(\@args, 0, 2)) {
420 \$self->_ext_rw('${name}', \$this_key, \$this_value);
423 }; 1 } or die "Method builder failed for ${singular}s: $@";
424 eval qq{sub wrap_${singular}s {
425 my (\$self, \@args) = \@_;
426 while (my (\$this_key, \$this_builder) = splice(\@args, 0, 2)) {
427 my \$orig = \$self->_ext_rw('${name}', \$this_key);
429 '${name}', \$this_key,
430 \$this_builder->(\$orig, '${name}', \$this_key),
434 }; 1 } or die "Method builder failed for wrap_${singular}s: $@";
435 eval qq{sub ${singular}_list { sort keys %{\$_[0]->{\$name}} }; 1; }
436 or die "Method builder failed for ${singular}_list: $@";
438 foreach my $singular (qw(unop_expander binop_expander)) {
439 eval qq{sub ${singular} { shift->${singular}s(\@_) }; 1 }
440 or die "Method builder failed for ${singular}: $@";
441 eval qq{sub ${singular}s {
442 my (\$self, \@args) = \@_;
443 while (my (\$this_key, \$this_value) = splice(\@args, 0, 2)) {
445 expand_op => \$this_key,
446 \$self->make_${singular}(\$this_value),
450 }; 1 } or die "Method builder failed for ${singular}s: $@";
454 #sub register_op { $_[0]->{is_op}{$_[1]} = 1; $_[0] }
456 sub statement_list { sort keys %{$_[0]->{clauses_of}} }
459 my ($self, $of, @clauses) = @_;
461 return @{$self->{clauses_of}{$of}||[]};
463 if (ref($clauses[0]) eq 'CODE') {
464 @clauses = $self->${\($clauses[0])}(@{$self->{clauses_of}{$of}||[]});
466 $self->{clauses_of}{$of} = \@clauses;
475 ref($self->{$_}) eq 'HASH'
484 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
485 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
487 sub _assert_pass_injection_guard {
488 if ($_[1] =~ $_[0]->{injection_guard}) {
489 my $class = ref $_[0];
490 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
491 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
492 . "{injection_guard} attribute to ${class}->new()"
497 #======================================================================
499 #======================================================================
502 my ($self, $table, $data, $options) = @_;
505 if (ref($table) eq 'HASH') {
508 my %clauses = (target => $table, values => $data, %{$options||{}});
512 my @rendered = $self->render_statement({ -insert => $stmt });
513 return wantarray ? @rendered : $rendered[0];
516 sub _expand_insert_clause_target {
517 +(target => $_[0]->expand_expr($_[2], -ident));
520 sub _expand_insert_clause_fields {
522 $_[0]->expand_expr({ -list => $_[2] }, -ident)
523 ] } if ref($_[2]) eq 'ARRAY';
524 return $_[2]; # should maybe still expand somewhat?
527 sub _expand_insert_clause_from {
528 my ($self, undef, $data) = @_;
529 if (ref($data) eq 'HASH' and (keys(%$data))[0] =~ /^-/) {
530 return $self->expand_expr($data);
532 my ($f_aqt, $v_aqt) = $self->_expand_insert_values($data);
534 from => { -values => [ $v_aqt ] },
535 ($f_aqt ? (fields => $f_aqt) : ()),
539 sub _expand_insert_clause_returning {
540 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
543 sub _expand_insert_values {
544 my ($self, $data) = @_;
545 if (is_literal_value($data)) {
546 (undef, $self->expand_expr($data));
548 my ($fields, $values) = (
549 ref($data) eq 'HASH' ?
550 ([ sort keys %$data ], [ @{$data}{sort keys %$data} ])
554 # no names (arrayref) means can't generate bindtype
555 !($fields) && $self->{bindtype} eq 'columns'
556 && belch "can't do 'columns' bindtype when called with arrayref";
560 ? $self->expand_expr({ -row => $fields }, -ident)
565 local our $Cur_Col_Meta = $fields->[$_];
566 $self->_expand_insert_value($values->[$_])
573 sub _render_insert_clause_fields {
574 return $_[0]->render_aqt($_[2]);
577 sub _render_insert_clause_target {
578 my ($self, undef, $from) = @_;
579 $self->join_query_parts(' ', { -keyword => 'insert into' }, $from);
582 sub _render_insert_clause_from {
583 return $_[0]->render_aqt($_[2], 1);
586 # So that subclasses can override INSERT ... RETURNING separately from
587 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
588 sub _insert_returning { shift->_returning(@_) }
590 sub _redispatch_returning {
591 my ($self, $type, undef, $returning) = @_;
592 [ $self->${\"_${type}_returning"}({ returning => $returning }) ];
596 my ($self, $options) = @_;
598 my $f = $options->{returning};
600 my ($sql, @bind) = @{ $self->render_aqt(
601 $self->expand_expr({ -list => $f }, -ident)
603 my $rsql = $self->_sqlcase(' returning ').$sql;
604 return wantarray ? ($rsql, @bind) : $rsql;
607 sub _expand_insert_value {
610 my $k = our $Cur_Col_Meta;
612 if (ref($v) eq 'ARRAY') {
613 if ($self->{array_datatypes}) {
614 return +{ -bind => [ $k, $v ] };
616 my ($sql, @bind) = @$v;
617 $self->_assert_bindval_matches_bindtype(@bind);
618 return +{ -literal => $v };
620 if (ref($v) eq 'HASH') {
621 if (grep !/^-/, keys %$v) {
622 belch "HASH ref as bind value in insert is not supported";
623 return +{ -bind => [ $k, $v ] };
627 return +{ -bind => [ $k, undef ] };
629 return $self->expand_expr($v);
634 #======================================================================
636 #======================================================================
639 my ($self, $table, $set, $where, $options) = @_;
642 if (ref($table) eq 'HASH') {
646 @clauses{qw(target set where)} = ($table, $set, $where);
647 puke "Unsupported data type specified to \$sql->update"
648 unless ref($clauses{set}) eq 'HASH';
649 @clauses{keys %$options} = values %$options;
653 my @rendered = $self->render_statement({ -update => $stmt });
654 return wantarray ? @rendered : $rendered[0];
657 sub _render_update_clause_target {
658 my ($self, undef, $target) = @_;
659 $self->join_query_parts(' ', { -keyword => 'update' }, $target);
662 sub _update_set_values {
663 my ($self, $data) = @_;
665 return @{ $self->render_aqt(
666 $self->_expand_update_set_values(undef, $data),
670 sub _expand_update_set_values {
671 my ($self, undef, $data) = @_;
672 $self->expand_expr({ -list => [
675 $set = { -bind => $_ } unless defined $set;
676 +{ -op => [ '=', { -ident => $k }, $set ] };
682 ? ($self->{array_datatypes}
683 ? [ $k, +{ -bind => [ $k, $v ] } ]
684 : [ $k, +{ -literal => $v } ])
686 local our $Cur_Col_Meta = $k;
687 [ $k, $self->_expand_expr($v) ]
694 sub _expand_update_clause_target {
695 my ($self, undef, $target) = @_;
696 +(target => $self->expand_expr({ -list => $target }, -ident));
699 sub _expand_update_clause_set {
700 return $_[2] if ref($_[2]) eq 'HASH' and ($_[2]->{-op}||[''])->[0] eq ',';
701 +(set => $_[0]->_expand_update_set_values($_[1], $_[2]));
704 sub _expand_update_clause_where {
705 +(where => $_[0]->expand_expr($_[2]));
708 sub _expand_update_clause_returning {
709 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
712 # So that subclasses can override UPDATE ... RETURNING separately from
714 sub _update_returning { shift->_returning(@_) }
718 #======================================================================
720 #======================================================================
723 my ($self, @args) = @_;
725 if (ref(my $sel = $args[0]) eq 'HASH') {
729 @clauses{qw(from select where order_by)} = @args;
731 # This oddity is to literalify since historically SQLA doesn't quote
732 # a single identifier argument, so we convert it into a literal
734 $clauses{select} = { -literal => [ $clauses{select}||'*' ] }
735 unless ref($clauses{select});
740 my @rendered = $self->render_statement({ -select => $stmt });
741 return wantarray ? @rendered : $rendered[0];
744 sub _expand_select_clause_select {
745 my ($self, undef, $select) = @_;
746 +(select => $self->expand_expr({ -list => $select }, -ident));
749 sub _expand_select_clause_from {
750 my ($self, undef, $from) = @_;
751 +(from => $self->expand_expr({ -list => $from }, -ident));
754 sub _expand_select_clause_where {
755 my ($self, undef, $where) = @_;
758 if (my $conv = $self->{convert}) {
770 ->wrap_expander(bind => $_wrap)
771 ->wrap_op_expanders(map +($_ => $_wrap), qw(ident value))
772 ->wrap_expander(func => sub {
775 my ($self, $type, $thing) = @_;
776 if (ref($thing) eq 'ARRAY' and $thing->[0] eq $conv
777 and @$thing == 2 and ref($thing->[1]) eq 'HASH'
780 or $thing->[1]{-value}
781 or $thing->[1]{-bind})
783 return { -func => $thing }; # already went through our expander
785 return $self->$orig($type, $thing);
793 return +(where => $sqla->expand_expr($where));
796 sub _expand_select_clause_order_by {
797 my ($self, undef, $order_by) = @_;
798 +(order_by => $self->_expand_order_by($order_by));
802 my ($self, $fields) = @_;
803 return $fields unless ref($fields);
804 my ($sql, @bind) = @{ $self->render_aqt(
805 $self->expand_expr({ -list => $fields }, '-ident')
807 return wantarray ? ($sql, @bind) : $sql;
810 #======================================================================
812 #======================================================================
815 my ($self, $table, $where, $options) = @_;
818 if (ref($table) eq 'HASH') {
821 my %clauses = (target => $table, where => $where, %{$options||{}});
825 my @rendered = $self->render_statement({ -delete => $stmt });
826 return wantarray ? @rendered : $rendered[0];
829 # So that subclasses can override DELETE ... RETURNING separately from
831 sub _delete_returning { shift->_returning(@_) }
833 sub _expand_delete_clause_target {
834 +(target => $_[0]->expand_expr({ -list => $_[2] }, -ident));
837 sub _expand_delete_clause_where { +(where => $_[0]->expand_expr($_[2])); }
839 sub _expand_delete_clause_returning {
840 +(returning => $_[0]->expand_expr({ -list => $_[2] }, -ident));
843 sub _render_delete_clause_target {
844 my ($self, undef, $from) = @_;
845 $self->join_query_parts(' ', { -keyword => 'delete from' }, $from);
848 #======================================================================
850 #======================================================================
854 # Finally, a separate routine just to handle WHERE clauses
856 my ($self, $where, $order) = @_;
858 local $self->{convert_where} = $self->{convert};
861 my ($sql, @bind) = defined($where)
862 ? $self->_recurse_where($where)
864 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
868 my ($order_sql, @order_bind) = $self->_order_by($order);
870 push @bind, @order_bind;
873 return wantarray ? ($sql, @bind) : $sql;
876 { our $Default_Scalar_To = -value }
879 my ($self, $expr, $default_scalar_to) = @_;
880 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
881 $self->_expand_expr($expr);
885 my ($self, $aqt, $top_level) = @_;
886 my ($k, $v, @rest) = %$aqt;
888 die "Not a node type: $k" unless $k =~ s/^-//;
889 if (my $meth = $self->{render}{$k}) {
890 local our $Render_Top_Level = $top_level;
891 return $self->$meth($k, $v)||[];
893 die "notreached: $k";
897 my ($self, $expr, $default_scalar_to) = @_;
898 return @{ $self->render_aqt(
899 $self->expand_expr($expr, $default_scalar_to)
903 sub render_statement {
904 my ($self, $expr, $default_scalar_to) = @_;
906 $self->expand_expr($expr, $default_scalar_to), 1
910 sub _expand_statement {
911 my ($self, $type, $args) = @_;
912 my $ec = $self->{expand_clause};
915 $args->{$type} = delete $args->{_}
917 my %has_clause = map +($_ => 1), @{$self->{clauses_of}{$type}};
918 return +{ "-${type}" => +{
920 my $val = $args->{$_};
921 if (defined($val) and my $exp = $ec->{"${type}.$_"}) {
922 if ((my (@exp) = $self->$exp($_ => $val)) == 1) {
927 } elsif ($has_clause{$_}) {
928 ($_ => $self->expand_expr($val))
936 sub _render_statement {
937 my ($self, $type, $args) = @_;
939 foreach my $clause (@{$self->{clauses_of}{$type}}) {
940 next unless my $clause_expr = $args->{$clause};
942 if (my $rdr = $self->{render_clause}{"${type}.${clause}"}) {
943 $self->$rdr($clause, $clause_expr, $args);
945 my $r = $self->render_aqt($clause_expr, 1);
946 next unless defined $r->[0] and length $r->[0];
947 $self->join_query_parts(' ',
948 { -keyword => $clause },
955 my $q = $self->join_query_parts(' ', @parts);
956 return $self->join_query_parts('',
957 (our $Render_Top_Level ? $q : ('(', $q, ')'))
962 my ($self, $raw) = @_;
964 return $op if grep $_->{$op}, @{$self}{qw(expand_op render_op)};
965 s/^-(?=.)//, s/\s+/_/g for $op;
970 my ($self, $expr) = @_;
971 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
972 return undef unless defined($expr);
973 if (ref($expr) eq 'HASH') {
974 return undef unless my $kc = keys %$expr;
976 return $self->_expand_logop(and => $expr);
978 my ($key, $value) = %$expr;
979 if ($key =~ /^-/ and $key =~ s/ [_\s]? \d+ $//x ) {
980 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
981 . "You probably wanted ...-and => [ $key => COND1, $key => COND2 ... ]";
983 return $self->_expand_hashpair($key, $value);
985 if (ref($expr) eq 'ARRAY') {
986 return $self->_expand_logop(lc($self->{logic}), $expr);
988 if (my $literal = is_literal_value($expr)) {
989 return +{ -literal => $literal };
991 if (!ref($expr) or Scalar::Util::blessed($expr)) {
992 return $self->_expand_scalar($expr);
997 sub _expand_hashpair {
998 my ($self, $k, $v) = @_;
999 unless (defined($k) and length($k)) {
1000 if (defined($k) and my $literal = is_literal_value($v)) {
1001 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
1002 return { -literal => $literal };
1004 puke "Supplying an empty left hand side argument is not supported";
1007 return $self->_expand_hashpair_op($k, $v);
1008 } elsif ($k =~ /^\W+$/) {
1009 my ($lhs, @rhs) = ref($v) eq 'ARRAY' ? @$v : $v;
1010 return $self->_expand_op(
1011 -op, [ $k, $self->expand_expr($lhs, -ident), @rhs ]
1014 return $self->_expand_hashpair_ident($k, $v);
1017 sub _expand_hashpair_ident {
1018 my ($self, $k, $v) = @_;
1020 local our $Cur_Col_Meta = $k;
1022 # hash with multiple or no elements is andor
1024 if (ref($v) eq 'HASH' and keys %$v != 1) {
1025 return $self->_expand_logop(and => $v, $k);
1028 # undef needs to be re-sent with cmp to achieve IS/IS NOT NULL
1030 if (is_undef_value($v)) {
1031 return $self->_expand_hashpair_cmp($k => undef);
1034 # scalars and objects get expanded as whatever requested or values
1036 if (!ref($v) or Scalar::Util::blessed($v)) {
1037 return $self->_expand_hashpair_scalar($k, $v);
1040 # single key hashref is a hashtriple
1042 if (ref($v) eq 'HASH') {
1043 return $self->_expand_hashtriple($k, %$v);
1046 # arrayref needs re-engineering over the elements
1048 if (ref($v) eq 'ARRAY') {
1049 return $self->sqlfalse unless @$v;
1050 $self->_debug("ARRAY($k) means distribute over elements");
1052 $v->[0] =~ /^-(and|or)$/i
1053 ? (shift(@{$v = [ @$v ]}), $1)
1054 : lc($self->{logic} || 'OR')
1056 return $self->_expand_logop(
1061 if (my $literal = is_literal_value($v)) {
1062 unless (length $k) {
1063 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
1066 my ($sql, @bind) = @$literal;
1067 if ($self->{bindtype} eq 'columns') {
1069 $self->_assert_bindval_matches_bindtype($_);
1072 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
1077 sub _expand_scalar {
1078 my ($self, $expr) = @_;
1080 return $self->_expand_expr({ (our $Default_Scalar_To) => $expr });
1083 sub _expand_hashpair_scalar {
1084 my ($self, $k, $v) = @_;
1086 return $self->_expand_hashpair_cmp(
1087 $k, $self->_expand_scalar($v),
1091 sub _expand_hashpair_op {
1092 my ($self, $k, $v) = @_;
1094 $self->_assert_pass_injection_guard($k =~ /\A-(.*)\Z/s);
1096 my $op = $self->_normalize_op($k);
1098 my $wsop = join(' ', split '_', $op);
1100 my $is_special = List::Util::first { $wsop =~ $_->{regex} }
1101 @{$self->{special_ops}};
1105 # the old special op system requires illegality for top-level use
1108 (our $Expand_Depth) == 1
1112 $self->{disable_old_special_ops}
1113 and List::Util::first { $wsop =~ $_->{regex} } @BUILTIN_SPECIAL_OPS
1117 puke "Illegal use of top-level '-$wsop'"
1121 if (my $exp = $self->{expand}{$op}||$self->{expand_op}{$op}) {
1122 return $self->$exp($op, $v);
1125 if ($self->{render}{$op}) {
1126 return { "-${op}" => $v };
1129 # Ops prefixed with -not_ get converted
1131 if (my ($rest) = $op =~/^not_(.*)$/) {
1134 $self->_expand_expr({ "-${rest}", $v })
1140 # the old unary op system means we should touch nothing and let it work
1142 my $op = join(' ', split '_', $op);
1144 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1145 return { -op => [ $op, $v ] };
1149 my $type = $is_special || $self->{render_op}{$op} ? -op : -func;
1151 if ($self->{restore_old_unop_handling}) {
1158 and (keys %$v)[0] =~ /^-/
1159 and not $self->{render_op}{$op}
1168 if ($type eq -func and ref($v) eq 'ARRAY') {
1169 return $self->_expand_expr({ -func => [ $op, @$v ] });
1172 return $self->_expand_expr({ $type => [ $op, $v ] });
1175 sub _expand_hashpair_cmp {
1176 my ($self, $k, $v) = @_;
1177 $self->_expand_hashtriple($k, $self->{cmp}, $v);
1180 sub _expand_hashtriple {
1181 my ($self, $k, $vk, $vv) = @_;
1183 my $ik = $self->_expand_expr({ -ident => $k });
1185 my $op = $self->_normalize_op($vk);
1186 $self->_assert_pass_injection_guard($op);
1188 if ($op =~ s/ _? \d+ $//x ) {
1189 return $self->_expand_expr($k, { $vk, $vv });
1191 if (my $x = $self->{expand_op}{$op}) {
1192 local our $Cur_Col_Meta = $k;
1193 return $self->$x($op, $vv, $k);
1197 my $op = join(' ', split '_', $op);
1199 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
1200 return { -op => [ $op, $ik, $vv ] };
1202 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1206 { -op => [ $op, $vv ] }
1210 if (ref($vv) eq 'ARRAY') {
1212 my $logic = (defined($raw[0]) and $raw[0] =~ /^-(and|or)$/i)
1213 ? (shift(@raw), lc $1) : 'or';
1214 my @values = map +{ $vk => $_ }, @raw;
1216 $op =~ $self->{inequality_op}
1217 or $op =~ $self->{not_like_op}
1219 if (lc($logic) eq 'or' and @values > 1) {
1220 belch "A multi-element arrayref as an argument to the inequality op '${\uc(join ' ', split '_', $op)}' "
1221 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
1222 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
1227 # try to DWIM on equality operators
1228 return ($self->_dwim_op_to_is($op,
1229 "Supplying an empty arrayref to '%s' is deprecated",
1230 "operator '%s' applied on an empty array (field '$k')"
1231 ) ? $self->sqlfalse : $self->sqltrue);
1233 return $self->_expand_logop($logic => \@values, $k);
1235 if (is_undef_value($vv)) {
1236 my $is = ($self->_dwim_op_to_is($op,
1237 "Supplying an undefined argument to '%s' is deprecated",
1238 "unexpected operator '%s' with undef operand",
1239 ) ? 'is' : 'is not');
1241 return $self->_expand_hashpair($k => { $is, undef });
1243 local our $Cur_Col_Meta = $k;
1247 $self->_expand_expr($vv)
1251 sub _dwim_op_to_is {
1252 my ($self, $raw, $empty, $fail) = @_;
1254 my $op = $self->_normalize_op($raw);
1256 if ($op =~ /^not$/i) {
1259 if ($op =~ $self->{equality_op}) {
1262 if ($op =~ $self->{like_op}) {
1263 belch(sprintf $empty, uc(join ' ', split '_', $op));
1266 if ($op =~ $self->{inequality_op}) {
1269 if ($op =~ $self->{not_like_op}) {
1270 belch(sprintf $empty, uc(join ' ', split '_', $op));
1273 puke(sprintf $fail, $op);
1277 my ($self, undef, $args) = @_;
1278 my ($func, @args) = @$args;
1279 return +{ -func => [ $func, map $self->expand_expr($_), @args ] };
1283 my ($self, undef, $body) = @_;
1284 unless (defined($body) or (ref($body) and ref($body) eq 'ARRAY')) {
1285 puke "-ident requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
1287 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
1288 ref($body) ? @$body : $body;
1289 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
1290 unless ($self->{quote_char}) {
1291 $self->_assert_pass_injection_guard($_) for @parts;
1293 return +{ -ident => \@parts };
1297 +{ -bind => [ our $Cur_Col_Meta, $_[2] ] };
1301 my ($self, undef, $args) = @_;
1302 +{ -row => [ map $self->expand_expr($_), @$args ] };
1306 my ($self, undef, $args) = @_;
1307 my ($op, @opargs) = @$args;
1308 if (my $exp = $self->{expand_op}{$op}) {
1309 return $self->$exp($op, \@opargs);
1311 if (List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1312 return { -op => [ $op, @opargs ] };
1314 +{ -op => [ $op, map $self->expand_expr($_), @opargs ] };
1318 my ($self, undef, $v) = @_;
1320 return $self->_expand_expr($v);
1322 puke "-bool => undef not supported" unless defined($v);
1323 return $self->_expand_expr({ -ident => $v });
1327 my ($self, undef, $expr) = @_;
1329 ',', map $self->expand_expr($_),
1330 @{$expr->{-op}}[1..$#{$expr->{-op}}]
1331 ] } if ref($expr) eq 'HASH' and ($expr->{-op}||[''])->[0] eq ',';
1332 return +{ -op => [ ',',
1333 map $self->expand_expr($_),
1334 ref($expr) eq 'ARRAY' ? @$expr : $expr
1339 my ($self, $logop, $v, $k) = @_;
1340 $self->${\$self->{expand_op}{$logop}}($logop, $v, $k);
1343 sub _expand_op_andor {
1344 my ($self, $logop, $v, $k) = @_;
1346 $v = [ map +{ $k, $_ },
1348 ? (map +{ $_ => $v->{$_} }, sort keys %$v)
1352 if (ref($v) eq 'HASH') {
1353 return undef unless keys %$v;
1356 map $self->_expand_expr({ $_ => $v->{$_} }),
1360 if (ref($v) eq 'ARRAY') {
1361 $logop eq 'and' or $logop eq 'or' or puke "unknown logic: $logop";
1364 (ref($_) eq 'ARRAY' and @$_)
1365 or (ref($_) eq 'HASH' and %$_)
1371 while (my ($el) = splice @expr, 0, 1) {
1372 puke "Supplying an empty left hand side argument is not supported in array-pairs"
1373 unless defined($el) and length($el);
1374 my $elref = ref($el);
1376 local our $Expand_Depth = 0;
1377 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
1378 } elsif ($elref eq 'ARRAY') {
1379 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
1380 } elsif (my $l = is_literal_value($el)) {
1381 push @res, { -literal => $l };
1382 } elsif ($elref eq 'HASH') {
1383 local our $Expand_Depth = 0;
1384 push @res, grep defined, $self->_expand_expr($el) if %$el;
1390 # return $res[0] if @res == 1;
1391 return { -op => [ $logop, @res ] };
1397 my ($self, $op, $vv, $k) = @_;
1398 ($k, $vv) = @$vv unless defined $k;
1399 puke "$op can only take undef as argument"
1403 and exists($vv->{-value})
1404 and !defined($vv->{-value})
1406 return +{ -op => [ $op.'_null', $self->expand_expr($k, -ident) ] };
1409 sub _expand_between {
1410 my ($self, $op, $vv, $k) = @_;
1411 my @rhs = map $self->_expand_expr($_),
1412 ref($vv) eq 'ARRAY' ? @$vv : $vv;
1414 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
1416 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
1418 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1422 $self->expand_expr($k),
1423 map $self->expand_expr($_, -value), @rhs
1428 my ($self, $op, $vv, $k) = @_;
1429 if (my $literal = is_literal_value($vv)) {
1430 my ($sql, @bind) = @$literal;
1431 my $opened_sql = $self->_open_outer_paren($sql);
1433 $op, $self->expand_expr($k, -ident),
1434 { -literal => [ $opened_sql, @bind ] }
1438 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1439 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1440 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1441 . 'will emit the logically correct SQL instead of raising this exception)'
1443 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
1445 my @rhs = map $self->expand_expr($_, -value),
1446 map { defined($_) ? $_: puke($undef_err) }
1447 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
1448 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
1452 $self->expand_expr($k, -ident),
1458 my ($self, undef, $v) = @_;
1459 # DBIx::Class requires a nest warning to be emitted once but the private
1460 # method it overrode to do so no longer exists
1461 if ($self->{warn_once_on_nest}) {
1462 unless (our $Nest_Warned) {
1464 "-nest in search conditions is deprecated, you most probably wanted:\n"
1465 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
1470 return $self->_expand_expr($v);
1473 sub _expand_values {
1474 my ($self, undef, $values) = @_;
1475 return { -values => [
1478 ? $self->expand_expr($_)
1479 : +{ -row => [ map $self->expand_expr($_), @$_ ] }
1480 ), ref($values) eq 'ARRAY' ? @$values : $values
1484 sub _recurse_where {
1485 my ($self, $where) = @_;
1487 # Special case: top level simple string treated as literal
1489 my $where_exp = (ref($where)
1490 ? $self->_expand_select_clause_where(undef, $where)
1491 : { -literal => [ $where ] });
1493 # dispatch expanded expression
1495 my ($sql, @bind) = defined($where_exp) ? @{ $self->render_aqt($where_exp) || [] } : ();
1496 # DBIx::Class used to call _recurse_where in scalar context
1497 # something else might too...
1499 return ($sql, @bind);
1502 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
1508 my ($self, undef, $ident) = @_;
1510 return [ $self->_quote($ident) ];
1514 my ($self, undef, $values) = @_;
1515 return $self->join_query_parts('',
1517 $self->_render_op(undef, [ ',', @$values ]),
1523 my ($self, undef, $rest) = @_;
1524 my ($func, @args) = @$rest;
1525 return $self->join_query_parts('',
1526 $self->_sqlcase($func),
1527 $self->join_query_parts('',
1529 $self->join_query_parts(', ', @args),
1536 my ($self, undef, $bind) = @_;
1537 return [ '?', $self->_bindtype(@$bind) ];
1540 sub _render_literal {
1541 my ($self, undef, $literal) = @_;
1542 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1546 sub _render_keyword {
1547 my ($self, undef, $keyword) = @_;
1548 return [ $self->_sqlcase(
1549 ref($keyword) ? $$keyword : join ' ', split '_', $keyword
1554 my ($self, undef, $v) = @_;
1555 my ($op, @args) = @$v;
1556 if (my $r = $self->{render_op}{$op}) {
1557 return $self->$r($op, \@args);
1562 my $op = join(' ', split '_', $op);
1564 my $ss = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1565 if ($ss and @args > 1) {
1566 puke "Special op '${op}' requires first value to be identifier"
1567 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1568 my $k = join(($self->{name_sep}||'.'), @$ident);
1569 local our $Expand_Depth = 1;
1570 return [ $self->${\($ss->{handler})}($k, $op, $args[1]) ];
1572 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1573 return [ $self->${\($us->{handler})}($op, $args[0]) ];
1576 return $self->_render_unop_paren($op, \@args);
1580 return $self->_render_unop_prefix($op, \@args);
1582 return $self->_render_op_multop($op, \@args);
1588 sub _render_op_between {
1589 my ($self, $op, $args) = @_;
1590 my ($left, $low, $high) = @$args;
1593 puke "Single arg to between must be a literal"
1594 unless $low->{-literal};
1597 +($low, { -keyword => 'and' }, $high);
1600 return $self->join_query_parts(' ',
1601 '(', $left, { -keyword => $op }, @rh, ')',
1606 my ($self, $op, $args) = @_;
1607 my ($lhs, @rhs) = @$args;
1609 return $self->join_query_parts(' ',
1611 { -keyword => $op },
1612 $self->join_query_parts(' ',
1614 $self->join_query_parts(', ', @rhs),
1620 sub _render_op_andor {
1621 my ($self, $op, $args) = @_;
1622 return undef unless @$args;
1623 return $self->join_query_parts('', $args->[0]) if @$args == 1;
1624 my $inner = $self->_render_op_multop($op, $args);
1625 return undef unless defined($inner->[0]) and length($inner->[0]);
1626 return $self->join_query_parts(' ',
1631 sub _render_op_multop {
1632 my ($self, $op, $args) = @_;
1634 return undef unless @parts;
1635 return $self->render_aqt($parts[0]) if @parts == 1;
1636 my $join = ($op eq ','
1638 : { -keyword => " ${op} " }
1640 return $self->join_query_parts($join, @parts);
1643 sub _render_values {
1644 my ($self, undef, $values) = @_;
1645 my $inner = $self->join_query_parts(' ',
1646 { -keyword => 'values' },
1647 $self->join_query_parts(', ',
1648 ref($values) eq 'ARRAY' ? @$values : $values
1651 return $self->join_query_parts('',
1652 (our $Render_Top_Level ? $inner : ('(', $inner, ')'))
1656 sub join_query_parts {
1657 my ($self, $join, @parts) = @_;
1658 if (ref($join) eq 'HASH') {
1659 $join = $self->render_aqt($join)->[0];
1663 ? $self->render_aqt($_)
1664 : ((ref($_) eq 'ARRAY') ? $_ : [ $_ ])
1667 $self->{join_sql_parts}->(
1668 $join, grep defined && length, map $_->[0], @final
1670 (map @{$_}[1..$#$_], @final),
1674 sub _render_unop_paren {
1675 my ($self, $op, $v) = @_;
1676 return $self->join_query_parts('',
1677 '(', $self->_render_unop_prefix($op, $v), ')'
1681 sub _render_unop_prefix {
1682 my ($self, $op, $v) = @_;
1683 my $op_sql = $self->{restore_old_unop_handling}
1684 ? $self->_sqlcase($op)
1685 : { -keyword => $op };
1686 return $self->join_query_parts(' ',
1687 ($self->{restore_old_unop_handling}
1688 ? $self->_sqlcase($op)
1689 : { -keyword => \$op }),
1694 sub _render_unop_postfix {
1695 my ($self, $op, $v) = @_;
1696 return $self->join_query_parts(' ',
1697 $v->[0], { -keyword => $op },
1701 # Some databases (SQLite) treat col IN (1, 2) different from
1702 # col IN ( (1, 2) ). Use this to strip all outer parens while
1703 # adding them back in the corresponding method
1704 sub _open_outer_paren {
1705 my ($self, $sql) = @_;
1707 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1709 # there are closing parens inside, need the heavy duty machinery
1710 # to reevaluate the extraction starting from $sql (full reevaluation)
1711 if ($inner =~ /\)/) {
1712 require Text::Balanced;
1714 my (undef, $remainder) = do {
1715 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1717 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1720 # the entire expression needs to be a balanced bracketed thing
1721 # (after an extract no remainder sans trailing space)
1722 last if defined $remainder and $remainder =~ /\S/;
1731 sub _where_field_IN {
1732 my ($self, $k, $op, $vals) = @_;
1733 @{$self->_render_op_in(
1736 $self->expand_expr($k, -ident),
1737 map $self->expand_expr($_, -value),
1738 ref($vals) eq 'ARRAY' ? @$vals : $vals
1743 sub _where_field_BETWEEN {
1744 my ($self, $k, $op, $vals) = @_;
1745 @{$self->_render_op_between(
1747 [ $self->expand_expr($k, -ident), ref($vals) eq 'ARRAY' ? @$vals : $vals ]
1751 #======================================================================
1753 #======================================================================
1755 sub _expand_order_by {
1756 my ($self, $arg) = @_;
1758 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1760 return $self->expand_expr({ -list => $arg })
1761 if ref($arg) eq 'HASH' and ($arg->{-op}||[''])->[0] eq ',';
1763 my $expander = sub {
1764 my ($self, $dir, $expr) = @_;
1765 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1766 foreach my $arg (@to_expand) {
1770 and grep /^-(asc|desc)$/, keys %$arg
1772 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1776 defined($dir) ? { -op => [ $dir =~ /^-?(.*)$/ ,=> $_ ] } : $_
1778 map $self->expand_expr($_, -ident),
1779 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
1780 return undef unless @exp;
1781 return undef if @exp == 1 and not defined($exp[0]);
1782 return +{ -op => [ ',', @exp ] };
1785 local @{$self->{expand}}{qw(asc desc)} = (($expander) x 2);
1787 return $self->$expander(undef, $arg);
1791 my ($self, $arg) = @_;
1793 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
1795 my ($sql, @bind) = @{ $self->render_aqt($expanded) };
1797 return '' unless length($sql);
1799 my $final_sql = $self->_sqlcase(' order by ').$sql;
1801 return $final_sql unless wantarray;
1803 return ($final_sql, @bind);
1806 # _order_by no longer needs to call this so doesn't but DBIC uses it.
1808 sub _order_by_chunks {
1809 my ($self, $arg) = @_;
1811 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1813 my @res = $self->_chunkify_order_by($expanded);
1814 (ref() ? $_->[0] : $_) .= '' for @res;
1818 sub _chunkify_order_by {
1819 my ($self, $expanded) = @_;
1821 return grep length, @{ $self->render_aqt($expanded) }
1822 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1825 if (ref() eq 'HASH' and $_->{-op} and $_->{-op}[0] eq ',') {
1826 my ($comma, @list) = @{$_->{-op}};
1827 return map $self->_chunkify_order_by($_), @list;
1829 return $self->render_aqt($_);
1833 #======================================================================
1834 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1835 #======================================================================
1841 $self->expand_expr({ -list => $from }, -ident)
1846 #======================================================================
1848 #======================================================================
1850 # highly optimized, as it's called way too often
1852 # my ($self, $label) = @_;
1854 return '' unless defined $_[1];
1855 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1856 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1858 unless ($_[0]->{quote_char}) {
1859 if (ref($_[1]) eq 'ARRAY') {
1860 return join($_[0]->{name_sep}||'.', @{$_[1]});
1862 $_[0]->_assert_pass_injection_guard($_[1]);
1867 my $qref = ref $_[0]->{quote_char};
1869 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1870 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1871 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1873 my $esc = $_[0]->{escape_char} || $r;
1875 # parts containing * are naturally unquoted
1877 $_[0]->{name_sep}||'',
1881 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1883 (ref($_[1]) eq 'ARRAY'
1887 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1895 # Conversion, if applicable
1897 #my ($self, $arg) = @_;
1898 if (my $conv = $_[0]->{convert_where}) {
1899 return @{ $_[0]->join_query_parts('',
1900 $_[0]->_sqlcase($conv),
1909 #my ($self, $col, @vals) = @_;
1910 # called often - tighten code
1911 return $_[0]->{bindtype} eq 'columns'
1912 ? map {[$_[1], $_]} @_[2 .. $#_]
1917 # Dies if any element of @bind is not in [colname => value] format
1918 # if bindtype is 'columns'.
1919 sub _assert_bindval_matches_bindtype {
1920 # my ($self, @bind) = @_;
1922 if ($self->{bindtype} eq 'columns') {
1924 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1925 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1931 # Fix SQL case, if so requested
1933 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1934 # don't touch the argument ... crooked logic, but let's not change it!
1935 return $_[0]->{case} ? $_[1] : uc($_[1]);
1938 #======================================================================
1939 # DISPATCHING FROM REFKIND
1940 #======================================================================
1943 my ($self, $data) = @_;
1945 return 'UNDEF' unless defined $data;
1947 # blessed objects are treated like scalars
1948 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1950 return 'SCALAR' unless $ref;
1953 while ($ref eq 'REF') {
1955 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1959 return ($ref||'SCALAR') . ('REF' x $n_steps);
1963 my ($self, $data) = @_;
1964 my @try = ($self->_refkind($data));
1965 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1966 push @try, 'FALLBACK';
1970 sub _METHOD_FOR_refkind {
1971 my ($self, $meth_prefix, $data) = @_;
1974 for (@{$self->_try_refkind($data)}) {
1975 $method = $self->can($meth_prefix."_".$_)
1979 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1983 sub _SWITCH_refkind {
1984 my ($self, $data, $dispatch_table) = @_;
1987 for (@{$self->_try_refkind($data)}) {
1988 $coderef = $dispatch_table->{$_}
1992 puke "no dispatch entry for ".$self->_refkind($data)
2001 #======================================================================
2002 # VALUES, GENERATE, AUTOLOAD
2003 #======================================================================
2005 # LDNOTE: original code from nwiger, didn't touch code in that section
2006 # I feel the AUTOLOAD stuff should not be the default, it should
2007 # only be activated on explicit demand by user.
2011 my $data = shift || return;
2012 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
2013 unless ref $data eq 'HASH';
2016 foreach my $k (sort keys %$data) {
2017 my $v = $data->{$k};
2018 $self->_SWITCH_refkind($v, {
2020 if ($self->{array_datatypes}) { # array datatype
2021 push @all_bind, $self->_bindtype($k, $v);
2023 else { # literal SQL with bind
2024 my ($sql, @bind) = @$v;
2025 $self->_assert_bindval_matches_bindtype(@bind);
2026 push @all_bind, @bind;
2029 ARRAYREFREF => sub { # literal SQL with bind
2030 my ($sql, @bind) = @${$v};
2031 $self->_assert_bindval_matches_bindtype(@bind);
2032 push @all_bind, @bind;
2034 SCALARREF => sub { # literal SQL without bind
2036 SCALAR_or_UNDEF => sub {
2037 push @all_bind, $self->_bindtype($k, $v);
2048 my(@sql, @sqlq, @sqlv);
2052 if ($ref eq 'HASH') {
2053 for my $k (sort keys %$_) {
2056 my $label = $self->_quote($k);
2057 if ($r eq 'ARRAY') {
2058 # literal SQL with bind
2059 my ($sql, @bind) = @$v;
2060 $self->_assert_bindval_matches_bindtype(@bind);
2061 push @sqlq, "$label = $sql";
2063 } elsif ($r eq 'SCALAR') {
2064 # literal SQL without bind
2065 push @sqlq, "$label = $$v";
2067 push @sqlq, "$label = ?";
2068 push @sqlv, $self->_bindtype($k, $v);
2071 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
2072 } elsif ($ref eq 'ARRAY') {
2073 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
2076 if ($r eq 'ARRAY') { # literal SQL with bind
2077 my ($sql, @bind) = @$v;
2078 $self->_assert_bindval_matches_bindtype(@bind);
2081 } elsif ($r eq 'SCALAR') { # literal SQL without bind
2082 # embedded literal SQL
2089 push @sql, '(' . join(', ', @sqlq) . ')';
2090 } elsif ($ref eq 'SCALAR') {
2094 # strings get case twiddled
2095 push @sql, $self->_sqlcase($_);
2099 my $sql = join ' ', @sql;
2101 # this is pretty tricky
2102 # if ask for an array, return ($stmt, @bind)
2103 # otherwise, s/?/shift @sqlv/ to put it inline
2105 return ($sql, @sqlv);
2107 1 while $sql =~ s/\?/my $d = shift(@sqlv);
2108 ref $d ? $d->[1] : $d/e;
2117 # This allows us to check for a local, then _form, attr
2119 my($name) = $AUTOLOAD =~ /.*::(.+)/;
2120 puke "AUTOLOAD invoked for method name ${name} and allow_autoload option not set" unless $self->{allow_autoload};
2121 return $self->generate($name, @_);
2132 SQL::Abstract - Generate SQL from Perl data structures
2138 my $sql = SQL::Abstract->new;
2140 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
2142 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
2144 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
2146 my($stmt, @bind) = $sql->delete($table, \%where);
2148 # Then, use these in your DBI statements
2149 my $sth = $dbh->prepare($stmt);
2150 $sth->execute(@bind);
2152 # Just generate the WHERE clause
2153 my($stmt, @bind) = $sql->where(\%where, $order);
2155 # Return values in the same order, for hashed queries
2156 # See PERFORMANCE section for more details
2157 my @bind = $sql->values(\%fieldvals);
2161 This module was inspired by the excellent L<DBIx::Abstract>.
2162 However, in using that module I found that what I really wanted
2163 to do was generate SQL, but still retain complete control over my
2164 statement handles and use the DBI interface. So, I set out to
2165 create an abstract SQL generation module.
2167 While based on the concepts used by L<DBIx::Abstract>, there are
2168 several important differences, especially when it comes to WHERE
2169 clauses. I have modified the concepts used to make the SQL easier
2170 to generate from Perl data structures and, IMO, more intuitive.
2171 The underlying idea is for this module to do what you mean, based
2172 on the data structures you provide it. The big advantage is that
2173 you don't have to modify your code every time your data changes,
2174 as this module figures it out.
2176 To begin with, an SQL INSERT is as easy as just specifying a hash
2177 of C<key=value> pairs:
2180 name => 'Jimbo Bobson',
2181 phone => '123-456-7890',
2182 address => '42 Sister Lane',
2183 city => 'St. Louis',
2184 state => 'Louisiana',
2187 The SQL can then be generated with this:
2189 my($stmt, @bind) = $sql->insert('people', \%data);
2191 Which would give you something like this:
2193 $stmt = "INSERT INTO people
2194 (address, city, name, phone, state)
2195 VALUES (?, ?, ?, ?, ?)";
2196 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
2197 '123-456-7890', 'Louisiana');
2199 These are then used directly in your DBI code:
2201 my $sth = $dbh->prepare($stmt);
2202 $sth->execute(@bind);
2204 =head2 Inserting and Updating Arrays
2206 If your database has array types (like for example Postgres),
2207 activate the special option C<< array_datatypes => 1 >>
2208 when creating the C<SQL::Abstract> object.
2209 Then you may use an arrayref to insert and update database array types:
2211 my $sql = SQL::Abstract->new(array_datatypes => 1);
2213 planets => [qw/Mercury Venus Earth Mars/]
2216 my($stmt, @bind) = $sql->insert('solar_system', \%data);
2220 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
2222 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
2225 =head2 Inserting and Updating SQL
2227 In order to apply SQL functions to elements of your C<%data> you may
2228 specify a reference to an arrayref for the given hash value. For example,
2229 if you need to execute the Oracle C<to_date> function on a value, you can
2230 say something like this:
2234 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
2237 The first value in the array is the actual SQL. Any other values are
2238 optional and would be included in the bind values array. This gives
2241 my($stmt, @bind) = $sql->insert('people', \%data);
2243 $stmt = "INSERT INTO people (name, date_entered)
2244 VALUES (?, to_date(?,'MM/DD/YYYY'))";
2245 @bind = ('Bill', '03/02/2003');
2247 An UPDATE is just as easy, all you change is the name of the function:
2249 my($stmt, @bind) = $sql->update('people', \%data);
2251 Notice that your C<%data> isn't touched; the module will generate
2252 the appropriately quirky SQL for you automatically. Usually you'll
2253 want to specify a WHERE clause for your UPDATE, though, which is
2254 where handling C<%where> hashes comes in handy...
2256 =head2 Complex where statements
2258 This module can generate pretty complicated WHERE statements
2259 easily. For example, simple C<key=value> pairs are taken to mean
2260 equality, and if you want to see if a field is within a set
2261 of values, you can use an arrayref. Let's say we wanted to
2262 SELECT some data based on this criteria:
2265 requestor => 'inna',
2266 worker => ['nwiger', 'rcwe', 'sfz'],
2267 status => { '!=', 'completed' }
2270 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
2272 The above would give you something like this:
2274 $stmt = "SELECT * FROM tickets WHERE
2275 ( requestor = ? ) AND ( status != ? )
2276 AND ( worker = ? OR worker = ? OR worker = ? )";
2277 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
2279 Which you could then use in DBI code like so:
2281 my $sth = $dbh->prepare($stmt);
2282 $sth->execute(@bind);
2288 The methods are simple. There's one for every major SQL operation,
2289 and a constructor you use first. The arguments are specified in a
2290 similar order for each method (table, then fields, then a where
2291 clause) to try and simplify things.
2293 =head2 new(option => 'value')
2295 The C<new()> function takes a list of options and values, and returns
2296 a new B<SQL::Abstract> object which can then be used to generate SQL
2297 through the methods below. The options accepted are:
2303 If set to 'lower', then SQL will be generated in all lowercase. By
2304 default SQL is generated in "textbook" case meaning something like:
2306 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
2308 Any setting other than 'lower' is ignored.
2312 This determines what the default comparison operator is. By default
2313 it is C<=>, meaning that a hash like this:
2315 %where = (name => 'nwiger', email => 'nate@wiger.org');
2317 Will generate SQL like this:
2319 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
2321 However, you may want loose comparisons by default, so if you set
2322 C<cmp> to C<like> you would get SQL such as:
2324 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
2326 You can also override the comparison on an individual basis - see
2327 the huge section on L</"WHERE CLAUSES"> at the bottom.
2329 =item sqltrue, sqlfalse
2331 Expressions for inserting boolean values within SQL statements.
2332 By default these are C<1=1> and C<1=0>. They are used
2333 by the special operators C<-in> and C<-not_in> for generating
2334 correct SQL even when the argument is an empty array (see below).
2338 This determines the default logical operator for multiple WHERE
2339 statements in arrays or hashes. If absent, the default logic is "or"
2340 for arrays, and "and" for hashes. This means that a WHERE
2344 event_date => {'>=', '2/13/99'},
2345 event_date => {'<=', '4/24/03'},
2348 will generate SQL like this:
2350 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
2352 This is probably not what you want given this query, though (look
2353 at the dates). To change the "OR" to an "AND", simply specify:
2355 my $sql = SQL::Abstract->new(logic => 'and');
2357 Which will change the above C<WHERE> to:
2359 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
2361 The logic can also be changed locally by inserting
2362 a modifier in front of an arrayref:
2364 @where = (-and => [event_date => {'>=', '2/13/99'},
2365 event_date => {'<=', '4/24/03'} ]);
2367 See the L</"WHERE CLAUSES"> section for explanations.
2371 This will automatically convert comparisons using the specified SQL
2372 function for both column and value. This is mostly used with an argument
2373 of C<upper> or C<lower>, so that the SQL will have the effect of
2374 case-insensitive "searches". For example, this:
2376 $sql = SQL::Abstract->new(convert => 'upper');
2377 %where = (keywords => 'MaKe iT CAse inSeNSItive');
2379 Will turn out the following SQL:
2381 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
2383 The conversion can be C<upper()>, C<lower()>, or any other SQL function
2384 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
2385 not validate this option; it will just pass through what you specify verbatim).
2389 This is a kludge because many databases suck. For example, you can't
2390 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
2391 Instead, you have to use C<bind_param()>:
2393 $sth->bind_param(1, 'reg data');
2394 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
2396 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
2397 which loses track of which field each slot refers to. Fear not.
2399 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
2400 Currently, you can specify either C<normal> (default) or C<columns>. If you
2401 specify C<columns>, you will get an array that looks like this:
2403 my $sql = SQL::Abstract->new(bindtype => 'columns');
2404 my($stmt, @bind) = $sql->insert(...);
2407 [ 'column1', 'value1' ],
2408 [ 'column2', 'value2' ],
2409 [ 'column3', 'value3' ],
2412 You can then iterate through this manually, using DBI's C<bind_param()>.
2414 $sth->prepare($stmt);
2417 my($col, $data) = @$_;
2418 if ($col eq 'details' || $col eq 'comments') {
2419 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
2420 } elsif ($col eq 'image') {
2421 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
2423 $sth->bind_param($i, $data);
2427 $sth->execute; # execute without @bind now
2429 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
2430 Basically, the advantage is still that you don't have to care which fields
2431 are or are not included. You could wrap that above C<for> loop in a simple
2432 sub called C<bind_fields()> or something and reuse it repeatedly. You still
2433 get a layer of abstraction over manual SQL specification.
2435 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
2436 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
2437 will expect the bind values in this format.
2441 This is the character that a table or column name will be quoted
2442 with. By default this is an empty string, but you could set it to
2443 the character C<`>, to generate SQL like this:
2445 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
2447 Alternatively, you can supply an array ref of two items, the first being the left
2448 hand quote character, and the second the right hand quote character. For
2449 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
2450 that generates SQL like this:
2452 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
2454 Quoting is useful if you have tables or columns names that are reserved
2455 words in your database's SQL dialect.
2459 This is the character that will be used to escape L</quote_char>s appearing
2460 in an identifier before it has been quoted.
2462 The parameter default in case of a single L</quote_char> character is the quote
2465 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
2466 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
2467 of the B<opening (left)> L</quote_char> within the identifier are currently left
2468 untouched. The default for opening-closing-style quotes may change in future
2469 versions, thus you are B<strongly encouraged> to specify the escape character
2474 This is the character that separates a table and column name. It is
2475 necessary to specify this when the C<quote_char> option is selected,
2476 so that tables and column names can be individually quoted like this:
2478 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2480 =item injection_guard
2482 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2483 column name specified in a query structure. This is a safety mechanism to avoid
2484 injection attacks when mishandling user input e.g.:
2486 my %condition_as_column_value_pairs = get_values_from_user();
2487 $sqla->select( ... , \%condition_as_column_value_pairs );
2489 If the expression matches an exception is thrown. Note that literal SQL
2490 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2492 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2494 =item array_datatypes
2496 When this option is true, arrayrefs in INSERT or UPDATE are
2497 interpreted as array datatypes and are passed directly
2499 When this option is false, arrayrefs are interpreted
2500 as literal SQL, just like refs to arrayrefs
2501 (but this behavior is for backwards compatibility; when writing
2502 new queries, use the "reference to arrayref" syntax
2508 Takes a reference to a list of "special operators"
2509 to extend the syntax understood by L<SQL::Abstract>.
2510 See section L</"SPECIAL OPERATORS"> for details.
2514 Takes a reference to a list of "unary operators"
2515 to extend the syntax understood by L<SQL::Abstract>.
2516 See section L</"UNARY OPERATORS"> for details.
2522 =head2 insert($table, \@values || \%fieldvals, \%options)
2524 This is the simplest function. You simply give it a table name
2525 and either an arrayref of values or hashref of field/value pairs.
2526 It returns an SQL INSERT statement and a list of bind values.
2527 See the sections on L</"Inserting and Updating Arrays"> and
2528 L</"Inserting and Updating SQL"> for information on how to insert
2529 with those data types.
2531 The optional C<\%options> hash reference may contain additional
2532 options to generate the insert SQL. Currently supported options
2539 Takes either a scalar of raw SQL fields, or an array reference of
2540 field names, and adds on an SQL C<RETURNING> statement at the end.
2541 This allows you to return data generated by the insert statement
2542 (such as row IDs) without performing another C<SELECT> statement.
2543 Note, however, this is not part of the SQL standard and may not
2544 be supported by all database engines.
2548 =head2 update($table, \%fieldvals, \%where, \%options)
2550 This takes a table, hashref of field/value pairs, and an optional
2551 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2553 See the sections on L</"Inserting and Updating Arrays"> and
2554 L</"Inserting and Updating SQL"> for information on how to insert
2555 with those data types.
2557 The optional C<\%options> hash reference may contain additional
2558 options to generate the update SQL. Currently supported options
2565 See the C<returning> option to
2566 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2570 =head2 select($source, $fields, $where, $order)
2572 This returns a SQL SELECT statement and associated list of bind values, as
2573 specified by the arguments:
2579 Specification of the 'FROM' part of the statement.
2580 The argument can be either a plain scalar (interpreted as a table
2581 name, will be quoted), or an arrayref (interpreted as a list
2582 of table names, joined by commas, quoted), or a scalarref
2583 (literal SQL, not quoted).
2587 Specification of the list of fields to retrieve from
2589 The argument can be either an arrayref (interpreted as a list
2590 of field names, will be joined by commas and quoted), or a
2591 plain scalar (literal SQL, not quoted).
2592 Please observe that this API is not as flexible as that of
2593 the first argument C<$source>, for backwards compatibility reasons.
2597 Optional argument to specify the WHERE part of the query.
2598 The argument is most often a hashref, but can also be
2599 an arrayref or plain scalar --
2600 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2604 Optional argument to specify the ORDER BY part of the query.
2605 The argument can be a scalar, a hashref or an arrayref
2606 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2612 =head2 delete($table, \%where, \%options)
2614 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2615 It returns an SQL DELETE statement and list of bind values.
2617 The optional C<\%options> hash reference may contain additional
2618 options to generate the delete SQL. Currently supported options
2625 See the C<returning> option to
2626 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2630 =head2 where(\%where, $order)
2632 This is used to generate just the WHERE clause. For example,
2633 if you have an arbitrary data structure and know what the
2634 rest of your SQL is going to look like, but want an easy way
2635 to produce a WHERE clause, use this. It returns an SQL WHERE
2636 clause and list of bind values.
2639 =head2 values(\%data)
2641 This just returns the values from the hash C<%data>, in the same
2642 order that would be returned from any of the other above queries.
2643 Using this allows you to markedly speed up your queries if you
2644 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2646 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2648 Warning: This is an experimental method and subject to change.
2650 This returns arbitrarily generated SQL. It's a really basic shortcut.
2651 It will return two different things, depending on return context:
2653 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2654 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2656 These would return the following:
2658 # First calling form
2659 $stmt = "CREATE TABLE test (?, ?)";
2660 @bind = (field1, field2);
2662 # Second calling form
2663 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2665 Depending on what you're trying to do, it's up to you to choose the correct
2666 format. In this example, the second form is what you would want.
2670 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2674 ALTER SESSION SET nls_date_format = 'MM/YY'
2676 You get the idea. Strings get their case twiddled, but everything
2677 else remains verbatim.
2679 =head1 EXPORTABLE FUNCTIONS
2681 =head2 is_plain_value
2683 Determines if the supplied argument is a plain value as understood by this
2688 =item * The value is C<undef>
2690 =item * The value is a non-reference
2692 =item * The value is an object with stringification overloading
2694 =item * The value is of the form C<< { -value => $anything } >>
2698 On failure returns C<undef>, on success returns a B<scalar> reference
2699 to the original supplied argument.
2705 The stringification overloading detection is rather advanced: it takes
2706 into consideration not only the presence of a C<""> overload, but if that
2707 fails also checks for enabled
2708 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2709 on either C<0+> or C<bool>.
2711 Unfortunately testing in the field indicates that this
2712 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2713 but only when very large numbers of stringifying objects are involved.
2714 At the time of writing ( Sep 2014 ) there is no clear explanation of
2715 the direct cause, nor is there a manageably small test case that reliably
2716 reproduces the problem.
2718 If you encounter any of the following exceptions in B<random places within
2719 your application stack> - this module may be to blame:
2721 Operation "ne": no method found,
2722 left argument in overloaded package <something>,
2723 right argument in overloaded package <something>
2727 Stub found while resolving method "???" overloading """" in package <something>
2729 If you fall victim to the above - please attempt to reduce the problem
2730 to something that could be sent to the L<SQL::Abstract developers
2731 |DBIx::Class/GETTING HELP/SUPPORT>
2732 (either publicly or privately). As a workaround in the meantime you can
2733 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2734 value, which will most likely eliminate your problem (at the expense of
2735 not being able to properly detect exotic forms of stringification).
2737 This notice and environment variable will be removed in a future version,
2738 as soon as the underlying problem is found and a reliable workaround is
2743 =head2 is_literal_value
2745 Determines if the supplied argument is a literal value as understood by this
2750 =item * C<\$sql_string>
2752 =item * C<\[ $sql_string, @bind_values ]>
2756 On failure returns C<undef>, on success returns an B<array> reference
2757 containing the unpacked version of the supplied literal SQL and bind values.
2759 =head2 is_undef_value
2761 Tests for undef, whether expanded or not.
2763 =head1 WHERE CLAUSES
2767 This module uses a variation on the idea from L<DBIx::Abstract>. It
2768 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2769 module is that things in arrays are OR'ed, and things in hashes
2772 The easiest way to explain is to show lots of examples. After
2773 each C<%where> hash shown, it is assumed you used:
2775 my($stmt, @bind) = $sql->where(\%where);
2777 However, note that the C<%where> hash can be used directly in any
2778 of the other functions as well, as described above.
2780 =head2 Key-value pairs
2782 So, let's get started. To begin, a simple hash:
2786 status => 'completed'
2789 Is converted to SQL C<key = val> statements:
2791 $stmt = "WHERE user = ? AND status = ?";
2792 @bind = ('nwiger', 'completed');
2794 One common thing I end up doing is having a list of values that
2795 a field can be in. To do this, simply specify a list inside of
2800 status => ['assigned', 'in-progress', 'pending'];
2803 This simple code will create the following:
2805 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2806 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2808 A field associated to an empty arrayref will be considered a
2809 logical false and will generate 0=1.
2811 =head2 Tests for NULL values
2813 If the value part is C<undef> then this is converted to SQL <IS NULL>
2822 $stmt = "WHERE user = ? AND status IS NULL";
2825 To test if a column IS NOT NULL:
2829 status => { '!=', undef },
2832 =head2 Specific comparison operators
2834 If you want to specify a different type of operator for your comparison,
2835 you can use a hashref for a given column:
2839 status => { '!=', 'completed' }
2842 Which would generate:
2844 $stmt = "WHERE user = ? AND status != ?";
2845 @bind = ('nwiger', 'completed');
2847 To test against multiple values, just enclose the values in an arrayref:
2849 status => { '=', ['assigned', 'in-progress', 'pending'] };
2851 Which would give you:
2853 "WHERE status = ? OR status = ? OR status = ?"
2856 The hashref can also contain multiple pairs, in which case it is expanded
2857 into an C<AND> of its elements:
2861 status => { '!=', 'completed', -not_like => 'pending%' }
2864 # Or more dynamically, like from a form
2865 $where{user} = 'nwiger';
2866 $where{status}{'!='} = 'completed';
2867 $where{status}{'-not_like'} = 'pending%';
2869 # Both generate this
2870 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2871 @bind = ('nwiger', 'completed', 'pending%');
2874 To get an OR instead, you can combine it with the arrayref idea:
2878 priority => [ { '=', 2 }, { '>', 5 } ]
2881 Which would generate:
2883 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2884 @bind = ('2', '5', 'nwiger');
2886 If you want to include literal SQL (with or without bind values), just use a
2887 scalar reference or reference to an arrayref as the value:
2890 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2891 date_expires => { '<' => \"now()" }
2894 Which would generate:
2896 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2897 @bind = ('11/26/2008');
2900 =head2 Logic and nesting operators
2902 In the example above,
2903 there is a subtle trap if you want to say something like
2904 this (notice the C<AND>):
2906 WHERE priority != ? AND priority != ?
2908 Because, in Perl you I<can't> do this:
2910 priority => { '!=' => 2, '!=' => 1 }
2912 As the second C<!=> key will obliterate the first. The solution
2913 is to use the special C<-modifier> form inside an arrayref:
2915 priority => [ -and => {'!=', 2},
2919 Normally, these would be joined by C<OR>, but the modifier tells it
2920 to use C<AND> instead. (Hint: You can use this in conjunction with the
2921 C<logic> option to C<new()> in order to change the way your queries
2922 work by default.) B<Important:> Note that the C<-modifier> goes
2923 B<INSIDE> the arrayref, as an extra first element. This will
2924 B<NOT> do what you think it might:
2926 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2928 Here is a quick list of equivalencies, since there is some overlap:
2931 status => {'!=', 'completed', 'not like', 'pending%' }
2932 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2935 status => {'=', ['assigned', 'in-progress']}
2936 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2937 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2941 =head2 Special operators: IN, BETWEEN, etc.
2943 You can also use the hashref format to compare a list of fields using the
2944 C<IN> comparison operator, by specifying the list as an arrayref:
2947 status => 'completed',
2948 reportid => { -in => [567, 2335, 2] }
2951 Which would generate:
2953 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2954 @bind = ('completed', '567', '2335', '2');
2956 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2959 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2960 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2961 'sqltrue' (by default: C<1=1>).
2963 In addition to the array you can supply a chunk of literal sql or
2964 literal sql with bind:
2967 customer => { -in => \[
2968 'SELECT cust_id FROM cust WHERE balance > ?',
2971 status => { -in => \'SELECT status_codes FROM states' },
2977 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2978 AND status IN ( SELECT status_codes FROM states )
2982 Finally, if the argument to C<-in> is not a reference, it will be
2983 treated as a single-element array.
2985 Another pair of operators is C<-between> and C<-not_between>,
2986 used with an arrayref of two values:
2990 completion_date => {
2991 -not_between => ['2002-10-01', '2003-02-06']
2997 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2999 Just like with C<-in> all plausible combinations of literal SQL
3003 start0 => { -between => [ 1, 2 ] },
3004 start1 => { -between => \["? AND ?", 1, 2] },
3005 start2 => { -between => \"lower(x) AND upper(y)" },
3006 start3 => { -between => [
3008 \["upper(?)", 'stuff' ],
3015 ( start0 BETWEEN ? AND ? )
3016 AND ( start1 BETWEEN ? AND ? )
3017 AND ( start2 BETWEEN lower(x) AND upper(y) )
3018 AND ( start3 BETWEEN lower(x) AND upper(?) )
3020 @bind = (1, 2, 1, 2, 'stuff');
3023 These are the two builtin "special operators"; but the
3024 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
3026 =head2 Unary operators: bool
3028 If you wish to test against boolean columns or functions within your
3029 database you can use the C<-bool> and C<-not_bool> operators. For
3030 example to test the column C<is_user> being true and the column
3031 C<is_enabled> being false you would use:-
3035 -not_bool => 'is_enabled',
3040 WHERE is_user AND NOT is_enabled
3042 If a more complex combination is required, testing more conditions,
3043 then you should use the and/or operators:-
3048 -not_bool => { two=> { -rlike => 'bar' } },
3049 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
3060 (NOT ( three = ? OR three > ? ))
3063 =head2 Nested conditions, -and/-or prefixes
3065 So far, we've seen how multiple conditions are joined with a top-level
3066 C<AND>. We can change this by putting the different conditions we want in
3067 hashes and then putting those hashes in an array. For example:
3072 status => { -like => ['pending%', 'dispatched'] },
3076 status => 'unassigned',
3080 This data structure would create the following:
3082 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
3083 OR ( user = ? AND status = ? ) )";
3084 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
3087 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
3088 to change the logic inside:
3094 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
3095 -or => { workhrs => {'<', 50}, geo => 'EURO' },
3102 $stmt = "WHERE ( user = ?
3103 AND ( ( workhrs > ? AND geo = ? )
3104 OR ( workhrs < ? OR geo = ? ) ) )";
3105 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
3107 =head3 Algebraic inconsistency, for historical reasons
3109 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
3110 operator goes C<outside> of the nested structure; whereas when connecting
3111 several constraints on one column, the C<-and> operator goes
3112 C<inside> the arrayref. Here is an example combining both features:
3115 -and => [a => 1, b => 2],
3116 -or => [c => 3, d => 4],
3117 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
3122 WHERE ( ( ( a = ? AND b = ? )
3123 OR ( c = ? OR d = ? )
3124 OR ( e LIKE ? AND e LIKE ? ) ) )
3126 This difference in syntax is unfortunate but must be preserved for
3127 historical reasons. So be careful: the two examples below would
3128 seem algebraically equivalent, but they are not
3131 { -like => 'foo%' },
3132 { -like => '%bar' },
3134 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
3137 { col => { -like => 'foo%' } },
3138 { col => { -like => '%bar' } },
3140 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
3143 =head2 Literal SQL and value type operators
3145 The basic premise of SQL::Abstract is that in WHERE specifications the "left
3146 side" is a column name and the "right side" is a value (normally rendered as
3147 a placeholder). This holds true for both hashrefs and arrayref pairs as you
3148 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
3149 alter this behavior. There are several ways of doing so.
3153 This is a virtual operator that signals the string to its right side is an
3154 identifier (a column name) and not a value. For example to compare two
3155 columns you would write:
3158 priority => { '<', 2 },
3159 requestor => { -ident => 'submitter' },
3164 $stmt = "WHERE priority < ? AND requestor = submitter";
3167 If you are maintaining legacy code you may see a different construct as
3168 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
3173 This is a virtual operator that signals that the construct to its right side
3174 is a value to be passed to DBI. This is for example necessary when you want
3175 to write a where clause against an array (for RDBMS that support such
3176 datatypes). For example:
3179 array => { -value => [1, 2, 3] }
3184 $stmt = 'WHERE array = ?';
3185 @bind = ([1, 2, 3]);
3187 Note that if you were to simply say:
3193 the result would probably not be what you wanted:
3195 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
3200 Finally, sometimes only literal SQL will do. To include a random snippet
3201 of SQL verbatim, you specify it as a scalar reference. Consider this only
3202 as a last resort. Usually there is a better way. For example:
3205 priority => { '<', 2 },
3206 requestor => { -in => \'(SELECT name FROM hitmen)' },
3211 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
3214 Note that in this example, you only get one bind parameter back, since
3215 the verbatim SQL is passed as part of the statement.
3219 Never use untrusted input as a literal SQL argument - this is a massive
3220 security risk (there is no way to check literal snippets for SQL
3221 injections and other nastyness). If you need to deal with untrusted input
3222 use literal SQL with placeholders as described next.
3224 =head3 Literal SQL with placeholders and bind values (subqueries)
3226 If the literal SQL to be inserted has placeholders and bind values,
3227 use a reference to an arrayref (yes this is a double reference --
3228 not so common, but perfectly legal Perl). For example, to find a date
3229 in Postgres you can use something like this:
3232 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
3237 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
3240 Note that you must pass the bind values in the same format as they are returned
3241 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
3242 to C<columns>, you must provide the bind values in the
3243 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
3244 scalar value; most commonly the column name, but you can use any scalar value
3245 (including references and blessed references), L<SQL::Abstract> will simply
3246 pass it through intact. So if C<bindtype> is set to C<columns> the above
3247 example will look like:
3250 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
3253 Literal SQL is especially useful for nesting parenthesized clauses in the
3254 main SQL query. Here is a first example:
3256 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
3260 bar => \["IN ($sub_stmt)" => @sub_bind],
3265 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
3266 WHERE c2 < ? AND c3 LIKE ?))";
3267 @bind = (1234, 100, "foo%");
3269 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
3270 are expressed in the same way. Of course the C<$sub_stmt> and
3271 its associated bind values can be generated through a former call
3274 my ($sub_stmt, @sub_bind)
3275 = $sql->select("t1", "c1", {c2 => {"<" => 100},
3276 c3 => {-like => "foo%"}});
3279 bar => \["> ALL ($sub_stmt)" => @sub_bind],
3282 In the examples above, the subquery was used as an operator on a column;
3283 but the same principle also applies for a clause within the main C<%where>
3284 hash, like an EXISTS subquery:
3286 my ($sub_stmt, @sub_bind)
3287 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
3288 my %where = ( -and => [
3290 \["EXISTS ($sub_stmt)" => @sub_bind],
3295 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
3296 WHERE c1 = ? AND c2 > t0.c0))";
3300 Observe that the condition on C<c2> in the subquery refers to
3301 column C<t0.c0> of the main query: this is I<not> a bind
3302 value, so we have to express it through a scalar ref.
3303 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
3304 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
3305 what we wanted here.
3307 Finally, here is an example where a subquery is used
3308 for expressing unary negation:
3310 my ($sub_stmt, @sub_bind)
3311 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
3312 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
3314 lname => {like => '%son%'},
3315 \["NOT ($sub_stmt)" => @sub_bind],
3320 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
3321 @bind = ('%son%', 10, 20)
3323 =head3 Deprecated usage of Literal SQL
3325 Below are some examples of archaic use of literal SQL. It is shown only as
3326 reference for those who deal with legacy code. Each example has a much
3327 better, cleaner and safer alternative that users should opt for in new code.
3333 my %where = ( requestor => \'IS NOT NULL' )
3335 $stmt = "WHERE requestor IS NOT NULL"
3337 This used to be the way of generating NULL comparisons, before the handling
3338 of C<undef> got formalized. For new code please use the superior syntax as
3339 described in L</Tests for NULL values>.
3343 my %where = ( requestor => \'= submitter' )
3345 $stmt = "WHERE requestor = submitter"
3347 This used to be the only way to compare columns. Use the superior L</-ident>
3348 method for all new code. For example an identifier declared in such a way
3349 will be properly quoted if L</quote_char> is properly set, while the legacy
3350 form will remain as supplied.
3354 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
3356 $stmt = "WHERE completed > ? AND is_ready"
3357 @bind = ('2012-12-21')
3359 Using an empty string literal used to be the only way to express a boolean.
3360 For all new code please use the much more readable
3361 L<-bool|/Unary operators: bool> operator.
3367 These pages could go on for a while, since the nesting of the data
3368 structures this module can handle are pretty much unlimited (the
3369 module implements the C<WHERE> expansion as a recursive function
3370 internally). Your best bet is to "play around" with the module a
3371 little to see how the data structures behave, and choose the best
3372 format for your data based on that.
3374 And of course, all the values above will probably be replaced with
3375 variables gotten from forms or the command line. After all, if you
3376 knew everything ahead of time, you wouldn't have to worry about
3377 dynamically-generating SQL and could just hardwire it into your
3380 =head1 ORDER BY CLAUSES
3382 Some functions take an order by clause. This can either be a scalar (just a
3383 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
3384 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
3387 Given | Will Generate
3388 ---------------------------------------------------------------
3390 'colA' | ORDER BY colA
3392 [qw/colA colB/] | ORDER BY colA, colB
3394 {-asc => 'colA'} | ORDER BY colA ASC
3396 {-desc => 'colB'} | ORDER BY colB DESC
3398 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
3400 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
3402 \'colA DESC' | ORDER BY colA DESC
3404 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
3405 | /* ...with $x bound to ? */
3408 { -asc => 'colA' }, | colA ASC,
3409 { -desc => [qw/colB/] }, | colB DESC,
3410 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
3411 \'colE DESC', | colE DESC,
3412 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
3413 ] | /* ...with $x bound to ? */
3414 ===============================================================
3418 =head1 OLD EXTENSION SYSTEM
3420 =head2 SPECIAL OPERATORS
3422 my $sqlmaker = SQL::Abstract->new(special_ops => [
3426 my ($self, $field, $op, $arg) = @_;
3432 handler => 'method_name',
3436 A "special operator" is a SQL syntactic clause that can be
3437 applied to a field, instead of a usual binary operator.
3440 WHERE field IN (?, ?, ?)
3441 WHERE field BETWEEN ? AND ?
3442 WHERE MATCH(field) AGAINST (?, ?)
3444 Special operators IN and BETWEEN are fairly standard and therefore
3445 are builtin within C<SQL::Abstract> (as the overridable methods
3446 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
3447 like the MATCH .. AGAINST example above which is specific to MySQL,
3448 you can write your own operator handlers - supply a C<special_ops>
3449 argument to the C<new> method. That argument takes an arrayref of
3450 operator definitions; each operator definition is a hashref with two
3457 the regular expression to match the operator
3461 Either a coderef or a plain scalar method name. In both cases
3462 the expected return is C<< ($sql, @bind) >>.
3464 When supplied with a method name, it is simply called on the
3465 L<SQL::Abstract> object as:
3467 $self->$method_name($field, $op, $arg)
3471 $field is the LHS of the operator
3472 $op is the part that matched the handler regex
3475 When supplied with a coderef, it is called as:
3477 $coderef->($self, $field, $op, $arg)
3482 For example, here is an implementation
3483 of the MATCH .. AGAINST syntax for MySQL
3485 my $sqlmaker = SQL::Abstract->new(special_ops => [
3487 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3488 {regex => qr/^match$/i,
3490 my ($self, $field, $op, $arg) = @_;
3491 $arg = [$arg] if not ref $arg;
3492 my $label = $self->_quote($field);
3493 my ($placeholder) = $self->_convert('?');
3494 my $placeholders = join ", ", (($placeholder) x @$arg);
3495 my $sql = $self->_sqlcase('match') . " ($label) "
3496 . $self->_sqlcase('against') . " ($placeholders) ";
3497 my @bind = $self->_bindtype($field, @$arg);
3498 return ($sql, @bind);
3505 =head2 UNARY OPERATORS
3507 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3511 my ($self, $op, $arg) = @_;
3517 handler => 'method_name',
3521 A "unary operator" is a SQL syntactic clause that can be
3522 applied to a field - the operator goes before the field
3524 You can write your own operator handlers - supply a C<unary_ops>
3525 argument to the C<new> method. That argument takes an arrayref of
3526 operator definitions; each operator definition is a hashref with two
3533 the regular expression to match the operator
3537 Either a coderef or a plain scalar method name. In both cases
3538 the expected return is C<< $sql >>.
3540 When supplied with a method name, it is simply called on the
3541 L<SQL::Abstract> object as:
3543 $self->$method_name($op, $arg)
3547 $op is the part that matched the handler regex
3548 $arg is the RHS or argument of the operator
3550 When supplied with a coderef, it is called as:
3552 $coderef->($self, $op, $arg)
3557 =head1 NEW METHODS (EXPERIMENTAL)
3559 See L<SQL::Abstract::Reference> for the C<expr> versus C<aqt> concept and
3560 an explanation of what the below extensions are extending.
3564 $sqla->plugin('+Foo');
3566 Enables plugin SQL::Abstract::Plugin::Foo.
3570 my ($sql, @bind) = $sqla->render_expr($expr);
3572 =head2 render_statement
3574 Use this if you may be rendering a top level statement so e.g. a SELECT
3575 query doesn't get wrapped in parens
3577 my ($sql, @bind) = $sqla->render_statement($expr);
3581 Expression expansion with optional default for scalars.
3583 my $aqt = $self->expand_expr($expr);
3584 my $aqt = $self->expand_expr($expr, -ident);
3588 Top level means avoid parens on statement AQT.
3590 my $res = $self->render_aqt($aqt, $top_level);
3591 my ($sql, @bind) = @$res;
3593 =head2 join_query_parts
3595 Similar to join() but will render hashrefs as nodes for both join and parts,
3596 and treats arrayref as a nested C<[ $join, @parts ]> structure.
3598 my $part = $self->join_query_parts($join, @parts);
3600 =head1 NEW EXTENSION SYSTEM
3604 my $sqla2 = $sqla->clone;
3606 Performs a semi-shallow copy such that extension methods won't leak state
3607 but excessive depth is avoided.
3617 =head2 clause_expander
3619 =head2 clause_expanders
3621 $sqla->expander('name' => sub { ... });
3622 $sqla->expanders('name1' => sub { ... }, 'name2' => sub { ... });
3624 =head2 expander_list
3626 =head2 op_expander_list
3628 =head2 clause_expander_list
3630 my @names = $sqla->expander_list;
3632 =head2 wrap_expander
3634 =head2 wrap_expanders
3636 =head2 wrap_op_expander
3638 =head2 wrap_op_expanders
3640 =head2 wrap_clause_expander
3642 =head2 wrap_clause_expanders
3644 $sqla->wrap_expander('name' => sub { my ($orig) = @_; sub { ... } });
3645 $sqla->wrap_expanders(
3646 'name1' => sub { my ($orig1) = @_; sub { ... } },
3647 'name2' => sub { my ($orig2) = @_; sub { ... } },
3658 =head2 clause_renderer
3660 =head2 clause_renderers
3662 $sqla->renderer('name' => sub { ... });
3663 $sqla->renderers('name1' => sub { ... }, 'name2' => sub { ... });
3665 =head2 renderer_list
3667 =head2 op_renderer_list
3669 =head2 clause_renderer_list
3671 my @names = $sqla->renderer_list;
3673 =head2 wrap_renderer
3675 =head2 wrap_renderers
3677 =head2 wrap_op_renderer
3679 =head2 wrap_op_renderers
3681 =head2 wrap_clause_renderer
3683 =head2 wrap_clause_renderers
3685 $sqla->wrap_renderer('name' => sub { my ($orig) = @_; sub { ... } });
3686 $sqla->wrap_renderers(
3687 'name1' => sub { my ($orig1) = @_; sub { ... } },
3688 'name2' => sub { my ($orig2) = @_; sub { ... } },
3693 my @clauses = $sqla->clauses_of('select');
3694 $sqla->clauses_of(select => \@new_clauses);
3695 $sqla->clauses_of(select => sub {
3696 my (undef, @old_clauses) = @_;
3698 return @new_clauses;
3701 =head2 statement_list
3703 my @list = $sqla->statement_list;
3705 =head2 make_unop_expander
3707 my $exp = $sqla->make_unop_expander(sub { ... });
3709 If the op is found as a binop, assumes it wants a default comparison, so
3710 the inner expander sub can reliably operate as
3712 sub { my ($self, $name, $body) = @_; ... }
3714 =head2 make_binop_expander
3716 my $exp = $sqla->make_binop_expander(sub { ... });
3718 If the op is found as a unop, assumes the value will be an arrayref with the
3719 LHS as the first entry, and converts that to an ident node if it's a simple
3720 scalar. So the inner expander sub looks like
3723 my ($self, $name, $body, $k) = @_;
3724 { -blah => [ map $self->expand_expr($_), $k, $body ] }
3727 =head2 unop_expander
3729 =head2 unop_expanders
3731 =head2 binop_expander
3733 =head2 binop_expanders
3735 The above methods operate exactly like the op_ versions but wrap the coderef
3736 using the appropriate make_ method first.
3740 Thanks to some benchmarking by Mark Stosberg, it turns out that
3741 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3742 I must admit this wasn't an intentional design issue, but it's a
3743 byproduct of the fact that you get to control your C<DBI> handles
3746 To maximize performance, use a code snippet like the following:
3748 # prepare a statement handle using the first row
3749 # and then reuse it for the rest of the rows
3751 for my $href (@array_of_hashrefs) {
3752 $stmt ||= $sql->insert('table', $href);
3753 $sth ||= $dbh->prepare($stmt);
3754 $sth->execute($sql->values($href));
3757 The reason this works is because the keys in your C<$href> are sorted
3758 internally by B<SQL::Abstract>. Thus, as long as your data retains
3759 the same structure, you only have to generate the SQL the first time
3760 around. On subsequent queries, simply use the C<values> function provided
3761 by this module to return your values in the correct order.
3763 However this depends on the values having the same type - if, for
3764 example, the values of a where clause may either have values
3765 (resulting in sql of the form C<column = ?> with a single bind
3766 value), or alternatively the values might be C<undef> (resulting in
3767 sql of the form C<column IS NULL> with no bind value) then the
3768 caching technique suggested will not work.
3772 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3773 really like this part (I do, at least). Building up a complex query
3774 can be as simple as the following:
3781 use CGI::FormBuilder;
3784 my $form = CGI::FormBuilder->new(...);
3785 my $sql = SQL::Abstract->new;
3787 if ($form->submitted) {
3788 my $field = $form->field;
3789 my $id = delete $field->{id};
3790 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3793 Of course, you would still have to connect using C<DBI> to run the
3794 query, but the point is that if you make your form look like your
3795 table, the actual query script can be extremely simplistic.
3797 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3798 a fast interface to returning and formatting data. I frequently
3799 use these three modules together to write complex database query
3800 apps in under 50 lines.
3802 =head1 HOW TO CONTRIBUTE
3804 Contributions are always welcome, in all usable forms (we especially
3805 welcome documentation improvements). The delivery methods include git-
3806 or unified-diff formatted patches, GitHub pull requests, or plain bug
3807 reports either via RT or the Mailing list. Contributors are generally
3808 granted full access to the official repository after their first several
3809 patches pass successful review.
3811 This project is maintained in a git repository. The code and related tools are
3812 accessible at the following locations:
3816 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3818 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3820 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3822 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3828 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3829 Great care has been taken to preserve the I<published> behavior
3830 documented in previous versions in the 1.* family; however,
3831 some features that were previously undocumented, or behaved
3832 differently from the documentation, had to be changed in order
3833 to clarify the semantics. Hence, client code that was relying
3834 on some dark areas of C<SQL::Abstract> v1.*
3835 B<might behave differently> in v1.50.
3837 The main changes are:
3843 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3847 support for the { operator => \"..." } construct (to embed literal SQL)
3851 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3855 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3859 defensive programming: check arguments
3863 fixed bug with global logic, which was previously implemented
3864 through global variables yielding side-effects. Prior versions would
3865 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3866 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3867 Now this is interpreted
3868 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3873 fixed semantics of _bindtype on array args
3877 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3878 we just avoid shifting arrays within that tree.
3882 dropped the C<_modlogic> function
3886 =head1 ACKNOWLEDGEMENTS
3888 There are a number of individuals that have really helped out with
3889 this module. Unfortunately, most of them submitted bugs via CPAN
3890 so I have no idea who they are! But the people I do know are:
3892 Ash Berlin (order_by hash term support)
3893 Matt Trout (DBIx::Class support)
3894 Mark Stosberg (benchmarking)
3895 Chas Owens (initial "IN" operator support)
3896 Philip Collins (per-field SQL functions)
3897 Eric Kolve (hashref "AND" support)
3898 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3899 Dan Kubb (support for "quote_char" and "name_sep")
3900 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3901 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3902 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3903 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3904 Oliver Charles (support for "RETURNING" after "INSERT")
3910 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3914 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3916 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3918 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3919 While not an official support venue, C<DBIx::Class> makes heavy use of
3920 C<SQL::Abstract>, and as such list members there are very familiar with
3921 how to create queries.
3925 This module is free software; you may copy this under the same
3926 terms as perl itself (either the GNU General Public License or
3927 the Artistic License)