>table(\"foo") now works
[dbsrgits/DBIx-Class-Historic.git] / lib / DBIx / Class / SQLAHacks.pm
CommitLineData
6f4ddea1 1package # Hide from PAUSE
855c6fd0 2 DBIx::Class::SQLAHacks;
6f4ddea1 3
4use base qw/SQL::Abstract::Limit/;
e3764383 5use strict;
6use warnings;
b2b22cd6 7use Carp::Clan qw/^DBIx::Class|^SQL::Abstract/;
8
9BEGIN {
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}
6f4ddea1 29
30sub 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
6f4ddea1 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
50sub _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
67sub __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
79sub _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
85sub _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
15827712 91# Slow but ANSI standard Limit/Offset support. DB2 uses this
6f4ddea1 92sub _RowNumberOver {
93 my ($self, $sql, $order, $rows, $offset ) = @_;
94
95 $offset += 1;
03e1d9af 96 my $last = $rows + $offset - 1;
6f4ddea1 97 my ( $order_by ) = $self->_order_by( $order );
98
99 $sql = <<"SQL";
100SELECT * FROM
101(
102 SELECT Q1.*, ROW_NUMBER() OVER( ) AS ROW_NUM FROM (
103 $sql
104 $order_by
105 ) Q1
106) Q2
107WHERE ROW_NUM BETWEEN $offset AND $last
108
109SQL
110
111 return $sql;
112}
113
15827712 114# Crappy Top based Limit/Offset support. MSSQL uses this currently,
115# but may have to switch to RowNumberOver one day
116sub _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
8f6dbee9 122 $order = { %$order }; #copy
123
15827712 124 my $last = $rows + $offset;
125
126 my $req_order = $self->_order_by ($order->{order_by});
1cbd3034 127
15827712 128 my $limit_order = $req_order ? $order->{order_by} : $order->{_virtual_order_by};
129
8f6dbee9 130 delete $order->{$_} for qw/order_by _virtual_order_by/;
131 my $grpby_having = $self->_order_by ($order);
132
15827712 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 (
8f6dbee9 142 SELECT TOP $last $sql $grpby_having $order_by_inner
15827712 143 ) AS foo
144 $order_by_outer
145 ) AS bar
146 $req_order
147
148SQL
149 return $sql;
150}
151
152
6f4ddea1 153
154# While we're at it, this should make LIMIT queries more efficient,
155# without digging into things too deeply
6f4ddea1 156sub _find_syntax {
157 my ($self, $syntax) = @_;
ac788c46 158 return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
6f4ddea1 159}
160
161sub select {
162 my ($self, $table, $fields, $where, $order, @rest) = @_;
1cbd3034 163
164 $self->{"${_}_bind"} = [] for (qw/having from order/);
db56cf3d 165
c2b7c5dc 166 if (not ref($table) or ref($table) eq 'SCALAR') {
6f4ddea1 167 $table = $self->_quote($table);
168 }
c2b7c5dc 169
6f4ddea1 170 local $self->{rownum_hack_count} = 1
171 if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
172 @rest = (-1) unless defined $rest[0];
e8fcf76f 173 croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
6f4ddea1 174 # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
db56cf3d 175 my ($sql, @where_bind) = $self->SUPER::select(
6f4ddea1 176 $table, $self->_recurse_fields($fields), $where, $order, @rest
177 );
178 $sql .=
179 $self->{for} ?
180 (
181 $self->{for} eq 'update' ? ' FOR UPDATE' :
182 $self->{for} eq 'shared' ? ' FOR SHARE' :
183 ''
184 ) :
185 ''
186 ;
1cbd3034 187 return wantarray ? ($sql, @{$self->{from_bind}}, @where_bind, @{$self->{having_bind}}, @{$self->{order_bind}} ) : $sql;
6f4ddea1 188}
189
190sub insert {
191 my $self = shift;
192 my $table = shift;
c2b7c5dc 193 $table = $self->_quote($table);
7a72e5a5 194
195 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
196 # which is sadly understood only by MySQL. Change default behavior here,
197 # until SQLA2 comes with proper dialect support
198 if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
199 return "INSERT INTO ${table} DEFAULT VALUES"
200 }
201
6f4ddea1 202 $self->SUPER::insert($table, @_);
203}
204
205sub update {
206 my $self = shift;
207 my $table = shift;
c2b7c5dc 208 $table = $self->_quote($table);
6f4ddea1 209 $self->SUPER::update($table, @_);
210}
211
212sub delete {
213 my $self = shift;
214 my $table = shift;
c2b7c5dc 215 $table = $self->_quote($table);
6f4ddea1 216 $self->SUPER::delete($table, @_);
217}
218
219sub _emulate_limit {
220 my $self = shift;
221 if ($_[3] == -1) {
222 return $_[1].$self->_order_by($_[2]);
223 } else {
224 return $self->SUPER::_emulate_limit(@_);
225 }
226}
227
228sub _recurse_fields {
229 my ($self, $fields, $params) = @_;
230 my $ref = ref $fields;
231 return $self->_quote($fields) unless $ref;
232 return $$fields if $ref eq 'SCALAR';
233
234 if ($ref eq 'ARRAY') {
235 return join(', ', map {
236 $self->_recurse_fields($_)
237 .(exists $self->{rownum_hack_count} && !($params && $params->{no_rownum_hack})
238 ? ' AS col'.$self->{rownum_hack_count}++
239 : '')
240 } @$fields);
241 } elsif ($ref eq 'HASH') {
242 foreach my $func (keys %$fields) {
db56cf3d 243 if ($func eq 'distinct') {
244 my $_fields = $fields->{$func};
245 if (ref $_fields eq 'ARRAY' && @{$_fields} > 1) {
04ebc6f4 246 croak (
247 'The select => { distinct => ... } syntax is not supported for multiple columns.'
248 .' Instead please use { group_by => [ qw/' . (join ' ', @$_fields) . '/ ] }'
249 .' or { select => [ qw/' . (join ' ', @$_fields) . '/ ], distinct => 1 }'
250 );
db56cf3d 251 }
252 else {
253 $_fields = @{$_fields}[0] if ref $_fields eq 'ARRAY';
04ebc6f4 254 carp (
255 'The select => { distinct => ... } syntax will be deprecated in DBIC version 0.09,'
256 ." please use { group_by => '${_fields}' } or { select => '${_fields}', distinct => 1 }"
257 );
db56cf3d 258 }
259 }
6f4ddea1 260 return $self->_sqlcase($func)
261 .'( '.$self->_recurse_fields($fields->{$func}).' )';
262 }
263 }
264 # Is the second check absolutely necessary?
265 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
db56cf3d 266 return $self->_fold_sqlbind( $fields );
6f4ddea1 267 }
268 else {
e8fcf76f 269 croak($ref . qq{ unexpected in _recurse_fields()})
6f4ddea1 270 }
271}
272
273sub _order_by {
1cbd3034 274 my ($self, $arg) = @_;
15827712 275
1cbd3034 276 if (ref $arg eq 'HASH' and keys %$arg and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
277
278 my $ret = '';
279
280 if (defined $arg->{group_by}) {
6f4ddea1 281 $ret = $self->_sqlcase(' group by ')
1cbd3034 282 .$self->_recurse_fields($arg->{group_by}, { no_rownum_hack => 1 });
6f4ddea1 283 }
15827712 284
1cbd3034 285 if (defined $arg->{having}) {
286 my ($frag, @bind) = $self->_recurse_where($arg->{having});
287 push(@{$self->{having_bind}}, @bind);
6f4ddea1 288 $ret .= $self->_sqlcase(' having ').$frag;
289 }
15827712 290
1cbd3034 291 if (defined $arg->{order_by}) {
292 my ($frag, @bind) = $self->SUPER::_order_by($arg->{order_by});
293 push(@{$self->{order_bind}}, @bind);
294 $ret .= $frag;
6f4ddea1 295 }
15827712 296
1cbd3034 297 return $ret;
fde3719a 298 }
1cbd3034 299 else {
300 my ($sql, @bind) = $self->SUPER::_order_by ($arg);
301 push(@{$self->{order_bind}}, @bind);
302 return $sql;
fd4cb60a 303 }
6f4ddea1 304}
305
1cbd3034 306sub _order_directions {
fd4cb60a 307 my ($self, $order) = @_;
15827712 308
1cbd3034 309 # strip bind values - none of the current _order_directions users support them
310 return $self->SUPER::_order_directions( [ map
311 { ref $_ ? $_->[0] : $_ }
312 $self->_order_by_chunks ($order)
313 ]);
fd4cb60a 314}
315
6f4ddea1 316sub _table {
317 my ($self, $from) = @_;
318 if (ref $from eq 'ARRAY') {
319 return $self->_recurse_from(@$from);
320 } elsif (ref $from eq 'HASH') {
321 return $self->_make_as($from);
322 } else {
323 return $from; # would love to quote here but _table ends up getting called
324 # twice during an ->select without a limit clause due to
325 # the way S::A::Limit->select works. should maybe consider
326 # bypassing this and doing S::A::select($self, ...) in
327 # our select method above. meantime, quoting shims have
328 # been added to select/insert/update/delete here
329 }
330}
331
332sub _recurse_from {
333 my ($self, $from, @join) = @_;
334 my @sqlf;
335 push(@sqlf, $self->_make_as($from));
336 foreach my $j (@join) {
337 my ($to, $on) = @$j;
338
339 # check whether a join type exists
340 my $join_clause = '';
341 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
342 if (ref($to_jt) eq 'HASH' and exists($to_jt->{-join_type})) {
343 $join_clause = ' '.uc($to_jt->{-join_type}).' JOIN ';
344 } else {
345 $join_clause = ' JOIN ';
346 }
347 push(@sqlf, $join_clause);
348
349 if (ref $to eq 'ARRAY') {
350 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
351 } else {
352 push(@sqlf, $self->_make_as($to));
353 }
354 push(@sqlf, ' ON ', $self->_join_condition($on));
355 }
356 return join('', @sqlf);
357}
358
db56cf3d 359sub _fold_sqlbind {
360 my ($self, $sqlbind) = @_;
69989ea9 361
362 my @sqlbind = @$$sqlbind; # copy
363 my $sql = shift @sqlbind;
364 push @{$self->{from_bind}}, @sqlbind;
365
db56cf3d 366 return $sql;
6f4ddea1 367}
368
369sub _make_as {
370 my ($self, $from) = @_;
db56cf3d 371 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
372 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
373 : $self->_quote($_))
6f4ddea1 374 } reverse each %{$self->_skip_options($from)});
375}
376
377sub _skip_options {
378 my ($self, $hash) = @_;
379 my $clean_hash = {};
380 $clean_hash->{$_} = $hash->{$_}
381 for grep {!/^-/} keys %$hash;
382 return $clean_hash;
383}
384
385sub _join_condition {
386 my ($self, $cond) = @_;
387 if (ref $cond eq 'HASH') {
388 my %j;
389 for (keys %$cond) {
390 my $v = $cond->{$_};
391 if (ref $v) {
e8fcf76f 392 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
6f4ddea1 393 if ref($v) ne 'SCALAR';
394 $j{$_} = $v;
395 }
396 else {
397 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
398 }
399 };
400 return scalar($self->_recurse_where(\%j));
401 } elsif (ref $cond eq 'ARRAY') {
402 return join(' OR ', map { $self->_join_condition($_) } @$cond);
403 } else {
404 die "Can't handle this yet!";
405 }
406}
407
408sub _quote {
409 my ($self, $label) = @_;
410 return '' unless defined $label;
c2b7c5dc 411 return $$label if ref($label) eq 'SCALAR';
6f4ddea1 412 return "*" if $label eq '*';
413 return $label unless $self->{quote_char};
414 if(ref $self->{quote_char} eq "ARRAY"){
415 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
416 if !defined $self->{name_sep};
417 my $sep = $self->{name_sep};
418 return join($self->{name_sep},
419 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
420 split(/\Q$sep\E/,$label));
421 }
422 return $self->SUPER::_quote($label);
423}
424
425sub limit_dialect {
426 my $self = shift;
427 $self->{limit_dialect} = shift if @_;
428 return $self->{limit_dialect};
429}
430
431sub quote_char {
432 my $self = shift;
433 $self->{quote_char} = shift if @_;
434 return $self->{quote_char};
435}
436
437sub name_sep {
438 my $self = shift;
439 $self->{name_sep} = shift if @_;
440 return $self->{name_sep};
441}
442
4431;
444
445__END__
446
447=pod
448
449=head1 NAME
450
855c6fd0 451DBIx::Class::SQLAHacks - This module is a subclass of SQL::Abstract::Limit
452and includes a number of DBIC-specific workarounds, not yet suitable for
453inclusion into SQLA proper.
6f4ddea1 454
455=head1 METHODS
456
457=head2 new
458
459Tries to determine limit dialect.
460
461=head2 select
462
463Quotes table names, handles "limit" dialects (e.g. where rownum between x and
464y), supports SELECT ... FOR UPDATE and SELECT ... FOR SHARE.
465
466=head2 insert update delete
467
468Just quotes table names.
469
470=head2 limit_dialect
471
472Specifies the dialect of used for implementing an SQL "limit" clause for
473restricting the number of query results returned. Valid values are: RowNum.
474
475See L<DBIx::Class::Storage::DBI/connect_info> for details.
476
477=head2 name_sep
478
479Character separating quoted table names.
480
481See L<DBIx::Class::Storage::DBI/connect_info> for details.
482
483=head2 quote_char
484
485Set to an array-ref to specify separate left and right quotes for table names.
486
487See L<DBIx::Class::Storage::DBI/connect_info> for details.
488
489=cut
490