DBIx/Class/SQLMaker/LimitDialects.pm

filter: Statementstmt 99.6% 253 / 254 Branchbran 84.7% 78 / 92 Conditioncond 67.4% 29 / 43 MC/DCmcdc 37.5% 9 / 24 Subroutinesub 100% 20 / 20 Podpod n/a totaltotal 89.8% 389 / 433 CC 77 SCAR 25.2
CC
77
Cov
93%
_subqueried_limit_attrs
24.8
_GenericSubQ
16.0
_prep_for_skimming_limit
14.0
CRAP 12.5
« DBIx/Class/Storage/BlockRunner.pm ↑ Summary DBIx/Class/Storage/DBI/Sybase.pm »
1 package DBIx::Class::SQLMaker::LimitDialects;
2  
3 201 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 201 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 201 ▶use List::Util 'first';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 201 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # constants are used not only here, but also in comparison tests
10 sub __rows_bindtype () {
11 1520 ▶ +{ sqlt_datatype => 'integer' }
Subroutine __rows_bindtype: called CC=1 SCAR=0.0
12 }
13 sub __offset_bindtype () {
14 105 ▶ +{ sqlt_datatype => 'integer' }
Subroutine __offset_bindtype: called CC=1 SCAR=0.0
15 }
16 sub __total_bindtype () {
17 42 ▶ +{ sqlt_datatype => 'integer' }
Subroutine __total_bindtype: called CC=1 SCAR=0.0
18 }
19  
20 =head1 NAME
21  
22 DBIx::Class::SQLMaker::LimitDialects - SQL::Abstract::Limit-like functionality for DBIx::Class::SQLMaker
23  
24 =head1 DESCRIPTION
25  
26 This module replicates a lot of the functionality originally found in
27 L<SQL::Abstract::Limit>. While simple limits would work as-is, the more
28 complex dialects that require e.g. subqueries could not be reliably
29 implemented without taking full advantage of the metadata locked within
30 L<DBIx::Class::ResultSource> classes. After reimplementation of close to
31 80% of the L<SQL::Abstract::Limit> functionality it was deemed more
32 practical to simply make an independent DBIx::Class-specific limit-dialect
33 provider.
34  
35 =head1 SQL LIMIT DIALECTS
36  
37 Note that the actual implementations listed below never use C<*> literally.
38 Instead proper re-aliasing of selectors and order criteria is done, so that
39 the limit dialect are safe to use on joined resultsets with clashing column
40 names.
41  
42 Currently the provided dialects are:
43  
44 =head2 LimitOffset
45  
46 SELECT ... LIMIT $limit OFFSET $offset
47  
48 Supported by B<PostgreSQL> and B<SQLite>
49  
50 =cut
51 sub _LimitOffset {
52 1478 ▶ my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
Subroutine _LimitOffset: called CC=2 SCAR=6.9
53 1478 $sql .= $self->_parse_rs_attrs( $rs_attrs ) . " LIMIT ?";
54 1478 push @{$self->{limit_bind}}, [ $self->__rows_bindtype => $rows ];
55 1478 ▶ if ($offset) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset) 39 1439 1478
56 39 $sql .= " OFFSET ?";
57 39 push @{$self->{limit_bind}}, [ $self->__offset_bindtype => $offset ];
58 }
59 1478 return $sql;
60 }
61  
62 =head2 LimitXY
63  
64 SELECT ... LIMIT $offset $limit
65  
66 Supported by B<MySQL> and any L<SQL::Statement> based DBD
67  
68 =cut
69 sub _LimitXY {
70 2 ▶ my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
Subroutine _LimitXY: called CC=2 SCAR=6.9
71 2 $sql .= $self->_parse_rs_attrs( $rs_attrs ) . " LIMIT ";
72 2 ▶ if ($offset) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset) 2 0 2
73 2 $sql .= '?, ';
74 2 push @{$self->{limit_bind}}, [ $self->__offset_bindtype => $offset ];
75 }
76 2 $sql .= '?';
77 2 push @{$self->{limit_bind}}, [ $self->__rows_bindtype => $rows ];
78  
79 2 return $sql;
80 }
81  
82 =head2 RowNumberOver
83  
84 SELECT * FROM (
85 SELECT *, ROW_NUMBER() OVER( ORDER BY ... ) AS RNO__ROW__INDEX FROM (
86 SELECT ...
87 )
88 ) WHERE RNO__ROW__INDEX BETWEEN ($offset+1) AND ($limit+$offset)
89  
90  
91 ANSI standard Limit/Offset implementation. Supported by B<DB2> and
92 B<< MSSQL >= 2005 >>.
93  
94 =cut
95 sub _RowNumberOver {
96 13 ▶ my ($self, $sql, $rs_attrs, $rows, $offset ) = @_;
Subroutine _RowNumberOver: called CC=7 SCAR=19.5
97  
98 # get selectors, and scan the order_by (if any)
99 13 my $sq_attrs = $self->_subqueried_limit_attrs ( $sql, $rs_attrs );
100  
101 # make up an order if none exists
102 13 ▶ my $requested_order = (delete $rs_attrs->{order_by}) || $self->_rno_default_order;
Condition66%2/3
delete $rs_attrs->{'order_by'} || $self->_rno_default_order
l!l&&r!l&&!r
607
MC/DC50%1/2
delete $rs_attrs->{'order_by'} || $self->_rno_default_order
delete $rs_attrs->{'order_by'} $self->_rno_default_order
Truth table66%2/3
A || B
A= delete $rs_attrs->{'order_by'}B= $self->_rno_default_order
ABresult
1X1
011
000
103  
104 # the order binds (if any) will need to go at the end of the entire inner select
105 13 local $self->{order_bind};
106 13 my $rno_ord = $self->_order_by ($requested_order);
107 13 push @{$self->{select_bind}}, @{$self->{order_bind}};
108  
109 # this is the order supplement magic
110 13 my $mid_sel = $sq_attrs->{selection_outer};
111 13 ▶ if (my $extra_order_sel = $sq_attrs->{order_supplement}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $extra_order_sel = $sq_attrs->{"order_supplement"}) 4 9 13
112 4 for my $extra_col (sort
113 2 { $extra_order_sel->{$a} cmp $extra_order_sel->{$b} }
114 keys %$extra_order_sel
115 ) {
116 $sq_attrs->{selection_inner} .= sprintf (', %s AS %s',
117 $extra_col,
118 6 $extra_order_sel->{$extra_col},
119 );
120 }
121 }
122  
123 # and this is order re-alias magic
124 13 for my $map ($sq_attrs->{order_supplement}, $sq_attrs->{outer_renames}) {
125 26 ▶ for my $col (sort { (length $b) <=> (length $a) } keys %{$map||{}} ) {
Branch: 1 branch
BranchTrueFalseTotal
$map or {} 14 12 26
126 28 my $re_col = quotemeta ($col);
127 28 $rno_ord =~ s/$re_col/$map->{$col}/;
128 }
129 }
130  
131 # whatever is left of the order_by (only where is processed at this point)
132 13 my $group_having = $self->_parse_rs_attrs($rs_attrs);
133  
134 13 my $qalias = $self->_quote ($rs_attrs->{alias});
135 13 my $idx_name = $self->_quote ('rno__row__index');
136  
137 13 push @{$self->{limit_bind}}, [ $self->__offset_bindtype => $offset + 1], [ $self->__total_bindtype => $offset + $rows ];
138  
139 13 return <<EOS;
140  
141 SELECT $sq_attrs->{selection_outer} FROM (
142 SELECT $mid_sel, ROW_NUMBER() OVER( $rno_ord ) AS $idx_name FROM (
143 SELECT $sq_attrs->{selection_inner} $sq_attrs->{query_leftover}${group_having}
144 ) $qalias
145 ) $qalias WHERE $idx_name >= ? AND $idx_name <= ?
146  
147 EOS
148  
149 }
150  
151 # some databases are happy with OVER (), some need OVER (ORDER BY (SELECT (1)) )
152 sub _rno_default_order {
153 7 ▶ return undef;
Subroutine _rno_default_order: called CC=1 SCAR=0.0
154 }
155  
156 =head2 SkipFirst
157  
158 SELECT SKIP $offset FIRST $limit * FROM ...
159  
160 Suported by B<Informix>, almost like LimitOffset. According to
161 L<SQL::Abstract::Limit> C<... SKIP $offset LIMIT $limit ...> is also supported.
162  
163 =cut
164 sub _SkipFirst {
165 9 ▶ my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
Subroutine _SkipFirst: called CC=3 SCAR=11.0
166  
167 9 ▶ $sql =~ s/^ \s* SELECT \s+ //ix
Branch: 1 branch
BranchTrueFalseTotal
$sql =~ s/^ \s* SELECT \s+ //xi or $self->throw_exception("Unrecognizable SELECT: $sql") 0 9 9
168 or $self->throw_exception("Unrecognizable SELECT: $sql");
169  
170 return sprintf ('SELECT %s%s%s%s',
171 $offset
172 ? do {
173 8 push @{$self->{pre_select_bind}}, [ $self->__offset_bindtype => $offset];
174 8 'SKIP ? '
175 }
176 : ''
177 ,
178 9 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
$offset ? : 8 1 9
179 9 push @{$self->{pre_select_bind}}, [ $self->__rows_bindtype => $rows ];
180 9 'FIRST ? '
181 },
182 $sql,
183 $self->_parse_rs_attrs ($rs_attrs),
184 );
185 }
186  
187 =head2 FirstSkip
188  
189 SELECT FIRST $limit SKIP $offset * FROM ...
190  
191 Supported by B<Firebird/Interbase>, reverse of SkipFirst. According to
192 L<SQL::Abstract::Limit> C<... ROWS $limit TO $offset ...> is also supported.
193  
194 =cut
195 sub _FirstSkip {
196 9 ▶ my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
Subroutine _FirstSkip: called CC=3 SCAR=11.0
197  
198 9 ▶ $sql =~ s/^ \s* SELECT \s+ //ix
Branch: 1 branch
BranchTrueFalseTotal
$sql =~ s/^ \s* SELECT \s+ //xi or $self->throw_exception("Unrecognizable SELECT: $sql") 0 9 9
199 or $self->throw_exception("Unrecognizable SELECT: $sql");
200  
201 return sprintf ('SELECT %s%s%s%s',
202 do {
203 9 push @{$self->{pre_select_bind}}, [ $self->__rows_bindtype => $rows ];
204 9 ▶ 'FIRST ? '
Branch: 1 branch
BranchTrueFalseTotal
$offset ? : 8 1 9
205 },
206 $offset
207 9 ? do {
208 8 push @{$self->{pre_select_bind}}, [ $self->__offset_bindtype => $offset];
209 8 'SKIP ? '
210 }
211 : ''
212 ,
213 $sql,
214 $self->_parse_rs_attrs ($rs_attrs),
215 );
216 }
217  
218  
219 =head2 RowNum
220  
221 Depending on the resultset attributes one of:
222  
223 SELECT * FROM (
224 SELECT *, ROWNUM rownum__index FROM (
225 SELECT ...
226 ) WHERE ROWNUM <= ($limit+$offset)
227 ) WHERE rownum__index >= ($offset+1)
228  
229 or
230  
231 SELECT * FROM (
232 SELECT *, ROWNUM rownum__index FROM (
233 SELECT ...
234 )
235 ) WHERE rownum__index BETWEEN ($offset+1) AND ($limit+$offset)
236  
237 or
238  
239 SELECT * FROM (
240 SELECT ...
241 ) WHERE ROWNUM <= ($limit+1)
242  
243 Supported by B<Oracle>.
244  
245 =cut
246 sub _RowNum {
247 13 ▶ my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
Subroutine _RowNum: called CC=4 SCAR=13.9
248  
249 13 my $sq_attrs = $self->_subqueried_limit_attrs ($sql, $rs_attrs);
250  
251 13 my $qalias = $self->_quote ($rs_attrs->{alias});
252 13 my $idx_name = $self->_quote ('rownum__index');
253 13 my $order_group_having = $self->_parse_rs_attrs($rs_attrs);
254  
255  
256 # if no offset (e.g. first page) - we can skip one of the subqueries
257 13 ▶ if (! $offset) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($offset) 3 10 13
258 3 push @{$self->{limit_bind}}, [ $self->__rows_bindtype => $rows ];
259  
260 3 return <<EOS;
261 SELECT $sq_attrs->{selection_outer} FROM (
262 SELECT $sq_attrs->{selection_inner} $sq_attrs->{query_leftover}${order_group_having}
263 ) $qalias WHERE ROWNUM <= ?
264 EOS
265 }
266  
267 #
268 # There are two ways to limit in Oracle, one vastly faster than the other
269 # on large resultsets: https://decipherinfosys.wordpress.com/2007/08/09/paging-and-countstopkey-optimization/
270 # However Oracle is retarded and does not preserve stable ROWNUM() values
271 # when called twice in the same scope. Therefore unless the resultset is
272 # ordered by a unique set of columns, it is not safe to use the faster
273 # method, and the slower BETWEEN query is used instead
274 #
275 # FIXME - this is quite expensive, and does not perform caching of any sort
276 # as soon as some of the DQ work becomes viable consider switching this
277 # over
278 10 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($rs_attrs->{'order_by'} and $rs_attrs->{'_rsroot_rsrc'}->storage->_order_by_is_stable(@{$rs_attrs;}{'from', 'order_by', 'where'})) { } 3 7 10
Condition100%3/3
$rs_attrs->{"order_by"} and $rs_attrs->{"_rsroot_rsrc"}->storage->_order_by_is_stable(@{$rs_attrs;}{"from", "order_by", "where"})
!ll&&!rl&&r
523
MC/DC100%2/2
$rs_attrs->{"order_by"} and $rs_attrs->{"_rsroot_rsrc"}->storage->_order_by_is_stable(@{$rs_attrs;}{"from", "order_by", "where"})
$rs_attrs->{"order_by"} $rs_attrs->{"_rsroot_rsrc"}->storage->_order_by_is_stable(@{$rs_attrs;}{"from", "order_by", "where"})
Truth table100%3/3
A and B
A= $rs_attrs->{"order_by"}B= $rs_attrs->{"_rsroot_rsrc"}->storage->_order_by_is_stable(@{$rs_attrs;}{"from", "order_by", "where"})
ABresult
0X0
100
111
279 $rs_attrs->{order_by}
280 and
281 $rs_attrs->{_rsroot_rsrc}->storage->_order_by_is_stable(
282 5 @{$rs_attrs}{qw/from order_by where/}
283 )
284 ) {
285 3 push @{$self->{limit_bind}}, [ $self->__total_bindtype => $offset + $rows ], [ $self->__offset_bindtype => $offset + 1 ];
286  
287 3 return <<EOS;
288 SELECT $sq_attrs->{selection_outer} FROM (
289 SELECT $sq_attrs->{selection_outer}, ROWNUM $idx_name FROM (
290 SELECT $sq_attrs->{selection_inner} $sq_attrs->{query_leftover}${order_group_having}
291 ) $qalias WHERE ROWNUM <= ?
292 ) $qalias WHERE $idx_name >= ?
293 EOS
294 }
295 else {
296 7 push @{$self->{limit_bind}}, [ $self->__offset_bindtype => $offset + 1 ], [ $self->__total_bindtype => $offset + $rows ];
297  
298 7 return <<EOS;
299 SELECT $sq_attrs->{selection_outer} FROM (
300 SELECT $sq_attrs->{selection_outer}, ROWNUM $idx_name FROM (
301 SELECT $sq_attrs->{selection_inner} $sq_attrs->{query_leftover}${order_group_having}
302 ) $qalias
303 ) $qalias WHERE $idx_name BETWEEN ? AND ?
304 EOS
305 }
306 }
307  
308 # used by _Top and _FetchFirst below
309 sub _prep_for_skimming_limit {
310 46 ▶ my ( $self, $sql, $rs_attrs ) = @_;
Subroutine _prep_for_skimming_limit: called CC=14 SCAR=26.4
311  
312 # get selectors
313 46 my $sq_attrs = $self->_subqueried_limit_attrs ($sql, $rs_attrs);
314  
315 46 my $requested_order = delete $rs_attrs->{order_by};
316 46 $sq_attrs->{order_by_requested} = $self->_order_by ($requested_order);
317 46 $sq_attrs->{grpby_having} = $self->_parse_rs_attrs ($rs_attrs);
318  
319 # without an offset things are easy
320 46 ▶ if (! $rs_attrs->{offset}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $rs_attrs->{'offset'}) { } 7 39 46
321 7 $sq_attrs->{order_by_inner} = $sq_attrs->{order_by_requested};
322 }
323 else {
324 39 $sq_attrs->{quoted_rs_alias} = $self->_quote ($rs_attrs->{alias});
325  
326 # localise as we already have all the bind values we need
327 39 local $self->{order_bind};
328  
329 # make up an order unless supplied or sanity check what we are given
330 39 my $inner_order;
331 39 ▶ if ($sq_attrs->{order_by_requested}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sq_attrs->{'order_by_requested'}) { } 24 15 39
332 $self->throw_exception (
333 'Unable to safely perform "skimming type" limit with supplied unstable order criteria'
334 ) unless ($rs_attrs->{_rsroot_rsrc}->schema->storage->_order_by_is_stable(
335 $rs_attrs->{from},
336 $requested_order,
337 $rs_attrs->{where},
338 24 ▶ ));
Branch: 1 branch
BranchTrueFalseTotal
unless $rs_attrs->{"_rsroot_rsrc"}->schema->storage->_order_by_is_stable($rs_attrs->{"from"}, $requested_order, $rs_attrs->{"where"}) 0 24 24
339  
340 24 $inner_order = $requested_order;
341 }
342 else {
343 $inner_order = [ map
344 15 { "$rs_attrs->{alias}.$_" }
345 ( @{
346 15 $rs_attrs->{_rsroot_rsrc}->_identifying_column_set
347 ||
348 $self->throw_exception(sprintf(
349 'Unable to auto-construct stable order criteria for "skimming type" limit '
350 15 ▶ . "dialect based on source '%s'", $rs_attrs->{_rsroot_rsrc}->name) );
Branch: 1 branch
BranchTrueFalseTotal
$rs_attrs->{"_rsroot_rsrc"}->_identifying_column_set or $self->throw_exception(sprintf("Unable to auto-construct stable order criteria for \"skimming type\" limit dialect based on source '%s'", $rs_attrs->{"_rsroot_rsrc"}->name)) 0 15 15
351 } )
352 ];
353 }
354  
355 39 $sq_attrs->{order_by_inner} = $self->_order_by ($inner_order);
356  
357 39 my @out_chunks;
358 39 for my $ch ($self->_order_by_chunks ($inner_order)) {
359 55 ▶ $ch = $ch->[0] if ref $ch eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $ch eq "ARRAY" 22 33 55
360  
361 55 ($ch, my $is_desc) = $self->_split_order_chunk($ch);
362  
363 # !NOTE! outside chunks come in reverse order ( !$is_desc )
364 55 ▶ push @out_chunks, { ($is_desc ? '-asc' : '-desc') => \$ch };
Branch: 1 branch
BranchTrueFalseTotal
$is_desc ? : 9 46 55
365 }
366  
367 39 $sq_attrs->{order_by_middle} = $self->_order_by (\@out_chunks);
368  
369 # this is the order supplement magic
370 39 $sq_attrs->{selection_middle} = $sq_attrs->{selection_outer};
371 39 ▶ if (my $extra_order_sel = $sq_attrs->{order_supplement}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $extra_order_sel = $sq_attrs->{"order_supplement"}) 19 20 39
372 19 for my $extra_col (sort
373 10 { $extra_order_sel->{$a} cmp $extra_order_sel->{$b} }
374 keys %$extra_order_sel
375 ) {
376 $sq_attrs->{selection_inner} .= sprintf (', %s AS %s',
377 $extra_col,
378 29 $extra_order_sel->{$extra_col},
379 );
380  
381 29 $sq_attrs->{selection_middle} .= ', ' . $extra_order_sel->{$extra_col};
382 }
383  
384 # Whatever order bindvals there are, they will be realiased and
385 # reselected, and need to show up at end of the initial inner select
386 19 push @{$self->{select_bind}}, @{$self->{order_bind}};
387 }
388  
389 # and this is order re-alias magic
390 39 for my $map ($sq_attrs->{order_supplement}, $sq_attrs->{outer_renames}) {
391 78 ▶ for my $col (sort { (length $b) <=> (length $a) } keys %{$map||{}}) {
Branch: 1 branch
BranchTrueFalseTotal
$map or {} 28 50 78
392 99 my $re_col = quotemeta ($col);
393 $_ =~ s/$re_col/$map->{$col}/
394 99 for ($sq_attrs->{order_by_middle}, $sq_attrs->{order_by_requested});
395 }
396 }
397 }
398  
399 46 $sq_attrs;
400 }
401  
402 =head2 Top
403  
404 SELECT * FROM
405  
406 SELECT TOP $limit FROM (
407 SELECT TOP $limit FROM (
408 SELECT TOP ($limit+$offset) ...
409 ) ORDER BY $reversed_original_order
410 ) ORDER BY $original_order
411  
412 Unreliable Top-based implementation, supported by B<< MSSQL < 2005 >>.
413  
414 =head3 CAVEAT
415  
416 Due to its implementation, this limit dialect returns B<incorrect results>
417 when $limit+$offset > total amount of rows in the resultset.
418  
419 =cut
420  
421 sub _Top {
422 25 ▶ my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
Subroutine _Top: called CC=7 SCAR=19.5
423  
424 25 my $lim = $self->_prep_for_skimming_limit($sql, $rs_attrs);
425  
426 $sql = sprintf ('SELECT TOP %u %s %s %s %s',
427 $rows + ($offset||0),
428 $offset ? $lim->{selection_inner} : $lim->{selection_original},
429 $lim->{query_leftover},
430 $lim->{grpby_having},
431 $lim->{order_by_inner},
432 25 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
$offset ? : 21 4 25
Condition100%2/2
$offset || 0
l!l
214
MC/DC100%1/1
$offset || 0
$offset
Truth table100%2/2
A
A= $offset
Aresult
11
00
433  
434 $sql = sprintf ('SELECT TOP %u %s FROM ( %s ) %s %s',
435 $rows,
436 $lim->{selection_middle},
437 $sql,
438 $lim->{quoted_rs_alias},
439 $lim->{order_by_middle},
440 25 ▶ ) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 21 4 25
441  
442 $sql = sprintf ('SELECT %s FROM ( %s ) %s %s',
443 $lim->{selection_outer},
444 $sql,
445 $lim->{quoted_rs_alias},
446 $lim->{order_by_requested},
447 ) if $offset and (
448 $lim->{order_by_requested} or $lim->{selection_middle} ne $lim->{selection_outer}
449 25 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
if $offset and $lim->{"order_by_requested"} || $lim->{"selection_middle"} ne $lim->{"selection_outer"} 13 12 25
Condition66%4/6
$offset and $lim->{"order_by_requested"} || $lim->{"selection_middle"} ne $lim->{"selection_outer"}
!ll&&!rl&&r
4210
$lim->{"order_by_requested"} or $lim->{"selection_middle"} ne $lim->{"selection_outer"}
l!l&&r!l&&!r
1308
MC/DC0%0/3
$offset and $lim->{"order_by_requested"} || $lim->{"selection_middle"} ne $lim->{"selection_outer"}
$offset $lim->{"order_by_requested"} $lim->{"selection_middle"} ne $lim->{"selection_outer"}
Truth table50%2/4
A and B or C
A= $offsetB= $lim->{"order_by_requested"}C= $lim->{"selection_middle"} ne $lim->{"selection_outer"}
ABCresult
0XX0
1000
11X1
1011
450  
451 25 return $sql;
452 }
453  
454 =head2 FetchFirst
455  
456 SELECT * FROM
457 (
458 SELECT * FROM (
459 SELECT * FROM (
460 SELECT * FROM ...
461 ) ORDER BY $reversed_original_order
462 FETCH FIRST $limit ROWS ONLY
463 ) ORDER BY $original_order
464 FETCH FIRST $limit ROWS ONLY
465 )
466  
467 Unreliable FetchFirst-based implementation, supported by B<< IBM DB2 <= V5R3 >>.
468  
469 =head3 CAVEAT
470  
471 Due to its implementation, this limit dialect returns B<incorrect results>
472 when $limit+$offset > total amount of rows in the resultset.
473  
474 =cut
475  
476 sub _FetchFirst {
477 21 ▶ my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
Subroutine _FetchFirst: called CC=7 SCAR=19.5
478  
479 21 my $lim = $self->_prep_for_skimming_limit($sql, $rs_attrs);
480  
481 $sql = sprintf ('SELECT %s %s %s %s FETCH FIRST %u ROWS ONLY',
482 $offset ? $lim->{selection_inner} : $lim->{selection_original},
483 $lim->{query_leftover},
484 $lim->{grpby_having},
485 $lim->{order_by_inner},
486 21 ▶ $rows + ($offset||0),
Branch: 1 branch
BranchTrueFalseTotal
$offset ? : 18 3 21
Condition100%2/2
$offset || 0
l!l
183
MC/DC100%1/1
$offset || 0
$offset
Truth table100%2/2
A
A= $offset
Aresult
11
00
487 );
488  
489 $sql = sprintf ('SELECT %s FROM ( %s ) %s %s FETCH FIRST %u ROWS ONLY',
490 $lim->{selection_middle},
491 $sql,
492 $lim->{quoted_rs_alias},
493 $lim->{order_by_middle},
494 21 ▶ $rows,
Branch: 1 branch
BranchTrueFalseTotal
if $offset 18 3 21
495 ) if $offset;
496  
497  
498 $sql = sprintf ('SELECT %s FROM ( %s ) %s %s',
499 $lim->{selection_outer},
500 $sql,
501 $lim->{quoted_rs_alias},
502 $lim->{order_by_requested},
503 ) if $offset and (
504 $lim->{order_by_requested} or $lim->{selection_middle} ne $lim->{selection_outer}
505 21 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
if $offset and $lim->{"order_by_requested"} || $lim->{"selection_middle"} ne $lim->{"selection_outer"} 11 10 21
Condition66%4/6
$offset and $lim->{"order_by_requested"} || $lim->{"selection_middle"} ne $lim->{"selection_outer"}
!ll&&!rl&&r
3180
$lim->{"order_by_requested"} or $lim->{"selection_middle"} ne $lim->{"selection_outer"}
l!l&&r!l&&!r
1107
MC/DC0%0/3
$offset and $lim->{"order_by_requested"} || $lim->{"selection_middle"} ne $lim->{"selection_outer"}
$offset $lim->{"order_by_requested"} $lim->{"selection_middle"} ne $lim->{"selection_outer"}
Truth table50%2/4
A and B or C
A= $offsetB= $lim->{"order_by_requested"}C= $lim->{"selection_middle"} ne $lim->{"selection_outer"}
ABCresult
0XX0
1000
11X1
1011
506  
507 21 return $sql;
508 }
509  
510 =head2 GenericSubQ
511  
512 SELECT * FROM (
513 SELECT ...
514 )
515 WHERE (
516 SELECT COUNT(*) FROM $original_table cnt WHERE cnt.id < $original_table.id
517 ) BETWEEN $offset AND ($offset+$rows-1)
518  
519 This is the most evil limit "dialect" (more of a hack) for I<really> stupid
520 databases. It works by ordering the set by some unique column, and calculating
521 the amount of rows that have a less-er value (thus emulating a L</RowNum>-like
522 index). Of course this implies the set can only be ordered by a single unique
523 column.
524  
525 Also note that this technique can be and often is B<excruciatingly slow>. You
526 may have much better luck using L<DBIx::Class::ResultSet/software_limit>
527 instead.
528  
529 Currently used by B<Sybase ASE>, due to lack of any other option.
530  
531 =cut
532 sub _GenericSubQ {
533 23 ▶ my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
Subroutine _GenericSubQ: called CC=16 SCAR=27.7
534  
535 23 my $root_rsrc = $rs_attrs->{_rsroot_rsrc};
536  
537 # Explicitly require an order_by
538 # GenSubQ is slow enough as it is, just emulating things
539 # like in other cases is not wise - make the user work
540 # to shoot their DBA in the foot
541 23 ▶ my $supplied_order = delete $rs_attrs->{order_by} or $self->throw_exception (
Branch: 1 branch
BranchTrueFalseTotal
my $supplied_order = delete $rs_attrs->{"order_by"} or $self->throw_exception("Generic Subquery Limit does not work on resultsets without an order. Provide a stable, root-table-based order criteria.") 0 23 23
542 'Generic Subquery Limit does not work on resultsets without an order. Provide a stable, '
543 . 'root-table-based order criteria.'
544 );
545  
546 my $usable_order_ci = $root_rsrc->storage->_main_source_order_by_portion_is_stable(
547 $root_rsrc,
548 $supplied_order,
549 $rs_attrs->{where},
550 23 ▶ ) or $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
my $usable_order_ci = $root_rsrc->storage->_main_source_order_by_portion_is_stable($root_rsrc, $supplied_order, $rs_attrs->{"where"}) or $self->throw_exception("Generic Subquery Limit can not work with order criteria based on sources other than the current one") 0 23 23
551 'Generic Subquery Limit can not work with order criteria based on sources other than the current one'
552 );
553  
554 ###
555 ###
556 ### we need to know the directions after we figured out the above - reextract *again*
557 ### this is eyebleed - trying to get it to work at first
558 23 my @order_bits = do {
559 23 local $self->{quote_char};
560 23 local $self->{order_bind};
561 23 ▶ map { ref $_ ? $_->[0] : $_ } $self->_order_by_chunks ($supplied_order)
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 12 71 83
562 };
563  
564 # truncate to what we'll use
565 23 $#order_bits = ( (keys %$usable_order_ci) - 1 );
566  
567 # @order_bits likely will come back quoted (due to how the prefetch
568 # rewriter operates
569 # Hence supplement the column_info lookup table with quoted versions
570 23 ▶ if ($self->quote_char) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->quote_char) 15 8 23
571 $usable_order_ci->{$self->_quote($_)} = $usable_order_ci->{$_}
572 15 for keys %$usable_order_ci;
573 }
574  
575 # calculate the condition
576 23 my $count_tbl_alias = 'rownum__emulation';
577 23 my $root_alias = $rs_attrs->{alias};
578 23 my $root_tbl_name = $root_rsrc->name;
579  
580 23 my (@unqualified_names, @qualified_names, @is_desc, @new_order_by);
581  
582 23 for my $bit (@order_bits) {
583  
584 69 ($bit, my $is_desc) = $self->_split_order_chunk($bit);
585  
586 69 push @is_desc, $is_desc;
587 69 push @unqualified_names, $usable_order_ci->{$bit}{-colname};
588 69 push @qualified_names, $usable_order_ci->{$bit}{-fq_colname};
589  
590 69 ▶ push @new_order_by, { ($is_desc ? '-desc' : '-asc') => $usable_order_ci->{$bit}{-fq_colname} };
Branch: 1 branch
BranchTrueFalseTotal
$is_desc ? : 38 31 69
591 };
592  
593 23 my (@where_cond, @skip_colpair_stack);
594 23 for my $i (0 .. $#order_bits) {
595 69 my $ci = $usable_order_ci->{$order_bits[$i]};
596  
597 69 my ($subq_col, $main_col) = map { "$_.$ci->{-colname}" } ($count_tbl_alias, $root_alias);
598 69 ▶ my $cur_cond = { $subq_col => { ($is_desc[$i] ? '>' : '<') => { -ident => $main_col } } };
Branch: 1 branch
BranchTrueFalseTotal
$is_desc[$i] ? : 38 31 69
599  
600 69 push @skip_colpair_stack, [
601 { $main_col => { -ident => $subq_col } },
602 ];
603  
604 # we can trust the nullability flag because
605 # we already used it during _id_col_set resolution
606 #
607 69 ▶ if ($ci->{is_nullable}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ci->{"is_nullable"}) 24 45 69
608 24 push @{$skip_colpair_stack[-1]}, { $main_col => undef, $subq_col=> undef };
609  
610 24 ▶ $cur_cond = [
Branch: 2 branches
BranchTrueFalseTotal
$is_desc[$i] ? : 14 10 24
$is_desc[$i] ? : 14 10 24
611 {
612 ($is_desc[$i] ? $subq_col : $main_col) => { '!=', undef },
613 ($is_desc[$i] ? $main_col : $subq_col) => undef,
614 },
615 {
616 $subq_col => { '!=', undef },
617 $main_col => { '!=', undef },
618 -and => $cur_cond,
619 },
620 ];
621 }
622  
623 69 push @where_cond, { '-and', => [ @skip_colpair_stack[0..$i-1], $cur_cond ] };
624 }
625  
626 # reuse the sqlmaker WHERE, this will not be returning binds
627 23 my $counted_where = do {
628 23 local $self->{where_bind};
629 23 $self->where(\@where_cond);
630 };
631  
632 # construct the rownum condition by hand
633 23 my $rownum_cond;
634 23 ▶ if ($offset) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset) { } 15 8 23
635 15 $rownum_cond = 'BETWEEN ? AND ?';
636 15 push @{$self->{limit_bind}},
637 [ $self->__offset_bindtype => $offset ],
638 [ $self->__total_bindtype => $offset + $rows - 1]
639 ;
640 }
641 else {
642 8 $rownum_cond = '< ?';
643 8 push @{$self->{limit_bind}},
644 [ $self->__rows_bindtype => $rows ]
645 ;
646 }
647  
648 # and what we will order by inside
649 23 my $inner_order_sql = do {
650 23 local $self->{order_bind};
651  
652 23 my $s = $self->_order_by (\@new_order_by);
653  
654 $self->throw_exception('Inner gensubq order may not contain binds... something went wrong')
655 23 ▶ if @{$self->{order_bind}};
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->{"order_bind"};} 0 23 23
656  
657 23 $s;
658 };
659  
660 ### resume originally scheduled programming
661 ###
662 ###
663  
664 # we need to supply the order for the supplements to be properly calculated
665 23 my $sq_attrs = $self->_subqueried_limit_attrs (
666 $sql, { %$rs_attrs, order_by => \@new_order_by }
667 );
668  
669 23 my $in_sel = $sq_attrs->{selection_inner};
670  
671 # add the order supplement (if any) as this is what will be used for the outer WHERE
672 23 $in_sel .= ", $_" for sort keys %{$sq_attrs->{order_supplement}};
673  
674 23 my $group_having_sql = $self->_parse_rs_attrs($rs_attrs);
675  
676  
677 return sprintf ("
678 SELECT $sq_attrs->{selection_outer}
679 FROM (
680 SELECT $in_sel $sq_attrs->{query_leftover}${group_having_sql}
681 ) %s
682 WHERE ( SELECT COUNT(*) FROM %s %s $counted_where ) $rownum_cond
683 $inner_order_sql
684 69 ", map { $self->_quote ($_) } (
685 $rs_attrs->{alias},
686 23 $root_tbl_name,
687 $count_tbl_alias,
688 ));
689 }
690  
691  
692 # !!! THIS IS ALSO HORRIFIC !!! /me ashamed
693 #
694 # Generates inner/outer select lists for various limit dialects
695 # which result in one or more subqueries (e.g. RNO, Top, RowNum)
696 # Any non-root-table columns need to have their table qualifier
697 # turned into a column alias (otherwise names in subqueries clash
698 # and/or lose their source table)
699 #
700 # Returns mangled proto-sql, inner/outer strings of SQL QUOTED selectors
701 # with aliases (to be used in whatever select statement), and an alias
702 # index hashref of QUOTED SEL => QUOTED ALIAS pairs (to maybe be used
703 # for string-subst higher up).
704 # If an order_by is supplied, the inner select needs to bring out columns
705 # used in implicit (non-selected) orders, and the order condition itself
706 # needs to be realiased to the proper names in the outer query. Thus we
707 # also return a hashref (order doesn't matter) of QUOTED EXTRA-SEL =>
708 # QUOTED ALIAS pairs, which is a list of extra selectors that do *not*
709 # exist in the original select list
710 sub _subqueried_limit_attrs {
711 95 ▶ my ($self, $proto_sql, $rs_attrs) = @_;
Subroutine _subqueried_limit_attrs: called CC=22 SCAR=32.1
712  
713 95 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rs_attrs eq "HASH" 0 95 95
714 'Limit dialect implementation usable only in the context of DBIC (missing $rs_attrs)'
715 ) unless ref ($rs_attrs) eq 'HASH';
716  
717 # mangle the input sql as we will be replacing the selector entirely
718 95 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless ($rs_attrs->{"_selector_sql"} and $proto_sql =~ s/^ \s* SELECT \s* \Q$rs_attrs->{"_selector_sql"}\E//xi) 0 95 95
Condition33%1/3
$rs_attrs->{"_selector_sql"} and $proto_sql =~ s/^ \s* SELECT \s* \Q$rs_attrs->{"_selector_sql"}\E//xi
!ll&&!rl&&r
0095
MC/DC0%0/2
$rs_attrs->{"_selector_sql"} and $proto_sql =~ s/^ \s* SELECT \s* \Q$rs_attrs->{"_selector_sql"}\E//xi
$rs_attrs->{"_selector_sql"} $proto_sql =~ s/^ \s* SELECT \s* \Q$rs_attrs->{"_selector_sql"}\E//xi
Truth table33%1/3
A and B
A= $rs_attrs->{"_selector_sql"}B= $proto_sql =~ s/^ \s* SELECT \s* \Q$rs_attrs->{"_selector_sql"}\E//xi
ABresult
0X0
100
111
719 $rs_attrs->{_selector_sql}
720 and
721 $proto_sql =~ s/^ \s* SELECT \s* \Q$rs_attrs->{_selector_sql}//ix
722 ) {
723 0 $self->throw_exception("Unrecognizable SELECT: $proto_sql");
724 }
725  
726 95 my ($re_sep, $re_alias) = map { quotemeta $_ } ( $self->{name_sep}, $rs_attrs->{alias} );
727  
728 # insulate from the multiple _recurse_fields calls below
729 95 local $self->{select_bind};
730  
731 # correlate select and as, build selection index
732 95 my (@sel, $in_sel_index);
733 95 for my $i (0 .. $#{$rs_attrs->{select}}) {
734  
735 414 my $s = $rs_attrs->{select}[$i];
736 414 my $sql_sel = $self->_recurse_fields ($s);
737 414 ▶ my $sql_alias = (ref $s) eq 'HASH' ? $s->{-as} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $s eq 'HASH' ? : 0 414 414
738  
739 push @sel, {
740 arg => $s,
741 sql => $sql_sel,
742 unquoted_sql => do {
743 414 local $self->{quote_char};
744 414 ▶ $self->_recurse_fields ($s);
Condition33%2/6
$sql_alias || $rs_attrs->{'as'}[$i] || $self->throw_exception("Select argument $i ($s) without corresponding 'as'")
l!l&&r!l&&!r
41400
$sql_alias or $rs_attrs->{"as"}[$i]
l!l&&r!l&&!r
04140
MC/DC0%0/3
$sql_alias || $rs_attrs->{'as'}[$i] || $self->throw_exception("Select argument $i ($s) without corresponding 'as'")
$sql_alias $rs_attrs->{"as"}[$i] $self->throw_exception("Select argument $i ($s) without corresponding 'as'")
Truth table25%1/4
A or B || C
A= $sql_aliasB= $rs_attrs->{"as"}[$i]C= $self->throw_exception("Select argument $i ($s) without corresponding 'as'")
ABCresult
1XX1
01X1
0011
0000
745 },
746 as =>
747 $sql_alias
748 ||
749 414 $rs_attrs->{as}[$i]
750 ||
751 $self->throw_exception("Select argument $i ($s) without corresponding 'as'")
752 ,
753 };
754  
755 # anything with a placeholder in it needs re-selection
756 414 ▶ $in_sel_index->{$sql_sel}++ unless $sql_sel =~ / (?: ^ | \W ) \? (?: \W | $ ) /x;
Branch: 1 branch
BranchTrueFalseTotal
unless $sql_sel =~ / (?: ^ | \W ) \? (?: \W | $ ) /x 373 41 414
757  
758 414 ▶ $in_sel_index->{$self->_quote ($sql_alias)}++ if $sql_alias;
Branch: 1 branch
BranchTrueFalseTotal
if $sql_alias 0 414 414
759  
760 # record unqualified versions too, so we do not have
761 # to reselect the same column twice (in qualified and
762 # unqualified form)
763 414 ▶ if (! ref $s && $sql_sel =~ / $re_sep (.+) $/x) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $s and $sql_sel =~ / $re_sep (.+) $/x) 367 47 414
Condition66%2/3
not ref $s and $sql_sel =~ / $re_sep (.+) $/x
!ll&&!rl&&r
470367
MC/DC50%1/2
not ref $s and $sql_sel =~ / $re_sep (.+) $/x
not ref $s $sql_sel =~ / $re_sep (.+) $/x
Truth table66%2/3
not(A) and B
A= not ref $sB= $sql_sel =~ / $re_sep (.+) $/x
ABresult
0X0
100
111
764 367 $in_sel_index->{$1}++;
765 }
766 }
767  
768  
769 # re-alias and remove any name separators from aliases,
770 # unless we are dealing with the current source alias
771 # (which will transcend the subqueries as it is necessary
772 # for possible further chaining)
773 # same for anything we do not recognize
774 95 my ($sel, $renamed);
775 95 for my $node (@sel) {
776 414 push @{$sel->{original}}, $node->{sql};
777  
778 414 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (not $$in_sel_index{$node->{'sql'}} or $node->{'as'} =~ / (?<! ^ $re_alias ) \. /x or $node->{'unquoted_sql'} =~ / (?<! ^ $re_alias ) $re_sep /x) { } 161 253 414
Condition100%6/6
not $$in_sel_index{$node->{"sql"}} or $node->{"as"} =~ / (?<! ^ $re_alias ) \. /x or $node->{"unquoted_sql"} =~ / (?<! ^ $re_alias ) $re_sep /x
l!l&&r!l&&!r
14021253
not $$in_sel_index{$node->{"sql"}} or $node->{"as"} =~ / (?<! ^ $re_alias ) \. /x
l!l&&r!l&&!r
4199274
MC/DC100%3/3
not $$in_sel_index{$node->{"sql"}} or $node->{"as"} =~ / (?<! ^ $re_alias ) \. /x or $node->{"unquoted_sql"} =~ / (?<! ^ $re_alias ) $re_sep /x
not $$in_sel_index{$node->{"sql"}} $node->{"as"} =~ / (?<! ^ $re_alias ) \. /x $node->{"unquoted_sql"} =~ / (?<! ^ $re_alias ) $re_sep /x
Truth table100%4/4
not(A) or B or C
A= not $$in_sel_index{$node->{"sql"}}B= $node->{"as"} =~ / (?<! ^ $re_alias ) \. /xC= $node->{"unquoted_sql"} =~ / (?<! ^ $re_alias ) $re_sep /x
ABCresult
1XX1
01X1
0011
0000
779 ! $in_sel_index->{$node->{sql}}
780 or
781 $node->{as} =~ / (?<! ^ $re_alias ) \. /x
782 or
783 $node->{unquoted_sql} =~ / (?<! ^ $re_alias ) $re_sep /x
784 ) {
785 161 $node->{as} = $self->_unqualify_colname($node->{as});
786 161 my $quoted_as = $self->_quote($node->{as});
787 161 push @{$sel->{inner}}, sprintf '%s AS %s', $node->{sql}, $quoted_as;
788 161 push @{$sel->{outer}}, $quoted_as;
789 161 $renamed->{$node->{sql}} = $quoted_as;
790 }
791 else {
792 253 push @{$sel->{inner}}, $node->{sql};
793 253 ▶ push @{$sel->{outer}}, $self->_quote (ref $node->{arg} ? $node->{as} : $node->{arg});
Branch: 1 branch
BranchTrueFalseTotal
ref $node->{'arg'} ? : 0 253 253
794 }
795 }
796  
797 # see if the order gives us anything
798 95 my $extra_order_sel;
799 95 for my $chunk ($self->_order_by_chunks ($rs_attrs->{order_by})) {
800 # order with bind
801 134 ▶ $chunk = $chunk->[0] if (ref $chunk) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $chunk eq "ARRAY" 105 29 134
802 134 ($chunk) = $self->_split_order_chunk($chunk);
803  
804 134 ▶ next if $in_sel_index->{$chunk};
Branch: 1 branch
BranchTrueFalseTotal
if $in_sel_index->{$chunk} 79 55 134
805  
806 $extra_order_sel->{$chunk} ||= $self->_quote (
807 55 ▶ 'ORDER__BY__' . sprintf '%03d', scalar keys %{$extra_order_sel||{}}
Branch: 1 branch
BranchTrueFalseTotal
$extra_order_sel or {} 0 55 55
Condition33%1/3
$extra_order_sel->{$chunk} ||= $self->_quote('ORDER__BY__' . sprintf("%03d", scalar keys %{$extra_order_sel or {};}))
l!l&&r!l&&!r
0550
MC/DC0%0/2
$extra_order_sel->{$chunk} ||= $self->_quote('ORDER__BY__' . sprintf("%03d", scalar keys %{$extra_order_sel or {};}))
$extra_order_sel->{$chunk} $self->_quote('ORDER__BY__' . sprintf("%03d", scalar keys %{$extra_order_sel or {};}))
Truth table33%1/3
A ||= B
A= $extra_order_sel->{$chunk}B= $self->_quote('ORDER__BY__' . sprintf("%03d", scalar keys %{$extra_order_sel or {};}))
ABresult
1X1
011
000
808 );
809 }
810  
811 return {
812 query_leftover => $proto_sql,
813 95 (map {( "selection_$_" => join (', ', @{$sel->{$_}} ) )} keys %$sel ),
814 outer_renames => $renamed,
815 order_supplement => $extra_order_sel,
816 };
817 }
818  
819 sub _unqualify_colname {
820 161 ▶ my ($self, $fqcn) = @_;
Subroutine _unqualify_colname: called CC=1 SCAR=0.0
821 161 $fqcn =~ s/ \. /__/xg;
822 161 return $fqcn;
823 }
824  
825 201 1;
826  
827 =head1 AUTHORS
828  
829 See L<DBIx::Class/CONTRIBUTORS>.
830  
831 =head1 LICENSE
832  
833 You may distribute this code under the same terms as Perl itself.
834  
835 =cut
« DBIx/Class/Storage/BlockRunner.pm ↑ Summary DBIx/Class/Storage/DBI/Sybase.pm »