Join.pm

filter: Statementstmt 94.3% 1463 / 1551 Branchbran 84.4% 655 / 776 Conditioncond 72.5% 405 / 558 MC/DCmcdc 47.5% 156 / 328 Subroutinesub 97.0% 100 / 103 Podpod 100% 19 / 19 totaltotal 83.9% 2798 / 3335 CC 681 SCAR 38.1
CC
681
Cov
87%
_match_having_criterion
187.2
_joined_query_array
105.2
_sqlite_join
67.9
CRAP 45.4
↑ Summary Join/Catalog.pm »
1 package Database::Join;
2  
3 # ABSTRACT: Combined view across two or more Database::Abstraction objects
4  
5 29 ▶use 5.010001;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 29 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 29 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 29 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 29 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 29 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 29 ▶use List::Util qw(max);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 29 ▶use Log::Abstraction;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 29 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 29 ▶use Scalar::Util qw(blessed looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 29 ▶use Object::Configure;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 29 ▶use Params::Get qw(get_params);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 29 ▶use Params::Validate::Strict qw(validate_strict);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 29 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 # Named-pair keys accepted by add_database; kept here so the guard and the
22 # validate_strict schema cannot silently diverge.
23 29 Readonly::Array my @_ADD_DB_KEYS => qw(database join_column filter remove_columns);
24  
25 # SQL comparison operators that are safe to interpolate into WHERE clauses.
26 # Scalar-binding operators: the value is always passed as a bind param (?), so
27 # no quoting or escaping is required on the value side. LIKE and NOT LIKE are
28 # safe for the same reason — the pattern is bound, not interpolated.
29 29 Readonly::Hash my %SAFE_SQL_OPS => map { $_ => 1 } ('>', '<', '>=', '<=', '!=', '=', 'LIKE', 'NOT LIKE');
30  
31 # List-membership operators whose criterion value is an arrayref.
32 # Each element is bound as a separate ?, so injection is impossible.
33 # IN with an empty list → WHERE 1=0 (no rows match, correct SQL semantics).
34 # NOT IN with an empty list → no WHERE term (all rows match, correct semantics).
35 29 Readonly::Hash my %SAFE_LIST_OPS => map { $_ => 1 } ('IN', 'NOT IN');
36  
37 # Nullability operators: no bind parameter. The hashref value is ignored —
38 # any value (undef, 1, ...) signals intent; only the key selects the operator.
39 # A bare undef criterion value (col => undef) also generates IS NULL.
40 29 Readonly::Hash my %SAFE_NOARG_OPS => map { $_ => 1 } ('IS NULL', 'IS NOT NULL');
41  
42 # Key pushdown (array backend): the most primary keys that are passed to a
43 # secondary database as one { -in => [...] } criterion. Each key is a bind
44 # parameter, and SQLite builds before 3.32 allow at most 999 in a statement.
45 # Past this, reading the whole secondary is no worse than several queries.
46 29 Readonly::Scalar my $MAX_PUSHDOWN_KEYS => 999;
47  
48 # Database::Abstraction's spelling of SQL IN. It croaks on 'IN'.
49 29 Readonly::Scalar my $DA_IN_OP => '-in';
50  
51 # Valid aggregate functions for aggregate(). Lower-cased at validation time.
52 29 Readonly::Hash my %AGGREGATE_FNS => map { $_ => 1 } qw(sum avg min max count count_distinct);
53  
54 # Valid operator names for the mandatory_filters {col, op, val} predicate format.
55 29 Readonly::Hash my %MANDATORY_FILTER_OPS => map { $_ => 1 }
56 qw(eq ne lt lte gt gte like contains);
57  
58 # SQL operator string for each mandatory_filter op (used in _sqlite_criteria).
59 29 Readonly::Hash my %MANDATORY_OP_SQL => (
60 eq => '=',
61 ne => '!=',
62 lt => '<',
63 lte => '<=',
64 gt => '>',
65 gte => '>=',
66 like => 'LIKE',
67 contains => 'LIKE',
68 );
69  
70 29 ▶use version; our $VERSION = version->declare('0.011.2');
Subroutine BEGIN: called CC=1 SCAR=0.0
71  
72 # Package-level cache for threads availability. undef = not yet checked;
73 # 1 = available; 0 = not available. Checked lazily on the first parallel
74 # query and never re-evaluated (require is cached in %INC after success).
75 29 my $HAS_THREADS;
76  
77 # ---------------------------------------------------------------------------
78 # All user-facing strings route through this dictionary. Supply an i18n
79 # object with a translate($key, @sprintf_args) method to localise them.
80 # ---------------------------------------------------------------------------
81 29 Readonly::Hash my %MESSAGES => (
82 error_no_databases => 'At least one Database::Abstraction object is required',
83 error_invalid_db => 'databases[%d] does not support the selectall_arrayref/columns interface',
84 error_join_col_missing => 'join_column "%s" is absent from databases[%d] (%s)',
85 error_col_conflict => 'Column "%s" exists in multiple databases; use the owning database directly or rename the column',
86 error_remove_join_col => 'Cannot remove join_column "%s"; it is required for the join',
87 warn_unknown_column => 'Column "%s" is not present in any configured database; criterion ignored',
88 error_join_criterion => 'join => criteria are not supported on Database::Join (SQL JOINs target a single DA; use multiple DAs in the databases => [] constructor instead)',
89 error_query_unsupported => 'query() chained builder is not supported on Database::Join (Database::Abstraction::Query targets a single DA, not the merged view); use selectall_arrayref, selectall_array, fetchrow_hashref, count, or each_row instead',
90 error_group_by_unsupported => 'group_by() fluent chain is not supported on Database::Join (Database::Abstraction::Query targets a single DA, not the merged view); use aggregate() instead',
91 error_execute_unsupported => 'execute() raw SQL is not supported on Database::Join',
92 error_unknown_message => 'Unknown message key "%s"',
93 error_invalid_prefix => 'collision_prefix[%d] must be a plain string, not a reference; passing a reference would leak a heap address into column names',
94 error_invalid_backend => 'backend must be "array", "sqlite", or "auto"; got "%s"',
95 error_sqlite_connect => 'Failed to open temporary SQLite database for join backend: %s',
96 warn_schema_type_mismatch => 'column "%s" has type "%s" in database[%d] but type "%s" in database[%d]; use collision_prefix to preserve both values without silent type coercion',
97 error_invalid_callback => 'each_row: first argument must be a code reference',
98 error_aggregate_measures_required => 'aggregate: "measures" must be a non-empty arrayref',
99 error_aggregate_measure_ref => 'aggregate: measure must be a hashref, got %s',
100 error_aggregate_fn_unknown => 'aggregate: unknown measure function "%s"',
101 error_aggregate_col_required => 'aggregate: measure column is required for function "%s"',
102 error_aggregate_col_unknown => 'aggregate: column "%s" is not in the merged view',
103 error_aggregate_as_required => 'aggregate: measure "as" is required',
104 error_aggregate_as_invalid => 'aggregate: measure alias "%s" must be a plain word',
105 error_aggregate_as_duplicate => 'aggregate: duplicate measure alias "%s"',
106 error_aggregate_as_collision => 'aggregate: measure alias "%s" collides with a group-by column',
107 error_aggregate_by_invalid => 'aggregate: "by" must be an arrayref of column names',
108 error_aggregate_having_key => 'aggregate: having key "%s" is not a group-by column or measure alias',
109 error_aggregate_having_operator => 'aggregate: operator "%s" in having for key "%s" is not supported',
110 warn_aggregate_sort_key => 'aggregate: sort_by names "%s", which is not a group-by column or measure alias',
111 warn_aggregate_non_numeric => 'aggregate: column "%s" has %d non-numeric value(s), skipped, e.g. "%s"',
112 error_mandatory_filter_ref => 'mandatory_filters[%d] must be a hashref with col, op, and val keys',
113 error_mandatory_filter_col => 'mandatory_filters[%d]: column "%s" is not in the merged view',
114 error_mandatory_filter_op => 'mandatory_filters[%d]: op "%s" is not supported; use eq, ne, lt, lte, gt, gte, like, or contains',
115 );
116  
117 =head1 NAME
118  
119 Database::Join - Read-only combined view across two or more Database::Abstraction objects
120  
121 =head1 VERSION
122  
123 Version 0.011.2
124  
125 =head1 SYNOPSIS
126  
127 B<Basic two-database join>
128  
129 use Database::Join;
130  
131 # Step 1: create each component database the normal way
132 # See Database::Abstraction
133 my $customers = Database::Customers->new(directory => '/data');
134 my $loyalty = Database::Loyalty->new(directory => '/data');
135  
136 # Step 2: combine them on the shared key column 'entry'
137 my $join = Database::Join->new(
138 databases => [ $customers, $loyalty ],
139 join_column => 'entry',
140 );
141  
142 # Step 3: query exactly as you would a single Database::Abstraction object
143 my $all_rows = $join->selectall_arrayref();
144 my $vip_rows = $join->selectall_arrayref(tier => 'gold');
145 my $one_row = $join->fetchrow_hashref(entry => 'C001');
146 my $total = $join->count();
147 my $col_names = $join->columns();
148  
149 B<Hiding internal columns>
150  
151 my $join = Database::Join->new(
152 databases => [ $customers, $loyalty ],
153 join_column => 'entry',
154 remove_columns => [ 'internal_id', 'audit_ts' ],
155 );
156 # 'internal_id' and 'audit_ts' never appear in results or columns()
157  
158 B<join_map: when the key column has different names in each database>
159  
160 # $cities (index 0) has a column called 'statecode' -- matches join_column
161 # $stnames (index 1) has a column called 'entry' -- different name
162  
163 my $join = Database::Join->new(
164 databases => [ $cities, $stnames ],
165 # index 0 index 1
166 join_column => 'statecode',
167 join_map => { 1 => 'entry' }, # index 1 calls its join key 'entry'
168 );
169  
170 # All returned rows use 'statecode'; 'entry' is never exposed
171 my $rows = $join->selectall_arrayref();
172  
173 B<filters: permanently restrict a database's visible rows>
174  
175 # Only show orders placed more than 60 days ago, without repeating
176 # the criterion on every query call.
177 my $join = Database::Join->new(
178 databases => [ $customers, $orders ],
179 join_column => 'entry',
180 filters => { 1 => { age_days => { '>' => 60 } } },
181 );
182  
183 my $rows = $join->selectall_arrayref(); # all old orders
184 my $vip = $join->selectall_arrayref(tier => 'gold'); # old + gold tier
185  
186 B<Inner and outer join types>
187  
188 my $inner = Database::Join->new(
189 databases => [ $customers, $loyalty ],
190 join_column => 'entry',
191 join_type => 'inner', # only keys present in BOTH databases
192 );
193  
194 my $outer = Database::Join->new(
195 databases => [ $customers, $loyalty ],
196 join_column => 'entry',
197 join_type => 'outer', # all keys from EITHER database
198 );
199  
200 B<Building the view incrementally with add_database>
201  
202 my $join = Database::Join->new(
203 databases => [ $customers ],
204 join_column => 'entry',
205 );
206  
207 $join->add_database($loyalty)
208 ->add_database($scores, remove_columns => ['raw_score']);
209  
210 B<AUTOLOAD column shortcut>
211  
212 # Returns the 'name' value for entry 'C001' (scalar context)
213 my $name = $join->name(entry => 'C001');
214  
215 # Returns all 'tier' values (list context)
216 my @tiers = $join->tier();
217  
218 B<aggregate(): GROUP BY across the merged view>
219  
220 # Count and total score per tier, highest total first
221 my $rows = $join->aggregate(
222 by => ['tier'],
223 measures => [
224 { col => 'score', fn => 'sum', as => 'total' },
225 { fn => 'count', as => 'n' },
226 ],
227 sort_by => ['total', 'DESC'],
228 having => { total => { '>' => 100 } },
229 );
230 # => [ { tier => 'gold', total => 183, n => 2 }, ... ]
231  
232 # Grand total across the whole view (no 'by' key)
233 my $summary = $join->aggregate(
234 measures => [{ fn => 'count', as => 'n' }],
235 );
236 # => [ { n => 42 } ]
237  
238 B<SQLite join backend for large datasets>
239  
240 # 'auto' (default): switches to SQLite automatically above the threshold
241 my $join = Database::Join->new(
242 databases => [ $customers, $loyalty ],
243 join_column => 'entry',
244 backend => 'auto', # default
245 max_array_rows => 50_000, # use SQLite when combined rows > 50,000
246 );
247  
248 # Always use SQLite -- useful when you know the data is large
249 my $join = Database::Join->new(
250 databases => [ $customers, $loyalty ],
251 join_column => 'entry',
252 backend => 'sqlite',
253 tmpdir => '/fast/nvme/tmp', # optional: faster temp disk
254 );
255  
256 # Always use the original in-memory path
257 my $join = Database::Join->new(
258 databases => [ $customers, $loyalty ],
259 join_column => 'entry',
260 backend => 'array',
261 );
262  
263 =head1 DESCRIPTION
264  
265 C<Database::Join> merges two or more L<Database::Abstraction> objects into a
266 single logical, read-only view. Each component database is queried
267 independently through its own C<Database::Abstraction> interface. The results
268 are combined using a shared key column (C<join_column>).
269 In effect, this means that you can view data from more than one database using
270 an intuitive, non-SQL interface.
271  
272 Every storage format that C<Database::Abstraction> supports works as a
273 component database: CSV, PSV, TSV, SQLite, JSON, XML, XLSX, BerkeleyDB, HTML
274 URL, JSON URL, or any custom subclass. Component databases may mix formats
275 within the same join.
276  
277 The module exposes the same read-only API as C<Database::Abstraction>:
278 C<selectall_arrayref>, C<selectall_array>, C<fetchrow_hashref>, C<count>,
279 C<columns>, C<schema>, C<updated>, C<set_logger>, and the AUTOLOAD column
280 shortcut. Callers do not need to know how many underlying databases are
281 involved.
282  
283 Think of it as a virtual database table that is assembled on demand from
284 several real tables, one per component database.
285  
286 B<Join backends>
287  
288 By default (C<backend =E<gt> 'auto'>), C<Database::Join> first checks the
289 combined source row count. For small datasets (up to C<max_array_rows>,
290 default 10,000 rows) it merges entirely in Perl memory. For larger datasets it
291 automatically spills source rows into a temporary SQLite database and executes
292 a single SQL JOIN there, keeping peak RAM to roughly one times the source data
293 size instead of three. You can also force either path unconditionally with
294 C<backend =E<gt> 'sqlite'> or C<backend =E<gt> 'array'>.
295  
296 B<Key pushdown (array backend)>
297  
298 Under a C<left> or C<inner> join, only secondary rows whose key is one of the
299 primary's can appear in the result. So once the primary has been read, each
300 secondary that has no criterion on its join column is asked for just those
301 keys, as C<< { -in => [ ... ] } >> on its local join column, instead of being
302 read in full. Joining a few hundred primary rows to a large secondary table
303 then costs a few hundred rows, not the whole table. Pushdown is skipped when:
304  
305 =over 4
306  
307 =item * the join is C<outer>, which needs every secondary key;
308  
309 =item * the primary has no rows, or more than 999 keys (the bind-parameter
310 limit of older SQLite builds; past that, reading the whole table is no worse);
311  
312 =item * the query already has a criterion on the join column, which then
313 stands as given;
314  
315 =item * the secondary's C<selectall_arrayref> is not
316 C<Database::Abstraction>'s own. A subclass that overrides it, or another
317 object implementing the interface, may not understand C<-in>.
318  
319 =back
320  
321 If the secondary croaks on the C<-in> query, it is read in full instead. The
322 result is the same either way. Pushdown only narrows what is fetched; it never
323 counts as the secondary's own criterion, so it can't turn a C<left> join into
324 an C<inner> one.
325  
326 =head2 Join semantics
327  
328 The C<join_type> parameter controls what happens when a particular key value
329 exists in some component databases but not all:
330  
331 =over 4
332  
333 =item C<left> (the default)
334  
335 All rows from the I<primary> (first) database are returned. Columns from
336 subsequent databases are included where a matching row is found, and simply
337 absent from the hashref where there is no match. If you are familiar with
338 SQL, this is a LEFT OUTER JOIN on the first table.
339  
340 =item C<inner>
341  
342 Only rows whose join-column value is present in I<every> component database
343 are returned. This is equivalent to a SQL INNER JOIN.
344  
345 =item C<outer>
346  
347 Every join-column value found in I<any> component database is returned.
348 Columns from databases that do not have that key value are absent from the
349 merged row. This is a FULL OUTER JOIN.
350  
351 =back
352  
353 B<Important override rule:> whenever you pass a query criterion for a column
354 that belongs to a secondary database, that database automatically acts as an
355 inner-join partner for that query only -- regardless of C<join_type>. This
356 gives WHERE-clause semantics. For example, if you have a LEFT join but query
357 C<< tier => 'gold' >> on a secondary database, only rows whose secondary entry
358 has tier = 'gold' are returned (rows with no secondary entry are excluded, just
359 as a WHERE clause would exclude them).
360  
361 =head2 Column ownership and routing
362  
363 At construction time, C<Database::Join> calls C<columns()> on each component
364 database and builds an internal index that maps every column name to the
365 database that owns it.
366  
367 When you pass criteria to a query method, each key-value pair is automatically
368 routed to the right database. You never need to say which database a column
369 belongs to.
370  
371 The C<join_column> is special: criteria on it are broadcast to I<all>
372 databases so that each database fetches only the relevant rows before the
373 in-memory merge.
374  
375 When the same non-join column name exists in more than one database, the
376 I<last> database in the C<databases> array wins by default: its value
377 overwrites earlier ones in merged rows. Use C<collision_prefix> to
378 preserve both values under distinct names instead.
379  
380 =head1 LIMITATIONS
381  
382 =over 4
383  
384 =item Memory usage (array backend)
385  
386 When C<backend> is C<'array'> (or C<'auto'> and the dataset is small), all
387 matching rows are fetched into Perl memory. Key pushdown (see
388 L</DESCRIPTION>) limits a secondary to the primary's keys under C<left> and
389 C<inner> joins, but an C<outer> join, or a primary with more than 999 keys,
390 still reads every secondary row. Peak RAM is roughly three times
391 the source data size. For large datasets use C<backend =E<gt> 'sqlite'>, or
392 leave C<backend =E<gt> 'auto'> and set C<max_array_rows> appropriately.
393  
394 =item SQLite backend uses a persistent cache file
395  
396 When the SQLite path is active, a single C<.db> file with a randomly generated
397 name (chosen by C<File::Temp> to avoid collisions) is created in C<tmpdir> the
398 first time a query runs on a given C<Database::Join> object. Source data is
399 spilled into that file once; subsequent queries against the same object reuse
400 the file without re-fetching the source data.
401  
402 The cache is automatically invalidated and rebuilt whenever any source
403 database's C<updated()> timestamp changes (indicating new data), or when
404 C<add_database()> is called.
405  
406 The file is deleted when the C<Database::Join> object is destroyed (typically
407 when it goes out of scope). At any given moment no more than one such file
408 exists per object. The directory must be writable and have enough free space
409 for the full source data (once, not per-query).
410  
411 =item No chained builder or raw SQL
412  
413 C<query()> and C<execute()> are not implemented. Use C<selectall_arrayref>
414 or C<fetchrow_hashref> instead.
415  
416 =item Single-column equi-join only
417  
418 Joining on more than one column simultaneously, or on expressions, is not
419 supported. When the join key has different names in different databases,
420 use C<join_map> to declare each database's local column name.
421  
422 =item Sort order
423  
424 Results are sorted ascending by C<join_column> by default. Pass
425 C<< sort_by => 'colname' >> (or C<< sort_by => ['colname', 'DESC'] >>)
426 to any query method to override this. The array path uses string comparison
427 (C<cmp>); for accurate numeric ordering on large datasets use the SQLite
428 backend, which sorts natively by type.
429  
430 =item count() on the array backend fetches all rows
431  
432 On the array backend, C<count()> executes the full in-memory join and counts
433 the resulting rows in Perl; no C<COUNT(*)> is pushed to the component
434 databases. On the SQLite backend, C<count()> executes a C<SELECT COUNT(*)>
435 SQL query against the cached join tables, avoiding a full row transfer.
436  
437 =back
438  
439 =head1 COMMON PITFALLS
440  
441 =over 4
442  
443 =item The join_column must exist in every component database
444  
445 If even one database is missing the join key column, C<new()> (or
446 C<add_database()>) will C<croak> immediately. Use C<join_map> when the
447 column has a different local name in some databases.
448  
449 =item Criteria on a removed column are silently dropped
450  
451 If you call C<remove_column('tier')> and later query
452 C<< selectall_arrayref(tier => 'gold') >>, the criterion is ignored (with a
453 C<carp> warning) and all rows are returned. Always pass criteria before
454 removing columns, or restructure your code to avoid this.
455  
456 =item You cannot remove the join column
457  
458 C<< $join->remove_column($join->join_column) >> will C<croak>. The join key
459 is required for the merge to work.
460  
461 =item Left join does not guarantee all columns are populated
462  
463 Under a LEFT join, rows from the primary database that have no matching row
464 in a secondary database will be returned with I<no keys> from that secondary
465 database. Accessing C<< $row->{score} >> on such a row returns C<undef> --
466 not zero, not an empty string. Always test C<defined $row->{score}> rather
467 than just C<$row->{score}> when the secondary match is optional.
468  
469 =item Filters act as inner-join partners
470  
471 Any database that has a C<filters> entry is promoted to an inner-join partner,
472 regardless of C<join_type>. A row whose join-key value does not appear in
473 the filtered database's result is removed from the merged output entirely, not
474 merely missing its secondary columns. This is intentional but can be
475 surprising if you expected LEFT join semantics.
476  
477 =item Criteria-merging replaces scalar filters
478  
479 When both a base filter and a query criterion target the same column, and both
480 are operator hashrefs (e.g. C<< { '>' => 60 } >>), the operators are combined
481 (AND semantics). But if the query criterion is a plain scalar (e.g.
482 C<< score => 75 >>), it I<replaces> the base filter for that column entirely --
483 the base filter is ignored for that query.
484  
485 =item AUTOLOAD sees the full merged join when filters or join_map are active
486  
487 When either C<filters> or C<join_map> is in effect, the AUTOLOAD shortcut
488 (C<< $join->columnname(...) >>) runs the full join query rather than
489 delegating directly to the owning database. This is necessary for correctness
490 but means the result respects all active filters and join-key translations,
491 which may differ from what the owning database would return on its own.
492  
493 =item Duplicate column names: last database wins (unless collision_prefix is set)
494  
495 When two component databases each have a column called C<notes>, the second
496 database's value silently overwrites the first in every merged row. Use
497 C<collision_prefix => { 1 => 'right' }> to publish the second database's
498 C<notes> as C<right.notes> so both values survive, or use C<remove_columns>
499 (or C<remove_column>) to drop the unwanted duplicate entirely.
500  
501 =item Mutating the filters hashref after construction has no effect
502  
503 C<Database::Join> deep-copies the C<filters> hashref (and any C<filter>
504 passed to C<add_database>) at the moment of construction. The original hashref
505 you passed in is never stored. If you later modify it -- for example, to
506 tighten or loosen a filter criterion -- the joined view is I<not> affected.
507 Construct a new C<Database::Join> object, or use a component
508 C<Database::Abstraction> that supports dynamic filter modification.
509  
510 =item auto mode may always use the array path for some DAs
511  
512 C<backend =E<gt> 'auto'> counts rows cheaply only when each component database
513 either implements C<dbi_source()> (SQLite-backed) or directly defines a
514 C<count()> method in its own package. A DA that merely I<inherits> C<count()>
515 from C<Database::Abstraction> is treated as uncountable, because the parent
516 class C<count()> expects a key argument and behaves differently from a
517 "return total row count" function. In that case C<Database::Join>
518 conservatively uses the array path for the whole query, even if the dataset is
519 large. To opt in to the SQLite path for such a DA, either add your own
520 C<count()> override that returns the total row count, implement C<dbi_source()>,
521 or use C<backend =E<gt> 'sqlite'> unconditionally.
522  
523 =item dbi_source() ATTACH is unconditional - query-time criteria go into WHERE
524  
525 When a component database implements C<dbi_source()>, C<Database::Join> always
526 uses the zero-copy ATTACH path, I<even when the current query includes criteria
527 for columns in that database>. The criteria are translated into parameterised
528 SQL C<WHERE> clauses applied against the ATTACHed table; no row-level copy is
529 performed. (Prior to 0.005.0 the presence of any query-time criteria would
530 force a spill; that restriction has been removed.)
531  
532 =item Broadcast join-column criterion does not force secondaries into inner-join
533  
534 When a caller passes a join-column criterion (e.g. C<entry =E<gt> 'k1'>),
535 C<Database::Join> broadcasts it to all component databases so each DA can
536 filter its fetch to the requested key. Prior to 0.006.0 this broadcast was
537 incorrectly counted as "having criteria" for secondary databases, causing
538 C<left> and C<outer> joins to silently behave as C<inner> joins when a
539 join-column criterion was present. The fix: only non-join-column criteria
540 (e.g. column filters from the caller or base C<filters =E<gt> {...}>) promote
541 a secondary to inner-join status. The broadcast itself is now a transparent
542 key-range selector that does not affect join semantics.
543  
544 =item LIKE and NOT LIKE work on the SQLite path; other pattern operators do not yet
545  
546 C<LIKE>, C<NOT LIKE>, C<IN>, and C<NOT IN> are fully supported on the SQLite
547 backend. C<LIKE>/C<NOT LIKE> take a scalar pattern; C<IN>/C<NOT IN> take an
548 arrayref of values. All are injection-safe because values are passed as bind
549 parameters, never interpolated.
550  
551 # LIKE
552 my $rows = $join->selectall_arrayref(name => { LIKE => 'A%' });
553  
554 # IN
555 my $rows = $join->selectall_arrayref(tier => { IN => ['gold', 'silver'] });
556  
557 # NOT IN
558 my $rows = $join->selectall_arrayref(tier => { 'NOT IN' => ['bronze'] });
559  
560 C<IN> with an empty arrayref matches no rows (SQL semantics: C<IN ()> is
561 always false). C<NOT IN> with an empty arrayref matches all rows (no
562 constraint added).
563  
564 C<IS NULL> and C<IS NOT NULL> are supported on the SQLite backend using an
565 explicit operator hashref:
566  
567 my $rows = $join->selectall_arrayref(score => { 'IS NULL' => undef });
568 my $rows = $join->selectall_arrayref(score => { 'IS NOT NULL' => 1 });
569  
570 The hashref value is ignored; only the key selects the operator. A bare
571 C<undef> criterion value (C<< score => undef >>) also generates C<IS NULL>
572 on the SQLite path. Note: on the in-memory array path, the component DA
573 may treat an C<undef> criterion value as C<< no filter >> rather than
574 C<IS NULL>, so use the explicit hashref form for consistent behaviour
575 across backends.
576  
577 Any operator not in the supported set is skipped on the SQLite path with a
578 C<carp> warning. The array path forwards all operators to the component DA
579 unchanged, which may or may not honour them.
580  
581 =item Temp file directory must be writable and have free space
582  
583 The SQLite path creates one temporary C<.db> file per C<Database::Join> object
584 in C<tmpdir> (default: C<File::Spec-E<gt>tmpdir()>, usually C</tmp> on Unix).
585 The filename is randomly generated by C<File::Temp> -- you cannot predict it,
586 only the directory is under your control. The file is created on the first
587 query and kept alive until the object is destroyed; it is not re-created on
588 every query call. If the directory is not writable, or the filesystem is full,
589 the call will C<croak> with C<error_sqlite_connect>. Check permissions and
590 free space if you see that error.
591  
592 =item C<join =E<gt>> criteria are not supported
593  
594 C<Database::Abstraction> accepts a C<join =E<gt> { table =E<gt> ..., on =E<gt> ... }>
595 key in its criteria hashrefs to express an SQL JOIN within a single table.
596 C<Database::Join> cannot route this to a component DA meaningfully: the merged
597 view has no concept of a single underlying table. Passing C<join =E<gt>> to any
598 query method will C<croak> with C<error_join_criterion>.
599  
600 B<Fix:> Model the joined table as a separate C<Database::Abstraction> object and
601 add it to the C<databases =E<gt> []> list. Use C<join_column> or C<join_map> to
602 specify the shared key.
603  
604 =item aggregate(): omitting C<by> gives a grand total, not an error
605  
606 Calling C<aggregate()> without a C<by> key (or with C<< by => [] >>) does
607 I<not> croak. It returns a single-element arrayref containing one row with
608 all the computed measure aliases. This is a grand total over the entire view
609 (possibly filtered by any extra criteria you pass).
610  
611 my $total = $join->aggregate(measures => [{ fn => 'count', as => 'n' }]);
612 # $total->[0]{n} is the total row count
613  
614 If you expected multiple rows and got one, you probably forgot the C<by> key.
615  
616 =item aggregate(): non-numeric values behave differently across backends
617  
618 On the array backend (C<backend =E<gt> 'array'>), any non-numeric value in a
619 column targeted by C<sum> or C<avg> is I<skipped> (not counted, not coerced),
620 and a C<carp> warning C<warn_aggregate_non_numeric> is emitted. On the SQLite
621 backend, non-numeric values are silently coerced to C<0.0> via SQL C<CAST>.
622 The two backends therefore produce different numeric totals when the data
623 contains non-numeric values. Clean your data first if you need consistent
624 results across backends, or choose a backend explicitly.
625  
626 =item aggregate(): C<BETWEEN> is not supported in C<having>
627  
628 The C<having> hashref uses the same operator vocabulary as C<selectall_arrayref>,
629 which does not include C<BETWEEN>. Write a range as two explicit constraints:
630  
631 # Correct
632 having => { total => { '>=' => 10, '<=' => 50 } }
633  
634 # Wrong -- will croak with error_aggregate_having_operator
635 having => { total => { BETWEEN => [10, 50] } }
636  
637 =item aggregate(): C<count> without C<col> counts all rows, not distinct non-NULL values
638  
639 A measure with C<< fn => 'count' >> and no C<col> key emits C<COUNT(*)> on the
640 SQLite backend (or counts every row in Perl). This counts rows that have
641 C<undef>/NULL in other columns too. To count only rows where a specific
642 column is non-NULL, or to count distinct values, use C<count_distinct>:
643  
644 # Count rows with a non-NULL 'score' (one way -- use a pre-filter)
645 measures => [{ col => 'score', fn => 'count_distinct', as => 'distinct_scores' }]
646  
647 =item aggregate(): the result is never cached
648  
649 Unlike C<selectall_arrayref> (which benefits from the SQLite file cache on
650 repeated identical calls), C<aggregate()> always re-executes. If your
651 aggregation is expensive and the data changes infrequently, cache the result
652 yourself using C<updated()> as a staleness signal.
653  
654 =item distinct => 1 without columns returns full rows, not a column projection
655  
656 C<< distinct => 1 >> alone deduplicates on I<all> columns of the merged row.
657 If you want a distinct list of values for a single column (e.g. all unique
658 tiers), you B<must> supply C<< columns => ['tier'] >> as well. Without
659 C<columns>, every column participates in the key used to detect duplicates,
660 which means two rows that differ in any column (e.g. C<entry>) are never
661 considered duplicates, and the result will be the same as without C<distinct>.
662  
663 =item distinct => 1 with columns projects rows to those columns
664  
665 When C<columns> is supplied alongside C<distinct>, each returned row contains
666 I<only> the named columns -- all other columns are dropped. The projection
667 happens before deduplication, so the result set may be smaller than the full
668 merged row count. If you need the full row I<and> want to know unique values,
669 run two separate queries or post-process in Perl.
670  
671 =item mandatory_filters must never come from user-supplied input
672  
673 The predicates in C<mandatory_filters> form an enforcement boundary. They must
674 come from a trusted server-side source (a session store, a policy table, or
675 hard-coded application configuration) -- never from URL parameters, form fields,
676 HTTP headers, or other user-controlled input. A hostile user who can control
677 a mandatory_filters predicate can widen it to C<{ col => 'status', op => 'ne',
678 val => 'NONEXISTENT' }> and receive all rows regardless of status.
679  
680 =item mandatory_filters uses string comparison on the array path
681  
682 On the array backend, all C<mandatory_filters> comparisons (including C<lt>,
683 C<lte>, C<gt>, C<gte>) are I<lexicographic string comparisons>, not numeric.
684 C<< { col => 'score', op => 'gt', val => 9 } >> will match a score of C<'10'>
685 only if C<'10' gt '9'> is true -- which it is not (C<'1' lt '9'>). Use the
686 SQLite backend (C<< backend => 'sqlite' >>) when numeric comparisons are needed,
687 as SQLite uses the column's declared type for ordering.
688  
689 =back
690  
691 =head1 METHODS
692  
693 =head2 new
694  
695 =head3 SYNOPSIS
696  
697 my $join = Database::Join->new(
698 databases => [ $db1, $db2 ],
699 join_column => 'entry',
700 join_type => 'left',
701 join_map => { 1 => 'local_col' },
702 filters => { 1 => { score => { '>' => 60 } } },
703 base_criteria => { active => 1 },
704 mandatory_filters => [{ col => 'region', op => 'eq', val => 'West' }],
705 collision_prefix => { 1 => 'right' },
706 remove_columns => [ 'email', 'internal_id' ],
707 backend => 'auto', # 'auto' | 'sqlite' | 'array'
708 max_array_rows => 10_000, # threshold for 'auto' mode
709 tmpdir => '/tmp', # directory for temp SQLite file
710 logger => $log,
711 i18n => $locale,
712 );
713  
714 =head3 DESCRIPTION
715  
716 Constructs and returns a new C<Database::Join> object.
717  
718 Each element of C<databases> must be an already-instantiated subclass of
719 C<Database::Abstraction>. The constructor calls C<columns()> on every
720 database to build an internal column-routing table and verifies that
721 C<join_column> (or its local alias from C<join_map>) is present in each one.
722  
723 Columns listed in C<remove_columns> are hidden immediately: they do not appear
724 in C<columns()>, C<schema()>, or any returned row hashref. This is equivalent
725 to calling C<remove_column> once per name after construction.
726  
727 =head3 API SPECIFICATION
728  
729 =head4 Input
730  
731 databases => { type => 'arrayref', required => 1 }
732 # One or more Database::Abstraction subclass objects.
733 #
734 # DOMAIN -- EP valid: non-empty arrayref of blessed DA subclasses.
735 # DOMAIN -- EP invalid: scalar, hashref, or absent => croak.
736 # DOMAIN -- BVA size: minimum 1 element; no documented upper bound.
737 # DOMAIN -- BVA elem: each element must pass isa('Database::Abstraction').
738  
739 join_column => { type => 'string', optional => 1, default => 'entry' }
740 # The column name shared by all databases (the join key).
741 #
742 # DOMAIN -- EP valid: any non-empty string present in every component DA.
743 # DOMAIN -- EP invalid: column absent from any DA => croak join_col_missing.
744 # DOMAIN -- BVA: empty string '' is treated as a column name and
745 # will croak if (as expected) it is absent from every DA.
746 # DOMAIN -- NOTE: matching is case-sensitive and exact.
747  
748 join_type => { type => 'string', optional => 1, default => 'left',
749 enum => ['inner', 'left', 'outer'] }
750 # Controls which keys appear in the result when not all
751 # databases share the same key values.
752 #
753 # DOMAIN -- EP valid: exactly 'inner', 'left', or 'outer'.
754 # DOMAIN -- EP invalid: any other string including 'INNER', 'LEFT',
755 # 'OUTER' (enum check is case-sensitive), 'cross',
756 # or '' => croak from validate_strict.
757  
758 join_map => { type => 'hashref', optional => 1 }
759 # Zero-based database index => local column name.
760 # See the join_map section for full details.
761 #
762 # DOMAIN -- EP valid: hashref values must be plain strings.
763 # DOMAIN -- EP invalid: reference value (hashref, arrayref, coderef, etc.)
764 # => croak; the guard prevents heap-address leakage.
765 # DOMAIN -- BVA: out-of-range keys (beyond the databases array) are
766 # silently ignored.
767  
768 filters => { type => 'hashref', optional => 1 }
769 # Zero-based database index => criteria hashref.
770 # Permanent row restrictions on individual databases.
771 # See the filters section for full details.
772  
773 base_criteria => { type => 'hashref', optional => 1 }
774 # Column name => value hashref.
775 # Permanent criteria applied to every query, specified by
776 # column name rather than database index. Each key must
777 # be a column that appears in the merged view (or the
778 # join_column); each value is a plain scalar or an
779 # operator hashref in the same format as
780 # selectall_arrayref accepts. Criteria are automatically
781 # routed to the database that owns each column (same
782 # routing used by selectall_arrayref).
783 # Equivalent to filters but more convenient when you know
784 # the column name but not which database index owns it.
785 # When a column appears in both base_criteria and filters,
786 # the filters entry takes precedence.
787 # See the base_criteria section for full details.
788 #
789 # DOMAIN -- EP valid: hashref of column-name => scalar or
790 # operator-hashref pairs. Unknown column
791 # names emit warn_unknown_column (carp)
792 # and are silently dropped.
793 # DOMAIN -- EP invalid: non-hashref value => croak from
794 # validate_strict.
795 # DOMAIN -- BVA: {} empty hashref is a safe no-op.
796  
797 collision_prefix => { type => 'hashref', optional => 1 }
798 # Zero-based database index (>0) => prefix string.
799 # When a secondary database has a column that collides
800 # with a column already present in the merged view, the
801 # secondary column is published as "$prefix.$col" instead
802 # of silently overwriting the earlier value.
803 # Index 0 entries are silently ignored.
804 # Omitting this parameter preserves the original
805 # last-database-wins behaviour.
806 # See the collision_prefix section for full details.
807 #
808 # DOMAIN -- EP valid: absent or {} => last-database-wins (no change).
809 # DOMAIN -- EP valid: { N => 'prefix' } where N > 0 => colliding
810 # columns from DB[N] published as "$prefix.$col";
811 # non-colliding columns from the same DB added plain.
812 # DOMAIN -- EP note: index-0 entries are silently ignored.
813 # DOMAIN -- Invariant: join_column is never prefixed regardless of
814 # collision_prefix configuration.
815  
816 remove_columns => { type => 'arrayref', optional => 1 }
817 # Column names to hide from the merged view.
818 #
819 # DOMAIN -- EP valid: arrayref of any strings; non-existent columns
820 # are silently ignored (idempotent).
821 # DOMAIN -- EP invalid: join_column itself => croak remove_join_col.
822 # DOMAIN -- BVA: [] empty arrayref is a safe no-op.
823  
824 backend => { type => 'string', optional => 1, default => 'auto',
825 enum => ['array', 'sqlite', 'auto'] }
826 # Controls which join strategy is used.
827 # 'auto' -- (default) use 'array' when combined source row count
828 # <= max_array_rows, 'sqlite' otherwise.
829 # 'sqlite' -- always spill to a temporary SQLite database.
830 # 'array' -- always use the in-memory merge path.
831 #
832 # DOMAIN -- EP valid: 'array', 'sqlite', or 'auto' (case-sensitive).
833 # DOMAIN -- EP invalid: any other string => croak error_invalid_backend.
834 # DOMAIN -- Default: 'auto'.
835  
836 max_array_rows => { type => 'integer', optional => 1, default => 10_000 }
837 # Row-count threshold for 'auto' mode. When the combined
838 # source row count exceeds this value, the SQLite path is used.
839 # Ignored when backend is 'array' or 'sqlite'.
840 #
841 # DOMAIN -- EP valid: any non-negative integer.
842 # DOMAIN -- BVA: 0 means always use SQLite (all counts exceed 0).
843 # DOMAIN -- Default: 10,000.
844  
845 tmpdir => { type => 'string', optional => 1 }
846 # Directory for the per-call temporary SQLite database file.
847 # The file is created securely by File::Temp and removed when
848 # the query completes. Ignored when backend is 'array'.
849 #
850 # DOMAIN -- EP valid: any writable directory path string.
851 # DOMAIN -- EP absent: uses File::Spec->tmpdir() (system temp dir).
852  
853 parallel => { type => 'integer', optional => 1, default => 0 }
854 # When set to 1 and the join has more than 2 databases (primary +
855 # 2 or more secondaries), secondary DA fetches are issued in
856 # parallel Perl threads. Requires the 'threads' module; falls
857 # back to sequential with a carp warning when unavailable.
858 # Has no effect on the SQLite backend (which uses a single SQL
859 # JOIN). DBI-backed DAs are not thread-safe by default; only
860 # enable this for in-memory or otherwise thread-safe DA backends.
861 #
862 # DOMAIN -- EP valid: 0 (sequential, default) or 1 (parallel).
863 # DOMAIN -- EP invalid: any other integer is treated as truthy/falsy.
864 # DOMAIN -- Default: 0.
865  
866 autoload_pk => { type => 'string', optional => 1 }
867 # The column name used as the positional-argument key when
868 # AUTOLOAD performs a full join query (i.e. when join_map or
869 # filters is active). Calling $join->col('value') with a bare
870 # scalar maps that scalar to { autoload_pk => 'value' } before
871 # routing through the merged view.
872 #
873 # Defaults to join_column when omitted. Override when the
874 # primary DA's natural lookup key differs from join_column -
875 # for example, when join_column is 'statecode' but you want to
876 # look up by city name ('entry').
877 #
878 # DOMAIN -- EP valid: any string that is a visible column in
879 # the merged view (checked at call time by
880 # _partition_criteria; unknown names are
881 # carp'd and dropped).
882 # DOMAIN -- EP absent: defaults to join_column.
883  
884 mandatory_filters => { type => 'arrayref', optional => 1 }
885 # Arrayref of {col, op, val} predicate hashrefs.
886 # These filters are applied to every query result regardless
887 # of what criteria the caller supplies. They cannot be
888 # overridden, suppressed, or circumvented at query time.
889 # Each predicate must supply:
890 # col -- a column name present in the merged view
891 # op -- one of: eq, ne, lt, lte, gt, gte, like, contains
892 # val -- the comparison value (plain scalar)
893 # On the array backend: applied as a Perl-side grep after the
894 # in-memory merge, before sort/limit/offset.
895 # On the SQLite backend: injected as parameterised WHERE clauses
896 # into the per-call SQL query.
897 #
898 # SECURITY: Never set this from URL parameters or any
899 # user-supplied value. Predicates must come from the
900 # server-side session or policy store only.
901 #
902 # DOMAIN -- EP valid: [] empty arrayref => no constraint (safe no-op).
903 # DOMAIN -- EP valid: arrayref of {col, op, val} hashrefs where
904 # col is in the merged view and op is supported.
905 # DOMAIN -- EP invalid: element is not a hashref, or is missing
906 # col/op/val => croak error_mandatory_filter_ref.
907 # DOMAIN -- EP invalid: col not in merged view => croak error_mandatory_filter_col.
908 # DOMAIN -- EP invalid: op not in supported set => croak error_mandatory_filter_op.
909 # DOMAIN -- ops: eq (string eq), ne (string ne),
910 # lt/lte/gt/gte (string comparison),
911 # like (SQL LIKE pattern with % and _),
912 # contains (substring match, equivalent to LIKE %val%).
913  
914 logger => { type => 'object', optional => 1 }
915 # Logger object propagated to all component databases.
916  
917 i18n => { type => 'object', optional => 1 }
918 # Localisation object with a translate($key, @args) method.
919  
920 =head4 Output
921  
922 A blessed Database::Join object.
923  
924 =head3 EXAMPLE
925  
926 # Customers database: entry | name | email
927 # Loyalty database: entry | tier | points
928  
929 my $join = Database::Join->new(
930 databases => [ $customers, $loyalty ],
931 join_column => 'entry',
932 join_type => 'inner', # only customers who also have loyalty records
933 remove_columns => [ 'email' ], # hide PII from query results
934 filters => { 1 => { points => { '>' => 0 } } }, # ignore zero-point records
935 );
936  
937 my $rows = $join->selectall_arrayref();
938 # Each row: { entry => ..., name => ..., tier => ..., points => ... }
939 # 'email' is absent. Zero-point loyalty records are excluded.
940  
941 =head3 PSEUDOCODE
942  
943 validate all parameters with validate_strict
944 croak if databases is empty
945 croak if any element of databases is not a Database::Abstraction subclass
946 bless the object with all fields initialised
947 call _build_col_index to map every column to its owning database
948 and verify join_column presence in each database
949 if base_criteria given:
950 partition base_criteria by column ownership into per-db slices
951 for each database with a non-empty slice:
952 merge the slice into _filters[i]
953 (explicit filters win on plain-scalar conflicts)
954 if mandatory_filters given:
955 for each predicate in mandatory_filters:
956 croak error_mandatory_filter_ref if predicate is not a {col, op, val} hashref
957 croak error_mandatory_filter_col if col is not in the merged view
958 croak error_mandatory_filter_op if op is not in the supported set
959 store shallow copies of all validated predicates in _mandatory_filters
960 for each column in remove_columns: call remove_column
961 return the new object
962  
963 =head3 MESSAGES
964  
965 error_no_databases -- databases arrayref was empty
966 error_invalid_db -- an element of databases is not a D::A subclass
967 error_join_col_missing -- join_column (or its join_map alias) not found in a database
968 error_invalid_backend -- backend value is not 'array', 'sqlite', or 'auto'
969 error_sqlite_connect -- temporary SQLite database could not be created (backend='sqlite'/'auto')
970 error_mandatory_filter_ref -- a mandatory_filters element is not a hashref with col, op, and val keys
971 error_mandatory_filter_col -- a mandatory_filters element names a column not in the merged view
972 error_mandatory_filter_op -- a mandatory_filters element uses an unsupported op value
973 warn_schema_type_mismatch -- (carp) a shared column has different types across databases;
974 use collision_prefix to preserve both values
975  
976 =cut
977  
978 1351 ▶sub new {
Subroutine new: called CC=28 SCAR=33.4
Pod documented
979 1351 my ($class, @args) = @_;
980  
981 1351 ▶ my $p = validate_strict(
Condition50%1/2
get_params(undef, \@args) // {}
l!l
13510
MC/DC0%0/1
get_params(undef, \@args) // {}
get_params(undef, \@args)
Truth table50%1/2
A
A= get_params(undef, \@args)
Aresult
11
00
982 schema => {
983 # databases => { type => 'arrayref', element_type => 'object' },
984 databases => { type => 'arrayref' },
985 join_column => { type => 'string', optional => 1, default => 'entry' },
986 join_type => {
987 type => 'string',
988 optional => 1,
989 default => 'left',
990 enum => ['inner', 'left', 'outer']
991 },
992 join_map => { type => 'hashref', optional => 1 },
993 filters => { type => 'hashref', optional => 1 },
994 base_criteria => { type => 'hashref', optional => 1 },
995 collision_prefix => { type => 'hashref', optional => 1 },
996 remove_columns => { type => 'arrayref', optional => 1 },
997 backend => {
998 type => 'string',
999 optional => 1,
1000 default => 'auto',
1001 enum => ['array', 'sqlite', 'auto']
1002 },
1003 max_array_rows => { type => 'integer', optional => 1, default => 10_000 },
1004 tmpdir => { type => 'string', optional => 1 },
1005 parallel => { type => 'integer', optional => 1, default => 0 },
1006 mandatory_filters => { type => 'arrayref', optional => 1 },
1007 autoload_pk => { type => 'string', optional => 1 },
1008 logger => { type => 'object', optional => 1 },
1009 i18n => { type => 'object', optional => 1 },
1010 },
1011 input => get_params(undef, \@args) // {},
1012 );
1013  
1014 croak _msg($p->{i18n}, 'error_no_databases')
1015 1331 ▶ unless @{ $p->{databases} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$p->{"databases"};} 15 1316 1331
1016  
1017 # Capture caller-supplied logger and i18n object BEFORE Object::Configure::configure
1018 # overwrites them with class-level defaults. configure() reads default values
1019 # from Database::Abstraction's class config and silently replaces any caller-
1020 # supplied value if a class default exists for that key.
1021 1316 my $caller_logger = $p->{logger};
1022 1316 my $caller_i18n = $p->{i18n};
1023  
1024 1316 $p = Object::Configure::configure($class, $p);
1025  
1026 1316 for my $i (0 .. $#{ $p->{databases} }) {
1027 croak _msg($p->{i18n}, 'error_invalid_db', $i)
1028 unless blessed($p->{databases}[$i])
1029 && $p->{databases}[$i]->can('selectall_arrayref')
1030 2405 ▶ && $p->{databases}[$i]->can('columns');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($p->{"databases"}[$i]) and $p->{"databases"}[$i]->can("selectall_arrayref") and $p->{"databases"}[$i]->can("columns") 15 2390 2405
Condition100%6/6
builtin::blessed($p->{"databases"}[$i]) and $p->{"databases"}[$i]->can("selectall_arrayref") and $p->{"databases"}[$i]->can("columns")
!ll&&!rl&&r
1412390
builtin::blessed($p->{"databases"}[$i]) and $p->{"databases"}[$i]->can("selectall_arrayref")
!ll&&!rl&&r
952391
MC/DC100%3/3
builtin::blessed($p->{"databases"}[$i]) and $p->{"databases"}[$i]->can("selectall_arrayref") and $p->{"databases"}[$i]->can("columns")
builtin::blessed($p->{"databases"}[$i]) $p->{"databases"}[$i]->can("selectall_arrayref") $p->{"databases"}[$i]->can("columns")
Truth table100%4/4
A and B and C
A= builtin::blessed($p->{"databases"}[$i])B= $p->{"databases"}[$i]->can("selectall_arrayref")C= $p->{"databases"}[$i]->can("columns")
ABCresult
0XX0
10X0
1100
1111
1031 }
1032  
1033 # The positional-argument key AUTOLOAD uses when join_map or filters forces a
1034 # full join query. Callers set this explicitly via the autoload_pk constructor
1035 # param; the default is join_column.
1036 1301 ▶ my $primary_pk = $p->{autoload_pk} // $p->{join_column};
Condition66%2/3
$p->{"autoload_pk"} // $p->{"join_column"}
l!l&&r!l&&!r
512960
MC/DC0%0/2
$p->{"autoload_pk"} // $p->{"join_column"}
$p->{"autoload_pk"} $p->{"join_column"}
Truth table66%2/3
A // B
A= $p->{"autoload_pk"}B= $p->{"join_column"}
ABresult
1X1
011
000
1037  
1038 my $self = bless {
1039 _dbs => $p->{databases},
1040 _join_col => $p->{join_column},
1041 _join_type => $p->{join_type},
1042 _join_map => $p->{join_map} // {}, # db_index => local join col name
1043 # Security: deep-copy filters so post-construction mutation of the caller's
1044 # hashref cannot silently bypass the inner-join row-security guarantee.
1045 # Two-level copy mirrors the broadcast-copy idiom in _partition_criteria:
1046 # outer keys are db indices (integers); inner values are criteria hashrefs
1047 # whose operator sub-hashrefs are also shallow-copied one level deeper.
1048 _filters => _copy_filters($p->{filters}), # db_index => criteria hashref
1049 _collision_prefix => $p->{collision_prefix} // {}, # db_index => prefix string
1050 _logger => $caller_logger,
1051 _i18n => $caller_i18n,
1052 _col_db => {}, # published_col_name => db_index
1053 _db_cols => [], # per-db column-presence hashref
1054 _removed_cols => {}, # published_col_name => 1 (hidden from view)
1055 _col_cache => undef, # memoised columns() result
1056 _schema_cache => undef, # memoised schema() result
1057 _col_rename => [], # per-db: { orig_col => published_col } for collisions
1058 _col_unrename => [], # per-db: { published_col => orig_col } reverse map
1059 _autoload_pk => $primary_pk, # positional arg key for AUTOLOAD full-join path
1060 _backend => $p->{backend},
1061 _max_array_rows => $p->{max_array_rows},
1062 _tmpdir => $p->{tmpdir} // File::Spec->tmpdir,
1063 1301 ▶ _parallel => $p->{parallel} // 0,
Condition77%7/9
$p->{"join_map"} // {}
l!l
551246
$p->{"collision_prefix"} // {}
l!l
1221179
$p->{"tmpdir"} // "File::Spec"->tmpdir
l!l&&r!l&&!r
3912620
$p->{"parallel"} // 0
l!l
13010
MC/DC100%1/1
$p->{"join_map"} // {}
$p->{"join_map"}
MC/DC100%1/1
$p->{"collision_prefix"} // {}
$p->{"collision_prefix"}
MC/DC0%0/2
$p->{"tmpdir"} // "File::Spec"->tmpdir
$p->{"tmpdir"} "File::Spec"->tmpdir
MC/DC0%0/1
$p->{"parallel"} // 0
$p->{"parallel"}
Truth table100%2/2
A
A= $p->{"join_map"}
Aresult
11
00
Truth table100%2/2
A
A= $p->{"collision_prefix"}
Aresult
11
00
Truth table66%2/3
A // B
A= $p->{"tmpdir"}B= "File::Spec"->tmpdir
ABresult
1X1
011
000
Truth table50%1/2
A
A= $p->{"parallel"}
Aresult
11
00
1064 _mandatory_filters => [], # validated and replaced below after _build_col_index
1065 }, $class;
1066  
1067 1301 $self->_build_col_index();
1068 1271 $self->_validate_schema_types();
1069  
1070 # mandatory_filters: validate and store each {col, op, val} predicate.
1071 # These predicates are immutable row-level security guards that are applied
1072 # on every query regardless of what the caller passes at query time.
1073 # Security: deep-copied so post-construction mutation of the caller's arrayref
1074 # cannot widen or remove the mandatory constraints.
1075 1271 ▶ if (my $mf = $p->{mandatory_filters}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $mf = $p->{"mandatory_filters"}) 15 1256 1271
1076 15 my @validated;
1077 15 for my $j (0 .. $#{$mf}) {
1078 15 my $pred = $mf->[$j];
1079 croak $self->_err('error_mandatory_filter_ref', $j)
1080 unless ref($pred) eq 'HASH'
1081 && exists $pred->{col}
1082 && exists $pred->{op}
1083 15 ▶ && exists $pred->{val};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pred eq "HASH" and exists $pred->{"col"} and exists $pred->{"op"} and exists $pred->{"val"} 2 13 15
Condition77%7/9
ref $pred eq "HASH" and exists $pred->{"col"} and exists $pred->{"op"} and exists $pred->{"val"}
!ll&&!rl&&r
2013
ref $pred eq "HASH" and exists $pred->{"col"} and exists $pred->{"op"}
!ll&&!rl&&r
1113
ref $pred eq "HASH" and exists $pred->{"col"}
!ll&&!rl&&r
1014
MC/DC50%2/4
ref $pred eq "HASH" and exists $pred->{"col"} and exists $pred->{"op"} and exists $pred->{"val"}
ref $pred eq "HASH" exists $pred->{"col"} exists $pred->{"op"} exists $pred->{"val"}
Truth table60%3/5
A and B and C and D
A= ref $pred eq "HASH"B= exists $pred->{"col"}C= exists $pred->{"op"}D= exists $pred->{"val"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1084 croak $self->_err('error_mandatory_filter_col', $j, $pred->{col})
1085 13 ▶ unless exists $self->{_col_db}{ $pred->{col} };
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"_col_db"}{$pred->{"col"}} 1 12 13
1086 croak $self->_err('error_mandatory_filter_op', $j, $pred->{op})
1087 12 ▶ unless $MANDATORY_FILTER_OPS{ $pred->{op} };
Branch: 1 branch
BranchTrueFalseTotal
unless $MANDATORY_FILTER_OPS{$pred->{"op"}} 1 11 12
1088 11 push @validated, { %{$pred} }; # shallow copy
1089 }
1090 11 $self->{_mandatory_filters} = \@validated;
1091 }
1092  
1093 # base_criteria: partition by column ownership into _filters.
1094 # Security: _copy_criteria() deep-copies before partitioning so
1095 # post-construction mutation of the caller's hashref cannot bypass filters.
1096 # Explicit filters (db-indexed) take precedence: they are treated as
1097 # "extra" in _merge_criteria so their values win on plain-scalar conflicts.
1098 1267 ▶ if (my $bc = $p->{base_criteria}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bc = $p->{"base_criteria"}) 9 1258 1267
1099 9 my $partitioned = $self->_partition_criteria(_copy_criteria($bc));
1100 9 for my $i (0 .. $#{ $self->{_dbs} }) {
1101 18 ▶ next unless %{ $partitioned->[$i] };
Branch: 1 branch
BranchTrueFalseTotal
unless %{$partitioned->[$i];} 10 8 18
1102 $self->{_filters}{$i} = _merge_criteria(
1103 $partitioned->[$i],
1104 8 ▶ $self->{_filters}{$i} // {},
Condition100%2/2
$self->{"_filters"}{$i} // {}
l!l
17
MC/DC100%1/1
$self->{"_filters"}{$i} // {}
$self->{"_filters"}{$i}
Truth table100%2/2
A
A= $self->{"_filters"}{$i}
Aresult
11
00
1105 );
1106 }
1107 }
1108  
1109 # Propagate the logger to every component database if one was supplied.
1110 # set_logger() is used here (rather than a direct hash write) to honour each
1111 # DA's own logging setup hook and remain decoupled from DA internals.
1112 1267 ▶ if (my $log = $self->{_logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $log = $self->{"_logger"}) 3 1264 1267
1113 3 $_->set_logger($log) for @{ $self->{_dbs} };
1114 }
1115  
1116 # Apply column removals requested in the constructor
1117 1267 ▶ if (my $rc = $p->{remove_columns}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $p->{"remove_columns"}) 13 1254 1267
1118 13 $self->remove_column($_) for @{$rc};
1119 }
1120  
1121 1265 return $self;
1122 }
1123  
1124 # ---------------------------------------------------------------------------
1125 # Public API (mirrors Database::Abstraction)
1126 # ---------------------------------------------------------------------------
1127  
1128 =head2 join_map - joining on differently-named columns
1129  
1130 By default every component database must have a column whose name matches
1131 C<join_column>. If a database uses a different local name for the join key,
1132 declare the mapping with C<join_map>.
1133  
1134 C<join_map> is a hashref. Each B<key> is the B<zero-based position> of a
1135 database in the C<databases> array (0 = first, 1 = second, and so on). Each
1136 B<value> is the name that B<that particular database> uses for the join key.
1137  
1138 Databases not listed in C<join_map> are assumed to already have a column
1139 named C<join_column> and need no entry.
1140  
1141 Throughout the merged view the join key is I<always> referred to by the name
1142 given in C<join_column>. The local alias is never exposed in returned rows,
1143 in C<columns()>, or in C<schema()>.
1144  
1145 B<When do you need join_map?>
1146  
1147 You need C<join_map> when you have two tables like:
1148  
1149 cities table : entry (the city name) | statecode
1150 stnames table : entry (the state code) | state
1151  
1152 Here you want to join cities.statecode to stnames.entry. You choose
1153 C<< join_column => 'statecode' >> as the canonical name, but stnames calls
1154 that same concept C<entry>, so you declare:
1155  
1156 join_map => { 1 => 'entry' } # stnames (index 1) calls it 'entry'
1157  
1158 B<Example>
1159  
1160 # index 0 index 1
1161 my @databases = ( $cities, $stnames );
1162 # join key column: 'statecode' 'entry'
1163 # join_column: 'statecode' (chosen canonical name)
1164 # stnames differs, so declare the alias:
1165  
1166 my $join = Database::Join->new(
1167 databases => \@databases,
1168 join_column => 'statecode',
1169 join_map => { 1 => 'entry' },
1170 );
1171  
1172 my $rows = $join->selectall_arrayref();
1173 # Each $row has keys: entry (city), statecode, state
1174 # 'entry' from stnames is never exposed directly.
1175  
1176 my $row = $join->fetchrow_hashref(statecode => 'CA');
1177  
1178 B<Using add_database instead>
1179  
1180 If you build the join incrementally with C<add_database>, pass
1181 C<join_column> directly to that call instead of using C<join_map>:
1182  
1183 my $join = Database::Join->new(
1184 databases => [ $cities ],
1185 join_column => 'statecode',
1186 );
1187 $join->add_database($stnames, join_column => 'entry');
1188  
1189 This is exactly equivalent to the C<join_map> form above.
1190  
1191 =head2 filters - permanent per-database row filters
1192  
1193 C<filters> lets you restrict a component database to a subset of its rows
1194 permanently, without repeating the criterion on every query call.
1195  
1196 Think of it as telling the join: "whenever you query this database, always
1197 add these extra conditions". Callers never need to specify the restriction
1198 themselves and can never accidentally omit it.
1199  
1200 C<filters> is a hashref. Each B<key> is the B<zero-based position> of a
1201 database in the C<databases> array (same numbering as C<join_map>). Each
1202 B<value> is a criteria hashref in the same format as C<selectall_arrayref>
1203 accepts.
1204  
1205 B<Key-set semantics>
1206  
1207 A filtered database always acts as an inner-join partner, regardless of the
1208 C<join_type> setting. Any join-key value that does not pass the filter is
1209 excluded from the merged output entirely -- not just missing its secondary
1210 columns. This ensures the filter genuinely restricts the view rather than
1211 simply hiding a few fields.
1212  
1213 B<Criteria merging>
1214  
1215 When a query call also passes a criterion for a column that already has a base
1216 filter, the two constraints are combined:
1217  
1218 =over 4
1219  
1220 =item *
1221  
1222 When both the base filter value and the query criterion are operator hashrefs
1223 (e.g. C<< { '>' => 60 } >> and C<< { '<' => 365 } >>), their operators are
1224 merged: I<both> constraints apply simultaneously (AND semantics).
1225  
1226 =item *
1227  
1228 When either value is a plain scalar, or the operators conflict, the
1229 query-time criterion wins and the base filter for that column is ignored for
1230 that one call.
1231  
1232 =back
1233  
1234 B<Example -- only show orders placed more than 60 days ago>
1235  
1236 my $join = Database::Join->new(
1237 databases => [ $customers, $orders ],
1238 join_column => 'entry',
1239 filters => { 1 => { age_days => { '>' => 60 } } },
1240 );
1241  
1242 # Every query automatically sees only old orders
1243 my $rows = $join->selectall_arrayref();
1244  
1245 # Additional criteria layer on top -- gold tier AND old order
1246 my $vip = $join->selectall_arrayref(tier => 'gold');
1247  
1248 # Range intersection: age_days > 60 AND age_days < 365
1249 my $mid = $join->selectall_arrayref(age_days => { '<' => 365 });
1250  
1251 When using C<add_database>, pass C<filter> (singular) to set the base
1252 criteria for the new database:
1253  
1254 $join->add_database($orders, filter => { age_days => { '>' => 60 } });
1255  
1256 =head2 base_criteria - permanent view-level row filters by column name
1257  
1258 C<base_criteria> is a convenience alternative to C<filters> for callers who
1259 know the column names they want to restrict but prefer not to track database
1260 indices.
1261  
1262 my $join = Database::Join->new(
1263 databases => [ $customers, $orders ],
1264 join_column => 'entry',
1265 base_criteria => { active => 1, deleted_at => undef },
1266 );
1267  
1268 # Every query automatically sees only active, non-deleted rows.
1269 my $rows = $join->selectall_arrayref();
1270  
1271 At construction time C<base_criteria> is partitioned by column ownership
1272 using the same routing logic as C<selectall_arrayref>. Each criterion is
1273 sent to the database that owns that column and stored as a permanent base
1274 filter (equivalent to the corresponding C<filters> entry).
1275  
1276 B<Unknown columns> emit a C<warn_unknown_column> carp and are silently
1277 dropped, just as they would be in a query call.
1278  
1279 B<Key-set semantics> are identical to C<filters>: any database that receives
1280 a C<base_criteria> slice acts as an inner-join partner regardless of
1281 C<join_type>.
1282  
1283 B<Precedence>: when a column appears in both C<base_criteria> and C<filters>,
1284 the C<filters> entry wins on plain-scalar conflicts; operator-hashref values
1285 are combined with AND semantics.
1286  
1287 B<Use cases>
1288  
1289 =over 4
1290  
1291 =item *
1292  
1293 Row-level security: C<< base_criteria => { tenant_id => $tid } >>
1294  
1295 =item *
1296  
1297 Soft-delete filtering: C<< base_criteria => { deleted_at => undef } >>
1298  
1299 =item *
1300  
1301 Status gates: C<< base_criteria => { active => 1 } >>
1302  
1303 =back
1304  
1305 =head2 mandatory_filters - row-level security predicates that cannot be bypassed
1306  
1307 C<mandatory_filters> is an arrayref of C<{col, op, val}> predicate hashrefs.
1308 Every predicate is applied to the merged result of every query, regardless of
1309 what criteria the caller passes. Unlike C<filters> and C<base_criteria> (which
1310 are per-database constraints applied at fetch time), C<mandatory_filters>
1311 operates on the fully-merged row set, ensuring the constraint applies uniformly
1312 even when the same logical value is spread across multiple databases.
1313  
1314 my $join = Database::Join->new(
1315 databases => [ $customers, $loyalty ],
1316 join_column => 'entry',
1317 mandatory_filters => [
1318 { col => 'region', op => 'eq', val => 'West' },
1319 { col => 'tier', op => 'ne', val => 'banned' },
1320 { col => 'balance', op => 'gte', val => 0 },
1321 ],
1322 );
1323  
1324 Each predicate hashref must supply exactly these three keys:
1325  
1326 =over 4
1327  
1328 =item C<col>
1329  
1330 The column name in the merged view (as returned by C<columns()>). Must be
1331 present at construction time; columns added later via C<add_database()> are not
1332 retroactively covered by predicates already in C<_mandatory_filters>.
1333  
1334 =item C<op>
1335  
1336 The comparison operator. Supported values:
1337  
1338 eq -- string equality ($row->{col} eq $val)
1339 ne -- string inequality ($row->{col} ne $val)
1340 lt -- string less-than ($row->{col} lt $val)
1341 lte -- string <= ($row->{col} le $val)
1342 gt -- string greater-than ($row->{col} gt $val)
1343 gte -- string >= ($row->{col} ge $val)
1344 like -- SQL LIKE pattern (% = any sequence, _ = any one character)
1345 contains -- substring match (row value must contain val as a substring)
1346  
1347 Comparisons are lexicographic (string-based) on the array path; on the SQLite
1348 path they follow SQLite's default collation for the column type. Use the
1349 SQLite backend (C<backend =E<gt> 'sqlite'>) when numeric ordering matters.
1350  
1351 =item C<val>
1352  
1353 The right-hand side of the comparison. Must be a plain scalar.
1354  
1355 =back
1356  
1357 B<Supported use cases>
1358  
1359 =over 4
1360  
1361 =item *
1362  
1363 Row-level security: restrict the view to rows the current session is authorised
1364 to see: C<< { col => 'tenant_id', op => 'eq', val => $session_tenant } >>
1365  
1366 =item *
1367  
1368 Data classification gates: hide rows marked with a sensitivity label:
1369 C<< { col => 'classification', op => 'ne', val => 'restricted' } >>
1370  
1371 =item *
1372  
1373 Substring/pattern guards:
1374 C<< { col => 'email', op => 'contains', val => '@example.com' } >>
1375 or C<< { col => 'code', op => 'like', val => 'PROD_%' } >>
1376  
1377 =back
1378  
1379 B<SECURITY: C<mandatory_filters> must never be set from user-supplied values>
1380  
1381 The predicates in C<mandatory_filters> are an enforcement boundary. They must
1382 come from a trusted server-side source (a session store, a policy table, or
1383 hard-coded application configuration) -- never from URL parameters, form fields,
1384 HTTP headers, or any other user-controlled input. Setting this parameter from
1385 user-supplied data would allow an attacker to widen or replace the constraints
1386 and access rows they are not permitted to see.
1387  
1388 B<Array vs. SQLite backend>
1389  
1390 On the B<array backend>, C<mandatory_filters> is applied as a Perl-side C<grep>
1391 after the in-memory merge, immediately before C<sort_by>/C<limit>/C<offset>.
1392 A row that does not satisfy every predicate is silently dropped.
1393  
1394 On the B<SQLite backend>, each predicate is translated into a parameterised
1395 C<WHERE> clause and injected into the per-call SQL query. Values are always
1396 passed via DBI bind parameters, never by string interpolation.
1397  
1398 Both backends produce identical filtered results.
1399  
1400 =head2 distinct - deduplicate merged rows
1401  
1402 Pass C<< distinct => 1 >> to C<selectall_arrayref> or C<selectall_array> to
1403 remove duplicate rows from the merged result.
1404  
1405 # All unique tier values
1406 my $tiers = $join->selectall_arrayref(
1407 distinct => 1,
1408 columns => ['tier'],
1409 );
1410  
1411 # All unique region + tier combinations
1412 my $combos = $join->selectall_arrayref(
1413 distinct => 1,
1414 columns => ['region', 'tier'],
1415 );
1416  
1417 # Remove fully-identical merged rows (all columns participate)
1418 my $deduped = $join->selectall_arrayref(distinct => 1);
1419  
1420 The optional C<columns> arrayref projects each row to the named columns I<before>
1421 deduplication. Omitting C<columns> (or passing an empty arrayref) deduplicates
1422 on the full merged row: two rows must be identical in every column to be
1423 considered duplicates.
1424  
1425 B<Array backend>: deduplication is done in Perl using a seen-hash keyed on the
1426 selected column values. First occurrence wins.
1427  
1428 B<SQLite backend>: C<SELECT DISTINCT col1, col2, ...> is used; the SQL engine
1429 handles deduplication.
1430  
1431 Both backends produce identical results.
1432  
1433 B<Interaction with sort_by / limit / offset>: C<distinct> is applied first
1434 (before pagination and ordering), so C<limit> and C<offset> operate on the
1435 already-deduplicated set.
1436  
1437 =head2 collision_prefix - preserve colliding columns from secondary databases
1438  
1439 By default, when a column name appears in more than one database the I<last>
1440 database wins: its value silently overwrites earlier ones in merged rows.
1441 This loses data and makes the origin invisible.
1442  
1443 C<collision_prefix> changes this for secondary databases you designate.
1444 When a secondary database at index N has a column that already exists in the
1445 merged view, and C<collision_prefix-E<gt>{N}> is set, the colliding column is
1446 published as C<"$prefix.$col"> instead of overwriting. Both values are then
1447 visible: the original column keeps its name (from the earlier database), and
1448 the collision gets the prefixed name.
1449  
1450 C<collision_prefix> is a hashref. Each B<key> is the B<zero-based index> of
1451 a secondary database in the C<databases> array (same numbering as C<join_map>).
1452 Each B<value> is the prefix string to prepend. An index-0 entry is
1453 meaningless and silently ignored. Omitting C<collision_prefix> entirely
1454 preserves the previous last-wins behaviour and changes nothing.
1455  
1456 Non-colliding columns from a secondary database are always added as-is with
1457 no prefix, whether or not C<collision_prefix> is configured.
1458  
1459 B<Example -- sales table and products table, both with a "product" column>
1460  
1461 # $sales columns: id, product, amount, date
1462 # $products columns: sku, product, price, category
1463 # join on 'product' (left key) matched against 'sku' (right key via join_map)
1464  
1465 my $join = Database::Join->new(
1466 databases => [$sales, $products],
1467 join_column => 'product',
1468 join_map => { 1 => 'sku' },
1469 collision_prefix => { 1 => 'products' },
1470 );
1471  
1472 $join->columns;
1473 # => ['amount', 'category', 'date', 'id', 'price', 'product', 'products.product']
1474 # ^-- prefixed collision
1475  
1476 my $row = $join->fetchrow_hashref(product => 'widget');
1477 # $row->{product} -- value from $sales
1478 # $row->{'products.product'} -- value from $products (different row, same column name)
1479 # $row->{price} -- from $products, no collision, kept as-is
1480  
1481 B<Querying on a prefixed column>
1482  
1483 Use the full published name as the criterion key:
1484  
1485 my $rows = $join->selectall_arrayref('products.product' => 'widget');
1486 # Internally routes as: product => 'widget' to $products
1487  
1488 B<Interaction with remove_column>
1489  
1490 C<remove_column> operates on published names. To suppress a prefixed
1491 collision column entirely, pass the prefixed name:
1492  
1493 $join->remove_column('products.product');
1494  
1495 =head2 backend - SQLite join backend for large datasets
1496  
1497 C<Database::Join> can merge component databases in two different ways,
1498 controlled by the C<backend> constructor parameter.
1499  
1500 =over 4
1501  
1502 =item C<backend =E<gt> 'array'> -- in-memory merge (original behaviour)
1503  
1504 All matching rows are fetched from every component database into Perl hashes
1505 and merged there. Simple and fast for small and medium datasets. Peak RAM
1506 is roughly three times the combined source data size (one copy per database
1507 plus one merged copy).
1508  
1509 =item C<backend =E<gt> 'sqlite'> -- SQL JOIN via a cached temporary file
1510  
1511 C<Database::Join> creates a temporary SQLite database file, spills source
1512 rows into it (one table per component database), then executes a single SQL
1513 C<JOIN> statement per query call. Peak RAM drops to roughly one times the
1514 source data size.
1515  
1516 The temporary file is created once and reused across multiple query calls on
1517 the same object (the cache). Only query-time criteria vary per call; they
1518 are applied as SQL C<WHERE> clauses against the cached data. The cache is
1519 automatically rebuilt when any source database's C<updated()> timestamp
1520 changes. The file is deleted when the object is destroyed (goes out of
1521 scope). See I<Temporary file: name, location, and lifetime> below for
1522 details.
1523  
1524 Requires C<DBD::SQLite E<gt>= 1.70> (C<FULL OUTER JOIN> support was added in
1525 SQLite 3.39.0; DBD::SQLite 1.70 ships SQLite 3.39.2).
1526  
1527 =item C<backend =E<gt> 'auto'> (default)
1528  
1529 C<Database::Join> counts the total rows from all component databases cheaply
1530 -- without fetching them -- and then decides:
1531  
1532 =over 4
1533  
1534 =item *
1535  
1536 If the combined count is less than or equal to C<max_array_rows> (default
1537 10,000), use the array path.
1538  
1539 =item *
1540  
1541 If the combined count exceeds C<max_array_rows>, use the SQLite path.
1542  
1543 =back
1544  
1545 For counting to work without fetching, each component database must either
1546 implement the C<dbi_source()> interface (for SQLite-backed sources, where a
1547 C<COUNT(*)> SQL query is issued directly), or directly define a C<count()>
1548 method in its own package -- not just inherit one from a parent class. If
1549 neither is available for a particular database, C<Database::Join> plays it
1550 safe and uses the array path for the whole query without fetching any rows.
1551  
1552 =back
1553  
1554 B<Choosing max_array_rows>
1555  
1556 The default of 10,000 is a reasonable starting point. Adjust it to match
1557 your hardware and typical row width. For wide rows (many columns or long
1558 strings) you may want a lower threshold; for narrow rows you can raise it.
1559  
1560 B<Temporary file: name, location, and lifetime>
1561  
1562 When the SQLite path is active, a single temporary SQLite database file acts
1563 as the join cache for the life of the C<Database::Join> object.
1564  
1565 B<Name>: the filename is randomly generated by C<File::Temp>, for example:
1566  
1567 /tmp/Cj8xK7mP2Q.db
1568  
1569 The random portion (ten characters) is chosen automatically to avoid
1570 collisions. Only the directory is under your control; you cannot specify
1571 the filename itself.
1572  
1573 B<Location>: controlled by the C<tmpdir> constructor parameter.
1574 If C<tmpdir> is not specified, C<File::Spec-E<gt>tmpdir()> is used (usually
1575 C</tmp> on Unix, or the value of the C<TEMP> or C<TMP> environment variable
1576 on Windows).
1577  
1578 B<Lifetime: one file per object, deleted when the object is destroyed>: the
1579 file is created on the first query call that uses the SQLite path and kept
1580 alive until the C<Database::Join> object is destroyed (i.e. when it goes out
1581 of scope or is explicitly C<undef>-d). At most one file exists per object at
1582 any given moment. Calling C<selectall_arrayref()> ten times on the same
1583 object creates and uses I<one> file, not ten.
1584  
1585 B<Cache invalidation>: the cache is automatically rebuilt (the old file is
1586 replaced with a new one) when any source database's C<updated()> return value
1587 changes, or when C<add_database()> is called. Base-filter criteria
1588 (C<filters> constructor parameter) are applied once at build time for spilled
1589 sources; query-time criteria are applied per-call as SQL C<WHERE> clauses.
1590  
1591 To use a different directory -- for example a RAM-backed filesystem or a
1592 faster local disk:
1593  
1594 my $join = Database::Join->new(
1595 databases => [ $db1, $db2 ],
1596 join_column => 'entry',
1597 backend => 'sqlite',
1598 tmpdir => '/dev/shm', # Linux RAM disk
1599 );
1600  
1601 B<Parallel secondary fetches (C<parallel> constructor parameter)>
1602  
1603 By default, component databases are queried sequentially - the primary first,
1604 then each secondary in order. When the component databases are network- or
1605 disk-backed and have non-trivial per-query latency, the sequential fetch means
1606 total latency is the I<sum> of all per-DA latencies.
1607  
1608 Setting C<< parallel => 1 >> in the constructor enables concurrent fetching
1609 of secondary databases using Perl C<threads>. With C<parallel => 1> and
1610 two or more secondary databases (C<n E<gt> 2> total), secondary fetches run in
1611 parallel after the primary fetch completes; total latency drops to
1612 I<max(secondary latencies)> instead of I<sum(secondary latencies)>.
1613  
1614 my $join = Database::Join->new(
1615 databases => [ $customers, $loyalty, $scores ], # 3 DAs - 2 secondaries
1616 join_column => 'entry',
1617 parallel => 1, # loyalty and scores fetched concurrently
1618 );
1619  
1620 Requirements and caveats:
1621  
1622 =over 4
1623  
1624 =item *
1625  
1626 The C<threads> module must be available. Most distributions ship it, but it
1627 requires a Perl binary compiled with C<-Dusethreads>. When threads are
1628 unavailable, a C<carp> warning is emitted and fetching falls back to
1629 sequential; the result is identical, only slower.
1630  
1631 =item *
1632  
1633 Parallel fetching is only active when the join has three or more total
1634 databases (C<n E<gt> 2>). With two databases (one secondary), the thread
1635 creation overhead exceeds the benefit of concurrency; sequential is used
1636 regardless of C<parallel>.
1637  
1638 =item *
1639  
1640 Component databases must be safe to call from Perl threads. In-memory
1641 databases (CSV, JSON, TSV after slurp) are safe. DBI-backed databases
1642 whose handles were created in the same thread may not be safe - consult your
1643 DBD driver's thread documentation. The array backend is recommended for
1644 DBI-backed sources; the SQLite backend performs its join in a single SQL
1645 statement and does not use parallel fetching.
1646  
1647 =item *
1648  
1649 C<parallel => 1> applies to the array backend only. The SQLite backend
1650 performs a single SQL JOIN after spilling source data, so per-DA parallelism
1651 is irrelevant.
1652  
1653 =back
1654  
1655 B<Zero-copy ATTACH (C<dbi_source()> interface)>
1656  
1657 Normally, when the SQLite path is active, rows from each component database
1658 are fetched one by one and inserted into the temporary SQLite file. This is
1659 efficient but does involve INSERT overhead.
1660  
1661 If a component database is itself SQLite-backed and implements a
1662 C<dbi_source()> method, C<Database::Join> can skip the row-by-row copy
1663 entirely and instead use C<ATTACH DATABASE> to link the source file directly
1664 to the temporary join connection. This is the zero-copy path and is
1665 significantly faster for large SQLite sources.
1666  
1667 The C<dbi_source()> method must return a hashref with two keys:
1668  
1669 =over 4
1670  
1671 =item C<dbh>
1672  
1673 A connected C<DBD::SQLite> database handle (C<DBI> connection object).
1674  
1675 =item C<table>
1676  
1677 The name of the table in that database that holds the source rows.
1678  
1679 =back
1680  
1681 Example implementation:
1682  
1683 package My::SQLiteDatabase;
1684 use parent 'Database::Abstraction';
1685  
1686 sub dbi_source {
1687 my ($self) = @_;
1688 return {
1689 dbh => $self->{_dbh}, # connected DBD::SQLite handle
1690 table => $self->{_table}, # table name in that database
1691 };
1692 }
1693  
1694 1;
1695  
1696 The zero-copy ATTACH path is always used when a component database implements
1697 C<dbi_source()>. Query-time criteria are applied as parameterised SQL
1698 C<WHERE> clauses against the ATTACHed source table, so no row-level copy is
1699 needed even when the current call includes column filters. (Prior to 0.005.0
1700 any query-time criteria forced a spill; that restriction was removed in
1701 0.005.0.)
1702  
1703 B<Result identity>
1704  
1705 Both the array path and the SQLite path produce identical results for any
1706 given query. You can switch between them freely without changing callers.
1707 The C<collision_prefix> column renaming, C<join_map> key translation, and all
1708 three join types (left, inner, outer) work identically on both paths.
1709  
1710 =head2 selectall_arrayref
1711  
1712 =head3 SYNOPSIS
1713  
1714 my $rows = $join->selectall_arrayref();
1715 my $rows = $join->selectall_arrayref(tier => 'gold');
1716 my $rows = $join->selectall_arrayref(score => { '>' => 80 });
1717 my $rows = $join->selectall_arrayref('C001'); # positional: entry => 'C001'
1718 my $rows = $join->selectall_arrayref(sort_by => 'name');
1719 my $rows = $join->selectall_arrayref(tier => 'gold', sort_by => ['score', 'DESC']);
1720 my $rows = $join->selectall_arrayref(limit => 10);
1721 my $rows = $join->selectall_arrayref(limit => 10, offset => 20);
1722 my $rows = $join->selectall_arrayref(tier => 'gold', sort_by => 'name', limit => 5);
1723 my $rows = $join->selectall_arrayref(distinct => 1, columns => ['tier']);
1724 my $rows = $join->selectall_arrayref(distinct => 1); # distinct on all columns
1725  
1726 =head3 DESCRIPTION
1727  
1728 Returns an arrayref of hashrefs representing the merged view of all component
1729 databases, optionally filtered by the given criteria.
1730  
1731 Criteria for columns that live in different databases are routed
1732 automatically: each database is queried with only the criteria that apply to
1733 its own columns. The results are combined in memory using C<join_column>.
1734 Under a C<left> or C<inner> join, a secondary database is also limited to the
1735 primary's keys (see "Key pushdown" in L</DESCRIPTION>).
1736  
1737 Accepts the same criteria syntax as C<Database::Abstraction::selectall_arrayref>.
1738 A single plain scalar argument is interpreted as the C<join_column> value
1739 (equivalent to C<< entry => 'C001' >> when C<join_column> is C<'entry'>).
1740  
1741 Pass C<< distinct => 1 >> (with optional C<< columns => \@cols >>) to
1742 deduplicate results; see the C<distinct> feature section for details.
1743  
1744 =head3 API SPECIFICATION
1745  
1746 =head4 Input
1747  
1748 Calling conventions (in order of precedence):
1749 1. No arguments -- returns all rows
1750 2. One plain scalar -- shorthand for join_column => $scalar
1751 3. Key-value pairs or
1752 a criteria hashref -- routed per-database
1753  
1754 Values may be:
1755 Plain scalar -- exact match
1756 Hashref of operators -- e.g. { '>' => 80 }
1757  
1758 Optional parameters (mixed in with any of the above):
1759 sort_by => 'colname' -- sort ascending by that column
1760 sort_by => ['colname', 'DESC'] -- sort descending
1761 sort_by => ['colname', 'ASC'] -- sort ascending (explicit)
1762 limit => N -- return at most N rows (positive integer)
1763 offset => M -- skip the first M rows (non-negative integer)
1764  
1765 The column named in sort_by must be present in the merged view (i.e. it
1766 must appear in columns()). An unknown column or an invalid direction emits
1767 a carp warning and falls back to the default join_column ascending sort.
1768  
1769 limit and offset are applied after ordering. offset without limit skips
1770 rows but returns all remaining rows. limit without offset starts from
1771 the first qualifying row. An invalid limit or offset emits a carp warning
1772 and the parameter is ignored (treated as absent).
1773  
1774 DOMAIN -- sort_by:
1775 EP absent: result sorted by join_column ASC (default).
1776 EP string: any column name in columns(); sorts ASC by that column.
1777 EP ['col','ASC']: explicit ascending; equivalent to the string form.
1778 EP ['col','DESC']: descending sort by the named column.
1779 EP ['col']: single-element arrayref; direction defaults to ASC.
1780 EP []: empty arrayref; column is undef -> carp + join_col ASC fallback.
1781 EP invalid column: column not in columns() -> carp + join_col ASC fallback.
1782 EP invalid dir: direction not 'ASC' or 'DESC' -> carp + ASC used.
1783 Sort is lexicographic (cmp); use backend=>'sqlite' for numeric ORDER BY.
1784  
1785 DOMAIN -- limit:
1786 EP absent: no truncation; all qualifying rows are returned.
1787 EP 0: not a positive integer -> carp + ignored (all rows returned).
1788 BVA min valid = 1: exactly 1 row returned.
1789 BVA at count: limit == total rows -> all rows returned (no truncation).
1790 BVA above count: limit > total rows -> all rows returned.
1791 EP invalid: negative integer, float string, or non-numeric string
1792 => carp + ignored (all rows returned).
1793 Valid domain: integers in [1, INF); matched by /^\d+\z/a with value >= 1.
1794  
1795 DOMAIN -- offset:
1796 EP absent: no rows skipped; result starts from row 0.
1797 BVA min valid = 0: no rows skipped (zero is a valid non-negative integer).
1798 BVA offset=1: first row skipped; result starts from row 1.
1799 BVA offset=N-1: N-1 rows skipped; only the last row returned.
1800 BVA offset=N: all N rows skipped; empty result returned.
1801 BVA offset>N: all rows skipped; empty result returned.
1802 EP invalid: negative integer, float string, or non-numeric string
1803 => carp + ignored (no rows skipped).
1804 Valid domain: integers in [0, INF); matched by /^\d+\z/a.
1805  
1806 distinct => 1 -- deduplicate rows after the merge (see columns below)
1807 columns => \@cols -- arrayref of column names to project and deduplicate on;
1808 used together with distinct => 1
1809  
1810 DOMAIN -- distinct:
1811 EP absent or 0: no deduplication; all merged rows are returned.
1812 EP 1: duplicates are removed (see below); first occurrence wins.
1813 EP truthy (not 1): treated as truthy; deduplication is applied.
1814 Effect: on the array backend, a Perl seen-hash keyed on the
1815 selected column values is used; first occurrence wins.
1816 On the SQLite backend, SELECT DISTINCT is used.
1817  
1818 DOMAIN -- columns:
1819 EP absent/undef: when distinct is set, deduplication is on all columns
1820 and full rows are returned.
1821 EP []: empty arrayref treated the same as absent.
1822 EP valid: arrayref of column names present in the merged view;
1823 result rows are projected to those columns only, and
1824 deduplication is on the projected values.
1825 EP with distinct=0: columns is ignored when distinct is absent or false.
1826 Note: unknown column names in the list are silently ignored
1827 at projection time; the row may lack those keys.
1828  
1829 =head4 Output
1830  
1831 Arrayref of hashrefs; one hashref per qualifying merged row.
1832 Sorted ascending by join_column by default; caller-controlled via sort_by.
1833 At most C<limit> rows when limit is given; the first C<offset> rows are
1834 skipped when offset is given.
1835 Returns a reference to an empty array when no rows match.
1836  
1837 =head3 EXAMPLE
1838  
1839 # All rows from both databases
1840 my $all = $join->selectall_arrayref();
1841  
1842 # Only rows where the 'tier' column (from the loyalty database)
1843 # equals 'gold' -- the criterion is routed to the right database
1844 my $vip = $join->selectall_arrayref(tier => 'gold');
1845  
1846 # Operator hashref: score > 80
1847 my $high = $join->selectall_arrayref(score => { '>' => 80 });
1848  
1849 # Access each merged row
1850 for my $row (@{$vip}) {
1851 printf "%-10s tier=%-8s score=%d\n",
1852 $row->{entry}, $row->{tier}, $row->{score} // 0;
1853 }
1854  
1855 # Distinct tier values across all rows (project to one column, deduplicate)
1856 my $tiers = $join->selectall_arrayref(distinct => 1, columns => ['tier']);
1857 # Returns e.g. [{ tier => 'gold' }, { tier => 'silver' }, { tier => 'bronze' }]
1858 # regardless of how many rows exist for each tier
1859  
1860 # Distinct region+tier combinations
1861 my $combos = $join->selectall_arrayref(
1862 distinct => 1,
1863 columns => ['region', 'tier'],
1864 );
1865  
1866 # Distinct on all columns (remove fully-duplicate merged rows)
1867 my $deduped = $join->selectall_arrayref(distinct => 1);
1868  
1869 =head3 MESSAGES
1870  
1871 warn_unknown_column (carp)
1872 -- A criterion key names a column not present in any component database;
1873 the criterion is silently dropped and all rows are returned.
1874 error_join_criterion (croak)
1875 -- A criterion hashref contains a join => key (DA SQL-JOIN syntax).
1876 Use a separate DA object for the joined table instead.
1877 sort_by column unknown (carp)
1878 -- The column given in sort_by is not in the merged view; the result
1879 is returned in the default join_column ascending order instead.
1880 sort_by direction invalid (carp)
1881 -- The direction given in sort_by is not 'ASC' or 'DESC'; ASC is used.
1882 limit invalid (carp)
1883 -- The value given for limit is not a positive integer; it is ignored.
1884 offset invalid (carp)
1885 -- The value given for offset is not a non-negative integer; it is ignored.
1886 operator-unsupported (carp, SQLite/auto path only)
1887 -- An operator hashref key is not in the supported set (>, <, >=, <=,
1888 !=, =, LIKE, NOT LIKE, IS NULL, IS NOT NULL, IN, NOT IN); the
1889 individual operator term is dropped from the WHERE clause (other
1890 operators in the same hashref still apply).
1891 IN/NOT IN wrong value type (carp, SQLite/auto path only)
1892 -- An IN or NOT IN criterion was given a non-arrayref value; the operator
1893 term is skipped.
1894 error_sqlite_connect (croak, SQLite/auto path only)
1895 -- The temporary SQLite join file could not be created; check tmpdir
1896 permissions and available disk space.
1897  
1898 =cut
1899  
1900 787 ▶sub selectall_arrayref {
Subroutine selectall_arrayref: called CC=1 SCAR=0.0
Pod documented
1901 787 my ($self, @args) = @_;
1902 787 my $params = $self->_parse_query_args(undef, @args);
1903 787 my $sort_by = delete $params->{sort_by};
1904 787 my $limit = delete $params->{limit};
1905 787 my $offset = delete $params->{offset};
1906 787 my $distinct = delete $params->{distinct};
1907 787 my $columns = delete $params->{columns};
1908 787 return $self->_joined_query($params,
1909 sort_by => $sort_by, limit => $limit, offset => $offset,
1910 distinct => $distinct, columns => $columns);
1911 }
1912  
1913 =head2 selectall_array
1914  
1915 =head3 SYNOPSIS
1916  
1917 my @rows = $join->selectall_array(tier => 'gold');
1918  
1919 # Scalar context: only the first matching row
1920 my $first = $join->selectall_array(entry => 'C001');
1921  
1922 # Distinct column projection (list context)
1923 my @tiers = $join->selectall_array(distinct => 1, columns => ['tier']);
1924  
1925 # Distinct on all columns
1926 my @deduped = $join->selectall_array(distinct => 1);
1927  
1928 =head3 DESCRIPTION
1929  
1930 In list context returns a list of merged hashrefs -- the same rows that
1931 C<selectall_arrayref> would return, just as a flat list rather than an
1932 arrayref.
1933  
1934 In scalar context returns only the first matching hashref (or C<undef> if
1935 nothing matches).
1936  
1937 =head3 API SPECIFICATION
1938  
1939 =head4 Input
1940  
1941 Same as selectall_arrayref.
1942  
1943 =head4 Output
1944  
1945 List context: list of hashrefs (may be empty).
1946 Scalar context: single hashref or undef.
1947  
1948 =head3 EXAMPLE
1949  
1950 my @all = $join->selectall_array();
1951 print scalar @all, " rows\n";
1952  
1953 # First gold-tier customer only
1954 my $first_vip = $join->selectall_array(tier => 'gold');
1955 print $first_vip->{name}, "\n" if defined $first_vip;
1956  
1957 =head3 MESSAGES
1958  
1959 Same messages as C<selectall_arrayref>.
1960  
1961 =cut
1962  
1963 22 ▶sub selectall_array {
Subroutine selectall_array: called CC=2 SCAR=6.9
Pod documented
1964 22 my ($self, @args) = @_;
1965 22 my $params = $self->_parse_query_args(undef, @args);
1966 22 my $sort_by = delete $params->{sort_by};
1967 22 my $limit = delete $params->{limit};
1968 22 my $offset = delete $params->{offset};
1969 22 my $distinct = delete $params->{distinct};
1970 22 my $columns = delete $params->{columns};
1971 22 my $rows = $self->_joined_query($params,
1972 sort_by => $sort_by, limit => $limit, offset => $offset,
1973 distinct => $distinct, columns => $columns);
1974 22 ▶ return wantarray ? @{$rows} : $rows->[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 13 9 22
1975 }
1976  
1977 =head2 selectall_hashref
1978  
1979 Deprecated alias for L</selectall_arrayref>, present for compatibility with
1980 callers written against C<Database::Abstraction>'s deprecated API. Use
1981 C<selectall_arrayref> in new code.
1982  
1983 =cut
1984  
1985 5 ▶sub selectall_hashref {
Subroutine selectall_hashref: called CC=1 SCAR=0.0
Pod documented
1986 5 my $self = shift;
1987 5 carp 'Database::Join::selectall_hashref is deprecated; use selectall_arrayref';
1988 5 return $self->selectall_arrayref(@_);
1989 }
1990  
1991 =head2 selectall_hash
1992  
1993 Deprecated alias for L</selectall_array>, present for compatibility with
1994 callers written against C<Database::Abstraction>'s deprecated API. Use
1995 C<selectall_array> in new code.
1996  
1997 =cut
1998  
1999 5 ▶sub selectall_hash {
Subroutine selectall_hash: called CC=1 SCAR=0.0
Pod documented
2000 5 my $self = shift;
2001 5 carp 'Database::Join::selectall_hash is deprecated; use selectall_array';
2002 5 return $self->selectall_array(@_);
2003 }
2004  
2005 =head2 fetchrow_hashref
2006  
2007 =head3 SYNOPSIS
2008  
2009 my $row = $join->fetchrow_hashref(entry => 'C001');
2010 my $row = $join->fetchrow_hashref('C001'); # positional shorthand
2011  
2012 =head3 DESCRIPTION
2013  
2014 Returns a single merged hashref for the first row matching the given
2015 criteria, or C<undef> when nothing matches.
2016  
2017 Equivalent to calling C<selectall_arrayref> and taking only the first element.
2018 All the same criteria conventions apply.
2019  
2020 =head3 API SPECIFICATION
2021  
2022 =head4 Input
2023  
2024 Same as selectall_arrayref.
2025  
2026 =head4 Output
2027  
2028 Hashref, or undef when no row matches.
2029  
2030 =head3 EXAMPLE
2031  
2032 my $row = $join->fetchrow_hashref(entry => 'C001');
2033 if (defined $row) {
2034 print "Name: $row->{name}, Tier: $row->{tier}\n";
2035 } else {
2036 print "No record for C001\n";
2037 }
2038  
2039 # Positional: works when join_column is 'entry'
2040 my $row2 = $join->fetchrow_hashref('C001');
2041  
2042 =head3 MESSAGES
2043  
2044 Same messages as C<selectall_arrayref>.
2045  
2046 =cut
2047  
2048 68 ▶sub fetchrow_hashref {
Subroutine fetchrow_hashref: called CC=1 SCAR=0.0
Pod documented
2049 68 my ($self, @args) = @_;
2050 68 my $params = $self->_parse_query_args(undef, @args);
2051 68 my $sort_by = delete $params->{sort_by};
2052 68 delete $params->{limit}; # fetchrow_hashref always returns one row; limit is meaningless
2053 68 delete $params->{offset}; # offset would change which row is "first"; not supported here
2054 68 my $rows = $self->_joined_query($params, sort_by => $sort_by);
2055 68 return $rows->[0];
2056 }
2057  
2058 =head2 count
2059  
2060 =head3 SYNOPSIS
2061  
2062 my $total = $join->count();
2063 my $active = $join->count(tier => 'gold');
2064  
2065 =head3 DESCRIPTION
2066  
2067 Returns the number of merged rows that satisfy the given criteria.
2068  
2069 On the array backend, the full in-memory join is performed and the resulting
2070 rows are counted in Perl. On the SQLite backend, a C<SELECT COUNT(*)> SQL
2071 query is executed against the cached join tables, avoiding a full row fetch.
2072  
2073 =head3 API SPECIFICATION
2074  
2075 =head4 Input
2076  
2077 Same criteria syntax as selectall_arrayref.
2078  
2079 =head4 Output
2080  
2081 Non-negative integer.
2082  
2083 =head3 EXAMPLE
2084  
2085 my $total = $join->count();
2086 my $gold = $join->count(tier => 'gold');
2087 my $high = $join->count(score => { '>' => 90 });
2088  
2089 printf "%d total, %d gold-tier, %d high-scorers\n",
2090 $total, $gold, $high;
2091  
2092 =head3 MESSAGES
2093  
2094 Same messages as C<selectall_arrayref>.
2095  
2096 =cut
2097  
2098 79 ▶sub count {
Subroutine count: called CC=2 SCAR=6.9
Pod documented
2099 79 my ($self, @args) = @_;
2100 79 my $params = $self->_parse_query_args(undef, @args);
2101 79 delete $params->{sort_by}; # row ordering is irrelevant for a count
2102 79 delete $params->{limit}; # count returns total matching rows, not a page
2103 79 delete $params->{offset};
2104 # On the SQLite path, push COUNT(*) into SQL to avoid fetching all rows.
2105 return $self->_sqlite_join($params, count_only => 1)
2106 79 ▶ unless $self->{_backend} eq 'array';
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_backend"} eq "array" 73 6 79
2107 6 return scalar @{ $self->_joined_query_array($params) };
2108 }
2109  
2110 =head2 aggregate
2111  
2112 =head3 SYNOPSIS
2113  
2114 my $rows = $join->aggregate(
2115 by => ['tier'],
2116 measures => [
2117 { col => 'score', fn => 'sum', as => 'total' },
2118 { fn => 'count', as => 'n' },
2119 ],
2120 having => { total => { '>' => 100 } },
2121 sort_by => ['total', 'DESC'],
2122 limit => 10,
2123 );
2124 # => [ { tier => 'gold', total => 183, n => 2 }, ... ]
2125  
2126 =head3 DESCRIPTION
2127  
2128 Groups the merged view by one or more published column names and computes
2129 aggregate measures over each group.
2130  
2131 On the SQLite backend (C<backend =E<gt> 'sqlite'>) and the C<auto> backend,
2132 the aggregation is pushed into the existing SQLite cache as a C<GROUP BY>
2133 query - rows never pass through Perl. The C<auto> backend always takes this
2134 path for aggregation, skipping the row-count threshold probe (aggregation
2135 makes the row count irrelevant).
2136  
2137 On the array backend (C<backend =E<gt> 'array'>), merged rows are fetched in
2138 full and folded in Perl. This materialises the complete matching result set.
2139  
2140 The two paths return the same rows for the same input, except for two
2141 documented differences: C<min>/C<max> on a column declared C<TEXT> but
2142 storing numbers (SQL compares lexically; Perl detects numerics), and
2143 C<sum>/C<avg> with non-numeric values (SQL coerces to 0.0; Perl skips and
2144 warns via C<warn_aggregate_non_numeric>).
2145  
2146 C<Database::Join> has no C<no_fixate> and no CHI cache (unlike
2147 C<Database::Abstraction>); aggregation results are not cached between calls.
2148  
2149 =head3 API SPECIFICATION
2150  
2151 =head4 Input
2152  
2153 Reserved keys extracted before the rest is treated as WHERE criteria:
2154  
2155 by => arrayref of published column names (default: [] = grand total)
2156 measures => arrayref of measure hashrefs (required, non-empty)
2157 having => hashref of post-aggregation criteria
2158 sort_by => 'col' or ['col', 'DESC']
2159 limit => positive integer
2160 offset => non-negative integer
2161  
2162 Every other key is pre-aggregation criteria routed exactly as
2163 C<selectall_arrayref> routes criteria.
2164  
2165 Measure hashref keys:
2166  
2167 fn => function name (sum|avg|min|max|count|count_distinct), case-insensitive
2168 col => published column name (required for all functions except bare count)
2169 as => result key (required; must match C</^\w+\z/>; unique; not a by name)
2170  
2171 C<having> uses the same operator vocabulary as C<selectall_arrayref>:
2172 C<%SAFE_SQL_OPS> (E<gt>, E<lt>, E<gt>=, E<lt>=, !=, =, LIKE, NOT LIKE),
2173 C<%SAFE_LIST_OPS> (IN, NOT IN), C<%SAFE_NOARG_OPS> (IS NULL, IS NOT NULL),
2174 a bare scalar (= ?), and C<-or>/C<-and> groupings. Write C<-between> as
2175 two operators and C<LIKE> explicitly.
2176  
2177 =head4 Output
2178  
2179 Always an arrayref of hashrefs (never C<undef>). C<[]> when no group
2180 qualifies and C<by> is non-empty. When C<by> is omitted or C<[]> and no
2181 rows match, returns one all-normalised row (grand total of zero).
2182  
2183 Key order per row: C<by> columns in declaration order, then measure aliases
2184 in declaration order.
2185  
2186 =head3 EXAMPLE
2187  
2188 # Total score and row count per tier, highest total first
2189 my $rows = $join->aggregate(
2190 by => ['tier'],
2191 measures => [
2192 { col => 'score', fn => 'sum', as => 'total' },
2193 { fn => 'count', as => 'n' },
2194 ],
2195 sort_by => ['total', 'DESC'],
2196 );
2197 for my $r (@{$rows}) {
2198 printf "%s: total=%s n=%s\n", $r->{tier}, $r->{total}, $r->{n};
2199 }
2200  
2201 =head3 PSEUDOCODE
2202  
2203 1. get_params(undef, @args) -- hashref or kv-pairs only (no positional key)
2204 2. croak error_join_criterion if 'join =>' present
2205 3. _validate_aggregate_spec extracts by/measures/having/sort_by/limit/offset
2206 4. array backend:
2207 rows = _joined_query_array(remaining criteria, no sort/limit/offset)
2208 groups = _fold_aggregate(rows, spec)
2209 groups = [grep { _match_criteria($_, having) } @groups] if having
2210 _normalise_aggregate(groups, spec.measures)
2211 _sort_and_page(groups, spec)
2212 sqlite/auto backend:
2213 _sqlite_aggregate(remaining criteria, spec)
2214 5. return groups
2215  
2216 =head3 MESSAGES
2217  
2218 C<error_aggregate_measures_required>, C<error_aggregate_measure_ref>,
2219 C<error_aggregate_fn_unknown>, C<error_aggregate_col_required>,
2220 C<error_aggregate_col_unknown>, C<error_aggregate_as_required>,
2221 C<error_aggregate_as_invalid>, C<error_aggregate_as_duplicate>,
2222 C<error_aggregate_as_collision>, C<error_aggregate_by_invalid>,
2223 C<error_aggregate_having_key>, C<error_aggregate_having_operator>,
2224 C<warn_aggregate_sort_key>, C<warn_aggregate_non_numeric>.
2225  
2226 =cut
2227  
2228 103 ▶sub aggregate {
Subroutine aggregate: called CC=5 SCAR=16.1
Pod documented
2229 103 my ($self, @args) = @_;
2230 103 ▶ my $p = get_params(undef, @args) // {};
Condition100%2/2
get_params(undef, @args) // {}
l!l
1021
MC/DC100%1/1
get_params(undef, @args) // {}
get_params(undef, @args)
Truth table100%2/2
A
A= get_params(undef, @args)
Aresult
11
00
2231  
2232 103 ▶ croak $self->_err('error_join_criterion') if exists $p->{join};
Branch: 1 branch
BranchTrueFalseTotal
if exists $p->{"join"} 1 102 103
2233  
2234 102 my $spec = $self->_validate_aggregate_spec($p);
2235 # After _validate_aggregate_spec, aggregation keys have been deleted from $p.
2236 # Remaining keys in $p are WHERE criteria for the join.
2237  
2238 74 my $backend = $self->{_backend};
2239  
2240 74 ▶ if ($backend eq 'array') {
Branch: 1 branch
BranchTrueFalseTotal
if ($backend eq 'array') { } 37 37 74
2241 # Fetch all matching merged rows without sort/limit/offset —
2242 # those must be applied after grouping.
2243 37 my $merged = $self->_joined_query_array($p);
2244 37 my $groups = $self->_fold_aggregate($merged, $spec);
2245  
2246 # Apply HAVING on the folded groups.
2247 37 ▶ if (my $having = $spec->{having}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $having = $spec->{"having"}) 9 28 37
2248 9 $groups = [grep { $self->_match_criteria($_, $having) } @{$groups}];
2249 }
2250  
2251 37 $self->_normalise_aggregate($groups, $spec->{measures});
2252 37 $self->_sort_and_page($groups, $spec);
2253 37 return $groups;
2254 } else {
2255 # SQLite path (including 'auto'): always use SQL, no threshold probe.
2256 37 return $self->_sqlite_aggregate($p, $spec);
2257 }
2258 }
2259  
2260 =head2 each_row
2261  
2262 =head3 SYNOPSIS
2263  
2264 my $count = $join->each_row(sub { my ($row) = @_; ... });
2265 my $count = $join->each_row(sub { ... }, tier => 'gold');
2266 my $count = $join->each_row(sub { ... }, sort_by => 'name', limit => 100);
2267  
2268 =head3 DESCRIPTION
2269  
2270 Calls C<\&callback> once for every row in the merged view that matches the
2271 given criteria, then returns the total count of rows visited.
2272  
2273 Accepts the same criteria, C<sort_by>, C<limit>, and C<offset> parameters as
2274 C<selectall_arrayref>.
2275  
2276 B<Note on memory usage>: C<Database::Join> always materialises the complete
2277 merged result set before invoking the callback, because merging rows from
2278 multiple independent sources requires that every source be queried and
2279 cross-referenced first. True constant-memory streaming (as C<Database::Abstraction>
2280 provides on single-source SQL queries) is not possible at the join layer.
2281 For genuinely large result sets use the SQLite backend (C<backend =E<gt>
2282 'sqlite'>), which keeps peak RAM to approximately one times the source data
2283 size rather than three.
2284  
2285 Any exception thrown inside the callback propagates to the caller after the
2286 current row; subsequent rows are not visited.
2287  
2288 =head3 API SPECIFICATION
2289  
2290 =head4 Input
2291  
2292 \&callback Positional coderef (required).
2293 Called as $callback->($row_hashref) for each merged row.
2294  
2295 Additional arguments follow the same calling conventions as
2296 selectall_arrayref: no args, a single scalar join-column value,
2297 or key-value criteria pairs (including sort_by, limit, offset).
2298  
2299 =head4 Output
2300  
2301 Non-negative integer: the count of rows for which the callback was invoked.
2302  
2303 =head3 EXAMPLE
2304  
2305 # Print every gold-tier customer's name, sorted by name
2306 my $count = $join->each_row(
2307 sub { my ($row) = @_; print "$row->{name}\n" },
2308 tier => 'gold',
2309 sort_by => 'name',
2310 );
2311 print "$count gold-tier customers\n";
2312  
2313 # Accumulate without holding the full result
2314 my $total_score = 0;
2315 $join->each_row(sub { $total_score += $_[0]->{score} // 0 });
2316  
2317 =head3 MESSAGES
2318  
2319 error_invalid_callback (croak)
2320 -- First argument is not a code reference.
2321  
2322 =cut
2323  
2324 16 ▶sub each_row {
Subroutine each_row: called CC=3 SCAR=11.0
Pod documented
2325 16 my ($self, $cb, @args) = @_;
2326 16 ▶ croak $self->_err('error_invalid_callback')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 5 11 16
2327 unless ref($cb) eq 'CODE';
2328 # Materialise the full merged result first; multi-source joins cannot
2329 # stream rows one at a time because the merge key set is not known until
2330 # all sources have been queried and cross-referenced.
2331 11 my $rows = $self->selectall_arrayref(@args);
2332 11 my $count = 0;
2333 11 for my $row (@{$rows}) {
2334 17 $cb->($row);
2335 16 $count++;
2336 }
2337 10 return $count;
2338 }
2339  
2340 =head2 dbi_source
2341  
2342 =head3 SYNOPSIS
2343  
2344 # Use a Database::Join object as a zero-copy SQLite source inside a
2345 # parent Database::Join, giving the parent ATTACHed-speed access to
2346 # the child's joined data without iterating through Perl.
2347 my $child = Database::Join->new(databases => [$da, $db], join_column => 'id', backend => 'sqlite');
2348 my $parent = Database::Join->new(databases => [$child, $dc], join_column => 'id', backend => 'sqlite');
2349  
2350 =head3 DESCRIPTION
2351  
2352 Returns a hashref C<< { dbh => $sqlite_dbh, table => '_dj_result' } >> that
2353 allows a parent C<Database::Join> (or any other caller that understands the
2354 C<dbi_source()> interface) to ATTACH the child's temporary SQLite database
2355 file and query the materialised join result directly via SQL, without routing
2356 rows through Perl.
2357  
2358 The first call builds the SQLite cache (if not already current) and
2359 materialises the full join result - with C<filters> applied but no query-time
2360 criteria - into a real table named C<_dj_result> inside the cache file.
2361 Subsequent calls within the same cache cycle reuse the existing table.
2362  
2363 Returns C<undef> when the backend is C<'array'> (no SQLite file exists).
2364  
2365 =head3 API SPECIFICATION
2366  
2367 =head4 Input
2368  
2369 None.
2370  
2371 =head4 Output
2372  
2373 On the SQLite/auto backend:
2374 Hashref with keys:
2375 dbh => DBI handle to the child's temporary SQLite database file.
2376 table => '_dj_result' (the materialized join table inside that file).
2377 On the array backend:
2378 undef
2379  
2380 =head3 EXAMPLE
2381  
2382 # The parent automatically ATTACHes the child's SQLite file and queries
2383 # _dj_result for zero-copy composable nested joins.
2384 my $inner = Database::Join->new(
2385 databases => [$customers, $loyalty],
2386 join_column => 'entry',
2387 backend => 'sqlite',
2388 );
2389 my $outer = Database::Join->new(
2390 databases => [$inner, $scores],
2391 join_column => 'entry',
2392 backend => 'sqlite',
2393 );
2394 my $rows = $outer->selectall_arrayref(tier => 'gold');
2395  
2396 =head3 MESSAGES
2397  
2398 error_sqlite_connect (croak)
2399 -- The temporary SQLite join file could not be created.
2400  
2401 =cut
2402  
2403 26 ▶sub dbi_source {
Subroutine dbi_source: called CC=4 SCAR=13.9
Pod documented
2404 26 my ($self) = @_;
2405  
2406 # The array backend has no SQLite handle to expose.
2407 26 ▶ return undef if $self->{_backend} eq 'array';
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_backend"} eq "array" 6 20 26
2408  
2409 # Build or refresh the per-source SQLite cache. On 'auto' backend this
2410 # forces the SQLite path regardless of the auto-threshold decision — a
2411 # parent that wants to ATTACH us requires a real on-disk file.
2412 20 ▶ $self->_build_sqlite_cache() unless $self->_cache_fresh();
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_cache_fresh 14 6 20
2413  
2414 18 my $cache = $self->{_sqlite_cache};
2415  
2416 # If the materialised result table is already current, reuse it.
2417 # _dj_built is reset implicitly when _build_sqlite_cache creates a fresh
2418 # cache hashref (the old hashref is replaced, so its _dj_built is gone).
2419 18 ▶ unless ($cache->{_dj_built}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cache->{"_dj_built"}) 16 2 18
2420 # Materialise all joined rows (filter criteria only, no query-time
2421 # criteria) into _dj_result so a parent connection can ATTACH and
2422 # query it as a plain table.
2423 16 $self->_sqlite_join({}, create_table => '_dj_result');
2424 16 $cache->{_dj_built} = 1;
2425 }
2426  
2427 18 return { dbh => $cache->{dbh}, table => '_dj_result' };
2428 }
2429  
2430 =head2 columns
2431  
2432 =head3 SYNOPSIS
2433  
2434 my $cols = $join->columns();
2435  
2436 =head3 DESCRIPTION
2437  
2438 Returns an arrayref of all column names visible in the merged view,
2439 deduplicated and sorted alphabetically.
2440  
2441 The C<join_column> appears exactly once, even if it exists under different
2442 local names in some databases (see C<join_map>). Columns that have been
2443 hidden with C<remove_column> or C<remove_columns> do not appear.
2444  
2445 The result is memoised: repeated calls are cheap.
2446  
2447 =head3 API SPECIFICATION
2448  
2449 =head4 Input
2450  
2451 None.
2452  
2453 =head4 Output
2454  
2455 Arrayref of column name strings, sorted alphabetically.
2456  
2457 =head3 EXAMPLE
2458  
2459 my $cols = $join->columns();
2460 print join(', ', @{$cols}), "\n";
2461 # e.g. "entry, name, score, tier"
2462  
2463 =head3 MESSAGES
2464  
2465 C<columns()> does not itself emit any warnings or errors. Any exception thrown
2466 by a component database's C<columns()> method propagates uncaught.
2467  
2468 =cut
2469  
2470 185 ▶sub columns {
Subroutine columns: called CC=11 SCAR=24.0
Pod documented
2471 185 my ($self) = @_;
2472  
2473 185 ▶ return $self->{_col_cache} if $self->{_col_cache};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_col_cache"} 20 165 185
2474  
2475 165 my %seen;
2476 my @cols;
2477 165 my $join_col = $self->{_join_col};
2478  
2479 165 for my $i (0 .. $#{ $self->{_dbs} }) {
2480 341 my $local_jc = $self->{_join_map}{$i};
2481 341 ▶ my $renames = $self->{_col_rename}[$i] // {};
Condition50%1/2
$self->{"_col_rename"}[$i] // {}
l!l
3410
MC/DC0%0/1
$self->{"_col_rename"}[$i] // {}
$self->{"_col_rename"}[$i]
Truth table50%1/2
A
A= $self->{"_col_rename"}[$i]
Aresult
11
00
2482 341 for my $col (@{ $self->{_dbs}[$i]->columns() }) {
2483 # The local join-key alias is not a data column; the canonical name
2484 # is already contributed by the database that owns it under that name.
2485 828 ▶ next if $local_jc && $col eq $local_jc && $col ne $join_col;
Branch: 1 branch
BranchTrueFalseTotal
if $local_jc and $col eq $local_jc and $col ne $join_col 8 820 828
Condition83%5/6
$local_jc and $col eq $local_jc and $col ne $join_col
!ll&&!rl&&r
82008
$local_jc and $col eq $local_jc
!ll&&!rl&&r
81288
MC/DC66%2/3
$local_jc and $col eq $local_jc and $col ne $join_col
$local_jc $col eq $local_jc $col ne $join_col
Truth table75%3/4
A and B and C
A= $local_jcB= $col eq $local_jcC= $col ne $join_col
ABCresult
0XX0
10X0
1100
1111
2486 # Use the published name (prefixed if this column was a collision rename)
2487 820 ▶ my $pub = $renames->{$col} // $col;
Condition66%2/3
$renames->{$col} // $col
l!l&&r!l&&!r
247960
MC/DC0%0/2
$renames->{$col} // $col
$renames->{$col} $col
Truth table66%2/3
A // B
A= $renames->{$col}B= $col
ABresult
1X1
011
000
2488 820 ▶ next if $seen{$pub}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$pub}++ 172 648 820
2489 648 ▶ next if $self->{_removed_cols}{$pub};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_removed_cols"}{$pub} 47 601 648
2490 601 push @cols, $pub;
2491 }
2492 }
2493  
2494 165 $self->{_col_cache} = [ sort @cols ];
2495 165 return $self->{_col_cache};
2496 }
2497  
2498 =head2 schema
2499  
2500 =head3 SYNOPSIS
2501  
2502 my $schema = $join->schema();
2503  
2504 =head3 DESCRIPTION
2505  
2506 Returns a merged schema hashref for all visible columns across all component
2507 databases. Each key is a column name; each value is the schema metadata
2508 hashref returned by C<Database::Abstraction::schema()> for that column
2509 (typically C<{ type, nullable, default, pk }>).
2510  
2511 When the same column name appears in more than one database the I<last>
2512 database's metadata is used. Columns hidden with C<remove_column> are not
2513 included.
2514  
2515 The result is memoised.
2516  
2517 =head3 API SPECIFICATION
2518  
2519 =head4 Input
2520  
2521 None.
2522  
2523 =head4 Output
2524  
2525 Hashref: column_name => { type => ..., nullable => ..., default => ..., pk => ... }.
2526  
2527 =head3 EXAMPLE
2528  
2529 my $schema = $join->schema();
2530 for my $col (sort keys %{$schema}) {
2531 my $info = $schema->{$col};
2532 printf "%-15s type=%-10s nullable=%s\n",
2533 $col, $info->{type}, $info->{nullable} ? 'yes' : 'no';
2534 }
2535  
2536 =head3 MESSAGES
2537  
2538 C<schema()> does not itself emit any warnings or errors. Any exception thrown
2539 by a component database's C<schema()> method propagates uncaught.
2540  
2541 =cut
2542  
2543 56 ▶sub schema {
Subroutine schema: called CC=13 SCAR=25.7
Pod documented
2544 56 my ($self) = @_;
2545  
2546 56 ▶ return $self->{_schema_cache} if $self->{_schema_cache};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_schema_cache"} 7 49 56
2547  
2548 # Hash slice assignment (@merged{keys} = values) is O(M) per database;
2549 # the previous (%merged = (%merged, %s)) pattern was O(N×M) per iteration,
2550 # totalling O(N²×M) over all databases for the same result.
2551 49 my %merged;
2552 49 for my $i (0 .. $#{ $self->{_dbs} }) {
2553 97 ▶ my $s = $self->{_dbs}[$i]->schema() // {};
Condition100%2/2
$self->{"_dbs"}[$i]->schema // {}
l!l
961
MC/DC100%1/1
$self->{"_dbs"}[$i]->schema // {}
$self->{"_dbs"}[$i]->schema
Truth table100%2/2
A
A= $self->{"_dbs"}[$i]->schema
Aresult
11
00
2554 97 my $local_jc = $self->{_join_map}{$i};
2555 97 ▶ my $renames = $self->{_col_rename}[$i] // {};
Condition50%1/2
$self->{"_col_rename"}[$i] // {}
l!l
970
MC/DC0%0/1
$self->{"_col_rename"}[$i] // {}
$self->{"_col_rename"}[$i]
Truth table50%1/2
A
A= $self->{"_col_rename"}[$i]
Aresult
11
00
2556 97 ▶ my $skip_jc = $local_jc && $local_jc ne $self->{_join_col};
Condition66%2/3
$local_jc && $local_jc ne $self->{'_join_col'}
!ll&&!rl&&r
9304
MC/DC50%1/2
$local_jc && $local_jc ne $self->{'_join_col'}
$local_jc $local_jc ne $self->{'_join_col'}
Truth table66%2/3
A && B
A= $local_jcB= $local_jc ne $self->{'_join_col'}
ABresult
0X0
100
111
2557 97 ▶ if (!$skip_jc && !%{$renames}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $skip_jc || %{$renames;}) { } 88 9 97
Condition100%3/3
$skip_jc || %{$renames;}
l!l&&r!l&&!r
4588
MC/DC100%2/2
$skip_jc || %{$renames;}
$skip_jc %{$renames;}
Truth table100%3/3
A || B
A= $skip_jcB= %{$renames;}
ABresult
1X1
011
000
2558 # Fast path: no join-key alias to exclude and no collision renames
2559 88 @merged{keys %{$s}} = values %{$s};
2560 } else {
2561 9 for my $col (keys %{$s}) {
2562 24 ▶ next if $skip_jc && $col eq $local_jc;
Branch: 1 branch
BranchTrueFalseTotal
if $skip_jc and $col eq $local_jc 4 20 24
Condition100%3/3
$skip_jc and $col eq $local_jc
!ll&&!rl&&r
1644
MC/DC100%2/2
$skip_jc and $col eq $local_jc
$skip_jc $col eq $local_jc
Truth table100%3/3
A and B
A= $skip_jcB= $col eq $local_jc
ABresult
0X0
100
111
2563 20 ▶ $merged{ $renames->{$col} // $col } = $s->{$col};
Condition66%2/3
$renames->{$col} // $col
l!l&&r!l&&!r
5150
MC/DC0%0/2
$renames->{$col} // $col
$renames->{$col} $col
Truth table66%2/3
A // B
A= $renames->{$col}B= $col
ABresult
1X1
011
000
2564 }
2565 }
2566 }
2567  
2568 10 delete @merged{keys %{ $self->{_removed_cols} }}
2569 49 ▶ if %{ $self->{_removed_cols} };
Branch: 1 branch
BranchTrueFalseTotal
if %{$self->{"_removed_cols"};} 10 39 49
2570  
2571 49 $self->{_schema_cache} = \%merged;
2572 49 return $self->{_schema_cache};
2573 }
2574  
2575 =head2 updated
2576  
2577 =head3 SYNOPSIS
2578  
2579 my $ts = $join->updated();
2580  
2581 =head3 DESCRIPTION
2582  
2583 Returns the Unix timestamp of the most recent modification across all
2584 component databases. This is the maximum of all individual C<updated()>
2585 return values.
2586  
2587 Use this to implement simple cache-invalidation logic: if C<updated()>
2588 has advanced since your last snapshot, re-query.
2589  
2590 =head3 API SPECIFICATION
2591  
2592 =head4 Input
2593  
2594 None.
2595  
2596 =head4 Output
2597  
2598 Unix timestamp (positive integer).
2599  
2600 =head3 EXAMPLE
2601  
2602 my $last_modified = $join->updated();
2603 if ($last_modified > $my_cache_timestamp) {
2604 $my_cache = $join->selectall_arrayref();
2605 $my_cache_timestamp = $last_modified;
2606 }
2607  
2608 =head3 MESSAGES
2609  
2610 C<updated()> does not emit any warnings or errors. Component databases that do
2611 not implement C<updated()>, or whose C<updated()> throws, are silently skipped;
2612 only defined return values contribute to the maximum. If no component database
2613 implements C<updated()>, C<undef> is returned (same as C<List::Util::max> on an
2614 empty list).
2615  
2616 =cut
2617  
2618 35 ▶sub updated {
Subroutine updated: called CC=3 SCAR=11.0
Pod documented
2619 35 my ($self) = @_;
2620 35 my @timestamps;
2621 35 for my $db (@{ $self->{_dbs} }) {
2622 71 my $ts;
2623 71 do { local $@; $ts = eval { $db->updated() } };
2624 71 ▶ push @timestamps, $ts if defined $ts;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ts 53 18 71
2625 }
2626 35 return max(@timestamps);
2627 }
2628  
2629 =head2 set_logger
2630  
2631 =head3 SYNOPSIS
2632  
2633 $join->set_logger($log);
2634 $join->set_logger(logger => $log); # named-pair form also accepted
2635  
2636 =head3 DESCRIPTION
2637  
2638 Attaches a new logger object to the join and propagates it to every component
2639 database. The logger is used for diagnostic output by all component databases.
2640  
2641 Non-blessed values (a log-level string such as C<"debug">, a filename, or a
2642 code reference) are wrapped in C<Log::Abstraction->new(...)> automatically,
2643 matching the behaviour of C<Database::Abstraction::set_logger>.
2644  
2645 =head3 API SPECIFICATION
2646  
2647 =head4 Input
2648  
2649 logger Positional or named: a logger object, log-level string, filename,
2650 or code reference (required). Non-blessed values are wrapped in
2651 Log::Abstraction automatically.
2652  
2653 =head4 Output
2654  
2655 Returns C<$self> for method chaining.
2656  
2657 =head3 EXAMPLE
2658  
2659 # Log::Any is used here as an example; any object that implements
2660 # debug() and info() (or whichever methods your component databases
2661 # call internally) works equally well.
2662 use Log::Any qw($log);
2663  
2664 my $join = Database::Join->new(databases => [$db1, $db2], join_column => 'entry');
2665 $join->set_logger($log);
2666 # $log is now used by $join and by $db1 and $db2
2667  
2668 # Named-pair form (mirrors Database::Abstraction API):
2669 $join->set_logger(logger => $log);
2670  
2671 =head3 MESSAGES
2672  
2673 (croak) Usage: set_logger(logger => $logger)
2674 -- Called with an undefined argument. Pass a valid logger object.
2675  
2676 =cut
2677  
2678 17 ▶sub set_logger {
Subroutine set_logger: called CC=4 SCAR=13.9
Pod documented
2679 17 my $self = shift;
2680 17 my $p = Params::Get::get_params('logger', @_);
2681 17 my $logger = $p->{'logger'};
2682  
2683 17 ▶ croak 'Usage: set_logger(logger => $logger)' unless defined $logger;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $logger 3 14 17
2684  
2685 # Wrap non-blessed values (log-level strings, filenames, coderefs) exactly
2686 # as Database::Abstraction does, so callers get identical behaviour from DJ.
2687 14 ▶ $logger = Log::Abstraction->new($logger)
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($logger) 0 14 14
2688 unless Scalar::Util::blessed($logger);
2689  
2690 14 $self->{_logger} = $logger;
2691 14 $_->set_logger($logger) for @{ $self->{_dbs} };
2692  
2693 14 return $self;
2694 }
2695  
2696 =head2 add_database
2697  
2698 =head3 SYNOPSIS
2699  
2700 # Positional: database object as first argument
2701 $join->add_database($db);
2702  
2703 # Named: equivalent to the above
2704 $join->add_database(database => $db);
2705  
2706 # With options (mixed positional + named)
2707 $join->add_database($db, remove_columns => ['internal_id']);
2708 $join->add_database($db, join_column => 'local_key_name');
2709 $join->add_database($db, filter => { score => { '>' => 60 } });
2710  
2711 # Chainable
2712 $join->add_database($db1)->add_database($db2, remove_columns => ['notes']);
2713  
2714 =head3 DESCRIPTION
2715  
2716 Adds one more C<Database::Abstraction> subclass object to the logical view
2717 and immediately updates the column-ownership index.
2718  
2719 After the call, all query methods return rows that include columns from the
2720 newly added database, and criteria on those new columns are routed to it
2721 automatically.
2722  
2723 When a column name in the new database already exists in an earlier database,
2724 the new database becomes the authoritative source for that column
2725 (last-database-wins, the same rule that applies at construction time).
2726  
2727 The join-column must be present in the new database (or declared via
2728 C<join_column>). The logger is propagated to the new database if one is set.
2729  
2730 C<add_database> is the runtime equivalent of listing the database in the
2731 C<databases> array to C<new>. The optional C<join_column> parameter is
2732 equivalent to a C<join_map> entry; the optional C<filter> parameter is
2733 equivalent to a C<filters> entry.
2734  
2735 =head3 API SPECIFICATION
2736  
2737 =head4 Input
2738  
2739 database => { type => 'object', required => 1 }
2740 # A Database::Abstraction subclass instance.
2741 #
2742 # DOMAIN -- EP valid: blessed object that passes
2743 # isa('Database::Abstraction').
2744 # DOMAIN -- EP invalid: non-reference, unblessed ref, wrong class,
2745 # or non-reference non-key scalar (the guard at
2746 # the top of add_database rejects it with
2747 # error_invalid_db before validate_strict runs).
2748  
2749 join_column => { type => 'string', optional => 1 }
2750 # The name of the join key in THIS new database,
2751 # when it differs from the canonical join_column.
2752 #
2753 # DOMAIN -- EP valid: any string that exists as a column in the
2754 # new database.
2755 # DOMAIN -- EP invalid: string absent from the new database's columns()
2756 # => croak error_join_col_missing.
2757  
2758 filter => { type => 'hashref', optional => 1 }
2759 # Permanent criteria for this database only.
2760 # Same format as selectall_arrayref.
2761 #
2762 # DOMAIN -- EP valid: hashref of criteria (may be {} for no-op).
2763 # DOMAIN -- EP absent: no permanent filter applied; all rows visible.
2764 # DOMAIN -- Key-set: a non-empty filter makes this DB an inner-join
2765 # partner regardless of the outer join_type.
2766  
2767 remove_columns => { type => 'arrayref', optional => 1 }
2768 # Column names from this database to hide.
2769 #
2770 # DOMAIN -- EP valid: arrayref of strings; non-existent columns silently
2771 # ignored; empty [] is a safe no-op.
2772 # DOMAIN -- EP invalid: join_column itself => croak error_remove_join_col.
2773  
2774 =head4 Output
2775  
2776 Returns C<$self> to support method chaining.
2777  
2778 =head3 EXAMPLE
2779  
2780 my $join = Database::Join->new(
2781 databases => [ $customers ],
2782 join_column => 'entry',
2783 );
2784  
2785 # Add loyalty data; hide internal columns from it
2786 $join->add_database($loyalty, remove_columns => ['audit_ts']);
2787  
2788 # Add score data; only include rows with score > 60
2789 $join->add_database($scores, filter => { score => { '>' => 60 } });
2790  
2791 # Add a database whose join key has a different local name
2792 $join->add_database($stnames, join_column => 'state_code');
2793  
2794 # All three options combined, and chained
2795 $join->add_database($db4,
2796 join_column => 'ref_id',
2797 filter => { active => 1 },
2798 remove_columns => ['legacy_col'],
2799 );
2800  
2801 =head3 PSEUDOCODE
2802  
2803 determine the new database's index (length of current _dbs array)
2804 extract the database object from positional or named argument
2805 croak if it is not a Database::Abstraction subclass
2806 register join_column alias in _join_map if different from canonical
2807 register filter in _filters if provided
2808 fetch column list from the new database
2809 croak if the join key is missing from the new database
2810 append the new database to _dbs and _db_cols
2811 update _col_db: for each new column, point it at the new index
2812 (last-database-wins; skip removed columns and the local join alias)
2813 invalidate _col_cache and _schema_cache
2814 propagate logger if set
2815 apply remove_columns if provided
2816 return $self
2817  
2818 =head3 MESSAGES
2819  
2820 error_invalid_db -- argument is not a Database::Abstraction subclass
2821 error_join_col_missing -- join_column not found in the new database
2822 warn_schema_type_mismatch -- (carp) the new database has a shared column whose type
2823 differs from the type already in the view; use
2824 collision_prefix to preserve both values
2825  
2826 =cut
2827  
2828 113 ▶sub add_database {
Subroutine add_database: called CC=30 SCAR=34.1
Pod documented
2829 113 my ($self, @args) = @_;
2830  
2831 113 my $idx = scalar @{ $self->{_dbs} };
2832 113 my $db;
2833  
2834 # Fail-fast guard: a non-reference first arg must be a recognised named-pair key.
2835 # Modus Ponens: !ref(x) ∧ x ∉ @_ADD_DB_KEYS → cannot be a database object → croak.
2836 # De Morgan reduction: the elsif below is logically equivalent to (@args && ref(args[0]))
2837 # because the !ref branch was already handled; exhaustion makes the ref() check redundant.
2838 113 ▶ if (@args && !ref($args[0])) {
Branch: 2 branches
BranchTrueFalseTotal
if (@args and not ref $args[0]) { } 14 99 113
elsif (@args) { } 99 0 99
Condition66%2/3
@args and not ref $args[0]
!ll&&!rl&&r
09914
MC/DC50%1/2
@args and not ref $args[0]
@args not ref $args[0]
Truth table66%2/3
A and not(B)
A= @argsB= not ref $args[0]
ABresult
0X0
100
111
2839 croak $self->_err('error_invalid_db', $idx)
2840 14 ▶ unless defined($args[0]) && grep { $args[0] eq $_ } @_ADD_DB_KEYS;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args[0] and grep {$args[0] eq $_;} @_ADD_DB_KEYS 9 5 14
Condition100%3/3
defined $args[0] and grep {$args[0] eq $_;} @_ADD_DB_KEYS
!ll&&!rl&&r
275
MC/DC100%2/2
defined $args[0] and grep {$args[0] eq $_;} @_ADD_DB_KEYS
defined $args[0] grep {$args[0] eq $_;} @_ADD_DB_KEYS
Truth table100%3/3
A and B
A= defined $args[0]B= grep {$args[0] eq $_;} @_ADD_DB_KEYS
ABresult
0X0
100
111
2841 } elsif (@args) {
2842 # Positional form: first arg is a reference — extract it before get_params
2843 # to avoid the mixed positional+named-pairs confusion.
2844 99 $db = shift @args;
2845 }
2846  
2847 104 ▶ my $p = validate_strict(
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 28 76 104
Condition50%1/2
(@args ? get_params(undef, @args) : {}) // {}
l!l
1040
MC/DC0%0/1
(@args ? get_params(undef, @args) : {}) // {}
(@args ? get_params(undef, @args) : {})
Truth table50%1/2
A
A= (@args ? get_params(undef, @args) : {})
Aresult
11
00
2848 schema => {
2849 database => {
2850 type => 'object',
2851 optional => 1,
2852 can => ['selectall_arrayref', 'columns']
2853 },
2854 join_column => { type => 'string', optional => 1 },
2855 filter => { type => 'hashref', optional => 1 },
2856 remove_columns => { type => 'arrayref', optional => 1 },
2857 },
2858 input => (@args ? get_params(undef, @args) : {}) // {},
2859 );
2860  
2861 104 ▶ $db //= $p->{database};
Condition66%2/3
$db //= $p->{"database"}
l!l&&r!l&&!r
9950
MC/DC0%0/2
$db //= $p->{"database"}
$db $p->{"database"}
Truth table66%2/3
A //= B
A= $dbB= $p->{"database"}
ABresult
1X1
011
000
2862  
2863 104 ▶ croak $self->_err('error_invalid_db', $idx)
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($db) and $db->can("selectall_arrayref") and $db->can("columns") 7 97 104
Condition100%6/6
builtin::blessed($db) and $db->can("selectall_arrayref") and $db->can("columns")
!ll&&!rl&&r
6197
builtin::blessed($db) and $db->can("selectall_arrayref")
!ll&&!rl&&r
2498
MC/DC100%3/3
builtin::blessed($db) and $db->can("selectall_arrayref") and $db->can("columns")
builtin::blessed($db) $db->can("selectall_arrayref") $db->can("columns")
Truth table100%4/4
A and B and C
A= builtin::blessed($db)B= $db->can("selectall_arrayref")C= $db->can("columns")
ABCresult
0XX0
10X0
1100
1111
2864 unless blessed($db)
2865 && $db->can('selectall_arrayref')
2866 && $db->can('columns');
2867  
2868 # Determine and register the local join column name for this database
2869 97 ▶ my $local_jc = $p->{join_column} // $self->{_join_col};
Condition66%2/3
$p->{"join_column"} // $self->{"_join_col"}
l!l&&r!l&&!r
9880
MC/DC0%0/2
$p->{"join_column"} // $self->{"_join_col"}
$p->{"join_column"} $self->{"_join_col"}
Truth table66%2/3
A // B
A= $p->{"join_column"}B= $self->{"_join_col"}
ABresult
1X1
011
000
2870 97 ▶ $self->{_join_map}{$idx} = $local_jc if $p->{join_column};
Branch: 1 branch
BranchTrueFalseTotal
if $p->{"join_column"} 9 88 97
2871 # Security: deep-copy the filter; same rationale as the constructor's _copy_filters call.
2872 97 ▶ $self->{_filters}{$idx} = _copy_criteria($p->{filter}) if $p->{filter};
Branch: 1 branch
BranchTrueFalseTotal
if $p->{"filter"} 10 87 97
2873  
2874 97 my $cols = $db->columns();
2875 97 my %col_presence = map { $_ => 1 } @{$cols};
2876  
2877 croak $self->_err('error_join_col_missing', $local_jc, $idx, ref($db))
2878 97 ▶ unless $col_presence{$local_jc};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_presence{$local_jc} 4 93 97
2879  
2880 # Register the new database
2881 93 push @{ $self->{_dbs} }, $db;
2882 93 push @{ $self->{_db_cols} }, \%col_presence;
2883  
2884 # Update column routing: last-database-wins for duplicates, unless a
2885 # collision_prefix is configured for this index (in which case the
2886 # duplicate is published under "$prefix.$col" instead of overwriting).
2887 93 my $prefix = $self->{_collision_prefix}{$idx};
2888 93 ▶ $self->{_col_rename}[$idx] //= {};
Condition50%1/2
$self->{"_col_rename"}[$idx] //= {}
l!l
093
MC/DC0%0/1
$self->{"_col_rename"}[$idx] //= {}
$self->{"_col_rename"}[$idx]
Truth table50%1/2
A
A= $self->{"_col_rename"}[$idx]
Aresult
11
00
2889 93 ▶ $self->{_col_unrename}[$idx] //= {};
Condition50%1/2
$self->{"_col_unrename"}[$idx] //= {}
l!l
093
MC/DC0%0/1
$self->{"_col_unrename"}[$idx] //= {}
$self->{"_col_unrename"}[$idx]
Truth table50%1/2
A
A= $self->{"_col_unrename"}[$idx]
Aresult
11
00
2890  
2891 93 for my $col (@{$cols}) {
2892 207 ▶ next if $local_jc ne $self->{_join_col} && $col eq $local_jc;
Branch: 1 branch
BranchTrueFalseTotal
if $local_jc ne $self->{"_join_col"} and $col eq $local_jc 8 199 207
Condition100%3/3
$local_jc ne $self->{"_join_col"} and $col eq $local_jc
!ll&&!rl&&r
19188
MC/DC100%2/2
$local_jc ne $self->{"_join_col"} and $col eq $local_jc
$local_jc ne $self->{"_join_col"} $col eq $local_jc
Truth table100%3/3
A and B
A= $local_jc ne $self->{"_join_col"}B= $col eq $local_jc
ABresult
0X0
100
111
2893  
2894 199 my $pub;
2895 199 ▶ if (defined $prefix && exists $self->{_col_db}{$col} && $col ne $self->{_join_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $prefix and exists $self->{'_col_db'}{$col} and $col ne $self->{'_join_col'}) { } 4 195 199
Condition100%6/6
defined $prefix and exists $self->{"_col_db"}{$col} and $col ne $self->{"_join_col"}
!ll&&!rl&&r
19144
defined $prefix and exists $self->{"_col_db"}{$col}
!ll&&!rl&&r
18748
MC/DC100%3/3
defined $prefix and exists $self->{"_col_db"}{$col} and $col ne $self->{"_join_col"}
defined $prefix exists $self->{"_col_db"}{$col} $col ne $self->{"_join_col"}
Truth table100%4/4
A and B and C
A= defined $prefixB= exists $self->{"_col_db"}{$col}C= $col ne $self->{"_join_col"}
ABCresult
0XX0
10X0
1100
1111
2896 # Same guard as _build_col_index: never prefix the join_column itself.
2897 4 $pub = "$prefix.$col";
2898 4 $self->{_col_rename}[$idx]{$col} = $pub;
2899 4 $self->{_col_unrename}[$idx]{$pub} = $col;
2900 } else {
2901 195 $pub = $col;
2902 }
2903  
2904 199 ▶ next if $self->{_removed_cols}{$pub};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_removed_cols"}{$pub} 2 197 199
2905 197 $self->{_col_db}{$pub} = $idx;
2906 }
2907  
2908 # Invalidate memoisation caches
2909 93 $self->{_col_cache} = undef;
2910 93 $self->{_schema_cache} = undef;
2911  
2912 # Warn about schema type mismatches introduced by the new database.
2913 93 $self->_validate_schema_types();
2914  
2915 # Invalidate the SQLite join cache: a new source requires a full rebuild.
2916 93 ▶ if (my $old = delete $self->{_sqlite_cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $old = delete $self->{"_sqlite_cache"}) 5 88 93
2917 5 local $@;
2918 5 ▶ eval { $old->{dbh}->disconnect } if $old->{dbh};
Branch: 1 branch
BranchTrueFalseTotal
if $old->{"dbh"} 5 0 5
2919 }
2920  
2921 # Propagate logger if one is configured
2922 93 ▶ if (my $log = $self->{_logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $log = $self->{"_logger"}) 4 89 93
2923 4 $db->set_logger($log);
2924 }
2925  
2926 # Apply any column removals requested for this database
2927 93 ▶ if (my $rc = $p->{remove_columns}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $p->{"remove_columns"}) 6 87 93
2928 6 $self->remove_column($_) for @{$rc};
2929 }
2930  
2931 93 return $self;
2932 }
2933  
2934 =head2 remove_column
2935  
2936 =head3 SYNOPSIS
2937  
2938 $join->remove_column('email');
2939  
2940 # Chainable
2941 $join->remove_column('internal_id')->remove_column('audit_ts');
2942  
2943 =head3 DESCRIPTION
2944  
2945 Permanently hides a column from the merged view. After this call:
2946  
2947 =over 4
2948  
2949 =item *
2950  
2951 The column does not appear in C<columns()> or C<schema()>.
2952  
2953 =item *
2954  
2955 Returned row hashrefs do not contain the column key.
2956  
2957 =item *
2958  
2959 Any query criterion that references the removed column is silently dropped
2960 (with a C<carp> warning).
2961  
2962 =back
2963  
2964 The C<join_column> cannot be removed; attempting to do so will C<croak>.
2965 Removing a column that does not exist in any database is silently ignored
2966 (the call is idempotent and safe). The C<columns()> and C<schema()>
2967 memoisation caches are cleared automatically.
2968  
2969 =head3 API SPECIFICATION
2970  
2971 =head4 Input
2972  
2973 $col Positional string: the column name to remove.
2974  
2975 DOMAIN -- EP valid: any string; non-existent columns are silently
2976 ignored (idempotent call, returns $self).
2977 DOMAIN -- EP invalid: join_column value => croak error_remove_join_col.
2978 DOMAIN -- BVA: undef and '' are explicit no-ops (returns $self).
2979 These are below the minimum meaningful string
2980 length and are handled without any warning.
2981  
2982 =head4 Output
2983  
2984 Returns C<$self> to support method chaining.
2985  
2986 =head3 EXAMPLE
2987  
2988 # Hide private fields immediately after construction
2989 my $join = Database::Join->new(
2990 databases => [ $customers, $loyalty ],
2991 join_column => 'entry',
2992 )->remove_column('email')
2993 ->remove_column('internal_notes');
2994  
2995 # Verify they are gone
2996 my $cols = $join->columns();
2997 # 'email' and 'internal_notes' are absent
2998  
2999 =head3 MESSAGES
3000  
3001 error_remove_join_col -- attempt to remove the join_column itself
3002  
3003 =cut
3004  
3005 128 ▶sub remove_column {
Subroutine remove_column: called CC=4 SCAR=13.9
Pod documented
3006 128 my ($self, $col) = @_;
3007  
3008 # Premise: undef and '' are provably no-ops (nothing to remove).
3009 # Conclusion: guard at the top eliminates two separate defined() checks below.
3010 128 ▶ return $self unless defined $col && length $col;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col and length $col 14 114 128
Condition100%3/3
defined $col and length $col
!ll&&!rl&&r
77114
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
3011  
3012 # Premise: $col is defined (proven above) and join_col is always a non-empty string.
3013 # Conclusion: direct string comparison is safe without a redundant defined() check.
3014 croak $self->_err('error_remove_join_col', $col)
3015 114 ▶ if $col eq $self->{_join_col};
Branch: 1 branch
BranchTrueFalseTotal
if $col eq $self->{"_join_col"} 14 100 114
3016  
3017 100 $self->{_removed_cols}{$col} = 1;
3018 100 delete $self->{_col_db}{$col};
3019 100 $self->{_col_cache} = undef;
3020 100 $self->{_schema_cache} = undef;
3021 100 $self->{_removed_list} = undef; # invalidate the cached removed-column list
3022  
3023 100 return $self;
3024 }
3025  
3026 =head2 query
3027  
3028 Not supported. C<Database::Join> does not implement the
3029 C<Database::Abstraction::Query> chained builder because the builder's
3030 C<.all()> / C<.first()> methods would be targeting a single component DA
3031 rather than the merged view. Calling this method will always C<croak>.
3032  
3033 Use C<selectall_arrayref>, C<selectall_array>, C<fetchrow_hashref>,
3034 C<count>, or C<each_row> against the C<Database::Join> object instead.
3035  
3036 =cut
3037  
3038 8 ▶sub query {
Subroutine query: called CC=1 SCAR=0.0
Pod documented
3039 8 my $self = $_[0];
3040 8 croak $self->_err('error_query_unsupported');
3041 }
3042  
3043 =head2 group_by
3044  
3045 Not supported. C<Database::Join> does not implement the
3046 C<Database::Abstraction::Query> fluent chain entry point because the chain's
3047 C<.all()> / C<.first()> methods would target a single component DA rather
3048 than the merged view. Calling this method will always C<croak>.
3049  
3050 Use C<aggregate()> against the C<Database::Join> object instead.
3051  
3052 =cut
3053  
3054 1 ▶sub group_by {
Subroutine group_by: called CC=1 SCAR=0.0
Pod documented
3055 1 my $self = $_[0];
3056 1 croak $self->_err('error_group_by_unsupported');
3057 }
3058  
3059 =head2 execute
3060  
3061 Not supported. Raw SQL cannot span heterogeneous backends that may use
3062 different database engines. Calling this method will always C<croak>.
3063  
3064 Use C<selectall_arrayref> or C<fetchrow_hashref> to query the joined view.
3065  
3066 =cut
3067  
3068 8 ▶sub execute {
Subroutine execute: called CC=1 SCAR=0.0
Pod documented
3069 8 my $self = $_[0];
3070 8 croak $self->_err('error_execute_unsupported');
3071 }
3072  
3073 =head2 AUTOLOAD - column shortcut
3074  
3075 Calling an unknown method whose name matches a visible column name performs
3076 a column lookup across the merged view.
3077  
3078 =head3 SYNOPSIS
3079  
3080 # Scalar context: value from the first matching row
3081 my $name = $join->name(entry => 'C001');
3082  
3083 # List context: values from every matching row
3084 my @tiers = $join->tier();
3085  
3086 # With a positional join-key argument (when join_column is 'entry')
3087 my $score = $join->score('C001');
3088  
3089 =head3 DESCRIPTION
3090  
3091 AUTOLOAD routes the call to the appropriate component database by looking up
3092 the column name in the internal column-ownership index.
3093  
3094 When either C<join_map> or C<filters> is active, AUTOLOAD performs a full
3095 join query instead of delegating directly to the owning database. This is
3096 necessary because:
3097  
3098 =over 4
3099  
3100 =item *
3101  
3102 With C<join_map>, the owning database's primary key may differ from the
3103 canonical join key used in the call arguments.
3104  
3105 =item *
3106  
3107 With C<filters>, bypassing the join would return rows that the filter is
3108 meant to exclude.
3109  
3110 =back
3111  
3112 In list context, every matching merged row contributes one value to the
3113 returned list. In scalar context, only the first row's value is returned.
3114  
3115 Calling a method whose name begins with C<_> (a private method) via AUTOLOAD
3116 will C<croak> with a clear error message rather than being silently ignored.
3117  
3118 =head3 EXAMPLE
3119  
3120 # Lookup a single customer's name (scalar context)
3121 my $name = $join->name('C001'); # 'C001' maps to entry => 'C001'
3122 print "Name: $name\n";
3123  
3124 # Get every tier value in the view (list context)
3125 my @all_tiers = $join->tier();
3126 my %freq;
3127 $freq{$_}++ for @all_tiers;
3128  
3129 # join_map active: AUTOLOAD runs a full join so the criteria are
3130 # translated correctly between the canonical and local key names.
3131 my @leesburg_states = sort $join->state('Leesburg');
3132 # ['Florida', 'Virginia'] if Leesburg appears in two states
3133  
3134 =head3 PSEUDOCODE
3135  
3136 extract column name from $AUTOLOAD
3137 return if DESTROY
3138 croak if column name starts with '_' (private method guard)
3139 croak if column name is not in _col_db (unknown column)
3140 if join_map or filters are active:
3141 parse calling arguments using _parse_query_args
3142 call _joined_query to get all merged rows
3143 return map { $_->{col} } @rows in list context
3144 return $rows[0]{col} in scalar context
3145 else:
3146 delegate directly to the owning database
3147  
3148 =head3 MESSAGES
3149  
3150 (croak) Database::Join: cannot call private method '_NAME' via AUTOLOAD
3151 -- Method name begins with '_'. Private methods must be called directly,
3152 not via AUTOLOAD. This is a programming error.
3153  
3154 (croak) Database::Join: unknown column 'NAME'
3155 -- Method name does not match any visible column in the merged view.
3156 Check spelling, or whether the column was removed with remove_column().
3157  
3158 =cut
3159  
3160 29 our $AUTOLOAD;
3161  
3162 56 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=7 SCAR=19.5
3163 56 my $self = shift;
3164  
3165 56 my ($col) = $AUTOLOAD =~ /
3166 :: # package separator — skip the fully-qualified prefix
3167 (\w++) # method name: possessive quantifier commits immediately;
3168 # no backtrack possible because \w chars cannot match \z
3169 \z # strict end-of-string (\z never matches a trailing newline,
3170 # unlike $ which can — important if $AUTOLOAD ever embeds \n)
3171 /x;
3172  
3173 # Private methods must not be reached via AUTOLOAD — croak immediately so
3174 # typos like $join->_join_col are not silently swallowed.
3175 # substr() avoids regex-engine overhead for this single-character prefix check.
3176 56 ▶ croak ref($self), ": cannot call private method '$col' via AUTOLOAD"
Branch: 1 branch
BranchTrueFalseTotal
if substr($col, 0, 1) eq "_" 10 46 56
3177 if substr($col, 0, 1) eq '_';
3178  
3179 46 my $db_idx = $self->{_col_db}{$col};
3180 46 ▶ croak ref($self), ": unknown column '$col'" unless defined $db_idx;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $db_idx 11 35 46
3181  
3182 # Use a full join query when join_map OR filters are active. Direct
3183 # delegation to the owning database would bypass the join key translation
3184 # (join_map) and skip any permanent per-database row filters (filters).
3185 35 ▶ if (%{ $self->{_join_map} } || %{ $self->{_filters} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$self->{"_join_map"};} or %{$self->{"_filters"};}) 27 8 35
Condition100%3/3
%{$self->{"_join_map"};} or %{$self->{"_filters"};}
l!l&&r!l&&!r
11168
MC/DC100%2/2
%{$self->{"_join_map"};} or %{$self->{"_filters"};}
%{$self->{"_join_map"};} %{$self->{"_filters"};}
Truth table100%3/3
A or B
A= %{$self->{"_join_map"};}B= %{$self->{"_filters"};}
ABresult
1X1
011
000
3186 # _autoload_pk is the autoload_pk constructor param (defaults to join_column).
3187 27 my $params = $self->_parse_query_args($self->{_autoload_pk}, @_);
3188 27 my $sort_by = delete $params->{sort_by};
3189 27 my $limit = delete $params->{limit};
3190 27 my $offset = delete $params->{offset};
3191 27 my $rows = $self->_joined_query($params, sort_by => $sort_by, limit => $limit, offset => $offset);
3192 27 ▶ return map { $_->{$col} } @{$rows} if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 9 18 27
3193 18 ▶ return @{$rows} ? $rows->[0]{$col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
@{$rows;} ? : 13 5 18
3194 }
3195  
3196 # $db is resolved here (not earlier) to avoid a dead store on the join path above.
3197 8 my $db = $self->{_dbs}[$db_idx];
3198 8 return $db->$col(@_);
3199 }
3200  
3201 1357 ▶sub DESTROY {
Subroutine DESTROY: called CC=3 SCAR=11.0
3202 1357 my ($self) = @_;
3203 # Disconnect and release the cached SQLite handle (if any) so File::Temp
3204 # can unlink the temp file before the object is freed.
3205 1357 ▶ if (my $cache = delete $self->{_sqlite_cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cache = delete $self->{"_sqlite_cache"}) 208 1149 1357
3206 208 local $@;
3207 208 ▶ eval { $cache->{dbh}->disconnect } if $cache->{dbh};
Branch: 1 branch
BranchTrueFalseTotal
if $cache->{"dbh"} 208 0 208
3208 # $cache->{tmpfile} (File::Temp, UNLINK => 1) is released here.
3209 }
3210 }
3211  
3212 # ---------------------------------------------------------------------------
3213 # Private helpers
3214 # ---------------------------------------------------------------------------
3215  
3216 # _parse_query_args( $self, $positional_key, @caller_args ) -> \%params
3217 # Purpose: Normalise the three calling conventions used by every public query
3218 # method and AUTOLOAD into a single criteria hashref.
3219 # Entry: $positional_key -- the column name mapped to a bare scalar argument;
3220 # pass undef to use the join_column (the default for public methods).
3221 # Exit: Always returns a hashref; never undef.
3222 989 ▶sub _parse_query_args :Protected {
Subroutine _parse_query_args: called CC=6 SCAR=18.0
3223 989 my ($self, $key, @args) = @_;
3224 # D~ elimination (Modus Tollens): when @args is empty the early return fires
3225 # before $key is ever read, making the $key //= assignment a dead store.
3226 # Moving the guard above the assignment removes the wasted hash dereference.
3227 989 ▶ return {} unless @args;
Branch: 1 branch
BranchTrueFalseTotal
unless @args 505 484 989
3228 484 ▶ $key //= $self->{_join_col};
Condition66%2/3
$key //= $self->{"_join_col"}
l!l&&r!l&&!r
224620
MC/DC0%0/2
$key //= $self->{"_join_col"}
$key $self->{"_join_col"}
Truth table66%2/3
A //= B
A= $keyB= $self->{"_join_col"}
ABresult
1X1
011
000
3229 484 ▶ return { $key => $args[0] } if @args == 1 && !ref($args[0]);
Branch: 1 branch
BranchTrueFalseTotal
if @args == 1 and not ref $args[0] 38 446 484
Condition100%3/3
@args == 1 and not ref $args[0]
!ll&&!rl&&r
4311538
MC/DC100%2/2
@args == 1 and not ref $args[0]
@args == 1 not ref $args[0]
Truth table100%3/3
A and not(B)
A= @args == 1B= not ref $args[0]
ABresult
0X0
100
111
3230 446 ▶ return get_params(undef, @args) // {};
Condition50%1/2
get_params(undef, @args) // {}
l!l
4460
MC/DC0%0/1
get_params(undef, @args) // {}
get_params(undef, @args)
Truth table50%1/2
A
A= get_params(undef, @args)
Aresult
11
00
3231 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3232  
3233 # _err( $self, $msg_key, @sprintf_args ) -> $string
3234 # Convenience wrapper around _msg for use after construction, so callers do
3235 # not have to extract $self->{_i18n} at every error site.
3236 177 ▶sub _err :Protected {
Subroutine _err: called CC=1 SCAR=0.0
3237 177 my ($self, $key, @args) = @_;
3238 177 return _msg($self->{_i18n}, $key, @args);
3239 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3240  
3241 # _build_col_index()
3242 # Purpose: Populate _col_db (column_name => db_index) and _db_cols
3243 # (per-db column-presence hashrefs) by calling columns() on each
3244 # component database at construction time.
3245 # Entry: _dbs, _join_col, _join_map must already be set.
3246 # Exit: _col_db and _db_cols are set; join_column verified in every db.
3247 # Effects: Croaks if any database is missing its join key column.
3248 1313 ▶sub _build_col_index :Protected {
Subroutine _build_col_index: called CC=15 SCAR=27.1
3249 1313 my ($self) = @_;
3250  
3251 1313 my $join_col = $self->{_join_col};
3252 1313 ▶ my $cp = $self->{_collision_prefix} // {};
Condition50%1/2
$self->{"_collision_prefix"} // {}
l!l
13130
MC/DC0%0/1
$self->{"_collision_prefix"} // {}
$self->{"_collision_prefix"}
Truth table50%1/2
A
A= $self->{"_collision_prefix"}
Aresult
11
00
3253 1313 my %col_db;
3254 my @db_cols;
3255 1313 my @col_rename; # per-db: { orig_col => published_col } for renamed collisions
3256 1313 my @col_unrename; # per-db: { published_col => orig_col } reverse map
3257  
3258 1313 for my $i (0 .. $#{ $self->{_dbs} }) {
3259 2404 my $db = $self->{_dbs}[$i];
3260 2404 ▶ my $local_jc = $self->{_join_map}{$i} // $join_col;
Condition66%2/3
$self->{"_join_map"}{$i} // $join_col
l!l&&r!l&&!r
5423500
MC/DC0%0/2
$self->{"_join_map"}{$i} // $join_col
$self->{"_join_map"}{$i} $join_col
Truth table66%2/3
A // B
A= $self->{"_join_map"}{$i}B= $join_col
ABresult
1X1
011
000
3261 2404 my $cols = $db->columns();
3262 2403 $db_cols[$i] = { map { $_ => 1 } @{$cols} };
3263 2403 $col_rename[$i] = {};
3264 2403 $col_unrename[$i] = {};
3265  
3266 # Guard: a join_map value that is a reference (e.g. a hashref) would
3267 # stringify to "HASH(0x...)" when interpolated into an error message,
3268 # leaking a heap address to callers. Reject early with a clear message.
3269 2403 ▶ croak $self->_err('error_join_col_missing', "(join_map[$i] must be a string)", $i, ref($db))
Branch: 1 branch
BranchTrueFalseTotal
if ref $local_jc 12 2391 2403
3270 if ref $local_jc;
3271  
3272 croak $self->_err('error_join_col_missing', $local_jc, $i, ref($db))
3273 2391 ▶ unless $db_cols[$i]{$local_jc};
Branch: 1 branch
BranchTrueFalseTotal
unless $db_cols[$i]{$local_jc} 16 2375 2391
3274  
3275 # collision_prefix only applies to secondary databases (index > 0);
3276 # an index-0 entry is meaningless and silently ignored.
3277 2375 ▶ my $prefix = ($i > 0) ? $cp->{$i} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$i > 0 ? : 1082 1293 2375
3278  
3279 # Guard: a collision_prefix value that is a reference would stringify
3280 # to "HASH(0x...)" or "ARRAY(0x...)" when interpolated into "$prefix.$col",
3281 # leaking a heap address into every column name, columns(), schema(), and
3282 # merged row hashref. This is the same class of leak as the join_map guard
3283 # above; reject early with a clear message before any column name is built.
3284 2375 ▶ croak $self->_err('error_invalid_prefix', $i)
Branch: 1 branch
BranchTrueFalseTotal
if defined $prefix and ref $prefix 3 2372 2375
Condition100%3/3
defined $prefix and ref $prefix
!ll&&!rl&&r
22551173
MC/DC100%2/2
defined $prefix and ref $prefix
defined $prefix ref $prefix
Truth table100%3/3
A and B
A= defined $prefixB= ref $prefix
ABresult
0X0
100
111
3285 if defined $prefix && ref $prefix;
3286  
3287 2372 for my $col (@{$cols}) {
3288 # Skip the local alias for the join key — it is not a data column
3289 5576 ▶ next if $local_jc ne $join_col && $col eq $local_jc;
Branch: 1 branch
BranchTrueFalseTotal
if $local_jc ne $join_col and $col eq $local_jc 40 5536 5576
Condition100%3/3
$local_jc ne $join_col and $col eq $local_jc
!ll&&!rl&&r
54855140
MC/DC100%2/2
$local_jc ne $join_col and $col eq $local_jc
$local_jc ne $join_col $col eq $local_jc
Truth table100%3/3
A and B
A= $local_jc ne $join_colB= $col eq $local_jc
ABresult
0X0
100
111
3290  
3291 5536 ▶ if (defined $prefix && exists $col_db{$col} && $col ne $join_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $prefix and exists $col_db{$col} and $col ne $join_col) { } 111 5425 5536
Condition100%6/6
defined $prefix and exists $col_db{$col} and $col ne $join_col
!ll&&!rl&&r
5316109111
defined $prefix and exists $col_db{$col}
!ll&&!rl&&r
5207109220
MC/DC100%3/3
defined $prefix and exists $col_db{$col} and $col ne $join_col
defined $prefix exists $col_db{$col} $col ne $join_col
Truth table100%4/4
A and B and C
A= defined $prefixB= exists $col_db{$col}C= $col ne $join_col
ABCresult
0XX0
10X0
1100
1111
3292 # Column already claimed by an earlier database AND a prefix is
3293 # configured: publish the collision as "$prefix.$col" so both
3294 # values survive in the merged row rather than one silently winning.
3295 # The join_column itself is never prefixed — it is the shared merge
3296 # key and is always broadcast by name; renaming it would break routing.
3297 111 my $pub = "$prefix.$col";
3298 111 $col_rename[$i]{$col} = $pub;
3299 111 $col_unrename[$i]{$pub} = $col;
3300 111 $col_db{$pub} = $i;
3301 } else {
3302 # No collision, or no prefix configured: last database wins
3303 # (preserved backward-compatible behaviour).
3304 5425 $col_db{$col} = $i;
3305 }
3306 }
3307 }
3308  
3309 1281 $self->{_col_db} = \%col_db;
3310 1281 $self->{_db_cols} = \@db_cols;
3311 1281 $self->{_col_rename} = \@col_rename;
3312 1281 $self->{_col_unrename} = \@col_unrename;
3313  
3314 1281 return;
3315 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3316  
3317 # _validate_schema_types()
3318 # Purpose: Carp when two databases share a column name (without collision_prefix)
3319 # but disagree on its type, which would cause silent type coercion.
3320 # Entry: _dbs, _col_rename, _join_map, _join_col are all populated.
3321 # Exit: Emits one carp per mismatched column; no other side effects.
3322 1367 ▶sub _validate_schema_types :Protected {
Subroutine _validate_schema_types: called CC=16 SCAR=27.8
3323 1367 my ($self) = @_;
3324  
3325 1367 my $join_col = $self->{_join_col};
3326 1367 my %seen; # col_name => { idx => $i, type => $type_str }
3327  
3328 1367 for my $i (0 .. $#{ $self->{_dbs} }) {
3329 2583 my $db = $self->{_dbs}[$i];
3330 2583 ▶ my $s = do { local $@; eval { $db->schema() } } // {};
Condition100%2/2
do { local $@; eval { do { $db->schema } } } // {}
l!l
2380203
MC/DC100%1/1
do { local $@; eval { do { $db->schema } } } // {}
do { local $@; eval { do { $db->schema } } }
Truth table100%2/2
A
A= do { local $@; eval { do { $db->schema } } }
Aresult
11
00
3331 2583 ▶ my $local_jc = $self->{_join_map}{$i} // $join_col;
Condition66%2/3
$self->{"_join_map"}{$i} // $join_col
l!l&&r!l&&!r
5025330
MC/DC0%0/2
$self->{"_join_map"}{$i} // $join_col
$self->{"_join_map"}{$i} $join_col
Truth table66%2/3
A // B
A= $self->{"_join_map"}{$i}B= $join_col
ABresult
1X1
011
000
3332 2583 ▶ my $renames = $self->{_col_rename}[$i] // {};
Condition50%1/2
$self->{"_col_rename"}[$i] // {}
l!l
25830
MC/DC0%0/1
$self->{"_col_rename"}[$i] // {}
$self->{"_col_rename"}[$i]
Truth table50%1/2
A
A= $self->{"_col_rename"}[$i]
Aresult
11
00
3333  
3334 2583 for my $orig_col (keys %{$s}) {
3335 # Skip the join-key alias (a different name for the same join key)
3336 2640 ▶ next if $local_jc ne $join_col && $orig_col eq $local_jc;
Branch: 1 branch
BranchTrueFalseTotal
if $local_jc ne $join_col and $orig_col eq $local_jc 14 2626 2640
Condition100%3/3
$local_jc ne $join_col and $orig_col eq $local_jc
!ll&&!rl&&r
26062014
MC/DC100%2/2
$local_jc ne $join_col and $orig_col eq $local_jc
$local_jc ne $join_col $orig_col eq $local_jc
Truth table100%3/3
A and B
A= $local_jc ne $join_colB= $orig_col eq $local_jc
ABresult
0X0
100
111
3337  
3338 # Skip the canonical join column itself — types may legitimately
3339 # differ between DAs (e.g. INTEGER PK vs TEXT) without causing issues
3340 # because the join column is not a data column.
3341 2626 ▶ next if $orig_col eq $join_col;
Branch: 1 branch
BranchTrueFalseTotal
if $orig_col eq $join_col 978 1648 2626
3342  
3343 # Skip columns that have a collision prefix configured for this DB:
3344 # they are published under distinct names, so no silent merge occurs.
3345 1648 ▶ next if exists $renames->{$orig_col};
Branch: 1 branch
BranchTrueFalseTotal
if exists $renames->{$orig_col} 41 1607 1648
3346  
3347 # Normalise to a plain type string; skip if the DA returns no type.
3348 1607 my $entry = $s->{$orig_col};
3349 my $type_str = ref($entry) eq 'HASH'
3350 1607 ▶ ? uc($entry->{type} // '')
Branch: 1 branch
BranchTrueFalseTotal
ref $entry eq 'HASH' ? : 1419 188 1607
Condition75%3/4
$entry->{"type"} // ""
l!l
14145
$entry // ""
l!l
1880
MC/DC100%1/1
$entry->{"type"} // ""
$entry->{"type"}
MC/DC0%0/1
$entry // ""
$entry
Truth table100%2/2
A
A= $entry->{"type"}
Aresult
11
00
Truth table50%1/2
A
A= $entry
Aresult
11
00
3351 : uc($entry // '');
3352 1607 ▶ next unless length $type_str;
Branch: 1 branch
BranchTrueFalseTotal
unless length $type_str 5 1602 1607
3353  
3354 1602 ▶ if (exists $seen{$orig_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $seen{$orig_col}) { } 18 1584 1602
3355 18 my $prev = $seen{$orig_col};
3356 18 ▶ if ($prev->{type} ne $type_str) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prev->{"type"} ne $type_str) 12 6 18
3357 carp $self->_err(
3358 'warn_schema_type_mismatch',
3359 $orig_col,
3360 $prev->{type}, $prev->{idx},
3361 12 $type_str, $i,
3362 );
3363 }
3364 } else {
3365 1584 $seen{$orig_col} = { idx => $i, type => $type_str };
3366 }
3367 }
3368 }
3369  
3370 1367 return;
3371 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3372  
3373 # _partition_criteria( \%params ) -> \@per_db
3374 # Purpose: Split a flat criteria hashref into one slice per component database.
3375 # Entry: $params is a criteria hashref; all keys must be column names or
3376 # join_column.
3377 # Exit: Returns an arrayref of per-database criteria hashrefs. The
3378 # join_column criterion is broadcast to every database using each
3379 # database's local join-key name. Unknown columns trigger a carp.
3380 # Effects: Carps for each unrecognised column name.
3381 1699 ▶sub _partition_criteria :Protected {
Subroutine _partition_criteria: called CC=9 SCAR=22.1
3382 1699 my ($self, $params) = @_;
3383  
3384 1699 my $join_col = $self->{_join_col};
3385 1699 my $n = scalar @{ $self->{_dbs} };
3386 1699 my @per_db = map { {} } 1 .. $n;
3387  
3388 1699 for my $col (keys %{$params}) {
3389 563 ▶ if ($col eq $join_col) {
Branch: 3 branches
BranchTrueFalseTotal
if ($col eq $join_col) { } 255 308 563
elsif ($col eq 'join') { } 0 308 308
elsif (defined(my $idx = $self->{'_col_db'}{$col})) { } 273 35 308
3390 # Broadcast to every database using each one's local key column name.
3391 # Shallow-copy operator hashrefs so a malicious component DA that
3392 # mutates its criteria hashref contents cannot corrupt siblings.
3393 255 my $val = $params->{$col};
3394 255 for my $i (0 .. $n - 1) {
3395 499 ▶ my $local = $self->{_join_map}{$i} // $join_col;
Condition66%2/3
$self->{"_join_map"}{$i} // $join_col
l!l&&r!l&&!r
414580
MC/DC0%0/2
$self->{"_join_map"}{$i} // $join_col
$self->{"_join_map"}{$i} $join_col
Truth table66%2/3
A // B
A= $self->{"_join_map"}{$i}B= $join_col
ABresult
1X1
011
000
3396 499 ▶ $per_db[$i]{$local} = ref($val) eq 'HASH' ? { %{$val} } : $val;
Branch: 1 branch
BranchTrueFalseTotal
ref $val eq 'HASH' ? : 24 475 499
3397 }
3398 } elsif ($col eq 'join') {
3399 # DA accepts a 'join =>' criteria key for SQL JOINs within one table.
3400 # DJ cannot route such a criterion to a component DA meaningfully, so
3401 # croak early with a diagnostic rather than silently dropping it.
3402 0 croak $self->_err('error_join_criterion');
3403 } elsif (defined(my $idx = $self->{_col_db}{$col})) {
3404 # Translate the published column name back to the database's own name
3405 # when the column was renamed for a collision (e.g. "pfx.col" -> "col").
3406 # Invariant: _col_unrename[$idx] is always initialised to {} by _build_col_index
3407 # and add_database, so the // {} fallback can never trigger (transitive reduction).
3408 273 ▶ my $db_col = $self->{_col_unrename}[$idx]{$col} // $col;
Condition66%2/3
$self->{"_col_unrename"}[$idx]{$col} // $col
l!l&&r!l&&!r
162570
MC/DC0%0/2
$self->{"_col_unrename"}[$idx]{$col} // $col
$self->{"_col_unrename"}[$idx]{$col} $col
Truth table66%2/3
A // B
A= $self->{"_col_unrename"}[$idx]{$col}B= $col
ABresult
1X1
011
000
3409 273 $per_db[$idx]{$db_col} = $params->{$col};
3410 } else {
3411 35 carp $self->_err('warn_unknown_column', $col);
3412 }
3413 }
3414  
3415 1699 return \@per_db;
3416 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3417  
3418 # _select_rows( $db, \%criteria, \%pushdown_or_undef ) -> \@rows
3419 # Purpose: Fetch a component database's rows, asking for only the primary's
3420 # keys when key pushdown applies, and falling back to the plain
3421 # criteria if the database can't answer that.
3422 # Entry: $db is a component database; $criteria is its partitioned criteria;
3423 # $pushdown is undef, or $criteria plus { local_jc => { -in => [...] } }.
3424 # Exit: Returns an arrayref of row hashrefs (never undef).
3425 # Effects: Calls selectall_arrayref once, or twice when the pushdown query
3426 # croaks or returns a non-arrayref.
3427 # Notes: A plain function, not a :Protected method, because the parallel
3428 # path calls it inside a thread closure that deliberately doesn't
3429 # capture $self. The fallback costs only time: rows for keys outside
3430 # the primary's are never merged, so either query gives the same
3431 # result. A genuine error (e.g. a missing file) croaks again from the
3432 # fallback query, so it isn't hidden. local $@ keeps a failed
3433 # pushdown from leaking into the caller's $@.
3434 1533 ▶sub _select_rows {
Subroutine _select_rows: called CC=4 SCAR=13.9
3435 1533 my ($db, $criteria, $pushdown) = @_;
3436  
3437 1533 ▶ if ($pushdown) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pushdown) 127 1406 1533
3438 127 my $rows = do { local $@; eval { $db->selectall_arrayref($pushdown) } };
3439 127 ▶ return $rows if ref($rows) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $rows eq "ARRAY" 116 11 127
3440 }
3441  
3442 1417 ▶ return $db->selectall_arrayref($criteria) // [];
Condition100%2/2
$db->selectall_arrayref($criteria) // []
l!l
14038
MC/DC100%1/1
$db->selectall_arrayref($criteria) // []
$db->selectall_arrayref($criteria)
Truth table100%2/2
A
A= $db->selectall_arrayref($criteria)
Aresult
11
00
3443 }
3444  
3445 # _understands_in( $db ) -> $bool
3446 # Purpose: Whether a component database can be given a { -in => [...] }
3447 # criterion, i.e. whether its selectall_arrayref is
3448 # Database::Abstraction's own.
3449 # Entry: $db is a component database (any object with the DA interface).
3450 # Exit: True or false.
3451 # Effects: None.
3452 # Notes: isa('Database::Abstraction') isn't enough: a subclass that overrides
3453 # selectall_arrayref with plain equality matching would compare each
3454 # row with the hashref and silently return nothing, losing rows from a
3455 # left join. Database::Abstraction->can() is undef when the module
3456 # isn't loaded, so then nothing is pushed down. Plain function, since
3457 # it needs no object state.
3458 533 ▶sub _understands_in {
Subroutine _understands_in: called CC=5 SCAR=16.2
3459 533 my $db = shift;
3460  
3461 533 my $da_select = Database::Abstraction->can('selectall_arrayref');
3462 533 ▶ my $db_select = blessed($db) ? $db->can('selectall_arrayref') : undef;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($db) ? : 533 0 533
3463  
3464 533 ▶ return ($da_select && $db_select && $db_select == $da_select) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$da_select && $db_select && $db_select == $da_select ? : 127 406 533
Condition83%5/6
$da_select and $db_select and $db_select == $da_select
!ll&&!rl&&r
203203127
$da_select and $db_select
!ll&&!rl&&r
2030330
MC/DC66%2/3
$da_select and $db_select and $db_select == $da_select
$da_select $db_select $db_select == $da_select
Truth table75%3/4
A and B and C
A= $da_selectB= $db_selectC= $db_select == $da_select
ABCresult
0XX0
10X0
1100
1111
3465 }
3466  
3467 # _pushdown_criteria( \@per_db, \%primary_index ) -> \@pushdown
3468 # Purpose: Decide which secondary databases can be asked for only the primary's
3469 # keys, and build the criteria to ask them with. Without this a
3470 # secondary with no criteria is read in full: joining 118 rows to a
3471 # 3,800-row, 17 MB CSV read the whole CSV (0.32s of a 0.34s join;
3472 # 0.02s with pushdown).
3473 # Entry: \@per_db is the partitioned criteria from _partition_criteria, with
3474 # base filters already overlaid; \%primary_index is the primary's
3475 # rows indexed by join key, from _fetch_indexed.
3476 # Exit: Returns an arrayref indexed like _dbs. Element $i is a new criteria
3477 # hashref for secondary $i, or undef where pushdown doesn't apply:
3478 # an outer join (every secondary key is wanted); no primary keys; more
3479 # than $MAX_PUSHDOWN_KEYS keys; a secondary that already has a
3480 # criterion on its join column (the caller's restriction stands); or a
3481 # secondary whose query method isn't Database::Abstraction's own (see
3482 # _understands_in).
3483 # Effects: None. \@per_db is not modified, so the pushed-down key never
3484 # counts as a secondary's own criterion in the key-set resolution.
3485 # Notes: The keys are sorted so that the same primary gives the same query,
3486 # which keeps Database::Abstraction's query cache useful.
3487 802 ▶sub _pushdown_criteria :Protected {
Subroutine _pushdown_criteria: called CC=8 SCAR=20.8
3488 802 my ($self, $per_db, $primary_index) = @_;
3489  
3490 802 my @pushdown;
3491 802 ▶ my @keys = $self->{_join_type} eq 'outer' ? () : sort keys %{$primary_index};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'_join_type'} eq 'outer' ? : 35 767 802
3492  
3493 # An empty -in list is an SQL syntax error on some backends, and an empty
3494 # primary under left/inner already produced an empty result upstream
3495 802 ▶ if (@keys && @keys <= $MAX_PUSHDOWN_KEYS) {
Branch: 1 branch
BranchTrueFalseTotal
if (@keys and @keys <= $MAX_PUSHDOWN_KEYS) 739 63 802
Condition100%3/3
@keys and @keys <= $MAX_PUSHDOWN_KEYS
!ll&&!rl&&r
612739
MC/DC100%2/2
@keys and @keys <= $MAX_PUSHDOWN_KEYS
@keys @keys <= $MAX_PUSHDOWN_KEYS
Truth table100%3/3
A and B
A= @keysB= @keys <= $MAX_PUSHDOWN_KEYS
ABresult
0X0
100
111
3496 739 for my $i (1 .. $#{ $self->{_dbs} }) {
3497 643 my $db = $self->{_dbs}[$i];
3498 643 ▶ my $local_jc = $self->{_join_map}{$i} // $self->{_join_col};
Condition66%2/3
$self->{"_join_map"}{$i} // $self->{"_join_col"}
l!l&&r!l&&!r
515920
MC/DC0%0/2
$self->{"_join_map"}{$i} // $self->{"_join_col"}
$self->{"_join_map"}{$i} $self->{"_join_col"}
Truth table66%2/3
A // B
A= $self->{"_join_map"}{$i}B= $self->{"_join_col"}
ABresult
1X1
011
000
3499 643 ▶ next if exists $per_db->[$i]{$local_jc};
Branch: 1 branch
BranchTrueFalseTotal
if exists $per_db->[$i]{$local_jc} 97 546 643
3500 546 ▶ next unless _understands_in($db);
Branch: 1 branch
BranchTrueFalseTotal
unless _understands_in($db) 419 127 546
3501  
3502 # A copy per database, as in _partition_criteria, so that one
3503 # database mutating its criteria can't affect another
3504 127 $pushdown[$i] = { %{ $per_db->[$i] }, $local_jc => { $DA_IN_OP => [ @keys ] } };
3505 }
3506 }
3507  
3508 802 return \@pushdown;
3509 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3510  
3511 # _fetch_indexed( $db_idx, \%criteria [, \%pushdown] ) -> \%join_val_to_\@rows
3512 # Purpose: Query one component database and index its rows by join-key value.
3513 # Entry: $db_idx is the zero-based database index; $criteria is the
3514 # pre-partitioned criteria hashref for this database; $pushdown is
3515 # the optional key-pushdown criteria (see _select_rows).
3516 # Exit: Returns a hashref: join-key value => arrayref of row hashrefs.
3517 # Multiple rows sharing the same join-key value are all preserved
3518 # (important for the primary database when one key maps to many rows).
3519 # Effects: Calls selectall_arrayref on the component database.
3520 1533 ▶sub _fetch_indexed :Protected {
Subroutine _fetch_indexed: called CC=4 SCAR=13.9
3521 1533 my ($self, $db_idx, $criteria, $pushdown) = @_;
3522  
3523 1533 my $db = $self->{_dbs}[$db_idx];
3524 1533 ▶ my $local_jc = $self->{_join_map}{$db_idx} // $self->{_join_col};
Condition66%2/3
$self->{"_join_map"}{$db_idx} // $self->{"_join_col"}
l!l&&r!l&&!r
6114720
MC/DC0%0/2
$self->{"_join_map"}{$db_idx} // $self->{"_join_col"}
$self->{"_join_map"}{$db_idx} $self->{"_join_col"}
Truth table66%2/3
A // B
A= $self->{"_join_map"}{$db_idx}B= $self->{"_join_col"}
ABresult
1X1
011
000
3525  
3526 1533 my $rows = _select_rows($db, $criteria, $pushdown);
3527  
3528 1527 my %indexed;
3529 1527 for my $row (@{$rows}) {
3530 5269 my $key = $row->{$local_jc};
3531 5269 ▶ next unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 4 5265 5269
3532 5265 push @{ $indexed{$key} }, $row;
3533 }
3534  
3535 1526 return \%indexed;
3536 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3537  
3538 # _joined_query( \%params, %opts ) -> \@merged_rows
3539 #
3540 # Purpose: Dispatcher — routes to the array (in-memory) or SQLite join backend
3541 # based on $self->{_backend}. %opts are passed through to the backend
3542 # (currently: sort_by, limit, offset).
3543 904 ▶sub _joined_query :Protected {
Subroutine _joined_query: called CC=2 SCAR=6.9
3544 904 my ($self, $params, %opts) = @_;
3545 904 my $backend = $self->{_backend};
3546 904 ▶ return $self->_joined_query_array($params, %opts) if $backend eq 'array';
Branch: 1 branch
BranchTrueFalseTotal
if $backend eq "array" 167 737 904
3547 737 return $self->_sqlite_join($params, %opts);
3548 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3549  
3550 # _joined_query_array( \%params ) -> \@merged_rows
3551 #
3552 # Purpose: Core in-memory join algorithm. Partitions criteria, fetches per-database
3553 # results, resolves the key set, and merges rows.
3554 #
3555 # Key-set resolution (applied for each secondary database after the primary):
3556 #
3557 # If the database had criteria in this query call (after base filter overlay),
3558 # it acts as an INNER-JOIN partner: only keys present in its filtered result
3559 # survive. This gives WHERE-clause semantics even under a LEFT join.
3560 #
3561 # If the database had NO effective criteria:
3562 # inner -> intersect (standard inner join)
3563 # left -> no change (primary defines the key set)
3564 # outer -> union (all keys from any database)
3565 #
3566 # Row merge: for each qualifying primary row, secondary rows are overlaid in
3567 # index order. For duplicate columns, later databases win. Local join-key
3568 # aliases are renamed to the canonical join_column before merging.
3569 # Removed columns are deleted from every merged row.
3570 # _validate_pagination( $limit, $offset ) -> ($validated_limit, $validated_offset)
3571 #
3572 # Purpose: Single source of truth for pagination parameter validation.
3573 # Shared by _joined_query_array (array path) and _sqlite_join (SQLite path).
3574 # Entry: $limit and $offset are raw caller values -- may be undef, negative,
3575 # non-integer, etc.
3576 # Exit: Returns the original values when valid; returns undef (with carp) when
3577 # invalid. Premise: after this call, limit ∈ ℤ+ ∪ {undef} and
3578 # offset ∈ ℤ≥0 ∪ {undef}. All downstream guards may safely rely on this.
3579 994 ▶sub _validate_pagination :Protected {
Subroutine _validate_pagination: called CC=6 SCAR=17.9
3580 994 my ($self, $limit, $offset) = @_;
3581 # Syllogism: limit must be a positive integer ∧ matches /^\d+\z/a ∧ >= 1.
3582 # Conclusion: any value that fails either check is treated as absent.
3583 # \z (not $): rejects strings ending with \n that $ would silently accept.
3584 # /a flag: restricts \d to ASCII [0-9]; rejects Unicode decimal digits
3585 # (e.g. Arabic-Indic ٣) that \d matches but Perl's numeric
3586 # coercion would silently treat as 0, bypassing the >= 1 guard.
3587 994 ▶ if (defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 75 919 994
3588 75 ▶ if ($limit !~ /^\d+\z/a || $limit < 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $limit =~ /^\d+\z/a or $limit < 1) 15 60 75
Condition100%3/3
not $limit =~ /^\d+\z/a or $limit < 1
l!l&&r!l&&!r
9660
MC/DC100%2/2
not $limit =~ /^\d+\z/a or $limit < 1
not $limit =~ /^\d+\z/a $limit < 1
Truth table100%3/3
not(A) or B
A= not $limit =~ /^\d+\z/aB= $limit < 1
ABresult
1X1
011
000
3589 15 carp('Database::Join: limit must be a positive integer; ignored');
3590 15 undef $limit;
3591 }
3592 }
3593 # Syllogism: offset must be a non-negative integer ∧ matches /^\d+\z/a.
3594 # Conclusion: any value that fails the check is treated as absent.
3595 # Same \z / /a rationale as limit above.
3596 994 ▶ if (defined $offset) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 64 930 994
3597 64 ▶ if ($offset !~ /^\d+\z/a) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($offset =~ /^\d+\z/a) 9 55 64
3598 9 carp('Database::Join: offset must be a non-negative integer; ignored');
3599 9 undef $offset;
3600 }
3601 }
3602 994 return ($limit, $offset);
3603 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3604  
3605 818 ▶sub _joined_query_array :Protected {
Subroutine _joined_query_array: called CC=73 SCAR=46.6
3606 818 my ($self, $params, %opts) = @_;
3607 818 my $sort_by = $opts{sort_by};
3608 818 my $limit = $opts{limit};
3609 818 my $offset = $opts{offset};
3610 818 my $distinct = $opts{distinct};
3611 818 my $columns = $opts{columns};
3612  
3613 # Fast path: skip Sub::Protected dispatch entirely when no pagination params are
3614 # supplied (the common case). Saves one method-lookup overhead per query.
3615 818 ▶ ($limit, $offset) = $self->_validate_pagination($limit, $offset)
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit or defined $offset 66 752 818
Condition100%3/3
defined $limit or defined $offset
l!l&&r!l&&!r
4422752
MC/DC100%2/2
defined $limit or defined $offset
defined $limit defined $offset
Truth table100%3/3
A or B
A= defined $limitB= defined $offset
ABresult
1X1
011
000
3616 if defined $limit || defined $offset;
3617  
3618 818 my $join_col = $self->{_join_col};
3619 818 my $join_type = $self->{_join_type};
3620 818 my $n = scalar @{ $self->{_dbs} };
3621  
3622 818 my $per_db = $self->_partition_criteria($params);
3623  
3624 # Overlay any per-database base filters onto the partitioned criteria.
3625 # A filtered database always has effective criteria, so $had_criteria will
3626 # be true for it — giving inner-join key-set semantics regardless of join_type.
3627 818 for my $i (0 .. $n - 1) {
3628 1540 ▶ my $base = $self->{_filters}{$i} // {};
Condition100%2/2
$self->{"_filters"}{$i} // {}
l!l
1031437
MC/DC100%1/1
$self->{"_filters"}{$i} // {}
$self->{"_filters"}{$i}
Truth table100%2/2
A
A= $self->{"_filters"}{$i}
Aresult
11
00
3629 1540 ▶ next unless %{$base};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$base;} 1442 98 1540
3630 98 $per_db->[$i] = _merge_criteria($base, $per_db->[$i]);
3631 }
3632  
3633 # Fetch and index each database with its own criteria slice.
3634 818 my @indexed;
3635 818 $indexed[0] = $self->_fetch_indexed(0, $per_db->[0]);
3636  
3637 # Early exit: for inner and left joins, an empty primary result means the
3638 # key set is provably empty (left: primary defines it; inner: ∩ ∅ = ∅).
3639 # Skipping secondary fetches avoids up to N-1 unnecessary DA round-trips.
3640 #
3641 # Two guards prevent premature exit:
3642 # (a) join-column broadcast: when a join-col criterion is present it must
3643 # be physically delivered to each secondary DA (the call itself is what
3644 # forwards it; the partition only prepared the per-db slice).
3645 # (b) secondary-owned criteria: a secondary with its own criteria (e.g.
3646 # score => $val) must still be queried so those criteria are delivered.
3647 # Without the call the DA never receives them — breaking the partition-
3648 # isolation invariant the security tests verify.
3649 817 ▶ my $local_jc_0_early = $self->{_join_map}{0} // $join_col;
Condition33%1/3
$self->{"_join_map"}{0} // $join_col
l!l&&r!l&&!r
08170
MC/DC0%0/2
$self->{"_join_map"}{0} // $join_col
$self->{"_join_map"}{0} $join_col
Truth table33%1/3
A // B
A= $self->{"_join_map"}{0}B= $join_col
ABresult
1X1
011
000
3650 817 my $sec_has_criteria = grep { %{ $per_db->[$_] } } 1 .. $n - 1;
3651 817 return [] if !%{ $indexed[0] }
3652 && $join_type ne 'outer'
3653 817 ▶ && !exists $per_db->[0]{$local_jc_0_early}
Branch: 1 branch
BranchTrueFalseTotal
if not %{$indexed[0];} and $join_type ne "outer" and not exists $per_db->[0]{$local_jc_0_early} and not $sec_has_criteria 15 802 817
Condition100%9/9
not %{$indexed[0];} and $join_type ne "outer" and not exists $per_db->[0]{$local_jc_0_early} and not $sec_has_criteria
!ll&&!rl&&r
801115
not %{$indexed[0];} and $join_type ne "outer" and not exists $per_db->[0]{$local_jc_0_early}
!ll&&!rl&&r
7762516
not %{$indexed[0];} and $join_type ne "outer"
!ll&&!rl&&r
774241
MC/DC100%4/4
not %{$indexed[0];} and $join_type ne "outer" and not exists $per_db->[0]{$local_jc_0_early} and not $sec_has_criteria
not %{$indexed[0];} $join_type ne "outer" not exists $per_db->[0]{$local_jc_0_early} not $sec_has_criteria
Truth table100%5/5
not(A) and B and not(C) and not(D)
A= not %{$indexed[0];}B= $join_type ne "outer"C= not exists $per_db->[0]{$local_jc_0_early}D= not $sec_has_criteria
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3654 && !$sec_has_criteria;
3655  
3656 # Fetch and index secondary databases.
3657 # With parallel => 1 and 2+ secondaries: spawn one Perl thread per secondary
3658 # so all secondaries are queried concurrently. Total latency becomes
3659 # max(DA latencies) instead of sum(DA latencies). The primary was already
3660 # fetched sequentially above (needed for the early-exit short-circuit).
3661 # The thread closure captures only $db, $crit, $push and $local_jc (plain scalars
3662 # or in-memory data) — $self is intentionally not captured to avoid copying
3663 # the full blessed hashref (including all DA refs) into each thread.
3664 # Falls back to sequential when: threads module is unavailable, n <= 2, or
3665 # parallel => 0 (the default).
3666 #
3667 # Windows / ithreads safety: cloned DBI handles inside DA objects are not
3668 # thread-safe. Pre-initialise every secondary slot to {} so that if a thread
3669 # fails the slot holds a valid (empty) hashref rather than undef, which would
3670 # corrupt the inner-join key-set resolution. Any secondary whose thread does
3671 # not deliver a valid hashref is re-fetched sequentially after all joins
3672 # complete, preserving correctness on every platform.
3673 802 $indexed[$_] = {} for 1 .. $n - 1;
3674  
3675 # Key pushdown: a secondary with no criteria on its join column would
3676 # otherwise be read in full, although only rows matching a primary key can
3677 # be merged under a left or inner join. Ask it for just those keys. A
3678 # separate criteria list is used for the fetch so that the pushed-down key
3679 # can never count as the secondary's own criteria in the key-set
3680 # resolution below (which would turn a left join into an inner one).
3681 # Outer joins need every secondary key, so they are excluded. Only
3682 # databases using Database::Abstraction's own query method are asked,
3683 # since other implementations of the interface may not know -in.
3684 802 my @pushdown = @{ $self->_pushdown_criteria($per_db, $indexed[0]) };
3685  
3686 802 ▶ if ($self->{_parallel} && $n > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_parallel'} and $n > 2) { } 14 788 802
Condition100%3/3
$self->{"_parallel"} and $n > 2
!ll&&!rl&&r
780814
MC/DC100%2/2
$self->{"_parallel"} and $n > 2
$self->{"_parallel"} $n > 2
Truth table100%3/3
A and B
A= $self->{"_parallel"}B= $n > 2
ABresult
0X0
100
111
3687 0 ▶ $HAS_THREADS //= do { local $@; eval { require threads; 1 } ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require threads; 1 } } ? : 0 10 10
Condition66%2/3
$HAS_THREADS //= do { local $@; eval { do { require threads; 1 } } ? 1 : 0 }
l!l&&r!l&&!r
4100
MC/DC0%0/2
$HAS_THREADS //= do { local $@; eval { do { require threads; 1 } } ? 1 : 0 }
$HAS_THREADS do { local $@; eval { do { require threads; 1 } } ? 1 : 0 }
Truth table66%2/3
A //= B
A= $HAS_THREADSB= do { local $@; eval { do { require threads; 1 } } ? 1 : 0 }
ABresult
1X1
011
000
3688 14 ▶ if ($HAS_THREADS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HAS_THREADS) { } 0 14 14
3689 0 my @thr;
3690 0 for my $i (1 .. $n - 1) {
3691 my ($db, $crit, $push, $local_jc) = (
3692 $self->{_dbs}[$i], $per_db->[$i], $pushdown[$i],
3693 0 ▶ $self->{_join_map}{$i} // $join_col,
Condition0%0/3
$self->{"_join_map"}{$i} // $join_col
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_join_map"}{$i} // $join_col
$self->{"_join_map"}{$i} $join_col
Truth table0%0/3
A // B
A= $self->{"_join_map"}{$i}B= $join_col
ABresult
1X1
011
000
3694 );
3695 # Wrap thread creation: it can fail if the DA cannot be cloned
3696 # (e.g. DBI handles on Windows). On failure we skip the push so
3697 # the sequential fallback below handles that secondary.
3698 0 local $@;
3699 0 my $t = eval {
3700 0 ▶ threads->create(sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
3701 # eval inside the thread: prevents a DA exception from
3702 # killing the thread and returning an empty list to join().
3703 0 local $@;
3704 0 ▶ my $rows = eval { _select_rows($db, $crit, $push) } // [];
Condition0%0/2
eval { do { _select_rows($db, $crit, $push) } } // []
l!l
00
MC/DC0%0/1
eval { do { _select_rows($db, $crit, $push) } } // []
eval { do { _select_rows($db, $crit, $push) } }
Truth table0%0/2
A
A= eval { do { _select_rows($db, $crit, $push) } }
Aresult
11
00
3705 0 my %idx;
3706 0 for my $row (@{$rows}) {
3707 0 my $key = $row->{$local_jc};
3708 0 ▶ push @{$idx{$key}}, $row if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 0 0 0
3709 }
3710 0 return ($i, \%idx);
3711 0 });
3712 };
3713 0 ▶ push @thr, $t if $t;
Branch: 1 branch
BranchTrueFalseTotal
if $t 0 0 0
3714 }
3715  
3716 0 my %done;
3717 0 for my $t (@thr) {
3718 # eval on join: a thread that died (e.g. uncaught exception)
3719 # causes join() to rethrow on some platforms.
3720 0 local $@;
3721 0 my ($i, $idx);
3722 0 eval { ($i, $idx) = $t->join() };
3723 0 ▶ if (defined $i && ref($idx) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $i and ref $idx eq "HASH") 0 0 0
Condition0%0/3
defined $i and ref $idx eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $i and ref $idx eq "HASH"
defined $i ref $idx eq "HASH"
Truth table0%0/3
A and B
A= defined $iB= ref $idx eq "HASH"
ABresult
0X0
100
111
3724 0 $indexed[$i] = $idx;
3725 0 $done{$i} = 1;
3726 }
3727 }
3728  
3729 # Re-fetch sequentially any secondary not delivered by a thread.
3730 # This covers: thread creation failure, thread death, or an empty
3731 # result that may indicate a non-thread-safe DA (e.g. DBI on Windows).
3732 0 for my $i (1 .. $n - 1) {
3733 0 ▶ next if $done{$i};
Branch: 1 branch
BranchTrueFalseTotal
if $done{$i} 0 0 0
3734 0 $indexed[$i] = $self->_fetch_indexed($i, $per_db->[$i], $pushdown[$i]);
3735 }
3736 } else {
3737 14 carp 'Database::Join: parallel => 1 requires the threads module; falling back to sequential';
3738 14 $indexed[$_] = $self->_fetch_indexed($_, $per_db->[$_], $pushdown[$_]) for 1 .. $n - 1;
3739 }
3740 } else {
3741 788 $indexed[$_] = $self->_fetch_indexed($_, $per_db->[$_], $pushdown[$_]) for 1 .. $n - 1;
3742 }
3743  
3744 # Premise: the key-set resolution loop starts at i=1 (primary seeds %key_set).
3745 # Conclusion: $had_criteria[0] is a dead store (D~); compute only for i >= 1.
3746 #
3747 # The broadcast join-column criterion (entry=>'A3' delivered to ALL databases)
3748 # must NOT count as "had criteria" for secondaries. It is a key-range selector
3749 # on the merged view, not a predicate that bounds what the secondary contributes.
3750 # Only base filters and non-join-column query-time criteria trigger inner-join.
3751 796 my @had_criteria;
3752 796 for my $i (1 .. $n - 1) {
3753 702 ▶ my $local_jc = $self->{_join_map}{$i} // $join_col;
Condition66%2/3
$self->{"_join_map"}{$i} // $join_col
l!l&&r!l&&!r
596430
MC/DC0%0/2
$self->{"_join_map"}{$i} // $join_col
$self->{"_join_map"}{$i} $join_col
Truth table66%2/3
A // B
A= $self->{"_join_map"}{$i}B= $join_col
ABresult
1X1
011
000
3754 702 ▶ my $has_filter = !!%{ $self->{_filters}{$i} // {} };
Condition100%2/2
$self->{"_filters"}{$i} // {}
l!l
72630
MC/DC100%1/1
$self->{"_filters"}{$i} // {}
$self->{"_filters"}{$i}
Truth table100%2/2
A
A= $self->{"_filters"}{$i}
Aresult
11
00
3755 702 my $crit = $per_db->[$i];
3756 # Avoid copying the criteria hash just to delete the join-col key.
3757 # Arithmetic is O(1) allocations: count total keys, subtract 1 when the
3758 # local join-col key is present. Any result > 0 is truthy (has own criteria).
3759 702 ▶ my $own = (keys %{$crit}) - (exists $crit->{$local_jc} ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
exists $crit->{$local_jc} ? : 123 579 702
3760 702 ▶ $had_criteria[$i] = $has_filter || $own;
Condition100%3/3
$has_filter || $own
l!l&&r!l&&!r
7050582
MC/DC100%2/2
$has_filter || $own
$has_filter $own
Truth table100%3/3
A || B
A= $has_filterB= $own
ABresult
1X1
011
000
3761 }
3762  
3763 # Seed the key set from the primary database.
3764 # Hash-slice assignment avoids the intermediate 2K-element flat list that
3765 # map { $_ => 1 } would allocate before assigning to %key_set. Values are
3766 # undef; only exists() is used for lookups, so the sentinel value is irrelevant.
3767 796 my %key_set;
3768 796 @key_set{ keys %{ $indexed[0] } } = ();
3769  
3770 # Merge in each secondary database.
3771 # Premise 1: indexed[$i] is a valid hashref (returned by _fetch_indexed).
3772 # Premise 2: join_type ∈ {left, inner, outer} (enforced by validate_strict).
3773 # Conclusion: the three branches below are exhaustive and mutually exclusive.
3774 796 for my $i (1 .. $n - 1) {
3775 702 ▶ if ($had_criteria[$i] || $join_type eq 'inner') {
Branch: 2 branches
BranchTrueFalseTotal
if ($had_criteria[$i] or $join_type eq 'inner') { } 218 484 702
elsif ($join_type eq 'outer') { } 32 452 484
Condition100%3/3
$had_criteria[$i] or $join_type eq "inner"
l!l&&r!l&&!r
12098484
MC/DC100%2/2
$had_criteria[$i] or $join_type eq "inner"
$had_criteria[$i] $join_type eq "inner"
Truth table100%3/3
A or B
A= $had_criteria[$i]B= $join_type eq "inner"
ABresult
1X1
011
000
3776 # Intersect: single-pass delete for keys absent from this secondary.
3777 # A single loop avoids the intermediate list that grep would allocate
3778 # before the delete loop could iterate it (saves O(K) allocations).
3779 218 for my $k (keys %key_set) {
3780 2510 ▶ delete $key_set{$k} unless exists $indexed[$i]{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $indexed[$i]{$k} 2185 325 2510
3781 }
3782 } elsif ($join_type eq 'outer') {
3783 # Union: hash slice assignment is a single Perl op, not a per-key loop.
3784 32 @key_set{ keys %{ $indexed[$i] } } = ();
3785 }
3786 # left + no criteria: key_set unchanged (primary defines the set).
3787 }
3788  
3789 # Pre-hoist per-secondary constants outside the key loop.
3790 # $sec_local_jc[$i], the rename flag, and $sec_renames[$i] are all invariant
3791 # across every key and every primary row. Computing them inside the key loop
3792 # wastes K dereferences per secondary database (K = number of qualifying keys).
3793 # Splitting the inner column loop on the rename flag eliminates the flag check
3794 # from inside the per-column loop, saving R-1 branch evaluations per secondary
3795 # per row (R = columns in the secondary row).
3796 796 my (@sec_local_jc, @sec_rename, @sec_renames);
3797 796 for my $i (1 .. $n - 1) {
3798 702 $sec_local_jc[$i] = $self->{_join_map}{$i};
3799 702 ▶ $sec_rename[$i] = ($sec_local_jc[$i] && $sec_local_jc[$i] ne $join_col) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$sec_local_jc[$i] && $sec_local_jc[$i] ne $join_col ? : 57 645 702
Condition100%3/3
$sec_local_jc[$i] and $sec_local_jc[$i] ne $join_col
!ll&&!rl&&r
643257
MC/DC100%2/2
$sec_local_jc[$i] and $sec_local_jc[$i] ne $join_col
$sec_local_jc[$i] $sec_local_jc[$i] ne $join_col
Truth table100%3/3
A and B
A= $sec_local_jc[$i]B= $sec_local_jc[$i] ne $join_col
ABresult
0X0
100
111
3800 # _col_rename[$i] is always initialised to {} by _build_col_index / add_database
3801 # (transitive reduction: the // {} fallback can never trigger).
3802 702 $sec_renames[$i] = $self->{_col_rename}[$i];
3803 }
3804  
3805 # Cache the removed-column list across calls; avoids extracting keys %hash every
3806 # query. Lazily built here and invalidated to undef by remove_column().
3807 796 ▶ my $removed = ($self->{_removed_list} //= [keys %{ $self->{_removed_cols} }]);
Condition100%2/2
$self->{"_removed_list"} //= [keys %{$$self{"_removed_cols"};}]
l!l
163633
MC/DC100%1/1
$self->{"_removed_list"} //= [keys %{$$self{"_removed_cols"};}]
$self->{"_removed_list"}
Truth table100%2/2
A
A= $self->{"_removed_list"}
Aresult
11
00
3808  
3809 # Parse sort_by once before the merge loop so we can decide whether the
3810 # initial O(K log K) sort of %key_set is necessary.
3811 # When sort_by targets a column other than the join_col, that initial sort
3812 # is overridden by the final Schwarzian pass -- skip it to save a full sort.
3813 # When sort_by is absent or targets the join_col, the initial sort IS the
3814 # final order and must be kept.
3815 796 my ($ob_col, $ob_dir) = ($join_col, 'ASC');
3816 796 ▶ if (defined $sort_by) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_by) 55 741 796
3817 55 ▶ my ($req_col, $req_dir) = ref($sort_by) eq 'ARRAY' ? @{$sort_by} : ($sort_by, 'ASC');
Branch: 1 branch
BranchTrueFalseTotal
ref $sort_by eq 'ARRAY' ? : 29 26 55
3818 55 ▶ $req_dir = uc($req_dir // 'ASC');
Condition100%2/2
$req_dir // "ASC"
l!l
532
MC/DC100%1/1
$req_dir // "ASC"
$req_dir
Truth table100%2/2
A
A= $req_dir
Aresult
11
00
3819 55 ▶ unless ($req_dir eq 'ASC' || $req_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($req_dir eq "ASC" or $req_dir eq "DESC") 6 49 55
Condition100%3/3
$req_dir eq "ASC" or $req_dir eq "DESC"
l!l&&r!l&&!r
33166
MC/DC100%2/2
$req_dir eq "ASC" or $req_dir eq "DESC"
$req_dir eq "ASC" $req_dir eq "DESC"
Truth table100%3/3
A or B
A= $req_dir eq "ASC"B= $req_dir eq "DESC"
ABresult
1X1
011
000
3820 6 carp "Database::Join: sort_by direction '$req_dir' is not supported; using ASC";
3821 6 $req_dir = 'ASC';
3822 }
3823 55 ▶ if ($req_col ne $join_col && !exists $self->{_col_db}{$req_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req_col ne $join_col and not exists $self->{'_col_db'}{$req_col}) { } 8 47 55
Condition100%3/3
$req_col ne $join_col and not exists $self->{"_col_db"}{$req_col}
!ll&&!rl&&r
11368
MC/DC100%2/2
$req_col ne $join_col and not exists $self->{"_col_db"}{$req_col}
$req_col ne $join_col not exists $self->{"_col_db"}{$req_col}
Truth table100%3/3
A and not(B)
A= $req_col ne $join_colB= not exists $self->{"_col_db"}{$req_col}
ABresult
0X0
100
111
3824 8 carp "Database::Join: sort_by column '$req_col' is not in the merged view; result sorted by join_column";
3825 } else {
3826 47 ($ob_col, $ob_dir) = ($req_col, $req_dir);
3827 }
3828 }
3829 # True when sort_by targets a non-join column: the initial sort is redundant.
3830 796 my $ob_override = ($ob_col ne $join_col);
3831  
3832 # Build one merged result row for every primary-database row that qualifies.
3833 # Secondary databases act as lookup tables: when a key maps to multiple
3834 # secondary rows, the last one wins (consistent with construction-time
3835 # last-database-wins column routing).
3836 796 my @result;
3837 # When sort_by will override the join_col order, iterate keys unsorted (O(K))
3838 # instead of sorted (O(K log K)); the Schwarzian pass at the end reorders.
3839 796 ▶ for my $key ($ob_override ? keys %key_set : sort keys %key_set) {
Branch: 1 branch
BranchTrueFalseTotal
$ob_override ? : 36 760 796
3840 # Iterate directly over the arrayref: avoids copying primary rows into a
3841 # new @base_rows array (saves P element copies per key, P = rows per key).
3842 # [{}] ensures outer-join keys absent from the primary produce one merged row.
3843 1698 ▶ for my $prow (@{ $indexed[0]{$key} // [{}] }) {
Condition100%2/2
$indexed[0]{$key} // [{}]
l!l
166632
MC/DC100%1/1
$indexed[0]{$key} // [{}]
$indexed[0]{$key}
Truth table100%2/2
A
A= $indexed[0]{$key}
Aresult
11
00
3844 1728 my %merged = %{$prow};
3845  
3846 1728 for my $i (1 .. $n - 1) {
3847 1449 my $sec_arr = $indexed[$i]{$key};
3848 1449 ▶ next unless $sec_arr && @{$sec_arr};
Branch: 1 branch
BranchTrueFalseTotal
unless $sec_arr and @{$sec_arr;} 137 1312 1449
Condition66%2/3
$sec_arr and @{$sec_arr;}
!ll&&!rl&&r
13701312
MC/DC50%1/2
$sec_arr and @{$sec_arr;}
$sec_arr @{$sec_arr;}
Truth table66%2/3
A and B
A= $sec_arrB= @{$sec_arr;}
ABresult
0X0
100
111
3849  
3850 # Write secondary columns directly into %merged without copying
3851 # the source row into a temporary hash first.
3852 # Before: %row_copy = %{$src} then %merged = (%merged,%row_copy)
3853 # → 2 full hash copies per secondary per row: O(C) + O(|merged|+C)
3854 # After: per-key loop writes straight into %merged
3855 # → O(C) key assignments only; no intermediate allocation
3856 1312 my $src = $sec_arr->[-1];
3857  
3858 1312 ▶ if ($sec_rename[$i]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sec_rename[$i]) { } 116 1196 1312
3859 116 my $local_jc = $sec_local_jc[$i];
3860 116 my $renames = $sec_renames[$i];
3861 116 for my $k (keys %{$src}) {
3862 303 ▶ if ($k eq $local_jc) {
Branch: 2 branches
BranchTrueFalseTotal
if ($k eq $local_jc) { } 116 187 303
elsif (my $pub = $renames->{$k}) { } 60 127 187
3863 # Translate local join-key alias to the canonical join_column name
3864 116 $merged{$join_col} = $src->{$k};
3865 } elsif (my $pub = $renames->{$k}) {
3866 60 $merged{$pub} = $src->{$k};
3867 } else {
3868 127 $merged{$k} = $src->{$k};
3869 }
3870 }
3871 } else {
3872 1196 my $renames = $sec_renames[$i];
3873 1196 for my $k (keys %{$src}) {
3874 2709 ▶ if (my $pub = $renames->{$k}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pub = $renames->{$k}) { } 153 2556 2709
3875 # Collision-renamed column: write under the published prefixed name
3876 153 $merged{$pub} = $src->{$k};
3877 } else {
3878 2556 $merged{$k} = $src->{$k};
3879 }
3880 }
3881 }
3882 }
3883  
3884 1728 ▶ delete @merged{@{$removed}} if @{$removed};
Branch: 1 branch
BranchTrueFalseTotal
if @{$removed;} 61 1667 1728
3885 1728 push @result, \%merged;
3886 }
3887 }
3888  
3889 # Apply mandatory_filters (row-level security predicates).
3890 # These are construction-time guards applied on every query after the merge,
3891 # before sort and pagination, so they cannot be bypassed by caller criteria.
3892 796 ▶ if (@{ $self->{_mandatory_filters} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"_mandatory_filters"};}) 14 782 796
3893 14 @result = grep { _pass_mandatory_filters($_, $self->{_mandatory_filters}) } @result;
3894 }
3895  
3896 # distinct: deduplicate merged rows.
3897 # With columns: project to those columns and deduplicate on their values.
3898 # Without columns: deduplicate on all column values (return distinct full rows).
3899 796 ▶ if ($distinct) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distinct) 7 789 796
3900 7 @result = @{ _apply_distinct_array(\@result, $columns) };
3901 }
3902  
3903 # Caller-specified ORDER BY.
3904 # $ob_col / $ob_dir / $ob_override were parsed BEFORE the merge loop.
3905 # Three cases:
3906 # 1. Non-join-col override ($ob_override true): Schwarzian transform
3907 # O(R) key extractions + O(R log R) scalar comparisons -- cheaper than
3908 # O(2R log R) hash dereferences that a naive sort block would make.
3909 # 2. join_col DESC: O(R) reverse -- already sorted ASC by the loop.
3910 # 3. join_col ASC (default): already in order, nothing to do.
3911 796 ▶ if ($ob_override) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ob_override) { } 36 760 796
elsif ($ob_dir eq 'DESC') { } 7 753 760
3912 # Schwarzian: decorate, sort, undecorate.
3913 # String comparison (cmp). For accurate numeric ordering on large
3914 # numeric columns use backend => 'sqlite', which sorts by SQL type.
3915 36 ▶ my @tagged = map { [$_, $_->{$ob_col} // ''] } @result;
Condition100%2/2
$_->{$ob_col} // ""
l!l
1013
MC/DC100%1/1
$_->{$ob_col} // ""
$_->{$ob_col}
Truth table100%2/2
A
A= $_->{$ob_col}
Aresult
11
00
3916 36 ▶ if ($ob_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ob_dir eq 'DESC') { } 9 27 36
3917 9 @result = map { $_->[0] } sort { $b->[1] cmp $a->[1] } @tagged;
3918 } else {
3919 27 @result = map { $_->[0] } sort { $a->[1] cmp $b->[1] } @tagged;
3920 }
3921 } elsif ($ob_dir eq 'DESC') {
3922 # join_col DESC: O(R) reverse is cheaper than O(R log R) re-sort
3923 # because the merge loop already produced join_col ASC order.
3924 7 @result = reverse @result;
3925 }
3926 # join_col ASC: @result is already in join_column ascending order.
3927  
3928 # LIMIT / OFFSET pagination — applied after ordering.
3929 # splice removes elements from the front (offset) then truncates to limit.
3930 796 ▶ if (defined $offset && $offset > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset and $offset > 0) 27 769 796
Condition100%3/3
defined $offset and $offset > 0
!ll&&!rl&&r
762727
MC/DC100%2/2
defined $offset and $offset > 0
defined $offset $offset > 0
Truth table100%3/3
A and B
A= defined $offsetB= $offset > 0
ABresult
0X0
100
111
3931 27 splice(@result, 0, $offset);
3932 }
3933 796 ▶ if (defined $limit && $limit < scalar @result) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit and $limit < scalar @result) 28 768 796
Condition100%3/3
defined $limit and $limit < scalar @result
!ll&&!rl&&r
760828
MC/DC100%2/2
defined $limit and $limit < scalar @result
defined $limit $limit < scalar @result
Truth table100%3/3
A and B
A= defined $limitB= $limit < scalar @result
ABresult
0X0
100
111
3934 28 splice(@result, $limit);
3935 }
3936  
3937 796 return \@result;
3938 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3939  
3940 # _cache_fresh() -> bool
3941 # Purpose: Check whether the SQLite join cache is still valid.
3942 # Entry: $self->{_sqlite_cache} may or may not be set.
3943 # Exit: Returns 1 if the cache exists, the DBI handle is active, the source
3944 # count matches, and all source updated() timestamps match. Returns 0
3945 # if any of these conditions fail (caller must rebuild the cache).
3946 304 ▶sub _cache_fresh :Protected {
Subroutine _cache_fresh: called CC=9 SCAR=22.0
3947 304 my ($self) = @_;
3948  
3949 304 ▶ my $cache = $self->{_sqlite_cache} // return 0;
Condition100%2/2
$self->{"_sqlite_cache"} // (return 0)
l!l
89215
MC/DC100%1/1
$self->{"_sqlite_cache"} // (return 0)
$self->{"_sqlite_cache"}
Truth table100%2/2
A
A= $self->{"_sqlite_cache"}
Aresult
11
00
3950 89 my $n = scalar @{ $self->{_dbs} };
3951  
3952 89 ▶ return 0 if ($cache->{n} // 0) != $n;
Branch: 1 branch
BranchTrueFalseTotal
if ($cache->{"n"} // 0) != $n 3 86 89
Condition50%1/2
$cache->{"n"} // 0
l!l
890
MC/DC0%0/1
$cache->{"n"} // 0
$cache->{"n"}
Truth table50%1/2
A
A= $cache->{"n"}
Aresult
11
00
3953  
3954 # Verify the DBI handle is still usable.
3955 86 ▶ return 0 unless do { local $@; eval { $cache->{dbh}{Active} } };
Branch: 1 branch
BranchTrueFalseTotal
unless do { local $@; eval { do { $cache->{"dbh"}{"Active"} } } } 2 84 86
3956  
3957 # Verify that no source has been updated since the cache was built.
3958 # If a source does not implement updated(), skip the timestamp check for
3959 # it (the data is assumed stable; the cache stays valid indefinitely for
3960 # that source unless add_database() is called or the object is destroyed).
3961 84 for my $i (0 .. $n - 1) {
3962 145 ▶ my $cached_ts = $cache->{updated}{$i} // next; # not captured → skip
Condition100%2/2
$cache->{"updated"}{$i} // (next)
l!l
8362
MC/DC100%1/1
$cache->{"updated"}{$i} // (next)
$cache->{"updated"}{$i}
Truth table100%2/2
A
A= $cache->{"updated"}{$i}
Aresult
11
00
3963 83 my $current_ts;
3964 83 do { local $@; $current_ts = eval { $self->{_dbs}[$i]->updated() } };
3965 83 ▶ next unless defined $current_ts; # no updated() → skip
Branch: 1 branch
BranchTrueFalseTotal
unless defined $current_ts 0 83 83
3966 83 ▶ return 0 if $current_ts != $cached_ts;
Branch: 1 branch
BranchTrueFalseTotal
if $current_ts != $cached_ts 7 76 83
3967 }
3968  
3969 77 return 1;
3970 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3971  
3972 # _build_sqlite_cache()
3973 # Purpose: Create (or rebuild) the persistent SQLite join cache. Spills each
3974 # source database into a temp SQLite file using filter-only criteria;
3975 # SQLite-backed sources are zero-copy ATTACHed instead of spilled.
3976 # Query-time criteria are NOT applied here — they become WHERE clauses
3977 # in the per-call SQL generated by _sqlite_join.
3978 # _sql_quote_identifier( $name ) -> $quoted
3979 # Purpose: Produce a properly double-quoted SQL identifier, escaping any
3980 # embedded double-quote characters by doubling them (SQL standard).
3981 # Defence-in-depth: prevents SQL identifier injection when DA-supplied
3982 # column names or table names contain literal double-quote characters.
3983 # SQLite, like all ANSI SQL databases, represents a literal " inside a
3984 # double-quoted identifier as ""; this routine applies that transform.
3985 # Entry: $name — raw identifier string (column name, table name, or alias).
3986 # Exit: Returns the double-quoted, injection-safe SQL identifier string.
3987 5773 ▶sub _sql_quote_identifier {
Subroutine _sql_quote_identifier: called CC=1 SCAR=0.0
3988 5773 my ($name) = @_;
3989 5773 (my $safe = $name) =~ s/"/""/g;
3990 5773 return "\"$safe\"";
3991 }
3992  
3993 # Entry: _dbs, _join_map, _filters, _tmpdir must be set.
3994 # Exit: $self->{_sqlite_cache} holds {dbh, tmpfile, table_refs, source_cols,
3995 # is_attached, updated, n}. Any previous cache is disconnected first.
3996 # Each spilled table has a B-tree index on its join column.
3997 # Effects: Creates a File::Temp file (SUFFIX='.db', DIR=_tmpdir, UNLINK=1, EXLOCK=0).
3998 # Croaks with error_sqlite_connect if DBI::connect fails.
3999 227 ▶sub _build_sqlite_cache :Protected {
Subroutine _build_sqlite_cache: called CC=21 SCAR=30.8
4000 227 my ($self) = @_;
4001  
4002 # Disconnect any previous cache to release the old temp file.
4003 227 ▶ if (my $old = delete $self->{_sqlite_cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $old = delete $self->{"_sqlite_cache"}) 6 221 227
4004 6 local $@;
4005 6 ▶ eval { $old->{dbh}->disconnect } if $old->{dbh};
Branch: 1 branch
BranchTrueFalseTotal
if $old->{"dbh"} 6 0 6
4006 }
4007  
4008 227 require DBI;
4009 227 require File::Temp;
4010  
4011 227 my $join_col = $self->{_join_col};
4012 227 my $n = scalar @{ $self->{_dbs} };
4013  
4014 # EXLOCK => 0: before 0.2307 File::Temp defaults to O_EXLOCK, as Perl 5.28's copy
4015 # does. On a BSD that lock stops SQLite writing to the file: CREATE TABLE waits
4016 # out the busy timeout, then fails with "database is locked".
4017 my $tmpfile = File::Temp->new(
4018 SUFFIX => '.db',
4019 DIR => $self->{_tmpdir},
4020 227 UNLINK => 1,
4021 EXLOCK => 0,
4022 );
4023  
4024 216 ▶ my $tmpdbh = DBI->connect(
Branch: 1 branch
BranchTrueFalseTotal
my $tmpdbh = "DBI"->connect('dbi:SQLite:dbname=' . $tmpfile->filename, "", "", {"RaiseError", 1, "PrintError", 0, "AutoCommit", 1}) or croak($self->_err("error_sqlite_connect", "DBI"->errstr // "unknown error")) 214 2 216
Condition50%1/2
"DBI"->errstr // "unknown error"
l!l
02
MC/DC0%0/1
"DBI"->errstr // "unknown error"
"DBI"->errstr
Truth table50%1/2
A
A= "DBI"->errstr
Aresult
11
00
4025 'dbi:SQLite:dbname=' . $tmpfile->filename, '', '',
4026 { RaiseError => 1, PrintError => 0, AutoCommit => 1 },
4027 ) or croak $self->_err('error_sqlite_connect', DBI->errstr // 'unknown error');
4028  
4029 214 my (@table_refs, @source_cols, @is_attached);
4030  
4031 214 for my $i (0 .. $n - 1) {
4032 379 my $db = $self->{_dbs}[$i];
4033 379 ▶ my $local_jc = $self->{_join_map}{$i} // $join_col;
Condition66%2/3
$self->{"_join_map"}{$i} // $join_col
l!l&&r!l&&!r
23770
MC/DC0%0/2
$self->{"_join_map"}{$i} // $join_col
$self->{"_join_map"}{$i} $join_col
Truth table66%2/3
A // B
A= $self->{"_join_map"}{$i}B= $join_col
ABresult
1X1
011
000
4034  
4035 # Zero-copy ATTACH path: unconditionally available when the source
4036 # implements dbi_source() returning a live SQLite handle. Query-time
4037 # criteria for this source will go into the SQL WHERE clause.
4038 # eval wraps can() to suppress ISA warnings from stub packages in tests.
4039 379 ▶ if (do { local $@; eval { $db->can('dbi_source') } }) {
Branch: 1 branch
BranchTrueFalseTotal
if (do { local $@; eval { do { $db->can("dbi_source") } } }) 294 85 379
4040 # Probe dbi_source() in an isolated scope: local $@ prevents leaking
4041 # eval failure into the caller's $@; local $SIG{__WARN__} suppresses
4042 # spurious warnings from inherited dbi_source() probing non-SQLite DAs
4043 # (e.g. Database::Abstraction 0.46 base-class dbi_source() calling
4044 # _open() on a DA with no backing file).
4045 294 my $src = do {
4046 294 ▶ local $SIG{__WARN__} = sub {};
Subroutine __ANON__: not called CC=1 SCAR=0.0
4047 294 local $@;
4048 294 eval { $db->dbi_source() }
4049 };
4050 294 ▶ if ($src && ref($src) eq 'HASH' && $src->{dbh} && $src->{table}
Branch: 1 branch
BranchTrueFalseTotal
if ($src and ref $src eq "HASH" and $src->{"dbh"} and $src->{"table"} and eval { do { $src->{"dbh"}{"Driver"}{"Name"} } } eq "SQLite") 7 287 294
Condition66%8/12
$src and ref $src eq "HASH" and $src->{"dbh"} and $src->{"table"} and eval { do { $src->{"dbh"}{"Driver"}{"Name"} } } eq "SQLite"
!ll&&!rl&&r
28707
$src and ref $src eq "HASH" and $src->{"dbh"} and $src->{"table"}
!ll&&!rl&&r
28707
$src and ref $src eq "HASH" and $src->{"dbh"}
!ll&&!rl&&r
28707
$src and ref $src eq "HASH"
!ll&&!rl&&r
28707
MC/DC20%1/5
$src and ref $src eq "HASH" and $src->{"dbh"} and $src->{"table"} and eval { do { $src->{"dbh"}{"Driver"}{"Name"} } } eq "SQLite"
$src ref $src eq "HASH" $src->{"dbh"} $src->{"table"} eval { do { $src->{"dbh"}{"Driver"}{"Name"} } } eq "SQLite"
Truth table33%2/6
A and B and C and D and E
A= $srcB= ref $src eq "HASH"C= $src->{"dbh"}D= $src->{"table"}E= eval { do { $src->{"dbh"}{"Driver"}{"Name"} } } eq "SQLite"
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
4051 7 && eval { $src->{dbh}{Driver}{Name} } eq 'SQLite') {
4052 my ($db_file) = $src->{dbh}->selectrow_array(
4053 7 "SELECT file FROM pragma_database_list WHERE name='main'"
4054 );
4055 7 my $alias = "ext$i";
4056 7 $tmpdbh->do(sprintf("ATTACH DATABASE %s AS %s",
4057 $tmpdbh->quote($db_file), $alias));
4058 7 $table_refs[$i] = $alias . '.' . _sql_quote_identifier($src->{table});
4059 7 $is_attached[$i] = 1;
4060 # Transitive reduction: new() and add_database() both validate
4061 # can('columns') before registering any DA (P1 invariant).
4062 # The else branch is dead code; the guard is vacuous.
4063 7 $source_cols[$i] = $db->columns();
4064 7 next;
4065 }
4066 }
4067  
4068 # Spill path: fetch rows using filter-only criteria. Query-time
4069 # criteria are NOT applied here — they become WHERE clauses per call.
4070 372 ▶ my $filter_crit = $self->{_filters}{$i} // {};
Condition100%2/2
$self->{"_filters"}{$i} // {}
l!l
4368
MC/DC100%1/1
$self->{"_filters"}{$i} // {}
$self->{"_filters"}{$i}
Truth table100%2/2
A
A= $self->{"_filters"}{$i}
Aresult
11
00
4071 372 ▶ my $rows = $db->selectall_arrayref($filter_crit) // [];
Condition50%1/2
$db->selectall_arrayref($filter_crit) // []
l!l
3710
MC/DC0%0/1
$db->selectall_arrayref($filter_crit) // []
$db->selectall_arrayref($filter_crit)
Truth table50%1/2
A
A= $db->selectall_arrayref($filter_crit)
Aresult
11
00
4072  
4073 # No need to check if $rows exists or not
4074 # Transitive reduction (P1 invariant): can('columns') is guaranteed for
4075 # all _dbs elements
4076 371 $source_cols[$i] = $db->columns();
4077  
4078 371 my $tbl = "t$i";
4079 371 ▶ my $cols = $source_cols[$i] // [];
Condition50%1/2
$source_cols[$i] // []
l!l
3710
MC/DC0%0/1
$source_cols[$i] // []
$source_cols[$i]
Truth table50%1/2
A
A= $source_cols[$i]
Aresult
11
00
4080  
4081 371 my $col_defs = join(', ', map { _sql_quote_identifier($_) . ' TEXT' } @{$cols});
4082 371 $tmpdbh->do('CREATE TABLE ' . _sql_quote_identifier($tbl) . " ($col_defs)");
4083 # Index on the join column: upgrades ON-clause equality lookups from
4084 # an O(N²) full-table nested-loop scan to O(N log N) b-tree seek.
4085 # SQLite query planner uses it for INNER JOIN / LEFT JOIN ON expressions.
4086 371 $tmpdbh->do('CREATE INDEX ' . _sql_quote_identifier("${tbl}_jc")
4087 . ' ON ' . _sql_quote_identifier($tbl)
4088 . ' (' . _sql_quote_identifier($local_jc) . ')');
4089  
4090 371 ▶ if (@{$rows}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$rows;}) 366 5 371
4091 366 my $col_list = join(', ', map { _sql_quote_identifier($_) } @{$cols});
4092 366 my $placeholders = join(', ', ('?') x scalar @{$cols});
4093 366 my $sth = $tmpdbh->prepare(
4094 'INSERT INTO ' . _sql_quote_identifier($tbl) . " ($col_list) VALUES ($placeholders)"
4095 );
4096 366 my $batch = 0;
4097 366 $tmpdbh->begin_work;
4098 366 for my $row (@{$rows}) {
4099 1116 $sth->execute(map { $row->{$_} } @{$cols});
4100 1116 ▶ if (++$batch >= 1_000) {
Branch: 1 branch
BranchTrueFalseTotal
if (++$batch >= 1000) 0 1116 1116
4101 0 $tmpdbh->commit;
4102 0 $tmpdbh->begin_work;
4103 0 $batch = 0;
4104 }
4105 }
4106 366 $tmpdbh->commit;
4107 }
4108 371 $table_refs[$i] = _sql_quote_identifier($tbl);
4109 371 $is_attached[$i] = 0;
4110 }
4111  
4112 # Snapshot updated() timestamps for cache-validity checks.
4113 213 my %updated;
4114 213 for my $i (0 .. $n - 1) {
4115 377 local $@;
4116 377 my $ts = eval { $self->{_dbs}[$i]->updated() };
4117 377 ▶ $updated{$i} = $ts unless $@;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ 279 98 377
4118 }
4119  
4120 $self->{_sqlite_cache} = {
4121 213 dbh => $tmpdbh,
4122 tmpfile => $tmpfile,
4123 table_refs => \@table_refs,
4124 source_cols => \@source_cols,
4125 is_attached => \@is_attached,
4126 updated => \%updated,
4127 n => $n,
4128 };
4129  
4130 213 return;
4131 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4132  
4133 # _sqlite_join( \%params ) -> \@merged_rows
4134 #
4135 # Purpose: Join via a persistent SQLite database cache. The first call (or
4136 # any call after a source updated() changes) spills source data into
4137 # a File::Temp SQLite file via _build_sqlite_cache; subsequent calls
4138 # reuse the same file and handle. A single SQL JOIN with a per-call
4139 # WHERE clause (built from query-time criteria) produces the result.
4140 # For 'auto' mode, uses count() or dbi_source() COUNT(*) to check
4141 # the threshold without fetching rows; falls back to
4142 # _joined_query_array when count <= $self->{_max_array_rows} or when
4143 # no count method is available.
4144 # Entry: $params is the query criteria hashref.
4145 # Exit: Returns arrayref of merged hashrefs sorted by join_column.
4146 # Effects: On the first call (or after cache invalidation), creates a
4147 # File::Temp SQLite file in _tmpdir; the file persists until the
4148 # Database::Join object is destroyed or the source data changes.
4149 826 ▶sub _sqlite_join :Protected {
Subroutine _sqlite_join: called CC=64 SCAR=42.2
4150 826 my ($self, $params, %opts) = @_;
4151 826 ▶ my $count_only = $opts{count_only} // 0;
Condition100%2/2
$opts{"count_only"} // 0
l!l
73753
MC/DC100%1/1
$opts{"count_only"} // 0
$opts{"count_only"}
Truth table100%2/2
A
A= $opts{"count_only"}
Aresult
11
00
4152 826 my $sort_by = $opts{sort_by};
4153 826 my $limit = $opts{limit};
4154 826 my $offset = $opts{offset};
4155 826 my $create_table = $opts{create_table}; # when set, materialize into a real table
4156 826 my $distinct = $opts{distinct};
4157 826 my $columns = $opts{columns};
4158  
4159 # Transitive reduction: _validate_pagination is the single validation site.
4160 # count() and dbi_source() never supply limit/offset (both methods delete them
4161 # before calling _sqlite_join), so for those callers this is a cheap undef-check.
4162 826 ($limit, $offset) = $self->_validate_pagination($limit, $offset);
4163  
4164 826 my $backend = $self->{_backend};
4165 826 my $join_col = $self->{_join_col};
4166 826 my $join_type = $self->{_join_type};
4167 826 my $n = scalar @{ $self->{_dbs} };
4168  
4169 826 my ($per_db_query, $per_db_full, $had_criteria) = $self->_sqlite_criteria($params);
4170  
4171 # For 'auto' mode: check total row count without fetching rows.
4172 # Count(*) is used for dbi_source() sources; count() for others.
4173 # If any source supports neither, fall back to the array path.
4174 # Skipped when create_table is set — dbi_source() has already committed to
4175 # the SQLite path and we must materialise regardless of row count.
4176 826 ▶ if ($backend eq 'auto' && !defined $create_table) {
Branch: 1 branch
BranchTrueFalseTotal
if ($backend eq "auto" and not defined $create_table) 606 220 826
Condition100%3/3
$backend eq "auto" and not defined $create_table
!ll&&!rl&&r
2173606
MC/DC100%2/2
$backend eq "auto" and not defined $create_table
$backend eq "auto" not defined $create_table
Truth table100%3/3
A and not(B)
A= $backend eq "auto"B= not defined $create_table
ABresult
0X0
100
111
4177 606 my $total = 0;
4178 606 my $can_count = 1;
4179 606 for my $i (0 .. $n - 1) {
4180 741 my $db = $self->{_dbs}[$i];
4181 # dbi_source() path: COUNT(*) against the entire source table
4182 # (no WHERE) gives a conservative upper bound on the spilled size.
4183 741 ▶ if (do { local $@; eval { $db->can('dbi_source') } }) {
Branch: 1 branch
BranchTrueFalseTotal
if (do { local $@; eval { do { $db->can("dbi_source") } } }) 558 183 741
4184 558 my $src = do {
4185 558 ▶ local $SIG{__WARN__} = sub {};
Subroutine __ANON__: not called CC=1 SCAR=0.0
4186 558 local $@;
4187 558 eval { $db->dbi_source() }
4188 };
4189 558 ▶ if ($src && ref($src) eq 'HASH' && $src->{dbh} && $src->{table}
Branch: 1 branch
BranchTrueFalseTotal
if ($src and ref $src eq "HASH" and $src->{"dbh"} and $src->{"table"} and eval { do { $src->{"dbh"}{"Driver"}{"Name"} } } eq "SQLite") 238 320 558
Condition66%8/12
$src and ref $src eq "HASH" and $src->{"dbh"} and $src->{"table"} and eval { do { $src->{"dbh"}{"Driver"}{"Name"} } } eq "SQLite"
!ll&&!rl&&r
3200238
$src and ref $src eq "HASH" and $src->{"dbh"} and $src->{"table"}
!ll&&!rl&&r
3200238
$src and ref $src eq "HASH" and $src->{"dbh"}
!ll&&!rl&&r
3200238
$src and ref $src eq "HASH"
!ll&&!rl&&r
3200238
MC/DC20%1/5
$src and ref $src eq "HASH" and $src->{"dbh"} and $src->{"table"} and eval { do { $src->{"dbh"}{"Driver"}{"Name"} } } eq "SQLite"
$src ref $src eq "HASH" $src->{"dbh"} $src->{"table"} eval { do { $src->{"dbh"}{"Driver"}{"Name"} } } eq "SQLite"
Truth table33%2/6
A and B and C and D and E
A= $srcB= ref $src eq "HASH"C= $src->{"dbh"}D= $src->{"table"}E= eval { do { $src->{"dbh"}{"Driver"}{"Name"} } } eq "SQLite"
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
4190 238 && eval { $src->{dbh}{Driver}{Name} } eq 'SQLite') {
4191 my ($cnt) = $src->{dbh}->selectrow_array(
4192 'SELECT COUNT(*) FROM '
4193 . _sql_quote_identifier($src->{table})
4194 238 );
4195 238 ▶ $total += $cnt // 0;
Condition50%1/2
$cnt // 0
l!l
2380
MC/DC0%0/1
$cnt // 0
$cnt
Truth table50%1/2
A
A= $cnt
Aresult
11
00
4196 238 next;
4197 }
4198 }
4199 # count() path: only use it when the DA's own class directly defines
4200 # count() (not inherited). Database::Abstraction's inherited count($entry)
4201 # takes a key argument and emits uninitialized-value warnings when called
4202 # with no args, so we must not invoke it for the threshold probe.
4203 503 ▶ my $pkg = ref($db) // '';
Condition50%1/2
ref $db // ""
l!l
5030
MC/DC0%0/1
ref $db // ""
ref $db
Truth table50%1/2
A
A= ref $db
Aresult
11
00
4204 29 ▶ if ($pkg && do { no strict 'refs'; defined &{"${pkg}::count"} }) {
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if ($pkg and do { no strict 'refs'; defined &{"${pkg}::count";} }) 27 476 503
Condition66%2/3
$pkg and do { no strict 'refs'; defined &{"${pkg}::count";} }
!ll&&!rl&&r
047627
MC/DC50%1/2
$pkg and do { no strict 'refs'; defined &{"${pkg}::count";} }
$pkg do { no strict 'refs'; defined &{"${pkg}::count";} }
Truth table66%2/3
A and B
A= $pkgB= do { no strict 'refs'; defined &{"${pkg}::count";} }
ABresult
0X0
100
111
4205 27 my ($cnt, $failed);
4206 27 do { local $@; $cnt = eval { $db->count() }; $failed = $@ };
4207 27 ▶ if ($failed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($failed) 0 27 27
4208 0 $can_count = 0;
4209 0 last;
4210 }
4211 27 ▶ $total += $cnt // 0;
Condition50%1/2
$cnt // 0
l!l
270
MC/DC0%0/1
$cnt // 0
$cnt
Truth table50%1/2
A
A= $cnt
Aresult
11
00
4212 27 next;
4213 }
4214 476 $can_count = 0;
4215 476 last;
4216 }
4217 606 ▶ if (!$can_count || $total <= $self->{_max_array_rows}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $can_count or $total <= $self->{"_max_array_rows"}) 597 9 606
Condition100%3/3
not $can_count or $total <= $self->{"_max_array_rows"}
l!l&&r!l&&!r
4761219
MC/DC100%2/2
not $can_count or $total <= $self->{"_max_array_rows"}
not $can_count $total <= $self->{"_max_array_rows"}
Truth table100%3/3
not(A) or B
A= not $can_countB= $total <= $self->{"_max_array_rows"}
ABresult
1X1
011
000
4218 597 my $rows = $self->_joined_query_array($params,
4219 sort_by => $sort_by, limit => $limit, offset => $offset);
4220 591 ▶ return $count_only ? scalar @{$rows} : $rows;
Branch: 1 branch
BranchTrueFalseTotal
$count_only ? : 62 529 591
4221 }
4222 }
4223  
4224 # Ensure the SQLite cache is valid; rebuild if stale or absent.
4225 229 ▶ $self->_build_sqlite_cache() unless $self->_cache_fresh();
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_cache_fresh 180 49 229
4226  
4227 217 my $cache = $self->{_sqlite_cache};
4228 217 my $tmpdbh = $cache->{dbh};
4229 217 my @table_refs = @{ $cache->{table_refs} };
4230 217 my @source_cols = @{ $cache->{source_cols} };
4231 217 my @is_attached = @{ $cache->{is_attached} };
4232  
4233 217 my ($where_sql, $bind_vals_ref) = $self->_sqlite_where(
4234 $per_db_query, $per_db_full, \@table_refs, \@is_attached);
4235 217 my @bind_vals = @{$bind_vals_ref};
4236  
4237 217 ▶ my $local_jc_0 = $self->{_join_map}{0} // $join_col;
Condition33%1/3
$self->{"_join_map"}{0} // $join_col
l!l&&r!l&&!r
02170
MC/DC0%0/2
$self->{"_join_map"}{0} // $join_col
$self->{"_join_map"}{0} $join_col
Truth table33%1/3
A // B
A= $self->{"_join_map"}{0}B= $join_col
ABresult
1X1
011
000
4238  
4239 # Build JOIN clauses. Hoisted before the SELECT list so the count_only
4240 # path can return early without building the (unused) column expressions.
4241 217 my $from = $table_refs[0];
4242 217 my $join_sql = $self->_sqlite_join_clause(\@table_refs, $had_criteria, $local_jc_0);
4243  
4244 # COUNT(*) short-circuit: WHERE and JOIN are built; SELECT list and ORDER BY
4245 # are not needed. selectrow_array returns a single integer without fetching rows.
4246 217 ▶ if ($count_only) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count_only) 11 206 217
4247 11 my ($cnt) = $tmpdbh->selectrow_array(
4248 'SELECT COUNT(*) FROM ' . $from . $join_sql . $where_sql,
4249 undef,
4250 @bind_vals,
4251 );
4252 11 ▶ return $cnt // 0;
Condition50%1/2
$cnt // 0
l!l
110
MC/DC0%0/1
$cnt // 0
$cnt
Truth table50%1/2
A
A= $cnt
Aresult
11
00
4253 }
4254  
4255 # Build SELECT clause.
4256 # Walk sources in order, applying collision_prefix renaming exactly as
4257 # _build_col_index does: first occurrence of a column name wins; subsequent
4258 # occurrences in a source that has a collision_prefix are published as
4259 # "$prefix.$col"; removed columns are omitted.
4260 206 my %pub_seen;
4261 my @selects;
4262 206 my @select_pubs; # parallel to @selects: published column name for each expression
4263  
4264 # Join-column expression: for outer joins, use COALESCE across all sources
4265 # so that B-only (primary-absent) rows carry their join key rather than NULL.
4266 206 ▶ unless ($self->{_removed_cols}{$join_col}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_removed_cols"}{$join_col}) 206 0 206
4267 206 my $jc_expr;
4268 206 ▶ if ($join_type eq 'outer' && $n > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($join_type eq 'outer' and $n > 1) { } 3 203 206
Condition66%2/3
$join_type eq "outer" and $n > 1
!ll&&!rl&&r
20303
MC/DC50%1/2
$join_type eq "outer" and $n > 1
$join_type eq "outer" $n > 1
Truth table66%2/3
A and B
A= $join_type eq "outer"B= $n > 1
ABresult
0X0
100
111
4269 $jc_expr = 'COALESCE('
4270 . join(', ', map {
4271 3 ▶ my $lc = $self->{_join_map}{$_} // $join_col;
Condition33%1/3
$self->{"_join_map"}{$_} // $join_col
l!l&&r!l&&!r
060
MC/DC0%0/2
$self->{"_join_map"}{$_} // $join_col
$self->{"_join_map"}{$_} $join_col
Truth table33%1/3
A // B
A= $self->{"_join_map"}{$_}B= $join_col
ABresult
1X1
011
000
4272 6 $table_refs[$_] . '.' . _sql_quote_identifier($lc)
4273 } 0 .. $n - 1)
4274 . ') AS ' . _sql_quote_identifier($join_col);
4275 } else {
4276 203 $jc_expr = $table_refs[0] . '.' . _sql_quote_identifier($local_jc_0);
4277 203 ▶ $jc_expr .= ' AS ' . _sql_quote_identifier($join_col) if $local_jc_0 ne $join_col;
Branch: 1 branch
BranchTrueFalseTotal
if $local_jc_0 ne $join_col 0 203 203
4278 }
4279 206 push @selects, $jc_expr;
4280 206 push @select_pubs, $join_col;
4281 206 $pub_seen{$join_col} = 1;
4282 }
4283  
4284 # Non-join columns from the primary table.
4285 206 ▶ for my $col (@{$source_cols[0] // []}) {
Condition50%1/2
$source_cols[0] // []
l!l
2060
MC/DC0%0/1
$source_cols[0] // []
$source_cols[0]
Truth table50%1/2
A
A= $source_cols[0]
Aresult
11
00
4286 515 ▶ next if $col eq $local_jc_0; # join column already handled above
Branch: 1 branch
BranchTrueFalseTotal
if $col eq $local_jc_0 206 309 515
4287 309 ▶ next if $self->{_removed_cols}{$col};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_removed_cols"}{$col} 0 309 309
4288 309 $pub_seen{$col} = 1;
4289 309 push @selects, $table_refs[0] . '.' . _sql_quote_identifier($col);
4290 309 push @select_pubs, $col;
4291 }
4292  
4293 # Non-join columns from secondary tables, with collision_prefix renaming.
4294 206 for my $i (1 .. $n - 1) {
4295 153 ▶ my $local_jc = $self->{_join_map}{$i} // $join_col;
Condition66%2/3
$self->{"_join_map"}{$i} // $join_col
l!l&&r!l&&!r
21510
MC/DC0%0/2
$self->{"_join_map"}{$i} // $join_col
$self->{"_join_map"}{$i} $join_col
Truth table66%2/3
A // B
A= $self->{"_join_map"}{$i}B= $join_col
ABresult
1X1
011
000
4296 153 my $prefix = $self->{_collision_prefix}{$i};
4297 153 ▶ for my $col (@{$source_cols[$i] // []}) {
Condition50%1/2
$source_cols[$i] // []
l!l
1530
MC/DC0%0/1
$source_cols[$i] // []
$source_cols[$i]
Truth table50%1/2
A
A= $source_cols[$i]
Aresult
11
00
4298 308 ▶ next if $col eq $local_jc; # join key already contributed above
Branch: 1 branch
BranchTrueFalseTotal
if $col eq $local_jc 153 155 308
4299 155 my $pub = $col;
4300 $pub = "$prefix.$col"
4301 155 ▶ if defined $prefix && exists $pub_seen{$col} && $col ne $join_col;
Branch: 1 branch
BranchTrueFalseTotal
if defined $prefix and exists $pub_seen{$col} and $col ne $join_col 2 153 155
Condition83%5/6
defined $prefix and exists $pub_seen{$col} and $col ne $join_col
!ll&&!rl&&r
15302
defined $prefix and exists $pub_seen{$col}
!ll&&!rl&&r
15122
MC/DC66%2/3
defined $prefix and exists $pub_seen{$col} and $col ne $join_col
defined $prefix exists $pub_seen{$col} $col ne $join_col
Truth table75%3/4
A and B and C
A= defined $prefixB= exists $pub_seen{$col}C= $col ne $join_col
ABCresult
0XX0
10X0
1100
1111
4302 155 ▶ next if $self->{_removed_cols}{$pub};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_removed_cols"}{$pub} 0 155 155
4303 155 $pub_seen{$pub} = 1;
4304 155 my $expr = $table_refs[$i] . '.' . _sql_quote_identifier($col);
4305 155 ▶ $expr .= ' AS ' . _sql_quote_identifier($pub) if $pub ne $col;
Branch: 1 branch
BranchTrueFalseTotal
if $pub ne $col 2 153 155
4306 155 push @selects, $expr;
4307 155 push @select_pubs, $pub;
4308 }
4309 }
4310  
4311 # distinct + column projection: filter SELECT list to requested columns only.
4312 # When both distinct and columns are specified, project to those columns and
4313 # apply DISTINCT so the SQL engine deduplicates before returning rows.
4314 # Without columns, DISTINCT applies to all selected columns.
4315 206 ▶ if ($distinct && $columns && @{$columns}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distinct and $columns and @{$columns;}) 2 204 206
Condition83%5/6
$distinct and $columns and @{$columns;}
!ll&&!rl&&r
20402
$distinct and $columns
!ll&&!rl&&r
20312
MC/DC66%2/3
$distinct and $columns and @{$columns;}
$distinct $columns @{$columns;}
Truth table75%3/4
A and B and C
A= $distinctB= $columnsC= @{$columns;}
ABCresult
0XX0
10X0
1100
1111
4316 2 my %want = map { $_ => 1 } @{$columns};
4317 2 my @filtered;
4318 2 for my $j (0 .. $#selects) {
4319 8 ▶ push @filtered, $selects[$j] if $want{ $select_pubs[$j] };
Branch: 1 branch
BranchTrueFalseTotal
if $want{$select_pubs[$j]} 2 6 8
4320 }
4321 2 @selects = @filtered;
4322 }
4323  
4324 # dbi_source() materialisation path: CREATE TABLE name AS SELECT ...
4325 # Executed BEFORE ORDER BY / LIMIT / OFFSET because they are irrelevant here —
4326 # the parent join will impose its own ordering and pagination per-call.
4327 # _sql_quote_identifier guards against any injection via the table name.
4328 # D~: $sort_by, $limit, $offset are dead stores on this path. They were
4329 # parsed and validated above (shared with the normal query path) but the
4330 # caller of create_table always passes undef for these, so _validate_pagination
4331 # is a no-op and the variables are harmlessly abandoned at this return.
4332 206 ▶ if (defined $create_table) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $create_table) 16 190 206
4333 16 my $mat_sql = 'SELECT ' . join(', ', @selects)
4334 . ' FROM ' . $from . $join_sql . $where_sql;
4335 16 $tmpdbh->do('DROP TABLE IF EXISTS ' . _sql_quote_identifier($create_table));
4336 16 $tmpdbh->do('CREATE TABLE ' . _sql_quote_identifier($create_table)
4337 . ' AS ' . $mat_sql,
4338 undef, @bind_vals);
4339 16 return;
4340 }
4341  
4342 # ORDER BY: default is join_column ascending. Caller may override via
4343 # sort_by => 'col' or sort_by => ['col', 'DESC'].
4344 # For the join column on an outer join, reference the COALESCE alias.
4345 # For any other column, reference the published SELECT-list alias —
4346 # SQLite resolves ORDER BY aliases from the SELECT clause.
4347 190 my ($ob_col, $ob_dir) = ($join_col, 'ASC');
4348 190 ▶ if (defined $sort_by) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_by) 18 172 190
4349 18 ▶ my ($req_col, $req_dir) = ref($sort_by) eq 'ARRAY' ? @{$sort_by} : ($sort_by, 'ASC');
Branch: 1 branch
BranchTrueFalseTotal
ref $sort_by eq 'ARRAY' ? : 8 10 18
4350 18 ▶ $req_dir = uc($req_dir // 'ASC');
Condition50%1/2
$req_dir // "ASC"
l!l
180
MC/DC0%0/1
$req_dir // "ASC"
$req_dir
Truth table50%1/2
A
A= $req_dir
Aresult
11
00
4351 18 ▶ unless ($req_dir eq 'ASC' || $req_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($req_dir eq "ASC" or $req_dir eq "DESC") 2 16 18
Condition100%3/3
$req_dir eq "ASC" or $req_dir eq "DESC"
l!l&&r!l&&!r
1062
MC/DC100%2/2
$req_dir eq "ASC" or $req_dir eq "DESC"
$req_dir eq "ASC" $req_dir eq "DESC"
Truth table100%3/3
A or B
A= $req_dir eq "ASC"B= $req_dir eq "DESC"
ABresult
1X1
011
000
4352 2 carp "Database::Join: sort_by direction '$req_dir' is not supported; using ASC";
4353 2 $req_dir = 'ASC';
4354 }
4355 18 ▶ if ($req_col ne $join_col && !exists $self->{_col_db}{$req_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req_col ne $join_col and not exists $self->{'_col_db'}{$req_col}) { } 2 16 18
Condition100%3/3
$req_col ne $join_col and not exists $self->{"_col_db"}{$req_col}
!ll&&!rl&&r
2142
MC/DC100%2/2
$req_col ne $join_col and not exists $self->{"_col_db"}{$req_col}
$req_col ne $join_col not exists $self->{"_col_db"}{$req_col}
Truth table100%3/3
A and not(B)
A= $req_col ne $join_colB= not exists $self->{"_col_db"}{$req_col}
ABresult
0X0
100
111
4356 2 carp "Database::Join: sort_by column '$req_col' is not in the merged view; result sorted by join_column";
4357 } else {
4358 16 ($ob_col, $ob_dir) = ($req_col, $req_dir);
4359 }
4360 }
4361 190 ▶ my $order_expr = ($ob_col eq $join_col)
Branch: 2 branches
BranchTrueFalseTotal
$ob_col eq $join_col ? : 176 14 190
$join_type eq 'outer' && $n > 1 ? : 3 173 176
Condition66%2/3
$join_type eq "outer" and $n > 1
!ll&&!rl&&r
17303
MC/DC50%1/2
$join_type eq "outer" and $n > 1
$join_type eq "outer" $n > 1
Truth table66%2/3
A and B
A= $join_type eq "outer"B= $n > 1
ABresult
0X0
100
111
4362 ? (($join_type eq 'outer' && $n > 1)
4363 ? _sql_quote_identifier($join_col)
4364 : $table_refs[0] . '.' . _sql_quote_identifier($local_jc_0))
4365 : _sql_quote_identifier($ob_col);
4366 190 ▶ my $select_kw = $distinct ? 'SELECT DISTINCT' : 'SELECT';
Branch: 1 branch
BranchTrueFalseTotal
$distinct ? : 3 187 190
4367 190 ▶ my $sql = $select_kw . ' '
Branch: 1 branch
BranchTrueFalseTotal
$ob_dir eq 'DESC' ? : 6 184 190
4368 . join(', ', @selects)
4369 . ' FROM ' . $from . $join_sql
4370 . $where_sql
4371 . ' ORDER BY ' . $order_expr . ($ob_dir eq 'DESC' ? ' DESC' : '');
4372  
4373 # LIMIT / OFFSET pagination — appended after ORDER BY as bind parameters
4374 # (never interpolated) to prevent any SQL injection from caller values.
4375 # OFFSET without LIMIT uses LIMIT -1 (SQLite extension: "all rows from offset").
4376 190 my @page_bind;
4377 190 ▶ if (defined $limit) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $limit) { } 11 179 190
elsif (defined $offset) { } 3 176 179
4378 11 $sql .= ' LIMIT ?';
4379 11 push @page_bind, $limit;
4380 11 ▶ if (defined $offset) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 6 5 11
4381 6 $sql .= ' OFFSET ?';
4382 6 push @page_bind, $offset;
4383 }
4384 } elsif (defined $offset) {
4385 3 $sql .= ' LIMIT -1 OFFSET ?';
4386 3 push @page_bind, $offset;
4387 }
4388  
4389 # prepare_cached reuses the parsed statement when the same SQL is executed
4390 # again (e.g. identical criteria pattern in a pagination or batch loop),
4391 # avoiding repeated statement compilation overhead. fetchall_arrayref
4392 # always exhausts the result set, so the handle is never left active.
4393 190 my $sth = $tmpdbh->prepare_cached($sql);
4394 190 $sth->execute(@bind_vals, @page_bind);
4395 190 return $sth->fetchall_arrayref({});
4396 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4397  
4398 # _sqlite_criteria( \%params ) -> ( $per_db_query, \@per_db_full, \@had_criteria )
4399 # Purpose: Partition query-time criteria and overlay per-db filters.
4400 # Extracted from _sqlite_join so _sqlite_aggregate can reuse the same logic.
4401 863 ▶sub _sqlite_criteria :Protected {
Subroutine _sqlite_criteria: called CC=12 SCAR=25.0
4402 863 my ($self, $params) = @_;
4403 863 my $join_col = $self->{_join_col};
4404 863 my $n = scalar @{ $self->{_dbs} };
4405  
4406 863 my $per_db_query = $self->_partition_criteria($params);
4407  
4408 # Inject mandatory_filters into per_db_query BEFORE building per_db_full.
4409 # Injecting here ensures they are present in:
4410 # - per_db_query (used by _sqlite_where for non-attached/spilled sources)
4411 # - per_db_full (built below by merging base_filter + per_db_query, so
4412 # mandatory criteria flow through automatically for attached sources)
4413 # Mandatory wins over any caller-supplied value for the same column: the
4414 # assignment overwrites any prior value in that slot.
4415 863 ▶ if (my $mf = $self->{_mandatory_filters}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $mf = $self->{"_mandatory_filters"}) 863 0 863
4416 863 for my $pred (@{$mf}) {
4417 3 my ($col, $op, $val) = @{$pred}{qw(col op val)};
4418 3 ▶ my $db_idx = $self->{_col_db}{$col} // next;
Condition50%1/2
$self->{"_col_db"}{$col} // (next)
l!l
30
MC/DC0%0/1
$self->{"_col_db"}{$col} // (next)
$self->{"_col_db"}{$col}
Truth table50%1/2
A
A= $self->{"_col_db"}{$col}
Aresult
11
00
4419 3 ▶ my $orig = $self->{_col_unrename}[$db_idx]{$col} // $col;
Condition33%1/3
$self->{"_col_unrename"}[$db_idx]{$col} // $col
l!l&&r!l&&!r
030
MC/DC0%0/2
$self->{"_col_unrename"}[$db_idx]{$col} // $col
$self->{"_col_unrename"}[$db_idx]{$col} $col
Truth table33%1/3
A // B
A= $self->{"_col_unrename"}[$db_idx]{$col}B= $col
ABresult
1X1
011
000
4420 3 $per_db_query->[$db_idx]{$orig} = _mandatory_op_to_crit($op, $val);
4421 }
4422 }
4423  
4424 863 my @per_db_full;
4425 863 for my $i (0 .. $n - 1) {
4426 1619 ▶ my $base = $self->{_filters}{$i} // {};
Condition100%2/2
$self->{"_filters"}{$i} // {}
l!l
1001519
MC/DC100%1/1
$self->{"_filters"}{$i} // {}
$self->{"_filters"}{$i}
Truth table100%2/2
A
A= $self->{"_filters"}{$i}
Aresult
11
00
4427 1619 ▶ $per_db_full[$i] = %{$base}
Branch: 1 branch
BranchTrueFalseTotal
%{$base;} ? : 95 1524 1619
4428 ? _merge_criteria($base, $per_db_query->[$i])
4429 : $per_db_query->[$i];
4430 }
4431  
4432 863 my @had_criteria;
4433 863 for my $i (1 .. $n - 1) {
4434 756 ▶ my $local_jc = $self->{_join_map}{$i} // $join_col;
Condition66%2/3
$self->{"_join_map"}{$i} // $join_col
l!l&&r!l&&!r
626940
MC/DC0%0/2
$self->{"_join_map"}{$i} // $join_col
$self->{"_join_map"}{$i} $join_col
Truth table66%2/3
A // B
A= $self->{"_join_map"}{$i}B= $join_col
ABresult
1X1
011
000
4435 756 ▶ my $has_filter = !!%{ $self->{_filters}{$i} // {} };
Condition100%2/2
$self->{"_filters"}{$i} // {}
l!l
68688
MC/DC100%1/1
$self->{"_filters"}{$i} // {}
$self->{"_filters"}{$i}
Truth table100%2/2
A
A= $self->{"_filters"}{$i}
Aresult
11
00
4436 756 my %q = %{ $per_db_query->[$i] };
4437 756 delete $q{$local_jc};
4438 756 ▶ $had_criteria[$i] = $has_filter || !!%q;
Condition100%3/3
$has_filter || !!%q
l!l&&r!l&&!r
6660630
MC/DC100%2/2
$has_filter || !!%q
$has_filter !!%q
Truth table100%3/3
A || B
A= $has_filterB= !!%q
ABresult
1X1
011
000
4439 }
4440  
4441 863 return ($per_db_query, \@per_db_full, \@had_criteria);
4442 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4443  
4444 # _sqlite_where( $per_db_query, \@per_db_full, \@table_refs, \@is_attached )
4445 # -> ( $where_sql, \@bind_vals )
4446 # Purpose: Build the WHERE clause and bind-value list from per-call criteria.
4447 # Extracted from _sqlite_join for reuse by _sqlite_aggregate.
4448 254 ▶sub _sqlite_where :Protected {
Subroutine _sqlite_where: called CC=19 SCAR=29.4
4449 254 my ($self, $per_db_query, $per_db_full, $table_refs, $is_attached) = @_;
4450 254 my $join_col = $self->{_join_col};
4451 254 my $n = scalar @{ $self->{_dbs} };
4452  
4453 254 my (@where_parts, @bind_vals);
4454 254 for my $i (0 .. $n - 1) {
4455 455 ▶ my $crit = $is_attached->[$i] ? $per_db_full->[$i] : $per_db_query->[$i];
Branch: 1 branch
BranchTrueFalseTotal
$is_attached->[$i] ? : 7 448 455
4456 455 ▶ next unless %{$crit};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$crit;} 372 83 455
4457 83 my $tref = $table_refs->[$i];
4458 83 ▶ my $local_jc_i = $i > 0 ? ($self->{_join_map}{$i} // $join_col) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$i > 0 ? : 27 56 83
Condition66%2/3
$self->{"_join_map"}{$i} // $join_col
l!l&&r!l&&!r
1260
MC/DC0%0/2
$self->{"_join_map"}{$i} // $join_col
$self->{"_join_map"}{$i} $join_col
Truth table66%2/3
A // B
A= $self->{"_join_map"}{$i}B= $join_col
ABresult
1X1
011
000
4459 83 for my $col (sort keys %{$crit}) {
4460 84 ▶ next if defined $local_jc_i && $col eq $local_jc_i;
Branch: 1 branch
BranchTrueFalseTotal
if defined $local_jc_i and $col eq $local_jc_i 8 76 84
Condition100%3/3
defined $local_jc_i and $col eq $local_jc_i
!ll&&!rl&&r
57198
MC/DC100%2/2
defined $local_jc_i and $col eq $local_jc_i
defined $local_jc_i $col eq $local_jc_i
Truth table100%3/3
A and B
A= defined $local_jc_iB= $col eq $local_jc_i
ABresult
0X0
100
111
4461 76 my $val = $crit->{$col};
4462 76 ▶ if (ref($val) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $val eq 'HASH') { } 50 26 76
elsif (not defined $val) { } 2 24 26
4463 50 for my $op (sort keys %{$val}) {
4464 51 ▶ if ($SAFE_LIST_OPS{$op}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($SAFE_LIST_OPS{$op}) 22 29 51
4465 22 my $arr = $val->{$op};
4466 22 ▶ unless (ref($arr) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $arr eq "ARRAY") 4 18 22
4467 4 carp "Database::Join: operator '$op' requires an arrayref value; criterion skipped";
4468 4 next;
4469 }
4470 18 my @items = @{$arr};
4471 18 ▶ if (!@items) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@items) 7 11 18
4472 7 ▶ push @where_parts, '1 = 0' if $op eq 'IN';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "IN" 4 3 7
4473 7 next;
4474 }
4475 11 push @where_parts,
4476 $tref . '.' . _sql_quote_identifier($col)
4477 . " $op (" . join(', ', ('?') x scalar @items) . ')';
4478 11 push @bind_vals, @items;
4479 11 next;
4480 }
4481 29 ▶ if ($SAFE_NOARG_OPS{$op}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($SAFE_NOARG_OPS{$op}) 8 21 29
4482 8 push @where_parts,
4483 $tref . '.' . _sql_quote_identifier($col) . " $op";
4484 8 next;
4485 }
4486 21 ▶ unless ($SAFE_SQL_OPS{$op}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($SAFE_SQL_OPS{$op}) 5 16 21
4487 5 carp "Database::Join: operator '$op' is not supported on the SQLite backend; criterion skipped (use the array backend or a supported operator)";
4488 5 next;
4489 }
4490 16 push @where_parts,
4491 $tref . '.' . _sql_quote_identifier($col) . " $op ?";
4492 16 push @bind_vals, $val->{$op};
4493 }
4494 } elsif (!defined $val) {
4495 2 push @where_parts,
4496 $tref . '.' . _sql_quote_identifier($col) . ' IS NULL';
4497 } else {
4498 24 push @where_parts,
4499 $tref . '.' . _sql_quote_identifier($col) . ' = ?';
4500 24 push @bind_vals, $val;
4501 }
4502 }
4503 }
4504 254 ▶ my $where_sql = @where_parts ? ' WHERE ' . join(' AND ', @where_parts) : '';
Branch: 1 branch
BranchTrueFalseTotal
@where_parts ? : 63 191 254
4505 254 return ($where_sql, \@bind_vals);
4506 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4507  
4508 # _sqlite_join_clause( \@table_refs, \@had_criteria, $local_jc_0 ) -> $join_sql
4509 # Purpose: Build the JOIN … ON … clause string.
4510 # Extracted from _sqlite_join for reuse by _sqlite_aggregate.
4511 254 ▶sub _sqlite_join_clause :Protected {
Subroutine _sqlite_join_clause: called CC=6 SCAR=17.9
4512 254 my ($self, $table_refs, $had_criteria, $local_jc_0) = @_;
4513 254 my $join_col = $self->{_join_col};
4514 254 my $join_type = $self->{_join_type};
4515 254 my $n = scalar @{ $self->{_dbs} };
4516  
4517 254 my $join_sql = '';
4518 254 for my $i (1 .. $n - 1) {
4519 201 ▶ my $local_jc = $self->{_join_map}{$i} // $join_col;
Condition66%2/3
$self->{"_join_map"}{$i} // $join_col
l!l&&r!l&&!r
31980
MC/DC0%0/2
$self->{"_join_map"}{$i} // $join_col
$self->{"_join_map"}{$i} $join_col
Truth table66%2/3
A // B
A= $self->{"_join_map"}{$i}B= $join_col
ABresult
1X1
011
000
4520 201 ▶ my $join_kw = ($had_criteria->[$i] || $join_type eq 'inner') ? 'JOIN'
Branch: 2 branches
BranchTrueFalseTotal
$had_criteria->[$i] || $join_type eq 'inner' ? : 43 158 201
$join_type eq 'outer' ? : 3 155 158
Condition100%3/3
$had_criteria->[$i] or $join_type eq "inner"
l!l&&r!l&&!r
2320158
MC/DC100%2/2
$had_criteria->[$i] or $join_type eq "inner"
$had_criteria->[$i] $join_type eq "inner"
Truth table100%3/3
A or B
A= $had_criteria->[$i]B= $join_type eq "inner"
ABresult
1X1
011
000
4521 : ($join_type eq 'outer') ? 'FULL OUTER JOIN'
4522 : 'LEFT JOIN';
4523 201 $join_sql .= " $join_kw $table_refs->[$i]"
4524 . ' ON ' . $table_refs->[0] . '.' . _sql_quote_identifier($local_jc_0)
4525 . ' = ' . $table_refs->[$i] . '.' . _sql_quote_identifier($local_jc);
4526 }
4527 254 return $join_sql;
4528 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4529  
4530 # _validate_having( \%having, \%valid_keys )
4531 # Purpose: Recursively validate a having hashref; croak on unknown keys or operators.
4532 # Entry: $having is the caller's having hashref; $valid_keys maps allowed keys to 1.
4533 # Effects: Croaks on first violation; returns normally when the spec is clean.
4534 30 ▶sub _validate_having :Protected {
Subroutine _validate_having: called CC=12 SCAR=24.9
4535 30 my ($self, $having, $valid_keys) = @_;
4536 30 for my $key (keys %{$having}) {
4537 30 ▶ if ($key eq '-or' || $key eq '-and') {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq "-or" or $key eq "-and") 4 26 30
Condition100%3/3
$key eq "-or" or $key eq "-and"
l!l&&r!l&&!r
2226
MC/DC100%2/2
$key eq "-or" or $key eq "-and"
$key eq "-or" $key eq "-and"
Truth table100%3/3
A or B
A= $key eq "-or"B= $key eq "-and"
ABresult
1X1
011
000
4538 4 my $list = $having->{$key};
4539 4 ▶ croak $self->_err('error_aggregate_having_key', $key)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" 0 4 4
4540 unless ref($list) eq 'ARRAY';
4541 4 for my $sub (@{$list}) {
4542 8 $self->_validate_having($sub, $valid_keys);
4543 }
4544 4 next;
4545 }
4546 croak $self->_err('error_aggregate_having_key', $key)
4547 26 ▶ unless exists $valid_keys->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $valid_keys->{$key} 2 24 26
4548 24 my $val = $having->{$key};
4549 24 ▶ if (ref($val) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq "HASH") 20 4 24
4550 20 for my $op (keys %{$val}) {
4551 20 ▶ unless ($SAFE_SQL_OPS{$op} || $SAFE_LIST_OPS{$op} || $SAFE_NOARG_OPS{$op}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($SAFE_SQL_OPS{$op} or $SAFE_LIST_OPS{$op} or $SAFE_NOARG_OPS{$op}) 2 18 20
Condition83%5/6
$SAFE_SQL_OPS{$op} or $SAFE_LIST_OPS{$op} or $SAFE_NOARG_OPS{$op}
l!l&&r!l&&!r
1802
$SAFE_SQL_OPS{$op} or $SAFE_LIST_OPS{$op}
l!l&&r!l&&!r
1262
MC/DC66%2/3
$SAFE_SQL_OPS{$op} or $SAFE_LIST_OPS{$op} or $SAFE_NOARG_OPS{$op}
$SAFE_SQL_OPS{$op} $SAFE_LIST_OPS{$op} $SAFE_NOARG_OPS{$op}
Truth table75%3/4
A or B or C
A= $SAFE_SQL_OPS{$op}B= $SAFE_LIST_OPS{$op}C= $SAFE_NOARG_OPS{$op}
ABCresult
1XX1
01X1
0011
0000
4552 2 croak $self->_err('error_aggregate_having_operator', $op, $key);
4553 }
4554 }
4555 }
4556 }
4557 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4558  
4559 # _validate_aggregate_spec( \%params ) -> \%spec
4560 # Purpose: Extract and validate aggregate-specific keys from %params, leaving
4561 # criteria keys in place for _partition_criteria to route.
4562 # Entry: $params is the raw caller hashref (mutated: aggregate keys deleted).
4563 # Exit: Returns a spec hashref:
4564 # by => [ { name, owner, db_col }, ... ]
4565 # measures => [ { fn, col, as, owner, db_col, is_numeric }, ... ]
4566 # aliases => { alias => 1, ... }
4567 # having => \%having or undef
4568 # sort => [ col, dir ] or undef
4569 # limit => positive int or undef
4570 # offset => non-neg int or undef
4571 102 ▶sub _validate_aggregate_spec :Protected {
Subroutine _validate_aggregate_spec: called CC=52 SCAR=40.6
4572 102 my ($self, $params) = @_;
4573  
4574 102 my $join_col = $self->{_join_col};
4575 102 my $n = scalar @{ $self->{_dbs} };
4576  
4577 102 my $by_raw = delete $params->{by};
4578 102 my $measures_raw = delete $params->{measures};
4579 102 my $having_raw = delete $params->{having};
4580 102 my $sort_by_raw = delete $params->{sort_by};
4581 102 my $limit_raw = delete $params->{limit};
4582 102 my $offset_raw = delete $params->{offset};
4583  
4584 102 my ($limit, $offset) = $self->_validate_pagination($limit_raw, $offset_raw);
4585  
4586 # by: default empty (grand total); must be arrayref of known, unambiguous columns.
4587 102 ▶ $by_raw = [] unless defined $by_raw;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $by_raw 45 57 102
4588 102 ▶ croak $self->_err('error_aggregate_by_invalid')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $by_raw eq "ARRAY" 1 101 102
4589 unless ref($by_raw) eq 'ARRAY';
4590  
4591 101 my @by_names;
4592 101 for my $col (@{$by_raw}) {
4593 60 ▶ croak $self->_err('error_aggregate_by_invalid')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col and length $col 0 60 60
Condition33%1/3
defined $col and length $col
!ll&&!rl&&r
0060
MC/DC0%0/2
defined $col and length $col
defined $col length $col
Truth table33%1/3
A and B
A= defined $colB= length $col
ABresult
0X0
100
111
4594 unless defined $col && length $col;
4595 60 my $owner = $self->{_col_db}{$col};
4596 60 ▶ croak $self->_err('error_aggregate_col_unknown', $col)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $owner 1 59 60
4597 unless defined $owner;
4598 # Ambiguity: any DB other than the owner also has the raw column name
4599 # without renaming it via collision_prefix → last-wins applied silently.
4600 59 ▶ if ($col ne $join_col && index($col, '.') < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($col ne $join_col and index($col, ".") == -1) 12 47 59
Condition100%3/3
$col ne $join_col and index($col, ".") == -1
!ll&&!rl&&r
14612
MC/DC100%2/2
$col ne $join_col and index($col, ".") == -1
$col ne $join_col index($col, ".") == -1
Truth table100%3/3
A and B
A= $col ne $join_colB= index($col, ".") == -1
ABresult
0X0
100
111
4601 12 for my $j (0 .. $n - 1) {
4602 24 ▶ next if $j == $owner;
Branch: 1 branch
BranchTrueFalseTotal
if $j == $owner 12 12 24
4603 12 ▶ if ($self->{_db_cols}[$j]{$col}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_db_cols"}[$j]{$col} and not exists $self->{"_col_rename"}[$j]{$col}) 0 12 12
Condition33%1/3
$self->{"_db_cols"}[$j]{$col} and not exists $self->{"_col_rename"}[$j]{$col}
!ll&&!rl&&r
1200
MC/DC0%0/2
$self->{"_db_cols"}[$j]{$col} and not exists $self->{"_col_rename"}[$j]{$col}
$self->{"_db_cols"}[$j]{$col} not exists $self->{"_col_rename"}[$j]{$col}
Truth table33%1/3
A and not(B)
A= $self->{"_db_cols"}[$j]{$col}B= not exists $self->{"_col_rename"}[$j]{$col}
ABresult
0X0
100
111
4604 && !exists $self->{_col_rename}[$j]{$col}) {
4605 0 croak $self->_err('error_col_conflict', $col);
4606 }
4607 }
4608 }
4609 59 ▶ my $db_col = $self->{_col_unrename}[$owner]{$col} // $col;
Condition66%2/3
$self->{"_col_unrename"}[$owner]{$col} // $col
l!l&&r!l&&!r
46130
MC/DC0%0/2
$self->{"_col_unrename"}[$owner]{$col} // $col
$self->{"_col_unrename"}[$owner]{$col} $col
Truth table66%2/3
A // B
A= $self->{"_col_unrename"}[$owner]{$col}B= $col
ABresult
1X1
011
000
4610 59 push @by_names, { name => $col, owner => $owner, db_col => $db_col };
4611 }
4612  
4613 # measures: required non-empty arrayref of hashrefs.
4614 croak $self->_err('error_aggregate_measures_required')
4615 100 ▶ unless ref($measures_raw) eq 'ARRAY' && @{$measures_raw};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $measures_raw eq "ARRAY" and @{$measures_raw;} 4 96 100
Condition100%3/3
ref $measures_raw eq "ARRAY" and @{$measures_raw;}
!ll&&!rl&&r
2296
MC/DC100%2/2
ref $measures_raw eq "ARRAY" and @{$measures_raw;}
ref $measures_raw eq "ARRAY" @{$measures_raw;}
Truth table100%3/3
A and B
A= ref $measures_raw eq "ARRAY"B= @{$measures_raw;}
ABresult
0X0
100
111
4616  
4617 96 my (@measures, %aliases, %by_name_set);
4618 96 $by_name_set{ $_->{name} } = 1 for @by_names;
4619  
4620 96 for my $m (@{$measures_raw}) {
4621 130 ▶ croak $self->_err('error_aggregate_measure_ref', ref($m) || 'SCALAR')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $m eq "HASH" 2 128 130
Condition50%1/2
ref $m || 'SCALAR'
l!l
02
MC/DC0%0/1
ref $m || 'SCALAR'
ref $m
Truth table50%1/2
A
A= ref $m
Aresult
11
00
4622 unless ref($m) eq 'HASH';
4623  
4624 128 ▶ my $fn = lc($m->{fn} // '');
Condition50%1/2
$m->{"fn"} // ""
l!l
1280
MC/DC0%0/1
$m->{"fn"} // ""
$m->{"fn"}
Truth table50%1/2
A
A= $m->{"fn"}
Aresult
11
00
4625 croak $self->_err('error_aggregate_fn_unknown', $m->{fn} // '')
4626 128 ▶ unless $AGGREGATE_FNS{$fn};
Branch: 1 branch
BranchTrueFalseTotal
unless $AGGREGATE_FNS{$fn} 2 126 128
Condition50%1/2
$m->{"fn"} // ""
l!l
20
MC/DC0%0/1
$m->{"fn"} // ""
$m->{"fn"}
Truth table50%1/2
A
A= $m->{"fn"}
Aresult
11
00
4627  
4628 126 my $col = $m->{col};
4629 126 my ($m_owner, $m_db_col, $m_is_numeric);
4630 126 ▶ if (defined $col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $col) { } 88 38 126
4631 88 my $col_owner = $self->{_col_db}{$col};
4632 88 ▶ croak $self->_err('error_aggregate_col_unknown', $col)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col_owner 3 85 88
4633 unless defined $col_owner;
4634 85 ▶ if ($col ne $join_col && index($col, '.') < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($col ne $join_col and index($col, ".") == -1) 83 2 85
Condition66%2/3
$col ne $join_col and index($col, ".") == -1
!ll&&!rl&&r
0283
MC/DC50%1/2
$col ne $join_col and index($col, ".") == -1
$col ne $join_col index($col, ".") == -1
Truth table66%2/3
A and B
A= $col ne $join_colB= index($col, ".") == -1
ABresult
0X0
100
111
4635 83 for my $j (0 .. $n - 1) {
4636 165 ▶ next if $j == $col_owner;
Branch: 1 branch
BranchTrueFalseTotal
if $j == $col_owner 82 83 165
4637 83 ▶ if ($self->{_db_cols}[$j]{$col}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_db_cols"}[$j]{$col} and not exists $self->{"_col_rename"}[$j]{$col}) 1 82 83
Condition66%2/3
$self->{"_db_cols"}[$j]{$col} and not exists $self->{"_col_rename"}[$j]{$col}
!ll&&!rl&&r
8201
MC/DC50%1/2
$self->{"_db_cols"}[$j]{$col} and not exists $self->{"_col_rename"}[$j]{$col}
$self->{"_db_cols"}[$j]{$col} not exists $self->{"_col_rename"}[$j]{$col}
Truth table66%2/3
A and not(B)
A= $self->{"_db_cols"}[$j]{$col}B= not exists $self->{"_col_rename"}[$j]{$col}
ABresult
0X0
100
111
4638 && !exists $self->{_col_rename}[$j]{$col}) {
4639 1 croak $self->_err('error_col_conflict', $col);
4640 }
4641 }
4642 }
4643 84 $m_owner = $col_owner;
4644 84 ▶ $m_db_col = $self->{_col_unrename}[$col_owner]{$col} // $col;
Condition66%2/3
$self->{"_col_unrename"}[$col_owner]{$col} // $col
l!l&&r!l&&!r
2820
MC/DC0%0/2
$self->{"_col_unrename"}[$col_owner]{$col} // $col
$self->{"_col_unrename"}[$col_owner]{$col} $col
Truth table66%2/3
A // B
A= $self->{"_col_unrename"}[$col_owner]{$col}B= $col
ABresult
1X1
011
000
4645 84 ▶ my $schema = do { local $@; eval { $self->{_dbs}[$col_owner]->schema() } } // {};
Condition50%1/2
do { local $@; eval { do { $self->{"_dbs"}[$col_owner]->schema } } } // {}
l!l
840
MC/DC0%0/1
do { local $@; eval { do { $self->{"_dbs"}[$col_owner]->schema } } } // {}
do { local $@; eval { do { $self->{"_dbs"}[$col_owner]->schema } } }
Truth table50%1/2
A
A= do { local $@; eval { do { $self->{"_dbs"}[$col_owner]->schema } } }
Aresult
11
00
4646 84 my $entry = $schema->{$m_db_col};
4647 84 ▶ my $type = uc(ref($entry) eq 'HASH' ? ($entry->{type} // '') : ($entry // ''));
Branch: 1 branch
BranchTrueFalseTotal
ref $entry eq 'HASH' ? : 4 80 84
Condition50%2/4
$entry->{"type"} // ""
l!l
40
$entry // ""
l!l
080
MC/DC0%0/1
$entry->{"type"} // ""
$entry->{"type"}
MC/DC0%0/1
$entry // ""
$entry
Truth table50%1/2
A
A= $entry->{"type"}
Aresult
11
00
Truth table50%1/2
A
A= $entry
Aresult
11
00
4648 84 ▶ $m_is_numeric = ($type =~ /INT|REAL|FLOAT|DOUBLE|DECIMAL|NUMERIC/) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$type =~ /INT|REAL|FLOAT|DOUBLE|DECIMAL|NUMERIC/ ? : 4 80 84
4649 } else {
4650 38 ▶ croak $self->_err('error_aggregate_col_required', $fn)
Branch: 1 branch
BranchTrueFalseTotal
if $fn ne "count" 2 36 38
4651 if $fn ne 'count';
4652 }
4653  
4654 120 my $as = $m->{as};
4655 120 ▶ croak $self->_err('error_aggregate_as_required')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $as and length $as 2 118 120
Condition66%2/3
defined $as and length $as
!ll&&!rl&&r
20118
MC/DC50%1/2
defined $as and length $as
defined $as length $as
Truth table66%2/3
A and B
A= defined $asB= length $as
ABresult
0X0
100
111
4656 unless defined $as && length $as;
4657 118 ▶ croak $self->_err('error_aggregate_as_invalid', $as)
Branch: 1 branch
BranchTrueFalseTotal
unless $as =~ /^\w+\z/ 2 116 118
4658 unless $as =~ /^\w+\z/;
4659 croak $self->_err('error_aggregate_as_duplicate', $as)
4660 116 ▶ if exists $aliases{$as};
Branch: 1 branch
BranchTrueFalseTotal
if exists $aliases{$as} 2 114 116
4661 croak $self->_err('error_aggregate_as_collision', $as)
4662 114 ▶ if exists $by_name_set{$as};
Branch: 1 branch
BranchTrueFalseTotal
if exists $by_name_set{$as} 2 112 114
4663  
4664 112 $aliases{$as} = 1;
4665 112 push @measures, {
4666 fn => $fn,
4667 col => $col,
4668 as => $as,
4669 owner => $m_owner,
4670 db_col => $m_db_col,
4671 is_numeric => $m_is_numeric,
4672 };
4673 }
4674  
4675 # having: validate keys and operators recursively.
4676 78 my %valid_having_keys = (%by_name_set, %aliases);
4677 78 ▶ if (defined $having_raw && %{$having_raw}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $having_raw and %{$having_raw;}) 22 56 78
Condition66%2/3
defined $having_raw and %{$having_raw;}
!ll&&!rl&&r
56022
MC/DC50%1/2
defined $having_raw and %{$having_raw;}
defined $having_raw %{$having_raw;}
Truth table66%2/3
A and B
A= defined $having_rawB= %{$having_raw;}
ABresult
0X0
100
111
4678 22 $self->_validate_having($having_raw, \%valid_having_keys);
4679 }
4680  
4681 # sort_by: name must be a by-column or measure alias; direction ASC/DESC.
4682 74 my ($sort_col, $sort_dir) = (undef, 'ASC');
4683 74 ▶ if (defined $sort_by_raw) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_by_raw) 17 57 74
4684 17 my ($req_col, $req_dir);
4685 17 ▶ if (ref($sort_by_raw) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $sort_by_raw eq 'ARRAY') { } 2 15 17
4686 2 ($req_col, $req_dir) = @{$sort_by_raw};
4687 } else {
4688 15 ($req_col, $req_dir) = ($sort_by_raw, 'ASC');
4689 }
4690 17 ▶ $req_dir = uc($req_dir // 'ASC');
Condition50%1/2
$req_dir // "ASC"
l!l
170
MC/DC0%0/1
$req_dir // "ASC"
$req_dir
Truth table50%1/2
A
A= $req_dir
Aresult
11
00
4691 17 ▶ unless ($req_dir eq 'ASC' || $req_dir eq 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($req_dir eq "ASC" or $req_dir eq "DESC") 0 17 17
Condition66%2/3
$req_dir eq "ASC" or $req_dir eq "DESC"
l!l&&r!l&&!r
1520
MC/DC0%0/2
$req_dir eq "ASC" or $req_dir eq "DESC"
$req_dir eq "ASC" $req_dir eq "DESC"
Truth table66%2/3
A or B
A= $req_dir eq "ASC"B= $req_dir eq "DESC"
ABresult
1X1
011
000
4692 0 carp "Database::Join: sort_by direction '$req_dir' is not supported; using ASC";
4693 0 $req_dir = 'ASC';
4694 }
4695 17 ▶ if (exists $valid_having_keys{$req_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $valid_having_keys{$req_col}) { } 14 3 17
4696 14 ($sort_col, $sort_dir) = ($req_col, $req_dir);
4697 } else {
4698 3 carp $self->_err('warn_aggregate_sort_key', $req_col);
4699 }
4700 }
4701  
4702 return {
4703 74 ▶ by => \@by_names,
Branch: 1 branch
BranchTrueFalseTotal
defined $sort_col ? : 14 60 74
4704 measures => \@measures,
4705 aliases => \%aliases,
4706 having => $having_raw,
4707 sort => defined($sort_col) ? [$sort_col, $sort_dir] : undef,
4708 limit => $limit,
4709 offset => $offset,
4710 };
4711 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4712  
4713 # _normalise_aggregate( \@rows, \@measures )
4714 # Purpose: Apply empty-set normalisation to fetched/folded group rows.
4715 # sum/count/count_distinct: NULL → 0
4716 # avg/min/max: NULL stays undef
4717 # Called on both SQLite and array paths so they cannot drift.
4718 74 ▶sub _normalise_aggregate :Protected {
Subroutine _normalise_aggregate: called CC=7 SCAR=19.5
4719 74 my ($self, $rows, $measures) = @_;
4720 74 for my $row (@{$rows}) {
4721 137 for my $m (@{$measures}) {
4722 193 my $fn = $m->{fn};
4723 193 ▶ next if defined $row->{ $m->{as} };
Branch: 1 branch
BranchTrueFalseTotal
if defined $$row{$m->{"as"}} 169 24 193
4724 24 ▶ if ($fn eq 'sum' || $fn eq 'count' || $fn eq 'count_distinct') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "sum" or $fn eq "count" or $fn eq "count_distinct") 12 12 24
Condition66%4/6
$fn eq "sum" or $fn eq "count" or $fn eq "count_distinct"
l!l&&r!l&&!r
12012
$fn eq "sum" or $fn eq "count"
l!l&&r!l&&!r
12012
MC/DC33%1/3
$fn eq "sum" or $fn eq "count" or $fn eq "count_distinct"
$fn eq "sum" $fn eq "count" $fn eq "count_distinct"
Truth table50%2/4
A or B or C
A= $fn eq "sum"B= $fn eq "count"C= $fn eq "count_distinct"
ABCresult
1XX1
01X1
0011
0000
4725 12 $row->{ $m->{as} } = 0;
4726 }
4727 }
4728 }
4729 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4730  
4731 # _match_having_criterion( $value, $criterion, $key ) -> bool
4732 # Purpose: Evaluate one leaf HAVING condition on the Perl array path.
4733 # Implements three-valued logic: a NULL (undef) lhs satisfies only IS NULL.
4734 31 ▶sub _match_having_criterion :Protected {
Subroutine _match_having_criterion: called CC=45 SCAR=52.3
4735 31 my ($self, $value, $criterion, $key) = @_;
4736  
4737 # Empty-list short-circuits precede three-valued logic:
4738 # NOT IN () → always true (vacuously nothing to exclude, including NULL).
4739 # IN () → always false.
4740 31 ▶ if (ref($criterion) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $criterion eq "HASH") 25 6 31
4741 25 ▶ if (exists $criterion->{'NOT IN'}
Branch: 1 branch
BranchTrueFalseTotal
if (exists $criterion->{"NOT IN"} and ref $criterion->{"NOT IN"} eq "ARRAY" and not @{$criterion->{"NOT IN"};}) 3 22 25
Condition66%4/6
exists $criterion->{"NOT IN"} and ref $criterion->{"NOT IN"} eq "ARRAY" and not @{$criterion->{"NOT IN"};}
!ll&&!rl&&r
2203
exists $criterion->{"NOT IN"} and ref $criterion->{"NOT IN"} eq "ARRAY"
!ll&&!rl&&r
2203
MC/DC33%1/3
exists $criterion->{"NOT IN"} and ref $criterion->{"NOT IN"} eq "ARRAY" and not @{$criterion->{"NOT IN"};}
exists $criterion->{"NOT IN"} ref $criterion->{"NOT IN"} eq "ARRAY" not @{$criterion->{"NOT IN"};}
Truth table50%2/4
A and B and not(C)
A= exists $criterion->{"NOT IN"}B= ref $criterion->{"NOT IN"} eq "ARRAY"C= not @{$criterion->{"NOT IN"};}
ABCresult
0XX0
10X0
1100
1111
4742 && ref($criterion->{'NOT IN'}) eq 'ARRAY'
4743 3 && !@{ $criterion->{'NOT IN'} }) {
4744 3 return 1;
4745 }
4746 22 ▶ if (exists $criterion->{'IN'}
Branch: 1 branch
BranchTrueFalseTotal
if (exists $criterion->{"IN"} and ref $criterion->{"IN"} eq "ARRAY" and not @{$criterion->{"IN"};}) 3 19 22
Condition83%5/6
exists $criterion->{"IN"} and ref $criterion->{"IN"} eq "ARRAY" and not @{$criterion->{"IN"};}
!ll&&!rl&&r
1633
exists $criterion->{"IN"} and ref $criterion->{"IN"} eq "ARRAY"
!ll&&!rl&&r
1606
MC/DC66%2/3
exists $criterion->{"IN"} and ref $criterion->{"IN"} eq "ARRAY" and not @{$criterion->{"IN"};}
exists $criterion->{"IN"} ref $criterion->{"IN"} eq "ARRAY" not @{$criterion->{"IN"};}
Truth table75%3/4
A and B and not(C)
A= exists $criterion->{"IN"}B= ref $criterion->{"IN"} eq "ARRAY"C= not @{$criterion->{"IN"};}
ABCresult
0XX0
10X0
1100
1111
4747 && ref($criterion->{'IN'}) eq 'ARRAY'
4748 6 && !@{ $criterion->{'IN'} }) {
4749 3 return 0;
4750 }
4751 }
4752  
4753 25 ▶ if (!defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value) 4 21 25
4754 # NULL satisfies: (1) bare undef criterion (IS NULL shorthand), or (2) IS NULL.
4755 4 ▶ return 1 unless defined $criterion;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $criterion 1 3 4
4756 3 ▶ return (ref($criterion) eq 'HASH' && exists $criterion->{'IS NULL'}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $criterion eq 'HASH' && exists $criterion->{'IS NULL'} ? : 0 3 3
Condition66%2/3
ref $criterion eq "HASH" and exists $criterion->{"IS NULL"}
!ll&&!rl&&r
120
MC/DC0%0/2
ref $criterion eq "HASH" and exists $criterion->{"IS NULL"}
ref $criterion eq "HASH" exists $criterion->{"IS NULL"}
Truth table66%2/3
A and B
A= ref $criterion eq "HASH"B= exists $criterion->{"IS NULL"}
ABresult
0X0
100
111
4757 }
4758 21 ▶ if (!defined $criterion) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $criterion) 2 19 21
4759 # bare undef means IS NULL; value is defined → false
4760 2 return 0;
4761 }
4762 19 ▶ if (ref($criterion) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $criterion eq "HASH") 17 2 19
4763 17 for my $op (keys %{$criterion}) {
4764 17 my $rhs = $criterion->{$op};
4765 17 ▶ if ($SAFE_NOARG_OPS{$op}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($SAFE_NOARG_OPS{$op}) { } 0 17 17
elsif ($SAFE_LIST_OPS{$op}) { } 2 15 17
elsif ($SAFE_SQL_OPS{$op}) { } 15 0 15
4766 0 ▶ return 0 if $op eq 'IS NULL'; # value is defined
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "IS NULL" 0 0 0
4767 # IS NOT NULL → pass
4768 } elsif ($SAFE_LIST_OPS{$op}) {
4769 2 ▶ my @items = ref($rhs) eq 'ARRAY' ? @{$rhs} : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $rhs eq 'ARRAY' ? : 2 0 2
4770 2 ▶ if ($op eq 'IN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq 'IN') { } 2 0 2
4771 2 ▶ return 0 unless grep { defined $_ && $_ eq $value } @items;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {defined $_ and $_ eq $value;} @items 0 2 2
Condition66%2/3
defined $_ && $_ eq $value
!ll&&!rl&&r
022
MC/DC50%1/2
defined $_ && $_ eq $value
defined $_ $_ eq $value
Truth table66%2/3
A && B
A= defined $_B= $_ eq $value
ABresult
0X0
100
111
4772 } else {
4773 0 ▶ return 0 if grep { defined $_ && $_ eq $value } @items;
Branch: 1 branch
BranchTrueFalseTotal
if grep {defined $_ and $_ eq $value;} @items 0 0 0
Condition0%0/3
defined $_ && $_ eq $value
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_ && $_ eq $value
defined $_ $_ eq $value
Truth table0%0/3
A && B
A= defined $_B= $_ eq $value
ABresult
0X0
100
111
4774 }
4775 } elsif ($SAFE_SQL_OPS{$op}) {
4776 15 ▶ my $num = looks_like_number($value) && looks_like_number($rhs);
Condition66%2/3
&looks_like_number($value) && &looks_like_number($rhs)
!ll&&!rl&&r
2013
MC/DC50%1/2
&looks_like_number($value) && &looks_like_number($rhs)
&looks_like_number($value) &looks_like_number($rhs)
Truth table66%2/3
A && B
A= &looks_like_number($value)B= &looks_like_number($rhs)
ABresult
0X0
100
111
4777 15 my $ok;
4778 0 ▶ if ($op eq '=') { $ok = $num ? $value == $rhs : $value eq $rhs }
Branch: 9 branches
BranchTrueFalseTotal
if ($op eq '=') { } 0 15 15
elsif ($op eq '!=') { } 2 13 15
elsif ($op eq '>') { } 9 4 13
elsif ($op eq '<') { } 4 0 4
elsif ($op eq '>=') { } 0 0 0
elsif ($op eq '<=') { } 0 0 0
elsif ($op eq 'LIKE') { } 0 0 0
elsif ($op eq 'NOT LIKE') { } 0 0 0
$num ? : 0 0 0
4779 2 ▶ elsif ($op eq '!=') { $ok = $num ? $value != $rhs : $value ne $rhs }
Branch: 1 branch
BranchTrueFalseTotal
$num ? : 0 2 2
4780 9 ▶ elsif ($op eq '>') { $ok = $num ? $value > $rhs : $value gt $rhs }
Branch: 1 branch
BranchTrueFalseTotal
$num ? : 9 0 9
4781 4 ▶ elsif ($op eq '<') { $ok = $num ? $value < $rhs : $value lt $rhs }
Branch: 1 branch
BranchTrueFalseTotal
$num ? : 4 0 4
4782 0 ▶ elsif ($op eq '>=') { $ok = $num ? $value >= $rhs : $value ge $rhs }
Branch: 1 branch
BranchTrueFalseTotal
$num ? : 0 0 0
4783 0 ▶ elsif ($op eq '<=') { $ok = $num ? $value <= $rhs : $value le $rhs }
Branch: 1 branch
BranchTrueFalseTotal
$num ? : 0 0 0
4784 elsif ($op eq 'LIKE') {
4785 0 my $pat = quotemeta($rhs);
4786 0 $pat =~ s/\\%/.*/g;
4787 0 $pat =~ s/\\_/./g;
4788 0 $ok = ($value =~ /\A$pat\z/i);
4789 } elsif ($op eq 'NOT LIKE') {
4790 0 my $pat = quotemeta($rhs);
4791 0 $pat =~ s/\\%/.*/g;
4792 0 $pat =~ s/\\_/./g;
4793 0 $ok = ($value !~ /\A$pat\z/i);
4794 } else {
4795 0 $ok = 0;
4796 }
4797 15 ▶ return 0 unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 8 7 15
4798 } else {
4799 0 croak $self->_err('error_aggregate_having_operator', $op, $key);
4800 }
4801 }
4802 9 return 1;
4803 }
4804 # Bare scalar: equality
4805 2 ▶ return looks_like_number($value) && looks_like_number($criterion)
Branch: 3 branches
BranchTrueFalseTotal
&looks_like_number($value) && &looks_like_number($criterion) ? : 0 2 2
$value == $criterion ? : 0 0 0
$value eq $criterion ? : 1 1 2
Condition33%1/3
&looks_like_number($value) and &looks_like_number($criterion)
!ll&&!rl&&r
200
MC/DC0%0/2
&looks_like_number($value) and &looks_like_number($criterion)
&looks_like_number($value) &looks_like_number($criterion)
Truth table33%1/3
A and B
A= &looks_like_number($value)B= &looks_like_number($criterion)
ABresult
0X0
100
111
4806 ? ($value == $criterion ? 1 : 0)
4807 : ($value eq $criterion ? 1 : 0);
4808 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4809  
4810 # _match_criteria( $row, \%criteria ) -> bool
4811 # Purpose: Evaluate a HAVING criteria hashref against a folded group row.
4812 # Supports -or / -and groupings recursively; delegates leaves to
4813 # _match_having_criterion. Used by the array path's aggregate() only.
4814 37 ▶sub _match_criteria :Protected {
Subroutine _match_criteria: called CC=11 SCAR=24.0
4815 37 my ($self, $row, $criteria) = @_;
4816 37 for my $key (keys %{$criteria}) {
4817 37 ▶ if ($key eq '-or') {
Branch: 2 branches
BranchTrueFalseTotal
if ($key eq '-or') { } 3 34 37
elsif ($key eq '-and') { } 3 31 34
4818 3 my $any = 0;
4819 3 for my $sub (@{ $criteria->{$key} }) {
4820 5 ▶ if ($self->_match_criteria($row, $sub)) { $any = 1; last }
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_match_criteria($row, $sub)) 2 3 5
4821 }
4822 3 ▶ return 0 unless $any;
Branch: 1 branch
BranchTrueFalseTotal
unless $any 1 2 3
4823 } elsif ($key eq '-and') {
4824 3 for my $sub (@{ $criteria->{$key} }) {
4825 5 ▶ return 0 unless $self->_match_criteria($row, $sub);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_match_criteria($row, $sub) 2 3 5
4826 }
4827 } else {
4828 31 ▶ my $val = exists $row->{$key} ? $row->{$key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$key} ? : 31 0 31
4829 31 ▶ return 0 unless $self->_match_having_criterion($val, $criteria->{$key}, $key);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_match_having_criterion($val, $criteria->{$key}, $key) 17 14 31
4830 }
4831 }
4832 17 return 1;
4833 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4834  
4835 # _fold_aggregate( \@merged_rows, \%spec ) -> \@groups
4836 # Purpose: Group merged rows and compute aggregate measures in Perl.
4837 # Used by the array backend path of aggregate().
4838 37 ▶sub _fold_aggregate :Protected {
Subroutine _fold_aggregate: called CC=55 SCAR=41.6
4839 37 my ($self, $rows, $spec) = @_;
4840 37 my @by = @{ $spec->{by} };
4841 37 my @measures = @{ $spec->{measures} };
4842  
4843 37 my (%groups, @order);
4844  
4845 83 ▶ my $new_group = sub {
Subroutine __ANON__: called CC=10 SCAR=23.0
4846 83 my ($row) = @_;
4847 83 my %g;
4848 83 for my $b (@by) {
4849 $g{ $b->{name} } = exists $row->{ $b->{name} }
4850 78 ▶ ? $row->{ $b->{name} } : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $$row{$b->{'name'}} ? : 58 20 78
4851 }
4852 83 for my $m (@measures) {
4853 111 my ($fn, $as) = ($m->{fn}, $m->{as});
4854 111 ▶ if ($fn eq 'sum') { $g{"${as}__sum"} = 0; $g{"${as}__bad"} = 0; $g{"${as}__badval"} = undef }
Branch: 5 branches
BranchTrueFalseTotal
if ($fn eq 'sum') { } 58 53 111
elsif ($fn eq 'avg') { } 5 48 53
elsif ($fn eq 'min' or $fn eq 'max') { } 14 34 48
elsif ($fn eq 'count') { } 32 2 34
elsif ($fn eq 'count_distinct') { } 2 0 2
4855 5 elsif ($fn eq 'avg') { $g{"${as}__sum"} = 0; $g{"${as}__cnt"} = 0; $g{"${as}__bad"} = 0; $g{"${as}__badval"} = undef }
4856 14 ▶ elsif ($fn eq 'min' || $fn eq 'max') { $g{"${as}__val"} = undef }
Condition100%3/3
$fn eq "min" or $fn eq "max"
l!l&&r!l&&!r
7734
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
4857 32 elsif ($fn eq 'count') { $g{"${as}__cnt"} = 0 }
4858 2 elsif ($fn eq 'count_distinct') { $g{"${as}__seen"} = {} }
4859 }
4860 83 return \%g;
4861 37 };
4862  
4863 37 for my $row (@{$rows}) {
4864 my $key = join("\x00",
4865 158 ▶ map { defined $row->{ $_->{name} } ? $row->{ $_->{name} } : '' }
Branch: 1 branch
BranchTrueFalseTotal
defined $$row{$_->{'name'}} ? : 102 20 122
4866 @by);
4867 158 ▶ my $g = $groups{$key} //= do { push @order, $key; $new_group->($row) };
Condition66%2/3
$groups{$key} //= do { push @order, $key; &$new_group($row) }
l!l&&r!l&&!r
76820
MC/DC0%0/2
$groups{$key} //= do { push @order, $key; &$new_group($row) }
$groups{$key} do { push @order, $key; &$new_group($row) }
Truth table66%2/3
A //= B
A= $groups{$key}B= do { push @order, $key; &$new_group($row) }
ABresult
1X1
011
000
4868  
4869 158 for my $m (@measures) {
4870 225 my ($fn, $as, $col) = ($m->{fn}, $m->{as}, $m->{col});
4871 my $val = defined $col
4872 225 ▶ ? (exists $row->{$col} ? $row->{$col} : undef)
Branch: 2 branches
BranchTrueFalseTotal
defined $col ? : 166 59 225
exists $row->{$col} ? : 136 30 166
4873 : undef;
4874  
4875 225 ▶ if ($fn eq 'sum') {
Branch: 6 branches
BranchTrueFalseTotal
if ($fn eq 'sum') { } 106 119 225
elsif ($fn eq 'avg') { } 10 109 119
elsif ($fn eq 'min') { } 15 94 109
elsif ($fn eq 'max') { } 15 79 94
elsif ($fn eq 'count') { } 69 10 79
elsif ($fn eq 'count_distinct') { } 10 0 10
4876 106 ▶ if (defined $val && $val ne '' && looks_like_number($val)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $val and $val ne '' and &looks_like_number($val)) { } 85 21 106
elsif (defined $val and $val ne '') { } 2 38 40
Condition83%5/6
defined $val and $val ne "" and &looks_like_number($val)
!ll&&!rl&&r
19285
defined $val and $val ne ""
!ll&&!rl&&r
19087
MC/DC66%2/3
defined $val and $val ne "" and &looks_like_number($val)
defined $val $val ne "" &looks_like_number($val)
Truth table75%3/4
A and B and C
A= defined $valB= $val ne ""C= &looks_like_number($val)
ABCresult
0XX0
10X0
1100
1111
4877 85 $g->{"${as}__sum"} += $val;
4878 ▶ } elsif (defined $val && $val ne '') {
Condition66%2/3
defined $val and $val ne ""
!ll&&!rl&&r
1902
MC/DC50%1/2
defined $val and $val ne ""
defined $val $val ne ""
Truth table66%2/3
A and B
A= defined $valB= $val ne ""
ABresult
0X0
100
111
4879 2 $g->{"${as}__bad"}++;
4880 2 ▶ $g->{"${as}__badval"} //= $val;
Condition33%1/3
$$g{"${as}__badval"} //= $val
l!l&&r!l&&!r
020
MC/DC0%0/2
$$g{"${as}__badval"} //= $val
$$g{"${as}__badval"} $val
Truth table33%1/3
A //= B
A= $$g{"${as}__badval"}B= $val
ABresult
1X1
011
000
4881 }
4882 } elsif ($fn eq 'avg') {
4883 10 ▶ if (defined $val && $val ne '' && looks_like_number($val)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $val and $val ne '' and &looks_like_number($val)) { } 8 2 10
elsif (defined $val and $val ne '') { } 0 4 4
Condition66%4/6
defined $val and $val ne "" and &looks_like_number($val)
!ll&&!rl&&r
208
defined $val and $val ne ""
!ll&&!rl&&r
208
MC/DC33%1/3
defined $val and $val ne "" and &looks_like_number($val)
defined $val $val ne "" &looks_like_number($val)
Truth table50%2/4
A and B and C
A= defined $valB= $val ne ""C= &looks_like_number($val)
ABCresult
0XX0
10X0
1100
1111
4884 8 $g->{"${as}__sum"} += $val;
4885 8 $g->{"${as}__cnt"}++;
4886 ▶ } elsif (defined $val && $val ne '') {
Condition33%1/3
defined $val and $val ne ""
!ll&&!rl&&r
200
MC/DC0%0/2
defined $val and $val ne ""
defined $val $val ne ""
Truth table33%1/3
A and B
A= defined $valB= $val ne ""
ABresult
0X0
100
111
4887 0 $g->{"${as}__bad"}++;
4888 0 ▶ $g->{"${as}__badval"} //= $val;
Condition0%0/3
$$g{"${as}__badval"} //= $val
l!l&&r!l&&!r
000
MC/DC0%0/2
$$g{"${as}__badval"} //= $val
$$g{"${as}__badval"} $val
Truth table0%0/3
A //= B
A= $$g{"${as}__badval"}B= $val
ABresult
1X1
011
000
4889 }
4890 } elsif ($fn eq 'min') {
4891 15 ▶ if (defined $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 12 3 15
4892 12 my $cur = $g->{"${as}__val"};
4893 12 ▶ if (!defined $cur) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $cur) { } 5 7 12
4894 5 $g->{"${as}__val"} = $val;
4895 } else {
4896 7 ▶ my $num = looks_like_number($cur) && looks_like_number($val);
Condition33%1/3
&looks_like_number($cur) && &looks_like_number($val)
!ll&&!rl&&r
007
MC/DC0%0/2
&looks_like_number($cur) && &looks_like_number($val)
&looks_like_number($cur) &looks_like_number($val)
Truth table33%1/3
A && B
A= &looks_like_number($cur)B= &looks_like_number($val)
ABresult
0X0
100
111
4897 7 ▶ $g->{"${as}__val"} = $val if $num ? $val < $cur : $val lt $cur;
Branch: 2 branches
BranchTrueFalseTotal
if $num ? $val < $cur : $val lt $cur 6 1 7
$num ? : 7 0 7
4898 }
4899 }
4900 } elsif ($fn eq 'max') {
4901 15 ▶ if (defined $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 12 3 15
4902 12 my $cur = $g->{"${as}__val"};
4903 12 ▶ if (!defined $cur) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $cur) { } 5 7 12
4904 5 $g->{"${as}__val"} = $val;
4905 } else {
4906 7 ▶ my $num = looks_like_number($cur) && looks_like_number($val);
Condition33%1/3
&looks_like_number($cur) && &looks_like_number($val)
!ll&&!rl&&r
007
MC/DC0%0/2
&looks_like_number($cur) && &looks_like_number($val)
&looks_like_number($cur) &looks_like_number($val)
Truth table33%1/3
A && B
A= &looks_like_number($cur)B= &looks_like_number($val)
ABresult
0X0
100
111
4907 7 ▶ $g->{"${as}__val"} = $val if $num ? $val > $cur : $val gt $cur;
Branch: 2 branches
BranchTrueFalseTotal
if $num ? $val > $cur : $val gt $cur 0 7 7
$num ? : 7 0 7
4908 }
4909 }
4910 } elsif ($fn eq 'count') {
4911 69 ▶ if (!defined $col) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $col) { } 59 10 69
4912 59 $g->{"${as}__cnt"}++;
4913 } else {
4914 10 ▶ $g->{"${as}__cnt"}++ if defined $val;
Branch: 1 branch
BranchTrueFalseTotal
if defined $val 8 2 10
4915 }
4916 } elsif ($fn eq 'count_distinct') {
4917 10 ▶ $g->{"${as}__seen"}{$val} = 1 if defined $val;
Branch: 1 branch
BranchTrueFalseTotal
if defined $val 9 1 10
4918 }
4919 }
4920 }
4921  
4922 # Grand total with no rows and no by: synthesise one zeroed row.
4923 37 ▶ if (!@by && !@order) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@by or @order) 1 36 37
Condition100%3/3
@by or @order
l!l&&r!l&&!r
24121
MC/DC100%2/2
@by or @order
@by @order
Truth table100%3/3
A or B
A= @byB= @order
ABresult
1X1
011
000
4924 1 push @order, '';
4925 1 $groups{''} = $new_group->({});
4926 }
4927  
4928 # Finalise accumulators into result rows.
4929 37 my (@result, %bad_warned);
4930 37 for my $key (@order) {
4931 83 my $g = $groups{$key};
4932 83 my %row;
4933 83 for my $b (@by) { $row{ $b->{name} } = $g->{ $b->{name} } }
4934 83 for my $m (@measures) {
4935 111 ▶ my ($fn, $as, $col) = ($m->{fn}, $m->{as}, $m->{col} // '(row)');
Condition100%2/2
$m->{"col"} // "(row)"
l!l
8328
MC/DC100%1/1
$m->{"col"} // "(row)"
$m->{"col"}
Truth table100%2/2
A
A= $m->{"col"}
Aresult
11
00
4936 111 ▶ if ($fn eq 'sum') {
Branch: 5 branches
BranchTrueFalseTotal
if ($fn eq 'sum') { } 58 53 111
elsif ($fn eq 'avg') { } 5 48 53
elsif ($fn eq 'min' or $fn eq 'max') { } 14 34 48
elsif ($fn eq 'count') { } 32 2 34
elsif ($fn eq 'count_distinct') { } 2 0 2
4937 58 ▶ if ($g->{"${as}__bad"} && !$bad_warned{$as}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$g{"${as}__bad"} and not $bad_warned{$as}) 2 56 58
Condition66%2/3
$$g{"${as}__bad"} and not $bad_warned{$as}
!ll&&!rl&&r
5602
MC/DC50%1/2
$$g{"${as}__bad"} and not $bad_warned{$as}
$$g{"${as}__bad"} not $bad_warned{$as}
Truth table66%2/3
A and not(B)
A= $$g{"${as}__bad"}B= not $bad_warned{$as}
ABresult
0X0
100
111
4938 carp $self->_err('warn_aggregate_non_numeric',
4939 2 $col, $g->{"${as}__bad"}, $g->{"${as}__badval"});
4940 2 $bad_warned{$as} = 1;
4941 }
4942 58 $row{$as} = $g->{"${as}__sum"};
4943 } elsif ($fn eq 'avg') {
4944 5 ▶ if ($g->{"${as}__bad"} && !$bad_warned{$as}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$g{"${as}__bad"} and not $bad_warned{$as}) 0 5 5
Condition33%1/3
$$g{"${as}__bad"} and not $bad_warned{$as}
!ll&&!rl&&r
500
MC/DC0%0/2
$$g{"${as}__bad"} and not $bad_warned{$as}
$$g{"${as}__bad"} not $bad_warned{$as}
Truth table33%1/3
A and not(B)
A= $$g{"${as}__bad"}B= not $bad_warned{$as}
ABresult
0X0
100
111
4945 carp $self->_err('warn_aggregate_non_numeric',
4946 0 $col, $g->{"${as}__bad"}, $g->{"${as}__badval"});
4947 0 $bad_warned{$as} = 1;
4948 }
4949 $row{$as} = $g->{"${as}__cnt"}
4950 5 ▶ ? $g->{"${as}__sum"} / $g->{"${as}__cnt"}
Branch: 1 branch
BranchTrueFalseTotal
$$g{"${as}__cnt"} ? : 3 2 5
4951 : undef;
4952 ▶ } elsif ($fn eq 'min' || $fn eq 'max') {
Condition100%3/3
$fn eq "min" or $fn eq "max"
l!l&&r!l&&!r
7734
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
4953 14 $row{$as} = $g->{"${as}__val"};
4954 } elsif ($fn eq 'count') {
4955 32 $row{$as} = $g->{"${as}__cnt"};
4956 } elsif ($fn eq 'count_distinct') {
4957 2 $row{$as} = scalar keys %{ $g->{"${as}__seen"} };
4958 }
4959 }
4960 83 push @result, \%row;
4961 }
4962 37 return \@result;
4963 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4964  
4965 # _sort_and_page( \@rows, \%spec )
4966 # Purpose: Sort and splice the array-path aggregate result in place.
4967 # Order of operations: sort → offset → limit (matching GROUP BY semantics).
4968 37 ▶sub _sort_and_page :Protected {
Subroutine _sort_and_page: called CC=22 SCAR=32.6
4969 37 my ($self, $rows, $spec) = @_;
4970 37 my $sort = $spec->{sort};
4971 37 my $limit = $spec->{limit};
4972 37 my $offset = $spec->{offset};
4973 37 my @by = @{ $spec->{by} };
4974  
4975 37 ▶ if (defined $sort) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort) { } 6 31 37
elsif (@by) { } 18 13 31
4976 6 my ($sc, $sd) = @{$sort};
4977 6 @{$rows} = sort {
4978 12 my ($va, $vb) = ($a->{$sc}, $b->{$sc});
4979 12 my $cmp;
4980 0 ▶ if (!defined $va && !defined $vb) { $cmp = 0 }
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $va || defined $vb) { } 0 12 12
elsif (not defined $va) { } 0 12 12
elsif (not defined $vb) { } 4 8 12
Condition33%1/3
defined $va || defined $vb
l!l&&r!l&&!r
1200
MC/DC0%0/2
defined $va || defined $vb
defined $va defined $vb
Truth table33%1/3
A || B
A= defined $vaB= defined $vb
ABresult
1X1
011
000
4981 0 elsif (!defined $va) { $cmp = -1 }
4982 4 elsif (!defined $vb) { $cmp = 1 }
4983 else {
4984 8 ▶ $cmp = looks_like_number($va) && looks_like_number($vb)
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($va) && &looks_like_number($vb) ? : 3 5 8
Condition66%2/3
&looks_like_number($va) and &looks_like_number($vb)
!ll&&!rl&&r
503
MC/DC50%1/2
&looks_like_number($va) and &looks_like_number($vb)
&looks_like_number($va) &looks_like_number($vb)
Truth table66%2/3
A and B
A= &looks_like_number($va)B= &looks_like_number($vb)
ABresult
0X0
100
111
4985 ? $va <=> $vb : $va cmp $vb;
4986 }
4987 12 ▶ $sd eq 'DESC' ? -$cmp : $cmp;
Branch: 1 branch
BranchTrueFalseTotal
$sd eq 'DESC' ? : 3 9 12
4988 6 } @{$rows};
4989 } elsif (@by) {
4990 18 @{$rows} = sort {
4991 24 my $cmp = 0;
4992 24 for my $dim (@by) {
4993 26 my $k = $dim->{name};
4994 26 my ($va, $vb) = ($a->{$k}, $b->{$k});
4995 0 ▶ if (!defined $va && !defined $vb) { $cmp = 0 }
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $va || defined $vb) { } 0 26 26
elsif (not defined $va) { } 0 26 26
elsif (not defined $vb) { } 9 17 26
Condition33%1/3
defined $va || defined $vb
l!l&&r!l&&!r
2600
MC/DC0%0/2
defined $va || defined $vb
defined $va defined $vb
Truth table33%1/3
A || B
A= defined $vaB= defined $vb
ABresult
1X1
011
000
4996 0 elsif (!defined $va) { $cmp = -1 }
4997 9 elsif (!defined $vb) { $cmp = 1 }
4998 else {
4999 17 ▶ $cmp = looks_like_number($va) && looks_like_number($vb)
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($va) && &looks_like_number($vb) ? : 0 17 17
Condition33%1/3
&looks_like_number($va) and &looks_like_number($vb)
!ll&&!rl&&r
1700
MC/DC0%0/2
&looks_like_number($va) and &looks_like_number($vb)
&looks_like_number($va) &looks_like_number($vb)
Truth table33%1/3
A and B
A= &looks_like_number($va)B= &looks_like_number($vb)
ABresult
0X0
100
111
5000 ? $va <=> $vb : $va cmp $vb;
5001 }
5002 26 ▶ last if $cmp;
Branch: 1 branch
BranchTrueFalseTotal
if $cmp 24 2 26
5003 }
5004 $cmp;
5005 18 } @{$rows};
5006 }
5007  
5008 37 ▶ splice(@{$rows}, 0, $offset) if defined $offset && $offset > 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $offset and $offset > 0 1 36 37
Condition66%2/3
defined $offset and $offset > 0
!ll&&!rl&&r
3601
MC/DC50%1/2
defined $offset and $offset > 0
defined $offset $offset > 0
Truth table66%2/3
A and B
A= defined $offsetB= $offset > 0
ABresult
0X0
100
111
5009 37 ▶ splice(@{$rows}, $limit) if defined $limit && $limit < scalar @{$rows};
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit and $limit < scalar @{$rows;} 1 36 37
Condition100%3/3
defined $limit and $limit < scalar @{$rows;}
!ll&&!rl&&r
3511
MC/DC100%2/2
defined $limit and $limit < scalar @{$rows;}
defined $limit $limit < scalar @{$rows;}
Truth table100%3/3
A and B
A= defined $limitB= $limit < scalar @{$rows;}
ABresult
0X0
100
111
5010 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5011  
5012 # _having_to_sql( \%having, \%have_map ) -> ( $sql_fragment, \@binds )
5013 # Purpose: Recursively convert a having hashref to a SQL fragment with bind values.
5014 # $have_map maps every valid key to { expr => SQL_expr, is_agg => bool }.
5015 # is_agg => 1 means the expression is an aggregate function → CAST(? AS REAL)
5016 # is_agg => 0 means it is a group-by column expression → plain ?
5017 # Supports -or / -and recursion; delegates leaves to the same three operator tables
5018 # as _sqlite_where (_sqlite_join's WHERE builder), for vocabulary consistency.
5019 13 ▶sub _having_to_sql :Protected {
Subroutine _having_to_sql: called CC=22 SCAR=31.3
5020 13 my ($self, $having, $have_map) = @_;
5021 13 my (@parts, @binds);
5022  
5023 13 for my $key (sort keys %{$having}) {
5024 13 ▶ if ($key eq '-or') {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq "-or") 1 12 13
5025 1 my (@sp, @sb);
5026 1 for my $sub (@{ $having->{$key} }) {
5027 2 my ($s, $b) = $self->_having_to_sql($sub, $have_map);
5028 2 ▶ push @sp, $s if length $s;
Branch: 1 branch
BranchTrueFalseTotal
if length $s 2 0 2
5029 2 push @sb, @{$b};
5030 }
5031 1 ▶ if (@sp) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sp) 1 0 1
5032 1 push @parts, '(' . join(' OR ', @sp) . ')';
5033 1 push @binds, @sb;
5034 }
5035 1 next;
5036 }
5037 12 ▶ if ($key eq '-and') {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq "-and") 1 11 12
5038 1 my (@sp, @sb);
5039 1 for my $sub (@{ $having->{$key} }) {
5040 2 my ($s, $b) = $self->_having_to_sql($sub, $have_map);
5041 2 ▶ push @sp, $s if length $s;
Branch: 1 branch
BranchTrueFalseTotal
if length $s 2 0 2
5042 2 push @sb, @{$b};
5043 }
5044 1 ▶ if (@sp) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sp) 1 0 1
5045 1 push @parts, '(' . join(' AND ', @sp) . ')';
5046 1 push @binds, @sb;
5047 }
5048 1 next;
5049 }
5050  
5051 11 my $entry = $have_map->{$key};
5052 11 ▶ my $expr = $entry ? $entry->{expr} : _sql_quote_identifier($key);
Branch: 1 branch
BranchTrueFalseTotal
$entry ? : 11 0 11
5053 11 ▶ my $is_agg = $entry ? $entry->{is_agg} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$entry ? : 11 0 11
5054 11 my $val = $having->{$key};
5055  
5056 11 ▶ if (!defined $val) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $val) { } 1 10 11
elsif (ref $val eq 'HASH') { } 9 1 10
5057 1 push @parts, "$expr IS NULL";
5058 } elsif (ref($val) eq 'HASH') {
5059 9 for my $op (sort keys %{$val}) {
5060 9 ▶ if ($SAFE_NOARG_OPS{$op}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($SAFE_NOARG_OPS{$op}) { } 0 9 9
elsif ($SAFE_LIST_OPS{$op}) { } 3 6 9
elsif ($SAFE_SQL_OPS{$op}) { } 6 0 6
5061 0 push @parts, "$expr $op";
5062 } elsif ($SAFE_LIST_OPS{$op}) {
5063 3 my $arr = $val->{$op};
5064 3 ▶ my @items = ref($arr) eq 'ARRAY' ? @{$arr} : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $arr eq 'ARRAY' ? : 3 0 3
5065 3 ▶ if (!@items) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@items) 2 1 3
5066 2 ▶ push @parts, '1 = 0' if $op eq 'IN';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "IN" 1 1 2
5067 2 next;
5068 }
5069 1 push @parts,
5070 "$expr $op (" . join(', ', ('?') x scalar @items) . ')';
5071 1 push @binds, @items;
5072 } elsif ($SAFE_SQL_OPS{$op}) {
5073 6 ▶ my $bind = $is_agg ? 'CAST(? AS REAL)' : '?';
Branch: 1 branch
BranchTrueFalseTotal
$is_agg ? : 5 1 6
5074 6 push @parts, "$expr $op $bind";
5075 6 push @binds, $val->{$op};
5076 } else {
5077 0 croak $self->_err('error_aggregate_having_operator', $op, $key);
5078 }
5079 }
5080 } else {
5081 1 push @parts, "$expr = ?";
5082 1 push @binds, $val;
5083 }
5084 }
5085  
5086 13 return (join(' AND ', @parts), \@binds);
5087 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5088  
5089 # _sqlite_aggregate( \%params, \%spec ) -> \@group_rows
5090 # Purpose: Execute an aggregate query against the SQLite spill cache.
5091 # Builds SELECT … GROUP BY … HAVING … ORDER BY … SQL from the spec returned
5092 # by _validate_aggregate_spec, reusing the three extracted _sqlite_* builders
5093 # so criteria semantics stay identical to _sqlite_join.
5094 37 ▶sub _sqlite_aggregate :Protected {
Subroutine _sqlite_aggregate: called CC=35 SCAR=37.9
5095 37 my ($self, $params, $spec) = @_;
5096 37 my $join_col = $self->{_join_col};
5097 37 my $join_type = $self->{_join_type};
5098 37 my $n = scalar @{ $self->{_dbs} };
5099  
5100 37 my ($per_db_query, $per_db_full, $had_criteria) = $self->_sqlite_criteria($params);
5101  
5102 37 ▶ $self->_build_sqlite_cache() unless $self->_cache_fresh();
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_cache_fresh 24 13 37
5103 37 my $cache = $self->{_sqlite_cache};
5104 37 my $tmpdbh = $cache->{dbh};
5105 37 my @table_refs = @{ $cache->{table_refs} };
5106 37 my @is_attached = @{ $cache->{is_attached} };
5107  
5108 37 ▶ my $local_jc_0 = $self->{_join_map}{0} // $join_col;
Condition33%1/3
$self->{"_join_map"}{0} // $join_col
l!l&&r!l&&!r
0370
MC/DC0%0/2
$self->{"_join_map"}{0} // $join_col
$self->{"_join_map"}{0} $join_col
Truth table33%1/3
A // B
A= $self->{"_join_map"}{0}B= $join_col
ABresult
1X1
011
000
5109 37 my $from = $table_refs[0];
5110  
5111 37 my ($where_sql, $where_binds) = $self->_sqlite_where(
5112 $per_db_query, $per_db_full, \@table_refs, \@is_attached);
5113 37 my $join_sql = $self->_sqlite_join_clause(\@table_refs, $had_criteria, $local_jc_0);
5114  
5115 # Build by-column expressions (GROUP BY / SELECT / ORDER BY).
5116 37 my @by_exprs;
5117 my @by_select;
5118 37 my %have_map; # key => { expr, is_agg } for _having_to_sql
5119  
5120 37 for my $b (@{ $spec->{by} }) {
5121 28 my ($bname, $owner, $db_col) = @{$b}{qw(name owner db_col)};
5122 28 my $expr;
5123 28 ▶ if ($bname eq $join_col) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bname eq $join_col) { } 0 28 28
5124 0 ▶ if ($join_type eq 'outer' && $n > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($join_type eq 'outer' and $n > 1) { } 0 0 0
Condition0%0/3
$join_type eq "outer" and $n > 1
!ll&&!rl&&r
000
MC/DC0%0/2
$join_type eq "outer" and $n > 1
$join_type eq "outer" $n > 1
Truth table0%0/3
A and B
A= $join_type eq "outer"B= $n > 1
ABresult
0X0
100
111
5125 $expr = 'COALESCE('
5126 . join(', ', map {
5127 0 ▶ my $lc = $self->{_join_map}{$_} // $join_col;
Condition0%0/3
$self->{"_join_map"}{$_} // $join_col
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_join_map"}{$_} // $join_col
$self->{"_join_map"}{$_} $join_col
Truth table0%0/3
A // B
A= $self->{"_join_map"}{$_}B= $join_col
ABresult
1X1
011
000
5128 0 $table_refs[$_] . '.' . _sql_quote_identifier($lc)
5129 } 0 .. $n - 1)
5130 . ')';
5131 } else {
5132 0 $expr = $table_refs[0] . '.' . _sql_quote_identifier($local_jc_0);
5133 }
5134 } else {
5135 28 $expr = $table_refs[$owner] . '.' . _sql_quote_identifier($db_col);
5136 }
5137 28 push @by_exprs, $expr;
5138 # Dotted names (collision_prefix) need an AS alias so fetchall_arrayref({})
5139 # returns the right key.
5140 28 ▶ push @by_select, ($bname =~ /\./)
Branch: 1 branch
BranchTrueFalseTotal
$bname =~ /\./ ? : 23 5 28
5141 ? "$expr AS " . _sql_quote_identifier($bname)
5142 : $expr;
5143 28 $have_map{$bname} = { expr => $expr, is_agg => 0 };
5144 }
5145  
5146 # Build measure expressions (SELECT list / HAVING substitution).
5147 37 my @measure_select;
5148 37 for my $m (@{ $spec->{measures} }) {
5149 my ($fn, $as, $owner, $db_col, $is_numeric) =
5150 53 @{$m}{qw(fn as owner db_col is_numeric)};
5151 53 ▶ $is_numeric //= 0;
Condition100%2/2
$is_numeric //= 0
l!l
3914
MC/DC100%1/1
$is_numeric //= 0
$is_numeric
Truth table100%2/2
A
A= $is_numeric
Aresult
11
00
5152  
5153 53 ▶ my $col_ref = defined $db_col
Branch: 1 branch
BranchTrueFalseTotal
defined $db_col ? : 39 14 53
5154 ? $table_refs[$owner] . '.' . _sql_quote_identifier($db_col)
5155 : undef;
5156  
5157 53 my $sql_expr;
5158 53 ▶ if ($fn eq 'sum') { $sql_expr = "SUM(CAST($col_ref AS REAL))" }
Branch: 6 branches
BranchTrueFalseTotal
if ($fn eq 'sum') { } 26 27 53
elsif ($fn eq 'avg') { } 3 24 27
elsif ($fn eq 'min') { } 3 21 24
elsif ($fn eq 'max') { } 3 18 21
elsif ($fn eq 'count') { } 16 2 18
elsif ($fn eq 'count_distinct') { } 2 0 2
5159 3 elsif ($fn eq 'avg') { $sql_expr = "AVG(CAST($col_ref AS REAL))" }
5160 elsif ($fn eq 'min') {
5161 3 ▶ $sql_expr = $is_numeric ? "MIN(CAST($col_ref AS REAL))" : "MIN($col_ref)" }
Branch: 1 branch
BranchTrueFalseTotal
$is_numeric ? : 0 3 3
5162 elsif ($fn eq 'max') {
5163 3 ▶ $sql_expr = $is_numeric ? "MAX(CAST($col_ref AS REAL))" : "MAX($col_ref)" }
Branch: 1 branch
BranchTrueFalseTotal
$is_numeric ? : 0 3 3
5164 elsif ($fn eq 'count') {
5165 16 ▶ $sql_expr = defined $col_ref ? "COUNT($col_ref)" : 'COUNT(*)' }
Branch: 1 branch
BranchTrueFalseTotal
defined $col_ref ? : 2 14 16
5166 2 elsif ($fn eq 'count_distinct') { $sql_expr = "COUNT(DISTINCT $col_ref)" }
5167  
5168 53 push @measure_select, "$sql_expr AS " . _sql_quote_identifier($as);
5169 53 $have_map{$as} = { expr => $sql_expr, is_agg => 1 };
5170 }
5171  
5172 37 ▶ my $groupby_sql = @by_exprs
Branch: 1 branch
BranchTrueFalseTotal
@by_exprs ? : 26 11 37
5173 ? ' GROUP BY ' . join(', ', @by_exprs)
5174 : '';
5175  
5176 # HAVING clause.
5177 37 my ($having_sql, $having_binds) = ('', []);
5178 37 ▶ if (defined $spec->{having} && %{ $spec->{having} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $spec->{"having"} and %{$spec->{"having"};}) 9 28 37
Condition66%2/3
defined $spec->{"having"} and %{$spec->{"having"};}
!ll&&!rl&&r
2809
MC/DC50%1/2
defined $spec->{"having"} and %{$spec->{"having"};}
defined $spec->{"having"} %{$spec->{"having"};}
Truth table66%2/3
A and B
A= defined $spec->{"having"}B= %{$spec->{"having"};}
ABresult
0X0
100
111
5179 9 my ($h_sql, $h_binds) = $self->_having_to_sql($spec->{having}, \%have_map);
5180 9 ▶ if (length $h_sql) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $h_sql) 8 1 9
5181 8 $having_sql = ' HAVING ' . $h_sql;
5182 8 $having_binds = $h_binds;
5183 }
5184 }
5185  
5186 # ORDER BY: default = by expressions ascending; override via spec->{sort}.
5187 37 my $order_sql;
5188 37 ▶ if (defined $spec->{sort}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $spec->{'sort'}) { } 8 29 37
elsif (@by_exprs) { } 18 11 29
5189 8 my ($sc, $sd) = @{ $spec->{sort} };
5190 my $sort_expr = $have_map{$sc} ? $have_map{$sc}{expr}
5191 8 ▶ : _sql_quote_identifier($sc);
Branch: 1 branch
BranchTrueFalseTotal
$have_map{$sc} ? : 8 0 8
5192 8 ▶ $order_sql = ' ORDER BY ' . $sort_expr . ($sd eq 'DESC' ? ' DESC' : '');
Branch: 1 branch
BranchTrueFalseTotal
$sd eq 'DESC' ? : 1 7 8
5193 } elsif (@by_exprs) {
5194 18 $order_sql = ' ORDER BY ' . join(', ', @by_exprs);
5195 } else {
5196 11 $order_sql = '';
5197 }
5198  
5199 37 my $sql = 'SELECT '
5200 . join(', ', @by_select, @measure_select)
5201 . ' FROM ' . $from . $join_sql
5202 . $where_sql
5203 . $groupby_sql
5204 . $having_sql
5205 . $order_sql;
5206  
5207 37 my @page_bind;
5208 37 my ($limit, $offset) = ($spec->{limit}, $spec->{offset});
5209 37 ▶ if (defined $limit) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $limit) { } 2 35 37
elsif (defined $offset) { } 0 35 35
5210 2 $sql .= ' LIMIT ?';
5211 2 push @page_bind, $limit;
5212 2 ▶ if (defined $offset) { $sql .= ' OFFSET ?'; push @page_bind, $offset }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 1 1 2
5213 } elsif (defined $offset) {
5214 0 $sql .= ' LIMIT -1 OFFSET ?';
5215 0 push @page_bind, $offset;
5216 }
5217  
5218 37 my $sth = $tmpdbh->prepare_cached($sql);
5219 37 $sth->execute(@{$where_binds}, @{$having_binds}, @page_bind);
5220 37 ▶ my $rows = $sth->fetchall_arrayref({}) // [];
Condition50%1/2
$sth->fetchall_arrayref({}) // []
l!l
370
MC/DC0%0/1
$sth->fetchall_arrayref({}) // []
$sth->fetchall_arrayref({})
Truth table50%1/2
A
A= $sth->fetchall_arrayref({})
Aresult
11
00
5221  
5222 37 $self->_normalise_aggregate($rows, $spec->{measures});
5223  
5224 # Grand total with no by and no matching rows: synthesise one normalised row.
5225 37 ▶ if (!@{ $spec->{by} } && !@{$rows}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@{$spec->{"by"};} or @{$rows;}) 0 37 37
Condition66%2/3
@{$spec->{"by"};} or @{$rows;}
l!l&&r!l&&!r
26110
MC/DC0%0/2
@{$spec->{"by"};} or @{$rows;}
@{$spec->{"by"};} @{$rows;}
Truth table66%2/3
A or B
A= @{$spec->{"by"};}B= @{$rows;}
ABresult
1X1
011
000
5226 0 my %row = map { $_->{as} => undef } @{ $spec->{measures} };
5227 0 $self->_normalise_aggregate([\%row], $spec->{measures});
5228 0 return [\%row];
5229 }
5230  
5231 37 return $rows;
5232 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5233  
5234 # _mandatory_op_to_crit( $op, $val ) -> $criterion_value
5235 # Purpose: Convert a mandatory_filter {col, op, val} operator name to the
5236 # internal criteria format used by _sqlite_where.
5237 # Entry: $op is one of: eq ne lt lte gt gte like contains.
5238 # $val is the comparison value.
5239 # Exit: Returns a plain scalar (for eq) or an operator hashref.
5240 3 ▶sub _mandatory_op_to_crit {
Subroutine _mandatory_op_to_crit: called CC=9 SCAR=41.8
5241 3 my ($op, $val) = @_;
5242 3 ▶ return $val if $op eq 'eq';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "eq" 3 0 3
5243 0 ▶ return { '!=' => $val } if $op eq 'ne';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "ne" 0 0 0
5244 0 ▶ return { '<' => $val } if $op eq 'lt';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "lt" 0 0 0
5245 0 ▶ return { '<=' => $val } if $op eq 'lte';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "lte" 0 0 0
5246 0 ▶ return { '>' => $val } if $op eq 'gt';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "gt" 0 0 0
5247 0 ▶ return { '>=' => $val } if $op eq 'gte';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "gte" 0 0 0
5248 0 ▶ return { LIKE => $val } if $op eq 'like';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "like" 0 0 0
5249 0 ▶ return { LIKE => "%$val%" } if $op eq 'contains';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "contains" 0 0 0
5250 0 return $val; # unreachable: validated at construction
5251 }
5252  
5253 # _pass_mandatory_filters( \%row, \@filters ) -> bool
5254 # Purpose: Test a single merged row against all mandatory_filter predicates.
5255 # Entry: $row is a merged row hashref; $filters is the _mandatory_filters arrayref.
5256 # Exit: Returns 1 if ALL predicates pass, 0 if any fails.
5257 # Perl-side evaluation mirrors the SQL semantics produced by _mandatory_op_to_crit.
5258 62 ▶sub _pass_mandatory_filters {
Subroutine _pass_mandatory_filters: called CC=21 SCAR=33.7
5259 62 my ($row, $filters) = @_;
5260 62 for my $pred (@{$filters}) {
5261 65 my ($col, $op, $val) = @{$pred}{qw(col op val)};
5262 65 my $rv = $row->{$col};
5263 65 ▶ return 0 unless defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rv 0 65 65
5264 65 ▶ if ($op eq 'eq') { return 0 unless $rv eq $val }
Branch: 9 branches
BranchTrueFalseTotal
if ($op eq 'eq') { } 45 20 65
elsif ($op eq 'ne') { } 5 15 20
elsif ($op eq 'lt') { } 0 15 15
elsif ($op eq 'lte') { } 0 15 15
elsif ($op eq 'gt') { } 5 10 15
elsif ($op eq 'gte') { } 0 10 10
elsif ($op eq 'contains') { } 5 5 10
elsif ($op eq 'like') { } 5 0 5
unless $rv eq $val 19 26 45
5265 5 ▶ elsif ($op eq 'ne') { return 0 unless $rv ne $val }
Branch: 1 branch
BranchTrueFalseTotal
unless $rv ne $val 3 2 5
5266 0 ▶ elsif ($op eq 'lt') { return 0 unless $rv lt $val }
Branch: 1 branch
BranchTrueFalseTotal
unless $rv lt $val 0 0 0
5267 0 ▶ elsif ($op eq 'lte') { return 0 unless $rv le $val }
Branch: 1 branch
BranchTrueFalseTotal
unless $rv le $val 0 0 0
5268 5 ▶ elsif ($op eq 'gt') { return 0 unless $rv gt $val }
Branch: 1 branch
BranchTrueFalseTotal
unless $rv gt $val 3 2 5
5269 0 ▶ elsif ($op eq 'gte') { return 0 unless $rv ge $val }
Branch: 1 branch
BranchTrueFalseTotal
unless $rv ge $val 0 0 0
5270 5 ▶ elsif ($op eq 'contains') { return 0 unless index($rv, $val) >= 0 }
Branch: 1 branch
BranchTrueFalseTotal
unless index($rv, $val) != -1 3 2 5
5271 elsif ($op eq 'like') {
5272 # Convert LIKE pattern (%=any, _=one char) to a Perl regex.
5273 my $re = join('', map {
5274 5 ▶ $_ eq '%' ? '.*'
Branch: 2 branches
BranchTrueFalseTotal
$_ eq '%' ? : 5 5 10
$_ eq '_' ? : 0 5 5
5275 : $_ eq '_' ? '.'
5276 : quotemeta($_)
5277 } split //, $val);
5278 5 ▶ return 0 unless $rv =~ /\A$re\z/s;
Branch: 1 branch
BranchTrueFalseTotal
unless $rv =~ /\A$re\z/s 3 2 5
5279 }
5280 }
5281 31 return 1;
5282 }
5283  
5284 # _apply_distinct_array( \@rows, \@columns ) -> \@deduped_rows
5285 # Purpose: Deduplicate an array of merged row hashrefs.
5286 # Entry: $rows is the full merged result arrayref (already sorted when called
5287 # from _joined_query_array — distinct is applied before sort, but
5288 # that is fine since dedup preserves relative order).
5289 # $columns: when provided, project each row to only those columns and
5290 # deduplicate on their combined value; when absent, deduplicate on all
5291 # columns (full-row equality).
5292 # Exit: Returns a new arrayref; first occurrence of each distinct key wins.
5293 7 ▶sub _apply_distinct_array {
Subroutine _apply_distinct_array: called CC=9 SCAR=22.1
5294 7 my ($rows, $columns) = @_;
5295 7 my %seen;
5296 my @result;
5297 7 ▶ if ($columns && @{$columns}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($columns and @{$columns;}) { } 6 1 7
Condition66%2/3
$columns and @{$columns;}
!ll&&!rl&&r
106
MC/DC50%1/2
$columns and @{$columns;}
$columns @{$columns;}
Truth table66%2/3
A and B
A= $columnsB= @{$columns;}
ABresult
0X0
100
111
5298 6 my @cols = @{$columns};
5299 6 for my $row (@{$rows}) {
5300 23 ▶ my $key = join("\0", map { $row->{$_} // '' } @cols);
Condition50%1/2
$row->{$_} // ""
l!l
300
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table50%1/2
A
A= $row->{$_}
Aresult
11
00
5301 23 ▶ next if $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$key}++ 8 15 23
5302 15 push @result, { map { $_ => $row->{$_} } @cols };
5303 }
5304 } else {
5305 1 for my $row (@{$rows}) {
5306 5 ▶ my $key = join("\0", map { ($row->{$_} // '') } sort keys %{$row});
Condition50%1/2
$row->{$_} // ""
l!l
200
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table50%1/2
A
A= $row->{$_}
Aresult
11
00
5307 5 ▶ next if $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$key}++ 0 5 5
5308 5 push @result, $row;
5309 }
5310 }
5311 7 return \@result;
5312 }
5313  
5314 # _merge_criteria( \%base, \%extra ) -> \%merged
5315 # Purpose: Merge two criteria hashrefs for the same database column set.
5316 # Entry: %base is the permanent filter; %extra is the query-time criteria.
5317 # Exit: Returns a new hashref with both applied.
5318 # Merging rule: when both values for the same column are operator hashrefs
5319 # (e.g. { '>' => 60 } and { '<' => 365 }), the operators are combined
5320 # so both constraints apply simultaneously (AND semantics).
5321 # Otherwise the extra (query-time) value overwrites the base value.
5322 207 ▶sub _merge_criteria :Protected {
Subroutine _merge_criteria: called CC=5 SCAR=16.1
5323 207 my ($base, $extra) = @_;
5324 207 my %merged = %{$base};
5325 207 for my $col (keys %{$extra}) {
5326 76 ▶ if (exists $merged{$col}
Branch: 1 branch
BranchTrueFalseTotal
if (exists $merged{$col} and ref $merged{$col} eq 'HASH' and ref $extra->{$col} eq 'HASH') { } 30 46 76
Condition100%6/6
exists $merged{$col} and ref $merged{$col} eq "HASH" and ref $extra->{$col} eq "HASH"
!ll&&!rl&&r
341230
exists $merged{$col} and ref $merged{$col} eq "HASH"
!ll&&!rl&&r
26842
MC/DC100%3/3
exists $merged{$col} and ref $merged{$col} eq "HASH" and ref $extra->{$col} eq "HASH"
exists $merged{$col} ref $merged{$col} eq "HASH" ref $extra->{$col} eq "HASH"
Truth table100%4/4
A and B and C
A= exists $merged{$col}B= ref $merged{$col} eq "HASH"C= ref $extra->{$col} eq "HASH"
ABCresult
0XX0
10X0
1100
1111
5327 && ref($merged{$col}) eq 'HASH'
5328 && ref($extra->{$col}) eq 'HASH') {
5329 30 $merged{$col} = { %{ $merged{$col} }, %{ $extra->{$col} } };
5330 } else {
5331 46 $merged{$col} = $extra->{$col};
5332 }
5333 }
5334 207 return \%merged;
5335 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5336  
5337 # _copy_criteria( \%criteria ) -> \%copy
5338 # Purpose: Return a two-level deep copy of a single criteria hashref so that
5339 # post-construction mutation of the caller's hash cannot change the
5340 # stored filter. Operator sub-hashrefs (e.g. { '>' => 80 }) are
5341 # shallow-copied one additional level, matching the broadcast-copy
5342 # idiom used in _partition_criteria for join-column criteria.
5343 # Entry: $criteria is a hashref (may be undef).
5344 # Exit: Returns a new hashref; never returns the input reference itself.
5345 101 ▶sub _copy_criteria {
Subroutine _copy_criteria: called CC=4 SCAR=13.9
5346 101 my ($criteria) = @_;
5347 101 ▶ return {} unless $criteria && %{$criteria};
Branch: 1 branch
BranchTrueFalseTotal
unless $criteria and %{$criteria;} 6 95 101
Condition66%2/3
$criteria and %{$criteria;}
!ll&&!rl&&r
0695
MC/DC50%1/2
$criteria and %{$criteria;}
$criteria %{$criteria;}
Truth table66%2/3
A and B
A= $criteriaB= %{$criteria;}
ABresult
0X0
100
111
5348 return {
5349 map {
5350 $_ => ref($criteria->{$_}) eq 'HASH'
5351 59 ? { %{ $criteria->{$_} } } # shallow-copy operator sub-hashref
5352 96 ▶ : $criteria->{$_}
Branch: 1 branch
BranchTrueFalseTotal
ref $criteria->{$_} eq 'HASH' ? : 59 37 96
5353 95 } keys %{$criteria}
5354 };
5355 }
5356  
5357 # _copy_filters( \%filters ) -> \%copy
5358 # Purpose: Deep-copy the filters hashref (db_index => criteria_hashref) so
5359 # that post-construction mutation of the caller's hash cannot silently
5360 # bypass the inner-join row-security guarantee.
5361 # Entry: $filters may be undef.
5362 # Exit: Returns a new hashref; never returns the input reference itself.
5363 1301 ▶sub _copy_filters {
Subroutine _copy_filters: called CC=3 SCAR=11.0
5364 1301 my ($filters) = @_;
5365 1301 ▶ return {} unless $filters && %{$filters};
Branch: 1 branch
BranchTrueFalseTotal
unless $filters and %{$filters;} 1220 81 1301
Condition100%3/3
$filters and %{$filters;}
!ll&&!rl&&r
1219181
MC/DC100%2/2
$filters and %{$filters;}
$filters %{$filters;}
Truth table100%3/3
A and B
A= $filtersB= %{$filters;}
ABresult
0X0
100
111
5366 81 return { map { $_ => _copy_criteria($filters->{$_}) } keys %{$filters} };
5367 }
5368  
5369 # _msg( $i18n, $key, @sprintf_args ) -> $string
5370 # Purpose: Format a user-facing message, routing through the i18n object when
5371 # one is provided. Falls back to the built-in %MESSAGES dictionary.
5372 # Entry: $i18n may be undef. $key must be a key in %MESSAGES.
5373 # Exit: Returns the formatted string.
5374 218 ▶sub _msg :Protected {
Subroutine _msg: called CC=5 SCAR=16.1
5375 218 my ($i18n, $key, @args) = @_;
5376  
5377 218 ▶ if ($i18n && $i18n->can('translate')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i18n and $i18n->can("translate")) 4 214 218
Condition100%3/3
$i18n and $i18n->can("translate")
!ll&&!rl&&r
21134
MC/DC100%2/2
$i18n and $i18n->can("translate")
$i18n $i18n->can("translate")
Truth table100%3/3
A and B
A= $i18nB= $i18n->can("translate")
ABresult
0X0
100
111
5378 4 return $i18n->translate($key, @args);
5379 }
5380  
5381 my $fmt = $MESSAGES{$key}
5382 214 ▶ // sprintf($MESSAGES{error_unknown_message}, $key);
Condition100%2/2
$MESSAGES{$key} // sprintf($MESSAGES{"error_unknown_message"}, $key)
l!l
2122
MC/DC100%1/1
$MESSAGES{$key} // sprintf($MESSAGES{"error_unknown_message"}, $key)
$MESSAGES{$key}
Truth table100%2/2
A
A= $MESSAGES{$key}
Aresult
11
00
5383  
5384 214 ▶ return @args ? sprintf($fmt, @args) : $fmt;
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 163 51 214
5385 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5386  
5387 29 1;
5388  
5389 __END__
↑ Summary Join/Catalog.pm »