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