SearchBuilder.pm

filter: Statementstmt 90.5% 490 / 541 Branchbran 79.4% 197 / 248 Conditioncond 67.1% 96 / 143 MC/DCmcdc 46.0% 35 / 76 Subroutinesub 87.8% 72 / 82 Podpod 97.9% 47 / 48 totaltotal 82.3% 937 / 1138 CC 188 SCAR 22.0
CC
188
Cov
84%
_GenericRestriction
26.3
Limit
19.9
_OrderClause
17.5
CRAP 9.1
« SearchBuilder/Handle/ODBC.pm ↑ Summary SearchBuilder/Handle/SQLite.pm »
1  
2 package DBIx::SearchBuilder;
3  
4 14 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 14 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 14 our $VERSION = "1.86";
8  
9 14 ▶use Clone qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 14 ▶use Encode qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 14 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 14 ▶use DBIx::SearchBuilder::Util qw/ sorted_values /;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 14 our $PREFER_BIND = $ENV{SB_PREFER_BIND};
14 14 our $PREFER_LAZY_LOAD = $ENV{SB_PREFER_LAZY_LOAD};
15  
16 =head1 NAME
17  
18 DBIx::SearchBuilder - Encapsulate SQL queries and rows in simple perl objects
19  
20 =head1 SYNOPSIS
21  
22 use DBIx::SearchBuilder;
23  
24 package My::Things;
25 use base qw/DBIx::SearchBuilder/;
26  
27 sub _Init {
28 my $self = shift;
29 $self->Table('Things');
30 return $self->SUPER::_Init(@_);
31 }
32  
33 sub NewItem {
34 my $self = shift;
35 # MyThing is a subclass of DBIx::SearchBuilder::Record
36 return(MyThing->new);
37 }
38  
39 package main;
40  
41 use DBIx::SearchBuilder::Handle;
42 my $handle = DBIx::SearchBuilder::Handle->new();
43 $handle->Connect( Driver => 'SQLite', Database => "my_test_db" );
44  
45 my $sb = My::Things->new( Handle => $handle );
46  
47 $sb->Limit( FIELD => "column_1", VALUE => "matchstring" );
48  
49 while ( my $record = $sb->Next ) {
50  
51 # SearchBuilder returns the vanilla value fetched from database drivers. Note
52 # that different drivers handle the encoding differently. Check your
53 # driver's documentation to get more details.
54  
55 print $record->my_column_name();
56 }
57  
58 # Show the generated SELECT query, possibly for debugging
59 my $QueryString = $sb->BuildSelectQuery();
60 print "Select query is: $QueryString";
61  
62 =head1 DESCRIPTION
63  
64 This module provides an object-oriented mechanism for retrieving and updating data in a DBI-accessible database.
65  
66 In order to use this module, you should create a subclass of C<DBIx::SearchBuilder> and a
67 subclass of C<DBIx::SearchBuilder::Record> for each table that you wish to access. (See
68 the documentation of C<DBIx::SearchBuilder::Record> for more information on subclassing it.)
69  
70 Your C<DBIx::SearchBuilder> subclass must override C<NewItem>, and probably should override
71 at least C<_Init> also; at the very least, C<_Init> should probably call C<_Handle> and C<_Table>
72 to set the database handle (a C<DBIx::SearchBuilder::Handle> object) and table name for the class.
73 You can try to override just about every other method here, as long as you think you know what you
74 are doing.
75  
76 =head1 METHOD NAMING
77  
78 Each method has a lower case alias; '_' is used to separate words.
79 For example, the method C<RedoSearch> has the alias C<redo_search>.
80  
81 =head1 METHODS
82  
83 =cut
84  
85  
86 =head2 new
87  
88 Creates a new SearchBuilder object and immediately calls C<_Init> with the same parameters
89 that were passed to C<new>. If you haven't overridden C<_Init> in your subclass, this means
90 that you should pass in a C<DBIx::SearchBuilder::Handle> (or one of its subclasses) like this:
91  
92 my $sb = My::DBIx::SearchBuilder::Subclass->new( Handle => $handle );
93  
94 However, if your subclass overrides _Init you do not need to take a Handle argument, as long
95 as your subclass returns an appropriate handle object from the C<_Handle> method. This is
96 useful if you want all of your SearchBuilder objects to use a shared global handle and don't want
97 to have to explicitly pass it in each time, for example.
98  
99 =cut
100  
101 159 ▶sub new {
Subroutine new: called CC=2 SCAR=7.0
Pod documented
102 159 my $proto = shift;
103 159 ▶ my $class = ref($proto) || $proto;
Condition66%2/3
ref $proto || $proto
l!l&&r!l&&!r
11580
MC/DC0%0/2
ref $proto || $proto
ref $proto $proto
Truth table66%2/3
A || B
A= ref $protoB= $proto
ABresult
1X1
011
000
104 159 my $self = {};
105 159 bless( $self, $class );
106 159 $self->_Init(@_);
107 159 return ($self);
108 }
109  
110  
111  
112 =head2 _Init
113  
114 This method is called by C<new> with whatever arguments were passed to C<new>.
115 By default, it takes a C<DBIx::SearchBuilder::Handle> object as a C<Handle>
116 argument, although this is not necessary if your subclass overrides C<_Handle>.
117  
118 =cut
119  
120 157 ▶sub _Init {
Subroutine _Init: called CC=1 SCAR=0.0
121 157 my $self = shift;
122 157 my %args = ( Handle => undef,
123 @_ );
124 157 $self->_Handle( $args{'Handle'} );
125  
126 157 $self->CleanSlate();
127 }
128  
129  
130  
131 =head2 CleanSlate
132  
133 This completely erases all the data in the SearchBuilder object. It's
134 useful if a subclass is doing funky stuff to keep track of a search and
135 wants to reset the SearchBuilder data without losing its own data;
136 it's probably cleaner to accomplish that in a different way, though.
137  
138 =cut
139  
140 195 ▶sub CleanSlate {
Subroutine CleanSlate: called CC=2 SCAR=6.9
Pod documented
141 195 my $self = shift;
142 195 $self->RedoSearch();
143 195 $self->{'itemscount'} = 0;
144 195 $self->{'limit_clause'} = "";
145 195 $self->{'order'} = "";
146 195 $self->{'alias_count'} = 0;
147 195 $self->{'first_row'} = 0;
148 195 $self->{'must_redo_search'} = 1;
149 195 $self->{'show_rows'} = 0;
150 195 $self->{'joins_are_distinct'} = undef;
151 195 @{ $self->{'aliases'} } = ();
152  
153 195 delete $self->{$_} for qw(
154 items
155 left_joins
156 count_all
157 subclauses
158 restrictions
159 _open_parens
160 _close_parens
161 group_by
162 columns
163 query_hint
164 _bind_values
165 _prefer_bind
166 _combine_search_and_count
167 _columns_for_query
168 _select_all_columns
169 );
170  
171 #we have no limit statements. DoSearch won't work.
172 195 $self->_isLimited(0);
173 }
174  
175 =head2 Clone
176  
177 Returns copy of the current object with all search restrictions.
178  
179 =cut
180  
181 sub Clone
182 13 ▶{
Subroutine Clone: called CC=3 SCAR=11.0
Pod documented
183 13 my $self = shift;
184  
185 13 my $obj = bless {}, ref($self);
186 13 %$obj = %$self;
187  
188 13 delete $obj->{$_} for qw(
189 items
190 );
191 13 $obj->{'must_redo_search'} = 1;
192 13 $obj->{'itemscount'} = 0;
193  
194 $obj->{ $_ } = Clone::clone( $obj->{ $_ } )
195 13 foreach grep exists $self->{ $_ }, $self->_ClonedAttributes;
196 13 return $obj;
197 }
198  
199 =head2 _ClonedAttributes
200  
201 Returns list of the object's fields that should be copied.
202  
203 If your subclass store references in the object that should be copied while
204 clonning then you probably want override this method and add own values to
205 the list.
206  
207 =cut
208  
209 sub _ClonedAttributes
210 13 ▶{
Subroutine _ClonedAttributes: called CC=1 SCAR=0.0
211 13 return qw(
212 aliases
213 left_joins
214 subclauses
215 restrictions
216 order_by
217 group_by
218 columns
219 query_hint
220 );
221 }
222  
223  
224  
225 =head2 _Handle [DBH]
226  
227 Get or set this object's DBIx::SearchBuilder::Handle object.
228  
229 =cut
230  
231 4323 ▶sub _Handle {
Subroutine _Handle: called CC=2 SCAR=6.9
232 4323 my $self = shift;
233 4323 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 159 4164 4323
234 159 $self->{'DBIxHandle'} = shift;
235 }
236 4323 return ( $self->{'DBIxHandle'} );
237 }
238  
239 =head2 _DoSearch
240  
241 This internal private method actually executes the search on the database;
242 it is called automatically the first time that you actually need results
243 (such as a call to C<Next>).
244  
245 =cut
246  
247 203 ▶sub _DoSearch {
Subroutine _DoSearch: called CC=3 SCAR=11.0
248 203 my $self = shift;
249  
250 203 ▶ if ( $self->{_combine_search_and_count} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_combine_search_and_count"}) 44 159 203
251 44 my ($count) = $self->_DoSearchAndCount;
252 44 return $count;
253 }
254  
255 159 my $QueryString = $self->BuildSelectQuery();
256 159 ▶ my $records = $self->_Handle->SimpleQuery( $QueryString, @{ $self->{_bind_values} || [] } );
Condition100%2/2
$self->{'_bind_values'} || []
l!l
10149
MC/DC100%1/1
$self->{'_bind_values'} || []
$self->{'_bind_values'}
Truth table100%2/2
A
A= $self->{'_bind_values'}
Aresult
11
00
257 159 return $self->__DoSearch($records);
258 }
259  
260 205 ▶sub __DoSearch {
Subroutine __DoSearch: called CC=6 SCAR=17.9
261 205 my $self = shift;
262 205 my $records = shift;
263  
264 # If we're about to redo the search, we need an empty set of items and a reset iterator
265 205 delete $self->{'items'};
266 205 $self->{'itemscount'} = 0;
267  
268 205 ▶ return 0 unless $records;
Branch: 1 branch
BranchTrueFalseTotal
unless $records 0 205 205
269  
270 205 ▶ while ( my $row = $records->fetchrow_hashref() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $records->fetchrow_hashref) 2238 205 2443
271  
272 # search_builder_count_all is from combine search
273 2238 ▶ if ( !defined $self->{count_all} && $row->{search_builder_count_all} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"count_all"} and $row->{"search_builder_count_all"}) 42 2196 2238
Condition100%3/3
not defined $self->{"count_all"} and $row->{"search_builder_count_all"}
!ll&&!rl&&r
627156942
MC/DC100%2/2
not defined $self->{"count_all"} and $row->{"search_builder_count_all"}
not defined $self->{"count_all"} $row->{"search_builder_count_all"}
Truth table100%3/3
not(A) and B
A= not defined $self->{"count_all"}B= $row->{"search_builder_count_all"}
ABresult
0X0
100
111
274 42 $self->{count_all} = $row->{search_builder_count_all};
275 }
276  
277 2238 my $item = $self->NewItem();
278 2238 $item->LoadFromHash($row);
279 2238 $self->AddRecord($item);
280 }
281 205 ▶ return $self->_RecordCount if $records->err;
Branch: 1 branch
BranchTrueFalseTotal
if $records->err 0 205 205
282  
283 205 $self->{'must_redo_search'} = 0;
284  
285 205 return $self->_RecordCount;
286 }
287  
288  
289 =head2 AddRecord RECORD
290  
291 Adds a record object to this collection.
292  
293 =cut
294  
295 2238 ▶sub AddRecord {
Subroutine AddRecord: called CC=1 SCAR=0.0
Pod documented
296 2238 my $self = shift;
297 2238 my $record = shift;
298 2238 push @{$self->{'items'}}, $record;
299 }
300  
301 =head2 _RecordCount
302  
303 This private internal method returns the number of Record objects saved
304 as a result of the last query.
305  
306 =cut
307  
308 1732 ▶sub _RecordCount {
Subroutine _RecordCount: called CC=2 SCAR=6.9
309 1732 my $self = shift;
310 1732 ▶ return 0 unless defined $self->{'items'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"items"} 27 1705 1732
311 1705 return scalar @{ $self->{'items'} };
312 }
313  
314  
315  
316 =head2 _DoCount
317  
318 This internal private method actually executes a counting operation on the database;
319 it is used by C<Count> and C<CountAll>.
320  
321 =cut
322  
323  
324 71 ▶sub _DoCount {
Subroutine _DoCount: called CC=2 SCAR=6.9
325 71 my $self = shift;
326  
327 71 ▶ if ( $self->{_combine_search_and_count} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_combine_search_and_count"}) 2 69 71
328 2 (undef, my $count_all) = $self->_DoSearchAndCount;
329 2 return $count_all;
330 }
331  
332 69 return $self->__DoCount;
333 }
334  
335 73 ▶sub __DoCount {
Subroutine __DoCount: called CC=4 SCAR=14.0
336 73 my $self = shift;
337  
338 73 my $QueryString = $self->BuildSelectCountQuery();
339 73 ▶ my $records = $self->_Handle->SimpleQuery( $QueryString, @{ $self->{_bind_values} || [] } );
Condition100%2/2
$self->{'_bind_values'} || []
l!l
766
MC/DC100%1/1
$self->{'_bind_values'} || []
$self->{'_bind_values'}
Truth table100%2/2
A
A= $self->{'_bind_values'}
Aresult
11
00
340 73 ▶ return 0 unless $records;
Branch: 1 branch
BranchTrueFalseTotal
unless $records 0 73 73
341  
342 73 my @row = $records->fetchrow_array();
343 73 ▶ return 0 if $records->err;
Branch: 1 branch
BranchTrueFalseTotal
if $records->err 0 73 73
344  
345 73 $self->{'count_all'} = $row[0];
346  
347 73 return ( $row[0] );
348 }
349  
350 =head2 _DoSearchAndCount
351  
352 This internal private method actually executes the search and also counting on the database;
353  
354 =cut
355  
356 46 ▶sub _DoSearchAndCount {
Subroutine _DoSearchAndCount: called CC=3 SCAR=11.1
357 46 my $self = shift;
358  
359 46 my $QueryString = $self->BuildSelectAndCountQuery();
360 46 ▶ my $records = $self->_Handle->SimpleQuery( $QueryString, @{ $self->{_bind_values} || [] } );
Condition50%1/2
$self->{'_bind_values'} || []
l!l
046
MC/DC0%0/1
$self->{'_bind_values'} || []
$self->{'_bind_values'}
Truth table50%1/2
A
A= $self->{'_bind_values'}
Aresult
11
00
361  
362 46 undef $self->{count_all};
363 # __DoSearch updates count_all
364 46 my $count = $self->__DoSearch($records);
365  
366 # If no results returned, we have to query the count separately.
367 46 ▶ $self->{count_all} //= $self->__DoCount;
Condition66%2/3
$self->{"count_all"} //= $self->__DoCount
l!l&&r!l&&!r
4240
MC/DC0%0/2
$self->{"count_all"} //= $self->__DoCount
$self->{"count_all"} $self->__DoCount
Truth table66%2/3
A //= B
A= $self->{"count_all"}B= $self->__DoCount
ABresult
1X1
011
000
368  
369 46 return ( $count, $self->{count_all} );
370 }
371  
372 =head2 _ApplyLimits STATEMENTREF
373  
374 This routine takes a reference to a scalar containing an SQL statement.
375 It massages the statement to limit the returned rows to only C<< $self->RowsPerPage >>
376 rows, skipping C<< $self->FirstRow >> rows. (That is, if rows are numbered
377 starting from 0, row number C<< $self->FirstRow >> will be the first row returned.)
378 Note that it probably makes no sense to set these variables unless you are also
379 enforcing an ordering on the rows (with C<OrderByCols>, say).
380  
381 =cut
382  
383  
384 231 ▶sub _ApplyLimits {
Subroutine _ApplyLimits: called CC=2 SCAR=6.9
385 231 my $self = shift;
386 231 my $statementref = shift;
387 231 $self->_Handle->ApplyLimits($statementref, $self->RowsPerPage, $self->FirstRow, $self);
388  
389 231 my $cols = $self->_ColumnsForQuery;
390 231 ▶ $$statementref =~ s/main\.\*/$cols/g unless $cols eq 'main.*';
Branch: 1 branch
BranchTrueFalseTotal
unless $cols eq "main.*" 51 180 231
391 }
392  
393  
394 =head2 _DistinctQuery STATEMENTREF
395  
396 This routine takes a reference to a scalar containing an SQL statement.
397 It massages the statement to ensure a distinct result set is returned.
398  
399 =cut
400  
401 68 ▶sub _DistinctQuery {
Subroutine _DistinctQuery: called CC=1 SCAR=0.0
402 68 my $self = shift;
403 68 my $statementref = shift;
404  
405 # XXX - Postgres gets unhappy with distinct and OrderBy aliases
406 68 $self->_Handle->DistinctQuery($statementref, $self)
407 }
408  
409 =head2 _DistinctQueryAndCount STATEMENTREF
410  
411 This routine takes a reference to a scalar containing an SQL statement.
412 It massages the statement to ensure a distinct result set and total number
413 of potential records are returned.
414  
415 =cut
416  
417 43 ▶sub _DistinctQueryAndCount {
Subroutine _DistinctQueryAndCount: called CC=1 SCAR=0.0
418 43 my $self = shift;
419 43 my $statementref = shift;
420  
421 43 $self->_Handle->DistinctQueryAndCount($statementref, $self);
422 }
423  
424 =head2 _BuildJoins
425  
426 Build up all of the joins we need to perform this query.
427  
428 =cut
429  
430  
431 318 ▶sub _BuildJoins {
Subroutine _BuildJoins: called CC=1 SCAR=0.0
432 318 my $self = shift;
433  
434 318 return ( $self->_Handle->_BuildJoins($self) );
435 }
436  
437  
438 =head2 _isJoined
439  
440 Returns true if this SearchBuilder will be joining multiple tables together.
441  
442 =cut
443  
444 317 ▶sub _isJoined {
Subroutine _isJoined: called CC=2 SCAR=6.9
445 317 my $self = shift;
446 317 ▶ if ( keys %{ $self->{'left_joins'} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %{$$self{'left_joins'};}) { } 152 165 317
447 152 return (1);
448 } else {
449 165 return (@{ $self->{'aliases'} });
450 }
451  
452 }
453  
454  
455  
456  
457 # LIMIT clauses are used for restricting ourselves to subsets of the search.
458  
459  
460  
461 0 ▶sub _LimitClause {
Subroutine _LimitClause: not called CC=3 SCAR=24.8
462 0 my $self = shift;
463 0 my $limit_clause;
464  
465 0 ▶ if ( $self->RowsPerPage ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->RowsPerPage) { } 0 0 0
466 0 $limit_clause = " LIMIT ";
467 0 ▶ if ( $self->FirstRow != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->FirstRow != 0) 0 0 0
468 0 $limit_clause .= $self->FirstRow . ", ";
469 }
470 0 $limit_clause .= $self->RowsPerPage;
471 }
472 else {
473 0 $limit_clause = "";
474 }
475 0 return $limit_clause;
476 }
477  
478  
479  
480 =head2 _isLimited
481  
482 If we've limited down this search, return true. Otherwise, return false.
483  
484 =cut
485  
486 2466 ▶sub _isLimited {
Subroutine _isLimited: called CC=2 SCAR=6.9
487 2466 my $self = shift;
488 2466 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 416 2050 2466
489 416 $self->{'is_limited'} = shift;
490 }
491 else {
492 2050 return ( $self->{'is_limited'} );
493 }
494 }
495  
496  
497  
498  
499 =head2 _ColumnsForQuery
500  
501 Returns the column selection string for use in SELECT statements.
502  
503 If explicit columns have been added via L</Column>, those are returned as-is.
504 If C<_select_all_columns> is set on the object, or if the package variable
505 C<$DBIx::SearchBuilder::PREFER_LAZY_LOAD> (controlled by the
506 C<SB_PREFER_LAZY_LOAD> environment variable) is false, returns C<main.*>.
507 Otherwise introspects the record class's C<_ClassAccessible> metadata and
508 excludes columns marked as C<lazy_load>, C<foreign-collection>, or
509 C<record-read>. Falls back to C<main.*> if no metadata is available.
510  
511 =cut
512  
513 310 ▶sub _ColumnsForQuery {
Subroutine _ColumnsForQuery: called CC=11 SCAR=25.1
514 310 my $self = shift;
515  
516 # Explicit column list from Column() calls takes priority; not cached
517 # since Column() may be called incrementally.
518 61 return join( ', ', @{ $self->{columns} } )
519 310 ▶ if $self->{columns} and @{ $self->{columns} };
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"columns"} and @{$self->{"columns"};} 61 249 310
Condition66%2/3
$self->{"columns"} and @{$self->{"columns"};}
!ll&&!rl&&r
249061
MC/DC50%1/2
$self->{"columns"} and @{$self->{"columns"};}
$self->{"columns"} @{$self->{"columns"};}
Truth table66%2/3
A and B
A= $self->{"columns"}B= @{$self->{"columns"};}
ABresult
0X0
100
111
520  
521 # _select_all_columns bypasses lazy_load filtering.
522 249 ▶ return 'main.*' if $self->{_select_all_columns};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_select_all_columns"} 1 248 249
523  
524 # Global flag: opt in to explicit column listing; default is main.*
525 248 ▶ return 'main.*' unless $PREFER_LAZY_LOAD;
Branch: 1 branch
BranchTrueFalseTotal
unless $DBIx::SearchBuilder::PREFER_LAZY_LOAD 245 3 248
526  
527 3 ▶ return $self->{_columns_for_query} if defined $self->{_columns_for_query};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_columns_for_query"} 1 2 3
528  
529 2 my $ca = $self->NewItem->_ClassAccessible;
530 2 ▶ unless ( $ca && %$ca ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ca and %$ca) 0 2 2
Condition33%1/3
$ca and %$ca
!ll&&!rl&&r
002
MC/DC0%0/2
$ca and %$ca
$ca %$ca
Truth table33%1/3
A and B
A= $caB= %$ca
ABresult
0X0
100
111
531 0 return ( $self->{_columns_for_query} = 'main.*' );
532 }
533  
534 my @cols = sort grep {
535 2 !$ca->{$_}{'foreign-collection'}
536 && !$ca->{$_}{'record-read'}
537 5 ▶ && !$ca->{$_}{'lazy_load'}
Condition50%3/6
$ca->{$_}{'foreign-collection'} || $ca->{$_}{'record-read'} || $ca->{$_}{'lazy_load'}
l!l&&r!l&&!r
023
$ca->{$_}{"foreign-collection"} or $ca->{$_}{"record-read"}
l!l&&r!l&&!r
005
MC/DC33%1/3
$ca->{$_}{'foreign-collection'} || $ca->{$_}{'record-read'} || $ca->{$_}{'lazy_load'}
$ca->{$_}{"foreign-collection"} $ca->{$_}{"record-read"} $ca->{$_}{'lazy_load'}
Truth table50%2/4
A or B || C
A= $ca->{$_}{"foreign-collection"}B= $ca->{$_}{"record-read"}C= $ca->{$_}{'lazy_load'}
ABCresult
1XX1
01X1
0011
0000
538 } keys %$ca;
539  
540 2 ▶ unless (@cols) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@cols) 0 2 2
541 0 return ( $self->{_columns_for_query} = 'main.*' );
542 }
543  
544 # Always include primary key columns so lazy-fetch can work later
545 2 my %in_cols = map { $_ => 1 } @cols;
546 2 push @cols, grep { !$in_cols{$_} } @{ $self->NewItem->_PrimaryKeys };
547  
548 2 return ( $self->{_columns_for_query} = join( ', ', map { "main.$_" } @cols ) );
549 }
550  
551 =head2 SelectAllColumns 1|0
552  
553 When set to true, forces selection of all columns (C<main.*>), bypassing any
554 C<lazy_load> filtering that would otherwise apply when
555 C<$DBIx::SearchBuilder::PREFER_LAZY_LOAD> is enabled. When set to false,
556 restores normal behaviour (C<main.*> by default, or C<lazy_load> filtering
557 if C<PREFER_LAZY_LOAD> is enabled).
558  
559 =cut
560  
561 1 ▶sub SelectAllColumns {
Subroutine SelectAllColumns: called CC=2 SCAR=7.0
Pod documented
562 1 my $self = shift;
563 1 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 1 0 1
564 1 $self->{_select_all_columns} = shift;
565 1 delete $self->{_columns_for_query};
566 }
567 1 return $self->{_select_all_columns};
568 }
569  
570 =head2 BuildSelectQuery PreferBind => 1|0
571  
572 Builds a query string for a "SELECT rows from Tables" statement for this
573 SearchBuilder object. Used internally and can also be handy for debugging.
574 Returns the query as a string.
575  
576 my $QueryString = $self->BuildSelectQuery();
577  
578 If C<PreferBind> is true, the generated query will use bind variables where
579 possible. If C<PreferBind> is not passed, it defaults to package variable
580 C<$DBIx::SearchBuilder::PREFER_BIND>, which defaults to
581 C<$ENV{SB_PREFER_BIND}>.
582  
583 To override global C<$DBIx::SearchBuilder::PREFER_BIND> for current object
584 only, you can also set C<_prefer_bind> accordingly, e.g.
585  
586 $sb->{_prefer_bind} = 1;
587  
588 =cut
589  
590 185 ▶sub BuildSelectQuery {
Subroutine BuildSelectQuery: called CC=5 SCAR=16.1
Pod documented
591 185 my $self = shift;
592  
593 # The initial SELECT or SELECT DISTINCT is decided later
594  
595 185 my $QueryString = $self->_BuildJoins . " ";
596 185 ▶ $QueryString .= $self->_WhereClause . " "
Branch: 1 branch
BranchTrueFalseTotal
if $self->_isLimited > 0 89 96 185
597 if ( $self->_isLimited > 0 );
598  
599 185 $self->_OptimizeQuery(\$QueryString, @_);
600  
601 185 my $QueryHint = $self->QueryHintFormatted;
602  
603 # DISTINCT query only required for multi-table selects
604 # when we have group by clause then the result set is distinct as
605 # it must contain only columns we group by or results of aggregate
606 # functions which give one result per group, so we can skip DISTINCTing
607 185 ▶ if ( my $clause = $self->_GroupClause ) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $clause = $self->_GroupClause) { } 5 180 185
elsif (not $self->{'joins_are_distinct'} and $self->_isJoined) { } 68 112 180
608 5 $QueryString = "SELECT" . $QueryHint . "main.* FROM $QueryString";
609 5 $QueryString .= $clause;
610 5 $QueryString .= $self->_OrderClause;
611 }
612 ▶ elsif ( !$self->{'joins_are_distinct'} && $self->_isJoined ) {
Condition100%3/3
not $self->{"joins_are_distinct"} and $self->_isJoined
!ll&&!rl&&r
410868
MC/DC100%2/2
not $self->{"joins_are_distinct"} and $self->_isJoined
not $self->{"joins_are_distinct"} $self->_isJoined
Truth table100%3/3
not(A) and B
A= not $self->{"joins_are_distinct"}B= $self->_isJoined
ABresult
0X0
100
111
613 68 $self->_DistinctQuery(\$QueryString);
614 }
615 else {
616 112 $QueryString = "SELECT" . $QueryHint . "main.* FROM $QueryString";
617 112 $QueryString .= $self->_OrderClause;
618 }
619  
620 185 $self->_ApplyLimits(\$QueryString);
621  
622 185 return($QueryString)
623  
624 }
625  
626  
627  
628 =head2 BuildSelectCountQuery PreferBind => 1|0
629  
630 Builds a SELECT statement to find the number of rows this SearchBuilder object would find.
631  
632 =cut
633  
634 83 ▶sub BuildSelectCountQuery {
Subroutine BuildSelectCountQuery: called CC=3 SCAR=11.0
Pod documented
635 83 my $self = shift;
636  
637 #TODO refactor DoSearch and DoCount such that we only have
638 # one place where we build most of the querystring
639 83 my $QueryString = $self->_BuildJoins . " ";
640  
641 83 ▶ $QueryString .= $self->_WhereClause . " "
Branch: 1 branch
BranchTrueFalseTotal
if $self->_isLimited > 0 72 11 83
642 if ( $self->_isLimited > 0 );
643  
644 83 $self->_OptimizeQuery(\$QueryString, @_);
645  
646 # DISTINCT query only required for multi-table selects
647 83 ▶ if ($self->_isJoined) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_isJoined) { } 41 42 83
648 41 $QueryString = $self->_Handle->DistinctCount(\$QueryString, $self);
649 } else {
650 42 my $QueryHint = $self->QueryHintFormatted;
651  
652 42 $QueryString = "SELECT" . $QueryHint . "count(main.id) FROM " . $QueryString;
653 }
654  
655 83 return ($QueryString);
656 }
657  
658 =head2 BuildSelectAndCountQuery PreferBind => 1|0
659  
660 Builds a query string that is a combination of BuildSelectQuery and
661 BuildSelectCountQuery.
662  
663 =cut
664  
665 46 ▶sub BuildSelectAndCountQuery {
Subroutine BuildSelectAndCountQuery: called CC=5 SCAR=16.6
Pod documented
666 46 my $self = shift;
667  
668 # Generally it's BuildSelectQuery plus extra COUNT part.
669 46 my $QueryString = $self->_BuildJoins . " ";
670 46 ▶ $QueryString .= $self->_WhereClause . " "
Branch: 1 branch
BranchTrueFalseTotal
if $self->_isLimited > 0 28 18 46
671 if ( $self->_isLimited > 0 );
672  
673 46 $self->_OptimizeQuery( \$QueryString, @_ );
674  
675 46 my $QueryHint = $self->QueryHintFormatted;
676  
677 46 ▶ if ( my $clause = $self->_GroupClause ) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $clause = $self->_GroupClause) { } 0 46 46
elsif (not $self->{'joins_are_distinct'} and $self->_isJoined) { } 43 3 46
678 0 $QueryString
679 = "SELECT" . $QueryHint . "main.*, COUNT(main.id) OVER() AS search_builder_count_all FROM $QueryString";
680 0 $QueryString .= $clause;
681 0 $QueryString .= $self->_OrderClause;
682 }
683 ▶ elsif ( !$self->{'joins_are_distinct'} && $self->_isJoined ) {
Condition66%2/3
not $self->{"joins_are_distinct"} and $self->_isJoined
!ll&&!rl&&r
0343
MC/DC50%1/2
not $self->{"joins_are_distinct"} and $self->_isJoined
not $self->{"joins_are_distinct"} $self->_isJoined
Truth table66%2/3
not(A) and B
A= not $self->{"joins_are_distinct"}B= $self->_isJoined
ABresult
0X0
100
111
684 43 $self->_DistinctQueryAndCount( \$QueryString );
685 }
686 else {
687 3 $QueryString
688 = "SELECT" . $QueryHint . "main.*, COUNT(main.id) OVER() AS search_builder_count_all FROM $QueryString";
689 3 $QueryString .= $self->_OrderClause;
690 }
691  
692 46 $self->_ApplyLimits( \$QueryString );
693 46 return ($QueryString);
694 }
695  
696  
697 =head2 Next
698  
699 Returns the next row from the set as an object of the type defined by sub NewItem.
700 When the complete set has been iterated through, returns undef and resets the search
701 such that the following call to Next will start over with the first item retrieved from the database.
702  
703 =cut
704  
705  
706  
707 1477 ▶sub Next {
Subroutine Next: called CC=4 SCAR=13.9
Pod documented
708 1477 my $self = shift;
709 1477 my @row;
710  
711 1477 ▶ return (undef) unless ( $self->_isLimited );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_isLimited 3 1474 1477
712  
713 1474 ▶ $self->_DoSearch() if $self->{'must_redo_search'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"must_redo_search"} 150 1324 1474
714  
715 1474 ▶ if ( $self->{'itemscount'} < $self->_RecordCount ) { #return the next item
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'itemscount'} < $self->_RecordCount) { } 1351 123 1474
716 1351 my $item = ( $self->{'items'}[ $self->{'itemscount'} ] );
717 1351 $self->{'itemscount'}++;
718 1351 return ($item);
719 }
720 else { #we've gone through the whole list. reset the count.
721 123 $self->GotoFirstItem();
722 123 return (undef);
723 }
724 }
725  
726  
727  
728 =head2 GotoFirstItem
729  
730 Starts the recordset counter over from the first item. The next time you call Next,
731 you'll get the first item returned by the database, as if you'd just started iterating
732 through the result set.
733  
734 =cut
735  
736  
737 212 ▶sub GotoFirstItem {
Subroutine GotoFirstItem: called CC=1 SCAR=0.0
Pod documented
738 212 my $self = shift;
739 212 $self->GotoItem(0);
740 }
741  
742  
743  
744  
745 =head2 GotoItem
746  
747 Takes an integer N and sets the record iterator to N. The first time L</Next>
748 is called afterwards, it will return the Nth item found by the search.
749  
750 You should only call GotoItem after you've already fetched at least one result
751 or otherwise forced the search query to run (such as via L</ItemsArrayRef>).
752 If GotoItem is called before the search query is ever run, it will reset the
753 item iterator and L</Next> will return the L</First> item.
754  
755 =cut
756  
757 216 ▶sub GotoItem {
Subroutine GotoItem: called CC=1 SCAR=0.0
Pod documented
758 216 my $self = shift;
759 216 my $item = shift;
760 216 $self->{'itemscount'} = $item;
761 }
762  
763  
764  
765 =head2 First
766  
767 Returns the first item
768  
769 =cut
770  
771 54 ▶sub First {
Subroutine First: called CC=1 SCAR=0.0
Pod documented
772 54 my $self = shift;
773 54 $self->GotoFirstItem();
774 54 return ( $self->Next );
775 }
776  
777  
778  
779 =head2 Last
780  
781 Returns the last item
782  
783 =cut
784  
785 4 ▶sub Last {
Subroutine Last: called CC=2 SCAR=6.9
Pod documented
786 4 my $self = shift;
787 4 ▶ $self->_DoSearch if $self->{'must_redo_search'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"must_redo_search"} 2 2 4
788 4 $self->GotoItem( ( $self->Count ) - 1 );
789 4 return ( $self->Next );
790 }
791  
792 =head2 DistinctFieldValues
793  
794 Returns list with distinct values of field. Limits on collection
795 are accounted, so collection should be L</UnLimit>ed to get values
796 from the whole table.
797  
798 Takes paramhash with the following keys:
799  
800 =over 4
801  
802 =item Field
803  
804 Field name. Can be first argument without key.
805  
806 =item Order
807  
808 'ASC', 'DESC' or undef. Defines whether results should
809 be sorted or not. By default results are not sorted.
810  
811 =item Max
812  
813 Maximum number of elements to fetch.
814  
815 =back
816  
817 =cut
818  
819 4 ▶sub DistinctFieldValues {
Subroutine DistinctFieldValues: called CC=6 SCAR=18.1
Pod documented
820 4 my $self = shift;
821 4 ▶ my %args = (
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 4 0 4
822 Field => undef,
823 Order => undef,
824 Max => undef,
825 @_%2 ? (Field => @_) : (@_)
826 );
827  
828 4 my $query_string = $self->_BuildJoins;
829 4 ▶ $query_string .= ' '. $self->_WhereClause
Branch: 1 branch
BranchTrueFalseTotal
if $self->_isLimited > 0 2 2 4
830 if $self->_isLimited > 0;
831  
832 4 my $query_hint = $self->QueryHintFormatted;
833  
834 4 my $column = 'main.'. $args{'Field'};
835 4 $query_string = "SELECT" . $query_hint . "DISTINCT $column FROM $query_string";
836  
837 4 ▶ if ( $args{'Order'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"Order"}) 4 0 4
838 $query_string .= ' ORDER BY '. $column
839 4 ▶ .' '. ($args{'Order'} =~ /^des/i ? 'DESC' : 'ASC');
Branch: 1 branch
BranchTrueFalseTotal
$args{'Order'} =~ /^des/i ? : 2 2 4
840 }
841  
842 4 my $dbh = $self->_Handle->dbh;
843 4 my $list = $dbh->selectcol_arrayref( $query_string, { MaxRows => $args{'Max'} } );
844 4 ▶ return $list? @$list : ();
Branch: 1 branch
BranchTrueFalseTotal
$list ? : 4 0 4
845 }
846  
847  
848  
849 =head2 ItemsArrayRef
850  
851 Return a reference to an array containing all objects found by this search.
852  
853 =cut
854  
855 54 ▶sub ItemsArrayRef {
Subroutine ItemsArrayRef: called CC=4 SCAR=13.9
Pod documented
856 54 my $self = shift;
857  
858 #If we're not limited, return an empty array
859 54 ▶ return [] unless $self->_isLimited;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_isLimited 1 53 54
860  
861 #Do a search if we need to.
862 53 ▶ $self->_DoSearch() if $self->{'must_redo_search'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"must_redo_search"} 48 5 53
863  
864 #If we've got any items in the array, return them.
865 # Otherwise, return an empty array
866 53 ▶ return ( $self->{'items'} || [] );
Condition50%1/2
$self->{'items'} || []
l!l
530
MC/DC0%0/1
$self->{'items'} || []
$self->{'items'}
Truth table50%1/2
A
A= $self->{'items'}
Aresult
11
00
867 }
868  
869  
870  
871  
872 =head2 NewItem
873  
874 NewItem must be subclassed. It is used by DBIx::SearchBuilder to create record
875 objects for each row returned from the database.
876  
877 =cut
878  
879 0 ▶sub NewItem {
Subroutine NewItem: not called CC=1 SCAR=6.9
Pod documented
880 0 my $self = shift;
881  
882 0 die
883 "DBIx::SearchBuilder needs to be subclassed. you can't use it directly.\n";
884 }
885  
886  
887  
888 =head2 RedoSearch
889  
890 Takes no arguments. Tells DBIx::SearchBuilder that the next time it's asked
891 for a record, it should requery the database
892  
893 =cut
894  
895 531 ▶sub RedoSearch {
Subroutine RedoSearch: called CC=1 SCAR=0.0
Pod documented
896 531 my $self = shift;
897 531 $self->{'must_redo_search'} = 1;
898 }
899  
900 =head2 CombineSearchAndCount 1|0
901  
902 Tells DBIx::SearchBuilder if it shall search both records and the total count
903 in a single query.
904  
905 =cut
906  
907 14 my $unsupported_combine_search_and_count_logged;
908 85 ▶sub CombineSearchAndCount {
Subroutine CombineSearchAndCount: called CC=5 SCAR=22.5
Pod documented
909 85 my $self = shift;
910 85 ▶ if ( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 85 0 85
911 85 ▶ if ( $self->_Handle->HasSupportForCombineSearchAndCount ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_Handle->HasSupportForCombineSearchAndCount) { } 85 0 85
912 85 $self->{'_combine_search_and_count'} = shift;
913 }
914 else {
915 0 ▶ warn "Current database version " . $self->_Handle->DatabaseVersion . " does not support CombineSearchAndCount. Consider upgrading to a newer version with support for windowing functions." unless $unsupported_combine_search_and_count_logged;
Branch: 1 branch
BranchTrueFalseTotal
unless $unsupported_combine_search_and_count_logged 0 0 0
916 0 ▶ $unsupported_combine_search_and_count_logged ||= 1;
Condition0%0/2
$unsupported_combine_search_and_count_logged ||= 1
l!l
00
MC/DC0%0/1
$unsupported_combine_search_and_count_logged ||= 1
$unsupported_combine_search_and_count_logged
Truth table0%0/2
A
A= $unsupported_combine_search_and_count_logged
Aresult
11
00
917 0 return undef;
918 }
919 }
920 85 return $self->{'_combine_search_and_count'};
921 }
922  
923  
924 =head2 UnLimit
925  
926 UnLimit clears all restrictions and causes this object to return all
927 rows in the primary table.
928  
929 =cut
930  
931 105 ▶sub UnLimit {
Subroutine UnLimit: called CC=1 SCAR=0.0
Pod documented
932 105 my $self = shift;
933 105 $self->_isLimited(-1);
934 }
935  
936  
937  
938 =head2 Limit
939  
940 Limit takes a hash of parameters with the following keys:
941  
942 =over 4
943  
944 =item TABLE
945  
946 Can be set to something different than this table if a join is
947 wanted (that means we can't do recursive joins as for now).
948  
949 =item ALIAS
950  
951 Unless ALIAS is set, the join criterias will be taken from EXT_LINKFIELD
952 and INT_LINKFIELD and added to the criterias. If ALIAS is set, new
953 criterias about the foreign table will be added.
954  
955 =item LEFTJOIN
956  
957 To apply the Limit inside the ON clause of a previously created left
958 join, pass this option along with the alias returned from creating
959 the left join. ( This is similar to using the EXPRESSION option when
960 creating a left join but this allows you to refer to the join alias
961 in the expression. )
962  
963 =item FIELD
964  
965 Column to be checked against.
966  
967 =item FUNCTION
968  
969 Function that should be checked against or applied to the FIELD before
970 check. See L</CombineFunctionWithField> for rules.
971  
972 =item VALUE
973  
974 Should always be set and will always be quoted.
975  
976 =item OPERATOR
977  
978 OPERATOR is the SQL operator to use for this phrase. Possible choices include:
979  
980 =over 4
981  
982 =item "="
983  
984 =item "!="
985  
986 =item "LIKE"
987  
988 In the case of LIKE, the string is surrounded in % signs. Yes. this is a bug.
989  
990 =item "NOT LIKE"
991  
992 =item "STARTSWITH"
993  
994 STARTSWITH is like LIKE, except it only appends a % at the end of the string
995  
996 =item "ENDSWITH"
997  
998 ENDSWITH is like LIKE, except it prepends a % to the beginning of the string
999  
1000 =item "MATCHES"
1001  
1002 MATCHES is equivalent to the database's LIKE -- that is, it's actually LIKE, but
1003 doesn't surround the string in % signs as LIKE does.
1004  
1005 =item "IN" and "NOT IN"
1006  
1007 VALUE can be an array reference or an object inherited from this class. If
1008 it's not then it's treated as any other operator and in most cases SQL would
1009 be wrong. Values in array are considered as constants and quoted according
1010 to QUOTEVALUE.
1011  
1012 If object is passed as VALUE then its select statement is used. If no L</Column>
1013 is selected then C<id> is used, if more than one selected then warning is issued
1014 and first column is used.
1015  
1016 =back
1017  
1018 =item ENTRYAGGREGATOR
1019  
1020 Can be C<AND> or C<OR> (or anything else valid to aggregate two clauses in SQL).
1021 Special value is C<none> which means that no entry aggregator should be used.
1022 The default value is C<OR>.
1023  
1024 =item CASESENSITIVE
1025  
1026 on some databases, such as postgres, setting CASESENSITIVE to 1 will make
1027 this search case sensitive
1028  
1029 =item SUBCLAUSE
1030  
1031 Subclause allows you to assign tags to Limit statements. Statements with
1032 matching SUBCLAUSE tags will be grouped together in the final SQL statement.
1033  
1034 Example:
1035  
1036 Suppose you want to create Limit statements which would produce results
1037 the same as the following SQL:
1038  
1039 SELECT * FROM Users WHERE EmailAddress OR Name OR RealName OR Email LIKE $query;
1040  
1041 You would use the following Limit statements:
1042  
1043 $folks->Limit( FIELD => 'EmailAddress', OPERATOR => 'LIKE', VALUE => "$query", SUBCLAUSE => 'groupsearch');
1044 $folks->Limit( FIELD => 'Name', OPERATOR => 'LIKE', VALUE => "$query", SUBCLAUSE => 'groupsearch');
1045 $folks->Limit( FIELD => 'RealName', OPERATOR => 'LIKE', VALUE => "$query", SUBCLAUSE => 'groupsearch');
1046  
1047 =back
1048  
1049 =cut
1050  
1051 116 ▶sub Limit {
Subroutine Limit: called CC=18 SCAR=29.9
Pod documented
1052 116 my $self = shift;
1053 116 my %args = (
1054 TABLE => $self->Table,
1055 ALIAS => undef,
1056 FIELD => undef,
1057 FUNCTION => undef,
1058 VALUE => undef,
1059 QUOTEVALUE => 1,
1060 ENTRYAGGREGATOR => undef,
1061 CASESENSITIVE => undef,
1062 OPERATOR => '=',
1063 SUBCLAUSE => undef,
1064 LEFTJOIN => undef,
1065 @_ # get the real argumentlist
1066 );
1067  
1068 116 ▶ unless ( $args{'ENTRYAGGREGATOR'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"ENTRYAGGREGATOR"}) 115 1 116
1069 115 ▶ if ( $args{'LEFTJOIN'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'LEFTJOIN'}) { } 2 113 115
1070 2 $args{'ENTRYAGGREGATOR'} = 'AND';
1071 } else {
1072 113 $args{'ENTRYAGGREGATOR'} = 'OR';
1073 }
1074 }
1075  
1076  
1077 #since we're changing the search criteria, we need to redo the search
1078 116 $self->RedoSearch();
1079  
1080 116 ▶ if ( $args{'OPERATOR'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"OPERATOR"}) 116 0 116
1081 #If it's a like, we supply the %s around the search term
1082 116 ▶ if ( $args{'OPERATOR'} =~ /LIKE/i ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($args{'OPERATOR'} =~ /LIKE/i) { } 8 108 116
elsif ($args{'OPERATOR'} =~ /STARTSWITH/i) { } 1 107 108
elsif ($args{'OPERATOR'} =~ /ENDSWITH/i) { } 1 106 107
elsif ($args{'OPERATOR'} =~ /\bIN$/i) { } 58 48 106
1083 8 $args{'VALUE'} = "%" . $args{'VALUE'} . "%";
1084 }
1085 elsif ( $args{'OPERATOR'} =~ /STARTSWITH/i ) {
1086 1 $args{'VALUE'} = $args{'VALUE'} . "%";
1087 }
1088 elsif ( $args{'OPERATOR'} =~ /ENDSWITH/i ) {
1089 1 $args{'VALUE'} = "%" . $args{'VALUE'};
1090 }
1091 elsif ( $args{'OPERATOR'} =~ /\bIN$/i ) {
1092 58 ▶ if ( blessed $args{'VALUE'} && $args{'VALUE'}->isa(__PACKAGE__) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($args{'VALUE'}) and $args{'VALUE'}->isa(__PACKAGE__)) { } 3 55 58
elsif (ref $args{'VALUE'}) { } 55 0 55
Condition66%2/3
builtin::blessed($args{"VALUE"}) and $args{"VALUE"}->isa(__PACKAGE__)
!ll&&!rl&&r
5503
MC/DC50%1/2
builtin::blessed($args{"VALUE"}) and $args{"VALUE"}->isa(__PACKAGE__)
builtin::blessed($args{"VALUE"}) $args{"VALUE"}->isa(__PACKAGE__)
Truth table66%2/3
A and B
A= builtin::blessed($args{"VALUE"})B= $args{"VALUE"}->isa(__PACKAGE__)
ABresult
0X0
100
111
1093 # if no columns selected then select id
1094 3 local $args{'VALUE'}{'columns'} = $args{'VALUE'}{'columns'};
1095 3 ▶ unless ( $args{'VALUE'}{'columns'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'VALUE'}{'columns'}) { } 1 2 3
if (do { @{$args{"VALUE"}{"columns"};} > 1 }) 0 1 1
1096 2 $args{'VALUE'}->Column( FIELD => 'id' );
1097 0 } elsif ( @{ $args{'VALUE'}{'columns'} } > 1 ) {
1098 0 warn "Collection in '$args{OPERATOR}' with more than one column selected, using first";
1099 0 splice @{ $args{'VALUE'}{'columns'} }, 1;
1100 }
1101 3 $args{'VALUE'} = '('. $args{'VALUE'}->BuildSelectQuery(PreferBind => 0) .')';
1102 3 $args{'QUOTEVALUE'} = 0;
1103 }
1104 elsif ( ref $args{'VALUE'} ) {
1105 55 ▶ if ( $args{'QUOTEVALUE'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'QUOTEVALUE'}) { } 55 0 55
1106 55 my $dbh = $self->_Handle->dbh;
1107 55 $args{'VALUE'} = join ', ', map $dbh->quote( $_ ), @{ $args{'VALUE'} };
1108 } else {
1109 0 $args{'VALUE'} = join ', ', @{ $args{'VALUE'} };
1110 }
1111 55 $args{'VALUE'} = "($args{VALUE})";
1112 55 $args{'QUOTEVALUE'} = 0;
1113 }
1114 else {
1115 # otherwise behave in backwards compatible way
1116 }
1117 }
1118 116 $args{'OPERATOR'} =~ s/(?:MATCHES|ENDSWITH|STARTSWITH)/LIKE/i;
1119  
1120 116 ▶ if ( $args{'OPERATOR'} =~ /IS/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"OPERATOR"} =~ /IS/i) 11 105 116
1121 11 $args{'VALUE'} = 'NULL';
1122 11 $args{'QUOTEVALUE'} = 0;
1123 }
1124 }
1125  
1126 116 ▶ if ( $args{'QUOTEVALUE'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"QUOTEVALUE"}) 45 71 116
1127 #if we're explicitly told not to to quote the value or
1128 # we're doing an IS or IS NOT (null), don't quote the operator.
1129  
1130 45 $args{'VALUE'} = $self->_Handle->dbh->quote( $args{'VALUE'} );
1131 }
1132  
1133 116 my $Alias = $self->_GenericRestriction(%args);
1134  
1135 116 ▶ warn "No table alias set!"
Branch: 1 branch
BranchTrueFalseTotal
unless $Alias 0 116 116
1136 unless $Alias;
1137  
1138 # We're now limited. people can do searches.
1139  
1140 116 $self->_isLimited(1);
1141  
1142 116 ▶ if ( defined($Alias) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Alias) { } 116 0 116
1143 116 return ($Alias);
1144 }
1145 else {
1146 0 return (1);
1147 }
1148 }
1149  
1150  
1151  
1152 116 ▶sub _GenericRestriction {
Subroutine _GenericRestriction: called CC=22 SCAR=32.7
1153 116 my $self = shift;
1154 116 my %args = ( TABLE => $self->Table,
1155 FIELD => undef,
1156 FUNCTION => undef,
1157 VALUE => undef,
1158 ALIAS => undef,
1159 LEFTJOIN => undef,
1160 ENTRYAGGREGATOR => undef,
1161 OPERATOR => '=',
1162 SUBCLAUSE => undef,
1163 CASESENSITIVE => undef,
1164 QUOTEVALUE => undef,
1165 @_ );
1166  
1167 #TODO: $args{'VALUE'} should take an array of values and generate
1168 # the proper where clause.
1169  
1170 #If we're performing a left join, we really want the alias to be the
1171 #left join criterion.
1172  
1173 116 ▶ if ( defined $args{'LEFTJOIN'} && !defined $args{'ALIAS'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"LEFTJOIN"} and not defined $args{"ALIAS"}) 2 114 116
Condition66%2/3
defined $args{"LEFTJOIN"} and not defined $args{"ALIAS"}
!ll&&!rl&&r
11402
MC/DC50%1/2
defined $args{"LEFTJOIN"} and not defined $args{"ALIAS"}
defined $args{"LEFTJOIN"} not defined $args{"ALIAS"}
Truth table66%2/3
A and not(B)
A= defined $args{"LEFTJOIN"}B= not defined $args{"ALIAS"}
ABresult
0X0
100
111
1174 2 $args{'ALIAS'} = $args{'LEFTJOIN'};
1175 }
1176  
1177 # if there's no alias set, we need to set it
1178  
1179 116 ▶ unless ( $args{'ALIAS'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"ALIAS"}) 50 66 116
1180  
1181 #if the table we're looking at is the same as the main table
1182 50 ▶ if ( $args{'TABLE'} eq $self->Table ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'TABLE'} eq $self->Table) { } 50 0 50
1183  
1184 # TODO this code assumes no self joins on that table.
1185 # if someone can name a case where we'd want to do that,
1186 # I'll change it.
1187  
1188 50 $args{'ALIAS'} = 'main';
1189 }
1190  
1191 # if we're joining, we need to work out the table alias
1192 else {
1193 0 $args{'ALIAS'} = $self->NewAlias( $args{'TABLE'} );
1194 }
1195 }
1196  
1197 # Set this to the name of the field and the alias, unless we've been
1198 # handed a subclause name
1199  
1200 116 ▶ my $ClauseId = $args{'SUBCLAUSE'} || ($args{'ALIAS'} . "." . $args{'FIELD'});
Condition100%2/2
$args{'SUBCLAUSE'} || $args{'ALIAS'} . '.' . $args{'FIELD'}
l!l
2114
MC/DC100%1/1
$args{'SUBCLAUSE'} || $args{'ALIAS'} . '.' . $args{'FIELD'}
$args{'SUBCLAUSE'}
Truth table100%2/2
A
A= $args{'SUBCLAUSE'}
Aresult
11
00
1201  
1202 # If we're trying to get a leftjoin restriction, let's set
1203 # $restriction to point there. Otherwise, let's construct normally.
1204  
1205 116 my $restriction;
1206 116 ▶ if ( $args{'LEFTJOIN'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'LEFTJOIN'}) { } 2 114 116
1207 2 ▶ if ( $args{'ENTRYAGGREGATOR'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"ENTRYAGGREGATOR"}) 2 0 2
1208 $self->{'left_joins'}{ $args{'LEFTJOIN'} }{'entry_aggregator'} =
1209 2 $args{'ENTRYAGGREGATOR'};
1210 }
1211 2 ▶ $restriction = $self->{'left_joins'}{ $args{'LEFTJOIN'} }{'criteria'}{ $ClauseId } ||= [];
Condition50%1/2
$self->{"left_joins"}{$args{"LEFTJOIN"}}{"criteria"}{$ClauseId} ||= []
l!l
02
MC/DC0%0/1
$self->{"left_joins"}{$args{"LEFTJOIN"}}{"criteria"}{$ClauseId} ||= []
$self->{"left_joins"}{$args{"LEFTJOIN"}}{"criteria"}{$ClauseId}
Truth table50%1/2
A
A= $self->{"left_joins"}{$args{"LEFTJOIN"}}{"criteria"}{$ClauseId}
Aresult
11
00
1212 }
1213 else {
1214 114 ▶ $restriction = $self->{'restrictions'}{ $ClauseId } ||= [];
Condition100%2/2
$self->{"restrictions"}{$ClauseId} ||= []
l!l
4110
MC/DC100%1/1
$self->{"restrictions"}{$ClauseId} ||= []
$self->{"restrictions"}{$ClauseId}
Truth table100%2/2
A
A= $self->{"restrictions"}{$ClauseId}
Aresult
11
00
1215 }
1216  
1217 116 my $QualifiedField = $self->CombineFunctionWithField( %args );
1218  
1219 # If it's a new value or we're overwriting this sort of restriction,
1220  
1221 116 ▶ if ( $self->_Handle->CaseSensitive && defined $args{'VALUE'} && $args{'VALUE'} ne '' && $args{'VALUE'} ne "''" && ($args{'OPERATOR'} !~/IS/ && $args{'VALUE'} !~ /^null$/i)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_Handle->CaseSensitive and defined $args{"VALUE"} and $args{"VALUE"} ne "" and $args{"VALUE"} ne "''" and not $args{"OPERATOR"} =~ /IS/ || $args{"VALUE"} =~ /^null$/i) 105 11 116
Condition46%7/15
$self->_Handle->CaseSensitive and defined $args{"VALUE"} and $args{"VALUE"} ne "" and $args{"VALUE"} ne "''" and not $args{"OPERATOR"} =~ /IS/ || $args{"VALUE"} =~ /^null$/i
!ll&&!rl&&r
011105
$self->_Handle->CaseSensitive and defined $args{"VALUE"} and $args{"VALUE"} ne "" and $args{"VALUE"} ne "''"
!ll&&!rl&&r
00116
$self->_Handle->CaseSensitive and defined $args{"VALUE"} and $args{"VALUE"} ne ""
!ll&&!rl&&r
00116
$self->_Handle->CaseSensitive and defined $args{"VALUE"}
!ll&&!rl&&r
00116
$args{'OPERATOR'} =~ /IS/ || $args{'VALUE'} =~ /^null$/i
l!l&&r!l&&!r
110105
MC/DC16%1/6
$self->_Handle->CaseSensitive and defined $args{"VALUE"} and $args{"VALUE"} ne "" and $args{"VALUE"} ne "''" and not $args{"OPERATOR"} =~ /IS/ || $args{"VALUE"} =~ /^null$/i
$self->_Handle->CaseSensitive defined $args{"VALUE"} $args{"VALUE"} ne "" $args{"VALUE"} ne "''" $args{'OPERATOR'} =~ /IS/ $args{'VALUE'} =~ /^null$/i
Truth table28%2/7
A and B and C and D and not(E || F)
A= $self->_Handle->CaseSensitiveB= defined $args{"VALUE"}C= $args{"VALUE"} ne ""D= $args{"VALUE"} ne "''"E= $args{'OPERATOR'} =~ /IS/F= $args{'VALUE'} =~ /^null$/i
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11111X0
1111010
1111001
1222  
1223 105 ▶ unless ( $args{'CASESENSITIVE'} || !$args{'QUOTEVALUE'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"CASESENSITIVE"} or not $args{"QUOTEVALUE"}) 45 60 105
Condition66%2/3
$args{"CASESENSITIVE"} or not $args{"QUOTEVALUE"}
l!l&&r!l&&!r
06045
MC/DC50%1/2
$args{"CASESENSITIVE"} or not $args{"QUOTEVALUE"}
$args{"CASESENSITIVE"} not $args{"QUOTEVALUE"}
Truth table66%2/3
A or not(B)
A= $args{"CASESENSITIVE"}B= not $args{"QUOTEVALUE"}
ABresult
1X1
011
000
1224 ( $QualifiedField, $args{'OPERATOR'}, $args{'VALUE'} ) =
1225 $self->_Handle->_MakeClauseCaseInsensitive( $QualifiedField,
1226 45 $args{'OPERATOR'}, $args{'VALUE'} );
1227 }
1228  
1229 }
1230  
1231 my $clause = {
1232 field => $QualifiedField,
1233 op => $args{'OPERATOR'},
1234 116 value => $args{'VALUE'},
1235 };
1236  
1237 # Juju because this should come _AFTER_ the EA
1238 116 my @prefix;
1239 116 ▶ if ( $self->{_open_parens}{ $ClauseId } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_open_parens"}{$ClauseId}) 1 115 116
1240 1 @prefix = ('(') x delete $self->{_open_parens}{ $ClauseId };
1241 }
1242  
1243 116 ▶ if ( lc( $args{'ENTRYAGGREGATOR'} || "" ) eq 'none' || !@$restriction ) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc($args{'ENTRYAGGREGATOR'} || '') eq 'none' or not @$restriction) { } 112 4 116
Condition60%3/5
lc($args{"ENTRYAGGREGATOR"} || "") eq "none" or not @$restriction
l!l&&r!l&&!r
01124
$args{'ENTRYAGGREGATOR'} || ''
l!l
1160
MC/DC0%0/2
lc($args{"ENTRYAGGREGATOR"} || "") eq "none" or not @$restriction
$args{'ENTRYAGGREGATOR'} not @$restriction
Truth table0%0/3
A or not(B)
A= $args{'ENTRYAGGREGATOR'}B= not @$restriction
ABresult
1X1
011
000
1244 112 @$restriction = (@prefix, $clause);
1245 }
1246 else {
1247 4 push @$restriction, $args{'ENTRYAGGREGATOR'}, @prefix, $clause;
1248 }
1249  
1250 116 return ( $args{'ALIAS'} );
1251  
1252 }
1253  
1254  
1255 1 ▶sub _OpenParen {
Subroutine _OpenParen: called CC=1 SCAR=0.0
1256 1 my ($self, $clause) = @_;
1257 1 $self->{_open_parens}{ $clause }++;
1258 }
1259  
1260 # Immediate Action
1261 1 ▶sub _CloseParen {
Subroutine _CloseParen: called CC=2 SCAR=7.1
1262 1 my ( $self, $clause ) = @_;
1263 1 ▶ my $restriction = ($self->{'restrictions'}{ $clause } ||= []);
Condition50%1/2
$self->{"restrictions"}{$clause} ||= []
l!l
10
MC/DC0%0/1
$self->{"restrictions"}{$clause} ||= []
$self->{"restrictions"}{$clause}
Truth table50%1/2
A
A= $self->{"restrictions"}{$clause}
Aresult
11
00
1264 1 push @$restriction, ')';
1265 }
1266  
1267  
1268 0 ▶sub _AddSubClause {
Subroutine _AddSubClause: not called CC=1 SCAR=6.9
1269 0 my $self = shift;
1270 0 my $clauseid = shift;
1271 0 my $subclause = shift;
1272  
1273 0 $self->{'subclauses'}{ $clauseid } = $subclause;
1274  
1275 }
1276  
1277  
1278  
1279 191 ▶sub _WhereClause {
Subroutine _WhereClause: called CC=4 SCAR=13.9
1280 191 my $self = shift;
1281  
1282 #Go through all the generic restrictions and build up the "generic_restrictions" subclause
1283 # That's the only one that SearchBuilder builds itself.
1284 # Arguably, the abstraction should be better, but I don't really see where to put it.
1285 191 $self->_CompileGenericRestrictions();
1286  
1287 #Go through all restriction types. Build the where clause from the
1288 #Various subclauses.
1289 191 my $where_clause = '';
1290 191 foreach my $subclause ( grep $_, sorted_values($self->{'subclauses'}) ) {
1291 182 ▶ $where_clause .= " AND " if $where_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $where_clause 0 182 182
1292 182 $where_clause .= $subclause;
1293 }
1294  
1295 191 ▶ $where_clause = " WHERE " . $where_clause if $where_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $where_clause 182 9 191
1296  
1297 191 return ($where_clause);
1298 }
1299  
1300  
1301 #Compile the restrictions to a WHERE Clause
1302  
1303 191 ▶sub _CompileGenericRestrictions {
Subroutine _CompileGenericRestrictions: called CC=5 SCAR=16.1
1304 191 my $self = shift;
1305  
1306 191 my $result = '';
1307 #Go through all the restrictions of this type. Buld up the generic subclause
1308 191 foreach my $restriction ( grep @$_, sorted_values($self->{'restrictions'}) ) {
1309 201 ▶ $result .= " AND " if $result;
Branch: 1 branch
BranchTrueFalseTotal
if $result 19 182 201
1310 201 $result .= '(';
1311 201 foreach my $entry ( @$restriction ) {
1312 217 ▶ unless ( ref $entry ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $entry) { } 207 10 217
1313 10 $result .= ' '. $entry . ' ';
1314 }
1315 else {
1316 207 $result .= join ' ', @{$entry}{qw(field op value)};
1317 }
1318 }
1319 201 $result .= ')';
1320 }
1321 191 return ($self->{'subclauses'}{'generic_restrictions'} = $result);
1322 }
1323  
1324  
1325 =head2 OrderBy PARAMHASH
1326  
1327 Orders the returned results by ALIAS.FIELD ORDER.
1328  
1329 Takes a paramhash of ALIAS, FIELD and ORDER.
1330 ALIAS defaults to C<main>.
1331 FIELD has no default value.
1332 ORDER defaults to ASC(ending). DESC(ending) is also a valid value for OrderBy.
1333  
1334 FIELD also accepts C<FUNCTION(FIELD)> format.
1335  
1336 =cut
1337  
1338 89 ▶sub OrderBy {
Subroutine OrderBy: called CC=1 SCAR=0.0
Pod documented
1339 89 my $self = shift;
1340 89 $self->OrderByCols( { @_ } );
1341 }
1342  
1343 =head2 OrderByCols ARRAY
1344  
1345 OrderByCols takes an array of paramhashes of the form passed to OrderBy.
1346 The result set is ordered by the items in the array.
1347  
1348 =cut
1349  
1350 116 ▶sub OrderByCols {
Subroutine OrderByCols: called CC=2 SCAR=6.9
Pod documented
1351 116 my $self = shift;
1352 116 my @args = @_;
1353  
1354 116 my $old_value = $self->_OrderClause;
1355 116 $self->{'order_by'} = \@args;
1356  
1357 116 ▶ if ( $self->_OrderClause ne $old_value ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_OrderClause ne $old_value) 115 1 116
1358 115 $self->RedoSearch();
1359 }
1360 }
1361  
1362 =head2 _OrderClause
1363  
1364 returns the ORDER BY clause for the search.
1365  
1366 =cut
1367  
1368 617 ▶sub _OrderClause {
Subroutine _OrderClause: called CC=16 SCAR=28.6
1369 617 my $self = shift;
1370  
1371 617 ▶ return '' unless $self->{'order_by'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"order_by"} 221 396 617
1372  
1373 396 my $nulls_order = $self->_Handle->NullsOrder;
1374  
1375 396 my $clause = '';
1376 396 foreach my $row ( @{$self->{'order_by'}} ) {
1377  
1378 455 my %rowhash = ( ALIAS => 'main',
1379 FIELD => undef,
1380 ORDER => 'ASC',
1381 %$row
1382 );
1383 455 ▶ if ($rowhash{'ORDER'} && $rowhash{'ORDER'} =~ /^des/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rowhash{'ORDER'} and $rowhash{'ORDER'} =~ /^des/i) { } 195 260 455
Condition66%2/3
$rowhash{"ORDER"} and $rowhash{"ORDER"} =~ /^des/i
!ll&&!rl&&r
0260195
MC/DC50%1/2
$rowhash{"ORDER"} and $rowhash{"ORDER"} =~ /^des/i
$rowhash{"ORDER"} $rowhash{"ORDER"} =~ /^des/i
Truth table66%2/3
A and B
A= $rowhash{"ORDER"}B= $rowhash{"ORDER"} =~ /^des/i
ABresult
0X0
100
111
1384 195 $rowhash{'ORDER'} = "DESC";
1385 195 ▶ $rowhash{'ORDER'} .= ' '. $nulls_order->{'DESC'} if $nulls_order;
Branch: 1 branch
BranchTrueFalseTotal
if $nulls_order 0 195 195
1386 }
1387 else {
1388 260 $rowhash{'ORDER'} = "ASC";
1389 260 ▶ $rowhash{'ORDER'} .= ' '. $nulls_order->{'ASC'} if $nulls_order;
Branch: 1 branch
BranchTrueFalseTotal
if $nulls_order 0 260 260
1390 }
1391 455 ▶ $rowhash{'ALIAS'} = 'main' unless defined $rowhash{'ALIAS'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rowhash{"ALIAS"} 0 455 455
1392  
1393 455 ▶ if ( defined $rowhash{'ALIAS'} and
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rowhash{"ALIAS"} and $rowhash{"FIELD"} and $rowhash{"ORDER"}) 455 0 455
Condition33%2/6
defined $rowhash{"ALIAS"} and $rowhash{"FIELD"} and $rowhash{"ORDER"}
!ll&&!rl&&r
00455
defined $rowhash{"ALIAS"} and $rowhash{"FIELD"}
!ll&&!rl&&r
00455
MC/DC0%0/3
defined $rowhash{"ALIAS"} and $rowhash{"FIELD"} and $rowhash{"ORDER"}
defined $rowhash{"ALIAS"} $rowhash{"FIELD"} $rowhash{"ORDER"}
Truth table25%1/4
A and B and C
A= defined $rowhash{"ALIAS"}B= $rowhash{"FIELD"}C= $rowhash{"ORDER"}
ABCresult
0XX0
10X0
1100
1111
1394 $rowhash{'FIELD'} and
1395 $rowhash{'ORDER'} ) {
1396  
1397 455 ▶ if ( length $rowhash{'ALIAS'} && $rowhash{'FIELD'} =~ /^(.*\()(.*\))$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $rowhash{"ALIAS"} and $rowhash{"FIELD"} =~ /^(.*\()(.*\))$/) 95 360 455
Condition100%3/3
length $rowhash{"ALIAS"} and $rowhash{"FIELD"} =~ /^(.*\()(.*\))$/
!ll&&!rl&&r
1834295
MC/DC100%2/2
length $rowhash{"ALIAS"} and $rowhash{"FIELD"} =~ /^(.*\()(.*\))$/
length $rowhash{"ALIAS"} $rowhash{"FIELD"} =~ /^(.*\()(.*\))$/
Truth table100%3/3
A and B
A= length $rowhash{"ALIAS"}B= $rowhash{"FIELD"} =~ /^(.*\()(.*\))$/
ABresult
0X0
100
111
1398 # handle 'FUNCTION(FIELD)' formatted fields
1399 95 $rowhash{'ALIAS'} = $1 . $rowhash{'ALIAS'};
1400 95 $rowhash{'FIELD'} = $2;
1401 }
1402  
1403 455 ▶ $clause .= ($clause ? ", " : " ");
Branch: 1 branch
BranchTrueFalseTotal
$clause ? : 59 396 455
1404 455 ▶ $clause .= $rowhash{'ALIAS'} . "." if length $rowhash{'ALIAS'};
Branch: 1 branch
BranchTrueFalseTotal
if length $rowhash{"ALIAS"} 437 18 455
1405 455 $clause .= $rowhash{'FIELD'} . " ";
1406 455 $clause .= $rowhash{'ORDER'};
1407 }
1408 }
1409 396 ▶ $clause = " ORDER BY$clause " if $clause;
Branch: 1 branch
BranchTrueFalseTotal
if $clause 396 0 396
1410  
1411 396 return $clause;
1412 }
1413  
1414 =head2 GroupByCols ARRAY_OF_HASHES
1415  
1416 Each hash contains the keys FIELD, FUNCTION and ALIAS. Hash
1417 combined into SQL with L</CombineFunctionWithField>.
1418  
1419 =cut
1420  
1421 5 ▶sub GroupByCols {
Subroutine GroupByCols: called CC=2 SCAR=7.0
Pod documented
1422 5 my $self = shift;
1423 5 my @args = @_;
1424  
1425 5 my $old_value = $self->_GroupClause;
1426 5 $self->{'group_by'} = \@args;
1427  
1428 5 ▶ if ( $self->_GroupClause ne $old_value ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_GroupClause ne $old_value) 5 0 5
1429 5 $self->RedoSearch();
1430 }
1431 }
1432  
1433 =head2 _GroupClause
1434  
1435 Private function to return the "GROUP BY" clause for this query.
1436  
1437 =cut
1438  
1439 352 ▶sub _GroupClause {
Subroutine _GroupClause: called CC=6 SCAR=18.2
1440 352 my $self = shift;
1441 352 ▶ return '' unless $self->{'group_by'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"group_by"} 304 48 352
1442  
1443 48 my $clause = '';
1444 48 foreach my $row ( @{$self->{'group_by'}} ) {
1445 48 ▶ my $part = $self->CombineFunctionWithField( %$row )
Branch: 1 branch
BranchTrueFalseTotal
my $part = $self->CombineFunctionWithField(%$row) or next 48 0 48
1446 or next;
1447  
1448 48 ▶ $clause .= ', ' if $clause;
Branch: 1 branch
BranchTrueFalseTotal
if $clause 0 48 48
1449 48 $clause .= $part;
1450 }
1451  
1452 48 ▶ return '' unless $clause;
Branch: 1 branch
BranchTrueFalseTotal
unless $clause 0 48 48
1453 48 return " GROUP BY $clause ";
1454 }
1455  
1456 =head2 NewAlias
1457  
1458 Takes the name of a table and paramhash with TYPE and DISTINCT.
1459  
1460 Use TYPE equal to C<LEFT> to indicate that it's LEFT JOIN. Old
1461 style way to call (see below) is also supported, but should be
1462 B<avoided>:
1463  
1464 $records->NewAlias('aTable', 'left');
1465  
1466 True DISTINCT value indicates that this join keeps result set
1467 distinct and DB side distinct is not required. See also L</Join>.
1468  
1469 Returns the string of a new Alias for that table, which can be used to Join tables
1470 or to Limit what gets found by a search.
1471  
1472 =cut
1473  
1474 6 ▶sub NewAlias {
Subroutine NewAlias: called CC=10 SCAR=28.1
Pod documented
1475 6 my $self = shift;
1476 6 ▶ my $table = shift || die "Missing parameter";
Condition50%1/2
shift() || die('Missing parameter')
l!l
60
MC/DC0%0/1
shift() || die('Missing parameter')
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
1477 6 ▶ my %args = @_%2? (TYPE => @_) : (@_);
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 6 6
1478  
1479 6 my $type = $args{'TYPE'};
1480  
1481 6 my $alias = $self->_GetAlias($table);
1482  
1483 6 ▶ $table = $self->_Handle->QuoteName($table) if $self->_Handle->QuoteTableNames;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_Handle->QuoteTableNames 0 6 6
1484 6 ▶ unless ( $type ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type) { } 0 6 6
if (do { lc $type eq 'left' }) { } 0 0 0
1485 6 push @{ $self->{'aliases'} }, "$table $alias";
1486 } elsif ( lc $type eq 'left' ) {
1487 0 ▶ my $meta = $self->{'left_joins'}{"$alias"} ||= {};
Condition0%0/2
$self->{"left_joins"}{"$alias"} ||= {}
l!l
00
MC/DC0%0/1
$self->{"left_joins"}{"$alias"} ||= {}
$self->{"left_joins"}{"$alias"}
Truth table0%0/2
A
A= $self->{"left_joins"}{"$alias"}
Aresult
11
00
1488 0 $meta->{'alias_string'} = " LEFT JOIN $table $alias ";
1489 0 $meta->{'type'} = 'LEFT';
1490 0 $meta->{'depends_on'} = '';
1491 } else {
1492 0 die "Unsupported alias(join) type";
1493 }
1494  
1495 6 ▶ if ( $args{'DISTINCT'} && !defined $self->{'joins_are_distinct'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'DISTINCT'} and not defined $self->{'joins_are_distinct'}) { } 1 5 6
elsif (not $args{'DISTINCT'}) { } 5 0 5
Condition66%2/3
$args{"DISTINCT"} and not defined $self->{"joins_are_distinct"}
!ll&&!rl&&r
501
MC/DC50%1/2
$args{"DISTINCT"} and not defined $self->{"joins_are_distinct"}
$args{"DISTINCT"} not defined $self->{"joins_are_distinct"}
Truth table66%2/3
A and not(B)
A= $args{"DISTINCT"}B= not defined $self->{"joins_are_distinct"}
ABresult
0X0
100
111
1496 1 $self->{'joins_are_distinct'} = 1;
1497 } elsif ( !$args{'DISTINCT'} ) {
1498 5 $self->{'joins_are_distinct'} = 0;
1499 }
1500  
1501 6 return $alias;
1502 }
1503  
1504  
1505  
1506 # _GetAlias is a private function which takes an tablename and
1507 # returns a new alias for that table without adding something
1508 # to self->{'aliases'}. This function is used by NewAlias
1509 # and the as-yet-unnamed left join code
1510  
1511 121 ▶sub _GetAlias {
Subroutine _GetAlias: called CC=1 SCAR=0.0
1512 121 my $self = shift;
1513 121 my $table = shift;
1514  
1515 121 $self->{'alias_count'}++;
1516 121 my $alias = $table . "_" . $self->{'alias_count'};
1517  
1518 121 return ($alias);
1519  
1520 }
1521  
1522  
1523  
1524 =head2 Join
1525  
1526 Join instructs DBIx::SearchBuilder to join two tables.
1527  
1528 The standard form takes a param hash with keys ALIAS1, FIELD1, ALIAS2 and
1529 FIELD2. ALIAS1 and ALIAS2 are column aliases obtained from $self->NewAlias or
1530 a $self->Limit. FIELD1 and FIELD2 are the fields in ALIAS1 and ALIAS2 that
1531 should be linked, respectively. For this type of join, this method
1532 has no return value.
1533  
1534 Supplying the parameter TYPE => 'left' causes Join to preform a left join.
1535 in this case, it takes ALIAS1, FIELD1, TABLE2 and FIELD2. Because of the way
1536 that left joins work, this method needs a TABLE for the second field
1537 rather than merely an alias. For this type of join, it will return
1538 the alias generated by the join.
1539  
1540 Instead of ALIAS1/FIELD1, it's possible to specify EXPRESSION, to join
1541 ALIAS2/TABLE2 on an arbitrary expression.
1542  
1543 It is also possible to join to a pre-existing, already-limited
1544 L<DBIx::SearchBuilder> object, by passing it as COLLECTION2, instead
1545 of providing an ALIAS2 or TABLE2.
1546  
1547 By passing true value as DISTINCT argument join can be marked distinct. If
1548 all joins are distinct then whole query is distinct and SearchBuilder can
1549 avoid L</_DistinctQuery> call that can hurt performance of the query. See
1550 also L</NewAlias>.
1551  
1552 =cut
1553  
1554 119 ▶sub Join {
Subroutine Join: called CC=1 SCAR=0.0
Pod documented
1555 119 my $self = shift;
1556 119 my %args = (
1557 TYPE => 'normal',
1558 FIELD1 => undef,
1559 ALIAS1 => 'main',
1560 TABLE2 => undef,
1561 COLLECTION2 => undef,
1562 FIELD2 => undef,
1563 ALIAS2 => undef,
1564 @_
1565 );
1566  
1567 119 $self->_Handle->Join( SearchBuilder => $self, %args );
1568  
1569 }
1570  
1571 =head2 Pages: size and changing
1572  
1573 Use L</RowsPerPage> to set size of pages. L</NextPage>,
1574 L</PrevPage>, L</FirstPage> or L</GotoPage> to change
1575 pages. L</FirstRow> to do tricky stuff.
1576  
1577 =head3 RowsPerPage
1578  
1579 Get or set the number of rows returned by the database.
1580  
1581 Takes an optional integer which restricts the # of rows returned
1582 in a result. Zero or undef argument flush back to "return all
1583 records matching current conditions".
1584  
1585 Returns the current page size.
1586  
1587 =cut
1588  
1589 529 ▶sub RowsPerPage {
Subroutine RowsPerPage: called CC=5 SCAR=16.1
Pod documented
1590 529 my $self = shift;
1591  
1592 529 ▶ if ( @_ && ($_[0]||0) != $self->{'show_rows'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and ($_[0] || 0) != $self->{"show_rows"}) 54 475 529
Condition100%5/5
@_ and ($_[0] || 0) != $self->{"show_rows"}
!ll&&!rl&&r
474154
$_[0] || 0
l!l
541
MC/DC100%2/2
@_ and ($_[0] || 0) != $self->{"show_rows"}
@_ $_[0]
Truth table100%3/3
A and B
A= @_B= $_[0]
ABresult
0X0
100
111
1593 54 ▶ $self->{'show_rows'} = shift || 0;
Condition50%1/2
shift() || 0
l!l
540
MC/DC0%0/1
shift() || 0
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
1594 54 $self->RedoSearch;
1595 }
1596  
1597 529 return ( $self->{'show_rows'} );
1598 }
1599  
1600 =head3 NextPage
1601  
1602 Turns one page forward.
1603  
1604 =cut
1605  
1606 8 ▶sub NextPage {
Subroutine NextPage: called CC=1 SCAR=0.0
Pod documented
1607 8 my $self = shift;
1608 8 $self->FirstRow( $self->FirstRow + 1 + $self->RowsPerPage );
1609 }
1610  
1611 =head3 PrevPage
1612  
1613 Turns one page backwards.
1614  
1615 =cut
1616  
1617 3 ▶sub PrevPage {
Subroutine PrevPage: called CC=2 SCAR=6.9
Pod documented
1618 3 my $self = shift;
1619 3 ▶ if ( ( $self->FirstRow - $self->RowsPerPage ) > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->FirstRow - $self->RowsPerPage > 0) { } 2 1 3
1620 2 $self->FirstRow( 1 + $self->FirstRow - $self->RowsPerPage );
1621 }
1622 else {
1623 1 $self->FirstRow(1);
1624 }
1625 }
1626  
1627 =head3 FirstPage
1628  
1629 Jumps to the first page.
1630  
1631 =cut
1632  
1633 0 ▶sub FirstPage {
Subroutine FirstPage: not called CC=1 SCAR=6.9
Pod documented
1634 0 my $self = shift;
1635 0 $self->FirstRow(1);
1636 }
1637  
1638 =head3 GotoPage
1639  
1640 Takes an integer number and jumps to that page or first page if
1641 number omitted. Numbering starts from zero.
1642  
1643 =cut
1644  
1645 41 ▶sub GotoPage {
Subroutine GotoPage: called CC=2 SCAR=7.1
Pod documented
1646 41 my $self = shift;
1647 41 ▶ my $page = shift || 0;
Condition50%1/2
shift() || 0
l!l
410
MC/DC0%0/1
shift() || 0
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
1648  
1649 41 $self->FirstRow( 1 + $self->RowsPerPage * $page );
1650 }
1651  
1652 =head3 FirstRow
1653  
1654 Get or set the first row of the result set the database should return.
1655 Takes an optional single integer argrument. Returns the currently set integer
1656 minus one (this is historical issue).
1657  
1658 Usually you don't need this method. Use L</RowsPerPage>, L</NextPage> and other
1659 methods to walk pages. It only may be helpful to get 10 records starting from
1660 5th.
1661  
1662 =cut
1663  
1664 297 ▶sub FirstRow {
Subroutine FirstRow: called CC=4 SCAR=13.9
Pod documented
1665 297 my $self = shift;
1666 297 ▶ if (@_ && ($_[0]||1) != ($self->{'first_row'}+1) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and ($_[0] || 1) != $self->{"first_row"} + 1) 37 260 297
Condition80%4/5
@_ and ($_[0] || 1) != $self->{"first_row"} + 1
!ll&&!rl&&r
2441637
$_[0] || 1
l!l
530
MC/DC50%1/2
@_ and ($_[0] || 1) != $self->{"first_row"} + 1
@_ $_[0]
Truth table66%2/3
A and B
A= @_B= $_[0]
ABresult
0X0
100
111
1667 37 $self->{'first_row'} = shift;
1668  
1669 #SQL starts counting at 0
1670 37 $self->{'first_row'}--;
1671  
1672 #gotta redo the search if changing pages
1673 37 $self->RedoSearch();
1674 }
1675 297 return ( $self->{'first_row'} );
1676 }
1677  
1678  
1679 =head2 _ItemsCounter
1680  
1681 Returns the current position in the record set.
1682  
1683 =cut
1684  
1685 5 ▶sub _ItemsCounter {
Subroutine _ItemsCounter: called CC=1 SCAR=0.0
1686 5 my $self = shift;
1687 5 return $self->{'itemscount'};
1688 }
1689  
1690  
1691 =head2 Count
1692  
1693 Returns the number of records in the set. When L</RowsPerPage> is set,
1694 returns number of records in the page only, otherwise the same as
1695 L</CountAll>.
1696  
1697 =cut
1698  
1699 72 ▶sub Count {
Subroutine Count: called CC=4 SCAR=13.9
Pod documented
1700 72 my $self = shift;
1701  
1702 # An unlimited search returns no tickets
1703 72 ▶ return 0 unless ($self->_isLimited);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_isLimited 7 65 72
1704  
1705 65 ▶ if ( $self->{'must_redo_search'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"must_redo_search"}) 49 16 65
1706 49 ▶ if ( $self->RowsPerPage ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->RowsPerPage) { } 3 46 49
1707 3 $self->_DoSearch;
1708 }
1709 else {
1710 # No RowsPerPage means Count == CountAll
1711 46 return $self->CountAll;
1712 }
1713 }
1714  
1715 19 return $self->_RecordCount;
1716 }
1717  
1718  
1719  
1720 =head2 CountAll
1721  
1722 Returns the total number of potential records in the set, ignoring any
1723 L</RowsPerPage> settings.
1724  
1725 =cut
1726  
1727 129 ▶sub CountAll {
Subroutine CountAll: called CC=6 SCAR=17.9
Pod documented
1728 129 my $self = shift;
1729  
1730 # An unlimited search returns no tickets
1731 129 ▶ return 0 unless ($self->_isLimited);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_isLimited 0 129 129
1732  
1733 # If we haven't actually got all objects loaded in memory, we
1734 # really just want to do a quick count from the database.
1735 # or if we have paging enabled then we count as well and store it in count_all
1736 129 ▶ if ( $self->{'must_redo_search'} || ( $self->RowsPerPage && !defined $self->{'count_all'} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'must_redo_search'} or $self->RowsPerPage and not defined $self->{'count_all'}) { } 71 58 129
elsif ($self->RowsPerPage) { } 25 33 58
Condition100%6/6
$self->{"must_redo_search"} or $self->RowsPerPage and not defined $self->{"count_all"}
l!l&&r!l&&!r
472458
$self->RowsPerPage and not defined $self->{"count_all"}
!ll&&!rl&&r
332524
MC/DC100%3/3
$self->{"must_redo_search"} or $self->RowsPerPage and not defined $self->{"count_all"}
$self->{"must_redo_search"} $self->RowsPerPage not defined $self->{"count_all"}
Truth table100%4/4
A or B and not(C)
A= $self->{"must_redo_search"}B= $self->RowsPerPageC= not defined $self->{"count_all"}
ABCresult
1XX1
0111
00X0
0100
1737 # If we haven't already asked the database for the row count, do that
1738 71 $self->_DoCount;
1739  
1740 #Report back the raw # of rows in the database
1741 71 return ( $self->{'count_all'} );
1742 }
1743  
1744 # if we have paging enabled and have count_all then return it
1745 elsif ( $self->RowsPerPage ) {
1746 25 return ( $self->{'count_all'} );
1747 }
1748  
1749 # If we have loaded everything from the DB we have an
1750 # accurate count already.
1751 else {
1752 33 return $self->_RecordCount;
1753 }
1754 }
1755  
1756  
1757 =head2 IsLast
1758  
1759 Returns true if the current row is the last record in the set.
1760  
1761 =cut
1762  
1763 9 ▶sub IsLast {
Subroutine IsLast: called CC=3 SCAR=11.0
Pod documented
1764 9 my $self = shift;
1765  
1766 9 ▶ return undef unless $self->Count;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->Count 4 5 9
1767  
1768 5 ▶ if ( $self->_ItemsCounter == $self->Count ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_ItemsCounter == $self->Count) { } 3 2 5
1769 3 return (1);
1770 }
1771 else {
1772 2 return (0);
1773 }
1774 }
1775  
1776  
1777 =head2 Column
1778  
1779 Call to specify which columns should be loaded from the table. Each
1780 calls adds one column to the set. Takes a hash with the following named
1781 arguments:
1782  
1783 =over 4
1784  
1785 =item FIELD
1786  
1787 Column name to fetch or apply function to.
1788  
1789 =item ALIAS
1790  
1791 Alias of a table the field is in; defaults to C<main>
1792  
1793 =item FUNCTION
1794  
1795 A SQL function that should be selected instead of FIELD or applied to it.
1796  
1797 =item AS
1798  
1799 The B<column> alias to use instead of the default. The default column alias is
1800 either the column's name (i.e. what is passed to FIELD) if it is in this table
1801 (ALIAS is 'main') or an autogenerated alias. Pass C<undef> to skip column
1802 aliasing entirely.
1803  
1804 =back
1805  
1806 C<FIELD>, C<ALIAS> and C<FUNCTION> are combined according to
1807 L</CombineFunctionWithField>.
1808  
1809 If a FIELD is provided and it is in this table (ALIAS is 'main'), then
1810 the column named FIELD and can be accessed as usual by accessors:
1811  
1812 $articles->Column(FIELD => 'id');
1813 $articles->Column(FIELD => 'Subject', FUNCTION => 'SUBSTR(?, 1, 20)');
1814 my $article = $articles->First;
1815 my $aid = $article->id;
1816 my $subject_prefix = $article->Subject;
1817  
1818 Returns the alias used for the column. If FIELD was not provided, or was
1819 from another table, then the returned column alias should be passed to
1820 the L<DBIx::SearchBuilder::Record/_Value> method to retrieve the
1821 column's result:
1822  
1823 my $time_alias = $articles->Column(FUNCTION => 'NOW()');
1824 my $article = $articles->First;
1825 my $now = $article->_Value( $time_alias );
1826  
1827 To choose the column's alias yourself, pass a value for the AS parameter (see
1828 above). Be careful not to conflict with existing column aliases.
1829  
1830 =cut
1831  
1832 87 ▶sub Column {
Subroutine Column: called CC=14 SCAR=26.5
Pod documented
1833 87 my $self = shift;
1834 87 my %args = ( TABLE => undef,
1835 ALIAS => undef,
1836 FIELD => undef,
1837 FUNCTION => undef,
1838 @_);
1839  
1840 87 ▶ $args{'ALIAS'} ||= 'main';
Condition100%2/2
$args{"ALIAS"} ||= "main"
l!l
2265
MC/DC100%1/1
$args{"ALIAS"} ||= "main"
$args{"ALIAS"}
Truth table100%2/2
A
A= $args{"ALIAS"}
Aresult
11
00
1841  
1842 87 ▶ my $name = $self->CombineFunctionWithField( %args ) || 'NULL';
Condition50%1/2
$self->CombineFunctionWithField(%args) || 'NULL'
l!l
870
MC/DC0%0/1
$self->CombineFunctionWithField(%args) || 'NULL'
$self->CombineFunctionWithField(%args)
Truth table50%1/2
A
A= $self->CombineFunctionWithField(%args)
Aresult
11
00
1843  
1844 87 my $column = $args{'AS'};
1845  
1846 87 ▶ if (not defined $column and not exists $args{'AS'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $column or exists $args{"AS"}) 77 10 87
Condition100%3/3
defined $column or exists $args{"AS"}
l!l&&r!l&&!r
6477
MC/DC100%2/2
defined $column or exists $args{"AS"}
defined $column exists $args{"AS"}
Truth table100%3/3
A or B
A= defined $columnB= exists $args{"AS"}
ABresult
1X1
011
000
1847 77 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'FIELD'} and $args{'ALIAS'} eq 'main' and !$args{'TABLE'} || $args{'TABLE'} eq $self->Table) { } 70 7 77
Condition66%6/9
$args{"FIELD"} and $args{"ALIAS"} eq "main" and !$args{"TABLE"} || $args{"TABLE"} eq $self->Table
!ll&&!rl&&r
7070
$args{"FIELD"} and $args{"ALIAS"} eq "main"
!ll&&!rl&&r
3470
not $args{"TABLE"} or $args{"TABLE"} eq $self->Table
l!l&&r!l&&!r
7000
MC/DC50%2/4
$args{"FIELD"} and $args{"ALIAS"} eq "main" and !$args{"TABLE"} || $args{"TABLE"} eq $self->Table
$args{"FIELD"} $args{"ALIAS"} eq "main" not $args{"TABLE"} $args{"TABLE"} eq $self->Table
Truth table60%3/5
A and B and not(C) or D
A= $args{"FIELD"}B= $args{"ALIAS"} eq "main"C= not $args{"TABLE"}D= $args{"TABLE"} eq $self->Table
ABCDresult
0XXX0
10XX0
11000
111X1
11011
1848 $args{FIELD} && $args{ALIAS} eq 'main'
1849 && (!$args{'TABLE'} || $args{'TABLE'} eq $self->Table )
1850 ) {
1851 70 $column = $args{FIELD};
1852  
1853 # make sure we don't fetch columns with duplicate aliases
1854 70 ▶ if ( $self->{columns} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"columns"}) 24 46 70
1855 24 my $suffix = " AS \L$column";
1856 24 ▶ if ( grep index($_, $suffix, -length $suffix) >= 0, @{ $self->{columns} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep index($_, $suffix, -length($suffix)) != -1, @{$$self{"columns"};}) 21 3 24
1857 21 $column .= scalar @{ $self->{columns} };
1858 }
1859 }
1860 }
1861 else {
1862 7 ▶ $column = "col" . @{ $self->{columns} ||= [] };
Condition50%1/2
$self->{"columns"} ||= []
l!l
70
MC/DC0%0/1
$self->{"columns"} ||= []
$self->{"columns"}
Truth table50%1/2
A
A= $self->{"columns"}
Aresult
11
00
1863 }
1864 }
1865 87 ▶ push @{ $self->{columns} ||= [] }, defined($column) ? "$name AS \L$column" : $name;
Branch: 1 branch
BranchTrueFalseTotal
defined $column ? : 83 4 87
Condition100%2/2
$self->{"columns"} ||= []
l!l
4047
MC/DC100%1/1
$self->{"columns"} ||= []
$self->{"columns"}
Truth table100%2/2
A
A= $self->{"columns"}
Aresult
11
00
1866 87 return $column;
1867 }
1868  
1869 =head2 CombineFunctionWithField
1870  
1871 Takes a hash with three optional arguments: FUNCTION, FIELD and ALIAS.
1872  
1873 Returns SQL with all three arguments combined according to the following
1874 rules.
1875  
1876 =over 4
1877  
1878 =item *
1879  
1880 FUNCTION or undef returned when FIELD is not provided
1881  
1882 =item *
1883  
1884 'main' ALIAS is used if not provided
1885  
1886 =item *
1887  
1888 ALIAS.FIELD returned when FUNCTION is not provided
1889  
1890 =item *
1891  
1892 NULL returned if FUNCTION is 'NULL'
1893  
1894 =item *
1895  
1896 If FUNCTION contains '?' (question marks) then they are replaced with
1897 ALIAS.FIELD and result returned.
1898  
1899 =item *
1900  
1901 If FUNCTION has no '(' (opening parenthesis) then ALIAS.FIELD is
1902 appended in parentheses and returned.
1903  
1904 =back
1905  
1906 Examples:
1907  
1908 $obj->CombineFunctionWithField()
1909 => undef
1910  
1911 $obj->CombineFunctionWithField(FUNCTION => 'FOO')
1912 => 'FOO'
1913  
1914 $obj->CombineFunctionWithField(FIELD => 'foo')
1915 => 'main.foo'
1916  
1917 $obj->CombineFunctionWithField(ALIAS => 'bar', FIELD => 'foo')
1918 => 'bar.foo'
1919  
1920 $obj->CombineFunctionWithField(FUNCTION => 'FOO(?, ?)', FIELD => 'bar')
1921 => 'FOO(main.bar, main.bar)'
1922  
1923 $obj->CombineFunctionWithField(FUNCTION => 'FOO', ALIAS => 'bar', FIELD => 'baz')
1924 => 'FOO(bar.baz)'
1925  
1926 $obj->CombineFunctionWithField(FUNCTION => 'NULL', FIELD => 'bar')
1927 => 'NULL'
1928  
1929 =cut
1930  
1931  
1932  
1933 253 ▶sub CombineFunctionWithField {
Subroutine CombineFunctionWithField: called CC=9 SCAR=22.1
Pod documented
1934 253 my $self = shift;
1935 253 my %args = (
1936 FUNCTION => undef,
1937 ALIAS => undef,
1938 FIELD => undef,
1939 @_
1940 );
1941  
1942 253 ▶ unless ( $args{'FIELD'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"FIELD"}) 11 242 253
1943 11 ▶ return $args{'FUNCTION'} || undef;
Condition50%1/2
$args{'FUNCTION'} || undef
l!l
110
MC/DC0%0/1
$args{'FUNCTION'} || undef
$args{'FUNCTION'}
Truth table50%1/2
A
A= $args{'FUNCTION'}
Aresult
11
00
1944 }
1945  
1946 242 ▶ my $field = ($args{'ALIAS'} || 'main') .'.'. $args{'FIELD'};
Condition100%2/2
$args{'ALIAS'} || 'main'
l!l
19646
MC/DC100%1/1
$args{'ALIAS'} || 'main'
$args{'ALIAS'}
Truth table100%2/2
A
A= $args{'ALIAS'}
Aresult
11
00
1947 242 ▶ return $field unless $args{'FUNCTION'};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"FUNCTION"} 207 35 242
1948  
1949 35 my $func = $args{'FUNCTION'};
1950 35 ▶ if ( $func =~ /^DISTINCT\s*COUNT$/i ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($func =~ /^DISTINCT\s*COUNT$/i) { } 0 35 35
elsif ($func =~ s/\?/$field/g) { } 30 5 35
elsif (not $func =~ /\(/ and lc $func ne 'null') { } 1 7 8
1951 0 $func = "COUNT(DISTINCT $field)";
1952 }
1953  
1954 # If we want to substitute
1955 elsif ( $func =~ s/\?/$field/g ) {
1956 # no need to do anything, we already replaced
1957 }
1958  
1959 # If we want to call a simple function on the column
1960 ▶ elsif ( $func !~ /\(/ && lc($func) ne 'null' ) {
Condition100%3/3
not $func =~ /\(/ and lc $func ne "null"
!ll&&!rl&&r
311
MC/DC100%2/2
not $func =~ /\(/ and lc $func ne "null"
not $func =~ /\(/ lc $func ne "null"
Truth table100%3/3
not(A) and B
A= not $func =~ /\(/B= lc $func ne "null"
ABresult
0X0
100
111
1961 1 $func = "\U$func\E($field)";
1962 }
1963  
1964 35 return $func;
1965 }
1966  
1967  
1968  
1969  
1970 =head2 Columns LIST
1971  
1972 Specify that we want to load only the columns in LIST
1973  
1974 =cut
1975  
1976 5 ▶sub Columns {
Subroutine Columns: called CC=2 SCAR=6.9
Pod documented
1977 5 my $self = shift;
1978 5 $self->Column( FIELD => $_ ) for @_;
1979 }
1980  
1981 =head2 AdditionalColumn
1982  
1983 Calls L</Column>, but first ensures that this table's standard columns are
1984 selected as well. Thus, each call to this method results in an additional
1985 column selected instead of replacing the default columns.
1986  
1987 Takes a hash of parameters which is the same as L</Column>. Returns the result
1988 of calling L</Column>.
1989  
1990 =cut
1991  
1992 3 ▶sub AdditionalColumn {
Subroutine AdditionalColumn: called CC=2 SCAR=7.4
Pod documented
1993 3 my $self = shift;
1994 $self->Column( FUNCTION => "main.*", AS => undef )
1995 0 ▶ unless grep { /^\Qmain.*\E$/ } @{$self->{columns}};
Branch: 1 branch
BranchTrueFalseTotal
unless grep {/^main\.\*$/;} @{$$self{"columns"};} 3 0 3
1996 3 return $self->Column(@_);
1997 }
1998  
1999 =head2 Fields TABLE
2000  
2001 Return a list of fields in TABLE. These fields are in the case
2002 presented by the database, which may be case-sensitive.
2003  
2004 =cut
2005  
2006 0 ▶sub Fields {
Subroutine Fields: not called CC=1 SCAR=6.9
Pod documented
2007 0 return (shift)->_Handle->Fields( @_ );
2008 }
2009  
2010  
2011 =head2 HasField { TABLE => undef, FIELD => undef }
2012  
2013 Returns true if TABLE has field FIELD.
2014 Return false otherwise
2015  
2016 Note: Both TABLE and FIELD are case-sensitive (See: L</Fields>)
2017  
2018 =cut
2019  
2020 0 ▶sub HasField {
Subroutine HasField: not called CC=3 SCAR=24.8
Pod documented
2021 0 my $self = shift;
2022 0 my %args = ( FIELD => undef,
2023 TABLE => undef,
2024 @_);
2025  
2026 0 ▶ my $table = $args{TABLE} or die;
Branch: 1 branch
BranchTrueFalseTotal
my $table = $args{"TABLE"} or die 0 0 0
2027 0 ▶ my $field = $args{FIELD} or die;
Branch: 1 branch
BranchTrueFalseTotal
my $field = $args{"FIELD"} or die 0 0 0
2028 0 return grep { $_ eq $field } $self->Fields($table);
2029 }
2030  
2031  
2032 =head2 Table [TABLE]
2033  
2034 If called with an argument, sets this collection's table.
2035  
2036 Always returns this collection's table.
2037  
2038 =cut
2039  
2040 741 ▶sub Table {
Subroutine Table: called CC=2 SCAR=6.9
Pod documented
2041 741 my $self = shift;
2042 741 ▶ $self->{table} = shift if (@_);
Branch: 1 branch
BranchTrueFalseTotal
if @_ 157 584 741
2043 741 return $self->{table};
2044 }
2045  
2046 =head2 QueryHint [Hint]
2047  
2048 If called with an argument, sets a query hint for this collection. Call
2049 this method before performing additional operations on a collection,
2050 such as C<Count()>, C<Next()>, etc.
2051  
2052 Always returns the query hint.
2053  
2054 When the query hint is included in the SQL query, the C</* ... */> will be
2055 included for you. Here's an example query hint for Oracle:
2056  
2057 $sb->QueryHint("+CURSOR_SHARING_EXACT");
2058  
2059 =cut
2060  
2061 351 ▶sub QueryHint {
Subroutine QueryHint: called CC=2 SCAR=6.9
Pod documented
2062 351 my $self = shift;
2063 351 ▶ $self->{query_hint} = shift if (@_);
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 350 351
2064 351 return $self->{query_hint};
2065 }
2066  
2067 =head2 QueryHintFormatted
2068  
2069 Returns the query hint formatted appropriately for inclusion in SQL queries.
2070  
2071 =cut
2072  
2073 277 ▶sub QueryHintFormatted {
Subroutine QueryHintFormatted: called CC=2 SCAR=6.9
Pod documented
2074 277 my $self = shift;
2075 277 my $QueryHint = $self->QueryHint;
2076  
2077 # As it turns out, we can't have a space between the opening /*
2078 # and the query hint, otherwise Oracle treats this as a comment.
2079 277 ▶ return $QueryHint ? " /*$QueryHint */ " : " ";
Branch: 1 branch
BranchTrueFalseTotal
$QueryHint ? : 3 274 277
2080 }
2081  
2082  
2083 314 ▶sub _OptimizeQuery {
Subroutine _OptimizeQuery: called CC=3 SCAR=11.0
2084 314 my $self = shift;
2085 314 my $query = shift;
2086  
2087 314 ▶ my %args = ( PreferBind => $self->{_prefer_bind} // $PREFER_BIND, @_ );
Condition66%2/3
$self->{"_prefer_bind"} // $DBIx::SearchBuilder::PREFER_BIND
l!l&&r!l&&!r
040274
MC/DC50%1/2
$self->{"_prefer_bind"} // $DBIx::SearchBuilder::PREFER_BIND
$self->{"_prefer_bind"} $DBIx::SearchBuilder::PREFER_BIND
Truth table66%2/3
A // B
A= $self->{"_prefer_bind"}B= $DBIx::SearchBuilder::PREFER_BIND
ABresult
1X1
011
000
2088  
2089 314 undef $self->{_bind_values};
2090 314 ▶ if ( $args{PreferBind} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"PreferBind"}) 34 280 314
2091 34 my @bind_values = $self->_Handle->_ExtractBindValues($query);
2092  
2093 # Set _bind_values even if no values are extracted, as we use it in
2094 # ApplyLimits to determine if bind is enabled.
2095 34 $self->{_bind_values} = \@bind_values;
2096 }
2097 }
2098  
2099 =head1 DEPRECATED METHODS
2100  
2101 =head2 GroupBy
2102  
2103 DEPRECATED. Alias for the L</GroupByCols> method.
2104  
2105 =cut
2106  
2107 4 ▶sub GroupBy { (shift)->GroupByCols( @_ ) }
Subroutine GroupBy: called CC=1 SCAR=0.0
Pod documented
2108  
2109 =head2 SetTable
2110  
2111 DEPRECATED. Alias for the L</Table> method.
2112  
2113 =cut
2114  
2115 0 ▶sub SetTable {
Subroutine SetTable: not called CC=1 SCAR=6.9
Pod documented
2116 0 my $self = shift;
2117 0 return $self->Table(@_);
2118 }
2119  
2120 =head2 ShowRestrictions
2121  
2122 DEPRECATED AND DOES NOTHING.
2123  
2124 =cut
2125  
2126 0 ▶sub ShowRestrictions { }
Subroutine ShowRestrictions: not called CC=1 SCAR=0.0
Pod documented
2127  
2128 =head2 ImportRestrictions
2129  
2130 DEPRECATED AND DOES NOTHING.
2131  
2132 =cut
2133  
2134 0 ▶sub ImportRestrictions { }
Subroutine ImportRestrictions: not called CC=1 SCAR=0.0
Pod documented
2135  
2136 # not even documented
2137 0 ▶sub DEBUG { warn "DEBUG is deprecated" }
Subroutine DEBUG: not called CC=1 SCAR=6.9
Pod undocumented
2138  
2139  
2140 14 ▶if( eval { require capitalization } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require capitalization } }) 0 14 14
2141 0 capitalization->unimport( __PACKAGE__ );
2142 }
2143  
2144 14 1;
2145 __END__
« SearchBuilder/Handle/ODBC.pm ↑ Summary SearchBuilder/Handle/SQLite.pm »