Abstraction.pm

filter: Statementstmt 82.2% 1887 / 2294 Branchbran 74.2% 1166 / 1570 Conditioncond 57.0% 502 / 880 MC/DCmcdc 42.9% 217 / 505 Subroutinesub 95.7% 90 / 94 Podpod 100% 18 / 18 totaltotal 72.3% 3880 / 5361 CC 1178 SCAR 63.2
CC
1178
Cov
75%
_open
1975.8
selectall_array
1602.2
selectall_arrayref
755.0
CRAP 557.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 53 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 53 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 53 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 53 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 53 ▶use Class::Abstract;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 53 ▶use Data::Reuse;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 53 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 53 ▶use Fcntl; # For O_RDONLY
Subroutine BEGIN: called CC=1 SCAR=0.0
31 53 ▶use Cwd;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 53 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 53 ▶use File::Temp;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 53 ▶use List::Util qw(all any);
Subroutine BEGIN: called CC=1 SCAR=0.0
35 53 ▶use Log::Abstraction 0.33;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 53 ▶use Object::Configure 0.16;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 53 ▶use Params::Get 0.17;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 53 ▶use Return::Set qw(set_return);
Subroutine BEGIN: called CC=1 SCAR=0.0
39 53 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 53 ▶use Sub::Private { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
41 53 ▶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 53 our %defaults;
46 53 ▶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 53 my $SAFE_IDENTIFIER = qr/\A[a-zA-Z_][a-zA-Z0-9_]*\z/;
53 53 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 53 ▶use constant INFER_TYPE_SAMPLE_SIZE => 100;
Subroutine BEGIN: called CC=1 SCAR=0.0
58 53 my $INFER_INT_RE = qr/\A-?\d+\z/;
59 53 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 53 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 53 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 53 my %VALID_JOIN_TYPES = map { $_ => 1 } qw(INNER LEFT RIGHT FULL CROSS);
93  
94 # Valid aggregate functions (lower-cased) for _validate_aggregate_spec.
95 53 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 53 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.56
109  
110 =cut
111  
112 53 our $VERSION = '0.56';
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 736 ▶sub new {
Subroutine new: called CC=46 SCAR=39.5
Pod documented
810 736 my $class = shift;
811 736 my %args;
812  
813 736 Class::Abstract::check_abstract($class); # enforces abstract contract
814  
815 # Handle hash or hashref arguments
816 730 ▶ if((scalar(@_) == 1) && !ref($_[0])) {
Branch: 2 branches
BranchTrueFalseTotal
if (scalar @_ == 1 and not ref $_[0]) { } 127 603 730
elsif (my $params = Params::Get::get_params(undef, @_)) { } 595 8 603
Condition100%3/3
scalar @_ == 1 and not ref $_[0]
!ll&&!rl&&r
53865127
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 595 %args = %{$params};
820 }
821  
822 730 ▶ if(!defined($class)) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $class) { } 0 730 730
elsif ($class eq __PACKAGE__) { } 0 730 730
elsif (builtin::blessed($class)) { } 13 717 730
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 717 %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 717 ▶ if(defined $args{'logger'} && !Scalar::Util::blessed($args{'logger'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"logger"} and not builtin::blessed($args{"logger"})) 0 717 717
Condition33%1/3
defined $args{"logger"} and not builtin::blessed($args{"logger"})
!ll&&!rl&&r
07170
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 717 ▶ 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"}) 612 105 717
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
1050612
$args{"dsn"} or $Database::Abstraction::defaults{"dsn"} or $args{"url"} or $Database::Abstraction::defaults{"url"} or $args{"database"}
l!l&&r!l&&!r
969612
$args{"dsn"} or $Database::Abstraction::defaults{"dsn"} or $args{"url"} or $Database::Abstraction::defaults{"url"}
l!l&&r!l&&!r
960621
$args{"dsn"} or $Database::Abstraction::defaults{"dsn"} or $args{"url"}
l!l&&r!l&&!r
5838621
$args{"dsn"} or $Database::Abstraction::defaults{"dsn"}
l!l&&r!l&&!r
580659
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 612 ▶ croak("$class: where are the files?") unless($args{'directory'} || $defaults{'directory'});
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"directory"} or $Database::Abstraction::defaults{"directory"} 5 607 612
Condition100%3/3
$args{"directory"} or $Database::Abstraction::defaults{"directory"}
l!l&&r!l&&!r
60345
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 607 ▶ my $given_host = $args{'host'} // $defaults{'host'};
Condition66%2/3
$args{"host"} // $Database::Abstraction::defaults{"host"}
l!l&&r!l&&!r
400567
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 607 ▶ unless($given_host && !$class->_is_local_host($given_host)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($given_host and not $class->_is_local_host($given_host)) 577 30 607
Condition100%3/3
$given_host and not $class->_is_local_host($given_host)
!ll&&!rl&&r
568930
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 577 ▶ 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 568 577
Condition50%3/6
$args{'directory'} || $Database::Abstraction::defaults{'directory'}
l!l&&r!l&&!r
57340
$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 703 for my $src (\%defaults, \%args) {
870 1406 ▶ if(defined $src->{'id'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"id"}) 65 1341 1406
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 1379 ▶ if(defined $src->{'host'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"host"}) 40 1339 1379
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 1356 ▶ if(defined $src->{'url'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"url"}) 39 1317 1356
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 1340 ▶ if(defined $src->{'database'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"database"}) 9 1331 1340
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 1336 ▶ if(defined $src->{'table'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"table"}) 35 1301 1336
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 1311 ▶ if(defined $src->{'redis_key'} && !defined $src->{'database'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"redis_key"} and not defined $$src{"database"}) 1 1310 1311
Condition100%3/3
defined $$src{"redis_key"} and not defined $$src{"database"}
!ll&&!rl&&r
130911
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 1310 ▶ if(defined $src->{'base_criteria'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$src{"base_criteria"}) 55 1255 1310
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 580 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 434 ▶sub _open :Protected
Subroutine _open: called CC=183 SCAR=75.9
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 434 ▶ 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 433 434
Condition66%2/3
$c and $c->isa(__PACKAGE__)
!ll&&!rl&&r
01433
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 433 my $self = shift;
997 433 my $params = Params::Get::get_params(undef, \@_);
998  
999 433 ▶ $params->{'sep_char'} ||= $self->{'sep_char'} ? $self->{'sep_char'} : '!';
Branch: 1 branch
BranchTrueFalseTotal
$$self{'sep_char'} ? : 47 385 432
Condition66%2/3
$$params{"sep_char"} ||= $$self{"sep_char"} ? $$self{"sep_char"} : "!"
l!l&&r!l&&!r
14320
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 433 ▶ 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
040429
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 433 ▶ my $table = $self->{'table'} || ref($self);
Condition33%1/3
$$self{'table'} || ref $self
l!l&&r!l&&!r
04330
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 433 $table =~ s/\A.*:://;
1004  
1005 433 $self->_trace(ref($self), ": _open $table");
1006  
1007 433 ▶ return if($self->{'_dbh'}{$table});
Branch: 1 branch
BranchTrueFalseTotal
if $$self{"_dbh"}{$table} 1 432 433
1008  
1009 # Read in the database
1010 432 my $dbh;
1011  
1012 # DSN-based connection bypasses file detection entirely
1013 432 ▶ if(my $dsn = $self->{'dsn'} || $defaults{'dsn'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $dsn = $$self{"dsn"} || $Database::Abstraction::defaults{"dsn"}) 54 378 432
Condition66%2/3
$$self{'dsn'} || $Database::Abstraction::defaults{'dsn'}
l!l&&r!l&&!r
540378
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 378 ▶ if(my $db_url = $self->{'database'} || $defaults{'database'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $db_url = $$self{"database"} || $Database::Abstraction::defaults{"database"}) 1 377 378
Condition66%2/3
$$self{'database'} || $Database::Abstraction::defaults{'database'}
l!l&&r!l&&!r
10377
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 377 ▶ if(my $url = $self->{'url'} || $defaults{'url'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $url = $$self{"url"} || $Database::Abstraction::defaults{"url"}) 17 360 377
Condition66%2/3
$$self{'url'} || $Database::Abstraction::defaults{'url'}
l!l&&r!l&&!r
170360
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 360 my $class_stem = ref($self);
1229 360 $class_stem =~ s/\A.*:://;
1230 360 ▶ my $dbname = $self->{'dbname'} || $defaults{'dbname'} || $class_stem;
Condition66%4/6
$$self{'dbname'} || $Database::Abstraction::defaults{'dbname'} || $class_stem
l!l&&r!l&&!r
433170
$$self{"dbname"} or $Database::Abstraction::defaults{"dbname"}
l!l&&r!l&&!r
430317
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 360 ▶ Carp::croak(ref($self), ": unsafe dbname '$dbname'")
Branch: 1 branch
BranchTrueFalseTotal
unless $dbname =~ /\A[a-zA-Z0-9_.-]+\z/ and not $dbname =~ /\.\./ 10 350 360
Condition100%3/3
$dbname =~ /\A[a-zA-Z0-9_.-]+\z/ and not $dbname =~ /\.\./
!ll&&!rl&&r
91350
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 350 my $dir;
1239 350 ▶ if(my $host = $self->{'host'} || $defaults{'host'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $host = $$self{'host'} || $Database::Abstraction::defaults{'host'}) { } 8 342 350
Condition66%2/3
$$self{'host'} || $Database::Abstraction::defaults{'host'}
l!l&&r!l&&!r
80342
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 342 ▶ my $raw_dir = $self->{'directory'} || $defaults{'directory'};
Condition33%1/3
$$self{'directory'} || $Database::Abstraction::defaults{'directory'}
l!l&&r!l&&!r
34200
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 342 ▶ Carp::croak(ref($self), ': no directory specified') unless $raw_dir;
Branch: 1 branch
BranchTrueFalseTotal
unless $raw_dir 0 342 342
1321 342 $dir = Cwd::abs_path($raw_dir);
1322 }
1323 # Probe for SQLite files (.sql, .sqlite, .sqlite3)
1324 349 my $slurp_file;
1325 349 for my $ext (qw(sql sqlite sqlite3)) {
1326 991 my $candidate = File::Spec->catfile($dir, "$dbname.$ext");
1327 991 ▶ if(-r $candidate) { $slurp_file = $candidate; last }
Branch: 1 branch
BranchTrueFalseTotal
if (-r $candidate) 31 960 991
1328 }
1329 349 ▶ $slurp_file //= File::Spec->catfile($dir, "$dbname.sql");
Condition66%2/3
$slurp_file //= "File::Spec"->catfile($dir, "$dbname.sql")
l!l&&r!l&&!r
313180
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 349 $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 349 my $deep_file;
1336 349 for my $ext (qw(dbm deep)) {
1337 692 my $candidate = File::Spec->catfile($dir, "$dbname.$ext");
1338 692 ▶ if(-r $candidate) { $deep_file = $candidate; last }
Branch: 1 branch
BranchTrueFalseTotal
if (-r $candidate) 12 680 692
1339 }
1340 # Also detect DBM::Deep files by magic bytes (covers .db files and arbitrary extensions).
1341 349 ▶ if(!$deep_file) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($deep_file) 337 12 349
1342 337 my $db_candidate = File::Spec->catfile($dir, "$dbname.db");
1343 337 ▶ $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 336 337
Condition100%3/3
-r $db_candidate and $self->_is_deep_db($db_candidate)
!ll&&!rl&&r
33511
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 349 ▶ if(-r $slurp_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $slurp_file) 31 318 349
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 349 ▶ if($dbh) {
Branch: 3 branches
BranchTrueFalseTotal
if ($dbh) { } 31 318 349
elsif ($deep_file) { } 13 305 318
elsif ($self->_is_berkeley_db('File::Spec'->catfile($dir, "$dbname.db"))) { } 0 305 305
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 305 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 305 for my $ext (qw(csv.gz db.gz)) {
1407 603 my $candidate = File::Spec->catfile($dir, "$dbname.$ext");
1408 603 ▶ next unless -r $candidate;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $candidate 595 8 603
1409 8 open($fin, '<', $candidate);
1410 8 $gz_file = $candidate;
1411 8 last;
1412 }
1413 305 ▶ if($gz_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($gz_file) { } 8 297 305
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 297 my $psv = File::Spec->catfile($dir, "$dbname.psv");
1424 297 ▶ if(-r $psv) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $psv) { } 8 289 297
1425 8 open($fin, '<', $psv);
1426 # Pipe separated file
1427 8 $slurp_file = $psv;
1428 8 $params->{'sep_char'} = '|';
1429 } else {
1430 289 my $tsv = File::Spec->catfile($dir, "$dbname.tsv");
1431 289 ▶ if(-r $tsv) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $tsv) { } 4 285 289
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 285 for my $ext (qw(csv db)) {
1439 323 my $candidate = File::Spec->catfile($dir, "$dbname.$ext");
1440 323 ▶ next unless -r $candidate;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $candidate 75 248 323
1441 248 open($fin, '<', $candidate);
1442 248 $slurp_file = $candidate;
1443 248 last;
1444 }
1445 }
1446 }
1447 }
1448 304 ▶ if(my $filename = $self->{'filename'} || $defaults{'filename'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $filename = $$self{"filename"} || $Database::Abstraction::defaults{"filename"}) 13 291 304
Condition66%2/3
$$self{'filename'} || $Database::Abstraction::defaults{'filename'}
l!l&&r!l&&!r
130291
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 295 ▶ if(defined($slurp_file) && (-r $slurp_file)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $slurp_file and -r $slurp_file) { } 263 32 295
Condition66%2/3
defined $slurp_file and -r $slurp_file
!ll&&!rl&&r
032263
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 32 my $xls_file = File::Spec->catfile($dir, "$dbname.xls");
1558 32 ▶ if(-r $xls_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $xls_file) { } 0 32 32
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 32 my $xlsx_file = File::Spec->catfile($dir, "$dbname.xlsx");
1570 32 ▶ if(-r $xlsx_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $xlsx_file) { } 0 32 32
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 32 $slurp_file = File::Spec->catfile($dir, "$dbname.xml");
1604 32 ▶ if(-r $slurp_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $slurp_file) { } 18 14 32
1605 18 ▶ if((-s $slurp_file) <= $max_slurp_size) {
Branch: 1 branch
BranchTrueFalseTotal
if (-s $slurp_file <= $max_slurp_size) { } 15 3 18
1606 15 require XML::Simple;
1607  
1608 14 my $xml = XML::Simple::XMLin($slurp_file);
1609 8 my @keys = keys %{$xml};
1610 8 my $key = $keys[0];
1611 8 my @data;
1612 8 ▶ if(ref($xml->{$key}) eq 'ARRAY') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $$xml{$key} eq 'ARRAY') { } 4 4 8
elsif (ref $xml eq 'ARRAY') { } 0 4 4
elsif (ref $xml eq 'HASH' and not $$self{'no_entry'}) { } 3 1 4
1613 4 @data = @{$xml->{$key}};
1614 } elsif(ref($xml) eq 'ARRAY') {
1615 0 @data = @{$xml};
1616 ▶ } elsif((ref($xml) eq 'HASH') && !$self->{'no_entry'}) {
Condition66%2/3
ref $xml eq "HASH" and not $$self{"no_entry"}
!ll&&!rl&&r
013
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
1617 3 ▶ if(scalar(keys %{$xml}) == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$xml;} == 1) { } 2 1 3
1618 2 ▶ if($xml->{$table}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$xml{$table}) { } 1 1 2
1619 1 @data = $xml->{$table};
1620 } else {
1621 1 Carp::croak('XML slurp: complex documents with an "entry" field are not yet supported');
1622 }
1623 } else {
1624 1 Carp::croak('XML slurp: multi-key documents are not yet supported');
1625 }
1626 } else {
1627 1 Carp::croak('XML slurp: cannot handle ', ref($xml), ' structure');
1628 }
1629 5 ▶ if($self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 2 3 5
1630 # Not keyed, will need to scan each entry
1631 2 my $i = 0;
1632 2 foreach my $d(@data) {
1633 10 $self->{'data'}->{$i++} = $d;
1634 }
1635 } else {
1636 # keyed on the $self->{'id'} (default: "entry") column
1637 3 foreach my $d(@data) {
1638 11 $self->{'data'}->{$d->{$self->{'id'}}} = $d;
1639 }
1640 }
1641 } else {
1642 3 $dbh = DBI->connect('dbi:XMLSimple(RaiseError=>1):');
1643 0 $dbh->{'RaiseError'} = 1;
1644 0 $self->_debug("read in $table from XML $slurp_file");
1645 0 $dbh->func($table, 'XML', $slurp_file, 'xmlsimple_import');
1646 }
1647 } else {
1648 14 my $json_file = File::Spec->catfile($dir, "$dbname.json");
1649 14 ▶ if(-r $json_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $json_file) { } 9 5 14
1650 9 ▶ if((-s $json_file) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (-s $json_file == 0) { } 1 8 9
1651 1 ▶ $self->{'data'} = $self->{'no_entry'} ? undef : {};
Branch: 1 branch
BranchTrueFalseTotal
$$self{'no_entry'} ? : 0 1 1
1652 } else {
1653 8 require JSON::MaybeXS;
1654  
1655 8 open(my $jfh, '<', $json_file);
1656 8 local $/;
1657 8 my $raw = <$jfh>;
1658 8 close $jfh;
1659 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
1660 # Whitespace-only — treat as empty, same as zero-byte
1661 1 ▶ $self->{'data'} = $self->{'no_entry'} ? undef : {};
Branch: 1 branch
BranchTrueFalseTotal
$$self{'no_entry'} ? : 0 1 1
1662 } else {
1663 7 my $parsed = JSON::MaybeXS::decode_json($raw);
1664 7 my @data;
1665 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
1666 7 @data = @{$parsed};
1667 } elsif(ref($parsed) eq 'HASH') {
1668 # Hash of id => row — inject id column into each row
1669 0 my $id_col = $self->{'id'};
1670 0 for my $k (sort keys %{$parsed}) {
1671 0 my $row = $parsed->{$k};
1672 0 ▶ if(ref($row) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $row eq 'HASH') { } 0 0 0
1673 0 push @data, { $id_col => $k, %{$row} };
1674 } else {
1675 0 push @data, { $id_col => $k, value => $row };
1676 }
1677 }
1678 } else {
1679 0 Carp::croak(ref($self), ": JSON slurp: unexpected top-level structure in $json_file");
1680 }
1681 7 ▶ if($self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 1 6 7
1682 1 ▶ $self->{'data'} = @data ? \@data : undef;
Branch: 1 branch
BranchTrueFalseTotal
@data ? : 1 0 1
1683 } else {
1684 6 $self->{'data'} = { map { $_->{$self->{'id'}} => $_ } @data };
1685 }
1686 }
1687 }
1688 9 $slurp_file = $json_file;
1689 9 $self->_debug("read in $table from JSON $json_file");
1690 9 $self->{'type'} = 'JSON';
1691 } else {
1692 # throw Error(-file => "$dir/$table");
1693 5 $self->_fatal("Can't find a file called '$dbname' for the table $table in $dir");
1694 }
1695 }
1696 14 ▶ $self->{'type'} //= 'XML';
Condition100%2/2
$$self{"type"} //= "XML"
l!l
95
MC/DC100%1/1
$$self{"type"} //= "XML"
$$self{"type"}
Truth table100%2/2
A
A= $$self{"type"}
Aresult
11
00
1697 }
1698 } # end: xlsx else (xml path)
1699 } # end: xls else
1700 }
1701  
1702 # ref() must be called on the variable, not on the result of 'eq'
1703 319 ▶ $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" 226 93 319
Condition100%3/3
$$self{"data"} and ref $$self{"data"} eq "HASH"
!ll&&!rl&&r
7320226
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
1704  
1705 319 $self->{'_dbh'}{$table} = $dbh;
1706 319 my @statb = stat($slurp_file);
1707 319 $self->{'_updated'} = $statb[9];
1708  
1709 319 return $self;
1710 53 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1711  
1712 # Project columns and/or deduplicate an arrayref of row hashrefs.
1713 # $rows - arrayref of hashrefs
1714 # $cols - arrayref of column names to keep, or undef for all columns
1715 # $distinct - true to remove duplicate rows (after projection)
1716 # Returns a new arrayref; input row hashrefs are not modified.
1717 7 ▶sub _apply_distinct {
Subroutine _apply_distinct: called CC=11 SCAR=25.2
1718 7 my ($rows, $cols, $distinct) = @_;
1719 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
1720 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
1721  
1722 7 my (@out, %seen);
1723 7 for my $row (@{$rows}) {
1724 31 my $r;
1725 31 ▶ if(defined $cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cols) { } 31 0 31
1726 # Use exists() guard: fixate() locks all keys in slurp hashrefs;
1727 # accessing a missing key on a locked hash throws an exception.
1728 31 ▶ $r = { map { $_ => (exists($row->{$_}) ? $row->{$_} : undef) } @{$cols} };
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$_} ? : 40 5 45
1729 } else {
1730 0 $r = $row;
1731 }
1732 31 ▶ if($distinct) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distinct) 8 23 31
1733 8 ▶ my $key = join("\x00", map { defined($r->{$_}) ? $r->{$_} : "\x01" } sort keys %{$r});
Branch: 1 branch
BranchTrueFalseTotal
defined $$r{$_} ? : 13 0 13
1734 8 ▶ next if $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$key}++ 2 6 8
1735 }
1736 29 push @out, $r;
1737 }
1738 7 return \@out;
1739 }
1740  
1741 =head2 selectall_arrayref
1742  
1743 Returns a reference to an array of hash references for every row that
1744 matches the given criteria, or C<undef> when there are no matches.
1745  
1746 my $rows = $db->selectall_arrayref(); # all rows
1747 my $rows = $db->selectall_arrayref(status => 'active'); # exact match
1748 my $rows = $db->selectall_arrayref(score => { '>' => 8 }); # operator
1749  
1750 The full criteria syntax is described in L</QUERY CRITERIA>.
1751  
1752 Pass a C<join> key to combine with another table:
1753  
1754 my $rows = $db->selectall_arrayref(
1755 dept_name => 'Engineering',
1756 join => { table => 'dept', on => 'e.dept_id = dept.id' },
1757 );
1758  
1759 Pass C<limit =E<gt> N> and/or C<offset =E<gt> M> for pagination:
1760  
1761 my $page = $db->selectall_arrayref(status => 'active', limit => 10, offset => 20);
1762  
1763 Both values must be non-negative integers; invalid values are ignored with a
1764 C<carp> warning. When C<offset> is given without C<limit> the SQL backend
1765 uses C<LIMIT -1> on SQLite (meaning "no upper bound") so the C<OFFSET> clause
1766 is legal.
1767  
1768 Pass C<sort_by =E<gt> 'col'> (ascending) or C<sort_by =E<gt> ['col', 'DESC']>
1769 to request a specific sort column and direction instead of the default primary-key
1770 ordering:
1771  
1772 my $rows = $db->selectall_arrayref(sort_by => 'name');
1773 my $rows = $db->selectall_arrayref(sort_by => ['score', 'DESC']);
1774  
1775 The column name is validated against the same identifier rules as all other
1776 column parameters. An unsafe name or an unrecognised direction (anything other
1777 than C<ASC> or C<DESC>, case-insensitive) is ignored with a C<carp> warning and
1778 the default sort order is used instead. Sorting is applied before
1779 C<limit>/C<offset> pagination.
1780  
1781 Pass C<distinct =E<gt> 1> to return only unique rows (deduplication):
1782  
1783 my $rows = $db->selectall_arrayref(distinct => 1);
1784 my $rows = $db->selectall_arrayref(distinct => 1, columns => [qw(status dept)]);
1785  
1786 Pass C<columns =E<gt> \@cols> to restrict which columns appear in the returned
1787 rows. Column names are validated against the same identifier rules as other
1788 parameters; invalid names are dropped with a C<carp> warning.
1789  
1790 On SQL-capable backends (SQLite, PostgreSQL, MySQL, DBD::CSV E<ge> 0.64)
1791 C<distinct =E<gt> 1> emits C<SELECT DISTINCT>. On the slurp (in-memory) path
1792 C<distinct> without C<columns> is a no-op because each row is already unique.
1793  
1794 B<Order of operations:> sort E<rarr> offset E<rarr> limit E<rarr> C<_apply_distinct>.
1795 This means C<< limit => N, distinct => 1 >> deduplicates the already-limited
1796 slice, not the full result set. If you need N distinct rows from a larger set,
1797 omit C<limit> and slice the returned arrayref yourself.
1798  
1799 Results are returned in the cache (if configured) and the returned array
1800 reference is made read-only unless C<no_fixate> was set.
1801  
1802 B<Note:> this always returns all matching rows. Use L</selectall_array>
1803 in scalar context, or C<< $db->query->limit(1)->all() >>, to fetch just one row.
1804  
1805 =head3 PSEUDOCODE
1806  
1807 1. Parse criteria; extract and build any JOIN clause.
1808 Extract distinct, columns, limit, offset, sort_by.
1809 2. If data is slurped AND no joins AND criteria are simple:
1810 a. No criteria -> return all rows as arrayref.
1811 b. entry-only lookup -> return [$data{entry}].
1812 c. Otherwise -> scan rows in-memory with _match_criterion.
1813 In all slurp cases: sort by sort_by column (if given), then apply
1814 offset/limit, then _apply_distinct (columns projection + dedup).
1815 3. Otherwise build SQL: SELECT [DISTINCT] [columns|*] FROM table
1816 [JOIN] [WHERE] ORDER BY sort_by [else id] [LIMIT] [OFFSET].
1817 All DBI backends (including DBD::CSV >= 0.64) use native SELECT DISTINCT.
1818 4. Check cache; return cached arrayref on HIT.
1819 5. prepare_cached + execute; fetch all rows.
1820 6. Store result in cache; fixate the array; return arrayref.
1821  
1822 =head3 API SPECIFICATION
1823  
1824 =head4 Arguments
1825  
1826 %criteria # optional key-value pairs or operator hashrefs
1827 join => HashRef | ArrayRef # optional join spec(s)
1828 sort_by => Str | ArrayRef # optional: 'col' or ['col','DESC']
1829 limit => Int # optional: max rows
1830 offset => Int # optional: rows to skip
1831 distinct => Bool # optional: deduplicate rows
1832 columns => ArrayRef[Str] # optional: restrict output columns
1833 no_fixate => Bool # optional: skip read-only locking
1834 table => Str # optional: override table name
1835  
1836 =head4 Returns
1837  
1838 ArrayRef[HashRef] | undef
1839  
1840 An arrayref of row hashrefs on success. Returns C<undef> when no
1841 rows match. Each hashref is read-only unless C<no_fixate> was set.
1842  
1843 =cut
1844  
1845 348 ▶sub selectall_arrayref {
Subroutine selectall_arrayref: called CC=126 SCAR=66.3
Pod documented
1846 348 my $self = shift;
1847  
1848 # Fire _open() first so $self->{'berkeley'} is known before we parse @_.
1849 # BerkeleyDB param parsing must use get_params(undef, \@_) so that
1850 # key-value pairs like (join => {...}) are not mangled by the positional
1851 # 'entry' mapping that non-BerkeleyDB paths use.
1852 348 $self->_open_table({});
1853  
1854 341 my $params;
1855  
1856 341 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 4 337 341
1857 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
1858 4 my $bl = delete $params->{'limit'};
1859 4 my $bo = delete $params->{'offset'};
1860 4 my $bdist = delete $params->{'distinct'};
1861 4 my $bcols = delete $params->{'columns'};
1862 4 my ($bsc, $bsd) = _parse_sort_by(delete($params->{'sort_by'}), 'selectall_arrayref');
1863 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
1864 0 Carp::carp('selectall_arrayref: limit must be a non-negative integer, ignoring');
1865 0 undef $bl;
1866 }
1867 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
1868 0 Carp::carp('selectall_arrayref: offset must be a non-negative integer, ignoring');
1869 0 undef $bo;
1870 }
1871 4 $params = $self->_merge_base_criteria($params);
1872 4 my $rows = $self->_scan_berkeley($params);
1873 4 ▶ if(defined $bsc) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bsc) 0 4 4
1874 0 ▶ if($bsd eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($bsd eq 'DESC') { } 0 0 0
1875 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
1876 } else {
1877 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
1878 }
1879 }
1880 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
1881 0 ▶ splice(@{$rows}, 0, int($bo)) if $bo;
Branch: 1 branch
BranchTrueFalseTotal
if $bo 0 0 0
1882 0 ▶ splice(@{$rows}, int($bl)) if defined $bl;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bl 0 0 0
1883 }
1884 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
1885 4 return set_return($rows, { type => 'arrayref' });
1886 }
1887  
1888 337 ▶ if($self->{'no_entry'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 127 210 337
elsif (scalar @_) { } 109 101 210
1889 127 $params = Params::Get::get_params(undef, \@_);
1890 } elsif(scalar(@_)) {
1891 109 $params = Params::Get::get_params('entry', @_);
1892 }
1893  
1894 337 my $table = $self->_open_table($params);
1895  
1896 334 ▶ $params //= {};
Condition100%2/2
$params //= {}
l!l
203131
MC/DC100%1/1
$params //= {}
$params
Truth table100%2/2
A
A= $params
Aresult
11
00
1897  
1898 334 my $join_clause = '';
1899 334 ▶ if(my $join_spec = delete $params->{'join'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $join_spec = delete $params->{"join"}) 45 289 334
1900 45 $join_clause = $self->_build_joins($join_spec);
1901 }
1902  
1903 310 my $limit = delete $params->{'limit'};
1904 310 my $offset = delete $params->{'offset'};
1905 310 ▶ if(defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 20 290 310
1906 20 ▶ if($limit !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $limit =~ /\A\d+\z/) { } 6 14 20
1907 6 Carp::carp('selectall_arrayref: limit must be a non-negative integer, ignoring');
1908 6 undef $limit;
1909 } else {
1910 14 $limit = int($limit);
1911 }
1912 }
1913 310 ▶ if(defined $offset) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 11 299 310
1914 11 ▶ if($offset !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $offset =~ /\A\d+\z/) { } 2 9 11
1915 2 Carp::carp('selectall_arrayref: offset must be a non-negative integer, ignoring');
1916 2 undef $offset;
1917 } else {
1918 9 $offset = int($offset);
1919 }
1920 }
1921  
1922 310 my ($sort_col, $sort_dir) = _parse_sort_by(delete($params->{'sort_by'}), 'selectall_arrayref');
1923  
1924 310 my $distinct = delete $params->{'distinct'};
1925 310 my $columns = delete $params->{'columns'};
1926 310 ▶ if(defined $columns) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $columns) 14 296 310
1927 14 ▶ if(ref($columns) ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $columns ne 'ARRAY') { } 1 13 14
1928 1 Carp::carp('selectall_arrayref: columns must be an arrayref, ignoring');
1929 1 undef $columns;
1930 } else {
1931 13 my @valid;
1932 13 for my $c (@{$columns}) {
1933 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
1934 16 push @valid, $c;
1935 } else {
1936 2 Carp::carp("selectall_arrayref: unsafe column name '$c', ignoring");
1937 }
1938 }
1939 13 ▶ $columns = @valid ? \@valid : undef;
Branch: 1 branch
BranchTrueFalseTotal
@valid ? : 11 2 13
1940 }
1941 }
1942  
1943 310 $params = $self->_merge_base_criteria($params);
1944  
1945 310 ▶ 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)) 170 140 310
Condition100%6/6
not $join_clause and $$self{"data"} and not $self->_has_complex_criteria($params)
!ll&&!rl&&r
1364170
not $join_clause and $$self{"data"}
!ll&&!rl&&r
20116174
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
1946 170 ▶ if(scalar(keys %{$params}) == 0) {
Branch: 4 branches
BranchTrueFalseTotal
if (scalar keys %{$params;} == 0) { } 122 48 170
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
1947 122 $self->_trace("$table: selectall_arrayref fast track return");
1948 122 my @rc;
1949 122 ▶ if(ref($self->{'data'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $$self{'data'} eq 'HASH') { } 118 4 122
1950 118 $self->_debug("$table: returning ", scalar keys %{$self->{'data'}}, ' entries');
1951 118 ▶ if(scalar keys %{$self->{'data'}} <= 10) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$$self{"data"};} <= 10) 118 0 118
1952 118 $self->_debug(do { require Data::Dumper; Data::Dumper::Dumper($self->{'data'}) });
1953 }
1954 118 @rc = values %{$self->{'data'}};
1955 } else {
1956 4 @rc = @{$self->{'data'}};
1957 }
1958 122 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 7 115 122
1959 7 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 3 4 7
1960 3 ▶ @rc = sort { ($b->{$sort_col} // '') cmp ($a->{$sort_col} // '') } @rc;
Condition75%3/4
$$b{$sort_col} // ""
l!l
130
$$a{$sort_col} // ""
l!l
121
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
MC/DC100%1/1
$$a{$sort_col} // ""
$$a{$sort_col}
Truth table50%1/2
A
A= $$b{$sort_col}
Aresult
11
00
Truth table100%2/2
A
A= $$a{$sort_col}
Aresult
11
00
1961 } else {
1962 4 ▶ @rc = sort { ($a->{$sort_col} // '') cmp ($b->{$sort_col} // '') } @rc;
Condition100%4/4
$$a{$sort_col} // ""
l!l
133
$$b{$sort_col} // ""
l!l
133
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
1963 }
1964 }
1965 122 ▶ if(defined($offset) || defined($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset or defined $limit) 18 104 122
Condition100%3/3
defined $offset or defined $limit
l!l&&r!l&&!r
99104
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
1966 18 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 7 11 18
1967 18 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 14 4 18
1968 }
1969 122 ▶ @rc = @{ _apply_distinct(\@rc, $columns, $columns ? $distinct : undef) }
Branch: 2 branches
BranchTrueFalseTotal
if $columns 6 116 122
$columns ? : 6 0 6
1970 if $columns;
1971 122 return set_return(\@rc, { type => 'arrayref' });
1972 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
1973 # exists() guard: fixate() locks all keys in the slurp hash; return []
1974 # (not [undef]) when the key is missing so callers get an empty result
1975 return set_return([], { type => 'arrayref' })
1976 15 ▶ unless exists($self->{'data'}->{$params->{'entry'}});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$self{"data"}{$$params{"entry"}} 7 8 15
1977 8 my @rc = ($self->{'data'}->{$params->{'entry'}});
1978 8 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 8 8
1979 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
1980 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
1981 } else {
1982 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
1983 }
1984 }
1985 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
1986 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
1987 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
1988 }
1989 0 ▶ @rc = @{ _apply_distinct(\@rc, $columns, $columns ? $distinct : undef) }
Branch: 2 branches
BranchTrueFalseTotal
if $columns 0 8 8
$columns ? : 0 0 0
1990 if $columns;
1991 8 return set_return(\@rc, { type => 'arrayref' });
1992 } elsif(ref($self->{'data'}) eq 'HASH') {
1993 # Scan in-memory hash for simple column criteria without touching DBI.
1994 # fixate() locks hash keys, so use exists() to avoid throwing on unknown columns.
1995 31 $self->_debug("$table: selectall_arrayref in-memory scan with criteria");
1996 # Pre-compute param keys once — avoids re-running keys() inside the inner
1997 # closure on every row iteration (N hash-key extractions → 1).
1998 31 my @param_keys = keys %{$params};
1999 my @rc = grep {
2000 121 my $row = $_;
2001 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
2002 31 } values %{$self->{'data'}};
2003 31 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 31 31
2004 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
2005 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
2006 } else {
2007 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
2008 }
2009 }
2010 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
2011 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2012 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2013 }
2014 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
2015 31 return set_return(\@rc, { type => 'arrayref' });
2016 ▶ } 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
2017 # In-memory scan for array-backed no_entry stores (JSON, XLSX, HTML URL)
2018 # where there is no DBI handle. Mirrors the equivalent path in count().
2019 1 $self->_debug("$table: selectall_arrayref in-memory array scan with criteria");
2020 1 my @param_keys = keys %{$params};
2021 my @rc = grep {
2022 3 my $row = $_;
2023 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
2024 1 } @{$self->{'data'}};
2025 1 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 1 1
2026 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
2027 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
2028 } else {
2029 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
2030 }
2031 }
2032 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
2033 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2034 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2035 }
2036 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
2037 1 return set_return(\@rc, { type => 'arrayref' });
2038 }
2039 }
2040  
2041 # Redis backend: when _open found no data (key doesn't exist or is empty),
2042 # avoid crashing on the DBI path which has no handle for a Redis connection.
2043 return set_return([], { type => 'arrayref' })
2044 141 ▶ if ($self->{'type'} // '') eq 'Redis';
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"type"} // "") eq "Redis" 0 141 141
Condition50%1/2
$$self{"type"} // ""
l!l
1410
MC/DC0%0/1
$$self{"type"} // ""
$$self{"type"}
Truth table50%1/2
A
A= $$self{"type"}
Aresult
11
00
2045  
2046 141 my ($where, $wargs) = $self->_build_where($params);
2047 132 my @query_args = @{$wargs};
2048  
2049 132 my $select_expr;
2050 132 ▶ if($distinct) {
Branch: 2 branches
BranchTrueFalseTotal
if ($distinct) { } 4 128 132
elsif ($columns) { } 1 127 128
2051 4 ▶ if($columns) {
Branch: 1 branch
BranchTrueFalseTotal
if ($columns) { } 3 1 4
2052 3 $select_expr = 'SELECT DISTINCT ' . join(', ', @{$columns});
2053 } else {
2054 1 $select_expr = 'SELECT DISTINCT *';
2055 }
2056 } elsif($columns) {
2057 1 $select_expr = 'SELECT ' . join(', ', @{$columns});
2058 } else {
2059 127 $select_expr = 'SELECT *';
2060 }
2061 132 my $query = "$select_expr FROM $table";
2062 132 ▶ $query .= " $join_clause" if $join_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $join_clause 20 112 132
2063 132 ▶ if($join_clause) {
Branch: 2 branches
BranchTrueFalseTotal
if ($join_clause) { } 20 112 132
elsif ($$self{'type'} eq 'CSV' and not $$self{'no_entry'}) { } 12 100 112
2064 20 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 6 14 20
2065 ▶ } elsif(($self->{'type'} eq 'CSV') && !$self->{'no_entry'}) {
Condition100%3/3
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
!ll&&!rl&&r
881212
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
2066 12 my $id = $self->{'id'};
2067 12 $query .= " WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
2068 12 ▶ $query .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 5 7 12
2069 } else {
2070 100 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 49 51 100
2071 }
2072 132 ▶ if(defined $sort_col) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort_col) { } 0 132 132
elsif (not $$self{'no_entry'}) { } 34 98 132
2073 0 $query .= " ORDER BY $sort_col $sort_dir";
2074 } elsif(!$self->{'no_entry'}) {
2075 34 $query .= ' ORDER BY ' . $self->{'id'};
2076 }
2077 132 ▶ if(defined($limit)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $limit) { } 0 132 132
elsif (defined $offset) { } 0 132 132
2078 0 $query .= ' LIMIT ?';
2079 0 push @query_args, $limit;
2080 } elsif(defined($offset)) {
2081 # SQLite requires a LIMIT clause when OFFSET is present; -1 means no limit
2082 0 my $dbh = $self->{'_dbh'}{$table};
2083 $query .= ' LIMIT -1'
2084 if ($dbh && (($dbh->{Driver}{Name} // '') eq 'SQLite'))
2085 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
2086 }
2087 132 ▶ if(defined($offset)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 0 132 132
2088 0 $query .= ' OFFSET ?';
2089 0 push @query_args, $offset;
2090 }
2091  
2092 132 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 56 76 132
2093 56 $self->_debug("selectall_arrayref $query: ", join(', ', @query_args));
2094 } else {
2095 76 $self->_debug("selectall_arrayref $query");
2096 }
2097  
2098 132 my $key;
2099 my $c;
2100 132 ▶ if($c = $self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c = $$self{'cache'}) { } 17 115 132
2101 17 $key = ref($self) . "::$query array";
2102 17 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) 2 15 17
2103 2 $key .= ' ' . join(', ', @query_args);
2104 }
2105 17 $self->_debug("cache key = '$key'");
2106 17 ▶ if(my $rc = $c->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $c->get($key)) 8 9 17
2107 8 $self->_debug('cache HIT');
2108 8 return $rc; # We stored a ref to the array
2109  
2110 # This use of a temporary variable is to avoid
2111 # "Implicit scalar context for array in return"
2112 # my @rc = @{$rc};
2113 # return @rc;
2114 }
2115 9 $self->_debug('cache MISS');
2116 } else {
2117 115 $self->_debug('cache not used');
2118 }
2119  
2120 124 ▶ if(my $sth = $self->{'_dbh'}{$table}->prepare_cached($query)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sth = $$self{"_dbh"}{$table}->prepare_cached($query)) 123 0 123
2121 123 ▶ $sth->execute(@query_args) || croak("$query: @query_args");
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@query_args) or croak("${query}: @query_args") 118 0 118
2122  
2123 118 my $rc;
2124 118 ▶ while(my $href = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $href = $sth->fetchrow_hashref) 313 118 431
2125 313 push @{$rc}, $href;
2126 }
2127  
2128 118 ▶ $c->set($key, $rc, $self->{'cache_duration'}) if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 9 109 118
2129  
2130 118 ▶ if($rc && !$self->{'no_fixate'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc and not $$self{"no_fixate"}) 104 14 118
Condition100%3/3
$rc and not $$self{"no_fixate"}
!ll&&!rl&&r
131104
MC/DC100%2/2
$rc and not $$self{"no_fixate"}
$rc not $$self{"no_fixate"}
Truth table100%3/3
A and not(B)
A= $rcB= not $$self{"no_fixate"}
ABresult
0X0
100
111
2131 104 $self->_fixate($rc);
2132 }
2133  
2134 118 return $rc;
2135 }
2136 0 $self->_warn("selectall_arrayref failure on $query: @query_args");
2137 0 croak("$query: @query_args");
2138 }
2139  
2140 =head2 selectall_hashref
2141  
2142 Deprecated alias for L</selectall_arrayref>. Use C<selectall_arrayref> in
2143 new code.
2144  
2145 =cut
2146  
2147 sub selectall_hashref
2148 8 ▶{
Subroutine selectall_hashref: called CC=1 SCAR=0.0
Pod documented
2149 8 my $self = shift;
2150 8 return $self->selectall_arrayref(@_);
2151 }
2152  
2153 =head2 each_row
2154  
2155 $db->each_row(\&callback);
2156 $db->each_row(\&callback, status => 'active');
2157 $db->each_row(\&callback, sort_by => 'name', limit => 100, offset => 20);
2158  
2159 Iterates over matching rows one at a time, calling C<\&callback> once per
2160 row with the row hashref as the sole argument. Uses B<constant memory> on
2161 the SQL path: rows are fetched from the database one at a time via
2162 C<fetchrow_hashref> without materialising the full result array. On the
2163 slurp/in-memory path data is already in RAM, so memory use is equivalent to
2164 L</selectall_arrayref>.
2165  
2166 Accepts the same criteria, C<join>, C<sort_by>, C<limit>, and C<offset>
2167 parameters as L</selectall_arrayref>.
2168  
2169 Returns the number of rows passed to C<\&callback>.
2170  
2171 Exceptions raised inside C<\&callback> abort iteration and propagate to
2172 the caller; the DBI statement handle is left in a valid state (C<finish()>
2173 is called on exception).
2174  
2175 B<Note:> rows on the SQL path are not fixated (made read-only) because they
2176 are discarded after each callback invocation. Slurp-path rows are already
2177 fixated from the initial load.
2178  
2179 =head3 API SPECIFICATION
2180  
2181 =head4 Arguments
2182  
2183 CodeRef # required: callback receiving one row hashref per call
2184 %criteria # optional: same criteria syntax as selectall_arrayref
2185 join => HashRef | ArrayRef # optional join spec(s)
2186 sort_by => Str | ArrayRef # optional sort column
2187 limit => Int # optional: max rows to visit
2188 offset => Int # optional: rows to skip
2189  
2190 =head4 Returns
2191  
2192 Int (>= 0)
2193  
2194 The number of rows visited (i.e. the number of times the callback
2195 was called). Any exception thrown inside the callback is re-thrown
2196 after the DBI statement handle is properly finished.
2197  
2198 =cut
2199  
2200 sub each_row
2201 55 ▶{
Subroutine each_row: called CC=73 SCAR=63.7
Pod documented
2202 55 my $self = shift;
2203 55 my $callback = shift;
2204  
2205 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
2206 unless ref($callback) eq 'CODE';
2207  
2208 44 $self->_open_table({});
2209  
2210 44 my $params;
2211  
2212 44 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 0 44 44
2213 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
2214 0 my $bl = delete $params->{'limit'};
2215 0 my $bo = delete $params->{'offset'};
2216 0 my ($bsc, $bsd) = _parse_sort_by(delete($params->{'sort_by'}), 'each_row');
2217 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
2218 0 Carp::carp('each_row: limit must be a non-negative integer, ignoring');
2219 0 undef $bl;
2220 }
2221 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
2222 0 Carp::carp('each_row: offset must be a non-negative integer, ignoring');
2223 0 undef $bo;
2224 }
2225 0 $params = $self->_merge_base_criteria($params);
2226 0 my $rows = $self->_scan_berkeley($params);
2227 0 ▶ if(defined $bsc) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bsc) 0 0 0
2228 0 ▶ if($bsd eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($bsd eq 'DESC') { } 0 0 0
2229 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
2230 } else {
2231 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
2232 }
2233 }
2234 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
2235 0 ▶ splice(@{$rows}, 0, int($bo)) if $bo;
Branch: 1 branch
BranchTrueFalseTotal
if $bo 0 0 0
2236 0 ▶ splice(@{$rows}, int($bl)) if defined $bl;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bl 0 0 0
2237 }
2238 0 my $n = 0;
2239 0 for my $row (@{$rows}) {
2240 0 local $_;
2241 0 $callback->($row);
2242 0 $n++;
2243 }
2244 0 return $n;
2245 }
2246  
2247 44 ▶ if($self->{'no_entry'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 3 41 44
elsif (scalar @_) { } 13 28 41
2248 3 $params = Params::Get::get_params(undef, \@_);
2249 } elsif(scalar(@_)) {
2250 13 $params = Params::Get::get_params('entry', @_);
2251 }
2252  
2253 44 my $table = $self->_open_table($params);
2254  
2255 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
2256  
2257 44 my $join_clause = '';
2258 44 ▶ if(my $join_spec = delete $params->{'join'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $join_spec = delete $params->{"join"}) 0 44 44
2259 0 $join_clause = $self->_build_joins($join_spec);
2260 }
2261  
2262 44 my $limit = delete $params->{'limit'};
2263 44 my $offset = delete $params->{'offset'};
2264 44 ▶ if(defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 3 41 44
2265 3 ▶ if($limit !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $limit =~ /\A\d+\z/) { } 0 3 3
2266 0 Carp::carp('each_row: limit must be a non-negative integer, ignoring');
2267 0 undef $limit;
2268 } else {
2269 3 $limit = int($limit);
2270 }
2271 }
2272 44 ▶ if(defined $offset) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 2 42 44
2273 2 ▶ if($offset !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $offset =~ /\A\d+\z/) { } 0 2 2
2274 0 Carp::carp('each_row: offset must be a non-negative integer, ignoring');
2275 0 undef $offset;
2276 } else {
2277 2 $offset = int($offset);
2278 }
2279 }
2280  
2281 44 my ($sort_col, $sort_dir) = _parse_sort_by(delete($params->{'sort_by'}), 'each_row');
2282 44 $params = $self->_merge_base_criteria($params);
2283  
2284 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
2285 29 my @rc;
2286 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
2287 21 ▶ @rc = ref($self->{'data'}) eq 'HASH' ? values %{$self->{'data'}} : @{$self->{'data'}};
Branch: 1 branch
BranchTrueFalseTotal
ref $$self{'data'} eq 'HASH' ? : 20 1 21
2288 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
2289 5 ▶ return 0 unless exists($self->{'data'}->{$params->{'entry'}});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$self{"data"}{$$params{"entry"}} 2 3 5
2290 3 @rc = ($self->{'data'}->{$params->{'entry'}});
2291 } elsif(ref($self->{'data'}) eq 'HASH') {
2292 3 $self->_debug("$table: each_row in-memory scan with criteria");
2293 3 my @param_keys = keys %{$params};
2294 @rc = grep {
2295 12 my $row = $_;
2296 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
2297 3 } values %{$self->{'data'}};
2298 ▶ } 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
2299 0 $self->_debug("$table: each_row in-memory array scan with criteria");
2300 0 my @param_keys = keys %{$params};
2301 @rc = grep {
2302 0 my $row = $_;
2303 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
2304 0 } @{$self->{'data'}};
2305 }
2306 27 ▶ if(@rc) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rc) 27 0 27
2307 27 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 7 20 27
2308 7 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 2 5 7
2309 2 ▶ @rc = sort { ($b->{$sort_col} // '') cmp ($a->{$sort_col} // '') } @rc;
Condition75%3/4
$$b{$sort_col} // ""
l!l
100
$$a{$sort_col} // ""
l!l
82
MC/DC0%0/1
$$b{$sort_col} // ""
$$b{$sort_col}
MC/DC100%1/1
$$a{$sort_col} // ""
$$a{$sort_col}
Truth table50%1/2
A
A= $$b{$sort_col}
Aresult
11
00
Truth table100%2/2
A
A= $$a{$sort_col}
Aresult
11
00
2310 } else {
2311 5 ▶ @rc = sort { ($a->{$sort_col} // '') cmp ($b->{$sort_col} // '') } @rc;
Condition50%2/4
$$a{$sort_col} // ""
l!l
250
$$b{$sort_col} // ""
l!l
250
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
2312 }
2313 }
2314 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
2315 4 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 2 2 4
2316 4 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 3 1 4
2317 }
2318 }
2319 27 my $n = 0;
2320 27 for my $row (@rc) {
2321 62 local $_;
2322 62 $callback->($row);
2323 54 $n++;
2324 }
2325 19 return $n;
2326 }
2327  
2328 15 my ($where, $wargs) = $self->_build_where($params);
2329 15 my @query_args = @{$wargs};
2330  
2331 15 my $query = "SELECT * FROM $table";
2332 15 ▶ $query .= " $join_clause" if $join_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $join_clause 0 15 15
2333 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
2334 0 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 0 0
2335 ▶ } 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
2336 5 my $id = $self->{'id'};
2337 5 $query .= " WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
2338 5 ▶ $query .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 5 5
2339 } else {
2340 10 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 10 10
2341 }
2342 15 ▶ if(defined $sort_col) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort_col) { } 0 15 15
elsif (not $$self{'no_entry'}) { } 13 2 15
2343 0 $query .= " ORDER BY $sort_col $sort_dir";
2344 } elsif(!$self->{'no_entry'}) {
2345 13 $query .= ' ORDER BY ' . $self->{'id'};
2346 }
2347 15 ▶ if(defined($limit)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $limit) { } 0 15 15
elsif (defined $offset) { } 0 15 15
2348 0 $query .= ' LIMIT ?';
2349 0 push @query_args, $limit;
2350 } elsif(defined($offset)) {
2351 0 my $dbh = $self->{'_dbh'}{$table};
2352 $query .= ' LIMIT -1'
2353 if ($dbh && (($dbh->{Driver}{Name} // '') eq 'SQLite'))
2354 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
2355 }
2356 15 ▶ if(defined($offset)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 0 15 15
2357 0 $query .= ' OFFSET ?';
2358 0 push @query_args, $offset;
2359 }
2360  
2361 15 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 0 15 15
2362 0 $self->_debug("each_row $query: ", join(', ', @query_args));
2363 } else {
2364 15 $self->_debug("each_row $query");
2365 }
2366  
2367 my $sth = $self->{'_dbh'}{$table}->prepare_cached($query)
2368 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
2369 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
2370  
2371 15 my $n = 0;
2372 15 eval {
2373 15 ▶ while(my $row = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 25 9 34
2374 25 local $_;
2375 25 $callback->($row);
2376 19 $n++;
2377 }
2378 };
2379 15 ▶ if(my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 6 9 15
2380 6 $sth->finish();
2381 6 die $err;
2382 }
2383 9 return $n;
2384 }
2385  
2386 =head2 selectall_array
2387  
2388 Similar to L</selectall_arrayref> but returns a list of hash references
2389 rather than a reference to an array.
2390  
2391 my @rows = $db->selectall_array(status => 'active');
2392  
2393 In B<scalar context> it applies C<LIMIT 1> and returns just the first
2394 matching hash reference - making it more efficient than C<selectall_arrayref>
2395 when you only need one row. In B<list context> all matching rows are returned.
2396  
2397 Accepts the same criteria, C<join>, C<limit>, C<offset>, and C<sort_by>
2398 parameters as L</selectall_arrayref>. When C<limit> is given in scalar context
2399 it overrides the implicit C<LIMIT 1>.
2400  
2401 =cut
2402  
2403 sub selectall_array
2404 75 ▶{
Subroutine selectall_array: called CC=104 SCAR=73.8
Pod documented
2405 75 my $self = shift;
2406  
2407 75 $self->_open_table({});
2408  
2409 75 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 3 72 75
2410 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
2411 3 my $bl = delete $params->{'limit'};
2412 3 my $bo = delete $params->{'offset'};
2413 3 my ($bsc, $bsd) = _parse_sort_by(delete($params->{'sort_by'}), 'selectall_array');
2414 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
2415 0 Carp::carp('selectall_array: limit must be a non-negative integer, ignoring');
2416 0 undef $bl;
2417 }
2418 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
2419 0 Carp::carp('selectall_array: offset must be a non-negative integer, ignoring');
2420 0 undef $bo;
2421 }
2422 3 $params = $self->_merge_base_criteria($params);
2423 3 my $rows = $self->_scan_berkeley($params);
2424 3 ▶ if(defined $bsc) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bsc) 0 3 3
2425 0 ▶ if($bsd eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($bsd eq 'DESC') { } 0 0 0
2426 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
2427 } else {
2428 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
2429 }
2430 }
2431 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
2432 0 ▶ splice(@{$rows}, 0, int($bo)) if $bo;
Branch: 1 branch
BranchTrueFalseTotal
if $bo 0 0 0
2433 0 ▶ splice(@{$rows}, int($bl)) if defined $bl;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bl 0 0 0
2434 }
2435 3 ▶ return wantarray ? @{$rows} : $rows->[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 1 3
2436 }
2437  
2438 72 my $params = Params::Get::get_params(undef, \@_);
2439 72 my $table = $self->_open_table($params);
2440  
2441 71 ▶ $params //= {};
Condition100%2/2
$params //= {}
l!l
2546
MC/DC100%1/1
$params //= {}
$params
Truth table100%2/2
A
A= $params
Aresult
11
00
2442 71 my $join_clause = '';
2443 71 ▶ if(my $join_spec = delete $params->{'join'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $join_spec = delete $params->{"join"}) 1 70 71
2444 1 $join_clause = $self->_build_joins($join_spec);
2445 }
2446  
2447 71 my $limit = delete $params->{'limit'};
2448 71 my $offset = delete $params->{'offset'};
2449 71 ▶ if(defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 0 71 71
2450 0 ▶ if($limit !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $limit =~ /\A\d+\z/) { } 0 0 0
2451 0 Carp::carp('selectall_array: limit must be a non-negative integer, ignoring');
2452 0 undef $limit;
2453 } else {
2454 0 $limit = int($limit);
2455 }
2456 }
2457 71 ▶ if(defined $offset) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 0 71 71
2458 0 ▶ if($offset !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $offset =~ /\A\d+\z/) { } 0 0 0
2459 0 Carp::carp('selectall_array: offset must be a non-negative integer, ignoring');
2460 0 undef $offset;
2461 } else {
2462 0 $offset = int($offset);
2463 }
2464 }
2465  
2466 71 my ($sort_col, $sort_dir) = _parse_sort_by(delete($params->{'sort_by'}), 'selectall_array');
2467 71 $params = $self->_merge_base_criteria($params);
2468  
2469 71 ▶ 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 24 71
Condition83%5/6
not $join_clause and $$self{"data"} and not $self->_has_complex_criteria($params)
!ll&&!rl&&r
24047
not $join_clause and $$self{"data"}
!ll&&!rl&&r
12347
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
2470 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
2471 31 $self->_trace("$table: selectall_array fast track return");
2472 my @rc = ref($self->{'data'}) eq 'HASH'
2473 30 ? values %{$self->{'data'}}
2474 31 ▶ : @{$self->{'data'}};
Branch: 1 branch
BranchTrueFalseTotal
ref $$self{'data'} eq 'HASH' ? : 30 1 31
2475 31 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 31 31
2476 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
2477 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
2478 } else {
2479 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
2480 }
2481 }
2482 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
2483 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2484 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2485 }
2486 31 return @rc;
2487 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
2488 # exists() guard: fixate() locks all keys; return empty list (not undef)
2489 # for a missing entry so callers in list context get 0 elements not 1
2490 6 ▶ return () unless exists($self->{'data'}->{$params->{'entry'}});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$self{"data"}{$$params{"entry"}} 3 3 6
2491 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
2492 # limit/offset: build list, splice, then return context-appropriately
2493 0 my @rc = ($self->{'data'}->{$params->{'entry'}});
2494 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2495 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2496 0 ▶ return wantarray ? @rc : $rc[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
2497 }
2498 # Preserve original scalar-context behaviour: return the hashref directly
2499 # (not the count of a 1-element list).
2500 3 return $self->{'data'}->{$params->{'entry'}};
2501 } elsif(ref($self->{'data'}) eq 'HASH') {
2502 # Same as selectall_arrayref scan but returns a list
2503 10 $self->_debug("$table: selectall_array in-memory scan with criteria");
2504 # Pre-compute param keys once — same optimisation as selectall_arrayref:
2505 # avoids N * K hash-key extractions inside the inner closure.
2506 10 my @param_keys = keys %{$params};
2507 my @rc = grep {
2508 36 my $row = $_;
2509 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
2510 10 } values %{$self->{'data'}};
2511 10 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 10 10
2512 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
2513 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
2514 } else {
2515 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
2516 }
2517 }
2518 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
2519 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2520 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2521 }
2522 10 return @rc;
2523 ▶ } 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
2524 # In-memory scan for array-backed no_entry stores (JSON, XLSX, HTML URL)
2525 # where there is no DBI handle. Mirrors the equivalent path in count().
2526 0 $self->_debug("$table: selectall_array in-memory array scan with criteria");
2527 0 my @param_keys = keys %{$params};
2528 my @rc = grep {
2529 0 my $row = $_;
2530 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
2531 0 } @{$self->{'data'}};
2532 0 ▶ if(defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 0 0 0
2533 0 ▶ if($sort_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sort_dir eq 'DESC') { } 0 0 0
2534 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
2535 } else {
2536 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
2537 }
2538 }
2539 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
2540 0 ▶ splice(@rc, 0, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
2541 0 ▶ splice(@rc, $limit) if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
2542 }
2543 0 return @rc;
2544 }
2545 }
2546  
2547 24 my ($where, $wargs) = $self->_build_where($params);
2548 24 my @query_args = @{$wargs};
2549  
2550 24 my $query = "SELECT * FROM $table";
2551 24 ▶ $query .= " $join_clause" if $join_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $join_clause 1 23 24
2552 24 ▶ if($join_clause) {
Branch: 2 branches
BranchTrueFalseTotal
if ($join_clause) { } 1 23 24
elsif ($$self{'type'} eq 'CSV' and not $$self{'no_entry'}) { } 3 20 23
2553 1 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 1 1
2554 ▶ } elsif(($self->{'type'} eq 'CSV') && !$self->{'no_entry'}) {
Condition100%3/3
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
!ll&&!rl&&r
1193
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
2555 3 my $id = $self->{'id'};
2556 3 $query .= " WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
2557 3 ▶ $query .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 1 2 3
2558 } else {
2559 20 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 4 16 20
2560 }
2561 24 ▶ if(defined $sort_col) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort_col) { } 0 24 24
elsif (not $$self{'no_entry'}) { } 11 13 24
2562 0 $query .= " ORDER BY $sort_col $sort_dir";
2563 } elsif(!$self->{'no_entry'}) {
2564 11 $query .= ' ORDER BY ' . $self->{'id'};
2565 }
2566 24 ▶ if(defined($limit)) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $limit) { } 0 24 24
elsif (not wantarray) { } 6 18 24
elsif (defined $offset) { } 0 18 18
2567 0 $query .= ' LIMIT ?';
2568 0 push @query_args, $limit;
2569 0 ▶ if(defined($offset)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 0 0 0
2570 0 $query .= ' OFFSET ?';
2571 0 push @query_args, $offset;
2572 }
2573 } elsif(!wantarray) {
2574 6 ▶ if(defined($offset)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) { } 0 6 6
2575 0 $query .= ' LIMIT 1 OFFSET ?';
2576 0 push @query_args, $offset;
2577 } else {
2578 6 $query .= ' LIMIT 1';
2579 }
2580 } elsif(defined($offset)) {
2581 # List context, offset but no limit — SQLite requires LIMIT with OFFSET
2582 0 my $dbh = $self->{'_dbh'}{$table};
2583 $query .= ' LIMIT -1'
2584 if ($dbh && (($dbh->{Driver}{Name} // '') eq 'SQLite'))
2585 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
2586 0 $query .= ' OFFSET ?';
2587 0 push @query_args, $offset;
2588 }
2589  
2590 24 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 5 19 24
2591 5 $self->_debug("selectall_array $query: ", join(', ', @query_args));
2592 } else {
2593 19 $self->_debug("selectall_array $query");
2594 }
2595  
2596 24 my $key;
2597 my $c;
2598 24 ▶ if($c = $self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c = $$self{'cache'}) { } 9 15 24
2599 9 $key = ref($self) . '::' . $query;
2600 9 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 6 3 9
2601 6 $key .= ' array';
2602 }
2603 9 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) 4 5 9
2604 4 $key .= ' ' . join(', ', @query_args);
2605 }
2606 9 $self->_debug("cache key = '$key'");
2607 9 ▶ if(my $rc = $c->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $c->get($key)) 4 5 9
2608 4 $self->_debug('cache HIT');
2609 4 ▶ return wantarray ? @{$rc} : $rc; # We stored a ref to the array
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 3 1 4
2610  
2611 # This use of a temporary variable is to avoid
2612 # "Implicit scalar context for array in return"
2613 # my @rc = @{$rc};
2614 # return @rc;
2615 }
2616 5 $self->_debug('cache MISS');
2617 } else {
2618 15 $self->_debug('cache not used');
2619 }
2620  
2621 20 ▶ if(my $sth = $self->{'_dbh'}{$table}->prepare_cached($query)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sth = $$self{"_dbh"}{$table}->prepare_cached($query)) 20 0 20
2622 20 ▶ $sth->execute(@query_args) || croak("$query: @query_args");
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@query_args) or croak("${query}: @query_args") 20 0 20
2623  
2624 20 my $rc;
2625 20 ▶ while(my $href = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $href = $sth->fetchrow_hashref) 53 15 68
2626 53 ▶ if(!wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
unless (wantarray) 5 48 53
2627 # Scalar context: return just the first row; cache it too
2628 5 $sth->finish();
2629 5 ▶ $c->set($key, [$href], $self->{'cache_duration'}) if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 2 3 5
2630 5 return $href;
2631 }
2632 48 push @{$rc}, $href;
2633 }
2634 15 ▶ $c->set($key, $rc, $self->{'cache_duration'}) if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 3 12 15
2635  
2636 15 ▶ if($rc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc) 15 0 15
2637 15 ▶ if(!$self->{'no_fixate'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($$self{"no_fixate"}) 15 0 15
2638 15 $self->_fixate($rc);
2639 }
2640 15 return @{$rc};
2641 }
2642 0 return;
2643 }
2644 0 $self->_warn("selectall_array failure on $query: @query_args");
2645 0 croak("$query: @query_args");
2646 }
2647  
2648 =head2 selectall_hash
2649  
2650 Deprecated alias for L</selectall_array>. Use C<selectall_array> in new
2651 code.
2652  
2653 =cut
2654  
2655 sub selectall_hash
2656 11 ▶{
Subroutine selectall_hash: called CC=1 SCAR=0.0
Pod documented
2657 11 my $self = shift;
2658 11 return $self->selectall_array(@_);
2659 }
2660  
2661 =head2 count
2662  
2663 Returns the number of rows matching the given criteria.
2664  
2665 my $total = $db->count();
2666 my $active = $db->count(status => 'active');
2667 my $high = $db->count(score => { '>' => 90 });
2668  
2669 Accepts the full criteria syntax described in L</QUERY CRITERIA>.
2670  
2671 =head3 API SPECIFICATION
2672  
2673 =head4 Arguments
2674  
2675 %criteria # optional: same criteria syntax as selectall_arrayref
2676 join => HashRef | ArrayRef # optional join spec(s)
2677 table => Str # optional: override table name
2678  
2679 =head4 Returns
2680  
2681 Int (>= 0)
2682  
2683 The number of rows that match the given criteria. Returns C<0>
2684 when no rows match -- never C<undef>.
2685  
2686 =cut
2687  
2688 sub count
2689 250 ▶{
Subroutine count: called CC=28 SCAR=33.6
Pod documented
2690 250 my $self = shift;
2691  
2692 250 $self->_open_table({});
2693  
2694 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
2695 213 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 2 211 213
2696 2 $params = $self->_merge_base_criteria($params);
2697 2 return scalar @{$self->_scan_berkeley($params)};
2698 }
2699  
2700 211 my $table = $self->_open_table($params);
2701 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
2702  
2703 210 ▶ if($self->{'data'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"data"}) 145 65 210
2704 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
2705 116 $self->_trace("$table: count fast track return");
2706 116 ▶ if(ref($self->{'data'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $$self{"data"} eq "HASH") 99 17 116
2707 99 return scalar keys %{$self->{'data'}};
2708 }
2709 17 return scalar @{$self->{'data'}};
2710 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
2711 # exists() guard: fixate() locks all keys in the slurp hash
2712 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
2713 ▶ } 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
2714 # General in-memory scan for simple column criteria.
2715 # Only taken when there is no DBI handle ($self->{'_dbh'}{$table} is undef),
2716 # i.e. slurp-only backends like Deep. CSV/XML/SQLite have a DBI handle
2717 # and must fall through to the SQL path so that column-name validation
2718 # fires in _build_where_conditions.
2719 3 $self->_debug("$table: count in-memory scan");
2720 3 my @param_keys = keys %{$params};
2721 # Pass the row list directly to grep — avoids materialising an
2722 # intermediate @rows array of N references on the stack.
2723 return scalar grep {
2724 9 my $row = $_;
2725 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
2726 0 ▶ } (ref($self->{'data'}) eq 'HASH' ? values %{$self->{'data'}} : @{$self->{'data'}});
Branch: 1 branch
BranchTrueFalseTotal
ref $$self{'data'} eq 'HASH' ? : 3 0 3
2727 }
2728 }
2729  
2730 81 my ($where, $wargs) = $self->_build_where($params);
2731 77 my @query_args = @{$wargs};
2732  
2733 77 my $query;
2734 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
2735 24 my $id = $self->{'id'};
2736 24 $query = "SELECT COUNT(*) FROM $table WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
2737 24 ▶ $query .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 13 11 24
2738 } elsif($self->{'no_entry'}) {
2739 36 $query = "SELECT COUNT(*) FROM $table";
2740 36 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 12 24 36
2741 } else {
2742 17 $query = "SELECT COUNT(" . $self->{'id'} . ") FROM $table";
2743 17 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 17 17
2744 }
2745  
2746 77 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 23 54 77
2747 23 $self->_debug("count $query: ", join(', ', @query_args));
2748 } else {
2749 54 $self->_debug("count $query");
2750 }
2751  
2752 77 my $key;
2753 my $c;
2754 77 ▶ if($c = $self->{'cache'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c = $$self{'cache'}) { } 7 70 77
2755 # Opportunistic: if a selectall_arrayref for the same criteria is already
2756 # in cache, derive the count from that array rather than hitting the DB.
2757 # The key is built to match what selectall_arrayref would store.
2758 7 $key = ref($self) . '::' . $query;
2759 # [^)]+ is a negated character class: O(n) with zero backtracking.
2760 # The former lazy .+? could scan past the first ) in pathological SQL;
2761 # [^)]+ is also semantically correct (COUNT(expr) never contains ) ).
2762 7 $key =~ s/COUNT\(([^)]+)\)/$1/;
2763 7 $key .= ' array';
2764 7 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) 3 4 7
2765 3 $key .= ' ' . join(', ', @query_args);
2766 }
2767 7 ▶ if(my $rc = $c->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $c->get($key)) 2 5 7
2768 2 $self->_debug('count: cache HIT (selectall array)');
2769 2 ▶ return ref($rc) eq 'ARRAY' ? scalar @{$rc} : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $rc eq 'ARRAY' ? : 2 0 2
2770 }
2771 5 $self->_debug('count: cache MISS');
2772 } else {
2773 70 $self->_debug('cache not used');
2774 }
2775  
2776 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
2777 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
2778  
2779 74 my $count = $sth->fetchrow_arrayref()->[0];
2780 74 $sth->finish();
2781  
2782 74 return $count;
2783 }
2784 0 $self->_warn("count failure on $query: @query_args");
2785 0 croak("$query: @query_args");
2786 }
2787  
2788 =head2 fetchrow_hashref
2789  
2790 Returns a hash reference for the first row matching the given criteria,
2791 or C<undef> when there is no match. Always applies C<LIMIT 1>.
2792  
2793 my $row = $db->fetchrow_hashref(entry => 'key1');
2794 my $row = $db->fetchrow_hashref(score => { '>=' => 10 });
2795  
2796 When C<no_entry> is B<not> set you may pass a single bare value and it is
2797 used as the C<entry> key:
2798  
2799 my $row = $db->fetchrow_hashref('key1'); # same as entry => 'key1'
2800  
2801 Accepts the full criteria syntax described in L</QUERY CRITERIA>, including
2802 the C<join> parameter:
2803  
2804 my $row = $db->fetchrow_hashref(
2805 name => 'Alice',
2806 join => { table => 'dept', on => 'e.dept_id = dept.id' },
2807 );
2808  
2809 Pass C<< table => $other_table >> to query a table other than the one
2810 derived from the class name.
2811  
2812 =head3 API SPECIFICATION
2813  
2814 =head4 Arguments
2815  
2816 entry => Str # primary-key value to look up (positional first
2817 # arg when no_entry is false)
2818 %criteria # optional additional column filters
2819 join => HashRef | ArrayRef # optional join spec(s)
2820 no_fixate => Bool # optional: skip read-only locking
2821 table => Str # optional: override table name
2822  
2823 =head4 Returns
2824  
2825 HashRef | undef
2826  
2827 A single row hashref when exactly one matching row is found. Returns
2828 C<undef> when the key is not found or no row matches the criteria.
2829 The hashref is read-only unless C<no_fixate> was set.
2830  
2831 B<Note:> C<fetchrow_hashref> does B<not> croak when multiple rows
2832 match the given criteria; it returns whichever row the backend
2833 delivers first (usually the first row in file/insertion order).
2834  
2835 =cut
2836  
2837 126 ▶sub fetchrow_hashref {
Subroutine fetchrow_hashref: called CC=41 SCAR=46.3
Pod documented
2838 126 my $self = shift;
2839  
2840 126 $self->_trace('Entering fetchrow_hashref');
2841  
2842 126 my $params;
2843  
2844 126 ▶ if(!$self->{'no_entry'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $$self{'no_entry'}) { } 114 12 126
2845 114 $params = Params::Get::get_params('entry', @_);
2846 } else {
2847 12 $params = Params::Get::get_params(undef, @_);
2848 }
2849  
2850 126 my $table = $self->_open_table($params);
2851  
2852 122 ▶ 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 34 122
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
34088
$$self{"data"} and not $$self{"no_entry"} and scalar keys %{$params;} == 1 and defined $$params{"entry"}
!ll&&!rl&&r
28688
$$self{"data"} and not $$self{"no_entry"} and scalar keys %{$params;} == 1
!ll&&!rl&&r
27194
$$self{"data"} and not $$self{"no_entry"}
!ll&&!rl&&r
27095
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
2853 88 $self->_debug('Fast return from slurped data');
2854 # Use exists(), fixate() locks the outer hash; accessing a missing key throws
2855 88 ▶ return undef unless exists($self->{'data'}->{$params->{'entry'}});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$self{"data"}{$$params{"entry"}} 17 71 88
2856 71 my $row = $self->{'data'}->{$params->{'entry'}};
2857 71 ▶ if(my $bc = $self->{'base_criteria'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bc = $$self{"base_criteria"}) 4 67 71
2858 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
2859 }
2860 69 return $row;
2861 }
2862  
2863 34 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 0 34 34
2864 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
2865 0 return { entry => $self->{'berkeley'}->{$params->{'entry'}} };
2866 }
2867 0 my $id = $self->{'id'};
2868 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
2869 0 ▶ if(my $rc = $self->{'berkeley'}->{$params->{$id}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $$self{"berkeley"}{$$params{$id}}) 0 0 0
2870 0 return { $params->{$id} => $rc } # Return key->value as a hash pair
2871 }
2872 0 return;
2873 }
2874 0 Carp::croak(ref($self), ': fetchrow_hashref is meaningless on a NoSQL database');
2875 }
2876  
2877 34 my $raw_target = delete $params->{'table'};
2878 34 ▶ if(defined $raw_target) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $raw_target) 0 34 34
2879 0 $raw_target =~ s/\A.*:://;
2880 0 ▶ Carp::croak(ref($self), ": unsafe table name '$raw_target'")
Branch: 1 branch
BranchTrueFalseTotal
unless $raw_target =~ /$SAFE_QUALIFIED/ 0 0 0
2881 unless $raw_target =~ $SAFE_QUALIFIED;
2882 }
2883 34 ▶ my $target = $raw_target // $table;
Condition33%1/3
$raw_target // $table
l!l&&r!l&&!r
0340
MC/DC0%0/2
$raw_target // $table
$raw_target $table
Truth table33%1/3
A // B
A= $raw_targetB= $table
ABresult
1X1
011
000
2884 34 my $join_spec = delete $params->{'join'};
2885 34 $params = $self->_merge_base_criteria($params);
2886 34 ▶ my $join_clause = $join_spec ? $self->_build_joins($join_spec) : '';
Branch: 1 branch
BranchTrueFalseTotal
$join_spec ? : 1 33 34
2887 34 my ($where, $wargs) = $self->_build_where($params);
2888 32 my @query_args = @{$wargs};
2889  
2890 32 my $query = "SELECT * FROM $target";
2891 32 ▶ $query .= " $join_clause" if $join_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $join_clause 1 31 32
2892 32 ▶ if($join_clause) {
Branch: 2 branches
BranchTrueFalseTotal
if ($join_clause) { } 1 31 32
elsif ($$self{'type'} eq 'CSV' and not $$self{'no_entry'}) { } 7 24 31
2893 1 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 1 0 1
2894 ▶ } elsif(($self->{'type'} eq 'CSV') && !$self->{'no_entry'}) {
Condition100%3/3
$$self{"type"} eq "CSV" and not $$self{"no_entry"}
!ll&&!rl&&r
2317
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
2895 7 my $id = $self->{'id'};
2896 7 $query .= " WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
2897 7 ▶ $query .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 7 0 7
2898 } else {
2899 24 ▶ $query .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 24 0 24
2900 }
2901 32 $query .= ' LIMIT 1';
2902 32 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 31 1 32
2903 31 my @call_details = caller(0);
2904 31 $self->_debug("fetchrow_hashref $query: ", join(', ', @query_args),
2905 ' called from ', $call_details[2], ' of ', $call_details[1]);
2906 } else {
2907 1 $self->_debug("fetchrow_hashref $query");
2908 }
2909 # Premise: $key is only needed when a cache is configured.
2910 # Conclusion: assemble it lazily inside the cache block — no dead store on
2911 # the common (no-cache) path.
2912 32 my $c = $self->{'cache'};
2913 32 my $key; # declared here so the second if($c) block (cache SET) can see it
2914 32 ▶ if($c) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c) 7 25 32
2915 7 $key = ref($self) . '::';
2916 7 ▶ if(defined($query_args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_args[0]) { } 7 0 7
2917 7 ▶ $key .= 'array ' if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 1 6 7
2918 7 $key .= "fetchrow $query " . join(', ', @query_args);
2919 } else {
2920 0 $key .= "fetchrow $query";
2921 }
2922 7 ▶ if(my $rc = $c->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $c->get($key)) 3 4 7
2923 3 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 3 3
2924 0 ▶ if(ref($rc) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rc eq "ARRAY") 0 0 0
2925 0 return @{$rc}; # We stored a ref to the array
2926 }
2927 } else {
2928 3 return $rc;
2929 }
2930 }
2931 }
2932  
2933 my $sth = $self->{'_dbh'}{$table}->prepare_cached($query)
2934 29 ▶ 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) 29 0 29
2935 29 ▶ $sth->execute(@query_args) || croak("$query: @query_args");
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@query_args) or croak("${query}: @query_args") 29 0 29
2936 29 my $rc = $sth->fetchrow_hashref();
2937 29 $sth->finish();
2938 29 ▶ if($c) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c) 4 25 29
2939 4 ▶ if($rc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc) { } 4 0 4
2940 4 $self->_debug("stash $key=>$rc in the cache for ", $self->{'cache_duration'});
2941 4 $self->_debug("returns ", do { require Data::Dumper; Data::Dumper->new([$rc])->Dump() });
2942 } else {
2943 0 $self->_debug("Stash $key=>undef in the cache for ", $self->{'cache_duration'});
2944 }
2945 4 $c->set($key, $rc, $self->{'cache_duration'});
2946 }
2947 29 return $rc;
2948 }
2949  
2950 =head2 execute
2951  
2952 Execute a raw SQL query on the underlying database.
2953  
2954 # Scalar context: returns the first row as a hashref
2955 my $row = $db->execute(query => 'SELECT * FROM foo WHERE id = 1');
2956  
2957 # List context: returns all rows as a list of hashrefs
2958 my @rows = $db->execute(query => 'SELECT * FROM foo WHERE score > ?',
2959 args => [80]);
2960  
2961 The C<FROM E<lt>tableE<gt>> clause is appended automatically if omitted.
2962  
2963 On CSV tables without C<no_entry> it may help to add
2964 C<WHERE entry IS NOT NULL AND entry NOT LIKE '#%'> to filter comment rows.
2965  
2966 If the data have been slurped into memory this method still hits the actual
2967 database file directly.
2968  
2969 C<args> is an arrayref of bind values (see L<DBI/execute>).
2970  
2971 =cut
2972  
2973 sub execute
2974 18 ▶{
Subroutine execute: called CC=10 SCAR=23.1
Pod documented
2975 18 my $self = shift;
2976  
2977 18 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 1 17 18
2978 1 Carp::croak(ref($self), ': execute is meaningless on a NoSQL database');
2979 }
2980  
2981 17 my $args = Params::Get::get_params('query', @_);
2982  
2983 # Ensure the 'query' parameter is provided
2984 Carp::croak(__PACKAGE__, ': Usage: execute(query => $query)')
2985 15 ▶ unless defined $args->{'query'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$args{"query"} 0 15 15
2986  
2987 15 my $table = $self->_open_table($args);
2988  
2989 15 my $query = $args->{'query'};
2990  
2991 # Append "FROM <table>" if missing
2992 # \bFROM\b catches the keyword at any word boundary (space, tab, newline),
2993 # unlike the former \sFROM\s which missed forms like "col\tFROM" or leading FROM.
2994 15 ▶ $query .= " FROM $table" unless $query =~ /\bFROM\b/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $query =~ /\bFROM\b/i 0 15 15
2995  
2996 # Log the query if a logger is available
2997 15 $self->_debug("execute $query");
2998  
2999 # Prepare and execute the query
3000 15 my $sth = $self->{'_dbh'}{$table}->prepare_cached($query);
3001 # DBI->execute() takes a list; normalise args to an array whether it
3002 # was passed as an arrayref ([30]) or a bare scalar/list (30).
3003 15 ▶ if(exists($args->{'args'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args->{'args'}) { } 9 6 15
3004 9 ▶ my @bind = ref($args->{'args'}) eq 'ARRAY' ? @{$args->{'args'}} : ($args->{'args'});
Branch: 1 branch
BranchTrueFalseTotal
ref $$args{'args'} eq 'ARRAY' ? : 5 4 9
3005 9 ▶ $sth->execute(@bind) or croak("$query: ", join(', ', @bind));
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@bind) or croak("${query}: ", join(", ", @bind)) 9 0 9
3006 } else {
3007 6 ▶ $sth->execute() or croak($query);
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute or croak($query) 6 0 6
3008 }
3009  
3010 # Fetch the results
3011 15 my @results;
3012 15 ▶ while (my $row = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 31 12 43
3013 31 ▶ unless(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
unless (wantarray) 3 28 31
3014 3 $sth->finish();
3015 3 return $row;
3016 }
3017 28 push @results, $row;
3018 }
3019  
3020 # Return all rows as an array in list context
3021 12 return @results;
3022 }
3023  
3024 =head2 updated
3025  
3026 Returns the Unix timestamp of the last database update.
3027  
3028 For file-based backends (CSV, XML, SQLite via C<directory>), this is the
3029 mtime of the backing file, set at C<new()> time.
3030  
3031 For SQLite DSN connections (C<dbi:SQLite:dbname=...>), the file path is
3032 extracted from the DSN and C<stat()>-ed live on every call, so callers
3033 get a current mtime suitable for cache-invalidation even when the database
3034 was opened via a DSN rather than a C<directory>.
3035  
3036 For all other DSN-based connections (PostgreSQL, MySQL, etc.) and for
3037 URL-based backends, returns the Unix timestamp of the most recent
3038 C<new()> call (connection time).
3039  
3040 =cut
3041  
3042 9 ▶sub updated {
Subroutine updated: called CC=6 SCAR=18.5
Pod documented
3043 9 my $self = shift;
3044  
3045 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
3046 5 my $dsn = $self->{'dsn'};
3047 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
3048 5 my $path = $1;
3049 5 my @st = stat($path);
3050 5 ▶ return $st[9] if @st;
Branch: 1 branch
BranchTrueFalseTotal
if @st 5 0 5
3051 }
3052 }
3053  
3054 4 return $self->{'_updated'};
3055 }
3056  
3057 =head2 columns
3058  
3059 Returns an array reference of column names for the current table.
3060  
3061 my $cols = $db->columns(); # e.g. ['entry', 'name', 'score', 'status']
3062  
3063 Column names are always returned in alphabetical (lexicographic) order,
3064 regardless of backend. This makes the result stable and portable when the
3065 same logical table is backed by different engines (CSV => SQLite, etc.).
3066  
3067 The source of column names varies by backend:
3068  
3069 =over 4
3070  
3071 =item * B<Slurp mode> - keys of the first row in memory.
3072  
3073 =item * B<SQLite / other DBI> - a zero-row C<SELECT *> exposes the driver's
3074 C<NAME> attribute.
3075  
3076 =item * B<BerkeleyDB> - always returns C<['entry', 'value']>.
3077  
3078 =back
3079  
3080 The result is cached inside the object after the first call.
3081  
3082 =head3 API SPECIFICATION
3083  
3084 =head4 Arguments
3085  
3086 None beyond the implicit invocant. The result is cached in the
3087 object after the first call.
3088  
3089 =head4 Returns
3090  
3091 ArrayRef[Str]
3092  
3093 A sorted (lexicographic, ascending) arrayref of column names. The
3094 sort order is identical across all backends, so switching from CSV
3095 to SQLite does not change the returned order.
3096  
3097 =cut
3098  
3099 34 ▶sub columns {
Subroutine columns: called CC=8 SCAR=20.9
Pod documented
3100 34 my $self = shift;
3101  
3102 34 ▶ return $self->{'_columns'} if $self->{'_columns'};
Branch: 1 branch
BranchTrueFalseTotal
if $$self{"_columns"} 6 28 34
3103  
3104 28 my $table = $self->_open_table({});
3105  
3106 27 my @cols;
3107  
3108 27 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 1 26 27
3109 1 return $self->{'_columns'} = ['entry', 'value'];
3110 }
3111  
3112 26 ▶ if(my $data = $self->{'data'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $data = $$self{'data'}) { } 14 12 26
3113 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
3114 10 my ($first) = values %{$data};
3115 10 ▶ @cols = sort keys %{$first} if $first;
Branch: 1 branch
BranchTrueFalseTotal
if $first 10 0 10
3116 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
3117 4 @cols = sort keys %{$data->[0]};
3118 }
3119 } else {
3120 12 my $sth = $self->{'_dbh'}{$table}->prepare_cached("SELECT * FROM $table WHERE 1=0");
3121 12 $sth->execute();
3122 12 @cols = sort @{$sth->{NAME}};
3123 12 $sth->finish();
3124 }
3125  
3126 26 return $self->{'_columns'} = \@cols;
3127 }
3128  
3129 =head2 schema
3130  
3131 Returns a hash reference describing the schema of the current table.
3132 Each key is a column name; each value is a hash reference with these keys:
3133  
3134 =over 4
3135  
3136 =item * C<type> - data type string (e.g. C<TEXT>, C<INTEGER>, C<REAL>)
3137  
3138 =item * C<nullable> - C<1> if the column may be NULL, C<0> if NOT NULL
3139  
3140 =item * C<default> - default value string, or C<undef>
3141  
3142 =item * C<pk> - C<1> if this column is (part of) the primary key, C<0> otherwise
3143  
3144 =back
3145  
3146 my $schema = $db->schema();
3147  
3148 for my $col (sort keys %{$schema}) {
3149 my $info = $schema->{$col};
3150 printf "%s %s %s\n",
3151 $col,
3152 $info->{type},
3153 $info->{nullable} ? 'NULL' : 'NOT NULL';
3154 }
3155  
3156 The schema is determined by the backend:
3157  
3158 =over 4
3159  
3160 =item * B<SQLite> - C<PRAGMA table_info(table)>
3161  
3162 =item * B<Other DBI drivers> - C<< $dbh->column_info(...) >>
3163  
3164 =item * B<Slurp mode> - inferred from the first row; all columns typed as
3165 C<TEXT> by default. When C<< infer_types => 1 >> was passed to the
3166 constructor, up to 100 rows are scanned per column and the type is
3167 promoted: all-integer values => C<INTEGER>; all-float values =>
3168 C<REAL>; all ISO-8601 timestamps (C<YYYY-MM-DDThh:mm>) => C<TIMESTAMP>;
3169 all ISO-8601 dates (C<YYYY-MM-DD>) => C<DATE>; otherwise C<TEXT>.
3170 C<undef> and empty-string values are treated as SQL C<NULL> and skipped
3171 during the scan.
3172  
3173 =item * B<BerkeleyDB> - always returns C<entry> (pk) and C<value>
3174  
3175 =back
3176  
3177 The result is cached inside the object after the first call.
3178  
3179 =head3 API SPECIFICATION
3180  
3181 =head4 Arguments
3182  
3183 infer_types => Bool # enable heuristic type inference for slurp backends
3184 # (may also be set at construction time)
3185  
3186 =head4 Returns
3187  
3188 HashRef[Str => HashRef]
3189  
3190 A hashref keyed by column name. Each value is a hashref with:
3191  
3192 type => Str # 'TEXT', 'INTEGER', 'REAL', 'TIMESTAMP', 'DATE'
3193 nullable => Bool # 1 if the column may be NULL, 0 if NOT NULL
3194 default => Str | undef # default value, or undef
3195 pk => Bool # 1 if (part of) the primary key
3196  
3197 For slurp-mode backends all columns default to type C<TEXT> unless
3198 C<infer_types> is set. The result is cached in the object after the
3199 first call.
3200  
3201 =cut
3202  
3203 29 ▶sub schema {
Subroutine schema: called CC=24 SCAR=33.9
Pod documented
3204 29 my $self = shift;
3205  
3206 29 ▶ return $self->{'_schema'} if $self->{'_schema'};
Branch: 1 branch
BranchTrueFalseTotal
if $$self{"_schema"} 8 21 29
3207  
3208 21 my $table = $self->_open_table({});
3209 21 my %schema;
3210  
3211 21 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 1 20 21
3212 1 return $self->{'_schema'} = {
3213 entry => { type => 'TEXT', nullable => 0, default => undef, pk => 1 },
3214 value => { type => 'TEXT', nullable => 1, default => undef, pk => 0 },
3215 };
3216 }
3217  
3218 20 ▶ if(my $data = $self->{'data'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $data = $$self{'data'}) { } 16 4 20
3219 16 my $first;
3220 my @sample;
3221 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
3222 10 ($first) = values %{$data};
3223 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
3224 2 my $n = 0;
3225 2 for my $row (values %{$data}) {
3226 6 push @sample, $row;
3227 6 ▶ last if ++$n >= INFER_TYPE_SAMPLE_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
if ++$n >= 100 0 6 6
3228 }
3229 }
3230 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
3231 6 $first = $data->[0];
3232 6 ▶ if($self->{'infer_types'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"infer_types"}) 1 5 6
3233 1 ▶ my $last = $#{$data} < INFER_TYPE_SAMPLE_SIZE - 1 ? $#{$data} : INFER_TYPE_SAMPLE_SIZE - 1;
Branch: 1 branch
BranchTrueFalseTotal
$#{$data;} < 99 ? : 1 0 1
3234 1 @sample = @{$data}[0 .. $last];
3235 }
3236 }
3237 16 ▶ if($first) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first) 16 0 16
3238 16 my $id = $self->{'id'};
3239 16 for my $col (keys %{$first}) {
3240 my $type = @sample
3241 43 ▶ ? _infer_type([map { exists($_->{$col}) ? $_->{$col} : undef } @sample])
Branch: 2 branches
BranchTrueFalseTotal
@sample ? : 12 31 43
exists $_->{$col} ? : 36 0 36
3242 : 'TEXT';
3243 43 ▶ $schema{$col} = {
Branch: 2 branches
BranchTrueFalseTotal
$col eq $id ? : 16 27 43
$col eq $id ? : 16 27 43
3244 type => $type,
3245 nullable => ($col eq $id ? 0 : 1),
3246 default => undef,
3247 pk => ($col eq $id ? 1 : 0),
3248 };
3249 }
3250 }
3251 } else {
3252 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
3253 4 ▶ if($driver eq 'SQLite') {
Branch: 1 branch
BranchTrueFalseTotal
if ($driver eq 'SQLite') { } 4 0 4
3254 4 my $sth = $self->{'_dbh'}{$table}->prepare_cached("PRAGMA table_info($table)");
3255 4 $sth->execute();
3256 4 ▶ while(my $row = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 11 4 15
3257 $schema{$row->{'name'}} = {
3258 type => $row->{'type'},
3259 nullable => !$row->{'notnull'},
3260 default => $row->{'dflt_value'},
3261 11 pk => $row->{'pk'},
3262 };
3263 }
3264 4 $sth->finish();
3265 } else {
3266 0 my $sth = $self->{'_dbh'}{$table}->column_info(undef, undef, $table, '%');
3267 0 ▶ if($sth) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth) 0 0 0
3268 0 ▶ while(my $row = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 0 0 0
3269 $schema{$row->{'COLUMN_NAME'}} = {
3270 type => $row->{'TYPE_NAME'},
3271 nullable => $row->{'NULLABLE'},
3272 0 default => $row->{'COLUMN_DEF'},
3273 pk => 0,
3274 };
3275 }
3276 0 $sth->finish();
3277 }
3278 }
3279 }
3280  
3281 20 return $self->{'_schema'} = \%schema;
3282 }
3283  
3284 =head2 dbi_source
3285  
3286 Returns a hashref C<{ dbh =E<gt> $dbh, table =E<gt> $name }> when the backend
3287 is a live SQLite connection, or C<undef> for every other backend (slurp-mode
3288 CSV, JSON, XLSX, HTML URL, DBM::Deep, BerkeleyDB, PostgreSQL, MySQL, ...).
3289  
3290 The hashref is consumed by C<Database::Join> to perform a zero-copy
3291 C<ATTACH DATABASE> so rows never pass through Perl.
3292 Nested C<Database::Join> objects that are themselves SQLite-backed expose themselves
3293 as attachable sources to parent joins through the same interface.
3294  
3295 Subclasses may override this method to expose non-SQLite DBI connections
3296 if their join layer supports them.
3297  
3298 =head3 API SPECIFICATION
3299  
3300 =head4 Arguments
3301  
3302 None beyond the implicit invocant.
3303  
3304 =head4 Returns
3305  
3306 A hashref C<{ dbh =E<gt> DBI::db, table =E<gt> Str }> on a SQLite-backed
3307 instance, or C<undef> on all other backends.
3308  
3309 =cut
3310  
3311 sub dbi_source
3312 2 ▶{
Subroutine dbi_source: called CC=5 SCAR=17.0
Pod documented
3313 2 my $self = shift;
3314  
3315 2 my $table = $self->_open_table({});
3316 2 my $dbh = $self->{'_dbh'}{$table};
3317  
3318 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
3319  
3320 1 return { dbh => $dbh, table => $table };
3321 }
3322  
3323 =head2 aggregate
3324  
3325 Groups matching rows and computes aggregate measures over each group.
3326 Pushes C<GROUP BY> SQL to the backend when a DBI handle is available;
3327 otherwise folds rows in Perl (BerkeleyDB, DBM::Deep, XLSX, JSON, HTML, Redis).
3328  
3329 my $rows = $db->aggregate(
3330 by => ['region', 'month'],
3331 measures => [
3332 { col => 'amount', fn => 'sum', as => 'revenue' },
3333 { fn => 'count', as => 'orders' },
3334 ],
3335 status => 'active',
3336 );
3337  
3338 # Grand total (no 'by')
3339 my $row = $db->aggregate(
3340 measures => [{ col => 'score', fn => 'avg', as => 'mean_score' }],
3341 )->[0];
3342  
3343 Reserved parameter keys (extracted before the rest is treated as WHERE criteria):
3344 C<by>, C<measures>, C<having>, C<sort_by>, C<limit>, C<offset>, C<table>, C<join>.
3345  
3346 Always returns an B<arrayref of hashrefs> (never C<undef>); returns C<[]> when
3347 no group qualifies. Row keys are the C<by> column names (in declaration order)
3348 followed by the measure aliases.
3349  
3350 =head3 Measure specification
3351  
3352 Each measure hashref:
3353  
3354 { col => 'amount', fn => 'sum', as => 'revenue' }
3355 { fn => 'count', as => 'orders' } # COUNT(*)
3356 { col => 'amount', fn => 'count', as => 'paid' } # COUNT(col)
3357 { col => 'customer', fn => 'count_distinct', as => 'customers' }
3358  
3359 C<fn> must be one of C<sum>, C<avg>, C<min>, C<max>, C<count>, C<count_distinct>,
3360 C<median>, C<stddev> (case-insensitive). C<col> is required for every function
3361 except plain C<count>. C<as> (the result key) must be a valid SQL identifier
3362 and must not duplicate another alias or a C<by> column name.
3363  
3364 C<median> computes the median (middle value of sorted values; average of two
3365 middle values for even count). C<stddev> computes the sample standard deviation
3366 (using N-1 denominator). Both are computed in Perl (no SQL pushdown); on SQL
3367 backends the full result set is fetched first and then folded in memory.
3368  
3369 Empty-set normalisation: C<median> and C<stddev> become C<undef> when no rows
3370 are present; C<stddev> on a single-row group returns C<0>.
3371  
3372 =head3 HAVING
3373  
3374 Pass C<< having => { alias_or_by_col => criterion } >> to filter groups
3375 after aggregation. Accepts the full criteria syntax.
3376  
3377 having => { revenue => { '>' => 1000 } }
3378  
3379 =head3 PSEUDOCODE
3380  
3381 1. _open_table; croak if JOIN requested on no-DBI backend.
3382 2. _validate_aggregate_spec: extract/validate by/measures/having/
3383 sort_by/limit/offset; remainder of params is WHERE criteria.
3384 3. Merge base_criteria.
3385 4. SQL path (DBI handle): _build_aggregate_sql; prepare_cached+execute;
3386 normalise empty-set values; cache; fixate; return.
3387 5. Perl fold: selectall_arrayref(criteria); _fold_aggregate;
3388 HAVING via _match_criteria; sort; offset; limit; fixate; return.
3389  
3390 =head3 Backend notes
3391  
3392 On slurp-only backends all matching rows are materialised before folding.
3393 Use a SQL backend (SQLite DSN, PostgreSQL, MySQL) for large datasets.
3394  
3395 =head3 API SPECIFICATION
3396  
3397 =head4 Arguments
3398  
3399 by => ArrayRef[Str] # optional: GROUP BY column names
3400 measures => ArrayRef[HashRef] # required: one or more measure specs
3401 having => HashRef # optional: post-group filter criteria
3402 sort_by => Str | ArrayRef # optional: sort column (Str) or [col,dir]
3403 limit => Int # optional: max rows to return
3404 offset => Int # optional: rows to skip before returning
3405 join => HashRef | ArrayRef # optional: join spec(s) -- SQL path only
3406 no_fixate => Bool # optional: skip read-only locking
3407 %criteria # optional: WHERE filter before grouping
3408  
3409 Each element of C<measures> is a hashref with keys:
3410  
3411 col => Str # column to aggregate; omit only for plain count()
3412 fn => Str # one of: sum avg min max count count_distinct median stddev
3413 as => Str # result key name (required; valid SQL identifier)
3414  
3415 =head4 Returns
3416  
3417 ArrayRef[HashRef]
3418  
3419 An arrayref of hashrefs. Each hashref has one key per C<by> column
3420 and one key per measure C<as> alias. Returns C<[]> (empty arrayref)
3421 when no groups match -- never C<undef>.
3422  
3423 Empty-set normalisation: C<sum>/C<count>/C<count_distinct> become
3424 C<0>; C<avg>/C<min>/C<max>/C<median>/C<stddev> become C<undef> when no rows
3425 are present.
3426  
3427 =cut
3428  
3429 sub aggregate
3430 166 ▶{
Subroutine aggregate: called CC=41 SCAR=39.6
Pod documented
3431 166 my $self = shift;
3432  
3433 166 $self->_open_table({});
3434  
3435 166 my $params;
3436 166 ▶ if($self->{'no_entry'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$self{'no_entry'}) { } 75 91 166
elsif (scalar @_) { } 90 1 91
3437 75 $params = Params::Get::get_params(undef, \@_);
3438 } elsif(scalar(@_)) {
3439 90 $params = Params::Get::get_params('entry', @_);
3440 }
3441 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
3442  
3443 166 my $table = $self->_open_table($params);
3444 166 my $no_fixate = delete $params->{'no_fixate'};
3445 166 my $join_spec = delete $params->{'join'};
3446 166 delete $params->{'table'};
3447  
3448 166 my $join_clause = '';
3449 166 ▶ if($join_spec) {
Branch: 1 branch
BranchTrueFalseTotal
if ($join_spec) 6 160 166
3450 6 $join_clause = $self->_build_joins($join_spec);
3451 }
3452  
3453 164 my $spec = $self->_validate_aggregate_spec($params);
3454  
3455 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
3456 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
3457 3 Carp::croak(ref($self), ": aggregate: cannot aggregate a JOIN on the $backend backend");
3458 }
3459  
3460 82 $spec->{'criteria'} = $self->_merge_base_criteria($spec->{'criteria'});
3461  
3462 # median and stddev are computed in Perl; skip SQL pushdown for them.
3463 82 my $has_perl_only = grep { $PERL_ONLY_AGG_FNS{$_->{'fn'}} } @{$spec->{'measures'}};
3464  
3465 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
3466 53 my ($sql, $args) = $self->_build_aggregate_sql($spec, $join_clause, $table, $self->{'_dbh'}{$table});
3467  
3468 49 ▶ if(defined($args->[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$args[0]) { } 21 28 49
3469 21 $self->_debug("aggregate $sql: ", join(', ', @{$args}));
3470 } else {
3471 28 $self->_debug("aggregate $sql");
3472 }
3473  
3474 49 my ($key, $c);
3475 49 ▶ if($c = $self->{'cache'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c = $$self{'cache'}) { } 0 49 49
3476 0 $key = ref($self) . "::$sql aggregate";
3477 0 ▶ $key .= ' ' . join(', ', @{$args}) if defined($args->[0]);
Branch: 1 branch
BranchTrueFalseTotal
if defined $$args[0] 0 0 0
3478 0 $self->_debug("aggregate cache key = '$key'");
3479 0 ▶ if(my $rc = $c->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $c->get($key)) 0 0 0
3480 0 $self->_debug('aggregate: cache HIT');
3481 0 return $rc;
3482 }
3483 0 $self->_debug('aggregate: cache MISS');
3484 } else {
3485 49 $self->_debug('aggregate cache not used');
3486 }
3487  
3488 my $sth = $self->{'_dbh'}{$table}->prepare_cached($sql)
3489 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
3490 0 $self->_warn("aggregate prepare failed on $sql");
3491 0 Carp::croak(ref($self), ': prepare failed: ', $self->{'_dbh'}{$table}->errstr());
3492 };
3493 0 ▶ $sth->execute(@{$args}) or Carp::croak("$sql: @{$args}");
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@{$args;}) or Carp::croak("${sql}: @{$args;}") 48 0 48
3494  
3495 48 my @rows;
3496 48 ▶ while(my $row = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 69 48 117
3497 69 push @rows, $row;
3498 }
3499  
3500 # Empty-set normalisation (§5.3 of design spec):
3501 # sum / count / count_distinct → 0; avg / min / max stay undef.
3502 48 for my $row (@rows) {
3503 69 for my $m (@{$spec->{'measures'}}) {
3504 76 my $as = $m->{'as'};
3505 76 my $fn = $m->{'fn'};
3506 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
3507 && ($fn eq 'sum' || $fn eq 'count' || $fn eq 'count_distinct')) {
3508 3 $row->{$as} = 0;
3509 }
3510 }
3511 }
3512  
3513 48 ▶ $c->set($key, \@rows, $self->{'cache_duration'}) if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 0 48 48
3514 48 ▶ $self->_fixate(\@rows) unless $no_fixate;
Branch: 1 branch
BranchTrueFalseTotal
unless $no_fixate 47 1 48
3515 48 return set_return(\@rows, { type => 'arrayref' });
3516 }
3517  
3518 # Perl fold path: fetch matching rows then group and aggregate in memory.
3519 # BerkeleyDB rows arrive via _scan_berkeley inside selectall_arrayref;
3520 # all other no-DBI backends (XLSX, Deep, JSON, HTML, Redis) have slurped data.
3521 29 my $rows = $self->selectall_arrayref(%{$spec->{'criteria'}});
3522 29 my $out = $self->_fold_aggregate($rows, $spec);
3523  
3524 29 ▶ if(my $hav = $spec->{'having'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $hav = $$spec{"having"}) 1 28 29
3525 1 $out = [ grep { $self->_match_criteria($_, $hav) } @{$out} ];
3526 }
3527  
3528 29 my @by_names = map { $_->{'name'} } @{$spec->{'by'}};
3529 29 ▶ if(my $s = $spec->{'sort'}) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $s = $$spec{'sort'}) { } 5 24 29
elsif (@by_names) { } 11 13 24
3530 5 my ($scol, $sdir) = @{$s};
3531 5 my $desc = ($sdir eq 'DESC');
3532 5 my $is_measure = $spec->{'aliases'}{$scol};
3533 5 @{$out} = sort {
3534 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
3535 5 ▶ $desc
Branch: 3 branches
BranchTrueFalseTotal
$desc ? : 1 4 5
$is_measure ? : 1 0 1
$is_measure ? : 0 4 4
3536 ? ($is_measure ? ($bv <=> $av) : ($bv cmp $av))
3537 : ($is_measure ? ($av <=> $bv) : ($av cmp $bv))
3538 5 } @{$out};
3539 } elsif(@by_names) {
3540 11 @{$out} = sort {
3541 6 my $cmp = 0;
3542 6 for my $bn (@by_names) {
3543 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
3544 6 ▶ last if $cmp;
Branch: 1 branch
BranchTrueFalseTotal
if $cmp 6 0 6
3545 }
3546 $cmp;
3547 11 } @{$out};
3548 }
3549  
3550 0 ▶ splice(@{$out}, 0, $spec->{'offset'}) if $spec->{'offset'};
Branch: 1 branch
BranchTrueFalseTotal
if $$spec{"offset"} 0 29 29
3551 29 ▶ splice(@{$out}, $spec->{'limit'}) if defined $spec->{'limit'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $$spec{"limit"} 4 25 29
3552  
3553 29 ▶ $self->_fixate($out) unless $no_fixate;
Branch: 1 branch
BranchTrueFalseTotal
unless $no_fixate 28 1 29
3554 29 return set_return($out, { type => 'arrayref' });
3555 }
3556  
3557 # Validate and extract aggregate spec from %params (mutates $params in place,
3558 # deleting aggregate control keys; the remainder becomes the WHERE criteria).
3559 # Returns \%spec on success; croaks on invalid input.
3560 # No database access — pure validation, trivially unit-testable.
3561 sub _validate_aggregate_spec
3562 230 ▶{
Subroutine _validate_aggregate_spec: called CC=53 SCAR=39.7
3563 230 my ($self, $params) = @_;
3564  
3565 230 my $by = delete $params->{'by'};
3566 230 my $meas = delete $params->{'measures'};
3567 230 my $having = delete $params->{'having'};
3568 230 my $sort_by = delete $params->{'sort_by'};
3569 230 my $limit = delete $params->{'limit'};
3570 230 my $offset = delete $params->{'offset'};
3571  
3572 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
3573 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
3574 unless ref($by) eq 'ARRAY';
3575  
3576 225 my (@by_names, %by_name_set);
3577 225 for my $col (@{$by}) {
3578 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
3579 unless defined($col) && $col =~ $SAFE_QUALIFIED;
3580 70 push @by_names, $col;
3581 70 $by_name_set{$col} = 1;
3582 }
3583  
3584 Carp::croak(ref($self), ": aggregate: 'measures' must be a non-empty arrayref")
3585 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
3586  
3587 201 my (@measure_specs, %alias_set);
3588 201 for my $m (@{$meas}) {
3589 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
3590 unless ref($m) eq 'HASH';
3591  
3592 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
3593 209 my $col = $m->{'col'};
3594 209 my $as = $m->{'as'};
3595  
3596 Carp::croak(ref($self), ": aggregate: unknown measure function '$fn'")
3597 209 ▶ unless $VALID_AGG_FNS{$fn};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_AGG_FNS{$fn} 9 200 209
3598  
3599 200 ▶ if($fn ne 'count') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn ne "count") 122 78 200
3600 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
3601 unless defined($col) && length($col);
3602 }
3603 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
3604 116 ▶ Carp::croak(ref($self), ": aggregate: unsafe measure column '$col'")
Branch: 1 branch
BranchTrueFalseTotal
unless $col =~ /$SAFE_QUALIFIED/ 12 104 116
3605 unless $col =~ $SAFE_QUALIFIED;
3606 }
3607  
3608 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
3609 unless defined($as) && length($as);
3610 174 ▶ Carp::croak(ref($self), ": aggregate: unsafe measure alias '$as'")
Branch: 1 branch
BranchTrueFalseTotal
unless $as =~ /$SAFE_IDENTIFIER/ 12 162 174
3611 unless $as =~ $SAFE_IDENTIFIER;
3612 Carp::croak(ref($self), ": aggregate: duplicate measure alias '$as'")
3613 162 ▶ if $alias_set{$as};
Branch: 1 branch
BranchTrueFalseTotal
if $alias_set{$as} 4 158 162
3614 Carp::croak(ref($self), ": aggregate: measure alias '$as' collides with a group-by column")
3615 158 ▶ if $by_name_set{$as};
Branch: 1 branch
BranchTrueFalseTotal
if $by_name_set{$as} 3 155 158
3616  
3617 155 $alias_set{$as} = 1;
3618  
3619 155 my $sql_expr;
3620 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
3621 67 $sql_expr = 'COUNT(*)';
3622 } elsif($fn eq 'count_distinct') {
3623 4 $sql_expr = "COUNT(DISTINCT $col)";
3624 } elsif($fn eq 'median') {
3625 6 $sql_expr = "MEDIAN($col)"; # Perl-fold path only; SQL expr unused
3626 } elsif($fn eq 'stddev') {
3627 3 $sql_expr = "STDDEV($col)"; # Perl-fold path only; SQL expr unused
3628 } else {
3629 75 $sql_expr = uc($fn) . "($col)";
3630 }
3631  
3632 155 push @measure_specs, { fn => $fn, col => $col, as => $as, sql => $sql_expr };
3633 }
3634  
3635 141 ▶ if(defined $having) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $having) 19 122 141
3636 19 ▶ Carp::croak(ref($self), ": aggregate: 'having' must be a hashref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $having eq "HASH" 3 16 19
3637 unless ref($having) eq 'HASH';
3638 16 for my $k (keys %{$having}) {
3639 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
3640 Carp::croak(ref($self), ": aggregate: having key '$k' is not a group-by column or measure alias")
3641 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
3642 }
3643 }
3644  
3645 134 my ($sort_col, $sort_dir);
3646 134 ▶ if(defined $sort_by) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_by) 22 112 134
3647 22 ▶ ($sort_col, $sort_dir) = ref($sort_by) eq 'ARRAY'
Branch: 1 branch
BranchTrueFalseTotal
ref $sort_by eq 'ARRAY' ? : 12 10 22
3648 ? ($sort_by->[0], $sort_by->[1])
3649 : ($sort_by, 'ASC');
3650 22 ▶ $sort_dir = defined($sort_dir) ? uc($sort_dir) : 'ASC';
Branch: 1 branch
BranchTrueFalseTotal
defined $sort_dir ? : 20 2 22
3651 Carp::croak(ref($self), ": aggregate: sort_by names '". ($sort_col // '') ."', which is not a group-by column or measure alias")
3652 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
3653 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
3654 unless $sort_dir eq 'ASC' || $sort_dir eq 'DESC';
3655 }
3656  
3657 128 ▶ if(defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 18 110 128
3658 18 ▶ if($limit !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $limit =~ /\A\d+\z/) { } 5 13 18
3659 5 Carp::carp('aggregate: limit must be a non-negative integer, ignoring');
3660 5 undef $limit;
3661 } else {
3662 13 $limit = int($limit);
3663 }
3664 }
3665 128 ▶ if(defined $offset) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 7 121 128
3666 7 ▶ if($offset !~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $offset =~ /\A\d+\z/) { } 3 4 7
3667 3 Carp::carp('aggregate: offset must be a non-negative integer, ignoring');
3668 3 undef $offset;
3669 } else {
3670 4 $offset = int($offset);
3671 }
3672 }
3673  
3674 return {
3675 128 ▶ by => [ map { { name => $_ } } @by_names ],
Branch: 1 branch
BranchTrueFalseTotal
defined $sort_col ? : 16 112 128
3676 measures => \@measure_specs,
3677 aliases => \%alias_set,
3678 by_names => \%by_name_set,
3679 having => $having,
3680 criteria => $params,
3681 sort => defined($sort_col) ? [ $sort_col, $sort_dir ] : undef,
3682 limit => $limit,
3683 offset => $offset,
3684 };
3685 }
3686  
3687 # Build the GROUP BY aggregate SQL query and bind-value list.
3688 # Returns ($sql, \@bind_args).
3689 sub _build_aggregate_sql
3690 61 ▶{
Subroutine _build_aggregate_sql: called CC=22 SCAR=33.0
3691 61 my ($self, $spec, $join_clause, $table, $dbh) = @_;
3692  
3693 61 my @by_names = map { $_->{'name'} } @{$spec->{'by'}};
3694 61 my @meas = @{$spec->{'measures'}};
3695  
3696 # SELECT: by columns then "expr AS alias" for each measure.
3697 61 my @sel;
3698 61 push @sel, @by_names;
3699 61 push @sel, map { "$_->{'sql'} AS $_->{'as'}" } @meas;
3700 61 my $sql = 'SELECT ' . join(', ', @sel) . " FROM $table";
3701 61 ▶ $sql .= " $join_clause" if $join_clause;
Branch: 1 branch
BranchTrueFalseTotal
if $join_clause 1 60 61
3702  
3703 # WHERE: criteria + CSV comment-row guard.
3704 61 my ($where, $wargs) = $self->_build_where($spec->{'criteria'});
3705 59 my @args = @{$wargs};
3706  
3707 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
3708 1 ▶ $sql .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 1 1
3709 ▶ } 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
3710 9 my $id = $self->{'id'};
3711 9 $sql .= " WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
3712 9 ▶ $sql .= " AND ($where)" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 0 9 9
3713 } else {
3714 49 ▶ $sql .= " WHERE $where" if $where;
Branch: 1 branch
BranchTrueFalseTotal
if $where 14 35 49
3715 }
3716  
3717 # GROUP BY.
3718 59 ▶ $sql .= ' GROUP BY ' . join(', ', @by_names) if @by_names;
Branch: 1 branch
BranchTrueFalseTotal
if @by_names 34 25 59
3719  
3720 # HAVING: substitute measure aliases with their SQL expressions so the
3721 # query is valid on PostgreSQL (which forbids output-column aliases in HAVING).
3722 59 ▶ if(my $hav = $spec->{'having'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $hav = $$spec{"having"}) 8 51 59
3723 8 my %a2s = map { $_->{'as'} => $_->{'sql'} } @meas;
3724 8 my ($hfrag, $hargs) = $self->_build_having_fragment($hav, \%a2s);
3725 6 ▶ if($hfrag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hfrag) 6 0 6
3726 6 $sql .= " HAVING $hfrag";
3727 6 push @args, @{$hargs};
3728 }
3729 }
3730  
3731 # ORDER BY: explicit sort_by takes precedence; default is by-columns ASC.
3732 57 ▶ if(my $s = $spec->{'sort'}) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $s = $$spec{'sort'}) { } 9 48 57
elsif (@by_names) { } 27 21 48
3733 9 $sql .= " ORDER BY $s->[0] $s->[1]";
3734 } elsif(@by_names) {
3735 27 $sql .= ' ORDER BY ' . join(', ', @by_names);
3736 }
3737  
3738 # LIMIT / OFFSET.
3739 57 ▶ if(defined $spec->{'limit'}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $$spec{'limit'}) { } 8 49 57
elsif (defined $$spec{'offset'}) { } 0 49 49
3740 8 $sql .= ' LIMIT ?';
3741 8 push @args, $spec->{'limit'};
3742 } elsif(defined $spec->{'offset'}) {
3743 # SQLite requires a LIMIT clause before OFFSET; -1 means no upper bound.
3744 $sql .= ' LIMIT -1'
3745 if ($dbh && (($dbh->{Driver}{Name} // '') eq 'SQLite'))
3746 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
3747 }
3748 57 ▶ if(defined $spec->{'offset'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$spec{"offset"}) 2 55 57
3749 2 $sql .= ' OFFSET ?';
3750 2 push @args, $spec->{'offset'};
3751 }
3752  
3753 57 return ($sql, \@args);
3754 }
3755  
3756 # Build a HAVING clause fragment, substituting measure aliases with their SQL
3757 # expressions (PostgreSQL forbids output-column aliases in HAVING).
3758 # $alias_to_sql maps alias → SQL expression (e.g. revenue → SUM(amount)).
3759 # Mirrors _build_where_conditions but uses pre-validated SQL expressions as LHS
3760 # for measure keys, so the $SAFE_QUALIFIED identifier check is skipped there.
3761 #
3762 # SQLite 3.51+ regression: bound parameters compared to aggregate expressions
3763 # (SUM, AVG, etc.) in HAVING are not type-coerced to numeric automatically,
3764 # causing numeric comparisons to return 0 rows. When the LHS was substituted
3765 # from an alias (i.e. it is an aggregate expression, not a bare column name),
3766 # wrap all numeric bind placeholders in CAST(? AS REAL) so SQLite performs the
3767 # comparison correctly. CAST(? AS REAL) is valid SQL in SQLite, PostgreSQL and
3768 # MySQL and is a no-op on those dialects where type coercion already works.
3769 #
3770 # Returns ($fragment, \@bind_values).
3771 sub _build_having_fragment
3772 26 ▶{
Subroutine _build_having_fragment: called CC=18 SCAR=28.9
3773 26 my ($self, $having, $alias_to_sql) = @_;
3774  
3775 26 my (@clauses, @args);
3776 26 for my $k (sort keys %{$having}) {
3777 26 my $agg_expr = $alias_to_sql->{$k};
3778 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
3779 26 my $val = $having->{$k};
3780  
3781 # ph() returns the right placeholder: CAST(? AS REAL) for aggregate
3782 # expression LHS (numeric result), bare ? for group-by column LHS.
3783 26 ▶ my $ph = defined($agg_expr) ? 'CAST(? AS REAL)' : '?';
Branch: 1 branch
BranchTrueFalseTotal
defined $agg_expr ? : 18 8 26
3784  
3785 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
3786 17 for my $op (keys %{$val}) {
3787 17 my $operand = $val->{$op};
3788 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
3789 2 ▶ my $sql_op = $op eq '-in' ? 'IN' : 'NOT IN';
Branch: 1 branch
BranchTrueFalseTotal
$op eq '-in' ? : 1 1 2
3790 2 my $phs = join(', ', ($ph) x scalar(@{$operand}));
3791 2 push @clauses, "$lhs $sql_op ($phs)";
3792 2 push @args, @{$operand};
3793 } elsif($op eq '-between') {
3794 1 push @clauses, "$lhs BETWEEN $ph AND $ph";
3795 1 push @args, $operand->[0], $operand->[1];
3796 } elsif($op eq '-like') {
3797 1 push @clauses, "$lhs LIKE ?";
3798 1 push @args, $operand;
3799 } elsif($op eq '-not_like') {
3800 1 push @clauses, "$lhs NOT LIKE ?";
3801 1 push @args, $operand;
3802 } elsif($op eq '!=') {
3803 2 ▶ if(!defined($operand)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $operand) { } 1 1 2
3804 1 push @clauses, "$lhs IS NOT NULL";
3805 } else {
3806 1 push @clauses, "$lhs != $ph";
3807 1 push @args, $operand;
3808 }
3809 } elsif($op =~ /\A[<>]=?\z/) {
3810 9 push @clauses, "$lhs $op $ph";
3811 9 push @args, $operand;
3812 } else {
3813 1 Carp::croak("Unknown operator '$op' in having for key '$k'");
3814 }
3815 }
3816 } elsif(ref($val)) {
3817 3 Carp::croak("$k: expected scalar or operator hashref, got ", ref($val));
3818 } elsif(!defined($val)) {
3819 1 push @clauses, "$lhs IS NULL";
3820 } elsif($val =~ /[%_]/) {
3821 1 push @clauses, "$lhs LIKE ?";
3822 1 push @args, $val;
3823 } else {
3824 4 push @clauses, "$lhs = $ph";
3825 4 push @args, $val;
3826 }
3827 }
3828  
3829 22 return (join(' AND ', @clauses), \@args);
3830 }
3831  
3832 # Recursive in-memory criterion matcher supporting -or/-and groupings.
3833 # Used by aggregate()'s Perl fold path for HAVING evaluation.
3834 # Leaf comparisons are delegated to _match_criterion.
3835 # Uses exists() guards for fixated slurp hashrefs (see Data::Reuse notes).
3836 sub _match_criteria
3837 37 ▶{
Subroutine _match_criteria: called CC=11 SCAR=24.0
3838 37 my ($self, $row, $criteria) = @_;
3839  
3840 37 for my $k (keys %{$criteria}) {
3841 37 ▶ if($k eq '-or') {
Branch: 2 branches
BranchTrueFalseTotal
if ($k eq '-or') { } 6 31 37
elsif ($k eq '-and') { } 5 26 31
3842 6 my $found = 0;
3843 6 for my $sub (@{$criteria->{$k}}) {
3844 8 ▶ if($self->_match_criteria($row, $sub)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_match_criteria($row, $sub)) 4 4 8
3845 4 $found = 1;
3846 4 last;
3847 }
3848 }
3849 6 ▶ return 0 unless $found;
Branch: 1 branch
BranchTrueFalseTotal
unless $found 2 4 6
3850 } elsif($k eq '-and') {
3851 5 for my $sub (@{$criteria->{$k}}) {
3852 8 ▶ return 0 unless $self->_match_criteria($row, $sub);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_match_criteria($row, $sub) 1 7 8
3853 }
3854 } else {
3855 26 ▶ my $row_val = exists($row->{$k}) ? $row->{$k} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$k} ? : 23 3 26
3856 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
3857 }
3858 }
3859 23 return 1;
3860 }
3861  
3862 # Group an arrayref of rows and compute aggregate measures in Perl.
3863 # Used by aggregate() when no DBI handle is available (slurp-only backends).
3864 # All matching rows are materialised by the caller before this is called.
3865 # Returns an arrayref of group rows (unsorted; sorting happens in aggregate()).
3866 sub _fold_aggregate
3867 46 ▶{
Subroutine _fold_aggregate: called CC=88 SCAR=51.4
3868 46 my ($self, $rows, $spec) = @_;
3869  
3870 46 my @by_specs = @{$spec->{'by'}};
3871 46 my @meas = @{$spec->{'measures'}};
3872  
3873 # Pre-compute per-measure numeric flag from cached schema (only when already
3874 # populated by a prior schema() call — never triggers a PRAGMA round-trip).
3875 my @meas_numeric = map {
3876 46 my $col = $_->{'col'};
3877 ($col && $self->{'_schema'})
3878 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
3879 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
3880 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
3881 }
3882 : 0;
3883 } @meas;
3884  
3885 46 my (%groups, @group_order);
3886  
3887 46 for my $row (@{$rows}) {
3888 # Build group key: NUL-separated by-column values ('undef' → '').
3889 my $key = join("\x00",
3890 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
3891 @by_specs
3892 );
3893  
3894 147 ▶ unless(exists $groups{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $groups{$key}) 57 90 147
3895 57 push @group_order, $key;
3896 57 my %g;
3897 # Seed group with by-column values from the first row seen.
3898 57 for my $b (@by_specs) {
3899 32 ▶ $g{$b->{'name'}} = exists($row->{$b->{'name'}}) ? $row->{$b->{'name'}} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $$row{$$b{'name'}} ? : 32 0 32
3900 }
3901 # Initialise per-measure accumulator state.
3902 57 for my $m (@meas) {
3903 62 my $fn = $m->{'fn'};
3904 62 my $as = $m->{'as'};
3905 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
3906 15 $g{"__agg_$as"} = { sum => 0, bad => 0, first_bad => undef };
3907 } elsif($fn eq 'avg') {
3908 5 $g{"__agg_$as"} = { sum => 0, cnt => 0, bad => 0, first_bad => undef };
3909 ▶ } 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
3910 3 $g{"__agg_$as"} = { val => undef };
3911 } elsif($fn eq 'count') {
3912 25 $g{"__agg_$as"} = { cnt => 0 };
3913 } elsif($fn eq 'count_distinct') {
3914 1 $g{"__agg_$as"} = { seen => {} };
3915 ▶ } 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
3916 13 $g{"__agg_$as"} = { vals => [] };
3917 }
3918 }
3919 57 $groups{$key} = \%g;
3920 }
3921  
3922 147 my $g = $groups{$key};
3923 147 my $mi = 0;
3924 147 for my $m (@meas) {
3925 161 my $fn = $m->{'fn'};
3926 161 my $col = $m->{'col'};
3927 161 my $as = $m->{'as'};
3928 161 my $numeric = $meas_numeric[$mi++];
3929 161 my $acc = $g->{"__agg_$as"};
3930 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
3931  
3932 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
3933 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
3934 30 $acc->{'sum'} += $val;
3935 ▶ } 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
3936 4 $acc->{'bad'}++;
3937 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
3938 }
3939 } elsif($fn eq 'avg') {
3940 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
3941 8 $acc->{'sum'} += $val;
3942 8 $acc->{'cnt'}++;
3943 ▶ } 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
3944 1 $acc->{'bad'}++;
3945 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
3946 }
3947 } elsif($fn eq 'min') {
3948 5 ▶ if(defined($val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 3 2 5
3949 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
3950 1 $acc->{'val'} = $val;
3951 ▶ } elsif($numeric ? ($val < $acc->{'val'}) : ($val lt $acc->{'val'})) {
Branch: 1 branch
BranchTrueFalseTotal
$numeric ? : 0 2 2
3952 1 $acc->{'val'} = $val;
3953 }
3954 }
3955 } elsif($fn eq 'max') {
3956 3 ▶ if(defined($val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 3 0 3
3957 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
3958 1 $acc->{'val'} = $val;
3959 ▶ } elsif($numeric ? ($val > $acc->{'val'}) : ($val gt $acc->{'val'})) {
Branch: 1 branch
BranchTrueFalseTotal
$numeric ? : 0 2 2
3960 0 $acc->{'val'} = $val;
3961 }
3962 }
3963 } elsif($fn eq 'count') {
3964 62 ▶ if(defined $col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $col) { } 2 60 62
3965 2 ▶ $acc->{'cnt'}++ if defined($val);
Branch: 1 branch
BranchTrueFalseTotal
if defined $val 1 1 2
3966 } else {
3967 60 $acc->{'cnt'}++;
3968 }
3969 } elsif($fn eq 'count_distinct') {
3970 4 ▶ $acc->{'seen'}{$val}++ if defined($val);
Branch: 1 branch
BranchTrueFalseTotal
if defined $val 3 1 4
3971 ▶ } 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
3972 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
3973 42 push @{$acc->{'vals'}}, $val + 0;
3974 ▶ } 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
3975 0 $acc->{'bad'}++;
3976 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
3977 }
3978 }
3979 }
3980 }
3981  
3982 # Finalise groups: derive final result values from accumulators.
3983 # %warned tracks which measure aliases have already had their non-numeric
3984 # warning emitted; the warning fires at most once per measure per call.
3985 46 my (%warned, @out);
3986 46 for my $key (@group_order) {
3987 57 my $g = $groups{$key};
3988 57 my %result;
3989 57 for my $b (@by_specs) {
3990 32 $result{$b->{'name'}} = $g->{$b->{'name'}};
3991 }
3992 57 for my $m (@meas) {
3993 62 my $fn = $m->{'fn'};
3994 62 my $as = $m->{'as'};
3995 62 my $col = $m->{'col'};
3996 62 my $acc = $g->{"__agg_$as"};
3997 62 my $val;
3998 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
3999 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
4000 3 Carp::carp("aggregate: column '$col' has $acc->{'bad'} non-numeric value(s), skipped, e.g. '$acc->{'first_bad'}'");
4001 }
4002 15 $val = $acc->{'sum'};
4003 } elsif($fn eq 'avg') {
4004 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
4005 1 Carp::carp("aggregate: column '$col' has $acc->{'bad'} non-numeric value(s), skipped, e.g. '$acc->{'first_bad'}'");
4006 }
4007 5 ▶ $val = $acc->{'cnt'} ? ($acc->{'sum'} / $acc->{'cnt'}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$$acc{'cnt'} ? : 3 2 5
4008 ▶ } 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
4009 3 $val = $acc->{'val'};
4010 } elsif($fn eq 'count') {
4011 25 $val = $acc->{'cnt'};
4012 } elsif($fn eq 'count_distinct') {
4013 1 $val = scalar(keys %{$acc->{'seen'}});
4014 } elsif($fn eq 'median') {
4015 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
4016 0 Carp::carp("aggregate: column '$col' has $acc->{'bad'} non-numeric value(s), skipped, e.g. '$acc->{'first_bad'}'");
4017 }
4018 8 my @sorted = sort { $a <=> $b } @{$acc->{'vals'}};
4019 8 my $n = scalar @sorted;
4020 8 ▶ if($n == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($n == 0) { } 0 8 8
elsif ($n % 2) { } 5 3 8
4021 0 $val = undef;
4022 } elsif($n % 2) {
4023 5 $val = $sorted[int($n / 2)];
4024 } else {
4025 3 $val = ($sorted[$n / 2 - 1] + $sorted[$n / 2]) / 2;
4026 }
4027 } elsif($fn eq 'stddev') {
4028 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
4029 0 Carp::carp("aggregate: column '$col' has $acc->{'bad'} non-numeric value(s), skipped, e.g. '$acc->{'first_bad'}'");
4030 }
4031 5 my $n = scalar @{$acc->{'vals'}};
4032 5 ▶ if($n < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n < 2) { } 1 4 5
4033 1 ▶ $val = $n == 1 ? 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$n == 1 ? : 1 0 1
4034 } else {
4035 4 my $mean = 0;
4036 4 $mean += $_ for @{$acc->{'vals'}};
4037 4 $mean /= $n;
4038 4 my $sq_sum = 0;
4039 4 $sq_sum += ($_ - $mean) ** 2 for @{$acc->{'vals'}};
4040 4 $val = sqrt($sq_sum / ($n - 1));
4041 }
4042 }
4043 62 $result{$as} = $val;
4044 }
4045 57 push @out, \%result;
4046 }
4047  
4048 46 return \@out;
4049 }
4050  
4051 =head2 query
4052  
4053 Returns a new L<Database::Abstraction::Query> builder object bound to this
4054 database instance, for fluent method-chaining queries.
4055  
4056 # All active rows with high scores, newest first, max 10
4057 my $rows = $db->query
4058 ->where(status => 'active')
4059 ->where(score => { '>' => 80 })
4060 ->order_by('score DESC')
4061 ->limit(10)
4062 ->all();
4063  
4064 # Single row
4065 my $row = $db->query->where(name => 'Alice')->first();
4066  
4067 # Just a count
4068 my $n = $db->query->where(status => 'active')->count();
4069  
4070 See L<Database::Abstraction::Query> for the full API.
4071  
4072 =cut
4073  
4074 sub query
4075 128 ▶{
Subroutine query: called CC=1 SCAR=0.0
Pod documented
4076 128 my $self = shift;
4077 128 require Database::Abstraction::Query;
4078 128 return Database::Abstraction::Query->new(_db => $self);
4079 }
4080  
4081 =head2 AUTOLOAD - column shortcut
4082  
4083 Calling an unknown method whose name matches a column name performs a column
4084 lookup. The method name is the column you want; the arguments are criteria.
4085  
4086 # Scalar context: return the first match
4087 my $name = $db->name(entry => 'key1');
4088  
4089 # List context: return all matching values
4090 my @names = $db->name();
4091  
4092 # Shortcut when the table has an 'entry' key column
4093 my $name = $db->name('key1'); # same as name(entry => 'key1')
4094  
4095 # Unique/distinct values
4096 my @statuses = $db->status(distinct => 1);
4097  
4098 B<In list context> the full column is returned (all rows), ordered by the
4099 column value. B<In scalar context> only the first match is returned
4100 (C<LIMIT 1>).
4101  
4102 Results come from the slurp cache when available.
4103  
4104 Throws an error if the column does not exist (slurp mode) or if AUTOLOAD
4105 has been disabled with C<< auto_load => 0 >>.
4106  
4107 =head3 PSEUDOCODE
4108  
4109 1. Extract column name from $AUTOLOAD; guard on DESTROY.
4110 2. Croak if auto_load => 0.
4111 3. Validate $column against /^[a-zA-Z_][a-zA-Z0-9_]*$/.
4112 4. If data is slurped:
4113 a. List context, no params -> map column over all rows (exists guard).
4114 b. entry-only param -> direct hash lookup (exists guard).
4115 c. No params, scalar -> first value in hash.
4116 d. no_entry set -> scan array for matching key/value pair.
4117 e. Other params -> scan keyed hash for matching column.
4118 5. If not slurped, build SQL:
4119 - List: SELECT column FROM table [WHERE ...] ORDER BY column
4120 - Scalar: SELECT DISTINCT column FROM table [WHERE ...] LIMIT 1
4121 6. Check cache; return on HIT.
4122 7. prepare_cached + execute; fetch result.
4123 8. Store in cache; fixate; return.
4124  
4125 =cut
4126  
4127 124 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=82 SCAR=46.8
4128 124 our $AUTOLOAD;
4129 124 my ($column) = $AUTOLOAD =~ /::([A-Za-z_]\w*)\z/;
4130  
4131 124 ▶ return if($column eq 'DESTROY');
Branch: 1 branch
BranchTrueFalseTotal
if $column eq "DESTROY" 0 124 124
4132 124 ▶ return if($column =~ /\A_/); # never treat private method names as column lookups
Branch: 1 branch
BranchTrueFalseTotal
if $column =~ /\A_/ 7 117 124
4133  
4134 117 ▶ my $self = shift or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = shift() or return 117 0 117
4135  
4136 117 ▶ Carp::croak(__PACKAGE__, ": Unknown column $column") if(!ref($self));
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 0 117 117
4137  
4138 # Allow the AUTOLOAD feature to be disabled
4139 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
4140  
4141 # Validate column name - only allow safe column name
4142 111 ▶ Carp::croak(__PACKAGE__, ": Invalid column name: $column") unless $column =~ $SAFE_IDENTIFIER;
Branch: 1 branch
BranchTrueFalseTotal
unless $column =~ /$SAFE_IDENTIFIER/ 0 111 111
4143  
4144 111 my $table = $self->_open_table();
4145  
4146 109 my %params;
4147 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
4148 2 %params = %{$_[0]};
4149 } elsif((scalar(@_) % 2) == 0) {
4150 78 %params = @_;
4151 } elsif(scalar(@_) == 1) {
4152 # Don't error on key-value databases, since there's no idea of columns
4153 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
4154 0 Carp::croak(ref($self), "::($_[0]): ", $self->{'id'}, ' is not a column');
4155 }
4156 29 $params{'entry'} = shift;
4157 }
4158  
4159 109 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 0 109 109
4160 0 ▶ if(my $id = $self->{'id'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = $$self{"id"}) 0 0 0
4161 0 return $self->{'berkeley'}->{$params{$id}};
4162 }
4163 0 return $self->{'berkeley'}->{$params{'entry'}};
4164 }
4165  
4166 109 ▶ croak('Where did the data come from?') if(!defined($self->{'type'}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$self{"type"} 0 109 109
4167 109 my $query;
4168 109 my $done_where = 0;
4169 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
4170  
4171 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
4172 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
4173 # Return all column values from the in-memory hash.
4174 # Use exists() because fixate() locks inner row hashes —
4175 # accessing a disallowed key would throw without the guard.
4176 # Handle both HASH (keyed data) and ARRAY (no_entry CSV slurp).
4177 18 ▶ my @_rows = ref($data) eq 'ARRAY' ? @{$data} : values %{$data};
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'ARRAY' ? : 2 16 18
4178 18 ▶ return map { exists($_->{$column}) ? $_->{$column} : undef } @_rows;
Branch: 1 branch
BranchTrueFalseTotal
exists $_->{$column} ? : 61 10 71
4179 }
4180 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
4181 # Non-DBI backends (JSON, XLSX, HTML URL): scan in-memory data with criteria.
4182 1 my @param_keys = keys %params;
4183 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
4184 1 ▶ return map { exists($_->{$column}) ? $_->{$column} : undef }
Branch: 1 branch
BranchTrueFalseTotal
exists $_->{$column} ? : 1 0 1
4185 grep {
4186 1 my $row = $_;
4187 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
4188 4 } @_rows;
4189 }
4190 5 my $id = $self->{'id'};
4191 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
4192 4 $query = "SELECT $column FROM $table WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
4193 4 $done_where = 1;
4194 } else {
4195 1 $query = "SELECT $column FROM $table";
4196 }
4197 } else {
4198 85 ▶ if(my $data = $self->{'data'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $data = $$self{"data"}) 64 21 85
4199 # The data has been read in using Text::xSV::Slurp,
4200 # so no need to do any SQL
4201 64 $self->_debug('AUTOLOAD using slurped data');
4202 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
4203 4 $self->_debug('no_entry is set');
4204 4 my ($key, $value) = %params;
4205 4 ▶ if(defined($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 4 0 4
4206 4 $self->_debug("key = $key, value = $value, column = $column");
4207 4 foreach my $row(@{$data}) {
4208 # exists() guards: fixate() locks row hashes recursively
4209 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
4210 3 ▶ my $rc = exists($row->{$column}) ? $row->{$column} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$column} ? : 3 0 3
4211 3 ▶ $self->_trace(__LINE__, ": AUTOLOAD $key: return ", defined($rc) ? "'$rc'" : 'undef', ' from slurped data');
Branch: 1 branch
BranchTrueFalseTotal
defined $rc ? : 3 0 3
4212 3 return $rc;
4213 }
4214 1 $self->_debug('not found in slurped data');
4215 }
4216 ▶ } 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
4217 # Look up a single entry by its key.
4218 # Use exists() before accessing — fixate() locks the outer hash and
4219 # dereferencing a missing key on a locked hash throws an exception.
4220 48 my $rc;
4221 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
4222 37 ▶ if(!exists($hash->{$column})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $hash->{$column}) 3 34 37
4223 3 Carp::croak(__PACKAGE__, ": There is no column $column in $table");
4224 }
4225 34 $rc = $hash->{$column};
4226 }
4227 45 ▶ if(defined($rc)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rc) { } 32 13 45
4228 32 $self->_trace(__LINE__, ": AUTOLOAD $key: return '$rc' from slurped data");
4229 } else {
4230 13 $self->_trace(__LINE__, ": AUTOLOAD $key: return undef from slurped data");
4231 }
4232 45 return $rc
4233 } elsif((scalar keys %params) == 0) {
4234 9 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 9 0 9
4235 9 ▶ if($distinct) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distinct) 9 0 9
4236 # Single pass instead of three (map→grep→map): avoids three
4237 # intermediate lists of size N on the stack.
4238 9 my %h;
4239 9 for my $r (values %{$data}) {
4240 34 ▶ my $v = exists($r->{$column}) ? $r->{$column} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $r->{$column} ? : 34 0 34
4241 34 ▶ $h{$v} = 1 if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 29 5 34
4242 }
4243 9 return keys %h;
4244 }
4245 # DEAD CODE: unreachable because the outer `if(wantarray && !$distinct)`
4246 # handles the wantarray+!distinct case. In this else branch, wantarray
4247 # implies $distinct (which returns above), so this line is never executed.
4248 # return map { exists($_->{$column}) ? $_->{$column} : undef } values %{$data}
4249 }
4250 # Scalar: return the first value found without building a full list
4251 0 foreach my $v (values %{$data}) {
4252 0 ▶ return exists($v->{$column}) ? $v->{$column} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $v->{$column} ? : 0 0 0
4253 }
4254 } else {
4255 # Keyed data but filtering on a non-key column
4256 3 my ($key, $value) = %params;
4257 3 foreach my $row (values %{$data}) {
4258 9 ▶ 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 6 3 9
Condition83%5/6
exists $row->{$key} and defined $$row{$key} and $$row{$key} eq $value
!ll&&!rl&&r
243
exists $row->{$key} and defined $$row{$key}
!ll&&!rl&&r
027
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
4259 3 ▶ next unless exists($row->{$column});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $row->{$column} 0 3 3
4260 3 ▶ if(my $rc = $row->{$column}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $$row{$column}) 3 0 3
4261 3 $self->_trace(__LINE__, ": AUTOLOAD $key: return '$rc' from slurped data");
4262 3 return $rc
4263 }
4264 }
4265 }
4266 return
4267 1 }
4268 # Data has not been slurped in
4269 21 my $id = $self->{'id'};
4270 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
4271 13 $query = "SELECT DISTINCT $column FROM $table WHERE $id IS NOT NULL AND $id NOT LIKE '#%'";
4272 13 $done_where = 1;
4273 } else {
4274 8 $query = "SELECT DISTINCT $column FROM $table";
4275 }
4276 }
4277 26 my @args;
4278 # Avoid `each` — it carries hidden iterator state across calls
4279 26 for my $k (sort keys %params) {
4280 # Guard against SQL injection via column names — same rule as _build_where_conditions
4281 21 ▶ Carp::croak(__PACKAGE__, ": unsafe column name '$k'")
Branch: 1 branch
BranchTrueFalseTotal
unless $k =~ /$SAFE_QUALIFIED/ 4 17 21
4282 unless $k =~ $SAFE_QUALIFIED;
4283 17 my $value = $params{$k};
4284 17 ▶ $self->_debug(__PACKAGE__, ": AUTOLOAD adding key/value pair $k=>", defined($value) ? $value : 'NULL');
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 15 2 17
4285 17 ▶ if(defined($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) { } 15 2 17
4286 15 ▶ $query .= $done_where ? " AND $k = ?" : " WHERE $k = ?";
Branch: 1 branch
BranchTrueFalseTotal
$done_where ? : 9 6 15
4287 15 $done_where = 1;
4288 15 push @args, $value;
4289 } else {
4290 2 ▶ $query .= $done_where ? " AND $k IS NULL" : " WHERE $k IS NULL";
Branch: 1 branch
BranchTrueFalseTotal
$done_where ? : 2 0 2
4291 2 $done_where = 1;
4292 }
4293 }
4294 22 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 5 17 22
4295 5 $query .= " ORDER BY $column";
4296 } else {
4297 17 $query .= ' LIMIT 1';
4298 }
4299 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
4300 15 $self->_debug("AUTOLOAD $query: ", join(', ', @args));
4301 } else {
4302 7 $self->_debug("AUTOLOAD $query");
4303 }
4304 22 my $cache;
4305 22 my $key = ref($self) . '::';
4306 22 ▶ if($cache = $self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache = $$self{'cache'}) { } 8 14 22
4307 8 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 2 6 8
4308 2 $key .= 'array ';
4309 }
4310 8 ▶ if(defined($args[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args[0]) { } 6 2 8
4311 6 $key .= "fetchrow $query " . join(', ', @args);
4312 } else {
4313 2 $key .= "fetchrow $query";
4314 }
4315 8 ▶ if(my $rc = $cache->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $cache->get($key)) 4 4 8
4316 4 $self->_debug('cache HIT');
4317 4 ▶ return wantarray ? @{$rc} : $rc; # We stored a ref to the array
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 1 3 4
4318 }
4319 4 $self->_debug('cache MISS');
4320 } else {
4321 14 $self->_debug('cache not used');
4322 }
4323 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
4324 18 ▶ $sth->execute(@args) || croak($query);
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@args) or croak($query) 18 0 18
4325  
4326 18 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 4 14 18
4327 # fetchall_arrayref([0]) asks DBI to project column 0 server-side, so each
4328 # returned row is [$col0] instead of the full row — less memory, same result.
4329 4 my @rc = map { $_->[0] } @{$sth->fetchall_arrayref([0])};
4330 4 ▶ if($cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache) 1 3 4
4331 1 $cache->set($key, \@rc, $self->{'cache_duration'}); # Store a ref to the array
4332 }
4333 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
4334 4 return @rc;
4335 }
4336 14 my $rc = $sth->fetchrow_array(); # Return the first match only
4337 14 $sth->finish();
4338 14 ▶ if($cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache) 3 11 14
4339 # Store the value, then return it — cache->set() return value is unreliable
4340 3 $cache->set($key, $rc, $self->{'cache_duration'});
4341 }
4342 14 return $rc;
4343 }
4344  
4345 sub DESTROY
4346 599 ▶{
Subroutine DESTROY: called CC=15 SCAR=28.0
4347 599 ▶ if(defined($^V) && ($^V ge 'v5.14.0')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $^V and $^V ge "v5.14.0") 599 0 599
Condition33%1/3
defined $^V and $^V ge "v5.14.0"
!ll&&!rl&&r
00599
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
4348 599 ▶ return if ${^GLOBAL_PHASE} eq 'DESTRUCT'; # >= 5.14.0 only
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" 0 599 599
4349 }
4350  
4351 599 my $self = shift;
4352  
4353 # Clean up temporary files — deleting File::Temp objects triggers auto-unlink/rmdir
4354 # If that doesn't happen for some reason, explicitly unlink
4355 599 ▶ if(defined $self->{'_temp_fh'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$self{"_temp_fh"}) 9 590 599
4356 9 my $temp_fh = $self->{'_temp_fh'};
4357 9 my $temp_path = eval { $temp_fh->filename() };
4358 9 delete $self->{'_temp_fh'};
4359 9 undef $temp_fh; # Release the local strong reference
4360 # Fallback explicit unlink if File::Temp didn't clean up
4361 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
4362 }
4363 599 delete $self->{'_remote_tmpdir'};
4364  
4365 # Disconnect Redis
4366 599 ▶ if(my $redis = delete $self->{'_redis'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $redis = delete $self->{"_redis"}) 0 599 599
4367 0 eval { $redis->quit() };
4368 }
4369  
4370 # Clean up database handles. They are kept apart from the object's own
4371 # fields, keyed by table, so that a table may have any name -- "data" or
4372 # "id" included -- without its handle overwriting the field of that name.
4373 599 ▶ if(ref($self->{'_dbh'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $$self{"_dbh"} eq "HASH") 441 158 599
4374 441 for my $dbh (grep { defined } values %{delete $self->{'_dbh'}}) {
4375 346 ▶ next unless Scalar::Util::blessed($dbh);
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($dbh) 0 346 346
4376 346 ▶ $dbh->disconnect() if $dbh->can('disconnect');
Branch: 1 branch
BranchTrueFalseTotal
if $dbh->can("disconnect") 346 0 346
4377 346 ▶ $dbh->finish() if $dbh->can('finish');
Branch: 1 branch
BranchTrueFalseTotal
if $dbh->can("finish") 0 346 346
4378 }
4379 }
4380  
4381 # Clean up Berkeley DB
4382 599 ▶ if($self->{'berkeley'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self{"berkeley"}) 16 583 599
4383 16 eval {
4384 16 untie %{$self->{'berkeley'}};
4385 };
4386 16 delete $self->{'berkeley'};
4387 }
4388  
4389 # Clear all other attributes to break potential circular references
4390 599 foreach my $key (keys %$self) {
4391 6312 delete $self->{$key};
4392 }
4393 }
4394  
4395 # Build the JOIN clause(s) from a single join hashref or arrayref of hashrefs.
4396 # Each spec needs keys: table (required), on (required), type (default INNER).
4397 sub _build_joins
4398 87 ▶{
Subroutine _build_joins: called CC=19 SCAR=29.4
4399 87 my ($self, $join_spec) = @_;
4400  
4401 87 ▶ my @specs = ref($join_spec) eq 'ARRAY' ? @{$join_spec} : ($join_spec);
Branch: 1 branch
BranchTrueFalseTotal
ref $join_spec eq 'ARRAY' ? : 8 79 87
4402 87 my @clauses;
4403  
4404 87 for my $j (@specs) {
4405 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
4406 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
4407 83 ▶ Carp::croak("join: unsafe table name '$jtable'")
Branch: 1 branch
BranchTrueFalseTotal
unless $jtable =~ /$SAFE_QUALIFIED/ 12 71 83
4408 unless $jtable =~ $SAFE_QUALIFIED;
4409 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
4410 65 ▶ Carp::croak("Invalid JOIN type: $type") unless $VALID_JOIN_TYPES{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_JOIN_TYPES{$type} 7 58 65
4411 58 my $on;
4412 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
4413 7 my @parts;
4414 7 for my $left (sort keys %{$on_raw}) {
4415 8 my $right = $on_raw->{$left};
4416 8 ▶ Carp::croak("join: unsafe on column '$left'")
Branch: 1 branch
BranchTrueFalseTotal
unless $left =~ /$SAFE_QUALIFIED/ 2 6 8
4417 unless $left =~ $SAFE_QUALIFIED;
4418 6 ▶ Carp::croak("join: unsafe on column '$right'")
Branch: 1 branch
BranchTrueFalseTotal
unless $right =~ /$SAFE_QUALIFIED/ 2 4 6
4419 unless $right =~ $SAFE_QUALIFIED;
4420 4 push @parts, "$left = $right";
4421 }
4422 3 $on = join(' AND ', @parts);
4423 } elsif(ref($on_raw) eq 'ARRAY') {
4424 14 my @elems = @{$on_raw};
4425 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
4426 unless @elems == 2 || @elems == 3;
4427 11 ▶ my ($left, $op, $right) = @elems == 2
Branch: 1 branch
BranchTrueFalseTotal
@elems == 2 ? : 2 9 11
4428 ? ($elems[0], '=', $elems[1])
4429 : @elems;
4430 11 ▶ Carp::croak("join: unsafe on column '$left'")
Branch: 1 branch
BranchTrueFalseTotal
unless $left =~ /$SAFE_QUALIFIED/ 1 10 11
4431 unless $left =~ $SAFE_QUALIFIED;
4432 10 ▶ Carp::croak("join: unsafe on column '$right'")
Branch: 1 branch
BranchTrueFalseTotal
unless $right =~ /$SAFE_QUALIFIED/ 1 9 10
4433 unless $right =~ $SAFE_QUALIFIED;
4434 9 ▶ Carp::croak("join: invalid on operator '$op'")
Branch: 1 branch
BranchTrueFalseTotal
unless $op =~ /\A(?:=|!=|<>|<|>|<=|>=)\z/ 2 7 9
4435 unless $op =~ /\A(?:=|!=|<>|<|>|<=|>=)\z/;
4436 7 $on = "$left $op $right";
4437 } else {
4438 37 $on = $on_raw;
4439 }
4440 47 push @clauses, "$type JOIN $jtable ON ($on)";
4441 }
4442  
4443 46 return join(' ', @clauses);
4444 }
4445  
4446 # Infer a SQL type token from an arrayref of sample values for one column.
4447 # Returns 'INTEGER', 'REAL', 'TIMESTAMP', 'DATE', or 'TEXT' (the default).
4448 # undef and empty-string values are treated as NULL and skipped; a column
4449 # whose entire sample is NULL is typed TEXT (most permissive safe default).
4450 # Order of checks: INTEGER before REAL (integers also match REAL); TIMESTAMP
4451 # before DATE (timestamps start like dates but have a time component).
4452 sub _infer_type
4453 21 ▶{
Subroutine _infer_type: called CC=7 SCAR=19.5
4454 21 my ($vals) = @_;
4455 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
4456 21 ▶ return 'TEXT' unless @non_null;
Branch: 1 branch
BranchTrueFalseTotal
unless @non_null 3 18 21
4457 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
4458 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
4459 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
4460 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
4461 3 return 'TEXT';
4462 }
4463  
4464 # Merge $self->{'base_criteria'} into a caller-supplied $params hashref.
4465 # Returns a new hashref with base_criteria keys added; caller keys WIN on collision
4466 # so callers can always further restrict. Returns $params unchanged when no
4467 # base_criteria is set, avoiding an extra allocation on the common code path.
4468 763 ▶sub _merge_base_criteria :Private {
Subroutine _merge_base_criteria: called CC=2 SCAR=6.9
4469 763 my ($self, $params) = @_;
4470 763 my $bc = $self->{'base_criteria'};
4471 763 ▶ return $params unless $bc;
Branch: 1 branch
BranchTrueFalseTotal
unless $bc 732 31 763
4472 31 return { %{$bc}, %{$params} };
4473 53 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4474  
4475 # Parse a sort_by parameter value into ($col, $dir).
4476 # Accepts: scalar column name (ASC), or [$col, $dir] arrayref.
4477 # Validates column against $SAFE_QUALIFIED and direction as ASC/DESC.
4478 # Carps and returns (undef, 'ASC') on invalid input so callers fall back
4479 # to the default id-column sort.
4480 sub _parse_sort_by
4481 450 ▶{
Subroutine _parse_sort_by: called CC=8 SCAR=20.8
4482 450 my ($sb, $method) = @_;
4483 450 ▶ return (undef, 'ASC') unless defined $sb;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sb 409 41 450
4484 41 ▶ my ($col, $dir) = ref($sb) eq 'ARRAY' ? @{$sb}[0, 1] : ($sb, undef);
Branch: 1 branch
BranchTrueFalseTotal
ref $sb eq 'ARRAY' ? : 20 21 41
4485 41 ▶ $dir = defined($dir) ? uc($dir) : 'ASC';
Branch: 1 branch
BranchTrueFalseTotal
defined $dir ? : 20 21 41
4486 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
4487 12 Carp::carp("$method: unsafe sort_by column, ignoring");
4488 12 return (undef, 'ASC');
4489 }
4490 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
4491 5 Carp::carp("$method: invalid sort_by direction '$dir', ignoring");
4492 5 return (undef, 'ASC');
4493 }
4494 24 return ($col, $dir);
4495 }
4496  
4497 # Return true when $params contains operator hashrefs, -or, or -and groupings
4498 # that the simple slurp fast-path cannot handle.
4499 sub _has_complex_criteria
4500 377 ▶{
Subroutine _has_complex_criteria: called CC=5 SCAR=16.1
4501 377 my ($self, $params) = @_;
4502 377 ▶ return 0 unless defined $params;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $params 3 374 377
4503 # -or / -and keys short-circuit immediately: no value scan needed.
4504 374 ▶ return 1 if exists $params->{'-or'} || exists $params->{'-and'};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params->{"-or"} or exists $params->{"-and"} 7 367 374
Condition100%3/3
exists $params->{"-or"} or exists $params->{"-and"}
l!l&&r!l&&!r
43367
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
4505 # LOGICAL INVARIANT: when this returns false, NO value in %$params is a
4506 # reference. This is the Boolean gate that makes _match_criterion's
4507 # hashref branch provably unreachable from the public select API:
4508 # Premise A — in-memory scan path requires: !_has_complex_criteria(params)
4509 # Premise B — _has_complex_criteria returns true if any value is a ref
4510 # Conclusion — inside the in-memory scan, every crit_val is a scalar/undef
4511 # any() short-circuits on the first truthy element; the for-loop equivalent
4512 # would iterate through all values before returning false in the common case.
4513 367 ▶ 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 359 367
4514 }
4515  
4516 # Build the WHERE clause body (everything after "WHERE") from a criteria hash.
4517 # Handles -or / -and groupings then delegates per-column work to _build_where_conditions.
4518 # Returns ($sql_fragment, \@bind_values).
4519 # Wrapper around Data::Reuse::fixate() that suppresses the spurious
4520 # "Use of uninitialized value in hash slice" warning. Data::Alias's XS
4521 # hash-aliasing code does not fully initialise key SVs on older Perl
4522 # versions when the source hash contains undef values (NULL columns).
4523 # Data::Reuse still fixates correctly; the warning is a false positive.
4524 # $struct must be the hashref or arrayref to fixate.
4525 434 ▶sub _fixate :Private
Subroutine _fixate: called CC=2 SCAR=8.7
4526 {
4527 434 my (undef, $struct) = @_;
4528 434 ▶ return unless defined $struct;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $struct 1 433 434
4529 # Clear stale address→canonical mappings from prior fixate calls before
4530 # fixating $struct. Without this, freed hashref addresses from a previous
4531 # object's slurp or DBI result can be reused by the allocator for new
4532 # hashrefs; fixate() would then find the stale entry and alias the new
4533 # hashref to the wrong canonical, silently substituting one row's data for
4534 # another. This is the same stale-address hazard that affects DBI paths
4535 # (see selectall_arrayref / selectall_array) but also affects the slurp
4536 # fixate when earlier objects go out of scope before a new slurp runs.
4537 433 Data::Reuse::forget();
4538 # Suppress the benign "Use of uninitialized value in hash slice" warning
4539 # that Data::Reuse/Data::Alias emits on some Perl < 5.34 builds when a
4540 # row has undef columns. All other warnings are re-emitted verbatim so
4541 # unrelated problems remain visible. This is intentional, not debug code.
4542 0 ▶ local $SIG{__WARN__} = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
4543 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
4544 index($_[0], 'Use of uninitialized value') == 0
4545 && index($_[0], 'in hash slice') >= 0;
4546 433 };
4547 433 &Data::Reuse::fixate($struct);
4548 53 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4549  
4550 sub _build_where
4551 444 ▶{
Subroutine _build_where: called CC=13 SCAR=25.7
4552 444 my ($self, $params) = @_;
4553  
4554 444 ▶ $params //= {};
Condition50%1/2
$params //= {}
l!l
4440
MC/DC0%0/1
$params //= {}
$params
Truth table50%1/2
A
A= $params
Aresult
11
00
4555 444 my @clauses;
4556 my @args;
4557  
4558 # Avoid an O(K) hash copy in the common case where neither -or nor -and is
4559 # present. Only copy when we actually need to delete grouping keys, so the
4560 # plain-criteria path (the vast majority of queries) passes $params through
4561 # directly to _build_where_conditions without any allocation.
4562 444 my $or_list = $params->{'-or'};
4563 444 my $and_list = $params->{'-and'};
4564 444 my $plain;
4565 444 ▶ if(defined($or_list) || defined($and_list)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $or_list or defined $and_list) { } 21 423 444
Condition100%3/3
defined $or_list or defined $and_list
l!l&&r!l&&!r
156423
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
4566 21 my %p = %{$params};
4567 21 delete @p{qw(-or -and)};
4568 21 $plain = \%p;
4569 } else {
4570 423 $plain = $params;
4571 }
4572  
4573 444 ▶ if($or_list) {
Branch: 1 branch
BranchTrueFalseTotal
if ($or_list) 15 429 444
4574 15 my (@sub_clauses, @sub_args);
4575 15 for my $cond (@{$or_list}) {
4576 28 my ($s, $a) = $self->_build_where_conditions($cond);
4577 28 ▶ if($s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s) 28 0 28
4578 28 push @sub_clauses, "($s)";
4579 28 push @sub_args, @{$a};
4580 }
4581 }
4582 15 ▶ if(@sub_clauses) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sub_clauses) 14 1 15
4583 14 push @clauses, '(' . join(' OR ', @sub_clauses) . ')';
4584 14 push @args, @sub_args;
4585 }
4586 }
4587 444 ▶ if($and_list) {
Branch: 1 branch
BranchTrueFalseTotal
if ($and_list) 6 438 444
4588 6 my (@sub_clauses, @sub_args);
4589 6 for my $cond (@{$and_list}) {
4590 9 my ($s, $a) = $self->_build_where_conditions($cond);
4591 9 ▶ if($s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s) 9 0 9
4592 9 push @sub_clauses, "($s)";
4593 9 push @sub_args, @{$a};
4594 }
4595 }
4596 6 ▶ if(@sub_clauses) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sub_clauses) 5 1 6
4597 5 push @clauses, '(' . join(' AND ', @sub_clauses) . ')';
4598 5 push @args, @sub_args;
4599 }
4600 }
4601  
4602 444 my ($more, $margs) = $self->_build_where_conditions($plain);
4603 426 ▶ if($more) {
Branch: 1 branch
BranchTrueFalseTotal
if ($more) 173 253 426
4604 173 push @clauses, $more;
4605 173 push @args, @{$margs};
4606 }
4607  
4608 426 return (join(' AND ', @clauses), \@args);
4609 }
4610  
4611 # Build a WHERE-body fragment for a flat col => val hash.
4612 # Values may be plain scalars (= / LIKE / IS NULL) or operator hashrefs
4613 # ({ '>' => n }, { -in => [...] }, { -between => [lo,hi] }, etc.).
4614 sub _build_where_conditions
4615 512 ▶{
Subroutine _build_where_conditions: called CC=17 SCAR=28.3
4616 512 my ($self, $params) = @_;
4617  
4618 512 my @clauses;
4619 my @args;
4620  
4621 512 for my $col (sort keys %{$params}) {
4622 269 my $val = $params->{$col};
4623  
4624 # Guard against SQL injection via column names; allow table.column notation for JOINs
4625 269 ▶ Carp::croak("_build_where_conditions: unsafe column name '$col'")
Branch: 1 branch
BranchTrueFalseTotal
unless $col =~ /$SAFE_QUALIFIED/ 18 251 269
4626 unless $col =~ $SAFE_QUALIFIED;
4627  
4628 251 ▶ if(ref($val) eq 'HASH') {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $val eq 'HASH') { } 69 182 251
elsif (ref $val) { } 4 178 182
elsif (not defined $val) { } 9 169 178
elsif ($val =~ /[%_]/) { } 6 163 169
4629 69 for my $op (keys %{$val}) { # no sort — operator hashes typically have 1-2 keys; sort adds O(K log K) overhead
4630 70 my $operand = $val->{$op};
4631 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
4632 13 ▶ my $sql_op = $op eq '-in' ? 'IN' : 'NOT IN';
Branch: 1 branch
BranchTrueFalseTotal
$op eq '-in' ? : 8 5 13
4633 13 my $ph = join(', ', ('?') x scalar(@{$operand}));
4634 13 push @clauses, "$col $sql_op ($ph)";
4635 13 push @args, @{$operand};
4636 } elsif($op eq '-between') {
4637 6 push @clauses, "$col BETWEEN ? AND ?";
4638 6 push @args, $operand->[0], $operand->[1];
4639 } elsif($op eq '-like') {
4640 5 push @clauses, "$col LIKE ?";
4641 5 push @args, $operand;
4642 } elsif($op eq '-not_like') {
4643 4 push @clauses, "$col NOT LIKE ?";
4644 4 push @args, $operand;
4645 } elsif($op eq '!=') {
4646 6 ▶ if(!defined($operand)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $operand) { } 2 4 6
4647 2 push @clauses, "$col IS NOT NULL";
4648 } else {
4649 4 push @clauses, "$col != ?";
4650 4 push @args, $operand;
4651 }
4652 # [<>]=? matches >, <, >=, <= as a single character class — no alternation
4653 # overhead, no backtracking, and self-documenting.
4654 } elsif($op =~ /\A[<>]=?\z/) {
4655 34 push @clauses, "$col $op ?";
4656 34 push @args, $operand;
4657 } else {
4658 2 Carp::croak("Unknown operator '$op' for column '$col'");
4659 }
4660 }
4661 } elsif(ref($val)) {
4662 4 Carp::croak("$col: expected scalar or operator hashref, got ", ref($val));
4663 } elsif(!defined($val)) {
4664 9 push @clauses, "$col IS NULL";
4665 } elsif($val =~ /[%_]/) {
4666 6 push @clauses, "$col LIKE ?";
4667 6 push @args, $val;
4668 } else {
4669 163 push @clauses, "$col = ?";
4670 163 push @args, $val;
4671 }
4672 }
4673  
4674 488 return (join(' AND ', @clauses), \@args);
4675 }
4676  
4677 # Test a single in-memory row value against a criteria value.
4678 # $crit_val may be a plain scalar or an operator hashref.
4679 # Returns true when the row value satisfies the criterion.
4680 # Scan the entire BerkeleyDB tied hash, building rows as {entry=>$k, value=>$v},
4681 # and filter by $params criteria using _match_criterion.
4682 # Croaks when JOINs or -or/-and groupings are requested (unsupported for key-value stores).
4683 sub _scan_berkeley
4684 18 ▶{
Subroutine _scan_berkeley: called CC=9 SCAR=22.0
4685 18 my ($self, $params) = @_;
4686 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
4687  
4688 # TODO: Data Flow Anomaly - Mutation side effect: delete mutates the caller's
4689 # $params hashref in-place. All current callers (selectall_arrayref,
4690 # selectall_array, count) do not reuse $params after this call, so it is safe;
4691 # but a future caller that reuses $params would silently lose the 'join' key.
4692 # Fix: use exists($params->{'join'}) to check; copy params before deleting.
4693 18 ▶ if(delete $params->{'join'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (delete $params->{"join"}) 2 16 18
4694 2 Carp::croak(ref($self), ': BerkeleyDB does not support JOINs');
4695 }
4696 # any() short-circuits: once the first -or/-and key is found the croak fires
4697 # without scanning the remaining keys — O(1) best case vs O(K) for grep.
4698 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
4699 3 Carp::croak(ref($self), ': BerkeleyDB does not support -or/-and groupings');
4700 }
4701  
4702 13 my $bdb = $self->{'berkeley'};
4703 13 my @cols = keys %{$params};
4704 13 my @rows;
4705  
4706 13 ▶ if(@cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cols) { } 3 10 13
4707 # Single-pass build+filter: avoids materialising the full N-row list
4708 # before filtering. Peak memory is O(matching rows) instead of O(N).
4709 3 for my $k (keys %{$bdb}) {
4710 7 my $row = { entry => $k, value => $bdb->{$k} };
4711 7 my $match = 1;
4712 7 for my $col (@cols) {
4713 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
4714 4 $match = 0;
4715 4 last;
4716 }
4717 }
4718 7 ▶ push @rows, $row if $match;
Branch: 1 branch
BranchTrueFalseTotal
if $match 3 4 7
4719 }
4720 } else {
4721 10 @rows = map { { entry => $_, value => $bdb->{$_} } } keys %{$bdb};
4722 }
4723  
4724 13 return \@rows;
4725 }
4726  
4727 # SQL LIKE match — case-insensitive, ReDoS-safe, no catastrophic backtracking.
4728 # % matches any sequence of chars; _ matches exactly one char.
4729 #
4730 # Fast paths cover the four most common LIKE shapes using O(1) string ops:
4731 # '%' → always true
4732 # no wildcard → lc eq comparison
4733 # '%suffix' → ends-with check via substr
4734 # 'prefix%' → starts-with check via index
4735 # '%mid%' → contains check via index (single inner literal, no _ wildcards)
4736 #
4737 # Full DP uses O(m) memory (two 1-D rolling arrays) instead of the O(m*n) 2-D
4738 # table the naive approach allocates. Character access uses substr() instead of
4739 # split(//) so no per-character scalar objects are created.
4740 sub _like_match
4741 83 ▶{
Subroutine _like_match: called CC=23 SCAR=31.4
4742 83 my ($str, $pattern) = @_;
4743  
4744 # Fast path 1: bare '%' — matches any string regardless of content.
4745 83 ▶ return 1 if $pattern eq '%';
Branch: 1 branch
BranchTrueFalseTotal
if $pattern eq "%" 8 75 83
4746  
4747 75 my $lc_str = lc($str);
4748 75 my $lc_pat = lc($pattern);
4749 75 my $pat_len = length($lc_pat);
4750 75 my $str_len = length($lc_str);
4751  
4752 # Fast path 2: no wildcard characters — plain case-insensitive equality.
4753 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
4754 if index($lc_pat, '%') == -1 && index($lc_pat, '_') == -1;
4755  
4756 # Fast paths 3-5 apply only when the pattern has no '_' wildcards.
4757 # (Patterns with '_' need per-character DP to enforce the single-char rule.)
4758 61 ▶ if(index($lc_pat, '_') == -1) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($lc_pat, "_") == -1) 48 13 61
4759 48 my $first_pct = index($lc_pat, '%');
4760 48 my $last_pct = rindex($lc_pat, '%');
4761  
4762 # Fast path 3: '%suffix' — exactly one '%', at the start.
4763 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
4764 12 my $sfx = substr($lc_pat, 1);
4765 12 my $sfx_len = length($sfx);
4766 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
4767 && substr($lc_str, $str_len - $sfx_len) eq $sfx;
4768 }
4769  
4770 # Fast path 4: 'prefix%' — exactly one '%', at the end.
4771 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
4772 17 my $pfx = substr($lc_pat, 0, $pat_len - 1);
4773 17 return index($lc_str, $pfx) == 0;
4774 }
4775  
4776 # Fast path 5: '%literal%' — '%' at both ends, no inner '%'.
4777 # pat_len >= 3 ensures there are two distinct '%' characters.
4778 # Only return here when the middle segment is free of further wildcards;
4779 # if it contains '%' (e.g. '%a%b%'), fall through to the full DP.
4780 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
4781 12 my $needle = substr($lc_pat, 1, $pat_len - 2);
4782 12 ▶ if(index($needle, '%') == -1) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($needle, "%") == -1) 7 5 12
4783 7 return index($lc_str, $needle) >= 0;
4784 }
4785 }
4786 }
4787  
4788 # Full DP — O(m*n) time, O(m) memory.
4789 # Two 1-D arrayrefs (@$prev, @$curr) replace the O(m*n) 2-D table.
4790 # substr() replaces split(//) — no per-char scalar allocation.
4791 # Ref-swap ($prev,$curr) = ($curr,$prev) at the end of each outer iteration
4792 # avoids the O(m) array copy that "@prev = @curr" would perform.
4793 25 my $m = $str_len;
4794 25 my $n = $pat_len;
4795  
4796 25 my ($prev, $curr) = ([1, (0) x $m], [(0) x ($m + 1)]);
4797  
4798 25 for my $i (1 .. $n) {
4799 252 @{$curr} = (0) x ($m + 1); # zero in-place — reuses existing allocation
4800 252 my $pc = substr($lc_pat, $i - 1, 1);
4801 252 ▶ if($pc eq '%') {
Branch: 1 branch
BranchTrueFalseTotal
if ($pc eq '%') { } 129 123 252
4802 129 $curr->[0] = $prev->[0];
4803 129 for my $j (1 .. $m) {
4804 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
4805 }
4806 } else {
4807 123 for my $j (1 .. $m) {
4808 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
4809 && ($pc eq '_' || $pc eq substr($lc_str, $j - 1, 1))) ? 1 : 0;
4810 }
4811 }
4812 252 ($prev, $curr) = ($curr, $prev); # O(1) ref swap — no array copy
4813 }
4814 25 return $prev->[$m];
4815 }
4816  
4817 sub _match_criterion
4818 342 ▶{
Subroutine _match_criterion: called CC=51 SCAR=39.4
4819 342 my ($self, $row_val, $crit_val, $col) = @_;
4820  
4821 # Use numeric equality/membership operators when the schema (if already
4822 # cached) reports the column as INTEGER or REAL. The numeric ordering
4823 # operators (>, <, >=, <=, -between) already use Perl's numeric context
4824 # regardless; only equality-family operators need the type-aware path.
4825 my $numeric = ($col && $self->{'_schema'})
4826 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
4827 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
4828 : 0;
4829  
4830 342 ▶ if(ref($crit_val) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $crit_val eq "HASH") 109 233 342
4831 109 for my $op (keys %{$crit_val}) {
4832 108 my $operand = $crit_val->{$op};
4833 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
4834 return 0 unless defined($row_val)
4835 && ($numeric
4836 4 ? grep { $row_val == $_ } @{$operand}
4837 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
4838 } elsif($op eq '-not_in') {
4839 return 0 if defined($row_val)
4840 && ($numeric
4841 2 ? grep { $row_val == $_ } @{$operand}
4842 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
4843 } elsif($op eq '-between') {
4844 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
4845 } elsif($op eq '-like') {
4846 31 ▶ return 0 unless defined($row_val);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val 1 30 31
4847 30 ▶ return 0 unless _like_match($row_val, $operand);
Branch: 1 branch
BranchTrueFalseTotal
unless _like_match($row_val, $operand) 13 17 30
4848 } elsif($op eq '-not_like') {
4849 5 ▶ return 0 unless defined($row_val);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val 1 4 5
4850 4 ▶ return 0 if _like_match($row_val, $operand);
Branch: 1 branch
BranchTrueFalseTotal
if _like_match($row_val, $operand) 1 3 4
4851 } elsif($op eq '!=') {
4852 14 ▶ if(!defined($operand)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $operand) { } 5 9 14
elsif ($numeric) { } 2 7 9
4853 5 ▶ return 0 unless defined($row_val);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_val 3 2 5
4854 } elsif($numeric) {
4855 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
4856 } else {
4857 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
4858 }
4859 } elsif($op eq '>') {
4860 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
4861 } elsif($op eq '<') {
4862 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
4863 } elsif($op eq '>=') {
4864 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
4865 } elsif($op eq '<=') {
4866 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
4867 }
4868 }
4869 58 return 1;
4870 }
4871  
4872 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) ? : 46 179 225
$numeric ? : 11 168 179
Condition100%6/6
defined $row_val || defined $crit_val
l!l&&r!l&&!r
194318
defined $row_val && defined $crit_val
!ll&&!rl&&r
3115179
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
4873 : !defined($row_val) || !defined($crit_val) ? 0
4874 : $numeric ? $row_val == $crit_val
4875 : $row_val eq $crit_val;
4876 }
4877  
4878 # Determine the table and open the database
4879 sub _open_table
4880 2204 ▶{
Subroutine _open_table: called CC=8 SCAR=20.9
4881 2204 my($self, $params) = @_;
4882  
4883 # Derive the table name, caching the result in '_table_name' for the common
4884 # case of no caller-supplied 'table' override. Avoids repeating ref()+regex
4885 # on every query when the same object makes many calls.
4886 2204 my $table;
4887 2204 ▶ if($params->{'table'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$params{'table'}) { } 10 2194 2204
4888 10 ($table = $params->{'table'}) =~ s/\A.*:://;
4889 10 ▶ Carp::croak(ref($self), ": unsafe table name '$table'")
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /$SAFE_QUALIFIED/ 7 3 10
4890 unless $table =~ $SAFE_QUALIFIED;
4891 } else {
4892 2194 ▶ $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
17614330
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
4893 433 ▶ my $t = $self->{'table'} || ref($self);
Condition33%1/3
$$self{'table'} || ref $self
l!l&&r!l&&!r
04330
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
4894 433 $t =~ s/\A.*:://;
4895 433 $t;
4896 };
4897 }
4898  
4899 # Open a connection if it's not already open.
4900 # BerkeleyDB never sets $self->{'_dbh'}{$table} (no DBI handle) or $self->{'data'},
4901 # so we also guard on $self->{'berkeley'} to avoid re-tying on every call.
4902 2197 ▶ $self->_open() if(!$self->{'_dbh'}{$table} && !$self->{'data'} && !$self->{'berkeley'});
Branch: 1 branch
BranchTrueFalseTotal
unless $$self{"_dbh"}{$table} or $$self{"data"} or $$self{"berkeley"} 433 1764 2197
Condition100%6/6
$$self{"_dbh"}{$table} or $$self{"data"} or $$self{"berkeley"}
l!l&&r!l&&!r
174915433
$$self{"_dbh"}{$table} or $$self{"data"}
l!l&&r!l&&!r
1544205448
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
4903  
4904 2148 return $table;
4905 }
4906  
4907 # Quote a SQL identifier using the current connection's dialect rules.
4908 # Falls back to ANSI double-quoting when no connection is available.
4909 sub _quote_identifier
4910 4 ▶{
Subroutine _quote_identifier: called CC=3 SCAR=11.2
4911 4 my ($self, $name) = @_;
4912  
4913 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
4914 4 $table =~ s/\A.*:://;
4915 4 ▶ if(my $dbh = $self->{'_dbh'}{$table}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $dbh = $$self{"_dbh"}{$table}) 2 2 4
4916 2 return $dbh->quote_identifier($name);
4917 }
4918 2 return qq{"$name"};
4919 }
4920  
4921 # The escape character a CSV/PSV/TSV file is written with. RFC 4180 (and
4922 # every spreadsheet) writes a quote inside a quoted field as two quotes,
4923 # "Adeste ""Overture""", which a backslash escape reads back as two quotes;
4924 # other files write it \", which a quote escape cannot read at all. So: a
4925 # backslash before a quote anywhere means backslash, the escape this module
4926 # always used; else two quotes in a row mean a quote; else backslash. An
4927 # empty quoted field ("") reads the same either way. Stops at the first
4928 # backslash-quote, else reads the file once.
4929 sub _csv_escape_char
4930 269 ▶{
Subroutine _csv_escape_char: called CC=6 SCAR=17.9
4931 269 my ($self, $file) = @_;
4932  
4933 269 my $fh;
4934 53 ▶ 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(0x556a8da15268)'; $^H{'no Fatal'} = 'HASH(0x556a8d7b7c08)'; } open $fh, "<:raw", $file } or return "\\" 268 1 269
4935 268 my $doubled = 0;
4936 268 ▶ while(my $line = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 1399 262 1661
4937 1399 ▶ if($line =~ /\\"/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\\"/) 6 1393 1399
4938 6 close $fh;
4939 6 return '\\';
4940 }
4941 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
4942 }
4943 262 close $fh;
4944 262 ▶ return $doubled ? '"' : '\\';
Branch: 1 branch
BranchTrueFalseTotal
$doubled ? : 4 258 262
4945 }
4946  
4947 # Determine whether a given file is a valid Berkeley DB file.
4948 # It combines a fast preliminary check with a more thorough validation step for accuracy.
4949 # It looks for the magic number at both byte 0 and byte 12.
4950 307 ▶sub _is_berkeley_db {
Subroutine _is_berkeley_db: called CC=4 SCAR=15.4
4951 307 my ($self, $file) = @_;
4952  
4953 # Step 1: Check magic number
4954 # no autodie here: the file may not exist, and we want a silent false return
4955 307 my $fh;
4956 53 ▶ 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(0x556a8da156b8)'; $^H{'no Fatal'} = 'HASH(0x556a8da15658)'; } open $fh, "<", $file } or return 0 2 305 307
4957 2 binmode $fh;
4958  
4959 2 my $is_db = $self->_has_bdb_magic($fh);
4960 2 close $fh;
4961  
4962 2 ▶ if($is_db) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_db) 0 2 2
4963 # Step 2: Attempt to open as Berkeley DB
4964  
4965 0 require DB_File;
4966  
4967 0 my %bdb;
4968 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
4969 # untie %db;
4970 0 $self->{'berkeley'} = \%bdb;
4971 0 return 1; # Successfully identified as a Berkeley DB file
4972 }
4973 }
4974 2 return 0;
4975 }
4976  
4977 # Check for Berkeley DB magic bytes at offsets 0 and 12.
4978 # Returns true if either location contains a recognised BDB magic number.
4979 8 ▶sub _has_bdb_magic {
Subroutine _has_bdb_magic: called CC=7 SCAR=19.5
4980 8 my ($self, $fh) = @_;
4981  
4982 # Offset 0: 32-bit magic number in both endian forms
4983 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
4984 7 my %magic = map { $_ => 1 } (0x00061561, 0x00053162, 0x00042253, 0x00052444);
4985 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
4986  
4987 # Offset 12: Btree magic prefix (fallback for some BDB file variants)
4988 4 ▶ seek $fh, 12, 0 or return 0;
Branch: 1 branch
BranchTrueFalseTotal
&Database::Abstraction::seek($fh, 12, 0) or return 0 4 0 4
4989 4 ▶ read($fh, $buf, 4) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
&Database::Abstraction::read($fh, \$buf, 4) or return 0 3 1 4
4990 3 my $hex12 = substr(unpack('H*', $buf), 0, 4);
4991 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
4992 }
4993  
4994 # Return true if $host refers to the current machine (localhost, loopback, or
4995 # the machine's own hostname). Strips an optional user@ prefix first.
4996 # Used by new() and _open() to decide whether to use local file access instead
4997 # of File::Slurp::Remote, so the caller never loads that module unnecessarily.
4998 77 ▶sub _is_local_host {
Subroutine _is_local_host: called CC=3 SCAR=11.0
4999 77 my ($self, $host) = @_;
5000  
5001 # Strip optional user@ prefix. \A (not ^) so a newline cannot split the match.
5002 77 (my $bare = $host) =~ s/\A[^@]*@//;
5003  
5004 # \z anchors at true end-of-string; $ would match before a trailing newline.
5005 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
5006  
5007 47 require Sys::Hostname;
5008 47 my $me = lc(Sys::Hostname::hostname());
5009 47 my $lc_bare = lc($bare);
5010 47 ▶ return 1 if $lc_bare eq $me;
Branch: 1 branch
BranchTrueFalseTotal
if $lc_bare eq $me 8 39 47
5011  
5012 # Match on short hostname: 'mybox' matches 'mybox.example.com' and vice-versa
5013 39 (my $me_short = $me) =~ s/\..*//;
5014 39 (my $bare_short = $lc_bare) =~ s/\..*//;
5015 39 return($bare_short eq $me_short);
5016 }
5017  
5018 # Determine whether a given file is a DBM::Deep file by checking its magic bytes.
5019 # The standard DBM::Deep magic is 'DPDB' (0x44 0x50 0x44 0x42); 'DPDP' (0x44 0x50 0x44 0x50)
5020 # is also accepted for compatibility with files created by alternative tooling.
5021 # Returns 1 if the first 4 bytes match a known DBM::Deep signature, 0 otherwise.
5022 20 ▶sub _is_deep_db {
Subroutine _is_deep_db: called CC=5 SCAR=16.1
5023 20 my ($self, $file) = @_;
5024  
5025 20 my $fh;
5026 53 ▶ 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(0x556a8da1fab0)'; $^H{'no Fatal'} = 'HASH(0x556a8da1fa50)'; } open $fh, "<", $file } or return 0 16 4 20
5027 16 binmode $fh;
5028 16 my $n = read($fh, my $magic, 4);
5029 16 close $fh;
5030 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
5031  
5032 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
5033 }
5034  
5035 # Log and remember a message
5036 sub _log
5037 3286 ▶{
Subroutine _log: called CC=3 SCAR=11.8
5038 3286 my ($self, $level, @messages) = @_;
5039  
5040 # FIXME: add caller's function
5041 # if(($level eq 'warn') || ($level eq 'notice')) {
5042 3286 push @{$self->{'messages'}}, { level => $level, message => join('', grep defined, @messages) };
5043 # }
5044  
5045 3286 ▶ if(scalar(@messages) && (my $logger = $self->{'logger'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @messages and my $logger = $$self{"logger"}) 3286 0 3286
Condition33%1/3
scalar @messages and my $logger = $$self{"logger"}
!ll&&!rl&&r
003286
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
5046 3286 $self->{'logger'}->$level(join('', grep defined, @messages));
5047 }
5048 }
5049  
5050 2399 ▶sub _debug {
Subroutine _debug: called CC=1 SCAR=0.0
5051 2399 my $self = shift;
5052 2399 $self->_log('debug', @_);
5053 }
5054  
5055 880 ▶sub _trace {
Subroutine _trace: called CC=1 SCAR=0.0
5056 880 my $self = shift;
5057 880 $self->_log('trace', @_);
5058 }
5059  
5060 # Emit a warning message somewhere
5061 1 ▶sub _warn {
Subroutine _warn: called CC=1 SCAR=0.0
5062 1 my $self = shift;
5063 1 my $params = Params::Get::get_params('warning', \@_);
5064  
5065 1 $self->_log('warn', $params->{'warning'});
5066 1 Carp::carp(join('', grep defined, $params->{'warning'}));
5067 }
5068  
5069 # Die
5070 6 ▶sub _fatal {
Subroutine _fatal: called CC=1 SCAR=0.0
5071 6 my $self = shift;
5072 6 my $params = Params::Get::get_params('warning', \@_);
5073  
5074 6 $self->_log('error', $params->{'warning'});
5075 6 Carp::croak(join('', grep defined, $params->{'warning'}));
5076 }
5077  
5078 =head1 AUTHOR
5079  
5080 Nigel Horne, C<< <njh at nigelhorne.com> >>
5081  
5082 =head1 SUPPORT
5083  
5084 This module is provided as-is without any warranty.
5085  
5086 Please report any bugs or feature requests to C<bug-database-abstraction at rt.cpan.org>,
5087 or through the web interface at
5088 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Database-Abstraction>.
5089 I will be notified, and then you'll
5090 automatically be notified of progress on your bug as I make changes.
5091  
5092 =head1 MESSAGES
5093  
5094 The table below lists every error that the module can croak or carp, what
5095 triggers it, and how to resolve it.
5096  
5097 =over 4
5098  
5099 =item C<< I<Class>: abstract class >>
5100  
5101 Direct instantiation of C<Database::Abstraction> was attempted.
5102 Create a subclass and instantiate that instead.
5103  
5104 =item C<< I<Class>: where are the files? >>
5105  
5106 Neither C<directory> nor C<dsn> was supplied to C<new()>.
5107  
5108 =item C<< I<Class>: I</path> is not a directory >>
5109  
5110 The C<directory> argument exists on disk but is not a directory.
5111  
5112 =item C<< I<Class>: cannot connect: I<$DBI::errstr> >>
5113  
5114 DBI failed to connect to the given C<dsn>. Check credentials and host.
5115  
5116 =item C<< Can't find a file called 'I<name>' for the table I<T> in I<dir> >>
5117  
5118 None of the probe extensions (C<.sql>, C<.sqlite>, C<.sqlite3>, C<.psv>, C<.tsv>, C<.csv>, C<.xlsx>, C<.db>, C<.xml>)
5119 matched in C<directory>.
5120  
5121 =item C<< I<Class>: prepare failed: I<$errstr> >>
5122  
5123 C<prepare_cached()> returned false. Usually a syntax error in an internally
5124 built query; file a bug if you see this from a normal API call.
5125  
5126 =item C<< _build_where_conditions: unsafe column name 'I<name>' >>
5127  
5128 A criteria key contained characters outside C<[A-Za-z0-9_.]>.
5129 This is a SQL-injection guard. Use only valid SQL identifier characters.
5130  
5131 =item C<< join: missing "table" >> / C<< join: missing "on" condition >>
5132  
5133 A join spec hashref is incomplete. Both C<table> and C<on> are required.
5134  
5135 =item C<< Invalid JOIN type: I<TYPE> >>
5136  
5137 C<type> in a join spec was not one of C<INNER LEFT RIGHT FULL CROSS>.
5138  
5139 =item C<< I<Class>: Unknown column I<col> >> / C<< I<Class>: AUTOLOAD disabled >>
5140  
5141 An AUTOLOAD call was made for a column that does not exist, or AUTOLOAD
5142 was disabled with C<< auto_load => 0 >>.
5143  
5144 =item C<< Usage: set_logger(logger => $logger) >>
5145  
5146 C<set_logger()> was called without a C<logger> argument.
5147  
5148 =item C<< Usage: execute(query => $query) >>
5149  
5150 C<execute()> was called without a C<query> argument.
5151  
5152 =item C<< XML slurp: I<...> is not yet supported >>
5153  
5154 The XML file structure is too complex for slurp mode.
5155 Use C<< max_slurp_size => 0 >> to force the DBI/XMLSimple SQL path.
5156  
5157 =item C<< I<Class>: I<method> is meaningless on a NoSQL database >>
5158  
5159 A relational method (C<selectall_arrayref>, C<count>, C<execute>, etc.)
5160 was called on a BerkeleyDB backend, which only supports key-value lookup
5161 via C<fetchrow_hashref>.
5162  
5163 =item C<< I<Class>: aggregate: 'measures' must be a non-empty arrayref >>
5164  
5165 C<aggregate()> was called without a C<measures> arrayref, or with an empty one.
5166  
5167 =item C<< I<Class>: aggregate: measure must be a hashref, got I<ref> >>
5168  
5169 An element of the C<measures> arrayref is not a hashref.
5170  
5171 =item C<< I<Class>: aggregate: unknown measure function 'I<fn>' >>
5172  
5173 C<fn> must be one of C<sum>, C<avg>, C<min>, C<max>, C<count>, C<count_distinct>,
5174 C<median>, C<stddev>.
5175  
5176 =item C<< I<Class>: aggregate: measure column is required for function 'I<fn>' >>
5177  
5178 C<col> was omitted for a function that requires it. Only plain C<count> (COUNT(*)) accepts a missing C<col>.
5179  
5180 =item C<< I<Class>: aggregate: unsafe measure column 'I<col>' >>
5181  
5182 The C<col> value is not a valid SQL identifier.
5183  
5184 =item C<< I<Class>: aggregate: measure 'as' is required >>
5185  
5186 The C<as> alias was missing from a measure hashref.
5187  
5188 =item C<< I<Class>: aggregate: unsafe measure alias 'I<as>' >>
5189  
5190 The C<as> value is not a valid SQL identifier.
5191  
5192 =item C<< I<Class>: aggregate: duplicate measure alias 'I<as>' >>
5193  
5194 Two measure hashrefs share the same C<as> alias.
5195  
5196 =item C<< I<Class>: aggregate: measure alias 'I<as>' collides with a group-by column >>
5197  
5198 A measure alias duplicates a name in the C<by> list.
5199  
5200 =item C<< I<Class>: aggregate: 'by' must be an arrayref of column names >>
5201  
5202 The C<by> parameter was not an arrayref.
5203  
5204 =item C<< I<Class>: aggregate: unsafe group-by column 'I<col>' >>
5205  
5206 A C<by> element is not a valid SQL identifier.
5207  
5208 =item C<< I<Class>: aggregate: having key 'I<key>' is not a group-by column or measure alias >>
5209  
5210 A C<having> key does not match any C<by> column name or measure C<as> alias.
5211  
5212 =item C<< I<Class>: aggregate: sort_by names 'I<name>', which is not a group-by column or measure alias >>
5213  
5214 The C<sort_by> column is not one of the C<by> columns or measure aliases.
5215  
5216 =item C<< I<Class>: aggregate: cannot aggregate a JOIN on the I<backend> backend >>
5217  
5218 C<join> was passed to C<aggregate()> on a slurp-only backend that has no DBI handle.
5219  
5220 =item C<< Database::Abstraction::Query: count() is not available once measure() has been called >>
5221  
5222 C<count()> was called on a query builder that has measures set. Use C<all()> and check C<scalar @{$rows}>.
5223  
5224 =back
5225  
5226 =head1 COMMON PITFALLS
5227  
5228 The following mistakes cause unexpected behaviour in common usage.
5229 Read this section before filing a bug report.
5230  
5231 =over 4
5232  
5233 =item B<Default CSV separator is C<!>, not C<,>>
5234  
5235 For historical reasons the module defaults to bang (C<!>) as the
5236 field separator for CSV files. Standard RFC 4180 comma-separated
5237 files require you to pass C<< sep_char => ',' >> in your subclass
5238 constructor.
5239  
5240 sub new {
5241 my ($class, %args) = @_;
5242 return $class->SUPER::new(sep_char => ',', %args);
5243 }
5244  
5245 =item B<Primary key column is named C<entry>, not C<key>>
5246  
5247 The default primary-key column name is C<entry> because C<key> is
5248 a reserved word in SQL. If your data uses a different column name
5249 (e.g. C<id>, C<customer_id>), pass C<< id => 'customer_id' >> to
5250 C<new()>.
5251  
5252 =item B<Duplicate primary keys silently overwrite earlier rows>
5253  
5254 In slurp mode the entire data file is loaded into a Perl hash keyed
5255 by the C<entry> column. If two rows share the same key value the
5256 second row replaces the first. To keep duplicates either disable
5257 slurp with C<< max_slurp_size => 0 >> or switch to a C<no_entry>
5258 schema.
5259  
5260 =item B<Operator-hash criteria do not work on no-DBI backends>
5261  
5262 No-DBI backends (XLSX, DBM::Deep, JSON, HTML URL, Redis) have no SQL
5263 engine. Criteria that use operator hashes (e.g.
5264 C<< score => { '>=' => 80 } >>) trigger the SQL path and will croak
5265 with a "meaningless on a NoSQL database" error. Use simple scalar
5266 criteria (C<< score => 80 >>) on these backends.
5267  
5268 =item B<Read-only results: do not modify returned hashrefs>
5269  
5270 Unless you pass C<< no_fixate => 1 >>, every hashref returned by
5271 C<selectall_arrayref>, C<fetchrow_hashref>, and similar methods is
5272 made read-only by C<Data::Reuse>. Attempting to assign a value to
5273 a key in the returned hashref will throw an exception. If you need
5274 to modify a row, either copy it first (C<my %row = %{$orig_row}>) or
5275 construct the object with C<< no_fixate => 1 >>.
5276  
5277 =item B<C<where()> calls in the query builder use AND semantics>
5278  
5279 Each call to C<< $q->where(...) >> adds an additional required
5280 condition. Two separate C<where()> calls do NOT produce OR
5281 semantics. To express OR, pass C<< -or => [...] >> inside a single
5282 C<where()> call:
5283  
5284 # Wrong: this is AND, not OR
5285 $q->where(status => 'active')->where(status => 'pending');
5286  
5287 # Correct: OR grouping inside one where() call
5288 $q->where(-or => [{ status => 'active' }, { status => 'pending' }]);
5289  
5290 =item B<C<aggregate()> C<sort_by> must name a grouped or aliased column>
5291  
5292 The C<sort_by> parameter for C<aggregate()> only accepts column names
5293 from the C<by> list or measure C<as> aliases. You cannot sort
5294 aggregate results by a raw data column that is not part of the group.
5295 This restriction applies equally to the C<< ->order_by() >> call on a
5296 query builder that has C<measure()> methods set.
5297  
5298 =item B<C<sort_by> is not an argument to the query builder's C<all()>>
5299  
5300 When using the fluent query builder to build an aggregate query, set
5301 the sort column via C<< ->order_by('col') >> before calling
5302 C<< ->all() >>. Passing C<< ->all(sort_by => 'col') >> has no
5303 effect because the C<all()> terminal method ignores extra arguments.
5304  
5305 =item B<C<Params::Get> positional mapping with C<no_entry = 0>>
5306  
5307 When C<no_entry> is false (the default), the first positional argument
5308 to C<selectall_arrayref> and C<fetchrow_hashref> is silently mapped to
5309 the C<entry> key. Passing an operator-hash criteria in that position
5310 (e.g. C<selectall_arrayref(status => { '!=' => 'x' })>) causes
5311 C<status> to be treated as the entry value rather than a column name,
5312 which will produce wrong results. Always pass a hashref of criteria
5313 as a single reference, or use C<no_entry => 1> in your subclass.
5314  
5315 =back
5316  
5317 =head1 ENCODING
5318  
5319 =over 4
5320  
5321 =item B<Column names> must match the pattern C<[a-zA-Z_][a-zA-Z0-9_.]*>.
5322 Only ASCII letters, digits, underscores, and dots (for qualified names
5323 such as C<table.column>) are accepted. Non-ASCII Unicode characters
5324 in column names will cause a croak with an "unsafe column name" error.
5325  
5326 =item B<Column values> (data stored in your rows) are passed through
5327 unchanged. Full UTF-8 strings, emoji, and any valid Perl string are
5328 safe as values in criteria and are stored and returned as-is. The
5329 exact encoding depends on your backend:
5330  
5331 =over 4
5332  
5333 =item * B<SQLite / DBI backends> -- DBD::SQLite stores strings as
5334 UTF-8 internally. Enable C<< sqlite_unicode => 1 >> in your DSN
5335 or connect attributes if you want Perl to receive decoded Unicode
5336 scalars rather than raw UTF-8 bytes.
5337  
5338 =item * B<CSV / PSV / TSV> -- Text::CSV and DBD::CSV pass bytes
5339 through unchanged. If your file is UTF-8-encoded, strings are
5340 returned as UTF-8 byte strings. You may need to decode them with
5341 C<Encode::decode('UTF-8', $val)> in your application.
5342  
5343 =item * B<JSON> -- JSON::MaybeXS decodes JSON strings to Perl Unicode
5344 scalars automatically. UTF-8 and emoji in JSON values are fully
5345 supported.
5346  
5347 =item * B<XML> -- XML::Simple decodes the file with the XML encoding
5348 declaration. UTF-8 encoded XML (the default) produces Perl Unicode
5349 scalars.
5350  
5351 =item * B<XLSX> -- Spreadsheet::ParseXLSX decodes strings to Perl
5352 Unicode scalars. Emoji in cell values are fully supported.
5353  
5354 =item * B<HTML URL> -- LWP::UserAgent fetches bytes; HTML::TableExtract
5355 returns them as-is. Decode with Encode if the page is UTF-8.
5356  
5357 =back
5358  
5359 =item B<File paths> are handled by C<File::Spec::catfile> and work
5360 on any platform. On Linux and macOS, UTF-8 directory and file names
5361 are fully supported.
5362  
5363 =back
5364  
5365 =head1 KNOWN LIMITATIONS
5366  
5367 =over 4
5368  
5369 =item *
5370  
5371 B<Read-only.> No INSERT, UPDATE, or DELETE is provided. C<execute()>
5372 runs raw read-only SQL.
5373  
5374 =item *
5375  
5376 B<Default CSV separator is C<!>>, not C<,>, for historical reasons.
5377 Pass C<< sep_char => ',' >> for standard RFC 4180 files.
5378  
5379 =item *
5380  
5381 B<Primary-key column is named C<entry>>, not C<key>, because C<key>
5382 is a SQL reserved word. Override with the C<id> parameter.
5383  
5384 =item *
5385  
5386 B<XML slurp is limited.> Only simple flat XML structures are supported
5387 in slurp mode. Multi-key or deeply nested documents will croak.
5388 Force SQL mode with C<< max_slurp_size => 0 >> if slurp fails.
5389  
5390 =item *
5391  
5392 B<Unique key assumption in slurp mode.> Duplicate values in the key
5393 column silently overwrite earlier rows. Disable slurp with
5394 C<< max_slurp_size => 0 >> if duplicates are expected.
5395  
5396 =item *
5397  
5398 B<BerkeleyDB does not support joins or the chained query builder.>
5399  
5400 =item *
5401  
5402 B<Column names must be valid SQL identifiers> (letters, digits,
5403 underscores, and a single dot for C<table.column> join notation).
5404 Other characters will cause a croak.
5405  
5406 =item *
5407  
5408 B<count() cache is opportunistic.> Count results are served from cache
5409 only when a prior C<selectall_arrayref()> or C<count()> call with the
5410 same criteria has already populated it.
5411  
5412 =back
5413  
5414 =head1 SEE ALSO
5415  
5416 =over 4
5417  
5418 =item * L<Database::Abstraction::Query> - chained query builder
5419  
5420 =item * L<Configure an Object at Runtime|Object::Configure>
5421  
5422 =item * L<JSON::MaybeXS> - JSON backend (optional; install for C<.json> support)
5423  
5424 =item * L<Test Dashboard|https://nigelhorne.github.io/Database-Abstraction/coverage/>
5425  
5426 =back
5427  
5428 =head1 FORMAL SPECIFICATION
5429  
5430 The following section uses Z-notation to describe the key state
5431 transitions and invariants for the module. Z is a formal
5432 specification language based on set theory and predicate logic.
5433 Unicode is used here as permitted by the documentation skill.
5434  
5435 =head2 Database object state
5436  
5437 State == [
5438 data : TABLE_NAME --> (ENTRY --> ROW) | seq ROW | undef,
5439 dbh : TABLE_NAME --> DBI_HANDLE | undef,
5440 type : Str | undef,
5441 base_crit : CRITERIA,
5442 _columns : seq Str | undef,
5443 _schema : NAME --> COL_INFO | undef,
5444 _destroyed : Bool
5445 ]
5446  
5447 Initial state S0 == [
5448 data? = undef,
5449 dbh? = undef,
5450 type? = undef,
5451 base_crit? = {},
5452 _columns? = undef,
5453 _schema? = undef,
5454 _destroyed? = false
5455 ]
5456  
5457 =head2 _open_table
5458  
5459 _open_table ___________________________________________
5460 DeltaState
5461 class? : CLASS
5462 dir? : DIRPATH | undef
5463 ────────────────────────────────────────────────────
5464 pre: _destroyed = false
5465 pre: dbh(table) = undef AND data(table) = undef
5466 post: (EXISTS f : FILE_FORMATS WITH f.probe(dir) = true
5467 IMPLIES (f.slurp? IMPLIES data'(table) != undef)
5468 AND (f.dbi? IMPLIES dbh'(table) != undef))
5469  
5470 =head2 selectall_arrayref
5471  
5472 selectall_arrayref __________________________________
5473 XiState (read-only; state unchanged except cache)
5474 criteria? : CRITERIA
5475 ────────────────────────────────────────────────────
5476 pre: _destroyed = false
5477 result == (data != undef AND simple(criteria)
5478 IMPLIES { r : data | match(r, criteria) }
5479 ELSE dbh != undef
5480 IMPLIES SQL_SELECT(dbh, criteria))
5481 post: result : seq ROW UNION {undef}
5482  
5483 =head2 aggregate
5484  
5485 aggregate ____________________________________________
5486 XiState
5487 by? : seq COLNAME
5488 measures? : seq MEASURE_SPEC
5489 criteria? : CRITERIA
5490 ────────────────────────────────────────────────────
5491 pre: measures != empty
5492 pre: FORALL m : measures WITH m.as NOT IN by
5493 pre: sort_by != undef IMPLIES sort_by IN ran(by) UNION aliases(measures)
5494 result == (dbh != undef
5495 IMPLIES SQL_GROUP_BY(dbh, by, measures, criteria)
5496 ELSE PERL_FOLD(selectall_arrayref(criteria), by, measures))
5497 post: result : seq ROW (keys = by UNION aliases(measures))
5498 post: FORALL r : result WITH
5499 r.count != undef IMPLIES r.count >= 0
5500 AND r.sum = undef IMPLIES no rows in that group
5501  
5502 =head2 DESTROY
5503  
5504 DESTROY ______________________________________________
5505 DeltaState
5506 ────────────────────────────────────────────────────
5507 post: _destroyed' = true
5508 post: dbh' = undef (DBI handles disconnected)
5509 post: data' = undef
5510 post: _columns' = undef
5511 post: _schema' = undef
5512  
5513 =head1 STATE DIAGRAM
5514  
5515 The following ASCII diagram shows every valid state the object can
5516 occupy and the transitions between them. Transitions are labelled
5517 with the method call or event that triggers them. Actions are shown
5518 in parentheses.
5519  
5520 .-----------------------------------------------------------.
5521 | S1: CONSTRUCTED |
5522 | dbh=undef, data=undef, type=undef |
5523 '---.-------.-------.-------.-------.-----.---.-------------'
5524 | | | | | | |
5525 | first query call triggers _open_table()
5526 | | | | | | |
5527 v v v v v v v
5528 .------. .------. .------. .------. .--. .--. .--.
5529 | S2 | | S3 | | S4 | | S5 | |S6| |S7| |S8|
5530 | DBI | | CSV | | XML | | JSON | |Xls| |Bk| |Dp|
5531 '---^--' '--^---' '--^---' '--^---' '-^-' '-^-' '-^-'
5532 | | | | | | | |
5533 | | '-------'-------' | | |
5534 | | slurp path | | |
5535 | '-----------+---------------' | |
5536 | | | |
5537 | (data populated, | |
5538 | _columns/_schema undef) | |
5539 | | |
5540 | (dbh populated, | |
5541 | data undef) | |
5542 | | |
5543 +-------+--------+-----------+----------+ |
5544 | | | |
5545 selectall fetchrow aggregate fetchrow
5546 count _hashref query->all _hashref
5547 each_row AUTOLOAD AUTOLOAD AUTOLOAD
5548 | | | |
5549 v v v v
5550 .-----------------------------------------------------------.
5551 | (result returned to caller) |
5552 | state is unchanged; only cache may be updated |
5553 '-----------------------------------------------------------'
5554 |
5555 DESTROY (or object goes out of scope)
5556 |
5557 v
5558 .-----------------------------------------------------------.
5559 | S_DEAD: DESTROYED |
5560 | _destroyed=true; all handles disconnected; |
5561 | temp files unlinked; _remote_tmpdir removed |
5562 '-----------------------------------------------------------'
5563  
5564 State labels:
5565 S1 CONSTRUCTED - new() returned; no I/O done yet (lazy open)
5566 S2 DBI - live DBI handle (SQLite file, DSN, DBD::CSV)
5567 S3 CSV_SLURP - small CSV/PSV/TSV/gzip-CSV slurped into RAM hash
5568 S4 XML_SLURP - XML file slurped into RAM hash
5569 S5 JSON_SLURP - JSON file slurped into RAM hash
5570 S6 XLSX_SLURP - XLSX file slurped (type='XLSX', no DBI handle)
5571 S7 BERKELEYDB - BerkeleyDB key-value file open (berkeley flag set)
5572 S8 DEEP_SLURP - DBM::Deep file slurped into plain RAM hash
5573  
5574 Blocked transitions (croak before state changes):
5575 S1 -> any if constructor arguments are invalid
5576 (unsafe id/table/host/url)
5577 S* -> S* aggregate() with join on S3/S4/S5/S6/S7/S8
5578 (no DBI handle)
5579 S7 -> S* join() or select()-projection on BerkeleyDB
5580 S8 -> S* join() on DBM::Deep
5581  
5582 =head1 LICENSE AND COPYRIGHT
5583  
5584 Copyright 2015-2026 Nigel Horne.
5585  
5586 Usage is subject to the GPL2 licence terms.
5587 If you use it,
5588 please let me know.
5589  
5590 =cut
5591  
5592 53 1;
↑ Summary Abstraction/Query.pm »