Support for -select/-as in SQLAHacks field selection
[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     my $orig = \&{"SQL::Abstract::$f"};
16     *{"SQL::Abstract::$f"} = sub {
17
18       local $Carp::CarpLevel = 1;   # even though Carp::Clan ignores this, $orig will not
19
20       if (Carp::longmess() =~ /DBIx::Class::SQLAHacks::[\w]+\(\) called/) {
21         __PACKAGE__->can($f)->(@_);
22       }
23       else {
24         $orig->(@_);
25       }
26     }
27   }
28 }
29
30 sub new {
31   my $self = shift->SUPER::new(@_);
32
33   # This prevents the caching of $dbh in S::A::L, I believe
34   # If limit_dialect is a ref (like a $dbh), go ahead and replace
35   #   it with what it resolves to:
36   $self->{limit_dialect} = $self->_find_syntax($self->{limit_dialect})
37     if ref $self->{limit_dialect};
38
39   $self;
40 }
41
42
43 # Some databases (sqlite) do not handle multiple parenthesis
44 # around in/between arguments. A tentative x IN ( ( 1, 2 ,3) )
45 # is interpreted as x IN 1 or something similar.
46 #
47 # Since we currently do not have access to the SQLA AST, resort
48 # to barbaric mutilation of any SQL supplied in literal form
49
50 sub _strip_outer_paren {
51   my ($self, $arg) = @_;
52
53   return $self->_SWITCH_refkind ($arg, {
54     ARRAYREFREF => sub {
55       $$arg->[0] = __strip_outer_paren ($$arg->[0]);
56       return $arg;
57     },
58     SCALARREF => sub {
59       return \__strip_outer_paren( $$arg );
60     },
61     FALLBACK => sub {
62       return $arg
63     },
64   });
65 }
66
67 sub __strip_outer_paren {
68   my $sql = shift;
69
70   if ($sql and not ref $sql) {
71     while ($sql =~ /^ \s* \( (.*) \) \s* $/x ) {
72       $sql = $1;
73     }
74   }
75
76   return $sql;
77 }
78
79 sub _where_field_IN {
80   my ($self, $lhs, $op, $rhs) = @_;
81   $rhs = $self->_strip_outer_paren ($rhs);
82   return $self->SUPER::_where_field_IN ($lhs, $op, $rhs);
83 }
84
85 sub _where_field_BETWEEN {
86   my ($self, $lhs, $op, $rhs) = @_;
87   $rhs = $self->_strip_outer_paren ($rhs);
88   return $self->SUPER::_where_field_BETWEEN ($lhs, $op, $rhs);
89 }
90
91 # Slow but ANSI standard Limit/Offset support. DB2 uses this
92 sub _RowNumberOver {
93   my ($self, $sql, $order, $rows, $offset ) = @_;
94
95   $offset += 1;
96   my $last = $rows + $offset - 1;
97   my ( $order_by ) = $self->_order_by( $order );
98
99   $sql = <<"SQL";
100 SELECT * FROM
101 (
102    SELECT Q1.*, ROW_NUMBER() OVER( ) AS ROW_NUM FROM (
103       $sql
104       $order_by
105    ) Q1
106 ) Q2
107 WHERE ROW_NUM BETWEEN $offset AND $last
108
109 SQL
110
111   return $sql;
112 }
113
114 # Crappy Top based Limit/Offset support. MSSQL uses this currently,
115 # but may have to switch to RowNumberOver one day
116 sub _Top {
117   my ( $self, $sql, $order, $rows, $offset ) = @_;
118
119   croak '$order supplied to SQLAHacks limit emulators must be a hash'
120     if (ref $order ne 'HASH');
121
122   $order = { %$order }; #copy
123
124   my $last = $rows + $offset;
125
126   my $req_order = $self->_order_by ($order->{order_by});
127
128   my $limit_order = $req_order ? $order->{order_by} : $order->{_virtual_order_by};
129
130   delete $order->{$_} for qw/order_by _virtual_order_by/;
131   my $grpby_having = $self->_order_by ($order);
132
133   my ( $order_by_inner, $order_by_outer ) = $self->_order_directions($limit_order);
134
135   $sql =~ s/^\s*(SELECT|select)//;
136
137   $sql = <<"SQL";
138   SELECT * FROM
139   (
140     SELECT TOP $rows * FROM
141     (
142         SELECT TOP $last $sql $grpby_having $order_by_inner
143     ) AS foo
144     $order_by_outer
145   ) AS bar
146   $req_order
147
148 SQL
149     return $sql;
150 }
151
152
153
154 # While we're at it, this should make LIMIT queries more efficient,
155 #  without digging into things too deeply
156 sub _find_syntax {
157   my ($self, $syntax) = @_;
158   return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
159 }
160
161 sub select {
162   my ($self, $table, $fields, $where, $order, @rest) = @_;
163
164   $self->{"${_}_bind"} = [] for (qw/having from order/);
165
166   if (ref $table eq 'SCALAR') {
167     $table = $$table;
168   }
169   elsif (not ref $table) {
170     $table = $self->_quote($table);
171   }
172   local $self->{rownum_hack_count} = 1
173     if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
174   @rest = (-1) unless defined $rest[0];
175   croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
176     # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
177   my ($sql, @where_bind) = $self->SUPER::select(
178     $table, $self->_recurse_fields($fields), $where, $order, @rest
179   );
180   $sql .= 
181     $self->{for} ?
182     (
183       $self->{for} eq 'update' ? ' FOR UPDATE' :
184       $self->{for} eq 'shared' ? ' FOR SHARE'  :
185       ''
186     ) :
187     ''
188   ;
189   return wantarray ? ($sql, @{$self->{from_bind}}, @where_bind, @{$self->{having_bind}}, @{$self->{order_bind}} ) : $sql;
190 }
191
192 sub insert {
193   my $self = shift;
194   my $table = shift;
195   $table = $self->_quote($table) unless ref($table);
196
197   # SQLA will emit INSERT INTO $table ( ) VALUES ( )
198   # which is sadly understood only by MySQL. Change default behavior here,
199   # until SQLA2 comes with proper dialect support
200   if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
201     return "INSERT INTO ${table} DEFAULT VALUES"
202   }
203
204   $self->SUPER::insert($table, @_);
205 }
206
207 sub update {
208   my $self = shift;
209   my $table = shift;
210   $table = $self->_quote($table) unless ref($table);
211   $self->SUPER::update($table, @_);
212 }
213
214 sub delete {
215   my $self = shift;
216   my $table = shift;
217   $table = $self->_quote($table) unless ref($table);
218   $self->SUPER::delete($table, @_);
219 }
220
221 sub _emulate_limit {
222   my $self = shift;
223   if ($_[3] == -1) {
224     return $_[1].$self->_order_by($_[2]);
225   } else {
226     return $self->SUPER::_emulate_limit(@_);
227   }
228 }
229
230 sub _recurse_fields {
231   my ($self, $fields, $params) = @_;
232   my $ref = ref $fields;
233   return $self->_quote($fields) unless $ref;
234   return $$fields if $ref eq 'SCALAR';
235
236   if ($ref eq 'ARRAY') {
237     return join(', ', map {
238       $self->_recurse_fields($_)
239         .(exists $self->{rownum_hack_count} && !($params && $params->{no_rownum_hack})
240           ? ' AS col'.$self->{rownum_hack_count}++
241           : '')
242       } @$fields);
243   }
244   elsif ($ref eq 'HASH') {
245     my %hash = %$fields;
246     my ($select, $as);
247
248     if ($hash{-select}) {
249       $select = $self->_recurse_fields (delete $hash{-select});
250       $as = $self->_quote (delete $hash{-as});
251     }
252     else {
253       my ($func, $args) = each %hash;
254       delete $hash{$func};
255
256       if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
257         croak (
258           'The select => { distinct => ... } syntax is not supported for multiple columns.'
259          .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
260          .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
261         );
262       }
263       $select = sprintf ('%s( %s )',
264         $self->_sqlcase($func),
265         $self->_recurse_fields($args)
266       );
267     }
268
269     # there should be nothing left
270     if (keys %hash) {
271       croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
272     }
273
274     $select .= " AS $as" if $as;
275     return $select;
276   }
277   # Is the second check absolutely necessary?
278   elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
279     return $self->_fold_sqlbind( $fields );
280   }
281   else {
282     croak($ref . qq{ unexpected in _recurse_fields()})
283   }
284 }
285
286 sub _order_by {
287   my ($self, $arg) = @_;
288
289   if (ref $arg eq 'HASH' and keys %$arg and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
290
291     my $ret = '';
292
293     if (my $g = $self->_recurse_fields($arg->{group_by}, { no_rownum_hack => 1 }) ) {
294       $ret = $self->_sqlcase(' group by ') . $g;
295     }
296
297     if (defined $arg->{having}) {
298       my ($frag, @bind) = $self->_recurse_where($arg->{having});
299       push(@{$self->{having_bind}}, @bind);
300       $ret .= $self->_sqlcase(' having ').$frag;
301     }
302
303     if (defined $arg->{order_by}) {
304       my ($frag, @bind) = $self->SUPER::_order_by($arg->{order_by});
305       push(@{$self->{order_bind}}, @bind);
306       $ret .= $frag;
307     }
308
309     return $ret;
310   }
311   else {
312     my ($sql, @bind) = $self->SUPER::_order_by ($arg);
313     push(@{$self->{order_bind}}, @bind);
314     return $sql;
315   }
316 }
317
318 sub _order_directions {
319   my ($self, $order) = @_;
320
321   # strip bind values - none of the current _order_directions users support them
322   return $self->SUPER::_order_directions( [ map
323     { ref $_ ? $_->[0] : $_ }
324     $self->_order_by_chunks ($order)
325   ]);
326 }
327
328 sub _table {
329   my ($self, $from) = @_;
330   if (ref $from eq 'ARRAY') {
331     return $self->_recurse_from(@$from);
332   } elsif (ref $from eq 'HASH') {
333     return $self->_make_as($from);
334   } else {
335     return $from; # would love to quote here but _table ends up getting called
336                   # twice during an ->select without a limit clause due to
337                   # the way S::A::Limit->select works. should maybe consider
338                   # bypassing this and doing S::A::select($self, ...) in
339                   # our select method above. meantime, quoting shims have
340                   # been added to select/insert/update/delete here
341   }
342 }
343
344 sub _recurse_from {
345   my ($self, $from, @join) = @_;
346   my @sqlf;
347   push(@sqlf, $self->_make_as($from));
348   foreach my $j (@join) {
349     my ($to, $on) = @$j;
350
351     # check whether a join type exists
352     my $join_clause = '';
353     my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
354     if (ref($to_jt) eq 'HASH' and exists($to_jt->{-join_type})) {
355       $join_clause = ' '.uc($to_jt->{-join_type}).' JOIN ';
356     } else {
357       $join_clause = ' JOIN ';
358     }
359     push(@sqlf, $join_clause);
360
361     if (ref $to eq 'ARRAY') {
362       push(@sqlf, '(', $self->_recurse_from(@$to), ')');
363     } else {
364       push(@sqlf, $self->_make_as($to));
365     }
366     push(@sqlf, ' ON ', $self->_join_condition($on));
367   }
368   return join('', @sqlf);
369 }
370
371 sub _fold_sqlbind {
372   my ($self, $sqlbind) = @_;
373
374   my @sqlbind = @$$sqlbind; # copy
375   my $sql = shift @sqlbind;
376   push @{$self->{from_bind}}, @sqlbind;
377
378   return $sql;
379 }
380
381 sub _make_as {
382   my ($self, $from) = @_;
383   return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
384                         : ref $_ eq 'REF'    ? $self->_fold_sqlbind($_)
385                         : $self->_quote($_))
386                        } reverse each %{$self->_skip_options($from)});
387 }
388
389 sub _skip_options {
390   my ($self, $hash) = @_;
391   my $clean_hash = {};
392   $clean_hash->{$_} = $hash->{$_}
393     for grep {!/^-/} keys %$hash;
394   return $clean_hash;
395 }
396
397 sub _join_condition {
398   my ($self, $cond) = @_;
399   if (ref $cond eq 'HASH') {
400     my %j;
401     for (keys %$cond) {
402       my $v = $cond->{$_};
403       if (ref $v) {
404         croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
405             if ref($v) ne 'SCALAR';
406         $j{$_} = $v;
407       }
408       else {
409         my $x = '= '.$self->_quote($v); $j{$_} = \$x;
410       }
411     };
412     return scalar($self->_recurse_where(\%j));
413   } elsif (ref $cond eq 'ARRAY') {
414     return join(' OR ', map { $self->_join_condition($_) } @$cond);
415   } else {
416     die "Can't handle this yet!";
417   }
418 }
419
420 sub _quote {
421   my ($self, $label) = @_;
422   return '' unless defined $label;
423   return "*" if $label eq '*';
424   return $label unless $self->{quote_char};
425   if(ref $self->{quote_char} eq "ARRAY"){
426     return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
427       if !defined $self->{name_sep};
428     my $sep = $self->{name_sep};
429     return join($self->{name_sep},
430         map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1]  }
431        split(/\Q$sep\E/,$label));
432   }
433   return $self->SUPER::_quote($label);
434 }
435
436 sub limit_dialect {
437     my $self = shift;
438     $self->{limit_dialect} = shift if @_;
439     return $self->{limit_dialect};
440 }
441
442 sub quote_char {
443     my $self = shift;
444     $self->{quote_char} = shift if @_;
445     return $self->{quote_char};
446 }
447
448 sub name_sep {
449     my $self = shift;
450     $self->{name_sep} = shift if @_;
451     return $self->{name_sep};
452 }
453
454 1;
455
456 __END__
457
458 =pod
459
460 =head1 NAME
461
462 DBIx::Class::SQLAHacks - This module is a subclass of SQL::Abstract::Limit
463 and includes a number of DBIC-specific workarounds, not yet suitable for
464 inclusion into SQLA proper.
465
466 =head1 METHODS
467
468 =head2 new
469
470 Tries to determine limit dialect.
471
472 =head2 select
473
474 Quotes table names, handles "limit" dialects (e.g. where rownum between x and
475 y), supports SELECT ... FOR UPDATE and SELECT ... FOR SHARE.
476
477 =head2 insert update delete
478
479 Just quotes table names.
480
481 =head2 limit_dialect
482
483 Specifies the dialect of used for implementing an SQL "limit" clause for
484 restricting the number of query results returned.  Valid values are: RowNum.
485
486 See L<DBIx::Class::Storage::DBI/connect_info> for details.
487
488 =head2 name_sep
489
490 Character separating quoted table names.
491
492 See L<DBIx::Class::Storage::DBI/connect_info> for details.
493
494 =head2 quote_char
495
496 Set to an array-ref to specify separate left and right quotes for table names.
497
498 See L<DBIx::Class::Storage::DBI/connect_info> for details.
499
500 =cut
501