SearchBuilder/Handle.pm

filter: Statementstmt 66.2% 450 / 679 Branchbran 56.8% 174 / 306 Conditioncond 54.2% 57 / 105 MC/DCmcdc 36.2% 21 / 58 Subroutinesub 69.2% 54 / 78 Podpod 92.4% 49 / 53 totaltotal 62.9% 805 / 1279 CC 213 SCAR 31.5
CC
213
Cov
62%
NullsOrder
81.0
Join
80.7
MayBeNull
53.2
CRAP 23.2
« SearchBuilder/Handle/MariaDB.pm ↑ Summary SearchBuilder/Handle/Oracle.pm »
1 package DBIx::SearchBuilder::Handle;
2  
3 26 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 26 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 26 ▶use feature 'state';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 26 ▶use Carp qw(croak cluck);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 26 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 26 ▶use Class::ReturnValue;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 26 ▶use Encode qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 26 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 26 ▶use DBIx::SearchBuilder::Util qw/ sorted_values /;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 26 ▶use vars qw(@ISA %DBIHandle $PrevHandle $DEBUG %TRANSDEPTH %TRANSROLLBACK %FIELDS_IN_TABLE);
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17  
18 =head1 NAME
19  
20 DBIx::SearchBuilder::Handle - Perl extension which is a generic DBI handle
21  
22 =head1 SYNOPSIS
23  
24 use DBIx::SearchBuilder::Handle;
25  
26 my $handle = DBIx::SearchBuilder::Handle->new();
27 $handle->Connect( Driver => 'mysql',
28 Database => 'dbname',
29 Host => 'hostname',
30 User => 'dbuser',
31 Password => 'dbpassword');
32 # now $handle isa DBIx::SearchBuilder::Handle::mysql
33  
34 =head1 DESCRIPTION
35  
36 This class provides a wrapper for DBI handles that can also perform a number of additional functions.
37  
38 =cut
39  
40  
41  
42 =head2 new
43  
44 Generic constructor
45  
46 =cut
47  
48 24 ▶sub new {
Subroutine new: called CC=2 SCAR=7.0
Pod documented
49 24 my $proto = shift;
50 24 ▶ my $class = ref($proto) || $proto;
Condition33%1/3
ref $proto || $proto
l!l&&r!l&&!r
0240
MC/DC0%0/2
ref $proto || $proto
ref $proto $proto
Truth table33%1/3
A || B
A= ref $protoB= $proto
ABresult
1X1
011
000
51 24 my $self = {};
52 24 bless ($self, $class);
53  
54 # Enable quotes table names
55 24 my %args = ( QuoteTableNames => 0, @_ );
56 24 $self->{'QuoteTableNames'} = $args{QuoteTableNames};
57  
58 24 @{$self->{'StatementLog'}} = ();
59 24 return $self;
60 }
61  
62  
63  
64 =head2 Connect PARAMHASH: Driver, Database, Host, User, Password, QuoteTableNames
65  
66 Takes a paramhash and connects to your DBI datasource.
67  
68 You should _always_ set
69  
70 DisconnectHandleOnDestroy => 1
71  
72 unless you have a legacy app like RT2 or RT 3.0.{0,1,2} that depends on the broken behaviour.
73  
74 If you created the handle with
75 DBIx::SearchBuilder::Handle->new
76 and there is a DBIx::SearchBuilder::Handle::(Driver) subclass for the driver you have chosen,
77 the handle will be automatically "upgraded" into that subclass.
78  
79 QuoteTableNames option will force all table names to be quoted if the driver subclass has a method
80 for quoting implemented. The mysql subclass will detect mysql version 8 and set the flag.
81  
82 =cut
83  
84 23 ▶sub Connect {
Subroutine Connect: called CC=11 SCAR=26.3
Pod documented
85 23 my $self = shift;
86 23 my %args = (
87 Driver => undef,
88 Database => undef,
89 Host => undef,
90 SID => undef,
91 Port => undef,
92 User => undef,
93 Password => undef,
94 RequireSSL => undef,
95 DisconnectHandleOnDestroy => undef,
96 QuoteTableNames => undef,
97 @_
98 );
99  
100 23 ▶ if ( $args{'Driver'} && !$self->isa( __PACKAGE__ .'::'. $args{'Driver'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"Driver"} and not $self->isa('DBIx::SearchBuilder::Handle::' . $args{"Driver"})) 1 22 23
Condition66%2/3
$args{"Driver"} and not $self->isa('DBIx::SearchBuilder::Handle::' . $args{"Driver"})
!ll&&!rl&&r
0221
MC/DC50%1/2
$args{"Driver"} and not $self->isa('DBIx::SearchBuilder::Handle::' . $args{"Driver"})
$args{"Driver"} not $self->isa('DBIx::SearchBuilder::Handle::' . $args{"Driver"})
Truth table66%2/3
A and not(B)
A= $args{"Driver"}B= not $self->isa('DBIx::SearchBuilder::Handle::' . $args{"Driver"})
ABresult
0X0
100
111
101 1 ▶ return $self->Connect( %args ) if $self->_UpgradeHandle( $args{'Driver'} );
Branch: 1 branch
BranchTrueFalseTotal
if $self->_UpgradeHandle($args{"Driver"}) 1 0 1
102 }
103  
104 # Setting this actually breaks old RT versions in subtle ways.
105 # So we need to explicitly call it
106 22 $self->{'DisconnectHandleOnDestroy'} = $args{'DisconnectHandleOnDestroy'};
107  
108 # Enable optional quoted table names
109 22 ▶ $self->{'QuoteTableNames'} = delete $args{QuoteTableNames} if defined $args{QuoteTableNames};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"QuoteTableNames"} 0 22 22
110  
111 22 ▶ my $old_dsn = $self->DSN || '';
Condition50%1/2
$self->DSN || ''
l!l
022
MC/DC0%0/1
$self->DSN || ''
$self->DSN
Truth table50%1/2
A
A= $self->DSN
Aresult
11
00
112 22 my $new_dsn = $self->BuildDSN( %args );
113  
114 # Only connect if we're not connected to this source already
115 22 ▶ return undef if $self->dbh && $self->dbh->ping && $new_dsn eq $old_dsn;
Branch: 1 branch
BranchTrueFalseTotal
if $self->dbh and $self->dbh->ping and $new_dsn eq $old_dsn 0 22 22
Condition33%2/6
$self->dbh and $self->dbh->ping and $new_dsn eq $old_dsn
!ll&&!rl&&r
2200
$self->dbh and $self->dbh->ping
!ll&&!rl&&r
2200
MC/DC0%0/3
$self->dbh and $self->dbh->ping and $new_dsn eq $old_dsn
$self->dbh $self->dbh->ping $new_dsn eq $old_dsn
Truth table25%1/4
A and B and C
A= $self->dbhB= $self->dbh->pingC= $new_dsn eq $old_dsn
ABCresult
0XX0
10X0
1100
1111
116  
117 my $handle = DBI->connect(
118 22 ▶ $new_dsn, $args{'User'}, $args{'Password'}
Branch: 1 branch
BranchTrueFalseTotal
my $handle = "DBI"->connect($new_dsn, $args{"User"}, $args{"Password"}) or croak("Connect Failed $DBI::errstr\n") 22 0 22
119 ) or croak "Connect Failed $DBI::errstr\n";
120  
121 # databases do case conversion on the name of columns returned.
122 # actually, some databases just ignore case. this smashes it to something consistent
123 22 $handle->{FetchHashKeyName} ='NAME_lc';
124  
125 # Set the handle
126 22 $self->dbh($handle);
127  
128 # Cache version info
129 22 $self->DatabaseVersion;
130  
131 # force quoted tables for mysql 8
132 22 ▶ $self->{'QuoteTableNames'} = 1 if $self->_RequireQuotedTables;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_RequireQuotedTables 0 22 22
133  
134 22 return 1;
135 }
136  
137  
138 =head2 _UpgradeHandle DRIVER
139  
140 This private internal method turns a plain DBIx::SearchBuilder::Handle into one
141 of the standard driver-specific subclasses.
142  
143 =cut
144  
145 1 ▶sub _UpgradeHandle {
Subroutine _UpgradeHandle: called CC=2 SCAR=7.0
146 1 my $self = shift;
147  
148 1 my $driver = shift;
149 1 my $class = 'DBIx::SearchBuilder::Handle::' . $driver;
150 1 local $@;
151 1 eval "require $class";
152 1 ▶ return if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
153  
154 1 bless $self, $class;
155 1 return 1;
156 }
157  
158  
159 =head2 BuildDSN PARAMHASH
160  
161 Takes a bunch of parameters:
162  
163 Required: Driver, Database,
164 Optional: Host, Port and RequireSSL
165  
166 Builds a DSN suitable for a DBI connection
167  
168 =cut
169  
170 22 ▶sub BuildDSN {
Subroutine BuildDSN: called CC=5 SCAR=16.8
Pod documented
171 22 my $self = shift;
172 22 my %args = (
173 Driver => undef,
174 Database => undef,
175 Host => undef,
176 Port => undef,
177 SID => undef,
178 RequireSSL => undef,
179 @_
180 );
181  
182 22 my $dsn = "dbi:$args{'Driver'}:dbname=$args{'Database'}";
183 22 ▶ $dsn .= ";sid=$args{'SID'}" if $args{'SID'};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"SID"} 0 22 22
184 22 ▶ $dsn .= ";host=$args{'Host'}" if $args{'Host'};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"Host"} 0 22 22
185 22 ▶ $dsn .= ";port=$args{'Port'}" if $args{'Port'};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"Port"} 0 22 22
186 22 ▶ $dsn .= ";requiressl=1" if $args{'RequireSSL'};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"RequireSSL"} 0 22 22
187  
188 22 return $self->{'dsn'} = $dsn;
189 }
190  
191  
192 =head2 DSN
193  
194 Returns the DSN for this database connection.
195  
196 =cut
197  
198 22 ▶sub DSN {
Subroutine DSN: called CC=1 SCAR=0.0
Pod documented
199 22 return shift->{'dsn'};
200 }
201  
202  
203  
204 =head2 RaiseError [MODE]
205  
206 Turns on the Database Handle's RaiseError attribute.
207  
208 =cut
209  
210 0 ▶sub RaiseError {
Subroutine RaiseError: not called CC=2 SCAR=17.9
Pod documented
211 0 my $self = shift;
212  
213 0 my $mode = 1;
214 0 ▶ $mode = shift if (@_);
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
215  
216 0 $self->dbh->{RaiseError}=$mode;
217 }
218  
219  
220  
221  
222 =head2 PrintError [MODE]
223  
224 Turns on the Database Handle's PrintError attribute.
225  
226 =cut
227  
228 0 ▶sub PrintError {
Subroutine PrintError: not called CC=2 SCAR=17.9
Pod documented
229 0 my $self = shift;
230  
231 0 my $mode = 1;
232 0 ▶ $mode = shift if (@_);
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
233  
234 0 $self->dbh->{PrintError}=$mode;
235 }
236  
237  
238  
239 =head2 LogSQLStatements BOOL
240  
241 Takes a boolean argument. If the boolean is true, SearchBuilder will log all SQL
242 statements, as well as their invocation times and execution times.
243  
244 Returns whether we're currently logging or not as a boolean
245  
246 =cut
247  
248 1144 ▶sub LogSQLStatements {
Subroutine LogSQLStatements: called CC=2 SCAR=8.4
Pod documented
249 1144 my $self = shift;
250 1144 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 1144 1144
251 0 require Time::HiRes;
252 0 $self->{'_DoLogSQL'} = shift;
253 }
254 1144 return ($self->{'_DoLogSQL'});
255 }
256  
257 =head2 _LogSQLStatement STATEMENT DURATION
258  
259 Add an SQL statement to our query log
260  
261 =cut
262  
263 0 ▶sub _LogSQLStatement {
Subroutine _LogSQLStatement: not called CC=1 SCAR=6.9
264 0 my $self = shift;
265 0 my $statement = shift;
266 0 my $duration = shift;
267 0 my @bind = @_;
268 0 push @{$self->{'StatementLog'}} , ([Time::HiRes::time(), $statement, [@bind], $duration, Carp::longmess("Executed SQL query")]);
269  
270 }
271  
272 =head2 ClearSQLStatementLog
273  
274 Clears out the SQL statement log.
275  
276  
277 =cut
278  
279 0 ▶sub ClearSQLStatementLog {
Subroutine ClearSQLStatementLog: not called CC=1 SCAR=6.9
Pod documented
280 0 my $self = shift;
281 0 @{$self->{'StatementLog'}} = ();
282 }
283  
284  
285 =head2 SQLStatementLog
286  
287 Returns the current SQL statement log as an array of arrays. Each entry is a triple of
288  
289 (Time, Statement, Duration)
290  
291 =cut
292  
293 0 ▶sub SQLStatementLog {
Subroutine SQLStatementLog: not called CC=1 SCAR=6.9
Pod documented
294 0 my $self = shift;
295 0 return (@{$self->{'StatementLog'}});
296  
297 }
298  
299  
300  
301 =head2 AutoCommit [MODE]
302  
303 Turns on the Database Handle's AutoCommit attribute.
304  
305 =cut
306  
307 0 ▶sub AutoCommit {
Subroutine AutoCommit: not called CC=2 SCAR=17.9
Pod documented
308 0 my $self = shift;
309  
310 0 my $mode = 1;
311 0 ▶ $mode = shift if (@_);
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
312  
313 0 $self->dbh->{AutoCommit}=$mode;
314 }
315  
316  
317  
318  
319 =head2 Disconnect
320  
321 Disconnect from your DBI datasource
322  
323 =cut
324  
325 0 ▶sub Disconnect {
Subroutine Disconnect: not called CC=6 SCAR=37.4
Pod documented
326 0 my $self = shift;
327 0 my $dbh = $self->dbh;
328 0 ▶ return unless $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh 0 0 0
329 0 $self->Rollback(1);
330  
331 0 my $ret = $dbh->disconnect;
332  
333 # DBD::mysql with MariaDB 10.2+ could cause segment faults when
334 # interacting with a disconnected handle, here we unset
335 # dbh to inform other code that there is no connection any more.
336 # See also https://github.com/perl5-dbi/DBD-mysql/issues/306
337 0 ▶ my ($version) = ( $self->DatabaseVersion // '' ) =~ /^(\d+\.\d+)/;
Condition0%0/2
$self->DatabaseVersion // ""
l!l
00
MC/DC0%0/1
$self->DatabaseVersion // ""
$self->DatabaseVersion
Truth table0%0/2
A
A= $self->DatabaseVersion
Aresult
11
00
338 0 ▶ if ( $self->isa('DBIx::SearchBuilder::Handle::mysql')
Branch: 1 branch
BranchTrueFalseTotal
if ($self->isa("DBIx::SearchBuilder::Handle::mysql") and $self->{"database_version"} =~ /mariadb/i and "version"->parse('v' . $version) > "version"->parse("v10.2")) 0 0 0
Condition0%0/6
$self->isa("DBIx::SearchBuilder::Handle::mysql") and $self->{"database_version"} =~ /mariadb/i and "version"->parse('v' . $version) > "version"->parse("v10.2")
!ll&&!rl&&r
000
$self->isa("DBIx::SearchBuilder::Handle::mysql") and $self->{"database_version"} =~ /mariadb/i
!ll&&!rl&&r
000
MC/DC0%0/3
$self->isa("DBIx::SearchBuilder::Handle::mysql") and $self->{"database_version"} =~ /mariadb/i and "version"->parse('v' . $version) > "version"->parse("v10.2")
$self->isa("DBIx::SearchBuilder::Handle::mysql") $self->{"database_version"} =~ /mariadb/i "version"->parse('v' . $version) > "version"->parse("v10.2")
Truth table0%0/4
A and B and C
A= $self->isa("DBIx::SearchBuilder::Handle::mysql")B= $self->{"database_version"} =~ /mariadb/iC= "version"->parse('v' . $version) > "version"->parse("v10.2")
ABCresult
0XX0
10X0
1100
1111
339 && $self->{'database_version'} =~ /mariadb/i
340 && version->parse('v'.$version) > version->parse('v10.2') )
341 {
342 0 $self->dbh(undef);
343 }
344  
345 0 return $ret;
346 }
347  
348  
349 =head2 dbh [HANDLE]
350  
351 Return the current DBI handle. If we're handed a parameter, make the database handle that.
352  
353 =cut
354  
355 # allow use of Handle as a synonym for DBH
356 26 *Handle=\&dbh;
357  
358 1044 ▶sub dbh {
Subroutine dbh: called CC=3 SCAR=11.0
Pod documented
359 1044 my $self=shift;
360  
361 #If we are setting the database handle, set it.
362 1044 ▶ if ( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 22 1022 1044
363 22 $DBIHandle{$self} = $PrevHandle = shift;
364 22 %FIELDS_IN_TABLE = ();
365 }
366  
367 1044 ▶ return($DBIHandle{$self} ||= $PrevHandle);
Condition66%2/3
$DBIx::SearchBuilder::Handle::DBIHandle{$self} ||= $DBIx::SearchBuilder::Handle::PrevHandle
l!l&&r!l&&!r
1007037
MC/DC50%1/2
$DBIx::SearchBuilder::Handle::DBIHandle{$self} ||= $DBIx::SearchBuilder::Handle::PrevHandle
$DBIx::SearchBuilder::Handle::DBIHandle{$self} $DBIx::SearchBuilder::Handle::PrevHandle
Truth table66%2/3
A ||= B
A= $DBIx::SearchBuilder::Handle::DBIHandle{$self}B= $DBIx::SearchBuilder::Handle::PrevHandle
ABresult
1X1
011
000
368 }
369  
370  
371 =head2 Insert $TABLE_NAME @KEY_VALUE_PAIRS
372  
373 Takes a table name and a set of key-value pairs in an array.
374 Splits the key value pairs, constructs an INSERT statement
375 and performs the insert.
376  
377 Base class return statement handle object, while DB specific
378 subclass should return row id.
379  
380 =cut
381  
382 162 ▶sub Insert {
Subroutine Insert: called CC=1 SCAR=0.0
Pod documented
383 162 my $self = shift;
384 162 return $self->SimpleQuery( $self->InsertQueryString(@_) );
385 }
386  
387 =head2 InsertQueryString $TABLE_NAME @KEY_VALUE_PAIRS
388  
389 Takes a table name and a set of key-value pairs in an array.
390 Splits the key value pairs, constructs an INSERT statement
391 and returns query string and set of bind values.
392  
393 This method is more useful for subclassing in DB specific
394 handles. L</Insert> method is preferred for end users.
395  
396 =cut
397  
398 162 ▶sub InsertQueryString {
Subroutine InsertQueryString: called CC=3 SCAR=11.0
Pod documented
399 162 my($self, $table, @pairs) = @_;
400 162 my(@cols, @vals, @bind);
401  
402 162 ▶ while ( my $key = shift @pairs ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $key = shift @pairs) 431 162 593
403 431 push @cols, $key;
404 431 push @vals, '?';
405 431 push @bind, shift @pairs;
406 }
407  
408 162 ▶ $table = $self->QuoteName($table) if $self->QuoteTableNames;
Branch: 1 branch
BranchTrueFalseTotal
if $self->QuoteTableNames 0 162 162
409 162 my $QueryString = "INSERT INTO $table";
410 162 $QueryString .= " (". join(", ", @cols) .")";
411 162 $QueryString .= " VALUES (". join(", ", @vals). ")";
412 162 return ($QueryString, @bind);
413 }
414  
415 =head2 InsertFromSelect
416  
417 Takes table name, array reference with columns, select query
418 and list of bind values. Inserts data select by the query
419 into the table.
420  
421 To make sure call is portable every column in result of
422 the query should have unique name or should be aliased.
423 See L<DBIx::SearchBuilder::Handle::Oracle/InsertFromSelect> for
424 details.
425  
426 =cut
427  
428 4 ▶sub InsertFromSelect {
Subroutine InsertFromSelect: called CC=6 SCAR=18.8
Pod documented
429 4 my ($self, $table, $columns, $query, @binds) = @_;
430  
431 4 ▶ $columns = join ', ', @$columns
Branch: 1 branch
BranchTrueFalseTotal
if $columns 4 0 4
432 if $columns;
433  
434 4 ▶ $table = $self->QuoteName($table) if $self->{'QuoteTableNames'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"QuoteTableNames"} 0 4 4
435 4 my $full_query = "INSERT INTO $table";
436 4 ▶ $full_query .= " ($columns)" if $columns;
Branch: 1 branch
BranchTrueFalseTotal
if $columns 4 0 4
437 4 $full_query .= ' '. $query;
438 4 my $sth = $self->SimpleQuery( $full_query, @binds );
439 4 ▶ return $sth unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 4 4
440  
441 4 my $rows = $sth->rows;
442 4 ▶ return $rows == 0? '0E0' : $rows;
Branch: 1 branch
BranchTrueFalseTotal
$rows == 0 ? : 0 4 4
443 }
444  
445 =head2 UpdateRecordValue
446  
447 Takes a hash with fields: Table, Column, Value PrimaryKeys, and
448 IsSQLFunction. Table, and Column should be obvious, Value is where you
449 set the new value you want the column to have. The primary_keys field should
450 be the lvalue of DBIx::SearchBuilder::Record::PrimaryKeys(). Finally
451 IsSQLFunction is set when the Value is a SQL function. For example, you
452 might have ('Value'=>'PASSWORD(string)'), by setting IsSQLFunction that
453 string will be inserted into the query directly rather then as a binding.
454  
455 =cut
456  
457 19 ▶sub UpdateRecordValue {
Subroutine UpdateRecordValue: called CC=4 SCAR=14.0
Pod documented
458 19 my $self = shift;
459 19 my %args = ( Table => undef,
460 Column => undef,
461 IsSQLFunction => undef,
462 PrimaryKeys => undef,
463 @_ );
464  
465 19 my @bind = ();
466 19 ▶ $args{Table} = $self->QuoteName($args{Table}) if $self->{'QuoteTableNames'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"QuoteTableNames"} 0 19 19
467 19 my $query = 'UPDATE ' . $args{'Table'} . ' ';
468 19 $query .= 'SET ' . $args{'Column'} . '=';
469  
470 ## Look and see if the field is being updated via a SQL function.
471 19 ▶ if ($args{'IsSQLFunction'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'IsSQLFunction'}) { } 0 19 19
472 0 $query .= $args{'Value'} . ' ';
473 }
474 else {
475 19 $query .= '? ';
476 19 push (@bind, $args{'Value'});
477 }
478  
479 ## Constructs the where clause.
480 19 my $where = 'WHERE ';
481 19 foreach my $key (sort keys %{$args{'PrimaryKeys'}}) {
482 19 $where .= $key . "=?" . " AND ";
483 19 push (@bind, $args{'PrimaryKeys'}{$key});
484 }
485 19 $where =~ s/AND\s$//;
486  
487 19 my $query_str = $query . $where;
488 19 return ($self->SimpleQuery($query_str, @bind));
489 }
490  
491  
492  
493  
494 =head2 UpdateTableValue TABLE COLUMN NEW_VALUE RECORD_ID IS_SQL
495  
496 Update column COLUMN of table TABLE where the record id = RECORD_ID. if IS_SQL is set,
497 don\'t quote the NEW_VALUE
498  
499 =cut
500  
501 0 ▶sub UpdateTableValue {
Subroutine UpdateTableValue: not called CC=1 SCAR=6.9
Pod documented
502 0 my $self = shift;
503  
504 ## This is just a wrapper to UpdateRecordValue().
505 0 my %args = ();
506 0 $args{'Table'} = shift;
507 0 $args{'Column'} = shift;
508 0 $args{'Value'} = shift;
509 0 $args{'PrimaryKeys'} = shift;
510 0 $args{'IsSQLFunction'} = shift;
511  
512 0 return $self->UpdateRecordValue(%args)
513 }
514  
515 =head1 SimpleUpdateFromSelect
516  
517 Takes table name, hash reference with (column, value) pairs,
518 select query and list of bind values.
519  
520 Updates the table, but only records with IDs returned by the
521 selected query, eg:
522  
523 UPDATE $table SET %values WHERE id IN ( $query )
524  
525 It's simple as values are static and search only allowed
526 by id.
527  
528 =cut
529  
530 1 ▶sub SimpleUpdateFromSelect {
Subroutine SimpleUpdateFromSelect: called CC=5 SCAR=16.3
Pod undocumented
531 1 my ($self, $table, $values, $query, @query_binds) = @_;
532  
533 1 my @columns; my @binds;
534 1 for my $k (sort keys %$values) {
535 2 push @columns, $k;
536 2 push @binds, $values->{$k};
537 }
538  
539 1 ▶ $table = $self->QuoteName($table) if $self->{'QuoteTableNames'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"QuoteTableNames"} 0 1 1
540 1 my $full_query = "UPDATE $table SET ";
541 1 $full_query .= join ', ', map "$_ = ?", @columns;
542 1 $full_query .= ' WHERE id IN ('. $query .')';
543 1 my $sth = $self->SimpleQuery( $full_query, @binds, @query_binds );
544 1 ▶ return $sth unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 1 1
545  
546 1 my $rows = $sth->rows;
547 1 ▶ return $rows == 0? '0E0' : $rows;
Branch: 1 branch
BranchTrueFalseTotal
$rows == 0 ? : 0 1 1
548 }
549  
550 =head1 DeleteFromSelect
551  
552 Takes table name, select query and list of bind values.
553  
554 Deletes from the table, but only records with IDs returned by the
555 select query, eg:
556  
557 DELETE FROM $table WHERE id IN ($query)
558  
559 =cut
560  
561 1 ▶sub DeleteFromSelect {
Subroutine DeleteFromSelect: called CC=4 SCAR=14.5
Pod undocumented
562 1 my ($self, $table, $query, @binds) = @_;
563 1 ▶ $table = $self->QuoteName($table) if $self->{'QuoteTableNames'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"QuoteTableNames"} 0 1 1
564 1 my $sth = $self->SimpleQuery(
565 "DELETE FROM $table WHERE id IN ($query)",
566 @binds
567 );
568 1 ▶ return $sth unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 1 1
569  
570 1 my $rows = $sth->rows;
571 1 ▶ return $rows == 0? '0E0' : $rows;
Branch: 1 branch
BranchTrueFalseTotal
$rows == 0 ? : 0 1 1
572 }
573  
574 =head2 SimpleQuery QUERY_STRING, [ BIND_VALUE, ... ]
575  
576 Execute the SQL string specified in QUERY_STRING
577  
578 =cut
579  
580 574 ▶sub SimpleQuery {
Subroutine SimpleQuery: called CC=14 SCAR=35.1
Pod documented
581 574 my $self = shift;
582 574 my $QueryString = shift;
583 574 my @bind_values;
584 574 ▶ @bind_values = (@_) if (@_);
Branch: 1 branch
BranchTrueFalseTotal
if @_ 278 296 574
585  
586 574 my $sth = $self->dbh->prepare($QueryString);
587 574 ▶ unless ($sth) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 2 572 574
588 2 ▶ if ($DEBUG) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DBIx::SearchBuilder::Handle::DEBUG) { } 0 2 2
589 0 die "$self couldn't prepare the query '$QueryString'"
590 . $self->dbh->errstr . "\n";
591 }
592 else {
593 2 warn "$self couldn't prepare the query '$QueryString'"
594 . $self->dbh->errstr . "\n";
595 2 my $ret = Class::ReturnValue->new();
596 2 $ret->as_error(
597 errno => '-1',
598 message => "Couldn't prepare the query '$QueryString'."
599 . $self->dbh->errstr,
600 do_backtrace => undef
601 );
602 2 return ( $ret->return_value );
603 }
604 }
605  
606 # Check @bind_values for HASH refs. These can be sent as type settings
607 # or hits for the DBD module for dealing with certain data types,
608 # usually BLOBS.
609 572 ▶ for ( my $bind_idx = 0 ; $bind_idx < scalar @bind_values ; $bind_idx++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bind_idx < scalar @bind_values) 583 572 1155
610 583 ▶ if ( ref( $bind_values[$bind_idx] ) eq "HASH" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $bind_values[$bind_idx] eq "HASH") 0 583 583
611 0 my $bhash = $bind_values[$bind_idx];
612 0 $bind_values[$bind_idx] = $bhash->{'value'};
613 0 delete $bhash->{'value'};
614  
615 # DBD::MariaDB only works using the string version of setting type,
616 # so convert the hash to the string for this case.
617 0 ▶ if ( $self->isa('DBIx::SearchBuilder::Handle::MariaDB')
Branch: 1 branch
BranchTrueFalseTotal
if ($self->isa('DBIx::SearchBuilder::Handle::MariaDB') and $bhash->{'TYPE'} and $bhash->{'TYPE'} eq 'SQL_BLOB') { } 0 0 0
Condition0%0/6
$self->isa("DBIx::SearchBuilder::Handle::MariaDB") and $bhash->{"TYPE"} and $bhash->{"TYPE"} eq "SQL_BLOB"
!ll&&!rl&&r
000
$self->isa("DBIx::SearchBuilder::Handle::MariaDB") and $bhash->{"TYPE"}
!ll&&!rl&&r
000
MC/DC0%0/3
$self->isa("DBIx::SearchBuilder::Handle::MariaDB") and $bhash->{"TYPE"} and $bhash->{"TYPE"} eq "SQL_BLOB"
$self->isa("DBIx::SearchBuilder::Handle::MariaDB") $bhash->{"TYPE"} $bhash->{"TYPE"} eq "SQL_BLOB"
Truth table0%0/4
A and B and C
A= $self->isa("DBIx::SearchBuilder::Handle::MariaDB")B= $bhash->{"TYPE"}C= $bhash->{"TYPE"} eq "SQL_BLOB"
ABCresult
0XX0
10X0
1100
1111
618 && $bhash->{'TYPE'}
619 && $bhash->{'TYPE'} eq 'SQL_BLOB' ) {
620 0 $sth->bind_param( $bind_idx + 1, undef, DBI::SQL_BLOB );
621 }
622 else {
623 0 $sth->bind_param( $bind_idx + 1, undef, $bhash );
624 }
625 }
626 }
627  
628 572 my $basetime;
629 572 ▶ if ( $self->LogSQLStatements ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->LogSQLStatements) 0 572 572
630 0 $basetime = Time::HiRes::time();
631 }
632 572 my $executed;
633 {
634 26 ▶ no warnings 'uninitialized' ; # undef in bind_values makes DBI sad
Subroutine BEGIN: called CC=1 SCAR=0.0
635 572 eval { $executed = $sth->execute(@bind_values) };
636 }
637 572 ▶ if ( $self->LogSQLStatements ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->LogSQLStatements) 0 572 572
638 0 $self->_LogSQLStatement( $QueryString, Time::HiRes::time() - $basetime, @bind_values );
639 }
640  
641 572 ▶ if ( $@ or !$executed ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $executed) 0 572 572
Condition33%1/3
$@ or not $executed
l!l&&r!l&&!r
00572
MC/DC0%0/2
$@ or not $executed
$@ not $executed
Truth table33%1/3
A or not(B)
A= $@B= not $executed
ABresult
1X1
011
000
642 0 ▶ if ($DEBUG) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DBIx::SearchBuilder::Handle::DEBUG) { } 0 0 0
643 0 die "$self couldn't execute the query '$QueryString'"
644 . $self->dbh->errstr . "\n";
645  
646 }
647 else {
648 0 cluck "$self couldn't execute the query '$QueryString'";
649  
650 0 my $ret = Class::ReturnValue->new();
651 0 $ret->as_error(
652 errno => '-1',
653 message => "Couldn't execute the query '$QueryString'"
654 . $self->dbh->errstr,
655 do_backtrace => undef
656 );
657 0 return ( $ret->return_value );
658 }
659  
660 }
661 572 return ($sth);
662  
663 }
664  
665  
666  
667 =head2 FetchResult QUERY, [ BIND_VALUE, ... ]
668  
669 Takes a SELECT query as a string, along with an array of BIND_VALUEs
670 If the select succeeds, returns the first row as an array.
671 Otherwise, returns a Class::ResturnValue object with the failure loaded
672 up.
673  
674 =cut
675  
676 0 ▶sub FetchResult {
Subroutine FetchResult: not called CC=2 SCAR=17.9
Pod documented
677 0 my $self = shift;
678 0 my $query = shift;
679 0 my @bind_values = @_;
680 0 my $sth = $self->SimpleQuery($query, @bind_values);
681 0 ▶ if ($sth) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth) { } 0 0 0
682 0 return ($sth->fetchrow);
683 }
684 else {
685 0 return($sth);
686 }
687 }
688  
689  
690 =head2 BinarySafeBLOBs
691  
692 Returns 1 if the current database supports BLOBs with embedded nulls.
693 Returns undef if the current database doesn't support BLOBs with embedded nulls
694  
695 =cut
696  
697 0 ▶sub BinarySafeBLOBs {
Subroutine BinarySafeBLOBs: not called CC=1 SCAR=6.9
Pod documented
698 0 my $self = shift;
699 0 return(1);
700 }
701  
702  
703  
704 =head2 KnowsBLOBs
705  
706 Returns 1 if the current database supports inserts of BLOBs automatically.
707 Returns undef if the current database must be informed of BLOBs for inserts.
708  
709 =cut
710  
711 181 ▶sub KnowsBLOBs {
Subroutine KnowsBLOBs: called CC=1 SCAR=0.0
Pod documented
712 181 my $self = shift;
713 181 return(1);
714 }
715  
716  
717  
718 =head2 BLOBParams FIELD_NAME FIELD_TYPE
719  
720 Returns a hash ref for the bind_param call to identify BLOB types used by
721 the current database for a particular column type.
722  
723 =cut
724  
725 0 ▶sub BLOBParams {
Subroutine BLOBParams: not called CC=1 SCAR=6.9
Pod documented
726 0 my $self = shift;
727 # Don't assign to key 'value' as it is defined later.
728 0 return ( {} );
729 }
730  
731  
732  
733 =head2 DatabaseVersion [Short => 1]
734  
735 Returns the database's version.
736  
737 If argument C<Short> is true returns short variant, in other
738 case returns whatever database handle/driver returns. By default
739 returns short version, e.g. '4.1.23' or '8.0-rc4'.
740  
741 Returns empty string on error or if database couldn't return version.
742  
743 The base implementation uses a C<SELECT VERSION()>
744  
745 =cut
746  
747 0 ▶sub DatabaseVersion {
Subroutine DatabaseVersion: not called CC=6 SCAR=37.4
Pod documented
748 0 my $self = shift;
749 0 my %args = ( Short => 1, @_ );
750  
751 0 ▶ unless ( defined $self->{'database_version'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"database_version"}) 0 0 0
752  
753 # turn off error handling, store old values to restore later
754 0 my $re = $self->RaiseError;
755 0 $self->RaiseError(0);
756 0 my $pe = $self->PrintError;
757 0 $self->PrintError(0);
758  
759 0 my $statement = "SELECT VERSION()";
760 0 my $sth = $self->SimpleQuery($statement);
761  
762 0 my $ver = '';
763 0 ▶ $ver = ( $sth->fetchrow_arrayref->[0] || '' ) if $sth;
Branch: 1 branch
BranchTrueFalseTotal
if $sth 0 0 0
Condition0%0/2
$sth->fetchrow_arrayref->[0] || ''
l!l
00
MC/DC0%0/1
$sth->fetchrow_arrayref->[0] || ''
$sth->fetchrow_arrayref->[0]
Truth table0%0/2
A
A= $sth->fetchrow_arrayref->[0]
Aresult
11
00
764 0 $ver =~ /(\d+(?:\.\d+)*(?:-[a-z0-9]+)?)/i;
765 0 $self->{'database_version'} = $ver;
766 0 ▶ $self->{'database_version_short'} = $1 || $ver;
Condition0%0/3
$1 || $ver
l!l&&r!l&&!r
000
MC/DC0%0/2
$1 || $ver
$1 $ver
Truth table0%0/3
A || B
A= $1B= $ver
ABresult
1X1
011
000
767  
768 0 $self->RaiseError($re);
769 0 $self->PrintError($pe);
770 }
771  
772 0 ▶ return $self->{'database_version_short'} if $args{'Short'};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"Short"} 0 0 0
773 0 return $self->{'database_version'};
774 }
775  
776 =head2 CaseSensitive
777  
778 Returns 1 if the current database's searches are case sensitive by default
779 Returns undef otherwise
780  
781 =cut
782  
783 0 ▶sub CaseSensitive {
Subroutine CaseSensitive: not called CC=1 SCAR=6.9
Pod documented
784 0 my $self = shift;
785 0 return(1);
786 }
787  
788 =head2 QuoteTableNames
789  
790 Returns 1 if table names will be quoted in queries, otherwise 0
791  
792 =cut
793  
794 355 ▶sub QuoteTableNames {
Subroutine QuoteTableNames: called CC=1 SCAR=0.0
Pod documented
795 355 return shift->{'QuoteTableNames'}
796 }
797  
798  
799  
800  
801  
802 =head2 _MakeClauseCaseInsensitive FIELD OPERATOR VALUE
803  
804 Takes a field, operator and value. performs the magic necessary to make
805 your database treat this clause as case insensitive.
806  
807 Returns a FIELD OPERATOR VALUE triple.
808  
809 =cut
810  
811 26 our $RE_CASE_INSENSITIVE_CHARS = qr/[-'"\d: ]/;
812  
813 45 ▶sub _MakeClauseCaseInsensitive {
Subroutine _MakeClauseCaseInsensitive: called CC=2 SCAR=6.9
814 45 my $self = shift;
815 45 my $field = shift;
816 45 my $operator = shift;
817 45 my $value = shift;
818  
819 # don't downcase integer values and things that looks like dates
820 45 ▶ if ($value !~ /^$RE_CASE_INSENSITIVE_CHARS+$/o) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($value =~ /^$DBIx::SearchBuilder::Handle::RE_CASE_INSENSITIVE_CHARS+$/o) 31 14 45
821 31 $field = "lower($field)";
822 31 $value = lc($value);
823 }
824 45 return ($field, $operator, $value,undef);
825 }
826  
827 =head2 Transactions
828  
829 L<DBIx::SearchBuilder::Handle> emulates nested transactions,
830 by keeping a transaction stack depth.
831  
832 B<NOTE:> In nested transactions you shouldn't mix rollbacks and commits,
833 because only last action really do commit/rollback. For example next code
834 would produce desired results:
835  
836 $handle->BeginTransaction;
837 $handle->BeginTransaction;
838 ...
839 $handle->Rollback;
840 $handle->BeginTransaction;
841 ...
842 $handle->Commit;
843 $handle->Commit;
844  
845 Only last action(Commit in example) finilize transaction in DB.
846  
847 =head3 BeginTransaction
848  
849 Tells DBIx::SearchBuilder to begin a new SQL transaction.
850 This will temporarily suspend Autocommit mode.
851  
852 =cut
853  
854 10 ▶sub BeginTransaction {
Subroutine BeginTransaction: called CC=3 SCAR=11.0
Pod documented
855 10 my $self = shift;
856  
857 10 my $depth = $self->TransactionDepth;
858 10 ▶ return unless defined $depth;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $depth 1 9 10
859  
860 9 $self->TransactionDepth(++$depth);
861 9 ▶ return 1 if $depth > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $depth > 1 3 6 9
862  
863 6 return $self->dbh->begin_work;
864 }
865  
866 =head3 EndTransaction [Action => 'commit'] [Force => 0]
867  
868 Tells to end the current transaction. Takes C<Action> argument
869 that could be C<commit> or C<rollback>, the default value
870 is C<commit>.
871  
872 If C<Force> argument is true then all nested transactions
873 would be committed or rolled back.
874  
875 If there is no transaction in progress then method throw
876 warning unless action is forced.
877  
878 Method returns true on success or false if an error occurred.
879  
880 =cut
881  
882 20 ▶sub EndTransaction {
Subroutine EndTransaction: called CC=11 SCAR=24.0
Pod documented
883 20 my $self = shift;
884 20 my %args = ( Action => 'commit', Force => 0, @_ );
885 20 ▶ my $action = lc $args{'Action'} eq 'commit'? 'commit': 'rollback';
Branch: 1 branch
BranchTrueFalseTotal
lc $args{'Action'} eq 'commit' ? : 11 9 20
886  
887 20 ▶ my $depth = $self->TransactionDepth || 0;
Condition100%2/2
$self->TransactionDepth || 0
l!l
911
MC/DC100%1/1
$self->TransactionDepth || 0
$self->TransactionDepth
Truth table100%2/2
A
A= $self->TransactionDepth
Aresult
11
00
888 20 ▶ unless ( $depth ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth) { } 9 11 20
889 11 ▶ unless( $args{'Force'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"Force"}) 4 7 11
890 4 Carp::cluck( "Attempted to $action a transaction with none in progress" );
891 4 return 0;
892 }
893 7 return 1;
894 } else {
895 9 $depth--;
896 }
897 9 ▶ $depth = 0 if $args{'Force'};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"Force"} 0 9 9
898  
899 9 $self->TransactionDepth( $depth );
900  
901 9 my $dbh = $self->dbh;
902 9 $TRANSROLLBACK{ $dbh }{ $action }++;
903 9 ▶ if ( $TRANSROLLBACK{ $dbh }{ $action eq 'commit'? 'rollback' : 'commit' } ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($DBIx::SearchBuilder::Handle::TRANSROLLBACK{$dbh}{$action eq "commit" ? "rollback" : "commit"}) 2 7 9
$action eq 'commit' ? : 6 3 9
904 2 warn "Rollback and commit are mixed while escaping nested transaction";
905 }
906 9 ▶ return 1 if $depth;
Branch: 1 branch
BranchTrueFalseTotal
if $depth 3 6 9
907  
908 6 delete $TRANSROLLBACK{ $dbh };
909  
910 6 ▶ if ($action eq 'commit') {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq 'commit') { } 4 2 6
911 4 return $dbh->commit;
912 }
913 else {
914 2 ▶ DBIx::SearchBuilder::Record::Cachable->FlushCache
Branch: 1 branch
BranchTrueFalseTotal
if "DBIx::SearchBuilder::Record::Cachable"->can("FlushCache") 0 2 2
915 if DBIx::SearchBuilder::Record::Cachable->can('FlushCache');
916 2 return $dbh->rollback;
917 }
918 }
919  
920 =head3 Commit [FORCE]
921  
922 Tells to commit the current SQL transaction.
923  
924 Method uses C<EndTransaction> method, read its
925 L<description|DBIx::SearchBuilder::Handle/EndTransaction>.
926  
927 =cut
928  
929 10 ▶sub Commit {
Subroutine Commit: called CC=1 SCAR=0.0
Pod documented
930 10 my $self = shift;
931 10 $self->EndTransaction( Action => 'commit', Force => shift );
932 }
933  
934  
935 =head3 Rollback [FORCE]
936  
937 Tells to abort the current SQL transaction.
938  
939 Method uses C<EndTransaction> method, read its
940 L<description|DBIx::SearchBuilder::Handle/EndTransaction>.
941  
942 =cut
943  
944 8 ▶sub Rollback {
Subroutine Rollback: called CC=1 SCAR=0.0
Pod documented
945 8 my $self = shift;
946 8 $self->EndTransaction( Action => 'rollback', Force => shift );
947 }
948  
949  
950 =head3 ForceRollback
951  
952 Force the handle to rollback.
953 Whether or not we're deep in nested transactions.
954  
955 =cut
956  
957 1 ▶sub ForceRollback {
Subroutine ForceRollback: called CC=1 SCAR=0.0
Pod documented
958 1 my $self = shift;
959 1 $self->Rollback(1);
960 }
961  
962  
963 =head3 TransactionDepth
964  
965 Returns the current depth of the nested transaction stack.
966 Returns C<undef> if there is no connection to database.
967  
968 =cut
969  
970 61 ▶sub TransactionDepth {
Subroutine TransactionDepth: called CC=6 SCAR=17.9
Pod documented
971 61 my $self = shift;
972  
973 61 my $dbh = $self->dbh;
974 61 ▶ return undef unless $dbh && $dbh->ping;
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh and $dbh->ping 10 51 61
Condition66%2/3
$dbh and $dbh->ping
!ll&&!rl&&r
10051
MC/DC50%1/2
$dbh and $dbh->ping
$dbh $dbh->ping
Truth table66%2/3
A and B
A= $dbhB= $dbh->ping
ABresult
0X0
100
111
975  
976 51 ▶ if ( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 18 33 51
977 18 my $depth = shift;
978 18 ▶ if ( $depth ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth) { } 12 6 18
979 12 $TRANSDEPTH{ $dbh } = $depth;
980 } else {
981 6 delete $TRANSDEPTH{ $dbh };
982 }
983 }
984 51 ▶ return $TRANSDEPTH{ $dbh } || 0;
Condition100%2/2
$DBIx::SearchBuilder::Handle::TRANSDEPTH{$dbh} || 0
l!l
3021
MC/DC100%1/1
$DBIx::SearchBuilder::Handle::TRANSDEPTH{$dbh} || 0
$DBIx::SearchBuilder::Handle::TRANSDEPTH{$dbh}
Truth table100%2/2
A
A= $DBIx::SearchBuilder::Handle::TRANSDEPTH{$dbh}
Aresult
11
00
985 }
986  
987  
988 =head2 ApplyLimits STATEMENTREF ROWS_PER_PAGE FIRST_ROW
989  
990 takes an SQL SELECT statement and massages it to return ROWS_PER_PAGE starting with FIRST_ROW;
991  
992 =cut
993  
994 231 ▶sub ApplyLimits {
Subroutine ApplyLimits: called CC=6 SCAR=17.9
Pod documented
995 231 my $self = shift;
996 231 my $statementref = shift;
997 231 my $per_page = shift;
998 231 my $first = shift;
999 231 my $sb = shift;
1000  
1001 231 my $limit_clause = '';
1002  
1003 231 ▶ if ( $per_page) {
Branch: 1 branch
BranchTrueFalseTotal
if ($per_page) 69 162 231
1004 69 $limit_clause = " LIMIT ";
1005 69 ▶ if ( $sb->{_bind_values} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sb->{"_bind_values"}) 6 63 69
1006 6 ▶ push @{$sb->{_bind_values}}, $first || (), $per_page;
Condition66%2/3
$first || ()
l!l&&r!l&&!r
204
MC/DC50%1/2
$first || ()
$first ()
Truth table66%2/3
A || B
A= $firstB= ()
ABresult
1X1
011
000
1007 6 ▶ $first = '?' if $first;
Branch: 1 branch
BranchTrueFalseTotal
if $first 2 4 6
1008 6 $per_page = '?';
1009 }
1010  
1011 69 ▶ if ( $first ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first) 36 33 69
1012 36 $limit_clause .= $first . ", ";
1013 }
1014 69 $limit_clause .= $per_page;
1015 }
1016  
1017 231 $$statementref .= $limit_clause;
1018 }
1019  
1020  
1021  
1022  
1023  
1024 =head2 Join { Paramhash }
1025  
1026 Takes a paramhash of everything Searchbuildler::Record does
1027 plus a parameter called 'SearchBuilder' that contains a ref
1028 to a SearchBuilder object'.
1029  
1030 This performs the join.
1031  
1032  
1033 =cut
1034  
1035  
1036 119 ▶sub Join {
Subroutine Join: called CC=22 SCAR=43.9
Pod documented
1037  
1038 119 my $self = shift;
1039 119 my %args = (
1040 SearchBuilder => undef,
1041 TYPE => 'normal',
1042 ALIAS1 => 'main',
1043 FIELD1 => undef,
1044 TABLE2 => undef,
1045 COLLECTION2 => undef,
1046 FIELD2 => undef,
1047 ALIAS2 => undef,
1048 EXPRESSION => undef,
1049 @_
1050 );
1051  
1052  
1053 119 my $alias;
1054  
1055 #If we're handed in an ALIAS2, we need to go remove it from the Aliases array.
1056 # Basically, if anyone generates an alias and then tries to use it in a join later, we want to be smart about
1057 # creating joins, so we need to go rip it out of the old aliases table and drop it in as an explicit join
1058 119 ▶ if ( $args{'ALIAS2'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'ALIAS2'}) { } 4 115 119
elsif ($args{'COLLECTION2'}) { } 0 115 115
1059  
1060 # this code is slow and wasteful, but it's clear.
1061 4 my @aliases = @{ $args{'SearchBuilder'}->{'aliases'} };
1062 4 my @new_aliases;
1063 4 foreach my $old_alias (@aliases) {
1064 4 ▶ if ( $old_alias =~ /^(.*?) (\Q$args{'ALIAS2'}\E)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($old_alias =~ /^(.*?) (\Q$args{'ALIAS2'}\E)$/) { } 4 0 4
1065 4 $args{'TABLE2'} = $1;
1066 4 $alias = $2;
1067 4 ▶ $args{'TABLE2'} = $self->DequoteName($args{'TABLE2'}) if $self->QuoteTableNames;
Branch: 1 branch
BranchTrueFalseTotal
if $self->QuoteTableNames 0 4 4
1068 }
1069 else {
1070 0 push @new_aliases, $old_alias;
1071 }
1072 }
1073  
1074 # If we found an alias, great. let's just pull out the table and alias for the other item
1075 4 ▶ unless ($alias) {
Branch: 1 branch
BranchTrueFalseTotal
if ($alias) { } 4 0 4
1076  
1077 # if we can't do that, can we reverse the join and have it work?
1078 0 my $a1 = $args{'ALIAS1'};
1079 0 my $f1 = $args{'FIELD1'};
1080 0 $args{'ALIAS1'} = $args{'ALIAS2'};
1081 0 $args{'FIELD1'} = $args{'FIELD2'};
1082 0 $args{'ALIAS2'} = $a1;
1083 0 $args{'FIELD2'} = $f1;
1084  
1085 0 @aliases = @{ $args{'SearchBuilder'}->{'aliases'} };
1086 0 @new_aliases = ();
1087 0 foreach my $old_alias (@aliases) {
1088 0 ▶ if ( $old_alias =~ /^(.*?) ($args{'ALIAS2'})$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($old_alias =~ /^(.*?) ($args{'ALIAS2'})$/) { } 0 0 0
1089 0 $args{'TABLE2'} = $1;
1090 0 $alias = $2;
1091 0 ▶ $args{'TABLE2'} = $self->DequoteName($args{'TABLE2'}) if $self->QuoteTableNames;
Branch: 1 branch
BranchTrueFalseTotal
if $self->QuoteTableNames 0 0 0
1092 }
1093 else {
1094 0 push @new_aliases, $old_alias;
1095 }
1096 }
1097  
1098 } else {
1099 # we found alias, so NewAlias should take care of distinctness
1100 4 ▶ $args{'DISTINCT'} = 1 unless exists $args{'DISTINCT'};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args{"DISTINCT"} 4 0 4
1101 }
1102  
1103 4 ▶ unless ( $alias ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($alias) 0 4 4
1104 # XXX: this situation is really bug in the caller!!!
1105 0 return ( $self->_NormalJoin(%args) );
1106 }
1107 4 $args{'SearchBuilder'}->{'aliases'} = \@new_aliases;
1108 } elsif ( $args{'COLLECTION2'} ) {
1109 # We're joining to a pre-limited collection. We need to take
1110 # all clauses in the other collection, munge 'main.' to a new
1111 # alias, apply them locally, then proceed as usual.
1112 0 my $collection = delete $args{'COLLECTION2'};
1113 0 $alias = $args{ALIAS2} = $args{'SearchBuilder'}->_GetAlias( $collection->Table );
1114 0 $args{TABLE2} = $collection->Table;
1115  
1116 0 eval {$collection->_ProcessRestrictions}; # RT hate
1117  
1118 # Move over unused aliases
1119 0 push @{$args{SearchBuilder}{aliases}}, @{$collection->{aliases}};
1120  
1121 # Move over joins, as well
1122 0 for my $join (sort keys %{$collection->{left_joins}}) {
1123 0 my %alias = %{$collection->{left_joins}{$join}};
1124 0 ▶ $alias{depends_on} = $alias if $alias{depends_on} eq "main";
Branch: 1 branch
BranchTrueFalseTotal
if $alias{"depends_on"} eq "main" 0 0 0
1125 $alias{criteria} = $self->_RenameRestriction(
1126 RESTRICTIONS => $alias{criteria},
1127 0 NEW => $alias
1128 );
1129 0 $args{SearchBuilder}{left_joins}{$join} = \%alias;
1130 }
1131  
1132 my $restrictions = $self->_RenameRestriction(
1133 RESTRICTIONS => $collection->{restrictions},
1134 0 NEW => $alias
1135 );
1136 0 $args{SearchBuilder}{restrictions}{$_} = $restrictions->{$_} for keys %{$restrictions};
1137 } else {
1138 115 $alias = $args{'SearchBuilder'}->_GetAlias( $args{'TABLE2'} );
1139 }
1140 119 ▶ $args{TABLE2} = $self->QuoteName($args{TABLE2}) if $self->QuoteTableNames;
Branch: 1 branch
BranchTrueFalseTotal
if $self->QuoteTableNames 0 119 119
1141  
1142 119 ▶ my $meta = $args{'SearchBuilder'}->{'left_joins'}{"$alias"} ||= {};
Condition50%1/2
$args{"SearchBuilder"}{"left_joins"}{"$alias"} ||= {}
l!l
0119
MC/DC0%0/1
$args{"SearchBuilder"}{"left_joins"}{"$alias"} ||= {}
$args{"SearchBuilder"}{"left_joins"}{"$alias"}
Truth table50%1/2
A
A= $args{"SearchBuilder"}{"left_joins"}{"$alias"}
Aresult
11
00
1143 119 ▶ if ( $args{'TYPE'} =~ /LEFT/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'TYPE'} =~ /LEFT/i) { } 54 65 119
1144 54 $meta->{'alias_string'} = " LEFT JOIN " . $args{'TABLE2'} . " $alias ";
1145 54 $meta->{'type'} = 'LEFT';
1146 }
1147 else {
1148 65 $meta->{'alias_string'} = " JOIN " . $args{'TABLE2'} . " $alias ";
1149 65 $meta->{'type'} = 'NORMAL';
1150 }
1151 119 $meta->{'depends_on'} = $args{'ALIAS1'};
1152  
1153 119 ▶ my $criterion = $args{'EXPRESSION'} || $args{'ALIAS1'}.".".$args{'FIELD1'};
Condition50%1/2
$args{'EXPRESSION'} || $args{'ALIAS1'} . '.' . $args{'FIELD1'}
l!l
0119
MC/DC0%0/1
$args{'EXPRESSION'} || $args{'ALIAS1'} . '.' . $args{'FIELD1'}
$args{'EXPRESSION'}
Truth table50%1/2
A
A= $args{'EXPRESSION'}
Aresult
11
00
1154 119 $meta->{'criteria'}{'base_criterion'} =
1155 [ { field => "$alias.$args{'FIELD2'}", op => '=', value => $criterion } ];
1156  
1157 119 ▶ if ( $args{'DISTINCT'} && !defined $args{'SearchBuilder'}{'joins_are_distinct'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'DISTINCT'} and not defined $args{'SearchBuilder'}{'joins_are_distinct'}) { } 1 118 119
elsif (not $args{'DISTINCT'}) { } 113 5 118
Condition100%3/3
$args{"DISTINCT"} and not defined $args{"SearchBuilder"}{"joins_are_distinct"}
!ll&&!rl&&r
11351
MC/DC100%2/2
$args{"DISTINCT"} and not defined $args{"SearchBuilder"}{"joins_are_distinct"}
$args{"DISTINCT"} not defined $args{"SearchBuilder"}{"joins_are_distinct"}
Truth table100%3/3
A and not(B)
A= $args{"DISTINCT"}B= not defined $args{"SearchBuilder"}{"joins_are_distinct"}
ABresult
0X0
100
111
1158 1 $args{SearchBuilder}{joins_are_distinct} = 1;
1159 } elsif ( !$args{'DISTINCT'} ) {
1160 113 $args{SearchBuilder}{joins_are_distinct} = 0;
1161 }
1162  
1163 119 return ($alias);
1164 }
1165  
1166 0 ▶sub _RenameRestriction {
Subroutine _RenameRestriction: not called CC=4 SCAR=30.0
1167 0 my $self = shift;
1168 0 my %args = (
1169 RESTRICTIONS => undef,
1170 OLD => "main",
1171 NEW => undef,
1172 @_,
1173 );
1174  
1175 0 my %return;
1176 0 for my $key ( keys %{$args{RESTRICTIONS}} ) {
1177 0 my $newkey = $key;
1178 0 $newkey =~ s/^\Q$args{OLD}\E\./$args{NEW}./;
1179 0 my @parts;
1180 0 for my $part ( @{ $args{RESTRICTIONS}{$key} } ) {
1181 0 ▶ if ( ref $part ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $part) { } 0 0 0
1182 0 my %part = %{$part};
1183 0 $part{field} =~ s/^\Q$args{OLD}\E\./$args{NEW}./;
1184 0 $part{value} =~ s/^\Q$args{OLD}\E\./$args{NEW}./;
1185 0 push @parts, \%part;
1186 } else {
1187 0 push @parts, $part;
1188 }
1189 }
1190 0 $return{$newkey} = \@parts;
1191 }
1192 0 return \%return;
1193 }
1194  
1195 0 ▶sub _NormalJoin {
Subroutine _NormalJoin: not called CC=4 SCAR=30.0
1196  
1197 0 my $self = shift;
1198 0 my %args = (
1199 SearchBuilder => undef,
1200 TYPE => 'normal',
1201 FIELD1 => undef,
1202 ALIAS1 => undef,
1203 TABLE2 => undef,
1204 FIELD2 => undef,
1205 ALIAS2 => undef,
1206 @_
1207 );
1208  
1209 0 my $sb = $args{'SearchBuilder'};
1210  
1211 0 ▶ if ( $args{'TYPE'} =~ /LEFT/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'TYPE'} =~ /LEFT/i) { } 0 0 0
1212 0 my $alias = $sb->_GetAlias( $args{'TABLE2'} );
1213 0 ▶ my $meta = $sb->{'left_joins'}{"$alias"} ||= {};
Condition0%0/2
$sb->{"left_joins"}{"$alias"} ||= {}
l!l
00
MC/DC0%0/1
$sb->{"left_joins"}{"$alias"} ||= {}
$sb->{"left_joins"}{"$alias"}
Truth table0%0/2
A
A= $sb->{"left_joins"}{"$alias"}
Aresult
11
00
1214 0 ▶ $args{TABLE2} = $self->QuoteName($args{TABLE2}) if $self->QuoteTableNames;
Branch: 1 branch
BranchTrueFalseTotal
if $self->QuoteTableNames 0 0 0
1215 0 $meta->{'alias_string'} = " LEFT JOIN $args{'TABLE2'} $alias ";
1216 0 $meta->{'depends_on'} = $args{'ALIAS1'};
1217 0 $meta->{'type'} = 'LEFT';
1218 0 $meta->{'criteria'}{'base_criterion'} = [ {
1219 field => "$args{'ALIAS1'}.$args{'FIELD1'}",
1220 op => '=',
1221 value => "$alias.$args{'FIELD2'}",
1222 } ];
1223  
1224 0 return ($alias);
1225 }
1226 else {
1227 $sb->DBIx::SearchBuilder::Limit(
1228 ENTRYAGGREGATOR => 'AND',
1229 QUOTEVALUE => 0,
1230 ALIAS => $args{'ALIAS1'},
1231 FIELD => $args{'FIELD1'},
1232 0 VALUE => $args{'ALIAS2'} . "." . $args{'FIELD2'},
1233 @_
1234 );
1235 }
1236 }
1237  
1238 # this code is all hacky and evil. but people desperately want _something_ and I'm
1239 # super tired. refactoring gratefully appreciated.
1240  
1241 318 ▶sub _BuildJoins {
Subroutine _BuildJoins: called CC=9 SCAR=22.0
1242 318 my $self = shift;
1243 318 my $sb = shift;
1244  
1245 318 $self->OptimizeJoins( SearchBuilder => $sb );
1246 318 ▶ my $table = $self->{'QuoteTableNames'} ? $self->QuoteName($sb->Table) : $sb->Table;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'QuoteTableNames'} ? : 0 318 318
1247  
1248 318 my $join_clause = join " CROSS JOIN ", ("$table main"), @{ $sb->{'aliases'} };
1249 318 my %processed = map { /^\S+\s+(\S+)$/; $1 => 1 } @{ $sb->{'aliases'} };
1250 318 $processed{'main'} = 1;
1251  
1252 # get a @list of joins that have not been processed yet, but depend on processed join
1253 318 my $joins = $sb->{'left_joins'};
1254 318 ▶ while ( my @list =
Branch: 1 branch
BranchTrueFalseTotal
if (my(@list) = grep((!$processed{$_} && (!$joins->{$_}{"depends_on"} || $processed{$joins->{$_}{"depends_on"}})), sort(keys %$joins))) 172 318 490
Condition83%5/6
!$processed{$_} && (!$joins->{$_}{'depends_on'} || $processed{$joins->{$_}{'depends_on'}})
!ll&&!rl&&r
18715172
not $joins->{$_}{"depends_on"} or $processed{$joins->{$_}{"depends_on"}}
l!l&&r!l&&!r
017215
MC/DC66%2/3
!$processed{$_} && (!$joins->{$_}{'depends_on'} || $processed{$joins->{$_}{'depends_on'}})
!$processed{$_} not $joins->{$_}{"depends_on"} $processed{$joins->{$_}{"depends_on"}}
Truth table75%3/4
not(A) && not(B) or C
A= !$processed{$_}B= not $joins->{$_}{"depends_on"}C= $processed{$joins->{$_}{"depends_on"}}
ABCresult
0XX0
1000
11X1
1011
1255 grep !$processed{ $_ }
1256 && (!$joins->{ $_ }{'depends_on'} || $processed{ $joins->{ $_ }{'depends_on'} }),
1257 sort keys %$joins
1258 ) {
1259 172 foreach my $join ( @list ) {
1260 172 $processed{ $join }++;
1261  
1262 172 my $meta = $joins->{ $join };
1263 172 ▶ my $aggregator = $meta->{'entry_aggregator'} || 'AND';
Condition100%2/2
$meta->{'entry_aggregator'} || 'AND'
l!l
9163
MC/DC100%1/1
$meta->{'entry_aggregator'} || 'AND'
$meta->{'entry_aggregator'}
Truth table100%2/2
A
A= $meta->{'entry_aggregator'}
Aresult
11
00
1264  
1265 172 $join_clause .= $meta->{'alias_string'} . " ON ";
1266 my @tmp = map {
1267 ref($_)?
1268 724 ▶ $_->{'field'} .' '. $_->{'op'} .' '. $_->{'value'}:
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 181 543 724
1269 $_
1270 }
1271 172 map { ('(', @$_, ')', $aggregator) } sorted_values($meta->{'criteria'});
1272 172 pop @tmp;
1273 172 $join_clause .= join ' ', @tmp;
1274 }
1275 }
1276  
1277 # here we could check if there is recursion in joins by checking that all joins
1278 # are processed
1279 318 ▶ if ( my @not_processed = grep !$processed{ $_ }, keys %$joins ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@not_processed) = grep((!$processed{$_}), keys %$joins)) 0 318 318
1280 0 die "Unsatisfied dependency chain in joins @not_processed";
1281 }
1282 318 return $join_clause;
1283 }
1284  
1285 318 ▶sub OptimizeJoins {
Subroutine OptimizeJoins: called CC=7 SCAR=19.5
Pod undocumented
1286 318 my $self = shift;
1287 318 my %args = (SearchBuilder => undef, @_);
1288 318 my $joins = $args{'SearchBuilder'}->{'left_joins'};
1289  
1290 318 my %processed = map { /^\S+\s+(\S+)$/; $1 => 1 } @{ $args{'SearchBuilder'}->{'aliases'} };
1291 318 $processed{ $_ }++ foreach grep $joins->{ $_ }{'type'} ne 'LEFT', keys %$joins;
1292 318 $processed{'main'}++;
1293  
1294 318 my @ordered;
1295 # get a @list of joins that have not been processed yet, but depend on processed join
1296 # if we are talking about forest then we'll get the second level of the forest,
1297 # but we should process nodes on this level at the end, so we build FILO ordered list.
1298 # finally we'll get ordered list with leafes in the beginning and top most nodes at
1299 # the end.
1300 318 ▶ while ( my @list = grep !$processed{ $_ }
Branch: 1 branch
BranchTrueFalseTotal
if (my(@list) = grep((!$processed{$_} && $processed{$joins->{$_}{"depends_on"}}), sort(keys %$joins))) 66 318 384
Condition100%3/3
!$processed{$_} && $processed{$joins->{$_}{'depends_on'}}
!ll&&!rl&&r
173166
MC/DC100%2/2
!$processed{$_} && $processed{$joins->{$_}{'depends_on'}}
!$processed{$_} $processed{$joins->{$_}{'depends_on'}}
Truth table100%3/3
not(A) && B
A= !$processed{$_}B= $processed{$joins->{$_}{'depends_on'}}
ABresult
0X0
100
111
1301 && $processed{ $joins->{ $_ }{'depends_on'} }, sort keys %$joins )
1302 {
1303 66 unshift @ordered, @list;
1304 66 $processed{ $_ }++ foreach @list;
1305 }
1306  
1307 318 foreach my $join ( @ordered ) {
1308 66 ▶ next if $self->MayBeNull( SearchBuilder => $args{'SearchBuilder'}, ALIAS => $join );
Branch: 1 branch
BranchTrueFalseTotal
if $self->MayBeNull("SearchBuilder", $args{"SearchBuilder"}, "ALIAS", $join) 63 3 66
1309  
1310 3 $joins->{ $join }{'alias_string'} =~ s/^\s*LEFT\s+/ /;
1311 3 $joins->{ $join }{'type'} = 'NORMAL';
1312 }
1313  
1314 # here we could check if there is recursion in joins by checking that all joins
1315 # are processed
1316  
1317 }
1318  
1319 =head2 MayBeNull
1320  
1321 Takes a C<SearchBuilder> and C<ALIAS> in a hash and resturns
1322 true if restrictions of the query allow NULLs in a table joined with
1323 the ALIAS, otherwise returns false value which means that you can
1324 use normal join instead of left for the aliased table.
1325  
1326 Works only for queries have been built with L<DBIx::SearchBuilder/Join> and
1327 L<DBIx::SearchBuilder/Limit> methods, for other cases return true value to
1328 avoid fault optimizations.
1329  
1330 =cut
1331  
1332 66 ▶sub MayBeNull {
Subroutine MayBeNull: called CC=29 SCAR=39.7
Pod documented
1333 66 my $self = shift;
1334 66 my %args = (SearchBuilder => undef, ALIAS => undef, @_);
1335 # if we have at least one subclause that is not generic then we should get out
1336 # of here as we can't parse subclauses
1337 66 ▶ return 1 if grep $_ ne 'generic_restrictions', keys %{ $args{'SearchBuilder'}->{'subclauses'} };
Branch: 1 branch
BranchTrueFalseTotal
if grep(($_ ne "generic_restrictions"), keys %{$args{"SearchBuilder"}{"subclauses"};}) 0 66 66
1338  
1339 # build full list of generic conditions
1340 66 my @conditions;
1341 66 foreach ( grep @$_, sorted_values($args{'SearchBuilder'}->{'restrictions'}) ) {
1342 10 ▶ push @conditions, 'AND' if @conditions;
Branch: 1 branch
BranchTrueFalseTotal
if @conditions 0 10 10
1343 10 push @conditions, '(', @$_, ')';
1344 }
1345  
1346 # find tables that depends on this alias and add their join conditions
1347 66 foreach my $join ( sorted_values($args{'SearchBuilder'}->{'left_joins'}) ) {
1348 # left joins on the left side so later we'll get 1 AND x expression
1349 # which equal to x, so we just skip it
1350 68 ▶ next if $join->{'type'} eq 'LEFT';
Branch: 1 branch
BranchTrueFalseTotal
if $join->{"type"} eq "LEFT" 67 1 68
1351 1 ▶ next unless $join->{'depends_on'} eq $args{'ALIAS'};
Branch: 1 branch
BranchTrueFalseTotal
unless $join->{"depends_on"} eq $args{"ALIAS"} 0 1 1
1352  
1353 1 my @tmp = map { ('(', @$_, ')', $join->{'entry_aggregator'}) } sorted_values($join->{'criteria'});
1354 1 pop @tmp;
1355  
1356 1 @conditions = ('(', @conditions, ')', 'AND', '(', @tmp ,')');
1357  
1358 }
1359 66 ▶ return 1 unless @conditions;
Branch: 1 branch
BranchTrueFalseTotal
unless @conditions 56 10 66
1360  
1361 # replace conditions with boolean result: 1 - allows nulls, 0 - not
1362 # all restrictions on that don't act on required alias allow nulls
1363 # otherwise only IS NULL operator
1364 10 foreach ( splice @conditions ) {
1365 46 ▶ unless ( ref $_ ) {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $_) { } 13 33 46
if (do { rindex($_->{'field'}, "$args{'ALIAS'}.", 0) == 0 }) { } 9 4 13
elsif ($_->{'value'} and rindex($_->{'value'}, "$args{'ALIAS'}.", 0) == 0) { } 1 3 4
elsif ($_->{'field'} =~ /^(?i:lower)\(\s*\Q$args{'ALIAS'}\.\E/) { } 0 3 3
1366 33 push @conditions, $_;
1367 } elsif ( rindex( $_->{'field'}, "$args{'ALIAS'}.", 0 ) == 0 ) {
1368 # field is alias.xxx op ... and only IS op allows NULLs
1369 9 push @conditions, lc $_->{op} eq 'is';
1370 ▶ } elsif ( $_->{'value'} && rindex( $_->{'value'}, "$args{'ALIAS'}.", 0 ) == 0 ) {
Condition66%2/3
$_->{"value"} and rindex($_->{"value"}, qq[$args{"ALIAS"}.], 0) == 0
!ll&&!rl&&r
031
MC/DC50%1/2
$_->{"value"} and rindex($_->{"value"}, qq[$args{"ALIAS"}.], 0) == 0
$_->{"value"} rindex($_->{"value"}, qq[$args{"ALIAS"}.], 0) == 0
Truth table66%2/3
A and B
A= $_->{"value"}B= rindex($_->{"value"}, qq[$args{"ALIAS"}.], 0) == 0
ABresult
0X0
100
111
1371 # value is alias.xxx so it can not be IS op
1372 1 push @conditions, 0;
1373 } elsif ( $_->{'field'} =~ /^(?i:lower)\(\s*\Q$args{'ALIAS'}\./ ) {
1374 # handle 'LOWER(alias.xxx) OP VALUE' we use for case insensetive
1375 0 push @conditions, lc $_->{op} eq 'is';
1376 } else {
1377 3 push @conditions, 1;
1378 }
1379 }
1380  
1381 # resturns index of closing paren by index of openning paren
1382 0 ▶ my $closing_paren = sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
1383 0 my $i = shift;
1384 0 my $count = 0;
1385 0 ▶ for ( ; $i < @conditions; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @conditions) 0 0 0
1386 0 ▶ if ( $conditions[$i] eq '(' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($conditions[$i] eq '(') { } 0 0 0
elsif ($conditions[$i] eq ')') { } 0 0 0
1387 0 $count++;
1388 }
1389 elsif ( $conditions[$i] eq ')' ) {
1390 0 $count--;
1391 }
1392 0 ▶ return $i unless $count;
Branch: 1 branch
BranchTrueFalseTotal
unless $count 0 0 0
1393 }
1394 0 die "lost in parens";
1395 10 };
1396  
1397 # solve boolean expression we have, an answer is our result
1398 10 my $parens_count = 0;
1399 10 my @tmp = ();
1400 10 ▶ while ( defined ( my $e = shift @conditions ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $e = shift @conditions)) 48 0 48
1401 #print "@tmp >>>$e<<< @conditions\n";
1402 48 ▶ return $e if !@conditions && !@tmp;
Branch: 1 branch
BranchTrueFalseTotal
unless @conditions or @tmp 10 38 48
Condition100%3/3
@conditions or @tmp
l!l&&r!l&&!r
35310
MC/DC100%2/2
@conditions or @tmp
@conditions @tmp
Truth table100%3/3
A or B
A= @conditionsB= @tmp
ABresult
1X1
011
000
1403  
1404 38 ▶ unless ( $e ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($e) { } 35 3 38
if (do { $e eq '1' }) { } 6 29 35
elsif ($e eq '(') { } 23 6 29
elsif ($e eq ')') { } 6 0 6
1405 3 ▶ if ( $conditions[0] eq ')' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($conditions[0] eq ")") 1 2 3
1406 1 push @tmp, $e;
1407 1 next;
1408 }
1409  
1410 2 my $aggreg = uc shift @conditions;
1411 2 ▶ if ( $aggreg eq 'OR' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($aggreg eq 'OR') { } 2 0 2
elsif ($aggreg eq 'AND') { } 0 0 0
1412 # 0 OR x == x
1413 2 next;
1414 } elsif ( $aggreg eq 'AND' ) {
1415 # 0 AND x == 0
1416 0 my $close_p = $closing_paren->(0);
1417 0 splice @conditions, 0, $close_p + 1, (0);
1418 } else {
1419 0 die "unknown aggregator: @tmp $e >>>$aggreg<<< @conditions";
1420 }
1421 } elsif ( $e eq '1' ) {
1422 6 ▶ if ( $conditions[0] eq ')' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($conditions[0] eq ")") 5 1 6
1423 5 push @tmp, $e;
1424 5 next;
1425 }
1426  
1427 1 my $aggreg = uc shift @conditions;
1428 1 ▶ if ( $aggreg eq 'OR' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($aggreg eq 'OR') { } 0 1 1
elsif ($aggreg eq 'AND') { } 1 0 1
1429 # 1 OR x == 1
1430 0 my $close_p = $closing_paren->(0);
1431 0 splice @conditions, 0, $close_p + 1, (1);
1432 } elsif ( $aggreg eq 'AND' ) {
1433 # 1 AND x == x
1434 1 next;
1435 } else {
1436 0 die "unknown aggregator: @tmp $e >>>$aggreg<<< @conditions";
1437 }
1438 } elsif ( $e eq '(' ) {
1439 23 ▶ if ( $conditions[1] eq ')' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($conditions[1] eq ')') { } 15 8 23
1440 15 splice @conditions, 1, 1;
1441 } else {
1442 8 $parens_count++;
1443 8 push @tmp, $e;
1444 }
1445 } elsif ( $e eq ')' ) {
1446 6 ▶ die "extra closing paren: @tmp >>>$e<<< @conditions"
Branch: 1 branch
BranchTrueFalseTotal
if --$parens_count < 0 0 6 6
1447 if --$parens_count < 0;
1448  
1449 6 unshift @conditions, @tmp, $e;
1450 6 @tmp = ();
1451 } else {
1452 0 die "lost: @tmp >>>$e<<< @conditions";
1453 }
1454 }
1455 0 return 1;
1456 }
1457  
1458 # Returns true if a DISTINCT search should use GROUP BY instead of
1459 # SELECT DISTINCT, i.e. when ORDER BY uses another alias or a column not
1460 # in the select list.
1461 111 ▶sub _DistinctNeedsGroupBy {
Subroutine _DistinctNeedsGroupBy: called CC=12 SCAR=24.9
1462 111 my $self = shift;
1463 111 my $sb = shift;
1464  
1465 # Other aliases may have several values per main row, needing MIN/MAX
1466 111 ▶ return 1 if $sb->_OrderClause =~ /(?<!main)\./;
Branch: 1 branch
BranchTrueFalseTotal
if $sb->_OrderClause =~ /(?<!main)\./ 32 79 111
1467  
1468 79 my $columns = $sb->_ColumnsForQuery;
1469 79 ▶ return 0 if $columns =~ /(?:^|,)\s*main\.\*/;
Branch: 1 branch
BranchTrueFalseTotal
if $columns =~ /(?:^|,)\s*main\.\*/ 69 10 79
1470  
1471 # GROUP BY main.id doesn't work with columns of other aliases
1472 10 ▶ return 0 if $columns =~ /(?<!main)\./;
Branch: 1 branch
BranchTrueFalseTotal
if $columns =~ /(?<!main)\./ 3 7 10
1473  
1474 7 ▶ for my $row ( @{ $sb->{'order_by'} || [] } ) {
Condition50%1/2
$sb->{'order_by'} || []
l!l
70
MC/DC0%0/1
$sb->{'order_by'} || []
$sb->{'order_by'}
Truth table50%1/2
A
A= $sb->{'order_by'}
Aresult
11
00
1475 8 ▶ next unless $row->{'FIELD'};
Branch: 1 branch
BranchTrueFalseTotal
unless $row->{"FIELD"} 0 8 8
1476 8 ▶ next if $self->_DistinctOrderIsBareName($row);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_DistinctOrderIsBareName($row) 1 7 8
1477 7 ▶ return 1 if ( $row->{'ALIAS'} // 'main' ) ne 'main';
Branch: 1 branch
BranchTrueFalseTotal
if ($row->{"ALIAS"} // "main") ne "main" 1 6 7
Condition100%2/2
$row->{"ALIAS"} // "main"
l!l
25
MC/DC100%1/1
$row->{"ALIAS"} // "main"
$row->{"ALIAS"}
Truth table100%2/2
A
A= $row->{"ALIAS"}
Aresult
11
00
1478 6 ▶ return 1 if $row->{'FIELD'} !~ /^\w+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $row->{"FIELD"} =~ /^\w+$/ 1 5 6
1479 5 ▶ return 1 unless $columns =~ /(?:^|,)\s*main\.\Q$row->{'FIELD'}\E\b/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $columns =~ /(?:^|,)\s*main\.\Q$row->{"FIELD"}\E\b/i 4 1 5
1480 }
1481 1 return 0;
1482 }
1483  
1484 # Returns true if an order row with an empty ALIAS is a bare name from
1485 # the select list, such as lname for "LOWER(main.Name) AS lname". Order by
1486 # it as it is.
1487 8 ▶sub _DistinctOrderIsBareName {
Subroutine _DistinctOrderIsBareName: called CC=4 SCAR=13.9
1488 8 my $self = shift;
1489 8 my $row = shift;
1490  
1491 return
1492 defined $row->{'ALIAS'}
1493 && $row->{'ALIAS'} eq ''
1494 8 ▶ && ( $row->{'FIELD'} // '' ) =~ /^\w+$/;
Condition87%7/8
defined $row->{'ALIAS'} && $row->{'ALIAS'} eq '' && ($row->{'FIELD'} // '') =~ /^\w+$/
!ll&&!rl&&r
611
defined $row->{"ALIAS"} and $row->{"ALIAS"} eq ""
!ll&&!rl&&r
512
$row->{"FIELD"} // ""
l!l
20
MC/DC66%2/3
defined $row->{'ALIAS'} && $row->{'ALIAS'} eq '' && ($row->{'FIELD'} // '') =~ /^\w+$/
defined $row->{"ALIAS"} $row->{"ALIAS"} eq "" $row->{"FIELD"}
Truth table75%3/4
A and B && C
A= defined $row->{"ALIAS"}B= $row->{"ALIAS"} eq ""C= $row->{"FIELD"}
ABCresult
0XX0
10X0
1100
1111
1495 }
1496  
1497 # Returns the order rows for the GROUP BY form, with columns of other
1498 # aliases wrapped in MIN() or MAX().
1499 38 ▶sub _DistinctGroupByOrder {
Subroutine _DistinctGroupByOrder: called CC=6 SCAR=18.0
1500 38 my $self = shift;
1501 38 my $sb = shift;
1502  
1503 return [
1504 map {
1505 44 ▶ my $function = ( $_->{'ORDER'} || '' ) =~ /^des/i ? 'MAX' : 'MIN';
Branch: 1 branch
BranchTrueFalseTotal
($_->{'ORDER'} || '') =~ /^des/i ? : 21 23 44
Condition50%1/2
$_->{'ORDER'} || ''
l!l
440
MC/DC0%0/1
$_->{'ORDER'} || ''
$_->{'ORDER'}
Truth table50%1/2
A
A= $_->{'ORDER'}
Aresult
11
00
1506 44 ▶ ( $_->{'ALIAS'} // 'main' ) eq 'main'
Branch: 1 branch
BranchTrueFalseTotal
($_->{'ALIAS'} // 'main') eq 'main' ? : 11 33 44
Condition100%2/2
$_->{"ALIAS"} // "main"
l!l
3410
MC/DC100%1/1
$_->{"ALIAS"} // "main"
$_->{"ALIAS"}
Truth table100%2/2
A
A= $_->{"ALIAS"}
Aresult
11
00
1507 ? $_
1508 : { %$_, FIELD => "$function($_->{'FIELD'})" }
1509 38 ▶ } @{ $sb->{'order_by'} || [] }
Condition50%1/2
$sb->{'order_by'} || []
l!l
380
MC/DC0%0/1
$sb->{'order_by'} || []
$sb->{'order_by'}
Truth table50%1/2
A
A= $sb->{'order_by'}
Aresult
11
00
1510 ];
1511 }
1512  
1513 =head2 DistinctQuery STATEMENTREF
1514  
1515 takes an incomplete SQL SELECT statement and massages it to return a DISTINCT result set.
1516  
1517  
1518 =cut
1519  
1520 73 ▶sub DistinctQuery {
Subroutine DistinctQuery: called CC=3 SCAR=11.0
Pod documented
1521 73 my $self = shift;
1522 73 my $statementref = shift;
1523 73 my $sb = shift;
1524 73 my %args = (
1525 Wrap => 0,
1526 @_
1527 );
1528  
1529 73 my $QueryHint = $sb->QueryHint;
1530 73 ▶ $QueryHint = $QueryHint ? " /* $QueryHint */ " : " ";
Branch: 1 branch
BranchTrueFalseTotal
$QueryHint ? : 0 73 73
1531  
1532 # Prepend select query for DBs which allow DISTINCT on all column types.
1533 73 $$statementref = "SELECT" . $QueryHint . "DISTINCT main.* FROM $$statementref";
1534 73 $$statementref .= $sb->_GroupClause;
1535 73 ▶ if ( $args{'Wrap'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"Wrap"}) 26 47 73
1536 26 $$statementref = "SELECT * FROM ($$statementref) main";
1537 }
1538 73 $$statementref .= $sb->_OrderClause;
1539 }
1540  
1541 =head2 DistinctQueryAndCount STATEMENTREF
1542  
1543 takes an incomplete SQL SELECT statement and massages it to return a
1544 DISTINCT result set and the total count of potential records.
1545  
1546 =cut
1547  
1548 43 ▶sub DistinctQueryAndCount {
Subroutine DistinctQueryAndCount: called CC=1 SCAR=0.0
Pod documented
1549 43 my $self = shift;
1550 43 my $statementref = shift;
1551 43 my $sb = shift;
1552  
1553 # order by clause should be on outer most query
1554 # SQL standard: ORDER BY command cannot be used in a Subquery
1555 # mariadb explanation: https://mariadb.com/kb/en/why-is-order-by-in-a-from-subquery-ignored/
1556 # pg: actually keeps order of a subquery as long as some conditions in outer query are met, but
1557 # it's just a coincidence, not a feature
1558 # SQL server: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver16
1559 # The ORDER BY clause is not valid in views, ... and *subqueries*, unless ...
1560  
1561 43 my $order = $sb->_OrderClause;
1562 43 my $wrap = $order !~ /(?<!main)\./;
1563  
1564 43 $self->DistinctQuery($statementref, $sb, Wrap => $wrap);
1565  
1566 # DistinctQuery already has an outer SELECT, which we can reuse
1567 43 $$statementref =~ s!(?= FROM)!, COUNT(main.id) OVER() AS search_builder_count_all!;
1568 }
1569  
1570  
1571  
1572 =head2 DistinctCount STATEMENTREF
1573  
1574 takes an incomplete SQL SELECT statement and massages it to return a DISTINCT result set.
1575  
1576  
1577 =cut
1578  
1579 0 ▶sub DistinctCount {
Subroutine DistinctCount: not called CC=2 SCAR=17.9
Pod documented
1580 0 my $self = shift;
1581 0 my $statementref = shift;
1582 0 my $sb = shift;
1583  
1584 0 my $QueryHint = $sb->QueryHint;
1585 0 ▶ $QueryHint = $QueryHint ? " /* $QueryHint */ " : " ";
Branch: 1 branch
BranchTrueFalseTotal
$QueryHint ? : 0 0 0
1586  
1587 # Prepend select query for DBs which allow DISTINCT on all column types.
1588 0 $$statementref = "SELECT" . $QueryHint . "COUNT(DISTINCT main.id) FROM $$statementref";
1589  
1590 }
1591  
1592 0 ▶sub Fields {
Subroutine Fields: not called CC=4 SCAR=30.0
Pod undocumented
1593 0 my $self = shift;
1594 0 my $table = lc shift;
1595  
1596 0 ▶ unless ( $FIELDS_IN_TABLE{$table} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($DBIx::SearchBuilder::Handle::FIELDS_IN_TABLE{$table}) 0 0 0
1597 0 $FIELDS_IN_TABLE{ $table } = [];
1598 0 ▶ my $sth = $self->dbh->column_info( undef, '', $table, '%' )
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->dbh->column_info(undef, "", $table, "%") or return () 0 0 0
1599 or return ();
1600 0 my $info = $sth->fetchall_arrayref({});
1601 0 foreach my $e ( @$info ) {
1602 0 push @{ $FIELDS_IN_TABLE{ $table } }, $e->{'COLUMN_NAME'};
1603 }
1604 }
1605  
1606 0 return @{ $FIELDS_IN_TABLE{ $table } };
1607 }
1608  
1609  
1610 =head2 Log MESSAGE
1611  
1612 Takes a single argument, a message to log.
1613  
1614 Currently prints that message to STDERR
1615  
1616 =cut
1617  
1618 0 ▶sub Log {
Subroutine Log: not called CC=1 SCAR=6.9
Pod documented
1619 0 my $self = shift;
1620 0 my $msg = shift;
1621 0 warn $msg."\n";
1622 }
1623  
1624 =head2 SimpleDateTimeFunctions
1625  
1626 See L</DateTimeFunction> for details on supported functions.
1627 This method is for implementers of custom DB connectors.
1628  
1629 Returns hash reference with (function name, sql template) pairs.
1630  
1631 =cut
1632  
1633 1 ▶sub SimpleDateTimeFunctions {
Subroutine SimpleDateTimeFunctions: called CC=1 SCAR=0.0
Pod documented
1634 1 my $self = shift;
1635 return {
1636 1 datetime => 'SUBSTR(?, 1, 19)',
1637 time => 'SUBSTR(?, 12, 8)',
1638  
1639 hourly => 'SUBSTR(?, 1, 13)',
1640 hour => 'SUBSTR(?, 12, 2 )',
1641  
1642 date => 'SUBSTR(?, 1, 10)',
1643 daily => 'SUBSTR(?, 1, 10)',
1644  
1645 day => 'SUBSTR(?, 9, 2 )',
1646 dayofmonth => 'SUBSTR(?, 9, 2 )',
1647  
1648 monthly => 'SUBSTR(?, 1, 7 )',
1649 month => 'SUBSTR(?, 6, 2 )',
1650  
1651 annually => 'SUBSTR(?, 1, 4 )',
1652 year => 'SUBSTR(?, 1, 4 )',
1653 };
1654 }
1655  
1656 =head2 DateTimeFunction
1657  
1658 Takes named arguments:
1659  
1660 =over 4
1661  
1662 =item * Field - SQL expression date/time function should be applied
1663 to. Note that this argument is used as is without any kind of quoting.
1664  
1665 =item * Type - name of the function, see supported values below.
1666  
1667 =item * Timezone - optional hash reference with From and To values,
1668 see L</ConvertTimezoneFunction> for details.
1669  
1670 =back
1671  
1672 Returns SQL statement. Returns NULL if function is not supported.
1673  
1674 =head3 Supported functions
1675  
1676 Type value in L</DateTimeFunction> is case insesitive. Spaces,
1677 underscores and dashes are ignored. So 'date time', 'DateTime'
1678 and 'date_time' are all synonyms. The following functions are
1679 supported:
1680  
1681 =over 4
1682  
1683 =item * date time - as is, no conversion, except applying timezone
1684 conversion if it's provided.
1685  
1686 =item * time - time only
1687  
1688 =item * hourly - datetime prefix up to the hours, e.g. '2010-03-25 16'
1689  
1690 =item * hour - hour, 0 - 23
1691  
1692 =item * date - date only
1693  
1694 =item * daily - synonym for date
1695  
1696 =item * day of week - 0 - 6, 0 - Sunday
1697  
1698 =item * day - day of month, 1 - 31
1699  
1700 =item * day of month - synonym for day
1701  
1702 =item * day of year - 1 - 366, support is database dependent
1703  
1704 =item * month - 1 - 12
1705  
1706 =item * monthly - year and month prefix, e.g. '2010-11'
1707  
1708 =item * year - e.g. '2023'
1709  
1710 =item * annually - synonym for year
1711  
1712 =item * week of year - 0-53, presence of zero week, 1st week meaning
1713 and whether week starts on Monday or Sunday heavily depends on database.
1714  
1715 =back
1716  
1717 =cut
1718  
1719 20 ▶sub DateTimeFunction {
Subroutine DateTimeFunction: called CC=4 SCAR=14.2
Pod documented
1720 20 my $self = shift;
1721 20 my %args = (
1722 Field => undef,
1723 Type => '',
1724 Timezone => undef,
1725 @_
1726 );
1727  
1728 20 ▶ my $res = $args{'Field'} || '?';
Condition50%1/2
$args{'Field'} || '?'
l!l
020
MC/DC0%0/1
$args{'Field'} || '?'
$args{'Field'}
Truth table50%1/2
A
A= $args{'Field'}
Aresult
11
00
1729 20 ▶ if ( $args{'Timezone'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"Timezone"}) 0 20 20
1730 $res = $self->ConvertTimezoneFunction(
1731 0 %{ $args{'Timezone'} },
1732 Field => $res,
1733 );
1734 }
1735  
1736 20 my $norm_type = lc $args{'Type'};
1737 20 $norm_type =~ s/[ _-]//g;
1738 20 ▶ if ( my $template = $self->SimpleDateTimeFunctions->{ $norm_type } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $template = $self->SimpleDateTimeFunctions->{$norm_type}) { } 18 2 20
1739 18 $template =~ s/\?/$res/;
1740 18 $res = $template;
1741 }
1742 else {
1743 2 return 'NULL';
1744 }
1745 18 return $res;
1746 }
1747  
1748 =head2 ConvertTimezoneFunction
1749  
1750 Generates a function applied to Field argument that converts timezone.
1751 By default converts from UTC. Examples:
1752  
1753 # UTC => Moscow
1754 $handle->ConvertTimezoneFunction( Field => '?', To => 'Europe/Moscow');
1755  
1756 If there is problem with arguments or timezones are equal
1757 then Field returned without any function applied. Field argument
1758 is not escaped in any way, it's your job.
1759  
1760 Implementation is very database specific. To be portable convert
1761 from UTC or to UTC. Some databases have internal storage for
1762 information about timezones that should be kept up to date.
1763 Read documentation for your DB.
1764  
1765 =cut
1766  
1767 0 ▶sub ConvertTimezoneFunction {
Subroutine ConvertTimezoneFunction: not called CC=1 SCAR=6.9
Pod documented
1768 0 my $self = shift;
1769 0 my %args = (
1770 From => 'UTC',
1771 To => undef,
1772 Field => '',
1773 @_
1774 );
1775 0 return $args{'Field'};
1776 }
1777  
1778 =head2 DateTimeIntervalFunction
1779  
1780 Generates a function to calculate interval in seconds between two
1781 dates. Takes From and To arguments which can be either scalar or
1782 a hash. Hash is processed with L<DBIx::SearchBuilder/CombineFunctionWithField>.
1783  
1784 Arguments are not quoted or escaped in any way. It's caller's job.
1785  
1786 =cut
1787  
1788 2 ▶sub DateTimeIntervalFunction {
Subroutine DateTimeIntervalFunction: called CC=2 SCAR=6.9
Pod documented
1789 2 my $self = shift;
1790 2 my %args = ( From => undef, To => undef, @_ );
1791  
1792 $_ = DBIx::SearchBuilder->CombineFunctionWithField(%$_)
1793 2 for grep ref, @args{'From', 'To'};
1794  
1795 2 return $self->_DateTimeIntervalFunction( %args );
1796 }
1797  
1798 0 ▶sub _DateTimeIntervalFunction { return 'NULL' }
Subroutine _DateTimeIntervalFunction: not called CC=1 SCAR=6.9
1799  
1800 =head2 NullsOrder
1801  
1802 Sets order of NULLs when sorting columns when called with mode,
1803 but only if DB supports it. Modes:
1804  
1805 =over 4
1806  
1807 =item * small
1808  
1809 NULLs are smaller then anything else, so come first when order
1810 is ASC and last otherwise.
1811  
1812 =item * large
1813  
1814 NULLs are larger then anything else.
1815  
1816 =item * first
1817  
1818 NULLs are always first.
1819  
1820 =item * last
1821  
1822 NULLs are always last.
1823  
1824 =item * default
1825  
1826 Return back to DB's default behaviour.
1827  
1828 =back
1829  
1830 When called without argument returns metadata required to generate
1831 SQL.
1832  
1833 =cut
1834  
1835 396 ▶sub NullsOrder {
Subroutine NullsOrder: called CC=11 SCAR=43.9
Pod documented
1836 396 my $self = shift;
1837  
1838 396 ▶ unless ($self->HasSupportForNullsOrder) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->HasSupportForNullsOrder) 396 0 396
1839 396 ▶ warn "No support for changing NULLs order" if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 396 396
1840 396 return undef;
1841 }
1842  
1843 0 ▶ if ( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 0 0
1844 0 ▶ my $mode = shift || 'default';
Condition0%0/2
shift() || 'default'
l!l
00
MC/DC0%0/1
shift() || 'default'
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1845 0 ▶ if ( $mode eq 'default' ) {
Branch: 5 branches
BranchTrueFalseTotal
if ($mode eq 'default') { } 0 0 0
elsif ($mode eq 'small') { } 0 0 0
elsif ($mode eq 'large') { } 0 0 0
elsif ($mode eq 'first') { } 0 0 0
elsif ($mode eq 'last') { } 0 0 0
1846 0 delete $self->{'nulls_order'};
1847 }
1848 elsif ( $mode eq 'small' ) {
1849 0 $self->{'nulls_order'} = { ASC => 'NULLS FIRST', DESC => 'NULLS LAST' };
1850 }
1851 elsif ( $mode eq 'large' ) {
1852 0 $self->{'nulls_order'} = { ASC => 'NULLS LAST', DESC => 'NULLS FIRST' };
1853 }
1854 elsif ( $mode eq 'first' ) {
1855 0 $self->{'nulls_order'} = { ASC => 'NULLS FIRST', DESC => 'NULLS FIRST' };
1856 }
1857 elsif ( $mode eq 'last' ) {
1858 0 $self->{'nulls_order'} = { ASC => 'NULLS LAST', DESC => 'NULLS LAST' };
1859 }
1860 else {
1861 0 warn "'$mode' is not supported NULLs ordering mode";
1862 0 delete $self->{'nulls_order'};
1863 }
1864 }
1865  
1866 0 ▶ return undef unless $self->{'nulls_order'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"nulls_order"} 0 0 0
1867 0 return $self->{'nulls_order'};
1868 }
1869  
1870 =head2 HasSupportForNullsOrder
1871  
1872 Returns true value if DB supports adjusting NULLs order while sorting
1873 a column, for example C<ORDER BY Value ASC NULLS FIRST>.
1874  
1875 =cut
1876  
1877 397 ▶sub HasSupportForNullsOrder {
Subroutine HasSupportForNullsOrder: called CC=1 SCAR=0.0
Pod documented
1878 397 return 0;
1879 }
1880  
1881 =head2 HasSupportForCombineSearchAndCount
1882  
1883 Returns true value if DB supports to combine search and count in single
1884 query.
1885  
1886 =cut
1887  
1888 88 ▶sub HasSupportForCombineSearchAndCount {
Subroutine HasSupportForCombineSearchAndCount: called CC=1 SCAR=0.0
Pod documented
1889 88 return 1;
1890 }
1891  
1892 =head2 HasSupportForEmptyString
1893  
1894 Returns true value if DB supports empty string.
1895  
1896 =cut
1897  
1898 0 ▶sub HasSupportForEmptyString {
Subroutine HasSupportForEmptyString: not called CC=1 SCAR=6.9
Pod documented
1899 0 return 1;
1900 }
1901  
1902 =head2 QuoteName
1903  
1904 Quote table or column name to avoid reserved word errors.
1905  
1906 Returns same value passed unless over-ridden in database-specific subclass.
1907  
1908 =cut
1909  
1910 # over-ride in subclass
1911 0 ▶sub QuoteName {
Subroutine QuoteName: not called CC=2 SCAR=17.9
Pod documented
1912 0 my ($self, $name) = @_;
1913 # use dbi built in quoting if we have a connection,
1914 0 ▶ if ($self->dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dbh) 0 0 0
1915 0 return $self->dbh->quote_identifier($name);
1916 }
1917 0 warn "QuoteName called without a db handle";
1918 0 return $name;
1919 }
1920  
1921 =head2 DequoteName
1922  
1923 Undo the effects of QuoteName by removing quoting.
1924  
1925 =cut
1926  
1927 0 ▶sub DequoteName {
Subroutine DequoteName: not called CC=4 SCAR=30.0
Pod documented
1928 0 my ($self, $name) = @_;
1929 0 ▶ if ($self->dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dbh) 0 0 0
1930 # 29 = SQL_IDENTIFIER_QUOTE_CHAR; see "perldoc DBI"
1931 0 my $quote_char = $self->dbh->get_info( 29 );
1932  
1933 0 ▶ if ($quote_char) {
Branch: 1 branch
BranchTrueFalseTotal
if ($quote_char) 0 0 0
1934 0 ▶ if ($name =~ /^$quote_char(.*)$quote_char$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /^$quote_char(.*)$quote_char$/) 0 0 0
1935 0 return $1;
1936 }
1937 }
1938 0 return $name;
1939 }
1940 0 warn "DequoteName called without a db handle";
1941 0 return $name;
1942 }
1943  
1944 =head2 $MAX_BIND_PARAMS
1945  
1946 Maximum number of bind parameters allowed when converting a query from
1947 literal values to placeholders. Defaults to 65,535 (the MySQL limit).
1948 If a query would require more placeholders than this value, the query is
1949 left as-is with literal values and no bind parameters are extracted.
1950  
1951 You can override this in driver subclasses or in tests to accommodate
1952 databases with different limits:
1953  
1954 local $DBIx::SearchBuilder::Handle::MAX_BIND_PARAMS = 32_767;
1955  
1956 =cut
1957  
1958 26 our $MAX_BIND_PARAMS = 65_535;
1959  
1960 36 ▶sub _ExtractBindValues {
Subroutine _ExtractBindValues: called CC=9 SCAR=22.3
1961 36 my ( $self, $string, $default_escape_char ) = @_;
1962 36 ▶ return unless defined $$string;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$string 0 36 36
1963  
1964 # A single regex used both for pre-counting and for substitution,
1965 # so that both passes always match the same tokens.
1966 36 state $token_re = qr{
1967 (?: e? ' (?: \\. | '' | [^'] )* ' ) # quoted string
1968 |
1969 (?: \b \d* \.? \d+ \b ) # number, but not the one in Groups_1.Name
1970 }isx;
1971 36 state $special_chars = {
1972 'b' => "\b",
1973 'f' => "\f",
1974 'n' => "\n",
1975 'r' => "\r",
1976 't' => "\t",
1977 };
1978  
1979 36 my $count = 0;
1980 36 ▶ while ( $$string =~ m!$token_re!g ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$string =~ /$token_re/g) 57 33 90
1981 # If the query has too many literals, leave it as-is. The caller
1982 # will still set _bind_values to [] (an empty-but-truthy arrayref),
1983 # so ApplyLimits can still bind its own LIMIT/OFFSET placeholders
1984 # against the unmodified query string.
1985 57 ▶ return if ++$count > $MAX_BIND_PARAMS;
Branch: 1 branch
BranchTrueFalseTotal
if ++$count > $DBIx::SearchBuilder::Handle::MAX_BIND_PARAMS 3 54 57
1986 }
1987  
1988 33 ▶ $default_escape_char ||= q{'};
Condition50%1/2
$default_escape_char ||= "'"
l!l
033
MC/DC0%0/1
$default_escape_char ||= "'"
$default_escape_char
Truth table50%1/2
A
A= $default_escape_char
Aresult
11
00
1989  
1990 33 my @values;
1991  
1992 33 $$string =~ s{($token_re)}{
1993 51 my $match = $1;
1994 51 ▶ if ( $match =~ /^(e?)'(.*)'$/si ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($match =~ /^(e?)'(.*)'$/is) { } 51 0 51
1995 51 my $e_notion = $1;
1996 51 my $value = $2;
1997 51 ▶ if ( $e_notion || $default_escape_char eq '\\' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($e_notion or $default_escape_char eq "\\") 1 50 51
Condition66%2/3
$e_notion or $default_escape_char eq "\\"
l!l&&r!l&&!r
1050
MC/DC50%1/2
$e_notion or $default_escape_char eq "\\"
$e_notion $default_escape_char eq "\\"
Truth table66%2/3
A or B
A= $e_notionB= $default_escape_char eq "\\"
ABresult
1X1
011
000
1998 # For unrecognised escapes (e.g. \q), strip the backslash
1999 # and keep the literal character — the correct behaviour
2000 # for SQL E-notation strings.
2001 1 ▶ $value =~ s!\\(.)!$special_chars->{$1} || $1!sgei;
Condition66%2/3
$special_chars->{$1} || $1
l!l&&r!l&&!r
110
MC/DC0%0/2
$special_chars->{$1} || $1
$special_chars->{$1} $1
Truth table66%2/3
A || B
A= $special_chars->{$1}B= $1
ABresult
1X1
011
000
2002 }
2003 51 $value =~ s!''!'!g;
2004 51 push @values, $value;
2005 }
2006 else {
2007 0 push @values, $match;
2008 }
2009 51 '?';
2010 }eg;
2011  
2012 33 return @values;
2013 }
2014  
2015 22 ▶sub _RequireQuotedTables { return 0 };
Subroutine _RequireQuotedTables: called CC=1 SCAR=0.0
2016  
2017 =head2 DESTROY
2018  
2019 When we get rid of the Searchbuilder::Handle, we need to disconnect from the database
2020  
2021 =cut
2022  
2023 23 ▶sub DESTROY {
Subroutine DESTROY: called CC=2 SCAR=7.1
2024 23 my $self = shift;
2025 23 ▶ $self->Disconnect if $self->{'DisconnectHandleOnDestroy'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"DisconnectHandleOnDestroy"} 0 23 23
2026 23 delete $DBIHandle{$self};
2027 }
2028  
2029 =head2 CastAsDecimal FIELD
2030  
2031 Cast the given field as decimal.
2032  
2033 E.g. on Pg, it's C<CAST(Content AS DECIMAL)>.
2034  
2035 =cut
2036  
2037 1 ▶sub CastAsDecimal {
Subroutine CastAsDecimal: called CC=2 SCAR=7.1
Pod documented
2038 1 my $self = shift;
2039 1 ▶ my $field = shift or return;
Branch: 1 branch
BranchTrueFalseTotal
my $field = shift() or return 1 0 1
2040 1 return "CAST($field AS DECIMAL)";
2041 }
2042  
2043 26 1;
« SearchBuilder/Handle/MariaDB.pm ↑ Summary SearchBuilder/Handle/Oracle.pm »