Fast/SQL.pm

filter: Statementstmt 85.7% 848 / 989 Branchbran 62.6% 238 / 380 Conditioncond 47.8% 111 / 232 MC/DCmcdc 23.4% 31 / 132 Subroutinesub 89.0% 81 / 91 Podpod 97.1% 34 / 35 totaltotal 72.2% 1343 / 1859 CC 307 SCAR 36.3
CC
307
Cov
75%
page
462.0
_expand_in
56.0
like
56.0
CRAP 37.6
« Fast/Profile/MariaDB.pm ↑ Summary Fast.pm »
1 package DBIx::Fast::SQL;
2  
3 34 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 34 ▶use Object::Pad 0.807;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 34 our $VERSION = '0.20';
7 34 ▶use DBI ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 34 ▶use DBIx::Fast::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 34 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 # Query and CRUD layer of DBIx::Fast, composed into the main class as a role.
12 # Object::Pad classes cannot span files, so the role owns the statement state
13 # ($sql/$p/$results/$last_id/$last_sql) and reaches the rest of the object
14 # (db/Q/dbd/schema/Exception/set_error/...) through the composed interface.
15  
16 role DBIx::Fast::SQL {
17  
18 # Statement state. Same attributes these fields had on the class, so the
19 # public API (sql/p accessors, read-only results/last_id/last_sql) and the
20 # encapsulation guarantees are unchanged.
21 field $sql :accessor = undef;
22 60 ▶ field $last_sql :reader = undef;
Subroutine sql: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ and $sql = shift() 7 53 60
23 8 ▶ field $p :accessor = undef;
Subroutine last_sql: called CC=1 SCAR=0.0
Pod documented
24 48 ▶ field $results :reader = undef;
Subroutine p: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ and $p = shift() 1 47 48
25 3 ▶ field $last_id :reader = undef;
Subroutine results: called CC=1 SCAR=0.0
Pod documented
26 3 ▶ field $_affected_rows :reader(rows) = undef; # rows affected by the last write
Subroutine last_id: called CC=1 SCAR=0.0
Pod documented
27  
28 # json_columns (see DBIx::Fast POD): table => { col => 1 } ('*' = any table)
29 # for writes, and the union of the names for reads. undef when not
30 # configured, so the hot paths pay nothing.
31 5 ▶ field $_json_write;
Subroutine rows: called CC=1 SCAR=0.0
Pod documented
32 34 field $_json_read;
33 34 field $_json_codec;
34 # True when the timestamps option is set (see DBIx::Fast::_timestamps_for);
35 # lets every writer skip the stamping code with a field test.
36 34 field $_ts_on;
37 2 ▶ method _timestamps_on () { $_ts_on = 1 }
Subroutine _timestamps_on: called CC=1 SCAR=0.0
38 34 field $_json_bytes; # same codec in UTF-8 byte mode (see _json_decode_rows)
39  
40 4 ▶ method _configure_json ($spec) {
Subroutine _configure_json: called CC=8 SCAR=21.0
41 4 ▶ $self->Exception("json_columns must be a hashref of table => [columns]")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 1 3 4
42 unless ref $spec eq 'HASH';
43 3 my (%write, %read);
44 3 for my $table (keys %$spec) {
45 4 my $cols = $spec->{$table};
46 4 ▶ $self->Exception("json_columns: '$table' must map to an arrayref of columns")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cols eq "ARRAY" 1 3 4
47 unless ref $cols eq 'ARRAY';
48 3 ▶ $self->TableName($table) unless $table eq '*';
Branch: 1 branch
BranchTrueFalseTotal
unless $table eq "*" 2 1 3
49 3 for my $col (@$cols) {
50 3 $self->_safe_id($col);
51 2 $write{$table}{$col} = 1;
52 2 $read{$col} = 1;
53 }
54 }
55 1 ▶ return unless %read;
Branch: 1 branch
BranchTrueFalseTotal
unless %read 0 1 1
56 1 ($_json_write, $_json_read) = (\%write, \%read);
57 1 my $class = eval { require Cpanel::JSON::XS; 'Cpanel::JSON::XS' }
58 1 ▶ || do { require JSON::PP; 'JSON::PP' };
Condition33%1/3
eval { do { require Cpanel::JSON::XS; 'Cpanel::JSON::XS' } } || do { require JSON::PP; 'JSON::PP' }
l!l&&r!l&&!r
100
MC/DC0%0/2
eval { do { require Cpanel::JSON::XS; 'Cpanel::JSON::XS' } } || do { require JSON::PP; 'JSON::PP' }
eval { do { require Cpanel::JSON::XS; 'Cpanel::JSON::XS' } } do { require JSON::PP; 'JSON::PP' }
Truth table33%1/3
A || B
A= eval { do { require Cpanel::JSON::XS; 'Cpanel::JSON::XS' } }B= do { require JSON::PP; 'JSON::PP' }
ABresult
1X1
011
000
59 1 $_json_codec = $class->new->canonical;
60 1 $_json_bytes = $class->new->canonical->utf8;
61 34 }
62  
63 # A copy of $row with hash/array values of the table's JSON columns encoded
64 # (the caller's hash is not modified); $row itself when nothing applies.
65 5 ▶ method _json_encode_row ($table, $row) {
Subroutine _json_encode_row: called CC=9 SCAR=23.3
66 5 ▶ return $row unless $_json_write && ref $row eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $_json_write and ref $row eq "HASH" 0 5 5
Condition33%1/3
$_json_write and ref $row eq "HASH"
!ll&&!rl&&r
005
MC/DC0%0/2
$_json_write and ref $row eq "HASH"
$_json_write ref $row eq "HASH"
Truth table33%1/3
A and B
A= $_json_writeB= ref $row eq "HASH"
ABresult
0X0
100
111
67 5 ▶ my $cols = { %{ $_json_write->{'*'} // {} }, %{ $_json_write->{$table} // {} } };
Condition50%2/4
$_json_write->{"*"} // {}
l!l
50
$_json_write->{$table} // {}
l!l
50
MC/DC0%0/1
$_json_write->{"*"} // {}
$_json_write->{"*"}
MC/DC0%0/1
$_json_write->{$table} // {}
$_json_write->{$table}
Truth table50%1/2
A
A= $_json_write->{"*"}
Aresult
11
00
Truth table50%1/2
A
A= $_json_write->{$table}
Aresult
11
00
68 5 my @enc = grep { exists $row->{$_} && (ref $row->{$_} eq 'HASH'
69 10 ▶ || ref $row->{$_} eq 'ARRAY') } keys %$cols;
Condition66%4/6
exists $row->{$_} && (ref $row->{$_} eq 'HASH' || ref $row->{$_} eq 'ARRAY')
!ll&&!rl&&r
406
ref $row->{$_} eq "HASH" or ref $row->{$_} eq "ARRAY"
l!l&&r!l&&!r
330
MC/DC33%1/3
exists $row->{$_} && (ref $row->{$_} eq 'HASH' || ref $row->{$_} eq 'ARRAY')
exists $row->{$_} ref $row->{$_} eq "HASH" ref $row->{$_} eq "ARRAY"
Truth table75%3/4
A && B or C
A= exists $row->{$_}B= ref $row->{$_} eq "HASH"C= ref $row->{$_} eq "ARRAY"
ABCresult
0XX0
1000
11X1
1011
70 5 ▶ return $row unless @enc;
Branch: 1 branch
BranchTrueFalseTotal
unless @enc 0 5 5
71 5 my %r = %$row;
72 5 $r{$_} = $_json_codec->encode($r{$_}) for @enc;
73 5 return \%r;
74 34 }
75  
76 1 ▶ method _json_encode_rows ($table, $rows) {
Subroutine _json_encode_rows: called CC=2 SCAR=7.0
77 1 ▶ return $rows unless $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
unless $_json_write 0 1 1
78 1 return [ map { $self->_json_encode_row($table, $_) } @$rows ];
79 34 }
80  
81 # Decode the JSON columns of fetched rows in place: only values that look
82 # like a JSON object/array; anything else (or malformed JSON) is left as is.
83 # JSON text is UTF-8: a driver without its UTF-8 flag (SQLite without
84 # sqlite_unicode, DBD::mysql without mysql_enable_utf8mb4) hands back the
85 # raw bytes, which are decoded as UTF-8; already-decoded character strings
86 # (DBD::Pg, DBD::MariaDB) as characters. Non-ASCII then round-trips on
87 # every driver whatever its flags.
88 3 ▶ method _json_decode_rows ($rows) {
Subroutine _json_decode_rows: called CC=11 SCAR=25.8
89 3 ▶ for my $row (ref $rows eq 'HASH' ? $rows : @$rows) {
Branch: 1 branch
BranchTrueFalseTotal
ref $rows eq 'HASH' ? : 1 2 3
90 5 ▶ next unless ref $row eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 0 5 5
91 5 for my $col (keys %$_json_read) {
92 10 my $v = $row->{$col};
93 10 ▶ next unless defined $v && !ref $v && $v =~ /\A\s*[\[{]/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and not ref $v and $v =~ /\A\s*[\[{]/u 4 6 10
Condition66%4/6
defined $v and not ref $v and $v =~ /\A\s*[\[{]/u
!ll&&!rl&&r
406
defined $v and not ref $v
!ll&&!rl&&r
406
MC/DC33%1/3
defined $v and not ref $v and $v =~ /\A\s*[\[{]/u
defined $v not ref $v $v =~ /\A\s*[\[{]/u
Truth table50%2/4
A and not(B) and C
A= defined $vB= not ref $vC= $v =~ /\A\s*[\[{]/u
ABCresult
0XX0
10X0
1100
1111
94 my $d = utf8::is_utf8($v)
95 0 ▶ ? eval { $_json_codec->decode($v) }
Condition33%1/3
eval { do { $_json_bytes->decode($v) } } // eval { do { $_json_codec->decode($v) } }
l!l&&r!l&&!r
600
MC/DC0%0/2
eval { do { $_json_bytes->decode($v) } } // eval { do { $_json_codec->decode($v) } }
eval { do { $_json_bytes->decode($v) } } eval { do { $_json_codec->decode($v) } }
Truth table33%1/3
A // B
A= eval { do { $_json_bytes->decode($v) } }B= eval { do { $_json_codec->decode($v) } }
ABresult
1X1
011
000
96 6 ▶ : eval { $_json_bytes->decode($v) } // eval { $_json_codec->decode($v) };
Branch: 1 branch
BranchTrueFalseTotal
utf8::is_utf8($v) ? : 0 6 6
97 6 ▶ $row->{$col} = $d if defined $d;
Branch: 1 branch
BranchTrueFalseTotal
if defined $d 6 0 6
98 }
99 }
100 3 return $rows;
101 34 }
102  
103 # CRUD statement cache. SQL::Abstract 2 needs 100-175us to render even a
104 # one-column INSERT/UPDATE/DELETE, yet for plain-scalar specs the SQL text
105 # depends only on the table and the (sorted) column names and the binds are
106 # the values in that same sorted order. SQL::Abstract stays the single
107 # source of truth: it renders each shape once, on the first miss.
108 34 field %_crud_sql;
109  
110 144 ▶ method _crud_stmt ($key, $render) {
Subroutine _crud_stmt: called CC=3 SCAR=11.0
111 144 ▶ %_crud_sql = () if keys %_crud_sql >= 1_000; # bound data-driven shapes
Branch: 1 branch
BranchTrueFalseTotal
if keys %_crud_sql >= 1000 0 144 144
112 144 ▶ return $_crud_sql{$key} //= ($render->())[0];
Condition100%3/3
$_crud_sql{$key} //= (&$render())[0]
l!l&&r!l&&!r
587313
MC/DC100%2/2
$_crud_sql{$key} //= (&$render())[0]
$_crud_sql{$key} (&$render())[0]
Truth table100%3/3
A //= B
A= $_crud_sql{$key}B= (&$render())[0]
ABresult
1X1
011
000
113 34 }
114  
115 # A WHERE hash the cache can serve: col => defined plain scalar only
116 # (undef means IS NULL, refs are operators - both go through SQL::Abstract).
117 12 ▶ sub _plain_where ($w) {
Subroutine _plain_where: called CC=6 SCAR=21.8
118 12 ▶ return 0 unless ref $w eq 'HASH' && %$w;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $w eq "HASH" and %$w 0 12 12
Condition33%1/3
ref $w eq "HASH" and %$w
!ll&&!rl&&r
0012
MC/DC0%0/2
ref $w eq "HASH" and %$w
ref $w eq "HASH" %$w
Truth table33%1/3
A and B
A= ref $w eq "HASH"B= %$w
ABresult
0X0
100
111
119 12 ▶ for (values %$w) { return 0 if !defined || ref }
Branch: 1 branch
BranchTrueFalseTotal
if not defined $_ or ref $_ 0 12 12
Condition33%1/3
not defined $_ or ref $_
l!l&&r!l&&!r
0012
MC/DC0%0/2
not defined $_ or ref $_
not defined $_ ref $_
Truth table33%1/3
not(A) or B
A= not defined $_B= ref $_
ABresult
1X1
011
000
120 12 return 1;
121 }
122  
123 320 ▶ method _track ($code) {
Subroutine _track: called CC=3 SCAR=11.0
124 320 ▶ if (my $tracker = $self->_active_tracker) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tracker = $self->_active_tracker) 17 303 320
125 17 my $t0 = Time::HiRes::time();
126 17 my $res = $code->();
127 17 ▶ $tracker->add_query($sql, $p // [], $t0, Time::HiRes::time());
Condition50%1/2
$p // []
l!l
170
MC/DC0%0/1
$p // []
$p
Truth table50%1/2
A
A= $p
Aresult
11
00
128 17 $last_sql = $sql;
129 17 return $res;
130 }
131 303 $last_sql = $sql;
132  
133 303 return $code->();
134 34 }
135  
136 # Statement-handle cache, replacing DBI's prepare_cached (Perl code in
137 # DBI.pm, ~15% of a simple read). Same semantics as its if_active=3 mode: a
138 # cached handle that is still Active (a live query() iterator on the same
139 # SQL) is replaced by a fresh one. Emptied by DBIx::Fast's on_connect hook on
140 # every (re)connect, so a handle never outlives its connection.
141 34 field %_sth_cache;
142 158 ▶ method _reset_sth_cache () { %_sth_cache = () }
Subroutine _reset_sth_cache: called CC=1 SCAR=0.0
143  
144 511 ▶ method _prepare ($dbh, $stmt) {
Subroutine _prepare: called CC=5 SCAR=16.1
145 511 my $sth = $_sth_cache{$stmt};
146 511 ▶ return $sth if $sth && !$sth->FETCH('Active');
Branch: 1 branch
BranchTrueFalseTotal
if $sth and not $sth->FETCH("Active") 163 348 511
Condition100%3/3
$sth and not $sth->FETCH("Active")
!ll&&!rl&&r
3408163
MC/DC100%2/2
$sth and not $sth->FETCH("Active")
$sth not $sth->FETCH("Active")
Truth table100%3/3
A and not(B)
A= $sthB= not $sth->FETCH("Active")
ABresult
0X0
100
111
147 348 ▶ $sth = $dbh->prepare($stmt) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sth = $dbh->prepare($stmt) or return undef 326 21 347
148 326 ▶ %_sth_cache = () if keys %_sth_cache >= 1_000; # bound data-driven SQL
Branch: 1 branch
BranchTrueFalseTotal
if keys %_sth_cache >= 1000 0 326 326
149 326 return $_sth_cache{$stmt} = $sth;
150 34 }
151  
152 # Run the current $sql/$p and shape the result with $shape (one of the
153 # _shape_* subs below, which take the executed handle - or undef when the
154 # prepare failed under RaiseError => 0 - and return the value). Without an
155 # active tracker (the normal case) nothing is allocated per call: no
156 # closure, no extra frame; with one, the query is timed and recorded.
157 190 ▶ method _fetch ($shape) {
Subroutine _fetch: called CC=10 SCAR=23.3
158 # Inline check (this runs on every read): only a statement with an
159 # arrayref bind pays for the IN (?) rewrite.
160 190 ▶ if ($p) { for (@$p) { if (ref $_ eq 'ARRAY') { $self->_expand_in_binds; last } } }
Branch: 2 branches
BranchTrueFalseTotal
if ($p) 189 1 190
if (ref $_ eq "ARRAY") 0 123 123
161 190 my $res;
162 190 ▶ if (my $tracker = $self->_active_tracker) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tracker = $self->_active_tracker) { } 11 179 190
163 11 my $t0 = Time::HiRes::time();
164 11 $res = $shape->($self->_read_exec);
165 11 ▶ $tracker->add_query($sql, $p // [], $t0, Time::HiRes::time());
Condition50%1/2
$p // []
l!l
110
MC/DC0%0/1
$p // []
$p
Truth table50%1/2
A
A= $p
Aresult
11
00
166 11 $last_sql = $sql;
167 }
168 else {
169 179 $last_sql = $sql;
170 179 $res = $shape->($self->_read_exec);
171 }
172 185 ▶ $self->_json_decode_rows($res)
Branch: 1 branch
BranchTrueFalseTotal
if $_json_read and $shape == \&DBIx::Fast::SQL::_shape_rows || $shape == \&DBIx::Fast::SQL::_shape_hash and $res 3 182 185
Condition88%8/9
$_json_read and $shape == \&DBIx::Fast::SQL::_shape_rows || $shape == \&DBIx::Fast::SQL::_shape_hash and $res
!ll&&!rl&&r
18203
$_json_read and $shape == \&DBIx::Fast::SQL::_shape_rows || $shape == \&DBIx::Fast::SQL::_shape_hash
!ll&&!rl&&r
18023
$shape == \&DBIx::Fast::SQL::_shape_rows or $shape == \&DBIx::Fast::SQL::_shape_hash
l!l&&r!l&&!r
212
MC/DC75%3/4
$_json_read and $shape == \&DBIx::Fast::SQL::_shape_rows || $shape == \&DBIx::Fast::SQL::_shape_hash and $res
$_json_read $shape == \&DBIx::Fast::SQL::_shape_rows $shape == \&DBIx::Fast::SQL::_shape_hash $res
Truth table66%4/6
A and B or C and D
A= $_json_readB= $shape == \&DBIx::Fast::SQL::_shape_rowsC= $shape == \&DBIx::Fast::SQL::_shape_hashD= $res
ABCDresult
0XXX0
100X0
11X00
10100
11X11
10111
173 if $_json_read && ($shape == \&_shape_rows || $shape == \&_shape_hash) && $res;
174 185 return $res;
175 34 }
176  
177 # "IN (?)" with an arrayref bind becomes "IN (?, ?, ?)" with the elements as
178 # binds. Only placeholders inside IN ( ... ) are expanded - an arrayref
179 # elsewhere stays one bind (DBD::Pg arrays, "= ANY(?)") - and placeholders
180 # inside quoted literals/identifiers are not counted. Returns undef for an
181 # empty list ("IN ()" is invalid SQL, and IN (NULL) would make NOT IN match
182 # nothing).
183 0 ▶ sub _expand_in ($stmt, $binds) {
Subroutine _expand_in: not called CC=7 SCAR=40.3
184 0 my ($out, @nb) = ('');
185 0 my $i = 0;
186 0 ▶ while ($stmt =~ m{\G( '(?:[^'\\]|\\.|'')*'
Branch: 1 branch
BranchTrueFalseTotal
if ($stmt =~ /\G( '(?:[^'\\]|\\.|'')*' | "(?:[^"\\]|\\.|"")*" | `[^`]*` | [^'"`?]+ | \? | . )/cgsux) 0 0 0
187 | "(?:[^"\\]|\\.|"")*"
188 | `[^`]*`
189 | [^'"`?]+
190 | \?
191 | . )}gcxs) {
192 0 my $tok = $1;
193 0 ▶ if ($tok ne '?') { $out .= $tok; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($tok ne "?") 0 0 0
194 0 my $v = $binds->[$i++];
195 0 ▶ if (ref $v eq 'ARRAY' && $out =~ /\bIN\s*\(\s*\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq 'ARRAY' and $out =~ /\bIN\s*\(\s*\z/iu) { } 0 0 0
Condition0%0/3
ref $v eq "ARRAY" and $out =~ /\bIN\s*\(\s*\z/iu
!ll&&!rl&&r
000
MC/DC0%0/2
ref $v eq "ARRAY" and $out =~ /\bIN\s*\(\s*\z/iu
ref $v eq "ARRAY" $out =~ /\bIN\s*\(\s*\z/iu
Truth table0%0/3
A and B
A= ref $v eq "ARRAY"B= $out =~ /\bIN\s*\(\s*\z/iu
ABresult
0X0
100
111
196 0 ▶ return undef unless @$v;
Branch: 1 branch
BranchTrueFalseTotal
unless @$v 0 0 0
197 0 $out .= join(', ', ('?') x @$v);
198 0 push @nb, @$v;
199 }
200 else {
201 0 $out .= '?';
202 0 push @nb, $v;
203 }
204 }
205 0 ▶ push @nb, @{$binds}[ $i .. $#$binds ] if $i < @$binds; # arity left to DBI
Branch: 1 branch
BranchTrueFalseTotal
if $i < @$binds 0 0 0
206 0 return ($out, \@nb);
207 }
208  
209  
210 # Apply _expand_in to the current statement when any bind is an arrayref.
211 0 ▶ method _expand_in_binds () {
Subroutine _expand_in_binds: not called CC=2 SCAR=17.9
212 0 my ($stmt, $binds) = _expand_in($sql, $p);
213 0 ▶ $self->Exception("IN (?) bound to an empty list") unless defined $stmt;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $stmt 0 0 0
214 0 ($sql, $p) = ($stmt, $binds);
215 34 }
216  
217 40 ▶ sub _shape_rows ($sth) {
Subroutine _shape_rows: called CC=2 SCAR=6.9
218 40 ▶ return [] unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 13 27 40
219 27 my $rows = $sth->fetchall_arrayref({});
220 27 $sth->finish;
221 27 return $rows;
222 }
223  
224 60 ▶ sub _shape_hash ($sth) {
Subroutine _shape_hash: called CC=2 SCAR=7.0
225 60 ▶ return undef unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 60 60
226 60 my $row = $sth->fetchrow_hashref;
227 60 $sth->finish;
228 60 return $row;
229 }
230  
231 # First column of first row - the historical val() contract (DBI leaves a
232 # multi-column scalar selectrow_array undefined; pin FIRST so val() never
233 # changes value between builds). Also count()'s shape.
234 66 ▶ sub _shape_val ($sth) {
Subroutine _shape_val: called CC=2 SCAR=6.9
235 66 ▶ return undef unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 1 65 66
236 65 my @row = $sth->fetchrow_array;
237 65 $sth->finish;
238 65 return $row[0];
239 }
240  
241 # fetchall_arrayref([0]) loops in DBI's C path - much faster than a per-row
242 # Perl fetch on large result sets.
243 6 ▶ sub _shape_column ($sth) {
Subroutine _shape_column: called CC=2 SCAR=7.0
244 6 ▶ return [] unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 6 6
245 6 my $col = $sth->fetchall_arrayref([0]);
246 6 $sth->finish;
247 6 return [ map { $_->[0] } @$col ];
248 }
249  
250 4 ▶ sub _shape_exists ($sth) {
Subroutine _shape_exists: called CC=3 SCAR=11.0
251 4 ▶ return 0 unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 4 4
252 4 my ($one) = $sth->fetchrow_array;
253 4 $sth->finish;
254 4 ▶ return $one ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$one ? : 3 1 4
255 }
256  
257 7 ▶ sub _shape_kv ($sth) {
Subroutine _shape_kv: called CC=3 SCAR=11.3
258 7 ▶ return {} unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 7 7
259 7 ▶ my $pair = $sth->fetchall_arrayref([0, 1]) // [];
Condition50%1/2
$sth->fetchall_arrayref([0, 1]) // []
l!l
70
MC/DC0%0/1
$sth->fetchall_arrayref([0, 1]) // []
$sth->fetchall_arrayref([0, 1])
Truth table50%1/2
A
A= $sth->fetchall_arrayref([0, 1])
Aresult
11
00
260 7 $sth->finish;
261 7 return { map { $_->[0] => $_->[1] } @$pair };
262 }
263  
264 2 ▶ sub _shape_sth ($sth) { $sth }
Subroutine _shape_sth: called CC=1 SCAR=0.0
265  
266 # Prepare (through the statement cache) + execute of the current $sql/$p for
267 # the read methods. With strict_reads a failed prepare/execute throws;
268 # otherwise the historical behaviour stands (HandleError records the error
269 # and the read returns an empty result). Returns undef when the prepare
270 # itself failed (SQLite/Pg reject bad SQL at prepare time; MariaDB only at
271 # execute), and each shape maps that to the same empty value MariaDB gives.
272 192 ▶ method _read_exec () {
Subroutine _read_exec: called CC=6 SCAR=18.0
273 192 my $dbh = $self->db->dbh;
274 192 my $sth = $self->_prepare($dbh, $sql);
275 192 ▶ unless ($sth) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 21 171 192
276 21 ▶ $self->_read_failed($dbh) if $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if $self->strict_reads 6 15 21
277 15 return undef;
278 }
279 171 ▶ my $rv = $p ? $sth->execute(@{$p}) : $sth->execute;
Branch: 1 branch
BranchTrueFalseTotal
$p ? : 170 1 171
280 171 ▶ $self->_read_failed($sth) unless $rv || !$self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
unless $rv or not $self->strict_reads 0 171 171
Condition33%1/3
$rv or not $self->strict_reads
l!l&&r!l&&!r
17100
MC/DC0%0/2
$rv or not $self->strict_reads
$rv not $self->strict_reads
Truth table33%1/3
A or not(B)
A= $rvB= not $self->strict_reads
ABresult
1X1
011
000
281 171 return $sth;
282 34 }
283  
284 6 ▶ method _read_failed ($h) {
Subroutine _read_failed: called CC=1 SCAR=0.0
285 # HandleError has already recorded the driver error; the text appends it.
286 6 $self->_db_fail("read failed", $h);
287 34 }
288  
289 # $sth->rows normalized: DBI's '0E0' -> 0, unknown (-1) -> undef.
290 # Rows affected by a write: execute()'s return value (DBI's contract: the
291 # count, '0E0' for none, -1 unknown), falling back to $sth->rows. The return
292 # value is the reliable one - DBD::Pg reports rows() -1 (or a stale count on
293 # a reused handle) after INSERT ... ON CONFLICT DO NOTHING.
294 318 ▶ sub _affected ($sth, $rv = undef) {
Subroutine _affected: called CC=7 SCAR=26.7
295 318 ▶ my $n = defined $rv && $rv >= 0 ? $rv : $sth ? $sth->rows : undef;
Branch: 2 branches
BranchTrueFalseTotal
defined $rv && $rv >= 0 ? : 318 0 318
$sth ? : 0 0 0
Condition33%1/3
defined $rv and $rv >= 0
!ll&&!rl&&r
00318
MC/DC0%0/2
defined $rv and $rv >= 0
defined $rv $rv >= 0
Truth table33%1/3
A and B
A= defined $rvB= $rv >= 0
ABresult
0X0
100
111
296 318 ▶ return defined $n && $n >= 0 ? $n + 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $n && $n >= 0 ? : 318 0 318
Condition33%1/3
defined $n and $n >= 0
!ll&&!rl&&r
00318
MC/DC0%0/2
defined $n and $n >= 0
defined $n $n >= 0
Truth table33%1/3
A and B
A= defined $nB= $n >= 0
ABresult
0X0
100
111
297 }
298  
299 2 ▶ method q ($stmt, @params) {
Subroutine q: called CC=1 SCAR=0.0
Pod documented
300 2 $sql = $stmt;
301 2 $p = \@params;
302 34 }
303  
304 40 ▶ method all (@args) {
Subroutine all: called CC=1 SCAR=0.0
Pod documented
305 40 $sql = shift @args;
306 40 $p = \@args;
307  
308 40 return $results = $self->_fetch(\&_shape_rows);
309 34 }
310  
311 2 ▶ method flat (@args) {
Subroutine flat: called CC=1 SCAR=0.0
Pod documented
312 2 $sql = shift @args;
313 2 $p = \@args;
314  
315 2 $results = $self->_fetch(\&_shape_column);
316 2 return @$results;
317 34 }
318  
319 61 ▶ method hash (@args) {
Subroutine hash: called CC=1 SCAR=0.0
Pod documented
320 61 $sql = shift @args;
321 61 $p = \@args;
322  
323 61 return $results = $self->_fetch(\&_shape_hash);
324 34 }
325  
326 60 ▶ method val (@args) {
Subroutine val: called CC=1 SCAR=0.0
Pod documented
327 60 $sql = shift @args;
328 60 $p = \@args;
329  
330 60 return $results = $self->_fetch(\&_shape_val);
331 34 }
332  
333 5 ▶ method array (@args) {
Subroutine array: called CC=1 SCAR=0.0
Pod documented
334 5 $sql = shift @args;
335 5 $p = \@args;
336  
337 5 return $results = $self->_fetch(\&_shape_column);
338 34 }
339  
340 2 ▶ method query ($stmt, @params) {
Subroutine query: called CC=1 SCAR=0.0
Pod documented
341 2 $sql = $stmt;
342 2 $p = \@params;
343  
344 2 return DBIx::Fast::Result->new(sth => $self->_fetch(\&_shape_sth));
345 34 }
346  
347 8 ▶ method count ($table_name, $skeel = undef) {
Subroutine count: called CC=4 SCAR=13.9
Pod documented
348 8 my $table = $self->TableName($table_name);
349 8 my $qtable = $self->_quote_ident_path($table);
350  
351 8 $sql = "SELECT COUNT(*) FROM $qtable";
352 8 $p = [];
353  
354 8 ▶ if ($skeel) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skeel) 7 1 8
355 7 my ($parts, $params) = $self->_where_parts($skeel);
356 6 ▶ $sql .= ' WHERE ' . join(' AND ', @$parts) if @$parts;
Branch: 1 branch
BranchTrueFalseTotal
if @$parts 6 0 6
357 6 $p = $params;
358 }
359  
360 7 return $results = $self->_fetch(\&_shape_val);
361 34 }
362  
363 # 1 if at least one row of $table matches the count()-style WHERE, else 0.
364 # Same validation as count() (TableName + _make_where whitelist); LIMIT 1
365 # lets the server stop at the first match.
366 5 ▶ method exists ($table_name, $skeel = undef) {
Subroutine exists: called CC=4 SCAR=13.9
Pod documented
367 5 my $table = $self->TableName($table_name);
368 5 my $qtable = $self->_quote_ident_path($table);
369  
370 5 $sql = "SELECT 1 FROM $qtable";
371 5 $p = [];
372  
373 5 ▶ if ($skeel) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skeel) 4 1 5
374 4 my ($parts, $params) = $self->_where_parts($skeel);
375 3 ▶ $sql .= ' WHERE ' . join(' AND ', @$parts) if @$parts;
Branch: 1 branch
BranchTrueFalseTotal
if @$parts 3 0 3
376 3 $p = $params;
377 }
378 4 $sql .= ' LIMIT 1';
379  
380 4 return $results = $self->_fetch(\&_shape_exists);
381 34 }
382  
383 # First column => second column, as a hashref (a later duplicate key wins).
384 8 ▶ method kv (@args) {
Subroutine kv: called CC=1 SCAR=0.0
Pod documented
385 8 $sql = shift @args;
386 8 $p = \@args;
387  
388 8 return $results = $self->_fetch(\&_shape_kv);
389 34 }
390  
391 # Rows keyed by the $key column, as a hashref of hashrefs (DBI's
392 # fetchall_hashref: a later row with the same key wins).
393 2 ▶ method all_by ($key, @args) {
Subroutine all_by: called CC=3 SCAR=11.4
Pod documented
394 2 ▶ $self->Exception("all_by: key column required")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and length $key 0 2 2
Condition33%1/3
defined $key and length $key
!ll&&!rl&&r
002
MC/DC0%0/2
defined $key and length $key
defined $key length $key
Truth table33%1/3
A and B
A= defined $keyB= length $key
ABresult
0X0
100
111
395 unless defined $key && length $key;
396  
397 2 $sql = shift @args;
398 2 $p = \@args;
399  
400 2 ▶ $results = $self->_track(sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
401 2 ▶ my $sth = $self->_read_exec or return {};
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->_read_exec or return {} 1 0 1
402 1 ▶ return $sth->fetchall_hashref($key) // {};
Condition50%1/2
$sth->fetchall_hashref($key) // {}
l!l
10
MC/DC0%0/1
$sth->fetchall_hashref($key) // {}
$sth->fetchall_hashref($key)
Truth table50%1/2
A
A= $sth->fetchall_hashref($key)
Aresult
11
00
403 2 });
404 1 return $results;
405 34 }
406  
407 0 ▶ method _make_where ($skeel) {
Subroutine _make_where: not called CC=2 SCAR=17.9
408 0 my ($parts, $params) = $self->_where_parts($skeel);
409 0 ▶ $sql .= ' WHERE ' . join(' AND ', @$parts) if @$parts;
Branch: 1 branch
BranchTrueFalseTotal
if @$parts 0 0 0
410 0 $p = $params;
411 34 }
412  
413 # The count()/exists()/where() condition builder: ($parts, $binds) for a
414 # { column => condition } hashref, without touching the statement state.
415 # Operators are whitelisted; columns validated and quoted per segment.
416 32 ▶ method _where_parts ($skeel) {
Subroutine _where_parts: called CC=25 SCAR=37.3
417 32 state %VALID_OPS = map { $_ => 1 }
418 ('=', '!=', '<>', '<', '<=', '>', '>=', 'LIKE', 'NOT', 'BETWEEN', 'IS',
419 'IN', 'NOT IN', 'CONTAINS', 'PREFIX', 'SUFFIX');
420 32 state %LIKE_MODE = (CONTAINS => 'contains', PREFIX => 'prefix',
421 SUFFIX => 'suffix');
422  
423 32 my @params;
424 my @parts;
425  
426 32 for my $K (sort keys %{$skeel}) {
427 # Validate AND quote the column by segment, so a qualified name like
428 # "t.col" becomes "t"."col" (not the bogus single identifier "t.col").
429 33 my $col = $self->_quote_ident_path($K);
430  
431 33 my $val = $skeel->{$K};
432  
433 # Fast path for the common case: col => defined plain value.
434 33 ▶ if (defined $val && !ref $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val and not ref $val) 26 7 33
Condition100%3/3
defined $val and not ref $val
!ll&&!rl&&r
1626
MC/DC100%2/2
defined $val and not ref $val
defined $val not ref $val
Truth table100%3/3
A and not(B)
A= defined $valB= not ref $val
ABresult
0X0
100
111
435 26 push @parts, "$col = ?";
436 26 push @params, $val;
437 26 next;
438 }
439  
440 7 ▶ my $op = ref $val eq 'ARRAY' ? 'IN' : '='; # [ ... ] means IN (...)
Branch: 1 branch
BranchTrueFalseTotal
ref $val eq 'ARRAY' ? : 0 7 7
441  
442 7 ▶ if (ref $val eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq "HASH") 6 1 7
443 6 ▶ $self->Exception("Multiple operators for column $K")
Branch: 1 branch
BranchTrueFalseTotal
if keys %$val > 1 1 5 6
444 if keys %$val > 1;
445 5 ($op) = keys %$val;
446 $self->Exception("Invalid operator: $op")
447 5 ▶ unless $VALID_OPS{uc $op};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_OPS{uc $op} 1 4 5
448 4 $val = $val->{$op};
449 4 $op = uc $op;
450 }
451  
452 5 ▶ if ($op eq 'IN' || $op eq 'NOT IN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IN" or $op eq "NOT IN") 0 5 5
Condition33%1/3
$op eq "IN" or $op eq "NOT IN"
l!l&&r!l&&!r
005
MC/DC0%0/2
$op eq "IN" or $op eq "NOT IN"
$op eq "IN" $op eq "NOT IN"
Truth table33%1/3
A or B
A= $op eq "IN"B= $op eq "NOT IN"
ABresult
1X1
011
000
453 0 ▶ $self->Exception("$op requires an arrayref of values")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val eq "ARRAY" 0 0 0
454 unless ref $val eq 'ARRAY';
455 0 ▶ $self->Exception("$op with an empty list for column $K")
Branch: 1 branch
BranchTrueFalseTotal
unless @$val 0 0 0
456 unless @$val;
457 0 push @parts, "$col $op (" . join(', ', ('?') x @$val) . ')';
458 0 push @params, @$val;
459 0 next;
460 }
461  
462 5 ▶ if (my $mode = $LIKE_MODE{$op}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $mode = $LIKE_MODE{$op}) 0 5 5
463 # Escaped user text, never a pattern: see like().
464 0 ▶ $self->Exception("$op requires a value") unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 0 0
465 0 push @parts, "$col LIKE ? ESCAPE '!'";
466 0 push @params, $self->like($val, $mode);
467 0 next;
468 }
469  
470 5 ▶ if ($op eq 'BETWEEN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "BETWEEN") 1 4 5
471 1 ▶ $self->Exception("BETWEEN requires a two-element arrayref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val eq "ARRAY" and @$val == 2 0 1 1
Condition33%1/3
ref $val eq "ARRAY" and @$val == 2
!ll&&!rl&&r
001
MC/DC0%0/2
ref $val eq "ARRAY" and @$val == 2
ref $val eq "ARRAY" @$val == 2
Truth table33%1/3
A and B
A= ref $val eq "ARRAY"B= @$val == 2
ABresult
0X0
100
111
472 unless ref $val eq 'ARRAY' && @$val == 2;
473 1 push @parts, "$col BETWEEN ? AND ?";
474 1 push @params, @$val;
475 1 next;
476 }
477  
478 4 ▶ if ($op eq 'IS') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IS") 1 3 4
479 1 ▶ $self->Exception("IS only accepts undef (IS NULL); "
Branch: 1 branch
BranchTrueFalseTotal
if defined $val 0 1 1
480 . "use { '!=' => undef } for IS NOT NULL")
481 if defined $val;
482 1 push @parts, "$col IS NULL";
483 1 next;
484 }
485  
486 # An undef operand collapses to NULL semantics: "col = NULL" / "col != NULL"
487 # are never true in SQL, so emit IS [NOT] NULL with no bind value.
488 3 ▶ if (!defined $val) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $val) 2 1 3
489 2 ▶ if ($op eq '=') {
Branch: 2 branches
BranchTrueFalseTotal
if ($op eq '=') { } 1 1 2
elsif ($op eq '!=' or $op eq '<>' or $op eq 'NOT') { } 1 0 1
490 1 push @parts, "$col IS NULL";
491 }
492 ▶ elsif ($op eq '!=' || $op eq '<>' || $op eq 'NOT') {
Condition33%2/6
$op eq "!=" or $op eq "<>" or $op eq "NOT"
l!l&&r!l&&!r
100
$op eq "!=" or $op eq "<>"
l!l&&r!l&&!r
100
MC/DC0%0/3
$op eq "!=" or $op eq "<>" or $op eq "NOT"
$op eq "!=" $op eq "<>" $op eq "NOT"
Truth table25%1/4
A or B or C
A= $op eq "!="B= $op eq "<>"C= $op eq "NOT"
ABCresult
1XX1
01X1
0011
0000
493 1 push @parts, "$col IS NOT NULL";
494 }
495 else {
496 0 $self->Exception("Operator '$op' does not accept an undef value");
497 }
498 2 next;
499 }
500  
501 # NOT on its own maps to <> for portability.
502 1 ▶ my $sql_op = $op eq 'NOT' ? '<>' : $op;
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'NOT' ? : 0 1 1
503 1 push @parts, "$col $sql_op ?";
504 1 push @params, $val;
505 }
506  
507 30 return (\@parts, \@params);
508 34 }
509  
510 # ('WHERE ...', @binds) for a { column => condition } filter, ready to
511 # append to hand-written SQL. Filters whose value is undef are SKIPPED (an
512 # absent form field means "do not filter"); ask for NULL explicitly with
513 # { col => { IS => undef } }. Same operators as count(), plus IN/NOT IN
514 # (an arrayref value is IN) and CONTAINS/PREFIX/SUFFIX (escaped LIKE).
515 # Returns ('') with no binds when nothing is left to filter on.
516 0 ▶ method where ($filters = {}) {
Subroutine where: not called CC=4 SCAR=30.0
Pod documented
517 0 ▶ $self->Exception("where: filters must be a hashref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $filters eq "HASH" 0 0 0
518 unless ref $filters eq 'HASH';
519 0 my %active = map { $_ => $filters->{$_} }
520 0 grep { defined $filters->{$_} } keys %$filters;
521 0 my ($parts, $params) = $self->_where_parts(\%active);
522 0 ▶ return ('') unless @$parts;
Branch: 1 branch
BranchTrueFalseTotal
unless @$parts 0 0 0
523 0 return ('WHERE ' . join(' AND ', @$parts), @$params);
524 34 }
525  
526 # A LIKE pattern from user text: %, _ and the escape character itself are
527 # escaped with '!', so the text matches literally. Use it as
528 # "col LIKE ? ESCAPE '!'" - '!' (unlike backslash) needs no special
529 # handling in SQLite, MariaDB/MySQL or PostgreSQL.
530 0 ▶ method like ($value, $mode = 'contains') {
Subroutine like: not called CC=7 SCAR=40.3
Pod documented
531 0 state %OK = map { $_ => 1 } qw(contains prefix suffix exact);
532 $self->Exception("like: mode must be contains, prefix, suffix or exact")
533 0 ▶ unless $OK{$mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $OK{$mode} 0 0 0
534 0 ▶ (my $v = $value // '') =~ s/([!%_])/!$1/g;
Condition0%0/2
$value // ""
l!l
00
MC/DC0%0/1
$value // ""
$value
Truth table0%0/2
A
A= $value
Aresult
11
00
535 0 ▶ return $mode eq 'prefix' ? "$v%"
Branch: 3 branches
BranchTrueFalseTotal
$mode eq 'prefix' ? : 0 0 0
$mode eq 'suffix' ? : 0 0 0
$mode eq 'exact' ? : 0 0 0
536 : $mode eq 'suffix' ? "%$v"
537 : $mode eq 'exact' ? $v
538 : "%$v%";
539 34 }
540  
541 # Run $code once per slice of at most $size elements of @$list (each slice
542 # an arrayref, e.g. for "... IN (?)"), returning the callbacks' results in
543 # order. For lists too long for one statement (max_allowed_packet, bind
544 # limits).
545 0 ▶ method in_chunks ($list, $size, $code) {
Subroutine in_chunks: not called CC=7 SCAR=40.3
Pod documented
546 0 ▶ $self->Exception("in_chunks: list arrayref, positive size and coderef required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" and defined $size and $size =~ /\A[1-9]\d*\z/u and ref $code eq "CODE" 0 0 0
Condition0%0/9
ref $list eq "ARRAY" and defined $size and $size =~ /\A[1-9]\d*\z/u and ref $code eq "CODE"
!ll&&!rl&&r
000
ref $list eq "ARRAY" and defined $size and $size =~ /\A[1-9]\d*\z/u
!ll&&!rl&&r
000
ref $list eq "ARRAY" and defined $size
!ll&&!rl&&r
000
MC/DC0%0/4
ref $list eq "ARRAY" and defined $size and $size =~ /\A[1-9]\d*\z/u and ref $code eq "CODE"
ref $list eq "ARRAY" defined $size $size =~ /\A[1-9]\d*\z/u ref $code eq "CODE"
Truth table0%0/5
A and B and C and D
A= ref $list eq "ARRAY"B= defined $sizeC= $size =~ /\A[1-9]\d*\z/uD= ref $code eq "CODE"
ABCDresult
0XXX0
10XX0
110X0
11100
11111
547 unless ref $list eq 'ARRAY' && defined $size && $size =~ /\A[1-9]\d*\z/
548 && ref $code eq 'CODE';
549 0 my @out;
550 0 ▶ for (my $i = 0; $i < @$list; $i += $size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$list) 0 0 0
551 0 my $end = $i + $size - 1;
552 0 ▶ $end = $#$list if $end > $#$list;
Branch: 1 branch
BranchTrueFalseTotal
if $end > $list->$#* 0 0 0
553 0 push @out, $code->([ @{$list}[ $i .. $end ] ]);
554 }
555 0 return @out;
556 34 }
557  
558 # One page of $stmt: { rows, total, page, per, pages }. total comes from
559 # COUNT(*) over the statement; ORDER BY only accepts columns listed in
560 # allowed_order ("col", "col DESC" or "-col"), quoted; LIMIT/OFFSET are
561 # validated integers (not binds - client-side prepares would quote them).
562 # $stmt must not carry its own ORDER BY / LIMIT when these are used.
563 0 ▶ method page ($stmt, $binds = [], %o) {
Subroutine page: not called CC=21 SCAR=61.4
Pod documented
564 0 ▶ $self->Exception("page: binds must be an arrayref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $binds eq "ARRAY" 0 0 0
565 unless ref $binds eq 'ARRAY';
566 0 ▶ my $max_per = $o{max_per} // 1000;
Condition0%0/2
$o{"max_per"} // 1000
l!l
00
MC/DC0%0/1
$o{"max_per"} // 1000
$o{"max_per"}
Truth table0%0/2
A
A= $o{"max_per"}
Aresult
11
00
567 0 ▶ my $page = $o{page} // 1;
Condition0%0/2
$o{"page"} // 1
l!l
00
MC/DC0%0/1
$o{"page"} // 1
$o{"page"}
Truth table0%0/2
A
A= $o{"page"}
Aresult
11
00
568 0 ▶ my $per = $o{per} // 20;
Condition0%0/2
$o{"per"} // 20
l!l
00
MC/DC0%0/1
$o{"per"} // 20
$o{"per"}
Truth table0%0/2
A
A= $o{"per"}
Aresult
11
00
569 0 for ([ page => $page ], [ per => $per ]) {
570 0 ▶ $self->Exception("page: $_->[0] must be a positive integer")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_->[1] and $_->[1] =~ /\A[1-9]\d*\z/u 0 0 0
Condition0%0/3
defined $_->[1] and $_->[1] =~ /\A[1-9]\d*\z/u
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_->[1] and $_->[1] =~ /\A[1-9]\d*\z/u
defined $_->[1] $_->[1] =~ /\A[1-9]\d*\z/u
Truth table0%0/3
A and B
A= defined $_->[1]B= $_->[1] =~ /\A[1-9]\d*\z/u
ABresult
0X0
100
111
571 unless defined $_->[1] && $_->[1] =~ /\A[1-9]\d*\z/;
572 }
573 0 ▶ $self->Exception("page: per exceeds max_per ($max_per)") if $per > $max_per;
Branch: 1 branch
BranchTrueFalseTotal
if $per > $max_per 0 0 0
574  
575 0 my $order = '';
576 0 ▶ if (defined $o{order} && length $o{order}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $o{"order"} and length $o{"order"}) 0 0 0
Condition0%0/3
defined $o{"order"} and length $o{"order"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $o{"order"} and length $o{"order"}
defined $o{"order"} length $o{"order"}
Truth table0%0/3
A and B
A= defined $o{"order"}B= length $o{"order"}
ABresult
0X0
100
111
577 0 ▶ my %allowed = map { $_ => 1 } @{ $o{allowed_order} // [] };
Condition0%0/2
$o{"allowed_order"} // []
l!l
00
MC/DC0%0/1
$o{"allowed_order"} // []
$o{"allowed_order"}
Truth table0%0/2
A
A= $o{"allowed_order"}
Aresult
11
00
578 0 my @terms;
579 0 ▶ for my $term (ref $o{order} eq 'ARRAY' ? @{ $o{order} } : $o{order}) {
Branch: 1 branch
BranchTrueFalseTotal
ref $o{'order'} eq 'ARRAY' ? : 0 0 0
580 0 ▶ my ($minus, $col, $dir) =
Branch: 1 branch
BranchTrueFalseTotal
() = $term =~ /\A\s*(-)?([A-Za-z_][\w.]*)(?:\s+(ASC|DESC))?\s*\z/iu or $self->Exception("page: invalid order term") 0 0 0
581 $term =~ /\A\s*(-)?([A-Za-z_][\w.]*)(?:\s+(ASC|DESC))?\s*\z/i
582 or $self->Exception("page: invalid order term");
583 $self->Exception("page: ordering by '$col' is not allowed")
584 0 ▶ unless $allowed{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $allowed{$col} 0 0 0
585 0 ▶ $dir = $minus ? 'DESC' : uc($dir // 'ASC');
Branch: 1 branch
BranchTrueFalseTotal
$minus ? : 0 0 0
Condition0%0/2
$dir // "ASC"
l!l
00
MC/DC0%0/1
$dir // "ASC"
$dir
Truth table0%0/2
A
A= $dir
Aresult
11
00
586 0 push @terms, $self->_quote_ident_path($col) . " $dir";
587 }
588 0 $order = ' ORDER BY ' . join(', ', @terms);
589 }
590  
591 0 ▶ my $total = $self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds) // 0;
Condition0%0/2
$self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds) // 0
l!l
00
MC/DC0%0/1
$self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds) // 0
$self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds)
Truth table0%0/2
A
A= $self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds)
Aresult
11
00
592 0 my $offset = ($page - 1) * $per;
593 0 my $rows = $self->all("$stmt$order LIMIT $per OFFSET $offset", @$binds);
594  
595 return {
596 0 ▶ rows => $rows,
Branch: 1 branch
BranchTrueFalseTotal
$total ? : 0 0 0
597 total => $total + 0,
598 page => $page + 0,
599 per => $per + 0,
600 pages => $total ? int(($total + $per - 1) / $per) : 0,
601 };
602 34 }
603  
604 140 ▶ method exec ($stmt, @params) {
Subroutine exec: called CC=5 SCAR=16.8
Pod documented
605 140 ▶ $self->Exception("exec() : SQL statement required") unless $stmt;
Branch: 1 branch
BranchTrueFalseTotal
unless $stmt 0 140 140
606  
607 140 $sql = $stmt;
608 140 $p = \@params;
609 140 ▶ for (@params) { if (ref $_ eq 'ARRAY') { $self->_expand_in_binds; last } }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_ eq "ARRAY") 0 58 58
610 140 my @binds = @$p;
611  
612 140 my $sth = $self->_prepare($self->db->dbh, $sql);
613  
614 139 my $rv;
615 139 ▶ $self->_track(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
616 139 ▶ $rv = @binds ? $sth->execute(@binds) : $sth->execute();
Branch: 1 branch
BranchTrueFalseTotal
@binds ? : 32 107 139
617 139 1;
618 139 });
619  
620 139 ▶ if ($DBI::err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DBI::err) 0 139 139
621 0 $self->set_error($DBI::err, $DBI::errstr);
622 0 $_affected_rows = undef;
623 0 return;
624 }
625  
626 139 $_affected_rows = _affected($sth, $rv);
627 139 return $sth;
628 34 }
629  
630 1 ▶ method execute ($stmt, $extra = undef, $type = 'arrayref') {
Subroutine execute: called CC=5 SCAR=16.5
Pod documented
631 1 $sql = $stmt;
632  
633 # make_sen sets $p from $extra; without $extra there are no binds, so clear
634 # any $p left over from a previous query (else it is bound to this
635 # statement - a stray-value or arity-mismatch failure).
636 1 ▶ if ($extra) { $self->make_sen($extra) }
Branch: 1 branch
BranchTrueFalseTotal
if ($extra) { } 0 1 1
637 1 else { $p = undef }
638  
639 1 ▶ $results = $self->_fetch($type eq 'hash' ? \&_shape_hash : \&_shape_rows);
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'hash' ? : 0 1 1
640 34 }
641  
642  
643 # A copy of $row with the table's timestamp columns added where the row does
644 # not set them already: $which 'insert' fills created + updated, 'update'
645 # only updated. The caller's hash is never modified. Returns $row itself
646 # when no timestamps apply.
647 22 ▶ method _stamp ($table, $row, $which) {
Subroutine _stamp: called CC=7 SCAR=19.5
648 22 ▶ my ($created, $updated, $value) = $self->_timestamps_for($table) or return $row;
Branch: 1 branch
BranchTrueFalseTotal
() = $self->_timestamps_for($table) or return $row 20 2 22
649 20 my %r = %$row;
650 20 ▶ $r{$created} = $value if $which eq 'insert' && $created && !exists $r{$created};
Branch: 1 branch
BranchTrueFalseTotal
if $which eq "insert" and $created and not exists $r{$created} 14 6 20
Condition100%6/6
$which eq "insert" and $created and not exists $r{$created}
!ll&&!rl&&r
4214
$which eq "insert" and $created
!ll&&!rl&&r
2216
MC/DC100%3/3
$which eq "insert" and $created and not exists $r{$created}
$which eq "insert" $created not exists $r{$created}
Truth table100%4/4
A and B and not(C)
A= $which eq "insert"B= $createdC= not exists $r{$created}
ABCresult
0XX0
10X0
1100
1111
651 20 ▶ $r{$updated} = $value if $updated && !exists $r{$updated};
Branch: 1 branch
BranchTrueFalseTotal
if $updated and not exists $r{$updated} 18 2 20
Condition66%2/3
$updated and not exists $r{$updated}
!ll&&!rl&&r
0218
MC/DC50%1/2
$updated and not exists $r{$updated}
$updated not exists $r{$updated}
Truth table66%2/3
A and not(B)
A= $updatedB= not exists $r{$updated}
ABresult
0X0
100
111
652 20 return \%r;
653 34 }
654  
655 # Placeholder for one value of a bound INSERT: a scalarref (only ever the
656 # server-side timestamp from _stamp, after user values were validated) is
657 # inlined as SQL, anything else is a ?.
658 137 ▶ sub _ph ($v) { ref $v eq 'SCALAR' ? $$v : '?' }
Subroutine _ph: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
ref $v eq 'SCALAR' ? : 6 131 137
659  
660 # CRUD
661 80 ▶ method insert ($table_name, $skeel, @extra) {
Subroutine insert: called CC=6 SCAR=17.9
Pod documented
662 80 my $table = $self->TableName($table_name);
663  
664 80 ▶ $skeel = $self->extra_args($skeel, @extra) if @extra;
Branch: 1 branch
BranchTrueFalseTotal
if @extra 0 80 80
665 80 ▶ $skeel = $self->_json_encode_row($table, $skeel) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 1 79 80
666  
667 80 $self->_safe_data($skeel);
668 80 ▶ $skeel = $self->_stamp($table, $skeel, 'insert') if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 8 72 80
669  
670 80 my @cols = sort keys %$skeel;
671 80 ▶ if (@cols && !grep { ref } @{$skeel}{@cols}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cols and not grep({ref $_;} @{$skeel;}{@cols})) { } 78 2 80
Condition66%2/3
@cols and not grep({ref $_;} @{$skeel;}{@cols})
!ll&&!rl&&r
0278
MC/DC50%1/2
@cols and not grep({ref $_;} @{$skeel;}{@cols})
@cols not grep({ref $_;} @{$skeel;}{@cols})
Truth table66%2/3
A and not(B)
A= @colsB= not grep({ref $_;} @{$skeel;}{@cols})
ABresult
0X0
100
111
672 $sql = $self->_crud_stmt(join("\0", 'I', $table, @cols),
673 78 ▶ sub { $self->Q->insert($table, $skeel) });
Subroutine __ANON__: called CC=1 SCAR=0.0
674 78 $self->execute_prepare(@{$skeel}{@cols});
675 }
676 else {
677 2 my ($stmt, @bind) = $self->Q->insert($table, $skeel);
678 2 $sql = $stmt;
679 2 $self->execute_prepare(@bind);
680 }
681  
682 80 $self->_update_last_id($table);
683 80 $self->_cache_invalidate_table($table);
684 80 return $last_id;
685 34 }
686  
687 102 ▶ method _update_last_id ($table) {
Subroutine _update_last_id: called CC=5 SCAR=22.1
688 102 my $dbd = $self->dbd;
689 102 my $dbh = $self->db->dbh;
690 102 ▶ if ($dbd eq 'SQLite') { $last_id = $dbh->sqlite_last_insert_rowid() }
Branch: 4 branches
BranchTrueFalseTotal
if ($dbd eq 'SQLite') { } 102 0 102
elsif ($dbd eq 'MariaDB') { } 0 0 0
elsif ($dbd eq 'mysql') { } 0 0 0
elsif ($dbd eq 'Pg') { } 0 0 0
691 0 elsif ($dbd eq 'MariaDB') { $last_id = $dbh->{mariadb_insertid} }
692 0 elsif ($dbd eq 'mysql') { $last_id = $dbh->{mysql_insertid} }
693 elsif ($dbd eq 'Pg') {
694 # DBD::Pg guesses the serial sequence from the table name. That fails for
695 # non-default schemas, renamed/custom sequences, or non-serial PKs. Guard
696 # it so a failed lookup yields undef last_id instead of dying AFTER the row
697 # was already inserted. NOTE: Pg last_id requires a serial/identity PK; for
698 # other cases use INSERT ... RETURNING via exec()/query().
699 0 $last_id = eval { $dbh->last_insert_id(undef, undef, $table, undef) };
700 }
701 34 }
702  
703 9 ▶ method update ($table_name, $skeel, @extra) {
Subroutine update: called CC=7 SCAR=19.5
Pod documented
704 9 my $table = $self->TableName($table_name);
705  
706 9 ▶ $skeel->{sen} = $self->extra_args($skeel->{sen}, @extra)
Branch: 1 branch
BranchTrueFalseTotal
if @extra 0 9 9
707 if @extra;
708  
709 my $set = $_json_write ? $self->_json_encode_row($table, $skeel->{sen})
710 9 ▶ : $skeel->{sen};
Branch: 1 branch
BranchTrueFalseTotal
$_json_write ? : 1 8 9
711 9 $self->_safe_data($set);
712 9 $self->_safe_columns($skeel->{where});
713  
714 9 my $where = $skeel->{where};
715 9 ▶ $set = $self->_stamp($table, $set, 'update') if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 2 7 9
716 9 my @scols = sort keys %$set;
717 9 my $sth;
718 9 ▶ if (@scols && !grep { ref } @{$set}{@scols} and _plain_where($where)) {
Branch: 1 branch
BranchTrueFalseTotal
if (@scols and not grep({ref $_;} @{$set;}{@scols}) and _plain_where($where)) { } 8 1 9
Condition66%4/6
@scols and not grep({ref $_;} @{$set;}{@scols}) and _plain_where($where)
!ll&&!rl&&r
108
@scols and not grep({ref $_;} @{$set;}{@scols})
!ll&&!rl&&r
018
MC/DC33%1/3
@scols and not grep({ref $_;} @{$set;}{@scols}) and _plain_where($where)
@scols not grep({ref $_;} @{$set;}{@scols}) _plain_where($where)
Truth table50%2/4
A and not(B) and C
A= @scolsB= not grep({ref $_;} @{$set;}{@scols})C= _plain_where($where)
ABCresult
0XX0
10X0
1100
1111
719 8 my @wcols = sort keys %$where;
720 $sql = $self->_crud_stmt(join("\0", 'U', $table, @scols, '', @wcols),
721 8 ▶ sub { $self->Q->update($table, $set, $where) });
Subroutine __ANON__: called CC=1 SCAR=0.0
722 8 $sth = $self->execute_prepare(@{$set}{@scols}, @{$where}{@wcols});
723 }
724 else {
725 1 my ($stmt, @bind) = $self->Q->update($table, $set, $where);
726 1 $sql = $stmt;
727 1 $sth = $self->execute_prepare(@bind);
728 }
729 9 $self->_cache_invalidate_table($table);
730 9 return $sth;
731 34 }
732  
733 9 ▶ method up ($table_name, $data, $where, $time_col = undef) {
Subroutine up: called CC=3 SCAR=11.1
Pod documented
734 9 ▶ if ($time_col) {
Branch: 1 branch
BranchTrueFalseTotal
if ($time_col) { } 0 9 9
735 0 $self->update($table_name,
736 { sen => $data, where => $where }, time => $time_col);
737 } else {
738 9 $self->update($table_name,
739 { sen => $data, where => $where });
740 }
741 34 }
742  
743 4 ▶ method delete ($table_name, $skeel) {
Subroutine delete: called CC=2 SCAR=7.1
Pod documented
744 4 my $table = $self->TableName($table_name);
745  
746 4 $self->_safe_columns($skeel);
747  
748 4 my $sth;
749 4 ▶ if (_plain_where($skeel)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_plain_where($skeel)) { } 4 0 4
750 4 my @wcols = sort keys %$skeel;
751 $sql = $self->_crud_stmt(join("\0", 'D', $table, @wcols),
752 4 ▶ sub { $self->Q->delete($table, $skeel) });
Subroutine __ANON__: called CC=1 SCAR=0.0
753 4 $sth = $self->execute_prepare(@{$skeel}{@wcols});
754 }
755 else {
756 0 my ($stmt, @bind) = $self->Q->delete($table, $skeel);
757 0 $sql = $stmt;
758 0 $sth = $self->execute_prepare(@bind);
759 }
760 4 $self->_cache_invalidate_table($table);
761 4 return $sth;
762 34 }
763  
764 56 ▶ method upsert ($table_name, $row, $conflict_keys, $update_cols = undef) {
Subroutine upsert: called CC=11 SCAR=24.1
Pod documented
765 56 ▶ $self->Exception("upsert: row hashref required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" and %$row 0 56 56
Condition33%1/3
ref $row eq "HASH" and %$row
!ll&&!rl&&r
0056
MC/DC0%0/2
ref $row eq "HASH" and %$row
ref $row eq "HASH" %$row
Truth table33%1/3
A and B
A= ref $row eq "HASH"B= %$row
ABresult
0X0
100
111
766 unless ref $row eq 'HASH' && %$row;
767 56 ▶ $self->Exception("upsert: conflict_keys arrayref required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $conflict_keys eq "ARRAY" and @$conflict_keys 0 56 56
Condition33%1/3
ref $conflict_keys eq "ARRAY" and @$conflict_keys
!ll&&!rl&&r
0056
MC/DC0%0/2
ref $conflict_keys eq "ARRAY" and @$conflict_keys
ref $conflict_keys eq "ARRAY" @$conflict_keys
Truth table33%1/3
A and B
A= ref $conflict_keys eq "ARRAY"B= @$conflict_keys
ABresult
0X0
100
111
768 unless ref $conflict_keys eq 'ARRAY' && @$conflict_keys;
769  
770 56 my $table = $self->TableName($table_name);
771 56 ▶ $row = $self->_json_encode_row($table, $row) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 1 55 56
772 56 $self->_safe_bind_row($row);
773 55 $self->_safe_id($_) for @$conflict_keys;
774  
775 # Without timestamps the statement depends only on the table, the
776 # columns, the conflict keys and update_cols as given: key the statement
777 # cache on those, so a repeated upsert skips normalizing/validating the
778 # update spec (done once, on the miss that built the statement - the row
779 # VALUES are still validated every call, above).
780 54 my @cols = sort keys %$row;
781 54 my $sets;
782 my $key;
783 54 ▶ if ($_ts_on) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ts_on) { } 2 52 54
784 # The update spec comes from the caller's columns (so a stamped created
785 # column is never overwritten on conflict); the stamped updated column
786 # is then always refreshed.
787 2 $sets = $self->_update_spec('upsert', $update_cols, $conflict_keys, \@cols);
788 2 $row = $self->_stamp($table, $row, 'insert');
789 2 $sets = $self->_touch_updated($table, $sets);
790 2 @cols = sort keys %$row;
791 2 ▶ $key = join("\0", 'S', $table, (map { ref $row->{$_} ? "$_=L" : $_ } @cols),
Branch: 1 branch
BranchTrueFalseTotal
ref $row->{$_} ? : 2 6 8
792 '', @$conflict_keys, '', _spec_key($sets));
793 }
794 else {
795 52 $key = join("\0", 'S', $table, @cols, '', @$conflict_keys, '',
796 _raw_spec_key($update_cols));
797 }
798  
799 $sql = $self->_crud_stmt($key,
800 48 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
801 48 ▶ $sets //= $self->_update_spec('upsert', $update_cols, $conflict_keys, \@cols);
Condition100%3/3
$sets //= $self->_update_spec("upsert", $update_cols, $conflict_keys, \@cols)
l!l&&r!l&&!r
23214
MC/DC100%2/2
$sets //= $self->_update_spec("upsert", $update_cols, $conflict_keys, \@cols)
$sets $self->_update_spec("upsert", $update_cols, $conflict_keys, \@cols)
Truth table100%3/3
A //= B
A= $setsB= $self->_update_spec("upsert", $update_cols, $conflict_keys, \@cols)
ABresult
1X1
011
000
802 26 my $dbh = $self->db->dbh;
803 26 my $qt = $self->_quote_ident_path($table);
804 26 my $qcols = join(', ', map { $dbh->quote_identifier($_) } @cols);
805 26 my $placeholders = join(', ', map { _ph($row->{$_}) } @cols);
806 26 my $clause = $self->_upsert_clause($conflict_keys, $sets, $qt);
807 26 "INSERT INTO " . $self->_upsert_target($qt) . " ($qcols) VALUES ($placeholders) $clause";
808 54 });
809 32 ▶ my @bind = $_ts_on ? (grep { ref ne 'SCALAR' } @{$row}{@cols}) : @{$row}{@cols};
Branch: 1 branch
BranchTrueFalseTotal
$_ts_on ? : 2 30 32
810 32 my $sth = $self->execute_prepare(@bind);
811 32 $self->_cache_invalidate_table($table);
812 32 return $sth;
813 34 }
814  
815 # Add the table's updated column to an upsert spec ('new'), unless the
816 # caller already says how to update it.
817 4 ▶ method _touch_updated ($table, $sets) {
Subroutine _touch_updated: called CC=5 SCAR=17.1
818 4 ▶ my (undef, $updated) = $self->_timestamps_for($table) or return $sets;
Branch: 1 branch
BranchTrueFalseTotal
my(undef, $updated) = $self->_timestamps_for($table) or return $sets 4 0 4
819 4 ▶ return $sets if !$updated || grep { (ref $_ ? $_->[0] : $_) eq $updated } @$sets;
Branch: 2 branches
BranchTrueFalseTotal
if not $updated or grep {(ref $_ ? $_->[0] : $_) eq $updated;} @$sets 0 4 4
ref $_ ? : 4 0 4
Condition33%1/3
not $updated or grep {(ref $_ ? $_->[0] : $_) eq $updated;} @$sets
l!l&&r!l&&!r
004
MC/DC0%0/2
not $updated or grep {(ref $_ ? $_->[0] : $_) eq $updated;} @$sets
not $updated grep {(ref $_ ? $_->[0] : $_) eq $updated;} @$sets
Truth table33%1/3
not(A) or B
A= not $updatedB= grep {(ref $_ ? $_->[0] : $_) eq $updated;} @$sets
ABresult
1X1
011
000
820 4 return [ @$sets, [ $updated, 'new' ] ];
821 34 }
822  
823 # Stamp every row of a batch (same values for all) - see _stamp.
824 4 ▶ method _stamp_rows ($table, $rows, $which) {
Subroutine _stamp_rows: called CC=2 SCAR=6.9
825 4 ▶ return $rows unless $self->_timestamps_for($table);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_timestamps_for($table) 0 4 4
826 4 return [ map { $self->_stamp($table, $_, $which) } @$rows ];
827 34 }
828  
829 # Runs $code->($slice) for consecutive slices of @$rows of at most $size and
830 # returns the sum of the results. Each slice is its own statement; wrap the
831 # call in txn() when all-or-nothing matters.
832 3 ▶ method _in_slices ($rows, $size, $code) {
Subroutine _in_slices: called CC=5 SCAR=16.1
833 3 ▶ $self->Exception("chunk must be a positive integer")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $size and $size =~ /\A[1-9]\d*\z/u 1 2 3
Condition66%2/3
defined $size and $size =~ /\A[1-9]\d*\z/u
!ll&&!rl&&r
012
MC/DC50%1/2
defined $size and $size =~ /\A[1-9]\d*\z/u
defined $size $size =~ /\A[1-9]\d*\z/u
Truth table66%2/3
A and B
A= defined $sizeB= $size =~ /\A[1-9]\d*\z/u
ABresult
0X0
100
111
834 unless defined $size && $size =~ /\A[1-9]\d*\z/;
835 2 my $total = 0;
836 2 ▶ for (my $i = 0; $i < @$rows; $i += $size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$rows) 8 2 10
837 8 my $end = $i + $size - 1;
838 8 ▶ $end = $#$rows if $end > $#$rows;
Branch: 1 branch
BranchTrueFalseTotal
if $end > $rows->$#* 2 6 8
839 8 $total += $code->([ @{$rows}[ $i .. $end ] ]);
840 }
841 2 return $total;
842 34 }
843  
844 16 ▶ method insert_many ($table_name, $rows, %opt) {
Subroutine insert_many: called CC=19 SCAR=29.8
Pod documented
845 16 ▶ $self->Exception("insert_many: at least one row required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rows eq "ARRAY" and @$rows 2 14 16
Condition100%3/3
ref $rows eq "ARRAY" and @$rows
!ll&&!rl&&r
1114
MC/DC100%2/2
ref $rows eq "ARRAY" and @$rows
ref $rows eq "ARRAY" @$rows
Truth table100%3/3
A and B
A= ref $rows eq "ARRAY"B= @$rows
ABresult
0X0
100
111
846 unless ref $rows eq 'ARRAY' && @$rows;
847 14 ▶ if (defined $opt{chunk} && @$rows > ($opt{chunk} =~ /\A\d+\z/ ? $opt{chunk} : 0)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opt{"chunk"} and @$rows > ($opt{"chunk"} =~ /\A\d+\z/u ? $opt{"chunk"} : 0)) 2 12 14
$opt{'chunk'} =~ /\A\d+\z/u ? : 2 0 2
Condition66%2/3
defined $opt{"chunk"} and @$rows > ($opt{"chunk"} =~ /\A\d+\z/u ? $opt{"chunk"} : 0)
!ll&&!rl&&r
1202
MC/DC50%1/2
defined $opt{"chunk"} and @$rows > ($opt{"chunk"} =~ /\A\d+\z/u ? $opt{"chunk"} : 0)
defined $opt{"chunk"} @$rows > ($opt{"chunk"} =~ /\A\d+\z/u ? $opt{"chunk"} : 0)
Truth table66%2/3
A and B
A= defined $opt{"chunk"}B= @$rows > ($opt{"chunk"} =~ /\A\d+\z/u ? $opt{"chunk"} : 0)
ABresult
0X0
100
111
848 2 my %rest = %opt;
849 2 delete $rest{chunk};
850 return $self->_in_slices($rows, $opt{chunk},
851 2 ▶ sub ($slice) { $self->insert_many($table_name, $slice, %rest) });
Subroutine __ANON__: called CC=1 SCAR=0.0
852 }
853 $self->Exception("insert_many: rows must be hashrefs")
854 12 ▶ if grep { ref $_ ne 'HASH' } @$rows;
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_ ne "HASH";} @$rows 0 12 12
855  
856 12 my $table = $self->TableName($table_name);
857 12 ▶ $rows = $self->_json_encode_rows($table, $rows) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 1 11 12
858 12 my @cols = sort keys %{ $rows->[0] };
859 12 $self->_safe_id($_) for @cols;
860  
861 # Same key set as row 0: same size and every row-0 column present
862 # (no per-row sort + join).
863 11 for my $i (1 .. $#$rows) {
864 40 my $r = $rows->[$i];
865 $self->Exception(
866 "insert_many: row $i has different columns than row 0")
867 40 ▶ if keys %$r != @cols || grep { !exists $r->{$_} } @cols;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$r != @cols or grep {not exists $r->{$_};} @cols 2 38 40
Condition66%2/3
keys %$r != @cols or grep {not exists $r->{$_};} @cols
l!l&&r!l&&!r
2038
MC/DC50%1/2
keys %$r != @cols or grep {not exists $r->{$_};} @cols
keys %$r != @cols grep {not exists $r->{$_};} @cols
Truth table66%2/3
A or B
A= keys %$r != @colsB= grep {not exists $r->{$_};} @cols
ABresult
1X1
011
000
868 }
869 9 my @bind = map { @{$_}{@cols} } @$rows;
870 9 $self->_safe_bind_values(\@bind);
871 9 ▶ if ($_ts_on) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ts_on) 2 7 9
872 2 $rows = $self->_stamp_rows($table, $rows, 'insert');
873 2 @cols = sort keys %{ $rows->[0] };
874 2 @bind = grep { ref ne 'SCALAR' } map { @{$_}{@cols} } @$rows;
875 }
876  
877 9 my $dbh = $self->db->dbh;
878 9 my $qt = $self->_quote_ident_path($table);
879 9 my $qcols = join(', ', map { $dbh->quote_identifier($_) } @cols);
880 9 my $row_ph = '(' . join(', ', map { _ph($rows->[0]{$_}) } @cols) . ')';
881 9 my $values = join(', ', ($row_ph) x scalar(@$rows));
882  
883 # ignore => 1: rows violating a UNIQUE/PRIMARY KEY are skipped (see
884 # insert_ignore); the return value is then the number actually inserted.
885 9 my $dbd = $self->dbd;
886 9 my ($verb, $tail) = ('INSERT INTO', '');
887 9 ▶ if ($opt{ignore}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"ignore"}) 1 8 9
888 1 ▶ if ($dbd eq 'MariaDB' || $dbd eq 'mysql') { $verb = 'INSERT IGNORE INTO' }
Branch: 2 branches
BranchTrueFalseTotal
if ($dbd eq 'MariaDB' or $dbd eq 'mysql') { } 0 1 1
elsif ($dbd eq 'SQLite') { } 1 0 1
Condition33%1/3
$dbd eq "MariaDB" or $dbd eq "mysql"
l!l&&r!l&&!r
001
MC/DC0%0/2
$dbd eq "MariaDB" or $dbd eq "mysql"
$dbd eq "MariaDB" $dbd eq "mysql"
Truth table33%1/3
A or B
A= $dbd eq "MariaDB"B= $dbd eq "mysql"
ABresult
1X1
011
000
889 1 elsif ($dbd eq 'SQLite') { $verb = 'INSERT OR IGNORE INTO' }
890 0 else { $tail = ' ON CONFLICT DO NOTHING' }
891 }
892  
893 9 $sql = "$verb $qt ($qcols) VALUES $values$tail";
894 9 $self->execute_prepare(@bind);
895  
896 9 $self->_update_last_id($table);
897 9 $self->_cache_invalidate_table($table);
898 9 ▶ return $opt{ignore} ? ($_affected_rows // 0) : scalar @$rows;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'ignore'} ? : 1 8 9
Condition50%1/2
$_affected_rows // 0
l!l
10
MC/DC0%0/1
$_affected_rows // 0
$_affected_rows
Truth table50%1/2
A
A= $_affected_rows
Aresult
11
00
899 34 }
900  
901 15 ▶ method upsert_many ($table_name, $rows, $conflict_keys, $update_cols = undef, %opt) {
Subroutine upsert_many: called CC=18 SCAR=29.6
Pod documented
902 15 ▶ $self->Exception("upsert_many: at least one row required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rows eq "ARRAY" and @$rows 0 15 15
Condition33%1/3
ref $rows eq "ARRAY" and @$rows
!ll&&!rl&&r
0015
MC/DC0%0/2
ref $rows eq "ARRAY" and @$rows
ref $rows eq "ARRAY" @$rows
Truth table33%1/3
A and B
A= ref $rows eq "ARRAY"B= @$rows
ABresult
0X0
100
111
903 unless ref $rows eq 'ARRAY' && @$rows;
904 15 ▶ if (defined $opt{chunk} && @$rows > ($opt{chunk} =~ /\A\d+\z/ ? $opt{chunk} : 0)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opt{"chunk"} and @$rows > ($opt{"chunk"} =~ /\A\d+\z/u ? $opt{"chunk"} : 0)) 1 14 15
$opt{'chunk'} =~ /\A\d+\z/u ? : 1 0 1
Condition66%2/3
defined $opt{"chunk"} and @$rows > ($opt{"chunk"} =~ /\A\d+\z/u ? $opt{"chunk"} : 0)
!ll&&!rl&&r
1401
MC/DC50%1/2
defined $opt{"chunk"} and @$rows > ($opt{"chunk"} =~ /\A\d+\z/u ? $opt{"chunk"} : 0)
defined $opt{"chunk"} @$rows > ($opt{"chunk"} =~ /\A\d+\z/u ? $opt{"chunk"} : 0)
Truth table66%2/3
A and B
A= defined $opt{"chunk"}B= @$rows > ($opt{"chunk"} =~ /\A\d+\z/u ? $opt{"chunk"} : 0)
ABresult
0X0
100
111
905 5 ▶ return $self->_in_slices($rows, $opt{chunk}, sub ($slice) {
Subroutine __ANON__: called CC=1 SCAR=0.0
906 5 $self->upsert_many($table_name, $slice, $conflict_keys, $update_cols)
907 1 });
908 }
909 $self->Exception("upsert_many: rows must be hashrefs")
910 14 ▶ if grep { ref $_ ne 'HASH' } @$rows;
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_ ne "HASH";} @$rows 0 14 14
911 14 ▶ $self->Exception("upsert_many: conflict_keys arrayref required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $conflict_keys eq "ARRAY" and @$conflict_keys 0 14 14
Condition33%1/3
ref $conflict_keys eq "ARRAY" and @$conflict_keys
!ll&&!rl&&r
0014
MC/DC0%0/2
ref $conflict_keys eq "ARRAY" and @$conflict_keys
ref $conflict_keys eq "ARRAY" @$conflict_keys
Truth table33%1/3
A and B
A= ref $conflict_keys eq "ARRAY"B= @$conflict_keys
ABresult
0X0
100
111
912 unless ref $conflict_keys eq 'ARRAY' && @$conflict_keys;
913  
914 14 my $table = $self->TableName($table_name);
915 14 ▶ $rows = $self->_json_encode_rows($table, $rows) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 0 14 14
916 14 my @cols = sort keys %{ $rows->[0] };
917 14 $self->_safe_id($_) for @cols;
918 14 $self->_safe_id($_) for @$conflict_keys;
919 13 my $sets = $self->_update_spec('upsert_many', $update_cols, $conflict_keys, \@cols);
920 13 ▶ $sets = $self->_touch_updated($table, $sets) if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 2 11 13
921  
922 # Same key set as row 0: same size and every row-0 column present
923 # (no per-row sort + join).
924 13 for my $i (1 .. $#$rows) {
925 34 my $r = $rows->[$i];
926 $self->Exception(
927 "upsert_many: row $i has different columns than row 0")
928 34 ▶ if keys %$r != @cols || grep { !exists $r->{$_} } @cols;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$r != @cols or grep {not exists $r->{$_};} @cols 0 34 34
Condition33%1/3
keys %$r != @cols or grep {not exists $r->{$_};} @cols
l!l&&r!l&&!r
0034
MC/DC0%0/2
keys %$r != @cols or grep {not exists $r->{$_};} @cols
keys %$r != @cols grep {not exists $r->{$_};} @cols
Truth table33%1/3
A or B
A= keys %$r != @colsB= grep {not exists $r->{$_};} @cols
ABresult
1X1
011
000
929 }
930  
931 13 my @bind = map { @{$_}{@cols} } @$rows;
932 13 $self->_safe_bind_values(\@bind);
933 13 ▶ if ($_ts_on) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ts_on) 2 11 13
934 2 $rows = $self->_stamp_rows($table, $rows, 'insert');
935 2 @cols = sort keys %{ $rows->[0] };
936 2 @bind = grep { ref ne 'SCALAR' } map { @{$_}{@cols} } @$rows;
937 }
938  
939 13 my $dbh = $self->db->dbh;
940 13 my $qt = $self->_quote_ident_path($table);
941 13 my $qcols = join(', ', map { $dbh->quote_identifier($_) } @cols);
942 13 my $row_ph = '(' . join(', ', map { _ph($rows->[0]{$_}) } @cols) . ')';
943 13 my $values = join(', ', ($row_ph) x scalar(@$rows));
944 13 my $clause = $self->_upsert_clause($conflict_keys, $sets, $qt);
945  
946 13 $sql = "INSERT INTO " . $self->_upsert_target($qt) . " ($qcols) VALUES $values $clause";
947 13 $self->execute_prepare(@bind);
948 13 $self->_cache_invalidate_table($table);
949  
950 13 return scalar @$rows;
951 34 }
952  
953  
954 # Builds the ON CONFLICT / ON DUPLICATE KEY UPDATE clause.
955 # Pg/SQLite use ON CONFLICT (cols) DO UPDATE SET c = excluded.c.
956 # MariaDB/mysql use ON DUPLICATE KEY UPDATE c = VALUES(c). The conflict_keys
957 # are validated for symmetry but not emitted in MariaDB syntax (any UNIQUE
958 # or PRIMARY KEY triggers the update there).
959 # The ON CONFLICT update spec, normalized to [ [col, mode], ... ]:
960 # undef every row column that is not a conflict key, 'new'
961 # [ cols ] those columns, 'new' (the historical form)
962 # { col => 'new' | '+' | { '+' => N } | \'SQL' }
963 # 'new' takes the incoming value, '+' adds it to the stored
964 # one (balances), { '+' => N } adds a constant (counters), a
965 # scalarref is literal SQL - the documented code-only escape
966 # hatch (a JSON body cannot carry one), e.g. \'CURRENT_TIMESTAMP'.
967 # A literal that reads the stored row is dialect-specific
968 # (PostgreSQL needs dbix_t.col); prefer the modes.
969 61 ▶ method _update_spec ($who, $update_cols, $conflict_keys, $cols) {
Subroutine _update_spec: called CC=19 SCAR=30.2
970 61 my @sets;
971 61 ▶ if (!defined $update_cols) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $update_cols) { } 12 49 61
elsif (ref $update_cols eq 'ARRAY') { } 7 42 49
elsif (ref $update_cols eq 'HASH') { } 42 0 42
972 12 my %ck = map { $_ => 1 } @$conflict_keys;
973 12 @sets = map { [ $_, 'new' ] } grep { !$ck{$_} } @$cols;
974 }
975 elsif (ref $update_cols eq 'ARRAY') {
976 7 @sets = map { [ $_, 'new' ] } @$update_cols;
977 }
978 elsif (ref $update_cols eq 'HASH') {
979 42 my %in = map { $_ => 1 } @$cols;
980 42 for my $col (sort keys %$update_cols) {
981 52 $self->_safe_id($col);
982 47 my $mode = $update_cols->{$col};
983 47 ▶ if (ref $mode eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $mode eq "HASH") 10 37 47
984 10 my ($op, $n) = %$mode;
985 10 ▶ $self->Exception("$who: { '+' => N } for $col needs a number")
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$mode == 1 and $op eq "+" and defined $n and not ref $n and $n =~ /\A-?\d+(?:\.\d+)?\z/u 5 5 10
Condition41%5/12
keys %$mode == 1 and $op eq "+" and defined $n and not ref $n and $n =~ /\A-?\d+(?:\.\d+)?\z/u
!ll&&!rl&&r
055
keys %$mode == 1 and $op eq "+" and defined $n and not ref $n
!ll&&!rl&&r
0010
keys %$mode == 1 and $op eq "+" and defined $n
!ll&&!rl&&r
0010
keys %$mode == 1 and $op eq "+"
!ll&&!rl&&r
0010
MC/DC20%1/5
keys %$mode == 1 and $op eq "+" and defined $n and not ref $n and $n =~ /\A-?\d+(?:\.\d+)?\z/u
keys %$mode == 1 $op eq "+" defined $n not ref $n $n =~ /\A-?\d+(?:\.\d+)?\z/u
Truth table33%2/6
A and B and C and not(D) and E
A= keys %$mode == 1B= $op eq "+"C= defined $nD= not ref $nE= $n =~ /\A-?\d+(?:\.\d+)?\z/u
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
986 unless keys %$mode == 1 && $op eq '+'
987 && defined $n && !ref $n && $n =~ /\A-?\d+(?:\.\d+)?\z/;
988 5 push @sets, [ $col, [ '+', $n ] ];
989 5 next;
990 }
991 37 ▶ if (ref $mode eq 'SCALAR') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $mode eq "SCALAR") 5 32 37
992 5 push @sets, [ $col, $mode ];
993 5 next;
994 }
995 32 ▶ $self->Exception("$who: update mode for $col must be 'new', '+', "
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mode and not ref $mode and $mode eq "new" || $mode eq "+" 5 27 32
Condition66%6/9
defined $mode and not ref $mode and $mode eq "new" || $mode eq "+"
!ll&&!rl&&r
0527
defined $mode and not ref $mode
!ll&&!rl&&r
0032
$mode eq "new" or $mode eq "+"
l!l&&r!l&&!r
7205
MC/DC50%2/4
defined $mode and not ref $mode and $mode eq "new" || $mode eq "+"
defined $mode not ref $mode $mode eq "new" $mode eq "+"
Truth table60%3/5
A and not(B) and C or D
A= defined $modeB= not ref $modeC= $mode eq "new"D= $mode eq "+"
ABCDresult
0XXX0
10XX0
11000
111X1
11011
996 . "{ '+' => N } or a scalarref of SQL")
997 unless defined $mode && !ref $mode && ($mode eq 'new' || $mode eq '+');
998 $self->Exception("$who: '$mode' for $col needs $col in the row")
999 27 ▶ unless $in{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $in{$col} 5 22 27
1000 22 push @sets, [ $col, $mode ];
1001 }
1002 }
1003 else {
1004 0 $self->Exception("$who: update_cols must be an arrayref or hashref");
1005 }
1006 41 ▶ $self->Exception(
Branch: 1 branch
BranchTrueFalseTotal
unless @sets 1 40 41
1007 "$who: nothing to update on conflict (all row columns are conflict keys)")
1008 unless @sets;
1009 40 $self->_safe_id($_->[0]) for @sets;
1010 39 return \@sets;
1011 34 }
1012  
1013 # Statement-cache key part for update_cols exactly as the caller passed it
1014 # (before normalization). Anything unexpected keys as 'X', which can never
1015 # be cached: _update_spec rejects it on the miss.
1016 52 ▶ sub _raw_spec_key ($u) {
Subroutine _raw_spec_key: called CC=8 SCAR=21.1
1017 52 ▶ return 'U' unless defined $u;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $u 10 42 52
1018 42 ▶ return join ',', 'A', @$u if ref $u eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $u eq "ARRAY" 7 35 42
1019 35 ▶ return 'X' unless ref $u eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $u eq "HASH" 0 35 35
1020 return join ',', 'H', map {
1021 35 my $m = $u->{$_};
1022 45 ▶ "$_=" . (ref $m eq 'SCALAR' ? "\\$$m"
Branch: 3 branches
BranchTrueFalseTotal
ref $m eq 'SCALAR' ? : 5 40 45
ref $m eq 'HASH' ? : 15 25 40
ref $m ? : 0 25 25
Condition50%1/2
$m // ""
l!l
250
MC/DC0%0/1
$m // ""
$m
Truth table50%1/2
A
A= $m
Aresult
11
00
1023 : ref $m eq 'HASH' ? '+' . join(':', %$m)
1024 : ref $m ? 'X'
1025 : $m // '');
1026 } sort keys %$u;
1027 }
1028  
1029 # Statement-cache key part for a normalized update spec.
1030 2 ▶ sub _spec_key ($sets) {
Subroutine _spec_key: called CC=3 SCAR=11.7
1031 return map {
1032 2 my $m = $_->[1];
1033 4 ▶ join '=', $_->[0], ref $m eq 'SCALAR' ? "\\$$m" : ref $m ? "+$m->[1]" : $m;
Branch: 2 branches
BranchTrueFalseTotal
ref $m eq 'SCALAR' ? : 0 4 4
ref $m ? : 0 4 4
1034 } @$sets;
1035 }
1036  
1037 # "INSERT INTO <target>" for an upsert: PostgreSQL gets the alias dbix_t, the
1038 # only unambiguous way to name the stored row in ON CONFLICT DO UPDATE (a
1039 # bare column there is ambiguous between it and EXCLUDED).
1040 39 ▶ method _upsert_target ($qt) {
Subroutine _upsert_target: called CC=2 SCAR=7.0
1041 39 ▶ return $self->dbd eq 'Pg' ? "$qt AS dbix_t" : $qt;
Branch: 1 branch
BranchTrueFalseTotal
$self->dbd eq 'Pg' ? : 0 39 39
1042 34 }
1043  
1044 # Builds the ON CONFLICT / ON DUPLICATE KEY UPDATE clause from a normalized
1045 # spec. The incoming value is VALUES(c) on MariaDB and MySQL < 8.0.19, the
1046 # row alias new.c on MySQL >= 8.0.19 (VALUES() is deprecated there) and
1047 # excluded.c on PostgreSQL/SQLite. MariaDB/MySQL ignore conflict_keys (any
1048 # UNIQUE or PRIMARY KEY triggers the update); they are validated for symmetry.
1049 42 ▶ method _upsert_clause ($conflict_keys, $sets, $qt = undef) {
Subroutine _upsert_clause: called CC=15 SCAR=27.2
1050 42 my $dbh = $self->db->dbh;
1051 42 my $dbd = $self->dbd;
1052  
1053 42 my ($incoming, $prefix);
1054 42 ▶ if ($dbd eq 'mysql' && ($dbh->{mysql_serverversion} // 0) >= 80019) {
Branch: 2 branches
BranchTrueFalseTotal
if ($dbd eq 'mysql' and ($dbh->{'mysql_serverversion'} // 0) >= 80019) { } 1 41 42
elsif ($dbd eq 'mysql' or $dbd eq 'MariaDB') { } 2 39 41
Condition80%4/5
$dbd eq "mysql" and ($dbh->{"mysql_serverversion"} // 0) >= 80019
!ll&&!rl&&r
4011
$dbh->{"mysql_serverversion"} // 0
l!l
20
MC/DC50%1/2
$dbd eq "mysql" and ($dbh->{"mysql_serverversion"} // 0) >= 80019
$dbd eq "mysql" $dbh->{"mysql_serverversion"}
Truth table66%2/3
A and B
A= $dbd eq "mysql"B= $dbh->{"mysql_serverversion"}
ABresult
0X0
100
111
1055 1 ▶ $incoming = sub ($qc) { "new.$qc" };
Subroutine __ANON__: called CC=1 SCAR=0.0
1056 1 $prefix = 'AS new ON DUPLICATE KEY UPDATE ';
1057 }
1058 ▶ elsif ($dbd eq 'mysql' || $dbd eq 'MariaDB') {
Condition100%3/3
$dbd eq "mysql" or $dbd eq "MariaDB"
l!l&&r!l&&!r
1139
MC/DC100%2/2
$dbd eq "mysql" or $dbd eq "MariaDB"
$dbd eq "mysql" $dbd eq "MariaDB"
Truth table100%3/3
A or B
A= $dbd eq "mysql"B= $dbd eq "MariaDB"
ABresult
1X1
011
000
1059 2 ▶ $incoming = sub ($qc) { "VALUES($qc)" };
Subroutine __ANON__: called CC=1 SCAR=0.0
1060 2 $prefix = 'ON DUPLICATE KEY UPDATE ';
1061 }
1062 else {
1063 39 my $qck = join(', ', map { $dbh->quote_identifier($_) } @$conflict_keys);
1064 39 ▶ $incoming = sub ($qc) { "excluded.$qc" };
Subroutine __ANON__: called CC=1 SCAR=0.0
1065 39 $prefix = "ON CONFLICT ($qck) DO UPDATE SET ";
1066 }
1067  
1068 # Naming the STORED row: PostgreSQL via the dbix_t alias (_upsert_target);
1069 # MySQL's row-alias form via the table name (a bare column is ambiguous
1070 # with new.col there); MariaDB/SQLite accept the bare column.
1071 0 ▶ my $stored = $dbd eq 'Pg' ? sub ($qc) { "dbix_t.$qc" }
Subroutine __ANON__: not called CC=1 SCAR=6.9
1072 0 ▶ : $dbd eq 'mysql' && $prefix =~ /^AS new/ && $qt ? sub ($qc) { "$qt.$qc" }
Subroutine __ANON__: not called CC=1 SCAR=6.9
1073 42 ▶ : sub ($qc) { $qc };
Subroutine __ANON__: called CC=1 SCAR=0.2
Branch: 2 branches
BranchTrueFalseTotal
$dbd eq 'Pg' ? : 0 42 42
$dbd eq 'mysql' && $prefix =~ /^AS new/u && $qt ? : 0 42 42
Condition83%5/6
$dbd eq "mysql" and $prefix =~ /^AS new/u and $qt
!ll&&!rl&&r
4110
$dbd eq "mysql" and $prefix =~ /^AS new/u
!ll&&!rl&&r
4011
MC/DC0%0/3
$dbd eq "mysql" and $prefix =~ /^AS new/u and $qt
$dbd eq "mysql" $prefix =~ /^AS new/u $qt
Truth table75%3/4
A and B and C
A= $dbd eq "mysql"B= $prefix =~ /^AS new/uC= $qt
ABCresult
0XX0
10X0
1100
1111
1074  
1075 my @sql = map {
1076 # A bare column name (the pre-0.20 [cols] form) means 'new'.
1077 42 ▶ my ($col, $mode) = ref $_ ? @$_ : ($_, 'new');
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 68 4 72
1078 72 my $qc = $dbh->quote_identifier($col);
1079 72 ▶ ref $mode eq 'SCALAR' ? "$qc = $$mode"
Branch: 3 branches
BranchTrueFalseTotal
ref $mode eq 'SCALAR' ? : 5 67 72
ref $mode ? : 5 62 67
$mode eq '+' ? : 15 47 62
1080 : ref $mode ? "$qc = " . $stored->($qc) . " + $mode->[1]"
1081 : $mode eq '+' ? "$qc = " . $stored->($qc) . ' + ' . $incoming->($qc)
1082 : "$qc = " . $incoming->($qc);
1083 } @$sets;
1084 42 return $prefix . join(', ', @sql);
1085 34 }
1086  
1087 # INSERT that silently skips a row violating a UNIQUE/PRIMARY KEY:
1088 # INSERT IGNORE (MariaDB/MySQL), INSERT OR IGNORE (SQLite), ON CONFLICT DO
1089 # NOTHING (PostgreSQL). Returns 1 when the row was inserted, 0 when it
1090 # already existed. Note: MariaDB/MySQL's IGNORE also downgrades other errors
1091 # (bad values, NOT NULL) to warnings.
1092 31 ▶ method insert_ignore ($table_name, $row) {
Subroutine insert_ignore: called CC=10 SCAR=23.7
Pod documented
1093 31 my $table = $self->TableName($table_name);
1094 31 ▶ $row = $self->_json_encode_row($table, $row) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 0 31 31
1095 31 $self->_safe_data($row);
1096 31 ▶ $self->Exception("insert_ignore: row hashref required") unless %$row;
Branch: 1 branch
BranchTrueFalseTotal
unless %$row 0 31 31
1097 31 ▶ $row = $self->_stamp($table, $row, 'insert') if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 2 29 31
1098  
1099 31 my ($stmt, @bind) = $self->Q->insert($table, $row);
1100 31 my $dbd = $self->dbd;
1101 31 ▶ if ($dbd eq 'MariaDB' || $dbd eq 'mysql') { $stmt =~ s/^INSERT INTO/INSERT IGNORE INTO/ }
Branch: 2 branches
BranchTrueFalseTotal
if ($dbd eq 'MariaDB' or $dbd eq 'mysql') { } 0 31 31
elsif ($dbd eq 'SQLite') { } 31 0 31
Condition33%1/3
$dbd eq "MariaDB" or $dbd eq "mysql"
l!l&&r!l&&!r
0031
MC/DC0%0/2
$dbd eq "MariaDB" or $dbd eq "mysql"
$dbd eq "MariaDB" $dbd eq "mysql"
Truth table33%1/3
A or B
A= $dbd eq "MariaDB"B= $dbd eq "mysql"
ABresult
1X1
011
000
1102 31 elsif ($dbd eq 'SQLite') { $stmt =~ s/^INSERT INTO/INSERT OR IGNORE INTO/ }
1103 0 else { $stmt .= ' ON CONFLICT DO NOTHING' }
1104  
1105 31 $sql = $stmt;
1106 31 $self->execute_prepare(@bind);
1107 31 ▶ my $inserted = $_affected_rows ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$_affected_rows ? : 13 18 31
1108 31 ▶ $self->_update_last_id($table) if $inserted;
Branch: 1 branch
BranchTrueFalseTotal
if $inserted 13 18 31
1109 31 ▶ $self->_cache_invalidate_table($table) if $inserted;
Branch: 1 branch
BranchTrueFalseTotal
if $inserted 13 18 31
1110 31 return $inserted;
1111 34 }
1112  
1113 # The row matching $key (a { column => value } hashref covered by a UNIQUE
1114 # index), inserting { %$defaults, %$key } first when there is none. Safe
1115 # against concurrent callers: the insert is insert_ignore, so a racing
1116 # duplicate is skipped and the existing row is read back. In list context
1117 # also returns whether this call created it.
1118 21 ▶ method find_or_create ($table_name, $key, $defaults = {}) {
Subroutine find_or_create: called CC=8 SCAR=21.9
Pod documented
1119 21 ▶ $self->Exception("find_or_create: key hashref required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $key eq "HASH" and %$key 0 21 21
Condition33%1/3
ref $key eq "HASH" and %$key
!ll&&!rl&&r
0021
MC/DC0%0/2
ref $key eq "HASH" and %$key
ref $key eq "HASH" %$key
Truth table33%1/3
A and B
A= ref $key eq "HASH"B= %$key
ABresult
0X0
100
111
1120 unless ref $key eq 'HASH' && %$key;
1121 21 ▶ $self->Exception("find_or_create: defaults must be a hashref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $defaults eq "HASH" 0 21 21
1122 unless ref $defaults eq 'HASH';
1123 $self->Exception("find_or_create: key values must be defined plain values")
1124 21 ▶ if grep { !defined || ref } values %$key;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not defined $_ or ref $_;} values %$key 0 21 21
Condition33%1/3
!defined($_) || ref $_
l!l&&r!l&&!r
0021
MC/DC0%0/2
!defined($_) || ref $_
!defined($_) ref $_
Truth table33%1/3
not(A) || B
A= !defined($_)B= ref $_
ABresult
1X1
011
000
1125  
1126 21 my $created = $self->insert_ignore($table_name, { %$defaults, %$key });
1127  
1128 21 my $table = $self->TableName($table_name);
1129 21 my ($parts, $params) = $self->_where_parts($key);
1130 21 my $row = $self->hash('SELECT * FROM ' . $self->_quote_ident_path($table)
1131 . ' WHERE ' . join(' AND ', @$parts), @$params);
1132 21 ▶ return wantarray ? ($row, $created) : $row;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 14 7 21
1133 34 }
1134  
1135 0 ▶ method extra_args ($skeel, %args) {
Subroutine extra_args: not called CC=2 SCAR=17.9
Pod undocumented
1136 0 ▶ if ($args{time}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"time"}) 0 0 0
1137 0 $self->_safe_id($args{time});
1138 0 $skeel->{ $args{time} } = $self->now();
1139 }
1140 0 return $skeel;
1141 34 }
1142  
1143 # :name -> ? rewrite, memoized per SQL text: the rewritten statement and
1144 # the placeholder order depend only on the text, so repeated execute()
1145 # calls skip the regex pass and just slice the bind values.
1146 34 field %_named_sql;
1147  
1148 5 ▶ method make_sen ($skeel) {
Subroutine make_sen: called CC=5 SCAR=16.3
Pod documented
1149 5 ▶ my $stmt = $sql // '';
Condition50%1/2
$sql // ""
l!l
50
MC/DC0%0/1
$sql // ""
$sql
Truth table50%1/2
A
A= $sql
Aresult
11
00
1150 5 ▶ my $parsed = $_named_sql{$stmt} //= do {
Condition33%1/3
$_named_sql{$stmt} //= do { %_named_sql = () if keys %_named_sql >= 1000; my @names; (my $out = $stmt) =~ s/ ( '[^']*' | "[^"]*" ) # $1: quoted literal -> leave as-is | (?<![:\w]) : ([A-Za-z_]\w*) # $2: named placeholder -> bind /defined $1 ? $1 : do { push @names, $2; "?" };/egux; [$out, \@names] }
l!l&&r!l&&!r
050
MC/DC0%0/2
$_named_sql{$stmt} //= do { %_named_sql = () if keys %_named_sql >= 1000; my @names; (my $out = $stmt) =~ s/ ( '[^']*' | "[^"]*" ) # $1: quoted literal -> leave as-is | (?<![:\w]) : ([A-Za-z_]\w*) # $2: named placeholder -> bind /defined $1 ? $1 : do { push @names, $2; "?" };/egux; [$out, \@names] }
$_named_sql{$stmt} do { %_named_sql = () if keys %_named_sql >= 1000; my @names; (my $out = $stmt) =~ s/ ( '[^']*' | "[^"]*" ) # $1: quoted literal -> leave as-is | (?<![:\w]) : ([A-Za-z_]\w*) # $2: named placeholder -> bind /defined $1 ? $1 : do { push @names, $2; "?" };/egux; [$out, \@names] }
Truth table33%1/3
A //= B
A= $_named_sql{$stmt}B= do { %_named_sql = () if keys %_named_sql >= 1000; my @names; (my $out = $stmt) =~ s/ ( '[^']*' | "[^"]*" ) # $1: quoted literal -> leave as-is | (?<![:\w]) : ([A-Za-z_]\w*) # $2: named placeholder -> bind /defined $1 ? $1 : do { push @names, $2; "?" };/egux; [$out, \@names] }
ABresult
1X1
011
000
1151 5 ▶ %_named_sql = () if keys %_named_sql >= 1_000;
Branch: 1 branch
BranchTrueFalseTotal
if keys %_named_sql >= 1000 0 5 5
1152 5 my @names;
1153 # Single left-to-right pass: a quoted string literal is matched as a
1154 # unit and left untouched, so ':' inside it is never substituted. The
1155 # (?<![:\w]) lookbehind keeps the second colon of a Postgres '::cast'
1156 # (and back-to-back names) from matching.
1157 5 (my $out = $stmt) =~ s{
1158 ( '[^']*' | "[^"]*" ) # $1: quoted literal -> leave as-is
1159 |
1160 (?<![:\w]) : ([A-Za-z_]\w*) # $2: named placeholder -> bind
1161 }{
1162 9 ▶ defined $1 ? $1 : do { push @names, $2; '?' }
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 1 8 9
1163 }gex;
1164 5 [ $out, \@names ];
1165 };
1166  
1167 5 $sql = $parsed->[0];
1168 # A hash slice yields undef for a missing name without autovivifying.
1169 5 $p = [ @{$skeel}{ @{ $parsed->[1] } } ];
1170 34 }
1171  
1172 179 ▶ method execute_prepare (@params) {
Subroutine execute_prepare: called CC=7 SCAR=21.6
Pod documented
1173 179 ▶ my $stmt = $sql // '';
Condition50%1/2
$sql // ""
l!l
1790
MC/DC0%0/1
$sql // ""
$sql
Truth table50%1/2
A
A= $sql
Aresult
11
00
1174  
1175 179 ▶ $self->Exception("execute_prepare(): SQL not set")
Branch: 1 branch
BranchTrueFalseTotal
unless length $stmt 0 179 179
1176 unless length $stmt;
1177  
1178 179 ▶ my $dbh = $self->db && $self->db->dbh
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = $self->db && $self->db->dbh or $self->Exception("execute_prepare(): No DB handle") 179 0 179
Condition33%1/3
$self->db && $self->db->dbh
!ll&&!rl&&r
00179
MC/DC0%0/2
$self->db && $self->db->dbh
$self->db $self->db->dbh
Truth table33%1/3
A && B
A= $self->dbB= $self->db->dbh
ABresult
0X0
100
111
1179 or $self->Exception("execute_prepare(): No DB handle");
1180  
1181 # Binds first: if prepare fails, HandleError's error entry must carry this
1182 # statement's binds, not the previous query's.
1183 179 $p = \@params;
1184 179 $_affected_rows = undef;
1185  
1186 # 3-arg form: if an identical cached handle is still active, get a fresh one
1187 # instead of emitting a "still Active" warning (execute_prepare returns an
1188 # unfinished handle to the caller).
1189 179 ▶ my $sth = $self->_prepare($dbh, $stmt)
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->_prepare($dbh, $stmt) or $self->_db_fail('prepare() failed: ' . ($dbh->errstr // "unknown"), $dbh) 179 0 179
Condition0%0/2
$dbh->errstr // "unknown"
l!l
00
MC/DC0%0/1
$dbh->errstr // "unknown"
$dbh->errstr
Truth table0%0/2
A
A= $dbh->errstr
Aresult
11
00
1190 or $self->_db_fail(
1191 "prepare() failed: " . ($dbh->errstr // 'unknown'), $dbh);
1192  
1193 179 my $rv;
1194 179 ▶ $self->_track(sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
1195 179 ▶ $rv = $sth->execute(@params)
Branch: 1 branch
BranchTrueFalseTotal
$rv = $sth->execute(@params) or $self->_db_fail('execute() failed: ' . ($sth->errstr // "unknown"), $sth) 179 0 179
Condition0%0/2
$sth->errstr // "unknown"
l!l
00
MC/DC0%0/1
$sth->errstr // "unknown"
$sth->errstr
Truth table0%0/2
A
A= $sth->errstr
Aresult
11
00
1196 or $self->_db_fail(
1197 "execute() failed: " . ($sth->errstr // 'unknown'), $sth);
1198 179 1;
1199 179 });
1200  
1201 179 $last_sql = $stmt;
1202 179 $_affected_rows = _affected($sth, $rv);
1203  
1204 179 return $sth;
1205 34 }
1206  
1207 }
1208  
1209 34 1;
1210  
1211 __END__
« Fast/Profile/MariaDB.pm ↑ Summary Fast.pm »