Fast/SQL.pm

filter: Statementstmt 76.9% 967 / 1256 Branchbran 60.8% 321 / 528 Conditioncond 48.7% 171 / 351 MC/DCmcdc 25.2% 53 / 210 Subroutinesub 76.6% 82 / 107 Podpod 97.3% 37 / 38 totaltotal 65.5% 1631 / 2490 CC 425 SCAR 36.5
CC
425
Cov
68%
page
462.0
stream
156.0
_observed
110.0
CRAP 38.4
« Fast/Profile/Pg.pm ↑ Summary Fast.pm »
1 package DBIx::Fast::SQL;
2  
3 35 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 35 ▶use Object::Pad 0.807;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 35 our $VERSION = '0.21';
7 35 ▶use DBI ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 35 ▶use DBIx::Fast::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 35 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 35 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # Histogram buckets (seconds) of the query-duration metric.
13 35 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 692 ▶sub _trim_cache ($h, $max) {
Subroutine _trim_cache: called CC=2 SCAR=11.6
19 692 ▶ return if keys %$h < $max;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$h < $max 692 0 692
20 0 my @k = keys %$h;
21 0 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 66 ▶ field $last_sql :reader = undef;
Subroutine sql: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ and $sql = shift() 4 62 66
36 9 ▶ field $p :accessor = undef;
Subroutine last_sql: called CC=1 SCAR=0.0
Pod documented
37 56 ▶ field $results :reader = undef;
Subroutine p: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ and $p = shift() 1 55 56
38 3 ▶ field $last_id :reader = undef;
Subroutine results: called CC=1 SCAR=0.0
Pod documented
39 3 ▶ 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 1 ▶ field $_json_write;
Subroutine rows: called CC=1 SCAR=0.0
Pod documented
45 35 field $_json_read;
46 35 field $_json_codec;
47 35 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 35 field $_ts_on;
51 2 ▶ 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 35 field $_tracker;
56 4 ▶ 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 35 field $_fast_rows = 1;
64  
65 # dbd() memo for _update_last_id (reset by DBIx::Fast::_set_dbd).
66 35 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 35 field %_pg_pk;
73  
74 # True when the cache option is set (DBIx::Fast ADJUST): writers skip the
75 # table invalidation call otherwise.
76 35 field $_cache_on;
77 6 ▶ 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 35 field $_write_dbh;
82  
83 # after_write hook (see DBIx::Fast POD); undef when not configured.
84 35 field $_after_write;
85 4 ▶ method _set_after_write ($cb) {
Subroutine _set_after_write: called CC=2 SCAR=6.9
86 4 ▶ $self->Exception("after_write must be a coderef") unless ref $cb eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 1 3 4
87 3 $_after_write = $cb;
88 35 }
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 9 ▶ method _fire_after_write (%w) {
Subroutine _fire_after_write: called CC=5 SCAR=16.6
93 9 ▶ $w{rows} //= $_affected_rows;
Condition33%1/3
$w{"rows"} //= $_affected_rows
l!l&&r!l&&!r
090
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 9 ▶ $w{last_id} //= $last_id if $w{op} =~ /^insert/;
Branch: 1 branch
BranchTrueFalseTotal
if $w{"op"} =~ /^insert/u 5 4 9
Condition33%1/3
$w{"last_id"} //= $last_id
l!l&&r!l&&!r
050
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 9 ▶ eval { $_after_write->(\%w); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$_after_write(\%w); 1 } } or warn "DBIx::Fast after_write hook died: $@" 8 1 9
96 or warn "DBIx::Fast after_write hook died: $@";
97 35 }
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 35 field $_observe;
102 35 field $_slow_s; # on_slow_query threshold, seconds
103 35 field $_slow_cb;
104 35 field $_slow_redact; # errors_redact: no bind values in the report
105 35 field $_metrics; # counters, see _observed / metrics
106  
107 0 ▶ method _set_slow_query ($ms, $cb, $redact) {
Subroutine _set_slow_query: not called CC=1 SCAR=6.9
108 0 ($_slow_s, $_slow_cb, $_slow_redact, $_observe) = ($ms / 1000, $cb, $redact, 1);
109 0 $self->_fast_flags;
110 35 }
111  
112 6 ▶ method _fast_flags () {
Subroutine _fast_flags: called CC=3 SCAR=11.2
113 6 ▶ $_fast = !$_observe && !$_tracker;
Condition66%2/3
$_observe || $_tracker
l!l&&r!l&&!r
042
MC/DC50%1/2
$_observe || $_tracker
$_observe $_tracker
Truth table66%2/3
A || B
A= $_observeB= $_tracker
ABresult
1X1
011
000
114 6 ▶ $_fast_rows = $_fast && !$_json_read;
Condition66%2/3
$_fast && !$_json_read
!ll&&!rl&&r
420
MC/DC0%0/2
$_fast && !$_json_read
$_fast !$_json_read
Truth table66%2/3
A && not(B)
A= $_fastB= !$_json_read
ABresult
0X0
100
111
115 35 }
116  
117 0 ▶ method _enable_metrics () {
Subroutine _enable_metrics: not called CC=1 SCAR=6.9
118 # buckets: per-bucket counts (index past the last = over 5 s); made
119 # cumulative only when read (metrics), so a query bumps one slot.
120 0 $_metrics = { queries => 0, seconds => 0, slow => 0, errors => {},
121 buckets => [ (0) x (@DBIx::Fast::SQL::BUCKETS + 1) ] };
122 0 $_observe = 1;
123 0 $self->_fast_flags;
124 35 }
125  
126 # One timed statement ($sql/$p are still the statement's).
127 0 ▶ method _observed ($dt) {
Subroutine _observed: not called CC=10 SCAR=47.0
128 0 ▶ if ($_metrics) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_metrics) 0 0 0
129 0 $_metrics->{queries}++;
130 0 $_metrics->{seconds} += $dt;
131 0 my $i = 0;
132 0 ▶ $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 } 0 0 0
Condition0%0/3
$i < @DBIx::Fast::SQL::BUCKETS and $dt > $DBIx::Fast::SQL::BUCKETS[$i]
!ll&&!rl&&r
000
MC/DC0%0/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 table0%0/3
A and B
A= $i < @DBIx::Fast::SQL::BUCKETSB= $dt > $DBIx::Fast::SQL::BUCKETS[$i]
ABresult
0X0
100
111
133 0 $_metrics->{buckets}[$i]++;
134 }
135 0 ▶ return unless $_slow_cb && $dt >= $_slow_s;
Branch: 1 branch
BranchTrueFalseTotal
unless $_slow_cb and $dt >= $_slow_s 0 0 0
Condition0%0/3
$_slow_cb and $dt >= $_slow_s
!ll&&!rl&&r
000
MC/DC0%0/2
$_slow_cb and $dt >= $_slow_s
$_slow_cb $dt >= $_slow_s
Truth table0%0/3
A and B
A= $_slow_cbB= $dt >= $_slow_s
ABresult
0X0
100
111
136 0 ▶ $_metrics->{slow}++ if $_metrics;
Branch: 1 branch
BranchTrueFalseTotal
if $_metrics 0 0 0
137 0 ▶ my @binds = @{ $p // [] };
Condition0%0/2
$p // []
l!l
00
MC/DC0%0/1
$p // []
$p
Truth table0%0/2
A
A= $p
Aresult
11
00
138 0 ▶ @binds = map { '<redacted>' } @binds if $_slow_redact;
Branch: 1 branch
BranchTrueFalseTotal
if $_slow_redact 0 0 0
139 0 my $q = { sql => $sql, binds => \@binds, ms => 0 + sprintf('%.3f', $dt * 1000) };
140 0 ▶ eval { $_slow_cb->($q); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$_slow_cb($q); 1 } } or warn "DBIx::Fast on_slow_query hook died: $@" 0 0 0
141 or warn "DBIx::Fast on_slow_query hook died: $@";
142 35 }
143  
144 0 ▶ method _count_error ($class) {
Subroutine _count_error: not called CC=2 SCAR=17.9
145 0 ▶ return unless $_metrics;
Branch: 1 branch
BranchTrueFalseTotal
unless $_metrics 0 0 0
146 0 $_metrics->{errors}{ $class =~ s/\ADBIx::Fast::X:://r }++;
147 35 }
148  
149 # Snapshot of the counters, or undef when metrics are off.
150 0 ▶ method metrics () {
Subroutine metrics: not called CC=3 SCAR=24.8
Pod documented
151 0 ▶ return undef unless $_metrics;
Branch: 1 branch
BranchTrueFalseTotal
unless $_metrics 0 0 0
152 0 my %m = %$_metrics;
153 0 $m{errors} = { %{ $_metrics->{errors} } };
154 0 my $acc = 0;
155 0 $m{buckets} = { map { $acc += $_metrics->{buckets}[$_];
156 0 ($DBIx::Fast::SQL::BUCKETS[$_] => $acc) }
157 0 .. $#DBIx::Fast::SQL::BUCKETS };
158 0 ▶ if (my $cache = $self->cache) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cache = $self->cache) 0 0 0
159 0 my $st = $cache->stats;
160 0 @m{qw(cache_hits cache_misses)} = @$st{qw(hits misses)};
161 }
162 0 return \%m;
163 35 }
164  
165 # Start the counters again (e.g. after a deploy warm-up).
166 0 ▶ method reset_metrics () { $self->_enable_metrics if $_metrics; return }
Subroutine reset_metrics: not called CC=2 SCAR=15.4
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
if $_metrics 0 0 0
167 35 field $_json_bytes; # same codec in UTF-8 byte mode (see _json_decode_rows)
168  
169 5 ▶ method _configure_json ($spec) {
Subroutine _configure_json: called CC=8 SCAR=21.0
170 5 ▶ $self->Exception("json_columns must be a hashref of table => [columns]")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 1 4 5
171 unless ref $spec eq 'HASH';
172 4 my (%write, %read);
173 4 for my $table (keys %$spec) {
174 5 my $cols = $spec->{$table};
175 5 ▶ $self->Exception("json_columns: '$table' must map to an arrayref of columns")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cols eq "ARRAY" 1 4 5
176 unless ref $cols eq 'ARRAY';
177 4 ▶ $self->TableName($table) unless $table eq '*';
Branch: 1 branch
BranchTrueFalseTotal
unless $table eq "*" 3 1 4
178 4 for my $col (@$cols) {
179 4 $self->_safe_id($col);
180 3 $write{$table}{$col} = 1;
181 3 $read{$col} = 1;
182 }
183 }
184 2 ▶ return unless %read;
Branch: 1 branch
BranchTrueFalseTotal
unless %read 0 2 2
185 2 ($_json_write, $_json_read) = (\%write, \%read);
186 2 %_json_tcols = ();
187 2 $self->_fast_flags;
188 2 my $class = eval { require Cpanel::JSON::XS; 'Cpanel::JSON::XS' }
189 2 ▶ || 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
200
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
190 2 $_json_codec = $class->new->canonical;
191 2 $_json_bytes = $class->new->canonical->utf8;
192 35 }
193  
194 # A copy of $row with hash/array values of the table's JSON columns encoded
195 # (the caller's hash is not modified); $row itself when nothing applies.
196 13 ▶ method _json_encode_row ($table, $row) {
Subroutine _json_encode_row: called CC=10 SCAR=23.5
197 13 ▶ return $row unless $_json_write && ref $row eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $_json_write and ref $row eq "HASH" 0 13 13
Condition33%1/3
$_json_write and ref $row eq "HASH"
!ll&&!rl&&r
0013
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
198 13 ▶ my $cols = $_json_tcols{$table} //= [ keys %{{ %{ $_json_write->{'*'} // {} },
Condition100%4/4
$_json_tcols{$table} //= [keys %{+{%{$_json_write->{"*"} // {};}, %{$_json_write->{$table} // {};}};}]
l!l
112
$_json_write->{"*"} // {}
l!l
11
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
199 2 ▶ %{ $_json_write->{$table} // {} } }} ];
Condition50%1/2
$_json_write->{$table} // {}
l!l
20
MC/DC0%0/1
$_json_write->{$table} // {}
$_json_write->{$table}
Truth table50%1/2
A
A= $_json_write->{$table}
Aresult
11
00
200 13 my @enc = grep { exists $row->{$_} && (ref $row->{$_} eq 'HASH'
201 18 ▶ || ref $row->{$_} eq 'ARRAY') } @$cols;
Condition66%4/6
exists $row->{$_} && (ref $row->{$_} eq 'HASH' || ref $row->{$_} eq 'ARRAY')
!ll&&!rl&&r
1107
ref $row->{$_} eq "HASH" or ref $row->{$_} eq "ARRAY"
l!l&&r!l&&!r
430
MC/DC33%1/3
exists $row->{$_} && (ref $row->{$_} eq 'HASH' || ref $row->{$_} eq 'ARRAY')
exists $row->{$_} ref $row->{$_} eq "HASH" ref $row->{$_} eq "ARRAY"
Truth table75%3/4
A && B or C
A= exists $row->{$_}B= ref $row->{$_} eq "HASH"C= ref $row->{$_} eq "ARRAY"
ABCresult
0XX0
1000
11X1
1011
202 13 ▶ return $row unless @enc;
Branch: 1 branch
BranchTrueFalseTotal
unless @enc 7 6 13
203 6 my %r = %$row;
204 6 $r{$_} = $_json_codec->encode($r{$_}) for @enc;
205 6 return \%r;
206 35 }
207  
208 3 ▶ method _json_encode_rows ($table, $rows) {
Subroutine _json_encode_rows: called CC=2 SCAR=7.0
209 3 ▶ return $rows unless $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
unless $_json_write 0 3 3
210 3 return [ map { $self->_json_encode_row($table, $_) } @$rows ];
211 35 }
212  
213 # Decode the JSON columns of fetched rows in place: only values that look
214 # like a JSON object/array; anything else (or malformed JSON) is left as is.
215 # JSON text is UTF-8: a driver without its UTF-8 flag (SQLite without
216 # sqlite_unicode, DBD::mysql without mysql_enable_utf8mb4) hands back the
217 # raw bytes, which are decoded as UTF-8; already-decoded character strings
218 # (DBD::Pg, DBD::MariaDB) as characters. Non-ASCII then round-trips on
219 # every driver whatever its flags.
220 3 ▶ method _json_decode_rows ($rows) {
Subroutine _json_decode_rows: called CC=13 SCAR=29.4
221 3 ▶ my @rows = ref $rows eq 'HASH' ? ($rows) : @$rows;
Branch: 1 branch
BranchTrueFalseTotal
ref $rows eq 'HASH' ? : 1 2 3
222 # Only the configured columns this result set actually has (all its rows
223 # share the first row's keys) - not every configured name on every row.
224 3 my $first = $rows[0];
225 3 ▶ return $rows unless ref $first eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $first eq "HASH" 0 3 3
226 3 ▶ 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 3 0 3
227 3 for my $row (@rows) {
228 5 ▶ next unless ref $row eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 0 5 5
229 5 for my $col (@cols) {
230 6 my $v = $row->{$col};
231 6 ▶ 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 6 6
Condition33%2/6
defined $v and not ref $v and $v =~ /\A\s*[\[{]/u
!ll&&!rl&&r
006
defined $v and not ref $v
!ll&&!rl&&r
006
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
232 my $d = utf8::is_utf8($v)
233 0 ▶ ? eval { $_json_codec->decode($v) }
Condition33%1/3
eval { do { $_json_bytes->decode($v) } } // eval { do { $_json_codec->decode($v) } }
l!l&&r!l&&!r
600
MC/DC0%0/2
eval { do { $_json_bytes->decode($v) } } // eval { do { $_json_codec->decode($v) } }
eval { do { $_json_bytes->decode($v) } } eval { do { $_json_codec->decode($v) } }
Truth table33%1/3
A // B
A= eval { do { $_json_bytes->decode($v) } }B= eval { do { $_json_codec->decode($v) } }
ABresult
1X1
011
000
234 6 ▶ : eval { $_json_bytes->decode($v) } // eval { $_json_codec->decode($v) };
Branch: 1 branch
BranchTrueFalseTotal
utf8::is_utf8($v) ? : 0 6 6
235 6 ▶ $row->{$col} = $d if defined $d;
Branch: 1 branch
BranchTrueFalseTotal
if defined $d 6 0 6
236 }
237 }
238 3 return $rows;
239 35 }
240  
241 # CRUD statement cache. SQL::Abstract 2 needs 100-175us to render even a
242 # one-column INSERT/UPDATE/DELETE, yet for plain-scalar specs the SQL text
243 # depends only on the table and the (sorted) column names and the binds are
244 # the values in that same sorted order. SQL::Abstract stays the single
245 # source of truth: it renders each shape once, on the first miss.
246 35 field %_crud_sql;
247  
248 108 ▶ method _crud_stmt ($key, $render) {
Subroutine _crud_stmt: called CC=2 SCAR=7.0
249 108 _trim_cache(\%_crud_sql, 1_000); # bound data-driven shapes
250 108 ▶ return $_crud_sql{$key} //= ($render->())[0];
Condition66%2/3
$_crud_sql{$key} //= (&$render())[0]
l!l&&r!l&&!r
09513
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
251 35 }
252  
253 # A WHERE hash the cache can serve: col => defined plain scalar only
254 # (undef means IS NULL, refs are operators - both go through SQL::Abstract).
255 22 ▶ sub _plain_where ($w) {
Subroutine _plain_where: called CC=6 SCAR=18.1
256 22 ▶ return 0 unless ref $w eq 'HASH' && %$w;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $w eq "HASH" and %$w 3 19 22
Condition66%2/3
ref $w eq "HASH" and %$w
!ll&&!rl&&r
3019
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
257 19 ▶ for (values %$w) { return 0 if !defined || ref }
Branch: 1 branch
BranchTrueFalseTotal
if not defined $_ or ref $_ 7 12 19
Condition66%2/3
not defined $_ or ref $_
l!l&&r!l&&!r
0712
MC/DC50%1/2
not defined $_ or ref $_
not defined $_ ref $_
Truth table66%2/3
not(A) or B
A= not defined $_B= ref $_
ABresult
1X1
011
000
258 12 return 1;
259 }
260  
261 127 ▶ method _track ($code) {
Subroutine _track: called CC=8 SCAR=31.2
262 127 ▶ my $tracker = $_tracker && $_tracker->enabled ? $_tracker : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_tracker && $_tracker->enabled ? : 0 127 127
Condition33%1/3
$_tracker and $_tracker->enabled
!ll&&!rl&&r
12700
MC/DC0%0/2
$_tracker and $_tracker->enabled
$_tracker $_tracker->enabled
Truth table33%1/3
A and B
A= $_trackerB= $_tracker->enabled
ABresult
0X0
100
111
263 127 ▶ if ($tracker || $_observe) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tracker or $_observe) 0 127 127
Condition33%1/3
$tracker or $_observe
l!l&&r!l&&!r
00127
MC/DC0%0/2
$tracker or $_observe
$tracker $_observe
Truth table33%1/3
A or B
A= $trackerB= $_observe
ABresult
1X1
011
000
264 0 my $t0 = Time::HiRes::time();
265 0 my $res = $code->();
266 0 my $t1 = Time::HiRes::time();
267 0 ▶ $tracker->add_query($sql, $p // [], $t0, $t1) if $tracker;
Branch: 1 branch
BranchTrueFalseTotal
if $tracker 0 0 0
Condition0%0/2
$p // []
l!l
00
MC/DC0%0/1
$p // []
$p
Truth table0%0/2
A
A= $p
Aresult
11
00
268 0 ▶ $self->_observed($t1 - $t0) if $_observe;
Branch: 1 branch
BranchTrueFalseTotal
if $_observe 0 0 0
269 0 $last_sql = $sql;
270 0 return $res;
271 }
272 127 $last_sql = $sql;
273  
274 127 return $code->();
275 35 }
276  
277 # Statement-handle cache, replacing DBI's prepare_cached (Perl code in
278 # DBI.pm, ~15% of a simple read). Same semantics as its if_active=3 mode: a
279 # cached handle that is still Active (a live query() iterator on the same
280 # SQL) is replaced by a fresh one. Emptied by DBIx::Fast's on_connect hook on
281 # every (re)connect, so a handle never outlives its connection.
282 35 field %_sth_cache;
283 180 ▶ method _reset_sth_cache () { %_sth_cache = (); %_pg_pk = () }
Subroutine _reset_sth_cache: called CC=1 SCAR=0.0
284  
285 436 ▶ method _prepare ($dbh, $stmt) {
Subroutine _prepare: called CC=4 SCAR=13.9
286 436 my $sth = $_sth_cache{$stmt};
287 436 ▶ return $sth if $sth && !$sth->FETCH('Active');
Branch: 1 branch
BranchTrueFalseTotal
if $sth and not $sth->FETCH("Active") 63 373 436
Condition66%2/3
$sth and not $sth->FETCH("Active")
!ll&&!rl&&r
373063
MC/DC50%1/2
$sth and not $sth->FETCH("Active")
$sth not $sth->FETCH("Active")
Truth table66%2/3
A and not(B)
A= $sthB= not $sth->FETCH("Active")
ABresult
0X0
100
111
288 373 ▶ $sth = $dbh->prepare($stmt) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sth = $dbh->prepare($stmt) or return undef 367 2 369
289 367 _trim_cache(\%_sth_cache, 1_000); # bound data-driven SQL
290 367 return $_sth_cache{$stmt} = $sth;
291 35 }
292  
293 # Run the current $sql/$p and shape the result with $shape (one of the
294 # _shape_* subs below, which take the executed handle - or undef when the
295 # prepare failed under RaiseError => 0 - and return the value). Without an
296 # active tracker (the normal case) nothing is allocated per call: no
297 # closure, no extra frame; with one, the query is timed and recorded.
298 134 ▶ method _fetch ($shape) {
Subroutine _fetch: called CC=15 SCAR=28.0
299 # Inline check (this runs on every read): only a statement with an
300 # arrayref bind pays for the IN (?) rewrite.
301 134 ▶ if ($p) { for (@$p) { if (ref $_ eq 'ARRAY') { $self->_expand_in_binds; last } } }
Branch: 2 branches
BranchTrueFalseTotal
if ($p) 134 0 134
if (ref $_ eq "ARRAY") 0 74 74
302 134 my $res;
303 134 ▶ my $tracker = $_tracker && $_tracker->enabled ? $_tracker : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_tracker && $_tracker->enabled ? : 5 129 134
Condition66%2/3
$_tracker and $_tracker->enabled
!ll&&!rl&&r
12905
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
304 134 ▶ if ($tracker || $_observe) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tracker or $_observe) { } 5 129 134
Condition66%2/3
$tracker or $_observe
l!l&&r!l&&!r
50129
MC/DC50%1/2
$tracker or $_observe
$tracker $_observe
Truth table66%2/3
A or B
A= $trackerB= $_observe
ABresult
1X1
011
000
305 5 my $t0 = Time::HiRes::time();
306 5 $res = $shape->($self->_read_exec);
307 5 my $t1 = Time::HiRes::time();
308 5 ▶ $tracker->add_query($sql, $p // [], $t0, $t1) if $tracker;
Branch: 1 branch
BranchTrueFalseTotal
if $tracker 5 0 5
Condition50%1/2
$p // []
l!l
50
MC/DC0%0/1
$p // []
$p
Truth table50%1/2
A
A= $p
Aresult
11
00
309 5 ▶ $self->_observed($t1 - $t0) if $_observe;
Branch: 1 branch
BranchTrueFalseTotal
if $_observe 0 5 5
310 5 $last_sql = $sql;
311 }
312 else {
313 129 $last_sql = $sql;
314 129 $res = $shape->($self->_read_exec);
315 }
316 129 ▶ $self->_json_decode_rows($res)
Branch: 1 branch
BranchTrueFalseTotal
if $_json_read and $shape == \&DBIx::Fast::SQL::_shape_rows || $shape == \&DBIx::Fast::SQL::_shape_hash and $res 3 126 129
Condition88%8/9
$_json_read and $shape == \&DBIx::Fast::SQL::_shape_rows || $shape == \&DBIx::Fast::SQL::_shape_hash and $res
!ll&&!rl&&r
12603
$_json_read and $shape == \&DBIx::Fast::SQL::_shape_rows || $shape == \&DBIx::Fast::SQL::_shape_hash
!ll&&!rl&&r
12423
$shape == \&DBIx::Fast::SQL::_shape_rows or $shape == \&DBIx::Fast::SQL::_shape_hash
l!l&&r!l&&!r
212
MC/DC75%3/4
$_json_read and $shape == \&DBIx::Fast::SQL::_shape_rows || $shape == \&DBIx::Fast::SQL::_shape_hash and $res
$_json_read $shape == \&DBIx::Fast::SQL::_shape_rows $shape == \&DBIx::Fast::SQL::_shape_hash $res
Truth table66%4/6
A and B or C and D
A= $_json_readB= $shape == \&DBIx::Fast::SQL::_shape_rowsC= $shape == \&DBIx::Fast::SQL::_shape_hashD= $res
ABCDresult
0XXX0
100X0
11X00
10100
11X11
10111
317 if $_json_read && ($shape == \&_shape_rows || $shape == \&_shape_hash) && $res;
318 129 return $res;
319 35 }
320  
321 # "IN (?)" with an arrayref bind becomes "IN (?, ?, ?)" with the elements as
322 # binds. Only placeholders inside IN ( ... ) are expanded - an arrayref
323 # elsewhere stays one bind (DBD::Pg arrays, "= ANY(?)") - and placeholders
324 # inside quoted literals/identifiers are not counted. Returns undef for an
325 # empty list ("IN ()" is invalid SQL, and IN (NULL) would make NOT IN match
326 # nothing).
327 0 ▶ sub _expand_in ($stmt, $binds) {
Subroutine _expand_in: not called CC=7 SCAR=40.3
328 0 my ($out, @nb) = ('');
329 0 my $i = 0;
330 0 ▶ while ($stmt =~ m{\G( '(?:[^'\\]|\\.|'')*'
Branch: 1 branch
BranchTrueFalseTotal
if ($stmt =~ /\G( '(?:[^'\\]|\\.|'')*' | "(?:[^"\\]|\\.|"")*" | `[^`]*` | [^'"`?]+ | \? | . )/cgsux) 0 0 0
331 | "(?:[^"\\]|\\.|"")*"
332 | `[^`]*`
333 | [^'"`?]+
334 | \?
335 | . )}gcxs) {
336 0 my $tok = $1;
337 0 ▶ if ($tok ne '?') { $out .= $tok; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($tok ne "?") 0 0 0
338 0 my $v = $binds->[$i++];
339 0 ▶ if (ref $v eq 'ARRAY' && $out =~ /\bIN\s*\(\s*\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq 'ARRAY' and $out =~ /\bIN\s*\(\s*\z/iu) { } 0 0 0
Condition0%0/3
ref $v eq "ARRAY" and $out =~ /\bIN\s*\(\s*\z/iu
!ll&&!rl&&r
000
MC/DC0%0/2
ref $v eq "ARRAY" and $out =~ /\bIN\s*\(\s*\z/iu
ref $v eq "ARRAY" $out =~ /\bIN\s*\(\s*\z/iu
Truth table0%0/3
A and B
A= ref $v eq "ARRAY"B= $out =~ /\bIN\s*\(\s*\z/iu
ABresult
0X0
100
111
340 0 ▶ return undef unless @$v;
Branch: 1 branch
BranchTrueFalseTotal
unless @$v 0 0 0
341 0 $out .= join(', ', ('?') x @$v);
342 0 push @nb, @$v;
343 }
344 else {
345 0 $out .= '?';
346 0 push @nb, $v;
347 }
348 }
349 0 ▶ push @nb, @{$binds}[ $i .. $#$binds ] if $i < @$binds; # arity left to DBI
Branch: 1 branch
BranchTrueFalseTotal
if $i < @$binds 0 0 0
350 0 return ($out, \@nb);
351 }
352  
353  
354 # Apply _expand_in to the current statement when any bind is an arrayref.
355 0 ▶ method _expand_in_binds () {
Subroutine _expand_in_binds: not called CC=2 SCAR=17.9
356 0 my ($stmt, $binds) = _expand_in($sql, $p);
357 0 ▶ $self->Exception("IN (?) bound to an empty list") unless defined $stmt;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $stmt 0 0 0
358 0 ($sql, $p) = ($stmt, $binds);
359 35 }
360  
361 # The hashes fetchall_arrayref({}) builds (FetchHashKeyName honoured, a
362 # later duplicate column wins), but the rows come from the driver's C
363 # fetchall and each hash is one slice: +15-20% on 10 rows (MariaDB, Pg,
364 # SQLite). A statement without result columns keeps the DBI path.
365 29 ▶ sub _shape_rows ($sth) {
Subroutine _shape_rows: called CC=4 SCAR=14.7
366 29 ▶ return [] unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 1 28 29
367 28 ▶ my $names = $sth->FETCH($sth->FETCH('FetchHashKeyName') || 'NAME');
Condition50%1/2
$sth->FETCH('FetchHashKeyName') || 'NAME'
l!l
280
MC/DC0%0/1
$sth->FETCH('FetchHashKeyName') || 'NAME'
$sth->FETCH('FetchHashKeyName')
Truth table50%1/2
A
A= $sth->FETCH('FetchHashKeyName')
Aresult
11
00
368 28 ▶ unless ($names) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($names) 0 28 28
369 0 my $rows = $sth->fetchall_arrayref({});
370 0 $sth->finish;
371 0 return $rows;
372 }
373 28 my $all = $sth->fetchall_arrayref;
374 28 $sth->finish;
375 28 return [ map { my %h; @h{@$names} = @$_; \%h } @$all ];
376 }
377  
378 27 ▶ sub _shape_hash ($sth) {
Subroutine _shape_hash: called CC=2 SCAR=7.0
379 27 ▶ return undef unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 27 27
380 27 my $row = $sth->fetchrow_hashref;
381 27 $sth->finish;
382 27 return $row;
383 }
384  
385 # First column of first row - the historical val() contract (DBI leaves a
386 # multi-column scalar selectrow_array undefined; pin FIRST so val() never
387 # changes value between builds). Also count()'s shape.
388 71 ▶ sub _shape_val ($sth) {
Subroutine _shape_val: called CC=2 SCAR=7.0
389 71 ▶ return undef unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 71 71
390 71 my ($first) = $sth->fetchrow_array;
391 71 $sth->finish;
392 71 return $first;
393 }
394  
395 # fetchall_arrayref([0]) loops in DBI's C path - much faster than a per-row
396 # Perl fetch on large result sets.
397 5 ▶ sub _shape_column ($sth) {
Subroutine _shape_column: called CC=2 SCAR=7.0
398 5 ▶ return [] unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 5 5
399 5 my $col = $sth->fetchall_arrayref([0]);
400 5 $sth->finish;
401 5 return [ map { $_->[0] } @$col ];
402 }
403  
404 0 ▶ sub _shape_exists ($sth) {
Subroutine _shape_exists: not called CC=3 SCAR=24.8
405 0 ▶ return 0 unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 0 0
406 0 my ($one) = $sth->fetchrow_array;
407 0 $sth->finish;
408 0 ▶ return $one ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$one ? : 0 0 0
409 }
410  
411 6 ▶ sub _shape_kv ($sth) {
Subroutine _shape_kv: called CC=3 SCAR=11.3
412 6 ▶ return {} unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 6 6
413 6 ▶ my $pair = $sth->fetchall_arrayref([0, 1]) // [];
Condition50%1/2
$sth->fetchall_arrayref([0, 1]) // []
l!l
60
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
414 6 $sth->finish;
415 6 return { map { $_->[0] => $_->[1] } @$pair };
416 }
417  
418 0 ▶ sub _shape_sth ($sth) { $sth }
Subroutine _shape_sth: not called CC=1 SCAR=6.9
419  
420 # Prepare (through the statement cache) + execute of the current $sql/$p for
421 # the read methods. With strict_reads a failed prepare/execute throws;
422 # otherwise the historical behaviour stands (HandleError records the error
423 # and the read returns an empty result). Returns undef when the prepare
424 # itself failed (SQLite/Pg reject bad SQL at prepare time; MariaDB only at
425 # execute), and each shape maps that to the same empty value MariaDB gives.
426 134 ▶ method _read_exec () {
Subroutine _read_exec: called CC=6 SCAR=18.2
427 134 my $dbh = $self->db->dbh;
428 134 my $sth = $self->_prepare($dbh, $sql);
429 131 ▶ unless ($sth) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 2 129 131
430 2 ▶ $self->_read_failed($dbh) if $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if $self->strict_reads 1 1 2
431 1 return undef;
432 }
433 129 ▶ my $rv = $p ? $sth->execute(@{$p}) : $sth->execute;
Branch: 1 branch
BranchTrueFalseTotal
$p ? : 129 0 129
434 128 ▶ $self->_read_failed($sth) unless $rv || !$self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
unless $rv or not $self->strict_reads 0 128 128
Condition33%1/3
$rv or not $self->strict_reads
l!l&&r!l&&!r
12800
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
435 128 return $sth;
436 35 }
437  
438 1 ▶ method _read_failed ($h) {
Subroutine _read_failed: called CC=1 SCAR=0.0
439 # HandleError has already recorded the driver error; the text appends it.
440 1 $self->_db_fail("read failed", $h);
441 35 }
442  
443 # $sth->rows normalized: DBI's '0E0' -> 0, unknown (-1) -> undef.
444 # Rows affected by a write: execute()'s return value (DBI's contract: the
445 # count, '0E0' for none, -1 unknown), falling back to $sth->rows. The return
446 # value is the reliable one - DBD::Pg reports rows() -1 (or a stale count on
447 # a reused handle) after INSERT ... ON CONFLICT DO NOTHING.
448 294 ▶ sub _affected ($sth, $rv = undef) {
Subroutine _affected: called CC=7 SCAR=26.7
449 294 ▶ my $n = defined $rv && $rv >= 0 ? $rv : $sth ? $sth->rows : undef;
Branch: 2 branches
BranchTrueFalseTotal
defined $rv && $rv >= 0 ? : 294 0 294
$sth ? : 0 0 0
Condition33%1/3
defined $rv and $rv >= 0
!ll&&!rl&&r
00294
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
450 294 ▶ return defined $n && $n >= 0 ? $n + 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $n && $n >= 0 ? : 294 0 294
Condition33%1/3
defined $n and $n >= 0
!ll&&!rl&&r
00294
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
451 }
452  
453 1 ▶ method q ($stmt, @params) {
Subroutine q: called CC=1 SCAR=0.0
Pod documented
454 1 $sql = $stmt;
455 1 $p = \@params;
456 35 }
457  
458 33 ▶ method all (@args) {
Subroutine all: called CC=10 SCAR=23.4
Pod documented
459 33 $sql = shift @args;
460 33 $p = \@args;
461  
462 # Fast path: the cached, idle statement handle executed directly, without
463 # the _fetch/_read_exec/_prepare layers - same result and errors (dbh()
464 # still runs first: fork/reconnect checks, and a reconnect empties the
465 # cache; a failed execute goes through _read_failed as in _read_exec).
466 # Kept inline (no helper call) on purpose: this is the hottest code.
467 33 ▶ if ($_fast_rows && defined $sql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_fast_rows and defined $sql) 28 5 33
Condition66%2/3
$_fast_rows and defined $sql
!ll&&!rl&&r
5028
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
468 FAST: {
469 28 ▶ for (@args) { last FAST if ref $_ eq 'ARRAY' } # IN (?) lists
Branch: 1 branch
BranchTrueFalseTotal
if ref $_ eq "ARRAY" 0 6 6
470 28 $self->db->dbh;
471 28 my $sth = $_sth_cache{$sql};
472 28 ▶ last FAST if !$sth || $sth->FETCH('Active');
Branch: 1 branch
BranchTrueFalseTotal
if not $sth or $sth->FETCH("Active") 19 9 28
Condition66%2/3
not $sth or $sth->FETCH("Active")
l!l&&r!l&&!r
1909
MC/DC50%1/2
not $sth or $sth->FETCH("Active")
not $sth $sth->FETCH("Active")
Truth table66%2/3
not(A) or B
A= not $sthB= $sth->FETCH("Active")
ABresult
1X1
011
000
473 9 $last_sql = $sql;
474 9 ▶ my $rv = @args ? $sth->execute(@args) : $sth->execute;
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 2 7 9
475 9 ▶ $self->_read_failed($sth) if !$rv && $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if not $rv and $self->strict_reads 0 9 9
Condition33%1/3
not $rv and $self->strict_reads
!ll&&!rl&&r
900
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
476 9 return $results = _shape_rows($sth);
477 }
478 }
479 24 return $results = $self->_fetch(\&_shape_rows);
480 35 }
481  
482 1 ▶ method flat (@args) {
Subroutine flat: called CC=1 SCAR=0.0
Pod documented
483 1 $sql = shift @args;
484 1 $p = \@args;
485  
486 1 $results = $self->_fetch(\&_shape_column);
487 1 return @$results;
488 35 }
489  
490 62 ▶ method hash (@args) {
Subroutine hash: called CC=10 SCAR=23.6
Pod documented
491 62 $sql = shift @args;
492 62 $p = \@args;
493  
494 # Fast path: the cached, idle statement handle executed directly, without
495 # the _fetch/_read_exec/_prepare layers - same result and errors (dbh()
496 # still runs first: fork/reconnect checks, and a reconnect empties the
497 # cache; a failed execute goes through _read_failed as in _read_exec).
498 # Kept inline (no helper call) on purpose: this is the hottest code.
499 62 ▶ if ($_fast_rows && defined $sql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_fast_rows and defined $sql) 60 2 62
Condition66%2/3
$_fast_rows and defined $sql
!ll&&!rl&&r
2060
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
500 FAST: {
501 60 ▶ for (@args) { last FAST if ref $_ eq 'ARRAY' } # IN (?) lists
Branch: 1 branch
BranchTrueFalseTotal
if ref $_ eq "ARRAY" 0 58 58
502 60 $self->db->dbh;
503 60 my $sth = $_sth_cache{$sql};
504 60 ▶ last FAST if !$sth || $sth->FETCH('Active');
Branch: 1 branch
BranchTrueFalseTotal
if not $sth or $sth->FETCH("Active") 25 35 60
Condition66%2/3
not $sth or $sth->FETCH("Active")
l!l&&r!l&&!r
25035
MC/DC50%1/2
not $sth or $sth->FETCH("Active")
not $sth $sth->FETCH("Active")
Truth table66%2/3
not(A) or B
A= not $sthB= $sth->FETCH("Active")
ABresult
1X1
011
000
505 35 $last_sql = $sql;
506 35 ▶ my $rv = @args ? $sth->execute(@args) : $sth->execute;
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 35 0 35
507 35 ▶ $self->_read_failed($sth) if !$rv && $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if not $rv and $self->strict_reads 0 35 35
Condition33%1/3
not $rv and $self->strict_reads
!ll&&!rl&&r
3500
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
508 35 my $row = $sth->fetchrow_hashref;
509 35 $sth->finish;
510 35 return $results = $row;
511 }
512 }
513 27 return $results = $self->_fetch(\&_shape_hash);
514 35 }
515  
516 63 ▶ method val (@args) {
Subroutine val: called CC=10 SCAR=23.4
Pod documented
517 63 $sql = shift @args;
518 63 $p = \@args;
519  
520 # Fast path: the cached, idle statement handle executed directly, without
521 # the _fetch/_read_exec/_prepare layers - same result and errors (dbh()
522 # still runs first: fork/reconnect checks, and a reconnect empties the
523 # cache; a failed execute goes through _read_failed as in _read_exec).
524 # Kept inline (no helper call) on purpose: this is the hottest code.
525 63 ▶ if ($_fast && defined $sql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_fast and defined $sql) 62 1 63
Condition66%2/3
$_fast and defined $sql
!ll&&!rl&&r
1062
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
526 FAST: {
527 62 ▶ for (@args) { last FAST if ref $_ eq 'ARRAY' } # IN (?) lists
Branch: 1 branch
BranchTrueFalseTotal
if ref $_ eq "ARRAY" 0 41 41
528 62 $self->db->dbh;
529 62 my $sth = $_sth_cache{$sql};
530 62 ▶ last FAST if !$sth || $sth->FETCH('Active');
Branch: 1 branch
BranchTrueFalseTotal
if not $sth or $sth->FETCH("Active") 45 17 62
Condition66%2/3
not $sth or $sth->FETCH("Active")
l!l&&r!l&&!r
45017
MC/DC50%1/2
not $sth or $sth->FETCH("Active")
not $sth $sth->FETCH("Active")
Truth table66%2/3
not(A) or B
A= not $sthB= $sth->FETCH("Active")
ABresult
1X1
011
000
531 17 $last_sql = $sql;
532 17 ▶ my $rv = @args ? $sth->execute(@args) : $sth->execute;
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 14 3 17
533 17 ▶ $self->_read_failed($sth) if !$rv && $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if not $rv and $self->strict_reads 0 17 17
Condition33%1/3
not $rv and $self->strict_reads
!ll&&!rl&&r
1700
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
534 17 my ($first) = $sth->fetchrow_array;
535 17 $sth->finish;
536 17 return $results = $first;
537 }
538 }
539 46 return $results = $self->_fetch(\&_shape_val);
540 35 }
541  
542 4 ▶ method array (@args) {
Subroutine array: called CC=1 SCAR=0.0
Pod documented
543 4 $sql = shift @args;
544 4 $p = \@args;
545  
546 4 return $results = $self->_fetch(\&_shape_column);
547 35 }
548  
549 0 ▶ method query ($stmt, @params) {
Subroutine query: not called CC=1 SCAR=6.9
Pod documented
550 0 $sql = $stmt;
551 0 $p = \@params;
552  
553 0 return DBIx::Fast::Result->new(sth => $self->_fetch(\&_shape_sth));
554 35 }
555  
556 # query() for big result sets: rows come from the server as they are read
557 # instead of being loaded into client memory first. MariaDB/MySQL fetch with
558 # use_result (the connection cannot run another statement until the
559 # iterator is drained or finished); SQLite streams natively; DBD::Pg always
560 # buffers (a server-side cursor would be needed), so there it behaves like
561 # query(). Not statement-cached: the handle carries the streaming attribute.
562 0 ▶ method stream ($stmt, @params) {
Subroutine stream: not called CC=12 SCAR=50.5
Pod documented
563 0 $sql = $stmt;
564 0 $p = \@params;
565 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
566  
567 0 my $dbd = $self->dbd;
568 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
569 : $dbd eq 'mysql' ? { mysql_use_result => 1 }
570 : {};
571 0 my $dbh = $self->db->dbh;
572  
573 0 ▶ my $run = sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
574 0 my $sth = $dbh->prepare($sql, $attr);
575 0 ▶ unless ($sth) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 0 0 0
576 0 ▶ $self->_read_failed($dbh) if $self->strict_reads;
Branch: 1 branch
BranchTrueFalseTotal
if $self->strict_reads 0 0 0
577 0 return undef;
578 }
579 0 ▶ my $rv = @$p ? $sth->execute(@$p) : $sth->execute;
Branch: 1 branch
BranchTrueFalseTotal
@$p ? : 0 0 0
580 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
581 0 return $sth;
582 0 };
583  
584 0 my $sth;
585 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
586 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
587 0 my $t0 = Time::HiRes::time();
588 0 $sth = $run->();
589 0 my $t1 = Time::HiRes::time();
590 0 ▶ $tracker->add_query($sql, $p, $t0, $t1) if $tracker;
Branch: 1 branch
BranchTrueFalseTotal
if $tracker 0 0 0
591 0 ▶ $self->_observed($t1 - $t0) if $_observe;
Branch: 1 branch
BranchTrueFalseTotal
if $_observe 0 0 0
592 }
593 else {
594 0 $sth = $run->();
595 }
596 0 $last_sql = $sql;
597 0 return DBIx::Fast::Result->new(sth => $sth);
598 35 }
599  
600 36 ▶ method count ($table_name, $skeel = undef) {
Subroutine count: called CC=4 SCAR=13.9
Pod documented
601 36 my $table = $self->TableName($table_name);
602 34 my $qtable = $self->_quote_ident_path($table);
603  
604 34 $sql = "SELECT COUNT(*) FROM $qtable";
605 34 $p = [];
606  
607 34 ▶ if ($skeel) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skeel) 26 8 34
608 26 my ($parts, $params) = $self->_where_parts($skeel);
609 18 ▶ $sql .= ' WHERE ' . join(' AND ', @$parts) if @$parts;
Branch: 1 branch
BranchTrueFalseTotal
if @$parts 18 0 18
610 18 $p = $params;
611 }
612  
613 26 return $results = $self->_fetch(\&_shape_val);
614 35 }
615  
616 # 1 if at least one row of $table matches the count()-style WHERE, else 0.
617 # Same validation as count() (TableName + _make_where whitelist); LIMIT 1
618 # lets the server stop at the first match.
619 0 ▶ method exists ($table_name, $skeel = undef) {
Subroutine exists: not called CC=4 SCAR=30.0
Pod documented
620 0 my $table = $self->TableName($table_name);
621 0 my $qtable = $self->_quote_ident_path($table);
622  
623 0 $sql = "SELECT 1 FROM $qtable";
624 0 $p = [];
625  
626 0 ▶ if ($skeel) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skeel) 0 0 0
627 0 my ($parts, $params) = $self->_where_parts($skeel);
628 0 ▶ $sql .= ' WHERE ' . join(' AND ', @$parts) if @$parts;
Branch: 1 branch
BranchTrueFalseTotal
if @$parts 0 0 0
629 0 $p = $params;
630 }
631 0 $sql .= ' LIMIT 1';
632  
633 0 return $results = $self->_fetch(\&_shape_exists);
634 35 }
635  
636 # First column => second column, as a hashref (a later duplicate key wins).
637 6 ▶ method kv (@args) {
Subroutine kv: called CC=1 SCAR=0.0
Pod documented
638 6 $sql = shift @args;
639 6 $p = \@args;
640  
641 6 return $results = $self->_fetch(\&_shape_kv);
642 35 }
643  
644 # Rows keyed by the $key column, as a hashref of hashrefs (DBI's
645 # fetchall_hashref: a later row with the same key wins).
646 0 ▶ method all_by ($key, @args) {
Subroutine all_by: not called CC=3 SCAR=24.8
Pod documented
647 0 ▶ $self->Exception("all_by: key column required")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and length $key 0 0 0
Condition0%0/3
defined $key and length $key
!ll&&!rl&&r
000
MC/DC0%0/2
defined $key and length $key
defined $key length $key
Truth table0%0/3
A and B
A= defined $keyB= length $key
ABresult
0X0
100
111
648 unless defined $key && length $key;
649  
650 0 $sql = shift @args;
651 0 $p = \@args;
652  
653 0 ▶ $results = $self->_track(sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
654 0 ▶ my $sth = $self->_read_exec or return {};
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->_read_exec or return {} 0 0 0
655 0 ▶ return $sth->fetchall_hashref($key) // {};
Condition0%0/2
$sth->fetchall_hashref($key) // {}
l!l
00
MC/DC0%0/1
$sth->fetchall_hashref($key) // {}
$sth->fetchall_hashref($key)
Truth table0%0/2
A
A= $sth->fetchall_hashref($key)
Aresult
11
00
656 0 });
657 0 return $results;
658 35 }
659  
660 0 ▶ method _make_where ($skeel) {
Subroutine _make_where: not called CC=2 SCAR=17.9
661 0 my ($parts, $params) = $self->_where_parts($skeel);
662 0 ▶ $sql .= ' WHERE ' . join(' AND ', @$parts) if @$parts;
Branch: 1 branch
BranchTrueFalseTotal
if @$parts 0 0 0
663 0 $p = $params;
664 35 }
665  
666 # The count()/exists()/where() condition builder: ($parts, $binds) for a
667 # { column => condition } hashref, without touching the statement state.
668 # Operators are whitelisted; columns validated and quoted per segment.
669 47 ▶ method _where_parts ($skeel) {
Subroutine _where_parts: called CC=25 SCAR=33.6
670 47 state %VALID_OPS = map { $_ => 1 }
671 ('=', '!=', '<>', '<', '<=', '>', '>=', 'LIKE', 'NOT', 'BETWEEN', 'IS',
672 'IN', 'NOT IN', 'CONTAINS', 'PREFIX', 'SUFFIX');
673 47 state %LIKE_MODE = (CONTAINS => 'contains', PREFIX => 'prefix',
674 SUFFIX => 'suffix');
675  
676 47 my @params;
677 my @parts;
678  
679 47 for my $K (sort keys %{$skeel}) {
680 # Validate AND quote the column by segment, so a qualified name like
681 # "t.col" becomes "t"."col" (not the bogus single identifier "t.col").
682 47 my $col = $self->_quote_ident_path($K);
683  
684 47 my $val = $skeel->{$K};
685  
686 # Fast path for the common case: col => defined plain value.
687 47 ▶ if (defined $val && !ref $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val and not ref $val) 26 21 47
Condition100%3/3
defined $val and not ref $val
!ll&&!rl&&r
12026
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
688 26 push @parts, "$col = ?";
689 26 push @params, $val;
690 26 next;
691 }
692  
693 21 ▶ my $op = ref $val eq 'ARRAY' ? 'IN' : '='; # [ ... ] means IN (...)
Branch: 1 branch
BranchTrueFalseTotal
ref $val eq 'ARRAY' ? : 1 20 21
694  
695 21 ▶ if (ref $val eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq "HASH") 19 2 21
696 19 ▶ $self->Exception("Multiple operators for column $K")
Branch: 1 branch
BranchTrueFalseTotal
if keys %$val > 1 1 18 19
697 if keys %$val > 1;
698 18 ($op) = keys %$val;
699 $self->Exception("Invalid operator: $op")
700 18 ▶ unless $VALID_OPS{uc $op};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_OPS{uc $op} 5 13 18
701 13 $val = $val->{$op};
702 13 $op = uc $op;
703 }
704  
705 15 ▶ if ($op eq 'IN' || $op eq 'NOT IN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IN" or $op eq "NOT IN") 3 12 15
Condition66%2/3
$op eq "IN" or $op eq "NOT IN"
l!l&&r!l&&!r
3012
MC/DC50%1/2
$op eq "IN" or $op eq "NOT IN"
$op eq "IN" $op eq "NOT IN"
Truth table66%2/3
A or B
A= $op eq "IN"B= $op eq "NOT IN"
ABresult
1X1
011
000
706 3 ▶ $self->Exception("$op requires an arrayref of values")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val eq "ARRAY" 1 2 3
707 unless ref $val eq 'ARRAY';
708 2 ▶ $self->Exception("$op with an empty list for column $K")
Branch: 1 branch
BranchTrueFalseTotal
unless @$val 1 1 2
709 unless @$val;
710 1 push @parts, "$col $op (" . join(', ', ('?') x @$val) . ')';
711 1 push @params, @$val;
712 1 next;
713 }
714  
715 12 ▶ if (my $mode = $LIKE_MODE{$op}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $mode = $LIKE_MODE{$op}) 0 12 12
716 # Escaped user text, never a pattern: see like().
717 0 ▶ $self->Exception("$op requires a value") unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 0 0
718 0 push @parts, "$col LIKE ? ESCAPE '!'";
719 0 push @params, $self->like($val, $mode);
720 0 next;
721 }
722  
723 12 ▶ if ($op eq 'BETWEEN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "BETWEEN") 1 11 12
724 1 ▶ $self->Exception("BETWEEN requires a two-element arrayref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val eq "ARRAY" and @$val == 2 0 1 1
Condition33%1/3
ref $val eq "ARRAY" and @$val == 2
!ll&&!rl&&r
001
MC/DC0%0/2
ref $val eq "ARRAY" and @$val == 2
ref $val eq "ARRAY" @$val == 2
Truth table33%1/3
A and B
A= ref $val eq "ARRAY"B= @$val == 2
ABresult
0X0
100
111
725 unless ref $val eq 'ARRAY' && @$val == 2;
726 1 push @parts, "$col BETWEEN ? AND ?";
727 1 push @params, @$val;
728 1 next;
729 }
730  
731 11 ▶ if ($op eq 'IS') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IS") 1 10 11
732 1 ▶ $self->Exception("IS only accepts undef (IS NULL); "
Branch: 1 branch
BranchTrueFalseTotal
if defined $val 0 1 1
733 . "use { '!=' => undef } for IS NOT NULL")
734 if defined $val;
735 1 push @parts, "$col IS NULL";
736 1 next;
737 }
738  
739 # An undef operand collapses to NULL semantics: "col = NULL" / "col != NULL"
740 # are never true in SQL, so emit IS [NOT] NULL with no bind value.
741 10 ▶ if (!defined $val) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $val) 2 8 10
742 2 ▶ if ($op eq '=') {
Branch: 2 branches
BranchTrueFalseTotal
if ($op eq '=') { } 1 1 2
elsif ($op eq '!=' or $op eq '<>' or $op eq 'NOT') { } 1 0 1
743 1 push @parts, "$col IS NULL";
744 }
745 ▶ elsif ($op eq '!=' || $op eq '<>' || $op eq 'NOT') {
Condition33%2/6
$op eq "!=" or $op eq "<>" or $op eq "NOT"
l!l&&r!l&&!r
100
$op eq "!=" or $op eq "<>"
l!l&&r!l&&!r
100
MC/DC0%0/3
$op eq "!=" or $op eq "<>" or $op eq "NOT"
$op eq "!=" $op eq "<>" $op eq "NOT"
Truth table25%1/4
A or B or C
A= $op eq "!="B= $op eq "<>"C= $op eq "NOT"
ABCresult
1XX1
01X1
0011
0000
746 1 push @parts, "$col IS NOT NULL";
747 }
748 else {
749 0 $self->Exception("Operator '$op' does not accept an undef value");
750 }
751 2 next;
752 }
753  
754 # NOT on its own maps to <> for portability.
755 8 ▶ my $sql_op = $op eq 'NOT' ? '<>' : $op;
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'NOT' ? : 0 8 8
756 8 push @parts, "$col $sql_op ?";
757 8 push @params, $val;
758 }
759  
760 39 return (\@parts, \@params);
761 35 }
762  
763 # ('WHERE ...', @binds) for a { column => condition } filter, ready to
764 # append to hand-written SQL. Filters whose value is undef are SKIPPED (an
765 # absent form field means "do not filter"); ask for NULL explicitly with
766 # { col => { IS => undef } }. Same operators as count(), plus IN/NOT IN
767 # (an arrayref value is IN) and CONTAINS/PREFIX/SUFFIX (escaped LIKE).
768 # Returns ('') with no binds when nothing is left to filter on.
769 0 ▶ method where ($filters = {}) {
Subroutine where: not called CC=4 SCAR=30.0
Pod documented
770 0 ▶ $self->Exception("where: filters must be a hashref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $filters eq "HASH" 0 0 0
771 unless ref $filters eq 'HASH';
772 0 my %active = map { $_ => $filters->{$_} }
773 0 grep { defined $filters->{$_} } keys %$filters;
774 0 my ($parts, $params) = $self->_where_parts(\%active);
775 0 ▶ return ('') unless @$parts;
Branch: 1 branch
BranchTrueFalseTotal
unless @$parts 0 0 0
776 0 return ('WHERE ' . join(' AND ', @$parts), @$params);
777 35 }
778  
779 # A LIKE pattern from user text: %, _ and the escape character itself are
780 # escaped with '!', so the text matches literally. Use it as
781 # "col LIKE ? ESCAPE '!'" - '!' (unlike backslash) needs no special
782 # handling in SQLite, MariaDB/MySQL or PostgreSQL.
783 0 ▶ method like ($value, $mode = 'contains') {
Subroutine like: not called CC=7 SCAR=40.3
Pod documented
784 0 state %OK = map { $_ => 1 } qw(contains prefix suffix exact);
785 $self->Exception("like: mode must be contains, prefix, suffix or exact")
786 0 ▶ unless $OK{$mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $OK{$mode} 0 0 0
787 0 ▶ (my $v = $value // '') =~ s/([!%_])/!$1/g;
Condition0%0/2
$value // ""
l!l
00
MC/DC0%0/1
$value // ""
$value
Truth table0%0/2
A
A= $value
Aresult
11
00
788 0 ▶ return $mode eq 'prefix' ? "$v%"
Branch: 3 branches
BranchTrueFalseTotal
$mode eq 'prefix' ? : 0 0 0
$mode eq 'suffix' ? : 0 0 0
$mode eq 'exact' ? : 0 0 0
789 : $mode eq 'suffix' ? "%$v"
790 : $mode eq 'exact' ? $v
791 : "%$v%";
792 35 }
793  
794 # Run $code once per slice of at most $size elements of @$list (each slice
795 # an arrayref, e.g. for "... IN (?)"), returning the callbacks' results in
796 # order. For lists too long for one statement (max_allowed_packet, bind
797 # limits).
798 0 ▶ method in_chunks ($list, $size, $code) {
Subroutine in_chunks: not called CC=7 SCAR=40.3
Pod documented
799 0 ▶ $self->Exception("in_chunks: list arrayref, positive size and coderef required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" and defined $size and $size =~ /\A[1-9]\d*\z/u and ref $code eq "CODE" 0 0 0
Condition0%0/9
ref $list eq "ARRAY" and defined $size and $size =~ /\A[1-9]\d*\z/u and ref $code eq "CODE"
!ll&&!rl&&r
000
ref $list eq "ARRAY" and defined $size and $size =~ /\A[1-9]\d*\z/u
!ll&&!rl&&r
000
ref $list eq "ARRAY" and defined $size
!ll&&!rl&&r
000
MC/DC0%0/4
ref $list eq "ARRAY" and defined $size and $size =~ /\A[1-9]\d*\z/u and ref $code eq "CODE"
ref $list eq "ARRAY" defined $size $size =~ /\A[1-9]\d*\z/u ref $code eq "CODE"
Truth table0%0/5
A and B and C and D
A= ref $list eq "ARRAY"B= defined $sizeC= $size =~ /\A[1-9]\d*\z/uD= ref $code eq "CODE"
ABCDresult
0XXX0
10XX0
110X0
11100
11111
800 unless ref $list eq 'ARRAY' && defined $size && $size =~ /\A[1-9]\d*\z/
801 && ref $code eq 'CODE';
802 0 my @out;
803 0 ▶ for (my $i = 0; $i < @$list; $i += $size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$list) 0 0 0
804 0 my $end = $i + $size - 1;
805 0 ▶ $end = $#$list if $end > $#$list;
Branch: 1 branch
BranchTrueFalseTotal
if $end > $list->$#* 0 0 0
806 0 push @out, $code->([ @{$list}[ $i .. $end ] ]);
807 }
808 0 return @out;
809 35 }
810  
811 # One page of $stmt: { rows, total, page, per, pages }. total comes from
812 # COUNT(*) over the statement; ORDER BY only accepts columns listed in
813 # allowed_order ("col", "col DESC" or "-col"), quoted; LIMIT/OFFSET are
814 # validated integers (not binds - client-side prepares would quote them).
815 # $stmt must not carry its own ORDER BY / LIMIT when these are used.
816 0 ▶ method page ($stmt, $binds = [], %o) {
Subroutine page: not called CC=21 SCAR=61.4
Pod documented
817 0 ▶ $self->Exception("page: binds must be an arrayref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $binds eq "ARRAY" 0 0 0
818 unless ref $binds eq 'ARRAY';
819 0 ▶ my $max_per = $o{max_per} // 1000;
Condition0%0/2
$o{"max_per"} // 1000
l!l
00
MC/DC0%0/1
$o{"max_per"} // 1000
$o{"max_per"}
Truth table0%0/2
A
A= $o{"max_per"}
Aresult
11
00
820 0 ▶ my $page = $o{page} // 1;
Condition0%0/2
$o{"page"} // 1
l!l
00
MC/DC0%0/1
$o{"page"} // 1
$o{"page"}
Truth table0%0/2
A
A= $o{"page"}
Aresult
11
00
821 0 ▶ my $per = $o{per} // 20;
Condition0%0/2
$o{"per"} // 20
l!l
00
MC/DC0%0/1
$o{"per"} // 20
$o{"per"}
Truth table0%0/2
A
A= $o{"per"}
Aresult
11
00
822 0 for ([ page => $page ], [ per => $per ]) {
823 0 ▶ $self->Exception("page: $_->[0] must be a positive integer")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_->[1] and $_->[1] =~ /\A[1-9]\d*\z/u 0 0 0
Condition0%0/3
defined $_->[1] and $_->[1] =~ /\A[1-9]\d*\z/u
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_->[1] and $_->[1] =~ /\A[1-9]\d*\z/u
defined $_->[1] $_->[1] =~ /\A[1-9]\d*\z/u
Truth table0%0/3
A and B
A= defined $_->[1]B= $_->[1] =~ /\A[1-9]\d*\z/u
ABresult
0X0
100
111
824 unless defined $_->[1] && $_->[1] =~ /\A[1-9]\d*\z/;
825 }
826 0 ▶ $self->Exception("page: per exceeds max_per ($max_per)") if $per > $max_per;
Branch: 1 branch
BranchTrueFalseTotal
if $per > $max_per 0 0 0
827  
828 0 my $order = '';
829 0 ▶ if (defined $o{order} && length $o{order}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $o{"order"} and length $o{"order"}) 0 0 0
Condition0%0/3
defined $o{"order"} and length $o{"order"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $o{"order"} and length $o{"order"}
defined $o{"order"} length $o{"order"}
Truth table0%0/3
A and B
A= defined $o{"order"}B= length $o{"order"}
ABresult
0X0
100
111
830 0 ▶ my %allowed = map { $_ => 1 } @{ $o{allowed_order} // [] };
Condition0%0/2
$o{"allowed_order"} // []
l!l
00
MC/DC0%0/1
$o{"allowed_order"} // []
$o{"allowed_order"}
Truth table0%0/2
A
A= $o{"allowed_order"}
Aresult
11
00
831 0 my @terms;
832 0 ▶ for my $term (ref $o{order} eq 'ARRAY' ? @{ $o{order} } : $o{order}) {
Branch: 1 branch
BranchTrueFalseTotal
ref $o{'order'} eq 'ARRAY' ? : 0 0 0
833 0 ▶ my ($minus, $col, $dir) =
Branch: 1 branch
BranchTrueFalseTotal
() = $term =~ /\A\s*(-)?([A-Za-z_][\w.]*)(?:\s+(ASC|DESC))?\s*\z/iu or $self->Exception("page: invalid order term") 0 0 0
834 $term =~ /\A\s*(-)?([A-Za-z_][\w.]*)(?:\s+(ASC|DESC))?\s*\z/i
835 or $self->Exception("page: invalid order term");
836 $self->Exception("page: ordering by '$col' is not allowed")
837 0 ▶ unless $allowed{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $allowed{$col} 0 0 0
838 0 ▶ $dir = $minus ? 'DESC' : uc($dir // 'ASC');
Branch: 1 branch
BranchTrueFalseTotal
$minus ? : 0 0 0
Condition0%0/2
$dir // "ASC"
l!l
00
MC/DC0%0/1
$dir // "ASC"
$dir
Truth table0%0/2
A
A= $dir
Aresult
11
00
839 0 push @terms, $self->_quote_ident_path($col) . " $dir";
840 }
841 0 $order = ' ORDER BY ' . join(', ', @terms);
842 }
843  
844 0 ▶ my $total = $self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds) // 0;
Condition0%0/2
$self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds) // 0
l!l
00
MC/DC0%0/1
$self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds) // 0
$self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds)
Truth table0%0/2
A
A= $self->val("SELECT COUNT(*) FROM ($stmt) dbix_fast_page", @$binds)
Aresult
11
00
845 0 my $offset = ($page - 1) * $per;
846 0 my $rows = $self->all("$stmt$order LIMIT $per OFFSET $offset", @$binds);
847  
848 return {
849 0 ▶ rows => $rows,
Branch: 1 branch
BranchTrueFalseTotal
$total ? : 0 0 0
850 total => $total + 0,
851 page => $page + 0,
852 per => $per + 0,
853 pages => $total ? int(($total + $per - 1) / $per) : 0,
854 };
855 35 }
856  
857 128 ▶ method exec ($stmt, @params) {
Subroutine exec: called CC=5 SCAR=16.8
Pod documented
858 128 ▶ $self->Exception("exec() : SQL statement required") unless $stmt;
Branch: 1 branch
BranchTrueFalseTotal
unless $stmt 0 128 128
859  
860 128 $sql = $stmt;
861 128 $p = \@params;
862 128 ▶ for (@params) { if (ref $_ eq 'ARRAY') { $self->_expand_in_binds; last } }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_ eq "ARRAY") 0 35 35
863 128 my @binds = @$p;
864  
865 128 my $sth = $self->_prepare($self->db->dbh, $sql);
866  
867 127 my $rv;
868 127 ▶ $self->_track(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
869 127 ▶ $rv = @binds ? $sth->execute(@binds) : $sth->execute();
Branch: 1 branch
BranchTrueFalseTotal
@binds ? : 20 107 127
870 127 1;
871 127 });
872  
873 127 ▶ if ($DBI::err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DBI::err) 0 127 127
874 0 $self->set_error($DBI::err, $DBI::errstr);
875 0 $_affected_rows = undef;
876 0 return;
877 }
878  
879 127 $_affected_rows = _affected($sth, $rv);
880 127 return $sth;
881 35 }
882  
883 0 ▶ method execute ($stmt, $extra = undef, $type = 'arrayref') {
Subroutine execute: not called CC=5 SCAR=34.0
Pod documented
884 0 $sql = $stmt;
885  
886 # make_sen sets $p from $extra; without $extra there are no binds, so clear
887 # any $p left over from a previous query (else it is bound to this
888 # statement - a stray-value or arity-mismatch failure).
889 0 ▶ if ($extra) { $self->make_sen($extra) }
Branch: 1 branch
BranchTrueFalseTotal
if ($extra) { } 0 0 0
890 0 else { $p = undef }
891  
892 0 ▶ $results = $self->_fetch($type eq 'hash' ? \&_shape_hash : \&_shape_rows);
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'hash' ? : 0 0 0
893 35 }
894  
895  
896 # A copy of $row with the table's timestamp columns added where the row does
897 # not set them already: $which 'insert' fills created + updated, 'update'
898 # only updated. The caller's hash is never modified. Returns $row itself
899 # when no timestamps apply.
900 22 ▶ method _stamp ($table, $row, $which) {
Subroutine _stamp: called CC=7 SCAR=19.5
901 22 ▶ my ($created, $updated, $value) = $self->_timestamps_for($table) or return $row;
Branch: 1 branch
BranchTrueFalseTotal
() = $self->_timestamps_for($table) or return $row 20 2 22
902 20 my %r = %$row;
903 20 ▶ $r{$created} = $value if $which eq 'insert' && $created && !exists $r{$created};
Branch: 1 branch
BranchTrueFalseTotal
if $which eq "insert" and $created and not exists $r{$created} 14 6 20
Condition100%6/6
$which eq "insert" and $created and not exists $r{$created}
!ll&&!rl&&r
4214
$which eq "insert" and $created
!ll&&!rl&&r
2216
MC/DC100%3/3
$which eq "insert" and $created and not exists $r{$created}
$which eq "insert" $created not exists $r{$created}
Truth table100%4/4
A and B and not(C)
A= $which eq "insert"B= $createdC= not exists $r{$created}
ABCresult
0XX0
10X0
1100
1111
904 20 ▶ $r{$updated} = $value if $updated && !exists $r{$updated};
Branch: 1 branch
BranchTrueFalseTotal
if $updated and not exists $r{$updated} 18 2 20
Condition66%2/3
$updated and not exists $r{$updated}
!ll&&!rl&&r
0218
MC/DC50%1/2
$updated and not exists $r{$updated}
$updated not exists $r{$updated}
Truth table66%2/3
A and not(B)
A= $updatedB= not exists $r{$updated}
ABresult
0X0
100
111
905 20 return \%r;
906 35 }
907  
908 # Placeholder for one value of a bound INSERT: a scalarref (only ever the
909 # server-side timestamp from _stamp, after user values were validated) is
910 # inlined as SQL, anything else is a ?.
911 152 ▶ 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 146 152
912  
913 # CRUD
914 65 ▶ method insert ($table_name, $skeel, @extra) {
Subroutine insert: called CC=13 SCAR=25.7
Pod documented
915 65 my $table = $self->TableName($table_name);
916  
917 65 ▶ $skeel = $self->extra_args($skeel, @extra) if @extra;
Branch: 1 branch
BranchTrueFalseTotal
if @extra 1 64 65
918 64 ▶ $skeel = $self->_json_encode_row($table, $skeel) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 2 62 64
919  
920 64 $self->_safe_data($skeel);
921 56 ▶ $skeel = $self->_stamp($table, $skeel, 'insert') if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 8 48 56
922  
923 # '' except on Pg (driver test inline: no method call on the others)
924 56 ▶ my $ret = ($_dbd_c //= $self->dbd) eq 'Pg' ? $self->_pg_returning($table) : '';
Branch: 1 branch
BranchTrueFalseTotal
($_dbd_c //= $self->dbd) eq 'Pg' ? : 5 51 56
Condition66%2/3
$_dbd_c //= $self->dbd
l!l&&r!l&&!r
30260
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
925 56 my @cols = sort keys %$skeel;
926 56 my $sth;
927 56 ▶ if (@cols && !grep { ref } @{$skeel}{@cols}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cols and not grep({ref $_;} @{$skeel;}{@cols})) { } 54 2 56
Condition66%2/3
@cols and not grep({ref $_;} @{$skeel;}{@cols})
!ll&&!rl&&r
0254
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
928 54 my $ck = join("\0", 'I', $table, @cols);
929 $sql = $_crud_sql{$ck} // $self->_crud_stmt($ck,
930 54 ▶ 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
10440
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
931 54 $sth = $self->execute_prepare(@{$skeel}{@cols});
932 }
933 else {
934 2 my ($stmt, @bind) = $self->Q->insert($table, $skeel);
935 2 $sql = $stmt . $ret;
936 2 $sth = $self->execute_prepare(@bind);
937 }
938  
939 49 ▶ if ($ret) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ret) { } 1 48 49
940 1 ▶ ($last_id) = $_affected_rows ? $sth->fetchrow_array : (undef);
Branch: 1 branch
BranchTrueFalseTotal
$_affected_rows ? : 1 0 1
941 1 $sth->finish;
942 }
943 else {
944 48 $self->_update_last_id($table);
945 }
946 49 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 5 44 49
947 49 ▶ $self->_fire_after_write(op => 'insert', table => $table, data => $skeel) if $_after_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write 3 46 49
948 49 return $last_id;
949 35 }
950  
951 # ' RETURNING "pk"' for a Pg insert into $table, or '' (no single-column
952 # primary key, not Pg, or the lookup failed: last_insert_id as before).
953 # to_regclass() yields NULL instead of an error, so a failed lookup can
954 # never abort the caller's transaction.
955 5 ▶ method _pg_returning ($table) {
Subroutine _pg_returning: called CC=7 SCAR=19.5
956 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
957 5 ▶ my $pk = $_pg_pk{$table} //= do {
Condition100%3/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
113
MC/DC100%2/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 table100%3/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
958 4 my $dbh = $self->db->dbh;
959 4 my $cols = eval {
960 4 local $dbh->{HandleError};
961 4 local $dbh->{RaiseError} = 1;
962 4 local $dbh->{PrintError} = 0;
963 4 $dbh->selectcol_arrayref(
964 q{SELECT a.attname FROM pg_index i
965 JOIN pg_attribute a ON a.attrelid = i.indrelid
966 AND a.attnum = ANY (i.indkey)
967 WHERE i.indrelid = to_regclass(?) AND i.indisprimary},
968 undef, $self->_quote_ident_path($table));
969 };
970 4 _trim_cache(\%_pg_pk, 1_000);
971 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
972 };
973 5 ▶ return $pk eq '' ? '' : ' RETURNING ' . $self->db->dbh->quote_identifier($pk);
Branch: 1 branch
BranchTrueFalseTotal
$pk eq '' ? : 4 1 5
974 35 }
975  
976 71 ▶ method _update_last_id ($table) {
Subroutine _update_last_id: called CC=7 SCAR=19.7
977 71 ▶ my $dbd = $_dbd_c //= $self->dbd;
Condition66%2/3
$_dbd_c //= $self->dbd
l!l&&r!l&&!r
7010
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
978 71 ▶ my $dbh = $_write_dbh // $self->db->dbh;
Condition33%1/3
$_write_dbh // $self->db->dbh
l!l&&r!l&&!r
7100
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
979 71 ▶ if ($dbd eq 'SQLite') { $last_id = $dbh->sqlite_last_insert_rowid() }
Branch: 4 branches
BranchTrueFalseTotal
if ($dbd eq 'SQLite') { } 62 9 71
elsif ($dbd eq 'MariaDB') { } 4 5 9
elsif ($dbd eq 'mysql') { } 1 4 5
elsif ($dbd eq 'Pg') { } 4 0 4
980 4 elsif ($dbd eq 'MariaDB') { $last_id = $dbh->{mariadb_insertid} }
981 1 elsif ($dbd eq 'mysql') { $last_id = $dbh->{mysql_insertid} }
982 elsif ($dbd eq 'Pg') {
983 # DBD::Pg guesses the serial sequence from the table name. That fails for
984 # non-default schemas, renamed/custom sequences, or non-serial PKs. Guard
985 # it so a failed lookup yields undef last_id instead of dying AFTER the row
986 # was already inserted. NOTE: Pg last_id requires a serial/identity PK; for
987 # other cases use INSERT ... RETURNING via exec()/query().
988 4 $last_id = eval { $dbh->last_insert_id(undef, undef, $table, undef) };
989 }
990 35 }
991  
992 38 ▶ method update ($table_name, $skeel, @extra) {
Subroutine update: called CC=10 SCAR=23.0
Pod documented
993 38 my $table = $self->TableName($table_name);
994  
995 38 ▶ $skeel->{sen} = $self->extra_args($skeel->{sen}, @extra)
Branch: 1 branch
BranchTrueFalseTotal
if @extra 1 37 38
996 if @extra;
997  
998 my $set = $_json_write ? $self->_json_encode_row($table, $skeel->{sen})
999 37 ▶ : $skeel->{sen};
Branch: 1 branch
BranchTrueFalseTotal
$_json_write ? : 2 35 37
1000 37 $self->_safe_data($set);
1001 30 $self->_safe_columns($skeel->{where});
1002  
1003 11 my $where = $skeel->{where};
1004 11 ▶ $set = $self->_stamp($table, $set, 'update') if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 2 9 11
1005 11 my @scols = sort keys %$set;
1006 11 my $sth;
1007 11 ▶ 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)) { } 6 5 11
Condition83%5/6
@scols and not grep({ref $_;} @{$set;}{@scols}) and _plain_where($where)
!ll&&!rl&&r
236
@scols and not grep({ref $_;} @{$set;}{@scols})
!ll&&!rl&&r
029
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
1008 6 my @wcols = sort keys %$where;
1009 6 my $ck = join("\0", 'U', $table, @scols, '', @wcols);
1010 $sql = $_crud_sql{$ck} // $self->_crud_stmt($ck,
1011 6 ▶ 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
060
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
1012 6 $sth = $self->execute_prepare(@{$set}{@scols}, @{$where}{@wcols});
1013 }
1014 else {
1015 5 my ($stmt, @bind) = $self->Q->update($table, $set, $where);
1016 5 $sql = $stmt;
1017 5 $sth = $self->execute_prepare(@bind);
1018 }
1019 11 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 1 10 11
1020 11 ▶ $self->_fire_after_write(op => 'update', table => $table, data => $set, where => $where) if $_after_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write 1 10 11
1021 11 return $sth;
1022 35 }
1023  
1024 13 ▶ method up ($table_name, $data, $where, $time_col = undef) {
Subroutine up: called CC=3 SCAR=11.0
Pod documented
1025 13 ▶ if ($time_col) {
Branch: 1 branch
BranchTrueFalseTotal
if ($time_col) { } 1 12 13
1026 1 $self->update($table_name,
1027 { sen => $data, where => $where }, time => $time_col);
1028 } else {
1029 12 $self->update($table_name,
1030 { sen => $data, where => $where });
1031 }
1032 35 }
1033  
1034 33 ▶ method delete ($table_name, $skeel) {
Subroutine delete: called CC=5 SCAR=16.1
Pod documented
1035 33 my $table = $self->TableName($table_name);
1036  
1037 33 $self->_safe_columns($skeel);
1038  
1039 13 my $sth;
1040 13 ▶ if (_plain_where($skeel)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_plain_where($skeel)) { } 6 7 13
1041 6 my @wcols = sort keys %$skeel;
1042 6 my $ck = join("\0", 'D', $table, @wcols);
1043 $sql = $_crud_sql{$ck} // $self->_crud_stmt($ck,
1044 6 ▶ 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
240
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
1045 6 $sth = $self->execute_prepare(@{$skeel}{@wcols});
1046 }
1047 else {
1048 7 my ($stmt, @bind) = $self->Q->delete($table, $skeel);
1049 7 $sql = $stmt;
1050 7 $sth = $self->execute_prepare(@bind);
1051 }
1052 13 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 1 12 13
1053 13 ▶ $self->_fire_after_write(op => 'delete', table => $table, where => $skeel) if $_after_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write 1 12 13
1054 13 return $sth;
1055 35 }
1056  
1057 66 ▶ method upsert ($table_name, $row, $conflict_keys, $update_cols = undef) {
Subroutine upsert: called CC=13 SCAR=25.7
Pod documented
1058 66 ▶ $self->Exception("upsert: row hashref required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" and %$row 0 66 66
Condition33%1/3
ref $row eq "HASH" and %$row
!ll&&!rl&&r
0066
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
1059 unless ref $row eq 'HASH' && %$row;
1060 66 ▶ $self->Exception("upsert: conflict_keys arrayref required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $conflict_keys eq "ARRAY" and @$conflict_keys 0 66 66
Condition33%1/3
ref $conflict_keys eq "ARRAY" and @$conflict_keys
!ll&&!rl&&r
0066
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
1061 unless ref $conflict_keys eq 'ARRAY' && @$conflict_keys;
1062  
1063 66 my $table = $self->TableName($table_name);
1064 66 ▶ $row = $self->_json_encode_row($table, $row) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 2 64 66
1065 66 $self->_safe_bind_row($row);
1066 61 $self->_safe_ids(@$conflict_keys);
1067  
1068 # Without timestamps the statement depends only on the table, the
1069 # columns, the conflict keys and update_cols as given: key the statement
1070 # cache on those, so a repeated upsert skips normalizing/validating the
1071 # update spec (done once, on the miss that built the statement - the row
1072 # VALUES are still validated every call, above).
1073 60 my @cols = sort keys %$row;
1074 60 my $sets;
1075 my $key;
1076 60 ▶ if ($_ts_on) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ts_on) { } 2 58 60
1077 # The update spec comes from the caller's columns (so a stamped created
1078 # column is never overwritten on conflict); the stamped updated column
1079 # is then always refreshed.
1080 2 $sets = $self->_update_spec('upsert', $update_cols, $conflict_keys, \@cols);
1081 2 $row = $self->_stamp($table, $row, 'insert');
1082 2 $sets = $self->_touch_updated($table, $sets);
1083 2 @cols = sort keys %$row;
1084 2 ▶ $key = join("\0", 'S', $table, (map { ref $row->{$_} ? "$_=L" : $_ } @cols),
Branch: 1 branch
BranchTrueFalseTotal
ref $row->{$_} ? : 2 6 8
1085 '', @$conflict_keys, '', _spec_key($sets));
1086 }
1087 else {
1088 58 $key = join("\0", 'S', $table, @cols, '', @$conflict_keys, '',
1089 _raw_spec_key($update_cols));
1090 }
1091  
1092 $sql = $_crud_sql{$key} // $self->_crud_stmt($key,
1093 54 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1094 54 ▶ $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
23814
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
1095 32 my $dbh = $self->db->dbh;
1096 32 my $qt = $self->_quote_ident_path($table);
1097 32 my $qcols = join(', ', map { $dbh->quote_identifier($_) } @cols);
1098 32 my $placeholders = join(', ', map { _ph($row->{$_}) } @cols);
1099 32 my $clause = $self->_upsert_clause($conflict_keys, $sets, $qt);
1100 32 "INSERT INTO " . $self->_upsert_target($qt) . " ($qcols) VALUES ($placeholders) $clause";
1101 60 ▶ });
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
64014
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
1102 38 ▶ my @bind = $_ts_on ? (grep { ref ne 'SCALAR' } @{$row}{@cols}) : @{$row}{@cols};
Branch: 1 branch
BranchTrueFalseTotal
$_ts_on ? : 2 36 38
1103 38 my $sth = $self->execute_prepare(@bind);
1104 38 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 1 37 38
1105 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 1 37 38
1106 38 return $sth;
1107 35 }
1108  
1109 # Add the table's updated column to an upsert spec ('new'), unless the
1110 # caller already says how to update it.
1111 4 ▶ method _touch_updated ($table, $sets) {
Subroutine _touch_updated: called CC=5 SCAR=17.1
1112 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
1113 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
1114 4 return [ @$sets, [ $updated, 'new' ] ];
1115 35 }
1116  
1117 # Stamp every row of a batch (same values for all) - see _stamp.
1118 4 ▶ method _stamp_rows ($table, $rows, $which) {
Subroutine _stamp_rows: called CC=2 SCAR=6.9
1119 4 ▶ return $rows unless $self->_timestamps_for($table);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_timestamps_for($table) 0 4 4
1120 4 return [ map { $self->_stamp($table, $_, $which) } @$rows ];
1121 35 }
1122  
1123 # Runs $code->($slice) for consecutive slices of @$rows of at most $size and
1124 # returns the sum of the results. Each slice is its own statement; wrap the
1125 # call in txn() when all-or-nothing matters.
1126 3 ▶ method _in_slices ($rows, $size, $code) {
Subroutine _in_slices: called CC=5 SCAR=16.1
1127 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
1128 unless defined $size && $size =~ /\A[1-9]\d*\z/;
1129 2 my $total = 0;
1130 2 ▶ for (my $i = 0; $i < @$rows; $i += $size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$rows) 8 2 10
1131 8 my $end = $i + $size - 1;
1132 8 ▶ $end = $#$rows if $end > $#$rows;
Branch: 1 branch
BranchTrueFalseTotal
if $end > $rows->$#* 2 6 8
1133 8 $total += $code->([ @{$rows}[ $i .. $end ] ]);
1134 }
1135 2 return $total;
1136 35 }
1137  
1138 21 ▶ method insert_many ($table_name, $rows, %opt) {
Subroutine insert_many: called CC=21 SCAR=30.8
Pod documented
1139 21 ▶ $self->Exception("insert_many: at least one row required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rows eq "ARRAY" and @$rows 2 19 21
Condition100%3/3
ref $rows eq "ARRAY" and @$rows
!ll&&!rl&&r
1119
MC/DC100%2/2
ref $rows eq "ARRAY" and @$rows
ref $rows eq "ARRAY" @$rows
Truth table100%3/3
A and B
A= ref $rows eq "ARRAY"B= @$rows
ABresult
0X0
100
111
1140 unless ref $rows eq 'ARRAY' && @$rows;
1141 19 ▶ 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 17 19
$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
1702
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
1142 2 my %rest = %opt;
1143 2 delete $rest{chunk};
1144 return $self->_in_slices($rows, $opt{chunk},
1145 2 ▶ sub ($slice) { $self->insert_many($table_name, $slice, %rest) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1146 }
1147 $self->Exception("insert_many: rows must be hashrefs")
1148 17 ▶ if grep { ref $_ ne 'HASH' } @$rows;
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_ ne "HASH";} @$rows 0 17 17
1149  
1150 17 my $table = $self->TableName($table_name);
1151 17 ▶ $rows = $self->_json_encode_rows($table, $rows) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 2 15 17
1152 17 my @cols = sort keys %{ $rows->[0] };
1153 17 $self->_safe_id($_) for @cols;
1154  
1155 # Same key set as row 0: same size and every row-0 column present
1156 # (no per-row sort + join).
1157 16 for my $i (1 .. $#$rows) {
1158 46 my $r = $rows->[$i];
1159 $self->Exception(
1160 "insert_many: row $i has different columns than row 0")
1161 46 ▶ if keys %$r != @cols || grep { !exists $r->{$_} } @cols;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$r != @cols or grep {not exists $r->{$_};} @cols 3 43 46
Condition100%3/3
keys %$r != @cols or grep {not exists $r->{$_};} @cols
l!l&&r!l&&!r
2143
MC/DC100%2/2
keys %$r != @cols or grep {not exists $r->{$_};} @cols
keys %$r != @cols grep {not exists $r->{$_};} @cols
Truth table100%3/3
A or B
A= keys %$r != @colsB= grep {not exists $r->{$_};} @cols
ABresult
1X1
011
000
1162 }
1163 13 my @bind = map { @{$_}{@cols} } @$rows;
1164 13 $self->_safe_bind_values(\@bind);
1165 9 ▶ if ($_ts_on) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ts_on) 2 7 9
1166 2 $rows = $self->_stamp_rows($table, $rows, 'insert');
1167 2 @cols = sort keys %{ $rows->[0] };
1168 2 @bind = grep { ref ne 'SCALAR' } map { @{$_}{@cols} } @$rows;
1169 }
1170  
1171 9 my $dbh = $self->db->dbh;
1172 9 my $qt = $self->_quote_ident_path($table);
1173 9 my $qcols = join(', ', map { $dbh->quote_identifier($_) } @cols);
1174 9 my $row_ph = '(' . join(', ', map { _ph($rows->[0]{$_}) } @cols) . ')';
1175 9 my $values = join(', ', ($row_ph) x scalar(@$rows));
1176  
1177 # ignore => 1: rows violating a UNIQUE/PRIMARY KEY are skipped (see
1178 # insert_ignore); the return value is then the number actually inserted.
1179 9 my $dbd = $self->dbd;
1180 9 my ($verb, $tail) = ('INSERT INTO', '');
1181 9 ▶ if ($opt{ignore}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"ignore"}) 1 8 9
1182 1 ▶ if ($dbd eq 'MariaDB' || $dbd eq 'mysql') { $verb = 'INSERT IGNORE INTO' }
Branch: 2 branches
BranchTrueFalseTotal
if ($dbd eq 'MariaDB' or $dbd eq 'mysql') { } 0 1 1
elsif ($dbd eq 'SQLite') { } 1 0 1
Condition33%1/3
$dbd eq "MariaDB" or $dbd eq "mysql"
l!l&&r!l&&!r
001
MC/DC0%0/2
$dbd eq "MariaDB" or $dbd eq "mysql"
$dbd eq "MariaDB" $dbd eq "mysql"
Truth table33%1/3
A or B
A= $dbd eq "MariaDB"B= $dbd eq "mysql"
ABresult
1X1
011
000
1183 1 elsif ($dbd eq 'SQLite') { $verb = 'INSERT OR IGNORE INTO' }
1184 0 else { $tail = ' ON CONFLICT DO NOTHING' }
1185 }
1186  
1187 9 $sql = "$verb $qt ($qcols) VALUES $values$tail";
1188 9 $self->execute_prepare(@bind);
1189  
1190 9 $self->_update_last_id($table);
1191 9 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 0 9 9
1192 9 ▶ $self->_fire_after_write(op => 'insert_many', table => $table, data => $rows) if $_after_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write 1 8 9
1193 9 ▶ return $opt{ignore} ? ($_affected_rows // 0) : scalar @$rows;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'ignore'} ? : 1 8 9
Condition50%1/2
$_affected_rows // 0
l!l
10
MC/DC0%0/1
$_affected_rows // 0
$_affected_rows
Truth table50%1/2
A
A= $_affected_rows
Aresult
11
00
1194 35 }
1195  
1196 20 ▶ method upsert_many ($table_name, $rows, $conflict_keys, $update_cols = undef, %opt) {
Subroutine upsert_many: called CC=20 SCAR=30.6
Pod documented
1197 20 ▶ $self->Exception("upsert_many: at least one row required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rows eq "ARRAY" and @$rows 0 20 20
Condition33%1/3
ref $rows eq "ARRAY" and @$rows
!ll&&!rl&&r
0020
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
1198 unless ref $rows eq 'ARRAY' && @$rows;
1199 20 ▶ 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 19 20
$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
1901
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
1200 5 ▶ return $self->_in_slices($rows, $opt{chunk}, sub ($slice) {
Subroutine __ANON__: called CC=1 SCAR=0.0
1201 5 $self->upsert_many($table_name, $slice, $conflict_keys, $update_cols)
1202 1 });
1203 }
1204 $self->Exception("upsert_many: rows must be hashrefs")
1205 19 ▶ if grep { ref $_ ne 'HASH' } @$rows;
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_ ne "HASH";} @$rows 0 19 19
1206 19 ▶ $self->Exception("upsert_many: conflict_keys arrayref required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $conflict_keys eq "ARRAY" and @$conflict_keys 0 19 19
Condition33%1/3
ref $conflict_keys eq "ARRAY" and @$conflict_keys
!ll&&!rl&&r
0019
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
1207 unless ref $conflict_keys eq 'ARRAY' && @$conflict_keys;
1208  
1209 19 my $table = $self->TableName($table_name);
1210 19 ▶ $rows = $self->_json_encode_rows($table, $rows) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 1 18 19
1211 19 my @cols = sort keys %{ $rows->[0] };
1212 19 $self->_safe_id($_) for @cols;
1213 19 $self->_safe_id($_) for @$conflict_keys;
1214 18 my $sets = $self->_update_spec('upsert_many', $update_cols, $conflict_keys, \@cols);
1215 18 ▶ $sets = $self->_touch_updated($table, $sets) if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 2 16 18
1216  
1217 # Same key set as row 0: same size and every row-0 column present
1218 # (no per-row sort + join).
1219 18 for my $i (1 .. $#$rows) {
1220 34 my $r = $rows->[$i];
1221 $self->Exception(
1222 "upsert_many: row $i has different columns than row 0")
1223 34 ▶ if keys %$r != @cols || grep { !exists $r->{$_} } @cols;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$r != @cols or grep {not exists $r->{$_};} @cols 0 34 34
Condition33%1/3
keys %$r != @cols or grep {not exists $r->{$_};} @cols
l!l&&r!l&&!r
0034
MC/DC0%0/2
keys %$r != @cols or grep {not exists $r->{$_};} @cols
keys %$r != @cols grep {not exists $r->{$_};} @cols
Truth table33%1/3
A or B
A= keys %$r != @colsB= grep {not exists $r->{$_};} @cols
ABresult
1X1
011
000
1224 }
1225  
1226 18 my @bind = map { @{$_}{@cols} } @$rows;
1227 18 $self->_safe_bind_values(\@bind);
1228 14 ▶ if ($_ts_on) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ts_on) 2 12 14
1229 2 $rows = $self->_stamp_rows($table, $rows, 'insert');
1230 2 @cols = sort keys %{ $rows->[0] };
1231 2 @bind = grep { ref ne 'SCALAR' } map { @{$_}{@cols} } @$rows;
1232 }
1233  
1234 14 my $dbh = $self->db->dbh;
1235 14 my $qt = $self->_quote_ident_path($table);
1236 14 my $qcols = join(', ', map { $dbh->quote_identifier($_) } @cols);
1237 14 my $row_ph = '(' . join(', ', map { _ph($rows->[0]{$_}) } @cols) . ')';
1238 14 my $values = join(', ', ($row_ph) x scalar(@$rows));
1239 14 my $clause = $self->_upsert_clause($conflict_keys, $sets, $qt);
1240  
1241 14 $sql = "INSERT INTO " . $self->_upsert_target($qt) . " ($qcols) VALUES $values $clause";
1242 14 $self->execute_prepare(@bind);
1243 14 ▶ $self->_cache_invalidate_table($table) if $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache_on 0 14 14
1244 14 ▶ $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 1 13 14
1245  
1246 14 return scalar @$rows;
1247 35 }
1248  
1249  
1250 # Builds the ON CONFLICT / ON DUPLICATE KEY UPDATE clause.
1251 # Pg/SQLite use ON CONFLICT (cols) DO UPDATE SET c = excluded.c.
1252 # MariaDB/mysql use ON DUPLICATE KEY UPDATE c = VALUES(c). The conflict_keys
1253 # are validated for symmetry but not emitted in MariaDB syntax (any UNIQUE
1254 # or PRIMARY KEY triggers the update there).
1255 # The ON CONFLICT update spec, normalized to [ [col, mode], ... ]:
1256 # undef every row column that is not a conflict key, 'new'
1257 # [ cols ] those columns, 'new' (the historical form)
1258 # { col => 'new' | '+' | { '+' => N } | \'SQL' }
1259 # 'new' takes the incoming value, '+' adds it to the stored
1260 # one (balances), { '+' => N } adds a constant (counters), a
1261 # scalarref is literal SQL - the documented code-only escape
1262 # hatch (a JSON body cannot carry one), e.g. \'CURRENT_TIMESTAMP'.
1263 # A literal that reads the stored row is dialect-specific
1264 # (PostgreSQL needs dbix_t.col); prefer the modes.
1265 72 ▶ method _update_spec ($who, $update_cols, $conflict_keys, $cols) {
Subroutine _update_spec: called CC=19 SCAR=30.2
1266 72 my @sets;
1267 72 ▶ if (!defined $update_cols) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $update_cols) { } 23 49 72
elsif (ref $update_cols eq 'ARRAY') { } 7 42 49
elsif (ref $update_cols eq 'HASH') { } 42 0 42
1268 23 my %ck = map { $_ => 1 } @$conflict_keys;
1269 23 @sets = map { [ $_, 'new' ] } grep { !$ck{$_} } @$cols;
1270 }
1271 elsif (ref $update_cols eq 'ARRAY') {
1272 7 @sets = map { [ $_, 'new' ] } @$update_cols;
1273 }
1274 elsif (ref $update_cols eq 'HASH') {
1275 42 my %in = map { $_ => 1 } @$cols;
1276 42 for my $col (sort keys %$update_cols) {
1277 52 $self->_safe_id($col);
1278 47 my $mode = $update_cols->{$col};
1279 47 ▶ if (ref $mode eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $mode eq "HASH") 10 37 47
1280 10 my ($op, $n) = %$mode;
1281 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
1282 unless keys %$mode == 1 && $op eq '+'
1283 && defined $n && !ref $n && $n =~ /\A-?\d+(?:\.\d+)?\z/;
1284 5 push @sets, [ $col, [ '+', $n ] ];
1285 5 next;
1286 }
1287 37 ▶ if (ref $mode eq 'SCALAR') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $mode eq "SCALAR") 5 32 37
1288 5 push @sets, [ $col, $mode ];
1289 5 next;
1290 }
1291 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
1292 . "{ '+' => N } or a scalarref of SQL")
1293 unless defined $mode && !ref $mode && ($mode eq 'new' || $mode eq '+');
1294 $self->Exception("$who: '$mode' for $col needs $col in the row")
1295 27 ▶ unless $in{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $in{$col} 5 22 27
1296 22 push @sets, [ $col, $mode ];
1297 }
1298 }
1299 else {
1300 0 $self->Exception("$who: update_cols must be an arrayref or hashref");
1301 }
1302 52 ▶ $self->Exception(
Branch: 1 branch
BranchTrueFalseTotal
unless @sets 1 51 52
1303 "$who: nothing to update on conflict (all row columns are conflict keys)")
1304 unless @sets;
1305 51 $self->_safe_id($_->[0]) for @sets;
1306 50 return \@sets;
1307 35 }
1308  
1309 # Statement-cache key part for update_cols exactly as the caller passed it
1310 # (before normalization). Anything unexpected keys as 'X', which can never
1311 # be cached: _update_spec rejects it on the miss.
1312 58 ▶ sub _raw_spec_key ($u) {
Subroutine _raw_spec_key: called CC=8 SCAR=21.1
1313 58 ▶ return 'U' unless defined $u;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $u 16 42 58
1314 42 ▶ return join ',', 'A', @$u if ref $u eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $u eq "ARRAY" 7 35 42
1315 35 ▶ return 'X' unless ref $u eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $u eq "HASH" 0 35 35
1316 return join ',', 'H', map {
1317 35 my $m = $u->{$_};
1318 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
1319 : ref $m eq 'HASH' ? '+' . join(':', %$m)
1320 : ref $m ? 'X'
1321 : $m // '');
1322 } sort keys %$u;
1323 }
1324  
1325 # Statement-cache key part for a normalized update spec.
1326 2 ▶ sub _spec_key ($sets) {
Subroutine _spec_key: called CC=3 SCAR=11.7
1327 return map {
1328 2 my $m = $_->[1];
1329 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
1330 } @$sets;
1331 }
1332  
1333 # "INSERT INTO <target>" for an upsert: PostgreSQL gets the alias dbix_t, the
1334 # only unambiguous way to name the stored row in ON CONFLICT DO UPDATE (a
1335 # bare column there is ambiguous between it and EXCLUDED).
1336 46 ▶ method _upsert_target ($qt) {
Subroutine _upsert_target: called CC=2 SCAR=6.9
1337 46 ▶ return $self->dbd eq 'Pg' ? "$qt AS dbix_t" : $qt;
Branch: 1 branch
BranchTrueFalseTotal
$self->dbd eq 'Pg' ? : 1 45 46
1338 35 }
1339  
1340 # Builds the ON CONFLICT / ON DUPLICATE KEY UPDATE clause from a normalized
1341 # spec. The incoming value is VALUES(c) on MariaDB and MySQL < 8.0.19, the
1342 # row alias new.c on MySQL >= 8.0.19 (VALUES() is deprecated there) and
1343 # excluded.c on PostgreSQL/SQLite. MariaDB/MySQL ignore conflict_keys (any
1344 # UNIQUE or PRIMARY KEY triggers the update); they are validated for symmetry.
1345 49 ▶ method _upsert_clause ($conflict_keys, $sets, $qt = undef) {
Subroutine _upsert_clause: called CC=15 SCAR=27.1
1346 49 my $dbh = $self->db->dbh;
1347 49 my $dbd = $self->dbd;
1348  
1349 49 my ($incoming, $prefix);
1350 49 ▶ if ($dbd eq 'mysql' && ($dbh->{mysql_serverversion} // 0) >= 80019) {
Branch: 2 branches
BranchTrueFalseTotal
if ($dbd eq 'mysql' and ($dbh->{'mysql_serverversion'} // 0) >= 80019) { } 2 47 49
elsif ($dbd eq 'mysql' or $dbd eq 'MariaDB') { } 3 44 47
Condition80%4/5
$dbd eq "mysql" and ($dbh->{"mysql_serverversion"} // 0) >= 80019
!ll&&!rl&&r
4612
$dbh->{"mysql_serverversion"} // 0
l!l
30
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
1351 2 ▶ $incoming = sub ($qc) { "new.$qc" };
Subroutine __ANON__: called CC=1 SCAR=0.0
1352 2 $prefix = 'AS new ON DUPLICATE KEY UPDATE ';
1353 }
1354 ▶ elsif ($dbd eq 'mysql' || $dbd eq 'MariaDB') {
Condition100%3/3
$dbd eq "mysql" or $dbd eq "MariaDB"
l!l&&r!l&&!r
1244
MC/DC100%2/2
$dbd eq "mysql" or $dbd eq "MariaDB"
$dbd eq "mysql" $dbd eq "MariaDB"
Truth table100%3/3
A or B
A= $dbd eq "mysql"B= $dbd eq "MariaDB"
ABresult
1X1
011
000
1355 3 ▶ $incoming = sub ($qc) { "VALUES($qc)" };
Subroutine __ANON__: called CC=1 SCAR=0.0
1356 3 $prefix = 'ON DUPLICATE KEY UPDATE ';
1357 }
1358 else {
1359 44 my $qck = join(', ', map { $dbh->quote_identifier($_) } @$conflict_keys);
1360 44 ▶ $incoming = sub ($qc) { "excluded.$qc" };
Subroutine __ANON__: called CC=1 SCAR=0.0
1361 44 $prefix = "ON CONFLICT ($qck) DO UPDATE SET ";
1362 }
1363  
1364 # Naming the STORED row: PostgreSQL via the dbix_t alias (_upsert_target);
1365 # MySQL's row-alias form via the table name (a bare column is ambiguous
1366 # with new.col there); MariaDB/SQLite accept the bare column.
1367 0 ▶ my $stored = $dbd eq 'Pg' ? sub ($qc) { "dbix_t.$qc" }
Subroutine __ANON__: not called CC=1 SCAR=6.9
1368 0 ▶ : $dbd eq 'mysql' && $prefix =~ /^AS new/ && $qt ? sub ($qc) { "$qt.$qc" }
Subroutine __ANON__: not called CC=1 SCAR=6.9
1369 49 ▶ : sub ($qc) { $qc };
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 2 branches
BranchTrueFalseTotal
$dbd eq 'Pg' ? : 1 48 49
$dbd eq 'mysql' && $prefix =~ /^AS new/u && $qt ? : 1 47 48
Condition100%6/6
$dbd eq "mysql" and $prefix =~ /^AS new/u and $qt
!ll&&!rl&&r
4611
$dbd eq "mysql" and $prefix =~ /^AS new/u
!ll&&!rl&&r
4512
MC/DC100%3/3
$dbd eq "mysql" and $prefix =~ /^AS new/u and $qt
$dbd eq "mysql" $prefix =~ /^AS new/u $qt
Truth table100%4/4
A and B and C
A= $dbd eq "mysql"B= $prefix =~ /^AS new/uC= $qt
ABCresult
0XX0
10X0
1100
1111
1370  
1371 my @sql = map {
1372 # A bare column name (the pre-0.20 [cols] form) means 'new'.
1373 49 ▶ my ($col, $mode) = ref $_ ? @$_ : ($_, 'new');
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 76 4 80
1374 80 my $qc = $dbh->quote_identifier($col);
1375 80 ▶ ref $mode eq 'SCALAR' ? "$qc = $$mode"
Branch: 3 branches
BranchTrueFalseTotal
ref $mode eq 'SCALAR' ? : 5 75 80
ref $mode ? : 5 70 75
$mode eq '+' ? : 15 55 70
1376 : ref $mode ? "$qc = " . $stored->($qc) . " + $mode->[1]"
1377 : $mode eq '+' ? "$qc = " . $stored->($qc) . ' + ' . $incoming->($qc)
1378 : "$qc = " . $incoming->($qc);
1379 } @$sets;
1380 49 return $prefix . join(', ', @sql);
1381 35 }
1382  
1383 # INSERT that silently skips a row violating a UNIQUE/PRIMARY KEY:
1384 # INSERT IGNORE (MariaDB/MySQL), INSERT OR IGNORE (SQLite), ON CONFLICT DO
1385 # NOTHING (PostgreSQL). Returns 1 when the row was inserted, 0 when it
1386 # already existed. Note: MariaDB/MySQL's IGNORE also downgrades other errors
1387 # (bad values, NOT NULL) to warnings.
1388 33 ▶ method insert_ignore ($table_name, $row) {
Subroutine insert_ignore: called CC=17 SCAR=30.7
Pod documented
1389 33 my $table = $self->TableName($table_name);
1390 33 ▶ $row = $self->_json_encode_row($table, $row) if $_json_write;
Branch: 1 branch
BranchTrueFalseTotal
if $_json_write 2 31 33
1391 33 $self->_safe_data($row);
1392 33 ▶ $self->Exception("insert_ignore: row hashref required") unless %$row;
Branch: 1 branch
BranchTrueFalseTotal
unless %$row 0 33 33
1393 33 ▶ $row = $self->_stamp($table, $row, 'insert') if $_ts_on;
Branch: 1 branch
BranchTrueFalseTotal
if $_ts_on 2 31 33
1394  
1395 33 my ($stmt, @bind) = $self->Q->insert($table, $row);
1396 33 my $dbd = $self->dbd;
1397 33 ▶ 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 33 33
elsif ($dbd eq 'SQLite') { } 33 0 33
Condition33%1/3
$dbd eq "MariaDB" or $dbd eq "mysql"
l!l&&r!l&&!r
0033
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
1398 33 elsif ($dbd eq 'SQLite') { $stmt =~ s/^INSERT INTO/INSERT OR IGNORE INTO/ }
1399 0 else { $stmt .= ' ON CONFLICT DO NOTHING' }
1400 33 ▶ my $ret = ($_dbd_c //= $self->dbd) eq 'Pg' # no row back when ignored
Branch: 1 branch
BranchTrueFalseTotal
($_dbd_c //= $self->dbd) eq 'Pg' ? : 0 33 33
Condition66%2/3
$_dbd_c //= $self->dbd
l!l&&r!l&&!r
2490
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
1401 ? $self->_pg_returning($table) : '';
1402 33 $stmt .= $ret;
1403  
1404 33 $sql = $stmt;
1405 33 my $sth = $self->execute_prepare(@bind);
1406 33 ▶ my $inserted = $_affected_rows ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$_affected_rows ? : 14 19 33
1407 33 ▶ if ($ret) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ret) { } 0 33 33
elsif ($inserted) { } 14 19 33
1408 0 ▶ ($last_id) = $sth->fetchrow_array if $inserted; # ignored: unchanged
Branch: 1 branch
BranchTrueFalseTotal
if $inserted 0 0 0
1409 0 $sth->finish;
1410 }
1411 elsif ($inserted) {
1412 14 $self->_update_last_id($table);
1413 }
1414 33 ▶ $self->_cache_invalidate_table($table) if $inserted && $_cache_on;
Branch: 1 branch
BranchTrueFalseTotal
if $inserted and $_cache_on 0 33 33
Condition66%2/3
$inserted and $_cache_on
!ll&&!rl&&r
19140
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
1415 33 ▶ $self->_fire_after_write(op => 'insert_ignore', table => $table, data => $row) if $_after_write && $inserted;
Branch: 1 branch
BranchTrueFalseTotal
if $_after_write and $inserted 1 32 33
Condition100%3/3
$_after_write and $inserted
!ll&&!rl&&r
3111
MC/DC100%2/2
$_after_write and $inserted
$_after_write $inserted
Truth table100%3/3
A and B
A= $_after_writeB= $inserted
ABresult
0X0
100
111
1416 33 return $inserted;
1417 35 }
1418  
1419 # The row matching $key (a { column => value } hashref covered by a UNIQUE
1420 # index), inserting { %$defaults, %$key } first when there is none. Safe
1421 # against concurrent callers: the insert is insert_ignore, so a racing
1422 # duplicate is skipped and the existing row is read back. In list context
1423 # also returns whether this call created it.
1424 21 ▶ method find_or_create ($table_name, $key, $defaults = {}) {
Subroutine find_or_create: called CC=8 SCAR=21.9
Pod documented
1425 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
1426 unless ref $key eq 'HASH' && %$key;
1427 21 ▶ $self->Exception("find_or_create: defaults must be a hashref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $defaults eq "HASH" 0 21 21
1428 unless ref $defaults eq 'HASH';
1429 $self->Exception("find_or_create: key values must be defined plain values")
1430 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
1431  
1432 21 my $created = $self->insert_ignore($table_name, { %$defaults, %$key });
1433  
1434 21 my $table = $self->TableName($table_name);
1435 21 my ($parts, $params) = $self->_where_parts($key);
1436 21 my $row = $self->hash('SELECT * FROM ' . $self->_quote_ident_path($table)
1437 . ' WHERE ' . join(' AND ', @$parts), @$params);
1438 21 ▶ return wantarray ? ($row, $created) : $row;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 14 7 21
1439 35 }
1440  
1441 2 ▶ method extra_args ($skeel, %args) {
Subroutine extra_args: called CC=2 SCAR=7.3
Pod undocumented
1442 2 ▶ if ($args{time}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"time"}) 2 0 2
1443 2 $self->_safe_id($args{time});
1444 0 $skeel->{ $args{time} } = $self->now();
1445 }
1446 0 return $skeel;
1447 35 }
1448  
1449 # :name -> ? rewrite, memoized per SQL text: the rewritten statement and
1450 # the placeholder order depend only on the text, so repeated execute()
1451 # calls skip the regex pass and just slice the bind values.
1452 35 field %_named_sql;
1453  
1454 3 ▶ method make_sen ($skeel) {
Subroutine make_sen: called CC=4 SCAR=13.9
Pod documented
1455 3 ▶ my $stmt = $sql // '';
Condition50%1/2
$sql // ""
l!l
30
MC/DC0%0/1
$sql // ""
$sql
Truth table50%1/2
A
A= $sql
Aresult
11
00
1456 3 ▶ my $parsed = $_named_sql{$stmt} //= do {
Condition33%1/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
030
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 table33%1/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
1457 3 _trim_cache(\%_named_sql, 1_000);
1458 3 my @names;
1459 # Single left-to-right pass: a quoted string literal is matched as a
1460 # unit and left untouched, so ':' inside it is never substituted. The
1461 # (?<![:\w]) lookbehind keeps the second colon of a Postgres '::cast'
1462 # (and back-to-back names) from matching.
1463 3 (my $out = $stmt) =~ s{
1464 ( '[^']*' | "[^"]*" ) # $1: quoted literal -> leave as-is
1465 |
1466 (?<![:\w]) : ([A-Za-z_]\w*) # $2: named placeholder -> bind
1467 }{
1468 5 ▶ defined $1 ? $1 : do { push @names, $2; '?' }
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 1 4 5
1469 }gex;
1470 3 [ $out, \@names ];
1471 };
1472  
1473 3 $sql = $parsed->[0];
1474 # A hash slice yields undef for a missing name without autovivifying.
1475 3 $p = [ @{$skeel}{ @{ $parsed->[1] } } ];
1476 35 }
1477  
1478 174 ▶ method execute_prepare (@params) {
Subroutine execute_prepare: called CC=17 SCAR=38.4
Pod documented
1479 174 ▶ my $stmt = $sql // '';
Condition50%1/2
$sql // ""
l!l
1740
MC/DC0%0/1
$sql // ""
$sql
Truth table50%1/2
A
A= $sql
Aresult
11
00
1480  
1481 174 ▶ $self->Exception("execute_prepare(): SQL not set")
Branch: 1 branch
BranchTrueFalseTotal
unless length $stmt 0 174 174
1482 unless length $stmt;
1483  
1484 174 my $conn = $self->db;
1485 174 ▶ my $dbh = $conn && $conn->dbh
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = $conn && $conn->dbh or $self->Exception("execute_prepare(): No DB handle") 174 0 174
Condition33%1/3
$conn && $conn->dbh
!ll&&!rl&&r
00174
MC/DC0%0/2
$conn && $conn->dbh
$conn $conn->dbh
Truth table33%1/3
A && B
A= $connB= $conn->dbh
ABresult
0X0
100
111
1486 or $self->Exception("execute_prepare(): No DB handle");
1487 174 $_write_dbh = $dbh;
1488 174 Scalar::Util::weaken($_write_dbh); # never keeps a handle alive (fork/disconnect)
1489  
1490 # Binds first: if prepare fails, HandleError's error entry must carry this
1491 # statement's binds, not the previous query's.
1492 174 $p = \@params;
1493 174 $_affected_rows = undef;
1494  
1495 # 3-arg form: if an identical cached handle is still active, get a fresh one
1496 # instead of emitting a "still Active" warning (execute_prepare returns an
1497 # unfinished handle to the caller).
1498 174 ▶ my $sth = $self->_prepare($dbh, $stmt)
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->_prepare($dbh, $stmt) or $self->_db_fail('prepare() failed: ' . ($dbh->errstr // "unknown"), $dbh) 174 0 174
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
1499 or $self->_db_fail(
1500 "prepare() failed: " . ($dbh->errstr // 'unknown'), $dbh);
1501  
1502 # Timing inline (as in _fetch): _track would allocate a closure per write.
1503 174 my $rv;
1504 174 ▶ my $tracker = $_tracker && $_tracker->enabled ? $_tracker : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_tracker && $_tracker->enabled ? : 0 174 174
Condition33%1/3
$_tracker and $_tracker->enabled
!ll&&!rl&&r
17400
MC/DC0%0/2
$_tracker and $_tracker->enabled
$_tracker $_tracker->enabled
Truth table33%1/3
A and B
A= $_trackerB= $_tracker->enabled
ABresult
0X0
100
111
1505 174 ▶ if ($tracker || $_observe) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tracker or $_observe) { } 0 174 174
Condition33%1/3
$tracker or $_observe
l!l&&r!l&&!r
00174
MC/DC0%0/2
$tracker or $_observe
$tracker $_observe
Truth table33%1/3
A or B
A= $trackerB= $_observe
ABresult
1X1
011
000
1506 0 my $t0 = Time::HiRes::time();
1507 0 ▶ $rv = $sth->execute(@params)
Branch: 1 branch
BranchTrueFalseTotal
$rv = $sth->execute(@params) or $self->_db_fail('execute() failed: ' . ($sth->errstr // "unknown"), $sth) 0 0 0
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
1508 or $self->_db_fail("execute() failed: " . ($sth->errstr // 'unknown'), $sth);
1509 0 my $t1 = Time::HiRes::time();
1510 0 ▶ $tracker->add_query($stmt, $p, $t0, $t1) if $tracker;
Branch: 1 branch
BranchTrueFalseTotal
if $tracker 0 0 0
1511 0 ▶ $self->_observed($t1 - $t0) if $_observe;
Branch: 1 branch
BranchTrueFalseTotal
if $_observe 0 0 0
1512 }
1513 else {
1514 174 ▶ $rv = $sth->execute(@params)
Branch: 1 branch
BranchTrueFalseTotal
$rv = $sth->execute(@params) or $self->_db_fail('execute() failed: ' . ($sth->errstr // "unknown"), $sth) 167 1 168
Condition50%1/2
$sth->errstr // "unknown"
l!l
10
MC/DC0%0/1
$sth->errstr // "unknown"
$sth->errstr
Truth table50%1/2
A
A= $sth->errstr
Aresult
11
00
1515 or $self->_db_fail("execute() failed: " . ($sth->errstr // 'unknown'), $sth);
1516 }
1517  
1518 167 $last_sql = $stmt;
1519 167 $_affected_rows = _affected($sth, $rv);
1520  
1521 167 return $sth;
1522 35 }
1523  
1524 }
1525  
1526 35 1;
1527  
1528 __END__
« Fast/Profile/Pg.pm ↑ Summary Fast.pm »