Join.pm

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