File Coverage

File:blib/lib/Database/Join.pm
Coverage:92.1%

linestmtbrancondsubtimecode
1package Database::Join;
2
3# ABSTRACT: Combined view across two or more Database::Abstraction objects
4
5
30
30
4527154
54
use 5.010001;
6
30
30
30
38
17
191
use strict;
7
30
30
30
32
22
500
use warnings;
8
30
30
30
1538
42815
66
use autodie qw(:all);
9
10
30
30
30
86032
17
538
use Carp qw(croak carp);
11
30
30
30
39
21
234
use File::Spec;
12
30
30
30
34
15
477
use List::Util qw(max);
13
30
30
30
3827
543125
254
use Log::Abstraction;
14
30
30
30
47
15
468
use Readonly;
15
30
30
30
35
18
374
use Scalar::Util qw(blessed looks_like_number);
16
30
30
30
2512
62595
253
use Object::Configure;
17
30
30
30
37
23
397
use Params::Get qw(get_params);
18
30
30
30
37
11
323
use Params::Validate::Strict qw(validate_strict);
19
30
30
30
1805
8390
73
use Sub::Protected;
20
21# Named-pair keys accepted by add_database; kept here so the guard and the
22# validate_strict schema cannot silently diverge.
23Readonly::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.
29Readonly::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).
35Readonly::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.
40Readonly::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.
46Readonly::Scalar my $MAX_PUSHDOWN_KEYS => 999;
47
48# Database::Abstraction's spelling of SQL IN.  It croaks on 'IN'.
49Readonly::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.
54my $_EMPTY_PRIMARY_ROW = [{}];
55
56# Valid aggregate functions for aggregate().  Lower-cased at validation time.
57Readonly::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.
60Readonly::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).
64Readonly::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
30
30
30
4465
33
88
use version; our $VERSION = version->declare('0.011.4');
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).
80my $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# ---------------------------------------------------------------------------
86Readonly::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 - 981
=head1 NAME

Database::Join - Read-only combined view across two or more Database::Abstraction objects

=head1 VERSION

Version 0.011.4

=head1 SYNOPSIS

B<Basic two-database join>

    use Database::Join;

    # Step 1: create each component database the normal way
    # See Database::Abstraction
    my $customers = Database::Customers->new(directory => '/data');
    my $loyalty   = Database::Loyalty->new(directory  => '/data');

    # Step 2: combine them on the shared key column 'entry'
    my $join = Database::Join->new(
        databases   => [ $customers, $loyalty ],
        join_column => 'entry',
    );

    # Step 3: query exactly as you would a single Database::Abstraction object
    my $all_rows  = $join->selectall_arrayref();
    my $vip_rows  = $join->selectall_arrayref(tier => 'gold');
    my $one_row   = $join->fetchrow_hashref(entry => 'C001');
    my $total     = $join->count();
    my $col_names = $join->columns();

B<Hiding internal columns>

    my $join = Database::Join->new(
        databases      => [ $customers, $loyalty ],
        join_column    => 'entry',
        remove_columns => [ 'internal_id', 'audit_ts' ],
    );
    # 'internal_id' and 'audit_ts' never appear in results or columns()

B<join_map: when the key column has different names in each database>

    # $cities  (index 0) has a column called 'statecode' -- matches join_column
    # $stnames (index 1) has a column called 'entry'     -- different name

    my $join = Database::Join->new(
        databases   => [ $cities,  $stnames ],
        #                index 0   index 1
        join_column => 'statecode',
        join_map    => { 1 => 'entry' },  # index 1 calls its join key 'entry'
    );

    # All returned rows use 'statecode'; 'entry' is never exposed
    my $rows = $join->selectall_arrayref();

B<filters: permanently restrict a database's visible rows>

    # Only show orders placed more than 60 days ago, without repeating
    # the criterion on every query call.
    my $join = Database::Join->new(
        databases   => [ $customers, $orders ],
        join_column => 'entry',
        filters     => { 1 => { age_days => { '>' => 60 } } },
    );

    my $rows = $join->selectall_arrayref();                 # all old orders
    my $vip  = $join->selectall_arrayref(tier => 'gold');   # old + gold tier

B<Inner and outer join types>

    my $inner = Database::Join->new(
        databases   => [ $customers, $loyalty ],
        join_column => 'entry',
        join_type   => 'inner',   # only keys present in BOTH databases
    );

    my $outer = Database::Join->new(
        databases   => [ $customers, $loyalty ],
        join_column => 'entry',
        join_type   => 'outer',   # all keys from EITHER database
    );

B<Building the view incrementally with add_database>

    my $join = Database::Join->new(
        databases   => [ $customers ],
        join_column => 'entry',
    );

    $join->add_database($loyalty)
         ->add_database($scores, remove_columns => ['raw_score']);

B<AUTOLOAD column shortcut>

    # Returns the 'name' value for entry 'C001' (scalar context)
    my $name = $join->name(entry => 'C001');

    # Returns all 'tier' values (list context)
    my @tiers = $join->tier();

B<aggregate(): GROUP BY across the merged view>

    # Count and total score per tier, highest total first
    my $rows = $join->aggregate(
        by       => ['tier'],
        measures => [
            { col => 'score', fn => 'sum',   as => 'total' },
            {                 fn => 'count', as => 'n'     },
        ],
        sort_by  => ['total', 'DESC'],
        having   => { total => { '>' => 100 } },
    );
    # => [ { tier => 'gold', total => 183, n => 2 }, ... ]

    # Grand total across the whole view (no 'by' key)
    my $summary = $join->aggregate(
        measures => [{ fn => 'count', as => 'n' }],
    );
    # => [ { n => 42 } ]

B<SQLite join backend for large datasets>

    # 'auto' (default): switches to SQLite automatically above the threshold
    my $join = Database::Join->new(
        databases      => [ $customers, $loyalty ],
        join_column    => 'entry',
        backend        => 'auto',          # default
        max_array_rows => 50_000,          # use SQLite when combined rows > 50,000
    );

    # Always use SQLite -- useful when you know the data is large
    my $join = Database::Join->new(
        databases   => [ $customers, $loyalty ],
        join_column => 'entry',
        backend     => 'sqlite',
        tmpdir      => '/fast/nvme/tmp',   # optional: faster temp disk
    );

    # Always use the original in-memory path
    my $join = Database::Join->new(
        databases   => [ $customers, $loyalty ],
        join_column => 'entry',
        backend     => 'array',
    );

=head1 DESCRIPTION

C<Database::Join> merges two or more L<Database::Abstraction> objects into a
single logical, read-only view.  Each component database is queried
independently through its own C<Database::Abstraction> interface.  The results
are combined using a shared key column (C<join_column>).
In effect, this means that you can view data from more than one database using
an intuitive, non-SQL interface.

Every storage format that C<Database::Abstraction> supports works as a
component database: CSV, PSV, TSV, SQLite, JSON, XML, XLSX, BerkeleyDB, HTML
URL, JSON URL, or any custom subclass.  Component databases may mix formats
within the same join.

The module exposes the same read-only API as C<Database::Abstraction>:
C<selectall_arrayref>, C<selectall_array>, C<fetchrow_hashref>, C<count>,
C<columns>, C<schema>, C<updated>, C<set_logger>, and the AUTOLOAD column
shortcut.  Callers do not need to know how many underlying databases are
involved.

Think of it as a virtual database table that is assembled on demand from
several real tables, one per component database.

B<Join backends>

By default (C<backend =E<gt> 'auto'>), C<Database::Join> first checks the
combined source row count.  For small datasets (up to C<max_array_rows>,
default 10,000 rows) it merges entirely in Perl memory.  For larger datasets it
automatically spills source rows into a temporary SQLite database and executes
a single SQL JOIN there, keeping peak RAM to roughly one times the source data
size instead of three.  You can also force either path unconditionally with
C<backend =E<gt> 'sqlite'> or C<backend =E<gt> 'array'>.

B<Key pushdown (array backend)>

Under a C<left> or C<inner> join, only secondary rows whose key is one of the
primary's can appear in the result.  So once the primary has been read, each
secondary that has no criterion on its join column is asked for just those
keys, as C<< { -in => [ ... ] } >> on its local join column, instead of being
read in full.  Joining a few hundred primary rows to a large secondary table
then costs a few hundred rows, not the whole table.  Pushdown is skipped when:

=over 4

=item * the join is C<outer>, which needs every secondary key;

=item * the primary has no rows, or more than 999 keys (the bind-parameter
limit of older SQLite builds; past that, reading the whole table is no worse);

=item * the query already has a criterion on the join column, which then
stands as given;

=item * the secondary's C<selectall_arrayref> is not
C<Database::Abstraction>'s own.  A subclass that overrides it, or another
object implementing the interface, may not understand C<-in>.

=back

If the secondary croaks on the C<-in> query, it is read in full instead.  The
result is the same either way.  Pushdown only narrows what is fetched; it never
counts as the secondary's own criterion, so it can't turn a C<left> join into
an C<inner> one.

=head2 Join semantics

The C<join_type> parameter controls what happens when a particular key value
exists in some component databases but not all:

=over 4

=item C<left> (the default)

All rows from the I<primary> (first) database are returned.  Columns from
subsequent databases are included where a matching row is found, and simply
absent from the hashref where there is no match.  If you are familiar with
SQL, this is a LEFT OUTER JOIN on the first table.

=item C<inner>

Only rows whose join-column value is present in I<every> component database
are returned.  This is equivalent to a SQL INNER JOIN.

=item C<outer>

Every join-column value found in I<any> component database is returned.
Columns from databases that do not have that key value are absent from the
merged row.  This is a FULL OUTER JOIN.

=back

B<Important override rule:> whenever you pass a query criterion for a column
that belongs to a secondary database, that database automatically acts as an
inner-join partner for that query only -- regardless of C<join_type>.  This
gives WHERE-clause semantics.  For example, if you have a LEFT join but query
C<< tier => 'gold' >> on a secondary database, only rows whose secondary entry
has tier = 'gold' are returned (rows with no secondary entry are excluded, just
as a WHERE clause would exclude them).

=head2 Column ownership and routing

At construction time, C<Database::Join> calls C<columns()> on each component
database and builds an internal index that maps every column name to the
database that owns it.

When you pass criteria to a query method, each key-value pair is automatically
routed to the right database.  You never need to say which database a column
belongs to.

The C<join_column> is special: criteria on it are broadcast to I<all>
databases so that each database fetches only the relevant rows before the
in-memory merge.

When the same non-join column name exists in more than one database, the
I<last> database in the C<databases> array wins by default: its value
overwrites earlier ones in merged rows.  Use C<collision_prefix> to
preserve both values under distinct names instead.

=head1 LIMITATIONS

=over 4

=item Memory usage (array backend)

When C<backend> is C<'array'> (or C<'auto'> and the dataset is small), all
matching rows are fetched into Perl memory.  Key pushdown (see
L</DESCRIPTION>) limits a secondary to the primary's keys under C<left> and
C<inner> joins, but an C<outer> join, or a primary with more than 999 keys,
still reads every secondary row.  Peak RAM is roughly three times
the source data size.  For large datasets use C<backend =E<gt> 'sqlite'>, or
leave C<backend =E<gt> 'auto'> and set C<max_array_rows> appropriately.

=item SQLite backend uses a persistent cache file

When the SQLite path is active, a single C<.db> file with a randomly generated
name (chosen by C<File::Temp> to avoid collisions) is created in C<tmpdir> the
first time a query runs on a given C<Database::Join> object.  Source data is
spilled into that file once; subsequent queries against the same object reuse
the file without re-fetching the source data.

The cache is automatically invalidated and rebuilt whenever any source
database's C<updated()> timestamp changes (indicating new data), or when
C<add_database()> is called.

The file is deleted when the C<Database::Join> object is destroyed (typically
when it goes out of scope).  At any given moment no more than one such file
exists per object.  The directory must be writable and have enough free space
for the full source data (once, not per-query).

=item No chained builder or raw SQL

C<query()> and C<execute()> are not implemented.  Use C<selectall_arrayref>
or C<fetchrow_hashref> instead.

=item Single-column equi-join only

Joining on more than one column simultaneously, or on expressions, is not
supported.  When the join key has different names in different databases,
use C<join_map> to declare each database's local column name.

=item Sort order

Results are sorted ascending by C<join_column> by default.  Pass
C<< sort_by => 'colname' >> (or C<< sort_by => ['colname', 'DESC'] >>)
to any query method to override this.  The array path uses string comparison
(C<cmp>); for accurate numeric ordering on large datasets use the SQLite
backend, which sorts natively by type.

=item count() on the array backend fetches all rows

On the array backend, C<count()> executes the full in-memory join and counts
the resulting rows in Perl; no C<COUNT(*)> is pushed to the component
databases.  On the SQLite backend, C<count()> executes a C<SELECT COUNT(*)>
SQL query against the cached join tables, avoiding a full row transfer.

=back

=head1 COMMON PITFALLS

=over 4

=item The join_column must exist in every component database

If even one database is missing the join key column, C<new()> (or
C<add_database()>) will C<croak> immediately.  Use C<join_map> when the
column has a different local name in some databases.

=item Criteria on a removed column are silently dropped

If you call C<remove_column('tier')> and later query
C<< selectall_arrayref(tier => 'gold') >>, the criterion is ignored (with a
C<carp> warning) and all rows are returned.  Always pass criteria before
removing columns, or restructure your code to avoid this.

=item You cannot remove the join column

C<< $join->remove_column($join->join_column) >> will C<croak>.  The join key
is required for the merge to work.

=item Left join does not guarantee all columns are populated

Under a LEFT join, rows from the primary database that have no matching row
in a secondary database will be returned with I<no keys> from that secondary
database.  Accessing C<< $row->{score} >> on such a row returns C<undef> --
not zero, not an empty string.  Always test C<defined $row->{score}> rather
than just C<$row->{score}> when the secondary match is optional.

=item Filters act as inner-join partners

Any database that has a C<filters> entry is promoted to an inner-join partner,
regardless of C<join_type>.  A row whose join-key value does not appear in
the filtered database's result is removed from the merged output entirely, not
merely missing its secondary columns.  This is intentional but can be
surprising if you expected LEFT join semantics.

=item Criteria-merging replaces scalar filters

When both a base filter and a query criterion target the same column, and both
are operator hashrefs (e.g. C<< { '>' => 60 } >>), the operators are combined
(AND semantics).  But if the query criterion is a plain scalar (e.g.
C<< score => 75 >>), it I<replaces> the base filter for that column entirely --
the base filter is ignored for that query.

=item AUTOLOAD sees the full merged join when filters or join_map are active

When either C<filters> or C<join_map> is in effect, the AUTOLOAD shortcut
(C<< $join->columnname(...) >>) runs the full join query rather than
delegating directly to the owning database.  This is necessary for correctness
but means the result respects all active filters and join-key translations,
which may differ from what the owning database would return on its own.

=item Duplicate column names: last database wins (unless collision_prefix is set)

When two component databases each have a column called C<notes>, the second
database's value silently overwrites the first in every merged row.  Use
C<collision_prefix => { 1 => 'right' }> to publish the second database's
C<notes> as C<right.notes> so both values survive, or use C<remove_columns>
(or C<remove_column>) to drop the unwanted duplicate entirely.

=item Mutating the filters hashref after construction has no effect

C<Database::Join> deep-copies the C<filters> hashref (and any C<filter>
passed to C<add_database>) at the moment of construction.  The original hashref
you passed in is never stored.  If you later modify it -- for example, to
tighten or loosen a filter criterion -- the joined view is I<not> affected.
Construct a new C<Database::Join> object, or use a component
C<Database::Abstraction> that supports dynamic filter modification.

=item auto mode may always use the array path for some DAs

C<backend =E<gt> 'auto'> counts rows cheaply only when each component database
either implements C<dbi_source()> (SQLite-backed) or directly defines a
C<count()> method in its own package.  A DA that merely I<inherits> C<count()>
from C<Database::Abstraction> is treated as uncountable, because the parent
class C<count()> expects a key argument and behaves differently from a
"return total row count" function.  In that case C<Database::Join>
conservatively uses the array path for the whole query, even if the dataset is
large.  To opt in to the SQLite path for such a DA, either add your own
C<count()> override that returns the total row count, implement C<dbi_source()>,
or use C<backend =E<gt> 'sqlite'> unconditionally.

=item dbi_source() ATTACH is unconditional - query-time criteria go into WHERE

When a component database implements C<dbi_source()>, C<Database::Join> always
uses the zero-copy ATTACH path, I<even when the current query includes criteria
for columns in that database>.  The criteria are translated into parameterised
SQL C<WHERE> clauses applied against the ATTACHed table; no row-level copy is
performed.  (Prior to 0.005.0 the presence of any query-time criteria would
force a spill; that restriction has been removed.)

=item Broadcast join-column criterion does not force secondaries into inner-join

When a caller passes a join-column criterion (e.g. C<entry =E<gt> 'k1'>),
C<Database::Join> broadcasts it to all component databases so each DA can
filter its fetch to the requested key.  Prior to 0.006.0 this broadcast was
incorrectly counted as "having criteria" for secondary databases, causing
C<left> and C<outer> joins to silently behave as C<inner> joins when a
join-column criterion was present.  The fix: only non-join-column criteria
(e.g. column filters from the caller or base C<filters =E<gt> {...}>) promote
a secondary to inner-join status.  The broadcast itself is now a transparent
key-range selector that does not affect join semantics.

=item LIKE and NOT LIKE work on the SQLite path; other pattern operators do not yet

C<LIKE>, C<NOT LIKE>, C<IN>, and C<NOT IN> are fully supported on the SQLite
backend.  C<LIKE>/C<NOT LIKE> take a scalar pattern; C<IN>/C<NOT IN> take an
arrayref of values.  All are injection-safe because values are passed as bind
parameters, never interpolated.

    # LIKE
    my $rows = $join->selectall_arrayref(name => { LIKE => 'A%' });

    # IN
    my $rows = $join->selectall_arrayref(tier => { IN => ['gold', 'silver'] });

    # NOT IN
    my $rows = $join->selectall_arrayref(tier => { 'NOT IN' => ['bronze'] });

C<IN> with an empty arrayref matches no rows (SQL semantics: C<IN ()> is
always false).  C<NOT IN> with an empty arrayref matches all rows (no
constraint added).

C<IS NULL> and C<IS NOT NULL> are supported on the SQLite backend using an
explicit operator hashref:

    my $rows = $join->selectall_arrayref(score => { 'IS NULL'     => undef });
    my $rows = $join->selectall_arrayref(score => { 'IS NOT NULL' => 1    });

The hashref value is ignored; only the key selects the operator.  A bare
C<undef> criterion value (C<< score => undef >>) also generates C<IS NULL>
on the SQLite path.  Note: on the in-memory array path, the component DA
may treat an C<undef> criterion value as C<< no filter >> rather than
C<IS NULL>, so use the explicit hashref form for consistent behaviour
across backends.

Any operator not in the supported set is skipped on the SQLite path with a
C<carp> warning.  The array path forwards all operators to the component DA
unchanged, which may or may not honour them.

=item Temp file directory must be writable and have free space

The SQLite path creates one temporary C<.db> file per C<Database::Join> object
in C<tmpdir> (default: C<File::Spec-E<gt>tmpdir()>, usually C</tmp> on Unix).
The filename is randomly generated by C<File::Temp> -- you cannot predict it,
only the directory is under your control.  The file is created on the first
query and kept alive until the object is destroyed; it is not re-created on
every query call.  If the directory is not writable, or the filesystem is full,
the call will C<croak> with C<error_sqlite_connect>.  Check permissions and
free space if you see that error.

=item C<join =E<gt>> criteria are not supported

C<Database::Abstraction> accepts a C<join =E<gt> { table =E<gt> ..., on =E<gt> ... }>
key in its criteria hashrefs to express an SQL JOIN within a single table.
C<Database::Join> cannot route this to a component DA meaningfully: the merged
view has no concept of a single underlying table.  Passing C<join =E<gt>> to any
query method will C<croak> with C<error_join_criterion>.

B<Fix:> Model the joined table as a separate C<Database::Abstraction> object and
add it to the C<databases =E<gt> []> list.  Use C<join_column> or C<join_map> to
specify the shared key.

=item aggregate(): omitting C<by> gives a grand total, not an error

Calling C<aggregate()> without a C<by> key (or with C<< by => [] >>) does
I<not> croak.  It returns a single-element arrayref containing one row with
all the computed measure aliases.  This is a grand total over the entire view
(possibly filtered by any extra criteria you pass).

    my $total = $join->aggregate(measures => [{ fn => 'count', as => 'n' }]);
    # $total->[0]{n} is the total row count

If you expected multiple rows and got one, you probably forgot the C<by> key.

=item aggregate(): non-numeric values behave differently across backends

On the array backend (C<backend =E<gt> 'array'>), any non-numeric value in a
column targeted by C<sum> or C<avg> is I<skipped> (not counted, not coerced),
and a C<carp> warning C<warn_aggregate_non_numeric> is emitted.  On the SQLite
backend, non-numeric values are silently coerced to C<0.0> via SQL C<CAST>.
The two backends therefore produce different numeric totals when the data
contains non-numeric values.  Clean your data first if you need consistent
results across backends, or choose a backend explicitly.

=item aggregate(): C<BETWEEN> is not supported in C<having>

The C<having> hashref uses the same operator vocabulary as C<selectall_arrayref>,
which does not include C<BETWEEN>.  Write a range as two explicit constraints:

    # Correct
    having => { total => { '>=' => 10, '<=' => 50 } }

    # Wrong -- will croak with error_aggregate_having_operator
    having => { total => { BETWEEN => [10, 50] } }

=item aggregate(): C<count> without C<col> counts all rows, not distinct non-NULL values

A measure with C<< fn => 'count' >> and no C<col> key emits C<COUNT(*)> on the
SQLite backend (or counts every row in Perl).  This counts rows that have
C<undef>/NULL in other columns too.  To count only rows where a specific
column is non-NULL, or to count distinct values, use C<count_distinct>:

    # Count rows with a non-NULL 'score' (one way -- use a pre-filter)
    measures => [{ col => 'score', fn => 'count_distinct', as => 'distinct_scores' }]

=item aggregate(): the result is never cached

Unlike C<selectall_arrayref> (which benefits from the SQLite file cache on
repeated identical calls), C<aggregate()> always re-executes.  If your
aggregation is expensive and the data changes infrequently, cache the result
yourself using C<updated()> as a staleness signal.

=item distinct => 1 without columns returns full rows, not a column projection

C<< distinct => 1 >> alone deduplicates on I<all> columns of the merged row.
If you want a distinct list of values for a single column (e.g. all unique
tiers), you B<must> supply C<< columns => ['tier'] >> as well.  Without
C<columns>, every column participates in the key used to detect duplicates,
which means two rows that differ in any column (e.g. C<entry>) are never
considered duplicates, and the result will be the same as without C<distinct>.

=item distinct => 1 with columns projects rows to those columns

When C<columns> is supplied alongside C<distinct>, each returned row contains
I<only> the named columns -- all other columns are dropped.  The projection
happens before deduplication, so the result set may be smaller than the full
merged row count.  If you need the full row I<and> want to know unique values,
run two separate queries or post-process in Perl.

=item mandatory_filters must never come from user-supplied input

The predicates in C<mandatory_filters> form an enforcement boundary.  They must
come from a trusted server-side source (a session store, a policy table, or
hard-coded application configuration) -- never from URL parameters, form fields,
HTTP headers, or other user-controlled input.  A hostile user who can control
a mandatory_filters predicate can widen it to C<{ col => 'status', op => 'ne',
val => 'NONEXISTENT' }> and receive all rows regardless of status.

=item mandatory_filters uses string comparison on the array path

On the array backend, all C<mandatory_filters> comparisons (including C<lt>,
C<lte>, C<gt>, C<gte>) are I<lexicographic string comparisons>, not numeric.
C<< { col => 'score', op => 'gt', val => 9 } >> will match a score of C<'10'>
only if C<'10' gt '9'> is true -- which it is not (C<'1' lt '9'>).  Use the
SQLite backend (C<< backend => 'sqlite' >>) when numeric comparisons are needed,
as SQLite uses the column's declared type for ordering.

=back

=head1 METHODS

=head2 new

=head3 SYNOPSIS

    my $join = Database::Join->new(
        databases         => [ $db1, $db2 ],
        join_column       => 'entry',
        join_type         => 'left',
        join_map          => { 1 => 'local_col' },
        filters           => { 1 => { score => { '>' => 60 } } },
        base_criteria     => { active => 1 },
        mandatory_filters => [{ col => 'region', op => 'eq', val => 'West' }],
        collision_prefix  => { 1 => 'right' },
        remove_columns    => [ 'email', 'internal_id' ],
        backend           => 'auto',        # 'auto' | 'sqlite' | 'array'
        max_array_rows    => 10_000,        # threshold for 'auto' mode
        tmpdir            => '/tmp',        # directory for temp SQLite file
        logger            => $log,
        i18n              => $locale,
    );

=head3 DESCRIPTION

Constructs and returns a new C<Database::Join> object.

Each element of C<databases> must be an already-instantiated subclass of
C<Database::Abstraction>.  The constructor calls C<columns()> on every
database to build an internal column-routing table and verifies that
C<join_column> (or its local alias from C<join_map>) is present in each one.

Columns listed in C<remove_columns> are hidden immediately: they do not appear
in C<columns()>, C<schema()>, or any returned row hashref.  This is equivalent
to calling C<remove_column> once per name after construction.

=head3 API SPECIFICATION

=head4 Input

    databases      => { type => 'arrayref', required => 1 }
                      # One or more Database::Abstraction subclass objects.
                      #
                      # DOMAIN -- EP valid:   non-empty arrayref of blessed DA subclasses.
                      # DOMAIN -- EP invalid: scalar, hashref, or absent => croak.
                      # DOMAIN -- BVA size:   minimum 1 element; no documented upper bound.
                      # DOMAIN -- BVA elem:   each element must pass isa('Database::Abstraction').

    join_column    => { type => 'string',   optional => 1, default => 'entry' }
                      # The column name shared by all databases (the join key).
                      #
                      # DOMAIN -- EP valid:   any non-empty string present in every component DA.
                      # DOMAIN -- EP invalid: column absent from any DA => croak join_col_missing.
                      # DOMAIN -- BVA:        empty string '' is treated as a column name and
                      #                       will croak if (as expected) it is absent from every DA.
                      # DOMAIN -- NOTE:       matching is case-sensitive and exact.

    join_type      => { type => 'string',   optional => 1, default => 'left',
                        enum => ['inner', 'left', 'outer'] }
                      # Controls which keys appear in the result when not all
                      # databases share the same key values.
                      #
                      # DOMAIN -- EP valid:   exactly 'inner', 'left', or 'outer'.
                      # DOMAIN -- EP invalid: any other string including 'INNER', 'LEFT',
                      #                       'OUTER' (enum check is case-sensitive), 'cross',
                      #                       or '' => croak from validate_strict.

    join_map       => { type => 'hashref',  optional => 1 }
                      # Zero-based database index => local column name.
                      # See the join_map section for full details.
                      #
                      # DOMAIN -- EP valid:   hashref values must be plain strings.
                      # DOMAIN -- EP invalid: reference value (hashref, arrayref, coderef, etc.)
                      #                       => croak; the guard prevents heap-address leakage.
                      # DOMAIN -- BVA:        out-of-range keys (beyond the databases array) are
                      #                       silently ignored.

    filters        => { type => 'hashref',  optional => 1 }
                      # Zero-based database index => criteria hashref.
                      # Permanent row restrictions on individual databases.
                      # See the filters section for full details.

    base_criteria  => { type => 'hashref',  optional => 1 }
                      # Column name => value hashref.
                      # Permanent criteria applied to every query, specified by
                      # column name rather than database index.  Each key must
                      # be a column that appears in the merged view (or the
                      # join_column); each value is a plain scalar or an
                      # operator hashref in the same format as
                      # selectall_arrayref accepts.  Criteria are automatically
                      # routed to the database that owns each column (same
                      # routing used by selectall_arrayref).
                      # Equivalent to filters but more convenient when you know
                      # the column name but not which database index owns it.
                      # When a column appears in both base_criteria and filters,
                      # the filters entry takes precedence.
                      # See the base_criteria section for full details.
                      #
                      # DOMAIN -- EP valid:   hashref of column-name => scalar or
                      #                       operator-hashref pairs.  Unknown column
                      #                       names emit warn_unknown_column (carp)
                      #                       and are silently dropped.
                      # DOMAIN -- EP invalid: non-hashref value => croak from
                      #                       validate_strict.
                      # DOMAIN -- BVA:        {} empty hashref is a safe no-op.

    collision_prefix => { type => 'hashref', optional => 1 }
                      # Zero-based database index (>0) => prefix string.
                      # When a secondary database has a column that collides
                      # with a column already present in the merged view, the
                      # secondary column is published as "$prefix.$col" instead
                      # of silently overwriting the earlier value.
                      # Index 0 entries are silently ignored.
                      # Omitting this parameter preserves the original
                      # last-database-wins behaviour.
                      # See the collision_prefix section for full details.
                      #
                      # DOMAIN -- EP valid:   absent or {} => last-database-wins (no change).
                      # DOMAIN -- EP valid:   { N => 'prefix' } where N > 0 => colliding
                      #                       columns from DB[N] published as "$prefix.$col";
                      #                       non-colliding columns from the same DB added plain.
                      # DOMAIN -- EP note:    index-0 entries are silently ignored.
                      # DOMAIN -- Invariant:  join_column is never prefixed regardless of
                      #                       collision_prefix configuration.

    remove_columns => { type => 'arrayref', optional => 1 }
                      # Column names to hide from the merged view.
                      #
                      # DOMAIN -- EP valid:   arrayref of any strings; non-existent columns
                      #                       are silently ignored (idempotent).
                      # DOMAIN -- EP invalid: join_column itself => croak remove_join_col.
                      # DOMAIN -- BVA:        [] empty arrayref is a safe no-op.

    backend        => { type => 'string',   optional => 1, default => 'auto',
                        enum => ['array', 'sqlite', 'auto'] }
                      # Controls which join strategy is used.
                      #   'auto'   -- (default) use 'array' when combined source row count
                      #              <= max_array_rows, 'sqlite' otherwise.
                      #   'sqlite' -- always spill to a temporary SQLite database.
                      #   'array'  -- always use the in-memory merge path.
                      #
                      # DOMAIN -- EP valid:   'array', 'sqlite', or 'auto' (case-sensitive).
                      # DOMAIN -- EP invalid: any other string => croak error_invalid_backend.
                      # DOMAIN -- Default:    'auto'.

    max_array_rows => { type => 'integer',  optional => 1, default => 10_000 }
                      # Row-count threshold for 'auto' mode.  When the combined
                      # source row count exceeds this value, the SQLite path is used.
                      # Ignored when backend is 'array' or 'sqlite'.
                      #
                      # DOMAIN -- EP valid:   any non-negative integer.
                      # DOMAIN -- BVA:        0 means always use SQLite (all counts exceed 0).
                      # DOMAIN -- Default:    10,000.

    tmpdir         => { type => 'string',   optional => 1 }
                      # Directory for the per-call temporary SQLite database file.
                      # The file is created securely by File::Temp and removed when
                      # the query completes.  Ignored when backend is 'array'.
                      #
                      # DOMAIN -- EP valid:   any writable directory path string.
                      # DOMAIN -- EP absent:  uses File::Spec->tmpdir() (system temp dir).

    parallel       => { type => 'integer',  optional => 1, default => 0 }
                      # When set to 1 and the join has more than 2 databases (primary +
                      # 2 or more secondaries), secondary DA fetches are issued in
                      # parallel Perl threads.  Requires the 'threads' module; falls
                      # back to sequential with a carp warning when unavailable.
                      # Has no effect on the SQLite backend (which uses a single SQL
                      # JOIN).  DBI-backed DAs are not thread-safe by default; only
                      # enable this for in-memory or otherwise thread-safe DA backends.
                      #
                      # DOMAIN -- EP valid:   0 (sequential, default) or 1 (parallel).
                      # DOMAIN -- EP invalid: any other integer is treated as truthy/falsy.
                      # DOMAIN -- Default:    0.

    autoload_pk     => { type => 'string',   optional => 1 }
                      # The column name used as the positional-argument key when
                      # AUTOLOAD performs a full join query (i.e. when join_map or
                      # filters is active).  Calling $join->col('value') with a bare
                      # scalar maps that scalar to { autoload_pk => 'value' } before
                      # routing through the merged view.
                      #
                      # Defaults to join_column when omitted.  Override when the
                      # primary DA's natural lookup key differs from join_column -
                      # for example, when join_column is 'statecode' but you want to
                      # look up by city name ('entry').
                      #
                      # DOMAIN -- EP valid:   any string that is a visible column in
                      #                       the merged view (checked at call time by
                      #                       _partition_criteria; unknown names are
                      #                       carp'd and dropped).
                      # DOMAIN -- EP absent:  defaults to join_column.

    mandatory_filters => { type => 'arrayref', optional => 1 }
                      # Arrayref of {col, op, val} predicate hashrefs.
                      # These filters are applied to every query result regardless
                      # of what criteria the caller supplies.  They cannot be
                      # overridden, suppressed, or circumvented at query time.
                      # Each predicate must supply:
                      #   col -- a column name present in the merged view
                      #   op  -- one of: eq, ne, lt, lte, gt, gte, like, contains
                      #   val -- the comparison value (plain scalar)
                      # On the array backend: applied as a Perl-side grep after the
                      # in-memory merge, before sort/limit/offset.
                      # On the SQLite backend: injected as parameterised WHERE clauses
                      # into the per-call SQL query.
                      #
                      # SECURITY: Never set this from URL parameters or any
                      # user-supplied value.  Predicates must come from the
                      # server-side session or policy store only.
                      #
                      # DOMAIN -- EP valid:   [] empty arrayref => no constraint (safe no-op).
                      # DOMAIN -- EP valid:   arrayref of {col, op, val} hashrefs where
                      #                       col is in the merged view and op is supported.
                      # DOMAIN -- EP invalid: element is not a hashref, or is missing
                      #                       col/op/val => croak error_mandatory_filter_ref.
                      # DOMAIN -- EP invalid: col not in merged view => croak error_mandatory_filter_col.
                      # DOMAIN -- EP invalid: op not in supported set => croak error_mandatory_filter_op.
                      # DOMAIN -- ops:        eq (string eq), ne (string ne),
                      #                       lt/lte/gt/gte (string comparison),
                      #                       like (SQL LIKE pattern with % and _),
                      #                       contains (substring match, equivalent to LIKE %val%).

    logger         => { type => 'object',   optional => 1 }
                      # Logger object propagated to all component databases.

    i18n           => { type => 'object',   optional => 1 }
                      # Localisation object with a translate($key, @args) method.

=head4 Output

    A blessed Database::Join object.

=head3 EXAMPLE

    # Customers database: entry | name | email
    # Loyalty   database: entry | tier | points

    my $join = Database::Join->new(
        databases      => [ $customers, $loyalty ],
        join_column    => 'entry',
        join_type      => 'inner',            # only customers who also have loyalty records
        remove_columns => [ 'email' ],        # hide PII from query results
        filters        => { 1 => { points => { '>' => 0 } } }, # ignore zero-point records
    );

    my $rows = $join->selectall_arrayref();
    # Each row: { entry => ..., name => ..., tier => ..., points => ... }
    # 'email' is absent. Zero-point loyalty records are excluded.

=head3 PSEUDOCODE

    validate all parameters with validate_strict
    croak if databases is empty
    croak if any element of databases is not a Database::Abstraction subclass
    bless the object with all fields initialised
    call _build_col_index to map every column to its owning database
        and verify join_column presence in each database
    if base_criteria given:
        partition base_criteria by column ownership into per-db slices
        for each database with a non-empty slice:
            merge the slice into _filters[i]
            (explicit filters win on plain-scalar conflicts)
    if mandatory_filters given:
        for each predicate in mandatory_filters:
            croak error_mandatory_filter_ref if predicate is not a {col, op, val} hashref
            croak error_mandatory_filter_col if col is not in the merged view
            croak error_mandatory_filter_op  if op is not in the supported set
        store shallow copies of all validated predicates in _mandatory_filters
    for each column in remove_columns: call remove_column
    return the new object

=head3 MESSAGES

    error_no_databases           -- databases arrayref was empty
    error_invalid_db             -- an element of databases is not a D::A subclass
    error_join_col_missing       -- join_column (or its join_map alias) not found in a database
    error_invalid_backend        -- backend value is not 'array', 'sqlite', or 'auto'
    error_sqlite_connect         -- temporary SQLite database could not be created (backend='sqlite'/'auto')
    error_mandatory_filter_ref   -- a mandatory_filters element is not a hashref with col, op, and val keys
    error_mandatory_filter_col   -- a mandatory_filters element names a column not in the merged view
    error_mandatory_filter_op    -- a mandatory_filters element uses an unsupported op value
    warn_schema_type_mismatch    -- (carp) a shared column has different types across databases;
                                    use collision_prefix to preserve both values

=cut
982
983sub new {
984
1364
2110743
        my ($class, @args) = @_;
985
986
1364
8714
        my $p = validate_strict(
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
1344
1344
399791
1495
                unless @{ $p->{databases} };
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
1329
843
        my $caller_logger = $p->{logger};
1027
1329
721
        my $caller_i18n   = $p->{i18n};
1028
1029
1329
2138
        $p = Object::Configure::configure($class, $p);
1030
1031
1329
1329
1983691
1743
        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
2431
7908
                            && $p->{databases}[$i]->can('columns');
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
1314
1828
        my $primary_pk = $p->{autoload_pk} // $p->{join_column};
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
1314
2327
                _parallel         => $p->{parallel} // 0,
1069                _mandatory_filters => [],   # validated and replaced below after _build_col_index
1070        }, $class;
1071
1072
1314
1994
        $self->_build_col_index();
1073
1285
1224
        $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
976
        if (my $mf = $p->{mandatory_filters}) {
1081
15
5
                my @validated;
1082
15
15
11
6
                for my $j (0 .. $#{$mf}) {
1083
15
10
                        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
35
                                    && exists $pred->{val};
1089                        croak $self->_err('error_mandatory_filter_col', $j, $pred->{col})
1090
13
27
                                unless exists $self->{_col_db}{ $pred->{col} };
1091                        croak $self->_err('error_mandatory_filter_op', $j, $pred->{op})
1092
12
23
                                unless $MANDATORY_FILTER_OPS{ $pred->{op} };
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
11
46
15
                        my %p = %{$pred};
1097
11
13
                        if ($p{op} eq 'like') {
1098                                my $re = join('', map {
1099
2
3
                                        $_ eq '%' ? '.*' : $_ eq '_' ? '.' : quotemeta($_)
1100
1
2
                                } split //, $p{val});
1101
1
10
                                $p{_re} = qr/\A$re\z/s;
1102                        }
1103
11
7
                        push @validated, \%p;
1104                }
1105
11
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
877
        if (my $bc = $p->{base_criteria}) {
1114
9
9
                my $partitioned = $self->_partition_criteria(_copy_criteria($bc));
1115
9
9
9
7
                for my $i (0 .. $#{ $self->{_dbs} }) {
1116
18
18
9
14
                        next unless %{ $partitioned->[$i] };
1117                        $self->{_filters}{$i} = _merge_criteria(
1118                                $partitioned->[$i],
1119
8
13
                                $self->{_filters}{$i} // {},
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
902
        if (my $log = $self->{_logger}) {
1128
3
3
0
5
                $_->set_logger($log) for @{ $self->{_dbs} };
1129        }
1130
1131        # Apply column removals requested in the constructor
1132
1281
861
        if (my $rc = $p->{remove_columns}) {
1133
13
13
9
23
                $self->remove_column($_) for @{$rc};
1134        }
1135
1136
1279
1778
        return $self;
1137}
1138
1139# ---------------------------------------------------------------------------
1140# Public API (mirrors Database::Abstraction)
1141# ---------------------------------------------------------------------------
1142
1143 - 1913
=head2 join_map - joining on differently-named columns

By default every component database must have a column whose name matches
C<join_column>.  If a database uses a different local name for the join key,
declare the mapping with C<join_map>.

C<join_map> is a hashref.  Each B<key> is the B<zero-based position> of a
database in the C<databases> array (0 = first, 1 = second, and so on).  Each
B<value> is the name that B<that particular database> uses for the join key.

Databases not listed in C<join_map> are assumed to already have a column
named C<join_column> and need no entry.

Throughout the merged view the join key is I<always> referred to by the name
given in C<join_column>.  The local alias is never exposed in returned rows,
in C<columns()>, or in C<schema()>.

B<When do you need join_map?>

You need C<join_map> when you have two tables like:

    cities table  : entry (the city name) | statecode
    stnames table : entry (the state code) | state

Here you want to join cities.statecode to stnames.entry.  You choose
C<< join_column => 'statecode' >> as the canonical name, but stnames calls
that same concept C<entry>, so you declare:

    join_map => { 1 => 'entry' }  # stnames (index 1) calls it 'entry'

B<Example>

    #                        index 0     index 1
    my @databases = (       $cities,    $stnames  );
    #  join key column:    'statecode'  'entry'
    #  join_column:        'statecode' (chosen canonical name)
    #  stnames differs, so declare the alias:

    my $join = Database::Join->new(
        databases   => \@databases,
        join_column => 'statecode',
        join_map    => { 1 => 'entry' },
    );

    my $rows = $join->selectall_arrayref();
    # Each $row has keys: entry (city), statecode, state
    # 'entry' from stnames is never exposed directly.

    my $row = $join->fetchrow_hashref(statecode => 'CA');

B<Using add_database instead>

If you build the join incrementally with C<add_database>, pass
C<join_column> directly to that call instead of using C<join_map>:

    my $join = Database::Join->new(
        databases   => [ $cities ],
        join_column => 'statecode',
    );
    $join->add_database($stnames, join_column => 'entry');

This is exactly equivalent to the C<join_map> form above.

=head2 filters - permanent per-database row filters

C<filters> lets you restrict a component database to a subset of its rows
permanently, without repeating the criterion on every query call.

Think of it as telling the join: "whenever you query this database, always
add these extra conditions".  Callers never need to specify the restriction
themselves and can never accidentally omit it.

C<filters> is a hashref.  Each B<key> is the B<zero-based position> of a
database in the C<databases> array (same numbering as C<join_map>).  Each
B<value> is a criteria hashref in the same format as C<selectall_arrayref>
accepts.

B<Key-set semantics>

A filtered database always acts as an inner-join partner, regardless of the
C<join_type> setting.  Any join-key value that does not pass the filter is
excluded from the merged output entirely -- not just missing its secondary
columns.  This ensures the filter genuinely restricts the view rather than
simply hiding a few fields.

B<Criteria merging>

When a query call also passes a criterion for a column that already has a base
filter, the two constraints are combined:

=over 4

=item *

When both the base filter value and the query criterion are operator hashrefs
(e.g. C<< { '>' => 60 } >> and C<< { '<' => 365 } >>), their operators are
merged: I<both> constraints apply simultaneously (AND semantics).

=item *

When either value is a plain scalar, or the operators conflict, the
query-time criterion wins and the base filter for that column is ignored for
that one call.

=back

B<Example -- only show orders placed more than 60 days ago>

    my $join = Database::Join->new(
        databases   => [ $customers, $orders ],
        join_column => 'entry',
        filters     => { 1 => { age_days => { '>' => 60 } } },
    );

    # Every query automatically sees only old orders
    my $rows = $join->selectall_arrayref();

    # Additional criteria layer on top -- gold tier AND old order
    my $vip  = $join->selectall_arrayref(tier => 'gold');

    # Range intersection: age_days > 60 AND age_days < 365
    my $mid  = $join->selectall_arrayref(age_days => { '<' => 365 });

When using C<add_database>, pass C<filter> (singular) to set the base
criteria for the new database:

    $join->add_database($orders, filter => { age_days => { '>' => 60 } });

=head2 base_criteria - permanent view-level row filters by column name

C<base_criteria> is a convenience alternative to C<filters> for callers who
know the column names they want to restrict but prefer not to track database
indices.

    my $join = Database::Join->new(
        databases     => [ $customers, $orders ],
        join_column   => 'entry',
        base_criteria => { active => 1, deleted_at => undef },
    );

    # Every query automatically sees only active, non-deleted rows.
    my $rows = $join->selectall_arrayref();

At construction time C<base_criteria> is partitioned by column ownership
using the same routing logic as C<selectall_arrayref>.  Each criterion is
sent to the database that owns that column and stored as a permanent base
filter (equivalent to the corresponding C<filters> entry).

B<Unknown columns> emit a C<warn_unknown_column> carp and are silently
dropped, just as they would be in a query call.

B<Key-set semantics> are identical to C<filters>: any database that receives
a C<base_criteria> slice acts as an inner-join partner regardless of
C<join_type>.

B<Precedence>: when a column appears in both C<base_criteria> and C<filters>,
the C<filters> entry wins on plain-scalar conflicts; operator-hashref values
are combined with AND semantics.

B<Use cases>

=over 4

=item *

Row-level security: C<< base_criteria => { tenant_id => $tid } >>

=item *

Soft-delete filtering: C<< base_criteria => { deleted_at => undef } >>

=item *

Status gates: C<< base_criteria => { active => 1 } >>

=back

=head2 mandatory_filters - row-level security predicates that cannot be bypassed

C<mandatory_filters> is an arrayref of C<{col, op, val}> predicate hashrefs.
Every predicate is applied to the merged result of every query, regardless of
what criteria the caller passes.  Unlike C<filters> and C<base_criteria> (which
are per-database constraints applied at fetch time), C<mandatory_filters>
operates on the fully-merged row set, ensuring the constraint applies uniformly
even when the same logical value is spread across multiple databases.

    my $join = Database::Join->new(
        databases         => [ $customers, $loyalty ],
        join_column       => 'entry',
        mandatory_filters => [
            { col => 'region',  op => 'eq',  val => 'West' },
            { col => 'tier',    op => 'ne',  val => 'banned' },
            { col => 'balance', op => 'gte', val => 0        },
        ],
    );

Each predicate hashref must supply exactly these three keys:

=over 4

=item C<col>

The column name in the merged view (as returned by C<columns()>).  Must be
present at construction time; columns added later via C<add_database()> are not
retroactively covered by predicates already in C<_mandatory_filters>.

=item C<op>

The comparison operator.  Supported values:

    eq       -- string equality      ($row->{col} eq $val)
    ne       -- string inequality    ($row->{col} ne $val)
    lt       -- string less-than     ($row->{col} lt $val)
    lte      -- string <=            ($row->{col} le $val)
    gt       -- string greater-than  ($row->{col} gt $val)
    gte      -- string >=            ($row->{col} ge $val)
    like     -- SQL LIKE pattern     (% = any sequence, _ = any one character)
    contains -- substring match      (row value must contain val as a substring)

Comparisons are lexicographic (string-based) on the array path; on the SQLite
path they follow SQLite's default collation for the column type.  Use the
SQLite backend (C<backend =E<gt> 'sqlite'>) when numeric ordering matters.

=item C<val>

The right-hand side of the comparison.  Must be a plain scalar.

=back

B<Supported use cases>

=over 4

=item *

Row-level security: restrict the view to rows the current session is authorised
to see: C<< { col => 'tenant_id', op => 'eq', val => $session_tenant } >>

=item *

Data classification gates: hide rows marked with a sensitivity label:
C<< { col => 'classification', op => 'ne', val => 'restricted' } >>

=item *

Substring/pattern guards:
C<< { col => 'email', op => 'contains', val => '@example.com' } >>
or C<< { col => 'code', op => 'like', val => 'PROD_%' } >>

=back

B<SECURITY: C<mandatory_filters> must never be set from user-supplied values>

The predicates in C<mandatory_filters> are an enforcement boundary.  They must
come from a trusted server-side source (a session store, a policy table, or
hard-coded application configuration) -- never from URL parameters, form fields,
HTTP headers, or any other user-controlled input.  Setting this parameter from
user-supplied data would allow an attacker to widen or replace the constraints
and access rows they are not permitted to see.

B<Array vs. SQLite backend>

On the B<array backend>, C<mandatory_filters> is applied as a Perl-side C<grep>
after the in-memory merge, immediately before C<sort_by>/C<limit>/C<offset>.
A row that does not satisfy every predicate is silently dropped.

On the B<SQLite backend>, each predicate is translated into a parameterised
C<WHERE> clause and injected into the per-call SQL query.  Values are always
passed via DBI bind parameters, never by string interpolation.

Both backends produce identical filtered results.

=head2 distinct - deduplicate merged rows

Pass C<< distinct => 1 >> to C<selectall_arrayref> or C<selectall_array> to
remove duplicate rows from the merged result.

    # All unique tier values
    my $tiers = $join->selectall_arrayref(
        distinct => 1,
        columns  => ['tier'],
    );

    # All unique region + tier combinations
    my $combos = $join->selectall_arrayref(
        distinct => 1,
        columns  => ['region', 'tier'],
    );

    # Remove fully-identical merged rows (all columns participate)
    my $deduped = $join->selectall_arrayref(distinct => 1);

The optional C<columns> arrayref projects each row to the named columns I<before>
deduplication.  Omitting C<columns> (or passing an empty arrayref) deduplicates
on the full merged row: two rows must be identical in every column to be
considered duplicates.

B<Array backend>: deduplication is done in Perl using a seen-hash keyed on the
selected column values.  First occurrence wins.

B<SQLite backend>: C<SELECT DISTINCT col1, col2, ...> is used; the SQL engine
handles deduplication.

Both backends produce identical results.

B<Interaction with sort_by / limit / offset>: C<distinct> is applied first
(before pagination and ordering), so C<limit> and C<offset> operate on the
already-deduplicated set.

=head2 collision_prefix - preserve colliding columns from secondary databases

By default, when a column name appears in more than one database the I<last>
database wins: its value silently overwrites earlier ones in merged rows.
This loses data and makes the origin invisible.

C<collision_prefix> changes this for secondary databases you designate.
When a secondary database at index N has a column that already exists in the
merged view, and C<collision_prefix-E<gt>{N}> is set, the colliding column is
published as C<"$prefix.$col"> instead of overwriting.  Both values are then
visible: the original column keeps its name (from the earlier database), and
the collision gets the prefixed name.

C<collision_prefix> is a hashref.  Each B<key> is the B<zero-based index> of
a secondary database in the C<databases> array (same numbering as C<join_map>).
Each B<value> is the prefix string to prepend.  An index-0 entry is
meaningless and silently ignored.  Omitting C<collision_prefix> entirely
preserves the previous last-wins behaviour and changes nothing.

Non-colliding columns from a secondary database are always added as-is with
no prefix, whether or not C<collision_prefix> is configured.

B<Example -- sales table and products table, both with a "product" column>

    # $sales    columns: id, product, amount, date
    # $products columns: sku, product, price, category
    # join on 'product' (left key) matched against 'sku' (right key via join_map)

    my $join = Database::Join->new(
        databases        => [$sales, $products],
        join_column      => 'product',
        join_map         => { 1 => 'sku' },
        collision_prefix => { 1 => 'products' },
    );

    $join->columns;
    # => ['amount', 'category', 'date', 'id', 'price', 'product', 'products.product']
    #                                                               ^-- prefixed collision

    my $row = $join->fetchrow_hashref(product => 'widget');
    # $row->{product}            -- value from $sales
    # $row->{'products.product'} -- value from $products (different row, same column name)
    # $row->{price}              -- from $products, no collision, kept as-is

B<Querying on a prefixed column>

Use the full published name as the criterion key:

    my $rows = $join->selectall_arrayref('products.product' => 'widget');
    # Internally routes as: product => 'widget' to $products

B<Interaction with remove_column>

C<remove_column> operates on published names.  To suppress a prefixed
collision column entirely, pass the prefixed name:

    $join->remove_column('products.product');

=head2 backend - SQLite join backend for large datasets

C<Database::Join> can merge component databases in two different ways,
controlled by the C<backend> constructor parameter.

=over 4

=item C<backend =E<gt> 'array'> -- in-memory merge (original behaviour)

All matching rows are fetched from every component database into Perl hashes
and merged there.  Simple and fast for small and medium datasets.  Peak RAM
is roughly three times the combined source data size (one copy per database
plus one merged copy).

=item C<backend =E<gt> 'sqlite'> -- SQL JOIN via a cached temporary file

C<Database::Join> creates a temporary SQLite database file, spills source
rows into it (one table per component database), then executes a single SQL
C<JOIN> statement per query call.  Peak RAM drops to roughly one times the
source data size.

The temporary file is created once and reused across multiple query calls on
the same object (the cache).  Only query-time criteria vary per call; they
are applied as SQL C<WHERE> clauses against the cached data.  The cache is
automatically rebuilt when any source database's C<updated()> timestamp
changes.  The file is deleted when the object is destroyed (goes out of
scope).  See I<Temporary file: name, location, and lifetime> below for
details.

Requires C<DBD::SQLite E<gt>= 1.70> (C<FULL OUTER JOIN> support was added in
SQLite 3.39.0; DBD::SQLite 1.70 ships SQLite 3.39.2).

=item C<backend =E<gt> 'auto'> (default)

C<Database::Join> counts the total rows from all component databases cheaply
-- without fetching them -- and then decides:

=over 4

=item *

If the combined count is less than or equal to C<max_array_rows> (default
10,000), use the array path.

=item *

If the combined count exceeds C<max_array_rows>, use the SQLite path.

=back

For counting to work without fetching, each component database must either
implement the C<dbi_source()> interface (for SQLite-backed sources, where a
C<COUNT(*)> SQL query is issued directly), or directly define a C<count()>
method in its own package -- not just inherit one from a parent class.  If
neither is available for a particular database, C<Database::Join> plays it
safe and uses the array path for the whole query without fetching any rows.

=back

B<Choosing max_array_rows>

The default of 10,000 is a reasonable starting point.  Adjust it to match
your hardware and typical row width.  For wide rows (many columns or long
strings) you may want a lower threshold; for narrow rows you can raise it.

B<Temporary file: name, location, and lifetime>

When the SQLite path is active, a single temporary SQLite database file acts
as the join cache for the life of the C<Database::Join> object.

B<Name>: the filename is randomly generated by C<File::Temp>, for example:

    /tmp/Cj8xK7mP2Q.db

The random portion (ten characters) is chosen automatically to avoid
collisions.  Only the directory is under your control; you cannot specify
the filename itself.

B<Location>: controlled by the C<tmpdir> constructor parameter.
If C<tmpdir> is not specified, C<File::Spec-E<gt>tmpdir()> is used (usually
C</tmp> on Unix, or the value of the C<TEMP> or C<TMP> environment variable
on Windows).

B<Lifetime: one file per object, deleted when the object is destroyed>: the
file is created on the first query call that uses the SQLite path and kept
alive until the C<Database::Join> object is destroyed (i.e. when it goes out
of scope or is explicitly C<undef>-d).  At most one file exists per object at
any given moment.  Calling C<selectall_arrayref()> ten times on the same
object creates and uses I<one> file, not ten.

B<Cache invalidation>: the cache is automatically rebuilt (the old file is
replaced with a new one) when any source database's C<updated()> return value
changes, or when C<add_database()> is called.  Base-filter criteria
(C<filters> constructor parameter) are applied once at build time for spilled
sources; query-time criteria are applied per-call as SQL C<WHERE> clauses.

To use a different directory -- for example a RAM-backed filesystem or a
faster local disk:

    my $join = Database::Join->new(
        databases      => [ $db1, $db2 ],
        join_column    => 'entry',
        backend        => 'sqlite',
        tmpdir         => '/dev/shm',     # Linux RAM disk
    );

B<Parallel secondary fetches (C<parallel> constructor parameter)>

By default, component databases are queried sequentially - the primary first,
then each secondary in order.  When the component databases are network- or
disk-backed and have non-trivial per-query latency, the sequential fetch means
total latency is the I<sum> of all per-DA latencies.

Setting C<< parallel => 1 >> in the constructor enables concurrent fetching
of secondary databases using Perl C<threads>.  With C<parallel => 1> and
two or more secondary databases (C<n E<gt> 2> total), secondary fetches run in
parallel after the primary fetch completes; total latency drops to
I<max(secondary latencies)> instead of I<sum(secondary latencies)>.

    my $join = Database::Join->new(
        databases   => [ $customers, $loyalty, $scores ],   # 3 DAs - 2 secondaries
        join_column => 'entry',
        parallel    => 1,    # loyalty and scores fetched concurrently
    );

Requirements and caveats:

=over 4

=item *

The C<threads> module must be available.  Most distributions ship it, but it
requires a Perl binary compiled with C<-Dusethreads>.  When threads are
unavailable, a C<carp> warning is emitted and fetching falls back to
sequential; the result is identical, only slower.

=item *

Parallel fetching is only active when the join has three or more total
databases (C<n E<gt> 2>).  With two databases (one secondary), the thread
creation overhead exceeds the benefit of concurrency; sequential is used
regardless of C<parallel>.

=item *

Component databases must be safe to call from Perl threads.  In-memory
databases (CSV, JSON, TSV after slurp) are safe.  DBI-backed databases
whose handles were created in the same thread may not be safe - consult your
DBD driver's thread documentation.  The array backend is recommended for
DBI-backed sources; the SQLite backend performs its join in a single SQL
statement and does not use parallel fetching.

=item *

C<parallel => 1> applies to the array backend only.  The SQLite backend
performs a single SQL JOIN after spilling source data, so per-DA parallelism
is irrelevant.

=back

B<Zero-copy ATTACH (C<dbi_source()> interface)>

Normally, when the SQLite path is active, rows from each component database
are fetched one by one and inserted into the temporary SQLite file.  This is
efficient but does involve INSERT overhead.

If a component database is itself SQLite-backed and implements a
C<dbi_source()> method, C<Database::Join> can skip the row-by-row copy
entirely and instead use C<ATTACH DATABASE> to link the source file directly
to the temporary join connection.  This is the zero-copy path and is
significantly faster for large SQLite sources.

The C<dbi_source()> method must return a hashref with two keys:

=over 4

=item C<dbh>

A connected C<DBD::SQLite> database handle (C<DBI> connection object).

=item C<table>

The name of the table in that database that holds the source rows.

=back

Example implementation:

    package My::SQLiteDatabase;
    use parent 'Database::Abstraction';

    sub dbi_source {
        my ($self) = @_;
        return {
            dbh   => $self->{_dbh},      # connected DBD::SQLite handle
            table => $self->{_table},    # table name in that database
        };
    }

    1;

The zero-copy ATTACH path is always used when a component database implements
C<dbi_source()>.  Query-time criteria are applied as parameterised SQL
C<WHERE> clauses against the ATTACHed source table, so no row-level copy is
needed even when the current call includes column filters.  (Prior to 0.005.0
any query-time criteria forced a spill; that restriction was removed in
0.005.0.)

B<Result identity>

Both the array path and the SQLite path produce identical results for any
given query.  You can switch between them freely without changing callers.
The C<collision_prefix> column renaming, C<join_map> key translation, and all
three join types (left, inner, outer) work identically on both paths.

=head2 selectall_arrayref

=head3 SYNOPSIS

    my $rows = $join->selectall_arrayref();
    my $rows = $join->selectall_arrayref(tier  => 'gold');
    my $rows = $join->selectall_arrayref(score => { '>' => 80 });
    my $rows = $join->selectall_arrayref('C001');  # positional: entry => 'C001'
    my $rows = $join->selectall_arrayref(sort_by => 'name');
    my $rows = $join->selectall_arrayref(tier => 'gold', sort_by => ['score', 'DESC']);
    my $rows = $join->selectall_arrayref(limit => 10);
    my $rows = $join->selectall_arrayref(limit => 10, offset => 20);
    my $rows = $join->selectall_arrayref(tier => 'gold', sort_by => 'name', limit => 5);
    my $rows = $join->selectall_arrayref(distinct => 1, columns => ['tier']);
    my $rows = $join->selectall_arrayref(distinct => 1);  # distinct on all columns

=head3 DESCRIPTION

Returns an arrayref of hashrefs representing the merged view of all component
databases, optionally filtered by the given criteria.

Criteria for columns that live in different databases are routed
automatically: each database is queried with only the criteria that apply to
its own columns.  The results are combined in memory using C<join_column>.
Under a C<left> or C<inner> join, a secondary database is also limited to the
primary's keys (see "Key pushdown" in L</DESCRIPTION>).

Accepts the same criteria syntax as C<Database::Abstraction::selectall_arrayref>.
A single plain scalar argument is interpreted as the C<join_column> value
(equivalent to C<< entry => 'C001' >> when C<join_column> is C<'entry'>).

Pass C<< distinct => 1 >> (with optional C<< columns => \@cols >>) to
deduplicate results; see the C<distinct> feature section for details.

=head3 API SPECIFICATION

=head4 Input

    Calling conventions (in order of precedence):
      1. No arguments             -- returns all rows
      2. One plain scalar         -- shorthand for join_column => $scalar
      3. Key-value pairs or
         a criteria hashref       -- routed per-database

    Values may be:
      Plain scalar                -- exact match
      Hashref of operators        -- e.g. { '>' => 80 }

    Optional parameters (mixed in with any of the above):
      sort_by => 'colname'            -- sort ascending by that column
      sort_by => ['colname', 'DESC']  -- sort descending
      sort_by => ['colname', 'ASC']   -- sort ascending (explicit)
      limit    => N                    -- return at most N rows (positive integer)
      offset   => M                   -- skip the first M rows (non-negative integer)

    The column named in sort_by must be present in the merged view (i.e. it
    must appear in columns()).  An unknown column or an invalid direction emits
    a carp warning and falls back to the default join_column ascending sort.

    limit and offset are applied after ordering.  offset without limit skips
    rows but returns all remaining rows.  limit without offset starts from
    the first qualifying row.  An invalid limit or offset emits a carp warning
    and the parameter is ignored (treated as absent).

    DOMAIN -- sort_by:
      EP absent:          result sorted by join_column ASC (default).
      EP string:          any column name in columns(); sorts ASC by that column.
      EP ['col','ASC']:   explicit ascending; equivalent to the string form.
      EP ['col','DESC']:  descending sort by the named column.
      EP ['col']:         single-element arrayref; direction defaults to ASC.
      EP []:              empty arrayref; column is undef -> carp + join_col ASC fallback.
      EP invalid column:  column not in columns() -> carp + join_col ASC fallback.
      EP invalid dir:     direction not 'ASC' or 'DESC' -> carp + ASC used.
      Sort is lexicographic (cmp); use backend=>'sqlite' for numeric ORDER BY.

    DOMAIN -- limit:
      EP absent:          no truncation; all qualifying rows are returned.
      EP 0:               not a positive integer -> carp + ignored (all rows returned).
      BVA min valid = 1:  exactly 1 row returned.
      BVA at count:       limit == total rows -> all rows returned (no truncation).
      BVA above count:    limit > total rows -> all rows returned.
      EP invalid:         negative integer, float string, or non-numeric string
                          => carp + ignored (all rows returned).
      Valid domain:       integers in [1, INF); matched by /^\d+\z/a with value >= 1.

    DOMAIN -- offset:
      EP absent:          no rows skipped; result starts from row 0.
      BVA min valid = 0:  no rows skipped (zero is a valid non-negative integer).
      BVA offset=1:       first row skipped; result starts from row 1.
      BVA offset=N-1:     N-1 rows skipped; only the last row returned.
      BVA offset=N:       all N rows skipped; empty result returned.
      BVA offset>N:       all rows skipped; empty result returned.
      EP invalid:         negative integer, float string, or non-numeric string
                          => carp + ignored (no rows skipped).
      Valid domain:       integers in [0, INF); matched by /^\d+\z/a.

    distinct => 1          -- deduplicate rows after the merge (see columns below)
    columns  => \@cols     -- arrayref of column names to project and deduplicate on;
                              used together with distinct => 1

    DOMAIN -- distinct:
      EP absent or 0:     no deduplication; all merged rows are returned.
      EP 1:               duplicates are removed (see below); first occurrence wins.
      EP truthy (not 1):  treated as truthy; deduplication is applied.
      Effect:             on the array backend, a Perl seen-hash keyed on the
                          selected column values is used; first occurrence wins.
                          On the SQLite backend, SELECT DISTINCT is used.

    DOMAIN -- columns:
      EP absent/undef:    when distinct is set, deduplication is on all columns
                          and full rows are returned.
      EP []:              empty arrayref treated the same as absent.
      EP valid:           arrayref of column names present in the merged view;
                          result rows are projected to those columns only, and
                          deduplication is on the projected values.
      EP with distinct=0: columns is ignored when distinct is absent or false.
      Note:               unknown column names in the list are silently ignored
                          at projection time; the row may lack those keys.

=head4 Output

    Arrayref of hashrefs; one hashref per qualifying merged row.
    Sorted ascending by join_column by default; caller-controlled via sort_by.
    At most C<limit> rows when limit is given; the first C<offset> rows are
    skipped when offset is given.
    Returns a reference to an empty array when no rows match.

=head3 EXAMPLE

    # All rows from both databases
    my $all = $join->selectall_arrayref();

    # Only rows where the 'tier' column (from the loyalty database)
    # equals 'gold' -- the criterion is routed to the right database
    my $vip = $join->selectall_arrayref(tier => 'gold');

    # Operator hashref: score > 80
    my $high = $join->selectall_arrayref(score => { '>' => 80 });

    # Access each merged row
    for my $row (@{$vip}) {
        printf "%-10s tier=%-8s score=%d\n",
            $row->{entry}, $row->{tier}, $row->{score} // 0;
    }

    # Distinct tier values across all rows (project to one column, deduplicate)
    my $tiers = $join->selectall_arrayref(distinct => 1, columns => ['tier']);
    # Returns e.g. [{ tier => 'gold' }, { tier => 'silver' }, { tier => 'bronze' }]
    # regardless of how many rows exist for each tier

    # Distinct region+tier combinations
    my $combos = $join->selectall_arrayref(
        distinct => 1,
        columns  => ['region', 'tier'],
    );

    # Distinct on all columns (remove fully-duplicate merged rows)
    my $deduped = $join->selectall_arrayref(distinct => 1);

=head3 MESSAGES

    warn_unknown_column (carp)
        -- A criterion key names a column not present in any component database;
           the criterion is silently dropped and all rows are returned.
    error_join_criterion (croak)
        -- A criterion hashref contains a join => key (DA SQL-JOIN syntax).
           Use a separate DA object for the joined table instead.
    sort_by column unknown (carp)
        -- The column given in sort_by is not in the merged view; the result
           is returned in the default join_column ascending order instead.
    sort_by direction invalid (carp)
        -- The direction given in sort_by is not 'ASC' or 'DESC'; ASC is used.
    limit invalid (carp)
        -- The value given for limit is not a positive integer; it is ignored.
    offset invalid (carp)
        -- The value given for offset is not a non-negative integer; it is ignored.
    operator-unsupported (carp, SQLite/auto path only)
        -- An operator hashref key is not in the supported set (>, <, >=, <=,
           !=, =, LIKE, NOT LIKE, IS NULL, IS NOT NULL, IN, NOT IN); the
           individual operator term is dropped from the WHERE clause (other
           operators in the same hashref still apply).
    IN/NOT IN wrong value type (carp, SQLite/auto path only)
        -- An IN or NOT IN criterion was given a non-arrayref value; the operator
           term is skipped.
    error_sqlite_connect (croak, SQLite/auto path only)
        -- The temporary SQLite join file could not be created; check tmpdir
           permissions and available disk space.

=cut
1914
1915sub selectall_arrayref {
1916
800
49502
        my ($self, @args) = @_;
1917
800
859
        my $params   = $self->_parse_query_args(undef, @args);
1918
800
3716
        my $sort_by  = delete $params->{sort_by};
1919
800
458
        my $limit    = delete $params->{limit};
1920
800
448
        my $offset   = delete $params->{offset};
1921
800
416
        my $distinct = delete $params->{distinct};
1922
800
393
        my $columns  = delete $params->{columns};
1923
800
866
        return $self->_joined_query($params,
1924                sort_by  => $sort_by, limit => $limit, offset => $offset,
1925                distinct => $distinct, columns => $columns);
1926}
1927
1928 - 1976
=head2 selectall_array

=head3 SYNOPSIS

    my @rows = $join->selectall_array(tier => 'gold');

    # Scalar context: only the first matching row
    my $first = $join->selectall_array(entry => 'C001');

    # Distinct column projection (list context)
    my @tiers = $join->selectall_array(distinct => 1, columns => ['tier']);

    # Distinct on all columns
    my @deduped = $join->selectall_array(distinct => 1);

=head3 DESCRIPTION

In list context returns a list of merged hashrefs -- the same rows that
C<selectall_arrayref> would return, just as a flat list rather than an
arrayref.

In scalar context returns only the first matching hashref (or C<undef> if
nothing matches).

=head3 API SPECIFICATION

=head4 Input

    Same as selectall_arrayref.

=head4 Output

    List context:   list of hashrefs (may be empty).
    Scalar context: single hashref or undef.

=head3 EXAMPLE

    my @all = $join->selectall_array();
    print scalar @all, " rows\n";

    # First gold-tier customer only
    my $first_vip = $join->selectall_array(tier => 'gold');
    print $first_vip->{name}, "\n" if defined $first_vip;

=head3 MESSAGES

Same messages as C<selectall_arrayref>.

=cut
1977
1978sub selectall_array {
1979
22
1577
        my ($self, @args) = @_;
1980
22
27
        my $params   = $self->_parse_query_args(undef, @args);
1981
22
65
        my $sort_by  = delete $params->{sort_by};
1982
22
17
        my $limit    = delete $params->{limit};
1983
22
13
        my $offset   = delete $params->{offset};
1984
22
11
        my $distinct = delete $params->{distinct};
1985
22
17
        my $columns  = delete $params->{columns};
1986
22
32
        my $rows     = $self->_joined_query($params,
1987                sort_by  => $sort_by, limit => $limit, offset => $offset,
1988                distinct => $distinct, columns => $columns);
1989
22
13
33
25
        return wantarray ? @{$rows} : $rows->[0];
1990}
1991
1992 - 1998
=head2 selectall_hashref

Deprecated alias for L</selectall_arrayref>, present for compatibility with
callers written against C<Database::Abstraction>'s deprecated API.  Use
C<selectall_arrayref> in new code.

=cut
1999
2000sub selectall_hashref {
2001
5
119
        my $self = shift;
2002
5
30
        carp 'Database::Join::selectall_hashref is deprecated; use selectall_arrayref';
2003
5
554
        return $self->selectall_arrayref(@_);
2004}
2005
2006 - 2012
=head2 selectall_hash

Deprecated alias for L</selectall_array>, present for compatibility with
callers written against C<Database::Abstraction>'s deprecated API.  Use
C<selectall_array> in new code.

=cut
2013
2014sub selectall_hash {
2015
5
106
        my $self = shift;
2016
5
29
        carp 'Database::Join::selectall_hash is deprecated; use selectall_array';
2017
5
506
        return $self->selectall_array(@_);
2018}
2019
2020 - 2061
=head2 fetchrow_hashref

=head3 SYNOPSIS

    my $row = $join->fetchrow_hashref(entry => 'C001');
    my $row = $join->fetchrow_hashref('C001');   # positional shorthand

=head3 DESCRIPTION

Returns a single merged hashref for the first row matching the given
criteria, or C<undef> when nothing matches.

Equivalent to calling C<selectall_arrayref> and taking only the first element.
All the same criteria conventions apply.

=head3 API SPECIFICATION

=head4 Input

    Same as selectall_arrayref.

=head4 Output

    Hashref, or undef when no row matches.

=head3 EXAMPLE

    my $row = $join->fetchrow_hashref(entry => 'C001');
    if (defined $row) {
        print "Name: $row->{name}, Tier: $row->{tier}\n";
    } else {
        print "No record for C001\n";
    }

    # Positional: works when join_column is 'entry'
    my $row2 = $join->fetchrow_hashref('C001');

=head3 MESSAGES

Same messages as C<selectall_arrayref>.

=cut
2062
2063sub fetchrow_hashref {
2064
68
8171
        my ($self, @args) = @_;
2065
68
84
        my $params   = $self->_parse_query_args(undef, @args);
2066
68
515
        my $sort_by = delete $params->{sort_by};
2067
68
42
        delete $params->{limit};   # fetchrow_hashref always returns one row; limit is meaningless
2068
68
42
        delete $params->{offset};  # offset would change which row is "first"; not supported here
2069
68
85
        my $rows     = $self->_joined_query($params, sort_by => $sort_by);
2070
68
276
        return $rows->[0];
2071}
2072
2073 - 2111
=head2 count

=head3 SYNOPSIS

    my $total  = $join->count();
    my $active = $join->count(tier => 'gold');

=head3 DESCRIPTION

Returns the number of merged rows that satisfy the given criteria.

On the array backend, the full in-memory join is performed and the resulting
rows are counted in Perl.  On the SQLite backend, a C<SELECT COUNT(*)> SQL
query is executed against the cached join tables, avoiding a full row fetch.

=head3 API SPECIFICATION

=head4 Input

    Same criteria syntax as selectall_arrayref.

=head4 Output

    Non-negative integer.

=head3 EXAMPLE

    my $total   = $join->count();
    my $gold    = $join->count(tier => 'gold');
    my $high    = $join->count(score => { '>' => 90 });

    printf "%d total, %d gold-tier, %d high-scorers\n",
        $total, $gold, $high;

=head3 MESSAGES

Same messages as C<selectall_arrayref>.

=cut
2112
2113sub count {
2114
79
12352
        my ($self, @args) = @_;
2115
79
101
        my $params = $self->_parse_query_args(undef, @args);
2116
79
249
        delete $params->{sort_by};  # row ordering is irrelevant for a count
2117
79
69
        delete $params->{limit};     # count returns total matching rows, not a page
2118
79
44
        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
140
                unless $self->{_backend} eq 'array';
2122
6
6
5
6
        return scalar @{ $self->_joined_query_array($params) };
2123}
2124
2125 - 2241
=head2 aggregate

=head3 SYNOPSIS

    my $rows = $join->aggregate(
        by       => ['tier'],
        measures => [
            { col => 'score', fn => 'sum', as => 'total' },
            {                 fn => 'count', as => 'n'   },
        ],
        having   => { total => { '>' => 100 } },
        sort_by  => ['total', 'DESC'],
        limit    => 10,
    );
    # => [ { tier => 'gold', total => 183, n => 2 }, ... ]

=head3 DESCRIPTION

Groups the merged view by one or more published column names and computes
aggregate measures over each group.

On the SQLite backend (C<backend =E<gt> 'sqlite'>) and the C<auto> backend,
the aggregation is pushed into the existing SQLite cache as a C<GROUP BY>
query - rows never pass through Perl.  The C<auto> backend always takes this
path for aggregation, skipping the row-count threshold probe (aggregation
makes the row count irrelevant).

On the array backend (C<backend =E<gt> 'array'>), merged rows are fetched in
full and folded in Perl.  This materialises the complete matching result set.

The two paths return the same rows for the same input, except for two
documented differences: C<min>/C<max> on a column declared C<TEXT> but
storing numbers (SQL compares lexically; Perl detects numerics), and
C<sum>/C<avg> with non-numeric values (SQL coerces to 0.0; Perl skips and
warns via C<warn_aggregate_non_numeric>).

C<Database::Join> has no C<no_fixate> and no CHI cache (unlike
C<Database::Abstraction>); aggregation results are not cached between calls.

=head3 API SPECIFICATION

=head4 Input

Reserved keys extracted before the rest is treated as WHERE criteria:

    by       => arrayref of published column names (default: [] = grand total)
    measures => arrayref of measure hashrefs (required, non-empty)
    having   => hashref of post-aggregation criteria
    sort_by  => 'col' or ['col', 'DESC']
    limit    => positive integer
    offset   => non-negative integer

Every other key is pre-aggregation criteria routed exactly as
C<selectall_arrayref> routes criteria.

Measure hashref keys:

    fn  => function name (sum|avg|min|max|count|count_distinct), case-insensitive
    col => published column name (required for all functions except bare count)
    as  => result key (required; must match C</^\w+\z/>; unique; not a by name)

C<having> uses the same operator vocabulary as C<selectall_arrayref>:
C<%SAFE_SQL_OPS> (E<gt>, E<lt>, E<gt>=, E<lt>=, !=, =, LIKE, NOT LIKE),
C<%SAFE_LIST_OPS> (IN, NOT IN), C<%SAFE_NOARG_OPS> (IS NULL, IS NOT NULL),
a bare scalar (= ?), and C<-or>/C<-and> groupings.  Write C<-between> as
two operators and C<LIKE> explicitly.

=head4 Output

Always an arrayref of hashrefs (never C<undef>).  C<[]> when no group
qualifies and C<by> is non-empty.  When C<by> is omitted or C<[]> and no
rows match, returns one all-normalised row (grand total of zero).

Key order per row: C<by> columns in declaration order, then measure aliases
in declaration order.

=head3 EXAMPLE

    # Total score and row count per tier, highest total first
    my $rows = $join->aggregate(
        by       => ['tier'],
        measures => [
            { col => 'score', fn => 'sum',   as => 'total' },
            {                 fn => 'count', as => 'n'     },
        ],
        sort_by  => ['total', 'DESC'],
    );
    for my $r (@{$rows}) {
        printf "%s: total=%s n=%s\n", $r->{tier}, $r->{total}, $r->{n};
    }

=head3 PSEUDOCODE

    1. get_params(undef, @args) -- hashref or kv-pairs only (no positional key)
    2. croak error_join_criterion if 'join =>' present
    3. _validate_aggregate_spec extracts by/measures/having/sort_by/limit/offset
    4. array backend:
         rows   = _joined_query_array(remaining criteria, no sort/limit/offset)
         groups = _fold_aggregate(rows, spec)
         groups = [grep { _match_criteria($_, having) } @groups] if having
         _normalise_aggregate(groups, spec.measures)
         _sort_and_page(groups, spec)
       sqlite/auto backend:
         _sqlite_aggregate(remaining criteria, spec)
    5. return groups

=head3 MESSAGES

C<error_aggregate_measures_required>, C<error_aggregate_measure_ref>,
C<error_aggregate_fn_unknown>, C<error_aggregate_col_required>,
C<error_aggregate_col_unknown>, C<error_aggregate_as_required>,
C<error_aggregate_as_invalid>, C<error_aggregate_as_duplicate>,
C<error_aggregate_as_collision>, C<error_aggregate_by_invalid>,
C<error_aggregate_having_key>, C<error_aggregate_having_operator>,
C<warn_aggregate_sort_key>, C<warn_aggregate_non_numeric>.

=cut
2242
2243sub aggregate {
2244
103
13304
        my ($self, @args) = @_;
2245
103
101
        my $p = get_params(undef, @args) // {};
2246
2247
103
1025
        croak $self->_err('error_join_criterion') if exists $p->{join};
2248
2249
102
97
        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
49
        my $backend = $self->{_backend};
2254
2255
74
57
        if ($backend eq 'array') {
2256                # Fetch all matching merged rows without sort/limit/offset —
2257                # those must be applied after grouping.
2258
37
32
                my $merged = $self->_joined_query_array($p);
2259
37
31
                my $groups = $self->_fold_aggregate($merged, $spec);
2260
2261                # Apply HAVING on the folded groups.
2262
37
31
                if (my $having = $spec->{having}) {
2263
9
27
9
4
19
5
                        $groups = [grep { $self->_match_criteria($_, $having) } @{$groups}];
2264                }
2265
2266
37
41
                $self->_normalise_aggregate($groups, $spec->{measures});
2267
37
29
                $self->_sort_and_page($groups, $spec);
2268
37
119
                return $groups;
2269        } else {
2270                # SQLite path (including 'auto'): always use SQL, no threshold probe.
2271
37
32
                return $self->_sqlite_aggregate($p, $spec);
2272        }
2273}
2274
2275 - 2337
=head2 each_row

=head3 SYNOPSIS

    my $count = $join->each_row(sub { my ($row) = @_; ... });
    my $count = $join->each_row(sub { ... }, tier => 'gold');
    my $count = $join->each_row(sub { ... }, sort_by => 'name', limit => 100);

=head3 DESCRIPTION

Calls C<\&callback> once for every row in the merged view that matches the
given criteria, then returns the total count of rows visited.

Accepts the same criteria, C<sort_by>, C<limit>, and C<offset> parameters as
C<selectall_arrayref>.

B<Note on memory usage>: C<Database::Join> always materialises the complete
merged result set before invoking the callback, because merging rows from
multiple independent sources requires that every source be queried and
cross-referenced first.  True constant-memory streaming (as C<Database::Abstraction>
provides on single-source SQL queries) is not possible at the join layer.
For genuinely large result sets use the SQLite backend (C<backend =E<gt>
'sqlite'>), which keeps peak RAM to approximately one times the source data
size rather than three.

Any exception thrown inside the callback propagates to the caller after the
current row; subsequent rows are not visited.

=head3 API SPECIFICATION

=head4 Input

    \&callback   Positional coderef (required).
                 Called as $callback->($row_hashref) for each merged row.

    Additional arguments follow the same calling conventions as
    selectall_arrayref: no args, a single scalar join-column value,
    or key-value criteria pairs (including sort_by, limit, offset).

=head4 Output

    Non-negative integer: the count of rows for which the callback was invoked.

=head3 EXAMPLE

    # Print every gold-tier customer's name, sorted by name
    my $count = $join->each_row(
        sub { my ($row) = @_; print "$row->{name}\n" },
        tier    => 'gold',
        sort_by => 'name',
    );
    print "$count gold-tier customers\n";

    # Accumulate without holding the full result
    my $total_score = 0;
    $join->each_row(sub { $total_score += $_[0]->{score} // 0 });

=head3 MESSAGES

    error_invalid_callback (croak)
        -- First argument is not a code reference.

=cut
2338
2339sub each_row {
2340
16
596
        my ($self, $cb, @args) = @_;
2341
16
16
        croak $self->_err('error_invalid_callback')
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
12
        my $rows  = $self->selectall_arrayref(@args);
2347
11
8
        my $count = 0;
2348
11
11
4
8
        for my $row (@{$rows}) {
2349
17
14
                $cb->($row);
2350
16
17
                $count++;
2351        }
2352
10
12
        return $count;
2353}
2354
2355 - 2416
=head2 dbi_source

=head3 SYNOPSIS

    # Use a Database::Join object as a zero-copy SQLite source inside a
    # parent Database::Join, giving the parent ATTACHed-speed access to
    # the child's joined data without iterating through Perl.
    my $child  = Database::Join->new(databases => [$da, $db], join_column => 'id', backend => 'sqlite');
    my $parent = Database::Join->new(databases => [$child, $dc], join_column => 'id', backend => 'sqlite');

=head3 DESCRIPTION

Returns a hashref C<< { dbh => $sqlite_dbh, table => '_dj_result' } >> that
allows a parent C<Database::Join> (or any other caller that understands the
C<dbi_source()> interface) to ATTACH the child's temporary SQLite database
file and query the materialised join result directly via SQL, without routing
rows through Perl.

The first call builds the SQLite cache (if not already current) and
materialises the full join result - with C<filters> applied but no query-time
criteria - into a real table named C<_dj_result> inside the cache file.
Subsequent calls within the same cache cycle reuse the existing table.

Returns C<undef> when the backend is C<'array'> (no SQLite file exists).

=head3 API SPECIFICATION

=head4 Input

    None.

=head4 Output

    On the SQLite/auto backend:
      Hashref with keys:
        dbh   => DBI handle to the child's temporary SQLite database file.
        table => '_dj_result'  (the materialized join table inside that file).
    On the array backend:
      undef

=head3 EXAMPLE

    # The parent automatically ATTACHes the child's SQLite file and queries
    # _dj_result for zero-copy composable nested joins.
    my $inner = Database::Join->new(
        databases   => [$customers, $loyalty],
        join_column => 'entry',
        backend     => 'sqlite',
    );
    my $outer = Database::Join->new(
        databases   => [$inner, $scores],
        join_column => 'entry',
        backend     => 'sqlite',
    );
    my $rows = $outer->selectall_arrayref(tier => 'gold');

=head3 MESSAGES

    error_sqlite_connect (croak)
        -- The temporary SQLite join file could not be created.

=cut
2417
2418sub dbi_source {
2419
33
3415
        my ($self) = @_;
2420
2421        # The array backend has no SQLite handle to expose.
2422
33
48
        return undef if $self->{_backend} eq 'array';
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
32
        $self->_build_sqlite_cache() unless $self->_cache_fresh();
2428
2429
25
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
24
        unless ($cache->{_dj_built}) {
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
31
                $self->_sqlite_join({}, create_table => '_dj_result');
2439
20
29
                $cache->{_dj_built} = 1;
2440        }
2441
2442
25
75
        return { dbh => $cache->{dbh}, table => '_dj_result' };
2443}
2444
2445 - 2483
=head2 columns

=head3 SYNOPSIS

    my $cols = $join->columns();

=head3 DESCRIPTION

Returns an arrayref of all column names visible in the merged view,
deduplicated and sorted alphabetically.

The C<join_column> appears exactly once, even if it exists under different
local names in some databases (see C<join_map>).  Columns that have been
hidden with C<remove_column> or C<remove_columns> do not appear.

The result is memoised: repeated calls are cheap.

=head3 API SPECIFICATION

=head4 Input

    None.

=head4 Output

    Arrayref of column name strings, sorted alphabetically.

=head3 EXAMPLE

    my $cols = $join->columns();
    print join(', ', @{$cols}), "\n";
    # e.g. "entry, name, score, tier"

=head3 MESSAGES

C<columns()> does not itself emit any warnings or errors.  Any exception thrown
by a component database's C<columns()> method propagates uncaught.

=cut
2484
2485sub columns {
2486
189
9641
        my ($self) = @_;
2487
2488
189
188
        return $self->{_col_cache} if $self->{_col_cache};
2489
2490
167
103
        my %seen;
2491        my @cols;
2492
167
111
        my $join_col = $self->{_join_col};
2493
2494
167
167
93
136
        for my $i (0 .. $#{ $self->{_dbs} }) {
2495
345
213
                my $local_jc = $self->{_join_map}{$i};
2496
345
250
                my $renames  = $self->{_col_rename}[$i] // {};
2497
345
345
156
249
                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
744
                        next if $local_jc && $col eq $local_jc && $col ne $join_col;
2501                        # Use the published name (prefixed if this column was a collision rename)
2502
830
601
                        my $pub = $renames->{$col} // $col;
2503
830
574
                        next if $seen{$pub}++;
2504
656
398
                        next if $self->{_removed_cols}{$pub};
2505
609
386
                        push @cols, $pub;
2506                }
2507        }
2508
2509
167
260
        $self->{_col_cache} = [ sort @cols ];
2510
167
234
        return $self->{_col_cache};
2511}
2512
2513 - 2556
=head2 schema

=head3 SYNOPSIS

    my $schema = $join->schema();

=head3 DESCRIPTION

Returns a merged schema hashref for all visible columns across all component
databases.  Each key is a column name; each value is the schema metadata
hashref returned by C<Database::Abstraction::schema()> for that column
(typically C<{ type, nullable, default, pk }>).

When the same column name appears in more than one database the I<last>
database's metadata is used.  Columns hidden with C<remove_column> are not
included.

The result is memoised.

=head3 API SPECIFICATION

=head4 Input

    None.

=head4 Output

    Hashref: column_name => { type => ..., nullable => ..., default => ..., pk => ... }.

=head3 EXAMPLE

    my $schema = $join->schema();
    for my $col (sort keys %{$schema}) {
        my $info = $schema->{$col};
        printf "%-15s type=%-10s nullable=%s\n",
            $col, $info->{type}, $info->{nullable} ? 'yes' : 'no';
    }

=head3 MESSAGES

C<schema()> does not itself emit any warnings or errors.  Any exception thrown
by a component database's C<schema()> method propagates uncaught.

=cut
2557
2558sub schema {
2559
58
4117
        my ($self) = @_;
2560
2561
58
496
        return $self->{_schema_cache} if $self->{_schema_cache};
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
31
        my %merged;
2567
51
51
40
42
        for my $i (0 .. $#{ $self->{_dbs} }) {
2568
99
99
                my $s        = $self->{_dbs}[$i]->schema() // {};
2569
97
129
                my $local_jc = $self->{_join_map}{$i};
2570
97
79
                my $renames  = $self->{_col_rename}[$i] // {};
2571
97
76
                my $skip_jc  = $local_jc && $local_jc ne $self->{_join_col};
2572
97
68
                if (!$skip_jc && !%{$renames}) {
2573                        # Fast path: no join-key alias to exclude and no collision renames
2574
88
88
88
33
97
77
                        @merged{keys %{$s}} = values %{$s};
2575                } else {
2576
9
9
7
8
                        for my $col (keys %{$s}) {
2577
24
24
                                next if $skip_jc && $col eq $local_jc;
2578
20
32
                                $merged{ $renames->{$col} // $col } = $s->{$col};
2579                        }
2580                }
2581        }
2582
2583
10
14
        delete @merged{keys %{ $self->{_removed_cols} }}
2584
49
49
24
57
                if %{ $self->{_removed_cols} };
2585
2586
49
40
        $self->{_schema_cache} = \%merged;
2587
49
72
        return $self->{_schema_cache};
2588}
2589
2590 - 2631
=head2 updated

=head3 SYNOPSIS

    my $ts = $join->updated();

=head3 DESCRIPTION

Returns the Unix timestamp of the most recent modification across all
component databases.  This is the maximum of all individual C<updated()>
return values.

Use this to implement simple cache-invalidation logic: if C<updated()>
has advanced since your last snapshot, re-query.

=head3 API SPECIFICATION

=head4 Input

    None.

=head4 Output

    Unix timestamp (positive integer).

=head3 EXAMPLE

    my $last_modified = $join->updated();
    if ($last_modified > $my_cache_timestamp) {
        $my_cache = $join->selectall_arrayref();
        $my_cache_timestamp = $last_modified;
    }

=head3 MESSAGES

C<updated()> does not emit any warnings or errors.  Component databases that do
not implement C<updated()>, or whose C<updated()> throws, are silently skipped;
only defined return values contribute to the maximum.  If no component database
implements C<updated()>, C<undef> is returned (same as C<List::Util::max> on an
empty list).

=cut
2632
2633sub updated {
2634
37
1588
        my ($self) = @_;
2635
37
26
        my @timestamps;
2636
37
37
18
40
        for my $db (@{ $self->{_dbs} }) {
2637
75
29
                my $ts;
2638
75
75
75
75
39
38
34
131
                do { local $@; $ts = eval { $db->updated() } };
2639
75
873
                push @timestamps, $ts if defined $ts;
2640        }
2641
37
81
        return max(@timestamps);
2642}
2643
2644 - 2691
=head2 set_logger

=head3 SYNOPSIS

    $join->set_logger($log);
    $join->set_logger(logger => $log);   # named-pair form also accepted

=head3 DESCRIPTION

Attaches a new logger object to the join and propagates it to every component
database.  The logger is used for diagnostic output by all component databases.

Non-blessed values (a log-level string such as C<"debug">, a filename, or a
code reference) are wrapped in C<Log::Abstraction->new(...)> automatically,
matching the behaviour of C<Database::Abstraction::set_logger>.

=head3 API SPECIFICATION

=head4 Input

    logger  Positional or named: a logger object, log-level string, filename,
            or code reference (required).  Non-blessed values are wrapped in
            Log::Abstraction automatically.

=head4 Output

    Returns C<$self> for method chaining.

=head3 EXAMPLE

    # Log::Any is used here as an example; any object that implements
    # debug() and info() (or whichever methods your component databases
    # call internally) works equally well.
    use Log::Any qw($log);

    my $join = Database::Join->new(databases => [$db1, $db2], join_column => 'entry');
    $join->set_logger($log);
    # $log is now used by $join and by $db1 and $db2

    # Named-pair form (mirrors Database::Abstraction API):
    $join->set_logger(logger => $log);

=head3 MESSAGES

    (croak) Usage: set_logger(logger => $logger)
        -- Called with an undefined argument.  Pass a valid logger object.

=cut
2692
2693sub set_logger {
2694
17
265
        my $self = shift;
2695
17
18
        my $p    = Params::Get::get_params('logger', @_);
2696
17
170
        my $logger = $p->{'logger'};
2697
2698
17
32
        croak 'Usage: set_logger(logger => $logger)' unless defined $logger;
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
45
        $logger = Log::Abstraction->new($logger)
2703                unless Scalar::Util::blessed($logger);
2704
2705
14
13
        $self->{_logger} = $logger;
2706
14
14
10
22
        $_->set_logger($logger) for @{ $self->{_dbs} };
2707
2708
14
113
        return $self;
2709}
2710
2711 - 2841
=head2 add_database

=head3 SYNOPSIS

    # Positional: database object as first argument
    $join->add_database($db);

    # Named: equivalent to the above
    $join->add_database(database => $db);

    # With options (mixed positional + named)
    $join->add_database($db, remove_columns => ['internal_id']);
    $join->add_database($db, join_column    => 'local_key_name');
    $join->add_database($db, filter         => { score => { '>' => 60 } });

    # Chainable
    $join->add_database($db1)->add_database($db2, remove_columns => ['notes']);

=head3 DESCRIPTION

Adds one more C<Database::Abstraction> subclass object to the logical view
and immediately updates the column-ownership index.

After the call, all query methods return rows that include columns from the
newly added database, and criteria on those new columns are routed to it
automatically.

When a column name in the new database already exists in an earlier database,
the new database becomes the authoritative source for that column
(last-database-wins, the same rule that applies at construction time).

The join-column must be present in the new database (or declared via
C<join_column>).  The logger is propagated to the new database if one is set.

C<add_database> is the runtime equivalent of listing the database in the
C<databases> array to C<new>.  The optional C<join_column> parameter is
equivalent to a C<join_map> entry; the optional C<filter> parameter is
equivalent to a C<filters> entry.

=head3 API SPECIFICATION

=head4 Input

    database       => { type => 'object',   required => 1 }
                      # A Database::Abstraction subclass instance.
                      #
                      # DOMAIN -- EP valid:   blessed object that passes
                      #                       isa('Database::Abstraction').
                      # DOMAIN -- EP invalid: non-reference, unblessed ref, wrong class,
                      #                       or non-reference non-key scalar (the guard at
                      #                       the top of add_database rejects it with
                      #                       error_invalid_db before validate_strict runs).

    join_column    => { type => 'string',   optional => 1 }
                      # The name of the join key in THIS new database,
                      # when it differs from the canonical join_column.
                      #
                      # DOMAIN -- EP valid:   any string that exists as a column in the
                      #                       new database.
                      # DOMAIN -- EP invalid: string absent from the new database's columns()
                      #                       => croak error_join_col_missing.

    filter         => { type => 'hashref',  optional => 1 }
                      # Permanent criteria for this database only.
                      # Same format as selectall_arrayref.
                      #
                      # DOMAIN -- EP valid:   hashref of criteria (may be {} for no-op).
                      # DOMAIN -- EP absent:  no permanent filter applied; all rows visible.
                      # DOMAIN -- Key-set:    a non-empty filter makes this DB an inner-join
                      #                       partner regardless of the outer join_type.

    remove_columns => { type => 'arrayref', optional => 1 }
                      # Column names from this database to hide.
                      #
                      # DOMAIN -- EP valid:   arrayref of strings; non-existent columns silently
                      #                       ignored; empty [] is a safe no-op.
                      # DOMAIN -- EP invalid: join_column itself => croak error_remove_join_col.

=head4 Output

    Returns C<$self> to support method chaining.

=head3 EXAMPLE

    my $join = Database::Join->new(
        databases   => [ $customers ],
        join_column => 'entry',
    );

    # Add loyalty data; hide internal columns from it
    $join->add_database($loyalty, remove_columns => ['audit_ts']);

    # Add score data; only include rows with score > 60
    $join->add_database($scores, filter => { score => { '>' => 60 } });

    # Add a database whose join key has a different local name
    $join->add_database($stnames, join_column => 'state_code');

    # All three options combined, and chained
    $join->add_database($db4,
        join_column    => 'ref_id',
        filter         => { active => 1 },
        remove_columns => ['legacy_col'],
    );

=head3 PSEUDOCODE

    determine the new database's index (length of current _dbs array)
    extract the database object from positional or named argument
    croak if it is not a Database::Abstraction subclass
    register join_column alias in _join_map if different from canonical
    register filter in _filters if provided
    fetch column list from the new database
    croak if the join key is missing from the new database
    append the new database to _dbs and _db_cols
    update _col_db: for each new column, point it at the new index
        (last-database-wins; skip removed columns and the local join alias)
    invalidate _col_cache and _schema_cache
    propagate logger if set
    apply remove_columns if provided
    return $self

=head3 MESSAGES

    error_invalid_db          -- argument is not a Database::Abstraction subclass
    error_join_col_missing    -- join_column not found in the new database
    warn_schema_type_mismatch -- (carp) the new database has a shared column whose type
                                 differs from the type already in the view; use
                                 collision_prefix to preserve both values

=cut
2842
2843sub add_database {
2844
113
5873
        my ($self, @args) = @_;
2845
2846
113
113
58
91
        my $idx = scalar @{ $self->{_dbs} };
2847
113
72
        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
234
        if (@args && !ref($args[0])) {
2854                croak $self->_err('error_invalid_db', $idx)
2855
14
48
50
133
                        unless defined($args[0]) && grep { $args[0] eq $_ } @_ADD_DB_KEYS;
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
66
                $db = shift @args;
2860        }
2861
2862
104
369
        my $p = validate_strict(
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
9010
        $db //= $p->{database};
2877
2878
104
360
        croak $self->_err('error_invalid_db', $idx)
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
141
        my $local_jc = $p->{join_column} // $self->{_join_col};
2885
97
101
        $self->{_join_map}{$idx} = $local_jc if $p->{join_column};
2886        # Security: deep-copy the filter; same rationale as the constructor's _copy_filters call.
2887
97
104
        $self->{_filters}{$idx}  = _copy_criteria($p->{filter}) if $p->{filter};
2888
2889
97
82
        my $cols         = $db->columns();
2890
97
211
97
1062
152
94
        my %col_presence = map { $_ => 1 } @{$cols};
2891
2892        croak $self->_err('error_join_col_missing', $local_jc, $idx, ref($db))
2893
97
109
                unless $col_presence{$local_jc};
2894
2895        # Register the new database
2896
93
93
46
78
        push @{ $self->{_dbs} },     $db;
2897
93
93
58
76
        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
64
        my $prefix = $self->{_collision_prefix}{$idx};
2903
93
150
        $self->{_col_rename}[$idx]   //= {};
2904
93
126
        $self->{_col_unrename}[$idx] //= {};
2905
2906
93
93
44
70
        for my $col (@{$cols}) {
2907
207
182
                next if $local_jc ne $self->{_join_col} && $col eq $local_jc;
2908
2909
199
91
                my $pub;
2910
199
155
                if (defined $prefix && exists $self->{_col_db}{$col} && $col ne $self->{_join_col}) {
2911                        # Same guard as _build_col_index: never prefix the join_column itself.
2912
4
4
                        $pub = "$prefix.$col";
2913
4
3
                        $self->{_col_rename}[$idx]{$col}   = $pub;
2914
4
4
                        $self->{_col_unrename}[$idx]{$pub} = $col;
2915                } else {
2916
195
96
                        $pub = $col;
2917                }
2918
2919
199
137
                next if $self->{_removed_cols}{$pub};
2920
197
152
                $self->{_col_db}{$pub} = $idx;
2921        }
2922
2923        # Invalidate memoisation caches
2924
93
57
        $self->{_col_cache}    = undef;
2925
93
59
        $self->{_schema_cache} = undef;
2926
2927        # Warn about schema type mismatches introduced by the new database.
2928
93
89
        $self->_validate_schema_types();
2929
2930        # Invalidate the SQLite join cache: a new source requires a full rebuild.
2931
93
94
        if (my $old = delete $self->{_sqlite_cache}) {
2932
5
5
                local $@;
2933
5
5
8
90
                eval { $old->{dbh}->disconnect } if $old->{dbh};
2934        }
2935
2936        # Propagate logger if one is configured
2937
93
84
        if (my $log = $self->{_logger}) {
2938
4
5
                $db->set_logger($log);
2939        }
2940
2941        # Apply any column removals requested for this database
2942
93
104
        if (my $rc = $p->{remove_columns}) {
2943
6
6
4
10
                $self->remove_column($_) for @{$rc};
2944        }
2945
2946
93
160
        return $self;
2947}
2948
2949 - 3018
=head2 remove_column

=head3 SYNOPSIS

    $join->remove_column('email');

    # Chainable
    $join->remove_column('internal_id')->remove_column('audit_ts');

=head3 DESCRIPTION

Permanently hides a column from the merged view.  After this call:

=over 4

=item *

The column does not appear in C<columns()> or C<schema()>.

=item *

Returned row hashrefs do not contain the column key.

=item *

Any query criterion that references the removed column is silently dropped
(with a C<carp> warning).

=back

The C<join_column> cannot be removed; attempting to do so will C<croak>.
Removing a column that does not exist in any database is silently ignored
(the call is idempotent and safe).  The C<columns()> and C<schema()>
memoisation caches are cleared automatically.

=head3 API SPECIFICATION

=head4 Input

    $col    Positional string: the column name to remove.

            DOMAIN -- EP valid:   any string; non-existent columns are silently
                                  ignored (idempotent call, returns $self).
            DOMAIN -- EP invalid: join_column value => croak error_remove_join_col.
            DOMAIN -- BVA:        undef and '' are explicit no-ops (returns $self).
                                  These are below the minimum meaningful string
                                  length and are handled without any warning.

=head4 Output

    Returns C<$self> to support method chaining.

=head3 EXAMPLE

    # Hide private fields immediately after construction
    my $join = Database::Join->new(
        databases   => [ $customers, $loyalty ],
        join_column => 'entry',
    )->remove_column('email')
     ->remove_column('internal_notes');

    # Verify they are gone
    my $cols = $join->columns();
    # 'email' and 'internal_notes' are absent

=head3 MESSAGES

    error_remove_join_col -- attempt to remove the join_column itself

=cut
3019
3020sub remove_column {
3021
128
4429
        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
208
        return $self unless defined $col && length $col;
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
120
                if $col eq $self->{_join_col};
3031
3032
100
80
        $self->{_removed_cols}{$col} = 1;
3033
100
77
        delete $self->{_col_db}{$col};
3034
100
63
        $self->{_col_cache}    = undef;
3035
100
46
        $self->{_schema_cache} = undef;
3036
100
93
        $self->{_removed_list} = undef;      # invalidate the cached removed-column list
3037
3038
100
85
        return $self;
3039}
3040
3041 - 3051
=head2 query

Not supported.  C<Database::Join> does not implement the
C<Database::Abstraction::Query> chained builder because the builder's
C<.all()> / C<.first()> methods would be targeting a single component DA
rather than the merged view.  Calling this method will always C<croak>.

Use C<selectall_arrayref>, C<selectall_array>, C<fetchrow_hashref>,
C<count>, or C<each_row> against the C<Database::Join> object instead.

=cut
3052
3053sub query {
3054
8
456
        my $self = $_[0];
3055
8
17
        croak $self->_err('error_query_unsupported');
3056}
3057
3058 - 3067
=head2 group_by

Not supported.  C<Database::Join> does not implement the
C<Database::Abstraction::Query> fluent chain entry point because the chain's
C<.all()> / C<.first()> methods would target a single component DA rather
than the merged view.  Calling this method will always C<croak>.

Use C<aggregate()> against the C<Database::Join> object instead.

=cut
3068
3069sub group_by {
3070
1
25
        my $self = $_[0];
3071
1
1
        croak $self->_err('error_group_by_unsupported');
3072}
3073
3074 - 3081
=head2 execute

Not supported.  Raw SQL cannot span heterogeneous backends that may use
different database engines.  Calling this method will always C<croak>.

Use C<selectall_arrayref> or C<fetchrow_hashref> to query the joined view.

=cut
3082
3083sub execute {
3084
8
656
        my $self = $_[0];
3085
8
12
        croak $self->_err('error_execute_unsupported');
3086}
3087
3088 - 3173
=head2 AUTOLOAD - column shortcut

Calling an unknown method whose name matches a visible column name performs
a column lookup across the merged view.

=head3 SYNOPSIS

    # Scalar context: value from the first matching row
    my $name  = $join->name(entry => 'C001');

    # List context: values from every matching row
    my @tiers = $join->tier();

    # With a positional join-key argument (when join_column is 'entry')
    my $score = $join->score('C001');

=head3 DESCRIPTION

AUTOLOAD routes the call to the appropriate component database by looking up
the column name in the internal column-ownership index.

When either C<join_map> or C<filters> is active, AUTOLOAD performs a full
join query instead of delegating directly to the owning database.  This is
necessary because:

=over 4

=item *

With C<join_map>, the owning database's primary key may differ from the
canonical join key used in the call arguments.

=item *

With C<filters>, bypassing the join would return rows that the filter is
meant to exclude.

=back

In list context, every matching merged row contributes one value to the
returned list.  In scalar context, only the first row's value is returned.

Calling a method whose name begins with C<_> (a private method) via AUTOLOAD
will C<croak> with a clear error message rather than being silently ignored.

=head3 EXAMPLE

    # Lookup a single customer's name (scalar context)
    my $name = $join->name('C001');   # 'C001' maps to entry => 'C001'
    print "Name: $name\n";

    # Get every tier value in the view (list context)
    my @all_tiers = $join->tier();
    my %freq;
    $freq{$_}++ for @all_tiers;

    # join_map active: AUTOLOAD runs a full join so the criteria are
    # translated correctly between the canonical and local key names.
    my @leesburg_states = sort $join->state('Leesburg');
    # ['Florida', 'Virginia'] if Leesburg appears in two states

=head3 PSEUDOCODE

    extract column name from $AUTOLOAD
    return if DESTROY
    croak if column name starts with '_' (private method guard)
    croak if column name is not in _col_db (unknown column)
    if join_map or filters are active:
        parse calling arguments using _parse_query_args
        call _joined_query to get all merged rows
        return map { $_->{col} } @rows  in list context
        return $rows[0]{col}            in scalar context
    else:
        delegate directly to the owning database

=head3 MESSAGES

    (croak) Database::Join: cannot call private method '_NAME' via AUTOLOAD
        -- Method name begins with '_'.  Private methods must be called directly,
           not via AUTOLOAD.  This is a programming error.

    (croak) Database::Join: unknown column 'NAME'
        -- Method name does not match any visible column in the merged view.
           Check spelling, or whether the column was removed with remove_column().

=cut
3174
3175our $AUTOLOAD;
3176
3177sub AUTOLOAD {
3178
56
2528
        my $self = shift;
3179
3180
56
143
        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
144
        croak ref($self), ": cannot call private method '$col' via AUTOLOAD"
3192                if substr($col, 0, 1) eq '_';
3193
3194
46
41
        my $db_idx = $self->{_col_db}{$col};
3195
46
104
        croak ref($self), ": unknown column '$col'" unless defined $db_idx;
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
35
24
22
48
31
        if (%{ $self->{_join_map} } || %{ $self->{_filters} }) {
3201                # _autoload_pk is the autoload_pk constructor param (defaults to join_column).
3202
27
44
                my $params   = $self->_parse_query_args($self->{_autoload_pk}, @_);
3203
27
78
                my $sort_by = delete $params->{sort_by};
3204
27
21
                my $limit    = delete $params->{limit};
3205
27
16
                my $offset   = delete $params->{offset};
3206
27
44
                my $rows     = $self->_joined_query($params, sort_by => $sort_by, limit => $limit, offset => $offset);
3207
27
10
9
27
18
8
                return map { $_->{$col} } @{$rows} if wantarray;
3208
18
18
38
50
                return @{$rows} ? $rows->[0]{$col} : undef;
3209        }
3210
3211        # $db is resolved here (not earlier) to avoid a dead store on the join path above.
3212
8
10
        my $db = $self->{_dbs}[$db_idx];
3213
8
16
        return $db->$col(@_);
3214}
3215
3216sub DESTROY {
3217
1351
436450
        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
1351
6600
        if (my $cache = delete $self->{_sqlite_cache}) {
3221
212
146
                local $@;
3222
212
212
310
7456
                eval { $cache->{dbh}->disconnect } if $cache->{dbh};
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.
3237sub _parse_query_args :Protected {
3238        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        return {} unless @args;
3243        $key //= $self->{_join_col};
3244        return { $key => $args[0] }        if @args == 1 && !ref($args[0]);
3245        return get_params(undef, @args) // {};
3246
30
30
30
42921
29
361
}
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.
3251sub _err :Protected {
3252        my ($self, $key, @args) = @_;
3253        return _msg($self->{_i18n}, $key, @args);
3254
30
30
30
7861
20
156
}
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.
3263sub _build_col_index :Protected {
3264        my ($self) = @_;
3265
3266        my $join_col = $self->{_join_col};
3267        my $cp       = $self->{_collision_prefix} // {};
3268        my %col_db;
3269        my @db_cols;
3270        my @col_rename;    # per-db: { orig_col => published_col } for renamed collisions
3271        my @col_unrename;  # per-db: { published_col => orig_col } reverse map
3272
3273        for my $i (0 .. $#{ $self->{_dbs} }) {
3274                my $db        = $self->{_dbs}[$i];
3275                my $local_jc  = $self->{_join_map}{$i} // $join_col;
3276                my $cols      = $db->columns();
3277                $db_cols[$i]      = { map { $_ => 1 } @{$cols} };
3278                $col_rename[$i]   = {};
3279                $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                croak $self->_err('error_join_col_missing', "(join_map[$i] must be a string)", $i, ref($db))
3285                        if ref $local_jc;
3286
3287                croak $self->_err('error_join_col_missing', $local_jc, $i, ref($db))
3288                        unless $db_cols[$i]{$local_jc};
3289
3290                # collision_prefix only applies to secondary databases (index > 0);
3291                # an index-0 entry is meaningless and silently ignored.
3292                my $prefix = ($i > 0) ? $cp->{$i} : undef;
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                croak $self->_err('error_invalid_prefix', $i)
3300                        if defined $prefix && ref $prefix;
3301
3302                for my $col (@{$cols}) {
3303                        # Skip the local alias for the join key — it is not a data column
3304                        next if $local_jc ne $join_col && $col eq $local_jc;
3305
3306                        if (defined $prefix && exists $col_db{$col} && $col ne $join_col) {
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                                my $pub = "$prefix.$col";
3313                                $col_rename[$i]{$col}   = $pub;
3314                                $col_unrename[$i]{$pub} = $col;
3315                                $col_db{$pub} = $i;
3316                        } else {
3317                                # No collision, or no prefix configured: last database wins
3318                                # (preserved backward-compatible behaviour).
3319                                $col_db{$col} = $i;
3320                        }
3321                }
3322        }
3323
3324        $self->{_col_db}       = \%col_db;
3325        $self->{_db_cols}      = \@db_cols;
3326        $self->{_col_rename}   = \@col_rename;
3327        $self->{_col_unrename} = \@col_unrename;
3328
3329        return;
3330
30
30
30
11001
20
188
}
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.
3337sub _validate_schema_types :Protected {
3338        my ($self) = @_;
3339
3340        my $join_col = $self->{_join_col};
3341        my %seen;    # col_name => { idx => $i, type => $type_str }
3342
3343        for my $i (0 .. $#{ $self->{_dbs} }) {
3344                my $db       = $self->{_dbs}[$i];
3345                my $s        = do { local $@; eval { $db->schema() } } // {};
3346                my $local_jc = $self->{_join_map}{$i} // $join_col;
3347                my $renames  = $self->{_col_rename}[$i] // {};
3348
3349                for my $orig_col (keys %{$s}) {
3350                        # Skip the join-key alias (a different name for the same join key)
3351                        next if $local_jc ne $join_col && $orig_col eq $local_jc;
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                        next if $orig_col eq $join_col;
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                        next if exists $renames->{$orig_col};
3361
3362                        # Normalise to a plain type string; skip if the DA returns no type.
3363                        my $entry    = $s->{$orig_col};
3364                        my $type_str = ref($entry) eq 'HASH'
3365                                ? uc($entry->{type} // '')
3366                                : uc($entry // '');
3367                        next unless length $type_str;
3368
3369                        if (exists $seen{$orig_col}) {
3370                                my $prev = $seen{$orig_col};
3371                                if ($prev->{type} ne $type_str) {
3372                                        carp $self->_err(
3373                                                'warn_schema_type_mismatch',
3374                                                $orig_col,
3375                                                $prev->{type}, $prev->{idx},
3376                                                $type_str,     $i,
3377                                        );
3378                                }
3379                        } else {
3380                                $seen{$orig_col} = { idx => $i, type => $type_str };
3381                        }
3382                }
3383        }
3384
3385        return;
3386
30
30
30
9372
20
156
}
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.
3396sub _partition_criteria :Protected {
3397        my ($self, $params) = @_;
3398
3399        my $join_col = $self->{_join_col};
3400        my $n        = scalar @{ $self->{_dbs} };
3401        my @per_db   = map { {} } 1 .. $n;
3402
3403        for my $col (keys %{$params}) {
3404                if ($col eq $join_col) {
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                        my $val = $params->{$col};
3409                        for my $i (0 .. $n - 1) {
3410                                my $local = $self->{_join_map}{$i} // $join_col;
3411                                $per_db[$i]{$local} = ref($val) eq 'HASH' ? { %{$val} } : $val;
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                        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                my $db_col = $self->{_col_unrename}[$idx]{$col} // $col;
3424                        $per_db[$idx]{$db_col} = $params->{$col};
3425                } else {
3426                        carp $self->_err('warn_unknown_column', $col);
3427                }
3428        }
3429
3430        return \@per_db;
3431
30
30
30
10273
17
154
}
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 $@.
3449sub _select_rows {
3450
1557
908
        my ($db, $criteria, $pushdown) = @_;
3451
3452
1557
927
        if ($pushdown) {
3453
137
137
137
137
64
51
85
90
                my $rows = do { local $@; eval { $db->selectall_arrayref($pushdown) } };
3454
137
95346
                return $rows if ref($rows) eq 'ARRAY';
3455        }
3456
3457
1431
1587
        return $db->selectall_arrayref($criteria) // [];
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.
3473sub _understands_in {
3474
545
282
        my $db = shift;
3475
3476
545
922
        my $da_select = Database::Abstraction->can('selectall_arrayref');
3477
545
794
        my $db_select = blessed($db) ? $db->can('selectall_arrayref') : undef;
3478
3479
545
1160
        return ($da_select && $db_select && $db_select == $da_select) ? 1 : 0;
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.
3502sub _pushdown_criteria :Protected {
3503        my ($self, $per_db, $primary_index) = @_;
3504
3505        my @pushdown;
3506        my @keys = $self->{_join_type} eq 'outer' ? () : sort keys %{$primary_index};
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        if (@keys && @keys <= $MAX_PUSHDOWN_KEYS) {
3511                for my $i (1 .. $#{ $self->{_dbs} }) {
3512                        my $db       = $self->{_dbs}[$i];
3513                        my $local_jc = $self->{_join_map}{$i} // $self->{_join_col};
3514                        next if exists $per_db->[$i]{$local_jc};
3515                        next unless _understands_in($db);
3516
3517                        # A copy per database, as in _partition_criteria, so that one
3518                        # database mutating its criteria can't affect another
3519                        $pushdown[$i] = { %{ $per_db->[$i] }, $local_jc => { $DA_IN_OP => [ @keys ] } };
3520                }
3521        }
3522
3523        return \@pushdown;
3524
30
30
30
10105
23
160
}
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.
3535sub _fetch_indexed :Protected {
3536        my ($self, $db_idx, $criteria, $pushdown) = @_;
3537
3538        my $db        = $self->{_dbs}[$db_idx];
3539        my $local_jc  = $self->{_join_map}{$db_idx} // $self->{_join_col};
3540
3541        my $rows = _select_rows($db, $criteria, $pushdown);
3542
3543        my %indexed;
3544        for my $row (@{$rows}) {
3545                my $key = $row->{$local_jc};
3546                next unless defined $key;
3547                push @{ $indexed{$key} }, $row;
3548        }
3549
3550        return \%indexed;
3551
30
30
30
8211
17
139
}
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).
3558sub _joined_query :Protected {
3559        my ($self, $params, %opts) = @_;
3560        my $backend = $self->{_backend};
3561        return $self->_joined_query_array($params, %opts) if $backend eq 'array';
3562        return $self->_sqlite_join($params, %opts);
3563
30
30
30
7179
18
152
}
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.
3594sub _validate_pagination :Protected {
3595        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        if (defined $limit) {
3603                if ($limit !~ /^\d+\z/a || $limit < 1) {
3604                        carp('Database::Join: limit must be a positive integer; ignored');
3605                        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        if (defined $offset) {
3612                if ($offset !~ /^\d+\z/a) {
3613                        carp('Database::Join: offset must be a non-negative integer; ignored');
3614                        undef $offset;
3615                }
3616        }
3617        return ($limit, $offset);
3618
30
30
30
7893
14
162
}
3619
3620sub _joined_query_array :Protected {
3621        my ($self, $params, %opts) = @_;
3622        my $sort_by  = $opts{sort_by};
3623        my $limit    = $opts{limit};
3624        my $offset   = $opts{offset};
3625        my $distinct = $opts{distinct};
3626        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        ($limit, $offset) = $self->_validate_pagination($limit, $offset)
3631                if defined $limit || defined $offset;
3632
3633        my $join_col  = $self->{_join_col};
3634        my $join_type = $self->{_join_type};
3635        my $n         = scalar @{ $self->{_dbs} };
3636
3637        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        for my $i (0 .. $n - 1) {
3643                my $base = $self->{_filters}{$i} // {};
3644                next unless %{$base};
3645                $per_db->[$i] = _merge_criteria($base, $per_db->[$i]);
3646        }
3647
3648        # Fetch and index each database with its own criteria slice.
3649        my @indexed;
3650        $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        my $local_jc_0_early    = $self->{_join_map}{0} // $join_col;
3665        my $sec_has_criteria    = grep { %{ $per_db->[$_] } } 1 .. $n - 1;
3666        return [] if !%{ $indexed[0] }
3667                  && $join_type ne 'outer'
3668                  && !exists $per_db->[0]{$local_jc_0_early}
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        $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        my @pushdown = @{ $self->_pushdown_criteria($per_db, $indexed[0]) };
3700
3701        if ($self->{_parallel} && $n > 2) {
3702                $HAS_THREADS //= do { local $@; eval { require threads; 1 } ? 1 : 0 };
3703                if ($HAS_THREADS) {
3704                        my @thr;
3705                        for my $i (1 .. $n - 1) {
3706                                my ($db, $crit, $push, $local_jc) = (
3707                                        $self->{_dbs}[$i], $per_db->[$i], $pushdown[$i],
3708                                        $self->{_join_map}{$i} // $join_col,
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                                local $@;
3714                                my $t = eval {
3715                                        threads->create(sub {
3716                                                # eval inside the thread: prevents a DA exception from
3717                                                # killing the thread and returning an empty list to join().
3718                                                local $@;
3719                                                my $rows = eval { _select_rows($db, $crit, $push) } // [];
3720                                                my %idx;
3721                                                for my $row (@{$rows}) {
3722                                                        my $key = $row->{$local_jc};
3723                                                        push @{$idx{$key}}, $row if defined $key;
3724                                                }
3725                                                return ($i, \%idx);
3726                                        });
3727                                };
3728                                push @thr, $t if $t;
3729                        }
3730
3731                        my %done;
3732                        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                                local $@;
3736                                my ($i, $idx);
3737                                eval { ($i, $idx) = $t->join() };
3738                                if (defined $i && ref($idx) eq 'HASH') {
3739                                        $indexed[$i] = $idx;
3740                                        $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                        for my $i (1 .. $n - 1) {
3748                                next if $done{$i};
3749                                $indexed[$i] = $self->_fetch_indexed($i, $per_db->[$i], $pushdown[$i]);
3750                        }
3751                } else {
3752                        carp 'Database::Join: parallel => 1 requires the threads module; falling back to sequential';
3753                        $indexed[$_] = $self->_fetch_indexed($_, $per_db->[$_], $pushdown[$_]) for 1 .. $n - 1;
3754                }
3755        } else {
3756                $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        my @had_criteria;
3767        for my $i (1 .. $n - 1) {
3768                my $local_jc   = $self->{_join_map}{$i} // $join_col;
3769                my $has_filter = !!%{ $self->{_filters}{$i} // {} };
3770                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                my $own = (keys %{$crit}) - (exists $crit->{$local_jc} ? 1 : 0);
3775                $had_criteria[$i] = $has_filter || $own;
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        my %key_set;
3783        @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        for my $i (1 .. $n - 1) {
3790                if ($had_criteria[$i] || $join_type eq 'inner') {
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                        for my $k (keys %key_set) {
3795                                delete $key_set{$k} unless exists $indexed[$i]{$k};
3796                        }
3797                } elsif ($join_type eq 'outer') {
3798                        # Union: hash slice assignment is a single Perl op, not a per-key loop.
3799                        @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        my (@sec_local_jc, @sec_rename, @sec_renames);
3812        for my $i (1 .. $n - 1) {
3813                $sec_local_jc[$i] = $self->{_join_map}{$i};
3814                $sec_rename[$i]   = ($sec_local_jc[$i] && $sec_local_jc[$i] ne $join_col) ? 1 : 0;
3815                # _col_rename[$i] is always initialised to {} by _build_col_index / add_database
3816                # (transitive reduction: the // {} fallback can never trigger).
3817                $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        my $removed = ($self->{_removed_list} //= [keys %{ $self->{_removed_cols} }]);
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        my ($ob_col, $ob_dir) = ($join_col, 'ASC');
3831        if (defined $sort_by) {
3832                my ($req_col, $req_dir) = ref($sort_by) eq 'ARRAY' ? @{$sort_by} : ($sort_by, 'ASC');
3833                $req_dir = uc($req_dir // 'ASC');
3834                unless ($req_dir eq 'ASC' || $req_dir eq 'DESC') {
3835                        carp "Database::Join: sort_by direction '$req_dir' is not supported; using ASC";
3836                        $req_dir = 'ASC';
3837                }
3838                if ($req_col ne $join_col && !exists $self->{_col_db}{$req_col}) {
3839                        carp "Database::Join: sort_by column '$req_col' is not in the merged view; result sorted by join_column";
3840                } else {
3841                        ($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        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        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        for my $key ($ob_override ? keys %key_set : sort keys %key_set) {
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                for my $prow (@{ $indexed[0]{$key} // $_EMPTY_PRIMARY_ROW }) {
3861                        my %merged = %{$prow};
3862
3863                        for my $i (1 .. $n - 1) {
3864                                my $sec_arr = $indexed[$i]{$key};
3865                                next unless $sec_arr && @{$sec_arr};
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                                my $src = $sec_arr->[-1];
3874
3875                                if ($sec_rename[$i]) {
3876                                        my $local_jc = $sec_local_jc[$i];
3877                                        my $renames  = $sec_renames[$i];
3878                                        for my $k (keys %{$src}) {
3879                                                if ($k eq $local_jc) {
3880                                                        # Translate local join-key alias to the canonical join_column name
3881                                                        $merged{$join_col} = $src->{$k};
3882                                                } elsif (my $pub = $renames->{$k}) {
3883                                                        $merged{$pub} = $src->{$k};
3884                                                } else {
3885                                                        $merged{$k} = $src->{$k};
3886                                                }
3887                                        }
3888                                } else {
3889                                        my $renames = $sec_renames[$i];
3890                                        for my $k (keys %{$src}) {
3891                                                if (my $pub = $renames->{$k}) {
3892                                                        # Collision-renamed column: write under the published prefixed name
3893                                                        $merged{$pub} = $src->{$k};
3894                                                } else {
3895                                                        $merged{$k} = $src->{$k};
3896                                                }
3897                                        }
3898                                }
3899                        }
3900
3901                        delete @merged{@{$removed}} if @{$removed};
3902                        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        if (@{ $self->{_mandatory_filters} }) {
3910                @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        if ($distinct) {
3917                @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        if ($ob_override) {
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                my @tagged = map { [$_, $_->{$ob_col} // ''] } @result;
3933                if ($ob_dir eq 'DESC') {
3934                        @result = map { $_->[0] } sort { $b->[1] cmp $a->[1] } @tagged;
3935                } else {
3936                        @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                @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        if (defined $offset && $offset > 0) {
3948                splice(@result, 0, $offset);
3949        }
3950        if (defined $limit && $limit < scalar @result) {
3951                splice(@result, $limit);
3952        }
3953
3954        return \@result;
3955
30
30
30
26022
21
235
}
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).
3963sub _cache_fresh :Protected {
3964        my ($self) = @_;
3965
3966        my $cache = $self->{_sqlite_cache} // return 0;
3967        my $n     = scalar @{ $self->{_dbs} };
3968
3969        return 0 if ($cache->{n} // 0) != $n;
3970
3971        # Verify the DBI handle is still usable.
3972        return 0 unless do { local $@; eval { $cache->{dbh}{Active} } };
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        for my $i (0 .. $n - 1) {
3979                my $cached_ts = $cache->{updated}{$i} // next;   # not captured → skip
3980                my $current_ts;
3981                do { local $@; $current_ts = eval { $self->{_dbs}[$i]->updated() } };
3982                next unless defined $current_ts;                  # no updated() → skip
3983                return 0 if $current_ts != $cached_ts;
3984        }
3985
3986        return 1;
3987
30
30
30
9565
31
156
}
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.
4004sub _sql_quote_identifier {
4005
5882
3277
        my ($name) = @_;
4006
5882
3628
        (my $safe = $name) =~ s/"/""/g;
4007
5882
8294
        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.
4016sub _build_sqlite_cache :Protected {
4017        my ($self) = @_;
4018
4019        # Disconnect any previous cache to release the old temp file.
4020        if (my $old = delete $self->{_sqlite_cache}) {
4021                local $@;
4022                eval { $old->{dbh}->disconnect } if $old->{dbh};
4023        }
4024
4025        require DBI;
4026        require File::Temp;
4027
4028        my $join_col = $self->{_join_col};
4029        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                UNLINK => 1,
4038                EXLOCK => 0,
4039        );
4040
4041        my $tmpdbh = DBI->connect(
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        my (@table_refs, @source_cols, @is_attached);
4047
4048        for my $i (0 .. $n - 1) {
4049                my $db       = $self->{_dbs}[$i];
4050                my $local_jc = $self->{_join_map}{$i} // $join_col;
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                if (do { local $@; eval { $db->can('dbi_source') } }) {
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                        my $src = do {
4063                                local $SIG{__WARN__} = sub {};
4064                                local $@;
4065                                eval { $db->dbi_source() }
4066                        };
4067                        if ($src && ref($src) eq 'HASH' && $src->{dbh} && $src->{table}
4068                                && eval { $src->{dbh}{Driver}{Name} } eq 'SQLite') {
4069                                my ($db_file) = $src->{dbh}->selectrow_array(
4070                                        "SELECT file FROM pragma_database_list WHERE name='main'"
4071                                );
4072                                my $alias = "ext$i";
4073                                $tmpdbh->do(sprintf("ATTACH DATABASE %s AS %s",
4074                                        $tmpdbh->quote($db_file), $alias));
4075                                $table_refs[$i]  = $alias . '.' . _sql_quote_identifier($src->{table});
4076                                $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                                $source_cols[$i] = $db->columns();
4081                                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                my $filter_crit = $self->{_filters}{$i} // {};
4088                my $rows        = $db->selectall_arrayref($filter_crit) // [];
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                $source_cols[$i] = $db->columns();
4094
4095                my $tbl  = "t$i";
4096                my $cols = $source_cols[$i] // [];
4097
4098                my $col_defs = join(', ', map { _sql_quote_identifier($_) . ' TEXT' } @{$cols});
4099                $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                $tmpdbh->do('CREATE INDEX ' . _sql_quote_identifier("${tbl}_jc")
4104                        . ' ON ' . _sql_quote_identifier($tbl)
4105                        . ' (' . _sql_quote_identifier($local_jc) . ')');
4106
4107                if (@{$rows}) {
4108                        my $col_list     = join(', ', map { _sql_quote_identifier($_) } @{$cols});
4109                        my $placeholders = join(', ', ('?') x scalar @{$cols});
4110                        my $sth = $tmpdbh->prepare(
4111                                'INSERT INTO ' . _sql_quote_identifier($tbl) . " ($col_list) VALUES ($placeholders)"
4112                        );
4113                        my $batch = 0;
4114                        $tmpdbh->begin_work;
4115                        for my $row (@{$rows}) {
4116                                $sth->execute(map { $row->{$_} } @{$cols});
4117                                if (++$batch >= 1_000) {
4118                                        $tmpdbh->commit;
4119                                        $tmpdbh->begin_work;
4120                                        $batch = 0;
4121                                }
4122                        }
4123                        $tmpdbh->commit;
4124                }
4125                $table_refs[$i]  = _sql_quote_identifier($tbl);
4126                $is_attached[$i] = 0;
4127        }
4128
4129        # Snapshot updated() timestamps for cache-validity checks.
4130        my %updated;
4131        for my $i (0 .. $n - 1) {
4132                local $@;
4133                my $ts = eval { $self->{_dbs}[$i]->updated() };
4134                $updated{$i} = $ts unless $@;
4135        }
4136
4137        $self->{_sqlite_cache} = {
4138                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        return;
4148
30
30
30
17724
24
226
}
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.
4166sub _sqlite_join :Protected {
4167        my ($self, $params, %opts) = @_;
4168        my $count_only   = $opts{count_only} // 0;
4169        my $sort_by      = $opts{sort_by};
4170        my $limit        = $opts{limit};
4171        my $offset       = $opts{offset};
4172        my $create_table = $opts{create_table};  # when set, materialize into a real table
4173        my $distinct     = $opts{distinct};
4174        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        ($limit, $offset) = $self->_validate_pagination($limit, $offset);
4180
4181        my $backend   = $self->{_backend};
4182        my $join_col  = $self->{_join_col};
4183        my $join_type = $self->{_join_type};
4184        my $n         = scalar @{ $self->{_dbs} };
4185
4186        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        if ($backend eq 'auto' && !defined $create_table) {
4194                my $total     = 0;
4195                my $can_count = 1;
4196                for my $i (0 .. $n - 1) {
4197                        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                        if (do { local $@; eval { $db->can('dbi_source') } }) {
4201                                my $src = do {
4202                                        local $SIG{__WARN__} = sub {};
4203                                        local $@;
4204                                        eval { $db->dbi_source() }
4205                                };
4206                                if ($src && ref($src) eq 'HASH' && $src->{dbh} && $src->{table}
4207                                        && 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                                        );
4212                                        $total += $cnt // 0;
4213                                        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                        my $pkg = ref($db) // '';
4221
30
30
30
10606
38
13505
                        if ($pkg && do { no strict 'refs'; defined &{"${pkg}::count"} }) {
4222                                my ($cnt, $failed);
4223                                do { local $@; $cnt = eval { $db->count() }; $failed = $@ };
4224                                if ($failed) {
4225                                        $can_count = 0;
4226                                        last;
4227                                }
4228                                $total += $cnt // 0;
4229                                next;
4230                        }
4231                        $can_count = 0;
4232                        last;
4233                }
4234                if (!$can_count || $total <= $self->{_max_array_rows}) {
4235                        my $rows = $self->_joined_query_array($params,
4236                                sort_by => $sort_by, limit => $limit, offset => $offset);
4237                        return $count_only ? scalar @{$rows} : $rows;
4238                }
4239        }
4240
4241        # Ensure the SQLite cache is valid; rebuild if stale or absent.
4242        $self->_build_sqlite_cache() unless $self->_cache_fresh();
4243
4244        my $cache       = $self->{_sqlite_cache};
4245        my $tmpdbh      = $cache->{dbh};
4246        my @table_refs  = @{ $cache->{table_refs}  };
4247        my @source_cols = @{ $cache->{source_cols} };
4248        my @is_attached = @{ $cache->{is_attached} };
4249
4250        my ($where_sql, $bind_vals_ref) = $self->_sqlite_where(
4251                $per_db_query, $per_db_full, \@table_refs, \@is_attached);
4252        my @bind_vals = @{$bind_vals_ref};
4253
4254        my $local_jc_0 = $self->{_join_map}{0} // $join_col;
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        my $from     = $table_refs[0];
4259        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        if ($count_only) {
4264                my ($cnt) = $tmpdbh->selectrow_array(
4265                        'SELECT COUNT(*) FROM ' . $from . $join_sql . $where_sql,
4266                        undef,
4267                        @bind_vals,
4268                );
4269                return $cnt // 0;
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        my %pub_seen;
4278        my @selects;
4279        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        unless ($self->{_removed_cols}{$join_col}) {
4284                my $jc_expr;
4285                if ($join_type eq 'outer' && $n > 1) {
4286                        $jc_expr = 'COALESCE('
4287                                 . join(', ', map {
4288                                       my $lc = $self->{_join_map}{$_} // $join_col;
4289                                       $table_refs[$_] . '.' . _sql_quote_identifier($lc)
4290                                   } 0 .. $n - 1)
4291                                 . ') AS ' . _sql_quote_identifier($join_col);
4292                } else {
4293                        $jc_expr = $table_refs[0] . '.' . _sql_quote_identifier($local_jc_0);
4294                        $jc_expr .= ' AS ' . _sql_quote_identifier($join_col) if $local_jc_0 ne $join_col;
4295                }
4296                push @selects, $jc_expr;
4297                push @select_pubs, $join_col;
4298                $pub_seen{$join_col} = 1;
4299        }
4300
4301        # Non-join columns from the primary table.
4302        for my $col (@{$source_cols[0] // []}) {
4303                next if $col eq $local_jc_0;    # join column already handled above
4304                next if $self->{_removed_cols}{$col};
4305                $pub_seen{$col} = 1;
4306                push @selects, $table_refs[0] . '.' . _sql_quote_identifier($col);
4307                push @select_pubs, $col;
4308        }
4309
4310        # Non-join columns from secondary tables, with collision_prefix renaming.
4311        for my $i (1 .. $n - 1) {
4312                my $local_jc = $self->{_join_map}{$i} // $join_col;
4313                my $prefix   = $self->{_collision_prefix}{$i};
4314                for my $col (@{$source_cols[$i] // []}) {
4315                        next if $col eq $local_jc;      # join key already contributed above
4316                        my $pub = $col;
4317                        $pub = "$prefix.$col"
4318                                if defined $prefix && exists $pub_seen{$col} && $col ne $join_col;
4319                        next if $self->{_removed_cols}{$pub};
4320                        $pub_seen{$pub} = 1;
4321                        my $expr = $table_refs[$i] . '.' . _sql_quote_identifier($col);
4322                        $expr   .= ' AS ' . _sql_quote_identifier($pub) if $pub ne $col;
4323                        push @selects, $expr;
4324                        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        if ($distinct && $columns && @{$columns}) {
4333                my %want = map { $_ => 1 } @{$columns};
4334                my @filtered;
4335                for my $j (0 .. $#selects) {
4336                        push @filtered, $selects[$j] if $want{ $select_pubs[$j] };
4337                }
4338                @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        if (defined $create_table) {
4350                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                $tmpdbh->do('DROP TABLE IF EXISTS main.' . _sql_quote_identifier($create_table));
4356                $tmpdbh->do('CREATE TABLE main.' . _sql_quote_identifier($create_table)
4357                          . ' AS ' . $mat_sql,
4358                          undef, @bind_vals);
4359                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        my ($ob_col, $ob_dir) = ($join_col, 'ASC');
4368        if (defined $sort_by) {
4369                my ($req_col, $req_dir) = ref($sort_by) eq 'ARRAY' ? @{$sort_by} : ($sort_by, 'ASC');
4370                $req_dir = uc($req_dir // 'ASC');
4371                unless ($req_dir eq 'ASC' || $req_dir eq 'DESC') {
4372                        carp "Database::Join: sort_by direction '$req_dir' is not supported; using ASC";
4373                        $req_dir = 'ASC';
4374                }
4375                if ($req_col ne $join_col && !exists $self->{_col_db}{$req_col}) {
4376                        carp "Database::Join: sort_by column '$req_col' is not in the merged view; result sorted by join_column";
4377                } else {
4378                        ($ob_col, $ob_dir) = ($req_col, $req_dir);
4379                }
4380        }
4381        my $order_expr = ($ob_col eq $join_col)
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        my $select_kw = $distinct ? 'SELECT DISTINCT' : 'SELECT';
4387        my $sql = $select_kw . ' '
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        my @page_bind;
4397        if (defined $limit) {
4398                $sql .= ' LIMIT ?';
4399                push @page_bind, $limit;
4400                if (defined $offset) {
4401                        $sql .= ' OFFSET ?';
4402                        push @page_bind, $offset;
4403                }
4404        } elsif (defined $offset) {
4405                $sql .= ' LIMIT -1 OFFSET ?';
4406                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        my $sth = $tmpdbh->prepare_cached($sql);
4414        $sth->execute(@bind_vals, @page_bind);
4415        return $sth->fetchall_arrayref({});
4416
30
30
30
64
64
241
}
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.
4421sub _sqlite_criteria :Protected {
4422        my ($self, $params) = @_;
4423        my $join_col = $self->{_join_col};
4424        my $n        = scalar @{ $self->{_dbs} };
4425
4426        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        if (my $mf = $self->{_mandatory_filters}) {
4436                for my $pred (@{$mf}) {
4437                        my ($col, $op, $val) = @{$pred}{qw(col op val)};
4438                        my $db_idx = $self->{_col_db}{$col} // next;
4439                        my $orig   = $self->{_col_unrename}[$db_idx]{$col} // $col;
4440                        $per_db_query->[$db_idx]{$orig} = _mandatory_op_to_crit($op, $val);
4441                }
4442        }
4443
4444        my @per_db_full;
4445        for my $i (0 .. $n - 1) {
4446                my $base = $self->{_filters}{$i} // {};
4447                $per_db_full[$i] = %{$base}
4448                        ? _merge_criteria($base, $per_db_query->[$i])
4449                        : $per_db_query->[$i];
4450        }
4451
4452        my @had_criteria;
4453        for my $i (1 .. $n - 1) {
4454                my $local_jc   = $self->{_join_map}{$i} // $join_col;
4455                my $has_filter = !!%{ $self->{_filters}{$i} // {} };
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                my $crit = $per_db_query->[$i];
4460                my $own  = (keys %{$crit}) - (exists $crit->{$local_jc} ? 1 : 0);
4461                $had_criteria[$i] = $has_filter || $own;
4462        }
4463
4464        return ($per_db_query, \@per_db_full, \@had_criteria);
4465
30
30
30
12156
22
167
}
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.
4471sub _sqlite_where :Protected {
4472        my ($self, $per_db_query, $per_db_full, $table_refs, $is_attached) = @_;
4473        my $join_col = $self->{_join_col};
4474        my $n        = scalar @{ $self->{_dbs} };
4475
4476        my (@where_parts, @bind_vals);
4477        for my $i (0 .. $n - 1) {
4478                my $crit = $is_attached->[$i] ? $per_db_full->[$i] : $per_db_query->[$i];
4479                next unless %{$crit};
4480                my $tref       = $table_refs->[$i];
4481                my $local_jc_i = $i > 0 ? ($self->{_join_map}{$i} // $join_col) : undef;
4482                for my $col (sort keys %{$crit}) {
4483                        next if defined $local_jc_i && $col eq $local_jc_i;
4484                        my $val = $crit->{$col};
4485                        if (ref($val) eq 'HASH') {
4486                                for my $op (sort keys %{$val}) {
4487                                        if ($SAFE_LIST_OPS{$op}) {
4488                                                my $arr = $val->{$op};
4489                                                unless (ref($arr) eq 'ARRAY') {
4490                                                        carp "Database::Join: operator '$op' requires an arrayref value; criterion skipped";
4491                                                        next;
4492                                                }
4493                                                my @items = @{$arr};
4494                                                if (!@items) {
4495                                                        push @where_parts, '1 = 0' if $op eq 'IN';
4496                                                        next;
4497                                                }
4498                                                push @where_parts,
4499                                                        $tref . '.' . _sql_quote_identifier($col)
4500                                                        . " $op (" . join(', ', ('?') x scalar @items) . ')';
4501                                                push @bind_vals, @items;
4502                                                next;
4503                                        }
4504                                        if ($SAFE_NOARG_OPS{$op}) {
4505                                                push @where_parts,
4506                                                        $tref . '.' . _sql_quote_identifier($col) . " $op";
4507                                                next;
4508                                        }
4509                                        unless ($SAFE_SQL_OPS{$op}) {
4510                                                carp "Database::Join: operator '$op' is not supported on the SQLite backend; criterion skipped (use the array backend or a supported operator)";
4511                                                next;
4512                                        }
4513                                        push @where_parts,
4514                                                $tref . '.' . _sql_quote_identifier($col) . " $op ?";
4515                                        push @bind_vals, $val->{$op};
4516                                }
4517                        } elsif (!defined $val) {
4518                                push @where_parts,
4519                                        $tref . '.' . _sql_quote_identifier($col) . ' IS NULL';
4520                        } else {
4521                                push @where_parts,
4522                                        $tref . '.' . _sql_quote_identifier($col) . ' = ?';
4523                                push @bind_vals, $val;
4524                        }
4525                }
4526        }
4527        my $where_sql = @where_parts ? ' WHERE ' . join(' AND ', @where_parts) : '';
4528        return ($where_sql, \@bind_vals);
4529
30
30
30
13147
32
177
}
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.
4534sub _sqlite_join_clause :Protected {
4535        my ($self, $table_refs, $had_criteria, $local_jc_0) = @_;
4536        my $join_col  = $self->{_join_col};
4537        my $join_type = $self->{_join_type};
4538        my $n         = scalar @{ $self->{_dbs} };
4539
4540        my $join_sql = '';
4541        for my $i (1 .. $n - 1) {
4542                my $local_jc = $self->{_join_map}{$i} // $join_col;
4543                my $join_kw  = ($had_criteria->[$i] || $join_type eq 'inner') ? 'JOIN'
4544                             : ($join_type eq 'outer')                        ? 'FULL OUTER JOIN'
4545                             :                                                   'LEFT JOIN';
4546                $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        return $join_sql;
4551
30
30
30
8938
20
150
}
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.
4557sub _validate_having :Protected {
4558        my ($self, $having, $valid_keys) = @_;
4559        for my $key (keys %{$having}) {
4560                if ($key eq '-or' || $key eq '-and') {
4561                        my $list = $having->{$key};
4562                        croak $self->_err('error_aggregate_having_key', $key)
4563                                unless ref($list) eq 'ARRAY';
4564                        for my $sub (@{$list}) {
4565                                $self->_validate_having($sub, $valid_keys);
4566                        }
4567                        next;
4568                }
4569                croak $self->_err('error_aggregate_having_key', $key)
4570                        unless exists $valid_keys->{$key};
4571                my $val = $having->{$key};
4572                if (ref($val) eq 'HASH') {
4573                        for my $op (keys %{$val}) {
4574                                unless ($SAFE_SQL_OPS{$op} || $SAFE_LIST_OPS{$op} || $SAFE_NOARG_OPS{$op}) {
4575                                        croak $self->_err('error_aggregate_having_operator', $op, $key);
4576                                }
4577                        }
4578                }
4579        }
4580
30
30
30
10146
19
166
}
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
4594sub _validate_aggregate_spec :Protected {
4595        my ($self, $params) = @_;
4596
4597        my $join_col = $self->{_join_col};
4598        my $n        = scalar @{ $self->{_dbs} };
4599
4600        my $by_raw       = delete $params->{by};
4601        my $measures_raw = delete $params->{measures};
4602        my $having_raw   = delete $params->{having};
4603        my $sort_by_raw  = delete $params->{sort_by};
4604        my $limit_raw    = delete $params->{limit};
4605        my $offset_raw   = delete $params->{offset};
4606
4607        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        $by_raw = [] unless defined $by_raw;
4611        croak $self->_err('error_aggregate_by_invalid')
4612                unless ref($by_raw) eq 'ARRAY';
4613
4614        my @by_names;
4615        for my $col (@{$by_raw}) {
4616                croak $self->_err('error_aggregate_by_invalid')
4617                        unless defined $col && length $col;
4618                my $owner = $self->{_col_db}{$col};
4619                croak $self->_err('error_aggregate_col_unknown', $col)
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                if ($col ne $join_col && index($col, '.') < 0) {
4624                        for my $j (0 .. $n - 1) {
4625                                next if $j == $owner;
4626                                if ($self->{_db_cols}[$j]{$col}
4627                                                && !exists $self->{_col_rename}[$j]{$col}) {
4628                                        croak $self->_err('error_col_conflict', $col);
4629                                }
4630                        }
4631                }
4632                my $db_col = $self->{_col_unrename}[$owner]{$col} // $col;
4633                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                unless ref($measures_raw) eq 'ARRAY' && @{$measures_raw};
4639
4640        my (@measures, %aliases, %by_name_set);
4641        $by_name_set{ $_->{name} } = 1 for @by_names;
4642
4643        for my $m (@{$measures_raw}) {
4644                croak $self->_err('error_aggregate_measure_ref', ref($m) || 'SCALAR')
4645                        unless ref($m) eq 'HASH';
4646
4647                my $fn = lc($m->{fn} // '');
4648                croak $self->_err('error_aggregate_fn_unknown', $m->{fn} // '')
4649                        unless $AGGREGATE_FNS{$fn};
4650
4651                my $col = $m->{col};
4652                my ($m_owner, $m_db_col, $m_is_numeric);
4653                if (defined $col) {
4654                        my $col_owner = $self->{_col_db}{$col};
4655                        croak $self->_err('error_aggregate_col_unknown', $col)
4656                                unless defined $col_owner;
4657                        if ($col ne $join_col && index($col, '.') < 0) {
4658                                for my $j (0 .. $n - 1) {
4659                                        next if $j == $col_owner;
4660                                        if ($self->{_db_cols}[$j]{$col}
4661                                                        && !exists $self->{_col_rename}[$j]{$col}) {
4662                                                croak $self->_err('error_col_conflict', $col);
4663                                        }
4664                                }
4665                        }
4666                        $m_owner  = $col_owner;
4667                        $m_db_col = $self->{_col_unrename}[$col_owner]{$col} // $col;
4668                        my $schema = do { local $@; eval { $self->{_dbs}[$col_owner]->schema() } } // {};
4669                        my $entry  = $schema->{$m_db_col};
4670                        my $type   = uc(ref($entry) eq 'HASH' ? ($entry->{type} // '') : ($entry // ''));
4671                        $m_is_numeric = ($type =~ /INT|REAL|FLOAT|DOUBLE|DECIMAL|NUMERIC/) ? 1 : 0;
4672                } else {
4673                        croak $self->_err('error_aggregate_col_required', $fn)
4674                                if $fn ne 'count';
4675                }
4676
4677                my $as = $m->{as};
4678                croak $self->_err('error_aggregate_as_required')
4679                        unless defined $as && length $as;
4680                croak $self->_err('error_aggregate_as_invalid', $as)
4681                        unless $as =~ /^\w+\z/;
4682                croak $self->_err('error_aggregate_as_duplicate', $as)
4683                        if exists $aliases{$as};
4684                croak $self->_err('error_aggregate_as_collision', $as)
4685                        if exists $by_name_set{$as};
4686
4687                $aliases{$as} = 1;
4688                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        my %valid_having_keys = (%by_name_set, %aliases);
4700        if (defined $having_raw && %{$having_raw}) {
4701                $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        my ($sort_col, $sort_dir) = (undef, 'ASC');
4706        if (defined $sort_by_raw) {
4707                my ($req_col, $req_dir);
4708                if (ref($sort_by_raw) eq 'ARRAY') {
4709                        ($req_col, $req_dir) = @{$sort_by_raw};
4710                } else {
4711                        ($req_col, $req_dir) = ($sort_by_raw, 'ASC');
4712                }
4713                $req_dir = uc($req_dir // 'ASC');
4714                unless ($req_dir eq 'ASC' || $req_dir eq 'DESC') {
4715                        carp "Database::Join: sort_by direction '$req_dir' is not supported; using ASC";
4716                        $req_dir = 'ASC';
4717                }
4718                if (exists $valid_having_keys{$req_col}) {
4719                        ($sort_col, $sort_dir) = ($req_col, $req_dir);
4720                } else {
4721                        carp $self->_err('warn_aggregate_sort_key', $req_col);
4722                }
4723        }
4724
4725        return {
4726                by       => \@by_names,
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
30
30
30
19058
15
213
}
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.
4741sub _normalise_aggregate :Protected {
4742        my ($self, $rows, $measures) = @_;
4743        for my $row (@{$rows}) {
4744                for my $m (@{$measures}) {
4745                        my $fn = $m->{fn};
4746                        next if defined $row->{ $m->{as} };
4747                        if ($fn eq 'sum' || $fn eq 'count' || $fn eq 'count_distinct') {
4748                                $row->{ $m->{as} } = 0;
4749                        }
4750                }
4751        }
4752
30
30
30
9044
21
149
}
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.
4757sub _match_having_criterion :Protected {
4758        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        if (ref($criterion) eq 'HASH') {
4764                if (exists $criterion->{'NOT IN'}
4765                                && ref($criterion->{'NOT IN'}) eq 'ARRAY'
4766                                && !@{ $criterion->{'NOT IN'} }) {
4767                        return 1;
4768                }
4769                if (exists $criterion->{'IN'}
4770                                && ref($criterion->{'IN'}) eq 'ARRAY'
4771                                && !@{ $criterion->{'IN'} }) {
4772                        return 0;
4773                }
4774        }
4775
4776        if (!defined $value) {
4777                # NULL satisfies: (1) bare undef criterion (IS NULL shorthand), or (2) IS NULL.
4778                return 1 unless defined $criterion;
4779                return (ref($criterion) eq 'HASH' && exists $criterion->{'IS NULL'}) ? 1 : 0;
4780        }
4781        if (!defined $criterion) {
4782                # bare undef means IS NULL; value is defined → false
4783                return 0;
4784        }
4785        if (ref($criterion) eq 'HASH') {
4786                for my $op (keys %{$criterion}) {
4787                        my $rhs = $criterion->{$op};
4788                        if ($SAFE_NOARG_OPS{$op}) {
4789                                return 0 if $op eq 'IS NULL';   # value is defined
4790                                # IS NOT NULL → pass
4791                        } elsif ($SAFE_LIST_OPS{$op}) {
4792                                my @items = ref($rhs) eq 'ARRAY' ? @{$rhs} : ();
4793                                if ($op eq 'IN') {
4794                                        return 0 unless grep { defined $_ && $_ eq $value } @items;
4795                                } else {
4796                                        return 0 if grep { defined $_ && $_ eq $value } @items;
4797                                }
4798                        } elsif ($SAFE_SQL_OPS{$op}) {
4799                                my $num = looks_like_number($value) && looks_like_number($rhs);
4800                                my $ok;
4801                                if    ($op eq '=')        { $ok = $num ? $value == $rhs : $value eq $rhs }
4802                                elsif ($op eq '!=')       { $ok = $num ? $value != $rhs : $value ne $rhs }
4803                                elsif ($op eq '>')        { $ok = $num ? $value > $rhs  : $value gt $rhs }
4804                                elsif ($op eq '<')        { $ok = $num ? $value < $rhs  : $value lt $rhs }
4805                                elsif ($op eq '>=')       { $ok = $num ? $value >= $rhs : $value ge $rhs }
4806                                elsif ($op eq '<=')       { $ok = $num ? $value <= $rhs : $value le $rhs }
4807                                elsif ($op eq 'LIKE') {
4808                                        my $pat = quotemeta($rhs);
4809                                        $pat =~ s/\\%/.*/g;
4810                                        $pat =~ s/\\_/./g;
4811                                        $ok = ($value =~ /\A$pat\z/i);
4812                                } elsif ($op eq 'NOT LIKE') {
4813                                        my $pat = quotemeta($rhs);
4814                                        $pat =~ s/\\%/.*/g;
4815                                        $pat =~ s/\\_/./g;
4816                                        $ok = ($value !~ /\A$pat\z/i);
4817                                } else {
4818                                        $ok = 0;
4819                                }
4820                                return 0 unless $ok;
4821                        } else {
4822                                croak $self->_err('error_aggregate_having_operator', $op, $key);
4823                        }
4824                }
4825                return 1;
4826        }
4827        # Bare scalar: equality
4828        return looks_like_number($value) && looks_like_number($criterion)
4829                ? ($value == $criterion ? 1 : 0)
4830                : ($value eq $criterion ? 1 : 0);
4831
30
30
30
13467
16
183
}
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.
4837sub _match_criteria :Protected {
4838        my ($self, $row, $criteria) = @_;
4839        for my $key (keys %{$criteria}) {
4840                if ($key eq '-or') {
4841                        my $any = 0;
4842                        for my $sub (@{ $criteria->{$key} }) {
4843                                if ($self->_match_criteria($row, $sub)) { $any = 1; last }
4844                        }
4845                        return 0 unless $any;
4846                } elsif ($key eq '-and') {
4847                        for my $sub (@{ $criteria->{$key} }) {
4848                                return 0 unless $self->_match_criteria($row, $sub);
4849                        }
4850                } else {
4851                        my $val = exists $row->{$key} ? $row->{$key} : undef;
4852                        return 0 unless $self->_match_having_criterion($val, $criteria->{$key}, $key);
4853                }
4854        }
4855        return 1;
4856
30
30
30
10328
18
151
}
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().
4861sub _fold_aggregate :Protected {
4862        my ($self, $rows, $spec) = @_;
4863        my @by      = @{ $spec->{by} };
4864        my @measures = @{ $spec->{measures} };
4865
4866        my (%groups, @order);
4867
4868        my $new_group = sub {
4869                my ($row) = @_;
4870                my %g;
4871                for my $b (@by) {
4872                        $g{ $b->{name} } = exists $row->{ $b->{name} }
4873                                ? $row->{ $b->{name} } : undef;
4874                }
4875                for my $m (@measures) {
4876                        my ($fn, $as) = ($m->{fn}, $m->{as});
4877                        if    ($fn eq 'sum')            { $g{"${as}__sum"} = 0; $g{"${as}__bad"} = 0; $g{"${as}__badval"} = undef }
4878                        elsif ($fn eq 'avg')            { $g{"${as}__sum"} = 0; $g{"${as}__cnt"} = 0; $g{"${as}__bad"} = 0; $g{"${as}__badval"} = undef }
4879                        elsif ($fn eq 'min' || $fn eq 'max') { $g{"${as}__val"} = undef }
4880                        elsif ($fn eq 'count')          { $g{"${as}__cnt"} = 0 }
4881                        elsif ($fn eq 'count_distinct') { $g{"${as}__seen"} = {} }
4882                }
4883                return \%g;
4884        };
4885
4886        for my $row (@{$rows}) {
4887                my $key = join("\x00",
4888                        map { defined $row->{ $_->{name} } ? $row->{ $_->{name} } : '' }
4889                        @by);
4890                my $g = $groups{$key} //= do { push @order, $key; $new_group->($row) };
4891
4892                for my $m (@measures) {
4893                        my ($fn, $as, $col) = ($m->{fn}, $m->{as}, $m->{col});
4894                        my $val = defined $col
4895                                ? (exists $row->{$col} ? $row->{$col} : undef)
4896                                : undef;
4897
4898                        if ($fn eq 'sum') {
4899                                if (defined $val && $val ne '' && looks_like_number($val)) {
4900                                        $g->{"${as}__sum"} += $val;
4901                                } elsif (defined $val && $val ne '') {
4902                                        $g->{"${as}__bad"}++;
4903                                        $g->{"${as}__badval"} //= $val;
4904                                }
4905                        } elsif ($fn eq 'avg') {
4906                                if (defined $val && $val ne '' && looks_like_number($val)) {
4907                                        $g->{"${as}__sum"} += $val;
4908                                        $g->{"${as}__cnt"}++;
4909                                } elsif (defined $val && $val ne '') {
4910                                        $g->{"${as}__bad"}++;
4911                                        $g->{"${as}__badval"} //= $val;
4912                                }
4913                        } elsif ($fn eq 'min') {
4914                                if (defined $val) {
4915                                        my $cur = $g->{"${as}__val"};
4916                                        if (!defined $cur) {
4917                                                $g->{"${as}__val"} = $val;
4918                                        } else {
4919                                                my $num = looks_like_number($cur) && looks_like_number($val);
4920                                                $g->{"${as}__val"} = $val if $num ? $val < $cur : $val lt $cur;
4921                                        }
4922                                }
4923                        } elsif ($fn eq 'max') {
4924                                if (defined $val) {
4925                                        my $cur = $g->{"${as}__val"};
4926                                        if (!defined $cur) {
4927                                                $g->{"${as}__val"} = $val;
4928                                        } else {
4929                                                my $num = looks_like_number($cur) && looks_like_number($val);
4930                                                $g->{"${as}__val"} = $val if $num ? $val > $cur : $val gt $cur;
4931                                        }
4932                                }
4933                        } elsif ($fn eq 'count') {
4934                                if (!defined $col) {
4935                                        $g->{"${as}__cnt"}++;
4936                                } else {
4937                                        $g->{"${as}__cnt"}++ if defined $val;
4938                                }
4939                        } elsif ($fn eq 'count_distinct') {
4940                                $g->{"${as}__seen"}{$val} = 1 if defined $val;
4941                        }
4942                }
4943        }
4944
4945        # Grand total with no rows and no by: synthesise one zeroed row.
4946        if (!@by && !@order) {
4947                push @order, '';
4948                $groups{''} = $new_group->({});
4949        }
4950
4951        # Finalise accumulators into result rows.
4952        my (@result, %bad_warned);
4953        for my $key (@order) {
4954                my $g = $groups{$key};
4955                my %row;
4956                for my $b (@by)     { $row{ $b->{name} } = $g->{ $b->{name} } }
4957                for my $m (@measures) {
4958                        my ($fn, $as, $col) = ($m->{fn}, $m->{as}, $m->{col} // '(row)');
4959                        if ($fn eq 'sum') {
4960                                if ($g->{"${as}__bad"} && !$bad_warned{$as}) {
4961                                        carp $self->_err('warn_aggregate_non_numeric',
4962                                                $col, $g->{"${as}__bad"}, $g->{"${as}__badval"});
4963                                        $bad_warned{$as} = 1;
4964                                }
4965                                $row{$as} = $g->{"${as}__sum"};
4966                        } elsif ($fn eq 'avg') {
4967                                if ($g->{"${as}__bad"} && !$bad_warned{$as}) {
4968                                        carp $self->_err('warn_aggregate_non_numeric',
4969                                                $col, $g->{"${as}__bad"}, $g->{"${as}__badval"});
4970                                        $bad_warned{$as} = 1;
4971                                }
4972                                $row{$as} = $g->{"${as}__cnt"}
4973                                        ? $g->{"${as}__sum"} / $g->{"${as}__cnt"}
4974                                        : undef;
4975                        } elsif ($fn eq 'min' || $fn eq 'max') {
4976                                $row{$as} = $g->{"${as}__val"};
4977                        } elsif ($fn eq 'count') {
4978                                $row{$as} = $g->{"${as}__cnt"};
4979                        } elsif ($fn eq 'count_distinct') {
4980                                $row{$as} = scalar keys %{ $g->{"${as}__seen"} };
4981                        }
4982                }
4983                push @result, \%row;
4984        }
4985        return \@result;
4986
30
30
30
20368
19
203
}
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).
4991sub _sort_and_page :Protected {
4992        my ($self, $rows, $spec) = @_;
4993        my $sort   = $spec->{sort};
4994        my $limit  = $spec->{limit};
4995        my $offset = $spec->{offset};
4996        my @by     = @{ $spec->{by} };
4997
4998        if (defined $sort) {
4999                my ($sc, $sd) = @{$sort};
5000                @{$rows} = sort {
5001                        my ($va, $vb) = ($a->{$sc}, $b->{$sc});
5002                        my $cmp;
5003                        if    (!defined $va && !defined $vb) { $cmp = 0 }
5004                        elsif (!defined $va)                 { $cmp = -1 }
5005                        elsif (!defined $vb)                 { $cmp = 1 }
5006                        else {
5007                                $cmp = looks_like_number($va) && looks_like_number($vb)
5008                                        ? $va <=> $vb : $va cmp $vb;
5009                        }
5010                        $sd eq 'DESC' ? -$cmp : $cmp;
5011                } @{$rows};
5012        } elsif (@by) {
5013                @{$rows} = sort {
5014                        my $cmp = 0;
5015                        for my $dim (@by) {
5016                                my $k = $dim->{name};
5017                                my ($va, $vb) = ($a->{$k}, $b->{$k});
5018                                if    (!defined $va && !defined $vb) { $cmp = 0 }
5019                                elsif (!defined $va)                 { $cmp = -1 }
5020                                elsif (!defined $vb)                 { $cmp = 1 }
5021                                else {
5022                                        $cmp = looks_like_number($va) && looks_like_number($vb)
5023                                                ? $va <=> $vb : $va cmp $vb;
5024                                }
5025                                last if $cmp;
5026                        }
5027                        $cmp;
5028                } @{$rows};
5029        }
5030
5031        splice(@{$rows}, 0, $offset) if defined $offset && $offset > 0;
5032        splice(@{$rows}, $limit)     if defined $limit  && $limit < scalar @{$rows};
5033
30
30
30
11773
15
167
}
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.
5042sub _having_to_sql :Protected {
5043        my ($self, $having, $have_map) = @_;
5044        my (@parts, @binds);
5045
5046        for my $key (sort keys %{$having}) {
5047                if ($key eq '-or') {
5048                        my (@sp, @sb);
5049                        for my $sub (@{ $having->{$key} }) {
5050                                my ($s, $b) = $self->_having_to_sql($sub, $have_map);
5051                                push @sp, $s if length $s;
5052                                push @sb, @{$b};
5053                        }
5054                        if (@sp) {
5055                                push @parts, '(' . join(' OR ', @sp) . ')';
5056                                push @binds, @sb;
5057                        }
5058                        next;
5059                }
5060                if ($key eq '-and') {
5061                        my (@sp, @sb);
5062                        for my $sub (@{ $having->{$key} }) {
5063                                my ($s, $b) = $self->_having_to_sql($sub, $have_map);
5064                                push @sp, $s if length $s;
5065                                push @sb, @{$b};
5066                        }
5067                        if (@sp) {
5068                                push @parts, '(' . join(' AND ', @sp) . ')';
5069                                push @binds, @sb;
5070                        }
5071                        next;
5072                }
5073
5074                my $entry  = $have_map->{$key};
5075                my $expr   = $entry ? $entry->{expr}   : _sql_quote_identifier($key);
5076                my $is_agg = $entry ? $entry->{is_agg} : 0;
5077                my $val    = $having->{$key};
5078
5079                if (!defined $val) {
5080                        push @parts, "$expr IS NULL";
5081                } elsif (ref($val) eq 'HASH') {
5082                        for my $op (sort keys %{$val}) {
5083                                if ($SAFE_NOARG_OPS{$op}) {
5084                                        push @parts, "$expr $op";
5085                                } elsif ($SAFE_LIST_OPS{$op}) {
5086                                        my $arr   = $val->{$op};
5087                                        my @items = ref($arr) eq 'ARRAY' ? @{$arr} : ();
5088                                        if (!@items) {
5089                                                push @parts, '1 = 0' if $op eq 'IN';
5090                                                next;
5091                                        }
5092                                        push @parts,
5093                                                "$expr $op (" . join(', ', ('?') x scalar @items) . ')';
5094                                        push @binds, @items;
5095                                } elsif ($SAFE_SQL_OPS{$op}) {
5096                                        my $bind = $is_agg ? 'CAST(? AS REAL)' : '?';
5097                                        push @parts, "$expr $op $bind";
5098                                        push @binds, $val->{$op};
5099                                } else {
5100                                        croak $self->_err('error_aggregate_having_operator', $op, $key);
5101                                }
5102                        }
5103                } else {
5104                        push @parts, "$expr = ?";
5105                        push @binds, $val;
5106                }
5107        }
5108
5109        return (join(' AND ', @parts), \@binds);
5110
30
30
30
13272
17
163
}
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.
5117sub _sqlite_aggregate :Protected {
5118        my ($self, $params, $spec) = @_;
5119        my $join_col  = $self->{_join_col};
5120        my $join_type = $self->{_join_type};
5121        my $n         = scalar @{ $self->{_dbs} };
5122
5123        my ($per_db_query, $per_db_full, $had_criteria) = $self->_sqlite_criteria($params);
5124
5125        $self->_build_sqlite_cache() unless $self->_cache_fresh();
5126        my $cache       = $self->{_sqlite_cache};
5127        my $tmpdbh      = $cache->{dbh};
5128        my @table_refs  = @{ $cache->{table_refs}  };
5129        my @is_attached = @{ $cache->{is_attached} };
5130
5131        my $local_jc_0 = $self->{_join_map}{0} // $join_col;
5132        my $from        = $table_refs[0];
5133
5134        my ($where_sql, $where_binds) = $self->_sqlite_where(
5135                $per_db_query, $per_db_full, \@table_refs, \@is_attached);
5136        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        my @by_exprs;
5140        my @by_select;
5141        my %have_map;   # key => { expr, is_agg } for _having_to_sql
5142
5143        for my $b (@{ $spec->{by} }) {
5144                my ($bname, $owner, $db_col) = @{$b}{qw(name owner db_col)};
5145                my $expr;
5146                if ($bname eq $join_col) {
5147                        if ($join_type eq 'outer' && $n > 1) {
5148                                $expr = 'COALESCE('
5149                                      . join(', ', map {
5150                                            my $lc = $self->{_join_map}{$_} // $join_col;
5151                                            $table_refs[$_] . '.' . _sql_quote_identifier($lc)
5152                                        } 0 .. $n - 1)
5153                                      . ')';
5154                        } else {
5155                                $expr = $table_refs[0] . '.' . _sql_quote_identifier($local_jc_0);
5156                        }
5157                } else {
5158                        $expr = $table_refs[$owner] . '.' . _sql_quote_identifier($db_col);
5159                }
5160                push @by_exprs, $expr;
5161                # Dotted names (collision_prefix) need an AS alias so fetchall_arrayref({})
5162                # returns the right key.
5163                push @by_select, ($bname =~ /\./)
5164                        ? "$expr AS " . _sql_quote_identifier($bname)
5165                        : $expr;
5166                $have_map{$bname} = { expr => $expr, is_agg => 0 };
5167        }
5168
5169        # Build measure expressions (SELECT list / HAVING substitution).
5170        my @measure_select;
5171        for my $m (@{ $spec->{measures} }) {
5172                my ($fn, $as, $owner, $db_col, $is_numeric) =
5173                        @{$m}{qw(fn as owner db_col is_numeric)};
5174                $is_numeric //= 0;
5175
5176                my $col_ref = defined $db_col
5177                        ? $table_refs[$owner] . '.' . _sql_quote_identifier($db_col)
5178                        : undef;
5179
5180                my $sql_expr;
5181                if    ($fn eq 'sum')            { $sql_expr = "SUM(CAST($col_ref AS REAL))" }
5182                elsif ($fn eq 'avg')            { $sql_expr = "AVG(CAST($col_ref AS REAL))" }
5183                elsif ($fn eq 'min')            {
5184                        $sql_expr = $is_numeric ? "MIN(CAST($col_ref AS REAL))" : "MIN($col_ref)" }
5185                elsif ($fn eq 'max')            {
5186                        $sql_expr = $is_numeric ? "MAX(CAST($col_ref AS REAL))" : "MAX($col_ref)" }
5187                elsif ($fn eq 'count')          {
5188                        $sql_expr = defined $col_ref ? "COUNT($col_ref)" : 'COUNT(*)' }
5189                elsif ($fn eq 'count_distinct') { $sql_expr = "COUNT(DISTINCT $col_ref)" }
5190
5191                push @measure_select, "$sql_expr AS " . _sql_quote_identifier($as);
5192                $have_map{$as} = { expr => $sql_expr, is_agg => 1 };
5193        }
5194
5195        my $groupby_sql = @by_exprs
5196                ? ' GROUP BY ' . join(', ', @by_exprs)
5197                : '';
5198
5199        # HAVING clause.
5200        my ($having_sql, $having_binds) = ('', []);
5201        if (defined $spec->{having} && %{ $spec->{having} }) {
5202                my ($h_sql, $h_binds) = $self->_having_to_sql($spec->{having}, \%have_map);
5203                if (length $h_sql) {
5204                        $having_sql   = ' HAVING ' . $h_sql;
5205                        $having_binds = $h_binds;
5206                }
5207        }
5208
5209        # ORDER BY: default = by expressions ascending; override via spec->{sort}.
5210        my $order_sql;
5211        if (defined $spec->{sort}) {
5212                my ($sc, $sd) = @{ $spec->{sort} };
5213                my $sort_expr = $have_map{$sc} ? $have_map{$sc}{expr}
5214                                               : _sql_quote_identifier($sc);
5215                $order_sql = ' ORDER BY ' . $sort_expr . ($sd eq 'DESC' ? ' DESC' : '');
5216        } elsif (@by_exprs) {
5217                $order_sql = ' ORDER BY ' . join(', ', @by_exprs);
5218        } else {
5219                $order_sql = '';
5220        }
5221
5222        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        my @page_bind;
5231        my ($limit, $offset) = ($spec->{limit}, $spec->{offset});
5232        if (defined $limit) {
5233                $sql .= ' LIMIT ?';
5234                push @page_bind, $limit;
5235                if (defined $offset) { $sql .= ' OFFSET ?'; push @page_bind, $offset }
5236        } elsif (defined $offset) {
5237                $sql .= ' LIMIT -1 OFFSET ?';
5238                push @page_bind, $offset;
5239        }
5240
5241        my $sth = $tmpdbh->prepare_cached($sql);
5242        $sth->execute(@{$where_binds}, @{$having_binds}, @page_bind);
5243        my $rows = $sth->fetchall_arrayref({}) // [];
5244
5245        $self->_normalise_aggregate($rows, $spec->{measures});
5246
5247        # Grand total with no by and no matching rows: synthesise one normalised row.
5248        if (!@{ $spec->{by} } && !@{$rows}) {
5249                my %row = map { $_->{as} => undef } @{ $spec->{measures} };
5250                $self->_normalise_aggregate([\%row], $spec->{measures});
5251                return [\%row];
5252        }
5253
5254        return $rows;
5255
30
30
30
19188
16
204
}
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.
5263sub _mandatory_op_to_crit {
5264
3
3
        my ($op, $val) = @_;
5265
3
5
        return $val                  if $op eq 'eq';
5266
0
0
        return { '!='  => $val }     if $op eq 'ne';
5267
0
0
        return { '<'   => $val }     if $op eq 'lt';
5268
0
0
        return { '<='  => $val }     if $op eq 'lte';
5269
0
0
        return { '>'   => $val }     if $op eq 'gt';
5270
0
0
        return { '>='  => $val }     if $op eq 'gte';
5271
0
0
        return { LIKE  => $val }     if $op eq 'like';
5272
0
0
        return { LIKE  => "%$val%" } if $op eq 'contains';
5273
0
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.
5281sub _pass_mandatory_filters {
5282
62
35
        my ($row, $filters) = @_;
5283
62
62
20
29
        for my $pred (@{$filters}) {
5284
65
65
28
32
                my ($col, $op, $val) = @{$pred}{qw(col op val)};
5285
65
39
                my $rv = $row->{$col};
5286
65
28
                return 0 unless defined $rv;
5287
65
45
48
32
                if    ($op eq 'eq')       { return 0 unless $rv eq $val }
5288
5
7
                elsif ($op eq 'ne')       { return 0 unless $rv ne $val }
5289
0
0
                elsif ($op eq 'lt')       { return 0 unless $rv lt $val }
5290
0
0
                elsif ($op eq 'lte')      { return 0 unless $rv le $val }
5291
5
4
                elsif ($op eq 'gt')       { return 0 unless $rv gt $val }
5292
0
0
                elsif ($op eq 'gte')      { return 0 unless $rv ge $val }
5293
5
5
                elsif ($op eq 'contains') { return 0 unless index($rv, $val) >= 0 }
5294                elsif ($op eq 'like') {
5295                        # _re was pre-compiled at construction time; no per-row regex build.
5296
5
8
                        return 0 unless $rv =~ $pred->{_re};
5297                }
5298        }
5299
31
28
        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.
5311sub _apply_distinct_array {
5312
7
3
        my ($rows, $columns) = @_;
5313
7
5
        my %seen;
5314        my @result;
5315
7
6
3
5
        if ($columns && @{$columns}) {
5316
6
6
3
5
                my @cols = @{$columns};
5317
6
6
4
3
                for my $row (@{$rows}) {
5318
23
30
12
23
                        my $key = join("\0", map { $row->{$_} // '' } @cols);
5319
23
19
                        next if $seen{$key}++;
5320
15
21
6
18
                        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
1
1
1
1
2
                my @col_order = @{$rows} ? sort keys %{ $rows->[0] } : ();
5326
1
1
1
0
                for my $row (@{$rows}) {
5327
5
20
3
15
                        my $key = join("\0", map { ($row->{$_} // '') } @col_order);
5328
5
6
                        next if $seen{$key}++;
5329
5
2
                        push @result, $row;
5330                }
5331        }
5332
7
11
        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.
5343sub _merge_criteria :Protected {
5344        my ($base, $extra) = @_;
5345        my %merged = %{$base};
5346        for my $col (keys %{$extra}) {
5347                if (exists $merged{$col}
5348                        && ref($merged{$col}) eq 'HASH'
5349                        && ref($extra->{$col}) eq 'HASH') {
5350                        $merged{$col} = { %{ $merged{$col} }, %{ $extra->{$col} } };
5351                } else {
5352                        $merged{$col} = $extra->{$col};
5353                }
5354        }
5355        return \%merged;
5356
30
30
30
14324
16
181
}
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.
5366sub _copy_criteria {
5367
101
70
        my ($criteria) = @_;
5368
101
101
94
133
        return {} unless $criteria && %{$criteria};
5369        return {
5370                map {
5371                        $_ => ref($criteria->{$_}) eq 'HASH'
5372
59
450
                                ? { %{ $criteria->{$_} } }  # shallow-copy operator sub-hashref
5373
96
385
                                : $criteria->{$_}
5374
95
95
51
77
                } 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.
5384sub _copy_filters {
5385
1314
1092
        my ($filters) = @_;
5386
1314
82
10728
100
        return {} unless $filters && %{$filters};
5387
81
82
81
57
104
60
        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.
5395sub _msg :Protected {
5396        my ($i18n, $key, @args) = @_;
5397
5398        if ($i18n && $i18n->can('translate')) {
5399                return $i18n->translate($key, @args);
5400        }
5401
5402        my $fmt = $MESSAGES{$key}
5403                // sprintf($MESSAGES{error_unknown_message}, $key);
5404
5405        return @args ? sprintf($fmt, @args) : $fmt;
5406
30
30
30
11086
18
155
}
5407
54081;
5409