SearchBuilder/Handle/mysql.pm

filter: Statementstmt 14.5% 21 / 144 Branchbran 5.8% 4 / 68 Conditioncond 0.0% 0 / 20 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 27.2% 6 / 22 Podpod 78.5% 11 / 14 totaltotal 15.1% 42 / 278 CC 48 SCAR 40.0
CC
48
Cov
11%
DistinctQuery
182.0
SimpleMassChangeFromSelect
72.0
Fields
42.0
CRAP 54.7
« SearchBuilder/Handle/MariaDB.pm ↑ Summary SearchBuilder/Handle/Pg.pm »
1 package DBIx::SearchBuilder::Handle::mysql;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 2 ▶use base qw(DBIx::SearchBuilder::Handle);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 =head1 NAME
10  
11 DBIx::SearchBuilder::Handle::mysql - A mysql specific Handle object
12  
13 =head1 SYNOPSIS
14  
15  
16 =head1 DESCRIPTION
17  
18 This module provides a subclass of DBIx::SearchBuilder::Handle that
19 compensates for some of the idiosyncrasies of MySQL.
20  
21 =head1 METHODS
22  
23 =head2 Insert
24  
25 Takes a table name as the first argument and assumes that the rest of the arguments are an array of key-value pairs to be inserted.
26  
27 If the insert succeeds, returns the id of the insert, otherwise, returns
28 a Class::ReturnValue object with the error reported.
29  
30 =cut
31  
32 0 ▶sub Insert {
Subroutine Insert: not called CC=4 SCAR=30.0
Pod documented
33 0 my $self = shift;
34  
35 0 my $sth = $self->SUPER::Insert(@_);
36 0 ▶ if (!$sth) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 0 0 0
37 0 return ($sth);
38 }
39  
40 0 $self->{'id'}=$self->dbh->{'mysql_insertid'};
41  
42 # Yay. we get to work around mysql_insertid being null some of the time :/
43 0 ▶ unless ($self->{'id'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"id"}) 0 0 0
44 0 $self->{'id'} = $self->FetchResult('SELECT LAST_INSERT_ID()');
45 }
46 0 ▶ warn "$self no row id returned on row creation" unless ($self->{'id'});
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"id"} 0 0 0
47  
48 0 return( $self->{'id'}); #Add Succeded. return the id
49 }
50  
51  
52 =head2 SimpleUpdateFromSelect
53  
54 Customization of L<DBIx::SearchBuilder::Handle/SimpleUpdateFromSelect>.
55 Mysql doesn't support update with subqueries when those fetch data from
56 the table that is updated.
57  
58 =cut
59  
60 0 ▶sub SimpleUpdateFromSelect {
Subroutine SimpleUpdateFromSelect: not called CC=5 SCAR=34.0
Pod documented
61 0 my ($self, $table, $values, $query, @query_binds) = @_;
62  
63 0 ▶ return $self->SUPER::SimpleUpdateFromSelect(
Branch: 1 branch
BranchTrueFalseTotal
unless $query =~ /\b\Q$table\E\b/i 0 0 0
64 $table, $values, $query, @query_binds
65 ) unless $query =~ /\b\Q$table\E\b/i;
66  
67 0 my $sth = $self->SimpleQuery( $query, @query_binds );
68 0 ▶ return $sth unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 0 0
69  
70 0 my (@binds, @columns);
71 0 for my $k (sort keys %$values) {
72 0 push @columns, $k;
73 0 push @binds, $values->{$k};
74 }
75  
76 0 ▶ $table = $self->QuoteName($table) if $self->{'QuoteTableNames'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"QuoteTableNames"} 0 0 0
77 0 my $update_query = "UPDATE $table SET "
78 . join( ', ', map "$_ = ?", @columns )
79 .' WHERE ID IN ';
80  
81 0 return $self->SimpleMassChangeFromSelect(
82 $update_query, \@binds,
83 $query, @query_binds
84 );
85 }
86  
87  
88 0 ▶sub DeleteFromSelect {
Subroutine DeleteFromSelect: not called CC=3 SCAR=24.8
Pod undocumented
89 0 my ($self, $table, $query, @query_binds) = @_;
90  
91 0 ▶ return $self->SUPER::DeleteFromSelect(
Branch: 1 branch
BranchTrueFalseTotal
unless $query =~ /\b\Q$table\E\b/i 0 0 0
92 $table, $query, @query_binds
93 ) unless $query =~ /\b\Q$table\E\b/i;
94  
95 0 ▶ $table = $self->QuoteName($table) if $self->{'QuoteTableNames'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"QuoteTableNames"} 0 0 0
96 0 return $self->SimpleMassChangeFromSelect(
97 "DELETE FROM $table WHERE id IN ", [],
98 $query, @query_binds
99 );
100 }
101  
102 0 ▶sub SimpleMassChangeFromSelect {
Subroutine SimpleMassChangeFromSelect: not called CC=8 SCAR=42.8
Pod undocumented
103 0 my ($self, $update_query, $update_binds, $search, @search_binds) = @_;
104  
105 0 my $sth = $self->SimpleQuery( $search, @search_binds );
106 0 ▶ return $sth unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 0 0
107  
108  
109 # tried TEMPORARY tables, much slower than fetching and delete
110 # also size of ENGINE=MEMORY is limitted by option, on disk
111 # tables more slower than in memory
112 0 my $res = 0;
113  
114 0 my @ids;
115 0 ▶ while ( my $id = ($sth->fetchrow_array)[0] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = ($sth->fetchrow_array)[0]) 0 0 0
116 0 push @ids, $id;
117 0 ▶ next if @ids < 1000;
Branch: 1 branch
BranchTrueFalseTotal
if @ids < 1000 0 0 0
118  
119 0 my $q = $update_query .'('. join( ',', ('?')x@ids ) .')';
120 0 my $sth = $self->SimpleQuery( $q, @$update_binds, splice @ids );
121 0 ▶ return $sth unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 0 0
122  
123 0 $res += $sth->rows;
124 }
125 0 ▶ if ( @ids ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ids) 0 0 0
126 0 my $q = $update_query .'('. join( ',', ('?')x@ids ) .')';
127 0 my $sth = $self->SimpleQuery( $q, @$update_binds, splice @ids );
128 0 ▶ return $sth unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 0 0
129  
130 0 $res += $sth->rows;
131 }
132 0 ▶ return $res == 0? '0E0': $res;
Branch: 1 branch
BranchTrueFalseTotal
$res == 0 ? : 0 0 0
133 }
134  
135 =head2 DatabaseVersion
136  
137 Returns the mysql version, trimming off any -foo identifier
138  
139 =cut
140  
141 0 ▶sub DatabaseVersion {
Subroutine DatabaseVersion: not called CC=1 SCAR=6.9
Pod documented
142 0 my $self = shift;
143 0 my $v = $self->SUPER::DatabaseVersion();
144  
145 0 $v =~ s/\-.*$//;
146 0 return ($v);
147 }
148  
149 =head2 CaseSensitive
150  
151 Returns undef, since mysql's searches are not case sensitive by default
152  
153 =cut
154  
155 0 ▶sub CaseSensitive {
Subroutine CaseSensitive: not called CC=1 SCAR=6.9
Pod documented
156 0 my $self = shift;
157 0 return(undef);
158 }
159  
160 0 ▶sub DistinctQuery {
Subroutine DistinctQuery: not called CC=13 SCAR=52.0
Pod documented
161 0 my $self = shift;
162 0 my $statementref = shift;
163 0 my $sb = shift;
164  
165 0 ▶ return $self->SUPER::DistinctQuery( $statementref, $sb, @_ )
Branch: 1 branch
BranchTrueFalseTotal
unless $sb->_OrderClause =~ /(?<!main)\./ 0 0 0
166 if $sb->_OrderClause !~ /(?<!main)\./;
167  
168 0 ▶ if ( substr($self->DatabaseVersion, 0, 1) == 4 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($self->DatabaseVersion, 0, 1) == 4) { } 0 0 0
169 0 local $sb->{'group_by'} = [{FIELD => 'id'}];
170  
171 0 my ($idx, @tmp, @specials) = (0, ());
172 0 foreach ( @{$sb->{'order_by'}} ) {
173 0 ▶ if ( !exists $_->{'ALIAS'} || ($_->{'ALIAS'}||'') eq "main" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $_->{"ALIAS"} or ($_->{"ALIAS"} || "") eq "main") 0 0 0
Condition0%0/5
not exists $_->{"ALIAS"} or ($_->{"ALIAS"} || "") eq "main"
l!l&&r!l&&!r
000
$_->{'ALIAS'} || ''
l!l
00
MC/DC0%0/2
not exists $_->{"ALIAS"} or ($_->{"ALIAS"} || "") eq "main"
not exists $_->{"ALIAS"} $_->{'ALIAS'}
Truth table0%0/3
not(A) or B
A= not exists $_->{"ALIAS"}B= $_->{'ALIAS'}
ABresult
1X1
011
000
174 0 push @tmp, $_; next;
175 }
176  
177 push @specials,
178 ((($_->{'ORDER'}||'') =~ /^des/i)?'MAX':'MIN')
179 0 ▶ ."(". $_->{'ALIAS'} .".". $_->{'FIELD'} .")"
Branch: 1 branch
BranchTrueFalseTotal
($_->{'ORDER'} || '') =~ /^des/i ? : 0 0 0
Condition0%0/2
$_->{'ORDER'} || ''
l!l
00
MC/DC0%0/1
$_->{'ORDER'} || ''
$_->{'ORDER'}
Truth table0%0/2
A
A= $_->{'ORDER'}
Aresult
11
00
180 ." __special_sort_$idx";
181 0 push @tmp, { ALIAS => '', FIELD => "__special_sort_$idx", ORDER => $_->{'ORDER'} };
182 0 $idx++;
183 }
184  
185 0 local $sb->{'order_by'} = \@tmp;
186 0 $$statementref = "SELECT ". join( ", ", 'main.*', @specials ) ." FROM $$statementref";
187 0 $$statementref .= $sb->_GroupClause;
188 0 $$statementref .= $sb->_OrderClause;
189 } else {
190 0 local $sb->{'group_by'} = [{FIELD => 'id'}];
191 local $sb->{'order_by'} = [
192 map {
193 ($_->{'ALIAS'}||'') ne "main"
194 0 ▶ ? { %{$_}, FIELD => ((($_->{'ORDER'}||'') =~ /^des/i)?'MAX':'MIN') ."(".$_->{FIELD}.")" }
Branch: 2 branches
BranchTrueFalseTotal
($_->{'ALIAS'} || '') ne 'main' ? : 0 0 0
($_->{'ORDER'} || '') =~ /^des/i ? : 0 0 0
Condition0%0/4
$_->{'ALIAS'} || ''
l!l
00
$_->{'ORDER'} || ''
l!l
00
MC/DC0%0/1
$_->{'ALIAS'} || ''
$_->{'ALIAS'}
MC/DC0%0/1
$_->{'ORDER'} || ''
$_->{'ORDER'}
Truth table0%0/2
A
A= $_->{'ALIAS'}
Aresult
11
00
Truth table0%0/2
A
A= $_->{'ORDER'}
Aresult
11
00
195 : $_
196 }
197 0 @{$sb->{'order_by'}}
198 ];
199 0 $$statementref = "SELECT main.* FROM $$statementref";
200 0 $$statementref .= $sb->_GroupClause;
201 0 $$statementref .= $sb->_OrderClause;
202 }
203 }
204  
205 0 ▶sub Fields {
Subroutine Fields: not called CC=6 SCAR=37.4
Pod undocumented
206 0 my $self = shift;
207 0 my $table = shift;
208  
209 0 my $cache = \%DBIx::SearchBuilder::Handle::FIELDS_IN_TABLE;
210 0 ▶ unless ( $cache->{ lc $table } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($$cache{lc $table}) 0 0 0
211 0 ▶ my $sth = $self->dbh->column_info( undef, undef, $table, '%' )
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->dbh->column_info(undef, undef, $table, "%") or return () 0 0 0
212 or return ();
213 0 my $info = $sth->fetchall_arrayref({});
214 0 foreach my $e ( sort {$a->{'ORDINAL_POSITION'} <=> $b->{'ORDINAL_POSITION'}} @$info ) {
215 0 ▶ push @{ $cache->{ lc $e->{'TABLE_NAME'} } ||= [] }, lc $e->{'COLUMN_NAME'};
Condition0%0/2
$$cache{lc $e->{"TABLE_NAME"}} ||= []
l!l
00
MC/DC0%0/1
$$cache{lc $e->{"TABLE_NAME"}} ||= []
$$cache{lc $e->{"TABLE_NAME"}}
Truth table0%0/2
A
A= $$cache{lc $e->{"TABLE_NAME"}}
Aresult
11
00
216 }
217 }
218 0 ▶ return @{ $cache->{ lc $table } || [] };
Condition0%0/2
$$cache{lc $table} || []
l!l
00
MC/DC0%0/1
$$cache{lc $table} || []
$$cache{lc $table}
Truth table0%0/2
A
A= $$cache{lc $table}
Aresult
11
00
219 }
220  
221 =head2 SimpleDateTimeFunctions
222  
223 Returns hash reference with specific date time functions of this
224 database for L<DBIx::SearchBuilder::Handle/DateTimeFunction>.
225  
226 =cut
227  
228 0 ▶sub SimpleDateTimeFunctions {
Subroutine SimpleDateTimeFunctions: not called CC=2 SCAR=17.9
Pod documented
229 0 my $self = shift;
230 return $self->{'_simple_date_time_functions'} ||= {
231 0 ▶ %{ $self->SUPER::SimpleDateTimeFunctions(@_) },
Condition0%0/2
$self->{"_simple_date_time_functions"} ||= {%{$self->SUPER::SimpleDateTimeFunctions(@_);}, "datetime", "?", "time", "TIME(?)", "hourly", "DATE_FORMAT(?, '%Y-%m-%d %H')", "hour", "HOUR(?)", "date", "DATE(?)", "daily", "DATE(?)", "day", "DAYOFMONTH(?)", "dayofmonth", "DAYOFMONTH(?)", "monthly", "DATE_FORMAT(?, '%Y-%m')", "month", "MONTH(?)", "annually", "YEAR(?)", "year", "YEAR(?)", "dayofweek", "DAYOFWEEK(?) - 1", "dayofyear", "DAYOFYEAR(?)", "weekofyear", "WEEK(?)"}
l!l
00
MC/DC0%0/1
$self->{"_simple_date_time_functions"} ||= {%{$self->SUPER::SimpleDateTimeFunctions(@_);}, "datetime", "?", "time", "TIME(?)", "hourly", "DATE_FORMAT(?, '%Y-%m-%d %H')", "hour", "HOUR(?)", "date", "DATE(?)", "daily", "DATE(?)", "day", "DAYOFMONTH(?)", "dayofmonth", "DAYOFMONTH(?)", "monthly", "DATE_FORMAT(?, '%Y-%m')", "month", "MONTH(?)", "annually", "YEAR(?)", "year", "YEAR(?)", "dayofweek", "DAYOFWEEK(?) - 1", "dayofyear", "DAYOFYEAR(?)", "weekofyear", "WEEK(?)"}
$self->{"_simple_date_time_functions"}
Truth table0%0/2
A
A= $self->{"_simple_date_time_functions"}
Aresult
11
00
232 datetime => '?',
233 time => 'TIME(?)',
234  
235 hourly => "DATE_FORMAT(?, '%Y-%m-%d %H')",
236 hour => 'HOUR(?)',
237  
238 date => 'DATE(?)',
239 daily => 'DATE(?)',
240  
241 day => 'DAYOFMONTH(?)',
242 dayofmonth => 'DAYOFMONTH(?)',
243  
244 monthly => "DATE_FORMAT(?, '%Y-%m')",
245 month => 'MONTH(?)',
246  
247 annually => 'YEAR(?)',
248 year => 'YEAR(?)',
249  
250 dayofweek => "DAYOFWEEK(?) - 1", # 1-7, 1 - Sunday
251 dayofyear => "DAYOFYEAR(?)", # 1-366
252 weekofyear => "WEEK(?)", # skip mode argument, so it can be controlled in mysql config
253 };
254 }
255  
256  
257 =head2 ConvertTimezoneFunction
258  
259 Custom implementation of L<DBIx::SearchBuilder::Handle/ConvertTimezoneFunction>.
260  
261 Use the following query to get list of timezones:
262  
263 SELECT Name FROM mysql.time_zone_name;
264  
265 Read docs about keeping timezone data up to date:
266  
267 http://dev.mysql.com/doc/refman/5.5/en/time-zone-upgrades.html
268  
269 =cut
270  
271 0 ▶sub ConvertTimezoneFunction {
Subroutine ConvertTimezoneFunction: not called CC=5 SCAR=34.0
Pod documented
272 0 my $self = shift;
273 0 my %args = (
274 From => 'UTC',
275 To => undef,
276 Field => '',
277 @_
278 );
279 0 ▶ return $args{'Field'} unless $args{From} && $args{'To'};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"From"} and $args{"To"} 0 0 0
Condition0%0/3
$args{"From"} and $args{"To"}
!ll&&!rl&&r
000
MC/DC0%0/2
$args{"From"} and $args{"To"}
$args{"From"} $args{"To"}
Truth table0%0/3
A and B
A= $args{"From"}B= $args{"To"}
ABresult
0X0
100
111
280 0 ▶ return $args{'Field'} if lc $args{From} eq lc $args{'To'};
Branch: 1 branch
BranchTrueFalseTotal
if lc $args{"From"} eq lc $args{"To"} 0 0 0
281 0 my $dbh = $self->dbh;
282 0 $_ = $dbh->quote( $_ ) foreach @args{'From', 'To'};
283 0 return "CONVERT_TZ( $args{'Field'}, $args{'From'}, $args{'To'} )";
284 }
285  
286 0 ▶sub _DateTimeIntervalFunction {
Subroutine _DateTimeIntervalFunction: not called CC=1 SCAR=6.9
287 0 my $self = shift;
288 0 my %args = ( From => undef, To => undef, @_ );
289  
290 0 return "TIMESTAMPDIFF(SECOND, $args{'From'}, $args{'To'})";
291 }
292  
293  
294 =head2 QuoteName
295  
296 Quote table or column name to avoid reserved word errors.
297  
298 =cut
299  
300 # over-rides inherited method
301 1 ▶sub QuoteName {
Subroutine QuoteName: called CC=2 SCAR=7.6
Pod documented
302 1 my ($self, $name) = @_;
303 # use dbi built in quoting if we have a connection,
304 1 ▶ if ($self->dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dbh) 0 1 1
305 0 return $self->SUPER::QuoteName($name);
306 }
307  
308 1 return sprintf('`%s`', $name);
309 }
310  
311 4 ▶sub DequoteName {
Subroutine DequoteName: called CC=3 SCAR=11.2
Pod documented
312 4 my ($self, $name) = @_;
313  
314 # If we have a handle, the base class can do it for us
315 4 ▶ if ($self->dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dbh) 0 4 4
316 0 return $self->SUPER::DequoteName($name);
317 }
318  
319 4 ▶ if ($name =~ /^`(.*)`$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /^`(.*)`$/) 1 3 4
320 1 return $1;
321 }
322 3 return $name;
323 }
324  
325 0 ▶sub _ExtractBindValues {
Subroutine _ExtractBindValues: not called CC=1 SCAR=6.9
326 0 my $self = shift;
327 0 my $value = shift;
328 0 return $self->SUPER::_ExtractBindValues( $value, '\\' );
329 }
330  
331 0 ▶sub _IsMariaDB {
Subroutine _IsMariaDB: not called CC=1 SCAR=6.9
332 0 my $self = shift;
333  
334 # We override DatabaseVersion to chop off "-MariaDB-whatever", so
335 # call super here to get the original version
336 0 my $v = $self->SUPER::DatabaseVersion();
337  
338 0 return ($v =~ /mariadb/i);
339 }
340  
341 0 ▶sub _RequireQuotedTables {
Subroutine _RequireQuotedTables: not called CC=3 SCAR=24.8
342 0 my $self = shift;
343  
344 # MariaDB version does not match mysql, and hasn't added new reserved words
345 0 ▶ return 0 if $self->_IsMariaDB;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_IsMariaDB 0 0 0
346  
347 0 my $version = $self->DatabaseVersion;
348  
349 # Get major version number by chopping off everything after the first "."
350 0 $version =~ s/\..*//;
351 0 ▶ if ( $version >= 8 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($version >= 8) 0 0 0
352 0 return 1;
353 }
354 0 return 0;
355 }
356  
357 =head2 HasSupportForCombineSearchAndCount
358  
359 MariaDB 10.2+ and MySQL 8+ support this.
360  
361 =cut
362  
363 0 ▶sub HasSupportForCombineSearchAndCount {
Subroutine HasSupportForCombineSearchAndCount: not called CC=4 SCAR=30.0
Pod documented
364 0 my $self = shift;
365 0 my ($version) = $self->DatabaseVersion =~ /^(\d+\.\d+)/;
366  
367 0 ▶ if ( $self->_IsMariaDB ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_IsMariaDB) { } 0 0 0
368 0 ▶ return (version->parse('v'.$version) >= version->parse('v10.2')) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
'version'->parse('v' . $version) >= 'version'->parse('v10.2') ? : 0 0 0
369 }
370 else {
371 0 ▶ return (version->parse('v'.$version) >= version->parse('v8')) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
'version'->parse('v' . $version) >= 'version'->parse('v8') ? : 0 0 0
372 }
373 }
374  
375 0 ▶sub CastAsDecimal {
Subroutine CastAsDecimal: not called CC=2 SCAR=17.9
Pod documented
376 0 my $self = shift;
377 0 ▶ my $field = shift or return;
Branch: 1 branch
BranchTrueFalseTotal
my $field = shift() or return 0 0 0
378  
379 # CAST($field AS DECIMAL) rounds values to integers by default. It supports
380 # specific precisions like CAST($field AS DECIMAL(5,2)), but we don't know
381 # the precisions in advance. +0 works like other dbs.
382 0 return "($field+0)";
383 }
384  
385 2 1;
« SearchBuilder/Handle/MariaDB.pm ↑ Summary SearchBuilder/Handle/Pg.pm »