SearchBuilder/Handle.pm

filter: Statementstmt 65.0% 427 / 656 Branchbran 54.5% 157 / 288 Conditioncond 48.8% 41 / 84 MC/DCmcdc 35.4% 17 / 48 Subroutinesub 68.0% 51 / 75 Podpod 92.4% 49 / 53 totaltotal 61.6% 742 / 1204 CC 194 SCAR 31.9
CC
194
Cov
61%
NullsOrder
81.0
Join
80.7
MayBeNull
53.2
CRAP 24.4
« SearchBuilder/Handle/Pg.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 sub new {
49 24 ▶ my $proto = shift;
Subroutine new: called CC=2 SCAR=7.0
Pod documented
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 sub Connect {
85 23 ▶ my $self = shift;
Subroutine Connect: called CC=11 SCAR=26.3
Pod documented
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") 0 22 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 sub _UpgradeHandle {
146 1 ▶ my $self = shift;
Subroutine _UpgradeHandle: called CC=2 SCAR=7.0
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 sub BuildDSN {
171 22 ▶ my $self = shift;
Subroutine BuildDSN: called CC=5 SCAR=16.8
Pod documented
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 sub DSN {
199 22 ▶ return shift->{'dsn'};
Subroutine DSN: called CC=1 SCAR=0.0
Pod documented
200 }
201  
202  
203  
204 =head2 RaiseError [MODE]
205  
206 Turns on the Database Handle's RaiseError attribute.
207  
208 =cut
209  
210 sub RaiseError {
211 0 ▶ my $self = shift;
Subroutine RaiseError: not called CC=2 SCAR=17.9
Pod documented
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 sub PrintError {
229 0 ▶ my $self = shift;
Subroutine PrintError: not called CC=2 SCAR=17.9
Pod documented
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 sub LogSQLStatements {
249 1070 ▶ my $self = shift;
Subroutine LogSQLStatements: called CC=2 SCAR=8.4
Pod documented
250 1070 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 1070 1070
251 0 require Time::HiRes;
252 0 $self->{'_DoLogSQL'} = shift;
253 }
254 1070 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 sub _LogSQLStatement {
264 0 ▶ my $self = shift;
Subroutine _LogSQLStatement: not called CC=1 SCAR=6.9
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 sub ClearSQLStatementLog {
280 0 ▶ my $self = shift;
Subroutine ClearSQLStatementLog: not called CC=1 SCAR=6.9
Pod documented
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 sub SQLStatementLog {
294 0 ▶ my $self = shift;
Subroutine SQLStatementLog: not called CC=1 SCAR=6.9
Pod documented
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 sub AutoCommit {
308 0 ▶ my $self = shift;
Subroutine AutoCommit: not called CC=2 SCAR=17.9
Pod documented
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 sub Disconnect {
326 0 ▶ my $self = shift;
Subroutine Disconnect: not called CC=6 SCAR=37.4
Pod documented
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 sub dbh {
359 995 ▶ my $self=shift;
Subroutine dbh: called CC=3 SCAR=11.0
Pod documented
360  
361 #If we are setting the database handle, set it.
362 995 ▶ if ( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 22 973 995
363 22 $DBIHandle{$self} = $PrevHandle = shift;
364 22 %FIELDS_IN_TABLE = ();
365 }
366  
367 995 ▶ return($DBIHandle{$self} ||= $PrevHandle);
Condition66%2/3
$DBIx::SearchBuilder::Handle::DBIHandle{$self} ||= $DBIx::SearchBuilder::Handle::PrevHandle
l!l&&r!l&&!r
958037
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 sub Insert {
383 150 ▶ my $self = shift;
Subroutine Insert: called CC=1 SCAR=0.0
Pod documented
384 150 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 sub InsertQueryString {
399 150 ▶ my($self, $table, @pairs) = @_;
Subroutine InsertQueryString: called CC=3 SCAR=11.0
Pod documented
400 150 my(@cols, @vals, @bind);
401  
402 150 ▶ while ( my $key = shift @pairs ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $key = shift @pairs) 395 150 545
403 395 push @cols, $key;
404 395 push @vals, '?';
405 395 push @bind, shift @pairs;
406 }
407  
408 150 ▶ $table = $self->QuoteName($table) if $self->QuoteTableNames;
Branch: 1 branch
BranchTrueFalseTotal
if $self->QuoteTableNames 0 150 150
409 150 my $QueryString = "INSERT INTO $table";
410 150 $QueryString .= " (". join(", ", @cols) .")";
411 150 $QueryString .= " VALUES (". join(", ", @vals). ")";
412 150 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 sub InsertFromSelect {
429 4 ▶ my ($self, $table, $columns, $query, @binds) = @_;
Subroutine InsertFromSelect: called CC=6 SCAR=18.8
Pod documented
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 sub UpdateRecordValue {
458 19 ▶ my $self = shift;
Subroutine UpdateRecordValue: called CC=4 SCAR=14.0
Pod documented
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 sub UpdateTableValue {
502 0 ▶ my $self = shift;
Subroutine UpdateTableValue: not called CC=1 SCAR=6.9
Pod documented
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 sub SimpleUpdateFromSelect {
531 1 ▶ my ($self, $table, $values, $query, @query_binds) = @_;
Subroutine SimpleUpdateFromSelect: called CC=5 SCAR=16.3
Pod undocumented
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 sub DeleteFromSelect {
562 1 ▶ my ($self, $table, $query, @binds) = @_;
Subroutine DeleteFromSelect: called CC=4 SCAR=14.5
Pod undocumented
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 sub SimpleQuery {
581 537 ▶ my $self = shift;
Subroutine SimpleQuery: called CC=14 SCAR=35.1
Pod documented
582 537 my $QueryString = shift;
583 537 my @bind_values;
584 537 ▶ @bind_values = (@_) if (@_);
Branch: 1 branch
BranchTrueFalseTotal
if @_ 266 271 537
585  
586 537 my $sth = $self->dbh->prepare($QueryString);
587 537 ▶ unless ($sth) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 2 535 537
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 535 ▶ for ( my $bind_idx = 0 ; $bind_idx < scalar @bind_values ; $bind_idx++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bind_idx < scalar @bind_values) 547 535 1082
610 547 ▶ if ( ref( $bind_values[$bind_idx] ) eq "HASH" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $bind_values[$bind_idx] eq "HASH") 0 547 547
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 535 my $basetime;
629 535 ▶ if ( $self->LogSQLStatements ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->LogSQLStatements) 0 535 535
630 0 $basetime = Time::HiRes::time();
631 }
632 535 my $executed;
633 {
634 26 ▶ no warnings 'uninitialized' ; # undef in bind_values makes DBI sad
Subroutine BEGIN: called CC=1 SCAR=0.0
635 535 eval { $executed = $sth->execute(@bind_values) };
636 }
637 535 ▶ if ( $self->LogSQLStatements ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->LogSQLStatements) 0 535 535
638 0 $self->_LogSQLStatement( $QueryString, Time::HiRes::time() - $basetime, @bind_values );
639 }
640  
641 535 ▶ if ( $@ or !$executed ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $executed) 0 535 535
Condition33%1/3
$@ or not $executed
l!l&&r!l&&!r
00535
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 535 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 sub FetchResult {
677 0 ▶ my $self = shift;
Subroutine FetchResult: not called CC=2 SCAR=17.9
Pod documented
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 sub BinarySafeBLOBs {
698 0 ▶ my $self = shift;
Subroutine BinarySafeBLOBs: not called CC=1 SCAR=6.9
Pod documented
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 sub KnowsBLOBs {
712 169 ▶ my $self = shift;
Subroutine KnowsBLOBs: called CC=1 SCAR=0.0
Pod documented
713 169 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 sub BLOBParams {
726 0 ▶ my $self = shift;
Subroutine BLOBParams: not called CC=1 SCAR=6.9
Pod documented
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 sub DatabaseVersion {
748 0 ▶ my $self = shift;
Subroutine DatabaseVersion: not called CC=6 SCAR=37.4
Pod documented
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 sub CaseSensitive {
784 0 ▶ my $self = shift;
Subroutine CaseSensitive: not called CC=1 SCAR=6.9
Pod documented
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 sub QuoteTableNames {
795 328 ▶ return shift->{'QuoteTableNames'}
Subroutine QuoteTableNames: called CC=1 SCAR=0.0
Pod documented
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 sub _MakeClauseCaseInsensitive {
814 45 ▶ my $self = shift;
Subroutine _MakeClauseCaseInsensitive: called CC=2 SCAR=6.9
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 sub BeginTransaction {
855 10 ▶ my $self = shift;
Subroutine BeginTransaction: called CC=3 SCAR=11.0
Pod documented
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 sub EndTransaction {
883 20 ▶ my $self = shift;
Subroutine EndTransaction: called CC=11 SCAR=24.0
Pod documented
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 sub Commit {
930 10 ▶ my $self = shift;
Subroutine Commit: called CC=1 SCAR=0.0
Pod documented
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 sub Rollback {
945 8 ▶ my $self = shift;
Subroutine Rollback: called CC=1 SCAR=0.0
Pod documented
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 sub ForceRollback {
958 1 ▶ my $self = shift;
Subroutine ForceRollback: called CC=1 SCAR=0.0
Pod documented
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 sub TransactionDepth {
971 61 ▶ my $self = shift;
Subroutine TransactionDepth: called CC=6 SCAR=17.9
Pod documented
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 sub ApplyLimits {
995 206 ▶ my $self = shift;
Subroutine ApplyLimits: called CC=6 SCAR=17.9
Pod documented
996 206 my $statementref = shift;
997 206 my $per_page = shift;
998 206 my $first = shift;
999 206 my $sb = shift;
1000  
1001 206 my $limit_clause = '';
1002  
1003 206 ▶ if ( $per_page) {
Branch: 1 branch
BranchTrueFalseTotal
if ($per_page) 69 137 206
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 206 $$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 sub Join {
1037  
1038 104 ▶ my $self = shift;
Subroutine Join: called CC=22 SCAR=43.9
Pod documented
1039 104 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 104 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 104 ▶ if ( $args{'ALIAS2'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'ALIAS2'}) { } 4 100 104
elsif ($args{'COLLECTION2'}) { } 0 100 100
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 100 $alias = $args{'SearchBuilder'}->_GetAlias( $args{'TABLE2'} );
1139 }
1140 104 ▶ $args{TABLE2} = $self->QuoteName($args{TABLE2}) if $self->QuoteTableNames;
Branch: 1 branch
BranchTrueFalseTotal
if $self->QuoteTableNames 0 104 104
1141  
1142 104 ▶ my $meta = $args{'SearchBuilder'}->{'left_joins'}{"$alias"} ||= {};
Condition50%1/2
$args{"SearchBuilder"}{"left_joins"}{"$alias"} ||= {}
l!l
0104
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 104 ▶ if ( $args{'TYPE'} =~ /LEFT/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'TYPE'} =~ /LEFT/i) { } 39 65 104
1144 39 $meta->{'alias_string'} = " LEFT JOIN " . $args{'TABLE2'} . " $alias ";
1145 39 $meta->{'type'} = 'LEFT';
1146 }
1147 else {
1148 65 $meta->{'alias_string'} = " JOIN " . $args{'TABLE2'} . " $alias ";
1149 65 $meta->{'type'} = 'NORMAL';
1150 }
1151 104 $meta->{'depends_on'} = $args{'ALIAS1'};
1152  
1153 104 ▶ my $criterion = $args{'EXPRESSION'} || $args{'ALIAS1'}.".".$args{'FIELD1'};
Condition50%1/2
$args{'EXPRESSION'} || $args{'ALIAS1'} . '.' . $args{'FIELD1'}
l!l
0104
MC/DC0%0/1
$args{'EXPRESSION'} || $args{'ALIAS1'} . '.' . $args{'FIELD1'}
$args{'EXPRESSION'}
Truth table50%1/2
A
A= $args{'EXPRESSION'}
Aresult
11
00
1154 104 $meta->{'criteria'}{'base_criterion'} =
1155 [ { field => "$alias.$args{'FIELD2'}", op => '=', value => $criterion } ];
1156  
1157 104 ▶ 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 103 104
elsif (not $args{'DISTINCT'}) { } 98 5 103
Condition100%3/3
$args{"DISTINCT"} and not defined $args{"SearchBuilder"}{"joins_are_distinct"}
!ll&&!rl&&r
9851
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 98 $args{SearchBuilder}{joins_are_distinct} = 0;
1161 }
1162  
1163 104 return ($alias);
1164 }
1165  
1166 sub _RenameRestriction {
1167 0 ▶ my $self = shift;
Subroutine _RenameRestriction: not called CC=4 SCAR=30.0
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 sub _NormalJoin {
1196  
1197 0 ▶ my $self = shift;
Subroutine _NormalJoin: not called CC=4 SCAR=30.0
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 sub _BuildJoins {
1242 293 ▶ my $self = shift;
Subroutine _BuildJoins: called CC=9 SCAR=22.0
1243 293 my $sb = shift;
1244  
1245 293 $self->OptimizeJoins( SearchBuilder => $sb );
1246 293 ▶ my $table = $self->{'QuoteTableNames'} ? $self->QuoteName($sb->Table) : $sb->Table;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'QuoteTableNames'} ? : 0 293 293
1247  
1248 293 my $join_clause = join " CROSS JOIN ", ("$table main"), @{ $sb->{'aliases'} };
1249 293 my %processed = map { /^\S+\s+(\S+)$/; $1 => 1 } @{ $sb->{'aliases'} };
1250 293 $processed{'main'} = 1;
1251  
1252 # get a @list of joins that have not been processed yet, but depend on processed join
1253 293 my $joins = $sb->{'left_joins'};
1254 293 ▶ while ( my @list =
Branch: 1 branch
BranchTrueFalseTotal
if (my(@list) = grep((!$processed{$_} && (!$joins->{$_}{"depends_on"} || $processed{$joins->{$_}{"depends_on"}})), sort(keys %$joins))) 157 293 450
Condition83%5/6
!$processed{$_} && (!$joins->{$_}{'depends_on'} || $processed{$joins->{$_}{'depends_on'}})
!ll&&!rl&&r
17215157
not $joins->{$_}{"depends_on"} or $processed{$joins->{$_}{"depends_on"}}
l!l&&r!l&&!r
015715
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 157 foreach my $join ( @list ) {
1260 157 $processed{ $join }++;
1261  
1262 157 my $meta = $joins->{ $join };
1263 157 ▶ my $aggregator = $meta->{'entry_aggregator'} || 'AND';
Condition100%2/2
$meta->{'entry_aggregator'} || 'AND'
l!l
9148
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 157 $join_clause .= $meta->{'alias_string'} . " ON ";
1266 my @tmp = map {
1267 ref($_)?
1268 664 ▶ $_->{'field'} .' '. $_->{'op'} .' '. $_->{'value'}:
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 166 498 664
1269 $_
1270 }
1271 157 map { ('(', @$_, ')', $aggregator) } sorted_values($meta->{'criteria'});
1272 157 pop @tmp;
1273 157 $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 293 ▶ if ( my @not_processed = grep !$processed{ $_ }, keys %$joins ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@not_processed) = grep((!$processed{$_}), keys %$joins)) 0 293 293
1280 0 die "Unsatisfied dependency chain in joins @not_processed";
1281 }
1282 293 return $join_clause;
1283 }
1284  
1285 sub OptimizeJoins {
1286 293 ▶ my $self = shift;
Subroutine OptimizeJoins: called CC=7 SCAR=19.5
Pod undocumented
1287 293 my %args = (SearchBuilder => undef, @_);
1288 293 my $joins = $args{'SearchBuilder'}->{'left_joins'};
1289  
1290 293 my %processed = map { /^\S+\s+(\S+)$/; $1 => 1 } @{ $args{'SearchBuilder'}->{'aliases'} };
1291 293 $processed{ $_ }++ foreach grep $joins->{ $_ }{'type'} ne 'LEFT', keys %$joins;
1292 293 $processed{'main'}++;
1293  
1294 293 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 293 ▶ while ( my @list = grep !$processed{ $_ }
Branch: 1 branch
BranchTrueFalseTotal
if (my(@list) = grep((!$processed{$_} && $processed{$joins->{$_}{"depends_on"}}), sort(keys %$joins))) 51 293 344
Condition100%3/3
!$processed{$_} && $processed{$joins->{$_}{'depends_on'}}
!ll&&!rl&&r
158151
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 51 unshift @ordered, @list;
1304 51 $processed{ $_ }++ foreach @list;
1305 }
1306  
1307 293 foreach my $join ( @ordered ) {
1308 51 ▶ next if $self->MayBeNull( SearchBuilder => $args{'SearchBuilder'}, ALIAS => $join );
Branch: 1 branch
BranchTrueFalseTotal
if $self->MayBeNull("SearchBuilder", $args{"SearchBuilder"}, "ALIAS", $join) 48 3 51
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 sub MayBeNull {
1333 51 ▶ my $self = shift;
Subroutine MayBeNull: called CC=29 SCAR=39.7
Pod documented
1334 51 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 51 ▶ 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 51 51
1338  
1339 # build full list of generic conditions
1340 51 my @conditions;
1341 51 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 51 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 53 ▶ next if $join->{'type'} eq 'LEFT';
Branch: 1 branch
BranchTrueFalseTotal
if $join->{"type"} eq "LEFT" 52 1 53
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 51 ▶ return 1 unless @conditions;
Branch: 1 branch
BranchTrueFalseTotal
unless @conditions 41 10 51
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 my $closing_paren = sub {
1383 0 ▶ my $i = shift;
Subroutine __ANON__: not called CC=5 SCAR=34.0
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 =head2 DistinctQuery STATEMENTREF
1459  
1460 takes an incomplete SQL SELECT statement and massages it to return a DISTINCT result set.
1461  
1462  
1463 =cut
1464  
1465 sub DistinctQuery {
1466 64 ▶ my $self = shift;
Subroutine DistinctQuery: called CC=3 SCAR=11.0
Pod documented
1467 64 my $statementref = shift;
1468 64 my $sb = shift;
1469 64 my %args = (
1470 Wrap => 0,
1471 @_
1472 );
1473  
1474 64 my $QueryHint = $sb->QueryHint;
1475 64 ▶ $QueryHint = $QueryHint ? " /* $QueryHint */ " : " ";
Branch: 1 branch
BranchTrueFalseTotal
$QueryHint ? : 0 64 64
1476  
1477 # Prepend select query for DBs which allow DISTINCT on all column types.
1478 64 $$statementref = "SELECT" . $QueryHint . "DISTINCT main.* FROM $$statementref";
1479 64 $$statementref .= $sb->_GroupClause;
1480 64 ▶ if ( $args{'Wrap'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"Wrap"}) 25 39 64
1481 25 $$statementref = "SELECT * FROM ($$statementref) main";
1482 }
1483 64 $$statementref .= $sb->_OrderClause;
1484 }
1485  
1486 =head2 DistinctQueryAndCount STATEMENTREF
1487  
1488 takes an incomplete SQL SELECT statement and massages it to return a
1489 DISTINCT result set and the total count of potential records.
1490  
1491 =cut
1492  
1493 sub DistinctQueryAndCount {
1494 41 ▶ my $self = shift;
Subroutine DistinctQueryAndCount: called CC=1 SCAR=0.0
Pod documented
1495 41 my $statementref = shift;
1496 41 my $sb = shift;
1497  
1498 # order by clause should be on outer most query
1499 # SQL standard: ORDER BY command cannot be used in a Subquery
1500 # mariadb explanation: https://mariadb.com/kb/en/why-is-order-by-in-a-from-subquery-ignored/
1501 # pg: actually keeps order of a subquery as long as some conditions in outer query are met, but
1502 # it's just a coincidence, not a feature
1503 # SQL server: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver16
1504 # The ORDER BY clause is not valid in views, ... and *subqueries*, unless ...
1505  
1506 41 my $order = $sb->_OrderClause;
1507 41 my $wrap = $order !~ /(?<!main)\./;
1508  
1509 41 $self->DistinctQuery($statementref, $sb, Wrap => $wrap);
1510  
1511 # DistinctQuery already has an outer SELECT, which we can reuse
1512 41 $$statementref =~ s!(?= FROM)!, COUNT(main.id) OVER() AS search_builder_count_all!;
1513 }
1514  
1515  
1516  
1517 =head2 DistinctCount STATEMENTREF
1518  
1519 takes an incomplete SQL SELECT statement and massages it to return a DISTINCT result set.
1520  
1521  
1522 =cut
1523  
1524 sub DistinctCount {
1525 0 ▶ my $self = shift;
Subroutine DistinctCount: not called CC=2 SCAR=17.9
Pod documented
1526 0 my $statementref = shift;
1527 0 my $sb = shift;
1528  
1529 0 my $QueryHint = $sb->QueryHint;
1530 0 ▶ $QueryHint = $QueryHint ? " /* $QueryHint */ " : " ";
Branch: 1 branch
BranchTrueFalseTotal
$QueryHint ? : 0 0 0
1531  
1532 # Prepend select query for DBs which allow DISTINCT on all column types.
1533 0 $$statementref = "SELECT" . $QueryHint . "COUNT(DISTINCT main.id) FROM $$statementref";
1534  
1535 }
1536  
1537 sub Fields {
1538 0 ▶ my $self = shift;
Subroutine Fields: not called CC=4 SCAR=30.0
Pod undocumented
1539 0 my $table = lc shift;
1540  
1541 0 ▶ unless ( $FIELDS_IN_TABLE{$table} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($DBIx::SearchBuilder::Handle::FIELDS_IN_TABLE{$table}) 0 0 0
1542 0 $FIELDS_IN_TABLE{ $table } = [];
1543 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
1544 or return ();
1545 0 my $info = $sth->fetchall_arrayref({});
1546 0 foreach my $e ( @$info ) {
1547 0 push @{ $FIELDS_IN_TABLE{ $table } }, $e->{'COLUMN_NAME'};
1548 }
1549 }
1550  
1551 0 return @{ $FIELDS_IN_TABLE{ $table } };
1552 }
1553  
1554  
1555 =head2 Log MESSAGE
1556  
1557 Takes a single argument, a message to log.
1558  
1559 Currently prints that message to STDERR
1560  
1561 =cut
1562  
1563 sub Log {
1564 0 ▶ my $self = shift;
Subroutine Log: not called CC=1 SCAR=6.9
Pod documented
1565 0 my $msg = shift;
1566 0 warn $msg."\n";
1567 }
1568  
1569 =head2 SimpleDateTimeFunctions
1570  
1571 See L</DateTimeFunction> for details on supported functions.
1572 This method is for implementers of custom DB connectors.
1573  
1574 Returns hash reference with (function name, sql template) pairs.
1575  
1576 =cut
1577  
1578 sub SimpleDateTimeFunctions {
1579 1 ▶ my $self = shift;
Subroutine SimpleDateTimeFunctions: called CC=1 SCAR=0.0
Pod documented
1580 return {
1581 1 datetime => 'SUBSTR(?, 1, 19)',
1582 time => 'SUBSTR(?, 12, 8)',
1583  
1584 hourly => 'SUBSTR(?, 1, 13)',
1585 hour => 'SUBSTR(?, 12, 2 )',
1586  
1587 date => 'SUBSTR(?, 1, 10)',
1588 daily => 'SUBSTR(?, 1, 10)',
1589  
1590 day => 'SUBSTR(?, 9, 2 )',
1591 dayofmonth => 'SUBSTR(?, 9, 2 )',
1592  
1593 monthly => 'SUBSTR(?, 1, 7 )',
1594 month => 'SUBSTR(?, 6, 2 )',
1595  
1596 annually => 'SUBSTR(?, 1, 4 )',
1597 year => 'SUBSTR(?, 1, 4 )',
1598 };
1599 }
1600  
1601 =head2 DateTimeFunction
1602  
1603 Takes named arguments:
1604  
1605 =over 4
1606  
1607 =item * Field - SQL expression date/time function should be applied
1608 to. Note that this argument is used as is without any kind of quoting.
1609  
1610 =item * Type - name of the function, see supported values below.
1611  
1612 =item * Timezone - optional hash reference with From and To values,
1613 see L</ConvertTimezoneFunction> for details.
1614  
1615 =back
1616  
1617 Returns SQL statement. Returns NULL if function is not supported.
1618  
1619 =head3 Supported functions
1620  
1621 Type value in L</DateTimeFunction> is case insesitive. Spaces,
1622 underscores and dashes are ignored. So 'date time', 'DateTime'
1623 and 'date_time' are all synonyms. The following functions are
1624 supported:
1625  
1626 =over 4
1627  
1628 =item * date time - as is, no conversion, except applying timezone
1629 conversion if it's provided.
1630  
1631 =item * time - time only
1632  
1633 =item * hourly - datetime prefix up to the hours, e.g. '2010-03-25 16'
1634  
1635 =item * hour - hour, 0 - 23
1636  
1637 =item * date - date only
1638  
1639 =item * daily - synonym for date
1640  
1641 =item * day of week - 0 - 6, 0 - Sunday
1642  
1643 =item * day - day of month, 1 - 31
1644  
1645 =item * day of month - synonym for day
1646  
1647 =item * day of year - 1 - 366, support is database dependent
1648  
1649 =item * month - 1 - 12
1650  
1651 =item * monthly - year and month prefix, e.g. '2010-11'
1652  
1653 =item * year - e.g. '2023'
1654  
1655 =item * annually - synonym for year
1656  
1657 =item * week of year - 0-53, presence of zero week, 1st week meaning
1658 and whether week starts on Monday or Sunday heavily depends on database.
1659  
1660 =back
1661  
1662 =cut
1663  
1664 sub DateTimeFunction {
1665 20 ▶ my $self = shift;
Subroutine DateTimeFunction: called CC=4 SCAR=14.2
Pod documented
1666 20 my %args = (
1667 Field => undef,
1668 Type => '',
1669 Timezone => undef,
1670 @_
1671 );
1672  
1673 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
1674 20 ▶ if ( $args{'Timezone'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"Timezone"}) 0 20 20
1675 $res = $self->ConvertTimezoneFunction(
1676 0 %{ $args{'Timezone'} },
1677 Field => $res,
1678 );
1679 }
1680  
1681 20 my $norm_type = lc $args{'Type'};
1682 20 $norm_type =~ s/[ _-]//g;
1683 20 ▶ if ( my $template = $self->SimpleDateTimeFunctions->{ $norm_type } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $template = $self->SimpleDateTimeFunctions->{$norm_type}) { } 18 2 20
1684 18 $template =~ s/\?/$res/;
1685 18 $res = $template;
1686 }
1687 else {
1688 2 return 'NULL';
1689 }
1690 18 return $res;
1691 }
1692  
1693 =head2 ConvertTimezoneFunction
1694  
1695 Generates a function applied to Field argument that converts timezone.
1696 By default converts from UTC. Examples:
1697  
1698 # UTC => Moscow
1699 $handle->ConvertTimezoneFunction( Field => '?', To => 'Europe/Moscow');
1700  
1701 If there is problem with arguments or timezones are equal
1702 then Field returned without any function applied. Field argument
1703 is not escaped in any way, it's your job.
1704  
1705 Implementation is very database specific. To be portable convert
1706 from UTC or to UTC. Some databases have internal storage for
1707 information about timezones that should be kept up to date.
1708 Read documentation for your DB.
1709  
1710 =cut
1711  
1712 sub ConvertTimezoneFunction {
1713 0 ▶ my $self = shift;
Subroutine ConvertTimezoneFunction: not called CC=1 SCAR=6.9
Pod documented
1714 0 my %args = (
1715 From => 'UTC',
1716 To => undef,
1717 Field => '',
1718 @_
1719 );
1720 0 return $args{'Field'};
1721 }
1722  
1723 =head2 DateTimeIntervalFunction
1724  
1725 Generates a function to calculate interval in seconds between two
1726 dates. Takes From and To arguments which can be either scalar or
1727 a hash. Hash is processed with L<DBIx::SearchBuilder/CombineFunctionWithField>.
1728  
1729 Arguments are not quoted or escaped in any way. It's caller's job.
1730  
1731 =cut
1732  
1733 sub DateTimeIntervalFunction {
1734 2 ▶ my $self = shift;
Subroutine DateTimeIntervalFunction: called CC=2 SCAR=6.9
Pod documented
1735 2 my %args = ( From => undef, To => undef, @_ );
1736  
1737 $_ = DBIx::SearchBuilder->CombineFunctionWithField(%$_)
1738 2 for grep ref, @args{'From', 'To'};
1739  
1740 2 return $self->_DateTimeIntervalFunction( %args );
1741 }
1742  
1743 0 ▶sub _DateTimeIntervalFunction { return 'NULL' }
Subroutine _DateTimeIntervalFunction: not called CC=1 SCAR=6.9
1744  
1745 =head2 NullsOrder
1746  
1747 Sets order of NULLs when sorting columns when called with mode,
1748 but only if DB supports it. Modes:
1749  
1750 =over 4
1751  
1752 =item * small
1753  
1754 NULLs are smaller then anything else, so come first when order
1755 is ASC and last otherwise.
1756  
1757 =item * large
1758  
1759 NULLs are larger then anything else.
1760  
1761 =item * first
1762  
1763 NULLs are always first.
1764  
1765 =item * last
1766  
1767 NULLs are always last.
1768  
1769 =item * default
1770  
1771 Return back to DB's default behaviour.
1772  
1773 =back
1774  
1775 When called without argument returns metadata required to generate
1776 SQL.
1777  
1778 =cut
1779  
1780 sub NullsOrder {
1781 331 ▶ my $self = shift;
Subroutine NullsOrder: called CC=11 SCAR=43.9
Pod documented
1782  
1783 331 ▶ unless ($self->HasSupportForNullsOrder) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->HasSupportForNullsOrder) 331 0 331
1784 331 ▶ warn "No support for changing NULLs order" if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 331 331
1785 331 return undef;
1786 }
1787  
1788 0 ▶ if ( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 0 0
1789 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
1790 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
1791 0 delete $self->{'nulls_order'};
1792 }
1793 elsif ( $mode eq 'small' ) {
1794 0 $self->{'nulls_order'} = { ASC => 'NULLS FIRST', DESC => 'NULLS LAST' };
1795 }
1796 elsif ( $mode eq 'large' ) {
1797 0 $self->{'nulls_order'} = { ASC => 'NULLS LAST', DESC => 'NULLS FIRST' };
1798 }
1799 elsif ( $mode eq 'first' ) {
1800 0 $self->{'nulls_order'} = { ASC => 'NULLS FIRST', DESC => 'NULLS FIRST' };
1801 }
1802 elsif ( $mode eq 'last' ) {
1803 0 $self->{'nulls_order'} = { ASC => 'NULLS LAST', DESC => 'NULLS LAST' };
1804 }
1805 else {
1806 0 warn "'$mode' is not supported NULLs ordering mode";
1807 0 delete $self->{'nulls_order'};
1808 }
1809 }
1810  
1811 0 ▶ return undef unless $self->{'nulls_order'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"nulls_order"} 0 0 0
1812 0 return $self->{'nulls_order'};
1813 }
1814  
1815 =head2 HasSupportForNullsOrder
1816  
1817 Returns true value if DB supports adjusting NULLs order while sorting
1818 a column, for example C<ORDER BY Value ASC NULLS FIRST>.
1819  
1820 =cut
1821  
1822 sub HasSupportForNullsOrder {
1823 332 ▶ return 0;
Subroutine HasSupportForNullsOrder: called CC=1 SCAR=0.0
Pod documented
1824 }
1825  
1826 =head2 HasSupportForCombineSearchAndCount
1827  
1828 Returns true value if DB supports to combine search and count in single
1829 query.
1830  
1831 =cut
1832  
1833 sub HasSupportForCombineSearchAndCount {
1834 84 ▶ return 1;
Subroutine HasSupportForCombineSearchAndCount: called CC=1 SCAR=0.0
Pod documented
1835 }
1836  
1837 =head2 HasSupportForEmptyString
1838  
1839 Returns true value if DB supports empty string.
1840  
1841 =cut
1842  
1843 sub HasSupportForEmptyString {
1844 0 ▶ return 1;
Subroutine HasSupportForEmptyString: not called CC=1 SCAR=6.9
Pod documented
1845 }
1846  
1847 =head2 QuoteName
1848  
1849 Quote table or column name to avoid reserved word errors.
1850  
1851 Returns same value passed unless over-ridden in database-specific subclass.
1852  
1853 =cut
1854  
1855 # over-ride in subclass
1856 sub QuoteName {
1857 0 ▶ my ($self, $name) = @_;
Subroutine QuoteName: not called CC=2 SCAR=17.9
Pod documented
1858 # use dbi built in quoting if we have a connection,
1859 0 ▶ if ($self->dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dbh) 0 0 0
1860 0 return $self->dbh->quote_identifier($name);
1861 }
1862 0 warn "QuoteName called without a db handle";
1863 0 return $name;
1864 }
1865  
1866 =head2 DequoteName
1867  
1868 Undo the effects of QuoteName by removing quoting.
1869  
1870 =cut
1871  
1872 sub DequoteName {
1873 0 ▶ my ($self, $name) = @_;
Subroutine DequoteName: not called CC=4 SCAR=30.0
Pod documented
1874 0 ▶ if ($self->dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dbh) 0 0 0
1875 # 29 = SQL_IDENTIFIER_QUOTE_CHAR; see "perldoc DBI"
1876 0 my $quote_char = $self->dbh->get_info( 29 );
1877  
1878 0 ▶ if ($quote_char) {
Branch: 1 branch
BranchTrueFalseTotal
if ($quote_char) 0 0 0
1879 0 ▶ if ($name =~ /^$quote_char(.*)$quote_char$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /^$quote_char(.*)$quote_char$/) 0 0 0
1880 0 return $1;
1881 }
1882 }
1883 0 return $name;
1884 }
1885 0 warn "DequoteName called without a db handle";
1886 0 return $name;
1887 }
1888  
1889 =head2 $MAX_BIND_PARAMS
1890  
1891 Maximum number of bind parameters allowed when converting a query from
1892 literal values to placeholders. Defaults to 65,535 (the MySQL limit).
1893 If a query would require more placeholders than this value, the query is
1894 left as-is with literal values and no bind parameters are extracted.
1895  
1896 You can override this in driver subclasses or in tests to accommodate
1897 databases with different limits:
1898  
1899 local $DBIx::SearchBuilder::Handle::MAX_BIND_PARAMS = 32_767;
1900  
1901 =cut
1902  
1903 26 our $MAX_BIND_PARAMS = 65_535;
1904  
1905 sub _ExtractBindValues {
1906 36 ▶ my ( $self, $string, $default_escape_char ) = @_;
Subroutine _ExtractBindValues: called CC=9 SCAR=22.2
1907 36 ▶ return unless defined $$string;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$string 0 36 36
1908  
1909 # A single regex used both for pre-counting and for substitution,
1910 # so that both passes always match the same tokens.
1911 36 state $token_re = qr{
1912 (?: e? ' (?: \\. | '' | [^'] )* ' ) # quoted string
1913 |
1914 (?: \b \d* \.? \d+ \b ) # number, but not the one in Groups_1.Name
1915 }isx;
1916 36 state %special_chars = (
1917 'b' => "\b",
1918 'f' => "\f",
1919 'n' => "\n",
1920 'r' => "\r",
1921 't' => "\t",
1922 );
1923  
1924 36 my $count = 0;
1925 36 ▶ while ( $$string =~ m!$token_re!g ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$string =~ /$token_re/g) 57 33 90
1926 # If the query has too many literals, leave it as-is. The caller
1927 # will still set _bind_values to [] (an empty-but-truthy arrayref),
1928 # so ApplyLimits can still bind its own LIMIT/OFFSET placeholders
1929 # against the unmodified query string.
1930 57 ▶ return if ++$count > $MAX_BIND_PARAMS;
Branch: 1 branch
BranchTrueFalseTotal
if ++$count > $DBIx::SearchBuilder::Handle::MAX_BIND_PARAMS 3 54 57
1931 }
1932  
1933 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
1934  
1935 33 my @values;
1936  
1937 33 $$string =~ s{($token_re)}{
1938 51 my $match = $1;
1939 51 ▶ if ( $match =~ /^(e?)'(.*)'$/si ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($match =~ /^(e?)'(.*)'$/is) { } 51 0 51
1940 51 my $e_notion = $1;
1941 51 my $value = $2;
1942 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
1943 # For unrecognised escapes (e.g. \q), strip the backslash
1944 # and keep the literal character — the correct behaviour
1945 # for SQL E-notation strings.
1946 1 ▶ $value =~ s!\\(.)!$special_chars{$1} || $1!sgei;
Branch: 1 branch
BranchTrueFalseTotal
$special_chars{$1} or $1 1 1 2
1947 }
1948 51 $value =~ s!''!'!g;
1949 51 push @values, $value;
1950 }
1951 else {
1952 0 push @values, $match;
1953 }
1954 51 '?';
1955 }eg;
1956  
1957 33 return @values;
1958 }
1959  
1960 22 ▶sub _RequireQuotedTables { return 0 };
Subroutine _RequireQuotedTables: called CC=1 SCAR=0.0
1961  
1962 =head2 DESTROY
1963  
1964 When we get rid of the Searchbuilder::Handle, we need to disconnect from the database
1965  
1966 =cut
1967  
1968 sub DESTROY {
1969 23 ▶ my $self = shift;
Subroutine DESTROY: called CC=2 SCAR=7.1
1970 23 ▶ $self->Disconnect if $self->{'DisconnectHandleOnDestroy'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"DisconnectHandleOnDestroy"} 0 23 23
1971 23 delete $DBIHandle{$self};
1972 }
1973  
1974 =head2 CastAsDecimal FIELD
1975  
1976 Cast the given field as decimal.
1977  
1978 E.g. on Pg, it's C<CAST(Content AS DECIMAL)>.
1979  
1980 =cut
1981  
1982 sub CastAsDecimal {
1983 1 ▶ my $self = shift;
Subroutine CastAsDecimal: called CC=2 SCAR=7.1
Pod documented
1984 1 ▶ my $field = shift or return;
Branch: 1 branch
BranchTrueFalseTotal
my $field = shift() or return 0 1 1
1985 1 return "CAST($field AS DECIMAL)";
1986 }
1987  
1988 26 1;
« SearchBuilder/Handle/Pg.pm ↑ Summary SearchBuilder/Handle/Oracle.pm »