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