Fast.pm

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