Some hack consolidation
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLAHacks.pm
1 package # Hide from PAUSE
2   DBIx::Class::SQLAHacks;
3
4 use base qw/SQL::Abstract::Limit/;
5 use strict;
6 use warnings;
7 use Carp::Clan qw/^DBIx::Class|^SQL::Abstract/;
8
9 BEGIN {
10   # reinstall the carp()/croak() functions imported into SQL::Abstract
11   # as Carp and Carp::Clan do not like each other much
12   no warnings qw/redefine/;
13   no strict qw/refs/;
14   for my $f (qw/carp croak/) {
15
16     my $orig = \&{"SQL::Abstract::$f"};
17     *{"SQL::Abstract::$f"} = sub {
18
19       local $Carp::CarpLevel = 1;   # even though Carp::Clan ignores this, $orig will not
20
21       if (Carp::longmess() =~ /DBIx::Class::SQLAHacks::[\w]+ .+? called \s at/x) {
22         __PACKAGE__->can($f)->(@_);
23       }
24       else {
25         $orig->(@_);
26       }
27     }
28   }
29 }
30
31 sub new {
32   my $self = shift->SUPER::new(@_);
33
34   # This prevents the caching of $dbh in S::A::L, I believe
35   # If limit_dialect is a ref (like a $dbh), go ahead and replace
36   #   it with what it resolves to:
37   $self->{limit_dialect} = $self->_find_syntax($self->{limit_dialect})
38     if ref $self->{limit_dialect};
39
40   $self;
41 }
42
43
44 # Some databases (sqlite) do not handle multiple parenthesis
45 # around in/between arguments. A tentative x IN ( ( 1, 2 ,3) )
46 # is interpreted as x IN 1 or something similar.
47 #
48 # Since we currently do not have access to the SQLA AST, resort
49 # to barbaric mutilation of any SQL supplied in literal form
50
51 sub _strip_outer_paren {
52   my ($self, $arg) = @_;
53
54   return $self->_SWITCH_refkind ($arg, {
55     ARRAYREFREF => sub {
56       $$arg->[0] = __strip_outer_paren ($$arg->[0]);
57       return $arg;
58     },
59     SCALARREF => sub {
60       return \__strip_outer_paren( $$arg );
61     },
62     FALLBACK => sub {
63       return $arg
64     },
65   });
66 }
67
68 sub __strip_outer_paren {
69   my $sql = shift;
70
71   if ($sql and not ref $sql) {
72     while ($sql =~ /^ \s* \( (.*) \) \s* $/x ) {
73       $sql = $1;
74     }
75   }
76
77   return $sql;
78 }
79
80 sub _where_field_IN {
81   my ($self, $lhs, $op, $rhs) = @_;
82   $rhs = $self->_strip_outer_paren ($rhs);
83   return $self->SUPER::_where_field_IN ($lhs, $op, $rhs);
84 }
85
86 sub _where_field_BETWEEN {
87   my ($self, $lhs, $op, $rhs) = @_;
88   $rhs = $self->_strip_outer_paren ($rhs);
89   return $self->SUPER::_where_field_BETWEEN ($lhs, $op, $rhs);
90 }
91
92 # Slow but ANSI standard Limit/Offset support. DB2 uses this
93 sub _RowNumberOver {
94   my ($self, $sql, $order, $rows, $offset ) = @_;
95
96   $offset += 1;
97   my $last = $rows + $offset - 1;
98   my ( $order_by ) = $self->_order_by( $order );
99
100   $sql = <<"SQL";
101 SELECT * FROM
102 (
103    SELECT Q1.*, ROW_NUMBER() OVER( ) AS ROW_NUM FROM (
104       $sql
105       $order_by
106    ) Q1
107 ) Q2
108 WHERE ROW_NUM BETWEEN $offset AND $last
109
110 SQL
111
112   return $sql;
113 }
114
115 # Crappy Top based Limit/Offset support. MSSQL uses this currently,
116 # but may have to switch to RowNumberOver one day
117 sub _Top {
118   my ( $self, $sql, $order, $rows, $offset ) = @_;
119
120   # mangle the input sql so it can be properly aliased in the outer queries
121   $sql =~ s/^ \s* SELECT \s+ (.+?) \s+ (?=FROM)//ix
122     or croak "Unrecognizable SELECT: $sql";
123   my $sql_select = $1;
124   my @sql_select = split (/\s*,\s*/, $sql_select);
125
126   # we can't support subqueries (in fact MSSQL can't) - croak
127   if (@sql_select != @{$self->{_dbic_rs_attrs}{select}}) {
128     croak (sprintf (
129       'SQL SELECT did not parse cleanly - retrieved %d comma separated elements, while '
130     . 'the resultset select attribure contains %d elements: %s',
131       scalar @sql_select,
132       scalar @{$self->{_dbic_rs_attrs}{select}},
133       $sql_select,
134     ));
135   }
136
137   my $name_sep = $self->name_sep || '.';
138   $name_sep = "\Q$name_sep\E";
139   my $col_re = qr/ ^ (?: (.+) $name_sep )? ([^$name_sep]+) $ /x;
140
141   # construct the new select lists, rename(alias) some columns if necessary
142   my (@outer_select, @inner_select, %seen_names, %col_aliases, %outer_col_aliases);
143
144   for (@{$self->{_dbic_rs_attrs}{select}}) {
145     next if ref $_;
146     my ($table, $orig_colname) = ( $_ =~ $col_re );
147     next unless $table;
148     $seen_names{$orig_colname}++;
149   }
150
151   for my $i (0 .. $#sql_select) {
152
153     my $colsel_arg = $self->{_dbic_rs_attrs}{select}[$i];
154     my $colsel_sql = $sql_select[$i];
155
156     # this may or may not work (in case of a scalarref or something)
157     my ($table, $orig_colname) = ( $colsel_arg =~ $col_re );
158
159     my $quoted_alias;
160     # do not attempt to understand non-scalar selects - alias numerically
161     if (ref $colsel_arg) {
162       $quoted_alias = $self->_quote ('column_' . (@inner_select + 1) );
163     }
164     # column name seen more than once - alias it
165     elsif ($orig_colname && ($seen_names{$orig_colname} > 1) ) {
166       $quoted_alias = $self->_quote ("${table}__${orig_colname}");
167     }
168
169     # we did rename - make a record and adjust
170     if ($quoted_alias) {
171       # alias inner
172       push @inner_select, "$colsel_sql AS $quoted_alias";
173
174       # push alias to outer
175       push @outer_select, $quoted_alias;
176
177       # Any aliasing accumulated here will be considered
178       # both for inner and outer adjustments of ORDER BY
179       $self->__record_alias (
180         \%col_aliases,
181         $quoted_alias,
182         $colsel_arg,
183         $table ? $orig_colname : undef,
184       );
185     }
186
187     # otherwise just leave things intact inside, and use the abbreviated one outside
188     # (as we do not have table names anymore)
189     else {
190       push @inner_select, $colsel_sql;
191
192       my $outer_quoted = $self->_quote ($orig_colname);  # it was not a duplicate so should just work
193       push @outer_select, $outer_quoted;
194       $self->__record_alias (
195         \%outer_col_aliases,
196         $outer_quoted,
197         $colsel_arg,
198         $table ? $orig_colname : undef,
199       );
200     }
201   }
202
203   my $outer_select = join (', ', @outer_select );
204   my $inner_select = join (', ', @inner_select );
205
206   %outer_col_aliases = (%outer_col_aliases, %col_aliases);
207
208   # deal with order
209   croak '$order supplied to SQLAHacks limit emulators must be a hash'
210     if (ref $order ne 'HASH');
211
212   $order = { %$order }; #copy
213
214   my $req_order = $order->{order_by};
215
216   # examine normalized version, collapses nesting
217   my $limit_order;
218   if (scalar $self->_order_by_chunks ($req_order)) {
219     $limit_order = $req_order;
220   }
221   else {
222     my $rs_alias = $self->{_dbic_rs_attrs}{alias};
223     $limit_order = [ map
224       { join ('', $rs_alias, $name_sep, $_ ) }
225       ( $self->{_dbic_rs_attrs}{_source_handle}->resolve->primary_columns )
226     ];
227   }
228
229   my ( $order_by_inner, $order_by_outer ) = $self->_order_directions($limit_order);
230   my $order_by_requested = $self->_order_by ($req_order);
231
232   # generate the rest
233   delete $order->{order_by};
234   my $grpby_having = $self->_order_by ($order);
235
236   # short circuit for counts - the ordering complexity is needless
237   if ($self->{_dbic_rs_attrs}{-for_count_only}) {
238     return "SELECT TOP $rows $inner_select $sql $grpby_having $order_by_outer";
239   }
240
241   # we can't really adjust the order_by columns, as introspection is lacking
242   # resort to simple substitution
243   for my $col (keys %outer_col_aliases) {
244     for ($order_by_requested, $order_by_outer) {
245       $_ =~ s/\s+$col\s+/ $outer_col_aliases{$col} /g;
246     }
247   }
248   for my $col (keys %col_aliases) {
249     $order_by_inner =~ s/\s+$col\s+/$col_aliases{$col}/g;
250   }
251
252
253   my $inner_lim = $rows + $offset;
254
255   $sql = "SELECT TOP $inner_lim $inner_select $sql $grpby_having $order_by_inner";
256
257   if ($offset) {
258     $sql = <<"SQL";
259
260     SELECT TOP $rows $outer_select FROM
261     (
262       $sql
263     ) AS me
264     $order_by_outer
265 SQL
266
267   }
268
269   if ($order_by_requested) {
270     $sql = <<"SQL";
271
272     SELECT $outer_select FROM
273       ( $sql ) AS me
274     $order_by_requested;
275 SQL
276
277   }
278
279   return $sql;
280 }
281
282 # action at a distance to shorten Top code above
283 sub __record_alias {
284   my ($self, $register, $alias, $fqcol, $col) = @_;
285
286   # record qualified name
287   $register->{$fqcol} = $alias;
288   $register->{$self->_quote($fqcol)} = $alias;
289
290   return unless $col;
291
292   # record unqualified name, undef (no adjustment) if a duplicate is found
293   if (exists $register->{$col}) {
294     $register->{$col} = undef;
295   }
296   else {
297     $register->{$col} = $alias;
298   }
299
300   $register->{$self->_quote($col)} = $register->{$col};
301 }
302
303
304
305 # While we're at it, this should make LIMIT queries more efficient,
306 #  without digging into things too deeply
307 sub _find_syntax {
308   my ($self, $syntax) = @_;
309   return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
310 }
311
312 my $for_syntax = {
313   update => 'FOR UPDATE',
314   shared => 'FOR SHARE',
315 };
316 sub select {
317   my ($self, $table, $fields, $where, $order, @rest) = @_;
318
319   $self->{"${_}_bind"} = [] for (qw/having from order/);
320
321   if (ref $table eq 'SCALAR') {
322     $table = $$table;
323   }
324   elsif (not ref $table) {
325     $table = $self->_quote($table);
326   }
327   local $self->{rownum_hack_count} = 1
328     if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
329   @rest = (-1) unless defined $rest[0];
330   croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
331     # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
332   my ($sql, @where_bind) = $self->SUPER::select(
333     $table, $self->_recurse_fields($fields), $where, $order, @rest
334   );
335   if (my $for = delete $self->{_dbic_rs_attrs}{for}) {
336     $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
337   }
338
339   return wantarray ? ($sql, @{$self->{from_bind}}, @where_bind, @{$self->{having_bind}}, @{$self->{order_bind}} ) : $sql;
340 }
341
342 sub insert {
343   my $self = shift;
344   my $table = shift;
345   $table = $self->_quote($table) unless ref($table);
346
347   # SQLA will emit INSERT INTO $table ( ) VALUES ( )
348   # which is sadly understood only by MySQL. Change default behavior here,
349   # until SQLA2 comes with proper dialect support
350   if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
351     return "INSERT INTO ${table} DEFAULT VALUES"
352   }
353
354   $self->SUPER::insert($table, @_);
355 }
356
357 sub update {
358   my $self = shift;
359   my $table = shift;
360   $table = $self->_quote($table) unless ref($table);
361   $self->SUPER::update($table, @_);
362 }
363
364 sub delete {
365   my $self = shift;
366   my $table = shift;
367   $table = $self->_quote($table) unless ref($table);
368   $self->SUPER::delete($table, @_);
369 }
370
371 sub _emulate_limit {
372   my $self = shift;
373   if ($_[3] == -1) {
374     return $_[1].$self->_order_by($_[2]);
375   } else {
376     return $self->SUPER::_emulate_limit(@_);
377   }
378 }
379
380 sub _recurse_fields {
381   my ($self, $fields, $params) = @_;
382   my $ref = ref $fields;
383   return $self->_quote($fields) unless $ref;
384   return $$fields if $ref eq 'SCALAR';
385
386   if ($ref eq 'ARRAY') {
387     return join(', ', map {
388       $self->_recurse_fields($_)
389         .(exists $self->{rownum_hack_count} && !($params && $params->{no_rownum_hack})
390           ? ' AS col'.$self->{rownum_hack_count}++
391           : '')
392       } @$fields);
393   }
394   elsif ($ref eq 'HASH') {
395     my %hash = %$fields;
396     my ($select, $as);
397
398     if ($hash{-select}) {
399       $select = $self->_recurse_fields (delete $hash{-select});
400       $as = $self->_quote (delete $hash{-as});
401     }
402     else {
403       my ($func, $args) = each %hash;
404       delete $hash{$func};
405
406       if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
407         croak (
408           'The select => { distinct => ... } syntax is not supported for multiple columns.'
409          .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
410          .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
411         );
412       }
413       $select = sprintf ('%s( %s )',
414         $self->_sqlcase($func),
415         $self->_recurse_fields($args)
416       );
417     }
418
419     # there should be nothing left
420     if (keys %hash) {
421       croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
422     }
423
424     $select .= " AS $as" if $as;
425     return $select;
426   }
427   # Is the second check absolutely necessary?
428   elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
429     return $self->_fold_sqlbind( $fields );
430   }
431   else {
432     croak($ref . qq{ unexpected in _recurse_fields()})
433   }
434 }
435
436 sub _order_by {
437   my ($self, $arg) = @_;
438
439   if (ref $arg eq 'HASH' and keys %$arg and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
440
441     my $ret = '';
442
443     if (my $g = $self->_recurse_fields($arg->{group_by}, { no_rownum_hack => 1 }) ) {
444       $ret = $self->_sqlcase(' group by ') . $g;
445     }
446
447     if (defined $arg->{having}) {
448       my ($frag, @bind) = $self->_recurse_where($arg->{having});
449       push(@{$self->{having_bind}}, @bind);
450       $ret .= $self->_sqlcase(' having ').$frag;
451     }
452
453     if (defined $arg->{order_by}) {
454       my ($frag, @bind) = $self->SUPER::_order_by($arg->{order_by});
455       push(@{$self->{order_bind}}, @bind);
456       $ret .= $frag;
457     }
458
459     return $ret;
460   }
461   else {
462     my ($sql, @bind) = $self->SUPER::_order_by ($arg);
463     push(@{$self->{order_bind}}, @bind);
464     return $sql;
465   }
466 }
467
468 sub _order_directions {
469   my ($self, $order) = @_;
470
471   # strip bind values - none of the current _order_directions users support them
472   return $self->SUPER::_order_directions( [ map
473     { ref $_ ? $_->[0] : $_ }
474     $self->_order_by_chunks ($order)
475   ]);
476 }
477
478 sub _table {
479   my ($self, $from) = @_;
480   if (ref $from eq 'ARRAY') {
481     return $self->_recurse_from(@$from);
482   } elsif (ref $from eq 'HASH') {
483     return $self->_make_as($from);
484   } else {
485     return $from; # would love to quote here but _table ends up getting called
486                   # twice during an ->select without a limit clause due to
487                   # the way S::A::Limit->select works. should maybe consider
488                   # bypassing this and doing S::A::select($self, ...) in
489                   # our select method above. meantime, quoting shims have
490                   # been added to select/insert/update/delete here
491   }
492 }
493
494 sub _recurse_from {
495   my ($self, $from, @join) = @_;
496   my @sqlf;
497   push(@sqlf, $self->_make_as($from));
498   foreach my $j (@join) {
499     my ($to, $on) = @$j;
500
501     # check whether a join type exists
502     my $join_clause = '';
503     my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
504     if (ref($to_jt) eq 'HASH' and exists($to_jt->{-join_type})) {
505       $join_clause = ' '.uc($to_jt->{-join_type}).' JOIN ';
506     } else {
507       $join_clause = ' JOIN ';
508     }
509     push(@sqlf, $join_clause);
510
511     if (ref $to eq 'ARRAY') {
512       push(@sqlf, '(', $self->_recurse_from(@$to), ')');
513     } else {
514       push(@sqlf, $self->_make_as($to));
515     }
516     push(@sqlf, ' ON ', $self->_join_condition($on));
517   }
518   return join('', @sqlf);
519 }
520
521 sub _fold_sqlbind {
522   my ($self, $sqlbind) = @_;
523
524   my @sqlbind = @$$sqlbind; # copy
525   my $sql = shift @sqlbind;
526   push @{$self->{from_bind}}, @sqlbind;
527
528   return $sql;
529 }
530
531 sub _make_as {
532   my ($self, $from) = @_;
533   return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
534                         : ref $_ eq 'REF'    ? $self->_fold_sqlbind($_)
535                         : $self->_quote($_))
536                        } reverse each %{$self->_skip_options($from)});
537 }
538
539 sub _skip_options {
540   my ($self, $hash) = @_;
541   my $clean_hash = {};
542   $clean_hash->{$_} = $hash->{$_}
543     for grep {!/^-/} keys %$hash;
544   return $clean_hash;
545 }
546
547 sub _join_condition {
548   my ($self, $cond) = @_;
549   if (ref $cond eq 'HASH') {
550     my %j;
551     for (keys %$cond) {
552       my $v = $cond->{$_};
553       if (ref $v) {
554         croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
555             if ref($v) ne 'SCALAR';
556         $j{$_} = $v;
557       }
558       else {
559         my $x = '= '.$self->_quote($v); $j{$_} = \$x;
560       }
561     };
562     return scalar($self->_recurse_where(\%j));
563   } elsif (ref $cond eq 'ARRAY') {
564     return join(' OR ', map { $self->_join_condition($_) } @$cond);
565   } else {
566     die "Can't handle this yet!";
567   }
568 }
569
570 sub _quote {
571   my ($self, $label) = @_;
572   return '' unless defined $label;
573   return "*" if $label eq '*';
574   return $label unless $self->{quote_char};
575   if(ref $self->{quote_char} eq "ARRAY"){
576     return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
577       if !defined $self->{name_sep};
578     my $sep = $self->{name_sep};
579     return join($self->{name_sep},
580         map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1]  }
581        split(/\Q$sep\E/,$label));
582   }
583   return $self->SUPER::_quote($label);
584 }
585
586 sub limit_dialect {
587     my $self = shift;
588     $self->{limit_dialect} = shift if @_;
589     return $self->{limit_dialect};
590 }
591
592 sub quote_char {
593     my $self = shift;
594     $self->{quote_char} = shift if @_;
595     return $self->{quote_char};
596 }
597
598 sub name_sep {
599     my $self = shift;
600     $self->{name_sep} = shift if @_;
601     return $self->{name_sep};
602 }
603
604 1;
605
606 __END__
607
608 =pod
609
610 =head1 NAME
611
612 DBIx::Class::SQLAHacks - This module is a subclass of SQL::Abstract::Limit
613 and includes a number of DBIC-specific workarounds, not yet suitable for
614 inclusion into SQLA proper.
615
616 =head1 METHODS
617
618 =head2 new
619
620 Tries to determine limit dialect.
621
622 =head2 select
623
624 Quotes table names, handles "limit" dialects (e.g. where rownum between x and
625 y), supports SELECT ... FOR UPDATE and SELECT ... FOR SHARE.
626
627 =head2 insert update delete
628
629 Just quotes table names.
630
631 =head2 limit_dialect
632
633 Specifies the dialect of used for implementing an SQL "limit" clause for
634 restricting the number of query results returned.  Valid values are: RowNum.
635
636 See L<DBIx::Class::Storage::DBI/connect_info> for details.
637
638 =head2 name_sep
639
640 Character separating quoted table names.
641
642 See L<DBIx::Class::Storage::DBI/connect_info> for details.
643
644 =head2 quote_char
645
646 Set to an array-ref to specify separate left and right quotes for table names.
647
648 See L<DBIx::Class::Storage::DBI/connect_info> for details.
649
650 =cut
651