Abstraction.pm

filter: Statementstmt 82.2% 1896 / 2304 Branchbran 74.3% 1173 / 1578 Conditioncond 57.1% 510 / 892 MC/DCmcdc 42.5% 218 / 513 Subroutinesub 95.7% 90 / 94 Podpod 100% 18 / 18 totaltotal 72.3% 3905 / 5399 CC 1186 SCAR 63.6
CC
1186
Cov
75%
_open
2079.7
selectall_array
1576.6
selectall_arrayref
746.6
CRAP 577.6
↑ Summary Abstraction/Query.pm »
1 package Database::Abstraction;
2  
3 # Author Nigel Horne: njh@nigelhorne.com
4 # Copyright (C) 2015-2026, Nigel Horne
5  
6 # Usage is subject to licence terms.
7  
8 # TODO: Switch "entry" to off by default, and enable by passing 'entry'
9 # though that wouldn't be so nice for AUTOLOAD
10 # TODO: support a directory hierarchy of databases
11 # TODO: consider returning an object or array of objects, rather than hashes
12 # Redis backend (database => 'redis://...') was added in 0.48.
13 # TODO: Add a "key" property, defaulting to "entry", which would be the name of the key
14 # TODO: The maximum number to return should be tuneable (as a LIMIT)
15 # TODO: Add full CRUD support
16 # TODO: It would be better for the default sep_char to be ',' rather than '!'
17 # TODO: Other noSQL databases e.g., MongoDB, Cassandra
18 # TODO: The no_entry/entry terminology is confusing. Replace with no_id/id_column
19 # TODO: Log queries and the time that they took to execute per database
20 # TODO: Use DBD::JSON if one is ever written
21  
22 54 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 54 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 54 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 54 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 54 ▶use Class::Abstract;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 54 ▶use Data::Reuse;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 54 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 54 ▶use Fcntl; # For O_RDONLY
Subroutine BEGIN: called CC=1 SCAR=0.0
31 54 ▶use Cwd;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 54 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 54 ▶use File::Temp;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 54 ▶use List::Util qw(all any);
Subroutine BEGIN: called CC=1 SCAR=0.0
35 54 ▶use Log::Abstraction 0.33;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 54 ▶use Object::Configure 0.16;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 54 ▶use Params::Get 0.17;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 54 ▶use Return::Set qw(set_return);
Subroutine BEGIN: called CC=1 SCAR=0.0
39 54 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 54 ▶use Sub::Private { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
41 54 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
42  
43 # File::Slurp::Remote is loaded lazily in _open() when host => '...' is given.
44  
45 54 our %defaults;
46 54 ▶use constant DEFAULT_MAX_SLURP_SIZE => 16 * 1024; # CSV files <= than this size are read into memory
Subroutine BEGIN: called CC=1 SCAR=0.0
47  
48 # Compiled once at module load; reused in every identifier-safety check.
49 # Using \A/\z (true string anchors) rather than ^/$ which match around \n.
50 # SAFE_IDENTIFIER: bare SQL identifier — letters, digits, underscore.
51 # SAFE_QUALIFIED: allows a single dot for table.column notation in JOINs.
52 54 my $SAFE_IDENTIFIER = qr/\A[a-zA-Z_][a-zA-Z0-9_]*\z/;
53 54 my $SAFE_QUALIFIED = qr/\A[a-zA-Z_][a-zA-Z0-9_.]*\z/;
54  
55 # Type-inference regexes and sample size for schema() when infer_types => 1.
56 # Compiled once at load; reused in _infer_type() across all schema() calls.
57 54 ▶use constant INFER_TYPE_SAMPLE_SIZE => 100;
Subroutine BEGIN: called CC=1 SCAR=0.0
58 54 my $INFER_INT_RE = qr/\A-?\d+\z/;
59 54 my $INFER_REAL_RE = qr/
60 \A # start of string
61 -? # optional leading minus
62 \d+ # integer part -- required
63 (?:\.\d+)? # optional decimal part
64 (?: # optional exponent block:
65 [eE] # e or E marker
66 [+-]? # optional sign
67 \d+ # exponent digits
68 )?
69 \z # end of string
70 /x;
71 # No \z anchor: intentionally matches any valid timestamp prefix so that full
72 # timestamps with seconds, fractional seconds, or timezone offsets are still
73 # classified as TIMESTAMP -- e.g. 2024-01-01 12:34:00.000+05:30
74 54 my $INFER_TS_RE = qr/
75 \A # start of string
76 \d{4} # 4-digit year
77 - (?:0[1-9]|1[0-2]) # month 01-12
78 - (?:0[1-9]|[12]\d|3[01]) # day 01-31
79 [T\ ] # ISO 8601 date-time separator: T or space
80 \d{2}:\d{2} # HH:MM -- no end anchor, see note above
81 /x;
82 54 my $INFER_DATE_RE = qr/
83 \A # start of string
84 \d{4} # 4-digit year
85 - (?:0[1-9]|1[0-2]) # month 01-12
86 - (?:0[1-9]|[12]\d|3[01]) # day 01-31
87 \z # end of string
88 /x;
89  
90 # Module-level constant: valid JOIN types after uc() normalisation.
91 # Built once at compile time; reused by every _build_joins call.
92 54 my %VALID_JOIN_TYPES = map { $_ => 1 } qw(INNER LEFT RIGHT FULL CROSS);
93  
94 # Valid aggregate functions (lower-cased) for _validate_aggregate_spec.
95 54 my %VALID_AGG_FNS = map { $_ => 1 } qw(sum avg min max count count_distinct median stddev);
96  
97 # Functions that are Perl-fold-only (no SQL pushdown).
98 54 my %PERL_ONLY_AGG_FNS = map { $_ => 1 } qw(median stddev);
99  
100 =encoding utf8
101  
102 =head1 NAME
103  
104 Database::Abstraction - Read-only Database Abstraction Layer (ORM)
105  
106 =head1 VERSION
107  
108 Version 0.57
109  
110 =cut
111  
112 54 our $VERSION = '0.57';
113  
114 =head1 DESCRIPTION
115  
116 C<Database::Abstraction> is a read-only ORM for Perl that gives a uniform
117 interface over CSV, PSV, TSV, JSON, XML, SQLite, DBM::Deep, BerkeleyDB, and
118 Excel (XLS/XLSX) files - local, remote (via SSH), or fetched from a URL -
119 without writing any SQL.
120 Effectively it allows you to access a database table, of many different
121 database formats, as an object.
122  
123 Key features:
124  
125 =over 4
126  
127 =item *
128  
129 B<No SQL required.> Use plain Perl method calls for simple lookups and
130 scans; switch storage formats without changing application code.
131  
132 =item *
133  
134 B<Rich query criteria.> Pass plain values, SQL wildcards, C<undef> (IS NULL),
135 comparison operators (C<< > >> C<< < >> C<< >= >> C<< <= >> C<!=>), pattern
136 operators (C<-like>, C<-not_like>), set operators (C<-in>, C<-not_in>,
137 C<-between>), and logical groupings (C<-or>, C<-and>).
138  
139 =item *
140  
141 B<Automatic joins.> Add a C<join> parameter to any select method to
142 combine tables with INNER, LEFT, RIGHT, FULL, or CROSS joins.
143  
144 =item *
145  
146 B<Chained query builder.> The C<query()> method returns a
147 L<Database::Abstraction::Query> object for fluent, composable queries:
148 C<< $db->query->where(...)->order_by(...)->limit(...)->all() >>.
149  
150 =item *
151  
152 B<Aggregation.> The C<aggregate()> method and the fluent
153 C<< ->group_by()->measure()->having()->all() >> chain push C<GROUP BY> to
154 SQL backends and fold rows in Perl on slurp-only backends.
155  
156 =item *
157  
158 B<Schema introspection.> C<columns()> lists column names; C<schema()>
159 returns full type/nullability metadata, using native driver introspection
160 (C<PRAGMA table_info> for SQLite, C<column_info> for others).
161  
162 =item *
163  
164 B<DSN portability.> Pass a C<dsn> (plus optional C<username>/C<password>)
165 to connect to any DBI-supported database (SQLite, PostgreSQL, MySQL, ...)
166 instead of pointing at a local file.
167  
168 =item *
169  
170 B<Performance.> Small files are slurped into a RAM hash for sub-millisecond
171 lookups. All DBI statement handles are cached with C<prepare_cached()>.
172 A CHI-compatible cache layer is also supported.
173  
174 =back
175  
176 =head1 SYNOPSIS
177  
178 # 1. Create a thin subclass for your table (e.g. Database/Foo.pm)
179 package Database::Foo;
180 use parent 'Database::Abstraction';
181  
182 # 2. Open the database - file is auto-detected from the class name
183 # (looks for foo.sql / foo.sqlite / foo.sqlite3 / foo.psv / foo.tsv / foo.csv / foo.xlsx / foo.xml / foo.json / foo.db)
184 my $db = Database::Foo->new(directory => '/path/to/data');
185  
186 # 3. Simple lookups -----------------------------------------------
187  
188 # Fetch one row
189 my $row = $db->fetchrow_hashref(entry => 'key1');
190  
191 # Fetch all rows matching a criterion
192 my $rows = $db->selectall_arrayref(status => 'active');
193  
194 # Column shortcut via AUTOLOAD
195 my $name = $db->name(entry => 'key1');
196  
197 # 4. Rich criteria ------------------------------------------------
198  
199 # Comparison operators
200 my $high = $db->selectall_arrayref(score => { '>' => 90 });
201  
202 # Set membership
203 my $selected = $db->selectall_arrayref(
204 name => { -in => ['Alice', 'Bob'] }
205 );
206  
207 # Range
208 my $mid = $db->selectall_arrayref(
209 score => { -between => [60, 80] }
210 );
211  
212 # OR grouping
213 my $either = $db->selectall_arrayref(
214 -or => [
215 { status => 'active' },
216 { score => { '>' => 95 } },
217 ]
218 );
219  
220 # 5. Joins --------------------------------------------------------
221  
222 my $joined = $db->selectall_arrayref(
223 join => { table => 'dept', on => 'foo.dept_id = dept.id', type => 'LEFT' }
224 );
225  
226 # 6. Chained query builder ----------------------------------------
227  
228 my $results = $db->query
229 ->where(status => 'active')
230 ->where(score => { '>=' => 80 })
231 ->order_by('score DESC')
232 ->limit(10)
233 ->all();
234  
235 my $first = $db->query->where(name => 'Alice')->first();
236 my $count = $db->query->where(status => 'active')->count();
237  
238 # 7. Connect via DSN (PostgreSQL, MySQL, SQLite, ...) ---------------
239  
240 my $db2 = Database::Foo->new(
241 dsn => 'dbi:Pg:dbname=mydb;host=db.example.com',
242 username => 'myuser',
243 password => 's3cret',
244 );
245  
246 # 8. Schema introspection -----------------------------------------
247  
248 my $cols = $db->columns(); # ['entry', 'name', 'score', ...]
249 my $schema = $db->schema(); # { name => { type=>'TEXT', nullable=>1, ... }, ... }
250  
251 # 9. Aggregation (GROUP BY) ----------------------------------------
252  
253 # Total revenue and order count per region
254 my $summary = $db->aggregate(
255 by => ['region'],
256 measures => [
257 { col => 'amount', fn => 'sum', as => 'revenue' },
258 { fn => 'count', as => 'orders' },
259 ],
260 );
261  
262 # Grand total across all rows
263 my $totals = $db->aggregate(
264 measures => [{ col => 'amount', fn => 'sum', as => 'total' }],
265 )->[0];
266  
267 # Fluent style with HAVING and sort
268 my $top = $db->query
269 ->group_by('region')
270 ->measure('amount', 'sum', 'revenue')
271 ->measure(undef, 'count', 'orders')
272 ->having(revenue => { '>' => 1000 })
273 ->order_by('revenue DESC')
274 ->limit(5)
275 ->all();
276  
277 =head1 QUICK START EXAMPLE
278  
279 If F</var/dat/foo.csv> contains:
280  
281 "customer_id","name"
282 "plugh","John"
283 "xyzzy","Jane"
284  
285 Create a driver in F<.../Database/foo.pm>:
286  
287 package Database::foo;
288 use parent 'Database::Abstraction';
289  
290 # Regular CSV: no entry column, comma-separated
291 sub new {
292 my ($class, %args) = @_;
293 return $class->SUPER::new(no_entry => 1, sep_char => ',', %args);
294 }
295  
296 Then query it:
297  
298 my $foo = Database::foo->new(directory => '/var/dat');
299  
300 # Prints "John"
301 print 'Customer: ', $foo->name(customer_id => 'plugh'), "\n";
302  
303 # Returns { customer_id => 'xyzzy', name => 'Jane' }
304 my $row = $foo->fetchrow_hashref(customer_id => 'xyzzy');
305  
306 =head1 FILE FORMATS
307  
308 The module probes the C<directory> for files in this priority order:
309  
310 =over 4
311  
312 =item 1. C<SQLite>
313  
314 File ending C<.sql>, C<.sqlite>, or C<.sqlite3>.
315 Requires L<DBD::SQLite>.
316  
317 =item 2. C<Deep>
318  
319 DBM::Deep file ending C<.dbm> or C<.deep>. The entire file is slurped
320 into a plain Perl hash on open; all in-memory fast-paths apply.
321 Requires L<DBM::Deep> (loaded lazily).
322  
323 =item 3. C<PSV>
324  
325 Pipe-separated file, ending C<.psv>.
326  
327 =item 4. C<TSV>
328  
329 Tab-separated file, ending C<.tsv>.
330  
331 =item 5. C<CSV>
332  
333 Comma (or custom) separated file, ending C<.csv> or C<.db>; can be
334 gzipped (C<.csv.gz> or C<.db.gz>).
335 B<Note:> the default separator is C<!> not C<,> for historical
336 reasons - pass C<< sep_char => ',' >> for standard CSVs.
337 Requires L<Text::xSV::Slurp> for the slurp fast-path (loaded lazily).
338  
339 =item 6. C<Excel> (C<.xls>) and C<XLSX> (C<.xlsx>)
340  
341 Two separate Excel backends - one per file format:
342  
343 =over 4
344  
345 =item B<.xls> - old binary format, opened via L<DBD::Excel> (which uses
346 L<Spreadsheet::ParseExcel> internally). All queries go through DBI/SQL;
347 no in-memory slurp path. C<max_slurp_size> has no effect.
348  
349 =item B<.xlsx> - modern OOXML format, parsed directly via
350 L<Spreadsheet::ParseXLSX> and slurped into an in-memory hash (keyed mode)
351 or array (C<no_entry> mode). No DBI handle is created; all queries use
352 the in-memory fast-path. Complex criteria (operator hashes, C<-or>/C<-and>)
353 will fall through to the SQL path and croak - use simple scalar criteria.
354  
355 =back
356  
357 For both formats, each worksheet is a separate logical table; the active
358 worksheet is determined by the class-derived table name (or the C<table>
359 constructor parameter). Both modules are loaded lazily.
360  
361 =item 7. C<XML>
362  
363 File ending C<.xml>.
364 Requires L<XML::Simple> for the slurp fast-path (loaded lazily).
365  
366 =item 8. C<JSON>
367  
368 File ending C<.json>, slurped into memory via L<JSON::MaybeXS> (loaded
369 lazily).
370  
371 The file may contain either a JSON array of row objects:
372  
373 [
374 { "entry": "key1", "col": "val1" },
375 { "entry": "key2", "col": "val2" }
376 ]
377  
378 or a JSON object whose keys are the primary-key values:
379  
380 {
381 "key1": { "col": "val1" },
382 "key2": { "col": "val2" }
383 }
384  
385 In the object form, each key is injected into its row hash under the C<id>
386 column name (default C<entry>), so all normal lookups work identically to
387 the array form.
388  
389 A zero-byte or whitespace-only file is treated as empty - all query methods
390 return 0 / C<undef> / C<[]> without throwing.
391 Requires L<JSON::MaybeXS> (loaded lazily).
392  
393 =item 9. C<BerkeleyDB>
394  
395 Binary key-value file ending C<.db>.
396  
397 =item 10. C<HTML>
398  
399 HTML page fetched via a C<url>. Pass C<url => 'https://...'> instead of
400 C<directory>; the module fetches the page with L<LWP::UserAgent::Cached>, parses all
401 C<< <table> >> elements with L<HTML::TableExtract>, and slurps the first (or
402 C<html_table_index>-selected) table into memory. The first row of the table
403 is treated as column headers. Both modules are loaded lazily and are not
404 required for other backends.
405  
406 =back
407  
408 Pass C<dsn> to bypass file detection entirely and connect via any DBI driver.
409 Pass C<url> to fetch and slurp data from a remote source without a local
410 directory. When the URL returns C<Content-Type: application/json> or the URL
411 path ends in C<.json>, the response is parsed as JSON (see item 8 above).
412 Otherwise the response is parsed as an HTML page (item 10).
413  
414 Example - fetching CPAN Testers results:
415  
416 package Database::cpantesters;
417 use parent 'Database::Abstraction';
418  
419 my $db = Database::cpantesters->new(
420 url => 'https://www.cpantesters.org/show/Database-Abstraction.json',
421 no_entry => 1,
422 );
423 my $passes = $db->selectall_arrayref(grade => 'PASS');
424  
425 =head1 QUERY CRITERIA
426  
427 All select methods (C<selectall_arrayref>, C<selectall_array>,
428 C<fetchrow_hashref>, C<count>) accept the same criteria syntax.
429  
430 =head2 Plain value
431  
432 status => 'active' # status = 'active'
433 name => undef # name IS NULL
434  
435 Values containing C<%> or C<_> are matched with C<LIKE>:
436  
437 name => 'A%' # name LIKE 'A%'
438  
439 =head2 Comparison operator hashref
440  
441 score => { '>' => 90 } # score > 90
442 score => { '<' => 50 } # score < 50
443 score => { '>=' => 80 } # score >= 80
444 score => { '<=' => 100 } # score <= 100
445 score => { '!=' => 0 } # score != 0
446  
447 Multiple operators on one column are ANDed:
448  
449 score => { '>' => 60, '<' => 90 } # 60 < score < 90
450  
451 =head2 Pattern matching
452  
453 name => { -like => 'A%' } # name LIKE 'A%'
454 name => { -not_like => 'Z%' } # name NOT LIKE 'Z%'
455  
456 =head2 Set membership
457  
458 name => { -in => ['Alice', 'Bob'] } # name IN (...)
459 name => { -not_in => ['Alice', 'Bob'] } # name NOT IN (...)
460  
461 =head2 Range
462  
463 score => { -between => [60, 90] } # score BETWEEN 60 AND 90
464  
465 =head2 Logical groupings
466  
467 C<-or> and C<-and> take an arrayref of condition hashrefs:
468  
469 -or => [
470 { status => 'active' },
471 { score => { '>' => 95 } },
472 ]
473  
474 -and => [
475 { status => 'active' },
476 { score => { '>=' => 80 } },
477 ]
478  
479 =head2 Joins
480  
481 Any select method accepts a C<join> key with a hashref (or arrayref of
482 hashrefs) describing the join:
483  
484 join => {
485 table => 'dept',
486 on => 'employees.dept_id = dept.id', # raw SQL string
487 type => 'LEFT', # INNER (default) | LEFT | RIGHT | FULL | CROSS
488 }
489  
490 The C<on> condition can also be expressed in Perl-native forms that avoid
491 writing raw SQL:
492  
493 # Hashref: { left_col => right_col } — equality, SQL-injection-safe
494 join => { table => 'dept', on => { 'employees.dept_id' => 'dept.id' } }
495  
496 # Multi-column equality join (hash pairs AND-ed together)
497 join => { table => 'dept', on => { 'e.dept_id' => 'd.id', 'e.region' => 'd.region' } }
498  
499 # Arrayref 2-element: [ left_col, right_col ] — implies '='
500 join => { table => 'dept', on => [ 'employees.dept_id', 'dept.id' ] }
501  
502 # Arrayref 3-element: [ left_col, operator, right_col ]
503 # Valid operators: = != <> < > <= >=
504 join => { table => 'ranges', on => [ 'log.score', '>=', 'ranges.min_score' ] }
505  
506 # Multiple joins
507 join => [
508 { table => 'dept', on => { 'e.dept_id' => 'dept.id' } },
509 { table => 'country', on => { 'e.country_id' => 'country.id' } },
510 ]
511  
512 =head1 SUBROUTINES/METHODS
513  
514 =head2 init
515  
516 Set class-level defaults shared by all instances.
517  
518 Database::Abstraction::init(directory => '../data');
519  
520 Accepts the same parameters as L</new>. Returns a reference to the
521 current defaults hash, so you can read them back:
522  
523 my $defaults = Database::Abstraction::init();
524 print $defaults->{'directory'}, "\n";
525  
526 =cut
527  
528 # Subroutine to initialize with args
529 sub init
530 171 ▶{
Subroutine init: called CC=5 SCAR=16.1
Pod documented
531 171 ▶ if(my $params = Params::Get::get_params(undef, \@_)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $params = Params::Get::get_params(undef, \@_)) 167 4 171
532 167 ▶ if(($params->{'expires_in'} && !$params->{'cache_duration'})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$params{"expires_in"} and not $$params{"cache_duration"}) 3 164 167
Condition100%3/3
$$params{"expires_in"} and not $$params{"cache_duration"}
!ll&&!rl&&r
16313
MC/DC100%2/2
$$params{"expires_in"} and not $$params{"cache_duration"}
$$params{"expires_in"} not $$params{"cache_duration"}
Truth table100%3/3
A and not(B)
A= $$params{"expires_in"}B= not $$params{"cache_duration"}
ABresult
0X0
100
111
533 # Compatibility with CHI
534 3 $params->{'cache_duration'} = $params->{'expires_in'};
535 }
536  
537 167 %defaults = (%defaults, %{$params});
538 167 ▶ $defaults{'cache_duration'} ||= '1 hour';
Condition100%2/2
$Database::Abstraction::defaults{"cache_duration"} ||= "1 hour"
l!l
11750
MC/DC100%1/1
$Database::Abstraction::defaults{"cache_duration"} ||= "1 hour"
$Database::Abstraction::defaults{"cache_duration"}
Truth table100%2/2
A
A= $Database::Abstraction::defaults{"cache_duration"}
Aresult
11
00
539 }
540  
541 171 return \%defaults
542 }
543  
544 =head2 import
545  
546 The module can be initialised by the C<use> directive.
547  
548 use Database::Abstraction 'directory' => '/etc/data';
549  
550 or
551  
552 use Database::Abstraction { 'directory' => '/etc/data' };
553  
554 =cut
555  
556 sub import
557 152 ▶{
Subroutine import: called CC=7 SCAR=23.8
558 152 my $pkg = shift;
559  
560 152 ▶ if((scalar(@_) == 0) && (ref($pkg) eq 'HASH')) {
Branch: 4 branches
BranchTrueFalseTotal
if (scalar @_ == 0 and ref $pkg eq 'HASH') { } 0 152 152
elsif (scalar(@_) % 2 == 0) { } 149 3 152
elsif (scalar @_ == 1 and ref $_[0] eq 'HASH') { } 3 0 3
elsif (scalar @_ > 0) { } 0 0 0
Condition66%2/3
scalar @_ == 0 and ref $pkg eq "HASH"
!ll&&!rl&&r
61460
MC/DC0%0/2
scalar @_ == 0 and ref $pkg eq "HASH"
scalar @_ == 0 ref $pkg eq "HASH"
Truth table66%2/3
A and B
A= scalar @_ == 0B= ref $pkg eq "HASH"
ABresult
0X0
100
111
561 0 init(Object::Configure::configure(__PACKAGE__, $pkg));
562 } elsif((scalar(@_) % 2) == 0) {
563 149 my %h = @_;
564 149 init(Object::Configure::configure($pkg, \%h));
565 ▶ } elsif((scalar(@_) == 1) && (ref($_[0]) eq 'HASH')) {
Condition33%1/3
scalar @_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
003
MC/DC0%0/2
scalar @_ == 1 and ref $_[0] eq "HASH"
scalar @_ == 1 ref $_[0] eq "HASH"
Truth table33%1/3
A and B
A= scalar @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
566 3 init(Object::Configure::configure($pkg, $_[0]));
567 } elsif(scalar(@_) > 0) { # >= 3 would also work here
568 0 init(\@_);
569 }
570 }
571  
572 =head2 new
573  
574 Create an object pointing to a read-only database.
575  
576 Accepts arguments as a hash, a hashref, or - as a shortcut - a single bare
577 string which is taken to be C<directory>.
578  
579 =head3 Connection parameters
580  
581 =over 4
582  
583 =item * C<directory>
584  
585 Directory containing the data files. The module probes this directory for
586 files named after the subclass (see L</FILE FORMATS>). Required unless
587 C<dsn> is given.
588  
589 =item * C<dsn>
590  
591 A DBI data-source string (e.g. C<dbi:SQLite:dbname=/path/to/db>,
592 C<dbi:Pg:dbname=mydb;host=db.example.com>, or
593 C<dbi:MariaDB:database=mydb;host=db.example.com>). When present, file
594 detection is skipped entirely and the DSN is used directly. The SQL
595 dialect is inferred from the DSN prefix (C<sqlite>, C<postgres>,
596 C<mysql> — C<dbi:MariaDB:> maps to the C<mysql> dialect).
597  
598 =item * C<username>
599  
600 Database username. Used only with C<dsn>; ignored for file-based backends.
601  
602 =item * C<password>
603  
604 Database password. Used only with C<dsn>; ignored for file-based backends.
605  
606 =item * C<dbname>
607  
608 Override the filename stem searched in C<directory> (default: the table
609 name derived from the class name).
610  
611 =item * C<table>
612  
613 Override the table (or worksheet) name used in SQL queries for this object.
614 Default is the class-name-derived table name (e.g. C<Database::Foo> =>
615 C<foo>). Particularly useful for Excel workbooks where a single F<.xlsx>
616 file contains multiple worksheets: pass C<< table => 'Summary' >> to query
617 the C<Summary> worksheet without creating a dedicated subclass. Also works
618 with SQLite/DSN connections to select a table other than the class-derived
619 default. The filename stem (C<dbname>) continues to fall back to the class
620 name, so the correct file is opened regardless of this override. The value
621 is validated against C<$SAFE_QUALIFIED> at construction time.
622  
623 =item * C<filename>
624  
625 Override the full filename (relative to C<directory>). Takes precedence
626 over C<dbname>.
627  
628 =item * C<host>
629  
630 Remote hostname (or C<user@host>) from which to fetch the data file(s) via
631 SSH/SCP. When present, each candidate filename is fetched with
632 L<File::Slurp::Remote> into a local temporary directory; the existing
633 extension-based file-type detection then runs against that directory.
634 C<directory> is treated as the remote path (no local canonicalization is
635 applied). Using C<filename> together with C<host> avoids probing multiple
636 extensions and is therefore more efficient. L<File::Slurp::Remote> must be
637 installed; it is loaded lazily (only when C<host> is given).
638  
639 =item * C<url>
640  
641 A URL (C<http://> or C<https://>) pointing to an HTML page that contains one
642 or more C<< <table> >> elements. When present, C<directory> is not required.
643 The first row of the selected table is used as column headers.
644 Requires L<LWP::UserAgent::Cached> and L<HTML::TableExtract> (both loaded lazily).
645  
646 =item * C<database>
647  
648 A Redis connection URL in the form C<redis://[password@]host[:port][/db_index]>.
649 When present, C<directory>, C<dsn>, and C<url> are not required. Rows are
650 expected to be stored as Redis Hashes at keys of the form
651 C<tablename:entry_value>; fields of each Hash become column values. The
652 module slurps all matching keys via C<KEYS tablename:*> + C<HGETALL> into the
653 same in-memory structure used by the CSV and DBM::Deep backends, so all
654 existing fast-paths (C<selectall_arrayref>, C<selectall_array>,
655 C<fetchrow_hashref>, C<count>, C<columns>, C<schema>, AUTOLOAD) work without
656 modification. C<no_entry> mode is supported.
657  
658 L<Redis::Fast> is tried first (XS, faster); if unavailable, L<Redis>
659 (pure-Perl) is used as a fallback. Both are loaded lazily - neither is
660 required when using file-based or DSN-based backends. The URL scheme is
661 validated at construction time (C<redis://> only; all other schemes croak).
662  
663 Use L</select> to switch the active Redis database on an already-open
664 connection.
665  
666 =back
667  
668 =head3 Behaviour parameters
669  
670 =over 4
671  
672 =item * C<no_entry>
673  
674 Set to C<1> when the table has no key column (standard CSVs, for example).
675 Default is C<0> (keyed on C<entry>).
676  
677 =item * C<id>
678  
679 Name of the key column. Default is C<entry>.
680  
681 =item * C<sep_char>
682  
683 Field separator for CSV/PSV files.
684 Default is C<!> - pass C<< sep_char => ',' >>
685 for standard comma-separated files.
686  
687 A quote inside a quoted field may be written as two quotes
688 (C<"a ""b"" c">, as RFC 4180 and spreadsheets write it) or with a backslash
689 (C<"a \"b\" c">). Each file is read with the one it uses: a backslash when
690 the file holds a backslash before a quote anywhere, otherwise the quote.
691  
692 =item * C<max_slurp_size>
693  
694 Files smaller than this (in bytes) are loaded entirely into memory for fast
695 lookups. Default is 16 KB. Set to C<0> to force SQL mode for all sizes.
696  
697 =item * C<no_fixate>
698  
699 Set to C<1> to return mutable arrays. Default is C<0> (arrays are made
700 read-only via L<Data::Reuse>).
701  
702 =item * C<auto_load>
703  
704 Set to C<0> to disable the AUTOLOAD column shortcut. Default is C<1>
705 (enabled).
706  
707 =item * C<html_table_index>
708  
709 Zero-based index of the HTML C<< <table> >> to extract when the C<url>
710 backend is used. Default is C<0> (the first table on the page).
711  
712 =item * C<infer_types>
713  
714 Set to C<1> to enable heuristic type inference in C<schema()> for
715 slurp-backed sources (CSV, JSON, XLSX, XML, HTML URL, DBM::Deep).
716 Default is C<0> (off; all columns reported as C<TEXT> for backward
717 compatibility).
718  
719 When enabled, C<schema()> scans the first 100 rows and promotes column
720 types: all-integer values => C<INTEGER>; all-floating-point values =>
721 C<REAL>; all ISO-8601 timestamps => C<TIMESTAMP>; all ISO-8601 dates =>
722 C<DATE>; otherwise C<TEXT>. C<NULL> (C<undef> or empty string) values
723 are skipped during the scan.
724  
725 =item * C<base_criteria>
726  
727 A hashref of column-value pairs that is ANDed into B<every> SELECT
728 automatically. Callers do not need to repeat these criteria on each
729 call. Common use cases:
730  
731 =over 4
732  
733 =item * Row-level security: C<< base_criteria => { tenant_id => $tid } >>
734  
735 =item * Soft-delete filtering: C<< base_criteria => { deleted_at => undef } >>
736  
737 =item * Status gates: C<< base_criteria => { active => 1 } >>
738  
739 =back
740  
741 The hashref is shallow-copied at construction time so later mutations to
742 the original do not affect the object. Column names are validated
743 against the same identifier rules as the C<id> parameter. C<-or> and
744 C<-and> groupings are allowed as keys.
745  
746 B<SQL path>: the criteria are merged into the C<WHERE> clause before
747 the caller-supplied criteria (caller values win on key collision).
748  
749 B<Slurp/in-memory path>: the criteria are applied as an additional
750 filter. The C<fetchrow_hashref> entry-key fast path checks
751 C<base_criteria> against the returned row before returning it.
752  
753 B<Query builder>: C<base_criteria> are merged into the C<WHERE> clause
754 generated by C<_build_sql>, so C<< $db->query->where(...)->all() >>
755 also respects them.
756  
757 =back
758  
759 =head3 Caching and logging
760  
761 =over 4
762  
763 =item * C<cache>
764  
765 A L<CHI>-compatible cache object. When set, query results are stored and
766 retrieved from the cache.
767  
768 =item * C<cache_duration> / C<expires_in>
769  
770 TTL for cached results. Default is C<'1 hour'>. C<expires_in> is a
771 synonym for compatibility with L<CHI>.
772  
773 =item * C<logger>
774  
775 An object that understands C<warn()> and C<trace()> (e.g.
776 L<Log::Log4perl>, L<Log::Any>), a code reference, or a filename.
777  
778 =item * C<config_file>
779  
780 Path to a YAML, XML, or INI configuration file whose keys are merged into
781 the constructor arguments. Loaded via L<Object::Configure>.
782  
783 =back
784  
785 =head3 Notes
786  
787 =over 4
788  
789 =item *
790  
791 If no arguments are set, class-level defaults set via C<init()> or C<use>
792 are used.
793  
794 =item *
795  
796 Slurp mode assumes the key column (C<entry>) is unique. If it is not,
797 searches will be incomplete - disable slurp mode by setting
798 C<< max_slurp_size => 0 >>.
799  
800 =item *
801  
802 Passing an existing object as C<$class> clones it, merging any new
803 arguments.
804  
805 =back
806  
807 =cut
808  
809 761 ▶sub new {
Subroutine new: called CC=46 SCAR=39.5
Pod documented
810 761 my $class = shift;
811 761 my %args;
812  
813 761 Class::Abstract::check_abstract($class); # enforces abstract contract
814  
815 # Handle hash or hashref arguments
816 755 ▶ if((scalar(@_) == 1) && !ref($_[0])) {
Branch: 2 branches
BranchTrueFalseTotal
if (scalar @_ == 1 and not ref $_[0]) { } 127 628 755
elsif (my $params = Params::Get::get_params(undef, @_)) { } 620 8 628
Condition100%3/3
scalar @_ == 1 and not ref $_[0]
!ll&&!rl&&r
56365127
MC/DC100%2/2
scalar @_ == 1 and not ref $_[0]
scalar @_ == 1 not ref $_[0]
Truth table100%3/3
A and not(B)
A= scalar @_ == 1B= not ref $_[0]
ABresult
0X0
100
111
817 127 $args{'directory'} = $_[0];
818 } elsif(my $params = Params::Get::get_params(undef, @_)) {
819 620 %args = %{$params};
820 }
821  
822 755 ▶ if(!defined($class)) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $class) { } 0 755 755
elsif ($class eq __PACKAGE__) { } 0 755 755
elsif (builtin::blessed($class)) { } 13 742 755
823 0 ▶ if((scalar keys %args) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %args > 0) 0 0 0
824 # Using Database::Abstraction->new(), not Database::Abstraction::new()
825 0 carp(__PACKAGE__, ' use ->new() not ::new() to instantiate');
826 0 return;
827 }
828 # FIXME: this only works when no arguments are given
829 0 $class = __PACKAGE__;
830 } elsif($class eq __PACKAGE__) {
831 0 croak("$class: abstract class");
832 } elsif(Scalar::Util::blessed($class)) {
833 # If $class is an object, clone it with new arguments.
834 # Validate 'id' and 'table' before merging — the validation block below is
835 # skipped by this early return, so hostile clone args would otherwise bypass
836 # all guards and be interpolated directly into SQL.
837 13 ▶ if(defined $args{'id'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"id"}) 5 8 13
838 croak(ref($class), ": unsafe id column name '$args{id}'")
839 5 ▶ unless $args{'id'} =~ $SAFE_IDENTIFIER;
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"id"} =~ /$SAFE_IDENTIFIER/ 4 1 5
840 }
841 9 ▶ if(defined $args{'table'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"table"}) 3 6 9
842 croak(ref($class), ": unsafe table name '$args{table}'")
843 3 ▶ unless $args{'table'} =~ $SAFE_QUALIFIED;
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"table"} =~ /$SAFE_QUALIFIED/ 3 0 3
844 }
845 6 return bless { %{$class}, %args }, ref($class);
846 }
847  
848 # Load the configuration from a config file, if provided
849 742 %args = %{Object::Configure::configure($class, \%args)};
850  
851 # Normalise logger: wrap code-refs, filenames, and strings in Log::Abstraction
852 # so that the rest of the code can always call ->$level(...) uniformly.
853 742 ▶ if(defined $args{'logger'} && !Scalar::Util::blessed($args{'logger'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"logger"} and not builtin::blessed($args{"logger"})) 0 742 742
Condition33%1/3
defined $args{"logger"} and not builtin::blessed($args{"logger"})
!ll&&!rl&&r
07420
MC/DC0%0/2
defined $args{"logger"} and not builtin::blessed($args{"logger"})
defined $args{"logger"} not builtin::blessed($args{"logger"})
Truth table33%1/3
A and not(B)
A= defined $args{"logger"}B= not builtin::blessed($args{"logger"})
ABresult
0X0
100
111
854 0 $args{'logger'} = Log::Abstraction->new($args{'logger'});
855 }
856  
857 742 ▶ unless($args{'dsn'} || $defaults{'dsn'} || $args{'url'} || $defaults{'url'} || $args{'database'} || $defaults{'database'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"dsn"} or $Database::Abstraction::defaults{"dsn"} or $args{"url"} or $Database::Abstraction::defaults{"url"} or $args{"database"} or $Database::Abstraction::defaults{"database"}) 637 105 742
Condition80%12/15
$args{"dsn"} or $Database::Abstraction::defaults{"dsn"} or $args{"url"} or $Database::Abstraction::defaults{"url"} or $args{"database"} or $Database::Abstraction::defaults{"database"}
l!l&&r!l&&!r
1050637
$args{"dsn"} or $Database::Abstraction::defaults{"dsn"} or $args{"url"} or $Database::Abstraction::defaults{"url"} or $args{"database"}
l!l&&r!l&&!r
969637
$args{"dsn"} or $Database::Abstraction::defaults{"dsn"} or $args{"url"} or $Database::Abstraction::defaults{"url"}
l!l&&r!l&&!r
960646
$args{"dsn"} or $Database::Abstraction::defaults{"dsn"} or $args{"url"}
l!l&&r!l&&!r
5838646
$args{"dsn"} or $Database::Abstraction::defaults{"dsn"}
l!l&&r!l&&!r
580684
MC/DC50%3/6
$args{"dsn"} or $Database::Abstraction::defaults{"dsn"} or $args{"url"} or $Database::Abstraction::defaults{"url"} or $args{"database"} or $Database::Abstraction::defaults{"database"}
$args{"dsn"} $Database::Abstraction::defaults{"dsn"} $args{"url"} $Database::Abstraction::defaults{"url"} $args{"database"} $Database::Abstraction::defaults{"database"}
Truth table57%4/7
A or B or C or D or E or F
A= $args{"dsn"}B= $Database::Abstraction::defaults{"dsn"}C= $args{"url"}D= $Database::Abstraction::defaults{"url"}E= $args{"database"}F= $Database::Abstraction::defaults{"database"}
ABCDEFresult
1XXXXX1
01XXXX1
001XXX1
0001XX1
00001X1
0000011
0000000
858 637 ▶ croak("$class: where are the files?") unless($args{'directory'} || $defaults{'directory'});
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"directory"} or $Database::Abstraction::defaults{"directory"} 5 632 637
Condition100%3/3
$args{"directory"} or $Database::Abstraction::defaults{"directory"}
l!l&&r!l&&!r
62845
MC/DC100%2/2
$args{"directory"} or $Database::Abstraction::defaults{"directory"}
$args{"directory"} $Database::Abstraction::defaults{"directory"}
Truth table100%3/3
A or B
A= $args{"directory"}B= $Database::Abstraction::defaults{"directory"}
ABresult
1X1
011
000
859  
860 # Skip the local -d check only for genuinely remote hosts.
861 # localhost / 127.0.0.1 / current hostname are treated as local.
862 632 ▶ my $given_host = $args{'host'} // $defaults{'host'};
Condition66%2/3
$args{"host"} // $Database::Abstraction::defaults{"host"}
l!l&&r!l&&!r
400592
MC/DC50%1/2
$args{"host"} // $Database::Abstraction::defaults{"host"}
$args{"host"} $Database::Abstraction::defaults{"host"}
Truth table66%2/3
A // B
A= $args{"host"}B= $Database::Abstraction::defaults{"host"}
ABresult
1X1
011
000
863 632 ▶ unless($given_host && !$class->_is_local_host($given_host)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($given_host and not $class->_is_local_host($given_host)) 602 30 632
Condition100%3/3
$given_host and not $class->_is_local_host($given_host)
!ll&&!rl&&r
593930
MC/DC100%2/2
$given_host and not $class->_is_local_host($given_host)
$given_host not $class->_is_local_host($given_host)
Truth table100%3/3
A and not(B)
A= $given_hostB= not $class->_is_local_host($given_host)
ABresult
0X0
100
111
864 602 ▶ croak("$class: ", $args{'directory'} || $defaults{'directory'}, ' is not a directory') unless(-d ($args{'directory'} || $defaults{'directory'}));
Branch: 1 branch
BranchTrueFalseTotal
unless -d ($args{"directory"} || $Database::Abstraction::defaults{"directory"}) 9 593 602
Condition50%3/6
$args{'directory'} || $Database::Abstraction::defaults{'directory'}
l!l&&r!l&&!r
59840
$args{'directory'} || $Database::Abstraction::defaults{'directory'}
l!l&&r!l&&!r
900
MC/DC0%0/2
$args{'directory'} || $Database::Abstraction::defaults{'directory'}
$args{'directory'} $Database::Abstraction::defaults{'directory'}
MC/DC0%0/2
$args{'directory'} || $Database::Abstraction::defaults{'directory'}
$args{'directory'} $Database::Abstraction::defaults{'directory'}
Truth table66%2/3
A || B
A= $args{'directory'}B= $Database::Abstraction::defaults{'directory'}
ABresult
1X1
011
000
Truth table33%1/3
A || B
A= $args{'directory'}B= $Database::Abstraction::defaults{'directory'}
ABresult
1X1
011
000
865 }
866 }
867  
868 # Validate the primary-key column name to prevent SQL injection via ORDER BY / WHERE
869 728 for my $src (\%defaults, \%args) {
870 1456 ▶ if(defined $src->{'id'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"id"}) 65 1391 1456
871 croak("$class: unsafe id column name '$src->{id}'")
872 65 ▶ unless $src->{'id'} =~ $SAFE_IDENTIFIER;
Branch: 1 branch
BranchTrueFalseTotal
unless $$src{"id"} =~ /$SAFE_IDENTIFIER/ 27 38 65
873 }
874 1429 ▶ if(defined $src->{'host'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"host"}) 40 1389 1429
875 croak("$class: unsafe host '$src->{host}'")
876 40 ▶ unless $src->{'host'} =~ /\A
Branch: 1 branch
BranchTrueFalseTotal
unless $$src{"host"} =~ /\A (?: # optional "user\@" prefix [a-zA-Z0-9] # username: first char must be alnum [a-zA-Z0-9._-]* # username: rest may include dots and hyphens \@ # literal at-sign; \@ prevents array interpolation )? [a-zA-Z0-9:] # first char of host or IP; colon allows IPv6 [a-zA-Z0-9._:-]* # rest: hostname, dotted IPv4, or IPv6 hex groups \z/x 23 17 40
877 (?: # optional "user\@" prefix
878 [a-zA-Z0-9] # username: first char must be alnum
879 [a-zA-Z0-9._-]* # username: rest may include dots and hyphens
880 \@ # literal at-sign; \@ prevents array interpolation
881 )?
882 [a-zA-Z0-9:] # first char of host or IP; colon allows IPv6
883 [a-zA-Z0-9._:-]* # rest: hostname, dotted IPv4, or IPv6 hex groups
884 \z/x;
885 }
886 1406 ▶ if(defined $src->{'url'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"url"}) 39 1367 1406
887 croak("$class: unsafe url '$src->{url}'")
888 39 ▶ unless $src->{'url'} =~ m{\Ahttps?://}i;
Branch: 1 branch
BranchTrueFalseTotal
unless $$src{"url"} =~ m[\Ahttps?://]i 16 23 39
889 }
890 1390 ▶ if(defined $src->{'database'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"database"}) 9 1381 1390
891 croak("$class: unsafe database '$src->{database}'")
892 9 ▶ unless $src->{'database'} =~ m{\Aredis://}i;
Branch: 1 branch
BranchTrueFalseTotal
unless $$src{"database"} =~ m[\Aredis://]i 4 5 9
893 }
894 1386 ▶ if(defined $src->{'table'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"table"}) 35 1351 1386
895 croak("$class: unsafe table name '$src->{table}'")
896 35 ▶ unless $src->{'table'} =~ $SAFE_QUALIFIED;
Branch: 1 branch
BranchTrueFalseTotal
unless $$src{"table"} =~ /$SAFE_QUALIFIED/ 25 10 35
897 }
898 # redis_key: the literal Redis key name used for lookups. It is
899 # intentionally NOT validated as a SQL identifier — Redis key names
900 # may contain colons, hyphens and other non-SQL characters. Only
901 # accepted when a database (redis://) URL is also present so it
902 # cannot be injected into non-Redis SQL paths.
903 1361 ▶ if(defined $src->{'redis_key'} && !defined $src->{'database'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"redis_key"} and not defined $$src{"database"}) 1 1360 1361
Condition100%3/3
defined $$src{"redis_key"} and not defined $$src{"database"}
!ll&&!rl&&r
135911
MC/DC100%2/2
defined $$src{"redis_key"} and not defined $$src{"database"}
defined $$src{"redis_key"} not defined $$src{"database"}
Truth table100%3/3
A and not(B)
A= defined $$src{"redis_key"}B= not defined $$src{"database"}
ABresult
0X0
100
111
904 1 croak("$class: redis_key is only valid with a redis:// database URL");
905 }
906 1360 ▶ if(defined $src->{'base_criteria'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"base_criteria"}) 55 1305 1360
907 55 my $bc = $src->{'base_criteria'};
908 55 ▶ croak("$class: base_criteria must be a hashref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $bc eq "HASH" 11 44 55
909 unless ref($bc) eq 'HASH';
910 44 for my $k (keys %{$bc}) {
911 41 ▶ next if $k =~ /\A-/; # allow -or/-and groupings
Branch: 1 branch
BranchTrueFalseTotal
if $k =~ /\A-/ 5 36 41
912 36 ▶ croak("$class: unsafe base_criteria key '$k'")
Branch: 1 branch
BranchTrueFalseTotal
unless $k =~ /$SAFE_QUALIFIED/ 16 20 36
913 unless $k =~ $SAFE_QUALIFIED;
914 }
915 28 $src->{'base_criteria'} = { %{$bc} }; # shallow copy for safety
916 }
917 }
918  
919 # Defaults are set first so that %args keys override them
920 605 return bless {
921 no_entry => 0,
922 no_fixate => 0,
923 id => 'entry',
924 cache_duration => '1 hour',
925 max_slurp_size => DEFAULT_MAX_SLURP_SIZE,
926 %defaults,
927 %args,
928 }, $class;
929 }
930  
931 =head2 set_logger
932  
933 Sets the class, code reference, or file that will be used for logging.
934  
935 =cut
936  
937 sub set_logger
938 15 ▶{
Subroutine set_logger: called CC=3 SCAR=11.0
Pod documented
939 15 my $self = shift;
940 15 my $params = Params::Get::get_params('logger', @_);
941  
942 12 ▶ if(my $logger = $params->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $$params{"logger"}) 11 1 12
943 11 ▶ if(Scalar::Util::blessed($logger)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($logger)) { } 4 7 11
944 4 $self->{'logger'} = $logger;
945 } else {
946 7 $self->{'logger'} = Log::Abstraction->new($logger);
947 }
948 11 return $self;
949 }
950 1 Carp::croak('Usage: set_logger(logger => $logger)')
951 }
952  
953 =head2 select
954  
955 Select a Redis database by number (0-15). Clears the in-memory data cache so
956 the next query re-slurps from the newly selected database. Returns C<$self>
957 for chaining. Croaks if the object is not backed by a Redis connection.
958  
959 $db->select(3); # switch to Redis DB 3
960 my $count = $db->count; # queries the new DB
961  
962 =cut
963  
964 sub select
965 0 ▶{
Subroutine select: not called CC=4 SCAR=30.0
Pod documented
966 0 my $self = shift;
967 0 my $db_num = Params::Get::get_params('database', \@_)->{'database'};
968  
969 0 ▶ Carp::croak(ref($self), ': select: db number must be a non-negative integer')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $db_num and $db_num =~ /\A\d+\z/ 0 0 0
Condition0%0/3
defined $db_num and $db_num =~ /\A\d+\z/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $db_num and $db_num =~ /\A\d+\z/
defined $db_num $db_num =~ /\A\d+\z/
Truth table0%0/3
A and B
A= defined $db_numB= $db_num =~ /\A\d+\z/
ABresult
0X0
100
111
970 unless defined($db_num) && $db_num =~ /\A\d+\z/;
971  
972 0 $self->_open_table({});
973 Carp::croak(ref($self), ': select: not a Redis connection')
974 0 ▶ unless $self->{'_redis'};
Branch: 1 branch
BranchTrueFalseTotal
unless $$self{"_redis"} 0 0 0
975  
976 0 $self->{'_redis'}->select(int($db_num));
977  
978 # Clear cached data so next query re-slurps from the new database
979 0 delete $self->{'data'};
980 0 delete $self->{'_columns'};
981 0 delete $self->{'_schema'};
982  
983 0 return $self;
984 }
985  
986 # Open the database connection based on the specified type (e.g., SQLite, CSV).
987 # Read the data into memory or establish a connection to the database file.
988 # column_names allows the column names to be overridden on CSV files
989  
990 459 ▶sub _open :Protected
Subroutine _open: called CC=189 SCAR=76.4
991 {
992 # Enforce that _open is only reachable from within this class hierarchy;
993 # caller() returns the calling package name as a plain string.
994 459 ▶ do { my $c = (caller)[0]; Carp::croak('Illegal Operation: _open may only be called within ', __PACKAGE__) unless $c && $c->isa(__PACKAGE__) };
Branch: 1 branch
BranchTrueFalseTotal
unless $c and $c->isa(__PACKAGE__) 1 458 459
Condition66%2/3
$c and $c->isa(__PACKAGE__)
!ll&&!rl&&r
01458
MC/DC50%1/2
$c and $c->isa(__PACKAGE__)
$c $c->isa(__PACKAGE__)
Truth table66%2/3
A and B
A= $cB= $c->isa(__PACKAGE__)
ABresult
0X0
100
111
995  
996 458 my $self = shift;
997 458 my $params = Params::Get::get_params(undef, \@_);
998  
999 458 ▶ $params->{'sep_char'} ||= $self->{'sep_char'} ? $self->{'sep_char'} : '!';
Branch: 1 branch
BranchTrueFalseTotal
$$self{'sep_char'} ? : 47 410 457
Condition66%2/3
$$params{"sep_char"} ||= $$self{"sep_char"} ? $$self{"sep_char"} : "!"
l!l&&r!l&&!r
14570
MC/DC0%0/2
$$params{"sep_char"} ||= $$self{"sep_char"} ? $$self{"sep_char"} : "!"
$$params{"sep_char"} $$self{"sep_char"} ? $$self{"sep_char"} : "!"
Truth table66%2/3
A ||= B
A= $$params{"sep_char"}B= $$self{"sep_char"} ? $$self{"sep_char"} : "!"
ABresult
1X1
011
000
1000 458 ▶ my $max_slurp_size = $params->{'max_slurp_size'} || $self->{'max_slurp_size'};
Condition66%2/3
$$params{'max_slurp_size'} || $$self{'max_slurp_size'}
l!l&&r!l&&!r
042929
MC/DC50%1/2
$$params{'max_slurp_size'} || $$self{'max_slurp_size'}
$$params{'max_slurp_size'} $$self{'max_slurp_size'}
Truth table66%2/3
A || B
A= $$params{'max_slurp_size'}B= $$self{'max_slurp_size'}
ABresult
1X1
011
000
1001  
1002 458 ▶ my $table = $self->{'table'} || ref($self);
Condition33%1/3
$$self{'table'} || ref $self
l!l&&r!l&&!r
04580
MC/DC0%0/2
$$self{'table'} || ref $self
$$self{'table'} ref $self
Truth table33%1/3
A || B
A= $$self{'table'}B= ref $self
ABresult
1X1
011
000
1003 458 $table =~ s/\A.*:://;
1004  
1005 458 $self->_trace(ref($self), ": _open $table");
1006  
1007 458 ▶ return if($self->{'_dbh'}{$table});
Branch: 1 branch
BranchTrueFalseTotal
if $$self{"_dbh"}{$table} 1 457 458
1008  
1009 # Read in the database
1010 457 my $dbh;
1011  
1012 # DSN-based connection bypasses file detection entirely
1013 457 ▶ if(my $dsn = $self->{'dsn'} || $defaults{'dsn'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $dsn = $$self{"dsn"} || $Database::Abstraction::defaults{"dsn"}) 54 403 457
Condition66%2/3
$$self{'dsn'} || $Database::Abstraction::defaults{'dsn'}
l!l&&r!l&&!r
540403
MC/DC50%1/2
$$self{'dsn'} || $Database::Abstraction::defaults{'dsn'}
$$self{'dsn'} $Database::Abstraction::defaults{'dsn'}
Truth table66%2/3
A || B
A= $$self{'dsn'}B= $Database::Abstraction::defaults{'dsn'}
ABresult
1X1
011
000
1014 54 my $dialect = 'generic';
1015 54 ▶ if ($dsn =~ /\Adbi:SQLite:/i) { $dialect = 'sqlite' }
Branch: 4 branches
BranchTrueFalseTotal
if ($dsn =~ /\Adbi:SQLite:/i) { } 53 1 54
elsif ($dsn =~ /\Adbi:Pg:/i) { } 0 1 1
elsif ($dsn =~ /\Adbi:mysql:/i) { } 0 1 1
elsif ($dsn =~ /\Adbi:MariaDB:/i) { } 0 1 1
1016 0 elsif ($dsn =~ /\Adbi:Pg:/i) { $dialect = 'postgres' }
1017 0 elsif ($dsn =~ /\Adbi:mysql:/i) { $dialect = 'mysql' }
1018 0 elsif ($dsn =~ /\Adbi:MariaDB:/i) { $dialect = 'mysql' }
1019 54 $self->{'_dialect'} = $dialect;
1020  
1021 $dbh = DBI->connect(
1022 $dsn,
1023 $self->{'username'},
1024 54 ▶ $self->{'password'},
Branch: 1 branch
BranchTrueFalseTotal
$dbh = "DBI"->connect($dsn, $$self{"username"}, $$self{"password"}, {"RaiseError", 1, "AutoCommit", 1}) or Carp::croak(ref $self, ": cannot connect: $DBI::errstr") 53 0 53
1025 { RaiseError => 1, AutoCommit => 1 },
1026 ) or Carp::croak(ref($self), ": cannot connect: $DBI::errstr");
1027  
1028 53 ▶ if($dialect eq 'sqlite') {
Branch: 1 branch
BranchTrueFalseTotal
if ($dialect eq "sqlite") 53 0 53
1029 53 $dbh->do('PRAGMA synchronous = OFF');
1030 52 $dbh->do('PRAGMA cache_size = -4096');
1031 52 $dbh->do('PRAGMA journal_mode = OFF');
1032 52 $dbh->do('PRAGMA temp_store = MEMORY');
1033 52 $dbh->do('PRAGMA mmap_size = 1048576');
1034 52 $dbh->sqlite_busy_timeout(100000);
1035 }
1036  
1037 52 $self->{'type'} = 'DBI';
1038 52 $self->{'_dbh'}{$table} = $dbh;
1039 52 $self->{'_updated'} = time();
1040 52 return $self;
1041 }
1042  
1043 # Redis backend — connects to a Redis server and slurps hash keys matching
1044 # "tablename:*" into memory, mirroring the DBM::Deep slurp structure.
1045 # Lazily loads Redis::Fast (preferred) or Redis.
1046 403 ▶ if(my $db_url = $self->{'database'} || $defaults{'database'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $db_url = $$self{"database"} || $Database::Abstraction::defaults{"database"}) 1 402 403
Condition66%2/3
$$self{'database'} || $Database::Abstraction::defaults{'database'}
l!l&&r!l&&!r
10402
MC/DC50%1/2
$$self{'database'} || $Database::Abstraction::defaults{'database'}
$$self{'database'} $Database::Abstraction::defaults{'database'}
Truth table66%2/3
A || B
A= $$self{'database'}B= $Database::Abstraction::defaults{'database'}
ABresult
1X1
011
000
1047 # Parse redis://[userinfo@]host[:port][/db_index]
1048 1 my ($userinfo, $host, $port, $db_idx) =
1049 $db_url =~ m{\Aredis://(?:([^@]*)@)?([^/:]*)?(?::(\d+))?(?:/(\d+))?\z}i;
1050 1 ▶ $host //= 'localhost';
Condition50%1/2
$host //= "localhost"
l!l
10
MC/DC0%0/1
$host //= "localhost"
$host
Truth table50%1/2
A
A= $host
Aresult
11
00
1051 1 ▶ $port //= 6379;
Condition50%1/2
$port //= 6379
l!l
01
MC/DC0%0/1
$port //= 6379
$port
Truth table50%1/2
A
A= $port
Aresult
11
00
1052 1 ▶ $db_idx //= 0;
Condition50%1/2
$db_idx //= 0
l!l
10
MC/DC0%0/1
$db_idx //= 0
$db_idx
Truth table50%1/2
A
A= $db_idx
Aresult
11
00
1053 1 my $password;
1054 1 ▶ if(defined $userinfo) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $userinfo) 0 1 1
1055 0 ▶ $password = ($userinfo =~ /:(.*)/) ? $1 : (length($userinfo) ? $userinfo : undef);
Branch: 2 branches
BranchTrueFalseTotal
$userinfo =~ /:(.*)/ ? : 0 0 0
length $userinfo ? : 0 0 0
1056 }
1057  
1058 1 ▶ unless($self->{'_redis'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($$self{"_redis"}) 1 0 1
1059 1 my $redis_class;
1060 0 eval { require Redis::Fast; $redis_class = 'Redis::Fast' };
1061 1 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 0 1
1062 1 require Redis;
1063 0 $redis_class = 'Redis';
1064 }
1065 0 $self->{'_redis'} = $redis_class->new(server => "$host:$port", reconnect => 2, every => 100);
1066 0 ▶ $self->{'_redis'}->auth($password) if defined $password && length $password;
Branch: 1 branch
BranchTrueFalseTotal
if defined $password and length $password 0 0 0
Condition0%0/3
defined $password and length $password
!ll&&!rl&&r
000
MC/DC0%0/2
defined $password and length $password
defined $password length $password
Truth table0%0/3
A and B
A= defined $passwordB= length $password
ABresult
0X0
100
111
1067 }
1068 0 ▶ $self->{'_redis'}->select($db_idx) if $db_idx;
Branch: 1 branch
BranchTrueFalseTotal
if $db_idx 0 0 0
1069  
1070 0 my $id = $self->{'id'};
1071 # redis_key overrides table for the actual Redis key lookup so that
1072 # callers can pass an arbitrary key name (colons, hyphens, etc.) without
1073 # it needing to pass the SQL-identifier check on the table parameter.
1074 0 ▶ my $redis_key = $self->{'redis_key'} // $table;
Condition0%0/3
$$self{"redis_key"} // $table
l!l&&r!l&&!r
000
MC/DC0%0/2
$$self{"redis_key"} // $table
$$self{"redis_key"} $table
Truth table0%0/3
A // B
A= $$self{"redis_key"}B= $table
ABresult
1X1
011
000
1075 0 my @keys = $self->{'_redis'}->keys("${redis_key}:*");
1076  
1077 0 ▶ if($self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 0 0 0
1078 0 my @data;
1079 0 for my $key (@keys) {
1080 0 my %fields = $self->{'_redis'}->hgetall($key);
1081 0 ▶ push @data, \%fields if %fields;
Branch: 1 branch
BranchTrueFalseTotal
if %fields 0 0 0
1082 }
1083 0 ▶ $self->{'data'} = @data ? \@data : undef;
Branch: 1 branch
BranchTrueFalseTotal
@data ? : 0 0 0
1084 } else {
1085 0 my %data;
1086 0 for my $key (@keys) {
1087 0 (my $entry = $key) =~ s/\A\Q${redis_key}\E://;
1088 0 my %fields = $self->{'_redis'}->hgetall($key);
1089 0 ▶ $data{$entry} = { $id => $entry, %fields } if %fields;
Branch: 1 branch
BranchTrueFalseTotal
if %fields 0 0 0
1090 }
1091 0 ▶ $self->{'data'} = %data ? \%data : undef;
Branch: 1 branch
BranchTrueFalseTotal
%data ? : 0 0 0
1092 }
1093  
1094 # Fallback: if no compound "keyname:entry" sub-keys were found, try
1095 # the key itself as a standalone value. This supports any Redis data
1096 # structure (hash, list, set, sorted set, string) stored under a plain
1097 # key rather than the keyname:entry compound-key convention.
1098 0 ▶ unless(@keys) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@keys) 0 0 0
1099 0 my $key_type = lc($self->{'_redis'}->type($redis_key));
1100 0 ▶ if($key_type eq 'hash') {
Branch: 5 branches
BranchTrueFalseTotal
if ($key_type eq 'hash') { } 0 0 0
elsif ($key_type eq 'list') { } 0 0 0
elsif ($key_type eq 'set') { } 0 0 0
elsif ($key_type eq 'zset') { } 0 0 0
elsif ($key_type eq 'string') { } 0 0 0
1101 0 my %fields = $self->{'_redis'}->hgetall($redis_key);
1102 0 ▶ if(%fields) {
Branch: 1 branch
BranchTrueFalseTotal
if (%fields) 0 0 0
1103 0 ▶ $self->{'data'} = $self->{'no_entry'}
Branch: 1 branch
BranchTrueFalseTotal
$$self{'no_entry'} ? : 0 0 0
1104 ? [\%fields]
1105 : { $redis_key => { $id => $redis_key, %fields } };
1106 }
1107 } elsif($key_type eq 'list') {
1108 0 my @items = $self->{'_redis'}->lrange($redis_key, 0, -1);
1109 0 my $i = 0;
1110 0 $self->{'data'} = [map { { index => $i++, value => $_ } } @items];
1111 } elsif($key_type eq 'set') {
1112 0 my @members = sort $self->{'_redis'}->smembers($redis_key);
1113 0 $self->{'data'} = [map { { member => $_ } } @members];
1114 } elsif($key_type eq 'zset') {
1115 0 my @pairs = $self->{'_redis'}->zrange($redis_key, 0, -1, 'WITHSCORES');
1116 0 my @rows;
1117 0 ▶ while(@pairs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@pairs) 0 0 0
1118 0 my($m, $s) = splice @pairs, 0, 2;
1119 0 push @rows, { member => $m, score => $s };
1120 }
1121 0 $self->{'data'} = \@rows;
1122 } elsif($key_type eq 'string') {
1123 0 my $val = $self->{'_redis'}->get($redis_key);
1124 0 ▶ $self->{'data'} = [{ value => $val }] if defined $val;
Branch: 1 branch
BranchTrueFalseTotal
if defined $val 0 0 0
1125 }
1126 # 'none': key does not exist -- data stays undef; returns empty below.
1127 }
1128  
1129 0 $self->{'type'} = 'Redis';
1130 0 $self->{'_updated'} = time();
1131 0 return $self;
1132 }
1133  
1134 # URL-based backend — handles both JSON and HTML table responses.
1135 # LWP::UserAgent::Cached is always required; JSON::MaybeXS and
1136 # HTML::TableExtract are loaded lazily based on the response Content-Type.
1137 402 ▶ if(my $url = $self->{'url'} || $defaults{'url'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $url = $$self{"url"} || $Database::Abstraction::defaults{"url"}) 17 385 402
Condition66%2/3
$$self{'url'} || $Database::Abstraction::defaults{'url'}
l!l&&r!l&&!r
170385
MC/DC50%1/2
$$self{'url'} || $Database::Abstraction::defaults{'url'}
$$self{'url'} $Database::Abstraction::defaults{'url'}
Truth table66%2/3
A || B
A= $$self{'url'}B= $Database::Abstraction::defaults{'url'}
ABresult
1X1
011
000
1138 17 require LWP::UserAgent::Cached;
1139  
1140 16 ▶ my $ua = $self->{ua} // LWP::UserAgent::Cached->new(timeout => 30, agent => __PACKAGE__ . '/' . $VERSION);
Condition33%1/3
$$self{"ua"} // "LWP::UserAgent::Cached"->new("timeout", 30, "agent", 'Database::Abstraction/' . $Database::Abstraction::VERSION)
l!l&&r!l&&!r
0160
MC/DC0%0/2
$$self{"ua"} // "LWP::UserAgent::Cached"->new("timeout", 30, "agent", 'Database::Abstraction/' . $Database::Abstraction::VERSION)
$$self{"ua"} "LWP::UserAgent::Cached"->new("timeout", 30, "agent", 'Database::Abstraction/' . $Database::Abstraction::VERSION)
Truth table33%1/3
A // B
A= $$self{"ua"}B= "LWP::UserAgent::Cached"->new("timeout", 30, "agent", 'Database::Abstraction/' . $Database::Abstraction::VERSION)
ABresult
1X1
011
000
1141 16 $ua->env_proxy(1);
1142 16 my $response = $ua->get($url);
1143 16 ▶ Carp::croak(ref($self), ": cannot fetch '$url': ", $response->status_line)
Branch: 1 branch
BranchTrueFalseTotal
unless $response->is_success 2 14 16
1144 unless $response->is_success;
1145  
1146 14 ▶ my $content_type = $response->content_type() // '';
Condition50%1/2
$response->content_type // ""
l!l
140
MC/DC0%0/1
$response->content_type // ""
$response->content_type
Truth table50%1/2
A
A= $response->content_type
Aresult
11
00
1147 14 ▶ if($content_type =~ m{\bapplication/json\b}i || $url =~ /\.json(?:[?#]|\z)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content_type =~ m[\bapplication/json\b]i or $url =~ /\.json(?:[?#]|\z)/i) { } 6 8 14
Condition100%3/3
$content_type =~ m[\bapplication/json\b]i or $url =~ /\.json(?:[?#]|\z)/i
l!l&&r!l&&!r
518
MC/DC100%2/2
$content_type =~ m[\bapplication/json\b]i or $url =~ /\.json(?:[?#]|\z)/i
$content_type =~ m[\bapplication/json\b]i $url =~ /\.json(?:[?#]|\z)/i
Truth table100%3/3
A or B
A= $content_type =~ m[\bapplication/json\b]iB= $url =~ /\.json(?:[?#]|\z)/i
ABresult
1X1
011
000
1148 # JSON URL backend — lazy-loads JSON::MaybeXS.
1149 # Detects by Content-Type: application/json or a .json URL suffix.
1150 6 require JSON::MaybeXS;
1151 6 my $parsed = JSON::MaybeXS::decode_json($response->decoded_content);
1152 6 my @data;
1153 6 ▶ if(ref($parsed) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $parsed eq 'ARRAY') { } 5 1 6
elsif (ref $parsed eq 'HASH') { } 1 0 1
1154 5 @data = @{$parsed};
1155 } elsif(ref($parsed) eq 'HASH') {
1156 # Object keyed by primary-key value — inject id column into each row
1157 1 my $id_col = $self->{'id'};
1158 1 for my $k (sort keys %{$parsed}) {
1159 2 my $row = $parsed->{$k};
1160 2 ▶ if(ref($row) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $row eq 'HASH') { } 2 0 2
1161 2 push @data, { $id_col => $k, %{$row} };
1162 } else {
1163 0 push @data, { $id_col => $k, value => $row };
1164 }
1165 }
1166 } else {
1167 0 Carp::croak(ref($self), ": JSON URL: unexpected top-level structure from '$url'");
1168 }
1169 6 ▶ if($self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 1 5 6
1170 1 ▶ $self->{'data'} = @data ? \@data : undef;
Branch: 1 branch
BranchTrueFalseTotal
@data ? : 1 0 1
1171 } else {
1172 5 $self->{'data'} = { map { $_->{$self->{'id'}} => $_ } @data };
1173 }
1174 6 $self->{'type'} = 'JSON';
1175 } else {
1176 # HTML table backend — lazy-loads HTML::TableExtract.
1177 8 require HTML::TableExtract;
1178  
1179 7 my $te = HTML::TableExtract->new();
1180 7 $te->parse($response->decoded_content);
1181  
1182 7 ▶ my $tidx = $self->{'html_table_index'} // $defaults{'html_table_index'} // 0;
Condition80%4/5
($$self{"html_table_index"} // $Database::Abstraction::defaults{"html_table_index"}) // 0
l!l
25
$$self{"html_table_index"} // $Database::Abstraction::defaults{"html_table_index"}
l!l&&r!l&&!r
205
MC/DC50%1/2
($$self{"html_table_index"} // $Database::Abstraction::defaults{"html_table_index"}) // 0
$$self{"html_table_index"} $Database::Abstraction::defaults{"html_table_index"}
Truth table66%2/3
A // B
A= $$self{"html_table_index"}B= $Database::Abstraction::defaults{"html_table_index"}
ABresult
1X1
011
000
1183 7 my @tables = $te->tables;
1184 7 ▶ Carp::croak(ref($self), ": no HTML tables found at '$url'")
Branch: 1 branch
BranchTrueFalseTotal
unless @tables 0 7 7
1185 unless @tables;
1186 7 ▶ Carp::croak(ref($self), ": html_table_index $tidx out of range (", scalar @tables, " tables) at '$url'")
Branch: 1 branch
BranchTrueFalseTotal
if $tidx >= @tables 1 6 7
1187 if $tidx >= @tables;
1188  
1189 6 my @rows = $tables[$tidx]->rows;
1190 6 ▶ Carp::croak(ref($self), ": empty HTML table at '$url'")
Branch: 1 branch
BranchTrueFalseTotal
unless @rows 0 6 6
1191 unless @rows;
1192  
1193 6 ▶ my @headers = map { defined($_) ? "$_" : '' } @{$rows[0]};
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 17 0 17
1194 6 my $id = $self->{'id'};
1195  
1196 6 ▶ if($self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 2 4 6
1197 2 my @data;
1198 2 for my $i (1 .. $#rows) {
1199 5 my %row;
1200 5 ▶ @row{@headers} = map { defined($_) ? "$_" : undef } @{$rows[$i]};
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 13 0 13
1201 5 push @data, \%row;
1202 }
1203 2 $self->{'data'} = \@data;
1204 } else {
1205 4 my %data;
1206 4 for my $i (1 .. $#rows) {
1207 12 my %row;
1208 12 ▶ @row{@headers} = map { defined($_) ? "$_" : undef } @{$rows[$i]};
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 36 0 36
1209 12 my $key = $row{$id};
1210 12 ▶ next unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 0 12 12
1211 12 $data{$key} = \%row;
1212 }
1213 4 $self->{'data'} = \%data;
1214 }
1215 6 $self->{'type'} = 'HTML';
1216 }
1217  
1218 12 $self->{'_updated'} = time();
1219 12 ▶ $self->_fixate($self->{'data'}) if $self->{'data'} && ref($self->{'data'}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if $$self{"data"} and ref $$self{"data"} eq "HASH" 9 3 12
Condition66%2/3
$$self{"data"} and ref $$self{"data"} eq "HASH"
!ll&&!rl&&r
039
MC/DC50%1/2
$$self{"data"} and ref $$self{"data"} eq "HASH"
$$self{"data"} ref $$self{"data"} eq "HASH"
Truth table66%2/3
A and B
A= $$self{"data"}B= ref $$self{"data"} eq "HASH"
ABresult
0X0
100
111
1220 12 $self->{'_dbh'}{$table} = undef; # No DBI handle; all queries use the in-memory data path
1221 12 return $self;
1222 }
1223  
1224 # Derive the filename stem from the class name, NOT from any $table override.
1225 # This allows table => 'Sheet2' to query a different worksheet within the same
1226 # file (e.g. test1.xlsx with a 'sheet2' worksheet) without needing an explicit
1227 # dbname. When dbname is set explicitly it always wins.
1228 385 my $class_stem = ref($self);
1229 385 $class_stem =~ s/\A.*:://;
1230 385 ▶ my $dbname = $self->{'dbname'} || $defaults{'dbname'} || $class_stem;
Condition66%4/6
$$self{'dbname'} || $Database::Abstraction::defaults{'dbname'} || $class_stem
l!l&&r!l&&!r
433420
$$self{"dbname"} or $Database::Abstraction::defaults{"dbname"}
l!l&&r!l&&!r
430342
MC/DC0%0/3
$$self{'dbname'} || $Database::Abstraction::defaults{'dbname'} || $class_stem
$$self{"dbname"} $Database::Abstraction::defaults{"dbname"} $class_stem
Truth table50%2/4
A or B || C
A= $$self{"dbname"}B= $Database::Abstraction::defaults{"dbname"}C= $class_stem
ABCresult
1XX1
01X1
0011
0000
1231 # \A/\z (not ^/$) so a trailing newline cannot sneak past the $ anchor.
1232 385 ▶ Carp::croak(ref($self), ": unsafe dbname '$dbname'")
Branch: 1 branch
BranchTrueFalseTotal
unless $dbname =~ /\A[a-zA-Z0-9_.-]+\z/ and not $dbname =~ /\.\./ 10 375 385
Condition100%3/3
$dbname =~ /\A[a-zA-Z0-9_.-]+\z/ and not $dbname =~ /\.\./
!ll&&!rl&&r
91375
MC/DC100%2/2
$dbname =~ /\A[a-zA-Z0-9_.-]+\z/ and not $dbname =~ /\.\./
$dbname =~ /\A[a-zA-Z0-9_.-]+\z/ not $dbname =~ /\.\./
Truth table100%3/3
A and not(B)
A= $dbname =~ /\A[a-zA-Z0-9_.-]+\z/B= not $dbname =~ /\.\./
ABresult
0X0
100
111
1233 unless $dbname =~ /\A[a-zA-Z0-9_.-]+\z/ && $dbname !~ /\.\./;
1234  
1235 # When a remote host is given, fetch all candidate files into a local temp
1236 # directory via File::Slurp::Remote (SSH/SCP). localhost / 127.0.0.1 / the
1237 # current machine's hostname are treated as local (no SSH, no temp dir).
1238 375 my $dir;
1239 375 ▶ if(my $host = $self->{'host'} || $defaults{'host'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $host = $$self{'host'} || $Database::Abstraction::defaults{'host'}) { } 8 367 375
Condition66%2/3
$$self{'host'} || $Database::Abstraction::defaults{'host'}
l!l&&r!l&&!r
80367
MC/DC50%1/2
$$self{'host'} || $Database::Abstraction::defaults{'host'}
$$self{'host'} $Database::Abstraction::defaults{'host'}
Truth table66%2/3
A || B
A= $$self{'host'}B= $Database::Abstraction::defaults{'host'}
ABresult
1X1
011
000
1240 8 ▶ if($self->_is_local_host($host)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_local_host($host)) { } 7 1 8
1241 7 $self->_debug("host '$host' is local; reading directory directly");
1242 7 ▶ my $raw_dir = $self->{'directory'} || $defaults{'directory'};
Condition33%1/3
$$self{'directory'} || $Database::Abstraction::defaults{'directory'}
l!l&&r!l&&!r
700
MC/DC0%0/2
$$self{'directory'} || $Database::Abstraction::defaults{'directory'}
$$self{'directory'} $Database::Abstraction::defaults{'directory'}
Truth table33%1/3
A || B
A= $$self{'directory'}B= $Database::Abstraction::defaults{'directory'}
ABresult
1X1
011
000
1243 7 ▶ Carp::croak(ref($self), ': no directory specified') unless $raw_dir;
Branch: 1 branch
BranchTrueFalseTotal
unless $raw_dir 0 7 7
1244 7 $dir = Cwd::abs_path($raw_dir);
1245 } else {
1246 1 require File::Slurp::Remote;
1247 0 require POSIX;
1248 0 ▶ my $remote_dir = $self->{'directory'} || $defaults{'directory'};
Condition0%0/3
$$self{'directory'} || $Database::Abstraction::defaults{'directory'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$$self{'directory'} || $Database::Abstraction::defaults{'directory'}
$$self{'directory'} $Database::Abstraction::defaults{'directory'}
Truth table0%0/3
A || B
A= $$self{'directory'}B= $Database::Abstraction::defaults{'directory'}
ABresult
1X1
011
000
1249 0 my $tmpdir_obj = File::Temp->newdir(CLEANUP => 1);
1250 0 $self->{'_remote_tmpdir'} = $tmpdir_obj; # auto-cleans on DESTROY
1251 0 my $tmpdir = $tmpdir_obj->dirname();
1252 0 my @probe_exts = qw(sql sqlite sqlite3 dbm deep db csv.gz db.gz psv tsv xls xlsx csv xml json);
1253  
1254 0 ▶ if(my $filename = $self->{'filename'} || $defaults{'filename'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $filename = $$self{'filename'} || $Database::Abstraction::defaults{'filename'}) { } 0 0 0
Condition0%0/3
$$self{'filename'} || $Database::Abstraction::defaults{'filename'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$$self{'filename'} || $Database::Abstraction::defaults{'filename'}
$$self{'filename'} $Database::Abstraction::defaults{'filename'}
Truth table0%0/3
A || B
A= $$self{'filename'}B= $Database::Abstraction::defaults{'filename'}
ABresult
1X1
011
000
1255 # Explicit filename given — one SSH fetch, no extension probing needed.
1256 # Validate the same way _open() will when it processes the filename later.
1257 0 ▶ Carp::croak(ref($self), ": unsafe filename '$filename'")
Branch: 1 branch
BranchTrueFalseTotal
unless $filename =~ /\A[a-zA-Z0-9_.-]+\z/ and not $filename =~ /\.\./ 0 0 0
Condition0%0/3
$filename =~ /\A[a-zA-Z0-9_.-]+\z/ and not $filename =~ /\.\./
!ll&&!rl&&r
000
MC/DC0%0/2
$filename =~ /\A[a-zA-Z0-9_.-]+\z/ and not $filename =~ /\.\./
$filename =~ /\A[a-zA-Z0-9_.-]+\z/ not $filename =~ /\.\./
Truth table0%0/3
A and not(B)
A= $filename =~ /\A[a-zA-Z0-9_.-]+\z/B= not $filename =~ /\.\./
ABresult
0X0
100
111
1258 unless $filename =~ /\A[a-zA-Z0-9_.-]+\z/ && $filename !~ /\.\./;
1259 0 my $remote_file = "$remote_dir/$filename";
1260 0 my $content = eval { scalar File::Slurp::Remote::read_remote_file($host, $remote_file) };
1261 0 ▶ if(defined($content) && length($content)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $content and length $content) 0 0 0
Condition0%0/3
defined $content and length $content
!ll&&!rl&&r
000
MC/DC0%0/2
defined $content and length $content
defined $content length $content
Truth table0%0/3
A and B
A= defined $contentB= length $content
ABresult
0X0
100
111
1262 0 my $local = File::Spec->catfile($tmpdir, $filename);
1263 0 open(my $fh, '>', $local);
1264 0 binmode $fh;
1265 0 print $fh $content;
1266 0 close $fh;
1267 0 $self->_debug("fetched remote $host:$remote_file");
1268 }
1269 } else {
1270 # No explicit filename — probe all candidate extensions.
1271 # Fork one child per extension so all SSH calls run concurrently.
1272 # Falls back to sequential for any extension whose fork() fails.
1273 # Children MUST exit via POSIX::_exit(0) to skip Perl's cleanup
1274 # phase; a normal exit(0) would run DESTROY on the inherited
1275 # File::Temp::Dir, deleting the tmpdir while the parent still needs it.
1276 0 my (@pids, @fallback_exts);
1277 0 for my $ext (@probe_exts) {
1278 0 my $pid = eval { fork() };
1279 0 ▶ if(!defined $pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $pid) 0 0 0
1280 # fork() failed or unavailable — defer to sequential pass
1281 0 push @fallback_exts, $ext;
1282 0 next;
1283 }
1284 0 ▶ if($pid == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid == 0) 0 0 0
1285 # child: fetch one extension; eval guards against autodie croaks
1286 0 eval {
1287 0 my $remote_file = "$remote_dir/$dbname.$ext";
1288 0 my $content = File::Slurp::Remote::read_remote_file($host, $remote_file);
1289 0 ▶ if(defined($content) && length($content)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $content and length $content) 0 0 0
Condition0%0/3
defined $content and length $content
!ll&&!rl&&r
000
MC/DC0%0/2
defined $content and length $content
defined $content length $content
Truth table0%0/3
A and B
A= defined $contentB= length $content
ABresult
0X0
100
111
1290 0 my $local = File::Spec->catfile($tmpdir, "$dbname.$ext");
1291 0 open(my $fh, '>', $local);
1292 0 binmode $fh;
1293 0 print $fh $content;
1294 0 close $fh;
1295 }
1296 };
1297 0 POSIX::_exit(0);
1298 }
1299 0 push @pids, $pid;
1300 }
1301 0 waitpid($_, 0) for @pids;
1302  
1303 # Sequential pass for any extensions that couldn't be forked
1304 0 for my $ext (@fallback_exts) {
1305 0 my $remote_file = "$remote_dir/$dbname.$ext";
1306 0 my $content = eval { scalar File::Slurp::Remote::read_remote_file($host, $remote_file) };
1307 0 ▶ next unless defined($content) && length($content);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content and length $content 0 0 0
Condition0%0/3
defined $content and length $content
!ll&&!rl&&r
000
MC/DC0%0/2
defined $content and length $content
defined $content length $content
Truth table0%0/3
A and B
A= defined $contentB= length $content
ABresult
0X0
100
111
1308 0 my $local = File::Spec->catfile($tmpdir, "$dbname.$ext");
1309 0 open(my $fh, '>', $local);
1310 0 binmode $fh;
1311 0 print $fh $content;
1312 0 close $fh;
1313 0 $self->_debug("fetched remote $host:$remote_file");
1314 }
1315 }
1316 0 $dir = $tmpdir;
1317 }
1318 } else {
1319 367 ▶ my $raw_dir = $self->{'directory'} || $defaults{'directory'};
Condition33%1/3
$$self{'directory'} || $Database::Abstraction::defaults{'directory'}
l!l&&r!l&&!r
36700
MC/DC0%0/2
$$self{'directory'} || $Database::Abstraction::defaults{'directory'}
$$self{'directory'} $Database::Abstraction::defaults{'directory'}
Truth table33%1/3
A || B
A= $$self{'directory'}B= $Database::Abstraction::defaults{'directory'}
ABresult
1X1
011
000
1320 367 ▶ Carp::croak(ref($self), ': no directory specified') unless $raw_dir;
Branch: 1 branch
BranchTrueFalseTotal
unless $raw_dir 0 367 367
1321 367 $dir = Cwd::abs_path($raw_dir);
1322 }
1323 # Probe for SQLite files (.sql, .sqlite, .sqlite3)
1324 374 my $slurp_file;
1325 374 for my $ext (qw(sql sqlite sqlite3)) {
1326 1066 my $candidate = File::Spec->catfile($dir, "$dbname.$ext");
1327 1066 ▶ if(-r $candidate) { $slurp_file = $candidate; last }
Branch: 1 branch
BranchTrueFalseTotal
if (-r $candidate) 31 1035 1066
1328 }
1329 374 ▶ $slurp_file //= File::Spec->catfile($dir, "$dbname.sql");
Condition66%2/3
$slurp_file //= "File::Spec"->catfile($dir, "$dbname.sql")
l!l&&r!l&&!r
313430
MC/DC0%0/2
$slurp_file //= "File::Spec"->catfile($dir, "$dbname.sql")
$slurp_file "File::Spec"->catfile($dir, "$dbname.sql")
Truth table66%2/3
A //= B
A= $slurp_fileB= "File::Spec"->catfile($dir, "$dbname.sql")
ABresult
1X1
011
000
1330  
1331 374 $self->_debug("_open: try to open $slurp_file");
1332  
1333 # Probe for DBM::Deep files (.dbm or .deep) before the CSV/BerkeleyDB fallback.
1334 # Loaded lazily so the DBM::Deep module is not required for other backends.
1335 374 my $deep_file;
1336 374 for my $ext (qw(dbm deep)) {
1337 742 my $candidate = File::Spec->catfile($dir, "$dbname.$ext");
1338 742 ▶ if(-r $candidate) { $deep_file = $candidate; last }
Branch: 1 branch
BranchTrueFalseTotal
if (-r $candidate) 12 730 742
1339 }
1340 # Also detect DBM::Deep files by magic bytes (covers .db files and arbitrary extensions).
1341 374 ▶ if(!$deep_file) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($deep_file) 362 12 374
1342 362 my $db_candidate = File::Spec->catfile($dir, "$dbname.db");
1343 362 ▶ $deep_file = $db_candidate if -r $db_candidate && $self->_is_deep_db($db_candidate);
Branch: 1 branch
BranchTrueFalseTotal
if -r $db_candidate and $self->_is_deep_db($db_candidate) 1 361 362
Condition100%3/3
-r $db_candidate and $self->_is_deep_db($db_candidate)
!ll&&!rl&&r
36011
MC/DC100%2/2
-r $db_candidate and $self->_is_deep_db($db_candidate)
-r $db_candidate $self->_is_deep_db($db_candidate)
Truth table100%3/3
A and B
A= -r $db_candidateB= $self->_is_deep_db($db_candidate)
ABresult
0X0
100
111
1344 }
1345  
1346 # Look at various places to find the file and derive the file type from the file's name
1347 374 ▶ if(-r $slurp_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $slurp_file) 31 343 374
1348 # SQLite file
1349 31 require DBD::SQLite::Constants;
1350 31 $dbh = DBI->connect("dbi:SQLite:dbname=$slurp_file", undef, undef, {
1351 sqlite_open_flags => DBD::SQLite::Constants::SQLITE_OPEN_READONLY(),
1352 });
1353 }
1354 374 ▶ if($dbh) {
Branch: 3 branches
BranchTrueFalseTotal
if ($dbh) { } 31 343 374
elsif ($deep_file) { } 13 330 343
elsif ($self->_is_berkeley_db('File::Spec'->catfile($dir, "$dbname.db"))) { } 0 330 330
1355 31 $dbh->do('PRAGMA synchronous = OFF');
1356 31 $dbh->do('PRAGMA cache_size = -4096'); # Use 4MB cache - negative = KB)
1357 31 $dbh->do('PRAGMA journal_mode = OFF'); # Read-only, no journal needed
1358 31 $dbh->do('PRAGMA temp_store = MEMORY'); # Store temp data in RAM
1359 31 $dbh->do('PRAGMA mmap_size = 1048576'); # Use 1MB memory-mapped I/O
1360 31 $dbh->sqlite_busy_timeout(100000); # 10s
1361 31 $self->_debug("read in $table from SQLite $slurp_file");
1362 31 $self->{'type'} = 'DBI';
1363 } elsif($deep_file) {
1364 # DBM::Deep file (.dbm or .deep) — slurp the entire tied hash into a plain
1365 # Perl hash so all existing in-memory fast-paths work without modification.
1366 13 require DBM::Deep;
1367 12 my $deep = DBM::Deep->new({ file => $deep_file, read_only => 1 });
1368 12 my $id = $self->{'id'};
1369 12 ▶ if($self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 2 10 12
1370 # Not keyed — produce an ordered arrayref of row hashrefs, same as CSV no_entry.
1371 2 my @data;
1372 2 for my $k (sort keys %{$deep}) {
1373 5 my $row = $deep->{$k};
1374 # Use reftype (not ref) so blessed DBM::Deep::Hash objects are recognised.
1375 # Inject the outer key as the id column so criteria on that column work.
1376 push @data, (Scalar::Util::reftype($row) // '') eq 'HASH'
1377 5 ▶ ? { $id => $k, %{$row} }
Branch: 1 branch
BranchTrueFalseTotal
(builtin::reftype($row) // '') eq 'HASH' ? : 3 2 5
Condition100%2/2
builtin::reftype($row) // ""
l!l
32
MC/DC100%1/1
builtin::reftype($row) // ""
builtin::reftype($row)
Truth table100%2/2
A
A= builtin::reftype($row)
Aresult
11
00
1378 : { $id => $k, value => $row };
1379 }
1380 2 ▶ $self->{'data'} = @data ? \@data : undef;
Branch: 1 branch
BranchTrueFalseTotal
@data ? : 2 0 2
1381 } else {
1382 # Keyed on the primary-key column (default: 'entry') for O(1) lookups.
1383 # Each row hash must contain the id column (like CSV rows), so that
1384 # selectall_arrayref and AUTOLOAD can access it by name.
1385 10 my %data;
1386 10 for my $k (keys %{$deep}) {
1387 26 my $row = $deep->{$k};
1388 $data{$k} = (Scalar::Util::reftype($row) // '') eq 'HASH'
1389 26 ▶ ? { $id => $k, %{$row} }
Branch: 1 branch
BranchTrueFalseTotal
(builtin::reftype($row) // '') eq 'HASH' ? : 24 2 26
Condition100%2/2
builtin::reftype($row) // ""
l!l
242
MC/DC100%1/1
builtin::reftype($row) // ""
builtin::reftype($row)
Truth table100%2/2
A
A= builtin::reftype($row)
Aresult
11
00
1390 : { $id => $k, value => $row };
1391 }
1392 10 ▶ $self->{'data'} = %data ? \%data : undef;
Branch: 1 branch
BranchTrueFalseTotal
%data ? : 10 0 10
1393 }
1394 12 $slurp_file = $deep_file;
1395 12 $self->_debug("read in $table from DBM::Deep $deep_file");
1396 12 $self->{'type'} = 'Deep';
1397 } elsif($self->_is_berkeley_db(File::Spec->catfile($dir, "$dbname.db"))) {
1398 0 $self->_debug("$table is a BerkeleyDB file");
1399 0 $self->{'type'} = 'BerkeleyDB';
1400 } else {
1401 330 my $fin;
1402 # File::pfopen splits $path on ':' which breaks Windows drive letters
1403 # (C:\foo becomes ['C', '\foo']). Since we always have a single directory
1404 # we use File::Spec->catfile directly — same behaviour, portable.
1405 my $gz_file;
1406 330 for my $ext (qw(csv.gz db.gz)) {
1407 653 my $candidate = File::Spec->catfile($dir, "$dbname.$ext");
1408 653 ▶ next unless -r $candidate;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $candidate 645 8 653
1409 8 open($fin, '<', $candidate);
1410 8 $gz_file = $candidate;
1411 8 last;
1412 }
1413 330 ▶ if($gz_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($gz_file) { } 8 322 330
1414 8 require Gzip::Faster;
1415  
1416 7 close($fin);
1417 7 $fin = File::Temp->new(SUFFIX => '.csv', UNLINK => 1, CLEANUP => 1);
1418 7 print $fin Gzip::Faster::gunzip_file($gz_file);
1419 7 $fin->flush();
1420 7 $slurp_file = $fin->filename();
1421 7 $self->{'_temp_fh'} = $fin; # Keep object alive; auto-unlinks at DESTROY
1422 } else {
1423 322 my $psv = File::Spec->catfile($dir, "$dbname.psv");
1424 322 ▶ if(-r $psv) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $psv) { } 8 314 322
1425 8 open($fin, '<', $psv);
1426 # Pipe separated file
1427 8 $slurp_file = $psv;
1428 8 $params->{'sep_char'} = '|';
1429 } else {
1430 314 my $tsv = File::Spec->catfile($dir, "$dbname.tsv");
1431 314 ▶ if(-r $tsv) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $tsv) { } 4 310 314
1432 4 open($fin, '<', $tsv);
1433 # Tab separated file
1434 4 $slurp_file = $tsv;
1435 4 $params->{'sep_char'} = "\t";
1436 } else {
1437 # CSV or BerkeleyDB-extension file
1438 310 for my $ext (qw(csv db)) {
1439 373 my $candidate = File::Spec->catfile($dir, "$dbname.$ext");
1440 373 ▶ next unless -r $candidate;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $candidate 125 248 373
1441 248 open($fin, '<', $candidate);
1442 248 $slurp_file = $candidate;
1443 248 last;
1444 }
1445 }
1446 }
1447 }
1448 329 ▶ if(my $filename = $self->{'filename'} || $defaults{'filename'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $filename = $$self{"filename"} || $Database::Abstraction::defaults{"filename"}) 13 316 329
Condition66%2/3
$$self{'filename'} || $Database::Abstraction::defaults{'filename'}
l!l&&r!l&&!r
130316
MC/DC50%1/2
$$self{'filename'} || $Database::Abstraction::defaults{'filename'}
$$self{'filename'} $Database::Abstraction::defaults{'filename'}
Truth table66%2/3
A || B
A= $$self{'filename'}B= $Database::Abstraction::defaults{'filename'}
ABresult
1X1
011
000
1449 13 ▶ Carp::croak(ref($self), ": unsafe filename '$filename'")
Branch: 1 branch
BranchTrueFalseTotal
unless $filename =~ /\A[a-zA-Z0-9_.-]+\z/ and not $filename =~ /\.\./ 9 4 13
Condition100%3/3
$filename =~ /\A[a-zA-Z0-9_.-]+\z/ and not $filename =~ /\.\./
!ll&&!rl&&r
724
MC/DC100%2/2
$filename =~ /\A[a-zA-Z0-9_.-]+\z/ and not $filename =~ /\.\./
$filename =~ /\A[a-zA-Z0-9_.-]+\z/ not $filename =~ /\.\./
Truth table100%3/3
A and not(B)
A= $filename =~ /\A[a-zA-Z0-9_.-]+\z/B= not $filename =~ /\.\./
ABresult
0X0
100
111
1450 unless $filename =~ /\A[a-zA-Z0-9_.-]+\z/ && $filename !~ /\.\./;
1451 4 $self->_debug("Looking for $filename in $dir");
1452 4 $slurp_file = File::Spec->catfile($dir, $filename);
1453 }
1454 320 ▶ if(defined($slurp_file) && (-r $slurp_file)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $slurp_file and -r $slurp_file) { } 263 57 320
Condition66%2/3
defined $slurp_file and -r $slurp_file
!ll&&!rl&&r
057263
MC/DC50%1/2
defined $slurp_file and -r $slurp_file
defined $slurp_file -r $slurp_file
Truth table66%2/3
A and B
A= defined $slurp_fileB= -r $slurp_file
ABresult
0X0
100
111
1455 263 ▶ close($fin) if(defined($fin));
Branch: 1 branch
BranchTrueFalseTotal
if defined $fin 262 1 263
1456 263 my $sep_char = $params->{'sep_char'};
1457 263 my $escape_char = $self->_csv_escape_char($slurp_file);
1458  
1459 263 $self->_debug(__LINE__, ' of ', __PACKAGE__, ": slurp_file = $slurp_file, sep_char = $sep_char");
1460  
1461 263 ▶ if($params->{'column_names'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$params{'column_names'}) { } 1 262 263
1462 $dbh = DBI->connect("dbi:CSV:db_name=$slurp_file", undef, undef,
1463 {
1464 csv_sep_char => $sep_char,
1465 csv_tables => {
1466 $table => {
1467 1 col_names => $params->{'column_names'},
1468 },
1469 },
1470 f_dir => $dir,
1471 RaiseError => 1,
1472 PrintError => 0
1473 }
1474 );
1475 } else {
1476 262 $dbh = DBI->connect("dbi:CSV:db_name=$slurp_file", undef, undef, { csv_sep_char => $sep_char, f_dir => $dir, RaiseError => 1 });
1477 }
1478 263 $dbh->{'RaiseError'} = 1;
1479  
1480 263 $self->_debug("read in $table from CSV $slurp_file");
1481  
1482 263 $dbh->{csv_tables}->{$table} = {
1483 allow_loose_quotes => 1,
1484 blank_is_undef => 1,
1485 empty_is_undef => 1,
1486 binary => 1,
1487 f_file => $slurp_file,
1488 escape_char => $escape_char,
1489 sep_char => $sep_char,
1490 # Don't do this, causes "Bizarre copy of HASH
1491 # in scalar assignment in error_diag
1492 # RT121127
1493 # auto_diag => 1,
1494 auto_diag => 0,
1495 # Don't do this, it causes "Attempt to free unreferenced scalar"
1496 # callbacks => {
1497 # after_parse => sub {
1498 # my ($csv, @rows) = @_;
1499 # my @rc;
1500 # foreach my $row(@rows) {
1501 # if($row->[0] !~ /^#/) {
1502 # push @rc, $row;
1503 # }
1504 # }
1505 # return @rc;
1506 # }
1507 # }
1508 };
1509  
1510 # Text::xSV::Slurp cannot override column names, so skip slurp when
1511 # column_names is set — the DBI CSV connection will supply names instead.
1512 263 ▶ if(((-s $slurp_file) <= $max_slurp_size) && !$params->{'column_names'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (-s $slurp_file <= $max_slurp_size and not $$params{"column_names"}) 233 30 263
Condition100%3/3
-s $slurp_file <= $max_slurp_size and not $$params{"column_names"}
!ll&&!rl&&r
291233
MC/DC100%2/2
-s $slurp_file <= $max_slurp_size and not $$params{"column_names"}
-s $slurp_file <= $max_slurp_size not $$params{"column_names"}
Truth table100%3/3
A and not(B)
A= -s $slurp_file <= $max_slurp_sizeB= not $$params{"column_names"}
ABresult
0X0
100
111
1513 233 ▶ if((-s $slurp_file) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (-s $slurp_file == 0) { } 5 228 233
1514 # Empty file — mirror what the newline-only path stores so
1515 # fast-path query methods return 0/undef/[] instead of falling
1516 # through to DBI (which croaks on a 0-column table).
1517 5 ▶ $self->{'data'} = $self->{'no_entry'} ? undef : {};
Branch: 1 branch
BranchTrueFalseTotal
$$self{'no_entry'} ? : 0 5 5
1518 } else {
1519 228 require Text::xSV::Slurp;
1520  
1521 227 $self->_debug('slurp in');
1522  
1523 227 my $dataref = Text::xSV::Slurp::xsv_slurp(
1524 shape => 'aoh',
1525 text_csv => {
1526 sep_char => $sep_char,
1527 allow_loose_quotes => 1,
1528 blank_is_undef => 1,
1529 empty_is_undef => 1,
1530 binary => 1,
1531 escape_char => $escape_char,
1532 },
1533 # string => \join('', grep(!/^\s*(#|$)/, <DATA>))
1534 file => $slurp_file
1535 );
1536  
1537 # Filter out blank lines and comment rows (lines starting with #)
1538 # Two passes replaced with one: pre-compute id column to avoid N hash
1539 # lookups per element, and combine both conditions into one grep.
1540 227 my $id_col = $self->{'id'};
1541 227 ▶ my @data = grep { defined($_->{$id_col}) && $_->{$id_col} !~ /\A\s*#/ } @{$dataref};
Condition100%3/3
defined $$_{$id_col} && !($$_{$id_col} =~ /\A\s*#/)
!ll&&!rl&&r
43157777
MC/DC100%2/2
defined $$_{$id_col} && !($$_{$id_col} =~ /\A\s*#/)
defined $$_{$id_col} !($$_{$id_col} =~ /\A\s*#/)
Truth table100%3/3
A && not(B)
A= defined $$_{$id_col}B= !($$_{$id_col} =~ /\A\s*#/)
ABresult
0X0
100
111
1542  
1543 227 ▶ if($self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 29 198 227
1544 # Not keyed on a primary column — keep as ordered list.
1545 # Only store a reference when rows were found; an empty-array ref
1546 # is truthy, which would activate the in-memory fast-path and
1547 # silently return 0 results instead of falling through to SQL.
1548 29 ▶ $self->{'data'} = @data ? \@data : undef;
Branch: 1 branch
BranchTrueFalseTotal
@data ? : 17 12 29
1549 } else {
1550 # Key the hash by $self->{'id'} for O(1) entry lookups
1551 198 $self->{'data'} = { map { $_->{$self->{'id'}} => $_ } @data };
1552 }
1553 }
1554 }
1555 262 $self->{'type'} = 'CSV';
1556 } else {
1557 57 my $xls_file = File::Spec->catfile($dir, "$dbname.xls");
1558 57 ▶ if(-r $xls_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $xls_file) { } 0 57 57
1559 # Old binary XLS format via DBD::Excel (Spreadsheet::ParseExcel).
1560 # All queries go through DBI/SQL; no in-memory slurp path.
1561 0 require DBD::Excel;
1562 0 ▶ $dbh = DBI->connect("dbi:Excel:file=$xls_file", undef, undef, {
Branch: 1 branch
BranchTrueFalseTotal
$dbh = "DBI"->connect("dbi:Excel:file=$xls_file", undef, undef, {"RaiseError", 1, "PrintError", 0}) or Carp::croak(ref $self, ": can't open ${xls_file}: $DBI::errstr") 0 0 0
1563 RaiseError => 1,
1564 PrintError => 0,
1565 }) or Carp::croak(ref($self), ": can't open $xls_file: $DBI::errstr");
1566 0 $self->{'type'} = 'Excel';
1567 0 $slurp_file = $xls_file;
1568 } else {
1569 57 my $xlsx_file = File::Spec->catfile($dir, "$dbname.xlsx");
1570 57 ▶ if(-r $xlsx_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $xlsx_file) { } 0 57 57
1571 # Modern OOXML format via Spreadsheet::ParseXLSX — slurped into
1572 # an in-memory hash (keyed) or array (no_entry). No DBI handle.
1573 0 require Spreadsheet::ParseXLSX;
1574 0 ▶ my $workbook = Spreadsheet::ParseXLSX->new()->parse($xlsx_file)
Branch: 1 branch
BranchTrueFalseTotal
my $workbook = "Spreadsheet::ParseXLSX"->new->parse($xlsx_file) or Carp::croak(ref $self, ": can't parse $xlsx_file") 0 0 0
1575 or Carp::croak(ref($self), ": can't parse $xlsx_file");
1576 0 my ($sheet) = grep { $_->get_name() eq $table } $workbook->worksheets();
1577 0 ▶ $sheet //= ($workbook->worksheets())[0];
Condition0%0/3
$sheet //= ($workbook->worksheets)[0]
l!l&&r!l&&!r
000
MC/DC0%0/2
$sheet //= ($workbook->worksheets)[0]
$sheet ($workbook->worksheets)[0]
Truth table0%0/3
A //= B
A= $sheetB= ($workbook->worksheets)[0]
ABresult
1X1
011
000
1578 0 ▶ Carp::croak(ref($self), ": no worksheet in $xlsx_file") unless $sheet;
Branch: 1 branch
BranchTrueFalseTotal
unless $sheet 0 0 0
1579 0 my ($row_min, $row_max) = $sheet->row_range();
1580 0 my ($col_min, $col_max) = $sheet->col_range();
1581 0 my @headers;
1582 0 for my $c ($col_min .. $col_max) {
1583 0 my $cell = $sheet->get_cell($row_min, $c);
1584 0 ▶ push @headers, $cell ? $cell->value() : "col$c";
Branch: 1 branch
BranchTrueFalseTotal
$cell ? : 0 0 0
1585 }
1586 0 my @data;
1587 0 for my $r ($row_min + 1 .. $row_max) {
1588 0 my %row;
1589 0 for my $c ($col_min .. $col_max) {
1590 0 my $cell = $sheet->get_cell($r, $c);
1591 0 ▶ $row{$headers[$c - $col_min]} = $cell ? $cell->value() : undef;
Branch: 1 branch
BranchTrueFalseTotal
$cell ? : 0 0 0
1592 }
1593 0 push @data, \%row;
1594 }
1595 0 ▶ if($self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 0 0 0
1596 0 ▶ $self->{'data'} = @data ? \@data : undef;
Branch: 1 branch
BranchTrueFalseTotal
@data ? : 0 0 0
1597 } else {
1598 0 $self->{'data'} = { map { $_->{$self->{'id'}} => $_ } @data };
1599 }
1600 0 $self->{'type'} = 'XLSX';
1601 0 $slurp_file = $xlsx_file;
1602 } else {
1603 57 $slurp_file = File::Spec->catfile($dir, "$dbname.xml");
1604 57 ▶ if(-r $slurp_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $slurp_file) { } 43 14 57
1605 43 ▶ if((-s $slurp_file) <= $max_slurp_size) {
Branch: 1 branch
BranchTrueFalseTotal
if (-s $slurp_file <= $max_slurp_size) { } 40 3 43
1606 40 require XML::Simple;
1607  
1608 39 my $xml = XML::Simple::XMLin($slurp_file);
1609 # Hash order is random: take the repeating element (the
1610 # one with most occurrences, then by name) so a document
1611 # with several top-level elements reads the same way
1612 # every time, not only when the right key came first.
1613 my @keys = ref($xml) eq 'HASH' ? sort {
1614 24 ▶ (ref($xml->{$b}) eq 'ARRAY' ? scalar(@{$xml->{$b}}) : 0)
Branch: 1 branch
BranchTrueFalseTotal
ref $$xml{$a} eq 'ARRAY' ? : 24 85 109
1615 109 ▶ <=> (ref($xml->{$a}) eq 'ARRAY' ? scalar(@{$xml->{$a}}) : 0)
Branch: 1 branch
BranchTrueFalseTotal
ref $$xml{$b} eq 'ARRAY' ? : 24 85 109
Condition66%2/3
(ref $$xml{$b} eq 'ARRAY' ? scalar @{$$xml{$b};} : 0) <=> (ref $$xml{$a} eq 'ARRAY' ? scalar @{$$xml{$a};} : 0) || $a cmp $b
l!l&&r!l&&!r
45640
MC/DC0%0/2
(ref $$xml{$b} eq 'ARRAY' ? scalar @{$$xml{$b};} : 0) <=> (ref $$xml{$a} eq 'ARRAY' ? scalar @{$$xml{$a};} : 0) || $a cmp $b
(ref $$xml{$b} eq 'ARRAY' ? scalar @{$$xml{$b};} : 0) <=> (ref $$xml{$a} eq 'ARRAY' ? scalar @{$$xml{$a};} : 0) $a cmp $b
Truth table66%2/3
A || B
A= (ref $$xml{$b} eq 'ARRAY' ? scalar @{$$xml{$b};} : 0) <=> (ref $$xml{$a} eq 'ARRAY' ? scalar @{$$xml{$a};} : 0)B= $a cmp $b
ABresult
1X1
011
000
1616 || $a cmp $b
1617 33 ▶ } keys %{$xml} : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $xml eq 'HASH' ? : 33 0 33
1618 33 my $key = $keys[0];
1619 33 my @data;
1620 33 ▶ if(ref($xml->{$key}) eq 'ARRAY') {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $$xml{$key} eq 'ARRAY') { } 28 5 33
elsif (ref $xml eq 'ARRAY') { } 0 5 5
elsif (ref $xml eq 'HASH' and not $$self{'no_entry'}) { } 3 2 5
elsif (ref $xml eq 'HASH' and scalar keys %{$xml;} > 1) { } 2 0 2
1621 28 @data = @{$xml->{$key}};
1622 } elsif(ref($xml) eq 'ARRAY') {
1623 0 @data = @{$xml};
1624 ▶ } elsif((ref($xml) eq 'HASH') && !$self->{'no_entry'}) {
Condition66%2/3
ref $xml eq "HASH" and not $$self{"no_entry"}
!ll&&!rl&&r
023
MC/DC50%1/2
ref $xml eq "HASH" and not $$self{"no_entry"}
ref $xml eq "HASH" not $$self{"no_entry"}
Truth table66%2/3
A and not(B)
A= ref $xml eq "HASH"B= not $$self{"no_entry"}
ABresult
0X0
100
111
1625 3 ▶ if(scalar(keys %{$xml}) == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$xml;} == 1) { } 2 1 3
1626 2 ▶ if($xml->{$table}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$xml{$table}) { } 1 1 2
1627 1 @data = $xml->{$table};
1628 } else {
1629 1 Carp::croak('XML slurp: complex documents with an "entry" field are not yet supported');
1630 }
1631 } else {
1632 1 Carp::croak('XML slurp: multi-key documents are not yet supported');
1633 }
1634 2 ▶ } elsif((ref($xml) eq 'HASH') && scalar(keys %{$xml}) > 1) {
Condition33%1/3
ref $xml eq "HASH" and scalar keys %{$xml;} > 1
!ll&&!rl&&r
002
MC/DC0%0/2
ref $xml eq "HASH" and scalar keys %{$xml;} > 1
ref $xml eq "HASH" scalar keys %{$xml;} > 1
Truth table33%1/3
A and B
A= ref $xml eq "HASH"B= scalar keys %{$xml;} > 1
ABresult
0X0
100
111
1635 2 Carp::croak('XML slurp: multi-key documents with no repeating element are not yet supported');
1636 } else {
1637 0 Carp::croak('XML slurp: cannot handle ', ref($xml), ' structure');
1638 }
1639 29 ▶ if($self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 26 3 29
1640 # Not keyed, will need to scan each entry
1641 26 my $i = 0;
1642 26 foreach my $d(@data) {
1643 80 $self->{'data'}->{$i++} = $d;
1644 }
1645 } else {
1646 # keyed on the $self->{'id'} (default: "entry") column
1647 3 foreach my $d(@data) {
1648 11 $self->{'data'}->{$d->{$self->{'id'}}} = $d;
1649 }
1650 }
1651 } else {
1652 3 $dbh = DBI->connect('dbi:XMLSimple(RaiseError=>1):');
1653 0 $dbh->{'RaiseError'} = 1;
1654 0 $self->_debug("read in $table from XML $slurp_file");
1655 0 $dbh->func($table, 'XML', $slurp_file, 'xmlsimple_import');
1656 }
1657 } else {
1658 14 my $json_file = File::Spec->catfile($dir, "$dbname.json");
1659 14 ▶ if(-r $json_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $json_file) { } 9 5 14
1660 9 ▶ if((-s $json_file) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (-s $json_file == 0) { } 1 8 9
1661 1 ▶ $self->{'data'} = $self->{'no_entry'} ? undef : {};
Branch: 1 branch
BranchTrueFalseTotal
$$self{'no_entry'} ? : 0 1 1
1662 } else {
1663 8 require JSON::MaybeXS;
1664  
1665 8 open(my $jfh, '<', $json_file);
1666 8 local $/;
1667 8 my $raw = <$jfh>;
1668 8 close $jfh;
1669 8 ▶ if(!defined($raw) || $raw =~ /\A\s*\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $raw or $raw =~ /\A\s*\z/) { } 1 7 8
Condition66%2/3
not defined $raw or $raw =~ /\A\s*\z/
l!l&&r!l&&!r
017
MC/DC50%1/2
not defined $raw or $raw =~ /\A\s*\z/
not defined $raw $raw =~ /\A\s*\z/
Truth table66%2/3
not(A) or B
A= not defined $rawB= $raw =~ /\A\s*\z/
ABresult
1X1
011
000
1670 # Whitespace-only — treat as empty, same as zero-byte
1671 1 ▶ $self->{'data'} = $self->{'no_entry'} ? undef : {};
Branch: 1 branch
BranchTrueFalseTotal
$$self{'no_entry'} ? : 0 1 1
1672 } else {
1673 7 my $parsed = JSON::MaybeXS::decode_json($raw);
1674 7 my @data;
1675 7 ▶ if(ref($parsed) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $parsed eq 'ARRAY') { } 7 0 7
elsif (ref $parsed eq 'HASH') { } 0 0 0
1676 7 @data = @{$parsed};
1677 } elsif(ref($parsed) eq 'HASH') {
1678 # Hash of id => row — inject id column into each row
1679 0 my $id_col = $self->{'id'};
1680 0 for my $k (sort keys %{$parsed}) {
1681 0 my $row = $parsed->{$k};
1682 0 ▶ if(ref($row) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $row eq 'HASH') { } 0 0 0
1683 0 push @data, { $id_col => $k, %{$row} };
1684 } else {
1685 0 push @data, { $id_col => $k, value => $row };
1686 }
1687 }
1688 } else {
1689 0 Carp::croak(ref($self), ": JSON slurp: unexpected top-level structure in $json_file");
1690 }
1691 7 ▶ if($self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 1 6 7
1692 1 ▶ $self->{'data'} = @data ? \@data : undef;
Branch: 1 branch
BranchTrueFalseTotal
@data ? : 1 0 1
1693 } else {
1694 6 $self->{'data'} = { map { $_->{$self->{'id'}} => $_ } @data };
1695 }
1696 }
1697 }
1698 9 $slurp_file = $json_file;
1699 9 $self->_debug("read in $table from JSON $json_file");
1700 9 $self->{'type'} = 'JSON';
1701 } else {
1702 # throw Error(-file => "$dir/$table");
1703 5 $self->_fatal("Can't find a file called '$dbname' for the table $table in $dir");
1704 }
1705 }
1706 38 ▶ $self->{'type'} //= 'XML';
Condition100%2/2
$$self{"type"} //= "XML"
l!l
929
MC/DC100%1/1
$$self{"type"} //= "XML"
$$self{"type"}
Truth table100%2/2
A
A= $$self{"type"}
Aresult
11
00
1707 }
1708 } # end: xlsx else (xml path)
1709 } # end: xls else
1710 }
1711  
1712 # ref() must be called on the variable, not on the result of 'eq'
1713 343 ▶ $self->_fixate($self->{'data'}) if($self->{'data'} && (ref($self->{'data'}) eq 'HASH'));
Branch: 1 branch
BranchTrueFalseTotal
if $$self{"data"} and ref $$self{"data"} eq "HASH" 250 93 343
Condition100%3/3
$$self{"data"} and ref $$self{"data"} eq "HASH"
!ll&&!rl&&r
7320250
MC/DC100%2/2
$$self{"data"} and ref $$self{"data"} eq "HASH"
$$self{"data"} ref $$self{"data"} eq "HASH"
Truth table100%3/3
A and B
A= $$self{"data"}B= ref $$self{"data"} eq "HASH"
ABresult
0X0
100
111
1714  
1715 343 $self->{'_dbh'}{$table} = $dbh;
1716 343 my @statb = stat($slurp_file);
1717 343 $self->{'_updated'} = $statb[9];
1718  
1719 343 return $self;
1720 54 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1721  
1722 # Project columns and/or deduplicate an arrayref of row hashrefs.
1723 # $rows - arrayref of hashrefs
1724 # $cols - arrayref of column names to keep, or undef for all columns
1725 # $distinct - true to remove duplicate rows (after projection)
1726 # Returns a new arrayref; input row hashrefs are not modified.
1727 7 ▶sub _apply_distinct {
Subroutine _apply_distinct: called CC=11 SCAR=25.2
1728 7 my ($rows, $cols, $distinct) = @_;
1729 7 ▶ return $rows unless defined($cols) || $distinct;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cols or $distinct 0 7 7
Condition33%1/3
defined $cols or $distinct
l!l&&r!l&&!r
700
MC/DC0%0/2
defined $cols or $distinct
defined $cols $distinct
Truth table33%1/3
A or B
A= defined $colsB= $distinct
ABresult
1X1
011
000
1730 7 ▶ return $rows unless defined($rows) && @{$rows};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rows and @{$rows;} 0 7 7
Condition33%1/3
defined $rows and @{$rows;}
!ll&&!rl&&r
007
MC/DC0%0/2
defined $rows and @{$rows;}
defined $rows @{$rows;}
Truth table33%1/3
A and B
A= defined $rowsB= @{$rows;}
ABresult
0X0
100
111
1731  
1732 7 my (@out, %seen);
1733 7 for my $row (@{$rows}) {
1734 31 my $r;
1735 31 ▶ if(defined $cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cols) { } 31 0 31
1736 # Use exists() guard: fixate() locks all keys in slurp hashrefs;
1737 # accessing a missing key on a locked hash throws an exception.
1738 31 ▶ $r = { map { $_ => (exists($row->{$_}) ? $row->{$_} : undef) } @{$cols} };
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$_} ? : 40 5 45
1739 } else {
1740 0 $r = $row;
1741 }
1742 31 ▶ if($distinct) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distinct) 8 23 31
1743 8 ▶ my $key = join("\x00", map { defined($r->{$_}) ? $r->{$_} : "\x01" } sort keys %{$r});
Branch: 1 branch
BranchTrueFalseTotal
defined $$r{$_} ? : 13 0 13
1744 8 ▶ next if $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$key}++ 2 6 8
1745 }
1746 29 push @out, $r;
1747 }
1748 7 return \@out;
1749 }
1750  
1751 =head2 selectall_arrayref
1752  
1753 Returns a reference to an array of hash references for every row that
1754 matches the given criteria, or C<undef> when there are no matches.
1755  
1756 my $rows = $db->selectall_arrayref(); # all rows
1757 my $rows = $db->selectall_arrayref(status => 'active'); # exact match
1758 my $rows = $db->selectall_arrayref(score => { '>' => 8 }); # operator
1759  
1760 The full criteria syntax is described in L</QUERY CRITERIA>.
1761  
1762 Pass a C<join> key to combine with another table:
1763  
1764 my $rows = $db->selectall_arrayref(
1765 dept_name => 'Engineering',
1766 join => { table => 'dept', on => 'e.dept_id = dept.id' },
1767 );
1768  
1769 Pass C<limit =E<gt> N> and/or C<offset =E<gt> M> for pagination:
1770  
1771 my $page = $db->selectall_arrayref(status => 'active', limit => 10, offset => 20);
1772  
1773 Both values must be non-negative integers; invalid values are ignored with a
1774 C<carp> warning. When C<offset> is given without C<limit> the SQL backend
1775 uses C<LIMIT -1> on SQLite (meaning "no upper bound") so the C<OFFSET> clause
1776 is legal.
1777  
1778 Pass C<sort_by =E<gt> 'col'> (ascending) or C<sort_by =E<gt> ['col', 'DESC']>
1779 to request a specific sort column and direction instead of the default primary-key
1780 ordering:
1781  
1782 my $rows = $db->selectall_arrayref(sort_by => 'name');
1783 my $rows = $db->selectall_arrayref(sort_by => ['score', 'DESC']);
1784  
1785 The column name is validated against the same identifier rules as all other
1786 column parameters. An unsafe name or an unrecognised direction (anything other
1787 than C<ASC> or C<DESC>, case-insensitive) is ignored with a C<carp> warning and
1788 the default sort order is used instead. Sorting is applied before
1789 C<limit>/C<offset> pagination.
1790  
1791 Pass C<distinct =E<gt> 1> to return only unique rows (deduplication):
1792  
1793 my $rows = $db->selectall_arrayref(distinct => 1);
1794 my $rows = $db->selectall_arrayref(distinct => 1, columns => [qw(status dept)]);
1795  
1796 Pass C<columns =E<gt> \@cols> to restrict which columns appear in the returned
1797 rows. Column names are validated against the same identifier rules as other
1798 parameters; invalid names are dropped with a C<carp> warning.
1799  
1800 On SQL-capable backends (SQLite, PostgreSQL, MySQL, DBD::CSV E<ge> 0.64)
1801 C<distinct =E<gt> 1> emits C<SELECT DISTINCT>. On the slurp (in-memory) path
1802 C<distinct> without C<columns> is a no-op because each row is already unique.
1803  
1804 B<Order of operations:> sort E<rarr> offset E<rarr> limit E<rarr> C<_apply_distinct>.
1805 This means C<< limit => N, distinct => 1 >> deduplicates the already-limited
1806 slice, not the full result set. If you need N distinct rows from a larger set,
1807 omit C<limit> and slice the returned arrayref yourself.
1808  
1809 Results are returned in the cache (if configured) and the returned array
1810 reference is made read-only unless C<no_fixate> was set.
1811  
1812 B<Note:> this always returns all matching rows. Use L</selectall_array>
1813 in scalar context, or C<< $db->query->limit(1)->all() >>, to fetch just one row.
1814  
1815 =head3 PSEUDOCODE
1816  
1817 1. Parse criteria; extract and build any JOIN clause.
1818 Extract distinct, columns, limit, offset, sort_by.
1819 2. If data is slurped AND no joins AND criteria are simple:
1820 a. No criteria -> return all rows as arrayref.
1821 b. entry-only lookup -> return [$data{entry}].
1822 c. Otherwise -> scan rows in-memory with _match_criterion.
1823 In all slurp cases: sort by sort_by column (if given), then apply
1824 offset/limit, then _apply_distinct (columns projection + dedup).
1825 3. Otherwise build SQL: SELECT [DISTINCT] [columns|*] FROM table
1826 [JOIN] [WHERE] ORDER BY sort_by [else id] [LIMIT] [OFFSET].
1827 All DBI backends (including DBD::CSV >= 0.64) use native SELECT DISTINCT.
1828 4. Check cache; return cached arrayref on HIT.
1829 5. prepare_cached + execute; fetch all rows.
1830 6. Store result in cache; fixate the array; return arrayref.
1831  
1832 =head3 API SPECIFICATION
1833  
1834 =head4 Arguments
1835  
1836 %criteria # optional key-value pairs or operator hashrefs
1837 join => HashRef | ArrayRef # optional join spec(s)
1838 sort_by => Str | ArrayRef # optional: 'col' or ['col','DESC']
1839 limit => Int # optional: max rows
1840 offset => Int # optional: rows to skip
1841 distinct => Bool # optional: deduplicate rows
1842 columns => ArrayRef[Str] # optional: restrict output columns
1843 no_fixate => Bool # optional: skip read-only locking
1844 table => Str # optional: override table name
1845  
1846 =head4 Returns
1847  
1848 ArrayRef[HashRef] | undef
1849  
1850 An arrayref of row hashrefs on success. Returns C<undef> when no
1851 rows match. Each hashref is read-only unless C<no_fixate> was set.
1852  
1853 =cut
1854  
1855 374 ▶sub selectall_arrayref {
Subroutine selectall_arrayref: called CC=127 SCAR=66.2
Pod documented
1856 374 my $self = shift;
1857  
1858 # Fire _open() first so $self->{'berkeley'} is known before we parse @_.
1859 # BerkeleyDB param parsing must use get_params(undef, \@_) so that
1860 # key-value pairs like (join => {...}) are not mangled by the positional
1861 # 'entry' mapping that non-BerkeleyDB paths use.
1862 374 $self->_open_table({});
1863  
1864 366 my $params;
1865  
1866 366 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 4 362 366
1867 4 ▶ $params = Params::Get::get_params(undef, \@_) // {};
Condition100%2/2
Params::Get::get_params(undef, \@_) // {}
l!l
31
MC/DC100%1/1
Params::Get::get_params(undef, \@_) // {}
Params::Get::get_params(undef, \@_)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
1868 4 my $bl = delete $params->{'limit'};
1869 4 my $bo = delete $params->{'offset'};
1870 4 my $bdist = delete $params->{'distinct'};
1871 4 my $bcols = delete $params->{'columns'};
1872 4 delete $params->{'no_fixate'};
1873 4 my ($bsc, $bsd) = _parse_sort_by(delete($params->{'sort_by'}), 'selectall_arrayref');
1874 4 ▶ if(defined($bl) && $bl !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bl and not $bl =~ /\A\d+\z/) 0 4 4
Condition33%1/3
defined $bl and not $bl =~ /\A\d+\z/
!ll&&!rl&&r
400
MC/DC0%0/2
defined $bl and not $bl =~ /\A\d+\z/
defined $bl not $bl =~ /\A\d+\z/
Truth table33%1/3
A and not(B)
A= defined $blB= not $bl =~ /\A\d+\z/
ABresult
0X0
100
111
1875 0 Carp::carp('selectall_arrayref: limit must be a non-negative integer, ignoring');
1876 0 undef $bl;
1877 }
1878 4 ▶ if(defined($bo) && $bo !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bo and not $bo =~ /\A\d+\z/) 0 4 4
Condition33%1/3
defined $bo and not $bo =~ /\A\d+\z/
!ll&&!rl&&r
400
MC/DC0%0/2
defined $bo and not $bo =~ /\A\d+\z/
defined $bo not $bo =~ /\A\d+\z/
Truth table33%1/3
A and not(B)
A= defined $boB= not $bo =~ /\A\d+\z/
ABresult
0X0
100
111
1879 0 Carp::carp('selectall_arrayref: offset must be a non-negative integer, ignoring');
1880 0 undef $bo;
1881 }
1882 4 $params = $self->_merge_base_criteria($params);
1883 4 my $rows = $self->_scan_berkeley($params);
1884 4 ▶ if(defined $bsc) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bsc) 0 4 4
1885 0 ▶ if($bsd eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($bsd eq 'DESC') { } 0 0 0
1886 0 ▶ @{$rows} = sort { ($b->{$bsc} // '') cmp ($a->{$bsc} // '') } @{$rows};
Condition0%0/4
$$b{$bsc} // ""
l!l
00
$$a{$bsc} // ""
l!l
00
MC/DC0%0/1
$$b{$bsc} // ""
$$b{$bsc}
MC/DC0%0/1
$$a{$bsc} // ""
$$a{$bsc}
Truth table0%0/2
A
A= $$b{$bsc}
Aresult
11
00
Truth table0%0/2
A
A= $$a{$bsc}
Aresult
11
00
1887 } else {
1888 0 ▶ @{$rows} = sort { ($a->{$bsc} // '') cmp ($b->{$bsc} // '') } @{$rows};
Condition0%0/4
$$a{$bsc} // ""
l!l
00
$$b{$bsc} // ""
l!l
00
MC/DC0%0/1
$$a{$bsc} // ""
$$a{$bsc}
MC/DC0%0/1
$$b{$bsc} // ""
$$b{$bsc}
Truth table0%0/2
A
A= $$a{$bsc}
Aresult
11
00
Truth table0%0/2
A
A= $$b{$bsc}
Aresult
11
00
1889 }
1890 }
1891 4 ▶ if(defined($bl) || defined($bo)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bl or defined $bo) 0 4 4
Condition33%1/3
defined $bl or defined $bo
l!l&&r!l&&!r
004
MC/DC0%0/2
defined $bl or defined $bo
defined $bl defined $bo
Truth table33%1/3
A or B
A= defined $blB= defined $bo
ABresult
1X1
011
000
1892 0 ▶ splice(@{$rows}, 0, int($bo)) if $bo;
Branch: 1 branch
BranchTrueFalseTotal
if $bo 0 0 0
1893 0 ▶ splice(@{$rows}, int($bl)) if defined $bl;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bl 0 0 0
1894 }
1895 4 ▶ $rows = _apply_distinct($rows, $bcols, $bdist) if $bcols || $bdist;
Branch: 1 branch
BranchTrueFalseTotal
if $bcols or $bdist 0 4 4
Condition33%1/3
$bcols or $bdist
l!l&&r!l&&!r
004
MC/DC0%0/2
$bcols or $bdist
$bcols $bdist
Truth table33%1/3
A or B
A= $bcolsB= $bdist
ABresult
1X1
011
000
1896 4 return set_return($rows, { type => 'arrayref' });
1897 }
1898  
1899 362 ▶ if($self->{'no_entry'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 152 210 362
elsif (scalar @_) { } 109 101 210
1900 152 $params = Params::Get::get_params(undef, \@_);
1901 } elsif(scalar(@_)) {
1902 109 $params = Params::Get::get_params('entry', @_);
1903 }
1904  
1905 362 my $table = $self->_open_table($params);
1906  
1907 359 ▶ $params //= {};
Condition100%2/2
$params //= {}
l!l
204155
MC/DC100%1/1
$params //= {}
$params
Truth table100%2/2
A
A= $params
Aresult
11
00
1908  
1909 359 my $join_clause = '';
1910 359 ▶ if(my $join_spec = delete $params->{'join'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $join_spec = delete $params->{"join"}) 45 314 359
1911 45 $join_clause = $self->_build_joins($join_spec);
1912 }
1913  
1914 335 my $limit = delete $params->{'limit'};
1915 335 my $offset = delete $params->{'offset'};
1916 335 ▶ if(defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 20 315 335
1917 20 ▶ if($limit !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $limit =~ /\A\d+\z/) { } 6 14 20
1918 6 Carp::carp('selectall_arrayref: limit must be a non-negative integer, ignoring');
1919 6 undef $limit;
1920 } else {
1921 14 $limit = int($limit);
1922 }
1923 }
1924 335 ▶ if(defined $offset) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 11 324 335
1925 11 ▶ if($offset !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $offset =~ /\A\d+\z/) { } 2 9 11
1926 2 Carp::carp('selectall_arrayref: offset must be a non-negative integer, ignoring');
1927 2 undef $offset;
1928 } else {
1929 9 $offset = int($offset);
1930 }
1931 }
1932  
1933 335 my ($sort_col, $sort_dir) = _parse_sort_by(delete($params->{'sort_by'}), 'selectall_arrayref');
1934  
1935 335 my $distinct = delete $params->{'distinct'};
1936 335 my $columns = delete $params->{'columns'};
1937 335 ▶ if(defined $columns) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $columns) 14 321 335
1938 14 ▶ if(ref($columns) ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $columns ne 'ARRAY') { } 1 13 14
1939 1 Carp::carp('selectall_arrayref: columns must be an arrayref, ignoring');
1940 1 undef $columns;
1941 } else {
1942 13 my @valid;
1943 13 for my $c (@{$columns}) {
1944 18 ▶ if(defined($c) && $c =~ $SAFE_QUALIFIED) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $c and $c =~ /$SAFE_QUALIFIED/) { } 16 2 18
Condition66%2/3
defined $c and $c =~ /$SAFE_QUALIFIED/
!ll&&!rl&&r
0216
MC/DC50%1/2
defined $c and $c =~ /$SAFE_QUALIFIED/
defined $c $c =~ /$SAFE_QUALIFIED/
Truth table66%2/3
A and B
A= defined $cB= $c =~ /$SAFE_QUALIFIED/
ABresult
0X0
100
111
1945 16 push @valid, $c;
1946 } else {
1947 2 Carp::carp("selectall_arrayref: unsafe column name '$c', ignoring");
1948 }
1949 }
1950 13 ▶ $columns = @valid ? \@valid : undef;
Branch: 1 branch
BranchTrueFalseTotal
@valid ? : 11 2 13
1951 }
1952 }
1953  
1954 335 ▶ my $no_fixate = delete($params->{'no_fixate'}) // $self->{'no_fixate'};
Condition66%2/3
delete $params->{"no_fixate"} // $$self{"no_fixate"}
l!l&&r!l&&!r
13340
MC/DC0%0/2
delete $params->{"no_fixate"} // $$self{"no_fixate"}
delete $params->{"no_fixate"} $$self{"no_fixate"}
Truth table66%2/3
A // B
A= delete $params->{"no_fixate"}B= $$self{"no_fixate"}
ABresult
1X1
011
000
1955 335 $params = $self->_merge_base_criteria($params);
1956  
1957 335 ▶ if(!$join_clause && $self->{'data'} && !$self->_has_complex_criteria($params)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $join_clause and $$self{"data"} and not $self->_has_complex_criteria($params)) 194 141 335
Condition100%6/6
not $join_clause and $$self{"data"} and not $self->_has_complex_criteria($params)
!ll&&!rl&&r
1374194
not $join_clause and $$self{"data"}
!ll&&!rl&&r
20117198
MC/DC100%3/3
not $join_clause and $$self{"data"} and not $self->_has_complex_criteria($params)
not $join_clause $$self{"data"} not $self->_has_complex_criteria($params)
Truth table100%4/4
not(A) and B and not(C)
A= not $join_clauseB= $$self{"data"}C= not $self->_has_complex_criteria($params)
ABCresult
0XX0
10X0
1100
1111
1958 194 ▶ if(scalar(keys %{$params}) == 0) {
Branch: 4 branches
BranchTrueFalseTotal
if (scalar keys %{$params;} == 0) { } 146 48 194
elsif (scalar keys %{$params;} == 1 and defined $$params{'entry'} and not $$self{'no_entry'}) { } 15 33 48
elsif (ref $$self{'data'} eq 'HASH') { } 31 2 33
elsif (ref $$self{'data'} eq 'ARRAY' and not $$self{'_dbh'}{$table}) { } 1 1 2
1959 146 $self->_trace("$table: selectall_arrayref fast track return");
1960 146 my @rc;
1961 146 ▶ if(ref($self->{'data'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $$self{'data'} eq 'HASH') { } 142 4 146
1962 142 $self->_debug("$table: returning ", scalar keys %{$self->{'data'}}, ' entries');
1963 142 ▶ if(scalar keys %{$self->{'data'}} <= 10) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$$self{"data"};} <= 10) 142 0 142
1964 142 $self->_debug(do { require Data::Dumper; Data::Dumper::Dumper($self->{'data'}) });
1965 }
1966 142 @rc = values %{$self->{'data'}};
1967 } else {
1968 4 @rc = @{$self->{'data'}};
1969 }
1970 146 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 7 139 146
1971 7 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 3 4 7
1972 3 ▶ @rc = sort { ($b->{$sort_col} // '') cmp ($a->{$sort_col} // '') } @rc;
Condition100%4/4
$$b{$sort_col} // ""
l!l
141
$$a{$sort_col} // ""
l!l
141
MC/DC100%1/1
$$b{$sort_col} // ""
$$b{$sort_col}
MC/DC100%1/1
$$a{$sort_col} // ""
$$a{$sort_col}
Truth table100%2/2
A
A= $$b{$sort_col}
Aresult
11
00
Truth table100%2/2
A
A= $$a{$sort_col}
Aresult
11
00
1973 } else {
1974 4 ▶ @rc = sort { ($a->{$sort_col} // '') cmp ($b->{$sort_col} // '') } @rc;
Condition100%4/4
$$a{$sort_col} // ""
l!l
173
$$b{$sort_col} // ""
l!l
173
MC/DC100%1/1
$$a{$sort_col} // ""
$$a{$sort_col}
MC/DC100%1/1
$$b{$sort_col} // ""
$$b{$sort_col}
Truth table100%2/2
A
A= $$a{$sort_col}
Aresult
11
00
Truth table100%2/2
A
A= $$b{$sort_col}
Aresult
11
00
1975 }
1976 }
1977 146 ▶ if(defined($offset) || defined($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset or defined $limit) 18 128 146
Condition100%3/3
defined $offset or defined $limit
l!l&&r!l&&!r
99128
MC/DC100%2/2
defined $offset or defined $limit
defined $offset defined $limit
Truth table100%3/3
A or B
A= defined $offsetB= defined $limit
ABresult
1X1
011
000
1978 18 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 7 11 18
1979 18 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 14 4 18
1980 }
1981 146 ▶ @rc = @{ _apply_distinct(\@rc, $columns, $columns ? $distinct : undef) }
Branch: 2 branches
BranchTrueFalseTotal
if $columns 6 140 146
$columns ? : 6 0 6
1982 if $columns;
1983 146 return set_return(\@rc, { type => 'arrayref' });
1984 48 ▶ } elsif((scalar(keys %{$params}) == 1) && defined($params->{'entry'}) && !$self->{'no_entry'}) {
Condition83%5/6
scalar keys %{$params;} == 1 and defined $$params{"entry"} and not $$self{"no_entry"}
!ll&&!rl&&r
33015
scalar keys %{$params;} == 1 and defined $$params{"entry"}
!ll&&!rl&&r
33015
MC/DC66%2/3
scalar keys %{$params;} == 1 and defined $$params{"entry"} and not $$self{"no_entry"}
scalar keys %{$params;} == 1 defined $$params{"entry"} not $$self{"no_entry"}
Truth table75%3/4
A and B and not(C)
A= scalar keys %{$params;} == 1B= defined $$params{"entry"}C= not $$self{"no_entry"}
ABCresult
0XX0
10X0
1100
1111
1985 # exists() guard: fixate() locks all keys in the slurp hash; return []
1986 # (not [undef]) when the key is missing so callers get an empty result
1987 return set_return([], { type => 'arrayref' })
1988 15 ▶ unless exists($self->{'data'}->{$params->{'entry'}});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$self{"data"}{$$params{"entry"}} 7 8 15
1989 8 my @rc = ($self->{'data'}->{$params->{'entry'}});
1990 8 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 8 8
1991 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
1992 0 ▶ @rc = sort { ($b->{$sort_col} // '') cmp ($a->{$sort_col} // '') } @rc;
Condition0%0/4
$$b{$sort_col} // ""
l!l
00
$$a{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
1993 } else {
1994 0 ▶ @rc = sort { ($a->{$sort_col} // '') cmp ($b->{$sort_col} // '') } @rc;
Condition0%0/4
$$a{$sort_col} // ""
l!l
00
$$b{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
1995 }
1996 }
1997 8 ▶ if(defined($offset) || defined($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset or defined $limit) 0 8 8
Condition33%1/3
defined $offset or defined $limit
l!l&&r!l&&!r
008
MC/DC0%0/2
defined $offset or defined $limit
defined $offset defined $limit
Truth table33%1/3
A or B
A= defined $offsetB= defined $limit
ABresult
1X1
011
000
1998 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
1999 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2000 }
2001 0 ▶ @rc = @{ _apply_distinct(\@rc, $columns, $columns ? $distinct : undef) }
Branch: 2 branches
BranchTrueFalseTotal
if $columns 0 8 8
$columns ? : 0 0 0
2002 if $columns;
2003 8 return set_return(\@rc, { type => 'arrayref' });
2004 } elsif(ref($self->{'data'}) eq 'HASH') {
2005 # Scan in-memory hash for simple column criteria without touching DBI.
2006 # fixate() locks hash keys, so use exists() to avoid throwing on unknown columns.
2007 31 $self->_debug("$table: selectall_arrayref in-memory scan with criteria");
2008 # Pre-compute param keys once — avoids re-running keys() inside the inner
2009 # closure on every row iteration (N hash-key extractions → 1).
2010 31 my @param_keys = keys %{$params};
2011 my @rc = grep {
2012 121 my $row = $_;
2013 124 ▶ all { $self->_match_criterion(exists($row->{$_}) ? $row->{$_} : undef, $params->{$_}, $_) } @param_keys
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$_} ? : 124 0 124
2014 31 } values %{$self->{'data'}};
2015 31 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 31 31
2016 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
2017 0 ▶ @rc = sort { ($b->{$sort_col} // '') cmp ($a->{$sort_col} // '') } @rc;
Condition0%0/4
$$b{$sort_col} // ""
l!l
00
$$a{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
2018 } else {
2019 0 ▶ @rc = sort { ($a->{$sort_col} // '') cmp ($b->{$sort_col} // '') } @rc;
Condition0%0/4
$$a{$sort_col} // ""
l!l
00
$$b{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
2020 }
2021 }
2022 31 ▶ if(defined($offset) || defined($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset or defined $limit) 0 31 31
Condition33%1/3
defined $offset or defined $limit
l!l&&r!l&&!r
0031
MC/DC0%0/2
defined $offset or defined $limit
defined $offset defined $limit
Truth table33%1/3
A or B
A= defined $offsetB= defined $limit
ABresult
1X1
011
000
2023 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2024 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2025 }
2026 31 ▶ @rc = @{ _apply_distinct(\@rc, $columns, $distinct) } if $columns || $distinct;
Branch: 1 branch
BranchTrueFalseTotal
if $columns or $distinct 1 30 31
Condition66%2/3
$columns or $distinct
l!l&&r!l&&!r
1030
MC/DC50%1/2
$columns or $distinct
$columns $distinct
Truth table66%2/3
A or B
A= $columnsB= $distinct
ABresult
1X1
011
000
2027 31 return set_return(\@rc, { type => 'arrayref' });
2028 ▶ } elsif(ref($self->{'data'}) eq 'ARRAY' && !$self->{'_dbh'}{$table}) {
Condition66%2/3
ref $$self{"data"} eq "ARRAY" and not $$self{"_dbh"}{$table}
!ll&&!rl&&r
011
MC/DC50%1/2
ref $$self{"data"} eq "ARRAY" and not $$self{"_dbh"}{$table}
ref $$self{"data"} eq "ARRAY" not $$self{"_dbh"}{$table}
Truth table66%2/3
A and not(B)
A= ref $$self{"data"} eq "ARRAY"B= not $$self{"_dbh"}{$table}
ABresult
0X0
100
111
2029 # In-memory scan for array-backed no_entry stores (JSON, XLSX, HTML URL)
2030 # where there is no DBI handle. Mirrors the equivalent path in count().
2031 1 $self->_debug("$table: selectall_arrayref in-memory array scan with criteria");
2032 1 my @param_keys = keys %{$params};
2033 my @rc = grep {
2034 3 my $row = $_;
2035 3 ▶ all { $self->_match_criterion(exists($row->{$_}) ? $row->{$_} : undef, $params->{$_}, $_) } @param_keys
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$_} ? : 3 0 3
2036 1 } @{$self->{'data'}};
2037 1 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 1 1
2038 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
2039 0 ▶ @rc = sort { ($b->{$sort_col} // '') cmp ($a->{$sort_col} // '') } @rc;
Condition0%0/4
$$b{$sort_col} // ""
l!l
00
$$a{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
2040 } else {
2041 0 ▶ @rc = sort { ($a->{$sort_col} // '') cmp ($b->{$sort_col} // '') } @rc;
Condition0%0/4
$$a{$sort_col} // ""
l!l
00
$$b{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
2042 }
2043 }
2044 1 ▶ if(defined($offset) || defined($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset or defined $limit) 0 1 1
Condition33%1/3
defined $offset or defined $limit
l!l&&r!l&&!r
001
MC/DC0%0/2
defined $offset or defined $limit
defined $offset defined $limit
Truth table33%1/3
A or B
A= defined $offsetB= defined $limit
ABresult
1X1
011
000
2045 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2046 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2047 }
2048 0 ▶ @rc = @{ _apply_distinct(\@rc, $columns, $distinct) } if $columns || $distinct;
Branch: 1 branch
BranchTrueFalseTotal
if $columns or $distinct 0 1 1
Condition33%1/3
$columns or $distinct
l!l&&r!l&&!r
001
MC/DC0%0/2
$columns or $distinct
$columns $distinct
Truth table33%1/3
A or B
A= $columnsB= $distinct
ABresult
1X1
011
000
2049 1 return set_return(\@rc, { type => 'arrayref' });
2050 }
2051 }
2052  
2053 # Redis backend: when _open found no data (key doesn't exist or is empty),
2054 # avoid crashing on the DBI path which has no handle for a Redis connection.
2055 return set_return([], { type => 'arrayref' })
2056 142 ▶ if ($self->{'type'} // '') eq 'Redis';
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"type"} // "") eq "Redis" 0 142 142
Condition50%1/2
$$self{"type"} // ""
l!l
1420
MC/DC0%0/1
$$self{"type"} // ""
$$self{"type"}
Truth table50%1/2
A
A= $$self{"type"}
Aresult
11
00
2057  
2058 142 my ($where, $wargs) = $self->_build_where($params);
2059 133 my @query_args = @{$wargs};
2060  
2061 133 my $select_expr;
2062 133 ▶ if($distinct) {
Branch: 2 branches
BranchTrueFalseTotal
if ($distinct) { } 4 129 133
elsif ($columns) { } 1 128 129
2063 4 ▶ if($columns) {
Branch: 1 branch
BranchTrueFalseTotal
if ($columns) { } 3 1 4
2064 3 $select_expr = 'SELECT DISTINCT ' . join(', ', @{$columns});
2065 } else {
2066 1 $select_expr = 'SELECT DISTINCT *';
2067 }
2068 } elsif($columns) {
2069 1 $select_expr = 'SELECT ' . join(', ', @{$columns});
2070 } else {
2071 128 $select_expr = 'SELECT *';
2072 }
2073 133 my $query = "$select_expr FROM $table";
2074 133 ▶ $query .= " $join_clause" if $join_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $join_clause 20 113 133
2075 133 ▶ if($join_clause) {
Branch: 2 branches
BranchTrueFalseTotal
if ($join_clause) { } 20 113 133
elsif ($$self{'type'} eq 'CSV' and not $$self{'no_entry'}) { } 12 101 113
2076 20 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 6 14 20
2077 ▶ } elsif(($self->{'type'} eq 'CSV') && !$self->{'no_entry'}) {
Condition100%3/3
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
!ll&&!rl&&r
891212
MC/DC100%2/2
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
$$self{"type"} eq "CSV" not $$self{"no_entry"}
Truth table100%3/3
A and not(B)
A= $$self{"type"} eq "CSV"B= not $$self{"no_entry"}
ABresult
0X0
100
111
2078 12 my $id = $self->{'id'};
2079 12 $query .= " WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
2080 12 ▶ $query .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 5 7 12
2081 } else {
2082 101 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 49 52 101
2083 }
2084 133 ▶ if(defined $sort_col) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort_col) { } 0 133 133
elsif (not $$self{'no_entry'}) { } 34 99 133
2085 0 $query .= " ORDER BY $sort_col $sort_dir";
2086 } elsif(!$self->{'no_entry'}) {
2087 34 $query .= ' ORDER BY ' . $self->{'id'};
2088 }
2089 133 ▶ if(defined($limit)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $limit) { } 0 133 133
elsif (defined $offset) { } 0 133 133
2090 0 $query .= ' LIMIT ?';
2091 0 push @query_args, $limit;
2092 } elsif(defined($offset)) {
2093 # SQLite requires a LIMIT clause when OFFSET is present; -1 means no limit
2094 0 my $dbh = $self->{'_dbh'}{$table};
2095 $query .= ' LIMIT -1'
2096 if ($dbh && (($dbh->{Driver}{Name} // '') eq 'SQLite'))
2097 0 ▶ || (($self->{'_dialect'} // '') eq 'sqlite');
Branch: 1 branch
BranchTrueFalseTotal
if $dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite" 0 0 0
Condition0%0/10
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite"
l!l&&r!l&&!r
000
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite"
!ll&&!rl&&r
000
$$dbh{"Driver"}{"Name"} // ""
l!l
00
$$self{"_dialect"} // ""
l!l
00
MC/DC0%0/3
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite"
$dbh $$dbh{"Driver"}{"Name"} $$self{"_dialect"}
Truth table0%0/5
A and B or C
A= $dbhB= $$dbh{"Driver"}{"Name"}C= $$self{"_dialect"}
ABCresult
11X1
0X11
1011
0X00
1000
2098 }
2099 133 ▶ if(defined($offset)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 0 133 133
2100 0 $query .= ' OFFSET ?';
2101 0 push @query_args, $offset;
2102 }
2103  
2104 133 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 56 77 133
2105 56 $self->_debug("selectall_arrayref $query: ", join(', ', @query_args));
2106 } else {
2107 77 $self->_debug("selectall_arrayref $query");
2108 }
2109  
2110 133 my $key;
2111 my $c;
2112 133 ▶ if($c = $self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c = $$self{'cache'}) { } 17 116 133
2113 17 $key = ref($self) . "::$query array";
2114 17 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) 2 15 17
2115 2 $key .= ' ' . join(', ', @query_args);
2116 }
2117 17 $self->_debug("cache key = '$key'");
2118 17 ▶ if(my $rc = $c->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $c->get($key)) 8 9 17
2119 8 $self->_debug('cache HIT');
2120 8 return $rc; # We stored a ref to the array
2121  
2122 # This use of a temporary variable is to avoid
2123 # "Implicit scalar context for array in return"
2124 # my @rc = @{$rc};
2125 # return @rc;
2126 }
2127 9 $self->_debug('cache MISS');
2128 } else {
2129 116 $self->_debug('cache not used');
2130 }
2131  
2132 125 ▶ if(my $sth = $self->{'_dbh'}{$table}->prepare_cached($query)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sth = $$self{"_dbh"}{$table}->prepare_cached($query)) 124 0 124
2133 124 ▶ $sth->execute(@query_args) || croak("$query: @query_args");
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@query_args) or croak("${query}: @query_args") 119 0 119
2134  
2135 119 my $rc;
2136 119 ▶ while(my $href = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $href = $sth->fetchrow_hashref) 316 119 435
2137 316 push @{$rc}, $href;
2138 }
2139  
2140 119 ▶ $c->set($key, $rc, $self->{'cache_duration'}) if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 9 110 119
2141  
2142 119 ▶ if($rc && !$no_fixate) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc and not $no_fixate) 104 15 119
Condition100%3/3
$rc and not $no_fixate
!ll&&!rl&&r
132104
MC/DC100%2/2
$rc and not $no_fixate
$rc not $no_fixate
Truth table100%3/3
A and not(B)
A= $rcB= not $no_fixate
ABresult
0X0
100
111
2143 104 $self->_fixate($rc);
2144 }
2145  
2146 119 return $rc;
2147 }
2148 0 $self->_warn("selectall_arrayref failure on $query: @query_args");
2149 0 croak("$query: @query_args");
2150 }
2151  
2152 =head2 selectall_hashref
2153  
2154 Deprecated alias for L</selectall_arrayref>. Use C<selectall_arrayref> in
2155 new code.
2156  
2157 =cut
2158  
2159 sub selectall_hashref
2160 8 ▶{
Subroutine selectall_hashref: called CC=1 SCAR=0.0
Pod documented
2161 8 my $self = shift;
2162 8 return $self->selectall_arrayref(@_);
2163 }
2164  
2165 =head2 each_row
2166  
2167 $db->each_row(\&callback);
2168 $db->each_row(\&callback, status => 'active');
2169 $db->each_row(\&callback, sort_by => 'name', limit => 100, offset => 20);
2170  
2171 Iterates over matching rows one at a time, calling C<\&callback> once per
2172 row with the row hashref as the sole argument. Uses B<constant memory> on
2173 the SQL path: rows are fetched from the database one at a time via
2174 C<fetchrow_hashref> without materialising the full result array. On the
2175 slurp/in-memory path data is already in RAM, so memory use is equivalent to
2176 L</selectall_arrayref>.
2177  
2178 Accepts the same criteria, C<join>, C<sort_by>, C<limit>, and C<offset>
2179 parameters as L</selectall_arrayref>.
2180  
2181 Returns the number of rows passed to C<\&callback>.
2182  
2183 Exceptions raised inside C<\&callback> abort iteration and propagate to
2184 the caller; the DBI statement handle is left in a valid state (C<finish()>
2185 is called on exception).
2186  
2187 B<Note:> rows on the SQL path are not fixated (made read-only) because they
2188 are discarded after each callback invocation. Slurp-path rows are already
2189 fixated from the initial load.
2190  
2191 =head3 API SPECIFICATION
2192  
2193 =head4 Arguments
2194  
2195 CodeRef # required: callback receiving one row hashref per call
2196 %criteria # optional: same criteria syntax as selectall_arrayref
2197 join => HashRef | ArrayRef # optional join spec(s)
2198 sort_by => Str | ArrayRef # optional sort column
2199 limit => Int # optional: max rows to visit
2200 offset => Int # optional: rows to skip
2201  
2202 =head4 Returns
2203  
2204 Int (>= 0)
2205  
2206 The number of rows visited (i.e. the number of times the callback
2207 was called). Any exception thrown inside the callback is re-thrown
2208 after the DBI statement handle is properly finished.
2209  
2210 =cut
2211  
2212 sub each_row
2213 55 ▶{
Subroutine each_row: called CC=73 SCAR=63.7
Pod documented
2214 55 my $self = shift;
2215 55 my $callback = shift;
2216  
2217 55 ▶ Carp::croak(ref($self), ': each_row: callback must be a code reference')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $callback eq "CODE" 11 44 55
2218 unless ref($callback) eq 'CODE';
2219  
2220 44 $self->_open_table({});
2221  
2222 44 my $params;
2223  
2224 44 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 0 44 44
2225 0 ▶ $params = Params::Get::get_params(undef, \@_) // {};
Condition0%0/2
Params::Get::get_params(undef, \@_) // {}
l!l
00
MC/DC0%0/1
Params::Get::get_params(undef, \@_) // {}
Params::Get::get_params(undef, \@_)
Truth table0%0/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
2226 0 my $bl = delete $params->{'limit'};
2227 0 my $bo = delete $params->{'offset'};
2228 0 my ($bsc, $bsd) = _parse_sort_by(delete($params->{'sort_by'}), 'each_row');
2229 0 ▶ if(defined($bl) && $bl !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bl and not $bl =~ /\A\d+\z/) 0 0 0
Condition0%0/3
defined $bl and not $bl =~ /\A\d+\z/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $bl and not $bl =~ /\A\d+\z/
defined $bl not $bl =~ /\A\d+\z/
Truth table0%0/3
A and not(B)
A= defined $blB= not $bl =~ /\A\d+\z/
ABresult
0X0
100
111
2230 0 Carp::carp('each_row: limit must be a non-negative integer, ignoring');
2231 0 undef $bl;
2232 }
2233 0 ▶ if(defined($bo) && $bo !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bo and not $bo =~ /\A\d+\z/) 0 0 0
Condition0%0/3
defined $bo and not $bo =~ /\A\d+\z/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $bo and not $bo =~ /\A\d+\z/
defined $bo not $bo =~ /\A\d+\z/
Truth table0%0/3
A and not(B)
A= defined $boB= not $bo =~ /\A\d+\z/
ABresult
0X0
100
111
2234 0 Carp::carp('each_row: offset must be a non-negative integer, ignoring');
2235 0 undef $bo;
2236 }
2237 0 $params = $self->_merge_base_criteria($params);
2238 0 my $rows = $self->_scan_berkeley($params);
2239 0 ▶ if(defined $bsc) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bsc) 0 0 0
2240 0 ▶ if($bsd eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($bsd eq 'DESC') { } 0 0 0
2241 0 ▶ @{$rows} = sort { ($b->{$bsc} // '') cmp ($a->{$bsc} // '') } @{$rows};
Condition0%0/4
$$b{$bsc} // ""
l!l
00
$$a{$bsc} // ""
l!l
00
MC/DC0%0/1
$$b{$bsc} // ""
$$b{$bsc}
MC/DC0%0/1
$$a{$bsc} // ""
$$a{$bsc}
Truth table0%0/2
A
A= $$b{$bsc}
Aresult
11
00
Truth table0%0/2
A
A= $$a{$bsc}
Aresult
11
00
2242 } else {
2243 0 ▶ @{$rows} = sort { ($a->{$bsc} // '') cmp ($b->{$bsc} // '') } @{$rows};
Condition0%0/4
$$a{$bsc} // ""
l!l
00
$$b{$bsc} // ""
l!l
00
MC/DC0%0/1
$$a{$bsc} // ""
$$a{$bsc}
MC/DC0%0/1
$$b{$bsc} // ""
$$b{$bsc}
Truth table0%0/2
A
A= $$a{$bsc}
Aresult
11
00
Truth table0%0/2
A
A= $$b{$bsc}
Aresult
11
00
2244 }
2245 }
2246 0 ▶ if(defined($bl) || defined($bo)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bl or defined $bo) 0 0 0
Condition0%0/3
defined $bl or defined $bo
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $bl or defined $bo
defined $bl defined $bo
Truth table0%0/3
A or B
A= defined $blB= defined $bo
ABresult
1X1
011
000
2247 0 ▶ splice(@{$rows}, 0, int($bo)) if $bo;
Branch: 1 branch
BranchTrueFalseTotal
if $bo 0 0 0
2248 0 ▶ splice(@{$rows}, int($bl)) if defined $bl;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bl 0 0 0
2249 }
2250 0 my $n = 0;
2251 0 for my $row (@{$rows}) {
2252 0 local $_;
2253 0 $callback->($row);
2254 0 $n++;
2255 }
2256 0 return $n;
2257 }
2258  
2259 44 ▶ if($self->{'no_entry'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 3 41 44
elsif (scalar @_) { } 13 28 41
2260 3 $params = Params::Get::get_params(undef, \@_);
2261 } elsif(scalar(@_)) {
2262 13 $params = Params::Get::get_params('entry', @_);
2263 }
2264  
2265 44 my $table = $self->_open_table($params);
2266  
2267 44 ▶ $params //= {};
Condition100%2/2
$params //= {}
l!l
1331
MC/DC100%1/1
$params //= {}
$params
Truth table100%2/2
A
A= $params
Aresult
11
00
2268  
2269 44 my $join_clause = '';
2270 44 ▶ if(my $join_spec = delete $params->{'join'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $join_spec = delete $params->{"join"}) 0 44 44
2271 0 $join_clause = $self->_build_joins($join_spec);
2272 }
2273  
2274 44 my $limit = delete $params->{'limit'};
2275 44 my $offset = delete $params->{'offset'};
2276 44 ▶ if(defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 3 41 44
2277 3 ▶ if($limit !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $limit =~ /\A\d+\z/) { } 0 3 3
2278 0 Carp::carp('each_row: limit must be a non-negative integer, ignoring');
2279 0 undef $limit;
2280 } else {
2281 3 $limit = int($limit);
2282 }
2283 }
2284 44 ▶ if(defined $offset) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 2 42 44
2285 2 ▶ if($offset !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $offset =~ /\A\d+\z/) { } 0 2 2
2286 0 Carp::carp('each_row: offset must be a non-negative integer, ignoring');
2287 0 undef $offset;
2288 } else {
2289 2 $offset = int($offset);
2290 }
2291 }
2292  
2293 44 my ($sort_col, $sort_dir) = _parse_sort_by(delete($params->{'sort_by'}), 'each_row');
2294 44 $params = $self->_merge_base_criteria($params);
2295  
2296 44 ▶ if(!$join_clause && $self->{'data'} && !$self->_has_complex_criteria($params)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $join_clause and $$self{"data"} and not $self->_has_complex_criteria($params)) 29 15 44
Condition66%4/6
not $join_clause and $$self{"data"} and not $self->_has_complex_criteria($params)
!ll&&!rl&&r
15029
not $join_clause and $$self{"data"}
!ll&&!rl&&r
01529
MC/DC33%1/3
not $join_clause and $$self{"data"} and not $self->_has_complex_criteria($params)
not $join_clause $$self{"data"} not $self->_has_complex_criteria($params)
Truth table50%2/4
not(A) and B and not(C)
A= not $join_clauseB= $$self{"data"}C= not $self->_has_complex_criteria($params)
ABCresult
0XX0
10X0
1100
1111
2297 29 my @rc;
2298 29 ▶ if(scalar(keys %{$params}) == 0) {
Branch: 4 branches
BranchTrueFalseTotal
if (scalar keys %{$params;} == 0) { } 21 8 29
elsif (scalar keys %{$params;} == 1 and defined $$params{'entry'} and not $$self{'no_entry'}) { } 5 3 8
elsif (ref $$self{'data'} eq 'HASH') { } 3 0 3
elsif (ref $$self{'data'} eq 'ARRAY' and not $$self{'_dbh'}{$table}) { } 0 0 0
2299 21 ▶ @rc = ref($self->{'data'}) eq 'HASH' ? values %{$self->{'data'}} : @{$self->{'data'}};
Branch: 1 branch
BranchTrueFalseTotal
ref $$self{'data'} eq 'HASH' ? : 20 1 21
2300 8 ▶ } elsif((scalar(keys %{$params}) == 1) && defined($params->{'entry'}) && !$self->{'no_entry'}) {
Condition66%4/6
scalar keys %{$params;} == 1 and defined $$params{"entry"} and not $$self{"no_entry"}
!ll&&!rl&&r
305
scalar keys %{$params;} == 1 and defined $$params{"entry"}
!ll&&!rl&&r
035
MC/DC33%1/3
scalar keys %{$params;} == 1 and defined $$params{"entry"} and not $$self{"no_entry"}
scalar keys %{$params;} == 1 defined $$params{"entry"} not $$self{"no_entry"}
Truth table50%2/4
A and B and not(C)
A= scalar keys %{$params;} == 1B= defined $$params{"entry"}C= not $$self{"no_entry"}
ABCresult
0XX0
10X0
1100
1111
2301 5 ▶ return 0 unless exists($self->{'data'}->{$params->{'entry'}});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$self{"data"}{$$params{"entry"}} 2 3 5
2302 3 @rc = ($self->{'data'}->{$params->{'entry'}});
2303 } elsif(ref($self->{'data'}) eq 'HASH') {
2304 3 $self->_debug("$table: each_row in-memory scan with criteria");
2305 3 my @param_keys = keys %{$params};
2306 @rc = grep {
2307 12 my $row = $_;
2308 12 ▶ all { $self->_match_criterion(exists($row->{$_}) ? $row->{$_} : undef, $params->{$_}, $_) } @param_keys
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$_} ? : 12 0 12
2309 3 } values %{$self->{'data'}};
2310 ▶ } elsif(ref($self->{'data'}) eq 'ARRAY' && !$self->{'_dbh'}{$table}) {
Condition0%0/3
ref $$self{"data"} eq "ARRAY" and not $$self{"_dbh"}{$table}
!ll&&!rl&&r
000
MC/DC0%0/2
ref $$self{"data"} eq "ARRAY" and not $$self{"_dbh"}{$table}
ref $$self{"data"} eq "ARRAY" not $$self{"_dbh"}{$table}
Truth table0%0/3
A and not(B)
A= ref $$self{"data"} eq "ARRAY"B= not $$self{"_dbh"}{$table}
ABresult
0X0
100
111
2311 0 $self->_debug("$table: each_row in-memory array scan with criteria");
2312 0 my @param_keys = keys %{$params};
2313 @rc = grep {
2314 0 my $row = $_;
2315 0 ▶ all { $self->_match_criterion(exists($row->{$_}) ? $row->{$_} : undef, $params->{$_}, $_) } @param_keys
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$_} ? : 0 0 0
2316 0 } @{$self->{'data'}};
2317 }
2318 27 ▶ if(@rc) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rc) 27 0 27
2319 27 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 7 20 27
2320 7 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 2 5 7
2321 2 ▶ @rc = sort { ($b->{$sort_col} // '') cmp ($a->{$sort_col} // '') } @rc;
Condition75%3/4
$$b{$sort_col} // ""
l!l
81
$$a{$sort_col} // ""
l!l
90
MC/DC100%1/1
$$b{$sort_col} // ""
$$b{$sort_col}
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
Truth table100%2/2
A
A= $$b{$sort_col}
Aresult
11
00
Truth table50%1/2
A
A= $$a{$sort_col}
Aresult
11
00
2322 } else {
2323 5 ▶ @rc = sort { ($a->{$sort_col} // '') cmp ($b->{$sort_col} // '') } @rc;
Condition50%2/4
$$a{$sort_col} // ""
l!l
230
$$b{$sort_col} // ""
l!l
230
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
Truth table50%1/2
A
A= $$a{$sort_col}
Aresult
11
00
Truth table50%1/2
A
A= $$b{$sort_col}
Aresult
11
00
2324 }
2325 }
2326 27 ▶ if(defined($offset) || defined($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset or defined $limit) 4 23 27
Condition100%3/3
defined $offset or defined $limit
l!l&&r!l&&!r
2223
MC/DC100%2/2
defined $offset or defined $limit
defined $offset defined $limit
Truth table100%3/3
A or B
A= defined $offsetB= defined $limit
ABresult
1X1
011
000
2327 4 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 2 2 4
2328 4 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 3 1 4
2329 }
2330 }
2331 27 my $n = 0;
2332 27 for my $row (@rc) {
2333 62 local $_;
2334 62 $callback->($row);
2335 54 $n++;
2336 }
2337 19 return $n;
2338 }
2339  
2340 15 my ($where, $wargs) = $self->_build_where($params);
2341 15 my @query_args = @{$wargs};
2342  
2343 15 my $query = "SELECT * FROM $table";
2344 15 ▶ $query .= " $join_clause" if $join_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $join_clause 0 15 15
2345 15 ▶ if($join_clause) {
Branch: 2 branches
BranchTrueFalseTotal
if ($join_clause) { } 0 15 15
elsif ($$self{'type'} eq 'CSV' and not $$self{'no_entry'}) { } 5 10 15
2346 0 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 0 0
2347 ▶ } elsif(($self->{'type'} eq 'CSV') && !$self->{'no_entry'}) {
Condition66%2/3
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
!ll&&!rl&&r
1005
MC/DC50%1/2
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
$$self{"type"} eq "CSV" not $$self{"no_entry"}
Truth table66%2/3
A and not(B)
A= $$self{"type"} eq "CSV"B= not $$self{"no_entry"}
ABresult
0X0
100
111
2348 5 my $id = $self->{'id'};
2349 5 $query .= " WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
2350 5 ▶ $query .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 5 5
2351 } else {
2352 10 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 10 10
2353 }
2354 15 ▶ if(defined $sort_col) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort_col) { } 0 15 15
elsif (not $$self{'no_entry'}) { } 13 2 15
2355 0 $query .= " ORDER BY $sort_col $sort_dir";
2356 } elsif(!$self->{'no_entry'}) {
2357 13 $query .= ' ORDER BY ' . $self->{'id'};
2358 }
2359 15 ▶ if(defined($limit)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $limit) { } 0 15 15
elsif (defined $offset) { } 0 15 15
2360 0 $query .= ' LIMIT ?';
2361 0 push @query_args, $limit;
2362 } elsif(defined($offset)) {
2363 0 my $dbh = $self->{'_dbh'}{$table};
2364 $query .= ' LIMIT -1'
2365 if ($dbh && (($dbh->{Driver}{Name} // '') eq 'SQLite'))
2366 0 ▶ || (($self->{'_dialect'} // '') eq 'sqlite');
Branch: 1 branch
BranchTrueFalseTotal
if $dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite" 0 0 0
Condition0%0/10
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite"
l!l&&r!l&&!r
000
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite"
!ll&&!rl&&r
000
$$dbh{"Driver"}{"Name"} // ""
l!l
00
$$self{"_dialect"} // ""
l!l
00
MC/DC0%0/3
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite"
$dbh $$dbh{"Driver"}{"Name"} $$self{"_dialect"}
Truth table0%0/5
A and B or C
A= $dbhB= $$dbh{"Driver"}{"Name"}C= $$self{"_dialect"}
ABCresult
11X1
0X11
1011
0X00
1000
2367 }
2368 15 ▶ if(defined($offset)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 0 15 15
2369 0 $query .= ' OFFSET ?';
2370 0 push @query_args, $offset;
2371 }
2372  
2373 15 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 0 15 15
2374 0 $self->_debug("each_row $query: ", join(', ', @query_args));
2375 } else {
2376 15 $self->_debug("each_row $query");
2377 }
2378  
2379 my $sth = $self->{'_dbh'}{$table}->prepare_cached($query)
2380 15 ▶ or Carp::croak(ref($self), ": each_row prepare failed: ", $self->{'_dbh'}{$table}->errstr());
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $$self{"_dbh"}{$table}->prepare_cached($query) or Carp::croak(ref $self, ": each_row prepare failed: ", $$self{"_dbh"}{$table}->errstr) 15 0 15
2381 15 ▶ $sth->execute(@query_args) || croak("$query: @query_args");
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@query_args) or croak("${query}: @query_args") 15 0 15
2382  
2383 15 my $n = 0;
2384 15 eval {
2385 15 ▶ while(my $row = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 25 9 34
2386 25 local $_;
2387 25 $callback->($row);
2388 19 $n++;
2389 }
2390 };
2391 15 ▶ if(my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 6 9 15
2392 6 $sth->finish();
2393 6 die $err;
2394 }
2395 9 return $n;
2396 }
2397  
2398 =head2 selectall_array
2399  
2400 Similar to L</selectall_arrayref> but returns a list of hash references
2401 rather than a reference to an array.
2402  
2403 my @rows = $db->selectall_array(status => 'active');
2404  
2405 In B<scalar context> it applies C<LIMIT 1> and returns just the first
2406 matching hash reference - making it more efficient than C<selectall_arrayref>
2407 when you only need one row. In B<list context> all matching rows are returned.
2408  
2409 Accepts the same criteria, C<join>, C<limit>, C<offset>, and C<sort_by>
2410 parameters as L</selectall_arrayref>. When C<limit> is given in scalar context
2411 it overrides the implicit C<LIMIT 1>.
2412  
2413 =cut
2414  
2415 sub selectall_array
2416 76 ▶{
Subroutine selectall_array: called CC=105 SCAR=73.6
Pod documented
2417 76 my $self = shift;
2418  
2419 76 $self->_open_table({});
2420  
2421 76 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 3 73 76
2422 3 ▶ my $params = Params::Get::get_params(undef, \@_) // {};
Condition50%1/2
Params::Get::get_params(undef, \@_) // {}
l!l
03
MC/DC0%0/1
Params::Get::get_params(undef, \@_) // {}
Params::Get::get_params(undef, \@_)
Truth table50%1/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
2423 3 my $bl = delete $params->{'limit'};
2424 3 my $bo = delete $params->{'offset'};
2425 3 delete $params->{'no_fixate'};
2426 3 my ($bsc, $bsd) = _parse_sort_by(delete($params->{'sort_by'}), 'selectall_array');
2427 3 ▶ if(defined($bl) && $bl !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bl and not $bl =~ /\A\d+\z/) 0 3 3
Condition33%1/3
defined $bl and not $bl =~ /\A\d+\z/
!ll&&!rl&&r
300
MC/DC0%0/2
defined $bl and not $bl =~ /\A\d+\z/
defined $bl not $bl =~ /\A\d+\z/
Truth table33%1/3
A and not(B)
A= defined $blB= not $bl =~ /\A\d+\z/
ABresult
0X0
100
111
2428 0 Carp::carp('selectall_array: limit must be a non-negative integer, ignoring');
2429 0 undef $bl;
2430 }
2431 3 ▶ if(defined($bo) && $bo !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bo and not $bo =~ /\A\d+\z/) 0 3 3
Condition33%1/3
defined $bo and not $bo =~ /\A\d+\z/
!ll&&!rl&&r
300
MC/DC0%0/2
defined $bo and not $bo =~ /\A\d+\z/
defined $bo not $bo =~ /\A\d+\z/
Truth table33%1/3
A and not(B)
A= defined $boB= not $bo =~ /\A\d+\z/
ABresult
0X0
100
111
2432 0 Carp::carp('selectall_array: offset must be a non-negative integer, ignoring');
2433 0 undef $bo;
2434 }
2435 3 $params = $self->_merge_base_criteria($params);
2436 3 my $rows = $self->_scan_berkeley($params);
2437 3 ▶ if(defined $bsc) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bsc) 0 3 3
2438 0 ▶ if($bsd eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($bsd eq 'DESC') { } 0 0 0
2439 0 ▶ @{$rows} = sort { ($b->{$bsc} // '') cmp ($a->{$bsc} // '') } @{$rows};
Condition0%0/4
$$b{$bsc} // ""
l!l
00
$$a{$bsc} // ""
l!l
00
MC/DC0%0/1
$$b{$bsc} // ""
$$b{$bsc}
MC/DC0%0/1
$$a{$bsc} // ""
$$a{$bsc}
Truth table0%0/2
A
A= $$b{$bsc}
Aresult
11
00
Truth table0%0/2
A
A= $$a{$bsc}
Aresult
11
00
2440 } else {
2441 0 ▶ @{$rows} = sort { ($a->{$bsc} // '') cmp ($b->{$bsc} // '') } @{$rows};
Condition0%0/4
$$a{$bsc} // ""
l!l
00
$$b{$bsc} // ""
l!l
00
MC/DC0%0/1
$$a{$bsc} // ""
$$a{$bsc}
MC/DC0%0/1
$$b{$bsc} // ""
$$b{$bsc}
Truth table0%0/2
A
A= $$a{$bsc}
Aresult
11
00
Truth table0%0/2
A
A= $$b{$bsc}
Aresult
11
00
2442 }
2443 }
2444 3 ▶ if(defined($bl) || defined($bo)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bl or defined $bo) 0 3 3
Condition33%1/3
defined $bl or defined $bo
l!l&&r!l&&!r
003
MC/DC0%0/2
defined $bl or defined $bo
defined $bl defined $bo
Truth table33%1/3
A or B
A= defined $blB= defined $bo
ABresult
1X1
011
000
2445 0 ▶ splice(@{$rows}, 0, int($bo)) if $bo;
Branch: 1 branch
BranchTrueFalseTotal
if $bo 0 0 0
2446 0 ▶ splice(@{$rows}, int($bl)) if defined $bl;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bl 0 0 0
2447 }
2448 3 ▶ return wantarray ? @{$rows} : $rows->[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 1 3
2449 }
2450  
2451 73 my $params = Params::Get::get_params(undef, \@_);
2452 73 my $table = $self->_open_table($params);
2453  
2454 72 ▶ $params //= {};
Condition100%2/2
$params //= {}
l!l
2646
MC/DC100%1/1
$params //= {}
$params
Truth table100%2/2
A
A= $params
Aresult
11
00
2455 72 my $join_clause = '';
2456 72 ▶ if(my $join_spec = delete $params->{'join'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $join_spec = delete $params->{"join"}) 1 71 72
2457 1 $join_clause = $self->_build_joins($join_spec);
2458 }
2459  
2460 72 my $limit = delete $params->{'limit'};
2461 72 my $offset = delete $params->{'offset'};
2462 72 ▶ if(defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 0 72 72
2463 0 ▶ if($limit !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $limit =~ /\A\d+\z/) { } 0 0 0
2464 0 Carp::carp('selectall_array: limit must be a non-negative integer, ignoring');
2465 0 undef $limit;
2466 } else {
2467 0 $limit = int($limit);
2468 }
2469 }
2470 72 ▶ if(defined $offset) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 0 72 72
2471 0 ▶ if($offset !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $offset =~ /\A\d+\z/) { } 0 0 0
2472 0 Carp::carp('selectall_array: offset must be a non-negative integer, ignoring');
2473 0 undef $offset;
2474 } else {
2475 0 $offset = int($offset);
2476 }
2477 }
2478  
2479 72 my ($sort_col, $sort_dir) = _parse_sort_by(delete($params->{'sort_by'}), 'selectall_array');
2480 72 ▶ my $no_fixate = delete($params->{'no_fixate'}) // $self->{'no_fixate'};
Condition66%2/3
delete $params->{"no_fixate"} // $$self{"no_fixate"}
l!l&&r!l&&!r
1710
MC/DC0%0/2
delete $params->{"no_fixate"} // $$self{"no_fixate"}
delete $params->{"no_fixate"} $$self{"no_fixate"}
Truth table66%2/3
A // B
A= delete $params->{"no_fixate"}B= $$self{"no_fixate"}
ABresult
1X1
011
000
2481 72 $params = $self->_merge_base_criteria($params);
2482  
2483 72 ▶ if(!$join_clause && $self->{'data'} && !$self->_has_complex_criteria($params)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $join_clause and $$self{"data"} and not $self->_has_complex_criteria($params)) 47 25 72
Condition83%5/6
not $join_clause and $$self{"data"} and not $self->_has_complex_criteria($params)
!ll&&!rl&&r
25047
not $join_clause and $$self{"data"}
!ll&&!rl&&r
12447
MC/DC66%2/3
not $join_clause and $$self{"data"} and not $self->_has_complex_criteria($params)
not $join_clause $$self{"data"} not $self->_has_complex_criteria($params)
Truth table75%3/4
not(A) and B and not(C)
A= not $join_clauseB= $$self{"data"}C= not $self->_has_complex_criteria($params)
ABCresult
0XX0
10X0
1100
1111
2484 47 ▶ if(scalar(keys %{$params}) == 0) {
Branch: 4 branches
BranchTrueFalseTotal
if (scalar keys %{$params;} == 0) { } 31 16 47
elsif (scalar keys %{$params;} == 1 and defined $$params{'entry'} and not $$self{'no_entry'}) { } 6 10 16
elsif (ref $$self{'data'} eq 'HASH') { } 10 0 10
elsif (ref $$self{'data'} eq 'ARRAY' and not $$self{'_dbh'}{$table}) { } 0 0 0
2485 31 $self->_trace("$table: selectall_array fast track return");
2486 my @rc = ref($self->{'data'}) eq 'HASH'
2487 30 ? values %{$self->{'data'}}
2488 31 ▶ : @{$self->{'data'}};
Branch: 1 branch
BranchTrueFalseTotal
ref $$self{'data'} eq 'HASH' ? : 30 1 31
2489 31 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 31 31
2490 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
2491 0 ▶ @rc = sort { ($b->{$sort_col} // '') cmp ($a->{$sort_col} // '') } @rc;
Condition0%0/4
$$b{$sort_col} // ""
l!l
00
$$a{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
2492 } else {
2493 0 ▶ @rc = sort { ($a->{$sort_col} // '') cmp ($b->{$sort_col} // '') } @rc;
Condition0%0/4
$$a{$sort_col} // ""
l!l
00
$$b{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
2494 }
2495 }
2496 31 ▶ if(defined($offset) || defined($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset or defined $limit) 0 31 31
Condition33%1/3
defined $offset or defined $limit
l!l&&r!l&&!r
0031
MC/DC0%0/2
defined $offset or defined $limit
defined $offset defined $limit
Truth table33%1/3
A or B
A= defined $offsetB= defined $limit
ABresult
1X1
011
000
2497 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2498 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2499 }
2500 31 return @rc;
2501 16 ▶ } elsif((scalar(keys %{$params}) == 1) && defined($params->{'entry'}) && !$self->{'no_entry'}) {
Condition66%4/6
scalar keys %{$params;} == 1 and defined $$params{"entry"} and not $$self{"no_entry"}
!ll&&!rl&&r
1006
scalar keys %{$params;} == 1 and defined $$params{"entry"}
!ll&&!rl&&r
0106
MC/DC33%1/3
scalar keys %{$params;} == 1 and defined $$params{"entry"} and not $$self{"no_entry"}
scalar keys %{$params;} == 1 defined $$params{"entry"} not $$self{"no_entry"}
Truth table50%2/4
A and B and not(C)
A= scalar keys %{$params;} == 1B= defined $$params{"entry"}C= not $$self{"no_entry"}
ABCresult
0XX0
10X0
1100
1111
2502 # exists() guard: fixate() locks all keys; return empty list (not undef)
2503 # for a missing entry so callers in list context get 0 elements not 1
2504 6 ▶ return () unless exists($self->{'data'}->{$params->{'entry'}});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$self{"data"}{$$params{"entry"}} 3 3 6
2505 3 ▶ if(defined($offset) || defined($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset or defined $limit) 0 3 3
Condition33%1/3
defined $offset or defined $limit
l!l&&r!l&&!r
003
MC/DC0%0/2
defined $offset or defined $limit
defined $offset defined $limit
Truth table33%1/3
A or B
A= defined $offsetB= defined $limit
ABresult
1X1
011
000
2506 # limit/offset: build list, splice, then return context-appropriately
2507 0 my @rc = ($self->{'data'}->{$params->{'entry'}});
2508 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2509 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2510 0 ▶ return wantarray ? @rc : $rc[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
2511 }
2512 # Preserve original scalar-context behaviour: return the hashref directly
2513 # (not the count of a 1-element list).
2514 3 return $self->{'data'}->{$params->{'entry'}};
2515 } elsif(ref($self->{'data'}) eq 'HASH') {
2516 # Same as selectall_arrayref scan but returns a list
2517 10 $self->_debug("$table: selectall_array in-memory scan with criteria");
2518 # Pre-compute param keys once — same optimisation as selectall_arrayref:
2519 # avoids N * K hash-key extractions inside the inner closure.
2520 10 my @param_keys = keys %{$params};
2521 my @rc = grep {
2522 36 my $row = $_;
2523 36 ▶ all { $self->_match_criterion(exists($row->{$_}) ? $row->{$_} : undef, $params->{$_}, $_) } @param_keys
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$_} ? : 36 0 36
2524 10 } values %{$self->{'data'}};
2525 10 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 10 10
2526 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
2527 0 ▶ @rc = sort { ($b->{$sort_col} // '') cmp ($a->{$sort_col} // '') } @rc;
Condition0%0/4
$$b{$sort_col} // ""
l!l
00
$$a{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
2528 } else {
2529 0 ▶ @rc = sort { ($a->{$sort_col} // '') cmp ($b->{$sort_col} // '') } @rc;
Condition0%0/4
$$a{$sort_col} // ""
l!l
00
$$b{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
2530 }
2531 }
2532 10 ▶ if(defined($offset) || defined($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset or defined $limit) 0 10 10
Condition33%1/3
defined $offset or defined $limit
l!l&&r!l&&!r
0010
MC/DC0%0/2
defined $offset or defined $limit
defined $offset defined $limit
Truth table33%1/3
A or B
A= defined $offsetB= defined $limit
ABresult
1X1
011
000
2533 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2534 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2535 }
2536 10 return @rc;
2537 ▶ } elsif(ref($self->{'data'}) eq 'ARRAY' && !$self->{'_dbh'}{$table}) {
Condition0%0/3
ref $$self{"data"} eq "ARRAY" and not $$self{"_dbh"}{$table}
!ll&&!rl&&r
000
MC/DC0%0/2
ref $$self{"data"} eq "ARRAY" and not $$self{"_dbh"}{$table}
ref $$self{"data"} eq "ARRAY" not $$self{"_dbh"}{$table}
Truth table0%0/3
A and not(B)
A= ref $$self{"data"} eq "ARRAY"B= not $$self{"_dbh"}{$table}
ABresult
0X0
100
111
2538 # In-memory scan for array-backed no_entry stores (JSON, XLSX, HTML URL)
2539 # where there is no DBI handle. Mirrors the equivalent path in count().
2540 0 $self->_debug("$table: selectall_array in-memory array scan with criteria");
2541 0 my @param_keys = keys %{$params};
2542 my @rc = grep {
2543 0 my $row = $_;
2544 0 ▶ all { $self->_match_criterion(exists($row->{$_}) ? $row->{$_} : undef, $params->{$_}, $_) } @param_keys
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$_} ? : 0 0 0
2545 0 } @{$self->{'data'}};
2546 0 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 0 0
2547 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
2548 0 ▶ @rc = sort { ($b->{$sort_col} // '') cmp ($a->{$sort_col} // '') } @rc;
Condition0%0/4
$$b{$sort_col} // ""
l!l
00
$$a{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
2549 } else {
2550 0 ▶ @rc = sort { ($a->{$sort_col} // '') cmp ($b->{$sort_col} // '') } @rc;
Condition0%0/4
$$a{$sort_col} // ""
l!l
00
$$b{$sort_col} // ""
l!l
00
MC/DC0%0/1
$$a{$sort_col} // ""
$$a{$sort_col}
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
Truth table0%0/2
A
A= $$a{$sort_col}
Aresult
11
00
Truth table0%0/2
A
A= $$b{$sort_col}
Aresult
11
00
2551 }
2552 }
2553 0 ▶ if(defined($offset) || defined($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset or defined $limit) 0 0 0
Condition0%0/3
defined $offset or defined $limit
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $offset or defined $limit
defined $offset defined $limit
Truth table0%0/3
A or B
A= defined $offsetB= defined $limit
ABresult
1X1
011
000
2554 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2555 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2556 }
2557 0 return @rc;
2558 }
2559 }
2560  
2561 25 my ($where, $wargs) = $self->_build_where($params);
2562 25 my @query_args = @{$wargs};
2563  
2564 25 my $query = "SELECT * FROM $table";
2565 25 ▶ $query .= " $join_clause" if $join_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $join_clause 1 24 25
2566 25 ▶ if($join_clause) {
Branch: 2 branches
BranchTrueFalseTotal
if ($join_clause) { } 1 24 25
elsif ($$self{'type'} eq 'CSV' and not $$self{'no_entry'}) { } 3 21 24
2567 1 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 1 1
2568 ▶ } elsif(($self->{'type'} eq 'CSV') && !$self->{'no_entry'}) {
Condition100%3/3
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
!ll&&!rl&&r
1293
MC/DC100%2/2
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
$$self{"type"} eq "CSV" not $$self{"no_entry"}
Truth table100%3/3
A and not(B)
A= $$self{"type"} eq "CSV"B= not $$self{"no_entry"}
ABresult
0X0
100
111
2569 3 my $id = $self->{'id'};
2570 3 $query .= " WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
2571 3 ▶ $query .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 1 2 3
2572 } else {
2573 21 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 4 17 21
2574 }
2575 25 ▶ if(defined $sort_col) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort_col) { } 0 25 25
elsif (not $$self{'no_entry'}) { } 11 14 25
2576 0 $query .= " ORDER BY $sort_col $sort_dir";
2577 } elsif(!$self->{'no_entry'}) {
2578 11 $query .= ' ORDER BY ' . $self->{'id'};
2579 }
2580 25 ▶ if(defined($limit)) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $limit) { } 0 25 25
elsif (not wantarray) { } 6 19 25
elsif (defined $offset) { } 0 19 19
2581 0 $query .= ' LIMIT ?';
2582 0 push @query_args, $limit;
2583 0 ▶ if(defined($offset)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 0 0 0
2584 0 $query .= ' OFFSET ?';
2585 0 push @query_args, $offset;
2586 }
2587 } elsif(!wantarray) {
2588 6 ▶ if(defined($offset)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) { } 0 6 6
2589 0 $query .= ' LIMIT 1 OFFSET ?';
2590 0 push @query_args, $offset;
2591 } else {
2592 6 $query .= ' LIMIT 1';
2593 }
2594 } elsif(defined($offset)) {
2595 # List context, offset but no limit — SQLite requires LIMIT with OFFSET
2596 0 my $dbh = $self->{'_dbh'}{$table};
2597 $query .= ' LIMIT -1'
2598 if ($dbh && (($dbh->{Driver}{Name} // '') eq 'SQLite'))
2599 0 ▶ || (($self->{'_dialect'} // '') eq 'sqlite');
Branch: 1 branch
BranchTrueFalseTotal
if $dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite" 0 0 0
Condition0%0/10
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite"
l!l&&r!l&&!r
000
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite"
!ll&&!rl&&r
000
$$dbh{"Driver"}{"Name"} // ""
l!l
00
$$self{"_dialect"} // ""
l!l
00
MC/DC0%0/3
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite"
$dbh $$dbh{"Driver"}{"Name"} $$self{"_dialect"}
Truth table0%0/5
A and B or C
A= $dbhB= $$dbh{"Driver"}{"Name"}C= $$self{"_dialect"}
ABCresult
11X1
0X11
1011
0X00
1000
2600 0 $query .= ' OFFSET ?';
2601 0 push @query_args, $offset;
2602 }
2603  
2604 25 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 5 20 25
2605 5 $self->_debug("selectall_array $query: ", join(', ', @query_args));
2606 } else {
2607 20 $self->_debug("selectall_array $query");
2608 }
2609  
2610 25 my $key;
2611 my $c;
2612 25 ▶ if($c = $self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c = $$self{'cache'}) { } 9 16 25
2613 9 $key = ref($self) . '::' . $query;
2614 9 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 6 3 9
2615 6 $key .= ' array';
2616 }
2617 9 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) 4 5 9
2618 4 $key .= ' ' . join(', ', @query_args);
2619 }
2620 9 $self->_debug("cache key = '$key'");
2621 9 ▶ if(my $rc = $c->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $c->get($key)) 4 5 9
2622 4 $self->_debug('cache HIT');
2623 4 ▶ return wantarray ? @{$rc} : $rc; # We stored a ref to the array
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 3 1 4
2624  
2625 # This use of a temporary variable is to avoid
2626 # "Implicit scalar context for array in return"
2627 # my @rc = @{$rc};
2628 # return @rc;
2629 }
2630 5 $self->_debug('cache MISS');
2631 } else {
2632 16 $self->_debug('cache not used');
2633 }
2634  
2635 21 ▶ if(my $sth = $self->{'_dbh'}{$table}->prepare_cached($query)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sth = $$self{"_dbh"}{$table}->prepare_cached($query)) 21 0 21
2636 21 ▶ $sth->execute(@query_args) || croak("$query: @query_args");
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@query_args) or croak("${query}: @query_args") 21 0 21
2637  
2638 21 my $rc;
2639 21 ▶ while(my $href = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $href = $sth->fetchrow_hashref) 56 16 72
2640 56 ▶ if(!wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
unless (wantarray) 5 51 56
2641 # Scalar context: return just the first row; cache it too
2642 5 $sth->finish();
2643 5 ▶ $c->set($key, [$href], $self->{'cache_duration'}) if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 2 3 5
2644 5 return $href;
2645 }
2646 51 push @{$rc}, $href;
2647 }
2648 16 ▶ $c->set($key, $rc, $self->{'cache_duration'}) if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 3 13 16
2649  
2650 16 ▶ if($rc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc) 16 0 16
2651 16 ▶ if(!$no_fixate) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($no_fixate) 15 1 16
2652 15 $self->_fixate($rc);
2653 }
2654 16 return @{$rc};
2655 }
2656 0 return;
2657 }
2658 0 $self->_warn("selectall_array failure on $query: @query_args");
2659 0 croak("$query: @query_args");
2660 }
2661  
2662 =head2 selectall_hash
2663  
2664 Deprecated alias for L</selectall_array>. Use C<selectall_array> in new
2665 code.
2666  
2667 =cut
2668  
2669 sub selectall_hash
2670 11 ▶{
Subroutine selectall_hash: called CC=1 SCAR=0.0
Pod documented
2671 11 my $self = shift;
2672 11 return $self->selectall_array(@_);
2673 }
2674  
2675 =head2 count
2676  
2677 Returns the number of rows matching the given criteria.
2678  
2679 my $total = $db->count();
2680 my $active = $db->count(status => 'active');
2681 my $high = $db->count(score => { '>' => 90 });
2682  
2683 Accepts the full criteria syntax described in L</QUERY CRITERIA>.
2684  
2685 =head3 API SPECIFICATION
2686  
2687 =head4 Arguments
2688  
2689 %criteria # optional: same criteria syntax as selectall_arrayref
2690 join => HashRef | ArrayRef # optional join spec(s)
2691 table => Str # optional: override table name
2692  
2693 =head4 Returns
2694  
2695 Int (>= 0)
2696  
2697 The number of rows that match the given criteria. Returns C<0>
2698 when no rows match -- never C<undef>.
2699  
2700 =cut
2701  
2702 sub count
2703 250 ▶{
Subroutine count: called CC=28 SCAR=33.6
Pod documented
2704 250 my $self = shift;
2705  
2706 250 $self->_open_table({});
2707  
2708 213 ▶ my $params = Params::Get::get_params(undef, \@_) // {};
Condition100%2/2
Params::Get::get_params(undef, \@_) // {}
l!l
35178
MC/DC100%1/1
Params::Get::get_params(undef, \@_) // {}
Params::Get::get_params(undef, \@_)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
2709 213 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 2 211 213
2710 2 $params = $self->_merge_base_criteria($params);
2711 2 return scalar @{$self->_scan_berkeley($params)};
2712 }
2713  
2714 211 my $table = $self->_open_table($params);
2715 210 ▶ $params = $self->_merge_base_criteria($params // {});
Condition50%1/2
$params // {}
l!l
2100
MC/DC0%0/1
$params // {}
$params
Truth table50%1/2
A
A= $params
Aresult
11
00
2716  
2717 210 ▶ if($self->{'data'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"data"}) 145 65 210
2718 145 ▶ if(scalar(keys %{$params}) == 0) {
Branch: 3 branches
BranchTrueFalseTotal
if (scalar keys %{$params;} == 0) { } 116 29 145
elsif (scalar keys %{$params;} == 1 and defined $$params{'entry'} and not $$self{'no_entry'}) { } 10 19 29
elsif (not $self->_has_complex_criteria($params) || $$self{'_dbh'}{$table}) { } 3 16 19
2719 116 $self->_trace("$table: count fast track return");
2720 116 ▶ if(ref($self->{'data'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $$self{"data"} eq "HASH") 99 17 116
2721 99 return scalar keys %{$self->{'data'}};
2722 }
2723 17 return scalar @{$self->{'data'}};
2724 29 ▶ } elsif((scalar(keys %{$params}) == 1) && defined($params->{'entry'}) && !$self->{'no_entry'}) {
Condition83%5/6
scalar keys %{$params;} == 1 and defined $$params{"entry"} and not $$self{"no_entry"}
!ll&&!rl&&r
19010
scalar keys %{$params;} == 1 and defined $$params{"entry"}
!ll&&!rl&&r
21710
MC/DC66%2/3
scalar keys %{$params;} == 1 and defined $$params{"entry"} and not $$self{"no_entry"}
scalar keys %{$params;} == 1 defined $$params{"entry"} not $$self{"no_entry"}
Truth table75%3/4
A and B and not(C)
A= scalar keys %{$params;} == 1B= defined $$params{"entry"}C= not $$self{"no_entry"}
ABCresult
0XX0
10X0
1100
1111
2725 # exists() guard: fixate() locks all keys in the slurp hash
2726 10 ▶ return (exists($self->{'data'}->{$params->{'entry'}}) && $self->{'data'}->{$params->{'entry'}}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $$self{'data'}{$$params{'entry'}} && $$self{'data'}{$$params{'entry'}} ? : 6 4 10
Condition66%2/3
exists $$self{"data"}{$$params{"entry"}} and $$self{"data"}{$$params{"entry"}}
!ll&&!rl&&r
406
MC/DC50%1/2
exists $$self{"data"}{$$params{"entry"}} and $$self{"data"}{$$params{"entry"}}
exists $$self{"data"}{$$params{"entry"}} $$self{"data"}{$$params{"entry"}}
Truth table66%2/3
A and B
A= exists $$self{"data"}{$$params{"entry"}}B= $$self{"data"}{$$params{"entry"}}
ABresult
0X0
100
111
2727 ▶ } elsif(!$self->_has_complex_criteria($params) && !$self->{'_dbh'}{$table}) {
Condition66%2/3
$self->_has_complex_criteria($params) || $$self{'_dbh'}{$table}
l!l&&r!l&&!r
0163
MC/DC50%1/2
$self->_has_complex_criteria($params) || $$self{'_dbh'}{$table}
$self->_has_complex_criteria($params) $$self{'_dbh'}{$table}
Truth table66%2/3
A || B
A= $self->_has_complex_criteria($params)B= $$self{'_dbh'}{$table}
ABresult
1X1
011
000
2728 # General in-memory scan for simple column criteria.
2729 # Only taken when there is no DBI handle ($self->{'_dbh'}{$table} is undef),
2730 # i.e. slurp-only backends like Deep. CSV/XML/SQLite have a DBI handle
2731 # and must fall through to the SQL path so that column-name validation
2732 # fires in _build_where_conditions.
2733 3 $self->_debug("$table: count in-memory scan");
2734 3 my @param_keys = keys %{$params};
2735 # Pass the row list directly to grep — avoids materialising an
2736 # intermediate @rows array of N references on the stack.
2737 return scalar grep {
2738 9 my $row = $_;
2739 9 ▶ all { $self->_match_criterion(exists($row->{$_}) ? $row->{$_} : undef, $params->{$_}, $_) } @param_keys
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$_} ? : 9 0 9
2740 0 ▶ } (ref($self->{'data'}) eq 'HASH' ? values %{$self->{'data'}} : @{$self->{'data'}});
Branch: 1 branch
BranchTrueFalseTotal
ref $$self{'data'} eq 'HASH' ? : 3 0 3
2741 }
2742 }
2743  
2744 81 my ($where, $wargs) = $self->_build_where($params);
2745 77 my @query_args = @{$wargs};
2746  
2747 77 my $query;
2748 77 ▶ if(($self->{'type'} eq 'CSV') && !$self->{'no_entry'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$self{'type'} eq 'CSV' and not $$self{'no_entry'}) { } 24 53 77
elsif ($$self{'no_entry'}) { } 36 17 53
Condition100%3/3
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
!ll&&!rl&&r
49424
MC/DC100%2/2
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
$$self{"type"} eq "CSV" not $$self{"no_entry"}
Truth table100%3/3
A and not(B)
A= $$self{"type"} eq "CSV"B= not $$self{"no_entry"}
ABresult
0X0
100
111
2749 24 my $id = $self->{'id'};
2750 24 $query = "SELECT COUNT(*) FROM $table WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
2751 24 ▶ $query .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 13 11 24
2752 } elsif($self->{'no_entry'}) {
2753 36 $query = "SELECT COUNT(*) FROM $table";
2754 36 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 12 24 36
2755 } else {
2756 17 $query = "SELECT COUNT(" . $self->{'id'} . ") FROM $table";
2757 17 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 17 17
2758 }
2759  
2760 77 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 23 54 77
2761 23 $self->_debug("count $query: ", join(', ', @query_args));
2762 } else {
2763 54 $self->_debug("count $query");
2764 }
2765  
2766 77 my $key;
2767 my $c;
2768 77 ▶ if($c = $self->{'cache'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c = $$self{'cache'}) { } 7 70 77
2769 # Opportunistic: if a selectall_arrayref for the same criteria is already
2770 # in cache, derive the count from that array rather than hitting the DB.
2771 # The key is built to match what selectall_arrayref would store.
2772 7 $key = ref($self) . '::' . $query;
2773 # [^)]+ is a negated character class: O(n) with zero backtracking.
2774 # The former lazy .+? could scan past the first ) in pathological SQL;
2775 # [^)]+ is also semantically correct (COUNT(expr) never contains ) ).
2776 7 $key =~ s/COUNT\(([^)]+)\)/$1/;
2777 7 $key .= ' array';
2778 7 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) 3 4 7
2779 3 $key .= ' ' . join(', ', @query_args);
2780 }
2781 7 ▶ if(my $rc = $c->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $c->get($key)) 2 5 7
2782 2 $self->_debug('count: cache HIT (selectall array)');
2783 2 ▶ return ref($rc) eq 'ARRAY' ? scalar @{$rc} : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $rc eq 'ARRAY' ? : 2 0 2
2784 }
2785 5 $self->_debug('count: cache MISS');
2786 } else {
2787 70 $self->_debug('cache not used');
2788 }
2789  
2790 75 ▶ if(my $sth = $self->{'_dbh'}{$table}->prepare_cached($query)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sth = $$self{"_dbh"}{$table}->prepare_cached($query)) 74 0 74
2791 74 ▶ $sth->execute(@query_args) || croak("$query: @query_args");
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@query_args) or croak("${query}: @query_args") 74 0 74
2792  
2793 74 my $count = $sth->fetchrow_arrayref()->[0];
2794 74 $sth->finish();
2795  
2796 74 return $count;
2797 }
2798 0 $self->_warn("count failure on $query: @query_args");
2799 0 croak("$query: @query_args");
2800 }
2801  
2802 =head2 fetchrow_hashref
2803  
2804 Returns a hash reference for the first row matching the given criteria,
2805 or C<undef> when there is no match. Always applies C<LIMIT 1>.
2806  
2807 my $row = $db->fetchrow_hashref(entry => 'key1');
2808 my $row = $db->fetchrow_hashref(score => { '>=' => 10 });
2809  
2810 When C<no_entry> is B<not> set you may pass a single bare value and it is
2811 used as the C<entry> key:
2812  
2813 my $row = $db->fetchrow_hashref('key1'); # same as entry => 'key1'
2814  
2815 Accepts the full criteria syntax described in L</QUERY CRITERIA>, including
2816 the C<join> parameter:
2817  
2818 my $row = $db->fetchrow_hashref(
2819 name => 'Alice',
2820 join => { table => 'dept', on => 'e.dept_id = dept.id' },
2821 );
2822  
2823 Pass C<< table => $other_table >> to query a table other than the one
2824 derived from the class name.
2825  
2826 =head3 API SPECIFICATION
2827  
2828 =head4 Arguments
2829  
2830 entry => Str # primary-key value to look up (positional first
2831 # arg when no_entry is false)
2832 %criteria # optional additional column filters
2833 join => HashRef | ArrayRef # optional join spec(s)
2834 no_fixate => Bool # optional: skip read-only locking
2835 table => Str # optional: override table name
2836  
2837 =head4 Returns
2838  
2839 HashRef | undef
2840  
2841 A single row hashref when exactly one matching row is found. Returns
2842 C<undef> when the key is not found or no row matches the criteria.
2843 The hashref is read-only unless C<no_fixate> was set.
2844  
2845 B<Note:> C<fetchrow_hashref> does B<not> croak when multiple rows
2846 match the given criteria; it returns whichever row the backend
2847 delivers first (usually the first row in file/insertion order).
2848  
2849 =cut
2850  
2851 127 ▶sub fetchrow_hashref {
Subroutine fetchrow_hashref: called CC=41 SCAR=46.2
Pod documented
2852 127 my $self = shift;
2853  
2854 127 $self->_trace('Entering fetchrow_hashref');
2855  
2856 127 my $params;
2857  
2858 127 ▶ if(!$self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $$self{'no_entry'}) { } 114 13 127
2859 114 $params = Params::Get::get_params('entry', @_);
2860 } else {
2861 13 $params = Params::Get::get_params(undef, @_);
2862 }
2863  
2864 127 my $table = $self->_open_table($params);
2865  
2866 123 ▶ if($self->{'data'} && (!$self->{'no_entry'}) && (scalar keys(%{$params}) == 1) && defined($params->{'entry'}) && !$self->_has_complex_criteria($params)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"data"} and not $$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $$params{"entry"} and not $self->_has_complex_criteria($params)) 88 35 123
Condition83%10/12
$$self{"data"} and not $$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $$params{"entry"} and not $self->_has_complex_criteria($params)
!ll&&!rl&&r
35088
$$self{"data"} and not $$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $$params{"entry"}
!ll&&!rl&&r
29688
$$self{"data"} and not $$self{"no_entry"} and scalar keys %{$params;} == 1
!ll&&!rl&&r
28194
$$self{"data"} and not $$self{"no_entry"}
!ll&&!rl&&r
28095
MC/DC60%3/5
$$self{"data"} and not $$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $$params{"entry"} and not $self->_has_complex_criteria($params)
$$self{"data"} not $$self{"no_entry"} scalar keys %{$params;} == 1 defined $$params{"entry"} not $self->_has_complex_criteria($params)
Truth table66%4/6
A and not(B) and C and D and not(E)
A= $$self{"data"}B= not $$self{"no_entry"}C= scalar keys %{$params;} == 1D= defined $$params{"entry"}E= not $self->_has_complex_criteria($params)
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
2867 88 $self->_debug('Fast return from slurped data');
2868 # Use exists(), fixate() locks the outer hash; accessing a missing key throws
2869 88 ▶ return undef unless exists($self->{'data'}->{$params->{'entry'}});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$self{"data"}{$$params{"entry"}} 17 71 88
2870 71 my $row = $self->{'data'}->{$params->{'entry'}};
2871 71 ▶ if(my $bc = $self->{'base_criteria'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bc = $$self{"base_criteria"}) 4 67 71
2872 4 ▶ return undef unless all { $self->_match_criterion(exists($row->{$_}) ? $row->{$_} : undef, $bc->{$_}, $_) } keys %{$bc};
Subroutine __ANON__: called CC=2 SCAR=7.0
Branch: 2 branches
BranchTrueFalseTotal
unless &all(sub { $self->_match_criterion(exists $row->{$_} ? $$row{$_} : undef, $$bc{$_}, $_); } , keys %{$bc;}) 2 2 4
exists $row->{$_} ? : 4 0 4
2873 }
2874 69 return $row;
2875 }
2876  
2877 35 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 0 35 35
2878 0 ▶ if((!$self->{'no_entry'}) && (scalar keys(%{$params}) == 1) && defined($params->{'entry'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $$params{"entry"}) 0 0 0
Condition0%0/6
not $$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $$params{"entry"}
!ll&&!rl&&r
000
not $$self{"no_entry"} and scalar keys %{$params;} == 1
!ll&&!rl&&r
000
MC/DC0%0/3
not $$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $$params{"entry"}
not $$self{"no_entry"} scalar keys %{$params;} == 1 defined $$params{"entry"}
Truth table0%0/4
not(A) and B and C
A= not $$self{"no_entry"}B= scalar keys %{$params;} == 1C= defined $$params{"entry"}
ABCresult
0XX0
10X0
1100
1111
2879 0 return { entry => $self->{'berkeley'}->{$params->{'entry'}} };
2880 }
2881 0 my $id = $self->{'id'};
2882 0 ▶ if($self->{'no_entry'} && (scalar keys(%{$params}) == 1) && defined($id) && defined($params->{$id})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $id and defined $$params{$id}) 0 0 0
Condition0%0/9
$$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $id and defined $$params{$id}
!ll&&!rl&&r
000
$$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $id
!ll&&!rl&&r
000
$$self{"no_entry"} and scalar keys %{$params;} == 1
!ll&&!rl&&r
000
MC/DC0%0/4
$$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $id and defined $$params{$id}
$$self{"no_entry"} scalar keys %{$params;} == 1 defined $id defined $$params{$id}
Truth table0%0/5
A and B and C and D
A= $$self{"no_entry"}B= scalar keys %{$params;} == 1C= defined $idD= defined $$params{$id}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2883 0 ▶ if(my $rc = $self->{'berkeley'}->{$params->{$id}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $$self{"berkeley"}{$$params{$id}}) 0 0 0
2884 0 return { $params->{$id} => $rc } # Return key->value as a hash pair
2885 }
2886 0 return;
2887 }
2888 0 Carp::croak(ref($self), ': fetchrow_hashref is meaningless on a NoSQL database');
2889 }
2890  
2891 35 my $raw_target = delete $params->{'table'};
2892 35 ▶ if(defined $raw_target) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $raw_target) 0 35 35
2893 0 $raw_target =~ s/\A.*:://;
2894 0 ▶ Carp::croak(ref($self), ": unsafe table name '$raw_target'")
Branch: 1 branch
BranchTrueFalseTotal
unless $raw_target =~ /$SAFE_QUALIFIED/ 0 0 0
2895 unless $raw_target =~ $SAFE_QUALIFIED;
2896 }
2897 35 ▶ my $target = $raw_target // $table;
Condition33%1/3
$raw_target // $table
l!l&&r!l&&!r
0350
MC/DC0%0/2
$raw_target // $table
$raw_target $table
Truth table33%1/3
A // B
A= $raw_targetB= $table
ABresult
1X1
011
000
2898 35 my $join_spec = delete $params->{'join'};
2899 35 delete $params->{'no_fixate'};
2900 35 $params = $self->_merge_base_criteria($params);
2901 35 ▶ my $join_clause = $join_spec ? $self->_build_joins($join_spec) : '';
Branch: 1 branch
BranchTrueFalseTotal
$join_spec ? : 1 34 35
2902 35 my ($where, $wargs) = $self->_build_where($params);
2903 33 my @query_args = @{$wargs};
2904  
2905 33 my $query = "SELECT * FROM $target";
2906 33 ▶ $query .= " $join_clause" if $join_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $join_clause 1 32 33
2907 33 ▶ if($join_clause) {
Branch: 2 branches
BranchTrueFalseTotal
if ($join_clause) { } 1 32 33
elsif ($$self{'type'} eq 'CSV' and not $$self{'no_entry'}) { } 7 25 32
2908 1 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 1 0 1
2909 ▶ } elsif(($self->{'type'} eq 'CSV') && !$self->{'no_entry'}) {
Condition100%3/3
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
!ll&&!rl&&r
2417
MC/DC100%2/2
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
$$self{"type"} eq "CSV" not $$self{"no_entry"}
Truth table100%3/3
A and not(B)
A= $$self{"type"} eq "CSV"B= not $$self{"no_entry"}
ABresult
0X0
100
111
2910 7 my $id = $self->{'id'};
2911 7 $query .= " WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
2912 7 ▶ $query .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 7 0 7
2913 } else {
2914 25 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 25 0 25
2915 }
2916 33 $query .= ' LIMIT 1';
2917 33 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 32 1 33
2918 32 my @call_details = caller(0);
2919 32 $self->_debug("fetchrow_hashref $query: ", join(', ', @query_args),
2920 ' called from ', $call_details[2], ' of ', $call_details[1]);
2921 } else {
2922 1 $self->_debug("fetchrow_hashref $query");
2923 }
2924 # Premise: $key is only needed when a cache is configured.
2925 # Conclusion: assemble it lazily inside the cache block — no dead store on
2926 # the common (no-cache) path.
2927 33 my $c = $self->{'cache'};
2928 33 my $key; # declared here so the second if($c) block (cache SET) can see it
2929 33 ▶ if($c) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c) 7 26 33
2930 7 $key = ref($self) . '::';
2931 7 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 7 0 7
2932 7 ▶ $key .= 'array ' if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 1 6 7
2933 7 $key .= "fetchrow $query " . join(', ', @query_args);
2934 } else {
2935 0 $key .= "fetchrow $query";
2936 }
2937 7 ▶ if(my $rc = $c->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $c->get($key)) 3 4 7
2938 3 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 3 3
2939 0 ▶ if(ref($rc) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rc eq "ARRAY") 0 0 0
2940 0 return @{$rc}; # We stored a ref to the array
2941 }
2942 } else {
2943 3 return $rc;
2944 }
2945 }
2946 }
2947  
2948 my $sth = $self->{'_dbh'}{$table}->prepare_cached($query)
2949 30 ▶ or Carp::croak(ref($self), ": prepare failed: ", $self->{'_dbh'}{$table}->errstr());
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $$self{"_dbh"}{$table}->prepare_cached($query) or Carp::croak(ref $self, ": prepare failed: ", $$self{"_dbh"}{$table}->errstr) 30 0 30
2950 30 ▶ $sth->execute(@query_args) || croak("$query: @query_args");
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@query_args) or croak("${query}: @query_args") 30 0 30
2951 30 my $rc = $sth->fetchrow_hashref();
2952 30 $sth->finish();
2953 30 ▶ if($c) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c) 4 26 30
2954 4 ▶ if($rc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc) { } 4 0 4
2955 4 $self->_debug("stash $key=>$rc in the cache for ", $self->{'cache_duration'});
2956 4 $self->_debug("returns ", do { require Data::Dumper; Data::Dumper->new([$rc])->Dump() });
2957 } else {
2958 0 $self->_debug("Stash $key=>undef in the cache for ", $self->{'cache_duration'});
2959 }
2960 4 $c->set($key, $rc, $self->{'cache_duration'});
2961 }
2962 30 return $rc;
2963 }
2964  
2965 =head2 execute
2966  
2967 Execute a raw SQL query on the underlying database.
2968  
2969 # Scalar context: returns the first row as a hashref
2970 my $row = $db->execute(query => 'SELECT * FROM foo WHERE id = 1');
2971  
2972 # List context: returns all rows as a list of hashrefs
2973 my @rows = $db->execute(query => 'SELECT * FROM foo WHERE score > ?',
2974 args => [80]);
2975  
2976 The C<FROM E<lt>tableE<gt>> clause is appended automatically if omitted.
2977  
2978 On CSV tables without C<no_entry> it may help to add
2979 C<WHERE entry IS NOT NULL AND entry NOT LIKE '#%'> to filter comment rows.
2980  
2981 If the data have been slurped into memory this method still hits the actual
2982 database file directly.
2983  
2984 C<args> is an arrayref of bind values (see L<DBI/execute>).
2985  
2986 =cut
2987  
2988 sub execute
2989 18 ▶{
Subroutine execute: called CC=10 SCAR=23.1
Pod documented
2990 18 my $self = shift;
2991  
2992 18 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 1 17 18
2993 1 Carp::croak(ref($self), ': execute is meaningless on a NoSQL database');
2994 }
2995  
2996 17 my $args = Params::Get::get_params('query', @_);
2997  
2998 # Ensure the 'query' parameter is provided
2999 Carp::croak(__PACKAGE__, ': Usage: execute(query => $query)')
3000 15 ▶ unless defined $args->{'query'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$args{"query"} 0 15 15
3001  
3002 15 my $table = $self->_open_table($args);
3003  
3004 15 my $query = $args->{'query'};
3005  
3006 # Append "FROM <table>" if missing
3007 # \bFROM\b catches the keyword at any word boundary (space, tab, newline),
3008 # unlike the former \sFROM\s which missed forms like "col\tFROM" or leading FROM.
3009 15 ▶ $query .= " FROM $table" unless $query =~ /\bFROM\b/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $query =~ /\bFROM\b/i 0 15 15
3010  
3011 # Log the query if a logger is available
3012 15 $self->_debug("execute $query");
3013  
3014 # Prepare and execute the query
3015 15 my $sth = $self->{'_dbh'}{$table}->prepare_cached($query);
3016 # DBI->execute() takes a list; normalise args to an array whether it
3017 # was passed as an arrayref ([30]) or a bare scalar/list (30).
3018 15 ▶ if(exists($args->{'args'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args->{'args'}) { } 9 6 15
3019 9 ▶ my @bind = ref($args->{'args'}) eq 'ARRAY' ? @{$args->{'args'}} : ($args->{'args'});
Branch: 1 branch
BranchTrueFalseTotal
ref $$args{'args'} eq 'ARRAY' ? : 5 4 9
3020 9 ▶ $sth->execute(@bind) or croak("$query: ", join(', ', @bind));
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@bind) or croak("${query}: ", join(", ", @bind)) 9 0 9
3021 } else {
3022 6 ▶ $sth->execute() or croak($query);
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute or croak($query) 6 0 6
3023 }
3024  
3025 # Fetch the results
3026 15 my @results;
3027 15 ▶ while (my $row = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 31 12 43
3028 31 ▶ unless(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
unless (wantarray) 3 28 31
3029 3 $sth->finish();
3030 3 return $row;
3031 }
3032 28 push @results, $row;
3033 }
3034  
3035 # Return all rows as an array in list context
3036 12 return @results;
3037 }
3038  
3039 =head2 updated
3040  
3041 Returns the Unix timestamp of the last database update.
3042  
3043 For file-based backends (CSV, XML, SQLite via C<directory>), this is the
3044 mtime of the backing file, set at C<new()> time.
3045  
3046 For SQLite DSN connections (C<dbi:SQLite:dbname=...>), the file path is
3047 extracted from the DSN and C<stat()>-ed live on every call, so callers
3048 get a current mtime suitable for cache-invalidation even when the database
3049 was opened via a DSN rather than a C<directory>.
3050  
3051 For all other DSN-based connections (PostgreSQL, MySQL, etc.) and for
3052 URL-based backends, returns the Unix timestamp of the most recent
3053 C<new()> call (connection time).
3054  
3055 =cut
3056  
3057 9 ▶sub updated {
Subroutine updated: called CC=6 SCAR=18.5
Pod documented
3058 9 my $self = shift;
3059  
3060 9 ▶ if(($self->{'_dialect'} // '') eq 'sqlite') {
Branch: 1 branch
BranchTrueFalseTotal
if (($$self{"_dialect"} // "") eq "sqlite") 5 4 9
Condition100%2/2
$$self{"_dialect"} // ""
l!l
54
MC/DC100%1/1
$$self{"_dialect"} // ""
$$self{"_dialect"}
Truth table100%2/2
A
A= $$self{"_dialect"}
Aresult
11
00
3061 5 my $dsn = $self->{'dsn'};
3062 5 ▶ if(defined($dsn) && $dsn =~ /\Adbi:SQLite:(?:dbname=)?(.+)\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dsn and $dsn =~ /\Adbi:SQLite:(?:dbname=)?(.+)\z/i) 5 0 5
Condition33%1/3
defined $dsn and $dsn =~ /\Adbi:SQLite:(?:dbname=)?(.+)\z/i
!ll&&!rl&&r
005
MC/DC0%0/2
defined $dsn and $dsn =~ /\Adbi:SQLite:(?:dbname=)?(.+)\z/i
defined $dsn $dsn =~ /\Adbi:SQLite:(?:dbname=)?(.+)\z/i
Truth table33%1/3
A and B
A= defined $dsnB= $dsn =~ /\Adbi:SQLite:(?:dbname=)?(.+)\z/i
ABresult
0X0
100
111
3063 5 my $path = $1;
3064 5 my @st = stat($path);
3065 5 ▶ return $st[9] if @st;
Branch: 1 branch
BranchTrueFalseTotal
if @st 5 0 5
3066 }
3067 }
3068  
3069 4 return $self->{'_updated'};
3070 }
3071  
3072 =head2 columns
3073  
3074 Returns an array reference of column names for the current table.
3075  
3076 my $cols = $db->columns(); # e.g. ['entry', 'name', 'score', 'status']
3077  
3078 Column names are always returned in alphabetical (lexicographic) order,
3079 regardless of backend. This makes the result stable and portable when the
3080 same logical table is backed by different engines (CSV => SQLite, etc.).
3081  
3082 The source of column names varies by backend:
3083  
3084 =over 4
3085  
3086 =item * B<Slurp mode> - keys of the first row in memory.
3087  
3088 =item * B<SQLite / other DBI> - a zero-row C<SELECT *> exposes the driver's
3089 C<NAME> attribute.
3090  
3091 =item * B<BerkeleyDB> - always returns C<['entry', 'value']>.
3092  
3093 =back
3094  
3095 The result is cached inside the object after the first call.
3096  
3097 =head3 API SPECIFICATION
3098  
3099 =head4 Arguments
3100  
3101 None beyond the implicit invocant. The result is cached in the
3102 object after the first call.
3103  
3104 =head4 Returns
3105  
3106 ArrayRef[Str]
3107  
3108 A sorted (lexicographic, ascending) arrayref of column names. The
3109 sort order is identical across all backends, so switching from CSV
3110 to SQLite does not change the returned order.
3111  
3112 =cut
3113  
3114 34 ▶sub columns {
Subroutine columns: called CC=8 SCAR=20.9
Pod documented
3115 34 my $self = shift;
3116  
3117 34 ▶ return $self->{'_columns'} if $self->{'_columns'};
Branch: 1 branch
BranchTrueFalseTotal
if $$self{"_columns"} 6 28 34
3118  
3119 28 my $table = $self->_open_table({});
3120  
3121 27 my @cols;
3122  
3123 27 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 1 26 27
3124 1 return $self->{'_columns'} = ['entry', 'value'];
3125 }
3126  
3127 26 ▶ if(my $data = $self->{'data'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $data = $$self{'data'}) { } 14 12 26
3128 14 ▶ if(ref($data) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $data eq 'HASH') { } 10 4 14
elsif (ref $data eq 'ARRAY' and @{$data;}) { } 4 0 4
3129 10 my ($first) = values %{$data};
3130 10 ▶ @cols = sort keys %{$first} if $first;
Branch: 1 branch
BranchTrueFalseTotal
if $first 10 0 10
3131 4 ▶ } elsif(ref($data) eq 'ARRAY' && @{$data}) {
Condition33%1/3
ref $data eq "ARRAY" and @{$data;}
!ll&&!rl&&r
004
MC/DC0%0/2
ref $data eq "ARRAY" and @{$data;}
ref $data eq "ARRAY" @{$data;}
Truth table33%1/3
A and B
A= ref $data eq "ARRAY"B= @{$data;}
ABresult
0X0
100
111
3132 4 @cols = sort keys %{$data->[0]};
3133 }
3134 } else {
3135 12 my $sth = $self->{'_dbh'}{$table}->prepare_cached("SELECT * FROM $table WHERE 1=0");
3136 12 $sth->execute();
3137 12 @cols = sort @{$sth->{NAME}};
3138 12 $sth->finish();
3139 }
3140  
3141 26 return $self->{'_columns'} = \@cols;
3142 }
3143  
3144 =head2 schema
3145  
3146 Returns a hash reference describing the schema of the current table.
3147 Each key is a column name; each value is a hash reference with these keys:
3148  
3149 =over 4
3150  
3151 =item * C<type> - data type string (e.g. C<TEXT>, C<INTEGER>, C<REAL>)
3152  
3153 =item * C<nullable> - C<1> if the column may be NULL, C<0> if NOT NULL
3154  
3155 =item * C<default> - default value string, or C<undef>
3156  
3157 =item * C<pk> - C<1> if this column is (part of) the primary key, C<0> otherwise
3158  
3159 =back
3160  
3161 my $schema = $db->schema();
3162  
3163 for my $col (sort keys %{$schema}) {
3164 my $info = $schema->{$col};
3165 printf "%s %s %s\n",
3166 $col,
3167 $info->{type},
3168 $info->{nullable} ? 'NULL' : 'NOT NULL';
3169 }
3170  
3171 The schema is determined by the backend:
3172  
3173 =over 4
3174  
3175 =item * B<SQLite> - C<PRAGMA table_info(table)>
3176  
3177 =item * B<Other DBI drivers> - C<< $dbh->column_info(...) >>
3178  
3179 =item * B<Slurp mode> - inferred from the first row; all columns typed as
3180 C<TEXT> by default. When C<< infer_types => 1 >> was passed to the
3181 constructor, up to 100 rows are scanned per column and the type is
3182 promoted: all-integer values => C<INTEGER>; all-float values =>
3183 C<REAL>; all ISO-8601 timestamps (C<YYYY-MM-DDThh:mm>) => C<TIMESTAMP>;
3184 all ISO-8601 dates (C<YYYY-MM-DD>) => C<DATE>; otherwise C<TEXT>.
3185 C<undef> and empty-string values are treated as SQL C<NULL> and skipped
3186 during the scan.
3187  
3188 =item * B<BerkeleyDB> - always returns C<entry> (pk) and C<value>
3189  
3190 =back
3191  
3192 The result is cached inside the object after the first call.
3193  
3194 =head3 API SPECIFICATION
3195  
3196 =head4 Arguments
3197  
3198 infer_types => Bool # enable heuristic type inference for slurp backends
3199 # (may also be set at construction time)
3200  
3201 =head4 Returns
3202  
3203 HashRef[Str => HashRef]
3204  
3205 A hashref keyed by column name. Each value is a hashref with:
3206  
3207 type => Str # 'TEXT', 'INTEGER', 'REAL', 'TIMESTAMP', 'DATE'
3208 nullable => Bool # 1 if the column may be NULL, 0 if NOT NULL
3209 default => Str | undef # default value, or undef
3210 pk => Bool # 1 if (part of) the primary key
3211  
3212 For slurp-mode backends all columns default to type C<TEXT> unless
3213 C<infer_types> is set. The result is cached in the object after the
3214 first call.
3215  
3216 =cut
3217  
3218 29 ▶sub schema {
Subroutine schema: called CC=24 SCAR=33.9
Pod documented
3219 29 my $self = shift;
3220  
3221 29 ▶ return $self->{'_schema'} if $self->{'_schema'};
Branch: 1 branch
BranchTrueFalseTotal
if $$self{"_schema"} 8 21 29
3222  
3223 21 my $table = $self->_open_table({});
3224 21 my %schema;
3225  
3226 21 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 1 20 21
3227 1 return $self->{'_schema'} = {
3228 entry => { type => 'TEXT', nullable => 0, default => undef, pk => 1 },
3229 value => { type => 'TEXT', nullable => 1, default => undef, pk => 0 },
3230 };
3231 }
3232  
3233 20 ▶ if(my $data = $self->{'data'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $data = $$self{'data'}) { } 16 4 20
3234 16 my $first;
3235 my @sample;
3236 16 ▶ if(ref($data) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $data eq 'HASH') { } 10 6 16
elsif (ref $data eq 'ARRAY' and @{$data;}) { } 6 0 6
3237 10 ($first) = values %{$data};
3238 10 ▶ if($self->{'infer_types'} && $first) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"infer_types"} and $first) 2 8 10
Condition66%2/3
$$self{"infer_types"} and $first
!ll&&!rl&&r
802
MC/DC50%1/2
$$self{"infer_types"} and $first
$$self{"infer_types"} $first
Truth table66%2/3
A and B
A= $$self{"infer_types"}B= $first
ABresult
0X0
100
111
3239 2 my $n = 0;
3240 2 for my $row (values %{$data}) {
3241 6 push @sample, $row;
3242 6 ▶ last if ++$n >= INFER_TYPE_SAMPLE_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
if ++$n >= 100 0 6 6
3243 }
3244 }
3245 6 ▶ } elsif(ref($data) eq 'ARRAY' && @{$data}) {
Condition33%1/3
ref $data eq "ARRAY" and @{$data;}
!ll&&!rl&&r
006
MC/DC0%0/2
ref $data eq "ARRAY" and @{$data;}
ref $data eq "ARRAY" @{$data;}
Truth table33%1/3
A and B
A= ref $data eq "ARRAY"B= @{$data;}
ABresult
0X0
100
111
3246 6 $first = $data->[0];
3247 6 ▶ if($self->{'infer_types'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"infer_types"}) 1 5 6
3248 1 ▶ my $last = $#{$data} < INFER_TYPE_SAMPLE_SIZE - 1 ? $#{$data} : INFER_TYPE_SAMPLE_SIZE - 1;
Branch: 1 branch
BranchTrueFalseTotal
$#{$data;} < 99 ? : 1 0 1
3249 1 @sample = @{$data}[0 .. $last];
3250 }
3251 }
3252 16 ▶ if($first) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first) 16 0 16
3253 16 my $id = $self->{'id'};
3254 16 for my $col (keys %{$first}) {
3255 my $type = @sample
3256 43 ▶ ? _infer_type([map { exists($_->{$col}) ? $_->{$col} : undef } @sample])
Branch: 2 branches
BranchTrueFalseTotal
@sample ? : 12 31 43
exists $_->{$col} ? : 36 0 36
3257 : 'TEXT';
3258 43 ▶ $schema{$col} = {
Branch: 2 branches
BranchTrueFalseTotal
$col eq $id ? : 16 27 43
$col eq $id ? : 16 27 43
3259 type => $type,
3260 nullable => ($col eq $id ? 0 : 1),
3261 default => undef,
3262 pk => ($col eq $id ? 1 : 0),
3263 };
3264 }
3265 }
3266 } else {
3267 4 ▶ my $driver = $self->{'_dbh'}{$table}->{'Driver'}{'Name'} // '';
Condition50%1/2
$$self{"_dbh"}{$table}{"Driver"}{"Name"} // ""
l!l
40
MC/DC0%0/1
$$self{"_dbh"}{$table}{"Driver"}{"Name"} // ""
$$self{"_dbh"}{$table}{"Driver"}{"Name"}
Truth table50%1/2
A
A= $$self{"_dbh"}{$table}{"Driver"}{"Name"}
Aresult
11
00
3268 4 ▶ if($driver eq 'SQLite') {
Branch: 1 branch
BranchTrueFalseTotal
if ($driver eq 'SQLite') { } 4 0 4
3269 4 my $sth = $self->{'_dbh'}{$table}->prepare_cached("PRAGMA table_info($table)");
3270 4 $sth->execute();
3271 4 ▶ while(my $row = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 11 4 15
3272 $schema{$row->{'name'}} = {
3273 type => $row->{'type'},
3274 nullable => !$row->{'notnull'},
3275 default => $row->{'dflt_value'},
3276 11 pk => $row->{'pk'},
3277 };
3278 }
3279 4 $sth->finish();
3280 } else {
3281 0 my $sth = $self->{'_dbh'}{$table}->column_info(undef, undef, $table, '%');
3282 0 ▶ if($sth) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth) 0 0 0
3283 0 ▶ while(my $row = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 0 0 0
3284 $schema{$row->{'COLUMN_NAME'}} = {
3285 type => $row->{'TYPE_NAME'},
3286 nullable => $row->{'NULLABLE'},
3287 0 default => $row->{'COLUMN_DEF'},
3288 pk => 0,
3289 };
3290 }
3291 0 $sth->finish();
3292 }
3293 }
3294 }
3295  
3296 20 return $self->{'_schema'} = \%schema;
3297 }
3298  
3299 =head2 dbi_source
3300  
3301 Returns a hashref C<{ dbh =E<gt> $dbh, table =E<gt> $name }> when the backend
3302 is a live SQLite connection, or C<undef> for every other backend (slurp-mode
3303 CSV, JSON, XLSX, HTML URL, DBM::Deep, BerkeleyDB, PostgreSQL, MySQL, ...).
3304  
3305 The hashref is consumed by C<Database::Join> to perform a zero-copy
3306 C<ATTACH DATABASE> so rows never pass through Perl.
3307 Nested C<Database::Join> objects that are themselves SQLite-backed expose themselves
3308 as attachable sources to parent joins through the same interface.
3309  
3310 Subclasses may override this method to expose non-SQLite DBI connections
3311 if their join layer supports them.
3312  
3313 =head3 API SPECIFICATION
3314  
3315 =head4 Arguments
3316  
3317 None beyond the implicit invocant.
3318  
3319 =head4 Returns
3320  
3321 A hashref C<{ dbh =E<gt> DBI::db, table =E<gt> Str }> on a SQLite-backed
3322 instance, or C<undef> on all other backends.
3323  
3324 =cut
3325  
3326 sub dbi_source
3327 2 ▶{
Subroutine dbi_source: called CC=5 SCAR=17.0
Pod documented
3328 2 my $self = shift;
3329  
3330 2 my $table = $self->_open_table({});
3331 2 my $dbh = $self->{'_dbh'}{$table};
3332  
3333 2 ▶ return undef unless $dbh && ref($dbh) && (($dbh->{Driver}{Name} // '') eq 'SQLite');
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh and ref $dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" 1 1 2
Condition50%4/8
$dbh and ref $dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite"
!ll&&!rl&&r
011
$dbh and ref $dbh
!ll&&!rl&&r
002
$$dbh{"Driver"}{"Name"} // ""
l!l
20
MC/DC0%0/3
$dbh and ref $dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite"
$dbh ref $dbh $$dbh{"Driver"}{"Name"}
Truth table25%1/4
A and B and C
A= $dbhB= ref $dbhC= $$dbh{"Driver"}{"Name"}
ABCresult
0XX0
10X0
1100
1111
3334  
3335 1 return { dbh => $dbh, table => $table };
3336 }
3337  
3338 =head2 aggregate
3339  
3340 Groups matching rows and computes aggregate measures over each group.
3341 Pushes C<GROUP BY> SQL to the backend when a DBI handle is available;
3342 otherwise folds rows in Perl (BerkeleyDB, DBM::Deep, XLSX, JSON, HTML, Redis).
3343  
3344 my $rows = $db->aggregate(
3345 by => ['region', 'month'],
3346 measures => [
3347 { col => 'amount', fn => 'sum', as => 'revenue' },
3348 { fn => 'count', as => 'orders' },
3349 ],
3350 status => 'active',
3351 );
3352  
3353 # Grand total (no 'by')
3354 my $row = $db->aggregate(
3355 measures => [{ col => 'score', fn => 'avg', as => 'mean_score' }],
3356 )->[0];
3357  
3358 Reserved parameter keys (extracted before the rest is treated as WHERE criteria):
3359 C<by>, C<measures>, C<having>, C<sort_by>, C<limit>, C<offset>, C<table>, C<join>.
3360  
3361 Always returns an B<arrayref of hashrefs> (never C<undef>); returns C<[]> when
3362 no group qualifies. Row keys are the C<by> column names (in declaration order)
3363 followed by the measure aliases.
3364  
3365 =head3 Measure specification
3366  
3367 Each measure hashref:
3368  
3369 { col => 'amount', fn => 'sum', as => 'revenue' }
3370 { fn => 'count', as => 'orders' } # COUNT(*)
3371 { col => 'amount', fn => 'count', as => 'paid' } # COUNT(col)
3372 { col => 'customer', fn => 'count_distinct', as => 'customers' }
3373  
3374 C<fn> must be one of C<sum>, C<avg>, C<min>, C<max>, C<count>, C<count_distinct>,
3375 C<median>, C<stddev> (case-insensitive). C<col> is required for every function
3376 except plain C<count>. C<as> (the result key) must be a valid SQL identifier
3377 and must not duplicate another alias or a C<by> column name.
3378  
3379 C<median> computes the median (middle value of sorted values; average of two
3380 middle values for even count). C<stddev> computes the sample standard deviation
3381 (using N-1 denominator). Both are computed in Perl (no SQL pushdown); on SQL
3382 backends the full result set is fetched first and then folded in memory.
3383  
3384 Empty-set normalisation: C<median> and C<stddev> become C<undef> when no rows
3385 are present; C<stddev> on a single-row group returns C<0>.
3386  
3387 =head3 HAVING
3388  
3389 Pass C<< having => { alias_or_by_col => criterion } >> to filter groups
3390 after aggregation. Accepts the full criteria syntax.
3391  
3392 having => { revenue => { '>' => 1000 } }
3393  
3394 =head3 PSEUDOCODE
3395  
3396 1. _open_table; croak if JOIN requested on no-DBI backend.
3397 2. _validate_aggregate_spec: extract/validate by/measures/having/
3398 sort_by/limit/offset; remainder of params is WHERE criteria.
3399 3. Merge base_criteria.
3400 4. SQL path (DBI handle): _build_aggregate_sql; prepare_cached+execute;
3401 normalise empty-set values; cache; fixate; return.
3402 5. Perl fold: selectall_arrayref(criteria); _fold_aggregate;
3403 HAVING via _match_criteria; sort; offset; limit; fixate; return.
3404  
3405 =head3 Backend notes
3406  
3407 On slurp-only backends all matching rows are materialised before folding.
3408 Use a SQL backend (SQLite DSN, PostgreSQL, MySQL) for large datasets.
3409  
3410 =head3 API SPECIFICATION
3411  
3412 =head4 Arguments
3413  
3414 by => ArrayRef[Str] # optional: GROUP BY column names
3415 measures => ArrayRef[HashRef] # required: one or more measure specs
3416 having => HashRef # optional: post-group filter criteria
3417 sort_by => Str | ArrayRef # optional: sort column (Str) or [col,dir]
3418 limit => Int # optional: max rows to return
3419 offset => Int # optional: rows to skip before returning
3420 join => HashRef | ArrayRef # optional: join spec(s) -- SQL path only
3421 no_fixate => Bool # optional: skip read-only locking
3422 %criteria # optional: WHERE filter before grouping
3423  
3424 Each element of C<measures> is a hashref with keys:
3425  
3426 col => Str # column to aggregate; omit only for plain count()
3427 fn => Str # one of: sum avg min max count count_distinct median stddev
3428 as => Str # result key name (required; valid SQL identifier)
3429  
3430 =head4 Returns
3431  
3432 ArrayRef[HashRef]
3433  
3434 An arrayref of hashrefs. Each hashref has one key per C<by> column
3435 and one key per measure C<as> alias. Returns C<[]> (empty arrayref)
3436 when no groups match -- never C<undef>.
3437  
3438 Empty-set normalisation: C<sum>/C<count>/C<count_distinct> become
3439 C<0>; C<avg>/C<min>/C<max>/C<median>/C<stddev> become C<undef> when no rows
3440 are present.
3441  
3442 =cut
3443  
3444 sub aggregate
3445 166 ▶{
Subroutine aggregate: called CC=41 SCAR=39.6
Pod documented
3446 166 my $self = shift;
3447  
3448 166 $self->_open_table({});
3449  
3450 166 my $params;
3451 166 ▶ if($self->{'no_entry'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 75 91 166
elsif (scalar @_) { } 90 1 91
3452 75 $params = Params::Get::get_params(undef, \@_);
3453 } elsif(scalar(@_)) {
3454 90 $params = Params::Get::get_params('entry', @_);
3455 }
3456 166 ▶ $params //= {};
Condition100%2/2
$params //= {}
l!l
1642
MC/DC100%1/1
$params //= {}
$params
Truth table100%2/2
A
A= $params
Aresult
11
00
3457  
3458 166 my $table = $self->_open_table($params);
3459 166 my $no_fixate = delete $params->{'no_fixate'};
3460 166 my $join_spec = delete $params->{'join'};
3461 166 delete $params->{'table'};
3462  
3463 166 my $join_clause = '';
3464 166 ▶ if($join_spec) {
Branch: 1 branch
BranchTrueFalseTotal
if ($join_spec) 6 160 166
3465 6 $join_clause = $self->_build_joins($join_spec);
3466 }
3467  
3468 164 my $spec = $self->_validate_aggregate_spec($params);
3469  
3470 85 ▶ if($join_clause && !$self->{'_dbh'}{$table}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($join_clause and not $$self{"_dbh"}{$table}) 3 82 85
Condition100%3/3
$join_clause and not $$self{"_dbh"}{$table}
!ll&&!rl&&r
8113
MC/DC100%2/2
$join_clause and not $$self{"_dbh"}{$table}
$join_clause not $$self{"_dbh"}{$table}
Truth table100%3/3
A and not(B)
A= $join_clauseB= not $$self{"_dbh"}{$table}
ABresult
0X0
100
111
3471 3 ▶ my $backend = $self->{'berkeley'} ? 'BerkeleyDB' : ($self->{'type'} // 'slurp');
Branch: 1 branch
BranchTrueFalseTotal
$$self{'berkeley'} ? : 0 3 3
Condition50%1/2
$$self{"type"} // "slurp"
l!l
30
MC/DC0%0/1
$$self{"type"} // "slurp"
$$self{"type"}
Truth table50%1/2
A
A= $$self{"type"}
Aresult
11
00
3472 3 Carp::croak(ref($self), ": aggregate: cannot aggregate a JOIN on the $backend backend");
3473 }
3474  
3475 82 $spec->{'criteria'} = $self->_merge_base_criteria($spec->{'criteria'});
3476  
3477 # median and stddev are computed in Perl; skip SQL pushdown for them.
3478 82 my $has_perl_only = grep { $PERL_ONLY_AGG_FNS{$_->{'fn'}} } @{$spec->{'measures'}};
3479  
3480 82 ▶ if($self->{'_dbh'}{$table} && !$has_perl_only) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"_dbh"}{$table} and not $has_perl_only) 53 29 82
Condition100%3/3
$$self{"_dbh"}{$table} and not $has_perl_only
!ll&&!rl&&r
21853
MC/DC100%2/2
$$self{"_dbh"}{$table} and not $has_perl_only
$$self{"_dbh"}{$table} not $has_perl_only
Truth table100%3/3
A and not(B)
A= $$self{"_dbh"}{$table}B= not $has_perl_only
ABresult
0X0
100
111
3481 53 my ($sql, $args) = $self->_build_aggregate_sql($spec, $join_clause, $table, $self->{'_dbh'}{$table});
3482  
3483 49 ▶ if(defined($args->[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$args[0]) { } 21 28 49
3484 21 $self->_debug("aggregate $sql: ", join(', ', @{$args}));
3485 } else {
3486 28 $self->_debug("aggregate $sql");
3487 }
3488  
3489 49 my ($key, $c);
3490 49 ▶ if($c = $self->{'cache'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c = $$self{'cache'}) { } 0 49 49
3491 0 $key = ref($self) . "::$sql aggregate";
3492 0 ▶ $key .= ' ' . join(', ', @{$args}) if defined($args->[0]);
Branch: 1 branch
BranchTrueFalseTotal
if defined $$args[0] 0 0 0
3493 0 $self->_debug("aggregate cache key = '$key'");
3494 0 ▶ if(my $rc = $c->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $c->get($key)) 0 0 0
3495 0 $self->_debug('aggregate: cache HIT');
3496 0 return $rc;
3497 }
3498 0 $self->_debug('aggregate: cache MISS');
3499 } else {
3500 49 $self->_debug('aggregate cache not used');
3501 }
3502  
3503 my $sth = $self->{'_dbh'}{$table}->prepare_cached($sql)
3504 49 ▶ or do {
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $$self{"_dbh"}{$table}->prepare_cached($sql) or do { $self->_warn("aggregate prepare failed on $sql"); Carp::croak(ref $self, ": prepare failed: ", $$self{"_dbh"}{$table}->errstr) } 49 0 49
3505 0 $self->_warn("aggregate prepare failed on $sql");
3506 0 Carp::croak(ref($self), ': prepare failed: ', $self->{'_dbh'}{$table}->errstr());
3507 };
3508 0 ▶ $sth->execute(@{$args}) or Carp::croak("$sql: @{$args}");
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@{$args;}) or Carp::croak("${sql}: @{$args;}") 48 0 48
3509  
3510 48 my @rows;
3511 48 ▶ while(my $row = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 69 48 117
3512 69 push @rows, $row;
3513 }
3514  
3515 # Empty-set normalisation (§5.3 of design spec):
3516 # sum / count / count_distinct → 0; avg / min / max stay undef.
3517 48 for my $row (@rows) {
3518 69 for my $m (@{$spec->{'measures'}}) {
3519 76 my $as = $m->{'as'};
3520 76 my $fn = $m->{'fn'};
3521 76 ▶ if(!defined($row->{$as})
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $$row{$as} and $fn eq "sum" || $fn eq "count" || $fn eq "count_distinct") 3 73 76
Condition77%7/9
not defined $$row{$as} and $fn eq "sum" || $fn eq "count" || $fn eq "count_distinct"
!ll&&!rl&&r
7213
$fn eq "sum" or $fn eq "count" or $fn eq "count_distinct"
l!l&&r!l&&!r
301
$fn eq "sum" or $fn eq "count"
l!l&&r!l&&!r
301
MC/DC50%2/4
not defined $$row{$as} and $fn eq "sum" || $fn eq "count" || $fn eq "count_distinct"
not defined $$row{$as} $fn eq "sum" $fn eq "count" $fn eq "count_distinct"
Truth table60%3/5
not(A) and B or C or D
A= not defined $$row{$as}B= $fn eq "sum"C= $fn eq "count"D= $fn eq "count_distinct"
ABCDresult
0XXX0
10000
11XX1
101X1
10011
3522 && ($fn eq 'sum' || $fn eq 'count' || $fn eq 'count_distinct')) {
3523 3 $row->{$as} = 0;
3524 }
3525 }
3526 }
3527  
3528 48 ▶ $c->set($key, \@rows, $self->{'cache_duration'}) if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 0 48 48
3529 48 ▶ $self->_fixate(\@rows) unless $no_fixate;
Branch: 1 branch
BranchTrueFalseTotal
unless $no_fixate 47 1 48
3530 48 return set_return(\@rows, { type => 'arrayref' });
3531 }
3532  
3533 # Perl fold path: fetch matching rows then group and aggregate in memory.
3534 # BerkeleyDB rows arrive via _scan_berkeley inside selectall_arrayref;
3535 # all other no-DBI backends (XLSX, Deep, JSON, HTML, Redis) have slurped data.
3536 29 my $rows = $self->selectall_arrayref(%{$spec->{'criteria'}});
3537 29 my $out = $self->_fold_aggregate($rows, $spec);
3538  
3539 29 ▶ if(my $hav = $spec->{'having'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $hav = $$spec{"having"}) 1 28 29
3540 1 $out = [ grep { $self->_match_criteria($_, $hav) } @{$out} ];
3541 }
3542  
3543 29 my @by_names = map { $_->{'name'} } @{$spec->{'by'}};
3544 29 ▶ if(my $s = $spec->{'sort'}) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $s = $$spec{'sort'}) { } 5 24 29
elsif (@by_names) { } 11 13 24
3545 5 my ($scol, $sdir) = @{$s};
3546 5 my $desc = ($sdir eq 'DESC');
3547 5 my $is_measure = $spec->{'aliases'}{$scol};
3548 5 @{$out} = sort {
3549 5 ▶ my ($av, $bv) = ($a->{$scol} // '', $b->{$scol} // '');
Condition50%2/4
$$a{$scol} // ""
l!l
50
$$b{$scol} // ""
l!l
50
MC/DC0%0/1
$$a{$scol} // ""
$$a{$scol}
MC/DC0%0/1
$$b{$scol} // ""
$$b{$scol}
Truth table50%1/2
A
A= $$a{$scol}
Aresult
11
00
Truth table50%1/2
A
A= $$b{$scol}
Aresult
11
00
3550 5 ▶ $desc
Branch: 3 branches
BranchTrueFalseTotal
$desc ? : 1 4 5
$is_measure ? : 1 0 1
$is_measure ? : 0 4 4
3551 ? ($is_measure ? ($bv <=> $av) : ($bv cmp $av))
3552 : ($is_measure ? ($av <=> $bv) : ($av cmp $bv))
3553 5 } @{$out};
3554 } elsif(@by_names) {
3555 11 @{$out} = sort {
3556 6 my $cmp = 0;
3557 6 for my $bn (@by_names) {
3558 6 ▶ $cmp = (($a->{$bn} // '') cmp ($b->{$bn} // ''));
Condition50%2/4
$$a{$bn} // ""
l!l
60
$$b{$bn} // ""
l!l
60
MC/DC0%0/1
$$a{$bn} // ""
$$a{$bn}
MC/DC0%0/1
$$b{$bn} // ""
$$b{$bn}
Truth table50%1/2
A
A= $$a{$bn}
Aresult
11
00
Truth table50%1/2
A
A= $$b{$bn}
Aresult
11
00
3559 6 ▶ last if $cmp;
Branch: 1 branch
BranchTrueFalseTotal
if $cmp 6 0 6
3560 }
3561 $cmp;
3562 11 } @{$out};
3563 }
3564  
3565 0 ▶ splice(@{$out}, 0, $spec->{'offset'}) if $spec->{'offset'};
Branch: 1 branch
BranchTrueFalseTotal
if $$spec{"offset"} 0 29 29
3566 29 ▶ splice(@{$out}, $spec->{'limit'}) if defined $spec->{'limit'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $$spec{"limit"} 4 25 29
3567  
3568 29 ▶ $self->_fixate($out) unless $no_fixate;
Branch: 1 branch
BranchTrueFalseTotal
unless $no_fixate 28 1 29
3569 29 return set_return($out, { type => 'arrayref' });
3570 }
3571  
3572 # Validate and extract aggregate spec from %params (mutates $params in place,
3573 # deleting aggregate control keys; the remainder becomes the WHERE criteria).
3574 # Returns \%spec on success; croaks on invalid input.
3575 # No database access — pure validation, trivially unit-testable.
3576 sub _validate_aggregate_spec
3577 230 ▶{
Subroutine _validate_aggregate_spec: called CC=53 SCAR=39.7
3578 230 my ($self, $params) = @_;
3579  
3580 230 my $by = delete $params->{'by'};
3581 230 my $meas = delete $params->{'measures'};
3582 230 my $having = delete $params->{'having'};
3583 230 my $sort_by = delete $params->{'sort_by'};
3584 230 my $limit = delete $params->{'limit'};
3585 230 my $offset = delete $params->{'offset'};
3586  
3587 230 ▶ $by //= [];
Condition100%2/2
$by //= []
l!l
100130
MC/DC100%1/1
$by //= []
$by
Truth table100%2/2
A
A= $by
Aresult
11
00
3588 230 ▶ Carp::croak(ref($self), ": aggregate: 'by' must be an arrayref of column names")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $by eq "ARRAY" 5 225 230
3589 unless ref($by) eq 'ARRAY';
3590  
3591 225 my (@by_names, %by_name_set);
3592 225 for my $col (@{$by}) {
3593 84 ▶ Carp::croak(ref($self), ": aggregate: unsafe group-by column '". ($col // '') ."'")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col and $col =~ /$SAFE_QUALIFIED/ 14 70 84
Condition100%5/5
defined $col and $col =~ /$SAFE_QUALIFIED/
!ll&&!rl&&r
11370
$col // ""
l!l
131
MC/DC100%2/2
defined $col and $col =~ /$SAFE_QUALIFIED/
defined $col $col =~ /$SAFE_QUALIFIED/
MC/DC100%1/1
$col // ""
$col
Truth table100%3/3
A and B
A= defined $colB= $col =~ /$SAFE_QUALIFIED/
ABresult
0X0
100
111
Truth table100%2/2
A
A= $col
Aresult
11
00
3594 unless defined($col) && $col =~ $SAFE_QUALIFIED;
3595 70 push @by_names, $col;
3596 70 $by_name_set{$col} = 1;
3597 }
3598  
3599 Carp::croak(ref($self), ": aggregate: 'measures' must be a non-empty arrayref")
3600 211 ▶ unless ref($meas) eq 'ARRAY' && scalar(@{$meas}) > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $meas eq "ARRAY" and scalar @{$meas;} > 0 10 201 211
Condition100%3/3
ref $meas eq "ARRAY" and scalar @{$meas;} > 0
!ll&&!rl&&r
73201
MC/DC100%2/2
ref $meas eq "ARRAY" and scalar @{$meas;} > 0
ref $meas eq "ARRAY" scalar @{$meas;} > 0
Truth table100%3/3
A and B
A= ref $meas eq "ARRAY"B= scalar @{$meas;} > 0
ABresult
0X0
100
111
3601  
3602 201 my (@measure_specs, %alias_set);
3603 201 for my $m (@{$meas}) {
3604 215 ▶ Carp::croak(ref($self), ": aggregate: measure must be a hashref, got ", (ref($m) || 'scalar'))
Branch: 1 branch
BranchTrueFalseTotal
unless ref $m eq "HASH" 6 209 215
Condition100%2/2
ref $m || 'scalar'
l!l
24
MC/DC100%1/1
ref $m || 'scalar'
ref $m
Truth table100%2/2
A
A= ref $m
Aresult
11
00
3605 unless ref($m) eq 'HASH';
3606  
3607 209 ▶ my $fn = lc($m->{'fn'} // '');
Condition100%2/2
$$m{"fn"} // ""
l!l
2072
MC/DC100%1/1
$$m{"fn"} // ""
$$m{"fn"}
Truth table100%2/2
A
A= $$m{"fn"}
Aresult
11
00
3608 209 my $col = $m->{'col'};
3609 209 my $as = $m->{'as'};
3610  
3611 Carp::croak(ref($self), ": aggregate: unknown measure function '$fn'")
3612 209 ▶ unless $VALID_AGG_FNS{$fn};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_AGG_FNS{$fn} 9 200 209
3613  
3614 200 ▶ if($fn ne 'count') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn ne "count") 122 78 200
3615 122 ▶ Carp::croak(ref($self), ": aggregate: measure column is required for function '$fn'")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col and length $col 9 113 122
Condition100%3/3
defined $col and length $col
!ll&&!rl&&r
81113
MC/DC100%2/2
defined $col and length $col
defined $col length $col
Truth table100%3/3
A and B
A= defined $colB= length $col
ABresult
0X0
100
111
3616 unless defined($col) && length($col);
3617 }
3618 191 ▶ if(defined($col) && length($col)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $col and length $col) 116 75 191
Condition66%2/3
defined $col and length $col
!ll&&!rl&&r
750116
MC/DC50%1/2
defined $col and length $col
defined $col length $col
Truth table66%2/3
A and B
A= defined $colB= length $col
ABresult
0X0
100
111
3619 116 ▶ Carp::croak(ref($self), ": aggregate: unsafe measure column '$col'")
Branch: 1 branch
BranchTrueFalseTotal
unless $col =~ /$SAFE_QUALIFIED/ 12 104 116
3620 unless $col =~ $SAFE_QUALIFIED;
3621 }
3622  
3623 179 ▶ Carp::croak(ref($self), ": aggregate: measure 'as' is required")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $as and length $as 5 174 179
Condition100%3/3
defined $as and length $as
!ll&&!rl&&r
32174
MC/DC100%2/2
defined $as and length $as
defined $as length $as
Truth table100%3/3
A and B
A= defined $asB= length $as
ABresult
0X0
100
111
3624 unless defined($as) && length($as);
3625 174 ▶ Carp::croak(ref($self), ": aggregate: unsafe measure alias '$as'")
Branch: 1 branch
BranchTrueFalseTotal
unless $as =~ /$SAFE_IDENTIFIER/ 12 162 174
3626 unless $as =~ $SAFE_IDENTIFIER;
3627 Carp::croak(ref($self), ": aggregate: duplicate measure alias '$as'")
3628 162 ▶ if $alias_set{$as};
Branch: 1 branch
BranchTrueFalseTotal
if $alias_set{$as} 4 158 162
3629 Carp::croak(ref($self), ": aggregate: measure alias '$as' collides with a group-by column")
3630 158 ▶ if $by_name_set{$as};
Branch: 1 branch
BranchTrueFalseTotal
if $by_name_set{$as} 3 155 158
3631  
3632 155 $alias_set{$as} = 1;
3633  
3634 155 my $sql_expr;
3635 155 ▶ if($fn eq 'count' && !(defined($col) && length($col))) {
Branch: 4 branches
BranchTrueFalseTotal
if ($fn eq 'count' and not defined $col && length $col) { } 67 88 155
elsif ($fn eq 'count_distinct') { } 4 84 88
elsif ($fn eq 'median') { } 6 78 84
elsif ($fn eq 'stddev') { } 3 75 78
Condition83%5/6
$fn eq "count" and not defined $col && length $col
!ll&&!rl&&r
85367
defined $col && length $col
!ll&&!rl&&r
6703
MC/DC66%2/3
$fn eq "count" and not defined $col && length $col
$fn eq "count" defined $col length $col
Truth table75%3/4
A and not(B && C)
A= $fn eq "count"B= defined $colC= length $col
ABCresult
0XX0
1110
10X1
1101
3636 67 $sql_expr = 'COUNT(*)';
3637 } elsif($fn eq 'count_distinct') {
3638 4 $sql_expr = "COUNT(DISTINCT $col)";
3639 } elsif($fn eq 'median') {
3640 6 $sql_expr = "MEDIAN($col)"; # Perl-fold path only; SQL expr unused
3641 } elsif($fn eq 'stddev') {
3642 3 $sql_expr = "STDDEV($col)"; # Perl-fold path only; SQL expr unused
3643 } else {
3644 75 $sql_expr = uc($fn) . "($col)";
3645 }
3646  
3647 155 push @measure_specs, { fn => $fn, col => $col, as => $as, sql => $sql_expr };
3648 }
3649  
3650 141 ▶ if(defined $having) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $having) 19 122 141
3651 19 ▶ Carp::croak(ref($self), ": aggregate: 'having' must be a hashref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $having eq "HASH" 3 16 19
3652 unless ref($having) eq 'HASH';
3653 16 for my $k (keys %{$having}) {
3654 16 ▶ next if $k eq '-or' || $k eq '-and';
Branch: 1 branch
BranchTrueFalseTotal
if $k eq "-or" or $k eq "-and" 3 13 16
Condition100%3/3
$k eq "-or" or $k eq "-and"
l!l&&r!l&&!r
2113
MC/DC100%2/2
$k eq "-or" or $k eq "-and"
$k eq "-or" $k eq "-and"
Truth table100%3/3
A or B
A= $k eq "-or"B= $k eq "-and"
ABresult
1X1
011
000
3655 Carp::croak(ref($self), ": aggregate: having key '$k' is not a group-by column or measure alias")
3656 13 ▶ unless $by_name_set{$k} || $alias_set{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless $by_name_set{$k} or $alias_set{$k} 4 9 13
Condition100%3/3
$by_name_set{$k} or $alias_set{$k}
l!l&&r!l&&!r
274
MC/DC100%2/2
$by_name_set{$k} or $alias_set{$k}
$by_name_set{$k} $alias_set{$k}
Truth table100%3/3
A or B
A= $by_name_set{$k}B= $alias_set{$k}
ABresult
1X1
011
000
3657 }
3658 }
3659  
3660 134 my ($sort_col, $sort_dir);
3661 134 ▶ if(defined $sort_by) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_by) 22 112 134
3662 22 ▶ ($sort_col, $sort_dir) = ref($sort_by) eq 'ARRAY'
Branch: 1 branch
BranchTrueFalseTotal
ref $sort_by eq 'ARRAY' ? : 12 10 22
3663 ? ($sort_by->[0], $sort_by->[1])
3664 : ($sort_by, 'ASC');
3665 22 ▶ $sort_dir = defined($sort_dir) ? uc($sort_dir) : 'ASC';
Branch: 1 branch
BranchTrueFalseTotal
defined $sort_dir ? : 20 2 22
3666 Carp::croak(ref($self), ": aggregate: sort_by names '". ($sort_col // '') ."', which is not a group-by column or measure alias")
3667 22 ▶ unless defined($sort_col) && ($by_name_set{$sort_col} || $alias_set{$sort_col});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sort_col and $by_name_set{$sort_col} || $alias_set{$sort_col} 5 17 22
Condition100%8/8
defined $sort_col and $by_name_set{$sort_col} || $alias_set{$sort_col}
!ll&&!rl&&r
1417
$by_name_set{$sort_col} or $alias_set{$sort_col}
l!l&&r!l&&!r
984
$sort_col // ""
l!l
41
MC/DC100%3/3
defined $sort_col and $by_name_set{$sort_col} || $alias_set{$sort_col}
defined $sort_col $by_name_set{$sort_col} $alias_set{$sort_col}
MC/DC100%1/1
$sort_col // ""
$sort_col
Truth table100%4/4
A and B or C
A= defined $sort_colB= $by_name_set{$sort_col}C= $alias_set{$sort_col}
ABCresult
0XX0
1000
11X1
1011
Truth table100%2/2
A
A= $sort_col
Aresult
11
00
3668 17 ▶ Carp::croak(ref($self), ": aggregate: sort_by names '". ($sort_col // '') ."', which is not a group-by column or measure alias")
Branch: 1 branch
BranchTrueFalseTotal
unless $sort_dir eq "ASC" or $sort_dir eq "DESC" 1 16 17
Condition80%4/5
$sort_dir eq "ASC" or $sort_dir eq "DESC"
l!l&&r!l&&!r
1151
$sort_col // ""
l!l
10
MC/DC100%2/2
$sort_dir eq "ASC" or $sort_dir eq "DESC"
$sort_dir eq "ASC" $sort_dir eq "DESC"
MC/DC0%0/1
$sort_col // ""
$sort_col
Truth table100%3/3
A or B
A= $sort_dir eq "ASC"B= $sort_dir eq "DESC"
ABresult
1X1
011
000
Truth table50%1/2
A
A= $sort_col
Aresult
11
00
3669 unless $sort_dir eq 'ASC' || $sort_dir eq 'DESC';
3670 }
3671  
3672 128 ▶ if(defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 18 110 128
3673 18 ▶ if($limit !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $limit =~ /\A\d+\z/) { } 5 13 18
3674 5 Carp::carp('aggregate: limit must be a non-negative integer, ignoring');
3675 5 undef $limit;
3676 } else {
3677 13 $limit = int($limit);
3678 }
3679 }
3680 128 ▶ if(defined $offset) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 7 121 128
3681 7 ▶ if($offset !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $offset =~ /\A\d+\z/) { } 3 4 7
3682 3 Carp::carp('aggregate: offset must be a non-negative integer, ignoring');
3683 3 undef $offset;
3684 } else {
3685 4 $offset = int($offset);
3686 }
3687 }
3688  
3689 return {
3690 128 ▶ by => [ map { { name => $_ } } @by_names ],
Branch: 1 branch
BranchTrueFalseTotal
defined $sort_col ? : 16 112 128
3691 measures => \@measure_specs,
3692 aliases => \%alias_set,
3693 by_names => \%by_name_set,
3694 having => $having,
3695 criteria => $params,
3696 sort => defined($sort_col) ? [ $sort_col, $sort_dir ] : undef,
3697 limit => $limit,
3698 offset => $offset,
3699 };
3700 }
3701  
3702 # Build the GROUP BY aggregate SQL query and bind-value list.
3703 # Returns ($sql, \@bind_args).
3704 sub _build_aggregate_sql
3705 61 ▶{
Subroutine _build_aggregate_sql: called CC=22 SCAR=33.0
3706 61 my ($self, $spec, $join_clause, $table, $dbh) = @_;
3707  
3708 61 my @by_names = map { $_->{'name'} } @{$spec->{'by'}};
3709 61 my @meas = @{$spec->{'measures'}};
3710  
3711 # SELECT: by columns then "expr AS alias" for each measure.
3712 61 my @sel;
3713 61 push @sel, @by_names;
3714 61 push @sel, map { "$_->{'sql'} AS $_->{'as'}" } @meas;
3715 61 my $sql = 'SELECT ' . join(', ', @sel) . " FROM $table";
3716 61 ▶ $sql .= " $join_clause" if $join_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $join_clause 1 60 61
3717  
3718 # WHERE: criteria + CSV comment-row guard.
3719 61 my ($where, $wargs) = $self->_build_where($spec->{'criteria'});
3720 59 my @args = @{$wargs};
3721  
3722 59 ▶ if($join_clause) {
Branch: 2 branches
BranchTrueFalseTotal
if ($join_clause) { } 1 58 59
elsif (($$self{'type'} // '') eq 'CSV' and not $$self{'no_entry'}) { } 9 49 58
3723 1 ▶ $sql .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 1 1
3724 ▶ } elsif(($self->{'type'} // '') eq 'CSV' && !$self->{'no_entry'}) {
Condition60%3/5
($$self{"type"} // "") eq "CSV" and not $$self{"no_entry"}
!ll&&!rl&&r
4909
$$self{"type"} // ""
l!l
580
MC/DC0%0/2
($$self{"type"} // "") eq "CSV" and not $$self{"no_entry"}
$$self{"type"} not $$self{"no_entry"}
Truth table33%1/3
A and not(B)
A= $$self{"type"}B= not $$self{"no_entry"}
ABresult
0X0
100
111
3725 9 my $id = $self->{'id'};
3726 9 $sql .= " WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
3727 9 ▶ $sql .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 9 9
3728 } else {
3729 49 ▶ $sql .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 14 35 49
3730 }
3731  
3732 # GROUP BY.
3733 59 ▶ $sql .= ' GROUP BY ' . join(', ', @by_names) if @by_names;
Branch: 1 branch
BranchTrueFalseTotal
if @by_names 34 25 59
3734  
3735 # HAVING: substitute measure aliases with their SQL expressions so the
3736 # query is valid on PostgreSQL (which forbids output-column aliases in HAVING).
3737 59 ▶ if(my $hav = $spec->{'having'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $hav = $$spec{"having"}) 8 51 59
3738 8 my %a2s = map { $_->{'as'} => $_->{'sql'} } @meas;
3739 8 my ($hfrag, $hargs) = $self->_build_having_fragment($hav, \%a2s);
3740 6 ▶ if($hfrag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hfrag) 6 0 6
3741 6 $sql .= " HAVING $hfrag";
3742 6 push @args, @{$hargs};
3743 }
3744 }
3745  
3746 # ORDER BY: explicit sort_by takes precedence; default is by-columns ASC.
3747 57 ▶ if(my $s = $spec->{'sort'}) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $s = $$spec{'sort'}) { } 9 48 57
elsif (@by_names) { } 27 21 48
3748 9 $sql .= " ORDER BY $s->[0] $s->[1]";
3749 } elsif(@by_names) {
3750 27 $sql .= ' ORDER BY ' . join(', ', @by_names);
3751 }
3752  
3753 # LIMIT / OFFSET.
3754 57 ▶ if(defined $spec->{'limit'}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $$spec{'limit'}) { } 8 49 57
elsif (defined $$spec{'offset'}) { } 0 49 49
3755 8 $sql .= ' LIMIT ?';
3756 8 push @args, $spec->{'limit'};
3757 } elsif(defined $spec->{'offset'}) {
3758 # SQLite requires a LIMIT clause before OFFSET; -1 means no upper bound.
3759 $sql .= ' LIMIT -1'
3760 if ($dbh && (($dbh->{Driver}{Name} // '') eq 'SQLite'))
3761 0 ▶ || (($self->{'_dialect'} // '') eq 'sqlite');
Branch: 1 branch
BranchTrueFalseTotal
if $dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite" 0 0 0
Condition0%0/10
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite"
l!l&&r!l&&!r
000
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite"
!ll&&!rl&&r
000
$$dbh{"Driver"}{"Name"} // ""
l!l
00
$$self{"_dialect"} // ""
l!l
00
MC/DC0%0/3
$dbh and ($$dbh{"Driver"}{"Name"} // "") eq "SQLite" or ($$self{"_dialect"} // "") eq "sqlite"
$dbh $$dbh{"Driver"}{"Name"} $$self{"_dialect"}
Truth table0%0/5
A and B or C
A= $dbhB= $$dbh{"Driver"}{"Name"}C= $$self{"_dialect"}
ABCresult
11X1
0X11
1011
0X00
1000
3762 }
3763 57 ▶ if(defined $spec->{'offset'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$spec{"offset"}) 2 55 57
3764 2 $sql .= ' OFFSET ?';
3765 2 push @args, $spec->{'offset'};
3766 }
3767  
3768 57 return ($sql, \@args);
3769 }
3770  
3771 # Build a HAVING clause fragment, substituting measure aliases with their SQL
3772 # expressions (PostgreSQL forbids output-column aliases in HAVING).
3773 # $alias_to_sql maps alias → SQL expression (e.g. revenue → SUM(amount)).
3774 # Mirrors _build_where_conditions but uses pre-validated SQL expressions as LHS
3775 # for measure keys, so the $SAFE_QUALIFIED identifier check is skipped there.
3776 #
3777 # SQLite 3.51+ regression: bound parameters compared to aggregate expressions
3778 # (SUM, AVG, etc.) in HAVING are not type-coerced to numeric automatically,
3779 # causing numeric comparisons to return 0 rows. When the LHS was substituted
3780 # from an alias (i.e. it is an aggregate expression, not a bare column name),
3781 # wrap all numeric bind placeholders in CAST(? AS REAL) so SQLite performs the
3782 # comparison correctly. CAST(? AS REAL) is valid SQL in SQLite, PostgreSQL and
3783 # MySQL and is a no-op on those dialects where type coercion already works.
3784 #
3785 # Returns ($fragment, \@bind_values).
3786 sub _build_having_fragment
3787 26 ▶{
Subroutine _build_having_fragment: called CC=18 SCAR=28.9
3788 26 my ($self, $having, $alias_to_sql) = @_;
3789  
3790 26 my (@clauses, @args);
3791 26 for my $k (sort keys %{$having}) {
3792 26 my $agg_expr = $alias_to_sql->{$k};
3793 26 ▶ my $lhs = $agg_expr // $k;
Condition66%2/3
$agg_expr // $k
l!l&&r!l&&!r
1880
MC/DC0%0/2
$agg_expr // $k
$agg_expr $k
Truth table66%2/3
A // B
A= $agg_exprB= $k
ABresult
1X1
011
000
3794 26 my $val = $having->{$k};
3795  
3796 # ph() returns the right placeholder: CAST(? AS REAL) for aggregate
3797 # expression LHS (numeric result), bare ? for group-by column LHS.
3798 26 ▶ my $ph = defined($agg_expr) ? 'CAST(? AS REAL)' : '?';
Branch: 1 branch
BranchTrueFalseTotal
defined $agg_expr ? : 18 8 26
3799  
3800 26 ▶ if(ref($val) eq 'HASH') {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $val eq 'HASH') { } 17 9 26
elsif (ref $val) { } 3 6 9
elsif (not defined $val) { } 1 5 6
elsif ($val =~ /[%_]/) { } 1 4 5
3801 17 for my $op (keys %{$val}) {
3802 17 my $operand = $val->{$op};
3803 17 ▶ if($op eq '-in' || $op eq '-not_in') {
Branch: 6 branches
BranchTrueFalseTotal
if ($op eq '-in' or $op eq '-not_in') { } 2 15 17
elsif ($op eq '-between') { } 1 14 15
elsif ($op eq '-like') { } 1 13 14
elsif ($op eq '-not_like') { } 1 12 13
elsif ($op eq '!=') { } 2 10 12
elsif ($op =~ /\A[<>]=?\z/) { } 9 1 10
Condition100%3/3
$op eq "-in" or $op eq "-not_in"
l!l&&r!l&&!r
1115
MC/DC100%2/2
$op eq "-in" or $op eq "-not_in"
$op eq "-in" $op eq "-not_in"
Truth table100%3/3
A or B
A= $op eq "-in"B= $op eq "-not_in"
ABresult
1X1
011
000
3804 2 ▶ my $sql_op = $op eq '-in' ? 'IN' : 'NOT IN';
Branch: 1 branch
BranchTrueFalseTotal
$op eq '-in' ? : 1 1 2
3805 2 my $phs = join(', ', ($ph) x scalar(@{$operand}));
3806 2 push @clauses, "$lhs $sql_op ($phs)";
3807 2 push @args, @{$operand};
3808 } elsif($op eq '-between') {
3809 1 push @clauses, "$lhs BETWEEN $ph AND $ph";
3810 1 push @args, $operand->[0], $operand->[1];
3811 } elsif($op eq '-like') {
3812 1 push @clauses, "$lhs LIKE ?";
3813 1 push @args, $operand;
3814 } elsif($op eq '-not_like') {
3815 1 push @clauses, "$lhs NOT LIKE ?";
3816 1 push @args, $operand;
3817 } elsif($op eq '!=') {
3818 2 ▶ if(!defined($operand)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $operand) { } 1 1 2
3819 1 push @clauses, "$lhs IS NOT NULL";
3820 } else {
3821 1 push @clauses, "$lhs != $ph";
3822 1 push @args, $operand;
3823 }
3824 } elsif($op =~ /\A[<>]=?\z/) {
3825 9 push @clauses, "$lhs $op $ph";
3826 9 push @args, $operand;
3827 } else {
3828 1 Carp::croak("Unknown operator '$op' in having for key '$k'");
3829 }
3830 }
3831 } elsif(ref($val)) {
3832 3 Carp::croak("$k: expected scalar or operator hashref, got ", ref($val));
3833 } elsif(!defined($val)) {
3834 1 push @clauses, "$lhs IS NULL";
3835 } elsif($val =~ /[%_]/) {
3836 1 push @clauses, "$lhs LIKE ?";
3837 1 push @args, $val;
3838 } else {
3839 4 push @clauses, "$lhs = $ph";
3840 4 push @args, $val;
3841 }
3842 }
3843  
3844 22 return (join(' AND ', @clauses), \@args);
3845 }
3846  
3847 # Recursive in-memory criterion matcher supporting -or/-and groupings.
3848 # Used by aggregate()'s Perl fold path for HAVING evaluation.
3849 # Leaf comparisons are delegated to _match_criterion.
3850 # Uses exists() guards for fixated slurp hashrefs (see Data::Reuse notes).
3851 sub _match_criteria
3852 37 ▶{
Subroutine _match_criteria: called CC=11 SCAR=24.0
3853 37 my ($self, $row, $criteria) = @_;
3854  
3855 37 for my $k (keys %{$criteria}) {
3856 37 ▶ if($k eq '-or') {
Branch: 2 branches
BranchTrueFalseTotal
if ($k eq '-or') { } 6 31 37
elsif ($k eq '-and') { } 5 26 31
3857 6 my $found = 0;
3858 6 for my $sub (@{$criteria->{$k}}) {
3859 8 ▶ if($self->_match_criteria($row, $sub)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_match_criteria($row, $sub)) 4 4 8
3860 4 $found = 1;
3861 4 last;
3862 }
3863 }
3864 6 ▶ return 0 unless $found;
Branch: 1 branch
BranchTrueFalseTotal
unless $found 2 4 6
3865 } elsif($k eq '-and') {
3866 5 for my $sub (@{$criteria->{$k}}) {
3867 8 ▶ return 0 unless $self->_match_criteria($row, $sub);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_match_criteria($row, $sub) 1 7 8
3868 }
3869 } else {
3870 26 ▶ my $row_val = exists($row->{$k}) ? $row->{$k} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$k} ? : 23 3 26
3871 26 ▶ return 0 unless $self->_match_criterion($row_val, $criteria->{$k}, $k);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_match_criterion($row_val, $$criteria{$k}, $k) 11 15 26
3872 }
3873 }
3874 23 return 1;
3875 }
3876  
3877 # Group an arrayref of rows and compute aggregate measures in Perl.
3878 # Used by aggregate() when no DBI handle is available (slurp-only backends).
3879 # All matching rows are materialised by the caller before this is called.
3880 # Returns an arrayref of group rows (unsorted; sorting happens in aggregate()).
3881 sub _fold_aggregate
3882 46 ▶{
Subroutine _fold_aggregate: called CC=88 SCAR=51.4
3883 46 my ($self, $rows, $spec) = @_;
3884  
3885 46 my @by_specs = @{$spec->{'by'}};
3886 46 my @meas = @{$spec->{'measures'}};
3887  
3888 # Pre-compute per-measure numeric flag from cached schema (only when already
3889 # populated by a prior schema() call — never triggers a PRAGMA round-trip).
3890 my @meas_numeric = map {
3891 46 my $col = $_->{'col'};
3892 ($col && $self->{'_schema'})
3893 50 ▶ ? do {
Branch: 1 branch
BranchTrueFalseTotal
$col && $$self{'_schema'} ? : 0 50 50
Condition66%2/3
$col and $$self{"_schema"}
!ll&&!rl&&r
20300
MC/DC0%0/2
$col and $$self{"_schema"}
$col $$self{"_schema"}
Truth table66%2/3
A and B
A= $colB= $$self{"_schema"}
ABresult
0X0
100
111
3894 0 ▶ my $t = ($self->{'_schema'}{$col} // {})->{'type'} // 'TEXT';
Condition0%0/4
($$self{"_schema"}{$col} // {})->{"type"} // "TEXT"
l!l
00
$$self{"_schema"}{$col} // {}
l!l
00
MC/DC0%0/1
($$self{"_schema"}{$col} // {})->{"type"} // "TEXT"
$$self{"_schema"}{$col}
Truth table0%0/2
A
A= $$self{"_schema"}{$col}
Aresult
11
00
3895 0 ▶ ($t eq 'INTEGER' || $t eq 'REAL') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$t eq 'INTEGER' || $t eq 'REAL' ? : 0 0 0
Condition0%0/3
$t eq "INTEGER" or $t eq "REAL"
l!l&&r!l&&!r
000
MC/DC0%0/2
$t eq "INTEGER" or $t eq "REAL"
$t eq "INTEGER" $t eq "REAL"
Truth table0%0/3
A or B
A= $t eq "INTEGER"B= $t eq "REAL"
ABresult
1X1
011
000
3896 }
3897 : 0;
3898 } @meas;
3899  
3900 46 my (%groups, @group_order);
3901  
3902 46 for my $row (@{$rows}) {
3903 # Build group key: NUL-separated by-column values ('undef' → '').
3904 my $key = join("\x00",
3905 147 ▶ map { exists($row->{$_->{'name'}}) ? ($row->{$_->{'name'}} // '') : '' }
Branch: 1 branch
BranchTrueFalseTotal
exists $$row{$$_{'name'}} ? : 77 0 77
Condition100%2/2
$$row{$$_{"name"}} // ""
l!l
761
MC/DC100%1/1
$$row{$$_{"name"}} // ""
$$row{$$_{"name"}}
Truth table100%2/2
A
A= $$row{$$_{"name"}}
Aresult
11
00
3906 @by_specs
3907 );
3908  
3909 147 ▶ unless(exists $groups{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $groups{$key}) 57 90 147
3910 57 push @group_order, $key;
3911 57 my %g;
3912 # Seed group with by-column values from the first row seen.
3913 57 for my $b (@by_specs) {
3914 32 ▶ $g{$b->{'name'}} = exists($row->{$b->{'name'}}) ? $row->{$b->{'name'}} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $$row{$$b{'name'}} ? : 32 0 32
3915 }
3916 # Initialise per-measure accumulator state.
3917 57 for my $m (@meas) {
3918 62 my $fn = $m->{'fn'};
3919 62 my $as = $m->{'as'};
3920 62 ▶ if($fn eq 'sum') {
Branch: 6 branches
BranchTrueFalseTotal
if ($fn eq 'sum') { } 15 47 62
elsif ($fn eq 'avg') { } 5 42 47
elsif ($fn eq 'min' or $fn eq 'max') { } 3 39 42
elsif ($fn eq 'count') { } 25 14 39
elsif ($fn eq 'count_distinct') { } 1 13 14
elsif ($fn eq 'median' or $fn eq 'stddev') { } 13 0 13
3921 15 $g{"__agg_$as"} = { sum => 0, bad => 0, first_bad => undef };
3922 } elsif($fn eq 'avg') {
3923 5 $g{"__agg_$as"} = { sum => 0, cnt => 0, bad => 0, first_bad => undef };
3924 ▶ } elsif($fn eq 'min' || $fn eq 'max') {
Condition100%3/3
$fn eq "min" or $fn eq "max"
l!l&&r!l&&!r
2139
MC/DC100%2/2
$fn eq "min" or $fn eq "max"
$fn eq "min" $fn eq "max"
Truth table100%3/3
A or B
A= $fn eq "min"B= $fn eq "max"
ABresult
1X1
011
000
3925 3 $g{"__agg_$as"} = { val => undef };
3926 } elsif($fn eq 'count') {
3927 25 $g{"__agg_$as"} = { cnt => 0 };
3928 } elsif($fn eq 'count_distinct') {
3929 1 $g{"__agg_$as"} = { seen => {} };
3930 ▶ } elsif($fn eq 'median' || $fn eq 'stddev') {
Condition66%2/3
$fn eq "median" or $fn eq "stddev"
l!l&&r!l&&!r
850
MC/DC0%0/2
$fn eq "median" or $fn eq "stddev"
$fn eq "median" $fn eq "stddev"
Truth table66%2/3
A or B
A= $fn eq "median"B= $fn eq "stddev"
ABresult
1X1
011
000
3931 13 $g{"__agg_$as"} = { vals => [] };
3932 }
3933 }
3934 57 $groups{$key} = \%g;
3935 }
3936  
3937 147 my $g = $groups{$key};
3938 147 my $mi = 0;
3939 147 for my $m (@meas) {
3940 161 my $fn = $m->{'fn'};
3941 161 my $col = $m->{'col'};
3942 161 my $as = $m->{'as'};
3943 161 my $numeric = $meas_numeric[$mi++];
3944 161 my $acc = $g->{"__agg_$as"};
3945 161 ▶ my $val = (defined($col) && exists($row->{$col})) ? $row->{$col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $col && exists $row->{$col} ? : 101 60 161
Condition66%2/3
defined $col and exists $row->{$col}
!ll&&!rl&&r
600101
MC/DC50%1/2
defined $col and exists $row->{$col}
defined $col exists $row->{$col}
Truth table66%2/3
A and B
A= defined $colB= exists $row->{$col}
ABresult
0X0
100
111
3946  
3947 161 ▶ if($fn eq 'sum') {
Branch: 7 branches
BranchTrueFalseTotal
if ($fn eq 'sum') { } 34 127 161
elsif ($fn eq 'avg') { } 11 116 127
elsif ($fn eq 'min') { } 5 111 116
elsif ($fn eq 'max') { } 3 108 111
elsif ($fn eq 'count') { } 62 46 108
elsif ($fn eq 'count_distinct') { } 4 42 46
elsif ($fn eq 'median' or $fn eq 'stddev') { } 42 0 42
3948 34 ▶ if(defined($val) && length($val) && Scalar::Util::looks_like_number($val)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $val and length $val and &Scalar::Util::looks_like_number($val)) { } 30 4 34
elsif (defined $val and length $val) { } 4 0 4
Condition50%3/6
defined $val and length $val and &Scalar::Util::looks_like_number($val)
!ll&&!rl&&r
0430
defined $val and length $val
!ll&&!rl&&r
0034
MC/DC33%1/3
defined $val and length $val and &Scalar::Util::looks_like_number($val)
defined $val length $val &Scalar::Util::looks_like_number($val)
Truth table50%2/4
A and B and C
A= defined $valB= length $valC= &Scalar::Util::looks_like_number($val)
ABCresult
0XX0
10X0
1100
1111
3949 30 $acc->{'sum'} += $val;
3950 ▶ } elsif(defined($val) && length($val)) {
Condition33%1/3
defined $val and length $val
!ll&&!rl&&r
004
MC/DC0%0/2
defined $val and length $val
defined $val length $val
Truth table33%1/3
A and B
A= defined $valB= length $val
ABresult
0X0
100
111
3951 4 $acc->{'bad'}++;
3952 4 ▶ $acc->{'first_bad'} //= $val;
Condition66%2/3
$$acc{"first_bad"} //= $val
l!l&&r!l&&!r
130
MC/DC0%0/2
$$acc{"first_bad"} //= $val
$$acc{"first_bad"} $val
Truth table66%2/3
A //= B
A= $$acc{"first_bad"}B= $val
ABresult
1X1
011
000
3953 }
3954 } elsif($fn eq 'avg') {
3955 11 ▶ if(defined($val) && length($val) && Scalar::Util::looks_like_number($val)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $val and length $val and &Scalar::Util::looks_like_number($val)) { } 8 3 11
elsif (defined $val and length $val) { } 1 4 5
Condition83%5/6
defined $val and length $val and &Scalar::Util::looks_like_number($val)
!ll&&!rl&&r
218
defined $val and length $val
!ll&&!rl&&r
209
MC/DC66%2/3
defined $val and length $val and &Scalar::Util::looks_like_number($val)
defined $val length $val &Scalar::Util::looks_like_number($val)
Truth table75%3/4
A and B and C
A= defined $valB= length $valC= &Scalar::Util::looks_like_number($val)
ABCresult
0XX0
10X0
1100
1111
3956 8 $acc->{'sum'} += $val;
3957 8 $acc->{'cnt'}++;
3958 ▶ } elsif(defined($val) && length($val)) {
Condition66%2/3
defined $val and length $val
!ll&&!rl&&r
201
MC/DC50%1/2
defined $val and length $val
defined $val length $val
Truth table66%2/3
A and B
A= defined $valB= length $val
ABresult
0X0
100
111
3959 1 $acc->{'bad'}++;
3960 1 ▶ $acc->{'first_bad'} //= $val;
Condition33%1/3
$$acc{"first_bad"} //= $val
l!l&&r!l&&!r
010
MC/DC0%0/2
$$acc{"first_bad"} //= $val
$$acc{"first_bad"} $val
Truth table33%1/3
A //= B
A= $$acc{"first_bad"}B= $val
ABresult
1X1
011
000
3961 }
3962 } elsif($fn eq 'min') {
3963 5 ▶ if(defined($val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 3 2 5
3964 3 ▶ if(!defined($acc->{'val'})) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $$acc{'val'}) { } 1 2 3
elsif ($numeric ? $val < $$acc{'val'} : $val lt $$acc{'val'}) { } 1 1 2
3965 1 $acc->{'val'} = $val;
3966 ▶ } elsif($numeric ? ($val < $acc->{'val'}) : ($val lt $acc->{'val'})) {
Branch: 1 branch
BranchTrueFalseTotal
$numeric ? : 0 2 2
3967 1 $acc->{'val'} = $val;
3968 }
3969 }
3970 } elsif($fn eq 'max') {
3971 3 ▶ if(defined($val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 3 0 3
3972 3 ▶ if(!defined($acc->{'val'})) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $$acc{'val'}) { } 1 2 3
elsif ($numeric ? $val > $$acc{'val'} : $val gt $$acc{'val'}) { } 0 2 2
3973 1 $acc->{'val'} = $val;
3974 ▶ } elsif($numeric ? ($val > $acc->{'val'}) : ($val gt $acc->{'val'})) {
Branch: 1 branch
BranchTrueFalseTotal
$numeric ? : 0 2 2
3975 0 $acc->{'val'} = $val;
3976 }
3977 }
3978 } elsif($fn eq 'count') {
3979 62 ▶ if(defined $col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $col) { } 2 60 62
3980 2 ▶ $acc->{'cnt'}++ if defined($val);
Branch: 1 branch
BranchTrueFalseTotal
if defined $val 1 1 2
3981 } else {
3982 60 $acc->{'cnt'}++;
3983 }
3984 } elsif($fn eq 'count_distinct') {
3985 4 ▶ $acc->{'seen'}{$val}++ if defined($val);
Branch: 1 branch
BranchTrueFalseTotal
if defined $val 3 1 4
3986 ▶ } elsif($fn eq 'median' || $fn eq 'stddev') {
Condition66%2/3
$fn eq "median" or $fn eq "stddev"
l!l&&r!l&&!r
27150
MC/DC0%0/2
$fn eq "median" or $fn eq "stddev"
$fn eq "median" $fn eq "stddev"
Truth table66%2/3
A or B
A= $fn eq "median"B= $fn eq "stddev"
ABresult
1X1
011
000
3987 42 ▶ if(defined($val) && length($val) && Scalar::Util::looks_like_number($val)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $val and length $val and &Scalar::Util::looks_like_number($val)) { } 42 0 42
elsif (defined $val and length $val) { } 0 0 0
Condition33%2/6
defined $val and length $val and &Scalar::Util::looks_like_number($val)
!ll&&!rl&&r
0042
defined $val and length $val
!ll&&!rl&&r
0042
MC/DC0%0/3
defined $val and length $val and &Scalar::Util::looks_like_number($val)
defined $val length $val &Scalar::Util::looks_like_number($val)
Truth table25%1/4
A and B and C
A= defined $valB= length $valC= &Scalar::Util::looks_like_number($val)
ABCresult
0XX0
10X0
1100
1111
3988 42 push @{$acc->{'vals'}}, $val + 0;
3989 ▶ } elsif(defined($val) && length($val)) {
Condition0%0/3
defined $val and length $val
!ll&&!rl&&r
000
MC/DC0%0/2
defined $val and length $val
defined $val length $val
Truth table0%0/3
A and B
A= defined $valB= length $val
ABresult
0X0
100
111
3990 0 $acc->{'bad'}++;
3991 0 ▶ $acc->{'first_bad'} //= $val;
Condition0%0/3
$$acc{"first_bad"} //= $val
l!l&&r!l&&!r
000
MC/DC0%0/2
$$acc{"first_bad"} //= $val
$$acc{"first_bad"} $val
Truth table0%0/3
A //= B
A= $$acc{"first_bad"}B= $val
ABresult
1X1
011
000
3992 }
3993 }
3994 }
3995 }
3996  
3997 # Finalise groups: derive final result values from accumulators.
3998 # %warned tracks which measure aliases have already had their non-numeric
3999 # warning emitted; the warning fires at most once per measure per call.
4000 46 my (%warned, @out);
4001 46 for my $key (@group_order) {
4002 57 my $g = $groups{$key};
4003 57 my %result;
4004 57 for my $b (@by_specs) {
4005 32 $result{$b->{'name'}} = $g->{$b->{'name'}};
4006 }
4007 57 for my $m (@meas) {
4008 62 my $fn = $m->{'fn'};
4009 62 my $as = $m->{'as'};
4010 62 my $col = $m->{'col'};
4011 62 my $acc = $g->{"__agg_$as"};
4012 62 my $val;
4013 62 ▶ if($fn eq 'sum') {
Branch: 7 branches
BranchTrueFalseTotal
if ($fn eq 'sum') { } 15 47 62
elsif ($fn eq 'avg') { } 5 42 47
elsif ($fn eq 'min' or $fn eq 'max') { } 3 39 42
elsif ($fn eq 'count') { } 25 14 39
elsif ($fn eq 'count_distinct') { } 1 13 14
elsif ($fn eq 'median') { } 8 5 13
elsif ($fn eq 'stddev') { } 5 0 5
4014 15 ▶ if($acc->{'bad'} && !$warned{$as}++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$acc{"bad"} and not $warned{$as}++) 3 12 15
Condition66%2/3
$$acc{"bad"} and not $warned{$as}++
!ll&&!rl&&r
1203
MC/DC50%1/2
$$acc{"bad"} and not $warned{$as}++
$$acc{"bad"} not $warned{$as}++
Truth table66%2/3
A and not(B)
A= $$acc{"bad"}B= not $warned{$as}++
ABresult
0X0
100
111
4015 3 Carp::carp("aggregate: column '$col' has $acc->{'bad'} non-numeric value(s), skipped, e.g. '$acc->{'first_bad'}'");
4016 }
4017 15 $val = $acc->{'sum'};
4018 } elsif($fn eq 'avg') {
4019 5 ▶ if($acc->{'bad'} && !$warned{$as}++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$acc{"bad"} and not $warned{$as}++) 1 4 5
Condition66%2/3
$$acc{"bad"} and not $warned{$as}++
!ll&&!rl&&r
401
MC/DC50%1/2
$$acc{"bad"} and not $warned{$as}++
$$acc{"bad"} not $warned{$as}++
Truth table66%2/3
A and not(B)
A= $$acc{"bad"}B= not $warned{$as}++
ABresult
0X0
100
111
4020 1 Carp::carp("aggregate: column '$col' has $acc->{'bad'} non-numeric value(s), skipped, e.g. '$acc->{'first_bad'}'");
4021 }
4022 5 ▶ $val = $acc->{'cnt'} ? ($acc->{'sum'} / $acc->{'cnt'}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$$acc{'cnt'} ? : 3 2 5
4023 ▶ } elsif($fn eq 'min' || $fn eq 'max') {
Condition100%3/3
$fn eq "min" or $fn eq "max"
l!l&&r!l&&!r
2139
MC/DC100%2/2
$fn eq "min" or $fn eq "max"
$fn eq "min" $fn eq "max"
Truth table100%3/3
A or B
A= $fn eq "min"B= $fn eq "max"
ABresult
1X1
011
000
4024 3 $val = $acc->{'val'};
4025 } elsif($fn eq 'count') {
4026 25 $val = $acc->{'cnt'};
4027 } elsif($fn eq 'count_distinct') {
4028 1 $val = scalar(keys %{$acc->{'seen'}});
4029 } elsif($fn eq 'median') {
4030 8 ▶ if($acc->{'bad'} && !$warned{$as}++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$acc{"bad"} and not $warned{$as}++) 0 8 8
Condition33%1/3
$$acc{"bad"} and not $warned{$as}++
!ll&&!rl&&r
800
MC/DC0%0/2
$$acc{"bad"} and not $warned{$as}++
$$acc{"bad"} not $warned{$as}++
Truth table33%1/3
A and not(B)
A= $$acc{"bad"}B= not $warned{$as}++
ABresult
0X0
100
111
4031 0 Carp::carp("aggregate: column '$col' has $acc->{'bad'} non-numeric value(s), skipped, e.g. '$acc->{'first_bad'}'");
4032 }
4033 8 my @sorted = sort { $a <=> $b } @{$acc->{'vals'}};
4034 8 my $n = scalar @sorted;
4035 8 ▶ if($n == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($n == 0) { } 0 8 8
elsif ($n % 2) { } 5 3 8
4036 0 $val = undef;
4037 } elsif($n % 2) {
4038 5 $val = $sorted[int($n / 2)];
4039 } else {
4040 3 $val = ($sorted[$n / 2 - 1] + $sorted[$n / 2]) / 2;
4041 }
4042 } elsif($fn eq 'stddev') {
4043 5 ▶ if($acc->{'bad'} && !$warned{$as}++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$acc{"bad"} and not $warned{$as}++) 0 5 5
Condition33%1/3
$$acc{"bad"} and not $warned{$as}++
!ll&&!rl&&r
500
MC/DC0%0/2
$$acc{"bad"} and not $warned{$as}++
$$acc{"bad"} not $warned{$as}++
Truth table33%1/3
A and not(B)
A= $$acc{"bad"}B= not $warned{$as}++
ABresult
0X0
100
111
4044 0 Carp::carp("aggregate: column '$col' has $acc->{'bad'} non-numeric value(s), skipped, e.g. '$acc->{'first_bad'}'");
4045 }
4046 5 my $n = scalar @{$acc->{'vals'}};
4047 5 ▶ if($n < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n < 2) { } 1 4 5
4048 1 ▶ $val = $n == 1 ? 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$n == 1 ? : 1 0 1
4049 } else {
4050 4 my $mean = 0;
4051 4 $mean += $_ for @{$acc->{'vals'}};
4052 4 $mean /= $n;
4053 4 my $sq_sum = 0;
4054 4 $sq_sum += ($_ - $mean) ** 2 for @{$acc->{'vals'}};
4055 4 $val = sqrt($sq_sum / ($n - 1));
4056 }
4057 }
4058 62 $result{$as} = $val;
4059 }
4060 57 push @out, \%result;
4061 }
4062  
4063 46 return \@out;
4064 }
4065  
4066 =head2 query
4067  
4068 Returns a new L<Database::Abstraction::Query> builder object bound to this
4069 database instance, for fluent method-chaining queries.
4070  
4071 # All active rows with high scores, newest first, max 10
4072 my $rows = $db->query
4073 ->where(status => 'active')
4074 ->where(score => { '>' => 80 })
4075 ->order_by('score DESC')
4076 ->limit(10)
4077 ->all();
4078  
4079 # Single row
4080 my $row = $db->query->where(name => 'Alice')->first();
4081  
4082 # Just a count
4083 my $n = $db->query->where(status => 'active')->count();
4084  
4085 See L<Database::Abstraction::Query> for the full API.
4086  
4087 =cut
4088  
4089 sub query
4090 128 ▶{
Subroutine query: called CC=1 SCAR=0.0
Pod documented
4091 128 my $self = shift;
4092 128 require Database::Abstraction::Query;
4093 128 return Database::Abstraction::Query->new(_db => $self);
4094 }
4095  
4096 =head2 AUTOLOAD - column shortcut
4097  
4098 Calling an unknown method whose name matches a column name performs a column
4099 lookup. The method name is the column you want; the arguments are criteria.
4100  
4101 # Scalar context: return the first match
4102 my $name = $db->name(entry => 'key1');
4103  
4104 # List context: return all matching values
4105 my @names = $db->name();
4106  
4107 # Shortcut when the table has an 'entry' key column
4108 my $name = $db->name('key1'); # same as name(entry => 'key1')
4109  
4110 # Unique/distinct values
4111 my @statuses = $db->status(distinct => 1);
4112  
4113 B<In list context> the full column is returned (all rows), ordered by the
4114 column value. B<In scalar context> only the first match is returned
4115 (C<LIMIT 1>).
4116  
4117 Results come from the slurp cache when available.
4118  
4119 Throws an error if the column does not exist (slurp mode) or if AUTOLOAD
4120 has been disabled with C<< auto_load => 0 >>.
4121  
4122 =head3 PSEUDOCODE
4123  
4124 1. Extract column name from $AUTOLOAD; guard on DESTROY.
4125 2. Croak if auto_load => 0.
4126 3. Validate $column against /^[a-zA-Z_][a-zA-Z0-9_]*$/.
4127 4. If data is slurped:
4128 a. List context, no params -> map column over all rows (exists guard).
4129 b. entry-only param -> direct hash lookup (exists guard).
4130 c. No params, scalar -> first value in hash.
4131 d. no_entry set -> scan array for matching key/value pair.
4132 e. Other params -> scan keyed hash for matching column.
4133 5. If not slurped, build SQL:
4134 - List: SELECT column FROM table [WHERE ...] ORDER BY column
4135 - Scalar: SELECT DISTINCT column FROM table [WHERE ...] LIMIT 1
4136 6. Check cache; return on HIT.
4137 7. prepare_cached + execute; fetch result.
4138 8. Store in cache; fixate; return.
4139  
4140 =cut
4141  
4142 124 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=82 SCAR=46.8
4143 124 our $AUTOLOAD;
4144 124 my ($column) = $AUTOLOAD =~ /::([A-Za-z_]\w*)\z/;
4145  
4146 124 ▶ return if($column eq 'DESTROY');
Branch: 1 branch
BranchTrueFalseTotal
if $column eq "DESTROY" 0 124 124
4147 124 ▶ return if($column =~ /\A_/); # never treat private method names as column lookups
Branch: 1 branch
BranchTrueFalseTotal
if $column =~ /\A_/ 7 117 124
4148  
4149 117 ▶ my $self = shift or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = shift() or return 117 0 117
4150  
4151 117 ▶ Carp::croak(__PACKAGE__, ": Unknown column $column") if(!ref($self));
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 0 117 117
4152  
4153 # Allow the AUTOLOAD feature to be disabled
4154 117 ▶ Carp::croak(__PACKAGE__, ": AUTOLOAD disabled (auto_load => 0)") if(exists($self->{'auto_load'}) && !$self->{'auto_load'});
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"auto_load"} and not $$self{"auto_load"} 6 111 117
Condition66%2/3
exists $self->{"auto_load"} and not $$self{"auto_load"}
!ll&&!rl&&r
11106
MC/DC50%1/2
exists $self->{"auto_load"} and not $$self{"auto_load"}
exists $self->{"auto_load"} not $$self{"auto_load"}
Truth table66%2/3
A and not(B)
A= exists $self->{"auto_load"}B= not $$self{"auto_load"}
ABresult
0X0
100
111
4155  
4156 # Validate column name - only allow safe column name
4157 111 ▶ Carp::croak(__PACKAGE__, ": Invalid column name: $column") unless $column =~ $SAFE_IDENTIFIER;
Branch: 1 branch
BranchTrueFalseTotal
unless $column =~ /$SAFE_IDENTIFIER/ 0 111 111
4158  
4159 111 my $table = $self->_open_table();
4160  
4161 109 my %params;
4162 109 ▶ if(ref($_[0]) eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $_[0] eq 'HASH') { } 2 107 109
elsif (scalar(@_) % 2 == 0) { } 78 29 107
elsif (scalar @_ == 1) { } 29 0 29
4163 2 %params = %{$_[0]};
4164 } elsif((scalar(@_) % 2) == 0) {
4165 78 %params = @_;
4166 } elsif(scalar(@_) == 1) {
4167 # Don't error on key-value databases, since there's no idea of columns
4168 29 ▶ if($self->{'no_entry'} && !$self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"no_entry"} and not $$self{"berkeley"}) 0 29 29
Condition33%1/3
$$self{"no_entry"} and not $$self{"berkeley"}
!ll&&!rl&&r
2900
MC/DC0%0/2
$$self{"no_entry"} and not $$self{"berkeley"}
$$self{"no_entry"} not $$self{"berkeley"}
Truth table33%1/3
A and not(B)
A= $$self{"no_entry"}B= not $$self{"berkeley"}
ABresult
0X0
100
111
4169 0 Carp::croak(ref($self), "::($_[0]): ", $self->{'id'}, ' is not a column');
4170 }
4171 29 $params{'entry'} = shift;
4172 }
4173  
4174 109 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 0 109 109
4175 0 ▶ if(my $id = $self->{'id'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = $$self{"id"}) 0 0 0
4176 0 return $self->{'berkeley'}->{$params{$id}};
4177 }
4178 0 return $self->{'berkeley'}->{$params{'entry'}};
4179 }
4180  
4181 109 ▶ croak('Where did the data come from?') if(!defined($self->{'type'}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$self{"type"} 0 109 109
4182 109 my $query;
4183 109 my $done_where = 0;
4184 109 ▶ my $distinct = delete($params{'distinct'}) || delete($params{'unique'});
Condition100%3/3
delete $params{'distinct'} || delete $params{'unique'}
l!l&&r!l&&!r
63100
MC/DC100%2/2
delete $params{'distinct'} || delete $params{'unique'}
delete $params{'distinct'} delete $params{'unique'}
Truth table100%3/3
A || B
A= delete $params{'distinct'}B= delete $params{'unique'}
ABresult
1X1
011
000
4185  
4186 109 ▶ if(wantarray && !$distinct) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray and not $distinct) { } 24 85 109
Condition100%3/3
wantarray and not $distinct
!ll&&!rl&&r
76924
MC/DC100%2/2
wantarray and not $distinct
wantarray not $distinct
Truth table100%3/3
A and not(B)
A= wantarrayB= not $distinct
ABresult
0X0
100
111
4187 24 ▶ if(((scalar keys %params) == 0) && (my $data = $self->{'data'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %params == 0 and my $data = $$self{"data"}) 18 6 24
Condition100%3/3
scalar keys %params == 0 and my $data = $$self{"data"}
!ll&&!rl&&r
2418
MC/DC100%2/2
scalar keys %params == 0 and my $data = $$self{"data"}
scalar keys %params == 0 my $data = $$self{"data"}
Truth table100%3/3
A and B
A= scalar keys %params == 0B= my $data = $$self{"data"}
ABresult
0X0
100
111
4188 # Return all column values from the in-memory hash.
4189 # Use exists() because fixate() locks inner row hashes —
4190 # accessing a disallowed key would throw without the guard.
4191 # Handle both HASH (keyed data) and ARRAY (no_entry CSV slurp).
4192 18 ▶ my @_rows = ref($data) eq 'ARRAY' ? @{$data} : values %{$data};
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'ARRAY' ? : 2 16 18
4193 18 ▶ return map { exists($_->{$column}) ? $_->{$column} : undef } @_rows;
Branch: 1 branch
BranchTrueFalseTotal
exists $_->{$column} ? : 61 10 71
4194 }
4195 6 ▶ if($self->{'data'} && !$self->{'_dbh'}{$table} && !$self->_has_complex_criteria(\%params)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"data"} and not $$self{"_dbh"}{$table} and not $self->_has_complex_criteria(\%params)) 1 5 6
Condition66%4/6
$$self{"data"} and not $$self{"_dbh"}{$table} and not $self->_has_complex_criteria(\%params)
!ll&&!rl&&r
501
$$self{"data"} and not $$self{"_dbh"}{$table}
!ll&&!rl&&r
501
MC/DC33%1/3
$$self{"data"} and not $$self{"_dbh"}{$table} and not $self->_has_complex_criteria(\%params)
$$self{"data"} not $$self{"_dbh"}{$table} not $self->_has_complex_criteria(\%params)
Truth table50%2/4
A and not(B) and not(C)
A= $$self{"data"}B= not $$self{"_dbh"}{$table}C= not $self->_has_complex_criteria(\%params)
ABCresult
0XX0
10X0
1100
1111
4196 # Non-DBI backends (JSON, XLSX, HTML URL): scan in-memory data with criteria.
4197 1 my @param_keys = keys %params;
4198 0 ▶ my @_rows = ref($self->{'data'}) eq 'ARRAY' ? @{$self->{'data'}} : values %{$self->{'data'}};
Branch: 1 branch
BranchTrueFalseTotal
ref $$self{'data'} eq 'ARRAY' ? : 0 1 1
4199 1 ▶ return map { exists($_->{$column}) ? $_->{$column} : undef }
Branch: 1 branch
BranchTrueFalseTotal
exists $_->{$column} ? : 1 0 1
4200 grep {
4201 1 my $row = $_;
4202 4 ▶ all { $self->_match_criterion(exists($row->{$_}) ? $row->{$_} : undef, $params{$_}, $_) } @param_keys
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$_} ? : 4 0 4
4203 4 } @_rows;
4204 }
4205 5 my $id = $self->{'id'};
4206 5 ▶ if(($self->{'type'} eq 'CSV') && !$self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'type'} eq 'CSV' and not $$self{'no_entry'}) { } 4 1 5
Condition66%2/3
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
!ll&&!rl&&r
104
MC/DC50%1/2
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
$$self{"type"} eq "CSV" not $$self{"no_entry"}
Truth table66%2/3
A and not(B)
A= $$self{"type"} eq "CSV"B= not $$self{"no_entry"}
ABresult
0X0
100
111
4207 4 $query = "SELECT $column FROM $table WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
4208 4 $done_where = 1;
4209 } else {
4210 1 $query = "SELECT $column FROM $table";
4211 }
4212 } else {
4213 85 ▶ if(my $data = $self->{'data'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $data = $$self{"data"}) 64 21 85
4214 # The data has been read in using Text::xSV::Slurp,
4215 # so no need to do any SQL
4216 64 $self->_debug('AUTOLOAD using slurped data');
4217 64 ▶ if($self->{'no_entry'}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 4 60 64
elsif (scalar keys %params == 1 and defined(my $key = $params{'entry'})) { } 48 12 60
elsif (scalar keys %params == 0) { } 9 3 12
4218 4 $self->_debug('no_entry is set');
4219 4 my ($key, $value) = %params;
4220 4 ▶ if(defined($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 4 0 4
4221 4 $self->_debug("key = $key, value = $value, column = $column");
4222 4 foreach my $row(@{$data}) {
4223 # exists() guards: fixate() locks row hashes recursively
4224 6 ▶ next unless exists($row->{$key}) && defined($row->{$key}) && $row->{$key} eq $value;
Branch: 1 branch
BranchTrueFalseTotal
unless exists $row->{$key} and defined $$row{$key} and $$row{$key} eq $value 3 3 6
Condition50%3/6
exists $row->{$key} and defined $$row{$key} and $$row{$key} eq $value
!ll&&!rl&&r
033
exists $row->{$key} and defined $$row{$key}
!ll&&!rl&&r
006
MC/DC33%1/3
exists $row->{$key} and defined $$row{$key} and $$row{$key} eq $value
exists $row->{$key} defined $$row{$key} $$row{$key} eq $value
Truth table50%2/4
A and B and C
A= exists $row->{$key}B= defined $$row{$key}C= $$row{$key} eq $value
ABCresult
0XX0
10X0
1100
1111
4225 3 ▶ my $rc = exists($row->{$column}) ? $row->{$column} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$column} ? : 3 0 3
4226 3 ▶ $self->_trace(__LINE__, ": AUTOLOAD $key: return ", defined($rc) ? "'$rc'" : 'undef', ' from slurped data');
Branch: 1 branch
BranchTrueFalseTotal
defined $rc ? : 3 0 3
4227 3 return $rc;
4228 }
4229 1 $self->_debug('not found in slurped data');
4230 }
4231 ▶ } elsif(((scalar keys %params) == 1) && defined(my $key = $params{'entry'})) {
Condition100%3/3
scalar keys %params == 1 and defined(my $key = $params{"entry"})
!ll&&!rl&&r
9348
MC/DC100%2/2
scalar keys %params == 1 and defined(my $key = $params{"entry"})
scalar keys %params == 1 defined(my $key = $params{"entry"})
Truth table100%3/3
A and B
A= scalar keys %params == 1B= defined(my $key = $params{"entry"})
ABresult
0X0
100
111
4232 # Look up a single entry by its key.
4233 # Use exists() before accessing — fixate() locks the outer hash and
4234 # dereferencing a missing key on a locked hash throws an exception.
4235 48 my $rc;
4236 48 ▶ if(exists($data->{$key}) && defined(my $hash = $data->{$key})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{$key} and defined(my $hash = $$data{$key})) 37 11 48
Condition66%2/3
exists $data->{$key} and defined(my $hash = $$data{$key})
!ll&&!rl&&r
11037
MC/DC50%1/2
exists $data->{$key} and defined(my $hash = $$data{$key})
exists $data->{$key} defined(my $hash = $$data{$key})
Truth table66%2/3
A and B
A= exists $data->{$key}B= defined(my $hash = $$data{$key})
ABresult
0X0
100
111
4237 37 ▶ if(!exists($hash->{$column})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $hash->{$column}) 3 34 37
4238 3 Carp::croak(__PACKAGE__, ": There is no column $column in $table");
4239 }
4240 34 $rc = $hash->{$column};
4241 }
4242 45 ▶ if(defined($rc)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rc) { } 32 13 45
4243 32 $self->_trace(__LINE__, ": AUTOLOAD $key: return '$rc' from slurped data");
4244 } else {
4245 13 $self->_trace(__LINE__, ": AUTOLOAD $key: return undef from slurped data");
4246 }
4247 45 return $rc
4248 } elsif((scalar keys %params) == 0) {
4249 9 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 9 0 9
4250 9 ▶ if($distinct) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distinct) 9 0 9
4251 # Single pass instead of three (map→grep→map): avoids three
4252 # intermediate lists of size N on the stack.
4253 9 my %h;
4254 9 for my $r (values %{$data}) {
4255 34 ▶ my $v = exists($r->{$column}) ? $r->{$column} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $r->{$column} ? : 34 0 34
4256 34 ▶ $h{$v} = 1 if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 29 5 34
4257 }
4258 9 return keys %h;
4259 }
4260 # DEAD CODE: unreachable because the outer `if(wantarray && !$distinct)`
4261 # handles the wantarray+!distinct case. In this else branch, wantarray
4262 # implies $distinct (which returns above), so this line is never executed.
4263 # return map { exists($_->{$column}) ? $_->{$column} : undef } values %{$data}
4264 }
4265 # Scalar: return the first value found without building a full list
4266 0 foreach my $v (values %{$data}) {
4267 0 ▶ return exists($v->{$column}) ? $v->{$column} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $v->{$column} ? : 0 0 0
4268 }
4269 } else {
4270 # Keyed data but filtering on a non-key column
4271 3 my ($key, $value) = %params;
4272 3 foreach my $row (values %{$data}) {
4273 10 ▶ next unless exists($row->{$key}) && defined($row->{$key}) && $row->{$key} eq $value;
Branch: 1 branch
BranchTrueFalseTotal
unless exists $row->{$key} and defined $$row{$key} and $$row{$key} eq $value 7 3 10
Condition83%5/6
exists $row->{$key} and defined $$row{$key} and $$row{$key} eq $value
!ll&&!rl&&r
343
exists $row->{$key} and defined $$row{$key}
!ll&&!rl&&r
037
MC/DC66%2/3
exists $row->{$key} and defined $$row{$key} and $$row{$key} eq $value
exists $row->{$key} defined $$row{$key} $$row{$key} eq $value
Truth table75%3/4
A and B and C
A= exists $row->{$key}B= defined $$row{$key}C= $$row{$key} eq $value
ABCresult
0XX0
10X0
1100
1111
4274 3 ▶ next unless exists($row->{$column});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $row->{$column} 0 3 3
4275 3 ▶ if(my $rc = $row->{$column}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $$row{$column}) 3 0 3
4276 3 $self->_trace(__LINE__, ": AUTOLOAD $key: return '$rc' from slurped data");
4277 3 return $rc
4278 }
4279 }
4280 }
4281 return
4282 1 }
4283 # Data has not been slurped in
4284 21 my $id = $self->{'id'};
4285 21 ▶ if(($self->{'type'} eq 'CSV') && !$self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'type'} eq 'CSV' and not $$self{'no_entry'}) { } 13 8 21
Condition100%3/3
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
!ll&&!rl&&r
5313
MC/DC100%2/2
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
$$self{"type"} eq "CSV" not $$self{"no_entry"}
Truth table100%3/3
A and not(B)
A= $$self{"type"} eq "CSV"B= not $$self{"no_entry"}
ABresult
0X0
100
111
4286 13 $query = "SELECT DISTINCT $column FROM $table WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
4287 13 $done_where = 1;
4288 } else {
4289 8 $query = "SELECT DISTINCT $column FROM $table";
4290 }
4291 }
4292 26 my @args;
4293 # Avoid `each` — it carries hidden iterator state across calls
4294 26 for my $k (sort keys %params) {
4295 # Guard against SQL injection via column names — same rule as _build_where_conditions
4296 21 ▶ Carp::croak(__PACKAGE__, ": unsafe column name '$k'")
Branch: 1 branch
BranchTrueFalseTotal
unless $k =~ /$SAFE_QUALIFIED/ 4 17 21
4297 unless $k =~ $SAFE_QUALIFIED;
4298 17 my $value = $params{$k};
4299 17 ▶ $self->_debug(__PACKAGE__, ": AUTOLOAD adding key/value pair $k=>", defined($value) ? $value : 'NULL');
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 15 2 17
4300 17 ▶ if(defined($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) { } 15 2 17
4301 15 ▶ $query .= $done_where ? " AND $k = ?" : " WHERE $k = ?";
Branch: 1 branch
BranchTrueFalseTotal
$done_where ? : 9 6 15
4302 15 $done_where = 1;
4303 15 push @args, $value;
4304 } else {
4305 2 ▶ $query .= $done_where ? " AND $k IS NULL" : " WHERE $k IS NULL";
Branch: 1 branch
BranchTrueFalseTotal
$done_where ? : 2 0 2
4306 2 $done_where = 1;
4307 }
4308 }
4309 22 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 5 17 22
4310 5 $query .= " ORDER BY $column";
4311 } else {
4312 17 $query .= ' LIMIT 1';
4313 }
4314 22 ▶ if(scalar(@args) && $args[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @args and $args[0]) { } 15 7 22
Condition66%2/3
scalar @args and $args[0]
!ll&&!rl&&r
7015
MC/DC50%1/2
scalar @args and $args[0]
scalar @args $args[0]
Truth table66%2/3
A and B
A= scalar @argsB= $args[0]
ABresult
0X0
100
111
4315 15 $self->_debug("AUTOLOAD $query: ", join(', ', @args));
4316 } else {
4317 7 $self->_debug("AUTOLOAD $query");
4318 }
4319 22 my $cache;
4320 22 my $key = ref($self) . '::';
4321 22 ▶ if($cache = $self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache = $$self{'cache'}) { } 8 14 22
4322 8 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 2 6 8
4323 2 $key .= 'array ';
4324 }
4325 8 ▶ if(defined($args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args[0]) { } 6 2 8
4326 6 $key .= "fetchrow $query " . join(', ', @args);
4327 } else {
4328 2 $key .= "fetchrow $query";
4329 }
4330 8 ▶ if(my $rc = $cache->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $cache->get($key)) 4 4 8
4331 4 $self->_debug('cache HIT');
4332 4 ▶ return wantarray ? @{$rc} : $rc; # We stored a ref to the array
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 1 3 4
4333 }
4334 4 $self->_debug('cache MISS');
4335 } else {
4336 14 $self->_debug('cache not used');
4337 }
4338 18 ▶ my $sth = $self->{'_dbh'}{$table}->prepare_cached($query) || croak($query);
Condition50%1/2
$$self{'_dbh'}{$table}->prepare_cached($query) || croak($query)
l!l
180
MC/DC0%0/1
$$self{'_dbh'}{$table}->prepare_cached($query) || croak($query)
$$self{'_dbh'}{$table}->prepare_cached($query)
Truth table50%1/2
A
A= $$self{'_dbh'}{$table}->prepare_cached($query)
Aresult
11
00
4339 18 ▶ $sth->execute(@args) || croak($query);
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@args) or croak($query) 18 0 18
4340  
4341 18 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 4 14 18
4342 # fetchall_arrayref([0]) asks DBI to project column 0 server-side, so each
4343 # returned row is [$col0] instead of the full row — less memory, same result.
4344 4 my @rc = map { $_->[0] } @{$sth->fetchall_arrayref([0])};
4345 4 ▶ if($cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache) 1 3 4
4346 1 $cache->set($key, \@rc, $self->{'cache_duration'}); # Store a ref to the array
4347 }
4348 4 ▶ Database::Abstraction::_fixate($self, \@rc) if(scalar(@rc) && !$self->{'no_fixate'});
Branch: 1 branch
BranchTrueFalseTotal
if scalar @rc and not $$self{"no_fixate"} 4 0 4
Condition33%1/3
scalar @rc and not $$self{"no_fixate"}
!ll&&!rl&&r
004
MC/DC0%0/2
scalar @rc and not $$self{"no_fixate"}
scalar @rc not $$self{"no_fixate"}
Truth table33%1/3
A and not(B)
A= scalar @rcB= not $$self{"no_fixate"}
ABresult
0X0
100
111
4349 4 return @rc;
4350 }
4351 14 my $rc = $sth->fetchrow_array(); # Return the first match only
4352 14 $sth->finish();
4353 14 ▶ if($cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache) 3 11 14
4354 # Store the value, then return it — cache->set() return value is unreliable
4355 3 $cache->set($key, $rc, $self->{'cache_duration'});
4356 }
4357 14 return $rc;
4358 }
4359  
4360 sub DESTROY
4361 624 ▶{
Subroutine DESTROY: called CC=15 SCAR=28.0
4362 624 ▶ if(defined($^V) && ($^V ge 'v5.14.0')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $^V and $^V ge "v5.14.0") 624 0 624
Condition33%1/3
defined $^V and $^V ge "v5.14.0"
!ll&&!rl&&r
00624
MC/DC0%0/2
defined $^V and $^V ge "v5.14.0"
defined $^V $^V ge "v5.14.0"
Truth table33%1/3
A and B
A= defined $^VB= $^V ge "v5.14.0"
ABresult
0X0
100
111
4363 624 ▶ return if ${^GLOBAL_PHASE} eq 'DESTRUCT'; # >= 5.14.0 only
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" 0 624 624
4364 }
4365  
4366 624 my $self = shift;
4367  
4368 # Clean up temporary files — deleting File::Temp objects triggers auto-unlink/rmdir
4369 # If that doesn't happen for some reason, explicitly unlink
4370 624 ▶ if(defined $self->{'_temp_fh'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$self{"_temp_fh"}) 9 615 624
4371 9 my $temp_fh = $self->{'_temp_fh'};
4372 9 my $temp_path = eval { $temp_fh->filename() };
4373 9 delete $self->{'_temp_fh'};
4374 9 undef $temp_fh; # Release the local strong reference
4375 # Fallback explicit unlink if File::Temp didn't clean up
4376 9 ▶ unlink($temp_path) if defined($temp_path) && -f $temp_path;
Branch: 1 branch
BranchTrueFalseTotal
if defined $temp_path and -f $temp_path 1 8 9
Condition100%3/3
defined $temp_path and -f $temp_path
!ll&&!rl&&r
171
MC/DC100%2/2
defined $temp_path and -f $temp_path
defined $temp_path -f $temp_path
Truth table100%3/3
A and B
A= defined $temp_pathB= -f $temp_path
ABresult
0X0
100
111
4377 }
4378 624 delete $self->{'_remote_tmpdir'};
4379  
4380 # Disconnect Redis
4381 624 ▶ if(my $redis = delete $self->{'_redis'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $redis = delete $self->{"_redis"}) 0 624 624
4382 0 eval { $redis->quit() };
4383 }
4384  
4385 # Clean up database handles. They are kept apart from the object's own
4386 # fields, keyed by table, so that a table may have any name -- "data" or
4387 # "id" included -- without its handle overwriting the field of that name.
4388 624 ▶ if(ref($self->{'_dbh'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $$self{"_dbh"} eq "HASH") 466 158 624
4389 466 for my $dbh (grep { defined } values %{delete $self->{'_dbh'}}) {
4390 346 ▶ next unless Scalar::Util::blessed($dbh);
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($dbh) 0 346 346
4391 346 ▶ $dbh->disconnect() if $dbh->can('disconnect');
Branch: 1 branch
BranchTrueFalseTotal
if $dbh->can("disconnect") 346 0 346
4392 346 ▶ $dbh->finish() if $dbh->can('finish');
Branch: 1 branch
BranchTrueFalseTotal
if $dbh->can("finish") 0 346 346
4393 }
4394 }
4395  
4396 # Clean up Berkeley DB
4397 624 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 16 608 624
4398 16 eval {
4399 16 untie %{$self->{'berkeley'}};
4400 };
4401 16 delete $self->{'berkeley'};
4402 }
4403  
4404 # Clear all other attributes to break potential circular references
4405 624 foreach my $key (keys %$self) {
4406 6609 delete $self->{$key};
4407 }
4408 }
4409  
4410 # Build the JOIN clause(s) from a single join hashref or arrayref of hashrefs.
4411 # Each spec needs keys: table (required), on (required), type (default INNER).
4412 sub _build_joins
4413 87 ▶{
Subroutine _build_joins: called CC=19 SCAR=29.4
4414 87 my ($self, $join_spec) = @_;
4415  
4416 87 ▶ my @specs = ref($join_spec) eq 'ARRAY' ? @{$join_spec} : ($join_spec);
Branch: 1 branch
BranchTrueFalseTotal
ref $join_spec eq 'ARRAY' ? : 8 79 87
4417 87 my @clauses;
4418  
4419 87 for my $j (@specs) {
4420 88 ▶ my $type = uc($j->{'type'} // 'INNER');
Condition100%2/2
$$j{"type"} // "INNER"
l!l
3454
MC/DC100%1/1
$$j{"type"} // "INNER"
$$j{"type"}
Truth table100%2/2
A
A= $$j{"type"}
Aresult
11
00
4421 88 ▶ my $jtable = $j->{'table'} or Carp::croak('join: missing "table"');
Branch: 1 branch
BranchTrueFalseTotal
my $jtable = $$j{"table"} or Carp::croak("join: missing \"table\"") 83 5 88
4422 83 ▶ Carp::croak("join: unsafe table name '$jtable'")
Branch: 1 branch
BranchTrueFalseTotal
unless $jtable =~ /$SAFE_QUALIFIED/ 12 71 83
4423 unless $jtable =~ $SAFE_QUALIFIED;
4424 71 ▶ my $on_raw = $j->{'on'} or Carp::croak('join: missing "on" condition');
Branch: 1 branch
BranchTrueFalseTotal
my $on_raw = $$j{"on"} or Carp::croak("join: missing \"on\" condition") 65 6 71
4425 65 ▶ Carp::croak("Invalid JOIN type: $type") unless $VALID_JOIN_TYPES{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_JOIN_TYPES{$type} 7 58 65
4426 58 my $on;
4427 58 ▶ if(ref($on_raw) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $on_raw eq 'HASH') { } 7 51 58
elsif (ref $on_raw eq 'ARRAY') { } 14 37 51
4428 7 my @parts;
4429 7 for my $left (sort keys %{$on_raw}) {
4430 8 my $right = $on_raw->{$left};
4431 8 ▶ Carp::croak("join: unsafe on column '$left'")
Branch: 1 branch
BranchTrueFalseTotal
unless $left =~ /$SAFE_QUALIFIED/ 2 6 8
4432 unless $left =~ $SAFE_QUALIFIED;
4433 6 ▶ Carp::croak("join: unsafe on column '$right'")
Branch: 1 branch
BranchTrueFalseTotal
unless $right =~ /$SAFE_QUALIFIED/ 2 4 6
4434 unless $right =~ $SAFE_QUALIFIED;
4435 4 push @parts, "$left = $right";
4436 }
4437 3 $on = join(' AND ', @parts);
4438 } elsif(ref($on_raw) eq 'ARRAY') {
4439 14 my @elems = @{$on_raw};
4440 14 ▶ Carp::croak('join: on arrayref must have 2 or 3 elements')
Branch: 1 branch
BranchTrueFalseTotal
unless @elems == 2 or @elems == 3 3 11 14
Condition100%3/3
@elems == 2 or @elems == 3
l!l&&r!l&&!r
293
MC/DC100%2/2
@elems == 2 or @elems == 3
@elems == 2 @elems == 3
Truth table100%3/3
A or B
A= @elems == 2B= @elems == 3
ABresult
1X1
011
000
4441 unless @elems == 2 || @elems == 3;
4442 11 ▶ my ($left, $op, $right) = @elems == 2
Branch: 1 branch
BranchTrueFalseTotal
@elems == 2 ? : 2 9 11
4443 ? ($elems[0], '=', $elems[1])
4444 : @elems;
4445 11 ▶ Carp::croak("join: unsafe on column '$left'")
Branch: 1 branch
BranchTrueFalseTotal
unless $left =~ /$SAFE_QUALIFIED/ 1 10 11
4446 unless $left =~ $SAFE_QUALIFIED;
4447 10 ▶ Carp::croak("join: unsafe on column '$right'")
Branch: 1 branch
BranchTrueFalseTotal
unless $right =~ /$SAFE_QUALIFIED/ 1 9 10
4448 unless $right =~ $SAFE_QUALIFIED;
4449 9 ▶ Carp::croak("join: invalid on operator '$op'")
Branch: 1 branch
BranchTrueFalseTotal
unless $op =~ /\A(?:=|!=|<>|<|>|<=|>=)\z/ 2 7 9
4450 unless $op =~ /\A(?:=|!=|<>|<|>|<=|>=)\z/;
4451 7 $on = "$left $op $right";
4452 } else {
4453 37 $on = $on_raw;
4454 }
4455 47 push @clauses, "$type JOIN $jtable ON ($on)";
4456 }
4457  
4458 46 return join(' ', @clauses);
4459 }
4460  
4461 # Infer a SQL type token from an arrayref of sample values for one column.
4462 # Returns 'INTEGER', 'REAL', 'TIMESTAMP', 'DATE', or 'TEXT' (the default).
4463 # undef and empty-string values are treated as NULL and skipped; a column
4464 # whose entire sample is NULL is typed TEXT (most permissive safe default).
4465 # Order of checks: INTEGER before REAL (integers also match REAL); TIMESTAMP
4466 # before DATE (timestamps start like dates but have a time component).
4467 sub _infer_type
4468 21 ▶{
Subroutine _infer_type: called CC=7 SCAR=19.5
4469 21 my ($vals) = @_;
4470 21 ▶ my @non_null = grep { defined($_) && $_ ne '' } @{$vals};
Condition100%3/3
defined $_ && $_ ne ''
!ll&&!rl&&r
8149
MC/DC100%2/2
defined $_ && $_ ne ''
defined $_ $_ ne ''
Truth table100%3/3
A && B
A= defined $_B= $_ ne ''
ABresult
0X0
100
111
4471 21 ▶ return 'TEXT' unless @non_null;
Branch: 1 branch
BranchTrueFalseTotal
unless @non_null 3 18 21
4472 18 ▶ return 'INTEGER' if all { $_ =~ $INFER_INT_RE } @non_null;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if &all(sub { $_ =~ /$INFER_INT_RE/; } , @non_null) 6 12 18
4473 12 ▶ return 'REAL' if all { $_ =~ $INFER_REAL_RE } @non_null;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if &all(sub { $_ =~ /$INFER_REAL_RE/; } , @non_null) 5 7 12
4474 7 ▶ return 'TIMESTAMP' if all { $_ =~ $INFER_TS_RE } @non_null;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if &all(sub { $_ =~ /$INFER_TS_RE/; } , @non_null) 2 5 7
4475 5 ▶ return 'DATE' if all { $_ =~ $INFER_DATE_RE } @non_null;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if &all(sub { $_ =~ /$INFER_DATE_RE/; } , @non_null) 2 3 5
4476 3 return 'TEXT';
4477 }
4478  
4479 # Merge $self->{'base_criteria'} into a caller-supplied $params hashref.
4480 # Returns a new hashref with base_criteria keys added; caller keys WIN on collision
4481 # so callers can always further restrict. Returns $params unchanged when no
4482 # base_criteria is set, avoiding an extra allocation on the common code path.
4483 790 ▶sub _merge_base_criteria :Private {
Subroutine _merge_base_criteria: called CC=2 SCAR=6.9
4484 790 my ($self, $params) = @_;
4485 790 my $bc = $self->{'base_criteria'};
4486 790 ▶ return $params unless $bc;
Branch: 1 branch
BranchTrueFalseTotal
unless $bc 759 31 790
4487 31 return { %{$bc}, %{$params} };
4488 54 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4489  
4490 # Parse a sort_by parameter value into ($col, $dir).
4491 # Accepts: scalar column name (ASC), or [$col, $dir] arrayref.
4492 # Validates column against $SAFE_QUALIFIED and direction as ASC/DESC.
4493 # Carps and returns (undef, 'ASC') on invalid input so callers fall back
4494 # to the default id-column sort.
4495 sub _parse_sort_by
4496 476 ▶{
Subroutine _parse_sort_by: called CC=8 SCAR=20.8
4497 476 my ($sb, $method) = @_;
4498 476 ▶ return (undef, 'ASC') unless defined $sb;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sb 435 41 476
4499 41 ▶ my ($col, $dir) = ref($sb) eq 'ARRAY' ? @{$sb}[0, 1] : ($sb, undef);
Branch: 1 branch
BranchTrueFalseTotal
ref $sb eq 'ARRAY' ? : 20 21 41
4500 41 ▶ $dir = defined($dir) ? uc($dir) : 'ASC';
Branch: 1 branch
BranchTrueFalseTotal
defined $dir ? : 20 21 41
4501 41 ▶ unless(defined($col) && $col =~ $SAFE_QUALIFIED) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $col and $col =~ /$SAFE_QUALIFIED/) 12 29 41
Condition100%3/3
defined $col and $col =~ /$SAFE_QUALIFIED/
!ll&&!rl&&r
11129
MC/DC100%2/2
defined $col and $col =~ /$SAFE_QUALIFIED/
defined $col $col =~ /$SAFE_QUALIFIED/
Truth table100%3/3
A and B
A= defined $colB= $col =~ /$SAFE_QUALIFIED/
ABresult
0X0
100
111
4502 12 Carp::carp("$method: unsafe sort_by column, ignoring");
4503 12 return (undef, 'ASC');
4504 }
4505 29 ▶ unless($dir eq 'ASC' || $dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dir eq "ASC" or $dir eq "DESC") 5 24 29
Condition100%3/3
$dir eq "ASC" or $dir eq "DESC"
l!l&&r!l&&!r
14105
MC/DC100%2/2
$dir eq "ASC" or $dir eq "DESC"
$dir eq "ASC" $dir eq "DESC"
Truth table100%3/3
A or B
A= $dir eq "ASC"B= $dir eq "DESC"
ABresult
1X1
011
000
4506 5 Carp::carp("$method: invalid sort_by direction '$dir', ignoring");
4507 5 return (undef, 'ASC');
4508 }
4509 24 return ($col, $dir);
4510 }
4511  
4512 # Return true when $params contains operator hashrefs, -or, or -and groupings
4513 # that the simple slurp fast-path cannot handle.
4514 sub _has_complex_criteria
4515 401 ▶{
Subroutine _has_complex_criteria: called CC=5 SCAR=16.1
4516 401 my ($self, $params) = @_;
4517 401 ▶ return 0 unless defined $params;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $params 3 398 401
4518 # -or / -and keys short-circuit immediately: no value scan needed.
4519 398 ▶ return 1 if exists $params->{'-or'} || exists $params->{'-and'};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params->{"-or"} or exists $params->{"-and"} 7 391 398
Condition100%3/3
exists $params->{"-or"} or exists $params->{"-and"}
l!l&&r!l&&!r
43391
MC/DC100%2/2
exists $params->{"-or"} or exists $params->{"-and"}
exists $params->{"-or"} exists $params->{"-and"}
Truth table100%3/3
A or B
A= exists $params->{"-or"}B= exists $params->{"-and"}
ABresult
1X1
011
000
4520 # LOGICAL INVARIANT: when this returns false, NO value in %$params is a
4521 # reference. This is the Boolean gate that makes _match_criterion's
4522 # hashref branch provably unreachable from the public select API:
4523 # Premise A — in-memory scan path requires: !_has_complex_criteria(params)
4524 # Premise B — _has_complex_criteria returns true if any value is a ref
4525 # Conclusion — inside the in-memory scan, every crit_val is a scalar/undef
4526 # any() short-circuits on the first truthy element; the for-loop equivalent
4527 # would iterate through all values before returning false in the common case.
4528 391 ▶ return (any { ref($_) } values %{$params}) ? 1 : 0;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
&any(sub { ref $_; } , values %{$params;}) ? : 8 383 391
4529 }
4530  
4531 # Build the WHERE clause body (everything after "WHERE") from a criteria hash.
4532 # Handles -or / -and groupings then delegates per-column work to _build_where_conditions.
4533 # Returns ($sql_fragment, \@bind_values).
4534 # Wrapper around Data::Reuse::fixate() that suppresses the spurious
4535 # "Use of uninitialized value in hash slice" warning. Data::Alias's XS
4536 # hash-aliasing code does not fully initialise key SVs on older Perl
4537 # versions when the source hash contains undef values (NULL columns).
4538 # Data::Reuse still fixates correctly; the warning is a false positive.
4539 # $struct must be the hashref or arrayref to fixate.
4540 458 ▶sub _fixate :Private
Subroutine _fixate: called CC=2 SCAR=8.7
4541 {
4542 458 my (undef, $struct) = @_;
4543 458 ▶ return unless defined $struct;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $struct 1 457 458
4544 # Clear stale address→canonical mappings from prior fixate calls before
4545 # fixating $struct. Without this, freed hashref addresses from a previous
4546 # object's slurp or DBI result can be reused by the allocator for new
4547 # hashrefs; fixate() would then find the stale entry and alias the new
4548 # hashref to the wrong canonical, silently substituting one row's data for
4549 # another. This is the same stale-address hazard that affects DBI paths
4550 # (see selectall_arrayref / selectall_array) but also affects the slurp
4551 # fixate when earlier objects go out of scope before a new slurp runs.
4552 457 Data::Reuse::forget();
4553 # Suppress the benign "Use of uninitialized value in hash slice" warning
4554 # that Data::Reuse/Data::Alias emits on some Perl < 5.34 builds when a
4555 # row has undef columns. All other warnings are re-emitted verbatim so
4556 # unrelated problems remain visible. This is intentional, not debug code.
4557 0 ▶ local $SIG{__WARN__} = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
4558 0 ▶ warn @_ unless
Branch: 1 branch
BranchTrueFalseTotal
unless index($_[0], "Use of uninitialized value") == 0 and index($_[0], "in hash slice") != -1 0 0 0
Condition0%0/3
index($_[0], "Use of uninitialized value") == 0 and index($_[0], "in hash slice") != -1
!ll&&!rl&&r
000
MC/DC0%0/2
index($_[0], "Use of uninitialized value") == 0 and index($_[0], "in hash slice") != -1
index($_[0], "Use of uninitialized value") == 0 index($_[0], "in hash slice") != -1
Truth table0%0/3
A and B
A= index($_[0], "Use of uninitialized value") == 0B= index($_[0], "in hash slice") != -1
ABresult
0X0
100
111
4559 index($_[0], 'Use of uninitialized value') == 0
4560 && index($_[0], 'in hash slice') >= 0;
4561 457 };
4562 457 &Data::Reuse::fixate($struct);
4563 54 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4564  
4565 sub _build_where
4566 447 ▶{
Subroutine _build_where: called CC=13 SCAR=25.7
4567 447 my ($self, $params) = @_;
4568  
4569 447 ▶ $params //= {};
Condition50%1/2
$params //= {}
l!l
4470
MC/DC0%0/1
$params //= {}
$params
Truth table50%1/2
A
A= $params
Aresult
11
00
4570 447 my @clauses;
4571 my @args;
4572  
4573 # Avoid an O(K) hash copy in the common case where neither -or nor -and is
4574 # present. Only copy when we actually need to delete grouping keys, so the
4575 # plain-criteria path (the vast majority of queries) passes $params through
4576 # directly to _build_where_conditions without any allocation.
4577 447 my $or_list = $params->{'-or'};
4578 447 my $and_list = $params->{'-and'};
4579 447 my $plain;
4580 447 ▶ if(defined($or_list) || defined($and_list)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $or_list or defined $and_list) { } 21 426 447
Condition100%3/3
defined $or_list or defined $and_list
l!l&&r!l&&!r
156426
MC/DC100%2/2
defined $or_list or defined $and_list
defined $or_list defined $and_list
Truth table100%3/3
A or B
A= defined $or_listB= defined $and_list
ABresult
1X1
011
000
4581 21 my %p = %{$params};
4582 21 delete @p{qw(-or -and)};
4583 21 $plain = \%p;
4584 } else {
4585 426 $plain = $params;
4586 }
4587  
4588 447 ▶ if($or_list) {
Branch: 1 branch
BranchTrueFalseTotal
if ($or_list) 15 432 447
4589 15 my (@sub_clauses, @sub_args);
4590 15 for my $cond (@{$or_list}) {
4591 28 my ($s, $a) = $self->_build_where_conditions($cond);
4592 28 ▶ if($s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s) 28 0 28
4593 28 push @sub_clauses, "($s)";
4594 28 push @sub_args, @{$a};
4595 }
4596 }
4597 15 ▶ if(@sub_clauses) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sub_clauses) 14 1 15
4598 14 push @clauses, '(' . join(' OR ', @sub_clauses) . ')';
4599 14 push @args, @sub_args;
4600 }
4601 }
4602 447 ▶ if($and_list) {
Branch: 1 branch
BranchTrueFalseTotal
if ($and_list) 6 441 447
4603 6 my (@sub_clauses, @sub_args);
4604 6 for my $cond (@{$and_list}) {
4605 9 my ($s, $a) = $self->_build_where_conditions($cond);
4606 9 ▶ if($s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s) 9 0 9
4607 9 push @sub_clauses, "($s)";
4608 9 push @sub_args, @{$a};
4609 }
4610 }
4611 6 ▶ if(@sub_clauses) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sub_clauses) 5 1 6
4612 5 push @clauses, '(' . join(' AND ', @sub_clauses) . ')';
4613 5 push @args, @sub_args;
4614 }
4615 }
4616  
4617 447 my ($more, $margs) = $self->_build_where_conditions($plain);
4618 429 ▶ if($more) {
Branch: 1 branch
BranchTrueFalseTotal
if ($more) 174 255 429
4619 174 push @clauses, $more;
4620 174 push @args, @{$margs};
4621 }
4622  
4623 429 return (join(' AND ', @clauses), \@args);
4624 }
4625  
4626 # Build a WHERE-body fragment for a flat col => val hash.
4627 # Values may be plain scalars (= / LIKE / IS NULL) or operator hashrefs
4628 # ({ '>' => n }, { -in => [...] }, { -between => [lo,hi] }, etc.).
4629 sub _build_where_conditions
4630 515 ▶{
Subroutine _build_where_conditions: called CC=17 SCAR=28.3
4631 515 my ($self, $params) = @_;
4632  
4633 515 my @clauses;
4634 my @args;
4635  
4636 515 for my $col (sort keys %{$params}) {
4637 270 my $val = $params->{$col};
4638  
4639 # Guard against SQL injection via column names; allow table.column notation for JOINs
4640 270 ▶ Carp::croak("_build_where_conditions: unsafe column name '$col'")
Branch: 1 branch
BranchTrueFalseTotal
unless $col =~ /$SAFE_QUALIFIED/ 18 252 270
4641 unless $col =~ $SAFE_QUALIFIED;
4642  
4643 252 ▶ if(ref($val) eq 'HASH') {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $val eq 'HASH') { } 69 183 252
elsif (ref $val) { } 4 179 183
elsif (not defined $val) { } 9 170 179
elsif ($val =~ /[%_]/) { } 6 164 170
4644 69 for my $op (keys %{$val}) { # no sort — operator hashes typically have 1-2 keys; sort adds O(K log K) overhead
4645 70 my $operand = $val->{$op};
4646 70 ▶ if($op eq '-in' || $op eq '-not_in') {
Branch: 6 branches
BranchTrueFalseTotal
if ($op eq '-in' or $op eq '-not_in') { } 13 57 70
elsif ($op eq '-between') { } 6 51 57
elsif ($op eq '-like') { } 5 46 51
elsif ($op eq '-not_like') { } 4 42 46
elsif ($op eq '!=') { } 6 36 42
elsif ($op =~ /\A[<>]=?\z/) { } 34 2 36
Condition100%3/3
$op eq "-in" or $op eq "-not_in"
l!l&&r!l&&!r
8557
MC/DC100%2/2
$op eq "-in" or $op eq "-not_in"
$op eq "-in" $op eq "-not_in"
Truth table100%3/3
A or B
A= $op eq "-in"B= $op eq "-not_in"
ABresult
1X1
011
000
4647 13 ▶ my $sql_op = $op eq '-in' ? 'IN' : 'NOT IN';
Branch: 1 branch
BranchTrueFalseTotal
$op eq '-in' ? : 8 5 13
4648 13 my $ph = join(', ', ('?') x scalar(@{$operand}));
4649 13 push @clauses, "$col $sql_op ($ph)";
4650 13 push @args, @{$operand};
4651 } elsif($op eq '-between') {
4652 6 push @clauses, "$col BETWEEN ? AND ?";
4653 6 push @args, $operand->[0], $operand->[1];
4654 } elsif($op eq '-like') {
4655 5 push @clauses, "$col LIKE ?";
4656 5 push @args, $operand;
4657 } elsif($op eq '-not_like') {
4658 4 push @clauses, "$col NOT LIKE ?";
4659 4 push @args, $operand;
4660 } elsif($op eq '!=') {
4661 6 ▶ if(!defined($operand)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $operand) { } 2 4 6
4662 2 push @clauses, "$col IS NOT NULL";
4663 } else {
4664 4 push @clauses, "$col != ?";
4665 4 push @args, $operand;
4666 }
4667 # [<>]=? matches >, <, >=, <= as a single character class — no alternation
4668 # overhead, no backtracking, and self-documenting.
4669 } elsif($op =~ /\A[<>]=?\z/) {
4670 34 push @clauses, "$col $op ?";
4671 34 push @args, $operand;
4672 } else {
4673 2 Carp::croak("Unknown operator '$op' for column '$col'");
4674 }
4675 }
4676 } elsif(ref($val)) {
4677 4 Carp::croak("$col: expected scalar or operator hashref, got ", ref($val));
4678 } elsif(!defined($val)) {
4679 9 push @clauses, "$col IS NULL";
4680 } elsif($val =~ /[%_]/) {
4681 6 push @clauses, "$col LIKE ?";
4682 6 push @args, $val;
4683 } else {
4684 164 push @clauses, "$col = ?";
4685 164 push @args, $val;
4686 }
4687 }
4688  
4689 491 return (join(' AND ', @clauses), \@args);
4690 }
4691  
4692 # Test a single in-memory row value against a criteria value.
4693 # $crit_val may be a plain scalar or an operator hashref.
4694 # Returns true when the row value satisfies the criterion.
4695 # Scan the entire BerkeleyDB tied hash, building rows as {entry=>$k, value=>$v},
4696 # and filter by $params criteria using _match_criterion.
4697 # Croaks when JOINs or -or/-and groupings are requested (unsupported for key-value stores).
4698 sub _scan_berkeley
4699 18 ▶{
Subroutine _scan_berkeley: called CC=9 SCAR=22.0
4700 18 my ($self, $params) = @_;
4701 18 ▶ $params //= {};
Condition50%1/2
$params //= {}
l!l
180
MC/DC0%0/1
$params //= {}
$params
Truth table50%1/2
A
A= $params
Aresult
11
00
4702  
4703 # TODO: Data Flow Anomaly - Mutation side effect: delete mutates the caller's
4704 # $params hashref in-place. All current callers (selectall_arrayref,
4705 # selectall_array, count) do not reuse $params after this call, so it is safe;
4706 # but a future caller that reuses $params would silently lose the 'join' key.
4707 # Fix: use exists($params->{'join'}) to check; copy params before deleting.
4708 18 ▶ if(delete $params->{'join'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (delete $params->{"join"}) 2 16 18
4709 2 Carp::croak(ref($self), ': BerkeleyDB does not support JOINs');
4710 }
4711 # any() short-circuits: once the first -or/-and key is found the croak fires
4712 # without scanning the remaining keys — O(1) best case vs O(K) for grep.
4713 16 ▶ if(any { $_ eq '-or' || $_ eq '-and' } keys %{$params}) {
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 2 branches
BranchTrueFalseTotal
if (&any(sub { $_ eq "-or" or $_ eq "-and"; } , keys %{$params;})) 3 13 16
$_ eq "-or" or $_ eq "-and" 2 4 6
4714 3 Carp::croak(ref($self), ': BerkeleyDB does not support -or/-and groupings');
4715 }
4716  
4717 13 my $bdb = $self->{'berkeley'};
4718 13 my @cols = keys %{$params};
4719 13 my @rows;
4720  
4721 13 ▶ if(@cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cols) { } 3 10 13
4722 # Single-pass build+filter: avoids materialising the full N-row list
4723 # before filtering. Peak memory is O(matching rows) instead of O(N).
4724 3 for my $k (keys %{$bdb}) {
4725 7 my $row = { entry => $k, value => $bdb->{$k} };
4726 7 my $match = 1;
4727 7 for my $col (@cols) {
4728 7 ▶ unless($self->_match_criterion($row->{$col}, $params->{$col}, $col)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_match_criterion($$row{$col}, $$params{$col}, $col)) 4 3 7
4729 4 $match = 0;
4730 4 last;
4731 }
4732 }
4733 7 ▶ push @rows, $row if $match;
Branch: 1 branch
BranchTrueFalseTotal
if $match 3 4 7
4734 }
4735 } else {
4736 10 @rows = map { { entry => $_, value => $bdb->{$_} } } keys %{$bdb};
4737 }
4738  
4739 13 return \@rows;
4740 }
4741  
4742 # SQL LIKE match — case-insensitive, ReDoS-safe, no catastrophic backtracking.
4743 # % matches any sequence of chars; _ matches exactly one char.
4744 #
4745 # Fast paths cover the four most common LIKE shapes using O(1) string ops:
4746 # '%' → always true
4747 # no wildcard → lc eq comparison
4748 # '%suffix' → ends-with check via substr
4749 # 'prefix%' → starts-with check via index
4750 # '%mid%' → contains check via index (single inner literal, no _ wildcards)
4751 #
4752 # Full DP uses O(m) memory (two 1-D rolling arrays) instead of the O(m*n) 2-D
4753 # table the naive approach allocates. Character access uses substr() instead of
4754 # split(//) so no per-character scalar objects are created.
4755 sub _like_match
4756 83 ▶{
Subroutine _like_match: called CC=23 SCAR=31.4
4757 83 my ($str, $pattern) = @_;
4758  
4759 # Fast path 1: bare '%' — matches any string regardless of content.
4760 83 ▶ return 1 if $pattern eq '%';
Branch: 1 branch
BranchTrueFalseTotal
if $pattern eq "%" 8 75 83
4761  
4762 75 my $lc_str = lc($str);
4763 75 my $lc_pat = lc($pattern);
4764 75 my $pat_len = length($lc_pat);
4765 75 my $str_len = length($lc_str);
4766  
4767 # Fast path 2: no wildcard characters — plain case-insensitive equality.
4768 75 ▶ return ($lc_str eq $lc_pat)
Branch: 1 branch
BranchTrueFalseTotal
if index($lc_pat, "%") == -1 and index($lc_pat, "_") == -1 14 61 75
Condition100%3/3
index($lc_pat, "%") == -1 and index($lc_pat, "_") == -1
!ll&&!rl&&r
491214
MC/DC100%2/2
index($lc_pat, "%") == -1 and index($lc_pat, "_") == -1
index($lc_pat, "%") == -1 index($lc_pat, "_") == -1
Truth table100%3/3
A and B
A= index($lc_pat, "%") == -1B= index($lc_pat, "_") == -1
ABresult
0X0
100
111
4769 if index($lc_pat, '%') == -1 && index($lc_pat, '_') == -1;
4770  
4771 # Fast paths 3-5 apply only when the pattern has no '_' wildcards.
4772 # (Patterns with '_' need per-character DP to enforce the single-char rule.)
4773 61 ▶ if(index($lc_pat, '_') == -1) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($lc_pat, "_") == -1) 48 13 61
4774 48 my $first_pct = index($lc_pat, '%');
4775 48 my $last_pct = rindex($lc_pat, '%');
4776  
4777 # Fast path 3: '%suffix' — exactly one '%', at the start.
4778 48 ▶ if($first_pct == 0 && $last_pct == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first_pct == 0 and $last_pct == 0) 12 36 48
Condition100%3/3
$first_pct == 0 and $last_pct == 0
!ll&&!rl&&r
201612
MC/DC100%2/2
$first_pct == 0 and $last_pct == 0
$first_pct == 0 $last_pct == 0
Truth table100%3/3
A and B
A= $first_pct == 0B= $last_pct == 0
ABresult
0X0
100
111
4779 12 my $sfx = substr($lc_pat, 1);
4780 12 my $sfx_len = length($sfx);
4781 12 ▶ return $str_len >= $sfx_len
Condition66%2/3
$str_len >= $sfx_len && substr($lc_str, $str_len - $sfx_len) eq $sfx
!ll&&!rl&&r
066
MC/DC50%1/2
$str_len >= $sfx_len && substr($lc_str, $str_len - $sfx_len) eq $sfx
$str_len >= $sfx_len substr($lc_str, $str_len - $sfx_len) eq $sfx
Truth table66%2/3
A && B
A= $str_len >= $sfx_lenB= substr($lc_str, $str_len - $sfx_len) eq $sfx
ABresult
0X0
100
111
4782 && substr($lc_str, $str_len - $sfx_len) eq $sfx;
4783 }
4784  
4785 # Fast path 4: 'prefix%' — exactly one '%', at the end.
4786 36 ▶ if($last_pct == $pat_len - 1 && $first_pct == $pat_len - 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($last_pct == $pat_len - 1 and $first_pct == $pat_len - 1) 17 19 36
Condition100%3/3
$last_pct == $pat_len - 1 and $first_pct == $pat_len - 1
!ll&&!rl&&r
71217
MC/DC100%2/2
$last_pct == $pat_len - 1 and $first_pct == $pat_len - 1
$last_pct == $pat_len - 1 $first_pct == $pat_len - 1
Truth table100%3/3
A and B
A= $last_pct == $pat_len - 1B= $first_pct == $pat_len - 1
ABresult
0X0
100
111
4787 17 my $pfx = substr($lc_pat, 0, $pat_len - 1);
4788 17 return index($lc_str, $pfx) == 0;
4789 }
4790  
4791 # Fast path 5: '%literal%' — '%' at both ends, no inner '%'.
4792 # pat_len >= 3 ensures there are two distinct '%' characters.
4793 # Only return here when the middle segment is free of further wildcards;
4794 # if it contains '%' (e.g. '%a%b%'), fall through to the full DP.
4795 19 ▶ if($first_pct == 0 && $last_pct == $pat_len - 1 && $pat_len >= 3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first_pct == 0 and $last_pct == $pat_len - 1 and $pat_len >= 3) 12 7 19
Condition83%5/6
$first_pct == 0 and $last_pct == $pat_len - 1 and $pat_len >= 3
!ll&&!rl&&r
7012
$first_pct == 0 and $last_pct == $pat_len - 1
!ll&&!rl&&r
3412
MC/DC66%2/3
$first_pct == 0 and $last_pct == $pat_len - 1 and $pat_len >= 3
$first_pct == 0 $last_pct == $pat_len - 1 $pat_len >= 3
Truth table75%3/4
A and B and C
A= $first_pct == 0B= $last_pct == $pat_len - 1C= $pat_len >= 3
ABCresult
0XX0
10X0
1100
1111
4796 12 my $needle = substr($lc_pat, 1, $pat_len - 2);
4797 12 ▶ if(index($needle, '%') == -1) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($needle, "%") == -1) 7 5 12
4798 7 return index($lc_str, $needle) >= 0;
4799 }
4800 }
4801 }
4802  
4803 # Full DP — O(m*n) time, O(m) memory.
4804 # Two 1-D arrayrefs (@$prev, @$curr) replace the O(m*n) 2-D table.
4805 # substr() replaces split(//) — no per-char scalar allocation.
4806 # Ref-swap ($prev,$curr) = ($curr,$prev) at the end of each outer iteration
4807 # avoids the O(m) array copy that "@prev = @curr" would perform.
4808 25 my $m = $str_len;
4809 25 my $n = $pat_len;
4810  
4811 25 my ($prev, $curr) = ([1, (0) x $m], [(0) x ($m + 1)]);
4812  
4813 25 for my $i (1 .. $n) {
4814 252 @{$curr} = (0) x ($m + 1); # zero in-place — reuses existing allocation
4815 252 my $pc = substr($lc_pat, $i - 1, 1);
4816 252 ▶ if($pc eq '%') {
Branch: 1 branch
BranchTrueFalseTotal
if ($pc eq '%') { } 129 123 252
4817 129 $curr->[0] = $prev->[0];
4818 129 for my $j (1 .. $m) {
4819 14596 ▶ $curr->[$j] = ($prev->[$j] || $curr->[$j - 1]) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$$prev[$j] || $$curr[$j - 1] ? : 9873 4723 14596
Condition100%3/3
$$prev[$j] or $$curr[$j - 1]
l!l&&r!l&&!r
844414294723
MC/DC100%2/2
$$prev[$j] or $$curr[$j - 1]
$$prev[$j] $$curr[$j - 1]
Truth table100%3/3
A or B
A= $$prev[$j]B= $$curr[$j - 1]
ABresult
1X1
011
000
4820 }
4821 } else {
4822 123 for my $j (1 .. $m) {
4823 14197 ▶ $curr->[$j] = ($prev->[$j - 1]
Branch: 1 branch
BranchTrueFalseTotal
$$prev[$j - 1] && ($pc eq '_' || $pc eq substr($lc_str, $j - 1, 1)) ? : 7945 6252 14197
Condition100%6/6
$$prev[$j - 1] and $pc eq "_" || $pc eq substr($lc_str, $j - 1, 1)
!ll&&!rl&&r
487513777945
$pc eq "_" or $pc eq substr($lc_str, $j - 1, 1)
l!l&&r!l&&!r
1779281377
MC/DC100%3/3
$$prev[$j - 1] and $pc eq "_" || $pc eq substr($lc_str, $j - 1, 1)
$$prev[$j - 1] $pc eq "_" $pc eq substr($lc_str, $j - 1, 1)
Truth table100%4/4
A and B or C
A= $$prev[$j - 1]B= $pc eq "_"C= $pc eq substr($lc_str, $j - 1, 1)
ABCresult
0XX0
1000
11X1
1011
4824 && ($pc eq '_' || $pc eq substr($lc_str, $j - 1, 1))) ? 1 : 0;
4825 }
4826 }
4827 252 ($prev, $curr) = ($curr, $prev); # O(1) ref swap — no array copy
4828 }
4829 25 return $prev->[$m];
4830 }
4831  
4832 sub _match_criterion
4833 342 ▶{
Subroutine _match_criterion: called CC=51 SCAR=39.4
4834 342 my ($self, $row_val, $crit_val, $col) = @_;
4835  
4836 # Use numeric equality/membership operators when the schema (if already
4837 # cached) reports the column as INTEGER or REAL. The numeric ordering
4838 # operators (>, <, >=, <=, -between) already use Perl's numeric context
4839 # regardless; only equality-family operators need the type-aware path.
4840 my $numeric = ($col && $self->{'_schema'})
4841 342 ▶ ? do { my $t = ($self->{'_schema'}{$col} // {})->{'type'} // 'TEXT';
Branch: 1 branch
BranchTrueFalseTotal
$col && $$self{'_schema'} ? : 26 316 342
Condition71%5/7
$col and $$self{"_schema"}
!ll&&!rl&&r
10920726
($$self{"_schema"}{$col} // {})->{"type"} // "TEXT"
l!l
260
$$self{"_schema"}{$col} // {}
l!l
260
MC/DC100%2/2
$col and $$self{"_schema"}
$col $$self{"_schema"}
MC/DC0%0/1
($$self{"_schema"}{$col} // {})->{"type"} // "TEXT"
$$self{"_schema"}{$col}
Truth table100%3/3
A and B
A= $colB= $$self{"_schema"}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $$self{"_schema"}{$col}
Aresult
11
00
4842 26 ▶ $t eq 'INTEGER' || $t eq 'REAL' }
Condition100%3/3
$t eq 'INTEGER' || $t eq 'REAL'
l!l&&r!l&&!r
3149
MC/DC100%2/2
$t eq 'INTEGER' || $t eq 'REAL'
$t eq 'INTEGER' $t eq 'REAL'
Truth table100%3/3
A || B
A= $t eq 'INTEGER'B= $t eq 'REAL'
ABresult
1X1
011
000
4843 : 0;
4844  
4845 342 ▶ if(ref($crit_val) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $crit_val eq "HASH") 109 233 342
4846 109 for my $op (keys %{$crit_val}) {
4847 108 my $operand = $crit_val->{$op};
4848 108 ▶ if($op eq '-in') {
Branch: 10 branches
BranchTrueFalseTotal
if ($op eq '-in') { } 11 97 108
elsif ($op eq '-not_in') { } 8 89 97
elsif ($op eq '-between') { } 10 79 89
elsif ($op eq '-like') { } 31 48 79
elsif ($op eq '-not_like') { } 5 43 48
elsif ($op eq '!=') { } 14 29 43
elsif ($op eq '>') { } 16 13 29
elsif ($op eq '<') { } 5 8 13
elsif ($op eq '>=') { } 4 4 8
elsif ($op eq '<=') { } 4 0 4
4849 return 0 unless defined($row_val)
4850 && ($numeric
4851 4 ? grep { $row_val == $_ } @{$operand}
4852 11 ▶ : grep { $row_val eq $_ } @{$operand});
Branch: 2 branches
BranchTrueFalseTotal
unless defined $row_val and $numeric ? grep({$row_val == $_;} @{$operand;}) : grep({$row_val eq $_;} @{$operand;}) 6 5 11
$numeric ? : 2 8 10
Condition100%3/3
defined $row_val and $numeric ? grep({$row_val == $_;} @{$operand;}) : grep({$row_val eq $_;} @{$operand;})
!ll&&!rl&&r
155
MC/DC100%2/2
defined $row_val and $numeric ? grep({$row_val == $_;} @{$operand;}) : grep({$row_val eq $_;} @{$operand;})
defined $row_val $numeric ? grep({$row_val == $_;} @{$operand;}) : grep({$row_val eq $_;} @{$operand;})
Truth table100%3/3
A and B
A= defined $row_valB= $numeric ? grep({$row_val == $_;} @{$operand;}) : grep({$row_val eq $_;} @{$operand;})
ABresult
0X0
100
111
4853 } elsif($op eq '-not_in') {
4854 return 0 if defined($row_val)
4855 && ($numeric
4856 2 ? grep { $row_val == $_ } @{$operand}
4857 8 ▶ : grep { $row_val eq $_ } @{$operand});
Branch: 2 branches
BranchTrueFalseTotal
if defined $row_val and $numeric ? grep({$row_val == $_;} @{$operand;}) : grep({$row_val eq $_;} @{$operand;}) 4 4 8
$numeric ? : 2 6 8
Condition66%2/3
defined $row_val and $numeric ? grep({$row_val == $_;} @{$operand;}) : grep({$row_val eq $_;} @{$operand;})
!ll&&!rl&&r
044
MC/DC50%1/2
defined $row_val and $numeric ? grep({$row_val == $_;} @{$operand;}) : grep({$row_val eq $_;} @{$operand;})
defined $row_val $numeric ? grep({$row_val == $_;} @{$operand;}) : grep({$row_val eq $_;} @{$operand;})
Truth table66%2/3
A and B
A= defined $row_valB= $numeric ? grep({$row_val == $_;} @{$operand;}) : grep({$row_val eq $_;} @{$operand;})
ABresult
0X0
100
111
4858 } elsif($op eq '-between') {
4859 10 ▶ return 0 unless defined($row_val) && $row_val >= $operand->[0] && $row_val <= $operand->[1];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val and $row_val >= $$operand[0] and $row_val <= $$operand[1] 5 5 10
Condition100%6/6
defined $row_val and $row_val >= $$operand[0] and $row_val <= $$operand[1]
!ll&&!rl&&r
325
defined $row_val and $row_val >= $$operand[0]
!ll&&!rl&&r
127
MC/DC100%3/3
defined $row_val and $row_val >= $$operand[0] and $row_val <= $$operand[1]
defined $row_val $row_val >= $$operand[0] $row_val <= $$operand[1]
Truth table100%4/4
A and B and C
A= defined $row_valB= $row_val >= $$operand[0]C= $row_val <= $$operand[1]
ABCresult
0XX0
10X0
1100
1111
4860 } elsif($op eq '-like') {
4861 31 ▶ return 0 unless defined($row_val);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val 1 30 31
4862 30 ▶ return 0 unless _like_match($row_val, $operand);
Branch: 1 branch
BranchTrueFalseTotal
unless _like_match($row_val, $operand) 13 17 30
4863 } elsif($op eq '-not_like') {
4864 5 ▶ return 0 unless defined($row_val);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val 1 4 5
4865 4 ▶ return 0 if _like_match($row_val, $operand);
Branch: 1 branch
BranchTrueFalseTotal
if _like_match($row_val, $operand) 1 3 4
4866 } elsif($op eq '!=') {
4867 14 ▶ if(!defined($operand)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $operand) { } 5 9 14
elsif ($numeric) { } 2 7 9
4868 5 ▶ return 0 unless defined($row_val);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val 3 2 5
4869 } elsif($numeric) {
4870 2 ▶ return 0 unless defined($row_val) && $row_val != $operand;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val and $row_val != $operand 1 1 2
Condition66%2/3
defined $row_val and $row_val != $operand
!ll&&!rl&&r
011
MC/DC50%1/2
defined $row_val and $row_val != $operand
defined $row_val $row_val != $operand
Truth table66%2/3
A and B
A= defined $row_valB= $row_val != $operand
ABresult
0X0
100
111
4871 } else {
4872 7 ▶ return 0 unless defined($row_val) && $row_val ne $operand;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val and $row_val ne $operand 4 3 7
Condition100%3/3
defined $row_val and $row_val ne $operand
!ll&&!rl&&r
133
MC/DC100%2/2
defined $row_val and $row_val ne $operand
defined $row_val $row_val ne $operand
Truth table100%3/3
A and B
A= defined $row_valB= $row_val ne $operand
ABresult
0X0
100
111
4873 }
4874 } elsif($op eq '>') {
4875 16 ▶ return 0 unless defined($row_val) && $row_val > $operand;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val and $row_val > $operand 8 8 16
Condition66%2/3
defined $row_val and $row_val > $operand
!ll&&!rl&&r
088
MC/DC50%1/2
defined $row_val and $row_val > $operand
defined $row_val $row_val > $operand
Truth table66%2/3
A and B
A= defined $row_valB= $row_val > $operand
ABresult
0X0
100
111
4876 } elsif($op eq '<') {
4877 5 ▶ return 0 unless defined($row_val) && $row_val < $operand;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val and $row_val < $operand 2 3 5
Condition66%2/3
defined $row_val and $row_val < $operand
!ll&&!rl&&r
023
MC/DC50%1/2
defined $row_val and $row_val < $operand
defined $row_val $row_val < $operand
Truth table66%2/3
A and B
A= defined $row_valB= $row_val < $operand
ABresult
0X0
100
111
4878 } elsif($op eq '>=') {
4879 4 ▶ return 0 unless defined($row_val) && $row_val >= $operand;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val and $row_val >= $operand 1 3 4
Condition66%2/3
defined $row_val and $row_val >= $operand
!ll&&!rl&&r
013
MC/DC50%1/2
defined $row_val and $row_val >= $operand
defined $row_val $row_val >= $operand
Truth table66%2/3
A and B
A= defined $row_valB= $row_val >= $operand
ABresult
0X0
100
111
4880 } elsif($op eq '<=') {
4881 4 ▶ return 0 unless defined($row_val) && $row_val <= $operand;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val and $row_val <= $operand 1 3 4
Condition66%2/3
defined $row_val and $row_val <= $operand
!ll&&!rl&&r
013
MC/DC50%1/2
defined $row_val and $row_val <= $operand
defined $row_val $row_val <= $operand
Truth table66%2/3
A and B
A= defined $row_valB= $row_val <= $operand
ABresult
0X0
100
111
4882 }
4883 }
4884 58 return 1;
4885 }
4886  
4887 233 ▶ return !defined($row_val) && !defined($crit_val) ? 1
Branch: 3 branches
BranchTrueFalseTotal
!(defined $row_val || defined $crit_val) ? : 8 225 233
!(defined $row_val && defined $crit_val) ? : 45 180 225
$numeric ? : 11 169 180
Condition100%6/6
defined $row_val || defined $crit_val
l!l&&r!l&&!r
195308
defined $row_val && defined $crit_val
!ll&&!rl&&r
3015180
MC/DC100%2/2
defined $row_val || defined $crit_val
defined $row_val defined $crit_val
MC/DC100%2/2
defined $row_val && defined $crit_val
defined $row_val defined $crit_val
Truth table100%3/3
A || B
A= defined $row_valB= defined $crit_val
ABresult
1X1
011
000
Truth table100%3/3
A && B
A= defined $row_valB= defined $crit_val
ABresult
0X0
100
111
4888 : !defined($row_val) || !defined($crit_val) ? 0
4889 : $numeric ? $row_val == $crit_val
4890 : $row_val eq $crit_val;
4891 }
4892  
4893 # Determine the table and open the database
4894 sub _open_table
4895 2258 ▶{
Subroutine _open_table: called CC=8 SCAR=20.9
4896 2258 my($self, $params) = @_;
4897  
4898 # Derive the table name, caching the result in '_table_name' for the common
4899 # case of no caller-supplied 'table' override. Avoids repeating ref()+regex
4900 # on every query when the same object makes many calls.
4901 2258 my $table;
4902 2258 ▶ if($params->{'table'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$params{'table'}) { } 10 2248 2258
4903 10 ($table = $params->{'table'}) =~ s/\A.*:://;
4904 10 ▶ Carp::croak(ref($self), ": unsafe table name '$table'")
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /$SAFE_QUALIFIED/ 7 3 10
4905 unless $table =~ $SAFE_QUALIFIED;
4906 } else {
4907 2248 ▶ $table = $self->{'_table_name'} //= do {
Condition66%2/3
$$self{"_table_name"} //= do { my $t = $$self{"table"} || ref $self; $t =~ s/\A.*:://; $t }
l!l&&r!l&&!r
17904580
MC/DC0%0/2
$$self{"_table_name"} //= do { my $t = $$self{"table"} || ref $self; $t =~ s/\A.*:://; $t }
$$self{"_table_name"} do { my $t = $$self{"table"} || ref $self; $t =~ s/\A.*:://; $t }
Truth table66%2/3
A //= B
A= $$self{"_table_name"}B= do { my $t = $$self{"table"} || ref $self; $t =~ s/\A.*:://; $t }
ABresult
1X1
011
000
4908 458 ▶ my $t = $self->{'table'} || ref($self);
Condition33%1/3
$$self{'table'} || ref $self
l!l&&r!l&&!r
04580
MC/DC0%0/2
$$self{'table'} || ref $self
$$self{'table'} ref $self
Truth table33%1/3
A || B
A= $$self{'table'}B= ref $self
ABresult
1X1
011
000
4909 458 $t =~ s/\A.*:://;
4910 458 $t;
4911 };
4912 }
4913  
4914 # Open a connection if it's not already open.
4915 # BerkeleyDB never sets $self->{'_dbh'}{$table} (no DBI handle) or $self->{'data'},
4916 # so we also guard on $self->{'berkeley'} to avoid re-tying on every call.
4917 2251 ▶ $self->_open() if(!$self->{'_dbh'}{$table} && !$self->{'data'} && !$self->{'berkeley'});
Branch: 1 branch
BranchTrueFalseTotal
unless $$self{"_dbh"}{$table} or $$self{"data"} or $$self{"berkeley"} 458 1793 2251
Condition100%6/6
$$self{"_dbh"}{$table} or $$self{"data"} or $$self{"berkeley"}
l!l&&r!l&&!r
177815458
$$self{"_dbh"}{$table} or $$self{"data"}
l!l&&r!l&&!r
1549229473
MC/DC100%3/3
$$self{"_dbh"}{$table} or $$self{"data"} or $$self{"berkeley"}
$$self{"_dbh"}{$table} $$self{"data"} $$self{"berkeley"}
Truth table100%4/4
A or B or C
A= $$self{"_dbh"}{$table}B= $$self{"data"}C= $$self{"berkeley"}
ABCresult
1XX1
01X1
0011
0000
4918  
4919 2201 return $table;
4920 }
4921  
4922 # Quote a SQL identifier using the current connection's dialect rules.
4923 # Falls back to ANSI double-quoting when no connection is available.
4924 sub _quote_identifier
4925 4 ▶{
Subroutine _quote_identifier: called CC=3 SCAR=11.2
4926 4 my ($self, $name) = @_;
4927  
4928 4 ▶ my $table = $self->{'table'} || ref($self);
Condition33%1/3
$$self{'table'} || ref $self
l!l&&r!l&&!r
040
MC/DC0%0/2
$$self{'table'} || ref $self
$$self{'table'} ref $self
Truth table33%1/3
A || B
A= $$self{'table'}B= ref $self
ABresult
1X1
011
000
4929 4 $table =~ s/\A.*:://;
4930 4 ▶ if(my $dbh = $self->{'_dbh'}{$table}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $dbh = $$self{"_dbh"}{$table}) 2 2 4
4931 2 return $dbh->quote_identifier($name);
4932 }
4933 2 return qq{"$name"};
4934 }
4935  
4936 # The escape character a CSV/PSV/TSV file is written with. RFC 4180 (and
4937 # every spreadsheet) writes a quote inside a quoted field as two quotes,
4938 # "Adeste ""Overture""", which a backslash escape reads back as two quotes;
4939 # other files write it \", which a quote escape cannot read at all. So: a
4940 # backslash before a quote anywhere means backslash, the escape this module
4941 # always used; else two quotes in a row mean a quote; else backslash. An
4942 # empty quoted field ("") reads the same either way. Stops at the first
4943 # backslash-quote, else reads the file once.
4944 sub _csv_escape_char
4945 269 ▶{
Subroutine _csv_escape_char: called CC=6 SCAR=17.9
4946 269 my ($self, $file) = @_;
4947  
4948 269 my $fh;
4949 54 ▶ do { no autodie qw(open); open $fh, '<:raw', $file } or return '\\';
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
do { BEGIN { $^H{'autodie::Scope::GuardStack/guard11'} = 'autodie::Scope::Guard=CODE(0x591690ff6838)'; $^H{'no Fatal'} = 'HASH(0x591690d9f8b8)'; } open $fh, "<:raw", $file } or return "\\" 268 1 269
4950 268 my $doubled = 0;
4951 268 ▶ while(my $line = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 1399 262 1661
4952 1399 ▶ if($line =~ /\\"/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\\"/) 6 1393 1399
4953 6 close $fh;
4954 6 return '\\';
4955 }
4956 1393 ▶ $doubled ||= ($line =~ /""/);
Condition100%3/3
$doubled ||= $line =~ /""/
l!l&&r!l&&!r
251386
MC/DC100%2/2
$doubled ||= $line =~ /""/
$doubled $line =~ /""/
Truth table100%3/3
A ||= B
A= $doubledB= $line =~ /""/
ABresult
1X1
011
000
4957 }
4958 262 close $fh;
4959 262 ▶ return $doubled ? '"' : '\\';
Branch: 1 branch
BranchTrueFalseTotal
$doubled ? : 4 258 262
4960 }
4961  
4962 # Determine whether a given file is a valid Berkeley DB file.
4963 # It combines a fast preliminary check with a more thorough validation step for accuracy.
4964 # It looks for the magic number at both byte 0 and byte 12.
4965 332 ▶sub _is_berkeley_db {
Subroutine _is_berkeley_db: called CC=4 SCAR=15.4
4966 332 my ($self, $file) = @_;
4967  
4968 # Step 1: Check magic number
4969 # no autodie here: the file may not exist, and we want a silent false return
4970 332 my $fh;
4971 54 ▶ do { no autodie qw(open); open $fh, '<', $file } or return 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
do { BEGIN { $^H{'autodie::Scope::GuardStack/guard12'} = 'autodie::Scope::Guard=CODE(0x591690ff6c88)'; $^H{'no Fatal'} = 'HASH(0x591690ff6c28)'; } open $fh, "<", $file } or return 0 2 330 332
4972 2 binmode $fh;
4973  
4974 2 my $is_db = $self->_has_bdb_magic($fh);
4975 2 close $fh;
4976  
4977 2 ▶ if($is_db) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_db) 0 2 2
4978 # Step 2: Attempt to open as Berkeley DB
4979  
4980 0 require DB_File;
4981  
4982 0 my %bdb;
4983 0 ▶ if(tie %bdb, 'DB_File', $file, O_RDONLY, 0644, $DB_File::DB_HASH) {
Branch: 1 branch
BranchTrueFalseTotal
if (tie %bdb, "DB_File", $file, 0, 420, $DB_File::DB_HASH) 0 0 0
4984 # untie %db;
4985 0 $self->{'berkeley'} = \%bdb;
4986 0 return 1; # Successfully identified as a Berkeley DB file
4987 }
4988 }
4989 2 return 0;
4990 }
4991  
4992 # Check for Berkeley DB magic bytes at offsets 0 and 12.
4993 # Returns true if either location contains a recognised BDB magic number.
4994 8 ▶sub _has_bdb_magic {
Subroutine _has_bdb_magic: called CC=7 SCAR=19.5
4995 8 my ($self, $fh) = @_;
4996  
4997 # Offset 0: 32-bit magic number in both endian forms
4998 8 ▶ read($fh, my $buf, 4) == 4 or return 0;
Branch: 1 branch
BranchTrueFalseTotal
&Database::Abstraction::read($fh, \my $buf, 4) == 4 or return 0 7 1 8
4999 7 my %magic = map { $_ => 1 } (0x00061561, 0x00053162, 0x00042253, 0x00052444);
5000 7 ▶ return 1 if $magic{unpack('N', $buf)} || $magic{unpack('V', $buf)};
Branch: 1 branch
BranchTrueFalseTotal
if $magic{unpack "N", $buf} or $magic{unpack "V", $buf} 3 4 7
Condition100%3/3
$magic{unpack "N", $buf} or $magic{unpack "V", $buf}
l!l&&r!l&&!r
214
MC/DC100%2/2
$magic{unpack "N", $buf} or $magic{unpack "V", $buf}
$magic{unpack "N", $buf} $magic{unpack "V", $buf}
Truth table100%3/3
A or B
A= $magic{unpack "N", $buf}B= $magic{unpack "V", $buf}
ABresult
1X1
011
000
5001  
5002 # Offset 12: Btree magic prefix (fallback for some BDB file variants)
5003 4 ▶ seek $fh, 12, 0 or return 0;
Branch: 1 branch
BranchTrueFalseTotal
&Database::Abstraction::seek($fh, 12, 0) or return 0 4 0 4
5004 4 ▶ read($fh, $buf, 4) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
&Database::Abstraction::read($fh, \$buf, 4) or return 0 3 1 4
5005 3 my $hex12 = substr(unpack('H*', $buf), 0, 4);
5006 3 ▶ return($hex12 eq '6115' || $hex12 eq '1561');
Condition66%2/3
$hex12 eq '6115' || $hex12 eq '1561'
l!l&&r!l&&!r
102
MC/DC50%1/2
$hex12 eq '6115' || $hex12 eq '1561'
$hex12 eq '6115' $hex12 eq '1561'
Truth table66%2/3
A || B
A= $hex12 eq '6115'B= $hex12 eq '1561'
ABresult
1X1
011
000
5007 }
5008  
5009 # Return true if $host refers to the current machine (localhost, loopback, or
5010 # the machine's own hostname). Strips an optional user@ prefix first.
5011 # Used by new() and _open() to decide whether to use local file access instead
5012 # of File::Slurp::Remote, so the caller never loads that module unnecessarily.
5013 77 ▶sub _is_local_host {
Subroutine _is_local_host: called CC=3 SCAR=11.0
5014 77 my ($self, $host) = @_;
5015  
5016 # Strip optional user@ prefix. \A (not ^) so a newline cannot split the match.
5017 77 (my $bare = $host) =~ s/\A[^@]*@//;
5018  
5019 # \z anchors at true end-of-string; $ would match before a trailing newline.
5020 77 ▶ return 1 if $bare =~ /\A(?:localhost|127\.0\.0\.1|::1)\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $bare =~ /\A(?:localhost|127\.0\.0\.1|::1)\z/i 30 47 77
5021  
5022 47 require Sys::Hostname;
5023 47 my $me = lc(Sys::Hostname::hostname());
5024 47 my $lc_bare = lc($bare);
5025 47 ▶ return 1 if $lc_bare eq $me;
Branch: 1 branch
BranchTrueFalseTotal
if $lc_bare eq $me 8 39 47
5026  
5027 # Match on short hostname: 'mybox' matches 'mybox.example.com' and vice-versa
5028 39 (my $me_short = $me) =~ s/\..*//;
5029 39 (my $bare_short = $lc_bare) =~ s/\..*//;
5030 39 return($bare_short eq $me_short);
5031 }
5032  
5033 # Determine whether a given file is a DBM::Deep file by checking its magic bytes.
5034 # The standard DBM::Deep magic is 'DPDB' (0x44 0x50 0x44 0x42); 'DPDP' (0x44 0x50 0x44 0x50)
5035 # is also accepted for compatibility with files created by alternative tooling.
5036 # Returns 1 if the first 4 bytes match a known DBM::Deep signature, 0 otherwise.
5037 20 ▶sub _is_deep_db {
Subroutine _is_deep_db: called CC=5 SCAR=16.1
5038 20 my ($self, $file) = @_;
5039  
5040 20 my $fh;
5041 54 ▶ do { no autodie qw(open); open $fh, '<', $file } or return 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
do { BEGIN { $^H{'autodie::Scope::GuardStack/guard13'} = 'autodie::Scope::Guard=CODE(0x5916910080f0)'; $^H{'no Fatal'} = 'HASH(0x591691008090)'; } open $fh, "<", $file } or return 0 16 4 20
5042 16 binmode $fh;
5043 16 my $n = read($fh, my $magic, 4);
5044 16 close $fh;
5045 16 ▶ return 0 unless defined($n) && $n == 4;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == 4 2 14 16
Condition66%2/3
defined $n and $n == 4
!ll&&!rl&&r
0214
MC/DC50%1/2
defined $n and $n == 4
defined $n $n == 4
Truth table66%2/3
A and B
A= defined $nB= $n == 4
ABresult
0X0
100
111
5046  
5047 14 ▶ return($magic eq 'DPDB' || $magic eq 'DPDP');
Condition100%3/3
$magic eq 'DPDB' || $magic eq 'DPDP'
l!l&&r!l&&!r
545
MC/DC100%2/2
$magic eq 'DPDB' || $magic eq 'DPDP'
$magic eq 'DPDB' $magic eq 'DPDP'
Truth table100%3/3
A || B
A= $magic eq 'DPDB'B= $magic eq 'DPDP'
ABresult
1X1
011
000
5048 }
5049  
5050 # Log and remember a message
5051 sub _log
5052 3414 ▶{
Subroutine _log: called CC=3 SCAR=11.8
5053 3414 my ($self, $level, @messages) = @_;
5054  
5055 # FIXME: add caller's function
5056 # if(($level eq 'warn') || ($level eq 'notice')) {
5057 3414 push @{$self->{'messages'}}, { level => $level, message => join('', grep defined, @messages) };
5058 # }
5059  
5060 3414 ▶ if(scalar(@messages) && (my $logger = $self->{'logger'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @messages and my $logger = $$self{"logger"}) 3414 0 3414
Condition33%1/3
scalar @messages and my $logger = $$self{"logger"}
!ll&&!rl&&r
003414
MC/DC0%0/2
scalar @messages and my $logger = $$self{"logger"}
scalar @messages my $logger = $$self{"logger"}
Truth table33%1/3
A and B
A= scalar @messagesB= my $logger = $$self{"logger"}
ABresult
0X0
100
111
5061 3414 $self->{'logger'}->$level(join('', grep defined, @messages));
5062 }
5063 }
5064  
5065 2477 ▶sub _debug {
Subroutine _debug: called CC=1 SCAR=0.0
5066 2477 my $self = shift;
5067 2477 $self->_log('debug', @_);
5068 }
5069  
5070 930 ▶sub _trace {
Subroutine _trace: called CC=1 SCAR=0.0
5071 930 my $self = shift;
5072 930 $self->_log('trace', @_);
5073 }
5074  
5075 # Emit a warning message somewhere
5076 1 ▶sub _warn {
Subroutine _warn: called CC=1 SCAR=0.0
5077 1 my $self = shift;
5078 1 my $params = Params::Get::get_params('warning', \@_);
5079  
5080 1 $self->_log('warn', $params->{'warning'});
5081 1 Carp::carp(join('', grep defined, $params->{'warning'}));
5082 }
5083  
5084 # Die
5085 6 ▶sub _fatal {
Subroutine _fatal: called CC=1 SCAR=0.0
5086 6 my $self = shift;
5087 6 my $params = Params::Get::get_params('warning', \@_);
5088  
5089 6 $self->_log('error', $params->{'warning'});
5090 6 Carp::croak(join('', grep defined, $params->{'warning'}));
5091 }
5092  
5093 =head1 AUTHOR
5094  
5095 Nigel Horne, C<< <njh at nigelhorne.com> >>
5096  
5097 =head1 SUPPORT
5098  
5099 This module is provided as-is without any warranty.
5100  
5101 Please report any bugs or feature requests to C<bug-database-abstraction at rt.cpan.org>,
5102 or through the web interface at
5103 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Database-Abstraction>.
5104 I will be notified, and then you'll
5105 automatically be notified of progress on your bug as I make changes.
5106  
5107 =head1 MESSAGES
5108  
5109 The table below lists every error that the module can croak or carp, what
5110 triggers it, and how to resolve it.
5111  
5112 =over 4
5113  
5114 =item C<< I<Class>: abstract class >>
5115  
5116 Direct instantiation of C<Database::Abstraction> was attempted.
5117 Create a subclass and instantiate that instead.
5118  
5119 =item C<< I<Class>: where are the files? >>
5120  
5121 Neither C<directory> nor C<dsn> was supplied to C<new()>.
5122  
5123 =item C<< I<Class>: I</path> is not a directory >>
5124  
5125 The C<directory> argument exists on disk but is not a directory.
5126  
5127 =item C<< I<Class>: cannot connect: I<$DBI::errstr> >>
5128  
5129 DBI failed to connect to the given C<dsn>. Check credentials and host.
5130  
5131 =item C<< Can't find a file called 'I<name>' for the table I<T> in I<dir> >>
5132  
5133 None of the probe extensions (C<.sql>, C<.sqlite>, C<.sqlite3>, C<.psv>, C<.tsv>, C<.csv>, C<.xlsx>, C<.db>, C<.xml>)
5134 matched in C<directory>.
5135  
5136 =item C<< I<Class>: prepare failed: I<$errstr> >>
5137  
5138 C<prepare_cached()> returned false. Usually a syntax error in an internally
5139 built query; file a bug if you see this from a normal API call.
5140  
5141 =item C<< _build_where_conditions: unsafe column name 'I<name>' >>
5142  
5143 A criteria key contained characters outside C<[A-Za-z0-9_.]>.
5144 This is a SQL-injection guard. Use only valid SQL identifier characters.
5145  
5146 =item C<< join: missing "table" >> / C<< join: missing "on" condition >>
5147  
5148 A join spec hashref is incomplete. Both C<table> and C<on> are required.
5149  
5150 =item C<< Invalid JOIN type: I<TYPE> >>
5151  
5152 C<type> in a join spec was not one of C<INNER LEFT RIGHT FULL CROSS>.
5153  
5154 =item C<< I<Class>: Unknown column I<col> >> / C<< I<Class>: AUTOLOAD disabled >>
5155  
5156 An AUTOLOAD call was made for a column that does not exist, or AUTOLOAD
5157 was disabled with C<< auto_load => 0 >>.
5158  
5159 =item C<< Usage: set_logger(logger => $logger) >>
5160  
5161 C<set_logger()> was called without a C<logger> argument.
5162  
5163 =item C<< Usage: execute(query => $query) >>
5164  
5165 C<execute()> was called without a C<query> argument.
5166  
5167 =item C<< XML slurp: I<...> is not yet supported >>
5168  
5169 The XML file structure is too complex for slurp mode.
5170 Use C<< max_slurp_size => 0 >> to force the DBI/XMLSimple SQL path.
5171  
5172 =item C<< I<Class>: I<method> is meaningless on a NoSQL database >>
5173  
5174 A relational method (C<selectall_arrayref>, C<count>, C<execute>, etc.)
5175 was called on a BerkeleyDB backend, which only supports key-value lookup
5176 via C<fetchrow_hashref>.
5177  
5178 =item C<< I<Class>: aggregate: 'measures' must be a non-empty arrayref >>
5179  
5180 C<aggregate()> was called without a C<measures> arrayref, or with an empty one.
5181  
5182 =item C<< I<Class>: aggregate: measure must be a hashref, got I<ref> >>
5183  
5184 An element of the C<measures> arrayref is not a hashref.
5185  
5186 =item C<< I<Class>: aggregate: unknown measure function 'I<fn>' >>
5187  
5188 C<fn> must be one of C<sum>, C<avg>, C<min>, C<max>, C<count>, C<count_distinct>,
5189 C<median>, C<stddev>.
5190  
5191 =item C<< I<Class>: aggregate: measure column is required for function 'I<fn>' >>
5192  
5193 C<col> was omitted for a function that requires it. Only plain C<count> (COUNT(*)) accepts a missing C<col>.
5194  
5195 =item C<< I<Class>: aggregate: unsafe measure column 'I<col>' >>
5196  
5197 The C<col> value is not a valid SQL identifier.
5198  
5199 =item C<< I<Class>: aggregate: measure 'as' is required >>
5200  
5201 The C<as> alias was missing from a measure hashref.
5202  
5203 =item C<< I<Class>: aggregate: unsafe measure alias 'I<as>' >>
5204  
5205 The C<as> value is not a valid SQL identifier.
5206  
5207 =item C<< I<Class>: aggregate: duplicate measure alias 'I<as>' >>
5208  
5209 Two measure hashrefs share the same C<as> alias.
5210  
5211 =item C<< I<Class>: aggregate: measure alias 'I<as>' collides with a group-by column >>
5212  
5213 A measure alias duplicates a name in the C<by> list.
5214  
5215 =item C<< I<Class>: aggregate: 'by' must be an arrayref of column names >>
5216  
5217 The C<by> parameter was not an arrayref.
5218  
5219 =item C<< I<Class>: aggregate: unsafe group-by column 'I<col>' >>
5220  
5221 A C<by> element is not a valid SQL identifier.
5222  
5223 =item C<< I<Class>: aggregate: having key 'I<key>' is not a group-by column or measure alias >>
5224  
5225 A C<having> key does not match any C<by> column name or measure C<as> alias.
5226  
5227 =item C<< I<Class>: aggregate: sort_by names 'I<name>', which is not a group-by column or measure alias >>
5228  
5229 The C<sort_by> column is not one of the C<by> columns or measure aliases.
5230  
5231 =item C<< I<Class>: aggregate: cannot aggregate a JOIN on the I<backend> backend >>
5232  
5233 C<join> was passed to C<aggregate()> on a slurp-only backend that has no DBI handle.
5234  
5235 =item C<< Database::Abstraction::Query: count() is not available once measure() has been called >>
5236  
5237 C<count()> was called on a query builder that has measures set. Use C<all()> and check C<scalar @{$rows}>.
5238  
5239 =back
5240  
5241 =head1 COMMON PITFALLS
5242  
5243 The following mistakes cause unexpected behaviour in common usage.
5244 Read this section before filing a bug report.
5245  
5246 =over 4
5247  
5248 =item B<Default CSV separator is C<!>, not C<,>>
5249  
5250 For historical reasons the module defaults to bang (C<!>) as the
5251 field separator for CSV files. Standard RFC 4180 comma-separated
5252 files require you to pass C<< sep_char => ',' >> in your subclass
5253 constructor.
5254  
5255 sub new {
5256 my ($class, %args) = @_;
5257 return $class->SUPER::new(sep_char => ',', %args);
5258 }
5259  
5260 =item B<Primary key column is named C<entry>, not C<key>>
5261  
5262 The default primary-key column name is C<entry> because C<key> is
5263 a reserved word in SQL. If your data uses a different column name
5264 (e.g. C<id>, C<customer_id>), pass C<< id => 'customer_id' >> to
5265 C<new()>.
5266  
5267 =item B<Duplicate primary keys silently overwrite earlier rows>
5268  
5269 In slurp mode the entire data file is loaded into a Perl hash keyed
5270 by the C<entry> column. If two rows share the same key value the
5271 second row replaces the first. To keep duplicates either disable
5272 slurp with C<< max_slurp_size => 0 >> or switch to a C<no_entry>
5273 schema.
5274  
5275 =item B<Operator-hash criteria do not work on no-DBI backends>
5276  
5277 No-DBI backends (XLSX, DBM::Deep, JSON, HTML URL, Redis) have no SQL
5278 engine. Criteria that use operator hashes (e.g.
5279 C<< score => { '>=' => 80 } >>) trigger the SQL path and will croak
5280 with a "meaningless on a NoSQL database" error. Use simple scalar
5281 criteria (C<< score => 80 >>) on these backends.
5282  
5283 =item B<Read-only results: do not modify returned hashrefs>
5284  
5285 Unless you pass C<< no_fixate => 1 >>, every hashref returned by
5286 C<selectall_arrayref>, C<fetchrow_hashref>, and similar methods is
5287 made read-only by C<Data::Reuse>. Attempting to assign a value to
5288 a key in the returned hashref will throw an exception. If you need
5289 to modify a row, either copy it first (C<my %row = %{$orig_row}>) or
5290 construct the object with C<< no_fixate => 1 >>.
5291  
5292 =item B<C<where()> calls in the query builder use AND semantics>
5293  
5294 Each call to C<< $q->where(...) >> adds an additional required
5295 condition. Two separate C<where()> calls do NOT produce OR
5296 semantics. To express OR, pass C<< -or => [...] >> inside a single
5297 C<where()> call:
5298  
5299 # Wrong: this is AND, not OR
5300 $q->where(status => 'active')->where(status => 'pending');
5301  
5302 # Correct: OR grouping inside one where() call
5303 $q->where(-or => [{ status => 'active' }, { status => 'pending' }]);
5304  
5305 =item B<C<aggregate()> C<sort_by> must name a grouped or aliased column>
5306  
5307 The C<sort_by> parameter for C<aggregate()> only accepts column names
5308 from the C<by> list or measure C<as> aliases. You cannot sort
5309 aggregate results by a raw data column that is not part of the group.
5310 This restriction applies equally to the C<< ->order_by() >> call on a
5311 query builder that has C<measure()> methods set.
5312  
5313 =item B<C<sort_by> is not an argument to the query builder's C<all()>>
5314  
5315 When using the fluent query builder to build an aggregate query, set
5316 the sort column via C<< ->order_by('col') >> before calling
5317 C<< ->all() >>. Passing C<< ->all(sort_by => 'col') >> has no
5318 effect because the C<all()> terminal method ignores extra arguments.
5319  
5320 =item B<C<Params::Get> positional mapping with C<no_entry = 0>>
5321  
5322 When C<no_entry> is false (the default), the first positional argument
5323 to C<selectall_arrayref> and C<fetchrow_hashref> is silently mapped to
5324 the C<entry> key. Passing an operator-hash criteria in that position
5325 (e.g. C<selectall_arrayref(status => { '!=' => 'x' })>) causes
5326 C<status> to be treated as the entry value rather than a column name,
5327 which will produce wrong results. Always pass a hashref of criteria
5328 as a single reference, or use C<no_entry => 1> in your subclass.
5329  
5330 =back
5331  
5332 =head1 ENCODING
5333  
5334 =over 4
5335  
5336 =item B<Column names> must match the pattern C<[a-zA-Z_][a-zA-Z0-9_.]*>.
5337 Only ASCII letters, digits, underscores, and dots (for qualified names
5338 such as C<table.column>) are accepted. Non-ASCII Unicode characters
5339 in column names will cause a croak with an "unsafe column name" error.
5340  
5341 =item B<Column values> (data stored in your rows) are passed through
5342 unchanged. Full UTF-8 strings, emoji, and any valid Perl string are
5343 safe as values in criteria and are stored and returned as-is. The
5344 exact encoding depends on your backend:
5345  
5346 =over 4
5347  
5348 =item * B<SQLite / DBI backends> -- DBD::SQLite stores strings as
5349 UTF-8 internally. Enable C<< sqlite_unicode => 1 >> in your DSN
5350 or connect attributes if you want Perl to receive decoded Unicode
5351 scalars rather than raw UTF-8 bytes.
5352  
5353 =item * B<CSV / PSV / TSV> -- Text::CSV and DBD::CSV pass bytes
5354 through unchanged. If your file is UTF-8-encoded, strings are
5355 returned as UTF-8 byte strings. You may need to decode them with
5356 C<Encode::decode('UTF-8', $val)> in your application.
5357  
5358 =item * B<JSON> -- JSON::MaybeXS decodes JSON strings to Perl Unicode
5359 scalars automatically. UTF-8 and emoji in JSON values are fully
5360 supported.
5361  
5362 =item * B<XML> -- XML::Simple decodes the file with the XML encoding
5363 declaration. UTF-8 encoded XML (the default) produces Perl Unicode
5364 scalars.
5365  
5366 =item * B<XLSX> -- Spreadsheet::ParseXLSX decodes strings to Perl
5367 Unicode scalars. Emoji in cell values are fully supported.
5368  
5369 =item * B<HTML URL> -- LWP::UserAgent fetches bytes; HTML::TableExtract
5370 returns them as-is. Decode with Encode if the page is UTF-8.
5371  
5372 =back
5373  
5374 =item B<File paths> are handled by C<File::Spec::catfile> and work
5375 on any platform. On Linux and macOS, UTF-8 directory and file names
5376 are fully supported.
5377  
5378 =back
5379  
5380 =head1 KNOWN LIMITATIONS
5381  
5382 =over 4
5383  
5384 =item *
5385  
5386 B<Read-only.> No INSERT, UPDATE, or DELETE is provided. C<execute()>
5387 runs raw read-only SQL.
5388  
5389 =item *
5390  
5391 B<Default CSV separator is C<!>>, not C<,>, for historical reasons.
5392 Pass C<< sep_char => ',' >> for standard RFC 4180 files.
5393  
5394 =item *
5395  
5396 B<Primary-key column is named C<entry>>, not C<key>, because C<key>
5397 is a SQL reserved word. Override with the C<id> parameter.
5398  
5399 =item *
5400  
5401 B<XML slurp is limited.> Only simple flat XML structures are supported
5402 in slurp mode. Multi-key or deeply nested documents will croak.
5403 Force SQL mode with C<< max_slurp_size => 0 >> if slurp fails.
5404  
5405 =item *
5406  
5407 B<Unique key assumption in slurp mode.> Duplicate values in the key
5408 column silently overwrite earlier rows. Disable slurp with
5409 C<< max_slurp_size => 0 >> if duplicates are expected.
5410  
5411 =item *
5412  
5413 B<BerkeleyDB does not support joins or the chained query builder.>
5414  
5415 =item *
5416  
5417 B<Column names must be valid SQL identifiers> (letters, digits,
5418 underscores, and a single dot for C<table.column> join notation).
5419 Other characters will cause a croak.
5420  
5421 =item *
5422  
5423 B<count() cache is opportunistic.> Count results are served from cache
5424 only when a prior C<selectall_arrayref()> or C<count()> call with the
5425 same criteria has already populated it.
5426  
5427 =back
5428  
5429 =head1 SEE ALSO
5430  
5431 =over 4
5432  
5433 =item * L<Database::Abstraction::Query> - chained query builder
5434  
5435 =item * L<Configure an Object at Runtime|Object::Configure>
5436  
5437 =item * L<JSON::MaybeXS> - JSON backend (optional; install for C<.json> support)
5438  
5439 =item * L<Test Dashboard|https://nigelhorne.github.io/Database-Abstraction/coverage/>
5440  
5441 =back
5442  
5443 =head1 FORMAL SPECIFICATION
5444  
5445 The following section uses Z-notation to describe the key state
5446 transitions and invariants for the module. Z is a formal
5447 specification language based on set theory and predicate logic.
5448 Unicode is used here as permitted by the documentation skill.
5449  
5450 =head2 Database object state
5451  
5452 State == [
5453 data : TABLE_NAME --> (ENTRY --> ROW) | seq ROW | undef,
5454 dbh : TABLE_NAME --> DBI_HANDLE | undef,
5455 type : Str | undef,
5456 base_crit : CRITERIA,
5457 _columns : seq Str | undef,
5458 _schema : NAME --> COL_INFO | undef,
5459 _destroyed : Bool
5460 ]
5461  
5462 Initial state S0 == [
5463 data? = undef,
5464 dbh? = undef,
5465 type? = undef,
5466 base_crit? = {},
5467 _columns? = undef,
5468 _schema? = undef,
5469 _destroyed? = false
5470 ]
5471  
5472 =head2 _open_table
5473  
5474 _open_table ___________________________________________
5475 DeltaState
5476 class? : CLASS
5477 dir? : DIRPATH | undef
5478 ────────────────────────────────────────────────────
5479 pre: _destroyed = false
5480 pre: dbh(table) = undef AND data(table) = undef
5481 post: (EXISTS f : FILE_FORMATS WITH f.probe(dir) = true
5482 IMPLIES (f.slurp? IMPLIES data'(table) != undef)
5483 AND (f.dbi? IMPLIES dbh'(table) != undef))
5484  
5485 =head2 selectall_arrayref
5486  
5487 selectall_arrayref __________________________________
5488 XiState (read-only; state unchanged except cache)
5489 criteria? : CRITERIA
5490 ────────────────────────────────────────────────────
5491 pre: _destroyed = false
5492 result == (data != undef AND simple(criteria)
5493 IMPLIES { r : data | match(r, criteria) }
5494 ELSE dbh != undef
5495 IMPLIES SQL_SELECT(dbh, criteria))
5496 post: result : seq ROW UNION {undef}
5497  
5498 =head2 aggregate
5499  
5500 aggregate ____________________________________________
5501 XiState
5502 by? : seq COLNAME
5503 measures? : seq MEASURE_SPEC
5504 criteria? : CRITERIA
5505 ────────────────────────────────────────────────────
5506 pre: measures != empty
5507 pre: FORALL m : measures WITH m.as NOT IN by
5508 pre: sort_by != undef IMPLIES sort_by IN ran(by) UNION aliases(measures)
5509 result == (dbh != undef
5510 IMPLIES SQL_GROUP_BY(dbh, by, measures, criteria)
5511 ELSE PERL_FOLD(selectall_arrayref(criteria), by, measures))
5512 post: result : seq ROW (keys = by UNION aliases(measures))
5513 post: FORALL r : result WITH
5514 r.count != undef IMPLIES r.count >= 0
5515 AND r.sum = undef IMPLIES no rows in that group
5516  
5517 =head2 DESTROY
5518  
5519 DESTROY ______________________________________________
5520 DeltaState
5521 ────────────────────────────────────────────────────
5522 post: _destroyed' = true
5523 post: dbh' = undef (DBI handles disconnected)
5524 post: data' = undef
5525 post: _columns' = undef
5526 post: _schema' = undef
5527  
5528 =head1 STATE DIAGRAM
5529  
5530 The following ASCII diagram shows every valid state the object can
5531 occupy and the transitions between them. Transitions are labelled
5532 with the method call or event that triggers them. Actions are shown
5533 in parentheses.
5534  
5535 .-----------------------------------------------------------.
5536 | S1: CONSTRUCTED |
5537 | dbh=undef, data=undef, type=undef |
5538 '---.-------.-------.-------.-------.-----.---.-------------'
5539 | | | | | | |
5540 | first query call triggers _open_table()
5541 | | | | | | |
5542 v v v v v v v
5543 .------. .------. .------. .------. .--. .--. .--.
5544 | S2 | | S3 | | S4 | | S5 | |S6| |S7| |S8|
5545 | DBI | | CSV | | XML | | JSON | |Xls| |Bk| |Dp|
5546 '---^--' '--^---' '--^---' '--^---' '-^-' '-^-' '-^-'
5547 | | | | | | | |
5548 | | '-------'-------' | | |
5549 | | slurp path | | |
5550 | '-----------+---------------' | |
5551 | | | |
5552 | (data populated, | |
5553 | _columns/_schema undef) | |
5554 | | |
5555 | (dbh populated, | |
5556 | data undef) | |
5557 | | |
5558 +-------+--------+-----------+----------+ |
5559 | | | |
5560 selectall fetchrow aggregate fetchrow
5561 count _hashref query->all _hashref
5562 each_row AUTOLOAD AUTOLOAD AUTOLOAD
5563 | | | |
5564 v v v v
5565 .-----------------------------------------------------------.
5566 | (result returned to caller) |
5567 | state is unchanged; only cache may be updated |
5568 '-----------------------------------------------------------'
5569 |
5570 DESTROY (or object goes out of scope)
5571 |
5572 v
5573 .-----------------------------------------------------------.
5574 | S_DEAD: DESTROYED |
5575 | _destroyed=true; all handles disconnected; |
5576 | temp files unlinked; _remote_tmpdir removed |
5577 '-----------------------------------------------------------'
5578  
5579 State labels:
5580 S1 CONSTRUCTED - new() returned; no I/O done yet (lazy open)
5581 S2 DBI - live DBI handle (SQLite file, DSN, DBD::CSV)
5582 S3 CSV_SLURP - small CSV/PSV/TSV/gzip-CSV slurped into RAM hash
5583 S4 XML_SLURP - XML file slurped into RAM hash
5584 S5 JSON_SLURP - JSON file slurped into RAM hash
5585 S6 XLSX_SLURP - XLSX file slurped (type='XLSX', no DBI handle)
5586 S7 BERKELEYDB - BerkeleyDB key-value file open (berkeley flag set)
5587 S8 DEEP_SLURP - DBM::Deep file slurped into plain RAM hash
5588  
5589 Blocked transitions (croak before state changes):
5590 S1 -> any if constructor arguments are invalid
5591 (unsafe id/table/host/url)
5592 S* -> S* aggregate() with join on S3/S4/S5/S6/S7/S8
5593 (no DBI handle)
5594 S7 -> S* join() or select()-projection on BerkeleyDB
5595 S8 -> S* join() on DBM::Deep
5596  
5597 =head1 LICENSE AND COPYRIGHT
5598  
5599 Copyright 2015-2026 Nigel Horne.
5600  
5601 Usage is subject to the GPL2 licence terms.
5602 If you use it,
5603 please let me know.
5604  
5605 =cut
5606  
5607 54 1;
↑ Summary Abstraction/Query.pm »