Fast/SQL.pm

filter: Statementstmt 93.6% 1499 / 1601 Branchbran 74.3% 513 / 690 Conditioncond 60.6% 288 / 475 MC/DCmcdc 37.0% 103 / 278 Subroutinesub 94.7% 125 / 132 Podpod 97.8% 46 / 47 totaltotal 79.8% 2574 / 3223 CC 558 SCAR 28.3
CC
558
Cov
83%
stream
156.0
_slow_plan
90.0
__ANON__
42.0
CRAP 16.9
« Fast.pm ↑ Summary Fast/Transaction.pm »
1 package DBIx::Fast::SQL;
2  
3 38 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 38 ▶use Object::Pad 0.807;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 38 our $VERSION = '0.22';
7 38 ▶use DBI ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 38 ▶use DBIx::Fast::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 38 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 38 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # Histogram buckets (seconds) of the query-duration metric.
13 38 our @BUCKETS = (0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5);
14  
15 # Bounded memo tables (statement caches, identifier memos) shed a quarter of
16 # their entries when full - an arbitrary quarter, Perl's hash order - instead
17 # of emptying at once: no burst of misses right after the limit.
18 2910 ▶sub _trim_cache ($h, $max) {
Subroutine _trim_cache: called CC=2 SCAR=6.9
19 2910 ▶ return if keys %$h < $max;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$h < $max 2906 4 2910
20 4 my @k = keys %$h;
21 4 delete @{$h}{ @k[0 .. int($#k / 4)] };
22 }
23  
24 # Query and CRUD layer of DBIx::Fast, composed into the main class as a role.
25 # Object::Pad classes cannot span files, so the role owns the statement state
26 # ($sql/$p/$results/$last_id/$last_sql) and reaches the rest of the object
27 # (db/Q/dbd/schema/Exception/set_error/...) through the composed interface.
28  
29 role DBIx::Fast::SQL {
30  
31 # Statement state. Same attributes these fields had on the class, so the
32 # public API (sql/p accessors, read-only results/last_id/last_sql) and the
33 # encapsulation guarantees are unchanged.
34 field $sql :accessor = undef;
35 114 ▶ field $last_sql :reader = undef;
Subroutine sql: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ and $sql = shift() 6 108 114
36 11 ▶ field $p :accessor = undef;
Subroutine last_sql: called CC=1 SCAR=0.0
Pod documented
37 100 ▶ field $results :reader = undef;
Subroutine p: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ and $p = shift() 1 99 100
38 10 ▶ field $last_id :reader = undef;
Subroutine results: called CC=1 SCAR=0.0
Pod documented
39 7 ▶ field $_affected_rows :reader(rows) = undef; # rows affected by the last write
Subroutine last_id: called CC=1 SCAR=0.0
Pod documented
40  
41 # json_columns (see DBIx::Fast POD): table => { col => 1 } ('*' = any table)
42 # for writes, and the union of the names for reads. undef when not
43 # configured, so the hot paths pay nothing.
44 8 ▶ field $_json_write;
Subroutine rows: called CC=1 SCAR=0.0
Pod documented
45 38 field $_json_read;
46 38 field $_json_codec;
47 38 field %_json_tcols; # table => [ json columns for writes ], memoized
48 # True when the timestamps option is set (see DBIx::Fast::_timestamps_for);
49 # lets every writer skip the stamping code with a field test.
50 38 field $_ts_on;
51 3 ▶ method _timestamps_on () { $_ts_on = 1 }
Subroutine _timestamps_on: called CC=1 SCAR=0.0
52  
53 # The profiler once DBIx::Fast::tracker() created it (undef until then), so
54 # the hot paths test a field instead of calling _active_tracker.
55 38 field $_tracker;
56 7 ▶ method _tracker_created ($t) { $_tracker = $t; $self->_fast_flags }
Subroutine _tracker_created: called CC=1 SCAR=0.0
57  
58 # Fast path of val/hash/all allowed (nothing has to happen around the
59 # query: no profiler, metrics or on_slow_query; for row shapes also no
60 # json_columns decoding). Recomputed by _fast_flags whenever one of those
61 # is configured, so the reads test one field.
62 field $_fast = 1;
63 38 field $_fast_rows = 1;
64  
65 # dbd() memo for _update_last_id (reset by DBIx::Fast::_set_dbd).
66 38 field $_dbd_c;
67 0 ▶ method _dbd_reset () { undef $_dbd_c }
Subroutine _dbd_reset: not called CC=1 SCAR=4.1
68  
69 # Pg: the single-column primary key of a table (or ''), looked up once, so
70 # insert/insert_ignore can get the new id with RETURNING in the same round
71 # trip - DBD::Pg's last_insert_id costs another one. Emptied on reconnect.
72 38 field %_pg_pk;
73  
74 # True when the cache option is set (DBIx::Fast ADJUST): writers skip the
75 # table invalidation call otherwise.
76 38 field $_cache_on;
77 10 ▶ method _cache_configured () { $_cache_on = 1 }
Subroutine _cache_configured: called CC=1 SCAR=0.0
78  
79 # The handle execute_prepare ran on (weak), so _update_last_id does not go
80 # through db->dbh (and its ping/fork checks) a second time.
81 38 field $_write_dbh;
82  
83 # after_write hook (see DBIx::Fast POD); undef when not configured.
84 38 field $_after_write;
85 2 ▶ method _set_after_write ($cb) {
Subroutine _set_after_write: called CC=2 SCAR=7.0
86 2 ▶ $self->Exception("after_write must be a coderef") unless ref $cb eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 2 2
87 2 $_after_write = $cb;
88 38 }
89  
90 # Call the after_write hook for a completed CRUD write. The write is done:
91 # a hook that dies is reported with warn, never propagated.
92 7 ▶ method _fire_after_write (%w) {
Subroutine _fire_after_write: called CC=5 SCAR=17.6
93 7 ▶ $w{rows} //= $_affected_rows;
Condition33%1/3
$w{"rows"} //= $_affected_rows
l!l&&r!l&&!r
070
MC/DC0%0/2
$w{"rows"} //= $_affected_rows
$w{"rows"} $_affected_rows
Truth table33%1/3
A //= B
A= $w{"rows"}B= $_affected_rows
ABresult
1X1
011
000
94 7 ▶ $w{last_id} //= $last_id if $w{op} =~ /^insert/;
Branch: 1 branch
BranchTrueFalseTotal
if $w{"op"} =~ /^insert/u 7 0 7
Condition33%1/3
$w{"last_id"} //= $last_id
l!l&&r!l&&!r
070
MC/DC0%0/2
$w{"last_id"} //= $last_id
$w{"last_id"} $last_id
Truth table33%1/3
A //= B
A= $w{"last_id"}B= $last_id
ABresult
1X1
011
000
95 7 ▶ eval { $_after_write->(\%w); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$_after_write(\%w); 1 } } or warn "DBIx::Fast after_write hook died: $@" 7 0 7
96 or warn "DBIx::Fast after_write hook died: $@";
97 38 }
98  
99 # Query observation: on_slow_query and metrics (see DBIx::Fast POD). $_observe
100 # stays undef unless one is configured, so the hot paths pay a field test.
101 38 field $_observe;
102 38 field $_slow_s; # on_slow_query threshold, seconds
103 38 field $_slow_cb;
104 38 field $_slow_redact; # 1 = no bind values in the report; coderef = masker
105 38 field $_slow_explain; # attach the EXPLAIN plan of slow SELECTs
106 38 field $_metrics; # counters, see _observed / metrics
107 38 field $_by_sql; # sql_stats or a scope is on: _count_sql per statement
108 38 field $_stats; # sql_stats: { key => [count, seconds, max] }
109 38 field $_stats_max; # distinct statements kept; the rest go to (other)
110 38 field $_scope; # scope_start .. scope_end: { queries, seconds, by, fired }
111 38 field $_repeat_n; # on_repeated_query threshold
112 38 field $_repeat_cb;
113 38 field %_sql_key; # statement -> stats key (memo of _sql_key)
114  
115 1 ▶ method _set_slow_query ($ms, $cb, $redact, $explain = 0) {
Subroutine _set_slow_query: called CC=2 SCAR=6.9
116 1 ($_slow_s, $_slow_cb, $_slow_redact, $_slow_explain) =
117 ($ms / 1000, $cb, $redact, $explain);
118 1 $self->_fast_flags;
119 38 }
120  
121 37 ▶ method _fast_flags () {
Subroutine _fast_flags: called CC=8 SCAR=20.8
122 37 ▶ $_by_sql = $_stats || $_scope ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$_stats || $_scope ? : 12 25 37
Condition100%3/3
$_stats or $_scope
l!l&&r!l&&!r
4825
MC/DC100%2/2
$_stats or $_scope
$_stats $_scope
Truth table100%3/3
A or B
A= $_statsB= $_scope
ABresult
1X1
011
000
123 37 ▶ $_observe = $_slow_cb || $_metrics || $_by_sql ? 1 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_slow_cb || $_metrics || $_by_sql ? : 18 19 37
Condition100%6/6
$_slow_cb or $_metrics or $_by_sql
l!l&&r!l&&!r
81019
$_slow_cb or $_metrics
l!l&&r!l&&!r
4429
MC/DC100%3/3
$_slow_cb or $_metrics or $_by_sql
$_slow_cb $_metrics $_by_sql
Truth table100%4/4
A or B or C
A= $_slow_cbB= $_metricsC= $_by_sql
ABCresult
1XX1
01X1
0011
0000
124 37 ▶ $_fast = !$_observe && !$_tracker;
Condition100%3/3
$_observe || $_tracker
l!l&&r!l&&!r
18712
MC/DC100%2/2
$_observe || $_tracker
$_observe $_tracker
Truth table100%3/3
A || B
A= $_observeB= $_tracker
ABresult
1X1
011
000
125 37 ▶ $_fast_rows = $_fast && !$_json_read;
Condition100%3/3
$_fast && !$_json_read
!ll&&!rl&&r
2557
MC/DC100%2/2
$_fast && !$_json_read
$_fast !$_json_read
Truth table100%3/3
A && not(B)
A= $_fastB= !$_json_read
ABresult
0X0
100
111
126 38 }
127  
128 6 ▶ method _enable_metrics () {
Subroutine _enable_metrics: called CC=1 SCAR=0.0
129 # buckets: per-bucket counts (index past the last = over 5 s); made
130 # cumulative only when read (metrics), so a query bumps one slot.
131 6 $_metrics = { queries => 0, seconds => 0, slow => 0, errors => {},
132 buckets => [ (0) x (@DBIx::Fast::SQL::BUCKETS + 1) ] };
133 6 $self->_fast_flags;
134 38 }
135  
136 3 ▶ method _enable_sql_stats ($max) {
Subroutine _enable_sql_stats: called CC=1 SCAR=0.0
137 3 ($_stats, $_stats_max) = ({}, $max);
138 3 $self->_fast_flags;
139 38 }
140  
141 2 ▶ method _set_repeated_query ($n, $cb) {
Subroutine _set_repeated_query: called CC=1 SCAR=0.0
142 2 ($_repeat_n, $_repeat_cb) = ($n, $cb);
143 38 }
144  
145 # One timed statement ($sql/$p are still the statement's).
146 95 ▶ method _observed ($dt) {
Subroutine _observed: called CC=8 SCAR=20.9
147 95 ▶ if ($_metrics) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_metrics) 45 50 95
148 45 $_metrics->{queries}++;
149 45 $_metrics->{seconds} += $dt;
150 45 my $i = 0;
151 45 ▶ $i++ while $i < @DBIx::Fast::SQL::BUCKETS && $dt > $DBIx::Fast::SQL::BUCKETS[$i];
Branch: 1 branch
BranchTrueFalseTotal
$i < @DBIx::Fast::SQL::BUCKETS and $dt > $DBIx::Fast::SQL::BUCKETS[$i] and do { ++$i } 66 45 111
Condition66%2/3
$i < @DBIx::Fast::SQL::BUCKETS and $dt > $DBIx::Fast::SQL::BUCKETS[$i]
!ll&&!rl&&r
04566
MC/DC50%1/2
$i < @DBIx::Fast::SQL::BUCKETS and $dt > $DBIx::Fast::SQL::BUCKETS[$i]
$i < @DBIx::Fast::SQL::BUCKETS $dt > $DBIx::Fast::SQL::BUCKETS[$i]
Truth table66%2/3
A and B
A= $i < @DBIx::Fast::SQL::BUCKETSB= $dt > $DBIx::Fast::SQL::BUCKETS[$i]
ABresult
0X0
100
111
152 45 $_metrics->{buckets}[$i]++;
153 }
154 95 ▶ $self->_count_sql($dt) if $_by_sql;
Branch: 1 branch
BranchTrueFalseTotal
if $_by_sql 55 40 95
155 95 ▶ return unless $_slow_cb && $dt >= $_slow_s;
Branch: 1 branch
BranchTrueFalseTotal
unless $_slow_cb and $dt >= $_slow_s 90 5 95
Condition66%2/3
$_slow_cb and $dt >= $_slow_s
!ll&&!rl&&r
9005
MC/DC50%1/2
$_slow_cb and $dt >= $_slow_s
$_slow_cb $dt >= $_slow_s
Truth table66%2/3
A and B
A= $_slow_cbB= $dt >= $_slow_s
ABresult
0X0
100
111
156 5 ▶ $_metrics->{slow}++ if $_metrics;
Branch: 1 branch
BranchTrueFalseTotal
if $_metrics 5 0 5
157 5 $self->_report_slow($dt);
158 38 }
159  
160 # Only for a slow statement, in its own method: _observed runs for every
161 # statement and Object::Pad binds every field a method mentions.
162 5 ▶ method _report_slow ($dt) {
Subroutine _report_slow: called CC=7 SCAR=23.2
163 5 ▶ my @binds = @{ $p // [] };
Condition50%1/2
$p // []
l!l
50
MC/DC0%0/1
$p // []
$p
Truth table50%1/2
A
A= $p
Aresult
11
00
164 5 my $q = { sql => $sql, ms => 0 + sprintf('%.3f', $dt * 1000), caller => _app_caller() };
165 5 ▶ $q->{explain} = $self->_slow_plan($sql, \@binds) if $_slow_explain;
Branch: 1 branch
BranchTrueFalseTotal
if $_slow_explain 0 5 5
166 5 ▶ if (ref $_slow_redact eq 'CODE') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $_slow_redact eq 'CODE') { } 0 5 5
elsif ($_slow_redact) { } 0 5 5
167 0 @binds = eval { $_slow_redact->($sql, @binds) };
168 0 ▶ @binds = ('<redacted>') if $@; # a broken masker never leaks the values
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
169 }
170 0 elsif ($_slow_redact) { @binds = map { '<redacted>' } @binds }
171 5 $q->{binds} = \@binds;
172 5 ▶ eval { $_slow_cb->($q); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$_slow_cb($q); 1 } } or warn "DBIx::Fast on_slow_query hook died: $@" 5 0 5
173 or warn "DBIx::Fast on_slow_query hook died: $@";
174 38 }
175  
176 # Stats key of a statement: the SQL with every all-placeholder list
177 # collapsed, so IN (?) expansions and multi-row VALUES of any length are
178 # one statement: "IN (?)" and "IN (?, ?, ?)" -> "IN (?, ...)",
179 # "VALUES (?, ?)" and "VALUES (?, ?), (?, ?)" -> "VALUES (?, ...), ...".
180 32 ▶ sub _sql_key ($s) {
Subroutine _sql_key: called CC=1 SCAR=0.0
181 32 $s =~ s/\(\s*\?(?:\s*,\s*\?)+\s*\)/(?, ...)/g;
182 32 $s =~ s/\bIN\s*\(\s*\?\s*\)/IN (?, ...)/gi; # a one-value list too
183 32 $s =~ s/\bVALUES\s*(\((?:\?|\?, \.\.\.)\))(?:\s*,\s*\1)*/VALUES $1, .../gi;
184 32 return $s;
185 }
186  
187 # Per-statement counters of sql_stats and of the open scope.
188 55 ▶ method _count_sql ($dt) {
Subroutine _count_sql: called CC=13 SCAR=25.7
189 55 my $key = $_sql_key{$sql};
190 55 ▶ unless (defined $key) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $key) 32 23 55
191 32 _trim_cache(\%_sql_key, 1_000);
192 32 ▶ $key = $_sql_key{$sql} = _sql_key($sql // '');
Condition50%1/2
$sql // ""
l!l
320
MC/DC0%0/1
$sql // ""
$sql
Truth table50%1/2
A
A= $sql
Aresult
11
00
193 }
194 55 ▶ if ($_stats) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_stats) 31 24 55
195 31 my $e = $_stats->{$key};
196 31 ▶ unless ($e) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($e) 22 9 31
197 22 ▶ $key = '(other)' if keys %$_stats >= $_stats_max; # bounded memory
Branch: 1 branch
BranchTrueFalseTotal
if keys %$_stats >= $_stats_max 7 15 22
198 22 ▶ $e = $_stats->{$key} //= [ 0, 0, 0 ];
Condition100%2/2
$_stats->{$key} //= [0, 0, 0]
l!l
616
MC/DC100%1/1
$_stats->{$key} //= [0, 0, 0]
$_stats->{$key}
Truth table100%2/2
A
A= $_stats->{$key}
Aresult
11
00
199 }
200 31 $e->[0]++;
201 31 $e->[1] += $dt;
202 31 ▶ $e->[2] = $dt if $dt > $e->[2];
Branch: 1 branch
BranchTrueFalseTotal
if $dt > $e->[2] 19 12 31
203 }
204 55 ▶ if (my $sc = $_scope) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sc = $_scope) 24 31 55
205 24 $sc->{queries}++;
206 24 $sc->{seconds} += $dt;
207 24 ▶ my $e = $sc->{by}{$key} //= [ 0, 0 ];
Condition100%2/2
$sc->{"by"}{$key} //= [0, 0]
l!l
168
MC/DC100%1/1
$sc->{"by"}{$key} //= [0, 0]
$sc->{"by"}{$key}
Truth table100%2/2
A
A= $sc->{"by"}{$key}
Aresult
11
00
208 24 $e->[0]++;
209 24 $e->[1] += $dt;
210 24 ▶ if ($_repeat_cb && $e->[0] == $_repeat_n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_repeat_cb and $e->[0] == $_repeat_n) 3 21 24
Condition100%3/3
$_repeat_cb and $e->[0] == $_repeat_n
!ll&&!rl&&r
7143
MC/DC100%2/2
$_repeat_cb and $e->[0] == $_repeat_n
$_repeat_cb $e->[0] == $_repeat_n
Truth table100%3/3
A and B
A= $_repeat_cbB= $e->[0] == $_repeat_n
ABresult
0X0
100
111
211 3 my $r = { sql => $key, count => $e->[0], seconds => 0 + sprintf('%.6f', $e->[1]),
212 caller => _app_caller() };
213 3 ▶ eval { $_repeat_cb->($r); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$_repeat_cb($r); 1 } } or warn "DBIx::Fast on_repeated_query hook died: $@" 2 1 3
214 or warn "DBIx::Fast on_repeated_query hook died: $@";
215 }
216 }
217 38 }
218  
219 # sql_stats: [ { sql, count, seconds, max } ] sorted by order (seconds,
220 # count or max; descending), at most top entries.
221 8 ▶ method sql_stats (%o) {
Subroutine sql_stats: called CC=8 SCAR=20.8
Pod documented
222 8 ▶ return undef unless $_stats;
Branch: 1 branch
BranchTrueFalseTotal
unless $_stats 1 7 8
223 7 ▶ my $order = $o{order} // 'seconds';
Condition100%2/2
$o{"order"} // "seconds"
l!l
25
MC/DC100%1/1
$o{"order"} // "seconds"
$o{"order"}
Truth table100%2/2
A
A= $o{"order"}
Aresult
11
00
224 7 my %col = (count => 0, seconds => 1, max => 2);
225 $self->Exception("sql_stats: order must be seconds, count or max")
226 7 ▶ unless exists $col{$order};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $col{$order} 1 6 7
227 6 my $c = $col{$order};
228 6 ▶ my @keys = sort { $_stats->{$b}[$c] <=> $_stats->{$a}[$c] || $a cmp $b } keys %$_stats;
Condition66%2/3
$_stats->{$b}[$c] <=> $_stats->{$a}[$c] || $a cmp $b
l!l&&r!l&&!r
2710
MC/DC0%0/2
$_stats->{$b}[$c] <=> $_stats->{$a}[$c] || $a cmp $b
$_stats->{$b}[$c] <=> $_stats->{$a}[$c] $a cmp $b
Truth table66%2/3
A || B
A= $_stats->{$b}[$c] <=> $_stats->{$a}[$c]B= $a cmp $b
ABresult
1X1
011
000
229 6 ▶ splice @keys, $o{top} if defined $o{top} && $o{top} =~ /\A\d+\z/ && $o{top} < @keys;
Branch: 1 branch
BranchTrueFalseTotal
if defined $o{"top"} and $o{"top"} =~ /\A\d+\z/u and $o{"top"} < @keys 1 5 6
Condition83%5/6
defined $o{"top"} and $o{"top"} =~ /\A\d+\z/u and $o{"top"} < @keys
!ll&&!rl&&r
411
defined $o{"top"} and $o{"top"} =~ /\A\d+\z/u
!ll&&!rl&&r
402
MC/DC66%2/3
defined $o{"top"} and $o{"top"} =~ /\A\d+\z/u and $o{"top"} < @keys
defined $o{"top"} $o{"top"} =~ /\A\d+\z/u $o{"top"} < @keys
Truth table75%3/4
A and B and C
A= defined $o{"top"}B= $o{"top"} =~ /\A\d+\z/uC= $o{"top"} < @keys
ABCresult
0XX0
10X0
1100
1111
230 6 return [ map { my $e = $_stats->{$_};
231 16 { sql => $_, count => $e->[0], seconds => 0 + sprintf('%.6f', $e->[1]),
232 max => 0 + sprintf('%.6f', $e->[2]) } } @keys ];
233 38 }
234  
235 4 ▶ method reset_sql_stats () { %$_stats = () if $_stats; return }
Subroutine reset_sql_stats: called CC=2 SCAR=7.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
if $_stats 4 0 4
236  
237 # A unit of work (a web request, a job): per-statement counts from here to
238 # scope_end, and on_repeated_query fires inside it. A new scope_start
239 # discards an open one.
240 8 ▶ method scope_start () {
Subroutine scope_start: called CC=1 SCAR=0.0
Pod documented
241 8 $_scope = { queries => 0, seconds => 0, by => {} };
242 8 $self->_fast_flags;
243 8 return;
244 38 }
245  
246 9 ▶ method scope_end () {
Subroutine scope_end: called CC=3 SCAR=11.0
Pod documented
247 9 ▶ my $sc = $_scope or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sc = $_scope or return undef 7 2 9
248 7 undef $_scope;
249 7 $self->_fast_flags;
250 7 my $by = $sc->{by};
251 1 ▶ my @rep = sort { $by->{$b}[0] <=> $by->{$a}[0] || $a cmp $b }
Condition33%1/3
$by->{$b}[0] <=> $by->{$a}[0] || $a cmp $b
l!l&&r!l&&!r
100
MC/DC0%0/2
$by->{$b}[0] <=> $by->{$a}[0] || $a cmp $b
$by->{$b}[0] <=> $by->{$a}[0] $a cmp $b
Truth table33%1/3
A || B
A= $by->{$b}[0] <=> $by->{$a}[0]B= $a cmp $b
ABresult
1X1
011
000
252 7 grep { $by->{$_}[0] > 1 } keys %$by;
253 return {
254 queries => $sc->{queries},
255 seconds => 0 + sprintf('%.6f', $sc->{seconds}),
256 statements => scalar keys %$by,
257 7 repeated => [ map { { sql => $_, count => $by->{$_}[0],
258 5 seconds => 0 + sprintf('%.6f', $by->{$_}[1]) } } @rep ],
259 };
260 38 }
261  
262 # "file:line" of the first frame outside DBIx::Fast: the application code
263 # that ran the statement.
264 8 ▶ sub _app_caller () {
Subroutine _app_caller: called CC=3 SCAR=11.7
265 8 ▶ for (my $i = 1; my @f = caller $i; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@f) = &CORE::GLOBAL::caller($i)) 33 0 33
266 33 ▶ return "$f[1]:$f[2]" unless $f[0] =~ /\ADBIx::Fast(?:::|\z)/;
Branch: 1 branch
BranchTrueFalseTotal
unless $f[0] =~ /\ADBIx::Fast(?:::|\z)/u 8 25 33
267 }
268 0 return undef;
269 }
270  
271 # EXPLAIN of a slow SELECT on the same handle, as rows (hashrefs, the
272 # driver's columns). Straight on the dbh: no statement cache, no
273 # observation, no HandleError (a failing EXPLAIN is not an error of the
274 # application). Skipped (undef) when it could disturb the connection: an
275 # unread result set on the handle (stream/query, MariaDB "commands out of
276 # sync"), a Pg transaction (a failure there would abort it), or Pg under
277 # redact (its plans print the bound values: "Filter: (email = 'x')").
278 0 ▶ method _slow_plan ($stmt, $binds) {
Subroutine _slow_plan: not called CC=9 SCAR=45.0
279 0 ▶ return undef unless $stmt =~ /\A\s*(?:SELECT|WITH)\b/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $stmt =~ /\A\s*(?:SELECT|WITH)\b/iu 0 0 0
280 0 ▶ my $dbh = $self->db->dbh or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = $self->db->dbh or return undef 0 0 0
281 0 ▶ return undef if $dbh->FETCH('ActiveKids');
Branch: 1 branch
BranchTrueFalseTotal
if $dbh->FETCH("ActiveKids") 0 0 0
282 0 ▶ my $dbd = $_dbd_c //= $self->dbd;
Condition0%0/3
$_dbd_c //= $self->dbd
l!l&&r!l&&!r
000
MC/DC0%0/2
$_dbd_c //= $self->dbd
$_dbd_c $self->dbd
Truth table0%0/3
A //= B
A= $_dbd_cB= $self->dbd
ABresult
1X1
011
000
283 0 ▶ return undef if $dbd eq 'Pg' && ($_slow_redact || !$dbh->FETCH('AutoCommit'));
Branch: 1 branch
BranchTrueFalseTotal
if $dbd eq "Pg" and $_slow_redact || !$dbh->FETCH("AutoCommit") 0 0 0
Condition0%0/6
$dbd eq "Pg" and $_slow_redact || !$dbh->FETCH("AutoCommit")
!ll&&!rl&&r
000
$_slow_redact or not $dbh->FETCH("AutoCommit")
l!l&&r!l&&!r
000
MC/DC0%0/3
$dbd eq "Pg" and $_slow_redact || !$dbh->FETCH("AutoCommit")
$dbd eq "Pg" $_slow_redact not $dbh->FETCH("AutoCommit")
Truth table0%0/4
A and B or not(C)
A= $dbd eq "Pg"B= $_slow_redactC= not $dbh->FETCH("AutoCommit")
ABCresult
0XX0
1000
11X1
1011
284 0 ▶ my $explain = $dbd eq 'SQLite' ? 'EXPLAIN QUERY PLAN' : 'EXPLAIN';
Branch: 1 branch
BranchTrueFalseTotal
$dbd eq 'SQLite' ? : 0 0 0
285 0 local $dbh->{RaiseError} = 1;
286 0 local $dbh->{PrintError} = 0;
287 0 local $dbh->{HandleError} = undef;
288 0 my $plan = eval { $dbh->selectall_arrayref("$explain $stmt", { Slice => {} }, @$binds) };
289 0 return $plan;
290 38 }
291  
292 0 ▶ method _count_error ($class) {
Subroutine _count_error: not called CC=2 SCAR=17.9
293 0 ▶ return unless $_metrics;
Branch: 1 branch
BranchTrueFalseTotal
unless $_metrics 0 0 0
294 0 $_metrics->{errors}{ $class =~ s/\ADBIx::Fast::X:://r }++;
295 38 }
296  
297 # Snapshot of the counters, or undef when metrics are off.
298 6 ▶ method metrics () {
Subroutine metrics: called CC=3 SCAR=11.3
Pod documented
299 6 ▶ return undef unless $_metrics;
Branch: 1 branch
BranchTrueFalseTotal
unless $_metrics 0 6 6
300 6 my %m = %$_metrics;
301 6 $m{errors} = { %{ $_metrics->{errors} } };
302 6 my $acc = 0;
303 6 $m{buckets} = { map { $acc += $_metrics->{buckets}[$_];
304 48 ($DBIx::Fast::SQL::BUCKETS[$_] => $acc) }
305 0 .. $#DBIx::Fast::SQL::BUCKETS };
306 6 ▶ if (my $cache = $self->cache) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cache = $self->cache) 0 6 6
307 0 my $st = $cache->stats;
308 0 @m{qw(cache_hits cache_misses)} = @$st{qw(hits misses)};
309 }
310 6 return \%m;
311 38 }
312  
313 # Start the counters again (e.g. after a deploy warm-up).
314 2 ▶ method reset_metrics () { $self->_enable_metrics if $_metrics; return }
Subroutine reset_metrics: called CC=2 SCAR=7.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
if $_metrics 2 0 2
315 38 field $_json_bytes; # same codec in UTF-8 byte mode (see _json_decode_rows)
316  
317 8 ▶ method _configure_json ($spec) {
Subroutine _configure_json: called CC=8 SCAR=21.0
318 8 ▶ $self->Exception("json_columns must be a hashref of table => [columns]")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 1 7 8
319 unless ref $spec eq 'HASH';
320 7 my (%write, %read);
321 7 for my $table (keys %$spec) {
322 9 my $cols = $spec->{$table};
323 9 ▶ $self->Exception("json_columns: '$table' must map to an arrayref of columns")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cols eq "ARRAY" 1 8 9
324 unless ref $cols eq 'ARRAY';
325 8 ▶ $self->TableName($table) unless $table eq '*';
Branch: 1 branch
BranchTrueFalseTotal
unless $table eq "*" 6 2 8
326 8 for my $col (@$cols) {
327 8 $self->_safe_id($col);
328 7 $write{$table}{$col} = 1;
329 7 $read{$col} = 1;
330 }
331 }
332 5 ▶ return unless %read;
Branch: 1 branch
BranchTrueFalseTotal
unless %read 0 5 5
333 5 ($_json_write, $_json_read) = (\%write, \%read);
334 5 %_json_tcols = ();
335 5 $self->_fast_flags;
336 5 my $class = eval { require Cpanel::JSON::XS; 'Cpanel::JSON::XS' }
337 0 ▶ || 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
500
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
338 5 $_json_codec = $class->new->canonical;
339 5 $_json_bytes = $class->new->canonical->utf8;
340 38 }
341  
342 # A copy of $row with hash/array values of the table's JSON columns encoded
343 # (the caller's hash is not modified); $row itself when nothing applies.
344 27 ▶ method _json_encode_row ($table, $row) {
Subroutine _json_encode_row: called CC=10 SCAR=23.2
345 27 ▶ return $row unless $_json_write && ref $row eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $_json_write and ref $row eq "HASH" 0 27 27
Condition33%1/3
$_json_write and ref $row eq "HASH"
!ll&&!rl&&r
0027
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
346 27 ▶ my $cols = $_json_tcols{$table} //= [ keys %{{ %{ $_json_write->{'*'} // {} },
Condition100%4/4
$_json_tcols{$table} //= [keys %{+{%{$_json_write->{"*"} // {};}, %{$_json_write->{$table} // {};}};}]
l!l
225
$_json_write->{"*"} // {}
l!l
23
MC/DC100%1/1
$_json_tcols{$table} //= [keys %{+{%{$_json_write->{"*"} // {};}, %{$_json_write->{$table} // {};}};}]
$_json_tcols{$table}
MC/DC100%1/1
$_json_write->{"*"} // {}
$_json_write->{"*"}
Truth table100%2/2
A
A= $_json_tcols{$table}
Aresult
11
00
Truth table100%2/2
A
A= $_json_write->{"*"}
Aresult
11
00
347 5 ▶ %{ $_json_write->{$table} // {} } }} ];
Condition50%1/2
$_json_write->{$table} // {}
l!l
50
MC/DC0%0/1
$_json_write->{$table} // {}
$_json_write->{$table}
Truth table50%1/2
A
A= $_json_write->{$table}
Aresult
11
00
348 27 my @enc = grep { exists $row->{$_} && (ref $row->{$_} eq 'HASH'
349 38 ▶ || ref $row->{$_} eq 'ARRAY') } @$cols;
Condition100%6/6
exists $row->{$_} && (ref $row->{$_} eq 'HASH' || ref $row->{$_} eq 'ARRAY')
!ll&&!rl&&r
4259
ref $row->{$_} eq "HASH" or ref $row->{$_} eq "ARRAY"
l!l&&r!l&&!r
5425
MC/DC100%3/3
exists $row->{$_} && (ref $row->{$_} eq 'HASH' || ref $row->{$_} eq 'ARRAY')
exists $row->{$_} ref $row->{$_} eq "HASH" ref $row->{$_} eq "ARRAY"
Truth table100%4/4
A && B or C
A= exists $row->{$_}B= ref $row->{$_} eq "HASH"C= ref $row->{$_} eq "ARRAY"
ABCresult
0XX0
1000
11X1
1011
350 27 ▶ return $row unless @enc;
Branch: 1 branch
BranchTrueFalseTotal
unless @enc 20 7 27
351 7 my %r = %$row;
352 7 $r{$_} = $_json_codec->encode($r{$_}) for @enc;
353 7 return \%r;
354 38 }
355  
356 1 ▶ method _json_encode_rows ($table, $rows) {
Subroutine _json_encode_rows: called CC=2 SCAR=7.0
357 1 ▶ return $rows unless $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
unless $_json_write 0 1 1
358 1 return [ map { $self->_json_encode_row($table, $_) } @$rows ];
359 38 }
360  
361 # Decode the JSON columns of fetched rows in place: only values that look
362 # like a JSON object/array; anything else (or malformed JSON) is left as is.
363 # JSON text is UTF-8: a driver without its UTF-8 flag (SQLite without
364 # sqlite_unicode, DBD::mysql without mysql_enable_utf8mb4) hands back the
365 # raw bytes, which are decoded as UTF-8; already-decoded character strings
366 # (DBD::Pg, DBD::MariaDB) as characters. Non-ASCII then round-trips on
367 # every driver whatever its flags.
368 17 ▶ method _json_decode_rows ($rows) {
Subroutine _json_decode_rows: called CC=13 SCAR=28.7
369 17 ▶ my @rows = ref $rows eq 'HASH' ? ($rows) : @$rows;
Branch: 1 branch
BranchTrueFalseTotal
ref $rows eq 'HASH' ? : 9 8 17
370 # Only the configured columns this result set actually has (all its rows
371 # share the first row's keys) - not every configured name on every row.
372 17 my $first = $rows[0];
373 17 ▶ return $rows unless ref $first eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $first eq "HASH" 0 17 17
374 17 ▶ my @cols = grep { exists $first->{$_} } keys %$_json_read or return $rows;
Branch: 1 branch
BranchTrueFalseTotal
my(@cols) = grep({exists $first->{$_};} keys %$_json_read) or return $rows 14 3 17
375 14 for my $row (@rows) {
376 16 ▶ next unless ref $row eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 0 16 16
377 16 for my $col (@cols) {
378 17 my $v = $row->{$col};
379 17 ▶ 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 0 17 17
Condition33%2/6
defined $v and not ref $v and $v =~ /\A\s*[\[{]/u
!ll&&!rl&&r
0017
defined $v and not ref $v
!ll&&!rl&&r
0017
MC/DC0%0/3
defined $v and not ref $v and $v =~ /\A\s*[\[{]/u
defined $v not ref $v $v =~ /\A\s*[\[{]/u
Truth table25%1/4
A and not(B) and C
A= defined $vB= not ref $vC= $v =~ /\A\s*[\[{]/u
ABCresult
0XX0
10X0
1100
1111
380 my $d = utf8::is_utf8($v)
381 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
1700
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
382 0 ▶ : eval { $_json_bytes->decode($v) } // eval { $_json_codec->decode($v) };
Branch: 1 branch
BranchTrueFalseTotal
utf8::is_utf8($v) ? : 0 17 17
383 17 ▶ $row->{$col} = $d if defined $d;
Branch: 1 branch
BranchTrueFalseTotal
if defined $d 17 0 17
384 }
385 }
386 14 return $rows;
387 38 }
388  
389 # CRUD statement cache. SQL::Abstract 2 needs 100-175us to render even a
390 # one-column INSERT/UPDATE/DELETE, yet for plain-scalar specs the SQL text
391 # depends only on the table and the (sorted) column names and the binds are
392 # the values in that same sorted order. SQL::Abstract stays the single
393 # source of truth: it renders each shape once, on the first miss.
394 38 field %_crud_sql;
395  
396 209 ▶ method _crud_stmt ($key, $render) {
Subroutine _crud_stmt: called CC=2 SCAR=7.0
397 209 _trim_cache(\%_crud_sql, 1_000); # bound data-driven shapes
398 209 ▶ return $_crud_sql{$key} //= ($render->())[0];
Condition66%2/3
$_crud_sql{$key} //= (&$render())[0]
l!l&&r!l&&!r
019712
MC/DC50%1/2
$_crud_sql{$key} //= (&$render())[0]
$_crud_sql{$key} (&$render())[0]
Truth table66%2/3
A //= B
A= $_crud_sql{$key}B= (&$render())[0]
ABresult
1X1
011
000
399 38 }
400  
401 # A WHERE hash the cache can serve: col => defined plain scalar only
402 # (undef means IS NULL, refs are operators - both go through SQL::Abstract).
403 151 ▶ sub _plain_where ($w) {
Subroutine _plain_where: called CC=6 SCAR=17.9
404 151 ▶ return 0 unless ref $w eq 'HASH' && %$w;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $w eq "HASH" and %$w 13 138 151
Condition66%2/3
ref $w eq "HASH" and %$w
!ll&&!rl&&r
130138
MC/DC50%1/2
ref $w eq "HASH" and %$w
ref $w eq "HASH" %$w
Truth table66%2/3
A and B
A= ref $w eq "HASH"B= %$w
ABresult
0X0
100
111
405 138 ▶ for (values %$w) { return 0 if !defined || ref }
Branch: 1 branch
BranchTrueFalseTotal
if not defined $_ or ref $_ 45 105 150
Condition100%3/3
not defined $_ or ref $_
l!l&&r!l&&!r
243105
MC/DC100%2/2
not defined $_ or ref $_
not defined $_ ref $_
Truth table100%3/3
not(A) or B
A= not defined $_B= ref $_
ABresult
1X1
011
000
406 93 return 1;
407 }
408  
409 216 ▶ method _track ($code) {
Subroutine _track: called CC=8 SCAR=20.8
410 216 ▶ my $tracker = $_tracker && $_tracker->enabled ? $_tracker : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_tracker && $_tracker->enabled ? : 11 205 216
Condition100%3/3
$_tracker and $_tracker->enabled
!ll&&!rl&&r
204111
MC/DC100%2/2
$_tracker and $_tracker->enabled
$_tracker $_tracker->enabled
Truth table100%3/3
A and B
A= $_trackerB= $_tracker->enabled
ABresult
0X0
100
111
411 216 ▶ if ($tracker || $_observe) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tracker or $_observe) 20 196 216
Condition100%3/3
$tracker or $_observe
l!l&&r!l&&!r
119196
MC/DC100%2/2
$tracker or $_observe
$tracker $_observe
Truth table100%3/3
A or B
A= $trackerB= $_observe
ABresult
1X1
011
000
412 20 my $t0 = Time::HiRes::time();
413 20 my $res = $code->();
414 20 my $t1 = Time::HiRes::time();
415 20 ▶ $tracker->add_query($sql, $p // [], $t0, $t1) if $tracker;
Branch: 1 branch
BranchTrueFalseTotal
if $tracker 11 9 20
Condition50%1/2
$p // []
l!l
110
MC/DC0%0/1
$p // []
$p
Truth table50%1/2
A
A= $p
Aresult
11
00
416 20 ▶ $self->_observed($t1 - $t0) if $_observe;
Branch: 1 branch
BranchTrueFalseTotal
if $_observe 9 11 20
417 20 $last_sql = $sql;
418 20 return $res;
419 }
420 196 $last_sql = $sql;
421  
422 196 return $code->();
423 38 }
424  
425 # Statement-handle cache, replacing DBI's prepare_cached (Perl code in
426 # DBI.pm, ~15% of a simple read). Same semantics as its if_active=3 mode: a
427 # cached handle that is still Active (a live query() iterator on the same
428 # SQL) is replaced by a fresh one. Emptied by DBIx::Fast's on_connect hook on
429 # every (re)connect, so a handle never outlives its connection.
430 #
431 # Two caches. %_sth_cache serves the reads that consume their result before
432 # returning (val, hash, all, array, flat, count, execute...): its handles
433 # are never left mid-result, so they are reused without the Active check
434 # (~160 ns per read). %_sth_live serves the handles given back to the caller
435 # (query() iterators, exec, execute_prepare): one of those may still be
436 # being read, so an Active one is replaced as before.
437 38 field %_sth_cache;
438 38 field %_sth_live;
439 38 field $_conn; # the connector (same object as DBIx::Fast's db)
440 144 ▶ method _set_conn ($c) { $_conn = $c }
Subroutine _set_conn: called CC=1 SCAR=0.0
441 289 ▶ method _reset_sth_cache () { %_sth_cache = (); %_sth_live = (); %_pg_pk = () }
Subroutine _reset_sth_cache: called CC=1 SCAR=0.0
442  
443 2122 ▶ method _prepare ($dbh, $stmt) {
Subroutine _prepare: called CC=3 SCAR=11.0
444 2122 my $sth = $_sth_cache{$stmt};
445 2122 ▶ return $sth if $sth;
Branch: 1 branch
BranchTrueFalseTotal
if $sth 74 2048 2122
446 2048 ▶ $sth = $dbh->prepare($stmt) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sth = $dbh->prepare($stmt) or return undef 2025 21 2046
447 2025 _trim_cache(\%_sth_cache, 1_000); # bound data-driven SQL
448 2025 return $_sth_cache{$stmt} = $sth;
449 38 }
450  
451 233 ▶ method _prepare_live ($dbh, $stmt) {
Subroutine _prepare_live: called CC=4 SCAR=13.9
452 233 my $sth = $_sth_live{$stmt};
453 233 ▶ return $sth if $sth && !$sth->FETCH('Active');
Branch: 1 branch
BranchTrueFalseTotal
if $sth and not $sth->FETCH("Active") 22 211 233
Condition100%3/3
$sth and not $sth->FETCH("Active")
!ll&&!rl&&r
202922
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
454 211 ▶ $sth = $dbh->prepare($stmt) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sth = $dbh->prepare($stmt) or return undef 208 1 209
455 208 _trim_cache(\%_sth_live, 1_000);
456 208 return $_sth_live{$stmt} = $sth;
457 38 }
458  
459 # Run the current $sql/$p and shape the result with $shape (one of the
460 # _shape_* subs below, which take the executed handle - or undef when the
461 # prepare failed under RaiseError => 0 - and return the value). Without an
462 # active tracker (the normal case) nothing is allocated per call: no
463 # closure, no extra frame; with one, the query is timed and recorded.
464 1866 ▶ method _fetch ($shape) {
Subroutine _fetch: called CC=15 SCAR=27.1
465 # Inline check (this runs on every read): only a statement with an
466 # arrayref bind pays for the IN (?) rewrite.
467 1866 ▶ if ($p) { for (@$p) { if (ref $_ eq 'ARRAY') { $self->_expand_in_binds; last } } }
Branch: 2 branches
BranchTrueFalseTotal
if ($p) 1863 3 1866
if (ref $_ eq "ARRAY") 22 1721 1743
468 1865 my $res;
469 1865 ▶ my $tracker = $_tracker && $_tracker->enabled ? $_tracker : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_tracker && $_tracker->enabled ? : 13 1852 1865
Condition66%2/3
$_tracker and $_tracker->enabled
!ll&&!rl&&r
1852013
MC/DC50%1/2
$_tracker and $_tracker->enabled
$_tracker $_tracker->enabled
Truth table66%2/3
A and B
A= $_trackerB= $_tracker->enabled
ABresult
0X0
100
111
470 1865 ▶ if ($tracker || $_observe) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tracker or $_observe) { } 77 1788 1865
Condition100%3/3
$tracker or $_observe
l!l&&r!l&&!r
13641788
MC/DC100%2/2
$tracker or $_observe
$tracker $_observe
Truth table100%3/3
A or B
A= $trackerB= $_observe
ABresult
1X1
011
000
471 77 my $t0 = Time::HiRes::time();
472 77 $res = $shape->($self->_read_exec($shape == \&_shape_sth));
473 77 my $t1 = Time::HiRes::time();
474 77 ▶ $tracker->add_query($sql, $p // [], $t0, $t1) if $tracker;
Branch: 1 branch
BranchTrueFalseTotal
if $tracker 13 64 77
Condition50%1/2
$p // []
l!l
130
MC/DC0%0/1
$p // []
$p
Truth table50%1/2
A
A= $p
Aresult
11
00
475 77 ▶ $self->_observed($t1 - $t0) if $_observe;
Branch: 1 branch
BranchTrueFalseTotal
if $_observe 64 13 77
476 77 $last_sql = $sql;
477 }
478 else {
479 1788 $last_sql = $sql;
480 1788 $res = $shape->($self->_read_exec($shape == \&_shape_sth));
481 }
482 1856 ▶ $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 17 1839 1856
Condition88%8/9
$_json_read and $shape == \&DBIx::Fast::SQL::_shape_rows || $shape == \&DBIx::Fast::SQL::_shape_hash and $res
!ll&&!rl&&r
1839017
$_json_read and $shape == \&DBIx::Fast::SQL::_shape_rows || $shape == \&DBIx::Fast::SQL::_shape_hash
!ll&&!rl&&r
18281117
$shape == \&DBIx::Fast::SQL::_shape_rows or $shape == \&DBIx::Fast::SQL::_shape_hash
l!l&&r!l&&!r
8911
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
483 if $_json_read && ($shape == \&_shape_rows || $shape == \&_shape_hash) && $res;
484 1856 return $res;
485 38 }
486  
487 # "IN (?)" with an arrayref bind becomes "IN (?, ?, ?)" with the elements as
488 # binds. Only placeholders inside IN ( ... ) are expanded - an arrayref
489 # elsewhere stays one bind (DBD::Pg arrays, "= ANY(?)") - and placeholders
490 # inside quoted literals/identifiers are not counted. Returns undef for an
491 # empty list ("IN ()" is invalid SQL, and IN (NULL) would make NOT IN match
492 # nothing).
493 24 ▶ sub _expand_in ($stmt, $binds) {
Subroutine _expand_in: called CC=7 SCAR=19.5
494 24 my ($out, @nb) = ('');
495 24 my $i = 0;
496 24 ▶ while ($stmt =~ m{\G( '(?:[^'\\]|\\.|'')*'
Branch: 1 branch
BranchTrueFalseTotal
if ($stmt =~ /\G( '(?:[^'\\]|\\.|'')*' | "(?:[^"\\]|\\.|"")*" | `[^`]*` | [^'"`?]+ | \? | . )/cgsux) 77 23 100
497 | "(?:[^"\\]|\\.|"")*"
498 | `[^`]*`
499 | [^'"`?]+
500 | \?
501 | . )}gcxs) {
502 77 my $tok = $1;
503 77 ▶ if ($tok ne '?') { $out .= $tok; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($tok ne "?") 51 26 77
504 26 my $v = $binds->[$i++];
505 26 ▶ 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) { } 24 2 26
Condition100%3/3
ref $v eq "ARRAY" and $out =~ /\bIN\s*\(\s*\z/iu
!ll&&!rl&&r
1124
MC/DC100%2/2
ref $v eq "ARRAY" and $out =~ /\bIN\s*\(\s*\z/iu
ref $v eq "ARRAY" $out =~ /\bIN\s*\(\s*\z/iu
Truth table100%3/3
A and B
A= ref $v eq "ARRAY"B= $out =~ /\bIN\s*\(\s*\z/iu
ABresult
0X0
100
111
506 24 ▶ return undef unless @$v;
Branch: 1 branch
BranchTrueFalseTotal
unless @$v 1 23 24
507 23 $out .= join(', ', ('?') x @$v);
508 23 push @nb, @$v;
509 }
510 else {
511 2 $out .= '?';
512 2 push @nb, $v;
513 }
514 }
515 0 ▶ push @nb, @{$binds}[ $i .. $#$binds ] if $i < @$binds; # arity left to DBI
Branch: 1 branch
BranchTrueFalseTotal
if $i < @$binds 0 23 23
516 23 return ($out, \@nb);
517 }
518  
519  
520 # Apply _expand_in to the current statement when any bind is an arrayref.
521 23 ▶ method _expand_in_binds () {
Subroutine _expand_in_binds: called CC=2 SCAR=6.9
522 23 my ($stmt, $binds) = _expand_in($sql, $p);
523 23 ▶ $self->Exception("IN (?) bound to an empty list") unless defined $stmt;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $stmt 1 22 23
524 22 ($sql, $p) = ($stmt, $binds);
525 38 }
526  
527 # The hashes fetchall_arrayref({}) builds (FetchHashKeyName honoured, a
528 # later duplicate column wins), but the rows come from the driver's C
529 # fetchall and each hash is one slice: +15-20% on 10 rows (MariaDB, Pg,
530 # SQLite). A statement without result columns keeps the DBI path.
531 111 ▶ sub _shape_rows ($sth) {
Subroutine _shape_rows: called CC=4 SCAR=14.7
532 111 ▶ return [] unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 13 98 111
533 98 ▶ my $names = $sth->FETCH($sth->FETCH('FetchHashKeyName') || 'NAME');
Condition50%1/2
$sth->FETCH('FetchHashKeyName') || 'NAME'
l!l
980
MC/DC0%0/1
$sth->FETCH('FetchHashKeyName') || 'NAME'
$sth->FETCH('FetchHashKeyName')
Truth table50%1/2
A
A= $sth->FETCH('FetchHashKeyName')
Aresult
11
00
534 98 ▶ unless ($names) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($names) 0 98 98
535 0 my $rows = $sth->fetchall_arrayref({});
536 0 $sth->finish;
537 0 return $rows;
538 }
539 98 my $all = $sth->fetchall_arrayref;
540 98 $sth->finish;
541 98 return [ map { my %h; @h{@$names} = @$_; \%h } @$all ];
542 }
543  
544 43 ▶ sub _shape_hash ($sth) {
Subroutine _shape_hash: called CC=2 SCAR=7.0
545 43 ▶ return undef unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 43 43
546 43 my $row = $sth->fetchrow_hashref;
547 43 $sth->finish;
548 43 return $row;
549 }
550  
551 # First column of first row - the historical val() contract (DBI leaves a
552 # multi-column scalar selectrow_array undefined; pin FIRST so val() never
553 # changes value between builds). Also count()'s shape.
554 1681 ▶ sub _shape_val ($sth) {
Subroutine _shape_val: called CC=2 SCAR=6.9
555 1681 ▶ return undef unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 1 1680 1681
556 1680 my ($first) = $sth->fetchrow_array;
557 1680 $sth->finish;
558 1680 return $first;
559 }
560  
561 # fetchall_arrayref([0]) loops in DBI's C path - much faster than a per-row
562 # Perl fetch on large result sets.
563 17 ▶ sub _shape_column ($sth) {
Subroutine _shape_column: called CC=2 SCAR=7.0
564 17 ▶ return [] unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 17 17
565 17 my $col = $sth->fetchall_arrayref([0]);
566 17 $sth->finish;
567 17 return [ map { $_->[0] } @$col ];
568 }
569  
570 4 ▶ sub _shape_exists ($sth) {
Subroutine _shape_exists: called CC=3 SCAR=11.0
571 4 ▶ return 0 unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 4 4
572 4 my ($one) = $sth->fetchrow_array;
573 4 $sth->finish;
574 4 ▶ return $one ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$one ? : 3 1 4
575 }
576  
577 11 ▶ sub _shape_kv ($sth) {
Subroutine _shape_kv: called CC=3 SCAR=11.3
578 11 ▶ return {} unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 11 11
579 11 ▶ my $pair = $sth->fetchall_arrayref([0, 1]) // [];
Condition50%1/2
$sth->fetchall_arrayref([0, 1]) // []
l!l
110
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
580 11 $sth->finish;
581 11 return { map { $_->[0] => $_->[1] } @$pair };
582 }
583  
584 16 ▶ sub _shape_sth ($sth) { $sth }
Subroutine _shape_sth: called CC=1 SCAR=0.0
585  
586 # Prepare (through the statement cache) + execute of the current $sql/$p for
587 # the read methods. With strict_reads a failed prepare/execute throws;
588 # otherwise the historical behaviour stands (HandleError records the error
589 # and the read returns an empty result). Returns undef when the prepare
590 # itself failed (SQLite/Pg reject bad SQL at prepare time; MariaDB only at
591 # execute), and each shape maps that to the same empty value MariaDB gives.
592 1867 ▶ method _read_exec ($live = 0) {
Subroutine _read_exec: called CC=8 SCAR=20.9
593 1867 my $dbh = $_conn->dbh;
594 1867 ▶ my $sth = $live ? $self->_prepare_live($dbh, $sql) : $self->_prepare($dbh, $sql);
Branch: 1 branch
BranchTrueFalseTotal
$live ? : 16 1851 1867
595 1865 ▶ unless ($sth) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 22 1843 1865
596 22 ▶ $self->_read_failed($dbh) if $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if $self->strict_reads 7 15 22
597 15 return undef;
598 }
599 1843 ▶ my $rv = $p ? $sth->execute(@{$p}) : $sth->execute;
Branch: 1 branch
BranchTrueFalseTotal
$p ? : 1842 1 1843
600 1842 ▶ $self->_read_failed($sth) unless $rv || !$self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
unless $rv or not $self->strict_reads 0 1842 1842
Condition33%1/3
$rv or not $self->strict_reads
l!l&&r!l&&!r
184200
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
601 1842 return $sth;
602 38 }
603  
604 9 ▶ method _read_failed ($h) {
Subroutine _read_failed: called CC=1 SCAR=0.0
605 # HandleError has already recorded the driver error; the text appends it.
606 9 $self->_db_fail("read failed", $h);
607 38 }
608  
609 # $sth->rows normalized: DBI's '0E0' -> 0, unknown (-1) -> undef.
610 # Rows affected by a write: execute()'s return value (DBI's contract: the
611 # count, '0E0' for none, -1 unknown), falling back to $sth->rows. The return
612 # value is the reliable one - DBD::Pg reports rows() -1 (or a stale count on
613 # a reused handle) after INSERT ... ON CONFLICT DO NOTHING.
614 485 ▶ sub _affected ($sth, $rv = undef) {
Subroutine _affected: called CC=7 SCAR=26.7
615 485 ▶ my $n = defined $rv && $rv >= 0 ? $rv : $sth ? $sth->rows : undef;
Branch: 2 branches
BranchTrueFalseTotal
defined $rv && $rv >= 0 ? : 485 0 485
$sth ? : 0 0 0
Condition33%1/3
defined $rv and $rv >= 0
!ll&&!rl&&r
00485
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
616 485 ▶ return defined $n && $n >= 0 ? $n + 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $n && $n >= 0 ? : 485 0 485
Condition33%1/3
defined $n and $n >= 0
!ll&&!rl&&r
00485
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
617 }
618  
619 2 ▶ method q ($stmt, @params) {
Subroutine q: called CC=1 SCAR=0.0
Pod documented
620 2 $sql = $stmt;
621 2 $p = \@params;
622 38 }
623  
624 101 ▶ method all (@args) {
Subroutine all: called CC=9 SCAR=22.1
Pod documented
625 101 $sql = shift @args;
626 101 $p = \@args;
627  
628 # Fast path: the cached, idle statement handle executed directly, without
629 # the _fetch/_read_exec/_prepare layers - same result and errors (dbh()
630 # still runs first: fork/reconnect checks, and a reconnect empties the
631 # cache; a failed execute goes through _read_failed as in _read_exec).
632 # Kept inline (no helper call) on purpose: this is the hottest code.
633 101 ▶ if ($_fast_rows && defined $sql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_fast_rows and defined $sql) 86 15 101
Condition66%2/3
$_fast_rows and defined $sql
!ll&&!rl&&r
15086
MC/DC50%1/2
$_fast_rows and defined $sql
$_fast_rows defined $sql
Truth table66%2/3
A and B
A= $_fast_rowsB= defined $sql
ABresult
0X0
100
111
634 FAST: {
635 86 ▶ for (@args) { last FAST if ref $_ eq 'ARRAY' } # IN (?) lists
Branch: 1 branch
BranchTrueFalseTotal
if ref $_ eq "ARRAY" 10 42 52
636 76 $_conn->dbh;
637 76 ▶ my $sth = $_sth_cache{$sql} or last FAST;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $_sth_cache{$sql} or last FAST 22 54 76
638 22 $last_sql = $sql;
639 22 ▶ my $rv = @args ? $sth->execute(@args) : $sth->execute;
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 15 7 22
640 22 ▶ $self->_read_failed($sth) if !$rv && $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if not $rv and $self->strict_reads 0 22 22
Condition33%1/3
not $rv and $self->strict_reads
!ll&&!rl&&r
2200
MC/DC0%0/2
not $rv and $self->strict_reads
not $rv $self->strict_reads
Truth table33%1/3
not(A) and B
A= not $rvB= $self->strict_reads
ABresult
0X0
100
111
641 22 return $results = _shape_rows($sth);
642 }
643 }
644 79 return $results = $self->_fetch(\&_shape_rows);
645 38 }
646  
647 6 ▶ method flat (@args) {
Subroutine flat: called CC=1 SCAR=0.0
Pod documented
648 6 $sql = shift @args;
649 6 $p = \@args;
650  
651 6 $results = $self->_fetch(\&_shape_column);
652 6 return @$results;
653 38 }
654  
655 87 ▶ method hash (@args) {
Subroutine hash: called CC=9 SCAR=22.4
Pod documented
656 87 $sql = shift @args;
657 87 $p = \@args;
658  
659 # Fast path: the cached, idle statement handle executed directly, without
660 # the _fetch/_read_exec/_prepare layers - same result and errors (dbh()
661 # still runs first: fork/reconnect checks, and a reconnect empties the
662 # cache; a failed execute goes through _read_failed as in _read_exec).
663 # Kept inline (no helper call) on purpose: this is the hottest code.
664 87 ▶ if ($_fast_rows && defined $sql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_fast_rows and defined $sql) 75 12 87
Condition66%2/3
$_fast_rows and defined $sql
!ll&&!rl&&r
12075
MC/DC50%1/2
$_fast_rows and defined $sql
$_fast_rows defined $sql
Truth table66%2/3
A and B
A= $_fast_rowsB= defined $sql
ABresult
0X0
100
111
665 FAST: {
666 75 ▶ for (@args) { last FAST if ref $_ eq 'ARRAY' } # IN (?) lists
Branch: 1 branch
BranchTrueFalseTotal
if ref $_ eq "ARRAY" 0 72 72
667 75 $_conn->dbh;
668 75 ▶ my $sth = $_sth_cache{$sql} or last FAST;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $_sth_cache{$sql} or last FAST 43 32 75
669 43 $last_sql = $sql;
670 43 ▶ my $rv = @args ? $sth->execute(@args) : $sth->execute;
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 43 0 43
671 43 ▶ $self->_read_failed($sth) if !$rv && $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if not $rv and $self->strict_reads 0 43 43
Condition33%1/3
not $rv and $self->strict_reads
!ll&&!rl&&r
4300
MC/DC0%0/2
not $rv and $self->strict_reads
not $rv $self->strict_reads
Truth table33%1/3
not(A) and B
A= not $rvB= $self->strict_reads
ABresult
0X0
100
111
672 43 my $row = $sth->fetchrow_hashref;
673 43 $sth->finish;
674 43 return $results = $row;
675 }
676 }
677 44 return $results = $self->_fetch(\&_shape_hash);
678 38 }
679  
680 1726 ▶ method val (@args) {
Subroutine val: called CC=9 SCAR=22.0
Pod documented
681 1726 $sql = shift @args;
682 1726 $p = \@args;
683  
684 # Fast path: the cached, idle statement handle executed directly, without
685 # the _fetch/_read_exec/_prepare layers - same result and errors (dbh()
686 # still runs first: fork/reconnect checks, and a reconnect empties the
687 # cache; a failed execute goes through _read_failed as in _read_exec).
688 # Kept inline (no helper call) on purpose: this is the hottest code.
689 1726 ▶ if ($_fast && defined $sql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_fast and defined $sql) 1672 54 1726
Condition66%2/3
$_fast and defined $sql
!ll&&!rl&&r
5401672
MC/DC50%1/2
$_fast and defined $sql
$_fast defined $sql
Truth table66%2/3
A and B
A= $_fastB= defined $sql
ABresult
0X0
100
111
690 FAST: {
691 1672 ▶ for (@args) { last FAST if ref $_ eq 'ARRAY' } # IN (?) lists
Branch: 1 branch
BranchTrueFalseTotal
if ref $_ eq "ARRAY" 4 1629 1633
692 1668 $_conn->dbh;
693 1668 ▶ my $sth = $_sth_cache{$sql} or last FAST;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $_sth_cache{$sql} or last FAST 70 1598 1668
694 70 $last_sql = $sql;
695 70 ▶ my $rv = @args ? $sth->execute(@args) : $sth->execute;
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 65 5 70
696 70 ▶ $self->_read_failed($sth) if !$rv && $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if not $rv and $self->strict_reads 2 68 70
Condition100%3/3
not $rv and $self->strict_reads
!ll&&!rl&&r
6622
MC/DC100%2/2
not $rv and $self->strict_reads
not $rv $self->strict_reads
Truth table100%3/3
not(A) and B
A= not $rvB= $self->strict_reads
ABresult
0X0
100
111
697 68 my ($first) = $sth->fetchrow_array;
698 68 $sth->finish;
699 68 return $results = $first;
700 }
701 }
702 1656 return $results = $self->_fetch(\&_shape_val);
703 38 }
704  
705 # Prepared operations: a closure over one statement for loops that run it
706 # many times. Same results and errors as val/hash/all/insert - each call
707 # takes the inline path when the statement is cached and nothing has to
708 # happen around it, and otherwise (first call, IN (?) lists, json_columns,
709 # metrics, profiler...) just calls the method - but without the method
710 # entry, argument copy, identifier checks and cache-key work per call.
711 # They do not update results(); sql/p/last_sql are kept for errors.
712 5 ▶ method compile_val ($stmt) {
Subroutine compile_val: called CC=3 SCAR=11.1
Pod documented
713 5 ▶ $self->Exception("compile_val: SQL statement required") unless defined $stmt && length $stmt;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $stmt and length $stmt 1 4 5
Condition66%2/3
defined $stmt and length $stmt
!ll&&!rl&&r
014
MC/DC50%1/2
defined $stmt and length $stmt
defined $stmt length $stmt
Truth table66%2/3
A and B
A= defined $stmtB= length $stmt
ABresult
0X0
100
111
714 11 ▶ return sub {
Subroutine __ANON__: called CC=7 SCAR=20.1
715 11 ▶ if ($_fast) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_fast) 11 0 11
716 FAST: {
717 11 ▶ for (@_) { last FAST if ref $_ eq 'ARRAY' }
Branch: 1 branch
BranchTrueFalseTotal
if ref $_ eq "ARRAY" 0 10 10
718 11 $_conn->dbh;
719 11 ▶ my $sth = $_sth_cache{$stmt} or last FAST;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $_sth_cache{$stmt} or last FAST 5 6 11
720 5 ($sql, $p, $last_sql) = ($stmt, [@_], $stmt);
721 5 my $rv = $sth->execute(@_);
722 5 ▶ $self->_read_failed($sth) if !$rv && $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if not $rv and $self->strict_reads 0 5 5
Condition33%1/3
not $rv and $self->strict_reads
!ll&&!rl&&r
500
MC/DC0%0/2
not $rv and $self->strict_reads
not $rv $self->strict_reads
Truth table33%1/3
not(A) and B
A= not $rvB= $self->strict_reads
ABresult
0X0
100
111
723 5 my ($first) = $sth->fetchrow_array;
724 5 $sth->finish;
725 5 return $first;
726 }
727 }
728 6 return $self->val($stmt, @_);
729 4 };
730 38 }
731  
732 2 ▶ method compile_hash ($stmt) {
Subroutine compile_hash: called CC=3 SCAR=11.2
Pod documented
733 2 ▶ $self->Exception("compile_hash: SQL statement required") unless defined $stmt && length $stmt;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $stmt and length $stmt 0 2 2
Condition33%1/3
defined $stmt and length $stmt
!ll&&!rl&&r
002
MC/DC0%0/2
defined $stmt and length $stmt
defined $stmt length $stmt
Truth table33%1/3
A and B
A= defined $stmtB= length $stmt
ABresult
0X0
100
111
734 7 ▶ return sub {
Subroutine __ANON__: called CC=7 SCAR=19.8
735 7 ▶ if ($_fast_rows) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_fast_rows) 6 1 7
736 FAST: {
737 6 ▶ for (@_) { last FAST if ref $_ eq 'ARRAY' }
Branch: 1 branch
BranchTrueFalseTotal
if ref $_ eq "ARRAY" 0 6 6
738 6 $_conn->dbh;
739 6 ▶ my $sth = $_sth_cache{$stmt} or last FAST;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $_sth_cache{$stmt} or last FAST 5 1 6
740 5 ($sql, $p, $last_sql) = ($stmt, [@_], $stmt);
741 5 my $rv = $sth->execute(@_);
742 5 ▶ $self->_read_failed($sth) if !$rv && $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if not $rv and $self->strict_reads 0 5 5
Condition33%1/3
not $rv and $self->strict_reads
!ll&&!rl&&r
500
MC/DC0%0/2
not $rv and $self->strict_reads
not $rv $self->strict_reads
Truth table33%1/3
not(A) and B
A= not $rvB= $self->strict_reads
ABresult
0X0
100
111
743 5 my $row = $sth->fetchrow_hashref;
744 5 $sth->finish;
745 5 return $row;
746 }
747 }
748 2 return $self->hash($stmt, @_);
749 2 };
750 38 }
751  
752 2 ▶ method compile_all ($stmt) {
Subroutine compile_all: called CC=3 SCAR=11.3
Pod documented
753 2 ▶ $self->Exception("compile_all: SQL statement required") unless defined $stmt && length $stmt;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $stmt and length $stmt 0 2 2
Condition33%1/3
defined $stmt and length $stmt
!ll&&!rl&&r
002
MC/DC0%0/2
defined $stmt and length $stmt
defined $stmt length $stmt
Truth table33%1/3
A and B
A= defined $stmtB= length $stmt
ABresult
0X0
100
111
754 8 ▶ return sub {
Subroutine __ANON__: called CC=7 SCAR=19.9
755 8 ▶ if ($_fast_rows) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_fast_rows) 8 0 8
756 FAST: {
757 8 ▶ for (@_) { last FAST if ref $_ eq 'ARRAY' }
Branch: 1 branch
BranchTrueFalseTotal
if ref $_ eq "ARRAY" 2 6 8
758 6 $_conn->dbh;
759 6 ▶ my $sth = $_sth_cache{$stmt} or last FAST;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $_sth_cache{$stmt} or last FAST 5 1 6
760 5 ($sql, $p, $last_sql) = ($stmt, [@_], $stmt);
761 5 my $rv = $sth->execute(@_);
762 5 ▶ $self->_read_failed($sth) if !$rv && $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if not $rv and $self->strict_reads 0 5 5
Condition33%1/3
not $rv and $self->strict_reads
!ll&&!rl&&r
500
MC/DC0%0/2
not $rv and $self->strict_reads
not $rv $self->strict_reads
Truth table33%1/3
not(A) and B
A= not $rvB= $self->strict_reads
ABresult
0X0
100
111
763 5 return _shape_rows($sth);
764 }
765 }
766 3 return $self->all($stmt, @_);
767 2 };
768 38 }
769  
770 # $ins->(@values) inserts one row (values in the order of @cols) and
771 # returns last_id, as insert() does. Table and columns are validated once,
772 # here. With timestamps, json_columns, after_write, a result cache or a
773 # reference value it builds the row hash and calls insert().
774 9 ▶ method compile_insert ($table_name, @cols) {
Subroutine compile_insert: called CC=6 SCAR=19.1
Pod documented
775 9 my $table = $self->TableName($table_name);
776 8 ▶ $self->Exception("compile_insert: column list required") unless @cols;
Branch: 1 branch
BranchTrueFalseTotal
unless @cols 1 7 8
777 7 $self->_safe_ids(@cols);
778 5 my %seen;
779 5 ▶ $seen{$_}++ and $self->Exception("compile_insert: column '$_' given twice") for @cols;
Branch: 1 branch
BranchTrueFalseTotal
$seen{$_}++ and $self->Exception("compile_insert: column '${_}' given twice") 1 7 8
780 4 ▶ my $dbd = $_dbd_c //= $self->dbd;
Condition33%1/3
$_dbd_c //= $self->dbd
l!l&&r!l&&!r
400
MC/DC0%0/2
$_dbd_c //= $self->dbd
$_dbd_c $self->dbd
Truth table33%1/3
A //= B
A= $_dbd_cB= $self->dbd
ABresult
1X1
011
000
781 4 ▶ my $ret = $dbd eq 'Pg' ? $self->_pg_returning($table) : '';
Branch: 1 branch
BranchTrueFalseTotal
$dbd eq 'Pg' ? : 0 4 4
782 4 my $dbh = $_conn->dbh;
783 my $stmt = 'INSERT INTO ' . $self->_quote_ident_path($table)
784 4 . ' (' . join(', ', map { $dbh->quote_identifier($_) } @cols) . ')'
785 . ' VALUES (' . join(', ', ('?') x @cols) . ')' . $ret;
786 4 my $n = @cols;
787 9 ▶ return sub {
Subroutine __ANON__: called CC=17 SCAR=33.4
788 9 ▶ $self->Exception("compile_insert: $n values expected, got " . scalar @_) unless @_ == $n;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == $n 1 8 9
789 8 ▶ if (!$_fast || $_json_write || $_ts_on || $_after_write || $_cache_on || grep { ref } @_) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $_fast or $_json_write or $_ts_on or $_after_write or $_cache_on or grep {ref $_;} @_) 2 6 8
Condition73%11/15
not $_fast or $_json_write or $_ts_on or $_after_write or $_cache_on or grep {ref $_;} @_
l!l&&r!l&&!r
206
not $_fast or $_json_write or $_ts_on or $_after_write or $_cache_on
l!l&&r!l&&!r
206
not $_fast or $_json_write or $_ts_on or $_after_write
l!l&&r!l&&!r
206
not $_fast or $_json_write or $_ts_on
l!l&&r!l&&!r
116
not $_fast or $_json_write
l!l&&r!l&&!r
107
MC/DC33%2/6
not $_fast or $_json_write or $_ts_on or $_after_write or $_cache_on or grep {ref $_;} @_
not $_fast $_json_write $_ts_on $_after_write $_cache_on grep {ref $_;} @_
Truth table42%3/7
not(A) or B or C or D or E or F
A= not $_fastB= $_json_writeC= $_ts_onD= $_after_writeE= $_cache_onF= grep {ref $_;} @_
ABCDEFresult
1XXXXX1
01XXXX1
001XXX1
0001XX1
00001X1
0000011
0000000
790 2 my %row;
791 2 @row{@cols} = @_;
792 2 return $self->insert($table, \%row);
793 }
794 6 $sql = $stmt;
795 6 my $dbh = $_conn->dbh;
796 6 my $sth = $_sth_cache{$stmt};
797 6 ▶ if ($sth) { # inline _write_exec
Branch: 1 branch
BranchTrueFalseTotal
if ($sth) { } 3 3 6
798 3 $_write_dbh = $dbh;
799 3 Scalar::Util::weaken($_write_dbh);
800 3 $p = [@_];
801 3 ▶ my $rv = $sth->execute(@_)
Branch: 1 branch
BranchTrueFalseTotal
my $rv = $sth->execute(@_) or $self->_db_fail('execute() failed: ' . ($sth->errstr // "unknown"), $sth) 2 0 2
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
802 or $self->_db_fail("execute() failed: " . ($sth->errstr // 'unknown'), $sth);
803 2 $last_sql = $stmt;
804 2 ▶ $_affected_rows = $rv >= 0 ? $rv + 0 : _affected($sth, $rv);
Branch: 1 branch
BranchTrueFalseTotal
$rv >= 0 ? : 2 0 2
805 }
806 else {
807 3 $sth = $self->_write_exec(@_);
808 }
809 5 ▶ if ($ret) {
Branch: 4 branches
BranchTrueFalseTotal
if ($ret) { } 0 5 5
elsif ($dbd eq 'SQLite') { } 5 0 5
elsif ($dbd eq 'MariaDB') { } 0 0 0
elsif ($dbd eq 'mysql') { } 0 0 0
810 0 ▶ ($last_id) = $_affected_rows ? $sth->fetchrow_array : (undef);
Branch: 1 branch
BranchTrueFalseTotal
$_affected_rows ? : 0 0 0
811 0 $sth->finish;
812 }
813 5 elsif ($dbd eq 'SQLite') { $last_id = $_write_dbh->sqlite_last_insert_rowid() }
814 0 elsif ($dbd eq 'MariaDB') { $last_id = $_write_dbh->{mariadb_insertid} }
815 0 elsif ($dbd eq 'mysql') { $last_id = $_write_dbh->{mysql_insertid} }
816 0 else { $self->_update_last_id($table) }
817 5 return $last_id;
818 4 };
819 38 }
820  
821 12 ▶ method array (@args) {
Subroutine array: called CC=1 SCAR=0.0
Pod documented
822 12 $sql = shift @args;
823 12 $p = \@args;
824  
825 12 return $results = $self->_fetch(\&_shape_column);
826 38 }
827  
828 16 ▶ method query ($stmt, @params) {
Subroutine query: called CC=1 SCAR=0.0
Pod documented
829 16 $sql = $stmt;
830 16 $p = \@params;
831  
832 16 return DBIx::Fast::Result->new(sth => $self->_fetch(\&_shape_sth));
833 38 }
834  
835 # query() for big result sets: rows come from the server as they are read
836 # instead of being loaded into client memory first. MariaDB/MySQL fetch with
837 # use_result (the connection cannot run another statement until the
838 # iterator is drained or finished); SQLite streams natively; DBD::Pg always
839 # buffers (a server-side cursor would be needed), so there it behaves like
840 # query(). Not statement-cached: the handle carries the streaming attribute.
841 0 ▶ method stream ($stmt, @params) {
Subroutine stream: not called CC=12 SCAR=50.5
Pod documented
842 0 $sql = $stmt;
843 0 $p = \@params;
844 0 ▶ if ($p) { for (@$p) { if (ref $_ eq 'ARRAY') { $self->_expand_in_binds; last } } }
Branch: 2 branches
BranchTrueFalseTotal
if ($p) 0 0 0
if (ref $_ eq "ARRAY") 0 0 0
845  
846 0 my $dbd = $self->dbd;
847 0 ▶ my $attr = $dbd eq 'MariaDB' ? { mariadb_use_result => 1 }
Branch: 2 branches
BranchTrueFalseTotal
$dbd eq 'MariaDB' ? : 0 0 0
$dbd eq 'mysql' ? : 0 0 0
848 : $dbd eq 'mysql' ? { mysql_use_result => 1 }
849 : {};
850 0 my $dbh = $self->db->dbh;
851  
852 0 ▶ my $run = sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
853 0 my $sth = $dbh->prepare($sql, $attr);
854 0 ▶ unless ($sth) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 0 0 0
855 0 ▶ $self->_read_failed($dbh) if $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if $self->strict_reads 0 0 0
856 0 return undef;
857 }
858 0 ▶ my $rv = @$p ? $sth->execute(@$p) : $sth->execute;
Branch: 1 branch
BranchTrueFalseTotal
@$p ? : 0 0 0
859 0 ▶ $self->_read_failed($sth) unless $rv || !$self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
unless $rv or not $self->strict_reads 0 0 0
Condition0%0/3
$rv or not $self->strict_reads
l!l&&r!l&&!r
000
MC/DC0%0/2
$rv or not $self->strict_reads
$rv not $self->strict_reads
Truth table0%0/3
A or not(B)
A= $rvB= not $self->strict_reads
ABresult
1X1
011
000
860 0 return $sth;
861 0 };
862  
863 0 my $sth;
864 0 ▶ my $tracker = $_tracker && $_tracker->enabled ? $_tracker : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_tracker && $_tracker->enabled ? : 0 0 0
Condition0%0/3
$_tracker and $_tracker->enabled
!ll&&!rl&&r
000
MC/DC0%0/2
$_tracker and $_tracker->enabled
$_tracker $_tracker->enabled
Truth table0%0/3
A and B
A= $_trackerB= $_tracker->enabled
ABresult
0X0
100
111
865 0 ▶ if ($tracker || $_observe) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tracker or $_observe) { } 0 0 0
Condition0%0/3
$tracker or $_observe
l!l&&r!l&&!r
000
MC/DC0%0/2
$tracker or $_observe
$tracker $_observe
Truth table0%0/3
A or B
A= $trackerB= $_observe
ABresult
1X1
011
000
866 0 my $t0 = Time::HiRes::time();
867 0 $sth = $run->();
868 0 my $t1 = Time::HiRes::time();
869 0 ▶ $tracker->add_query($sql, $p, $t0, $t1) if $tracker;
Branch: 1 branch
BranchTrueFalseTotal
if $tracker 0 0 0
870 0 ▶ $self->_observed($t1 - $t0) if $_observe;
Branch: 1 branch
BranchTrueFalseTotal
if $_observe 0 0 0
871 }
872 else {
873 0 $sth = $run->();
874 }
875 0 $last_sql = $sql;
876 0 return DBIx::Fast::Result->new(sth => $sth);
877 38 }
878  
879 37 ▶ method count ($table_name, $skeel = undef) {
Subroutine count: called CC=4 SCAR=13.9
Pod documented
880 37 my $table = $self->TableName($table_name);
881 35 my $qtable = $self->_quote_ident_path($table);
882  
883 35 $sql = "SELECT COUNT(*) FROM $qtable";
884 35 $p = [];
885  
886 35 ▶ if ($skeel) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skeel) 24 11 35
887 24 my ($parts, $params) = $self->_where_parts($skeel);
888 17 ▶ $sql .= ' WHERE ' . join(' AND ', @$parts) if @$parts;
Branch: 1 branch
BranchTrueFalseTotal
if @$parts 17 0 17
889 17 $p = $params;
890 }
891  
892 28 return $results = $self->_fetch(\&_shape_val);
893 38 }
894  
895 # { value => rows } of $table grouped by $column: one GROUP BY instead of a
896 # count() per value. Same WHERE as count(); rows where $column IS NULL are
897 # left out (a hash key cannot be NULL - count($table, { $column => undef })
898 # counts them).
899 6 ▶ method count_by ($table_name, $column, $skeel = undef) {
Subroutine count_by: called CC=5 SCAR=16.1
Pod documented
900 6 my $qtable = $self->_quote_ident_path($self->TableName($table_name));
901 6 ▶ $self->Exception("count_by: column required") unless defined $column && length $column;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $column and length $column 1 5 6
Condition66%2/3
defined $column and length $column
!ll&&!rl&&r
015
MC/DC50%1/2
defined $column and length $column
defined $column length $column
Truth table66%2/3
A and B
A= defined $columnB= length $column
ABresult
0X0
100
111
902 5 my $qcol = $self->_quote_ident_path($column);
903  
904 4 $sql = "SELECT $qcol, COUNT(*) FROM $qtable";
905 4 $p = [];
906 4 my @parts = ("$qcol IS NOT NULL");
907 4 ▶ if ($skeel) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skeel) 3 1 4
908 3 my ($where, $params) = $self->_where_parts($skeel);
909 2 push @parts, @$where;
910 2 $p = $params;
911 }
912 3 $sql .= ' WHERE ' . join(' AND ', @parts) . " GROUP BY $qcol";
913  
914 3 return $results = $self->_fetch(\&_shape_kv);
915 38 }
916  
917 # 1 if at least one row of $table matches the count()-style WHERE, else 0.
918 # Same validation as count() (TableName + _make_where whitelist); LIMIT 1
919 # lets the server stop at the first match.
920 5 ▶ method exists ($table_name, $skeel = undef) {
Subroutine exists: called CC=4 SCAR=13.9
Pod documented
921 5 my $table = $self->TableName($table_name);
922 5 my $qtable = $self->_quote_ident_path($table);
923  
924 5 $sql = "SELECT 1 FROM $qtable";
925 5 $p = [];
926  
927 5 ▶ if ($skeel) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skeel) 4 1 5
928 4 my ($parts, $params) = $self->_where_parts($skeel);
929 3 ▶ $sql .= ' WHERE ' . join(' AND ', @$parts) if @$parts;
Branch: 1 branch
BranchTrueFalseTotal
if @$parts 3 0 3
930 3 $p = $params;
931 }
932 4 $sql .= ' LIMIT 1';
933  
934 4 return $results = $self->_fetch(\&_shape_exists);
935 38 }
936  
937 # First column => second column, as a hashref (a later duplicate key wins).
938 9 ▶ method kv (@args) {
Subroutine kv: called CC=1 SCAR=0.0
Pod documented
939 9 $sql = shift @args;
940 9 $p = \@args;
941  
942 9 return $results = $self->_fetch(\&_shape_kv);
943 38 }
944  
945 # Rows keyed by the $key column, as a hashref of hashrefs (DBI's
946 # fetchall_hashref: a later row with the same key wins).
947 2 ▶ method all_by ($key, @args) {
Subroutine all_by: called CC=3 SCAR=11.4
Pod documented
948 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
949 unless defined $key && length $key;
950  
951 2 $sql = shift @args;
952 2 $p = \@args;
953  
954 2 ▶ $results = $self->_track(sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
955 2 ▶ my $sth = $self->_read_exec or return {};
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->_read_exec or return {} 1 0 1
956 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
957 2 });
958 1 return $results;
959 38 }
960  
961 2 ▶ method _make_where ($skeel) {
Subroutine _make_where: called CC=2 SCAR=7.0
962 2 my ($parts, $params) = $self->_where_parts($skeel);
963 2 ▶ $sql .= ' WHERE ' . join(' AND ', @$parts) if @$parts;
Branch: 1 branch
BranchTrueFalseTotal
if @$parts 2 0 2
964 2 $p = $params;
965 38 }
966  
967 # The count()/exists()/where() condition builder: ($parts, $binds) for a
968 # { column => condition } hashref, without touching the statement state.
969 # Operators are whitelisted; columns validated and quoted per segment.
970 66 ▶ method _where_parts ($skeel) {
Subroutine _where_parts: called CC=25 SCAR=35.2
971 66 state %VALID_OPS = map { $_ => 1 }
972 ('=', '!=', '<>', '<', '<=', '>', '>=', 'LIKE', 'NOT', 'BETWEEN', 'IS',
973 'IN', 'NOT IN', 'CONTAINS', 'PREFIX', 'SUFFIX');
974 66 state %LIKE_MODE = (CONTAINS => 'contains', PREFIX => 'prefix',
975 SUFFIX => 'suffix');
976  
977 66 my @params;
978 my @parts;
979  
980 66 for my $K (sort keys %{$skeel}) {
981 # Validate AND quote the column by segment, so a qualified name like
982 # "t.col" becomes "t"."col" (not the bogus single identifier "t.col").
983 71 my $col = $self->_quote_ident_path($K);
984  
985 69 my $val = $skeel->{$K};
986  
987 # Fast path for the common case: col => defined plain value.
988 69 ▶ if (defined $val && !ref $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val and not ref $val) 37 32 69
Condition100%3/3
defined $val and not ref $val
!ll&&!rl&&r
13137
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
989 37 push @parts, "$col = ?";
990 37 push @params, $val;
991 37 next;
992 }
993  
994 32 ▶ my $op = ref $val eq 'ARRAY' ? 'IN' : '='; # [ ... ] means IN (...)
Branch: 1 branch
BranchTrueFalseTotal
ref $val eq 'ARRAY' ? : 2 30 32
995  
996 32 ▶ if (ref $val eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq "HASH") 29 3 32
997 29 ▶ $self->Exception("Multiple operators for column $K")
Branch: 1 branch
BranchTrueFalseTotal
if keys %$val > 1 0 29 29
998 if keys %$val > 1;
999 29 ($op) = keys %$val;
1000 $self->Exception("Invalid operator: $op")
1001 29 ▶ unless $VALID_OPS{uc $op};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_OPS{uc $op} 7 22 29
1002 22 $val = $val->{$op};
1003 22 $op = uc $op;
1004 }
1005  
1006 25 ▶ if ($op eq 'IN' || $op eq 'NOT IN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IN" or $op eq "NOT IN") 5 20 25
Condition100%3/3
$op eq "IN" or $op eq "NOT IN"
l!l&&r!l&&!r
4120
MC/DC100%2/2
$op eq "IN" or $op eq "NOT IN"
$op eq "IN" $op eq "NOT IN"
Truth table100%3/3
A or B
A= $op eq "IN"B= $op eq "NOT IN"
ABresult
1X1
011
000
1007 5 ▶ $self->Exception("$op requires an arrayref of values")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val eq "ARRAY" 1 4 5
1008 unless ref $val eq 'ARRAY';
1009 4 ▶ $self->Exception("$op with an empty list for column $K")
Branch: 1 branch
BranchTrueFalseTotal
unless @$val 1 3 4
1010 unless @$val;
1011 3 push @parts, "$col $op (" . join(', ', ('?') x @$val) . ')';
1012 3 push @params, @$val;
1013 3 next;
1014 }
1015  
1016 20 ▶ if (my $mode = $LIKE_MODE{$op}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $mode = $LIKE_MODE{$op}) 6 14 20
1017 # Escaped user text, never a pattern: see like().
1018 6 ▶ $self->Exception("$op requires a value") unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 6 6
1019 6 push @parts, "$col LIKE ? ESCAPE '!'";
1020 6 push @params, $self->like($val, $mode);
1021 6 next;
1022 }
1023  
1024 14 ▶ if ($op eq 'BETWEEN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "BETWEEN") 0 14 14
1025 0 ▶ $self->Exception("BETWEEN requires a two-element arrayref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val eq "ARRAY" and @$val == 2 0 0 0
Condition0%0/3
ref $val eq "ARRAY" and @$val == 2
!ll&&!rl&&r
000
MC/DC0%0/2
ref $val eq "ARRAY" and @$val == 2
ref $val eq "ARRAY" @$val == 2
Truth table0%0/3
A and B
A= ref $val eq "ARRAY"B= @$val == 2
ABresult
0X0
100
111
1026 unless ref $val eq 'ARRAY' && @$val == 2;
1027 0 push @parts, "$col BETWEEN ? AND ?";
1028 0 push @params, @$val;
1029 0 next;
1030 }
1031  
1032 14 ▶ if ($op eq 'IS') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IS") 1 13 14
1033 1 ▶ $self->Exception("IS only accepts undef (IS NULL); "
Branch: 1 branch
BranchTrueFalseTotal
if defined $val 0 1 1
1034 . "use { '!=' => undef } for IS NOT NULL")
1035 if defined $val;
1036 1 push @parts, "$col IS NULL";
1037 1 next;
1038 }
1039  
1040 # An undef operand collapses to NULL semantics: "col = NULL" / "col != NULL"
1041 # are never true in SQL, so emit IS [NOT] NULL with no bind value.
1042 13 ▶ if (!defined $val) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $val) 1 12 13
1043 1 ▶ if ($op eq '=') {
Branch: 2 branches
BranchTrueFalseTotal
if ($op eq '=') { } 1 0 1
elsif ($op eq '!=' or $op eq '<>' or $op eq 'NOT') { } 0 0 0
1044 1 push @parts, "$col IS NULL";
1045 }
1046 ▶ elsif ($op eq '!=' || $op eq '<>' || $op eq 'NOT') {
Condition0%0/6
$op eq "!=" or $op eq "<>" or $op eq "NOT"
l!l&&r!l&&!r
000
$op eq "!=" or $op eq "<>"
l!l&&r!l&&!r
000
MC/DC0%0/3
$op eq "!=" or $op eq "<>" or $op eq "NOT"
$op eq "!=" $op eq "<>" $op eq "NOT"
Truth table0%0/4
A or B or C
A= $op eq "!="B= $op eq "<>"C= $op eq "NOT"
ABCresult
1XX1
01X1
0011
0000
1047 0 push @parts, "$col IS NOT NULL";
1048 }
1049 else {
1050 0 $self->Exception("Operator '$op' does not accept an undef value");
1051 }
1052 1 next;
1053 }
1054  
1055 # NOT on its own maps to <> for portability.
1056 12 ▶ my $sql_op = $op eq 'NOT' ? '<>' : $op;
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'NOT' ? : 0 12 12
1057 12 push @parts, "$col $sql_op ?";
1058 12 push @params, $val;
1059 }
1060  
1061 55 return (\@parts, \@params);
1062 38 }
1063  
1064 # ('WHERE ...', @binds) for a { column => condition } filter, ready to
1065 # append to hand-written SQL. Filters whose value is undef are SKIPPED (an
1066 # absent form field means "do not filter"); ask for NULL explicitly with
1067 # { col => { IS => undef } }. Same operators as count(), plus IN/NOT IN
1068 # (an arrayref value is IN) and CONTAINS/PREFIX/SUFFIX (escaped LIKE).
1069 # Returns ('') with no binds when nothing is left to filter on.
1070 12 ▶ method where ($filters = {}) {
Subroutine where: called CC=4 SCAR=13.9
Pod documented
1071 12 ▶ $self->Exception("where: filters must be a hashref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $filters eq "HASH" 0 12 12
1072 unless ref $filters eq 'HASH';
1073 13 my %active = map { $_ => $filters->{$_} }
1074 12 grep { defined $filters->{$_} } keys %$filters;
1075 12 my ($parts, $params) = $self->_where_parts(\%active);
1076 10 ▶ return ('') unless @$parts;
Branch: 1 branch
BranchTrueFalseTotal
unless @$parts 1 9 10
1077 9 return ('WHERE ' . join(' AND ', @$parts), @$params);
1078 38 }
1079  
1080 # A LIKE pattern from user text: %, _ and the escape character itself are
1081 # escaped with '!', so the text matches literally. Use it as
1082 # "col LIKE ? ESCAPE '!'" - '!' (unlike backslash) needs no special
1083 # handling in SQLite, MariaDB/MySQL or PostgreSQL.
1084 11 ▶ method like ($value, $mode = 'contains') {
Subroutine like: called CC=7 SCAR=19.5
Pod documented
1085 11 state %OK = map { $_ => 1 } qw(contains prefix suffix exact);
1086 $self->Exception("like: mode must be contains, prefix, suffix or exact")
1087 11 ▶ unless $OK{$mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $OK{$mode} 1 10 11
1088 10 ▶ (my $v = $value // '') =~ s/([!%_])/!$1/g;
Condition50%1/2
$value // ""
l!l
100
MC/DC0%0/1
$value // ""
$value
Truth table50%1/2
A
A= $value
Aresult
11
00
1089 10 ▶ return $mode eq 'prefix' ? "$v%"
Branch: 3 branches
BranchTrueFalseTotal
$mode eq 'prefix' ? : 3 7 10
$mode eq 'suffix' ? : 2 5 7
$mode eq 'exact' ? : 0 5 5
1090 : $mode eq 'suffix' ? "%$v"
1091 : $mode eq 'exact' ? $v
1092 : "%$v%";
1093 38 }
1094  
1095 # Run $code once per slice of at most $size elements of @$list (each slice
1096 # an arrayref, e.g. for "... IN (?)"), returning the callbacks' results in
1097 # order. For lists too long for one statement (max_allowed_packet, bind
1098 # limits).
1099 4 ▶ method in_chunks ($list, $size, $code) {
Subroutine in_chunks: called CC=7 SCAR=19.6
Pod documented
1100 4 ▶ $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" 1 3 4
Condition55%5/9
ref $list eq "ARRAY" and defined $size and $size =~ /\A[1-9]\d*\z/u and ref $code eq "CODE"
!ll&&!rl&&r
103
ref $list eq "ARRAY" and defined $size and $size =~ /\A[1-9]\d*\z/u
!ll&&!rl&&r
013
ref $list eq "ARRAY" and defined $size
!ll&&!rl&&r
004
MC/DC25%1/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 table40%2/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
1101 unless ref $list eq 'ARRAY' && defined $size && $size =~ /\A[1-9]\d*\z/
1102 && ref $code eq 'CODE';
1103 3 my @out;
1104 3 ▶ for (my $i = 0; $i < @$list; $i += $size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$list) 7 3 10
1105 7 my $end = $i + $size - 1;
1106 7 ▶ $end = $#$list if $end > $#$list;
Branch: 1 branch
BranchTrueFalseTotal
if $end > $list->$#* 2 5 7
1107 7 push @out, $code->([ @{$list}[ $i .. $end ] ]);
1108 }
1109 3 return @out;
1110 38 }
1111  
1112 # One page of $stmt: { rows, total, page, per, pages }. total comes from
1113 # COUNT(*) over the statement (count => 'window': COUNT(*) OVER () in the
1114 # page query itself, one pass instead of two); ORDER BY only accepts columns listed in
1115 # allowed_order ("col", "col DESC" or "-col"), quoted; LIMIT/OFFSET are
1116 # validated integers (not binds - client-side prepares would quote them).
1117 # $stmt must not carry its own ORDER BY / LIMIT when these are used.
1118 25 ▶ method page ($stmt, $binds = [], %o) {
Subroutine page: called CC=32 SCAR=34.8
Pod documented
1119 25 ▶ $self->Exception("page: binds must be an arrayref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $binds eq "ARRAY" 0 25 25
1120 unless ref $binds eq 'ARRAY';
1121 25 ▶ my $max_per = $o{max_per} // 1000;
Condition50%1/2
$o{"max_per"} // 1000
l!l
025
MC/DC0%0/1
$o{"max_per"} // 1000
$o{"max_per"}
Truth table50%1/2
A
A= $o{"max_per"}
Aresult
11
00
1122 25 ▶ my $page = $o{page} // 1;
Condition100%2/2
$o{"page"} // 1
l!l
1411
MC/DC100%1/1
$o{"page"} // 1
$o{"page"}
Truth table100%2/2
A
A= $o{"page"}
Aresult
11
00
1123 25 ▶ my $per = $o{per} // 20;
Condition100%2/2
$o{"per"} // 20
l!l
187
MC/DC100%1/1
$o{"per"} // 20
$o{"per"}
Truth table100%2/2
A
A= $o{"per"}
Aresult
11
00
1124 25 for ([ page => $page ], [ per => $per ]) {
1125 49 ▶ $self->Exception("page: $_->[0] must be a positive integer")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_->[1] and $_->[1] =~ /\A[1-9]\d*\z/u 2 47 49
Condition66%2/3
defined $_->[1] and $_->[1] =~ /\A[1-9]\d*\z/u
!ll&&!rl&&r
0247
MC/DC50%1/2
defined $_->[1] and $_->[1] =~ /\A[1-9]\d*\z/u
defined $_->[1] $_->[1] =~ /\A[1-9]\d*\z/u
Truth table66%2/3
A and B
A= defined $_->[1]B= $_->[1] =~ /\A[1-9]\d*\z/u
ABresult
0X0
100
111
1126 unless defined $_->[1] && $_->[1] =~ /\A[1-9]\d*\z/;
1127 }
1128 23 ▶ $self->Exception("page: per exceeds max_per ($max_per)") if $per > $max_per;
Branch: 1 branch
BranchTrueFalseTotal
if $per > $max_per 1 22 23
1129 22 ▶ my $count = $o{count} // 'query';
Condition100%2/2
$o{"count"} // "query"
l!l
1012
MC/DC100%1/1
$o{"count"} // "query"
$o{"count"}
Truth table100%2/2
A
A= $o{"count"}
Aresult
11
00
1130 22 ▶ $self->Exception("page: count must be 'query' or 'window'")
Branch: 1 branch
BranchTrueFalseTotal
unless $count eq "query" or $count eq "window" 1 21 22
Condition100%3/3
$count eq "query" or $count eq "window"
l!l&&r!l&&!r
1291
MC/DC100%2/2
$count eq "query" or $count eq "window"
$count eq "query" $count eq "window"
Truth table100%3/3
A or B
A= $count eq "query"B= $count eq "window"
ABresult
1X1
011
000
1131 unless $count eq 'query' || $count eq 'window';
1132  
1133 21 my $order = '';
1134 21 ▶ if (defined $o{order} && length $o{order}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $o{"order"} and length $o{"order"}) 17 4 21
Condition66%2/3
defined $o{"order"} and length $o{"order"}
!ll&&!rl&&r
4017
MC/DC50%1/2
defined $o{"order"} and length $o{"order"}
defined $o{"order"} length $o{"order"}
Truth table66%2/3
A and B
A= defined $o{"order"}B= length $o{"order"}
ABresult
0X0
100
111
1135 17 ▶ my %allowed = map { $_ => 1 } @{ $o{allowed_order} // [] };
Condition50%1/2
$o{"allowed_order"} // []
l!l
170
MC/DC0%0/1
$o{"allowed_order"} // []
$o{"allowed_order"}
Truth table50%1/2
A
A= $o{"allowed_order"}
Aresult
11
00
1136 17 my @terms;
1137 17 ▶ for my $term (ref $o{order} eq 'ARRAY' ? @{ $o{order} } : $o{order}) {
Branch: 1 branch
BranchTrueFalseTotal
ref $o{'order'} eq 'ARRAY' ? : 1 16 17
1138 18 ▶ 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") 17 1 18
1139 $term =~ /\A\s*(-)?([A-Za-z_][\w.]*)(?:\s+(ASC|DESC))?\s*\z/i
1140 or $self->Exception("page: invalid order term");
1141 # window wraps the statement: only its output columns are in scope.
1142 17 ▶ $self->Exception("page: count => 'window' orders by output columns ('$col' has a table prefix)")
Branch: 1 branch
BranchTrueFalseTotal
if $count eq "window" and $col =~ /\./u 1 16 17
Condition100%3/3
$count eq "window" and $col =~ /\./u
!ll&&!rl&&r
1061
MC/DC100%2/2
$count eq "window" and $col =~ /\./u
$count eq "window" $col =~ /\./u
Truth table100%3/3
A and B
A= $count eq "window"B= $col =~ /\./u
ABresult
0X0
100
111
1143 if $count eq 'window' && $col =~ /\./;
1144 $self->Exception("page: ordering by '$col' is not allowed")
1145 16 ▶ unless $allowed{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $allowed{$col} 1 15 16
1146 15 ▶ $dir = $minus ? 'DESC' : uc($dir // 'ASC');
Branch: 1 branch
BranchTrueFalseTotal
$minus ? : 12 3 15
Condition100%2/2
$dir // "ASC"
l!l
12
MC/DC100%1/1
$dir // "ASC"
$dir
Truth table100%2/2
A
A= $dir
Aresult
11
00
1147 15 push @terms, $self->_quote_ident_path($col) . " $dir";
1148 }
1149 14 $order = ' ORDER BY ' . join(', ', @terms);
1150 }
1151  
1152 18 my $offset = ($page - 1) * $per;
1153 18 my ($total, $rows);
1154 18 ▶ if ($count eq 'window') {
Branch: 1 branch
BranchTrueFalseTotal
if ($count eq "window") 8 10 18
1155 # One pass: the total rides on every row (COUNT(*) OVER () is computed
1156 # before LIMIT). A page past the end has no row to carry it: count.
1157 8 $rows = $self->all("SELECT dbix_fast_page.*, COUNT(*) OVER () AS dbix_fast_total"
1158 . " FROM ($stmt) dbix_fast_page$order LIMIT $per OFFSET $offset", @$binds);
1159 8 ▶ $total = @$rows ? $rows->[0]{dbix_fast_total} : $page == 1 ? 0 : undef;
Branch: 2 branches
BranchTrueFalseTotal
@$rows ? : 5 3 8
$page == 1 ? : 1 2 3
1160 8 delete $_->{dbix_fast_total} for @$rows;
1161 }
1162 18 ▶ $total //= $self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds) // 0;
Condition75%3/4
$total //= $self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds) // 0
l!l
612
$self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds) // 0
l!l
120
MC/DC100%1/1
$total //= $self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds) // 0
$total
Truth table100%2/2
A
A= $total
Aresult
11
00
1163 18 ▶ $rows //= $self->all("$stmt$order LIMIT $per OFFSET $offset", @$binds);
Condition66%2/3
$rows //= $self->all("$stmt$order LIMIT $per OFFSET $offset", @$binds)
l!l&&r!l&&!r
8100
MC/DC0%0/2
$rows //= $self->all("$stmt$order LIMIT $per OFFSET $offset", @$binds)
$rows $self->all("$stmt$order LIMIT $per OFFSET $offset", @$binds)
Truth table66%2/3
A //= B
A= $rowsB= $self->all("$stmt$order LIMIT $per OFFSET $offset", @$binds)
ABresult
1X1
011
000
1164  
1165 return {
1166 18 ▶ rows => $rows,
Branch: 1 branch
BranchTrueFalseTotal
$total ? : 17 1 18
1167 total => $total + 0,
1168 page => $page + 0,
1169 per => $per + 0,
1170 pages => $total ? int(($total + $per - 1) / $per) : 0,
1171 };
1172 38 }
1173  
1174 216 ▶ method exec ($stmt, @params) {
Subroutine exec: called CC=5 SCAR=16.3
Pod documented
1175 216 ▶ $self->Exception("exec() : SQL statement required") unless $stmt;
Branch: 1 branch
BranchTrueFalseTotal
unless $stmt 0 216 216
1176  
1177 216 $sql = $stmt;
1178 216 $p = \@params;
1179 216 ▶ for (@params) { if (ref $_ eq 'ARRAY') { $self->_expand_in_binds; last } }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_ eq "ARRAY") 1 41 42
1180 216 my @binds = @$p;
1181  
1182 216 my $sth = $self->_prepare_live($_conn->dbh, $sql);
1183  
1184 214 my $rv;
1185 214 ▶ $self->_track(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1186 214 ▶ $rv = @binds ? $sth->execute(@binds) : $sth->execute();
Branch: 1 branch
BranchTrueFalseTotal
@binds ? : 24 190 214
1187 214 1;
1188 214 });
1189  
1190 214 ▶ if ($DBI::err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DBI::err) 0 214 214
1191 0 $self->set_error($DBI::err, $DBI::errstr);
1192 0 $_affected_rows = undef;
1193 0 return;
1194 }
1195  
1196 214 $_affected_rows = _affected($sth, $rv);
1197 214 return $sth;
1198 38 }
1199  
1200 9 ▶ method execute ($stmt, $extra = undef, $type = 'arrayref') {
Subroutine execute: called CC=5 SCAR=16.1
Pod documented
1201 9 $sql = $stmt;
1202  
1203 # make_sen sets $p from $extra; without $extra there are no binds, so clear
1204 # any $p left over from a previous query (else it is bound to this
1205 # statement - a stray-value or arity-mismatch failure).
1206 9 ▶ if ($extra) { $self->make_sen($extra) }
Branch: 1 branch
BranchTrueFalseTotal
if ($extra) { } 6 3 9
1207 3 else { $p = undef }
1208  
1209 9 ▶ $results = $self->_fetch($type eq 'hash' ? \&_shape_hash : \&_shape_rows);
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'hash' ? : 0 9 9
1210 38 }
1211  
1212  
1213 # A copy of $row with the table's timestamp columns added where the row does
1214 # not set them already: $which 'insert' fills created + updated, 'update'
1215 # only updated. The caller's hash is never modified. Returns $row itself
1216 # when no timestamps apply.
1217 28 ▶ method _stamp ($table, $row, $which) {
Subroutine _stamp: called CC=7 SCAR=19.5
1218 28 ▶ my ($created, $updated, $value) = $self->_timestamps_for($table) or return $row;
Branch: 1 branch
BranchTrueFalseTotal
() = $self->_timestamps_for($table) or return $row 26 2 28
1219 26 my %r = %$row;
1220 26 ▶ $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} 20 6 26
Condition100%6/6
$which eq "insert" and $created and not exists $r{$created}
!ll&&!rl&&r
4220
$which eq "insert" and $created
!ll&&!rl&&r
2222
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
1221 26 ▶ $r{$updated} = $value if $updated && !exists $r{$updated};
Branch: 1 branch
BranchTrueFalseTotal
if $updated and not exists $r{$updated} 18 8 26
Condition100%3/3
$updated and not exists $r{$updated}
!ll&&!rl&&r
6218
MC/DC100%2/2
$updated and not exists $r{$updated}
$updated not exists $r{$updated}
Truth table100%3/3
A and not(B)
A= $updatedB= not exists $r{$updated}
ABresult
0X0
100
111
1222 26 return \%r;
1223 38 }
1224  
1225 # Placeholder for one value of a bound INSERT: a scalarref (only ever the
1226 # server-side timestamp from _stamp, after user values were validated) is
1227 # inlined as SQL, anything else is a ?.
1228 161 ▶ 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 155 161
1229  
1230 # CRUD
1231 331 ▶ method insert ($table_name, $skeel, @extra) {
Subroutine insert: called CC=23 SCAR=31.4
Pod documented
1232 331 my $table = $self->TableName($table_name);
1233  
1234 322 ▶ $skeel = $self->extra_args($skeel, @extra) if @extra;
Branch: 1 branch
BranchTrueFalseTotal
if @extra 7 315 322
1235 321 ▶ $skeel = $self->_json_encode_row($table, $skeel) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 23 298 321
1236  
1237 # '' except on Pg (driver test inline: no method call on the others)
1238 321 ▶ my $dbd = $_dbd_c //= $self->dbd;
Condition66%2/3
$_dbd_c //= $self->dbd
l!l&&r!l&&!r
259620
MC/DC0%0/2
$_dbd_c //= $self->dbd
$_dbd_c $self->dbd
Truth table66%2/3
A //= B
A= $_dbd_cB= $self->dbd
ABresult
1X1
011
000
1239 321 ▶ my $ret = $dbd eq 'Pg' ? $self->_pg_returning($table) : '';
Branch: 1 branch
BranchTrueFalseTotal
$dbd eq 'Pg' ? : 5 316 321
1240 321 my $sth;
1241  
1242 # A column set already in the CRUD cache was validated when its SQL was
1243 # built: with plain values (no refs) the per-column checks are skipped.
1244 # The key joins the names with "\0", so a name holding a NUL could
1245 # collide with a valid set ("a\0b" ~ a, b): never take the shortcut then.
1246 321 my (@cols, $hit);
1247 321 ▶ if (!$_ts_on && ref $skeel eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $_ts_on and ref $skeel eq "HASH") 307 14 321
Condition66%2/3
not $_ts_on and ref $skeel eq "HASH"
!ll&&!rl&&r
140307
MC/DC50%1/2
not $_ts_on and ref $skeel eq "HASH"
not $_ts_on ref $skeel eq "HASH"
Truth table66%2/3
not(A) and B
A= not $_ts_onB= ref $skeel eq "HASH"
ABresult
0X0
100
111
1248 307 @cols = sort keys %$skeel;
1249 307 ▶ $hit = @cols && $_crud_sql{ join("\0", 'I', $table, @cols) };
Condition66%2/3
@cols && $_crud_sql{join "\000", 'I', $table, @cols}
!ll&&!rl&&r
0143164
MC/DC50%1/2
@cols && $_crud_sql{join "\000", 'I', $table, @cols}
@cols $_crud_sql{join "\000", 'I', $table, @cols}
Truth table66%2/3
A && B
A= @colsB= $_crud_sql{join "\000", 'I', $table, @cols}
ABresult
0X0
100
111
1250 307 ▶ undef $hit if $hit && (grep({ ref } @{$skeel}{@cols}) || grep({ index($_, "\0") >= 0 } @cols));
Branch: 1 branch
BranchTrueFalseTotal
if $hit and grep({ref $_;} @{$skeel;}{@cols}) || grep({index($_, "\0") != -1;} @cols) 5 302 307
Condition100%6/6
$hit and grep({ref $_;} @{$skeel;}{@cols}) || grep({index($_, "\0") != -1;} @cols)
!ll&&!rl&&r
1431595
grep {ref $_;} @{$skeel;}{@cols} or grep {index($_, "\0") != -1;} @cols
l!l&&r!l&&!r
41159
MC/DC100%3/3
$hit and grep({ref $_;} @{$skeel;}{@cols}) || grep({index($_, "\0") != -1;} @cols)
$hit grep {ref $_;} @{$skeel;}{@cols} grep {index($_, "\0") != -1;} @cols
Truth table100%4/4
A and B or C
A= $hitB= grep {ref $_;} @{$skeel;}{@cols}C= grep {index($_, "\0") != -1;} @cols
ABCresult
0XX0
1000
11X1
1011
1251 }
1252 321 ▶ if ($hit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hit) { } 159 162 321
1253 159 $sql = $hit;
1254 159 $sth = $self->_write_exec(@{$skeel}{@cols});
1255 }
1256 else {
1257 162 $self->_safe_data($skeel);
1258 136 ▶ $skeel = $self->_stamp($table, $skeel, 'insert') if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 14 122 136
1259 136 @cols = sort keys %$skeel;
1260 136 ▶ if (@cols && !grep { ref } @{$skeel}{@cols}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cols and not grep({ref $_;} @{$skeel;}{@cols})) { } 134 2 136
Condition66%2/3
@cols and not grep({ref $_;} @{$skeel;}{@cols})
!ll&&!rl&&r
02134
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
1261 134 my $ck = join("\0", 'I', $table, @cols);
1262 $sql = $_crud_sql{$ck} // $self->_crud_stmt($ck,
1263 134 ▶ sub { ($self->Q->insert($table, $skeel))[0] . $ret });
Subroutine __ANON__: called CC=1 SCAR=0.1
Condition66%2/3
$_crud_sql{$ck} // $self->_crud_stmt($ck, sub { ($self->Q->insert($table, $skeel))[0] . $ret; } )
l!l&&r!l&&!r
51290
MC/DC0%0/2
$_crud_sql{$ck} // $self->_crud_stmt($ck, sub { ($self->Q->insert($table, $skeel))[0] . $ret; } )
$_crud_sql{$ck} $self->_crud_stmt($ck, sub { ($self->Q->insert($table, $skeel))[0] . $ret; } )
Truth table66%2/3
A // B
A= $_crud_sql{$ck}B= $self->_crud_stmt($ck, sub { ($self->Q->insert($table, $skeel))[0] . $ret; } )
ABresult
1X1
011
000
1264 134 $sth = $self->_write_exec(@{$skeel}{@cols});
1265 }
1266 else {
1267 2 my ($stmt, @bind) = $self->Q->insert($table, $skeel);
1268 2 $sql = $stmt . $ret;
1269 2 $sth = $self->_write_exec(@bind);
1270 }
1271 }
1272  
1273 294 ▶ if ($ret) {
Branch: 4 branches
BranchTrueFalseTotal
if ($ret) { } 1 293 294
elsif ($dbd eq 'SQLite') { } 284 9 293
elsif ($dbd eq 'MariaDB') { } 4 5 9
elsif ($dbd eq 'mysql') { } 1 4 5
1274 1 ▶ ($last_id) = $_affected_rows ? $sth->fetchrow_array : (undef);
Branch: 1 branch
BranchTrueFalseTotal
$_affected_rows ? : 1 0 1
1275 1 $sth->finish;
1276 }
1277 # Inline for the drivers that read it from the handle (no method call).
1278 284 elsif ($dbd eq 'SQLite') { $last_id = $_write_dbh->sqlite_last_insert_rowid() }
1279 4 elsif ($dbd eq 'MariaDB') { $last_id = $_write_dbh->{mariadb_insertid} }
1280 1 elsif ($dbd eq 'mysql') { $last_id = $_write_dbh->{mysql_insertid} }
1281 else {
1282 4 $self->_update_last_id($table);
1283 }
1284 294 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 5 289 294
1285 294 ▶ $self->_fire_after_write(op => 'insert', table => $table, data => $skeel) if $_after_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write 7 287 294
1286 294 return $last_id;
1287 38 }
1288  
1289 # ' RETURNING "pk"' for a Pg insert into $table, or '' (no single-column
1290 # primary key, not Pg, or the lookup failed: last_insert_id as before).
1291 # to_regclass() yields NULL instead of an error, so a failed lookup can
1292 # never abort the caller's transaction.
1293 5 ▶ method _pg_returning ($table) {
Subroutine _pg_returning: called CC=7 SCAR=19.6
1294 5 ▶ return '' unless ($_dbd_c //= $self->dbd) eq 'Pg';
Branch: 1 branch
BranchTrueFalseTotal
unless ($_dbd_c //= $self->dbd) eq "Pg" 0 5 5
Condition33%1/3
$_dbd_c //= $self->dbd
l!l&&r!l&&!r
500
MC/DC0%0/2
$_dbd_c //= $self->dbd
$_dbd_c $self->dbd
Truth table33%1/3
A //= B
A= $_dbd_cB= $self->dbd
ABresult
1X1
011
000
1295 5 ▶ my $pk = $_pg_pk{$table} //= do {
Condition66%2/3
$_pg_pk{$table} //= do { my $dbh = $self->db->dbh; my $cols = eval { do { local $dbh->{"HandleError"}; local $dbh->{"RaiseError"} = 1; local $dbh->{"PrintError"} = 0; $dbh->selectcol_arrayref("SELECT a.attname FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid\n AND a.attnum = ANY (i.indkey)\n WHERE i.indrelid = to_regclass(?) AND i.indisprimary", undef, $self->_quote_ident_path($table)) } }; _trim_cache(\%_pg_pk, 1000); $cols && @$cols == 1 ? $cols->[0] : "" }
l!l&&r!l&&!r
140
MC/DC0%0/2
$_pg_pk{$table} //= do { my $dbh = $self->db->dbh; my $cols = eval { do { local $dbh->{"HandleError"}; local $dbh->{"RaiseError"} = 1; local $dbh->{"PrintError"} = 0; $dbh->selectcol_arrayref("SELECT a.attname FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid\n AND a.attnum = ANY (i.indkey)\n WHERE i.indrelid = to_regclass(?) AND i.indisprimary", undef, $self->_quote_ident_path($table)) } }; _trim_cache(\%_pg_pk, 1000); $cols && @$cols == 1 ? $cols->[0] : "" }
$_pg_pk{$table} do { my $dbh = $self->db->dbh; my $cols = eval { do { local $dbh->{"HandleError"}; local $dbh->{"RaiseError"} = 1; local $dbh->{"PrintError"} = 0; $dbh->selectcol_arrayref("SELECT a.attname FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid\n AND a.attnum = ANY (i.indkey)\n WHERE i.indrelid = to_regclass(?) AND i.indisprimary", undef, $self->_quote_ident_path($table)) } }; _trim_cache(\%_pg_pk, 1000); $cols && @$cols == 1 ? $cols->[0] : "" }
Truth table66%2/3
A //= B
A= $_pg_pk{$table}B= do { my $dbh = $self->db->dbh; my $cols = eval { do { local $dbh->{"HandleError"}; local $dbh->{"RaiseError"} = 1; local $dbh->{"PrintError"} = 0; $dbh->selectcol_arrayref("SELECT a.attname FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid\n AND a.attnum = ANY (i.indkey)\n WHERE i.indrelid = to_regclass(?) AND i.indisprimary", undef, $self->_quote_ident_path($table)) } }; _trim_cache(\%_pg_pk, 1000); $cols && @$cols == 1 ? $cols->[0] : "" }
ABresult
1X1
011
000
1296 4 my $dbh = $self->db->dbh;
1297 4 my $cols = eval {
1298 4 local $dbh->{HandleError};
1299 4 local $dbh->{RaiseError} = 1;
1300 4 local $dbh->{PrintError} = 0;
1301 4 $dbh->selectcol_arrayref(
1302 q{SELECT a.attname FROM pg_index i
1303 JOIN pg_attribute a ON a.attrelid = i.indrelid
1304 AND a.attnum = ANY (i.indkey)
1305 WHERE i.indrelid = to_regclass(?) AND i.indisprimary},
1306 undef, $self->_quote_ident_path($table));
1307 };
1308 4 _trim_cache(\%_pg_pk, 1_000);
1309 4 ▶ $cols && @$cols == 1 ? $cols->[0] : '';
Branch: 1 branch
BranchTrueFalseTotal
$cols && @$cols == 1 ? : 1 3 4
Condition100%3/3
$cols and @$cols == 1
!ll&&!rl&&r
121
MC/DC100%2/2
$cols and @$cols == 1
$cols @$cols == 1
Truth table100%3/3
A and B
A= $colsB= @$cols == 1
ABresult
0X0
100
111
1310 };
1311 5 ▶ return $pk eq '' ? '' : ' RETURNING ' . $self->db->dbh->quote_identifier($pk);
Branch: 1 branch
BranchTrueFalseTotal
$pk eq '' ? : 4 1 5
1312 38 }
1313  
1314 35 ▶ method _update_last_id ($table) {
Subroutine _update_last_id: called CC=7 SCAR=21.3
1315 35 ▶ my $dbd = $_dbd_c //= $self->dbd;
Condition66%2/3
$_dbd_c //= $self->dbd
l!l&&r!l&&!r
2780
MC/DC0%0/2
$_dbd_c //= $self->dbd
$_dbd_c $self->dbd
Truth table66%2/3
A //= B
A= $_dbd_cB= $self->dbd
ABresult
1X1
011
000
1316 35 ▶ my $dbh = $_write_dbh // $self->db->dbh;
Condition33%1/3
$_write_dbh // $self->db->dbh
l!l&&r!l&&!r
3500
MC/DC0%0/2
$_write_dbh // $self->db->dbh
$_write_dbh $self->db->dbh
Truth table33%1/3
A // B
A= $_write_dbhB= $self->db->dbh
ABresult
1X1
011
000
1317 35 ▶ if ($dbd eq 'SQLite') { $last_id = $dbh->sqlite_last_insert_rowid() }
Branch: 4 branches
BranchTrueFalseTotal
if ($dbd eq 'SQLite') { } 31 4 35
elsif ($dbd eq 'MariaDB') { } 0 4 4
elsif ($dbd eq 'mysql') { } 0 4 4
elsif ($dbd eq 'Pg') { } 4 0 4
1318 0 elsif ($dbd eq 'MariaDB') { $last_id = $dbh->{mariadb_insertid} }
1319 0 elsif ($dbd eq 'mysql') { $last_id = $dbh->{mysql_insertid} }
1320 elsif ($dbd eq 'Pg') {
1321 # DBD::Pg guesses the serial sequence from the table name. That fails for
1322 # non-default schemas, renamed/custom sequences, or non-serial PKs. Guard
1323 # it so a failed lookup yields undef last_id instead of dying AFTER the row
1324 # was already inserted. NOTE: Pg last_id requires a serial/identity PK; for
1325 # other cases use INSERT ... RETURNING via exec()/query().
1326 4 $last_id = eval { $dbh->last_insert_id(undef, undef, $table, undef) };
1327 }
1328 38 }
1329  
1330 31 ▶ method update ($table_name, $skeel, @extra) {
Subroutine update: called CC=2 SCAR=6.9
Pod documented
1331 31 ▶ $skeel->{sen} = $self->extra_args($skeel->{sen}, @extra)
Branch: 1 branch
BranchTrueFalseTotal
if @extra 5 26 31
1332 if @extra;
1333 30 return $self->_update($table_name, $skeel->{sen}, $skeel->{where});
1334 38 }
1335  
1336 72 ▶ method _update ($table_name, $set, $where) {
Subroutine _update: called CC=19 SCAR=29.6
1337 72 my $table = $self->TableName($table_name);
1338 72 ▶ $set = $self->_json_encode_row($table, $set) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 1 71 72
1339  
1340 # Cached shape with plain values: validated when its SQL was built (see
1341 # insert, including the NUL-separator guard).
1342 72 my (@scols, @wcols, $hit);
1343 72 ▶ if (!$_ts_on && ref $set eq 'HASH' && _plain_where($where)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $_ts_on and ref $set eq "HASH" and _plain_where($where)) 47 25 72
Condition83%5/6
not $_ts_on and ref $set eq "HASH" and _plain_where($where)
!ll&&!rl&&r
22347
not $_ts_on and ref $set eq "HASH"
!ll&&!rl&&r
2070
MC/DC66%2/3
not $_ts_on and ref $set eq "HASH" and _plain_where($where)
not $_ts_on ref $set eq "HASH" _plain_where($where)
Truth table75%3/4
not(A) and B and C
A= not $_ts_onB= ref $set eq "HASH"C= _plain_where($where)
ABCresult
0XX0
10X0
1100
1111
1344 47 @scols = sort keys %$set;
1345 47 @wcols = sort keys %$where;
1346 47 ▶ $hit = @scols && $_crud_sql{ join("\0", 'U', $table, @scols, '', @wcols) };
Condition66%2/3
@scols && $_crud_sql{join "\000", 'U', $table, @scols, '', @wcols}
!ll&&!rl&&r
0425
MC/DC50%1/2
@scols && $_crud_sql{join "\000", 'U', $table, @scols, '', @wcols}
@scols $_crud_sql{join "\000", 'U', $table, @scols, '', @wcols}
Truth table66%2/3
A && B
A= @scolsB= $_crud_sql{join "\000", 'U', $table, @scols, '', @wcols}
ABresult
0X0
100
111
1347 7 undef $hit if $hit && (grep({ ref } @{$set}{@scols})
1348 47 ▶ || grep({ index($_, "\0") >= 0 } @scols, @wcols));
Branch: 1 branch
BranchTrueFalseTotal
if $hit and grep({ref $_;} @{$set;}{@scols}) || grep({index($_, "\0") != -1;} @scols, @wcols) 1 46 47
Condition83%5/6
$hit and grep({ref $_;} @{$set;}{@scols}) || grep({index($_, "\0") != -1;} @scols, @wcols)
!ll&&!rl&&r
4241
grep {ref $_;} @{$set;}{@scols} or grep {index($_, "\0") != -1;} @scols, @wcols
l!l&&r!l&&!r
104
MC/DC66%2/3
$hit and grep({ref $_;} @{$set;}{@scols}) || grep({index($_, "\0") != -1;} @scols, @wcols)
$hit grep {ref $_;} @{$set;}{@scols} grep {index($_, "\0") != -1;} @scols, @wcols
Truth table75%3/4
A and B or C
A= $hitB= grep {ref $_;} @{$set;}{@scols}C= grep {index($_, "\0") != -1;} @scols, @wcols
ABCresult
0XX0
1000
11X1
1011
1349 }
1350 72 my $sth;
1351 72 ▶ if ($hit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hit) 4 68 72
1352 4 $sql = $hit;
1353 4 $sth = $self->_write_exec(@{$set}{@scols}, @{$where}{@wcols});
1354 4 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 0 4 4
1355 4 ▶ $self->_fire_after_write(op => 'update', table => $table, data => $set, where => $where) if $_after_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write 0 4 4
1356 4 return $sth;
1357 }
1358  
1359 68 $self->_safe_data($set);
1360 52 $self->_safe_columns($where);
1361  
1362 24 ▶ $set = $self->_stamp($table, $set, 'update') if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 2 22 24
1363 24 @scols = sort keys %$set;
1364 24 ▶ 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)) { } 16 8 24
Condition83%5/6
@scols and not grep({ref $_;} @{$set;}{@scols}) and _plain_where($where)
!ll&&!rl&&r
3516
@scols and not grep({ref $_;} @{$set;}{@scols})
!ll&&!rl&&r
0321
MC/DC66%2/3
@scols and not grep({ref $_;} @{$set;}{@scols}) and _plain_where($where)
@scols not grep({ref $_;} @{$set;}{@scols}) _plain_where($where)
Truth table75%3/4
A and not(B) and C
A= @scolsB= not grep({ref $_;} @{$set;}{@scols})C= _plain_where($where)
ABCresult
0XX0
10X0
1100
1111
1365 16 @wcols = sort keys %$where;
1366 16 my $ck = join("\0", 'U', $table, @scols, '', @wcols);
1367 $sql = $_crud_sql{$ck} // $self->_crud_stmt($ck,
1368 16 ▶ sub { $self->Q->update($table, $set, $where) });
Subroutine __ANON__: called CC=1 SCAR=0.6
Condition33%1/3
$_crud_sql{$ck} // $self->_crud_stmt($ck, sub { $self->Q->update($table, $set, $where); } )
l!l&&r!l&&!r
0160
MC/DC0%0/2
$_crud_sql{$ck} // $self->_crud_stmt($ck, sub { $self->Q->update($table, $set, $where); } )
$_crud_sql{$ck} $self->_crud_stmt($ck, sub { $self->Q->update($table, $set, $where); } )
Truth table33%1/3
A // B
A= $_crud_sql{$ck}B= $self->_crud_stmt($ck, sub { $self->Q->update($table, $set, $where); } )
ABresult
1X1
011
000
1369 16 $sth = $self->_write_exec(@{$set}{@scols}, @{$where}{@wcols});
1370 }
1371 else {
1372 8 my ($stmt, @bind) = $self->Q->update($table, $set, $where);
1373 8 $sql = $stmt;
1374 8 $sth = $self->_write_exec(@bind);
1375 }
1376 24 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 1 23 24
1377 24 ▶ $self->_fire_after_write(op => 'update', table => $table, data => $set, where => $where) if $_after_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write 0 24 24
1378 24 return $sth;
1379 38 }
1380  
1381 44 ▶ method up ($table_name, $data, $where, $time_col = undef) {
Subroutine up: called CC=3 SCAR=11.0
Pod documented
1382 44 ▶ return $self->update($table_name, { sen => $data, where => $where }, time => $time_col)
Branch: 1 branch
BranchTrueFalseTotal
if $time_col 2 42 44
1383 if $time_col;
1384 42 return $self->_update($table_name, $data, $where);
1385 38 }
1386  
1387 60 ▶ method delete ($table_name, $skeel) {
Subroutine delete: called CC=7 SCAR=19.5
Pod documented
1388 60 my $table = $self->TableName($table_name);
1389  
1390 60 my $sth;
1391 60 ▶ if (_plain_where($skeel)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_plain_where($skeel)) { } 30 30 60
1392 30 my @wcols = sort keys %$skeel;
1393 30 my $ck = join("\0", 'D', $table, @wcols);
1394 # Cached shape: validated when its SQL was built (NUL guard: see insert).
1395 30 ▶ if (!$_crud_sql{$ck} || grep { index($_, "\0") >= 0 } @wcols) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $_crud_sql{$ck} or grep {index($_, "\0") != -1;} @wcols) 22 8 30
Condition66%2/3
not $_crud_sql{$ck} or grep {index($_, "\0") != -1;} @wcols
l!l&&r!l&&!r
2208
MC/DC50%1/2
not $_crud_sql{$ck} or grep {index($_, "\0") != -1;} @wcols
not $_crud_sql{$ck} grep {index($_, "\0") != -1;} @wcols
Truth table66%2/3
not(A) or B
A= not $_crud_sql{$ck}B= grep {index($_, "\0") != -1;} @wcols
ABresult
1X1
011
000
1396 22 $self->_safe_columns($skeel);
1397 }
1398 $sql = $_crud_sql{$ck} // $self->_crud_stmt($ck,
1399 20 ▶ sub { $self->Q->delete($table, $skeel) });
Subroutine __ANON__: called CC=1 SCAR=0.1
Condition66%2/3
$_crud_sql{$ck} // $self->_crud_stmt($ck, sub { $self->Q->delete($table, $skeel); } )
l!l&&r!l&&!r
8120
MC/DC0%0/2
$_crud_sql{$ck} // $self->_crud_stmt($ck, sub { $self->Q->delete($table, $skeel); } )
$_crud_sql{$ck} $self->_crud_stmt($ck, sub { $self->Q->delete($table, $skeel); } )
Truth table66%2/3
A // B
A= $_crud_sql{$ck}B= $self->_crud_stmt($ck, sub { $self->Q->delete($table, $skeel); } )
ABresult
1X1
011
000
1400 20 $sth = $self->_write_exec(@{$skeel}{@wcols});
1401 }
1402 else {
1403 30 $self->_safe_columns($skeel);
1404 11 my ($stmt, @bind) = $self->Q->delete($table, $skeel);
1405 11 $sql = $stmt;
1406 11 $sth = $self->_write_exec(@bind);
1407 }
1408 31 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 1 30 31
1409 31 ▶ $self->_fire_after_write(op => 'delete', table => $table, where => $skeel) if $_after_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write 0 31 31
1410 31 return $sth;
1411 38 }
1412  
1413 81 ▶ method upsert ($table_name, $row, $conflict_keys, $update_cols = undef) {
Subroutine upsert: called CC=13 SCAR=25.8
Pod documented
1414 81 ▶ $self->Exception("upsert: row hashref required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" and %$row 0 81 81
Condition33%1/3
ref $row eq "HASH" and %$row
!ll&&!rl&&r
0081
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
1415 unless ref $row eq 'HASH' && %$row;
1416 81 ▶ $self->Exception("upsert: conflict_keys arrayref required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $conflict_keys eq "ARRAY" and @$conflict_keys 0 81 81
Condition33%1/3
ref $conflict_keys eq "ARRAY" and @$conflict_keys
!ll&&!rl&&r
0081
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
1417 unless ref $conflict_keys eq 'ARRAY' && @$conflict_keys;
1418  
1419 81 my $table = $self->TableName($table_name);
1420 81 ▶ $row = $self->_json_encode_row($table, $row) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 1 80 81
1421  
1422 81 $self->_safe_bind_row($row);
1423 68 $self->_safe_ids(@$conflict_keys);
1424  
1425 # Without timestamps the statement depends only on the table, the
1426 # columns, the conflict keys and update_cols as given: key the statement
1427 # cache on those, so a repeated upsert skips normalizing/validating the
1428 # update spec (done once, on the miss that built the statement - the row
1429 # VALUES are still validated every call, above).
1430 58 my @cols = sort keys %$row;
1431 58 my $sets;
1432 my $key;
1433 58 ▶ if ($_ts_on) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ts_on) { } 2 56 58
1434 # The update spec comes from the caller's columns (so a stamped created
1435 # column is never overwritten on conflict); the stamped updated column
1436 # is then always refreshed.
1437 2 $sets = $self->_update_spec('upsert', $update_cols, $conflict_keys, \@cols);
1438 2 $row = $self->_stamp($table, $row, 'insert');
1439 2 $sets = $self->_touch_updated($table, $sets);
1440 2 @cols = sort keys %$row;
1441 2 ▶ $key = join("\0", 'S', $table, (map { ref $row->{$_} ? "$_=L" : $_ } @cols),
Branch: 1 branch
BranchTrueFalseTotal
ref $row->{$_} ? : 2 6 8
1442 '', @$conflict_keys, '', _spec_key($sets));
1443 }
1444 else {
1445 56 $key = join("\0", 'S', $table, @cols, '', @$conflict_keys, '',
1446 _raw_spec_key($update_cols));
1447 }
1448  
1449 $sql = $_crud_sql{$key} // $self->_crud_stmt($key,
1450 52 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1451 52 ▶ $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
23812
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
1452 32 my $dbh = $self->db->dbh;
1453 32 my $qt = $self->_quote_ident_path($table);
1454 32 my $qcols = join(', ', map { $dbh->quote_identifier($_) } @cols);
1455 32 my $placeholders = join(', ', map { _ph($row->{$_}) } @cols);
1456 32 my $clause = $self->_upsert_clause($conflict_keys, $sets, $qt);
1457 32 "INSERT INTO " . $self->_upsert_target($qt) . " ($qcols) VALUES ($placeholders) $clause";
1458 58 ▶ });
Condition100%3/3
$_crud_sql{$key} // $self->_crud_stmt($key, sub { $sets //= $self->_update_spec("upsert", $update_cols, $conflict_keys, \@cols); my $dbh = $self->db->dbh; my $qt = $self->_quote_ident_path($table); my $qcols = join(", ", map({$dbh->quote_identifier($_);} @cols)); my $placeholders = join(", ", map({_ph($row->{$_});} @cols)); my $clause = $self->_upsert_clause($conflict_keys, $sets, $qt); 'INSERT INTO ' . $self->_upsert_target($qt) . " ($qcols) VALUES ($placeholders) $clause"; } )
l!l&&r!l&&!r
64012
MC/DC0%0/2
$_crud_sql{$key} // $self->_crud_stmt($key, sub { $sets //= $self->_update_spec("upsert", $update_cols, $conflict_keys, \@cols); my $dbh = $self->db->dbh; my $qt = $self->_quote_ident_path($table); my $qcols = join(", ", map({$dbh->quote_identifier($_);} @cols)); my $placeholders = join(", ", map({_ph($row->{$_});} @cols)); my $clause = $self->_upsert_clause($conflict_keys, $sets, $qt); 'INSERT INTO ' . $self->_upsert_target($qt) . " ($qcols) VALUES ($placeholders) $clause"; } )
$_crud_sql{$key} $self->_crud_stmt($key, sub { $sets //= $self->_update_spec("upsert", $update_cols, $conflict_keys, \@cols); my $dbh = $self->db->dbh; my $qt = $self->_quote_ident_path($table); my $qcols = join(", ", map({$dbh->quote_identifier($_);} @cols)); my $placeholders = join(", ", map({_ph($row->{$_});} @cols)); my $clause = $self->_upsert_clause($conflict_keys, $sets, $qt); 'INSERT INTO ' . $self->_upsert_target($qt) . " ($qcols) VALUES ($placeholders) $clause"; } )
Truth table66%2/3
A // B
A= $_crud_sql{$key}B= $self->_crud_stmt($key, sub { $sets //= $self->_update_spec("upsert", $update_cols, $conflict_keys, \@cols); my $dbh = $self->db->dbh; my $qt = $self->_quote_ident_path($table); my $qcols = join(", ", map({$dbh->quote_identifier($_);} @cols)); my $placeholders = join(", ", map({_ph($row->{$_});} @cols)); my $clause = $self->_upsert_clause($conflict_keys, $sets, $qt); 'INSERT INTO ' . $self->_upsert_target($qt) . " ($qcols) VALUES ($placeholders) $clause"; } )
ABresult
1X1
011
000
1459 38 ▶ my @bind = $_ts_on ? (grep { ref ne 'SCALAR' } @{$row}{@cols}) : @{$row}{@cols};
Branch: 1 branch
BranchTrueFalseTotal
$_ts_on ? : 2 36 38
1460 38 my $sth = $self->_write_exec(@bind);
1461 38 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 1 37 38
1462 38 ▶ $self->_fire_after_write(op => 'upsert', table => $table, data => $row, conflict_keys => $conflict_keys) if $_after_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write 0 38 38
1463 38 return $sth;
1464 38 }
1465  
1466 # Add the table's updated column to an upsert spec ('new'), unless the
1467 # caller already says how to update it.
1468 4 ▶ method _touch_updated ($table, $sets) {
Subroutine _touch_updated: called CC=5 SCAR=17.1
1469 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
1470 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
1471 4 return [ @$sets, [ $updated, 'new' ] ];
1472 38 }
1473  
1474 # Stamp every row of a batch (same values for all) - see _stamp.
1475 4 ▶ method _stamp_rows ($table, $rows, $which) {
Subroutine _stamp_rows: called CC=2 SCAR=6.9
1476 4 ▶ return $rows unless $self->_timestamps_for($table);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_timestamps_for($table) 0 4 4
1477 4 return [ map { $self->_stamp($table, $_, $which) } @$rows ];
1478 38 }
1479  
1480 # Runs $code->($slice) for consecutive slices of @$rows of at most $size and
1481 # returns the sum of the results. Each slice is its own statement; wrap the
1482 # call in txn() when all-or-nothing matters.
1483 3 ▶ method _in_slices ($rows, $size, $code) {
Subroutine _in_slices: called CC=5 SCAR=16.1
1484 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
1485 unless defined $size && $size =~ /\A[1-9]\d*\z/;
1486 2 my $total = 0;
1487 2 ▶ for (my $i = 0; $i < @$rows; $i += $size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$rows) 8 2 10
1488 8 my $end = $i + $size - 1;
1489 8 ▶ $end = $#$rows if $end > $#$rows;
Branch: 1 branch
BranchTrueFalseTotal
if $end > $rows->$#* 2 6 8
1490 8 $total += $code->([ @{$rows}[ $i .. $end ] ]);
1491 }
1492 2 return $total;
1493 38 }
1494  
1495 24 ▶ method insert_many ($table_name, $rows, %opt) {
Subroutine insert_many: called CC=21 SCAR=31.8
Pod documented
1496 24 ▶ $self->Exception("insert_many: at least one row required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rows eq "ARRAY" and @$rows 0 24 24
Condition33%1/3
ref $rows eq "ARRAY" and @$rows
!ll&&!rl&&r
0024
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
1497 unless ref $rows eq 'ARRAY' && @$rows;
1498 24 ▶ 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 22 24
$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
2202
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
1499 2 my %rest = %opt;
1500 2 delete $rest{chunk};
1501 return $self->_in_slices($rows, $opt{chunk},
1502 2 ▶ sub ($slice) { $self->insert_many($table_name, $slice, %rest) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1503 }
1504 $self->Exception("insert_many: rows must be hashrefs")
1505 22 ▶ if grep { ref $_ ne 'HASH' } @$rows;
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_ ne "HASH";} @$rows 0 22 22
1506  
1507 22 my $table = $self->TableName($table_name);
1508 22 ▶ $rows = $self->_json_encode_rows($table, $rows) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 1 21 22
1509 22 my @cols = sort keys %{ $rows->[0] };
1510 22 $self->_safe_id($_) for @cols;
1511  
1512 # Same key set as row 0: same size and every row-0 column present
1513 # (no per-row sort + join).
1514 22 for my $i (1 .. $#$rows) {
1515 198 my $r = $rows->[$i];
1516 $self->Exception(
1517 "insert_many: row $i has different columns than row 0")
1518 198 ▶ if keys %$r != @cols || grep { !exists $r->{$_} } @cols;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$r != @cols or grep {not exists $r->{$_};} @cols 0 198 198
Condition33%1/3
keys %$r != @cols or grep {not exists $r->{$_};} @cols
l!l&&r!l&&!r
00198
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
1519 }
1520 22 my @bind = map { @{$_}{@cols} } @$rows;
1521 22 $self->_safe_bind_values(\@bind);
1522 18 ▶ if ($_ts_on) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ts_on) 2 16 18
1523 2 $rows = $self->_stamp_rows($table, $rows, 'insert');
1524 2 @cols = sort keys %{ $rows->[0] };
1525 2 @bind = grep { ref ne 'SCALAR' } map { @{$_}{@cols} } @$rows;
1526 }
1527  
1528 18 my $dbh = $self->db->dbh;
1529 18 my $qt = $self->_quote_ident_path($table);
1530 18 my $qcols = join(', ', map { $dbh->quote_identifier($_) } @cols);
1531 18 my $row_ph = '(' . join(', ', map { _ph($rows->[0]{$_}) } @cols) . ')';
1532 18 my $values = join(', ', ($row_ph) x scalar(@$rows));
1533  
1534 # ignore => 1: rows violating a UNIQUE/PRIMARY KEY are skipped (see
1535 # insert_ignore); the return value is then the number actually inserted.
1536 18 my $dbd = $self->dbd;
1537 18 my ($verb, $tail) = ('INSERT INTO', '');
1538 18 ▶ if ($opt{ignore}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"ignore"}) 1 17 18
1539 0 ▶ 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
1540 1 elsif ($dbd eq 'SQLite') { $verb = 'INSERT OR IGNORE INTO' }
1541 0 else { $tail = ' ON CONFLICT DO NOTHING' }
1542 }
1543  
1544 18 $sql = "$verb $qt ($qcols) VALUES $values$tail";
1545 18 $self->_write_exec(@bind);
1546  
1547 18 $self->_update_last_id($table);
1548 18 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 0 18 18
1549 18 ▶ $self->_fire_after_write(op => 'insert_many', table => $table, data => $rows) if $_after_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write 0 18 18
1550 18 ▶ return $opt{ignore} ? ($_affected_rows // 0) : scalar @$rows;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'ignore'} ? : 1 17 18
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
1551 38 }
1552  
1553 17 ▶ method upsert_many ($table_name, $rows, $conflict_keys, $update_cols = undef, %opt) {
Subroutine upsert_many: called CC=20 SCAR=31.0
Pod documented
1554 17 ▶ $self->Exception("upsert_many: at least one row required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rows eq "ARRAY" and @$rows 0 17 17
Condition33%1/3
ref $rows eq "ARRAY" and @$rows
!ll&&!rl&&r
0017
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
1555 unless ref $rows eq 'ARRAY' && @$rows;
1556 17 ▶ 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 16 17
$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
1601
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
1557 5 ▶ return $self->_in_slices($rows, $opt{chunk}, sub ($slice) {
Subroutine __ANON__: called CC=1 SCAR=0.0
1558 5 $self->upsert_many($table_name, $slice, $conflict_keys, $update_cols)
1559 1 });
1560 }
1561 $self->Exception("upsert_many: rows must be hashrefs")
1562 16 ▶ if grep { ref $_ ne 'HASH' } @$rows;
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_ ne "HASH";} @$rows 0 16 16
1563 16 ▶ $self->Exception("upsert_many: conflict_keys arrayref required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $conflict_keys eq "ARRAY" and @$conflict_keys 0 16 16
Condition33%1/3
ref $conflict_keys eq "ARRAY" and @$conflict_keys
!ll&&!rl&&r
0016
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
1564 unless ref $conflict_keys eq 'ARRAY' && @$conflict_keys;
1565  
1566 16 my $table = $self->TableName($table_name);
1567 16 ▶ $rows = $self->_json_encode_rows($table, $rows) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 0 16 16
1568 16 my @cols = sort keys %{ $rows->[0] };
1569 16 $self->_safe_id($_) for @cols;
1570 16 $self->_safe_id($_) for @$conflict_keys;
1571 16 my $sets = $self->_update_spec('upsert_many', $update_cols, $conflict_keys, \@cols);
1572 16 ▶ $sets = $self->_touch_updated($table, $sets) if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 2 14 16
1573  
1574 # Same key set as row 0: same size and every row-0 column present
1575 # (no per-row sort + join).
1576 16 for my $i (1 .. $#$rows) {
1577 32 my $r = $rows->[$i];
1578 $self->Exception(
1579 "upsert_many: row $i has different columns than row 0")
1580 32 ▶ if keys %$r != @cols || grep { !exists $r->{$_} } @cols;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$r != @cols or grep {not exists $r->{$_};} @cols 0 32 32
Condition33%1/3
keys %$r != @cols or grep {not exists $r->{$_};} @cols
l!l&&r!l&&!r
0032
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
1581 }
1582  
1583 16 my @bind = map { @{$_}{@cols} } @$rows;
1584 16 $self->_safe_bind_values(\@bind);
1585 12 ▶ if ($_ts_on) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ts_on) 2 10 12
1586 2 $rows = $self->_stamp_rows($table, $rows, 'insert');
1587 2 @cols = sort keys %{ $rows->[0] };
1588 2 @bind = grep { ref ne 'SCALAR' } map { @{$_}{@cols} } @$rows;
1589 }
1590  
1591 12 my $dbh = $self->db->dbh;
1592 12 my $qt = $self->_quote_ident_path($table);
1593 12 my $qcols = join(', ', map { $dbh->quote_identifier($_) } @cols);
1594 12 my $row_ph = '(' . join(', ', map { _ph($rows->[0]{$_}) } @cols) . ')';
1595 12 my $values = join(', ', ($row_ph) x scalar(@$rows));
1596 12 my $clause = $self->_upsert_clause($conflict_keys, $sets, $qt);
1597  
1598 12 $sql = "INSERT INTO " . $self->_upsert_target($qt) . " ($qcols) VALUES $values $clause";
1599 12 $self->_write_exec(@bind);
1600 12 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 0 12 12
1601 12 ▶ $self->_fire_after_write(op => 'upsert_many', table => $table, data => $rows, conflict_keys => $conflict_keys) if $_after_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write 0 12 12
1602  
1603 12 return scalar @$rows;
1604 38 }
1605  
1606  
1607 # Builds the ON CONFLICT / ON DUPLICATE KEY UPDATE clause.
1608 # Pg/SQLite use ON CONFLICT (cols) DO UPDATE SET c = excluded.c.
1609 # MariaDB/mysql use ON DUPLICATE KEY UPDATE c = VALUES(c). The conflict_keys
1610 # are validated for symmetry but not emitted in MariaDB syntax (any UNIQUE
1611 # or PRIMARY KEY triggers the update there).
1612 # The ON CONFLICT update spec, normalized to [ [col, mode], ... ]:
1613 # undef every row column that is not a conflict key, 'new'
1614 # [ cols ] those columns, 'new' (the historical form)
1615 # { col => 'new' | '+' | { '+' => N } | \'SQL' }
1616 # 'new' takes the incoming value, '+' adds it to the stored
1617 # one (balances), { '+' => N } adds a constant (counters), a
1618 # scalarref is literal SQL - the documented code-only escape
1619 # hatch (a JSON body cannot carry one), e.g. \'CURRENT_TIMESTAMP'.
1620 # A literal that reads the stored row is dialect-specific
1621 # (PostgreSQL needs dbix_t.col); prefer the modes.
1622 68 ▶ method _update_spec ($who, $update_cols, $conflict_keys, $cols) {
Subroutine _update_spec: called CC=19 SCAR=30.4
1623 68 my @sets;
1624 68 ▶ if (!defined $update_cols) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $update_cols) { } 20 48 68
elsif (ref $update_cols eq 'ARRAY') { } 6 42 48
elsif (ref $update_cols eq 'HASH') { } 42 0 42
1625 20 my %ck = map { $_ => 1 } @$conflict_keys;
1626 20 @sets = map { [ $_, 'new' ] } grep { !$ck{$_} } @$cols;
1627 }
1628 elsif (ref $update_cols eq 'ARRAY') {
1629 6 @sets = map { [ $_, 'new' ] } @$update_cols;
1630 }
1631 elsif (ref $update_cols eq 'HASH') {
1632 42 my %in = map { $_ => 1 } @$cols;
1633 42 for my $col (sort keys %$update_cols) {
1634 52 $self->_safe_id($col);
1635 47 my $mode = $update_cols->{$col};
1636 47 ▶ if (ref $mode eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $mode eq "HASH") 10 37 47
1637 10 my ($op, $n) = %$mode;
1638 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
1639 unless keys %$mode == 1 && $op eq '+'
1640 && defined $n && !ref $n && $n =~ /\A-?\d+(?:\.\d+)?\z/;
1641 5 push @sets, [ $col, [ '+', $n ] ];
1642 5 next;
1643 }
1644 37 ▶ if (ref $mode eq 'SCALAR') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $mode eq "SCALAR") 5 32 37
1645 5 push @sets, [ $col, $mode ];
1646 5 next;
1647 }
1648 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
1649 . "{ '+' => N } or a scalarref of SQL")
1650 unless defined $mode && !ref $mode && ($mode eq 'new' || $mode eq '+');
1651 $self->Exception("$who: '$mode' for $col needs $col in the row")
1652 27 ▶ unless $in{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $in{$col} 5 22 27
1653 22 push @sets, [ $col, $mode ];
1654 }
1655 }
1656 else {
1657 0 $self->Exception("$who: update_cols must be an arrayref or hashref");
1658 }
1659 48 ▶ $self->Exception(
Branch: 1 branch
BranchTrueFalseTotal
unless @sets 0 48 48
1660 "$who: nothing to update on conflict (all row columns are conflict keys)")
1661 unless @sets;
1662 48 $self->_safe_id($_->[0]) for @sets;
1663 48 return \@sets;
1664 38 }
1665  
1666 # Statement-cache key part for update_cols exactly as the caller passed it
1667 # (before normalization). Anything unexpected keys as 'X', which can never
1668 # be cached: _update_spec rejects it on the miss.
1669 56 ▶ sub _raw_spec_key ($u) {
Subroutine _raw_spec_key: called CC=8 SCAR=21.1
1670 56 ▶ return 'U' unless defined $u;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $u 15 41 56
1671 41 ▶ return join ',', 'A', @$u if ref $u eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $u eq "ARRAY" 6 35 41
1672 35 ▶ return 'X' unless ref $u eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $u eq "HASH" 0 35 35
1673 return join ',', 'H', map {
1674 35 my $m = $u->{$_};
1675 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
1676 : ref $m eq 'HASH' ? '+' . join(':', %$m)
1677 : ref $m ? 'X'
1678 : $m // '');
1679 } sort keys %$u;
1680 }
1681  
1682 # Statement-cache key part for a normalized update spec.
1683 2 ▶ sub _spec_key ($sets) {
Subroutine _spec_key: called CC=3 SCAR=11.7
1684 return map {
1685 2 my $m = $_->[1];
1686 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
1687 } @$sets;
1688 }
1689  
1690 # "INSERT INTO <target>" for an upsert: PostgreSQL gets the alias dbix_t, the
1691 # only unambiguous way to name the stored row in ON CONFLICT DO UPDATE (a
1692 # bare column there is ambiguous between it and EXCLUDED).
1693 44 ▶ method _upsert_target ($qt) {
Subroutine _upsert_target: called CC=2 SCAR=6.9
1694 44 ▶ return $self->dbd eq 'Pg' ? "$qt AS dbix_t" : $qt;
Branch: 1 branch
BranchTrueFalseTotal
$self->dbd eq 'Pg' ? : 1 43 44
1695 38 }
1696  
1697 # Builds the ON CONFLICT / ON DUPLICATE KEY UPDATE clause from a normalized
1698 # spec. The incoming value is VALUES(c) on MariaDB and MySQL < 8.0.19, the
1699 # row alias new.c on MySQL >= 8.0.19 (VALUES() is deprecated there) and
1700 # excluded.c on PostgreSQL/SQLite. MariaDB/MySQL ignore conflict_keys (any
1701 # UNIQUE or PRIMARY KEY triggers the update); they are validated for symmetry.
1702 44 ▶ method _upsert_clause ($conflict_keys, $sets, $qt = undef) {
Subroutine _upsert_clause: called CC=15 SCAR=27.4
1703 44 my $dbh = $self->db->dbh;
1704 44 my $dbd = $self->dbd;
1705  
1706 44 my ($incoming, $prefix);
1707 44 ▶ if ($dbd eq 'mysql' && ($dbh->{mysql_serverversion} // 0) >= 80019) {
Branch: 2 branches
BranchTrueFalseTotal
if ($dbd eq 'mysql' and ($dbh->{'mysql_serverversion'} // 0) >= 80019) { } 1 43 44
elsif ($dbd eq 'mysql' or $dbd eq 'MariaDB') { } 1 42 43
Condition60%3/5
$dbd eq "mysql" and ($dbh->{"mysql_serverversion"} // 0) >= 80019
!ll&&!rl&&r
4301
$dbh->{"mysql_serverversion"} // 0
l!l
10
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
1708 1 ▶ $incoming = sub ($qc) { "new.$qc" };
Subroutine __ANON__: called CC=1 SCAR=0.0
1709 1 $prefix = 'AS new ON DUPLICATE KEY UPDATE ';
1710 }
1711 ▶ elsif ($dbd eq 'mysql' || $dbd eq 'MariaDB') {
Condition66%2/3
$dbd eq "mysql" or $dbd eq "MariaDB"
l!l&&r!l&&!r
0142
MC/DC50%1/2
$dbd eq "mysql" or $dbd eq "MariaDB"
$dbd eq "mysql" $dbd eq "MariaDB"
Truth table66%2/3
A or B
A= $dbd eq "mysql"B= $dbd eq "MariaDB"
ABresult
1X1
011
000
1712 1 ▶ $incoming = sub ($qc) { "VALUES($qc)" };
Subroutine __ANON__: called CC=1 SCAR=0.0
1713 1 $prefix = 'ON DUPLICATE KEY UPDATE ';
1714 }
1715 else {
1716 42 my $qck = join(', ', map { $dbh->quote_identifier($_) } @$conflict_keys);
1717 42 ▶ $incoming = sub ($qc) { "excluded.$qc" };
Subroutine __ANON__: called CC=1 SCAR=0.0
1718 42 $prefix = "ON CONFLICT ($qck) DO UPDATE SET ";
1719 }
1720  
1721 # Naming the STORED row: PostgreSQL via the dbix_t alias (_upsert_target);
1722 # MySQL's row-alias form via the table name (a bare column is ambiguous
1723 # with new.col there); MariaDB/SQLite accept the bare column.
1724 0 ▶ my $stored = $dbd eq 'Pg' ? sub ($qc) { "dbix_t.$qc" }
Subroutine __ANON__: not called CC=1 SCAR=6.9
1725 0 ▶ : $dbd eq 'mysql' && $prefix =~ /^AS new/ && $qt ? sub ($qc) { "$qt.$qc" }
Subroutine __ANON__: not called CC=1 SCAR=6.9
1726 44 ▶ : sub ($qc) { $qc };
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 2 branches
BranchTrueFalseTotal
$dbd eq 'Pg' ? : 1 43 44
$dbd eq 'mysql' && $prefix =~ /^AS new/u && $qt ? : 1 42 43
Condition66%4/6
$dbd eq "mysql" and $prefix =~ /^AS new/u and $qt
!ll&&!rl&&r
4201
$dbd eq "mysql" and $prefix =~ /^AS new/u
!ll&&!rl&&r
4201
MC/DC33%1/3
$dbd eq "mysql" and $prefix =~ /^AS new/u and $qt
$dbd eq "mysql" $prefix =~ /^AS new/u $qt
Truth table50%2/4
A and B and C
A= $dbd eq "mysql"B= $prefix =~ /^AS new/uC= $qt
ABCresult
0XX0
10X0
1100
1111
1727  
1728 my @sql = map {
1729 # A bare column name (the pre-0.20 [cols] form) means 'new'.
1730 44 ▶ my ($col, $mode) = ref $_ ? @$_ : ($_, 'new');
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 71 0 71
1731 71 my $qc = $dbh->quote_identifier($col);
1732 71 ▶ ref $mode eq 'SCALAR' ? "$qc = $$mode"
Branch: 3 branches
BranchTrueFalseTotal
ref $mode eq 'SCALAR' ? : 5 66 71
ref $mode ? : 5 61 66
$mode eq '+' ? : 15 46 61
1733 : ref $mode ? "$qc = " . $stored->($qc) . " + $mode->[1]"
1734 : $mode eq '+' ? "$qc = " . $stored->($qc) . ' + ' . $incoming->($qc)
1735 : "$qc = " . $incoming->($qc);
1736 } @$sets;
1737 44 return $prefix . join(', ', @sql);
1738 38 }
1739  
1740 # INSERT that silently skips a row violating a UNIQUE/PRIMARY KEY:
1741 # INSERT IGNORE (MariaDB/MySQL), INSERT OR IGNORE (SQLite), ON CONFLICT DO
1742 # NOTHING (PostgreSQL). Returns 1 when the row was inserted, 0 when it
1743 # already existed. Note: MariaDB/MySQL's IGNORE also downgrades other errors
1744 # (bad values, NOT NULL) to warnings.
1745 31 ▶ method insert_ignore ($table_name, $row) {
Subroutine insert_ignore: called CC=17 SCAR=32.5
Pod documented
1746 31 my $table = $self->TableName($table_name);
1747 31 ▶ $row = $self->_json_encode_row($table, $row) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 0 31 31
1748 31 $self->_safe_data($row);
1749 31 ▶ $self->Exception("insert_ignore: row hashref required") unless %$row;
Branch: 1 branch
BranchTrueFalseTotal
unless %$row 0 31 31
1750 31 ▶ $row = $self->_stamp($table, $row, 'insert') if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 2 29 31
1751  
1752 31 my ($stmt, @bind) = $self->Q->insert($table, $row);
1753 31 my $dbd = $self->dbd;
1754 0 ▶ 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
1755 31 elsif ($dbd eq 'SQLite') { $stmt =~ s/^INSERT INTO/INSERT OR IGNORE INTO/ }
1756 0 else { $stmt .= ' ON CONFLICT DO NOTHING' }
1757 31 ▶ my $ret = ($_dbd_c //= $self->dbd) eq 'Pg' # no row back when ignored
Branch: 1 branch
BranchTrueFalseTotal
($_dbd_c //= $self->dbd) eq 'Pg' ? : 0 31 31
Condition66%2/3
$_dbd_c //= $self->dbd
l!l&&r!l&&!r
2290
MC/DC0%0/2
$_dbd_c //= $self->dbd
$_dbd_c $self->dbd
Truth table66%2/3
A //= B
A= $_dbd_cB= $self->dbd
ABresult
1X1
011
000
1758 ? $self->_pg_returning($table) : '';
1759 31 $stmt .= $ret;
1760  
1761 31 $sql = $stmt;
1762 31 my $sth = $self->_write_exec(@bind);
1763 31 ▶ my $inserted = $_affected_rows ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$_affected_rows ? : 13 18 31
1764 31 ▶ if ($ret) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ret) { } 0 31 31
elsif ($inserted) { } 13 18 31
1765 0 ▶ ($last_id) = $sth->fetchrow_array if $inserted; # ignored: unchanged
Branch: 1 branch
BranchTrueFalseTotal
if $inserted 0 0 0
1766 0 $sth->finish;
1767 }
1768 elsif ($inserted) {
1769 13 $self->_update_last_id($table);
1770 }
1771 31 ▶ $self->_cache_invalidate_table($table) if $inserted && $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $inserted and $_cache_on 0 31 31
Condition66%2/3
$inserted and $_cache_on
!ll&&!rl&&r
18130
MC/DC0%0/2
$inserted and $_cache_on
$inserted $_cache_on
Truth table66%2/3
A and B
A= $insertedB= $_cache_on
ABresult
0X0
100
111
1772 31 ▶ $self->_fire_after_write(op => 'insert_ignore', table => $table, data => $row) if $_after_write && $inserted;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write and $inserted 0 31 31
Condition33%1/3
$_after_write and $inserted
!ll&&!rl&&r
3100
MC/DC0%0/2
$_after_write and $inserted
$_after_write $inserted
Truth table33%1/3
A and B
A= $_after_writeB= $inserted
ABresult
0X0
100
111
1773 31 return $inserted;
1774 38 }
1775  
1776 # The row matching $key (a { column => value } hashref covered by a UNIQUE
1777 # index), inserting { %$defaults, %$key } first when there is none. Safe
1778 # against concurrent callers: the insert is insert_ignore, so a racing
1779 # duplicate is skipped and the existing row is read back. In list context
1780 # also returns whether this call created it.
1781 21 ▶ method find_or_create ($table_name, $key, $defaults = {}) {
Subroutine find_or_create: called CC=8 SCAR=21.9
Pod documented
1782 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
1783 unless ref $key eq 'HASH' && %$key;
1784 21 ▶ $self->Exception("find_or_create: defaults must be a hashref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $defaults eq "HASH" 0 21 21
1785 unless ref $defaults eq 'HASH';
1786 $self->Exception("find_or_create: key values must be defined plain values")
1787 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
1788  
1789 21 my $created = $self->insert_ignore($table_name, { %$defaults, %$key });
1790  
1791 21 my $table = $self->TableName($table_name);
1792 21 my ($parts, $params) = $self->_where_parts($key);
1793 21 my $row = $self->hash('SELECT * FROM ' . $self->_quote_ident_path($table)
1794 . ' WHERE ' . join(' AND ', @$parts), @$params);
1795 21 ▶ return wantarray ? ($row, $created) : $row;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 14 7 21
1796 38 }
1797  
1798 12 ▶ method extra_args ($skeel, %args) {
Subroutine extra_args: called CC=2 SCAR=6.9
Pod undocumented
1799 12 ▶ if ($args{time}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"time"}) 12 0 12
1800 12 $self->_safe_id($args{time});
1801 10 $skeel->{ $args{time} } = $self->now();
1802 }
1803 10 return $skeel;
1804 38 }
1805  
1806 # :name -> ? rewrite, memoized per SQL text: the rewritten statement and
1807 # the placeholder order depend only on the text, so repeated execute()
1808 # calls skip the regex pass and just slice the bind values.
1809 38 field %_named_sql;
1810  
1811 8 ▶ method make_sen ($skeel) {
Subroutine make_sen: called CC=4 SCAR=13.9
Pod documented
1812 8 ▶ my $stmt = $sql // '';
Condition50%1/2
$sql // ""
l!l
80
MC/DC0%0/1
$sql // ""
$sql
Truth table50%1/2
A
A= $sql
Aresult
11
00
1813 8 ▶ my $parsed = $_named_sql{$stmt} //= do {
Condition66%2/3
$_named_sql{$stmt} //= do { _trim_cache(\%_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
260
MC/DC0%0/2
$_named_sql{$stmt} //= do { _trim_cache(\%_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 { _trim_cache(\%_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 table66%2/3
A //= B
A= $_named_sql{$stmt}B= do { _trim_cache(\%_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
1814 6 _trim_cache(\%_named_sql, 1_000);
1815 6 my @names;
1816 # Single left-to-right pass: a quoted string literal is matched as a
1817 # unit and left untouched, so ':' inside it is never substituted. The
1818 # (?<![:\w]) lookbehind keeps the second colon of a Postgres '::cast'
1819 # (and back-to-back names) from matching.
1820 6 (my $out = $stmt) =~ s{
1821 ( '[^']*' | "[^"]*" ) # $1: quoted literal -> leave as-is
1822 |
1823 (?<![:\w]) : ([A-Za-z_]\w*) # $2: named placeholder -> bind
1824 }{
1825 11 ▶ defined $1 ? $1 : do { push @names, $2; '?' }
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 0 11 11
1826 }gex;
1827 6 [ $out, \@names ];
1828 };
1829  
1830 8 $sql = $parsed->[0];
1831 # A hash slice yields undef for a missing name without autovivifying.
1832 8 $p = [ @{$skeel}{ @{ $parsed->[1] } } ];
1833 38 }
1834  
1835 # execute_prepare for the CRUD methods: they consume the handle before
1836 # returning (a write, or Pg's RETURNING row read and finished at once), so
1837 # it comes from the cache without the Active check.
1838 #
1839 # Hot path inline: a cached handle, nothing observed - prepare, timing and
1840 # the result bookkeeping without the method calls (and in a method that
1841 # mentions few fields: Object::Pad binds every field a method names).
1842 # Anything else takes _exec_stmt, same results and errors.
1843 456 ▶ method _write_exec (@params) {
Subroutine _write_exec: called CC=8 SCAR=21.2
1844 456 my $stmt = $sql;
1845 456 my $sth;
1846 456 ▶ if ($_fast && defined $stmt && ($sth = $_sth_cache{$stmt})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_fast and defined $stmt and $sth = $_sth_cache{$stmt}) 185 271 456
Condition83%5/6
$_fast and defined $stmt and $sth = $_sth_cache{$stmt}
!ll&&!rl&&r
28243185
$_fast and defined $stmt
!ll&&!rl&&r
280428
MC/DC66%2/3
$_fast and defined $stmt and $sth = $_sth_cache{$stmt}
$_fast defined $stmt $sth = $_sth_cache{$stmt}
Truth table75%3/4
A and B and C
A= $_fastB= defined $stmtC= $sth = $_sth_cache{$stmt}
ABCresult
0XX0
10X0
1100
1111
1847 185 my $dbh = $_conn->dbh;
1848 185 $_write_dbh = $dbh;
1849 185 Scalar::Util::weaken($_write_dbh);
1850 185 $p = \@params;
1851 185 $_affected_rows = undef;
1852 # dbh() may have reconnected (and emptied the cache): re-check.
1853 185 ▶ $sth = $_sth_cache{$stmt} or return $self->_exec_stmt(0, @params);
Branch: 1 branch
BranchTrueFalseTotal
$sth = $_sth_cache{$stmt} or return $self->_exec_stmt(0, @params) 185 0 185
1854 185 ▶ my $rv = $sth->execute(@params)
Branch: 1 branch
BranchTrueFalseTotal
my $rv = $sth->execute(@params) or $self->_db_fail('execute() failed: ' . ($sth->errstr // "unknown"), $sth) 185 0 185
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
1855 or $self->_db_fail("execute() failed: " . ($sth->errstr // 'unknown'), $sth);
1856 185 $last_sql = $stmt;
1857 185 ▶ $_affected_rows = $rv >= 0 ? $rv + 0 : _affected($sth, $rv);
Branch: 1 branch
BranchTrueFalseTotal
$rv >= 0 ? : 185 0 185
1858 185 return $sth;
1859 }
1860 271 return $self->_exec_stmt(0, @params);
1861 38 }
1862  
1863 1 ▶ method execute_prepare (@params) { $self->_exec_stmt(1, @params) }
Subroutine execute_prepare: called CC=1 SCAR=0.0
Pod documented
1864  
1865 272 ▶ method _exec_stmt ($live, @params) {
Subroutine _exec_stmt: called CC=18 SCAR=31.2
1866 272 ▶ my $stmt = $sql // '';
Condition50%1/2
$sql // ""
l!l
2720
MC/DC0%0/1
$sql // ""
$sql
Truth table50%1/2
A
A= $sql
Aresult
11
00
1867  
1868 272 ▶ $self->Exception("execute_prepare(): SQL not set")
Branch: 1 branch
BranchTrueFalseTotal
unless length $stmt 0 272 272
1869 unless length $stmt;
1870  
1871 272 ▶ my $dbh = $_conn && $_conn->dbh
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = $_conn && $_conn->dbh or $self->Exception("execute_prepare(): No DB handle") 272 0 272
Condition33%1/3
$_conn && $_conn->dbh
!ll&&!rl&&r
00272
MC/DC0%0/2
$_conn && $_conn->dbh
$_conn $_conn->dbh
Truth table33%1/3
A && B
A= $_connB= $_conn->dbh
ABresult
0X0
100
111
1872 or $self->Exception("execute_prepare(): No DB handle");
1873 272 $_write_dbh = $dbh;
1874 272 Scalar::Util::weaken($_write_dbh); # never keeps a handle alive (fork/disconnect)
1875  
1876 # Binds first: if prepare fails, HandleError's error entry must carry this
1877 # statement's binds, not the previous query's.
1878 272 $p = \@params;
1879 272 $_affected_rows = undef;
1880  
1881 # 3-arg form: if an identical cached handle is still active, get a fresh one
1882 # instead of emitting a "still Active" warning (execute_prepare returns an
1883 # unfinished handle to the caller).
1884 272 ▶ my $sth = ($live ? $self->_prepare_live($dbh, $stmt) : $self->_prepare($dbh, $stmt))
Branch: 2 branches
BranchTrueFalseTotal
my $sth = $live ? $self->_prepare_live($dbh, $stmt) : $self->_prepare($dbh, $stmt) or $self->_db_fail('prepare() failed: ' . ($dbh->errstr // "unknown"), $dbh) 272 0 272
$live ? : 1 271 272
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
1885 or $self->_db_fail(
1886 "prepare() failed: " . ($dbh->errstr // 'unknown'), $dbh);
1887  
1888 # Timing inline (as in _fetch): _track would allocate a closure per write.
1889 272 my $rv;
1890 272 ▶ my $tracker = $_tracker && $_tracker->enabled ? $_tracker : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_tracker && $_tracker->enabled ? : 6 266 272
Condition66%2/3
$_tracker and $_tracker->enabled
!ll&&!rl&&r
26606
MC/DC50%1/2
$_tracker and $_tracker->enabled
$_tracker $_tracker->enabled
Truth table66%2/3
A and B
A= $_trackerB= $_tracker->enabled
ABresult
0X0
100
111
1891 272 ▶ if ($tracker || $_observe) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tracker or $_observe) { } 28 244 272
Condition100%3/3
$tracker or $_observe
l!l&&r!l&&!r
622244
MC/DC100%2/2
$tracker or $_observe
$tracker $_observe
Truth table100%3/3
A or B
A= $trackerB= $_observe
ABresult
1X1
011
000
1892 28 my $t0 = Time::HiRes::time();
1893 28 ▶ $rv = $sth->execute(@params)
Branch: 1 branch
BranchTrueFalseTotal
$rv = $sth->execute(@params) or $self->_db_fail('execute() failed: ' . ($sth->errstr // "unknown"), $sth) 28 0 28
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
1894 or $self->_db_fail("execute() failed: " . ($sth->errstr // 'unknown'), $sth);
1895 28 my $t1 = Time::HiRes::time();
1896 28 ▶ $tracker->add_query($stmt, $p, $t0, $t1) if $tracker;
Branch: 1 branch
BranchTrueFalseTotal
if $tracker 6 22 28
1897 28 ▶ $self->_observed($t1 - $t0) if $_observe;
Branch: 1 branch
BranchTrueFalseTotal
if $_observe 22 6 28
1898 }
1899 else {
1900 244 ▶ $rv = $sth->execute(@params)
Branch: 1 branch
BranchTrueFalseTotal
$rv = $sth->execute(@params) or $self->_db_fail('execute() failed: ' . ($sth->errstr // "unknown"), $sth) 243 0 243
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
1901 or $self->_db_fail("execute() failed: " . ($sth->errstr // 'unknown'), $sth);
1902 }
1903  
1904 271 $last_sql = $stmt;
1905 271 $_affected_rows = _affected($sth, $rv);
1906  
1907 271 return $sth;
1908 38 }
1909  
1910 }
1911  
1912 38 1;
1913  
1914 __END__
« Fast.pm ↑ Summary Fast/Transaction.pm »