Fast.pm

filter: Statementstmt 86.9% 468 / 538 Branchbran 65.7% 117 / 178 Conditioncond 47.3% 62 / 131 MC/DCmcdc 29.1% 21 / 72 Subroutinesub 90.6% 58 / 64 Podpod 100% 24 / 24 totaltotal 74.4% 750 / 1007 CC 154 SCAR 29.9
CC
154
Cov
76%
_safe_op_tree
159.5
_safe_columns
45.7
_check_timestamps
15.3
CRAP 20.0
« Fast/SQL.pm ↑ Summary Fast/Transaction.pm »
1 package DBIx::Fast;
2  
3 34 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 34 ▶use Object::Pad 0.807;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 34 our $VERSION = '0.20';
7  
8 34 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 34 ▶use DBIx::Fast::Connector;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 34 ▶use DBIx::Fast::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 34 ▶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 34 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 34 ▶use DBIx::Fast::X;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 34 ▶use Time::HiRes 'time';
Subroutine BEGIN: called CC=1 SCAR=0.0
17 34 ▶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 class DBIx::Fast :does(DBIx::Fast::SQL) {
24  
25 # Public fields. $db stays writable; the driver-aware SQL::Abstract
26 # instance is :reader only, so callers cannot clobber it (ranks 17/27).
27 field $db :accessor = undef;
28 973 ▶ field $Q :reader = undef;
Subroutine db: called CC=2 SCAR=7.1
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ and $db = shift() 0 973 973
29  
30 # Internal state with readers
31 82 ▶ field $_args :reader(args) = undef;
Subroutine Q: called CC=1 SCAR=0.0
Pod documented
32 12 ▶ field $_dbd :reader(dbd) = undef;
Subroutine args: called CC=1 SCAR=0.0
Pod documented
33 316 ▶ field $_dsn :reader(dsn) = undef;
Subroutine dbd: called CC=1 SCAR=0.0
Pod documented
34 0 ▶ field $_errors :reader(errors) = [];
Subroutine dsn: not called CC=1 SCAR=1.2
Pod documented
35 9 ▶ field $_last_error :reader(last_error) = undef;
Subroutine errors: called CC=1 SCAR=0.0
Pod documented
36  
37 # Lazy subsystems
38 2 ▶ field $_schema;
Subroutine last_error: called CC=1 SCAR=0.0
Pod documented
39 34 field $_transaction;
40 34 field $_profiler;
41 34 field $_query_tracker;
42 34 field $_cache;
43 34 field %_extensions;
44 34 field %_qid; # _quote_ident_path memo
45 34 field $_cache_ns; # cached() key namespace memo (see _cache_ns)
46  
47  
48 # Constructor params
49 field $_init_db :param(db) = undef;
50 34 field $_init_dsn :param(dsn) = '';
51 34 field $_init_SQLite :param(SQLite) = undef;
52 34 field $_init_driver :param(driver) = '';
53 34 field $_init_user :param(user) = '';
54 34 field $_init_password :param(password) = '';
55 34 field $_init_host :param(host) = '';
56 34 field $_init_port :param(port) = undef;
57 34 field $_init_tn :param(tn) = 0;
58 # Vestigial: accepted (and stored in args) for backward compatibility, but
59 # has no effect. Identifier quoting is automatic and driver-aware (see the
60 # SQL::Abstract quote_char below and _quote_id). The old on_connect used to
61 # call $dbh->quote($quote) - which quotes a VALUE and discards it, a no-op.
62 34 field $_init_quote :param(quote) = '';
63 34 field $_init_trace :param(trace) = '';
64 34 field $_init_profile :param(profile) = '';
65 34 field $_init_abstract :param(abstract) = 1;
66 34 field $_init_RaiseError :param(RaiseError) = undef;
67 34 field $_init_PrintError :param(PrintError) = undef;
68 34 field $_init_AutoCommit :param(AutoCommit) = undef;
69 34 field $_init_mysql_utf8 :param(mysql_enable_utf8) = 0;
70 34 field $_init_Error :param(Error) = undef; # Compat: use RaiseError/PrintError
71 34 field $_init_max_errors :param(max_errors) = 100;
72 34 field $_init_errors_redact :param(errors_redact) = 0;
73 34 field $_init_cache :param(cache) = undef;
74 # Error reporting / read strictness / per-connection SQL (see POD).
75 34 field $_init_on_error :param(on_error) = undef;
76 34 field $_init_strict_reads :param(strict_reads) = 0;
77 34 field $_init_on_connect_sql :param(on_connect_sql) = undef;
78 34 field $_err_seq = 0; # monotonic error sequence (error_mark/errors_since)
79 # Automatic created/updated columns (see POD "timestamps").
80 34 field $_init_timestamps :param(timestamps) = undef;
81 # JSON-encoded columns (see POD "json_columns"); handled by the SQL role.
82 34 field $_init_json_columns :param(json_columns) = undef;
83 # Profiler output routing (see DBIx::Fast::Output): 'text' | 'json' | coderef,
84 # plus an optional filehandle. Applied to both tracker() and profiler().
85 34 field $_init_profile_output :param(profile_output) = undef;
86 34 field $_init_profile_output_fh :param(profile_output_fh) = undef;
87  
88 34 ADJUST {
89 # SQLite shortcut
90 if ($_init_SQLite) {
91 $_init_db //= $_init_SQLite;
92 $_init_driver = 'SQLite';
93 }
94  
95 # Build processed config
96 $_args = {
97 DBI => {
98 AutoCommit => $_init_AutoCommit // 1,
99 RaiseError => $_init_RaiseError // 1,
100 PrintError => $_init_PrintError // 0
101 },
102 Auth => {
103 user => $_init_user,
104 password => $_init_password,
105 host => $_init_host,
106 port => $_init_port,
107 },
108 tn => $_init_tn,
109 db => $_init_db // '',
110 dsn => $_init_dsn,
111 driver => $_init_driver,
112 quote => $_init_quote,
113 trace => $_init_trace,
114 profile => $_init_profile,
115 abstract => $_init_abstract,
116 };
117
118 # SQLite file check
119 if ($_init_SQLite) {
120 $self->Exception("No DB Found : $_init_SQLite")
121 unless -e $_init_SQLite;
122 }
123  
124 unless ($_args->{dsn} || $_args->{db}) {
125 $self->Exception("Need a DSN or Host");
126 }
127  
128 $_dsn = $_args->{dsn}
129 ? $self->_check_dsn($_args->{dsn})
130 : $self->_make_dsn($_args);
131  
132 # Map the UTF-8 flag to the driver-appropriate attribute now that $_dbd is
133 # resolved: DBD::MariaDB ignores mysql_enable_utf8 (it honours
134 # mariadb_enable_utf8mb4), so applying it driver-blind silently fails.
135 if ($_init_mysql_utf8) {
136 if ($_dbd eq 'MariaDB') { $_args->{DBI}{mariadb_enable_utf8mb4} = 1 }
137 elsif ($_dbd eq 'mysql') { $_args->{DBI}{mysql_enable_utf8mb4} = 1 }
138 }
139  
140 if ($_args->{abstract}) {
141 require SQL::Abstract;
142 my $qchar =
143 ($_dbd eq 'MariaDB' || $_dbd eq 'mysql') ? '`' : '"';
144 $Q = SQL::Abstract->new(quote_char => $qchar, name_sep => '.');
145 }
146  
147 # Per-connection setup, run on every (re)connect with the fresh handle so
148 # HandleError/trace/quote/Profile survive a reconnect (rank 9). Capture only
149 # plain lexicals (and a WEAKENED $self) - capturing a field or a strong
150 # $self here would re-form the reference cycle weaken() is meant to break
151 # (rank 2). Uses the passed $dbh, never $db->dbh, to avoid re-entering the
152 # Connector during a (re)connect.
153 my $weak_self = $self;
154 weaken($weak_self);
155 my $trace_opt = $_args->{trace};
156 my $profile = $_args->{profile};
157  
158 $self->Exception("on_connect_sql must be an arrayref of statements")
159 if defined $_init_on_connect_sql && ref $_init_on_connect_sql ne 'ARRAY';
160 my @init_sql = @{ $_init_on_connect_sql // [] }; # lexical copy
161  
162 my $on_connect = sub ($dbh) {
163 return unless $dbh;
164 # Statement handles belong to one connection (see SQL.pm _prepare).
165 $weak_self->_reset_sth_cache if $weak_self;
166 $dbh->{HandleError} = sub ($msg, $h, @) {
167 return 0 unless $weak_self;
168 $weak_self->set_error($DBI::err, $DBI::errstr);
169 # RaiseError: throw a typed exception instead of DBI's string. It
170 # stringifies to the very text DBI would have died with (the location
171 # from shortmess matches DBI's), so string matching keeps working.
172 if ($h && $h->{RaiseError}) {
173 my $text = $msg . Carp::shortmess();
174 # DBI warns (PrintError) before it dies; dying here skips that.
175 warn $text if $h->{PrintError};
176 die $weak_self->_db_exception($text, $h);
177 }
178 return 0; # RaiseError off: let DBI carry on (PrintError)
179 };
180 $dbh->trace($trace_opt, 'dbix-fast-trace') if $trace_opt;
181 $dbh->{Profile} = $profile . "/DBI::ProfileDumper/File:dbix-fast-$$.log"
182 if $profile;
183 # Session setup (SET NAMES, time_zone, PRAGMA ...) re-applied on every
184 # reconnect, which a one-off $db->exec after construction is not.
185 $dbh->do($_) for @init_sql;
186 };
187  
188 # Handle db param: connector object or string
189 if ($_init_db && ref($_init_db)) {
190 $db = $_init_db;
191 } else {
192 $db = DBIx::Fast::Connector->new(
193 dsn => $_dsn,
194 user => $_args->{Auth}->{user},
195 pass => $_args->{Auth}->{password},
196 attrs => $_args->{DBI},
197 on_connect => $on_connect,
198 );
199 }
200  
201 # Apply now to the initial handle (and to an injected connector, whose
202 # reconnects we do not control).
203 $on_connect->($db->dbh);
204  
205 if (defined $_init_timestamps) {
206 $self->_check_timestamps;
207 $self->_timestamps_on;
208 }
209 $self->_configure_json($_init_json_columns) if defined $_init_json_columns;
210  
211 $self->schema->_load_tables_name if $_args->{tn};
212 }
213  
214 # Validate the timestamps option once, at construction.
215 7 ▶ method _check_timestamps () {
Subroutine _check_timestamps: called CC=15 SCAR=27.3
216 7 my $ts = $_init_timestamps;
217 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
218 6 for my $k (keys %$ts) {
219 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
220 unless $k =~ /\A(?:default|tables|source)\z/;
221 }
222 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
223 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
224 unless $source =~ /\A(?:host|utc|server)\z/;
225  
226 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
227 4 ▶ if (defined $ts->{tables}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ts->{"tables"}) 2 2 4
228 $self->Exception("timestamps: tables must be a hashref")
229 2 ▶ unless ref $ts->{tables} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ts->{"tables"} eq "HASH" 0 2 2
230 2 push @specs, values %{ $ts->{tables} };
231 }
232 4 for my $spec (@specs) {
233 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
234 unless ref $spec eq 'HASH';
235 8 for my $k (keys %$spec) {
236 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
237 unless $k eq 'created' || $k eq 'updated';
238 7 ▶ $self->_safe_id($spec->{$k}) if defined $spec->{$k};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{$k} 7 0 7
239 }
240 }
241 34 }
242  
243 # (created_col, updated_col, value) for a table, or () when no timestamps
244 # apply. A tables entry replaces the default for that table entirely
245 # ({} disables timestamps there). The value is a plain timestamp string
246 # (source host/utc) or \'CURRENT_TIMESTAMP' (source server).
247 30 ▶ method _timestamps_for ($table) {
Subroutine _timestamps_for: called CC=10 SCAR=23.4
248 30 ▶ return () unless $_init_timestamps;
Branch: 1 branch
BranchTrueFalseTotal
unless $_init_timestamps 0 30 30
249 my $spec = $_init_timestamps->{tables} && exists $_init_timestamps->{tables}{$table}
250 ? $_init_timestamps->{tables}{$table}
251 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
252 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
253 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
254 28 ▶ my $value = $source eq 'server' ? \'CURRENT_TIMESTAMP'
Branch: 2 branches
BranchTrueFalseTotal
$source eq 'server' ? : 14 14 28
$source eq 'utc' ? : 0 14 14
255 : $source eq 'utc' ? $self->now_utc
256 : $self->now;
257 28 return ($spec->{created}, $spec->{updated}, $value);
258 34 }
259  
260 # Setters for internal state (needed by tests and internal methods)
261 # (dsn/args feed the memoized cached() key namespace - drop it on change.)
262 0 ▶ method _set_args ($val) { $_args = $val; undef $_cache_ns }
Subroutine _set_args: not called CC=1 SCAR=4.9
263 0 ▶ method _set_dbd ($val) { $_dbd = $val }
Subroutine _set_dbd: not called CC=1 SCAR=4.6
264 0 ▶ method _set_dsn ($val) { $_dsn = $val; undef $_cache_ns }
Subroutine _set_dsn: not called CC=1 SCAR=4.9
265  
266 # Lazy subsystem accessors (loaded on demand)
267 30 ▶ method schema {
Subroutine schema: called CC=2 SCAR=7.0
Pod documented
268 30 ▶ $_schema //= do {
Condition66%2/3
$_schema //= do { require DBIx::Fast::Schema; "DBIx::Fast::Schema"->new("dbix", $self) }
l!l&&r!l&&!r
2550
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
269 5 require DBIx::Fast::Schema;
270 5 DBIx::Fast::Schema->new(dbix => $self);
271 };
272 34 }
273  
274 75 ▶ method transaction {
Subroutine transaction: called CC=2 SCAR=7.0
Pod documented
275 75 ▶ $_transaction //= do {
Condition66%2/3
$_transaction //= do { require DBIx::Fast::Transaction; "DBIx::Fast::Transaction"->new("dbix", $self) }
l!l&&r!l&&!r
6780
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
276 8 require DBIx::Fast::Transaction;
277 8 DBIx::Fast::Transaction->new(dbix => $self);
278 };
279 34 }
280  
281 # Only the profile_output* options the caller actually set, so the
282 # DBIx::Fast::Output role defaults apply otherwise.
283 9 ▶ method _output_opts {
Subroutine _output_opts: called CC=3 SCAR=11.2
284 return (
285 9 ▶ defined $_init_profile_output
Branch: 2 branches
BranchTrueFalseTotal
defined $_init_profile_output ? : 4 5 9
defined $_init_profile_output_fh ? : 0 9 9
286 ? (output => $_init_profile_output) : (),
287 defined $_init_profile_output_fh
288 ? (output_fh => $_init_profile_output_fh) : (),
289 );
290 34 }
291  
292 15 ▶ method tracker {
Subroutine tracker: called CC=2 SCAR=7.0
Pod documented
293 15 ▶ $_query_tracker //= do {
Condition66%2/3
$_query_tracker //= do { require DBIx::Fast::Profiler; "DBIx::Fast::Profiler"->new("dbix", $self, "auto_print", 0, $self->_output_opts) }
l!l&&r!l&&!r
960
MC/DC0%0/2
$_query_tracker //= do { require DBIx::Fast::Profiler; "DBIx::Fast::Profiler"->new("dbix", $self, "auto_print", 0, $self->_output_opts) }
$_query_tracker do { require DBIx::Fast::Profiler; "DBIx::Fast::Profiler"->new("dbix", $self, "auto_print", 0, $self->_output_opts) }
Truth table66%2/3
A //= B
A= $_query_trackerB= do { require DBIx::Fast::Profiler; "DBIx::Fast::Profiler"->new("dbix", $self, "auto_print", 0, $self->_output_opts) }
ABresult
1X1
011
000
294 6 require DBIx::Fast::Profiler;
295 6 DBIx::Fast::Profiler->new(dbix => $self, auto_print => 0,
296 $self->_output_opts);
297 };
298 34 }
299  
300 # Non-vivifying tracker lookup for the SQL role's _track: going through
301 # tracker() would instantiate the profiler and turn tracking on for every
302 # query from then on.
303 510 ▶ method _active_tracker {
Subroutine _active_tracker: called CC=3 SCAR=11.0
304 510 ▶ return $_query_tracker && $_query_tracker->enabled
Branch: 1 branch
BranchTrueFalseTotal
$_query_tracker && $_query_tracker->enabled ? : 28 482 510
Condition100%3/3
$_query_tracker and $_query_tracker->enabled
!ll&&!rl&&r
481128
MC/DC100%2/2
$_query_tracker and $_query_tracker->enabled
$_query_tracker $_query_tracker->enabled
Truth table100%3/3
A and B
A= $_query_trackerB= $_query_tracker->enabled
ABresult
0X0
100
111
305 ? $_query_tracker : undef;
306 34 }
307  
308 # Returns the cache instance if `cache => {...}` was passed at construction,
309 # otherwise undef. Caching is opt-in to keep zero-overhead for users that
310 # don't need it.
311 89 ▶ method cache {
Subroutine cache: called CC=4 SCAR=13.9
Pod documented
312 89 ▶ return $_cache if $_cache;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache 82 7 89
313 # Truthiness, not defined-ness: `cache => 0` / `''` (a common "disable"
314 # idiom, e.g. `cache => $enabled ? {...} : 0`) must NOT switch caching on.
315 7 ▶ return undef unless $_init_cache;
Branch: 1 branch
BranchTrueFalseTotal
unless $_init_cache 3 4 7
316  
317 4 require DBIx::Fast::Cache;
318 4 ▶ my %opts = ref $_init_cache eq 'HASH' ? %{$_init_cache} : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $_init_cache eq 'HASH' ? : 4 0 4
319 4 $_cache = DBIx::Fast::Cache->new(%opts);
320 34 }
321  
322 # Returns a query proxy that caches results. If cache is disabled,
323 # the proxy still works but transparently bypasses the cache.
324 37 ▶ method cached (%opts) {
Subroutine cached: called CC=1 SCAR=0.0
Pod documented
325 37 require DBIx::Fast::Cached;
326 37 DBIx::Fast::Cached->new(dbix => $self, %opts);
327 34 }
328  
329 # Connection identity prefix for DBIx::Fast::Cached keys: dsn and user are
330 # fixed after construction, so build it once instead of once per proxy.
331 37 ▶ method _cache_ns () {
Subroutine _cache_ns: called CC=4 SCAR=14.2
332 37 ▶ $_cache_ns //= ($_dsn // '') . "\0" . ($_args->{Auth}{user} // '') . "\0";
Condition66%4/6
$_cache_ns //= ($_dsn // "") . "\000" . ($_args->{"Auth"}{"user"} // "") . "\000"
l!l
325
$_dsn // ""
l!l
50
$_args->{"Auth"}{"user"} // ""
l!l
50
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
333 34 }
334  
335 6 ▶ method profiler {
Subroutine profiler: called CC=3 SCAR=11.6
Pod documented
336 6 ▶ return $_profiler if $_profiler;
Branch: 1 branch
BranchTrueFalseTotal
if $_profiler 3 3 6
337  
338 3 my $driver = $_dbd;
339 3 my $profile_class = "DBIx::Fast::Profile::$driver";
340  
341 3 (my $_pf = "$profile_class.pm") =~ s|::|/|g; eval { require $_pf };
342  
343 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3 3
344 0 warn "No profile support for $driver, using base profile";
345 0 require DBIx::Fast::Profile::Base;
346 0 $_profiler = DBIx::Fast::Profile::Base->new(dbix => $self,
347 $self->_output_opts);
348 0 return $_profiler;
349 }
350  
351 3 $_profiler = $profile_class->new(dbix => $self, $self->_output_opts);
352 3 $_profiler->init();
353  
354 3 return $_profiler;
355 34 }
356  
357 # Transaction helper
358 14 ▶ method txn ($code, $options = undef) {
Subroutine txn: called CC=2 SCAR=6.9
Pod documented
359 14 return $self->transaction->do($code, $options);
360 34 }
361  
362 3 ▶ method load_extension ($extension) {
Subroutine load_extension: called CC=6 SCAR=19.9
Pod documented
363 # A module name, not a path: "../../evil" or "Foo'Bar" would otherwise
364 # require an arbitrary .pm from outside the DBIx::Fast namespace.
365 3 ▶ $self->Exception("Invalid extension name")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $extension and $extension =~ /\A[A-Za-z]\w*(?:::\w+)*\z/u 0 3 3
Condition33%1/3
defined $extension and $extension =~ /\A[A-Za-z]\w*(?:::\w+)*\z/u
!ll&&!rl&&r
003
MC/DC0%0/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 table33%1/3
A and B
A= defined $extensionB= $extension =~ /\A[A-Za-z]\w*(?:::\w+)*\z/u
ABresult
0X0
100
111
366 unless defined $extension && $extension =~ /\A[A-Za-z]\w*(?:::\w+)*\z/;
367  
368 3 my $module = "DBIx::Fast::$extension";
369  
370 3 (my $_mf = "$module.pm") =~ s|::|/|g; eval { require $_mf };
371 3 ▶ $self->Exception("Error: load_extension => $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 2 3
372  
373 2 my $attr = lc($extension);
374  
375 # Check if there's already a method for this
376 2 ▶ if ($self->can($attr)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can($attr)) 2 0 2
377 2 return $self->$attr;
378 }
379  
380 0 ▶ return $_extensions{$attr} if exists $_extensions{$attr};
Branch: 1 branch
BranchTrueFalseTotal
if exists $_extensions{$attr} 0 0 0
381  
382 0 $_extensions{$attr} = $module->new(dbix => $self);
383 0 return $_extensions{$attr};
384 34 }
385  
386 15 ▶ method now () {
Subroutine now: called CC=1 SCAR=0.0
Pod documented
387 15 my ($sec, $min, $hour, $mday, $mon, $year) = localtime;
388  
389 15 return sprintf(
390 "%04d-%02d-%02d %02d:%02d:%02d",
391 $year + 1900, $mon + 1, $mday, $hour, $min, $sec
392 );
393 34 }
394  
395 # Like now() but in UTC (gmtime). Use when the DB session timezone differs
396 # from the host's, so stored timestamps stay comparable to server-side UTC.
397 1 ▶ method now_utc () {
Subroutine now_utc: called CC=1 SCAR=0.0
Pod documented
398 1 my ($sec, $min, $hour, $mday, $mon, $year) = gmtime;
399  
400 1 return sprintf(
401 "%04d-%02d-%02d %02d:%02d:%02d",
402 $year + 1900, $mon + 1, $mday, $hour, $min, $sec
403 );
404 34 }
405  
406 # Redact quoted literal values when errors_redact is on. Targets the common
407 # "Duplicate entry 'X' for key 'Y'" / "data X" patterns that leak PII or PCI
408 # data (card tokens, emails, etc.) into logs. Shared by set_error and
409 # Exception so both reporting paths honor the same policy.
410 114 ▶ method _redact ($msg) {
Subroutine _redact: called CC=3 SCAR=11.0
411 114 ▶ return $msg unless $_init_errors_redact && defined $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless $_init_errors_redact and defined $msg 111 3 114
Condition66%2/3
$_init_errors_redact and defined $msg
!ll&&!rl&&r
11103
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
412 3 $msg =~ s/'[^']*'/'<redacted>'/g;
413 3 $msg =~ s/"[^"]*"/"<redacted>"/g;
414 # MySQL/MariaDB quote identifiers (and some values) with backticks.
415 3 $msg =~ s/`[^`]*`/`<redacted>`/g;
416 3 return $msg;
417 34 }
418  
419 33 ▶ method set_error ($id, $error_msg) {
Subroutine set_error: called CC=8 SCAR=20.8
Pod documented
420 33 $error_msg = $self->_redact($error_msg);
421  
422 # The statement in flight (sql/p come from the SQL role) so the failing
423 # query can be reported without racing later queries that overwrite them.
424 33 my $binds = $self->p;
425 33 ▶ $binds = [ map { '<redacted>' } @$binds ]
Branch: 1 branch
BranchTrueFalseTotal
if $binds and $_init_errors_redact 1 32 33
Condition100%3/3
$binds and $_init_errors_redact
!ll&&!rl&&r
3291
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
426 if $binds && $_init_errors_redact;
427  
428 33 ▶ my $error = {
Branch: 1 branch
BranchTrueFalseTotal
$binds ? : 30 3 33
429 id => $id,
430 error => $error_msg,
431 time => time(),
432 seq => ++$_err_seq,
433 sql => $self->sql,
434 binds => $binds ? [ @$binds ] : [],
435 };
436  
437 33 push @{$_errors}, $error;
438  
439 # FIFO cap: drop oldest entries when above the configured ceiling. Prevents
440 # unbounded growth in long-running workers that hit recurring DB errors.
441 33 ▶ if ($_init_max_errors > 0
Branch: 1 branch
BranchTrueFalseTotal
if ($_init_max_errors > 0 and scalar @{$_errors;} > $_init_max_errors) 3 30 33
Condition66%2/3
$_init_max_errors > 0 and scalar @{$_errors;} > $_init_max_errors
!ll&&!rl&&r
0303
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
442 33 && scalar @{$_errors} > $_init_max_errors) {
443 3 splice @{$_errors}, 0,
444 3 scalar(@{$_errors}) - $_init_max_errors;
445 }
446  
447 $_last_error =
448 33 qq{$error->{time} - [$error->{id}] - $error->{error}};
449  
450 # A failing callback must never break the caller's DBI flow (this runs
451 # inside DBI's HandleError).
452 33 ▶ if ($_init_on_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_init_on_error) 2 31 33
453 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
454 or warn "DBIx::Fast on_error callback died: $@";
455 }
456  
457 33 return $_last_error;
458 34 }
459  
460 # Error scoping: take a mark before a unit of work (a request, a job) and
461 # collect exactly the errors it produced afterwards. Sequence-based, so it
462 # stays correct after the max_errors FIFO cap has dropped older entries.
463 2 ▶ method error_mark () { return $_err_seq }
Subroutine error_mark: called CC=1 SCAR=0.0
Pod documented
464  
465 2 ▶ method errors_since ($mark = 0) {
Subroutine errors_since: called CC=2 SCAR=6.9
Pod documented
466 2 return [ grep { $_->{seq} > $mark } @{$_errors} ];
467 34 }
468  
469 21 ▶ method strict_reads () { return $_init_strict_reads }
Subroutine strict_reads: called CC=1 SCAR=0.0
Pod documented
470  
471 # DSN handling
472  
473 86 ▶ method _Driver_dbd ($dbd_name) {
Subroutine _Driver_dbd: called CC=5 SCAR=16.2
474 86 ▶ $self->Exception("Error DBD Driver") unless $dbd_name;
Branch: 1 branch
BranchTrueFalseTotal
unless $dbd_name 0 86 86
475  
476 86 for my $d (qw(SQLite Pg MariaDB mysql)) {
477 102 ▶ if (lc($dbd_name) eq lc($d)) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $dbd_name eq lc $d) 86 16 102
478 86 $_dbd = $d;
479 86 last;
480 }
481 }
482  
483 86 ▶ $self->Exception("Error DBD Driver : $dbd_name") unless $_dbd;
Branch: 1 branch
BranchTrueFalseTotal
unless $_dbd 0 86 86
484 34 }
485  
486 75 ▶ method _dsn_dbi ($dsn_str) {
Subroutine _dsn_dbi: called CC=5 SCAR=17.0
487 # A native dbi:DRIVER:... DSN. DBI itself is the authority on the
488 # driver-specific remainder, so only confirm the 'dbi' prefix and resolve
489 # the driver. Split with a limit of 3 so the rest stays intact (e.g.
490 # SQLite's "dbi:SQLite::memory:", where the database part contains colons).
491 75 my ($dbi, $driver) = split /:/, $dsn_str, 3;
492  
493 75 ▶ $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 2 73 75
Condition44%4/9
defined $dbi and lc $dbi eq "dbi" and defined $driver and length $driver
!ll&&!rl&&r
0273
defined $dbi and lc $dbi eq "dbi" and defined $driver
!ll&&!rl&&r
0075
defined $dbi and lc $dbi eq "dbi"
!ll&&!rl&&r
0075
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
494 unless defined $dbi && lc($dbi) eq 'dbi'
495 && defined $driver && length $driver;
496  
497 73 $self->_Driver_dbd($driver);
498  
499 73 return $dsn_str;
500 34 }
501  
502 79 ▶ method _check_dsn ($dsn_str) {
Subroutine _check_dsn: called CC=2 SCAR=6.9
503 # Case-insensitive: "DBI:..." is as valid as "dbi:..." for DBI.
504 79 ▶ return $self->_dsn_dbi($dsn_str) if $dsn_str =~ /^dbi/i;
Branch: 1 branch
BranchTrueFalseTotal
if $dsn_str =~ /^dbi/iu 75 4 79
505 4 return $self->_dsn_to_dbi($dsn_str);
506 34 }
507  
508 13 ▶ method _make_dsn ($args) {
Subroutine _make_dsn: called CC=11 SCAR=26.3
509 13 ▶ $self->Exception("DSN Driver: Not defined") unless $args->{driver};
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"driver"} 0 13 13
510  
511 13 $self->_Driver_dbd($args->{driver});
512  
513 return 'dbi:SQLite:dbname=' . $args->{db}
514 13 ▶ if $args->{driver} eq 'SQLite';
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"driver"} eq "SQLite" 11 2 13
515  
516 # host/port live under Auth in the constructed config, but accept them at
517 # the top level too (direct callers / tests).
518 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
519 2 ▶ my $port = $args->{port} // ($args->{Auth} && $args->{Auth}{port});
Condition50%3/6
$args->{"port"} // $args->{"Auth"} && $args->{"Auth"}{"port"}
l!l&&r!l&&!r
101
$args->{"Auth"} and $args->{"Auth"}{"port"}
!ll&&!rl&&r
100
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
520  
521 2 ▶ $self->Exception("DSN Host: Not defined") unless $host;
Branch: 1 branch
BranchTrueFalseTotal
unless $host 0 2 2
522 2 ▶ $self->Exception("DSN DB: Not defined") unless $args->{db};
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"db"} 0 2 2
523 2 $self->_check_dsn_part($_) for grep { defined } $args->{db}, $host, $port;
524  
525 # Proper ';'-separated name=value DSN. The old "...:database=db:host" form
526 # folded the host into the dbname (so DBD drivers ignored it) and could not
527 # express a port.
528 2 my $dsn = "dbi:$_dbd:dbname=$args->{db};host=$host";
529 2 ▶ $dsn .= ";port=$port" if $port;
Branch: 1 branch
BranchTrueFalseTotal
if $port 1 1 2
530 2 return $dsn;
531 34 }
532  
533 19 ▶ method _dsn_to_dbi ($dsn_str) {
Subroutine _dsn_to_dbi: called CC=14 SCAR=26.5
534 19 my $URI;
535  
536 # SQLite
537 19 ▶ if ($dsn_str =~ /^sqlite:\/\/\/(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dsn_str =~ m[^sqlite:///(.*)$]u) 0 19 19
538 0 $_dbd = 'SQLite';
539 0 return 'dbi:SQLite:dbname=' . $1;
540 }
541  
542 # userinfo (user[:pass]@) is optional: a credential-less URI like
543 # "mariadb://localhost/db" is valid for socket / peer authentication.
544 # The userinfo match is greedy up to the LAST '@' before the path, so a
545 # raw '@' in the password still parses; %XX escapes are decoded below.
546 19 ($URI->{schema}, $URI->{UI}, $URI->{connect}, $URI->{db}) =
547 $dsn_str =~ m{^([^:]+)://(?:([^/]*)@)?([^/@]+)/(.+)$};
548  
549 19 ▶ $self->Exception("_dsn_to_dbi : schema") unless $URI->{schema};
Branch: 1 branch
BranchTrueFalseTotal
unless $URI->{"schema"} 1 18 19
550  
551 # The driver is resolved from the URI scheme at the bottom of this method
552 # (postgres/postgresql -> Pg, mariadb -> MariaDB, mysql/mysqlx -> mysql).
553 # Do NOT call _Driver_dbd($schema) here: it doesn't know those scheme aliases
554 # and, on a fresh construction (no $_dbd yet), would throw "Error DBD Driver"
555 # for a perfectly valid "postgres://" / "postgresql://" / "mysqlx://" DSN.
556 18 ▶ $self->Exception("_dsn_to_dbi : connect") unless $URI->{connect};
Branch: 1 branch
BranchTrueFalseTotal
unless $URI->{"connect"} 0 18 18
557  
558 $URI->{connect} =~ /:/
559 ? ($URI->{host}, $URI->{port}) = split ':', $URI->{connect}
560 18 ▶ : $URI->{host} = $URI->{connect};
Branch: 1 branch
BranchTrueFalseTotal
$URI->{'connect'} =~ /:/u ? : 14 4 18
561  
562 # UserInfo (absent for socket/peer auth - leave Auth untouched then).
563 18 ▶ if (defined $URI->{UI}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $URI->{"UI"}) 16 2 18
564 16 ▶ if ($URI->{UI} =~ /:/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($URI->{'UI'} =~ /:/u) { } 12 4 16
565 # Limit to two fields so a password containing ':' is kept intact.
566 ($URI->{user}, $URI->{password}) =
567 12 map { _uri_unescape($_) } split /:/, $URI->{UI}, 2;
568  
569 12 $_args->{Auth}->{user} = $URI->{user};
570 12 $_args->{Auth}->{password} = $URI->{password};
571 } else {
572 # User without password ("mariadb://alice@host/db"): still the login.
573 4 $URI->{user} = _uri_unescape($URI->{UI});
574 4 $_args->{Auth}->{user} = $URI->{user};
575 }
576 }
577  
578 18 ▶ $self->Exception('_dsn_to_dbi : No DB value') unless $URI->{db};
Branch: 1 branch
BranchTrueFalseTotal
unless $URI->{"db"} 0 18 18
579  
580 18 ▶ if ($URI->{db} =~ s/^(.*)\?(.*)$/$1/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($URI->{"db"} =~ s/^(.*)\?(.*)$/$1/u) 3 15 18
581 3 ($URI->{attribute}, $URI->{value}) = split '=', $2;
582 }
583 18 $URI->{db} = _uri_unescape($URI->{db});
584  
585 18 $self->_check_dsn_part($_) for grep { defined } @{$URI}{qw(db host port)};
586  
587 18 ▶ if ($dsn_str =~ /^(postgres|postgresql):/) {
Branch: 3 branches
BranchTrueFalseTotal
if ($dsn_str =~ /^(postgres|postgresql):/u) { } 6 12 18
elsif ($dsn_str =~ /^(mariadb):/u) { } 5 7 12
elsif ($dsn_str =~ /^(mysql|mysqlx):/u) { } 3 4 7
588 6 $_dbd = 'Pg';
589 } elsif ($dsn_str =~ /^(mariadb):/) {
590 5 $_dbd = 'MariaDB';
591 } elsif ($dsn_str =~ /^(mysql|mysqlx):/) {
592 3 $_dbd = 'mysql';
593 } else {
594 # Never echo the raw DSN: for URI-style DSNs it carries user:password.
595 4 (my $redacted = $dsn_str) =~ s{//[^/]*@}{//<redacted>@};
596 4 $self->Exception("_dsn_to_dbi : $redacted");
597 }
598  
599 $URI->{DSN} = sprintf('dbi:%s:dbname=%s;host=%s%s',
600 $_dbd, $URI->{db}, $URI->{host},
601 14 ▶ $URI->{port} ? ";port=$URI->{port}" : ''
Branch: 1 branch
BranchTrueFalseTotal
$URI->{'port'} ? : 12 2 14
602 );
603  
604 14 return $URI->{DSN};
605 34 }
606  
607 # A DSN component (db/host/port) is interpolated into a ';'-separated
608 # name=value DSN: a ';' or '=' would smuggle in extra driver attributes
609 # (e.g. db => 'app;mariadb_local_infile=1').
610 55 ▶ method _check_dsn_part ($part) {
Subroutine _check_dsn_part: called CC=2 SCAR=7.0
611 55 ▶ $self->Exception("Invalid character in DSN component")
Branch: 1 branch
BranchTrueFalseTotal
if $part =~ /[;=]/u 0 55 55
612 if $part =~ /[;=]/;
613 34 }
614  
615 46 ▶ sub _uri_unescape ($s) {
Subroutine _uri_unescape: called CC=2 SCAR=7.6
616 46 ▶ return $s unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 46 46
617 46 $s =~ s/%([0-9A-Fa-f]{2})/chr hex $1/ge;
618 46 return $s;
619 }
620  
621 0 ▶ method _profile ($stat) {
Subroutine _profile: not called CC=1 SCAR=6.9
622 0 $stat .= "/DBI::ProfileDumper/";
623 0 $stat .= qq{File:dbix-fast-$$.log};
624  
625 0 $db->dbh->{Profile} = $stat;
626 34 }
627  
628 # Validate identifier
629 719 ▶ method _safe_id ($name) {
Subroutine _safe_id: called CC=3 SCAR=11.0
630 719 ▶ $self->Exception("Invalid identifier")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and $name =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/u 13 706 719
Condition66%2/3
defined $name and $name =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/u
!ll&&!rl&&r
013706
MC/DC50%1/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 table66%2/3
A and B
A= defined $nameB= $name =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/u
ABresult
0X0
100
111
631 unless defined $name && $name =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/;
632  
633 706 return $name;
634 34 }
635  
636 # Validate and quote identifier (defense-in-depth)
637 0 ▶ method _quote_id ($name) {
Subroutine _quote_id: not called CC=1 SCAR=6.9
638 0 $self->_safe_id($name);
639 0 return $db->dbh->quote_identifier($name);
640 34 }
641  
642 # Validate and quote a possibly-qualified identifier ("schema.table",
643 # "t.col") by quoting each dot-separated segment, so quote_identifier does not
644 # wrap the whole dotted name as one literal identifier ("schema.table").
645 #
646 # Memoized per instance: the quoting is a pure function of the name and the
647 # (fixed) driver, and each miss costs a Connector->dbh round (fork check =
648 # getpid syscall) plus one quote_identifier per segment. Only names that
649 # passed _safe_id are ever stored.
650 125 ▶ method _quote_ident_path ($name) {
Subroutine _quote_ident_path: called CC=4 SCAR=13.9
651 125 ▶ return $_qid{$name} if defined $name && exists $_qid{$name};
Branch: 1 branch
BranchTrueFalseTotal
if defined $name and exists $_qid{$name} 86 39 125
Condition66%2/3
defined $name and exists $_qid{$name}
!ll&&!rl&&r
03986
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
652 39 $self->_safe_id($name);
653 39 ▶ %_qid = () if keys %_qid >= 1_000; # bound data-driven identifiers
Branch: 1 branch
BranchTrueFalseTotal
if keys %_qid >= 1000 0 39 39
654 39 my $dbh = $db->dbh;
655 return $_qid{$name} =
656 39 join '.', map { $dbh->quote_identifier($_) } split /\./, $name;
657 34 }
658  
659 # Validate a CRUD data/WHERE spec before it reaches SQL::Abstract, which
660 # interpolates hash keys verbatim (its injection_guard only blocks ';'). Must
661 # cover EVERY shape SQL::Abstract accepts, not just HASH: an arrayref WHERE
662 # (OR-of-conditions) or a scalarref WHERE (literal SQL) would otherwise slip
663 # past the operator whitelist entirely.
664 13 ▶ method _safe_columns ($spec) {
Subroutine _safe_columns: called CC=10 SCAR=38.2
665 13 my $ref = ref $spec;
666 13 ▶ if ($ref eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq 'HASH') { } 13 0 13
elsif ($ref eq 'ARRAY') { } 0 0 0
elsif ($ref) { } 0 0 0
667 13 $self->_safe_id($_) for keys %$spec;
668 13 $self->_safe_op_tree($_) for values %$spec;
669 }
670 elsif ($ref eq 'ARRAY') {
671 # OR-list. Elements are -and/-or logic tokens, nested hashref/arrayref
672 # conditions, or "column => condition" pairs (SQL::Abstract reads a plain
673 # scalar as a column name and the next element as its condition). Any
674 # other dash token is refused: [ -literal => ['1=1'] ] is raw SQL.
675 0 ▶ for (my $i = 0; $i < @$spec; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$spec) 0 0 0
676 0 my $el = $spec->[$i];
677 0 ▶ if (ref $el) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $el) { } 0 0 0
elsif (defined $el and $el =~ /^-(?:and|or)$/iu) { } 0 0 0
678 0 $self->_safe_columns($el);
679 }
680 ▶ elsif (defined $el && $el =~ /^-(?:and|or)$/i) {
Condition0%0/3
defined $el and $el =~ /^-(?:and|or)$/iu
!ll&&!rl&&r
000
MC/DC0%0/2
defined $el and $el =~ /^-(?:and|or)$/iu
defined $el $el =~ /^-(?:and|or)$/iu
Truth table0%0/3
A and B
A= defined $elB= $el =~ /^-(?:and|or)$/iu
ABresult
0X0
100
111
681 0 next;
682 }
683 else {
684 0 $self->_safe_id($el);
685 0 $self->_safe_op_tree($spec->[++$i]);
686 }
687 }
688 }
689 elsif ($ref) {
690 # A literal-SQL WHERE ( \'1=1' ) from a CRUD helper can never be trusted.
691 0 $self->Exception("Literal-SQL WHERE is not allowed in CRUD methods");
692 }
693 # plain scalar / undef: a bind value, nothing to validate.
694 34 }
695  
696 # Validate an INSERT row / UPDATE SET spec. SQL::Abstract 2 reads a hashref
697 # or arrayref value there as an expression, not a bind: [ '(SELECT ...)' ] is
698 # raw SQL and { -literal | -func | -ident => ... } build SQL from their
699 # argument - shapes a decoded JSON body can carry. Blessed objects (JSON
700 # booleans) stringify and bind normally. A scalarref ( \'NOW()' ) stays
701 # allowed: it is the documented literal-SQL escape hatch and cannot come
702 # from a JSON/form decoder, only from code.
703 120 ▶ method _safe_data ($spec) {
Subroutine _safe_data: called CC=7 SCAR=22.4
704 120 ▶ $self->Exception("CRUD data must be a hashref") unless ref $spec eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 0 120 120
705  
706 120 for my $col (keys %$spec) {
707 278 $self->_safe_id($col);
708 278 my $ref = ref $spec->{$col};
709 $self->Exception("Invalid value for column $col: "
710 . "hashref/arrayref values are not allowed in CRUD data")
711 278 ▶ 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" 0 278 278
Condition33%3/9
$ref and not builtin::blessed($spec->{$col}) and $ref ne "SCALAR" and $ref ne "REF"
!ll&&!rl&&r
27800
$ref and not builtin::blessed($spec->{$col}) and $ref ne "SCALAR"
!ll&&!rl&&r
27800
$ref and not builtin::blessed($spec->{$col})
!ll&&!rl&&r
27800
MC/DC0%0/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 table20%1/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
712 && $ref ne 'SCALAR' && $ref ne 'REF';
713 }
714 34 }
715  
716 # Validate the condition attached to one column in a CRUD WHERE spec. The
717 # grammar is deliberately narrow, because SQL::Abstract 2 is an expression
718 # language: a hashref on the right of an operator loses the column context and
719 # is expanded as a generic expression, where [ -literal => [...] ],
720 # [ -func => [...] ] and [ -ident => ... ] pairs (or the same as hash keys)
721 # emit raw SQL. So:
722 # condition := plain | [ (-and|-or)?, condition... ] | { key => ... }
723 # key := -and/-or => condition | operator => operand
724 # operand := plain | [ plain... ] (bind values only, never a hash)
725 # "plain" is a non-ref, undef, a blessed object (binds by stringification)
726 # or a scalarref - the documented literal-SQL escape hatch, which a JSON/form
727 # decoder cannot produce. Anything else is refused, never skipped.
728 # Validate a row for the hand-built, fully bound INSERTs (upsert/*_many).
729 # Values are placeholders there, so a reference would be bound as its
730 # stringification ("SCALAR(0x...)", "HASH(0x...)") and silently stored.
731 # Plain values and blessed objects bind; an arrayref is kept for Pg, where
732 # DBD::Pg binds it as a native array.
733 56 ▶ method _safe_bind_row ($row) {
Subroutine _safe_bind_row: called CC=2 SCAR=6.9
734 56 $self->_safe_id($_) for keys %$row;
735 55 $self->_safe_bind_values([ values %$row ]);
736 34 }
737  
738 # Value half of _safe_bind_row, for the *_many paths (whose column names
739 # are validated once, on row 0).
740 77 ▶ method _safe_bind_values ($vals) {
Subroutine _safe_bind_values: called CC=6 SCAR=25.6
741 77 my $pg = $self->dbd eq 'Pg';
742 77 for my $v (@$vals) {
743 330 ▶ my $ref = ref $v or next;
Branch: 1 branch
BranchTrueFalseTotal
my $ref = ref $v or next 0 330 330
744 0 ▶ next if blessed($v) || ($pg && $ref eq 'ARRAY');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($v) or $pg and $ref eq "ARRAY" 0 0 0
Condition0%0/6
builtin::blessed($v) or $pg and $ref eq "ARRAY"
l!l&&r!l&&!r
000
$pg and $ref eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/3
builtin::blessed($v) or $pg and $ref eq "ARRAY"
builtin::blessed($v) $pg $ref eq "ARRAY"
Truth table0%0/4
A or B and C
A= builtin::blessed($v)B= $pgC= $ref eq "ARRAY"
ABCresult
1XX1
0111
00X0
0100
745 0 $self->Exception("Invalid value: a $ref reference cannot be bound");
746 }
747 34 }
748  
749 13 ▶ method _safe_op_tree ($val) {
Subroutine _safe_op_tree: called CC=16 SCAR=50.7
750 13 state %VALID_OPS = map { $_ => 1 }
751 ('=', '!=', '<>', '<', '<=', '>', '>=',
752 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
753 'BETWEEN', 'NOT BETWEEN', 'IS', 'IS NOT');
754  
755 # SQL::Abstract dash-ops that only compare against bind values. Others
756 # are NOT harmless: -literal and -func interpolate raw SQL from their
757 # argument, -ident turns a value into a column reference (tautologies).
758 13 state %VALID_DASH_OPS = map { $_ => 1 }
759 qw(-in -not_in -between -not_between -like -not_like -is -is_not -value);
760  
761 13 ▶ return if _plain_value($val);
Branch: 1 branch
BranchTrueFalseTotal
if _plain_value($val) 13 0 13
762  
763 0 my $ref = ref $val;
764 0 ▶ if ($ref eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref eq "ARRAY") 0 0 0
765 0 for my $i (0 .. $#$val) {
766 0 my $el = $val->[$i];
767 0 ▶ 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 0 0 0
Condition0%0/9
$i == 0 and not ref $el and defined $el and $el =~ /^-(?:and|or)$/iu
!ll&&!rl&&r
000
$i == 0 and not ref $el and defined $el
!ll&&!rl&&r
000
$i == 0 and not ref $el
!ll&&!rl&&r
000
MC/DC0%0/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 table0%0/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
768 0 $self->_safe_op_tree($el);
769 }
770 0 return;
771 }
772  
773 0 ▶ $self->Exception("Invalid condition") unless $ref eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $ref eq "HASH" 0 0 0
774  
775 0 for my $op (keys %$val) {
776 0 my $rhs = $val->{$op};
777  
778 0 ▶ if ($op =~ /^-(?:and|or)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op =~ /^-(?:and|or)$/iu) 0 0 0
779 0 $self->_safe_op_tree($rhs);
780 0 next;
781 }
782  
783 $self->Exception("Invalid operator: $op")
784 0 ▶ 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} 0 0 0
Condition0%0/3
$VALID_OPS{uc $op} or $VALID_DASH_OPS{lc $op}
l!l&&r!l&&!r
000
MC/DC0%0/2
$VALID_OPS{uc $op} or $VALID_DASH_OPS{lc $op}
$VALID_OPS{uc $op} $VALID_DASH_OPS{lc $op}
Truth table0%0/3
A or B
A= $VALID_OPS{uc $op}B= $VALID_DASH_OPS{lc $op}
ABresult
1X1
011
000
785  
786 0 ▶ next if _plain_value($rhs);
Branch: 1 branch
BranchTrueFalseTotal
if _plain_value($rhs) 0 0 0
787 $self->Exception("Invalid operand for $op: only bind values allowed")
788 0 ▶ 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) 0 0 0
Condition0%0/3
ref $rhs eq "ARRAY" and not grep({not _plain_value($_);} @$rhs)
!ll&&!rl&&r
000
MC/DC0%0/2
ref $rhs eq "ARRAY" and not grep({not _plain_value($_);} @$rhs)
ref $rhs eq "ARRAY" not grep({not _plain_value($_);} @$rhs)
Truth table0%0/3
A and not(B)
A= ref $rhs eq "ARRAY"B= not grep({not _plain_value($_);} @$rhs)
ABresult
0X0
100
111
789 }
790 34 }
791  
792 # A bind value as far as SQL::Abstract is concerned (see _safe_op_tree).
793 13 ▶ sub _plain_value ($v) {
Subroutine _plain_value: called CC=4 SCAR=18.9
794 13 my $ref = ref $v;
795 13 ▶ return !$ref || blessed($v) || $ref eq 'SCALAR' || $ref eq 'REF';
Condition33%3/9
!$ref || builtin::blessed($v) || $ref eq 'SCALAR' || $ref eq 'REF'
l!l&&r!l&&!r
1300
not $ref or builtin::blessed($v) or $ref eq "SCALAR"
l!l&&r!l&&!r
1300
not $ref or builtin::blessed($v)
l!l&&r!l&&!r
1300
MC/DC0%0/4
!$ref || builtin::blessed($v) || $ref eq 'SCALAR' || $ref eq 'REF'
not $ref builtin::blessed($v) $ref eq "SCALAR" $ref eq 'REF'
Truth table20%1/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
796 }
797  
798  
799 # Query methods
800  
801  
802  
803  
804  
805  
806  
807  
808  
809  
810  
811  
812 # Invalidate any cached query tagged with the given table name. No-op
813 # when caching is disabled. The convention is that users tag cached
814 # reads with `tag => $table` so writes propagate transparently.
815 160 ▶ method _cache_invalidate_table ($table) {
Subroutine _cache_invalidate_table: called CC=4 SCAR=13.9
816 160 ▶ return unless $_cache || defined $_init_cache;
Branch: 1 branch
BranchTrueFalseTotal
unless $_cache or defined $_init_cache 152 8 160
Condition100%3/3
$_cache or defined $_init_cache
l!l&&r!l&&!r
71152
MC/DC100%2/2
$_cache or defined $_init_cache
$_cache defined $_init_cache
Truth table100%3/3
A or B
A= $_cacheB= defined $_init_cache
ABresult
1X1
011
000
817 8 ▶ my $cache = $self->cache or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cache = $self->cache or return 8 0 8
818 8 $cache->invalidate($table);
819 34 }
820  
821 # Public cache invalidation by tag(s). Use after mutations that bypass the
822 # CRUD auto-invalidation: raw exec()/query()/execute() writes, or reads that
823 # span several tables (which must be tagged with, and invalidated for, every
824 # table involved). No-op when caching is disabled.
825 1 ▶ method invalidate (@tags) {
Subroutine invalidate: called CC=3 SCAR=11.0
Pod documented
826 1 ▶ my $cache = $self->cache or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $cache = $self->cache or return 0 1 0 1
827 1 my $n = 0;
828 1 $n += $cache->invalidate($_) for @tags;
829 1 return $n;
830 34 }
831  
832  
833  
834  
835  
836  
837  
838  
839  
840 # Named parameter methods
841  
842  
843 # Execute helpers
844  
845  
846 # Validation
847  
848 247 ▶ method TableName ($table) {
Subroutine TableName: called CC=5 SCAR=16.1
Pod documented
849 247 ▶ $self->Exception("Not defined table") unless $table;
Branch: 1 branch
BranchTrueFalseTotal
unless $table 0 247 247
850  
851 # Format validation is unconditional (same pattern as _safe_id): count()
852 # and upsert() already rejected malformed names downstream, while
853 # insert()/update() let them through to SQL::Abstract - one rule for all.
854 247 ▶ $self->Exception("TableName not valid: $table")
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/u 1 246 247
855 unless $table =~ /\A[a-zA-Z_][a-zA-Z0-9_.]*\z/;
856  
857 246 ▶ return $table unless $_args->{tn};
Branch: 1 branch
BranchTrueFalseTotal
unless $_args->{"tn"} 242 4 246
858  
859 $self->Exception("TableName not exist: $table")
860 4 ▶ unless $self->schema->tables->{$table};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->schema->tables->{$table} 1 3 4
861  
862 3 return $table;
863 34 }
864  
865 75 ▶ method Exception ($msg) {
Subroutine Exception: called CC=1 SCAR=0.0
Pod documented
866 # Always croak. Validation/usage errors (e.g. _safe_id "Invalid identifier")
867 # must never be silently swallowed: a silent return used to let a rejected
868 # identifier flow on and become an injection vector when the handle was
869 # configured with RaiseError=0 & PrintError=0.
870 #
871 # The message honors errors_redact, and last_error is attached only when
872 # RECENT (likely causal context) - a DB error from minutes ago would only
873 # mislead the diagnosis and could leak stale data into a fresh exception.
874 # Thrown as a DBIx::Fast::X::Usage whose text is exactly what the former
875 # `croak $full` produced (croak is die + shortmess).
876 75 die DBIx::Fast::X::Usage->new(
877 message => $self->_exception_text($msg) . Carp::shortmess(),
878 error => $msg,
879 );
880 34 }
881  
882 # "Exception: <msg>[ - Last error: [id] error]" - shared by Exception and
883 # the DB failures raised through _db_fail.
884 81 ▶ method _exception_text ($msg) {
Subroutine _exception_text: called CC=5 SCAR=16.1
885 81 ▶ my $full = "Exception: " . ($self->_redact($msg) // '');
Condition50%1/2
$self->_redact($msg) // ""
l!l
810
MC/DC0%0/1
$self->_redact($msg) // ""
$self->_redact($msg)
Truth table50%1/2
A
A= $self->_redact($msg)
Aresult
11
00
886  
887 # No epoch in the message: identical failures must produce identical text
888 # so log aggregation can group them (the time is in errors()->[-1]{time}).
889 81 ▶ my $last = @{$_errors} ? $_errors->[-1] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@{$_errors;} ? : 9 72 81
890 $full .= " - Last error: [$last->{id}] $last->{error}"
891 81 ▶ if $last && (time() - $last->{time}) < 5;
Branch: 1 branch
BranchTrueFalseTotal
if $last and &DBIx::Fast::time() - $last->{"time"} < 5 8 73 81
Condition100%3/3
$last and &DBIx::Fast::time() - $last->{"time"} < 5
!ll&&!rl&&r
7218
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
892  
893 81 return $full;
894 34 }
895  
896 # A classified DBIx::Fast::X::DB (or subclass) for a driver error on handle
897 # $h, carrying the statement in flight. $message is the full text.
898 7 ▶ method _db_exception ($message, $h = undef) {
Subroutine _db_exception: called CC=7 SCAR=21.5
899 7 ▶ my ($code, $state, $text) =
Branch: 1 branch
BranchTrueFalseTotal
$h ? : 7 0 7
900 $h ? ($h->err, $h->state, $h->errstr) : ($DBI::err, $DBI::state, $DBI::errstr);
901 7 my $binds = $self->p;
902 7 ▶ $binds = [ map { '<redacted>' } @$binds ] if $binds && $_init_errors_redact;
Branch: 1 branch
BranchTrueFalseTotal
if $binds and $_init_errors_redact 0 7 7
Condition33%1/3
$binds and $_init_errors_redact
!ll&&!rl&&r
070
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
903  
904 7 ▶ my $class = DBIx::Fast::X::DB->class_for($_dbd // '', $code, $state, $text);
Condition50%1/2
$_dbd // ""
l!l
70
MC/DC0%0/1
$_dbd // ""
$_dbd
Truth table50%1/2
A
A= $_dbd
Aresult
11
00
905 7 ▶ return $class->new(
Branch: 1 branch
BranchTrueFalseTotal
$binds ? : 7 0 7
906 message => $message,
907 error => $text,
908 code => $code,
909 state => $state,
910 driver => $_dbd,
911 sql => $self->sql,
912 binds => $binds ? [ @$binds ] : [],
913 constraint => DBIx::Fast::X::DB->constraint_from($text),
914 );
915 34 }
916  
917 # A database failure detected by DBIx::Fast itself (RaiseError off, so DBI
918 # did not throw): same "Exception: ..." text as Exception(), typed by the
919 # driver error on $h.
920 6 ▶ method _db_fail ($msg, $h = undef) {
Subroutine _db_fail: called CC=2 SCAR=6.9
921 6 die $self->_db_exception(
922 $self->_exception_text($msg) . Carp::shortmess(), $h);
923 34 }
924 }
925  
926 34 1;
927  
928 __END__
« Fast/SQL.pm ↑ Summary Fast/Transaction.pm »