Fast.pm

filter: Statementstmt 82.2% 584 / 710 Branchbran 68.9% 160 / 232 Conditioncond 54.2% 90 / 166 MC/DCmcdc 29.7% 28 / 94 Subroutinesub 85.9% 67 / 78 Podpod 100% 33 / 33 totaltotal 73.2% 962 / 1313 CC 205 SCAR 29.9
CC
205
Cov
75%
configure_file
182.0
metrics_text
90.0
_check_on_slow_query
72.0
CRAP 19.9
« Fast/SQL.pm ↑ Summary Fast/Transaction.pm »
1 package DBIx::Fast;
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  
8 35 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 35 ▶use DBIx::Fast::Connector;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 35 ▶use DBIx::Fast::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 35 ▶use DBIx::Fast::SQL;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 # SQL::Abstract is required lazily in ADJUST, only when abstract => 1.
13  
14 35 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 35 ▶use DBIx::Fast::X;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 35 ▶use Time::HiRes 'time';
Subroutine BEGIN: called CC=1 SCAR=0.0
17 35 ▶use Scalar::Util qw(weaken blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19  
20 # The query and CRUD methods (and the statement state sql/p/results/last_id/
21 # last_sql they drive) are composed in from the DBIx::Fast::SQL role - see
22 # that module. Object::Pad classes cannot span files.
23 # Usage error from a class method (no instance to call Exception on): the
24 # same DBIx::Fast::X::Usage object and "Exception: ..." text.
25 10 ▶sub _croak_usage ($msg) {
Subroutine _croak_usage: called CC=1 SCAR=0.0
26 10 die DBIx::Fast::X::Usage->new(message => "Exception: $msg" . Carp::shortmess(),
27 error => $msg);
28 }
29  
30 # Connection registry (configure/connect): name => constructor args, and
31 # name => [ instance, owner pid ]. Per process - a forked child builds its own
32 # instance (the inherited one is neutralized by the Connector).
33 35 my %REGISTRY_ARGS;
34 my %REGISTRY;
35  
36 class DBIx::Fast :does(DBIx::Fast::SQL) {
37  
38 # Public fields. $db stays writable; the driver-aware SQL::Abstract
39 # instance is :reader only, so callers cannot clobber it (ranks 17/27).
40 field $db :accessor = undef;
41 821 ▶ field $Q :reader = undef;
Subroutine db: called CC=2 SCAR=7.1
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ and $db = shift() 0 821 821
42  
43 # Internal state with readers
44 113 ▶ field $_args :reader(args) = undef;
Subroutine Q: called CC=1 SCAR=0.0
Pod documented
45 19 ▶ field $_dbd :reader(dbd) = undef;
Subroutine args: called CC=1 SCAR=0.0
Pod documented
46 236 ▶ field $_dsn :reader(dsn) = undef;
Subroutine dbd: called CC=1 SCAR=0.0
Pod documented
47 0 ▶ field $_errors :reader(errors) = [];
Subroutine dsn: not called CC=1 SCAR=1.2
Pod documented
48 10 ▶ field $_last_error :reader(last_error) = undef;
Subroutine errors: called CC=1 SCAR=0.0
Pod documented
49  
50 # Lazy subsystems
51 1 ▶ field $_schema;
Subroutine last_error: called CC=1 SCAR=0.0
Pod documented
52 35 field $_transaction;
53 35 field $_profiler;
54 35 field $_query_tracker;
55 35 field $_cache;
56 35 field %_extensions;
57 35 field %_qid; # _quote_ident_path memo
58 35 field $_cache_ns; # cached() key namespace memo (see _cache_ns)
59  
60  
61 # Constructor params
62 field $_init_db :param(db) = undef;
63 35 field $_init_dsn :param(dsn) = '';
64 35 field $_init_SQLite :param(SQLite) = undef;
65 35 field $_init_driver :param(driver) = '';
66 35 field $_init_user :param(user) = '';
67 35 field $_init_password :param(password) = '';
68 35 field $_init_host :param(host) = '';
69 35 field $_init_port :param(port) = undef;
70 35 field $_init_tn :param(tn) = 0;
71 # Vestigial: accepted (and stored in args) for backward compatibility, but
72 # has no effect. Identifier quoting is automatic and driver-aware (see the
73 # SQL::Abstract quote_char below and _quote_id). The old on_connect used to
74 # call $dbh->quote($quote) - which quotes a VALUE and discards it, a no-op.
75 35 field $_init_quote :param(quote) = '';
76 35 field $_init_trace :param(trace) = '';
77 35 field $_init_profile :param(profile) = '';
78 35 field $_init_abstract :param(abstract) = 1;
79 35 field $_init_RaiseError :param(RaiseError) = undef;
80 35 field $_init_PrintError :param(PrintError) = undef;
81 35 field $_init_AutoCommit :param(AutoCommit) = undef;
82 35 field $_init_mysql_utf8 :param(mysql_enable_utf8) = 0;
83 35 field $_init_Error :param(Error) = undef; # Compat: use RaiseError/PrintError
84 35 field $_init_max_errors :param(max_errors) = 100;
85 35 field $_init_errors_redact :param(errors_redact) = 0;
86 35 field $_init_cache :param(cache) = undef;
87 # Error reporting / read strictness / per-connection SQL (see POD).
88 35 field $_init_on_error :param(on_error) = undef;
89 35 field $_init_strict_reads :param(strict_reads) = 0;
90 35 field $_init_on_connect_sql :param(on_connect_sql) = undef;
91 35 field $_err_seq = 0; # monotonic error sequence (error_mark/errors_since)
92 # Automatic created/updated columns (see POD "timestamps").
93 35 field $_init_timestamps :param(timestamps) = undef;
94 # JSON-encoded columns (see POD "json_columns"); handled by the SQL role.
95 35 field $_init_json_columns :param(json_columns) = undef;
96 # Coderef called after every CRUD write (see POD "after_write").
97 35 field $_init_after_write :param(after_write) = undef;
98 # { ms => N, cb => sub {...} }: report statements slower than N ms.
99 35 field $_init_on_slow_query :param(on_slow_query) = undef;
100 # 1 or a label: count statements, durations and errors (see metrics_text).
101 35 field $_init_metrics :param(metrics) = undef;
102 35 field $_metrics_label = 'default';
103 # Profiler output routing (see DBIx::Fast::Output): 'text' | 'json' | coderef,
104 # plus an optional filehandle. Applied to both tracker() and profiler().
105 35 field $_init_profile_output :param(profile_output) = undef;
106 35 field $_init_profile_output_fh :param(profile_output_fh) = undef;
107  
108 35 ADJUST {
109 # SQLite shortcut
110 if ($_init_SQLite) {
111 $_init_db //= $_init_SQLite;
112 $_init_driver = 'SQLite';
113 }
114  
115 # Build processed config
116 $_args = {
117 DBI => {
118 AutoCommit => $_init_AutoCommit // 1,
119 RaiseError => $_init_RaiseError // 1,
120 PrintError => $_init_PrintError // 0
121 },
122 Auth => {
123 user => $_init_user,
124 password => $_init_password,
125 host => $_init_host,
126 port => $_init_port,
127 },
128 tn => $_init_tn,
129 db => $_init_db // '',
130 dsn => $_init_dsn,
131 driver => $_init_driver,
132 quote => $_init_quote,
133 trace => $_init_trace,
134 profile => $_init_profile,
135 abstract => $_init_abstract,
136 };
137
138 # SQLite file check
139 if ($_init_SQLite) {
140 $self->Exception("No DB Found : $_init_SQLite")
141 unless -e $_init_SQLite;
142 }
143  
144 unless ($_args->{dsn} || $_args->{db}) {
145 $self->Exception("Need a DSN or Host");
146 }
147  
148 $_dsn = $_args->{dsn}
149 ? $self->_check_dsn($_args->{dsn})
150 : $self->_make_dsn($_args);
151  
152 # Map the UTF-8 flag to the driver-appropriate attribute now that $_dbd is
153 # resolved: DBD::MariaDB ignores mysql_enable_utf8 (it honours
154 # mariadb_enable_utf8mb4), so applying it driver-blind silently fails.
155 if ($_init_mysql_utf8) {
156 if ($_dbd eq 'MariaDB') { $_args->{DBI}{mariadb_enable_utf8mb4} = 1 }
157 elsif ($_dbd eq 'mysql') { $_args->{DBI}{mysql_enable_utf8mb4} = 1 }
158 }
159  
160 if ($_args->{abstract}) {
161 require SQL::Abstract;
162 my $qchar =
163 ($_dbd eq 'MariaDB' || $_dbd eq 'mysql') ? '`' : '"';
164 $Q = SQL::Abstract->new(quote_char => $qchar, name_sep => '.');
165 }
166  
167 # Per-connection setup, run on every (re)connect with the fresh handle so
168 # HandleError/trace/quote/Profile survive a reconnect (rank 9). Capture only
169 # plain lexicals (and a WEAKENED $self) - capturing a field or a strong
170 # $self here would re-form the reference cycle weaken() is meant to break
171 # (rank 2). Uses the passed $dbh, never $db->dbh, to avoid re-entering the
172 # Connector during a (re)connect.
173 my $weak_self = $self;
174 weaken($weak_self);
175 my $trace_opt = $_args->{trace};
176 my $profile = $_args->{profile};
177  
178 $self->Exception("on_connect_sql must be an arrayref of statements")
179 if defined $_init_on_connect_sql && ref $_init_on_connect_sql ne 'ARRAY';
180 my @init_sql = @{ $_init_on_connect_sql // [] }; # lexical copy
181  
182 my $on_connect = sub ($dbh) {
183 return unless $dbh;
184 # Statement handles belong to one connection (see SQL.pm _prepare).
185 $weak_self->_reset_sth_cache if $weak_self;
186 $dbh->{HandleError} = sub ($msg, $h, @) {
187 return 0 unless $weak_self;
188 $weak_self->set_error($DBI::err, $DBI::errstr);
189 $weak_self->_count_error(DBIx::Fast::X::DB->class_for(
190 $weak_self->dbd // '', $DBI::err, $DBI::state, $DBI::errstr))
191 if $weak_self->metrics_on;
192 # RaiseError: throw a typed exception instead of DBI's string. It
193 # stringifies to the very text DBI would have died with (the location
194 # from shortmess matches DBI's), so string matching keeps working.
195 if ($h && $h->{RaiseError}) {
196 my $text = $msg . Carp::shortmess();
197 # DBI warns (PrintError) before it dies; dying here skips that.
198 warn $text if $h->{PrintError};
199 die $weak_self->_db_exception($text, $h);
200 }
201 return 0; # RaiseError off: let DBI carry on (PrintError)
202 };
203 $dbh->trace($trace_opt, 'dbix-fast-trace') if $trace_opt;
204 $dbh->{Profile} = $profile . "/DBI::ProfileDumper/File:dbix-fast-$$.log"
205 if $profile;
206 # Session setup (SET NAMES, time_zone, PRAGMA ...) re-applied on every
207 # reconnect, which a one-off $db->exec after construction is not.
208 $dbh->do($_) for @init_sql;
209 };
210  
211 # Handle db param: connector object or string
212 if ($_init_db && ref($_init_db)) {
213 $db = $_init_db;
214 } else {
215 $db = DBIx::Fast::Connector->new(
216 dsn => $_dsn,
217 user => $_args->{Auth}->{user},
218 pass => $_args->{Auth}->{password},
219 attrs => $_args->{DBI},
220 on_connect => $on_connect,
221 );
222 }
223  
224 # Apply now to the initial handle (and to an injected connector, whose
225 # reconnects we do not control).
226 $on_connect->($db->dbh);
227  
228 if (defined $_init_timestamps) {
229 $self->_check_timestamps;
230 $self->_timestamps_on;
231 }
232 $self->_configure_json($_init_json_columns) if defined $_init_json_columns;
233 $self->_set_after_write($_init_after_write) if defined $_init_after_write;
234 $self->_cache_configured if defined $_init_cache;
235 $self->_check_on_slow_query if defined $_init_on_slow_query;
236 if ($_init_metrics) {
237 if ($_init_metrics ne '1') {
238 $self->Exception("metrics: label must match [A-Za-z0-9_.-]+")
239 unless $_init_metrics =~ /\A[\w.-]+\z/a;
240 $_metrics_label = $_init_metrics;
241 }
242 $self->_enable_metrics;
243 }
244  
245 $self->schema->_load_tables_name if $_args->{tn};
246 }
247  
248 # Validate the timestamps option once, at construction.
249 7 ▶ method _check_timestamps () {
Subroutine _check_timestamps: called CC=15 SCAR=27.3
250 7 my $ts = $_init_timestamps;
251 7 ▶ $self->Exception("timestamps must be a hashref") unless ref $ts eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ts eq "HASH" 1 6 7
252 6 for my $k (keys %$ts) {
253 10 ▶ $self->Exception("timestamps: unknown key '$k' (default, tables, source)")
Branch: 1 branch
BranchTrueFalseTotal
unless $k =~ /\A(?:default|tables|source)\z/u 1 9 10
254 unless $k =~ /\A(?:default|tables|source)\z/;
255 }
256 5 ▶ my $source = $ts->{source} // 'host';
Condition100%2/2
$ts->{"source"} // "host"
l!l
32
MC/DC100%1/1
$ts->{"source"} // "host"
$ts->{"source"}
Truth table100%2/2
A
A= $ts->{"source"}
Aresult
11
00
257 5 ▶ $self->Exception("timestamps: source must be host, utc or server")
Branch: 1 branch
BranchTrueFalseTotal
unless $source =~ /\A(?:host|utc|server)\z/u 1 4 5
258 unless $source =~ /\A(?:host|utc|server)\z/;
259  
260 4 ▶ my @specs = ($ts->{default} // ());
Condition33%1/3
$ts->{"default"} // ()
l!l&&r!l&&!r
400
MC/DC0%0/2
$ts->{"default"} // ()
$ts->{"default"} ()
Truth table33%1/3
A // B
A= $ts->{"default"}B= ()
ABresult
1X1
011
000
261 4 ▶ if (defined $ts->{tables}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ts->{"tables"}) 2 2 4
262 $self->Exception("timestamps: tables must be a hashref")
263 2 ▶ unless ref $ts->{tables} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ts->{"tables"} eq "HASH" 0 2 2
264 2 push @specs, values %{ $ts->{tables} };
265 }
266 4 for my $spec (@specs) {
267 8 ▶ $self->Exception("timestamps: each spec must be a hashref of created/updated")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 0 8 8
268 unless ref $spec eq 'HASH';
269 8 for my $k (keys %$spec) {
270 8 ▶ $self->Exception("timestamps: unknown spec key '$k' (created, updated)")
Branch: 1 branch
BranchTrueFalseTotal
unless $k eq "created" or $k eq "updated" 1 7 8
Condition100%3/3
$k eq "created" or $k eq "updated"
l!l&&r!l&&!r
341
MC/DC100%2/2
$k eq "created" or $k eq "updated"
$k eq "created" $k eq "updated"
Truth table100%3/3
A or B
A= $k eq "created"B= $k eq "updated"
ABresult
1X1
011
000
271 unless $k eq 'created' || $k eq 'updated';
272 7 ▶ $self->_safe_id($spec->{$k}) if defined $spec->{$k};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{$k} 7 0 7
273 }
274 }
275 35 }
276  
277 # (created_col, updated_col, value) for a table, or () when no timestamps
278 # apply. A tables entry replaces the default for that table entirely
279 # ({} disables timestamps there). The value is a plain timestamp string
280 # (source host/utc) or \'CURRENT_TIMESTAMP' (source server).
281 30 ▶ method _timestamps_for ($table) {
Subroutine _timestamps_for: called CC=10 SCAR=23.4
282 30 ▶ return () unless $_init_timestamps;
Branch: 1 branch
BranchTrueFalseTotal
unless $_init_timestamps 0 30 30
283 my $spec = $_init_timestamps->{tables} && exists $_init_timestamps->{tables}{$table}
284 ? $_init_timestamps->{tables}{$table}
285 30 ▶ : $_init_timestamps->{default};
Branch: 1 branch
BranchTrueFalseTotal
$_init_timestamps->{'tables'} && exists $_init_timestamps->{'tables'}{$table} ? : 4 26 30
Condition66%2/3
$_init_timestamps->{"tables"} and exists $_init_timestamps->{"tables"}{$table}
!ll&&!rl&&r
0264
MC/DC50%1/2
$_init_timestamps->{"tables"} and exists $_init_timestamps->{"tables"}{$table}
$_init_timestamps->{"tables"} exists $_init_timestamps->{"tables"}{$table}
Truth table66%2/3
A and B
A= $_init_timestamps->{"tables"}B= exists $_init_timestamps->{"tables"}{$table}
ABresult
0X0
100
111
286 30 ▶ return () unless $spec && ($spec->{created} || $spec->{updated});
Branch: 1 branch
BranchTrueFalseTotal
unless $spec and $spec->{"created"} || $spec->{"updated"} 2 28 30
Condition83%5/6
$spec and $spec->{"created"} || $spec->{"updated"}
!ll&&!rl&&r
0228
$spec->{"created"} or $spec->{"updated"}
l!l&&r!l&&!r
2622
MC/DC66%2/3
$spec and $spec->{"created"} || $spec->{"updated"}
$spec $spec->{"created"} $spec->{"updated"}
Truth table75%3/4
A and B or C
A= $specB= $spec->{"created"}C= $spec->{"updated"}
ABCresult
0XX0
1000
11X1
1011
287 28 ▶ my $source = $_init_timestamps->{source} // 'host';
Condition50%1/2
$_init_timestamps->{"source"} // "host"
l!l
280
MC/DC0%0/1
$_init_timestamps->{"source"} // "host"
$_init_timestamps->{"source"}
Truth table50%1/2
A
A= $_init_timestamps->{"source"}
Aresult
11
00
288 28 ▶ my $value = $source eq 'server' ? \'CURRENT_TIMESTAMP'
Branch: 2 branches
BranchTrueFalseTotal
$source eq 'server' ? : 14 14 28
$source eq 'utc' ? : 0 14 14
289 : $source eq 'utc' ? $self->now_utc
290 : $self->now;
291 28 return ($spec->{created}, $spec->{updated}, $value);
292 35 }
293  
294 # Setters for internal state (needed by tests and internal methods)
295 # (dsn/args feed the memoized cached() key namespace - drop it on change.)
296 1 ▶ method _set_args ($val) { $_args = $val; undef $_cache_ns }
Subroutine _set_args: called CC=1 SCAR=0.0
297 0 ▶ method _set_dbd ($val) { $_dbd = $val; $self->_dbd_reset }
Subroutine _set_dbd: not called CC=1 SCAR=4.9
298 0 ▶ method _set_dsn ($val) { $_dsn = $val; undef $_cache_ns }
Subroutine _set_dsn: not called CC=1 SCAR=4.9
299  
300 # Lazy subsystem accessors (loaded on demand)
301 28 ▶ method schema {
Subroutine schema: called CC=2 SCAR=7.0
Pod documented
302 28 ▶ $_schema //= do {
Condition66%2/3
$_schema //= do { require DBIx::Fast::Schema; "DBIx::Fast::Schema"->new("dbix", $self) }
l!l&&r!l&&!r
2440
MC/DC0%0/2
$_schema //= do { require DBIx::Fast::Schema; "DBIx::Fast::Schema"->new("dbix", $self) }
$_schema do { require DBIx::Fast::Schema; "DBIx::Fast::Schema"->new("dbix", $self) }
Truth table66%2/3
A //= B
A= $_schemaB= do { require DBIx::Fast::Schema; "DBIx::Fast::Schema"->new("dbix", $self) }
ABresult
1X1
011
000
303 4 require DBIx::Fast::Schema;
304 4 DBIx::Fast::Schema->new(dbix => $self);
305 };
306 35 }
307  
308 84 ▶ method transaction {
Subroutine transaction: called CC=2 SCAR=7.0
Pod documented
309 84 ▶ $_transaction //= do {
Condition66%2/3
$_transaction //= do { require DBIx::Fast::Transaction; "DBIx::Fast::Transaction"->new("dbix", $self) }
l!l&&r!l&&!r
7680
MC/DC0%0/2
$_transaction //= do { require DBIx::Fast::Transaction; "DBIx::Fast::Transaction"->new("dbix", $self) }
$_transaction do { require DBIx::Fast::Transaction; "DBIx::Fast::Transaction"->new("dbix", $self) }
Truth table66%2/3
A //= B
A= $_transactionB= do { require DBIx::Fast::Transaction; "DBIx::Fast::Transaction"->new("dbix", $self) }
ABresult
1X1
011
000
310 8 require DBIx::Fast::Transaction;
311 8 DBIx::Fast::Transaction->new(dbix => $self);
312 };
313 35 }
314  
315 # Only the profile_output* options the caller actually set, so the
316 # DBIx::Fast::Output role defaults apply otherwise.
317 7 ▶ method _output_opts {
Subroutine _output_opts: called CC=3 SCAR=11.2
318 return (
319 7 ▶ defined $_init_profile_output
Branch: 2 branches
BranchTrueFalseTotal
defined $_init_profile_output ? : 4 3 7
defined $_init_profile_output_fh ? : 0 7 7
320 ? (output => $_init_profile_output) : (),
321 defined $_init_profile_output_fh
322 ? (output_fh => $_init_profile_output_fh) : (),
323 );
324 35 }
325  
326 13 ▶ method tracker {
Subroutine tracker: called CC=2 SCAR=7.0
Pod documented
327 13 ▶ $_query_tracker //= do {
Condition66%2/3
$_query_tracker //= do { require DBIx::Fast::Profiler; my $t = "DBIx::Fast::Profiler"->new("dbix", $self, "auto_print", 0, $self->_output_opts); $self->_tracker_created($t); $t }
l!l&&r!l&&!r
940
MC/DC0%0/2
$_query_tracker //= do { require DBIx::Fast::Profiler; my $t = "DBIx::Fast::Profiler"->new("dbix", $self, "auto_print", 0, $self->_output_opts); $self->_tracker_created($t); $t }
$_query_tracker do { require DBIx::Fast::Profiler; my $t = "DBIx::Fast::Profiler"->new("dbix", $self, "auto_print", 0, $self->_output_opts); $self->_tracker_created($t); $t }
Truth table66%2/3
A //= B
A= $_query_trackerB= do { require DBIx::Fast::Profiler; my $t = "DBIx::Fast::Profiler"->new("dbix", $self, "auto_print", 0, $self->_output_opts); $self->_tracker_created($t); $t }
ABresult
1X1
011
000
328 4 require DBIx::Fast::Profiler;
329 4 my $t = DBIx::Fast::Profiler->new(dbix => $self, auto_print => 0,
330 $self->_output_opts);
331 4 $self->_tracker_created($t);
332 4 $t;
333 };
334 35 }
335  
336 # Non-vivifying tracker lookup for the SQL role's _track: going through
337 # tracker() would instantiate the profiler and turn tracking on for every
338 # query from then on.
339 0 ▶ method _active_tracker {
Subroutine _active_tracker: not called CC=3 SCAR=24.8
340 0 ▶ return $_query_tracker && $_query_tracker->enabled
Branch: 1 branch
BranchTrueFalseTotal
$_query_tracker && $_query_tracker->enabled ? : 0 0 0
Condition0%0/3
$_query_tracker and $_query_tracker->enabled
!ll&&!rl&&r
000
MC/DC0%0/2
$_query_tracker and $_query_tracker->enabled
$_query_tracker $_query_tracker->enabled
Truth table0%0/3
A and B
A= $_query_trackerB= $_query_tracker->enabled
ABresult
0X0
100
111
341 ? $_query_tracker : undef;
342 35 }
343  
344 # Returns the cache instance if `cache => {...}` was passed at construction,
345 # otherwise undef. Caching is opt-in to keep zero-overhead for users that
346 # don't need it.
347 90 ▶ method cache {
Subroutine cache: called CC=4 SCAR=13.9
Pod documented
348 90 ▶ return $_cache if $_cache;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache 82 8 90
349 # Truthiness, not defined-ness: `cache => 0` / `''` (a common "disable"
350 # idiom, e.g. `cache => $enabled ? {...} : 0`) must NOT switch caching on.
351 8 ▶ return undef unless $_init_cache;
Branch: 1 branch
BranchTrueFalseTotal
unless $_init_cache 2 6 8
352  
353 6 require DBIx::Fast::Cache;
354 6 ▶ my %opts = ref $_init_cache eq 'HASH' ? %{$_init_cache} : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $_init_cache eq 'HASH' ? : 6 0 6
355 6 $_cache = DBIx::Fast::Cache->new(%opts);
356 35 }
357  
358 # Returns a query proxy that caches results. If cache is disabled,
359 # the proxy still works but transparently bypasses the cache.
360 39 ▶ method cached (%opts) {
Subroutine cached: called CC=1 SCAR=0.0
Pod documented
361 39 require DBIx::Fast::Cached;
362 39 DBIx::Fast::Cached->new(dbix => $self, %opts);
363 35 }
364  
365 # Connection identity prefix for DBIx::Fast::Cached keys: dsn and user are
366 # fixed after construction, so build it once instead of once per proxy.
367 39 ▶ method _cache_ns () {
Subroutine _cache_ns: called CC=4 SCAR=14.2
368 39 ▶ $_cache_ns //= ($_dsn // '') . "\0" . ($_args->{Auth}{user} // '') . "\0";
Condition66%4/6
$_cache_ns //= ($_dsn // "") . "\000" . ($_args->{"Auth"}{"user"} // "") . "\000"
l!l
327
$_dsn // ""
l!l
70
$_args->{"Auth"}{"user"} // ""
l!l
70
MC/DC100%1/1
$_cache_ns //= ($_dsn // "") . "\000" . ($_args->{"Auth"}{"user"} // "") . "\000"
$_cache_ns
MC/DC0%0/1
$_args->{"Auth"}{"user"} // ""
$_args->{"Auth"}{"user"}
Truth table100%2/2
A
A= $_cache_ns
Aresult
11
00
Truth table50%1/2
A
A= $_args->{"Auth"}{"user"}
Aresult
11
00
369 35 }
370  
371 6 ▶ method profiler {
Subroutine profiler: called CC=3 SCAR=11.6
Pod documented
372 6 ▶ return $_profiler if $_profiler;
Branch: 1 branch
BranchTrueFalseTotal
if $_profiler 3 3 6
373  
374 3 my $driver = $_dbd;
375 3 my $profile_class = "DBIx::Fast::Profile::$driver";
376  
377 3 (my $_pf = "$profile_class.pm") =~ s|::|/|g; eval { require $_pf };
378  
379 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3 3
380 0 warn "No profile support for $driver, using base profile";
381 0 require DBIx::Fast::Profile::Base;
382 0 $_profiler = DBIx::Fast::Profile::Base->new(dbix => $self,
383 $self->_output_opts);
384 0 return $_profiler;
385 }
386  
387 3 $_profiler = $profile_class->new(dbix => $self, $self->_output_opts);
388 3 $_profiler->init();
389  
390 3 return $_profiler;
391 35 }
392  
393 # Transaction helper
394 25 ▶ method txn ($code, $options = undef) {
Subroutine txn: called CC=2 SCAR=6.9
Pod documented
395 25 return $self->transaction->do($code, $options);
396 35 }
397  
398 5 ▶ method load_extension ($extension) {
Subroutine load_extension: called CC=6 SCAR=19.4
Pod documented
399 # A module name, not a path: "../../evil" or "Foo'Bar" would otherwise
400 # require an arbitrary .pm from outside the DBIx::Fast namespace.
401 5 ▶ $self->Exception("Invalid extension name")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $extension and $extension =~ /\A[A-Za-z]\w*(?:::\w+)*\z/u 4 1 5
Condition66%2/3
defined $extension and $extension =~ /\A[A-Za-z]\w*(?:::\w+)*\z/u
!ll&&!rl&&r
041
MC/DC50%1/2
defined $extension and $extension =~ /\A[A-Za-z]\w*(?:::\w+)*\z/u
defined $extension $extension =~ /\A[A-Za-z]\w*(?:::\w+)*\z/u
Truth table66%2/3
A and B
A= defined $extensionB= $extension =~ /\A[A-Za-z]\w*(?:::\w+)*\z/u
ABresult
0X0
100
111
402 unless defined $extension && $extension =~ /\A[A-Za-z]\w*(?:::\w+)*\z/;
403  
404 1 my $module = "DBIx::Fast::$extension";
405  
406 1 (my $_mf = "$module.pm") =~ s|::|/|g; eval { require $_mf };
407 1 ▶ $self->Exception("Error: load_extension => $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
408  
409 1 my $attr = lc($extension);
410  
411 # Check if there's already a method for this
412 1 ▶ if ($self->can($attr)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can($attr)) 1 0 1
413 1 return $self->$attr;
414 }
415  
416 0 ▶ return $_extensions{$attr} if exists $_extensions{$attr};
Branch: 1 branch
BranchTrueFalseTotal
if exists $_extensions{$attr} 0 0 0
417  
418 0 $_extensions{$attr} = $module->new(dbix => $self);
419 0 return $_extensions{$attr};
420 35 }
421  
422 # --- Connection registry -------------------------------------------------
423  
424 # Register named connections: name => { constructor args }. Nothing
425 # connects here. Re-registering a name replaces its arguments and drops the
426 # instance built from the old ones.
427 10 ▶ method configure :common (%conf) {
Subroutine configure: called CC=7 SCAR=19.5
Pod documented
428 10 ▶ _croak_usage("configure: name => { constructor args } pairs required")
Branch: 1 branch
BranchTrueFalseTotal
unless %conf 2 8 10
429 unless %conf;
430 8 for my $name (keys %conf) {
431 10 ▶ _croak_usage("configure: invalid connection name")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and $name =~ /\A[A-Za-z_][\w.-]*\z/u 2 8 10
Condition66%2/3
defined $name and $name =~ /\A[A-Za-z_][\w.-]*\z/u
!ll&&!rl&&r
028
MC/DC50%1/2
defined $name and $name =~ /\A[A-Za-z_][\w.-]*\z/u
defined $name $name =~ /\A[A-Za-z_][\w.-]*\z/u
Truth table66%2/3
A and B
A= defined $nameB= $name =~ /\A[A-Za-z_][\w.-]*\z/u
ABresult
0X0
100
111
432 unless defined $name && $name =~ /\A[A-Za-z_][\w.-]*\z/;
433 _croak_usage("configure: arguments for '$name' must be a hashref")
434 8 ▶ unless ref $conf{$name} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $conf{$name} eq "HASH" 2 6 8
435 }
436 4 for my $name (keys %conf) {
437 6 $REGISTRY_ARGS{$name} = { %{ $conf{$name} } };
438 6 delete $REGISTRY{$name};
439 }
440 4 return $class;
441 35 }
442  
443 # The process-wide instance for a configured name, built on first use and
444 # rebuilt in a forked child. One connection per name per process instead of
445 # one per caller.
446 24 ▶ method connect :common ($name) {
Subroutine connect: called CC=5 SCAR=16.1
Pod documented
447 24 my $slot = $REGISTRY{$name};
448 24 ▶ return $slot->[0] if $slot && $slot->[1] == $$;
Branch: 1 branch
BranchTrueFalseTotal
if $slot and $slot->[1] == $$ 9 15 24
Condition100%3/3
$slot and $slot->[1] == $$
!ll&&!rl&&r
1419
MC/DC100%2/2
$slot and $slot->[1] == $$
$slot $slot->[1] == $$
Truth table100%3/3
A and B
A= $slotB= $slot->[1] == $$
ABresult
0X0
100
111
449 15 ▶ my $args = $REGISTRY_ARGS{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $args = $REGISTRY_ARGS{$name} or _croak_usage(q[connect: no connection configured as '] . ($name // "undef") . q[' (see configure)]) 11 4 15
Condition50%1/2
$name // "undef"
l!l
40
MC/DC0%0/1
$name // "undef"
$name
Truth table50%1/2
A
A= $name
Aresult
11
00
450 or _croak_usage("connect: no connection configured as '"
451 . ($name // 'undef') . "' (see configure)");
452 11 my $db = $class->new(%$args);
453 11 $db->_registry_label($name);
454 11 $REGISTRY{$name} = [ $db, $$ ];
455 11 return $db;
456 35 }
457  
458 # Names currently configured.
459 2 ▶ method configured :common () { return sort keys %REGISTRY_ARGS }
Subroutine configured: called CC=1 SCAR=0.0
Pod documented
460  
461 # configure() from a JSON file read once: either the whole file is
462 # name => { args }, or name => 'dotted.path' picks each connection's args.
463 # DBIx::Fast->configure_file('/etc/app/db.json', app => 'db', logs => 'db.logs');
464 0 ▶ method configure_file :common ($file, %map) {
Subroutine configure_file: not called CC=13 SCAR=52.0
Pod documented
465 0 ▶ _croak_usage("configure_file: file path required")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file and length $file 0 0 0
Condition0%0/3
defined $file and length $file
!ll&&!rl&&r
000
MC/DC0%0/2
defined $file and length $file
defined $file length $file
Truth table0%0/3
A and B
A= defined $fileB= length $file
ABresult
0X0
100
111
466 unless defined $file && length $file;
467 0 ▶ open my $fh, '<:raw', $file
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $file or _croak_usage("configure_file: cannot read '${file}': $!") 0 0 0
468 or _croak_usage("configure_file: cannot read '$file': $!");
469 0 my $raw = do { local $/; <$fh> };
470 0 close $fh;
471 0 my $codec = eval { require Cpanel::JSON::XS; Cpanel::JSON::XS->new->utf8 }
472 0 ▶ || do { require JSON::PP; JSON::PP->new->utf8 };
Condition0%0/3
eval { do { require Cpanel::JSON::XS; 'Cpanel::JSON::XS'->new->utf8 } } || do { require JSON::PP; 'JSON::PP'->new->utf8 }
l!l&&r!l&&!r
000
MC/DC0%0/2
eval { do { require Cpanel::JSON::XS; 'Cpanel::JSON::XS'->new->utf8 } } || do { require JSON::PP; 'JSON::PP'->new->utf8 }
eval { do { require Cpanel::JSON::XS; 'Cpanel::JSON::XS'->new->utf8 } } do { require JSON::PP; 'JSON::PP'->new->utf8 }
Truth table0%0/3
A || B
A= eval { do { require Cpanel::JSON::XS; 'Cpanel::JSON::XS'->new->utf8 } }B= do { require JSON::PP; 'JSON::PP'->new->utf8 }
ABresult
1X1
011
000
473 # Never echo the parser's message: it quotes the file (credentials).
474 0 my $conf = eval { $codec->decode($raw) };
475 0 ▶ _croak_usage("configure_file: '$file' is not a valid JSON object")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $conf eq "HASH" 0 0 0
476 unless ref $conf eq 'HASH';
477 0 my %args;
478 0 ▶ if (%map) {
Branch: 1 branch
BranchTrueFalseTotal
if (%map) { } 0 0 0
479 0 for my $name (keys %map) {
480 0 my $node = $conf;
481 0 ▶ for my $k (split /\./, $map{$name} // '') {
Condition0%0/2
$map{$name} // ""
l!l
00
MC/DC0%0/1
$map{$name} // ""
$map{$name}
Truth table0%0/2
A
A= $map{$name}
Aresult
11
00
482 0 ▶ $node = ref $node eq 'HASH' ? $node->{$k} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $node eq 'HASH' ? : 0 0 0
483 }
484 0 ▶ _croak_usage("configure_file: '" . ($map{$name} // '') . "' not found in '$file'")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node eq "HASH" 0 0 0
Condition0%0/2
$map{$name} // ""
l!l
00
MC/DC0%0/1
$map{$name} // ""
$map{$name}
Truth table0%0/2
A
A= $map{$name}
Aresult
11
00
485 unless ref $node eq 'HASH';
486 0 $args{$name} = $node;
487 }
488 }
489 else {
490 0 %args = %$conf;
491 }
492 0 return $class->configure(%args);
493 35 }
494  
495 # Prometheus text format for this instance (called on an object) or for
496 # every registry connection of this process with metrics on (class call).
497 0 ▶ sub metrics_text ($inv) {
Subroutine metrics_text: not called CC=9 SCAR=45.0
Pod documented
498 my @dbs = ref $inv ? ($inv)
499 0 ▶ : map { $REGISTRY{$_}[0] } grep { $REGISTRY{$_}[1] == $$ } sort keys %REGISTRY;
Branch: 1 branch
BranchTrueFalseTotal
ref $inv ? : 0 0 0
500 0 my %fam; # family => [ lines ]
501 0 ▶ for my $db (grep { $_ && $_->metrics_on } @dbs) {
Condition0%0/3
$_ && $_->metrics_on
!ll&&!rl&&r
000
MC/DC0%0/2
$_ && $_->metrics_on
$_ $_->metrics_on
Truth table0%0/3
A && B
A= $_B= $_->metrics_on
ABresult
0X0
100
111
502 0 my $m = $db->metrics;
503 0 my $l = sprintf 'db="%s",pid="%d"', $db->metrics_label, $$;
504 0 push @{ $fam{queries} }, "dbix_fast_queries_total{$l} $m->{queries}";
505 0 for my $le (@DBIx::Fast::SQL::BUCKETS) {
506 0 push @{ $fam{duration} }, qq{dbix_fast_query_duration_seconds_bucket{$l,le="$le"} $m->{buckets}{$le}};
507 }
508 0 push @{ $fam{duration} },
509 qq{dbix_fast_query_duration_seconds_bucket{$l,le="+Inf"} $m->{queries}},
510 0 "dbix_fast_query_duration_seconds_sum{$l} " . (0 + sprintf('%.6f', $m->{seconds})),
511 "dbix_fast_query_duration_seconds_count{$l} $m->{queries}";
512 0 push @{ $fam{slow} }, "dbix_fast_slow_queries_total{$l} $m->{slow}";
513 0 push @{ $fam{errors} }, qq{dbix_fast_errors_total{$l,class="$_"} $m->{errors}{$_}}
514 0 for sort keys %{ $m->{errors} };
515 0 ▶ if (defined $m->{cache_hits}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $m->{"cache_hits"}) 0 0 0
516 0 push @{ $fam{cache_hits} }, "dbix_fast_cache_hits_total{$l} $m->{cache_hits}";
517 0 push @{ $fam{cache_misses} }, "dbix_fast_cache_misses_total{$l} $m->{cache_misses}";
518 }
519 }
520 0 my @families = (
521 [ queries => 'dbix_fast_queries_total', 'counter', 'Statements executed.' ],
522 [ duration => 'dbix_fast_query_duration_seconds', 'histogram', 'Statement execution time.' ],
523 [ slow => 'dbix_fast_slow_queries_total', 'counter', 'Statements over the on_slow_query threshold.' ],
524 [ errors => 'dbix_fast_errors_total', 'counter', 'Database errors by DBIx::Fast::X class.' ],
525 [ cache_hits => 'dbix_fast_cache_hits_total', 'counter', 'Result cache hits.' ],
526 [ cache_misses => 'dbix_fast_cache_misses_total', 'counter', 'Result cache misses.' ],
527 );
528 0 my $out = '';
529 0 for my $f (@families) {
530 0 my ($key, $name, $type, $help) = @$f;
531 0 ▶ next unless $fam{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $fam{$key} 0 0 0
532 0 $out .= "# HELP $name $help\n# TYPE $name $type\n" . join("\n", @{ $fam{$key} }) . "\n";
533 }
534 0 return $out;
535 }
536  
537 # Drop a name's instance (and, with forget, its configuration). An instance
538 # still referenced elsewhere keeps working; the registry just stops handing
539 # it out.
540 2 ▶ method forget :common ($name) {
Subroutine forget: called CC=1 SCAR=0.0
Pod documented
541 2 delete $REGISTRY{$name};
542 2 delete $REGISTRY_ARGS{$name};
543 2 return;
544 35 }
545  
546 # Disconnect and drop every instance this process built (the configuration
547 # stays, so connect() reconnects). For orderly shutdown and tests.
548 3 ▶ method disconnect_all :common () {
Subroutine disconnect_all: called CC=4 SCAR=14.2
Pod documented
549 3 for my $name (keys %REGISTRY) {
550 5 my ($db, $pid) = @{ $REGISTRY{$name} };
551 5 ▶ eval { $db->db->disconnect } if $db && $pid == $$;
Branch: 1 branch
BranchTrueFalseTotal
if $db and $pid == $$ 5 0 5
Condition33%1/3
$db and $pid == $$
!ll&&!rl&&r
005
MC/DC0%0/2
$db and $pid == $$
$db $pid == $$
Truth table33%1/3
A and B
A= $dbB= $pid == $$
ABresult
0X0
100
111
552 5 delete $REGISTRY{$name};
553 }
554 3 return;
555 35 }
556  
557 14 ▶ method metrics_on () { return $_init_metrics ? 1 : 0 }
Subroutine metrics_on: called CC=2 SCAR=7.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$_init_metrics ? : 0 14 14
558  
559 0 ▶ method metrics_label () { return $_metrics_label }
Subroutine metrics_label: not called CC=1 SCAR=4.1
Pod documented
560  
561 # connect(): label the metrics with the registry name unless one was given.
562 11 ▶ method _registry_label ($name) {
Subroutine _registry_label: called CC=3 SCAR=11.8
563 11 ▶ $_metrics_label = $name if $_init_metrics && $_init_metrics eq '1';
Branch: 1 branch
BranchTrueFalseTotal
if $_init_metrics and $_init_metrics eq 1 0 11 11
Condition33%1/3
$_init_metrics and $_init_metrics eq 1
!ll&&!rl&&r
1100
MC/DC0%0/2
$_init_metrics and $_init_metrics eq 1
$_init_metrics $_init_metrics eq 1
Truth table33%1/3
A and B
A= $_init_metricsB= $_init_metrics eq 1
ABresult
0X0
100
111
564 35 }
565  
566 0 ▶ method _check_on_slow_query () {
Subroutine _check_on_slow_query: not called CC=8 SCAR=42.8
567 0 my $o = $_init_on_slow_query;
568 0 ▶ $self->Exception("on_slow_query must be a hashref { ms => N, cb => sub {...} }")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $o eq "HASH" 0 0 0
569 unless ref $o eq 'HASH';
570 0 for my $k (keys %$o) {
571 0 ▶ $self->Exception("on_slow_query: unknown key '$k' (ms, cb)") unless $k eq 'ms' || $k eq 'cb';
Branch: 1 branch
BranchTrueFalseTotal
unless $k eq "ms" or $k eq "cb" 0 0 0
Condition0%0/3
$k eq "ms" or $k eq "cb"
l!l&&r!l&&!r
000
MC/DC0%0/2
$k eq "ms" or $k eq "cb"
$k eq "ms" $k eq "cb"
Truth table0%0/3
A or B
A= $k eq "ms"B= $k eq "cb"
ABresult
1X1
011
000
572 }
573 $self->Exception("on_slow_query: ms must be a number >= 0")
574 0 ▶ unless defined $o->{ms} && $o->{ms} =~ /\A\d+(?:\.\d+)?\z/a;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $o->{"ms"} and $o->{"ms"} =~ /\A\d+(?:\.\d+)?\z/a 0 0 0
Condition0%0/3
defined $o->{"ms"} and $o->{"ms"} =~ /\A\d+(?:\.\d+)?\z/a
!ll&&!rl&&r
000
MC/DC0%0/2
defined $o->{"ms"} and $o->{"ms"} =~ /\A\d+(?:\.\d+)?\z/a
defined $o->{"ms"} $o->{"ms"} =~ /\A\d+(?:\.\d+)?\z/a
Truth table0%0/3
A and B
A= defined $o->{"ms"}B= $o->{"ms"} =~ /\A\d+(?:\.\d+)?\z/a
ABresult
0X0
100
111
575 0 ▶ $self->Exception("on_slow_query: cb must be a coderef") unless ref $o->{cb} eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $o->{"cb"} eq "CODE" 0 0 0
576 0 $self->_set_slow_query($o->{ms}, $o->{cb}, $_init_errors_redact);
577 35 }
578  
579 16 ▶ method now () {
Subroutine now: called CC=1 SCAR=0.0
Pod documented
580 16 my ($sec, $min, $hour, $mday, $mon, $year) = localtime;
581  
582 16 return sprintf(
583 "%04d-%02d-%02d %02d:%02d:%02d",
584 $year + 1900, $mon + 1, $mday, $hour, $min, $sec
585 );
586 35 }
587  
588 # Like now() but in UTC (gmtime). Use when the DB session timezone differs
589 # from the host's, so stored timestamps stay comparable to server-side UTC.
590 1 ▶ method now_utc () {
Subroutine now_utc: called CC=1 SCAR=0.0
Pod documented
591 1 my ($sec, $min, $hour, $mday, $mon, $year) = gmtime;
592  
593 1 return sprintf(
594 "%04d-%02d-%02d %02d:%02d:%02d",
595 $year + 1900, $mon + 1, $mday, $hour, $min, $sec
596 );
597 35 }
598  
599 # Redact quoted literal values when errors_redact is on. Targets the common
600 # "Duplicate entry 'X' for key 'Y'" / "data X" patterns that leak PII or PCI
601 # data (card tokens, emails, etc.) into logs. Shared by set_error and
602 # Exception so both reporting paths honor the same policy.
603 211 ▶ method _redact ($msg) {
Subroutine _redact: called CC=3 SCAR=11.0
604 211 ▶ return $msg unless $_init_errors_redact && defined $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless $_init_errors_redact and defined $msg 209 2 211
Condition66%2/3
$_init_errors_redact and defined $msg
!ll&&!rl&&r
20902
MC/DC50%1/2
$_init_errors_redact and defined $msg
$_init_errors_redact defined $msg
Truth table66%2/3
A and B
A= $_init_errors_redactB= defined $msg
ABresult
0X0
100
111
605 2 $msg =~ s/'[^']*'/'<redacted>'/g;
606 2 $msg =~ s/"[^"]*"/"<redacted>"/g;
607 # MySQL/MariaDB quote identifiers (and some values) with backticks.
608 2 $msg =~ s/`[^`]*`/`<redacted>`/g;
609 2 return $msg;
610 35 }
611  
612 38 ▶ method set_error ($id, $error_msg) {
Subroutine set_error: called CC=8 SCAR=22.1
Pod documented
613 38 $error_msg = $self->_redact($error_msg);
614  
615 # The statement in flight (sql/p come from the SQL role) so the failing
616 # query can be reported without racing later queries that overwrite them.
617 38 my $binds = $self->p;
618 38 ▶ $binds = [ map { '<redacted>' } @$binds ]
Branch: 1 branch
BranchTrueFalseTotal
if $binds and $_init_errors_redact 0 38 38
Condition66%2/3
$binds and $_init_errors_redact
!ll&&!rl&&r
14240
MC/DC0%0/2
$binds and $_init_errors_redact
$binds $_init_errors_redact
Truth table66%2/3
A and B
A= $bindsB= $_init_errors_redact
ABresult
0X0
100
111
619 if $binds && $_init_errors_redact;
620  
621 38 ▶ my $error = {
Branch: 1 branch
BranchTrueFalseTotal
$binds ? : 24 14 38
622 id => $id,
623 error => $error_msg,
624 time => time(),
625 seq => ++$_err_seq,
626 sql => $self->sql,
627 binds => $binds ? [ @$binds ] : [],
628 };
629  
630 38 push @{$_errors}, $error;
631  
632 # FIFO cap: drop oldest entries when above the configured ceiling. Prevents
633 # unbounded growth in long-running workers that hit recurring DB errors.
634 38 ▶ if ($_init_max_errors > 0
Branch: 1 branch
BranchTrueFalseTotal
if ($_init_max_errors > 0 and scalar @{$_errors;} > $_init_max_errors) 7 31 38
Condition66%2/3
$_init_max_errors > 0 and scalar @{$_errors;} > $_init_max_errors
!ll&&!rl&&r
0317
MC/DC50%1/2
$_init_max_errors > 0 and scalar @{$_errors;} > $_init_max_errors
$_init_max_errors > 0 scalar @{$_errors;} > $_init_max_errors
Truth table66%2/3
A and B
A= $_init_max_errors > 0B= scalar @{$_errors;} > $_init_max_errors
ABresult
0X0
100
111
635 38 && scalar @{$_errors} > $_init_max_errors) {
636 7 splice @{$_errors}, 0,
637 7 scalar(@{$_errors}) - $_init_max_errors;
638 }
639  
640 $_last_error =
641 38 qq{$error->{time} - [$error->{id}] - $error->{error}};
642  
643 # A failing callback must never break the caller's DBI flow (this runs
644 # inside DBI's HandleError).
645 38 ▶ if ($_init_on_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_init_on_error) 0 38 38
646 0 ▶ eval { $_init_on_error->($error); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$_init_on_error($error); 1 } } or warn "DBIx::Fast on_error callback died: $@" 0 0 0
647 or warn "DBIx::Fast on_error callback died: $@";
648 }
649  
650 38 return $_last_error;
651 35 }
652  
653 # Error scoping: take a mark before a unit of work (a request, a job) and
654 # collect exactly the errors it produced afterwards. Sequence-based, so it
655 # stays correct after the max_errors FIFO cap has dropped older entries.
656 0 ▶ method error_mark () { return $_err_seq }
Subroutine error_mark: not called CC=1 SCAR=4.1
Pod documented
657  
658 0 ▶ method errors_since ($mark = 0) {
Subroutine errors_since: not called CC=2 SCAR=17.9
Pod documented
659 0 return [ grep { $_->{seq} > $mark } @{$_errors} ];
660 35 }
661  
662 2 ▶ method strict_reads () { return $_init_strict_reads }
Subroutine strict_reads: called CC=1 SCAR=0.0
Pod documented
663  
664 # DSN handling
665  
666 104 ▶ method _Driver_dbd ($dbd_name) {
Subroutine _Driver_dbd: called CC=5 SCAR=16.2
667 104 ▶ $self->Exception("Error DBD Driver") unless $dbd_name;
Branch: 1 branch
BranchTrueFalseTotal
unless $dbd_name 0 104 104
668  
669 104 for my $d (qw(SQLite Pg MariaDB mysql)) {
670 144 ▶ if (lc($dbd_name) eq lc($d)) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $dbd_name eq lc $d) 103 41 144
671 103 $_dbd = $d;
672 103 last;
673 }
674 }
675  
676 104 ▶ $self->Exception("Error DBD Driver : $dbd_name") unless $_dbd;
Branch: 1 branch
BranchTrueFalseTotal
unless $_dbd 0 104 104
677 35 }
678  
679 84 ▶ method _dsn_dbi ($dsn_str) {
Subroutine _dsn_dbi: called CC=5 SCAR=18.3
680 # A native dbi:DRIVER:... DSN. DBI itself is the authority on the
681 # driver-specific remainder, so only confirm the 'dbi' prefix and resolve
682 # the driver. Split with a limit of 3 so the rest stays intact (e.g.
683 # SQLite's "dbi:SQLite::memory:", where the database part contains colons).
684 84 my ($dbi, $driver) = split /:/, $dsn_str, 3;
685  
686 84 ▶ $self->Exception("Invalid DSN (expected dbi:DRIVER:...): $dsn_str")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dbi and lc $dbi eq "dbi" and defined $driver and length $driver 0 84 84
Condition33%3/9
defined $dbi and lc $dbi eq "dbi" and defined $driver and length $driver
!ll&&!rl&&r
0084
defined $dbi and lc $dbi eq "dbi" and defined $driver
!ll&&!rl&&r
0084
defined $dbi and lc $dbi eq "dbi"
!ll&&!rl&&r
0084
MC/DC0%0/4
defined $dbi and lc $dbi eq "dbi" and defined $driver and length $driver
defined $dbi lc $dbi eq "dbi" defined $driver length $driver
Truth table20%1/5
A and B and C and D
A= defined $dbiB= lc $dbi eq "dbi"C= defined $driverD= length $driver
ABCDresult
0XXX0
10XX0
110X0
11100
11111
687 unless defined $dbi && lc($dbi) eq 'dbi'
688 && defined $driver && length $driver;
689  
690 84 $self->_Driver_dbd($driver);
691  
692 84 return $dsn_str;
693 35 }
694  
695 98 ▶ method _check_dsn ($dsn_str) {
Subroutine _check_dsn: called CC=2 SCAR=6.9
696 # Case-insensitive: "DBI:..." is as valid as "dbi:..." for DBI.
697 98 ▶ return $self->_dsn_dbi($dsn_str) if $dsn_str =~ /^dbi/i;
Branch: 1 branch
BranchTrueFalseTotal
if $dsn_str =~ /^dbi/iu 84 14 98
698 14 return $self->_dsn_to_dbi($dsn_str);
699 35 }
700  
701 15 ▶ method _make_dsn ($args) {
Subroutine _make_dsn: called CC=11 SCAR=26.3
702 15 ▶ $self->Exception("DSN Driver: Not defined") unless $args->{driver};
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"driver"} 0 15 15
703  
704 15 $self->_Driver_dbd($args->{driver});
705  
706 return 'dbi:SQLite:dbname=' . $args->{db}
707 15 ▶ if $args->{driver} eq 'SQLite';
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"driver"} eq "SQLite" 8 7 15
708  
709 # host/port live under Auth in the constructed config, but accept them at
710 # the top level too (direct callers / tests).
711 7 ▶ my $host = $args->{host} // ($args->{Auth} && $args->{Auth}{host});
Condition16%1/6
$args->{"host"} // $args->{"Auth"} && $args->{"Auth"}{"host"}
l!l&&r!l&&!r
700
$args->{"Auth"} and $args->{"Auth"}{"host"}
!ll&&!rl&&r
000
MC/DC0%0/3
$args->{"host"} // $args->{"Auth"} && $args->{"Auth"}{"host"}
$args->{"host"} $args->{"Auth"} $args->{"Auth"}{"host"}
Truth table25%1/4
A // B and C
A= $args->{"host"}B= $args->{"Auth"}C= $args->{"Auth"}{"host"}
ABCresult
1XX1
0111
00X0
0100
712 7 ▶ my $port = $args->{port} // ($args->{Auth} && $args->{Auth}{port});
Condition50%3/6
$args->{"port"} // $args->{"Auth"} && $args->{"Auth"}{"port"}
l!l&&r!l&&!r
205
$args->{"Auth"} and $args->{"Auth"}{"port"}
!ll&&!rl&&r
500
MC/DC33%1/3
$args->{"port"} // $args->{"Auth"} && $args->{"Auth"}{"port"}
$args->{"port"} $args->{"Auth"} $args->{"Auth"}{"port"}
Truth table50%2/4
A // B and C
A= $args->{"port"}B= $args->{"Auth"}C= $args->{"Auth"}{"port"}
ABCresult
1XX1
0111
00X0
0100
713  
714 7 ▶ $self->Exception("DSN Host: Not defined") unless $host;
Branch: 1 branch
BranchTrueFalseTotal
unless $host 0 7 7
715 7 ▶ $self->Exception("DSN DB: Not defined") unless $args->{db};
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"db"} 0 7 7
716 7 $self->_check_dsn_part($_) for grep { defined } $args->{db}, $host, $port;
717  
718 # Proper ';'-separated name=value DSN. The old "...:database=db:host" form
719 # folded the host into the dbname (so DBD drivers ignored it) and could not
720 # express a port.
721 5 my $dsn = "dbi:$_dbd:dbname=$args->{db};host=$host";
722 5 ▶ $dsn .= ";port=$port" if $port;
Branch: 1 branch
BranchTrueFalseTotal
if $port 2 3 5
723 5 return $dsn;
724 35 }
725  
726 20 ▶ method _dsn_to_dbi ($dsn_str) {
Subroutine _dsn_to_dbi: called CC=14 SCAR=26.9
727 20 my $URI;
728  
729 # SQLite
730 20 ▶ if ($dsn_str =~ /^sqlite:\/\/\/(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dsn_str =~ m[^sqlite:///(.*)$]u) 0 20 20
731 0 $_dbd = 'SQLite';
732 0 return 'dbi:SQLite:dbname=' . $1;
733 }
734  
735 # userinfo (user[:pass]@) is optional: a credential-less URI like
736 # "mariadb://localhost/db" is valid for socket / peer authentication.
737 # The userinfo match is greedy up to the LAST '@' before the path, so a
738 # raw '@' in the password still parses; %XX escapes are decoded below.
739 20 ($URI->{schema}, $URI->{UI}, $URI->{connect}, $URI->{db}) =
740 $dsn_str =~ m{^([^:]+)://(?:([^/]*)@)?([^/@]+)/(.+)$};
741  
742 20 ▶ $self->Exception("_dsn_to_dbi : schema") unless $URI->{schema};
Branch: 1 branch
BranchTrueFalseTotal
unless $URI->{"schema"} 0 20 20
743  
744 # The driver is resolved from the URI scheme at the bottom of this method
745 # (postgres/postgresql -> Pg, mariadb -> MariaDB, mysql/mysqlx -> mysql).
746 # Do NOT call _Driver_dbd($schema) here: it doesn't know those scheme aliases
747 # and, on a fresh construction (no $_dbd yet), would throw "Error DBD Driver"
748 # for a perfectly valid "postgres://" / "postgresql://" / "mysqlx://" DSN.
749 20 ▶ $self->Exception("_dsn_to_dbi : connect") unless $URI->{connect};
Branch: 1 branch
BranchTrueFalseTotal
unless $URI->{"connect"} 0 20 20
750  
751 $URI->{connect} =~ /:/
752 ? ($URI->{host}, $URI->{port}) = split ':', $URI->{connect}
753 20 ▶ : $URI->{host} = $URI->{connect};
Branch: 1 branch
BranchTrueFalseTotal
$URI->{'connect'} =~ /:/u ? : 6 14 20
754  
755 # UserInfo (absent for socket/peer auth - leave Auth untouched then).
756 20 ▶ if (defined $URI->{UI}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $URI->{"UI"}) 20 0 20
757 20 ▶ if ($URI->{UI} =~ /:/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($URI->{'UI'} =~ /:/u) { } 8 12 20
758 # Limit to two fields so a password containing ':' is kept intact.
759 ($URI->{user}, $URI->{password}) =
760 8 map { _uri_unescape($_) } split /:/, $URI->{UI}, 2;
761  
762 8 $_args->{Auth}->{user} = $URI->{user};
763 8 $_args->{Auth}->{password} = $URI->{password};
764 } else {
765 # User without password ("mariadb://alice@host/db"): still the login.
766 12 $URI->{user} = _uri_unescape($URI->{UI});
767 12 $_args->{Auth}->{user} = $URI->{user};
768 }
769 }
770  
771 20 ▶ $self->Exception('_dsn_to_dbi : No DB value') unless $URI->{db};
Branch: 1 branch
BranchTrueFalseTotal
unless $URI->{"db"} 0 20 20
772  
773 20 ▶ if ($URI->{db} =~ s/^(.*)\?(.*)$/$1/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($URI->{"db"} =~ s/^(.*)\?(.*)$/$1/u) 0 20 20
774 0 ($URI->{attribute}, $URI->{value}) = split '=', $2;
775 }
776 20 $URI->{db} = _uri_unescape($URI->{db});
777  
778 20 $self->_check_dsn_part($_) for grep { defined } @{$URI}{qw(db host port)};
779  
780 19 ▶ if ($dsn_str =~ /^(postgres|postgresql):/) {
Branch: 3 branches
BranchTrueFalseTotal
if ($dsn_str =~ /^(postgres|postgresql):/u) { } 6 13 19
elsif ($dsn_str =~ /^(mariadb):/u) { } 10 3 13
elsif ($dsn_str =~ /^(mysql|mysqlx):/u) { } 2 1 3
781 6 $_dbd = 'Pg';
782 } elsif ($dsn_str =~ /^(mariadb):/) {
783 10 $_dbd = 'MariaDB';
784 } elsif ($dsn_str =~ /^(mysql|mysqlx):/) {
785 2 $_dbd = 'mysql';
786 } else {
787 # Never echo the raw DSN: for URI-style DSNs it carries user:password.
788 1 (my $redacted = $dsn_str) =~ s{//[^/]*@}{//<redacted>@};
789 1 $self->Exception("_dsn_to_dbi : $redacted");
790 }
791  
792 $URI->{DSN} = sprintf('dbi:%s:dbname=%s;host=%s%s',
793 $_dbd, $URI->{db}, $URI->{host},
794 18 ▶ $URI->{port} ? ";port=$URI->{port}" : ''
Branch: 1 branch
BranchTrueFalseTotal
$URI->{'port'} ? : 6 12 18
795 );
796  
797 18 return $URI->{DSN};
798 35 }
799  
800 # A DSN component (db/host/port) is interpolated into a ';'-separated
801 # name=value DSN: a ';' or '=' would smuggle in extra driver attributes
802 # (e.g. db => 'app;mariadb_local_infile=1').
803 60 ▶ method _check_dsn_part ($part) {
Subroutine _check_dsn_part: called CC=2 SCAR=6.9
804 60 ▶ $self->Exception("Invalid character in DSN component")
Branch: 1 branch
BranchTrueFalseTotal
if $part =~ /[;=]/u 3 57 60
805 if $part =~ /[;=]/;
806 35 }
807  
808 48 ▶ sub _uri_unescape ($s) {
Subroutine _uri_unescape: called CC=2 SCAR=7.0
809 48 ▶ return $s unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 48 48
810 48 $s =~ s/%([0-9A-Fa-f]{2})/chr hex $1/ge;
811 48 return $s;
812 }
813  
814 0 ▶ method _profile ($stat) {
Subroutine _profile: not called CC=1 SCAR=6.9
815 0 $stat .= "/DBI::ProfileDumper/";
816 0 $stat .= qq{File:dbix-fast-$$.log};
817  
818 0 $db->dbh->{Profile} = $stat;
819 35 }
820  
821 # Validate identifier
822 # Identifiers that already passed _safe_id (same regex, run once per name):
823 # the CRUD validators check a hash instead of calling _safe_id per column
824 # on every write. Bounded like the statement caches.
825 35 field %_ok_id;
826  
827 176 ▶ method _remember_id ($name) {
Subroutine _remember_id: called CC=1 SCAR=0.0
828 176 $self->_safe_id($name);
829 165 DBIx::Fast::SQL::_trim_cache(\%_ok_id, 10_000);
830 165 $_ok_id{$name} = 1;
831 35 }
832  
833 510 ▶ method _safe_id ($name) {
Subroutine _safe_id: called CC=3 SCAR=11.0
834 510 ▶ $self->Exception("Invalid identifier")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and $name =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/u 45 465 510
Condition100%3/3
defined $name and $name =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/u
!ll&&!rl&&r
144465
MC/DC100%2/2
defined $name and $name =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/u
defined $name $name =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/u
Truth table100%3/3
A and B
A= defined $nameB= $name =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/u
ABresult
0X0
100
111
835 unless defined $name && $name =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/;
836  
837 465 return $name;
838 35 }
839  
840 # Validate and quote identifier (defense-in-depth)
841 2 ▶ method _quote_id ($name) {
Subroutine _quote_id: called CC=1 SCAR=0.0
842 2 $self->_safe_id($name);
843 1 return $db->dbh->quote_identifier($name);
844 35 }
845  
846 # Validate and quote a possibly-qualified identifier ("schema.table",
847 # "t.col") by quoting each dot-separated segment, so quote_identifier does not
848 # wrap the whole dotted name as one literal identifier ("schema.table").
849 #
850 # Memoized per instance: the quoting is a pure function of the name and the
851 # (fixed) driver, and each miss costs a Connector->dbh round (fork check =
852 # getpid syscall) plus one quote_identifier per segment. Only names that
853 # passed _safe_id are ever stored.
854 171 ▶ method _quote_ident_path ($name) {
Subroutine _quote_ident_path: called CC=3 SCAR=11.0
855 171 ▶ return $_qid{$name} if defined $name && exists $_qid{$name};
Branch: 1 branch
BranchTrueFalseTotal
if defined $name and exists $_qid{$name} 126 45 171
Condition66%2/3
defined $name and exists $_qid{$name}
!ll&&!rl&&r
045126
MC/DC50%1/2
defined $name and exists $_qid{$name}
defined $name exists $_qid{$name}
Truth table66%2/3
A and B
A= defined $nameB= exists $_qid{$name}
ABresult
0X0
100
111
856 45 $self->_safe_id($name);
857 45 DBIx::Fast::SQL::_trim_cache(\%_qid, 1_000); # bound data-driven identifiers
858 45 my $dbh = $db->dbh;
859 return $_qid{$name} =
860 45 join '.', map { $dbh->quote_identifier($_) } split /\./, $name;
861 35 }
862  
863 # Validate a CRUD data/WHERE spec before it reaches SQL::Abstract, which
864 # interpolates hash keys verbatim (its injection_guard only blocks ';'). Must
865 # cover EVERY shape SQL::Abstract accepts, not just HASH: an arrayref WHERE
866 # (OR-of-conditions) or a scalarref WHERE (literal SQL) would otherwise slip
867 # past the operator whitelist entirely.
868 72 ▶ method _safe_columns ($spec) {
Subroutine _safe_columns: called CC=11 SCAR=24.0
869 72 my $ref = ref $spec;
870 72 ▶ if ($ref eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq 'HASH') { } 57 15 72
elsif ($ref eq 'ARRAY') { } 14 1 15
elsif ($ref) { } 1 0 1
871 57 for my $k (keys %$spec) {
872 59 ▶ $_ok_id{$k} or $self->_remember_id($k);
Branch: 1 branch
BranchTrueFalseTotal
$_ok_id{$k} or $self->_remember_id($k) 53 6 59
873 # A plain scalar/undef is a bind value: nothing for _safe_op_tree.
874 57 ▶ $self->_safe_op_tree($spec->{$k}) if ref $spec->{$k};
Branch: 1 branch
BranchTrueFalseTotal
if ref $spec->{$k} 39 18 57
875 }
876 }
877 elsif ($ref eq 'ARRAY') {
878 # OR-list. Elements are -and/-or logic tokens, nested hashref/arrayref
879 # conditions, or "column => condition" pairs (SQL::Abstract reads a plain
880 # scalar as a column name and the next element as its condition). Any
881 # other dash token is refused: [ -literal => ['1=1'] ] is raw SQL.
882 14 ▶ for (my $i = 0; $i < @$spec; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$spec) 20 4 24
883 20 my $el = $spec->[$i];
884 20 ▶ if (ref $el) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $el) { } 9 11 20
elsif (defined $el and $el =~ /^-(?:and|or)$/iu) { } 3 8 11
885 9 $self->_safe_columns($el);
886 }
887 ▶ elsif (defined $el && $el =~ /^-(?:and|or)$/i) {
Condition66%2/3
defined $el and $el =~ /^-(?:and|or)$/iu
!ll&&!rl&&r
083
MC/DC50%1/2
defined $el and $el =~ /^-(?:and|or)$/iu
defined $el $el =~ /^-(?:and|or)$/iu
Truth table66%2/3
A and B
A= defined $elB= $el =~ /^-(?:and|or)$/iu
ABresult
0X0
100
111
888 3 next;
889 }
890 else {
891 8 $self->_safe_id($el);
892 4 $self->_safe_op_tree($spec->[++$i]);
893 }
894 }
895 }
896 elsif ($ref) {
897 # A literal-SQL WHERE ( \'1=1' ) from a CRUD helper can never be trusted.
898 1 $self->Exception("Literal-SQL WHERE is not allowed in CRUD methods");
899 }
900 # plain scalar / undef: a bind value, nothing to validate.
901 35 }
902  
903 # Validate an INSERT row / UPDATE SET spec. SQL::Abstract 2 reads a hashref
904 # or arrayref value there as an expression, not a bind: [ '(SELECT ...)' ] is
905 # raw SQL and { -literal | -func | -ident => ... } build SQL from their
906 # argument - shapes a decoded JSON body can carry. Blessed objects (JSON
907 # booleans) stringify and bind normally. A scalarref ( \'NOW()' ) stays
908 # allowed: it is the documented literal-SQL escape hatch and cannot come
909 # from a JSON/form decoder, only from code.
910 134 ▶ method _safe_data ($spec) {
Subroutine _safe_data: called CC=8 SCAR=20.9
911 134 ▶ $self->Exception("CRUD data must be a hashref") unless ref $spec eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 0 134 134
912  
913 134 for my $col (keys %$spec) {
914 225 ▶ $_ok_id{$col} or $self->_remember_id($col);
Branch: 1 branch
BranchTrueFalseTotal
$_ok_id{$col} or $self->_remember_id($col) 150 75 225
915 218 my $ref = ref $spec->{$col};
916 $self->Exception("Invalid value for column $col: "
917 . "hashref/arrayref values are not allowed in CRUD data")
918 218 ▶ if $ref && !blessed($spec->{$col})
Branch: 1 branch
BranchTrueFalseTotal
if $ref and not builtin::blessed($spec->{$col}) and $ref ne "SCALAR" and $ref ne "REF" 8 210 218
Condition77%7/9
$ref and not builtin::blessed($spec->{$col}) and $ref ne "SCALAR" and $ref ne "REF"
!ll&&!rl&&r
21008
$ref and not builtin::blessed($spec->{$col}) and $ref ne "SCALAR"
!ll&&!rl&&r
20918
$ref and not builtin::blessed($spec->{$col})
!ll&&!rl&&r
20909
MC/DC50%2/4
$ref and not builtin::blessed($spec->{$col}) and $ref ne "SCALAR" and $ref ne "REF"
$ref not builtin::blessed($spec->{$col}) $ref ne "SCALAR" $ref ne "REF"
Truth table60%3/5
A and not(B) and C and D
A= $refB= not builtin::blessed($spec->{$col})C= $ref ne "SCALAR"D= $ref ne "REF"
ABCDresult
0XXX0
10XX0
110X0
11100
11111
919 && $ref ne 'SCALAR' && $ref ne 'REF';
920 }
921 35 }
922  
923 # Validate the condition attached to one column in a CRUD WHERE spec. The
924 # grammar is deliberately narrow, because SQL::Abstract 2 is an expression
925 # language: a hashref on the right of an operator loses the column context and
926 # is expanded as a generic expression, where [ -literal => [...] ],
927 # [ -func => [...] ] and [ -ident => ... ] pairs (or the same as hash keys)
928 # emit raw SQL. So:
929 # condition := plain | [ (-and|-or)?, condition... ] | { key => ... }
930 # key := -and/-or => condition | operator => operand
931 # operand := plain | [ plain... ] (bind values only, never a hash)
932 # "plain" is a non-ref, undef, a blessed object (binds by stringification)
933 # or a scalarref - the documented literal-SQL escape hatch, which a JSON/form
934 # decoder cannot produce. Anything else is refused, never skipped.
935 # Validate a row for the hand-built, fully bound INSERTs (upsert/*_many).
936 # Values are placeholders there, so a reference would be bound as its
937 # stringification ("SCALAR(0x...)", "HASH(0x...)") and silently stored.
938 # Plain values and blessed objects bind; an arrayref is kept for Pg, where
939 # DBD::Pg binds it as a native array.
940 66 ▶ method _safe_bind_row ($row) {
Subroutine _safe_bind_row: called CC=5 SCAR=16.1
941 66 ▶ for my $k (keys %$row) { $_ok_id{$k} or $self->_remember_id($k) }
Branch: 1 branch
BranchTrueFalseTotal
$_ok_id{$k} or $self->_remember_id($k) 116 36 152
942 # Only a reference value needs the (driver-dependent) bind check.
943 65 for (values %$row) {
944 148 ▶ next unless ref;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $_ 143 5 148
945 5 $self->_safe_bind_values([ values %$row ]);
946 1 last;
947 }
948 35 }
949  
950 # _safe_id over a list, through the identifier memo (one call per list).
951 61 ▶ method _safe_ids (@names) {
Subroutine _safe_ids: called CC=4 SCAR=13.9
952 61 ▶ for my $n (@names) { $_ok_id{$n // ''} or $self->_remember_id($n) }
Branch: 1 branch
BranchTrueFalseTotal
$_ok_id{$n // ""} or $self->_remember_id($n) 60 1 61
Condition50%1/2
$n // ""
l!l
610
MC/DC0%0/1
$n // ""
$n
Truth table50%1/2
A
A= $n
Aresult
11
00
953 35 }
954  
955 # Value half of _safe_bind_row, for the *_many paths (whose column names
956 # are validated once, on row 0).
957 36 ▶ method _safe_bind_values ($vals) {
Subroutine _safe_bind_values: called CC=6 SCAR=18.2
958 36 my $pg = $self->dbd eq 'Pg';
959 36 for my $v (@$vals) {
960 234 ▶ my $ref = ref $v or next;
Branch: 1 branch
BranchTrueFalseTotal
my $ref = ref $v or next 13 221 234
961 13 ▶ next if blessed($v) || ($pg && $ref eq 'ARRAY');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($v) or $pg and $ref eq "ARRAY" 1 12 13
Condition50%3/6
builtin::blessed($v) or $pg and $ref eq "ARRAY"
l!l&&r!l&&!r
1012
$pg and $ref eq "ARRAY"
!ll&&!rl&&r
1200
MC/DC33%1/3
builtin::blessed($v) or $pg and $ref eq "ARRAY"
builtin::blessed($v) $pg $ref eq "ARRAY"
Truth table50%2/4
A or B and C
A= builtin::blessed($v)B= $pgC= $ref eq "ARRAY"
ABCresult
1XX1
0111
00X0
0100
962 12 $self->Exception("Invalid value: a $ref reference cannot be bound");
963 }
964 35 }
965  
966 45 ▶ method _safe_op_tree ($val) {
Subroutine _safe_op_tree: called CC=16 SCAR=28.0
967 45 state %VALID_OPS = map { $_ => 1 }
968 ('=', '!=', '<>', '<', '<=', '>', '>=',
969 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
970 'BETWEEN', 'NOT BETWEEN', 'IS', 'IS NOT');
971  
972 # SQL::Abstract dash-ops that only compare against bind values. Others
973 # are NOT harmless: -literal and -func interpolate raw SQL from their
974 # argument, -ident turns a value into a column reference (tautologies).
975 45 state %VALID_DASH_OPS = map { $_ => 1 }
976 qw(-in -not_in -between -not_between -like -not_like -is -is_not -value);
977  
978 45 ▶ return if _plain_value($val);
Branch: 1 branch
BranchTrueFalseTotal
if _plain_value($val) 3 42 45
979  
980 42 my $ref = ref $val;
981 42 ▶ if ($ref eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref eq "ARRAY") 1 41 42
982 1 for my $i (0 .. $#$val) {
983 3 my $el = $val->[$i];
984 3 ▶ next if $i == 0 && !ref $el && defined $el && $el =~ /^-(?:and|or)$/i;
Branch: 1 branch
BranchTrueFalseTotal
if $i == 0 and not ref $el and defined $el and $el =~ /^-(?:and|or)$/iu 1 2 3
Condition66%6/9
$i == 0 and not ref $el and defined $el and $el =~ /^-(?:and|or)$/iu
!ll&&!rl&&r
201
$i == 0 and not ref $el and defined $el
!ll&&!rl&&r
201
$i == 0 and not ref $el
!ll&&!rl&&r
201
MC/DC25%1/4
$i == 0 and not ref $el and defined $el and $el =~ /^-(?:and|or)$/iu
$i == 0 not ref $el defined $el $el =~ /^-(?:and|or)$/iu
Truth table40%2/5
A and not(B) and C and D
A= $i == 0B= not ref $elC= defined $elD= $el =~ /^-(?:and|or)$/iu
ABCDresult
0XXX0
10XX0
110X0
11100
11111
985 2 $self->_safe_op_tree($el);
986 }
987 1 return;
988 }
989  
990 41 ▶ $self->Exception("Invalid condition") unless $ref eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $ref eq "HASH" 0 41 41
991  
992 41 for my $op (keys %$val) {
993 41 my $rhs = $val->{$op};
994  
995 41 ▶ if ($op =~ /^-(?:and|or)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op =~ /^-(?:and|or)$/iu) 0 41 41
996 0 $self->_safe_op_tree($rhs);
997 0 next;
998 }
999  
1000 $self->Exception("Invalid operator: $op")
1001 41 ▶ unless $VALID_OPS{uc $op} || $VALID_DASH_OPS{lc $op};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_OPS{uc $op} or $VALID_DASH_OPS{lc $op} 14 27 41
Condition100%3/3
$VALID_OPS{uc $op} or $VALID_DASH_OPS{lc $op}
l!l&&r!l&&!r
151214
MC/DC100%2/2
$VALID_OPS{uc $op} or $VALID_DASH_OPS{lc $op}
$VALID_OPS{uc $op} $VALID_DASH_OPS{lc $op}
Truth table100%3/3
A or B
A= $VALID_OPS{uc $op}B= $VALID_DASH_OPS{lc $op}
ABresult
1X1
011
000
1002  
1003 27 ▶ next if _plain_value($rhs);
Branch: 1 branch
BranchTrueFalseTotal
if _plain_value($rhs) 5 22 27
1004 $self->Exception("Invalid operand for $op: only bind values allowed")
1005 22 ▶ unless ref $rhs eq 'ARRAY' && !grep { !_plain_value($_) } @$rhs;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rhs eq "ARRAY" and not grep({not _plain_value($_);} @$rhs) 18 4 22
Condition100%3/3
ref $rhs eq "ARRAY" and not grep({not _plain_value($_);} @$rhs)
!ll&&!rl&&r
1084
MC/DC100%2/2
ref $rhs eq "ARRAY" and not grep({not _plain_value($_);} @$rhs)
ref $rhs eq "ARRAY" not grep({not _plain_value($_);} @$rhs)
Truth table100%3/3
A and not(B)
A= ref $rhs eq "ARRAY"B= not grep({not _plain_value($_);} @$rhs)
ABresult
0X0
100
111
1006 }
1007 35 }
1008  
1009 # A bind value as far as SQL::Abstract is concerned (see _safe_op_tree).
1010 91 ▶ sub _plain_value ($v) {
Subroutine _plain_value: called CC=4 SCAR=14.6
1011 91 my $ref = ref $v;
1012 91 ▶ return !$ref || blessed($v) || $ref eq 'SCALAR' || $ref eq 'REF';
Condition66%6/9
!$ref || builtin::blessed($v) || $ref eq 'SCALAR' || $ref eq 'REF'
l!l&&r!l&&!r
19072
not $ref or builtin::blessed($v) or $ref eq "SCALAR"
l!l&&r!l&&!r
19072
not $ref or builtin::blessed($v)
l!l&&r!l&&!r
19072
MC/DC25%1/4
!$ref || builtin::blessed($v) || $ref eq 'SCALAR' || $ref eq 'REF'
not $ref builtin::blessed($v) $ref eq "SCALAR" $ref eq 'REF'
Truth table40%2/5
not(A) or B or C || D
A= not $refB= builtin::blessed($v)C= $ref eq "SCALAR"D= $ref eq 'REF'
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1013 }
1014  
1015  
1016 # Query methods
1017  
1018  
1019  
1020  
1021  
1022  
1023  
1024  
1025  
1026  
1027  
1028  
1029 # Invalidate any cached query tagged with the given table name. No-op
1030 # when caching is disabled. The convention is that users tag cached
1031 # reads with `tag => $table` so writes propagate transparently.
1032 8 ▶ method _cache_invalidate_table ($table) {
Subroutine _cache_invalidate_table: called CC=4 SCAR=14.2
1033 8 ▶ return unless $_cache || defined $_init_cache;
Branch: 1 branch
BranchTrueFalseTotal
unless $_cache or defined $_init_cache 0 8 8
Condition66%2/3
$_cache or defined $_init_cache
l!l&&r!l&&!r
710
MC/DC0%0/2
$_cache or defined $_init_cache
$_cache defined $_init_cache
Truth table66%2/3
A or B
A= $_cacheB= defined $_init_cache
ABresult
1X1
011
000
1034 8 ▶ my $cache = $self->cache or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cache = $self->cache or return 8 0 8
1035 8 $cache->invalidate($table);
1036 35 }
1037  
1038 # Public cache invalidation by tag(s). Use after mutations that bypass the
1039 # CRUD auto-invalidation: raw exec()/query()/execute() writes, or reads that
1040 # span several tables (which must be tagged with, and invalidated for, every
1041 # table involved). No-op when caching is disabled.
1042 1 ▶ method invalidate (@tags) {
Subroutine invalidate: called CC=3 SCAR=11.0
Pod documented
1043 1 ▶ my $cache = $self->cache or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $cache = $self->cache or return 0 1 0 1
1044 1 my $n = 0;
1045 1 $n += $cache->invalidate($_) for @tags;
1046 1 return $n;
1047 35 }
1048  
1049  
1050  
1051  
1052  
1053  
1054  
1055  
1056  
1057 # Named parameter methods
1058  
1059  
1060 # Execute helpers
1061  
1062  
1063 # Validation
1064  
1065 336 ▶ method TableName ($table) {
Subroutine TableName: called CC=6 SCAR=17.9
Pod documented
1066 336 ▶ $self->Exception("Not defined table") unless $table;
Branch: 1 branch
BranchTrueFalseTotal
unless $table 0 336 336
1067  
1068 # Format validation is unconditional (same pattern as _safe_id): count()
1069 # and upsert() already rejected malformed names downstream, while
1070 # insert()/update() let them through to SQL::Abstract - one rule for all.
1071 336 ▶ unless ($_ok_id{$table}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_ok_id{$table}) 61 275 336
1072 61 ▶ $self->Exception("TableName not valid: $table")
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/u 3 58 61
1073 unless $table =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/;
1074 58 $self->_remember_id($table); # same rule as _safe_id
1075 }
1076  
1077 333 ▶ return $table unless $_args->{tn};
Branch: 1 branch
BranchTrueFalseTotal
unless $_args->{"tn"} 329 4 333
1078  
1079 $self->Exception("TableName not exist: $table")
1080 4 ▶ unless $self->schema->tables->{$table};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->schema->tables->{$table} 1 3 4
1081  
1082 3 return $table;
1083 35 }
1084  
1085 171 ▶ method Exception ($msg) {
Subroutine Exception: called CC=1 SCAR=0.0
Pod documented
1086 # Always croak. Validation/usage errors (e.g. _safe_id "Invalid identifier")
1087 # must never be silently swallowed: a silent return used to let a rejected
1088 # identifier flow on and become an injection vector when the handle was
1089 # configured with RaiseError=0 & PrintError=0.
1090 #
1091 # The message honors errors_redact, and last_error is attached only when
1092 # RECENT (likely causal context) - a DB error from minutes ago would only
1093 # mislead the diagnosis and could leak stale data into a fresh exception.
1094 # Thrown as a DBIx::Fast::X::Usage whose text is exactly what the former
1095 # `croak $full` produced (croak is die + shortmess).
1096 171 die DBIx::Fast::X::Usage->new(
1097 message => $self->_exception_text($msg) . Carp::shortmess(),
1098 error => $msg,
1099 );
1100 35 }
1101  
1102 # "Exception: <msg>[ - Last error: [id] error]" - shared by Exception and
1103 # the DB failures raised through _db_fail.
1104 173 ▶ method _exception_text ($msg) {
Subroutine _exception_text: called CC=5 SCAR=16.2
1105 173 ▶ my $full = "Exception: " . ($self->_redact($msg) // '');
Condition50%1/2
$self->_redact($msg) // ""
l!l
1730
MC/DC0%0/1
$self->_redact($msg) // ""
$self->_redact($msg)
Truth table50%1/2
A
A= $self->_redact($msg)
Aresult
11
00
1106  
1107 # No epoch in the message: identical failures must produce identical text
1108 # so log aggregation can group them (the time is in errors()->[-1]{time}).
1109 173 ▶ my $last = @{$_errors} ? $_errors->[-1] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@{$_errors;} ? : 2 171 173
1110 $full .= " - Last error: [$last->{id}] $last->{error}"
1111 173 ▶ if $last && (time() - $last->{time}) < 5;
Branch: 1 branch
BranchTrueFalseTotal
if $last and &DBIx::Fast::time() - $last->{"time"} < 5 2 171 173
Condition66%2/3
$last and &DBIx::Fast::time() - $last->{"time"} < 5
!ll&&!rl&&r
17102
MC/DC50%1/2
$last and &DBIx::Fast::time() - $last->{"time"} < 5
$last &DBIx::Fast::time() - $last->{"time"} < 5
Truth table66%2/3
A and B
A= $lastB= &DBIx::Fast::time() - $last->{"time"} < 5
ABresult
0X0
100
111
1112  
1113 173 return $full;
1114 35 }
1115  
1116 # A classified DBIx::Fast::X::DB (or subclass) for a driver error on handle
1117 # $h, carrying the statement in flight. $message is the full text.
1118 13 ▶ method _db_exception ($message, $h = undef) {
Subroutine _db_exception: called CC=7 SCAR=21.5
1119 13 ▶ my ($code, $state, $text) =
Branch: 1 branch
BranchTrueFalseTotal
$h ? : 13 0 13
1120 $h ? ($h->err, $h->state, $h->errstr) : ($DBI::err, $DBI::state, $DBI::errstr);
1121 13 my $binds = $self->p;
1122 13 ▶ $binds = [ map { '<redacted>' } @$binds ] if $binds && $_init_errors_redact;
Branch: 1 branch
BranchTrueFalseTotal
if $binds and $_init_errors_redact 0 13 13
Condition33%1/3
$binds and $_init_errors_redact
!ll&&!rl&&r
0130
MC/DC0%0/2
$binds and $_init_errors_redact
$binds $_init_errors_redact
Truth table33%1/3
A and B
A= $bindsB= $_init_errors_redact
ABresult
0X0
100
111
1123  
1124 13 ▶ my $class = DBIx::Fast::X::DB->class_for($_dbd // '', $code, $state, $text);
Condition50%1/2
$_dbd // ""
l!l
130
MC/DC0%0/1
$_dbd // ""
$_dbd
Truth table50%1/2
A
A= $_dbd
Aresult
11
00
1125 13 ▶ return $class->new(
Branch: 1 branch
BranchTrueFalseTotal
$binds ? : 13 0 13
1126 message => $message,
1127 error => $text,
1128 code => $code,
1129 state => $state,
1130 driver => $_dbd,
1131 sql => $self->sql,
1132 binds => $binds ? [ @$binds ] : [],
1133 constraint => DBIx::Fast::X::DB->constraint_from($text),
1134 );
1135 35 }
1136  
1137 # A database failure detected by DBIx::Fast itself (RaiseError off, so DBI
1138 # did not throw): same "Exception: ..." text as Exception(), typed by the
1139 # driver error on $h.
1140 2 ▶ method _db_fail ($msg, $h = undef) {
Subroutine _db_fail: called CC=2 SCAR=6.9
1141 2 die $self->_db_exception(
1142 $self->_exception_text($msg) . Carp::shortmess(), $h);
1143 35 }
1144 }
1145  
1146 35 1;
1147  
1148 __END__
« Fast/SQL.pm ↑ Summary Fast/Transaction.pm »