lib/Database/Join.pm

Structural Coverage (Approximate)

TER1 (Statement): 97.66%
TER2 (Branch): 81.72%
TER3 (LCSAJ): 100.0% (82/82)
Approximate LCSAJ segments: 187

LCSAJ Legend

● Covered — this LCSAJ path was executed during testing.

● Not covered — this LCSAJ path was never executed. These are the paths to focus on.

Multiple dots on a line indicate that multiple control-flow paths begin at that line. Hovering over any dot shows:

        start → end → jump
        

Uncovered paths show [NOT COVERED] in the tooltip.

Mutant Testing Legend

Survived (tests missed this) Killed (tests detected this) No mutation
    1: package Database::Join;
    2: 
    3: # ABSTRACT: Combined view across two or more Database::Abstraction objects
    4: 
    5: use 5.010001;
    6: use strict;
    7: use warnings;
    8: use autodie qw(:all);
    9: 
   10: use Carp qw(croak carp);
   11: use File::Spec;
   12: use List::Util qw(max);
   13: use Log::Abstraction;
   14: use Readonly;
   15: use Scalar::Util qw(blessed looks_like_number);
   16: use Object::Configure;
   17: use Params::Get qw(get_params);
   18: use Params::Validate::Strict qw(validate_strict);
   19: 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.
   23: Readonly::Array my @_ADD_DB_KEYS => qw(database join_column filter remove_columns);
   24: 
   25: # SQL comparison operators that are safe to interpolate into WHERE clauses.
   26: # Scalar-binding operators: the value is always passed as a bind param (?), so
   27: # no quoting or escaping is required on the value side.  LIKE and NOT LIKE are
   28: # safe for the same reason — the pattern is bound, not interpolated.
   29: Readonly::Hash my %SAFE_SQL_OPS => map { $_ => 1 } ('>', '<', '>=', '<=', '!=', '=', 'LIKE', 'NOT LIKE');
   30: 
   31: # List-membership operators whose criterion value is an arrayref.
   32: # Each element is bound as a separate ?, so injection is impossible.
   33: # IN  with an empty list → WHERE 1=0 (no rows match, correct SQL semantics).
   34: # NOT IN with an empty list → no WHERE term (all rows match, correct semantics).
   35: Readonly::Hash my %SAFE_LIST_OPS => map { $_ => 1 } ('IN', 'NOT IN');
   36: 
   37: # Nullability operators: no bind parameter.  The hashref value is ignored —
   38: # any value (undef, 1, ...) signals intent; only the key selects the operator.
   39: # A bare undef criterion value (col => undef) also generates IS NULL.
   40: Readonly::Hash my %SAFE_NOARG_OPS => map { $_ => 1 } ('IS NULL', 'IS NOT NULL');
   41: 
   42: # Key pushdown (array backend): the most primary keys that are passed to a
   43: # secondary database as one { -in => [...] } criterion.  Each key is a bind
   44: # parameter, and SQLite builds before 3.32 allow at most 999 in a statement.
   45: # Past this, reading the whole secondary is no worse than several queries.
   46: Readonly::Scalar my $MAX_PUSHDOWN_KEYS => 999;
   47: 
   48: # Database::Abstraction's spelling of SQL IN.  It croaks on 'IN'.
   49: Readonly::Scalar my $DA_IN_OP => '-in';
   50: 
   51: # Sentinel for outer-join keys absent from the primary: a single pre-allocated
   52: # [{}] shared across all keys and queries.  The inner loop copies the {} into
   53: # %merged immediately, so the shared hashref is never mutated.
   54: my $_EMPTY_PRIMARY_ROW = [{}];
   55: 
   56: # Valid aggregate functions for aggregate().  Lower-cased at validation time.
   57: Readonly::Hash my %AGGREGATE_FNS => map { $_ => 1 } qw(sum avg min max count count_distinct);
   58: 
   59: # Valid operator names for the mandatory_filters {col, op, val} predicate format.
   60: Readonly::Hash my %MANDATORY_FILTER_OPS => map { $_ => 1 }
   61: 	qw(eq ne lt lte gt gte like contains);
   62: 
   63: # SQL operator string for each mandatory_filter op (used in _sqlite_criteria).
   64: Readonly::Hash my %MANDATORY_OP_SQL => (
   65: 	eq       => '=',
   66: 	ne       => '!=',
   67: 	lt       => '<',
   68: 	lte      => '<=',
   69: 	gt       => '>',
   70: 	gte      => '>=',
   71: 	like     => 'LIKE',
   72: 	contains => 'LIKE',
   73: );
   74: 
   75: 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).
   80: my $HAS_THREADS;
   81: 
   82: # ---------------------------------------------------------------------------
   83: # All user-facing strings route through this dictionary.  Supply an i18n
   84: # object with a translate($key, @sprintf_args) method to localise them.
   85: # ---------------------------------------------------------------------------
   86: Readonly::Hash my %MESSAGES => (
   87: 	error_no_databases	=> 'At least one Database::Abstraction object is required',
   88: 	error_invalid_db	=> 'databases[%d] does not support the selectall_arrayref/columns interface',
   89: 	error_join_col_missing	=> 'join_column "%s" is absent from databases[%d] (%s)',
   90: 	error_col_conflict	=> 'Column "%s" exists in multiple databases; use the owning database directly or rename the column',
   91: 	error_remove_join_col	=> 'Cannot remove join_column "%s"; it is required for the join',
   92: 	warn_unknown_column	=> 'Column "%s" is not present in any configured database; criterion ignored',
   93: 	error_join_criterion	=> 'join => criteria are not supported on Database::Join (SQL JOINs target a single DA; use multiple DAs in the databases => [] constructor instead)',
   94: 	error_query_unsupported	=> 'query() chained builder is not supported on Database::Join (Database::Abstraction::Query targets a single DA, not the merged view); use selectall_arrayref, selectall_array, fetchrow_hashref, count, or each_row instead',
   95: 	error_group_by_unsupported => 'group_by() fluent chain is not supported on Database::Join (Database::Abstraction::Query targets a single DA, not the merged view); use aggregate() instead',
   96: 	error_execute_unsupported => 'execute() raw SQL is not supported on Database::Join',
   97: 	error_unknown_message	=> 'Unknown message key "%s"',
   98: 	error_invalid_prefix	=> 'collision_prefix[%d] must be a plain string, not a reference; passing a reference would leak a heap address into column names',
   99: 	error_invalid_backend	=> 'backend must be "array", "sqlite", or "auto"; got "%s"',
  100: 	error_sqlite_connect	=> 'Failed to open temporary SQLite database for join backend: %s',
  101: 	warn_schema_type_mismatch => 'column "%s" has type "%s" in database[%d] but type "%s" in database[%d]; use collision_prefix to preserve both values without silent type coercion',
  102: 	error_invalid_callback	=> 'each_row: first argument must be a code reference',
  103: 	error_aggregate_measures_required => 'aggregate: "measures" must be a non-empty arrayref',
  104: 	error_aggregate_measure_ref       => 'aggregate: measure must be a hashref, got %s',
  105: 	error_aggregate_fn_unknown        => 'aggregate: unknown measure function "%s"',
  106: 	error_aggregate_col_required      => 'aggregate: measure column is required for function "%s"',
  107: 	error_aggregate_col_unknown       => 'aggregate: column "%s" is not in the merged view',
  108: 	error_aggregate_as_required       => 'aggregate: measure "as" is required',
  109: 	error_aggregate_as_invalid        => 'aggregate: measure alias "%s" must be a plain word',
  110: 	error_aggregate_as_duplicate      => 'aggregate: duplicate measure alias "%s"',
  111: 	error_aggregate_as_collision      => 'aggregate: measure alias "%s" collides with a group-by column',
  112: 	error_aggregate_by_invalid        => 'aggregate: "by" must be an arrayref of column names',
  113: 	error_aggregate_having_key        => 'aggregate: having key "%s" is not a group-by column or measure alias',
  114: 	error_aggregate_having_operator   => 'aggregate: operator "%s" in having for key "%s" is not supported',
  115: 	warn_aggregate_sort_key           => 'aggregate: sort_by names "%s", which is not a group-by column or measure alias',
  116: 	warn_aggregate_non_numeric        => 'aggregate: column "%s" has %d non-numeric value(s), skipped, e.g. "%s"',
  117: 	error_mandatory_filter_ref        => 'mandatory_filters[%d] must be a hashref with col, op, and val keys',
  118: 	error_mandatory_filter_col        => 'mandatory_filters[%d]: column "%s" is not in the merged view',
  119: 	error_mandatory_filter_op         => 'mandatory_filters[%d]: op "%s" is not supported; use eq, ne, lt, lte, gt, gte, like, or contains',
  120: );
  121: 
  122: =head1 NAME
  123: 
  124: Database::Join - Read-only combined view across two or more Database::Abstraction objects
  125: 
  126: =head1 VERSION
  127: 
  128: Version 0.011.4
  129: 
  130: =head1 SYNOPSIS
  131: 
  132: B<Basic two-database join>
  133: 
  134:     use Database::Join;
  135: 
  136:     # Step 1: create each component database the normal way
  137:     # See Database::Abstraction
  138:     my $customers = Database::Customers->new(directory => '/data');
  139:     my $loyalty   = Database::Loyalty->new(directory  => '/data');
  140: 
  141:     # Step 2: combine them on the shared key column 'entry'
  142:     my $join = Database::Join->new(
  143:         databases   => [ $customers, $loyalty ],
  144:         join_column => 'entry',
  145:     );
  146: 
  147:     # Step 3: query exactly as you would a single Database::Abstraction object
  148:     my $all_rows  = $join->selectall_arrayref();
  149:     my $vip_rows  = $join->selectall_arrayref(tier => 'gold');
  150:     my $one_row   = $join->fetchrow_hashref(entry => 'C001');
  151:     my $total     = $join->count();
  152:     my $col_names = $join->columns();
  153: 
  154: B<Hiding internal columns>
  155: 
  156:     my $join = Database::Join->new(
  157:         databases      => [ $customers, $loyalty ],
  158:         join_column    => 'entry',
  159:         remove_columns => [ 'internal_id', 'audit_ts' ],
  160:     );
  161:     # 'internal_id' and 'audit_ts' never appear in results or columns()
  162: 
  163: B<join_map: when the key column has different names in each database>
  164: 
  165:     # $cities  (index 0) has a column called 'statecode' -- matches join_column
  166:     # $stnames (index 1) has a column called 'entry'     -- different name
  167: 
  168:     my $join = Database::Join->new(
  169:         databases   => [ $cities,  $stnames ],
  170:         #                index 0   index 1
  171:         join_column => 'statecode',
  172:         join_map    => { 1 => 'entry' },  # index 1 calls its join key 'entry'
  173:     );
  174: 
  175:     # All returned rows use 'statecode'; 'entry' is never exposed
  176:     my $rows = $join->selectall_arrayref();
  177: 
  178: B<filters: permanently restrict a database's visible rows>
  179: 
  180:     # Only show orders placed more than 60 days ago, without repeating
  181:     # the criterion on every query call.
  182:     my $join = Database::Join->new(
  183:         databases   => [ $customers, $orders ],
  184:         join_column => 'entry',
  185:         filters     => { 1 => { age_days => { '>' => 60 } } },
  186:     );
  187: 
  188:     my $rows = $join->selectall_arrayref();                 # all old orders
  189:     my $vip  = $join->selectall_arrayref(tier => 'gold');   # old + gold tier
  190: 
  191: B<Inner and outer join types>
  192: 
  193:     my $inner = Database::Join->new(
  194:         databases   => [ $customers, $loyalty ],
  195:         join_column => 'entry',
  196:         join_type   => 'inner',   # only keys present in BOTH databases
  197:     );
  198: 
  199:     my $outer = Database::Join->new(
  200:         databases   => [ $customers, $loyalty ],
  201:         join_column => 'entry',
  202:         join_type   => 'outer',   # all keys from EITHER database
  203:     );
  204: 
  205: B<Building the view incrementally with add_database>
  206: 
  207:     my $join = Database::Join->new(
  208:         databases   => [ $customers ],
  209:         join_column => 'entry',
  210:     );
  211: 
  212:     $join->add_database($loyalty)
  213:          ->add_database($scores, remove_columns => ['raw_score']);
  214: 
  215: B<AUTOLOAD column shortcut>
  216: 
  217:     # Returns the 'name' value for entry 'C001' (scalar context)
  218:     my $name = $join->name(entry => 'C001');
  219: 
  220:     # Returns all 'tier' values (list context)
  221:     my @tiers = $join->tier();
  222: 
  223: B<aggregate(): GROUP BY across the merged view>
  224: 
  225:     # Count and total score per tier, highest total first
  226:     my $rows = $join->aggregate(
  227:         by       => ['tier'],
  228:         measures => [
  229:             { col => 'score', fn => 'sum',   as => 'total' },
  230:             {                 fn => 'count', as => 'n'     },
  231:         ],
  232:         sort_by  => ['total', 'DESC'],
  233:         having   => { total => { '>' => 100 } },
  234:     );
  235:     # => [ { tier => 'gold', total => 183, n => 2 }, ... ]
  236: 
  237:     # Grand total across the whole view (no 'by' key)
  238:     my $summary = $join->aggregate(
  239:         measures => [{ fn => 'count', as => 'n' }],
  240:     );
  241:     # => [ { n => 42 } ]
  242: 
  243: B<SQLite join backend for large datasets>
  244: 
  245:     # 'auto' (default): switches to SQLite automatically above the threshold
  246:     my $join = Database::Join->new(
  247:         databases      => [ $customers, $loyalty ],
  248:         join_column    => 'entry',
  249:         backend        => 'auto',          # default
  250:         max_array_rows => 50_000,          # use SQLite when combined rows > 50,000
  251:     );
  252: 
  253:     # Always use SQLite -- useful when you know the data is large
  254:     my $join = Database::Join->new(
  255:         databases   => [ $customers, $loyalty ],
  256:         join_column => 'entry',
  257:         backend     => 'sqlite',
  258:         tmpdir      => '/fast/nvme/tmp',   # optional: faster temp disk
  259:     );
  260: 
  261:     # Always use the original in-memory path
  262:     my $join = Database::Join->new(
  263:         databases   => [ $customers, $loyalty ],
  264:         join_column => 'entry',
  265:         backend     => 'array',
  266:     );
  267: 
  268: =head1 DESCRIPTION
  269: 
  270: C<Database::Join> merges two or more L<Database::Abstraction> objects into a
  271: single logical, read-only view.  Each component database is queried
  272: independently through its own C<Database::Abstraction> interface.  The results
  273: are combined using a shared key column (C<join_column>).
  274: In effect, this means that you can view data from more than one database using
  275: an intuitive, non-SQL interface.
  276: 
  277: Every storage format that C<Database::Abstraction> supports works as a
  278: component database: CSV, PSV, TSV, SQLite, JSON, XML, XLSX, BerkeleyDB, HTML
  279: URL, JSON URL, or any custom subclass.  Component databases may mix formats
  280: within the same join.
  281: 
  282: The module exposes the same read-only API as C<Database::Abstraction>:
  283: C<selectall_arrayref>, C<selectall_array>, C<fetchrow_hashref>, C<count>,
  284: C<columns>, C<schema>, C<updated>, C<set_logger>, and the AUTOLOAD column
  285: shortcut.  Callers do not need to know how many underlying databases are
  286: involved.
  287: 
  288: Think of it as a virtual database table that is assembled on demand from
  289: several real tables, one per component database.
  290: 
  291: B<Join backends>
  292: 
  293: By default (C<backend =E<gt> 'auto'>), C<Database::Join> first checks the
  294: combined source row count.  For small datasets (up to C<max_array_rows>,
  295: default 10,000 rows) it merges entirely in Perl memory.  For larger datasets it
  296: automatically spills source rows into a temporary SQLite database and executes
  297: a single SQL JOIN there, keeping peak RAM to roughly one times the source data
  298: size instead of three.  You can also force either path unconditionally with
  299: C<backend =E<gt> 'sqlite'> or C<backend =E<gt> 'array'>.
  300: 
  301: B<Key pushdown (array backend)>
  302: 
  303: Under a C<left> or C<inner> join, only secondary rows whose key is one of the
  304: primary's can appear in the result.  So once the primary has been read, each
  305: secondary that has no criterion on its join column is asked for just those
  306: keys, as C<< { -in => [ ... ] } >> on its local join column, instead of being
  307: read in full.  Joining a few hundred primary rows to a large secondary table
  308: then costs a few hundred rows, not the whole table.  Pushdown is skipped when:
  309: 
  310: =over 4
  311: 
  312: =item * the join is C<outer>, which needs every secondary key;
  313: 
  314: =item * the primary has no rows, or more than 999 keys (the bind-parameter
  315: limit of older SQLite builds; past that, reading the whole table is no worse);
  316: 
  317: =item * the query already has a criterion on the join column, which then
  318: stands as given;
  319: 
  320: =item * the secondary's C<selectall_arrayref> is not
  321: C<Database::Abstraction>'s own.  A subclass that overrides it, or another
  322: object implementing the interface, may not understand C<-in>.
  323: 
  324: =back
  325: 
  326: If the secondary croaks on the C<-in> query, it is read in full instead.  The
  327: result is the same either way.  Pushdown only narrows what is fetched; it never
  328: counts as the secondary's own criterion, so it can't turn a C<left> join into
  329: an C<inner> one.
  330: 
  331: =head2 Join semantics
  332: 
  333: The C<join_type> parameter controls what happens when a particular key value
  334: exists in some component databases but not all:
  335: 
  336: =over 4
  337: 
  338: =item C<left> (the default)
  339: 
  340: All rows from the I<primary> (first) database are returned.  Columns from
  341: subsequent databases are included where a matching row is found, and simply
  342: absent from the hashref where there is no match.  If you are familiar with
  343: SQL, this is a LEFT OUTER JOIN on the first table.
  344: 
  345: =item C<inner>
  346: 
  347: Only rows whose join-column value is present in I<every> component database
  348: are returned.  This is equivalent to a SQL INNER JOIN.
  349: 
  350: =item C<outer>
  351: 
  352: Every join-column value found in I<any> component database is returned.
  353: Columns from databases that do not have that key value are absent from the
  354: merged row.  This is a FULL OUTER JOIN.
  355: 
  356: =back
  357: 
  358: B<Important override rule:> whenever you pass a query criterion for a column
  359: that belongs to a secondary database, that database automatically acts as an
  360: inner-join partner for that query only -- regardless of C<join_type>.  This
  361: gives WHERE-clause semantics.  For example, if you have a LEFT join but query
  362: C<< tier => 'gold' >> on a secondary database, only rows whose secondary entry
  363: has tier = 'gold' are returned (rows with no secondary entry are excluded, just
  364: as a WHERE clause would exclude them).
  365: 
  366: =head2 Column ownership and routing
  367: 
  368: At construction time, C<Database::Join> calls C<columns()> on each component
  369: database and builds an internal index that maps every column name to the
  370: database that owns it.
  371: 
  372: When you pass criteria to a query method, each key-value pair is automatically
  373: routed to the right database.  You never need to say which database a column
  374: belongs to.
  375: 
  376: The C<join_column> is special: criteria on it are broadcast to I<all>
  377: databases so that each database fetches only the relevant rows before the
  378: in-memory merge.
  379: 
  380: When the same non-join column name exists in more than one database, the
  381: I<last> database in the C<databases> array wins by default: its value
  382: overwrites earlier ones in merged rows.  Use C<collision_prefix> to
  383: preserve both values under distinct names instead.
  384: 
  385: =head1 LIMITATIONS
  386: 
  387: =over 4
  388: 
  389: =item Memory usage (array backend)
  390: 
  391: When C<backend> is C<'array'> (or C<'auto'> and the dataset is small), all
  392: matching rows are fetched into Perl memory.  Key pushdown (see
  393: L</DESCRIPTION>) limits a secondary to the primary's keys under C<left> and
  394: C<inner> joins, but an C<outer> join, or a primary with more than 999 keys,
  395: still reads every secondary row.  Peak RAM is roughly three times
  396: the source data size.  For large datasets use C<backend =E<gt> 'sqlite'>, or
  397: leave C<backend =E<gt> 'auto'> and set C<max_array_rows> appropriately.
  398: 
  399: =item SQLite backend uses a persistent cache file
  400: 
  401: When the SQLite path is active, a single C<.db> file with a randomly generated
  402: name (chosen by C<File::Temp> to avoid collisions) is created in C<tmpdir> the
  403: first time a query runs on a given C<Database::Join> object.  Source data is
  404: spilled into that file once; subsequent queries against the same object reuse
  405: the file without re-fetching the source data.
  406: 
  407: The cache is automatically invalidated and rebuilt whenever any source
  408: database's C<updated()> timestamp changes (indicating new data), or when
  409: C<add_database()> is called.
  410: 
  411: The file is deleted when the C<Database::Join> object is destroyed (typically
  412: when it goes out of scope).  At any given moment no more than one such file
  413: exists per object.  The directory must be writable and have enough free space
  414: for the full source data (once, not per-query).
  415: 
  416: =item No chained builder or raw SQL
  417: 
  418: C<query()> and C<execute()> are not implemented.  Use C<selectall_arrayref>
  419: or C<fetchrow_hashref> instead.
  420: 
  421: =item Single-column equi-join only
  422: 
  423: Joining on more than one column simultaneously, or on expressions, is not
  424: supported.  When the join key has different names in different databases,
  425: use C<join_map> to declare each database's local column name.
  426: 
  427: =item Sort order
  428: 
  429: Results are sorted ascending by C<join_column> by default.  Pass
  430: C<< sort_by => 'colname' >> (or C<< sort_by => ['colname', 'DESC'] >>)
  431: to any query method to override this.  The array path uses string comparison
  432: (C<cmp>); for accurate numeric ordering on large datasets use the SQLite
  433: backend, which sorts natively by type.
  434: 
  435: =item count() on the array backend fetches all rows
  436: 
  437: On the array backend, C<count()> executes the full in-memory join and counts
  438: the resulting rows in Perl; no C<COUNT(*)> is pushed to the component
  439: databases.  On the SQLite backend, C<count()> executes a C<SELECT COUNT(*)>
  440: SQL query against the cached join tables, avoiding a full row transfer.
  441: 
  442: =back
  443: 
  444: =head1 COMMON PITFALLS
  445: 
  446: =over 4
  447: 
  448: =item The join_column must exist in every component database
  449: 
  450: If even one database is missing the join key column, C<new()> (or
  451: C<add_database()>) will C<croak> immediately.  Use C<join_map> when the
  452: column has a different local name in some databases.
  453: 
  454: =item Criteria on a removed column are silently dropped
  455: 
  456: If you call C<remove_column('tier')> and later query
  457: C<< selectall_arrayref(tier => 'gold') >>, the criterion is ignored (with a
  458: C<carp> warning) and all rows are returned.  Always pass criteria before
  459: removing columns, or restructure your code to avoid this.
  460: 
  461: =item You cannot remove the join column
  462: 
  463: C<< $join->remove_column($join->join_column) >> will C<croak>.  The join key
  464: is required for the merge to work.
  465: 
  466: =item Left join does not guarantee all columns are populated
  467: 
  468: Under a LEFT join, rows from the primary database that have no matching row
  469: in a secondary database will be returned with I<no keys> from that secondary
  470: database.  Accessing C<< $row->{score} >> on such a row returns C<undef> --
  471: not zero, not an empty string.  Always test C<defined $row->{score}> rather
  472: than just C<$row->{score}> when the secondary match is optional.
  473: 
  474: =item Filters act as inner-join partners
  475: 
  476: Any database that has a C<filters> entry is promoted to an inner-join partner,
  477: regardless of C<join_type>.  A row whose join-key value does not appear in
  478: the filtered database's result is removed from the merged output entirely, not
  479: merely missing its secondary columns.  This is intentional but can be
  480: surprising if you expected LEFT join semantics.
  481: 
  482: =item Criteria-merging replaces scalar filters
  483: 
  484: When both a base filter and a query criterion target the same column, and both
  485: are operator hashrefs (e.g. C<< { '>' => 60 } >>), the operators are combined
  486: (AND semantics).  But if the query criterion is a plain scalar (e.g.
  487: C<< score => 75 >>), it I<replaces> the base filter for that column entirely --
  488: the base filter is ignored for that query.
  489: 
  490: =item AUTOLOAD sees the full merged join when filters or join_map are active
  491: 
  492: When either C<filters> or C<join_map> is in effect, the AUTOLOAD shortcut
  493: (C<< $join->columnname(...) >>) runs the full join query rather than
  494: delegating directly to the owning database.  This is necessary for correctness
  495: but means the result respects all active filters and join-key translations,
  496: which may differ from what the owning database would return on its own.
  497: 
  498: =item Duplicate column names: last database wins (unless collision_prefix is set)
  499: 
  500: When two component databases each have a column called C<notes>, the second
  501: database's value silently overwrites the first in every merged row.  Use
  502: C<collision_prefix => { 1 => 'right' }> to publish the second database's
  503: C<notes> as C<right.notes> so both values survive, or use C<remove_columns>
  504: (or C<remove_column>) to drop the unwanted duplicate entirely.
  505: 
  506: =item Mutating the filters hashref after construction has no effect
  507: 
  508: C<Database::Join> deep-copies the C<filters> hashref (and any C<filter>
  509: passed to C<add_database>) at the moment of construction.  The original hashref
  510: you passed in is never stored.  If you later modify it -- for example, to
  511: tighten or loosen a filter criterion -- the joined view is I<not> affected.
  512: Construct a new C<Database::Join> object, or use a component
  513: C<Database::Abstraction> that supports dynamic filter modification.
  514: 
  515: =item auto mode may always use the array path for some DAs
  516: 
  517: C<backend =E<gt> 'auto'> counts rows cheaply only when each component database
  518: either implements C<dbi_source()> (SQLite-backed) or directly defines a
  519: C<count()> method in its own package.  A DA that merely I<inherits> C<count()>
  520: from C<Database::Abstraction> is treated as uncountable, because the parent
  521: class C<count()> expects a key argument and behaves differently from a
  522: "return total row count" function.  In that case C<Database::Join>
  523: conservatively uses the array path for the whole query, even if the dataset is
  524: large.  To opt in to the SQLite path for such a DA, either add your own
  525: C<count()> override that returns the total row count, implement C<dbi_source()>,
  526: or use C<backend =E<gt> 'sqlite'> unconditionally.
  527: 
  528: =item dbi_source() ATTACH is unconditional - query-time criteria go into WHERE
  529: 
  530: When a component database implements C<dbi_source()>, C<Database::Join> always
  531: uses the zero-copy ATTACH path, I<even when the current query includes criteria
  532: for columns in that database>.  The criteria are translated into parameterised
  533: SQL C<WHERE> clauses applied against the ATTACHed table; no row-level copy is
  534: performed.  (Prior to 0.005.0 the presence of any query-time criteria would
  535: force a spill; that restriction has been removed.)
  536: 
  537: =item Broadcast join-column criterion does not force secondaries into inner-join
  538: 
  539: When a caller passes a join-column criterion (e.g. C<entry =E<gt> 'k1'>),
  540: C<Database::Join> broadcasts it to all component databases so each DA can
  541: filter its fetch to the requested key.  Prior to 0.006.0 this broadcast was
  542: incorrectly counted as "having criteria" for secondary databases, causing
  543: C<left> and C<outer> joins to silently behave as C<inner> joins when a
  544: join-column criterion was present.  The fix: only non-join-column criteria
  545: (e.g. column filters from the caller or base C<filters =E<gt> {...}>) promote
  546: a secondary to inner-join status.  The broadcast itself is now a transparent
  547: key-range selector that does not affect join semantics.
  548: 
  549: =item LIKE and NOT LIKE work on the SQLite path; other pattern operators do not yet
  550: 
  551: C<LIKE>, C<NOT LIKE>, C<IN>, and C<NOT IN> are fully supported on the SQLite
  552: backend.  C<LIKE>/C<NOT LIKE> take a scalar pattern; C<IN>/C<NOT IN> take an
  553: arrayref of values.  All are injection-safe because values are passed as bind
  554: parameters, never interpolated.
  555: 
  556:     # LIKE
  557:     my $rows = $join->selectall_arrayref(name => { LIKE => 'A%' });
  558: 
  559:     # IN
  560:     my $rows = $join->selectall_arrayref(tier => { IN => ['gold', 'silver'] });
  561: 
  562:     # NOT IN
  563:     my $rows = $join->selectall_arrayref(tier => { 'NOT IN' => ['bronze'] });
  564: 
  565: C<IN> with an empty arrayref matches no rows (SQL semantics: C<IN ()> is
  566: always false).  C<NOT IN> with an empty arrayref matches all rows (no
  567: constraint added).
  568: 
  569: C<IS NULL> and C<IS NOT NULL> are supported on the SQLite backend using an
  570: explicit operator hashref:
  571: 
  572:     my $rows = $join->selectall_arrayref(score => { 'IS NULL'     => undef });
  573:     my $rows = $join->selectall_arrayref(score => { 'IS NOT NULL' => 1    });
  574: 
  575: The hashref value is ignored; only the key selects the operator.  A bare
  576: C<undef> criterion value (C<< score => undef >>) also generates C<IS NULL>
  577: on the SQLite path.  Note: on the in-memory array path, the component DA
  578: may treat an C<undef> criterion value as C<< no filter >> rather than
  579: C<IS NULL>, so use the explicit hashref form for consistent behaviour
  580: across backends.
  581: 
  582: Any operator not in the supported set is skipped on the SQLite path with a
  583: C<carp> warning.  The array path forwards all operators to the component DA
  584: unchanged, which may or may not honour them.
  585: 
  586: =item Temp file directory must be writable and have free space
  587: 
  588: The SQLite path creates one temporary C<.db> file per C<Database::Join> object
  589: in C<tmpdir> (default: C<File::Spec-E<gt>tmpdir()>, usually C</tmp> on Unix).
  590: The filename is randomly generated by C<File::Temp> -- you cannot predict it,
  591: only the directory is under your control.  The file is created on the first
  592: query and kept alive until the object is destroyed; it is not re-created on
  593: every query call.  If the directory is not writable, or the filesystem is full,
  594: the call will C<croak> with C<error_sqlite_connect>.  Check permissions and
  595: free space if you see that error.
  596: 
  597: =item C<join =E<gt>> criteria are not supported
  598: 
  599: C<Database::Abstraction> accepts a C<join =E<gt> { table =E<gt> ..., on =E<gt> ... }>
  600: key in its criteria hashrefs to express an SQL JOIN within a single table.
  601: C<Database::Join> cannot route this to a component DA meaningfully: the merged
  602: view has no concept of a single underlying table.  Passing C<join =E<gt>> to any
  603: query method will C<croak> with C<error_join_criterion>.
  604: 
  605: B<Fix:> Model the joined table as a separate C<Database::Abstraction> object and
  606: add it to the C<databases =E<gt> []> list.  Use C<join_column> or C<join_map> to
  607: specify the shared key.
  608: 
  609: =item aggregate(): omitting C<by> gives a grand total, not an error
  610: 
  611: Calling C<aggregate()> without a C<by> key (or with C<< by => [] >>) does
  612: I<not> croak.  It returns a single-element arrayref containing one row with
  613: all the computed measure aliases.  This is a grand total over the entire view
  614: (possibly filtered by any extra criteria you pass).
  615: 
  616:     my $total = $join->aggregate(measures => [{ fn => 'count', as => 'n' }]);
  617:     # $total->[0]{n} is the total row count
  618: 
  619: If you expected multiple rows and got one, you probably forgot the C<by> key.
  620: 
  621: =item aggregate(): non-numeric values behave differently across backends
  622: 
  623: On the array backend (C<backend =E<gt> 'array'>), any non-numeric value in a
  624: column targeted by C<sum> or C<avg> is I<skipped> (not counted, not coerced),
  625: and a C<carp> warning C<warn_aggregate_non_numeric> is emitted.  On the SQLite
  626: backend, non-numeric values are silently coerced to C<0.0> via SQL C<CAST>.
  627: The two backends therefore produce different numeric totals when the data
  628: contains non-numeric values.  Clean your data first if you need consistent
  629: results across backends, or choose a backend explicitly.
  630: 
  631: =item aggregate(): C<BETWEEN> is not supported in C<having>
  632: 
  633: The C<having> hashref uses the same operator vocabulary as C<selectall_arrayref>,
  634: which does not include C<BETWEEN>.  Write a range as two explicit constraints:
  635: 
  636:     # Correct
  637:     having => { total => { '>=' => 10, '<=' => 50 } }
  638: 
  639:     # Wrong -- will croak with error_aggregate_having_operator
  640:     having => { total => { BETWEEN => [10, 50] } }
  641: 
  642: =item aggregate(): C<count> without C<col> counts all rows, not distinct non-NULL values
  643: 
  644: A measure with C<< fn => 'count' >> and no C<col> key emits C<COUNT(*)> on the
  645: SQLite backend (or counts every row in Perl).  This counts rows that have
  646: C<undef>/NULL in other columns too.  To count only rows where a specific
  647: column is non-NULL, or to count distinct values, use C<count_distinct>:
  648: 
  649:     # Count rows with a non-NULL 'score' (one way -- use a pre-filter)
  650:     measures => [{ col => 'score', fn => 'count_distinct', as => 'distinct_scores' }]
  651: 
  652: =item aggregate(): the result is never cached
  653: 
  654: Unlike C<selectall_arrayref> (which benefits from the SQLite file cache on
  655: repeated identical calls), C<aggregate()> always re-executes.  If your
  656: aggregation is expensive and the data changes infrequently, cache the result
  657: yourself using C<updated()> as a staleness signal.
  658: 
  659: =item distinct => 1 without columns returns full rows, not a column projection
  660: 
  661: C<< distinct => 1 >> alone deduplicates on I<all> columns of the merged row.
  662: If you want a distinct list of values for a single column (e.g. all unique
  663: tiers), you B<must> supply C<< columns => ['tier'] >> as well.  Without
  664: C<columns>, every column participates in the key used to detect duplicates,
  665: which means two rows that differ in any column (e.g. C<entry>) are never
  666: considered duplicates, and the result will be the same as without C<distinct>.
  667: 
  668: =item distinct => 1 with columns projects rows to those columns
  669: 
  670: When C<columns> is supplied alongside C<distinct>, each returned row contains
  671: I<only> the named columns -- all other columns are dropped.  The projection
  672: happens before deduplication, so the result set may be smaller than the full
  673: merged row count.  If you need the full row I<and> want to know unique values,
  674: run two separate queries or post-process in Perl.
  675: 
  676: =item mandatory_filters must never come from user-supplied input
  677: 
  678: The predicates in C<mandatory_filters> form an enforcement boundary.  They must
  679: come from a trusted server-side source (a session store, a policy table, or
  680: hard-coded application configuration) -- never from URL parameters, form fields,
  681: HTTP headers, or other user-controlled input.  A hostile user who can control
  682: a mandatory_filters predicate can widen it to C<{ col => 'status', op => 'ne',
  683: val => 'NONEXISTENT' }> and receive all rows regardless of status.
  684: 
  685: =item mandatory_filters uses string comparison on the array path
  686: 
  687: On the array backend, all C<mandatory_filters> comparisons (including C<lt>,
  688: C<lte>, C<gt>, C<gte>) are I<lexicographic string comparisons>, not numeric.
  689: C<< { col => 'score', op => 'gt', val => 9 } >> will match a score of C<'10'>
  690: only if C<'10' gt '9'> is true -- which it is not (C<'1' lt '9'>).  Use the
  691: SQLite backend (C<< backend => 'sqlite' >>) when numeric comparisons are needed,
  692: as SQLite uses the column's declared type for ordering.
  693: 
  694: =back
  695: 
  696: =head1 METHODS
  697: 
  698: =head2 new
  699: 
  700: =head3 SYNOPSIS
  701: 
  702:     my $join = Database::Join->new(
  703:         databases         => [ $db1, $db2 ],
  704:         join_column       => 'entry',
  705:         join_type         => 'left',
  706:         join_map          => { 1 => 'local_col' },
  707:         filters           => { 1 => { score => { '>' => 60 } } },
  708:         base_criteria     => { active => 1 },
  709:         mandatory_filters => [{ col => 'region', op => 'eq', val => 'West' }],
  710:         collision_prefix  => { 1 => 'right' },
  711:         remove_columns    => [ 'email', 'internal_id' ],
  712:         backend           => 'auto',        # 'auto' | 'sqlite' | 'array'
  713:         max_array_rows    => 10_000,        # threshold for 'auto' mode
  714:         tmpdir            => '/tmp',        # directory for temp SQLite file
  715:         logger            => $log,
  716:         i18n              => $locale,
  717:     );
  718: 
  719: =head3 DESCRIPTION
  720: 
  721: Constructs and returns a new C<Database::Join> object.
  722: 
  723: Each element of C<databases> must be an already-instantiated subclass of
  724: C<Database::Abstraction>.  The constructor calls C<columns()> on every
  725: database to build an internal column-routing table and verifies that
  726: C<join_column> (or its local alias from C<join_map>) is present in each one.
  727: 
  728: Columns listed in C<remove_columns> are hidden immediately: they do not appear
  729: in C<columns()>, C<schema()>, or any returned row hashref.  This is equivalent
  730: to calling C<remove_column> once per name after construction.
  731: 
  732: =head3 API SPECIFICATION
  733: 
  734: =head4 Input
  735: 
  736:     databases      => { type => 'arrayref', required => 1 }
  737:                       # One or more Database::Abstraction subclass objects.
  738:                       #
  739:                       # DOMAIN -- EP valid:   non-empty arrayref of blessed DA subclasses.
  740:                       # DOMAIN -- EP invalid: scalar, hashref, or absent => croak.
  741:                       # DOMAIN -- BVA size:   minimum 1 element; no documented upper bound.
  742:                       # DOMAIN -- BVA elem:   each element must pass isa('Database::Abstraction').
  743: 
  744:     join_column    => { type => 'string',   optional => 1, default => 'entry' }
  745:                       # The column name shared by all databases (the join key).
  746:                       #
  747:                       # DOMAIN -- EP valid:   any non-empty string present in every component DA.
  748:                       # DOMAIN -- EP invalid: column absent from any DA => croak join_col_missing.
  749:                       # DOMAIN -- BVA:        empty string '' is treated as a column name and
  750:                       #                       will croak if (as expected) it is absent from every DA.
  751:                       # DOMAIN -- NOTE:       matching is case-sensitive and exact.
  752: 
  753:     join_type      => { type => 'string',   optional => 1, default => 'left',
  754:                         enum => ['inner', 'left', 'outer'] }
  755:                       # Controls which keys appear in the result when not all
  756:                       # databases share the same key values.
  757:                       #
  758:                       # DOMAIN -- EP valid:   exactly 'inner', 'left', or 'outer'.
  759:                       # DOMAIN -- EP invalid: any other string including 'INNER', 'LEFT',
  760:                       #                       'OUTER' (enum check is case-sensitive), 'cross',
  761:                       #                       or '' => croak from validate_strict.
  762: 
  763:     join_map       => { type => 'hashref',  optional => 1 }
  764:                       # Zero-based database index => local column name.
  765:                       # See the join_map section for full details.
  766:                       #
  767:                       # DOMAIN -- EP valid:   hashref values must be plain strings.
  768:                       # DOMAIN -- EP invalid: reference value (hashref, arrayref, coderef, etc.)
  769:                       #                       => croak; the guard prevents heap-address leakage.
  770:                       # DOMAIN -- BVA:        out-of-range keys (beyond the databases array) are
  771:                       #                       silently ignored.
  772: 
  773:     filters        => { type => 'hashref',  optional => 1 }
  774:                       # Zero-based database index => criteria hashref.
  775:                       # Permanent row restrictions on individual databases.
  776:                       # See the filters section for full details.
  777: 
  778:     base_criteria  => { type => 'hashref',  optional => 1 }
  779:                       # Column name => value hashref.
  780:                       # Permanent criteria applied to every query, specified by
  781:                       # column name rather than database index.  Each key must
  782:                       # be a column that appears in the merged view (or the
  783:                       # join_column); each value is a plain scalar or an
  784:                       # operator hashref in the same format as
  785:                       # selectall_arrayref accepts.  Criteria are automatically
  786:                       # routed to the database that owns each column (same
  787:                       # routing used by selectall_arrayref).
  788:                       # Equivalent to filters but more convenient when you know
  789:                       # the column name but not which database index owns it.
  790:                       # When a column appears in both base_criteria and filters,
  791:                       # the filters entry takes precedence.
  792:                       # See the base_criteria section for full details.
  793:                       #
  794:                       # DOMAIN -- EP valid:   hashref of column-name => scalar or
  795:                       #                       operator-hashref pairs.  Unknown column
  796:                       #                       names emit warn_unknown_column (carp)
  797:                       #                       and are silently dropped.
  798:                       # DOMAIN -- EP invalid: non-hashref value => croak from
  799:                       #                       validate_strict.
  800:                       # DOMAIN -- BVA:        {} empty hashref is a safe no-op.
  801: 
  802:     collision_prefix => { type => 'hashref', optional => 1 }
  803:                       # Zero-based database index (>0) => prefix string.
  804:                       # When a secondary database has a column that collides
  805:                       # with a column already present in the merged view, the
  806:                       # secondary column is published as "$prefix.$col" instead
  807:                       # of silently overwriting the earlier value.
  808:                       # Index 0 entries are silently ignored.
  809:                       # Omitting this parameter preserves the original
  810:                       # last-database-wins behaviour.
  811:                       # See the collision_prefix section for full details.
  812:                       #
  813:                       # DOMAIN -- EP valid:   absent or {} => last-database-wins (no change).
  814:                       # DOMAIN -- EP valid:   { N => 'prefix' } where N > 0 => colliding
  815:                       #                       columns from DB[N] published as "$prefix.$col";
  816:                       #                       non-colliding columns from the same DB added plain.
  817:                       # DOMAIN -- EP note:    index-0 entries are silently ignored.
  818:                       # DOMAIN -- Invariant:  join_column is never prefixed regardless of
  819:                       #                       collision_prefix configuration.
  820: 
  821:     remove_columns => { type => 'arrayref', optional => 1 }
  822:                       # Column names to hide from the merged view.
  823:                       #
  824:                       # DOMAIN -- EP valid:   arrayref of any strings; non-existent columns
  825:                       #                       are silently ignored (idempotent).
  826:                       # DOMAIN -- EP invalid: join_column itself => croak remove_join_col.
  827:                       # DOMAIN -- BVA:        [] empty arrayref is a safe no-op.
  828: 
  829:     backend        => { type => 'string',   optional => 1, default => 'auto',
  830:                         enum => ['array', 'sqlite', 'auto'] }
  831:                       # Controls which join strategy is used.
  832:                       #   'auto'   -- (default) use 'array' when combined source row count
  833:                       #              <= max_array_rows, 'sqlite' otherwise.
  834:                       #   'sqlite' -- always spill to a temporary SQLite database.
  835:                       #   'array'  -- always use the in-memory merge path.
  836:                       #
  837:                       # DOMAIN -- EP valid:   'array', 'sqlite', or 'auto' (case-sensitive).
  838:                       # DOMAIN -- EP invalid: any other string => croak error_invalid_backend.
  839:                       # DOMAIN -- Default:    'auto'.
  840: 
  841:     max_array_rows => { type => 'integer',  optional => 1, default => 10_000 }
  842:                       # Row-count threshold for 'auto' mode.  When the combined
  843:                       # source row count exceeds this value, the SQLite path is used.
  844:                       # Ignored when backend is 'array' or 'sqlite'.
  845:                       #
  846:                       # DOMAIN -- EP valid:   any non-negative integer.
  847:                       # DOMAIN -- BVA:        0 means always use SQLite (all counts exceed 0).
  848:                       # DOMAIN -- Default:    10,000.
  849: 
  850:     tmpdir         => { type => 'string',   optional => 1 }
  851:                       # Directory for the per-call temporary SQLite database file.
  852:                       # The file is created securely by File::Temp and removed when
  853:                       # the query completes.  Ignored when backend is 'array'.
  854:                       #
  855:                       # DOMAIN -- EP valid:   any writable directory path string.
  856:                       # DOMAIN -- EP absent:  uses File::Spec->tmpdir() (system temp dir).
  857: 
  858:     parallel       => { type => 'integer',  optional => 1, default => 0 }
  859:                       # When set to 1 and the join has more than 2 databases (primary +
  860:                       # 2 or more secondaries), secondary DA fetches are issued in
  861:                       # parallel Perl threads.  Requires the 'threads' module; falls
  862:                       # back to sequential with a carp warning when unavailable.
  863:                       # Has no effect on the SQLite backend (which uses a single SQL
  864:                       # JOIN).  DBI-backed DAs are not thread-safe by default; only
  865:                       # enable this for in-memory or otherwise thread-safe DA backends.
  866:                       #
  867:                       # DOMAIN -- EP valid:   0 (sequential, default) or 1 (parallel).
  868:                       # DOMAIN -- EP invalid: any other integer is treated as truthy/falsy.
  869:                       # DOMAIN -- Default:    0.
  870: 
  871:     autoload_pk     => { type => 'string',   optional => 1 }
  872:                       # The column name used as the positional-argument key when
  873:                       # AUTOLOAD performs a full join query (i.e. when join_map or
  874:                       # filters is active).  Calling $join->col('value') with a bare
  875:                       # scalar maps that scalar to { autoload_pk => 'value' } before
  876:                       # routing through the merged view.
  877:                       #
  878:                       # Defaults to join_column when omitted.  Override when the
  879:                       # primary DA's natural lookup key differs from join_column -
  880:                       # for example, when join_column is 'statecode' but you want to
  881:                       # look up by city name ('entry').
  882:                       #
  883:                       # DOMAIN -- EP valid:   any string that is a visible column in
  884:                       #                       the merged view (checked at call time by
  885:                       #                       _partition_criteria; unknown names are
  886:                       #                       carp'd and dropped).
  887:                       # DOMAIN -- EP absent:  defaults to join_column.
  888: 
  889:     mandatory_filters => { type => 'arrayref', optional => 1 }
  890:                       # Arrayref of {col, op, val} predicate hashrefs.
  891:                       # These filters are applied to every query result regardless
  892:                       # of what criteria the caller supplies.  They cannot be
  893:                       # overridden, suppressed, or circumvented at query time.
  894:                       # Each predicate must supply:
  895:                       #   col -- a column name present in the merged view
  896:                       #   op  -- one of: eq, ne, lt, lte, gt, gte, like, contains
  897:                       #   val -- the comparison value (plain scalar)
  898:                       # On the array backend: applied as a Perl-side grep after the
  899:                       # in-memory merge, before sort/limit/offset.
  900:                       # On the SQLite backend: injected as parameterised WHERE clauses
  901:                       # into the per-call SQL query.
  902:                       #
  903:                       # SECURITY: Never set this from URL parameters or any
  904:                       # user-supplied value.  Predicates must come from the
  905:                       # server-side session or policy store only.
  906:                       #
  907:                       # DOMAIN -- EP valid:   [] empty arrayref => no constraint (safe no-op).
  908:                       # DOMAIN -- EP valid:   arrayref of {col, op, val} hashrefs where
  909:                       #                       col is in the merged view and op is supported.
  910:                       # DOMAIN -- EP invalid: element is not a hashref, or is missing
  911:                       #                       col/op/val => croak error_mandatory_filter_ref.
  912:                       # DOMAIN -- EP invalid: col not in merged view => croak error_mandatory_filter_col.
  913:                       # DOMAIN -- EP invalid: op not in supported set => croak error_mandatory_filter_op.
  914:                       # DOMAIN -- ops:        eq (string eq), ne (string ne),
  915:                       #                       lt/lte/gt/gte (string comparison),
  916:                       #                       like (SQL LIKE pattern with % and _),
  917:                       #                       contains (substring match, equivalent to LIKE %val%).
  918: 
  919:     logger         => { type => 'object',   optional => 1 }
  920:                       # Logger object propagated to all component databases.
  921: 
  922:     i18n           => { type => 'object',   optional => 1 }
  923:                       # Localisation object with a translate($key, @args) method.
  924: 
  925: =head4 Output
  926: 
  927:     A blessed Database::Join object.
  928: 
  929: =head3 EXAMPLE
  930: 
  931:     # Customers database: entry | name | email
  932:     # Loyalty   database: entry | tier | points
  933: 
  934:     my $join = Database::Join->new(
  935:         databases      => [ $customers, $loyalty ],
  936:         join_column    => 'entry',
  937:         join_type      => 'inner',            # only customers who also have loyalty records
  938:         remove_columns => [ 'email' ],        # hide PII from query results
  939:         filters        => { 1 => { points => { '>' => 0 } } }, # ignore zero-point records
  940:     );
  941: 
  942:     my $rows = $join->selectall_arrayref();
  943:     # Each row: { entry => ..., name => ..., tier => ..., points => ... }
  944:     # 'email' is absent. Zero-point loyalty records are excluded.
  945: 
  946: =head3 PSEUDOCODE
  947: 
  948:     validate all parameters with validate_strict
  949:     croak if databases is empty
  950:     croak if any element of databases is not a Database::Abstraction subclass
  951:     bless the object with all fields initialised
  952:     call _build_col_index to map every column to its owning database
  953:         and verify join_column presence in each database
  954:     if base_criteria given:
  955:         partition base_criteria by column ownership into per-db slices
  956:         for each database with a non-empty slice:
  957:             merge the slice into _filters[i]
  958:             (explicit filters win on plain-scalar conflicts)
  959:     if mandatory_filters given:
  960:         for each predicate in mandatory_filters:
  961:             croak error_mandatory_filter_ref if predicate is not a {col, op, val} hashref
  962:             croak error_mandatory_filter_col if col is not in the merged view
  963:             croak error_mandatory_filter_op  if op is not in the supported set
  964:         store shallow copies of all validated predicates in _mandatory_filters
  965:     for each column in remove_columns: call remove_column
  966:     return the new object
  967: 
  968: =head3 MESSAGES
  969: 
  970:     error_no_databases           -- databases arrayref was empty
  971:     error_invalid_db             -- an element of databases is not a D::A subclass
  972:     error_join_col_missing       -- join_column (or its join_map alias) not found in a database
  973:     error_invalid_backend        -- backend value is not 'array', 'sqlite', or 'auto'
  974:     error_sqlite_connect         -- temporary SQLite database could not be created (backend='sqlite'/'auto')
  975:     error_mandatory_filter_ref   -- a mandatory_filters element is not a hashref with col, op, and val keys
  976:     error_mandatory_filter_col   -- a mandatory_filters element names a column not in the merged view
  977:     error_mandatory_filter_op    -- a mandatory_filters element uses an unsupported op value
  978:     warn_schema_type_mismatch    -- (carp) a shared column has different types across databases;
  979:                                     use collision_prefix to preserve both values
  980: 
  981: =cut
  982: 
  983: sub new {
●984 → 1031 → 1041  984: 	my ($class, @args) = @_;
  985: 
  986: 	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: 		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: 	my $caller_logger = $p->{logger};
 1027: 	my $caller_i18n   = $p->{i18n};
 1028: 
 1029: 	$p = Object::Configure::configure($class, $p);
 1030: 
 1031: 	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: 			    && $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 → 1080 → 1113 1041: 	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: 		_parallel         => $p->{parallel} // 0,
 1069: 		_mandatory_filters => [],   # validated and replaced below after _build_col_index
 1070: 	}, $class;
 1071: 
 1072: 	$self->_build_col_index();
 1073: 	$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: 	if (my $mf = $p->{mandatory_filters}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1081: my @validated; 1082: for my $j (0 .. $#{$mf}) { 1083: 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: && exists $pred->{val}; 1089: croak $self->_err('error_mandatory_filter_col', $j, $pred->{col}) 1090: unless exists $self->{_col_db}{ $pred->{col} }; 1091: croak $self->_err('error_mandatory_filter_op', $j, $pred->{op}) 1092: 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: my %p = %{$pred}; 1097: if ($p{op} eq 'like') {

Mutants (Total: 1, Killed: 1, Survived: 0)

1098: my $re = join('', map { 1099: $_ eq '%' ? '.*' : $_ eq '_' ? '.' : quotemeta($_) 1100: } split //, $p{val}); 1101: $p{_re} = qr/\A$re\z/s; 1102: } 1103: push @validated, \%p; 1104: } 1105: $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 → 1113 → 1127 1113: if (my $bc = $p->{base_criteria}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1114: my $partitioned = $self->_partition_criteria(_copy_criteria($bc)); 1115: for my $i (0 .. $#{ $self->{_dbs} }) { 1116: next unless %{ $partitioned->[$i] }; 1117: $self->{_filters}{$i} = _merge_criteria( 1118: $partitioned->[$i], 1119: $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 → 1127 → 1132 1127: if (my $log = $self->{_logger}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1128: $_->set_logger($log) for @{ $self->{_dbs} }; 1129: } 1130: 1131: # Apply column removals requested in the constructor ●1132 → 1132 → 1136 1132: if (my $rc = $p->{remove_columns}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1133: $self->remove_column($_) for @{$rc}; 1134: } 1135: 1136: return $self;

Mutants (Total: 2, Killed: 2, Survived: 0)

1137: } 1138: 1139: # --------------------------------------------------------------------------- 1140: # Public API (mirrors Database::Abstraction) 1141: # --------------------------------------------------------------------------- 1142: 1143: =head2 join_map - joining on differently-named columns 1144: 1145: By default every component database must have a column whose name matches 1146: C<join_column>. If a database uses a different local name for the join key, 1147: declare the mapping with C<join_map>. 1148: 1149: C<join_map> is a hashref. Each B<key> is the B<zero-based position> of a 1150: database in the C<databases> array (0 = first, 1 = second, and so on). Each 1151: B<value> is the name that B<that particular database> uses for the join key. 1152: 1153: Databases not listed in C<join_map> are assumed to already have a column 1154: named C<join_column> and need no entry. 1155: 1156: Throughout the merged view the join key is I<always> referred to by the name 1157: given in C<join_column>. The local alias is never exposed in returned rows, 1158: in C<columns()>, or in C<schema()>. 1159: 1160: B<When do you need join_map?> 1161: 1162: You need C<join_map> when you have two tables like: 1163: 1164: cities table : entry (the city name) | statecode 1165: stnames table : entry (the state code) | state 1166: 1167: Here you want to join cities.statecode to stnames.entry. You choose 1168: C<< join_column => 'statecode' >> as the canonical name, but stnames calls 1169: that same concept C<entry>, so you declare: 1170: 1171: join_map => { 1 => 'entry' } # stnames (index 1) calls it 'entry' 1172: 1173: B<Example> 1174: 1175: # index 0 index 1 1176: my @databases = ( $cities, $stnames ); 1177: # join key column: 'statecode' 'entry' 1178: # join_column: 'statecode' (chosen canonical name) 1179: # stnames differs, so declare the alias: 1180: 1181: my $join = Database::Join->new( 1182: databases => \@databases, 1183: join_column => 'statecode', 1184: join_map => { 1 => 'entry' }, 1185: ); 1186: 1187: my $rows = $join->selectall_arrayref(); 1188: # Each $row has keys: entry (city), statecode, state 1189: # 'entry' from stnames is never exposed directly. 1190: 1191: my $row = $join->fetchrow_hashref(statecode => 'CA'); 1192: 1193: B<Using add_database instead> 1194: 1195: If you build the join incrementally with C<add_database>, pass 1196: C<join_column> directly to that call instead of using C<join_map>: 1197: 1198: my $join = Database::Join->new( 1199: databases => [ $cities ], 1200: join_column => 'statecode', 1201: ); 1202: $join->add_database($stnames, join_column => 'entry'); 1203: 1204: This is exactly equivalent to the C<join_map> form above. 1205: 1206: =head2 filters - permanent per-database row filters 1207: 1208: C<filters> lets you restrict a component database to a subset of its rows 1209: permanently, without repeating the criterion on every query call. 1210: 1211: Think of it as telling the join: "whenever you query this database, always 1212: add these extra conditions". Callers never need to specify the restriction 1213: themselves and can never accidentally omit it. 1214: 1215: C<filters> is a hashref. Each B<key> is the B<zero-based position> of a 1216: database in the C<databases> array (same numbering as C<join_map>). Each 1217: B<value> is a criteria hashref in the same format as C<selectall_arrayref> 1218: accepts. 1219: 1220: B<Key-set semantics> 1221: 1222: A filtered database always acts as an inner-join partner, regardless of the 1223: C<join_type> setting. Any join-key value that does not pass the filter is 1224: excluded from the merged output entirely -- not just missing its secondary 1225: columns. This ensures the filter genuinely restricts the view rather than 1226: simply hiding a few fields. 1227: 1228: B<Criteria merging> 1229: 1230: When a query call also passes a criterion for a column that already has a base 1231: filter, the two constraints are combined: 1232: 1233: =over 4 1234: 1235: =item * 1236: 1237: When both the base filter value and the query criterion are operator hashrefs 1238: (e.g. C<< { '>' => 60 } >> and C<< { '<' => 365 } >>), their operators are 1239: merged: I<both> constraints apply simultaneously (AND semantics). 1240: 1241: =item * 1242: 1243: When either value is a plain scalar, or the operators conflict, the 1244: query-time criterion wins and the base filter for that column is ignored for 1245: that one call. 1246: 1247: =back 1248: 1249: B<Example -- only show orders placed more than 60 days ago> 1250: 1251: my $join = Database::Join->new( 1252: databases => [ $customers, $orders ], 1253: join_column => 'entry', 1254: filters => { 1 => { age_days => { '>' => 60 } } }, 1255: ); 1256: 1257: # Every query automatically sees only old orders 1258: my $rows = $join->selectall_arrayref(); 1259: 1260: # Additional criteria layer on top -- gold tier AND old order 1261: my $vip = $join->selectall_arrayref(tier => 'gold'); 1262: 1263: # Range intersection: age_days > 60 AND age_days < 365 1264: my $mid = $join->selectall_arrayref(age_days => { '<' => 365 }); 1265: 1266: When using C<add_database>, pass C<filter> (singular) to set the base 1267: criteria for the new database: 1268: 1269: $join->add_database($orders, filter => { age_days => { '>' => 60 } }); 1270: 1271: =head2 base_criteria - permanent view-level row filters by column name 1272: 1273: C<base_criteria> is a convenience alternative to C<filters> for callers who 1274: know the column names they want to restrict but prefer not to track database 1275: indices. 1276: 1277: my $join = Database::Join->new( 1278: databases => [ $customers, $orders ], 1279: join_column => 'entry', 1280: base_criteria => { active => 1, deleted_at => undef }, 1281: ); 1282: 1283: # Every query automatically sees only active, non-deleted rows. 1284: my $rows = $join->selectall_arrayref(); 1285: 1286: At construction time C<base_criteria> is partitioned by column ownership 1287: using the same routing logic as C<selectall_arrayref>. Each criterion is 1288: sent to the database that owns that column and stored as a permanent base 1289: filter (equivalent to the corresponding C<filters> entry). 1290: 1291: B<Unknown columns> emit a C<warn_unknown_column> carp and are silently 1292: dropped, just as they would be in a query call. 1293: 1294: B<Key-set semantics> are identical to C<filters>: any database that receives 1295: a C<base_criteria> slice acts as an inner-join partner regardless of 1296: C<join_type>. 1297: 1298: B<Precedence>: when a column appears in both C<base_criteria> and C<filters>, 1299: the C<filters> entry wins on plain-scalar conflicts; operator-hashref values 1300: are combined with AND semantics. 1301: 1302: B<Use cases> 1303: 1304: =over 4 1305: 1306: =item * 1307: 1308: Row-level security: C<< base_criteria => { tenant_id => $tid } >> 1309: 1310: =item * 1311: 1312: Soft-delete filtering: C<< base_criteria => { deleted_at => undef } >> 1313: 1314: =item * 1315: 1316: Status gates: C<< base_criteria => { active => 1 } >> 1317: 1318: =back 1319: 1320: =head2 mandatory_filters - row-level security predicates that cannot be bypassed 1321: 1322: C<mandatory_filters> is an arrayref of C<{col, op, val}> predicate hashrefs. 1323: Every predicate is applied to the merged result of every query, regardless of 1324: what criteria the caller passes. Unlike C<filters> and C<base_criteria> (which 1325: are per-database constraints applied at fetch time), C<mandatory_filters> 1326: operates on the fully-merged row set, ensuring the constraint applies uniformly 1327: even when the same logical value is spread across multiple databases. 1328: 1329: my $join = Database::Join->new( 1330: databases => [ $customers, $loyalty ], 1331: join_column => 'entry', 1332: mandatory_filters => [ 1333: { col => 'region', op => 'eq', val => 'West' }, 1334: { col => 'tier', op => 'ne', val => 'banned' }, 1335: { col => 'balance', op => 'gte', val => 0 }, 1336: ], 1337: ); 1338: 1339: Each predicate hashref must supply exactly these three keys: 1340: 1341: =over 4 1342: 1343: =item C<col> 1344: 1345: The column name in the merged view (as returned by C<columns()>). Must be 1346: present at construction time; columns added later via C<add_database()> are not 1347: retroactively covered by predicates already in C<_mandatory_filters>. 1348: 1349: =item C<op> 1350: 1351: The comparison operator. Supported values: 1352: 1353: eq -- string equality ($row->{col} eq $val) 1354: ne -- string inequality ($row->{col} ne $val) 1355: lt -- string less-than ($row->{col} lt $val) 1356: lte -- string <= ($row->{col} le $val) 1357: gt -- string greater-than ($row->{col} gt $val) 1358: gte -- string >= ($row->{col} ge $val) 1359: like -- SQL LIKE pattern (% = any sequence, _ = any one character) 1360: contains -- substring match (row value must contain val as a substring) 1361: 1362: Comparisons are lexicographic (string-based) on the array path; on the SQLite 1363: path they follow SQLite's default collation for the column type. Use the 1364: SQLite backend (C<backend =E<gt> 'sqlite'>) when numeric ordering matters. 1365: 1366: =item C<val> 1367: 1368: The right-hand side of the comparison. Must be a plain scalar. 1369: 1370: =back 1371: 1372: B<Supported use cases> 1373: 1374: =over 4 1375: 1376: =item * 1377: 1378: Row-level security: restrict the view to rows the current session is authorised 1379: to see: C<< { col => 'tenant_id', op => 'eq', val => $session_tenant } >> 1380: 1381: =item * 1382: 1383: Data classification gates: hide rows marked with a sensitivity label: 1384: C<< { col => 'classification', op => 'ne', val => 'restricted' } >> 1385: 1386: =item * 1387: 1388: Substring/pattern guards: 1389: C<< { col => 'email', op => 'contains', val => '@example.com' } >> 1390: or C<< { col => 'code', op => 'like', val => 'PROD_%' } >> 1391: 1392: =back 1393: 1394: B<SECURITY: C<mandatory_filters> must never be set from user-supplied values> 1395: 1396: The predicates in C<mandatory_filters> are an enforcement boundary. They must 1397: come from a trusted server-side source (a session store, a policy table, or 1398: hard-coded application configuration) -- never from URL parameters, form fields, 1399: HTTP headers, or any other user-controlled input. Setting this parameter from 1400: user-supplied data would allow an attacker to widen or replace the constraints 1401: and access rows they are not permitted to see. 1402: 1403: B<Array vs. SQLite backend> 1404: 1405: On the B<array backend>, C<mandatory_filters> is applied as a Perl-side C<grep> 1406: after the in-memory merge, immediately before C<sort_by>/C<limit>/C<offset>. 1407: A row that does not satisfy every predicate is silently dropped. 1408: 1409: On the B<SQLite backend>, each predicate is translated into a parameterised 1410: C<WHERE> clause and injected into the per-call SQL query. Values are always 1411: passed via DBI bind parameters, never by string interpolation. 1412: 1413: Both backends produce identical filtered results. 1414: 1415: =head2 distinct - deduplicate merged rows 1416: 1417: Pass C<< distinct => 1 >> to C<selectall_arrayref> or C<selectall_array> to 1418: remove duplicate rows from the merged result. 1419: 1420: # All unique tier values 1421: my $tiers = $join->selectall_arrayref( 1422: distinct => 1, 1423: columns => ['tier'], 1424: ); 1425: 1426: # All unique region + tier combinations 1427: my $combos = $join->selectall_arrayref( 1428: distinct => 1, 1429: columns => ['region', 'tier'], 1430: ); 1431: 1432: # Remove fully-identical merged rows (all columns participate) 1433: my $deduped = $join->selectall_arrayref(distinct => 1); 1434: 1435: The optional C<columns> arrayref projects each row to the named columns I<before> 1436: deduplication. Omitting C<columns> (or passing an empty arrayref) deduplicates 1437: on the full merged row: two rows must be identical in every column to be 1438: considered duplicates. 1439: 1440: B<Array backend>: deduplication is done in Perl using a seen-hash keyed on the 1441: selected column values. First occurrence wins. 1442: 1443: B<SQLite backend>: C<SELECT DISTINCT col1, col2, ...> is used; the SQL engine 1444: handles deduplication. 1445: 1446: Both backends produce identical results. 1447: 1448: B<Interaction with sort_by / limit / offset>: C<distinct> is applied first 1449: (before pagination and ordering), so C<limit> and C<offset> operate on the 1450: already-deduplicated set. 1451: 1452: =head2 collision_prefix - preserve colliding columns from secondary databases 1453: 1454: By default, when a column name appears in more than one database the I<last> 1455: database wins: its value silently overwrites earlier ones in merged rows. 1456: This loses data and makes the origin invisible. 1457: 1458: C<collision_prefix> changes this for secondary databases you designate. 1459: When a secondary database at index N has a column that already exists in the 1460: merged view, and C<collision_prefix-E<gt>{N}> is set, the colliding column is 1461: published as C<"$prefix.$col"> instead of overwriting. Both values are then 1462: visible: the original column keeps its name (from the earlier database), and 1463: the collision gets the prefixed name. 1464: 1465: C<collision_prefix> is a hashref. Each B<key> is the B<zero-based index> of 1466: a secondary database in the C<databases> array (same numbering as C<join_map>). 1467: Each B<value> is the prefix string to prepend. An index-0 entry is 1468: meaningless and silently ignored. Omitting C<collision_prefix> entirely 1469: preserves the previous last-wins behaviour and changes nothing. 1470: 1471: Non-colliding columns from a secondary database are always added as-is with 1472: no prefix, whether or not C<collision_prefix> is configured. 1473: 1474: B<Example -- sales table and products table, both with a "product" column> 1475: 1476: # $sales columns: id, product, amount, date 1477: # $products columns: sku, product, price, category 1478: # join on 'product' (left key) matched against 'sku' (right key via join_map) 1479: 1480: my $join = Database::Join->new( 1481: databases => [$sales, $products], 1482: join_column => 'product', 1483: join_map => { 1 => 'sku' }, 1484: collision_prefix => { 1 => 'products' }, 1485: ); 1486: 1487: $join->columns; 1488: # => ['amount', 'category', 'date', 'id', 'price', 'product', 'products.product'] 1489: # ^-- prefixed collision 1490: 1491: my $row = $join->fetchrow_hashref(product => 'widget'); 1492: # $row->{product} -- value from $sales 1493: # $row->{'products.product'} -- value from $products (different row, same column name) 1494: # $row->{price} -- from $products, no collision, kept as-is 1495: 1496: B<Querying on a prefixed column> 1497: 1498: Use the full published name as the criterion key: 1499: 1500: my $rows = $join->selectall_arrayref('products.product' => 'widget'); 1501: # Internally routes as: product => 'widget' to $products 1502: 1503: B<Interaction with remove_column> 1504: 1505: C<remove_column> operates on published names. To suppress a prefixed 1506: collision column entirely, pass the prefixed name: 1507: 1508: $join->remove_column('products.product'); 1509: 1510: =head2 backend - SQLite join backend for large datasets 1511: 1512: C<Database::Join> can merge component databases in two different ways, 1513: controlled by the C<backend> constructor parameter. 1514: 1515: =over 4 1516: 1517: =item C<backend =E<gt> 'array'> -- in-memory merge (original behaviour) 1518: 1519: All matching rows are fetched from every component database into Perl hashes 1520: and merged there. Simple and fast for small and medium datasets. Peak RAM 1521: is roughly three times the combined source data size (one copy per database 1522: plus one merged copy). 1523: 1524: =item C<backend =E<gt> 'sqlite'> -- SQL JOIN via a cached temporary file 1525: 1526: C<Database::Join> creates a temporary SQLite database file, spills source 1527: rows into it (one table per component database), then executes a single SQL 1528: C<JOIN> statement per query call. Peak RAM drops to roughly one times the 1529: source data size. 1530: 1531: The temporary file is created once and reused across multiple query calls on 1532: the same object (the cache). Only query-time criteria vary per call; they 1533: are applied as SQL C<WHERE> clauses against the cached data. The cache is 1534: automatically rebuilt when any source database's C<updated()> timestamp 1535: changes. The file is deleted when the object is destroyed (goes out of 1536: scope). See I<Temporary file: name, location, and lifetime> below for 1537: details. 1538: 1539: Requires C<DBD::SQLite E<gt>= 1.70> (C<FULL OUTER JOIN> support was added in 1540: SQLite 3.39.0; DBD::SQLite 1.70 ships SQLite 3.39.2). 1541: 1542: =item C<backend =E<gt> 'auto'> (default) 1543: 1544: C<Database::Join> counts the total rows from all component databases cheaply 1545: -- without fetching them -- and then decides: 1546: 1547: =over 4 1548: 1549: =item * 1550: 1551: If the combined count is less than or equal to C<max_array_rows> (default 1552: 10,000), use the array path. 1553: 1554: =item * 1555: 1556: If the combined count exceeds C<max_array_rows>, use the SQLite path. 1557: 1558: =back 1559: 1560: For counting to work without fetching, each component database must either 1561: implement the C<dbi_source()> interface (for SQLite-backed sources, where a 1562: C<COUNT(*)> SQL query is issued directly), or directly define a C<count()> 1563: method in its own package -- not just inherit one from a parent class. If 1564: neither is available for a particular database, C<Database::Join> plays it 1565: safe and uses the array path for the whole query without fetching any rows. 1566: 1567: =back 1568: 1569: B<Choosing max_array_rows> 1570: 1571: The default of 10,000 is a reasonable starting point. Adjust it to match 1572: your hardware and typical row width. For wide rows (many columns or long 1573: strings) you may want a lower threshold; for narrow rows you can raise it. 1574: 1575: B<Temporary file: name, location, and lifetime> 1576: 1577: When the SQLite path is active, a single temporary SQLite database file acts 1578: as the join cache for the life of the C<Database::Join> object. 1579: 1580: B<Name>: the filename is randomly generated by C<File::Temp>, for example: 1581: 1582: /tmp/Cj8xK7mP2Q.db 1583: 1584: The random portion (ten characters) is chosen automatically to avoid 1585: collisions. Only the directory is under your control; you cannot specify 1586: the filename itself. 1587: 1588: B<Location>: controlled by the C<tmpdir> constructor parameter. 1589: If C<tmpdir> is not specified, C<File::Spec-E<gt>tmpdir()> is used (usually 1590: C</tmp> on Unix, or the value of the C<TEMP> or C<TMP> environment variable 1591: on Windows). 1592: 1593: B<Lifetime: one file per object, deleted when the object is destroyed>: the 1594: file is created on the first query call that uses the SQLite path and kept 1595: alive until the C<Database::Join> object is destroyed (i.e. when it goes out 1596: of scope or is explicitly C<undef>-d). At most one file exists per object at 1597: any given moment. Calling C<selectall_arrayref()> ten times on the same 1598: object creates and uses I<one> file, not ten. 1599: 1600: B<Cache invalidation>: the cache is automatically rebuilt (the old file is 1601: replaced with a new one) when any source database's C<updated()> return value 1602: changes, or when C<add_database()> is called. Base-filter criteria 1603: (C<filters> constructor parameter) are applied once at build time for spilled 1604: sources; query-time criteria are applied per-call as SQL C<WHERE> clauses. 1605: 1606: To use a different directory -- for example a RAM-backed filesystem or a 1607: faster local disk: 1608: 1609: my $join = Database::Join->new( 1610: databases => [ $db1, $db2 ], 1611: join_column => 'entry', 1612: backend => 'sqlite', 1613: tmpdir => '/dev/shm', # Linux RAM disk 1614: ); 1615: 1616: B<Parallel secondary fetches (C<parallel> constructor parameter)> 1617: 1618: By default, component databases are queried sequentially - the primary first, 1619: then each secondary in order. When the component databases are network- or 1620: disk-backed and have non-trivial per-query latency, the sequential fetch means 1621: total latency is the I<sum> of all per-DA latencies. 1622: 1623: Setting C<< parallel => 1 >> in the constructor enables concurrent fetching 1624: of secondary databases using Perl C<threads>. With C<parallel => 1> and 1625: two or more secondary databases (C<n E<gt> 2> total), secondary fetches run in 1626: parallel after the primary fetch completes; total latency drops to 1627: I<max(secondary latencies)> instead of I<sum(secondary latencies)>. 1628: 1629: my $join = Database::Join->new( 1630: databases => [ $customers, $loyalty, $scores ], # 3 DAs - 2 secondaries 1631: join_column => 'entry', 1632: parallel => 1, # loyalty and scores fetched concurrently 1633: ); 1634: 1635: Requirements and caveats: 1636: 1637: =over 4 1638: 1639: =item * 1640: 1641: The C<threads> module must be available. Most distributions ship it, but it 1642: requires a Perl binary compiled with C<-Dusethreads>. When threads are 1643: unavailable, a C<carp> warning is emitted and fetching falls back to 1644: sequential; the result is identical, only slower. 1645: 1646: =item * 1647: 1648: Parallel fetching is only active when the join has three or more total 1649: databases (C<n E<gt> 2>). With two databases (one secondary), the thread 1650: creation overhead exceeds the benefit of concurrency; sequential is used 1651: regardless of C<parallel>. 1652: 1653: =item * 1654: 1655: Component databases must be safe to call from Perl threads. In-memory 1656: databases (CSV, JSON, TSV after slurp) are safe. DBI-backed databases 1657: whose handles were created in the same thread may not be safe - consult your 1658: DBD driver's thread documentation. The array backend is recommended for 1659: DBI-backed sources; the SQLite backend performs its join in a single SQL 1660: statement and does not use parallel fetching. 1661: 1662: =item * 1663: 1664: C<parallel => 1> applies to the array backend only. The SQLite backend 1665: performs a single SQL JOIN after spilling source data, so per-DA parallelism 1666: is irrelevant. 1667: 1668: =back 1669: 1670: B<Zero-copy ATTACH (C<dbi_source()> interface)> 1671: 1672: Normally, when the SQLite path is active, rows from each component database 1673: are fetched one by one and inserted into the temporary SQLite file. This is 1674: efficient but does involve INSERT overhead. 1675: 1676: If a component database is itself SQLite-backed and implements a 1677: C<dbi_source()> method, C<Database::Join> can skip the row-by-row copy 1678: entirely and instead use C<ATTACH DATABASE> to link the source file directly 1679: to the temporary join connection. This is the zero-copy path and is 1680: significantly faster for large SQLite sources. 1681: 1682: The C<dbi_source()> method must return a hashref with two keys: 1683: 1684: =over 4 1685: 1686: =item C<dbh> 1687: 1688: A connected C<DBD::SQLite> database handle (C<DBI> connection object). 1689: 1690: =item C<table> 1691: 1692: The name of the table in that database that holds the source rows. 1693: 1694: =back 1695: 1696: Example implementation: 1697: 1698: package My::SQLiteDatabase; 1699: use parent 'Database::Abstraction'; 1700: 1701: sub dbi_source { 1702: my ($self) = @_; 1703: return { 1704: dbh => $self->{_dbh}, # connected DBD::SQLite handle 1705: table => $self->{_table}, # table name in that database 1706: }; 1707: } 1708: 1709: 1; 1710: 1711: The zero-copy ATTACH path is always used when a component database implements 1712: C<dbi_source()>. Query-time criteria are applied as parameterised SQL 1713: C<WHERE> clauses against the ATTACHed source table, so no row-level copy is 1714: needed even when the current call includes column filters. (Prior to 0.005.0 1715: any query-time criteria forced a spill; that restriction was removed in 1716: 0.005.0.) 1717: 1718: B<Result identity> 1719: 1720: Both the array path and the SQLite path produce identical results for any 1721: given query. You can switch between them freely without changing callers. 1722: The C<collision_prefix> column renaming, C<join_map> key translation, and all 1723: three join types (left, inner, outer) work identically on both paths. 1724: 1725: =head2 selectall_arrayref 1726: 1727: =head3 SYNOPSIS 1728: 1729: my $rows = $join->selectall_arrayref(); 1730: my $rows = $join->selectall_arrayref(tier => 'gold'); 1731: my $rows = $join->selectall_arrayref(score => { '>' => 80 }); 1732: my $rows = $join->selectall_arrayref('C001'); # positional: entry => 'C001' 1733: my $rows = $join->selectall_arrayref(sort_by => 'name'); 1734: my $rows = $join->selectall_arrayref(tier => 'gold', sort_by => ['score', 'DESC']); 1735: my $rows = $join->selectall_arrayref(limit => 10); 1736: my $rows = $join->selectall_arrayref(limit => 10, offset => 20); 1737: my $rows = $join->selectall_arrayref(tier => 'gold', sort_by => 'name', limit => 5); 1738: my $rows = $join->selectall_arrayref(distinct => 1, columns => ['tier']); 1739: my $rows = $join->selectall_arrayref(distinct => 1); # distinct on all columns 1740: 1741: =head3 DESCRIPTION 1742: 1743: Returns an arrayref of hashrefs representing the merged view of all component 1744: databases, optionally filtered by the given criteria. 1745: 1746: Criteria for columns that live in different databases are routed 1747: automatically: each database is queried with only the criteria that apply to 1748: its own columns. The results are combined in memory using C<join_column>. 1749: Under a C<left> or C<inner> join, a secondary database is also limited to the 1750: primary's keys (see "Key pushdown" in L</DESCRIPTION>). 1751: 1752: Accepts the same criteria syntax as C<Database::Abstraction::selectall_arrayref>. 1753: A single plain scalar argument is interpreted as the C<join_column> value 1754: (equivalent to C<< entry => 'C001' >> when C<join_column> is C<'entry'>). 1755: 1756: Pass C<< distinct => 1 >> (with optional C<< columns => \@cols >>) to 1757: deduplicate results; see the C<distinct> feature section for details. 1758: 1759: =head3 API SPECIFICATION 1760: 1761: =head4 Input 1762: 1763: Calling conventions (in order of precedence): 1764: 1. No arguments -- returns all rows 1765: 2. One plain scalar -- shorthand for join_column => $scalar 1766: 3. Key-value pairs or 1767: a criteria hashref -- routed per-database 1768: 1769: Values may be: 1770: Plain scalar -- exact match 1771: Hashref of operators -- e.g. { '>' => 80 } 1772: 1773: Optional parameters (mixed in with any of the above): 1774: sort_by => 'colname' -- sort ascending by that column 1775: sort_by => ['colname', 'DESC'] -- sort descending 1776: sort_by => ['colname', 'ASC'] -- sort ascending (explicit) 1777: limit => N -- return at most N rows (positive integer) 1778: offset => M -- skip the first M rows (non-negative integer) 1779: 1780: The column named in sort_by must be present in the merged view (i.e. it 1781: must appear in columns()). An unknown column or an invalid direction emits 1782: a carp warning and falls back to the default join_column ascending sort. 1783: 1784: limit and offset are applied after ordering. offset without limit skips 1785: rows but returns all remaining rows. limit without offset starts from 1786: the first qualifying row. An invalid limit or offset emits a carp warning 1787: and the parameter is ignored (treated as absent). 1788: 1789: DOMAIN -- sort_by: 1790: EP absent: result sorted by join_column ASC (default). 1791: EP string: any column name in columns(); sorts ASC by that column. 1792: EP ['col','ASC']: explicit ascending; equivalent to the string form. 1793: EP ['col','DESC']: descending sort by the named column. 1794: EP ['col']: single-element arrayref; direction defaults to ASC. 1795: EP []: empty arrayref; column is undef -> carp + join_col ASC fallback. 1796: EP invalid column: column not in columns() -> carp + join_col ASC fallback. 1797: EP invalid dir: direction not 'ASC' or 'DESC' -> carp + ASC used. 1798: Sort is lexicographic (cmp); use backend=>'sqlite' for numeric ORDER BY. 1799: 1800: DOMAIN -- limit: 1801: EP absent: no truncation; all qualifying rows are returned. 1802: EP 0: not a positive integer -> carp + ignored (all rows returned). 1803: BVA min valid = 1: exactly 1 row returned. 1804: BVA at count: limit == total rows -> all rows returned (no truncation). 1805: BVA above count: limit > total rows -> all rows returned. 1806: EP invalid: negative integer, float string, or non-numeric string 1807: => carp + ignored (all rows returned). 1808: Valid domain: integers in [1, INF); matched by /^\d+\z/a with value >= 1. 1809: 1810: DOMAIN -- offset: 1811: EP absent: no rows skipped; result starts from row 0. 1812: BVA min valid = 0: no rows skipped (zero is a valid non-negative integer). 1813: BVA offset=1: first row skipped; result starts from row 1. 1814: BVA offset=N-1: N-1 rows skipped; only the last row returned. 1815: BVA offset=N: all N rows skipped; empty result returned. 1816: BVA offset>N: all rows skipped; empty result returned. 1817: EP invalid: negative integer, float string, or non-numeric string 1818: => carp + ignored (no rows skipped). 1819: Valid domain: integers in [0, INF); matched by /^\d+\z/a. 1820: 1821: distinct => 1 -- deduplicate rows after the merge (see columns below) 1822: columns => \@cols -- arrayref of column names to project and deduplicate on; 1823: used together with distinct => 1 1824: 1825: DOMAIN -- distinct: 1826: EP absent or 0: no deduplication; all merged rows are returned. 1827: EP 1: duplicates are removed (see below); first occurrence wins. 1828: EP truthy (not 1): treated as truthy; deduplication is applied. 1829: Effect: on the array backend, a Perl seen-hash keyed on the 1830: selected column values is used; first occurrence wins. 1831: On the SQLite backend, SELECT DISTINCT is used. 1832: 1833: DOMAIN -- columns: 1834: EP absent/undef: when distinct is set, deduplication is on all columns 1835: and full rows are returned. 1836: EP []: empty arrayref treated the same as absent. 1837: EP valid: arrayref of column names present in the merged view; 1838: result rows are projected to those columns only, and 1839: deduplication is on the projected values. 1840: EP with distinct=0: columns is ignored when distinct is absent or false. 1841: Note: unknown column names in the list are silently ignored 1842: at projection time; the row may lack those keys. 1843: 1844: =head4 Output 1845: 1846: Arrayref of hashrefs; one hashref per qualifying merged row. 1847: Sorted ascending by join_column by default; caller-controlled via sort_by. 1848: At most C<limit> rows when limit is given; the first C<offset> rows are 1849: skipped when offset is given. 1850: Returns a reference to an empty array when no rows match. 1851: 1852: =head3 EXAMPLE 1853: 1854: # All rows from both databases 1855: my $all = $join->selectall_arrayref(); 1856: 1857: # Only rows where the 'tier' column (from the loyalty database) 1858: # equals 'gold' -- the criterion is routed to the right database 1859: my $vip = $join->selectall_arrayref(tier => 'gold'); 1860: 1861: # Operator hashref: score > 80 1862: my $high = $join->selectall_arrayref(score => { '>' => 80 }); 1863: 1864: # Access each merged row 1865: for my $row (@{$vip}) { 1866: printf "%-10s tier=%-8s score=%d\n", 1867: $row->{entry}, $row->{tier}, $row->{score} // 0; 1868: } 1869: 1870: # Distinct tier values across all rows (project to one column, deduplicate) 1871: my $tiers = $join->selectall_arrayref(distinct => 1, columns => ['tier']); 1872: # Returns e.g. [{ tier => 'gold' }, { tier => 'silver' }, { tier => 'bronze' }] 1873: # regardless of how many rows exist for each tier 1874: 1875: # Distinct region+tier combinations 1876: my $combos = $join->selectall_arrayref( 1877: distinct => 1, 1878: columns => ['region', 'tier'], 1879: ); 1880: 1881: # Distinct on all columns (remove fully-duplicate merged rows) 1882: my $deduped = $join->selectall_arrayref(distinct => 1); 1883: 1884: =head3 MESSAGES 1885: 1886: warn_unknown_column (carp) 1887: -- A criterion key names a column not present in any component database; 1888: the criterion is silently dropped and all rows are returned. 1889: error_join_criterion (croak) 1890: -- A criterion hashref contains a join => key (DA SQL-JOIN syntax). 1891: Use a separate DA object for the joined table instead. 1892: sort_by column unknown (carp) 1893: -- The column given in sort_by is not in the merged view; the result 1894: is returned in the default join_column ascending order instead. 1895: sort_by direction invalid (carp) 1896: -- The direction given in sort_by is not 'ASC' or 'DESC'; ASC is used. 1897: limit invalid (carp) 1898: -- The value given for limit is not a positive integer; it is ignored. 1899: offset invalid (carp) 1900: -- The value given for offset is not a non-negative integer; it is ignored. 1901: operator-unsupported (carp, SQLite/auto path only) 1902: -- An operator hashref key is not in the supported set (>, <, >=, <=, 1903: !=, =, LIKE, NOT LIKE, IS NULL, IS NOT NULL, IN, NOT IN); the 1904: individual operator term is dropped from the WHERE clause (other 1905: operators in the same hashref still apply). 1906: IN/NOT IN wrong value type (carp, SQLite/auto path only) 1907: -- An IN or NOT IN criterion was given a non-arrayref value; the operator 1908: term is skipped. 1909: error_sqlite_connect (croak, SQLite/auto path only) 1910: -- The temporary SQLite join file could not be created; check tmpdir 1911: permissions and available disk space. 1912: 1913: =cut 1914: 1915: sub selectall_arrayref { 1916: my ($self, @args) = @_; 1917: my $params = $self->_parse_query_args(undef, @args); 1918: my $sort_by = delete $params->{sort_by}; 1919: my $limit = delete $params->{limit}; 1920: my $offset = delete $params->{offset}; 1921: my $distinct = delete $params->{distinct}; 1922: my $columns = delete $params->{columns}; 1923: return $self->_joined_query($params,

Mutants (Total: 2, Killed: 2, Survived: 0)

1924: sort_by => $sort_by, limit => $limit, offset => $offset, 1925: distinct => $distinct, columns => $columns); 1926: } 1927: 1928: =head2 selectall_array 1929: 1930: =head3 SYNOPSIS 1931: 1932: my @rows = $join->selectall_array(tier => 'gold'); 1933: 1934: # Scalar context: only the first matching row 1935: my $first = $join->selectall_array(entry => 'C001'); 1936: 1937: # Distinct column projection (list context) 1938: my @tiers = $join->selectall_array(distinct => 1, columns => ['tier']); 1939: 1940: # Distinct on all columns 1941: my @deduped = $join->selectall_array(distinct => 1); 1942: 1943: =head3 DESCRIPTION 1944: 1945: In list context returns a list of merged hashrefs -- the same rows that 1946: C<selectall_arrayref> would return, just as a flat list rather than an 1947: arrayref. 1948: 1949: In scalar context returns only the first matching hashref (or C<undef> if 1950: nothing matches). 1951: 1952: =head3 API SPECIFICATION 1953: 1954: =head4 Input 1955: 1956: Same as selectall_arrayref. 1957: 1958: =head4 Output 1959: 1960: List context: list of hashrefs (may be empty). 1961: Scalar context: single hashref or undef. 1962: 1963: =head3 EXAMPLE 1964: 1965: my @all = $join->selectall_array(); 1966: print scalar @all, " rows\n"; 1967: 1968: # First gold-tier customer only 1969: my $first_vip = $join->selectall_array(tier => 'gold'); 1970: print $first_vip->{name}, "\n" if defined $first_vip; 1971: 1972: =head3 MESSAGES 1973: 1974: Same messages as C<selectall_arrayref>. 1975: 1976: =cut 1977: 1978: sub selectall_array { 1979: my ($self, @args) = @_; 1980: my $params = $self->_parse_query_args(undef, @args); 1981: my $sort_by = delete $params->{sort_by}; 1982: my $limit = delete $params->{limit}; 1983: my $offset = delete $params->{offset}; 1984: my $distinct = delete $params->{distinct}; 1985: my $columns = delete $params->{columns}; 1986: my $rows = $self->_joined_query($params, 1987: sort_by => $sort_by, limit => $limit, offset => $offset, 1988: distinct => $distinct, columns => $columns); 1989: return wantarray ? @{$rows} : $rows->[0];

Mutants (Total: 2, Killed: 2, Survived: 0)

1990: } 1991: 1992: =head2 selectall_hashref 1993: 1994: Deprecated alias for L</selectall_arrayref>, present for compatibility with 1995: callers written against C<Database::Abstraction>'s deprecated API. Use 1996: C<selectall_arrayref> in new code. 1997: 1998: =cut 1999: 2000: sub selectall_hashref { 2001: my $self = shift; 2002: carp 'Database::Join::selectall_hashref is deprecated; use selectall_arrayref'; 2003: return $self->selectall_arrayref(@_);

Mutants (Total: 2, Killed: 2, Survived: 0)

2004: } 2005: 2006: =head2 selectall_hash 2007: 2008: Deprecated alias for L</selectall_array>, present for compatibility with 2009: callers written against C<Database::Abstraction>'s deprecated API. Use 2010: C<selectall_array> in new code. 2011: 2012: =cut 2013: 2014: sub selectall_hash { 2015: my $self = shift; 2016: carp 'Database::Join::selectall_hash is deprecated; use selectall_array'; 2017: return $self->selectall_array(@_);

Mutants (Total: 2, Killed: 2, Survived: 0)

2018: } 2019: 2020: =head2 fetchrow_hashref 2021: 2022: =head3 SYNOPSIS 2023: 2024: my $row = $join->fetchrow_hashref(entry => 'C001'); 2025: my $row = $join->fetchrow_hashref('C001'); # positional shorthand 2026: 2027: =head3 DESCRIPTION 2028: 2029: Returns a single merged hashref for the first row matching the given 2030: criteria, or C<undef> when nothing matches. 2031: 2032: Equivalent to calling C<selectall_arrayref> and taking only the first element. 2033: All the same criteria conventions apply. 2034: 2035: =head3 API SPECIFICATION 2036: 2037: =head4 Input 2038: 2039: Same as selectall_arrayref. 2040: 2041: =head4 Output 2042: 2043: Hashref, or undef when no row matches. 2044: 2045: =head3 EXAMPLE 2046: 2047: my $row = $join->fetchrow_hashref(entry => 'C001'); 2048: if (defined $row) { 2049: print "Name: $row->{name}, Tier: $row->{tier}\n"; 2050: } else { 2051: print "No record for C001\n"; 2052: } 2053: 2054: # Positional: works when join_column is 'entry' 2055: my $row2 = $join->fetchrow_hashref('C001'); 2056: 2057: =head3 MESSAGES 2058: 2059: Same messages as C<selectall_arrayref>. 2060: 2061: =cut 2062: 2063: sub fetchrow_hashref { 2064: my ($self, @args) = @_; 2065: my $params = $self->_parse_query_args(undef, @args); 2066: my $sort_by = delete $params->{sort_by}; 2067: delete $params->{limit}; # fetchrow_hashref always returns one row; limit is meaningless 2068: delete $params->{offset}; # offset would change which row is "first"; not supported here 2069: my $rows = $self->_joined_query($params, sort_by => $sort_by); 2070: return $rows->[0];

Mutants (Total: 2, Killed: 2, Survived: 0)

2071: } 2072: 2073: =head2 count 2074: 2075: =head3 SYNOPSIS 2076: 2077: my $total = $join->count(); 2078: my $active = $join->count(tier => 'gold'); 2079: 2080: =head3 DESCRIPTION 2081: 2082: Returns the number of merged rows that satisfy the given criteria. 2083: 2084: On the array backend, the full in-memory join is performed and the resulting 2085: rows are counted in Perl. On the SQLite backend, a C<SELECT COUNT(*)> SQL 2086: query is executed against the cached join tables, avoiding a full row fetch. 2087: 2088: =head3 API SPECIFICATION 2089: 2090: =head4 Input 2091: 2092: Same criteria syntax as selectall_arrayref. 2093: 2094: =head4 Output 2095: 2096: Non-negative integer. 2097: 2098: =head3 EXAMPLE 2099: 2100: my $total = $join->count(); 2101: my $gold = $join->count(tier => 'gold'); 2102: my $high = $join->count(score => { '>' => 90 }); 2103: 2104: printf "%d total, %d gold-tier, %d high-scorers\n", 2105: $total, $gold, $high; 2106: 2107: =head3 MESSAGES 2108: 2109: Same messages as C<selectall_arrayref>. 2110: 2111: =cut 2112: 2113: sub count { 2114: my ($self, @args) = @_; 2115: my $params = $self->_parse_query_args(undef, @args); 2116: delete $params->{sort_by}; # row ordering is irrelevant for a count 2117: delete $params->{limit}; # count returns total matching rows, not a page 2118: 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)

Mutants (Total: 2, Killed: 2, Survived: 0)

2121: unless $self->{_backend} eq 'array'; 2122: return scalar @{ $self->_joined_query_array($params) };

Mutants (Total: 2, Killed: 2, Survived: 0)

2123: } 2124: 2125: =head2 aggregate 2126: 2127: =head3 SYNOPSIS 2128: 2129: my $rows = $join->aggregate( 2130: by => ['tier'], 2131: measures => [ 2132: { col => 'score', fn => 'sum', as => 'total' }, 2133: { fn => 'count', as => 'n' }, 2134: ], 2135: having => { total => { '>' => 100 } }, 2136: sort_by => ['total', 'DESC'], 2137: limit => 10, 2138: ); 2139: # => [ { tier => 'gold', total => 183, n => 2 }, ... ] 2140: 2141: =head3 DESCRIPTION 2142: 2143: Groups the merged view by one or more published column names and computes 2144: aggregate measures over each group. 2145: 2146: On the SQLite backend (C<backend =E<gt> 'sqlite'>) and the C<auto> backend, 2147: the aggregation is pushed into the existing SQLite cache as a C<GROUP BY> 2148: query - rows never pass through Perl. The C<auto> backend always takes this 2149: path for aggregation, skipping the row-count threshold probe (aggregation 2150: makes the row count irrelevant). 2151: 2152: On the array backend (C<backend =E<gt> 'array'>), merged rows are fetched in 2153: full and folded in Perl. This materialises the complete matching result set. 2154: 2155: The two paths return the same rows for the same input, except for two 2156: documented differences: C<min>/C<max> on a column declared C<TEXT> but 2157: storing numbers (SQL compares lexically; Perl detects numerics), and 2158: C<sum>/C<avg> with non-numeric values (SQL coerces to 0.0; Perl skips and 2159: warns via C<warn_aggregate_non_numeric>). 2160: 2161: C<Database::Join> has no C<no_fixate> and no CHI cache (unlike 2162: C<Database::Abstraction>); aggregation results are not cached between calls. 2163: 2164: =head3 API SPECIFICATION 2165: 2166: =head4 Input 2167: 2168: Reserved keys extracted before the rest is treated as WHERE criteria: 2169: 2170: by => arrayref of published column names (default: [] = grand total) 2171: measures => arrayref of measure hashrefs (required, non-empty) 2172: having => hashref of post-aggregation criteria 2173: sort_by => 'col' or ['col', 'DESC'] 2174: limit => positive integer 2175: offset => non-negative integer 2176: 2177: Every other key is pre-aggregation criteria routed exactly as 2178: C<selectall_arrayref> routes criteria. 2179: 2180: Measure hashref keys: 2181: 2182: fn => function name (sum|avg|min|max|count|count_distinct), case-insensitive 2183: col => published column name (required for all functions except bare count) 2184: as => result key (required; must match C</^\w+\z/>; unique; not a by name) 2185: 2186: C<having> uses the same operator vocabulary as C<selectall_arrayref>: 2187: C<%SAFE_SQL_OPS> (E<gt>, E<lt>, E<gt>=, E<lt>=, !=, =, LIKE, NOT LIKE), 2188: C<%SAFE_LIST_OPS> (IN, NOT IN), C<%SAFE_NOARG_OPS> (IS NULL, IS NOT NULL), 2189: a bare scalar (= ?), and C<-or>/C<-and> groupings. Write C<-between> as 2190: two operators and C<LIKE> explicitly. 2191: 2192: =head4 Output 2193: 2194: Always an arrayref of hashrefs (never C<undef>). C<[]> when no group 2195: qualifies and C<by> is non-empty. When C<by> is omitted or C<[]> and no 2196: rows match, returns one all-normalised row (grand total of zero). 2197: 2198: Key order per row: C<by> columns in declaration order, then measure aliases 2199: in declaration order. 2200: 2201: =head3 EXAMPLE 2202: 2203: # Total score and row count per tier, highest total first 2204: my $rows = $join->aggregate( 2205: by => ['tier'], 2206: measures => [ 2207: { col => 'score', fn => 'sum', as => 'total' }, 2208: { fn => 'count', as => 'n' }, 2209: ], 2210: sort_by => ['total', 'DESC'], 2211: ); 2212: for my $r (@{$rows}) { 2213: printf "%s: total=%s n=%s\n", $r->{tier}, $r->{total}, $r->{n}; 2214: } 2215: 2216: =head3 PSEUDOCODE 2217: 2218: 1. get_params(undef, @args) -- hashref or kv-pairs only (no positional key) 2219: 2. croak error_join_criterion if 'join =>' present 2220: 3. _validate_aggregate_spec extracts by/measures/having/sort_by/limit/offset 2221: 4. array backend: 2222: rows = _joined_query_array(remaining criteria, no sort/limit/offset) 2223: groups = _fold_aggregate(rows, spec) 2224: groups = [grep { _match_criteria($_, having) } @groups] if having 2225: _normalise_aggregate(groups, spec.measures) 2226: _sort_and_page(groups, spec) 2227: sqlite/auto backend: 2228: _sqlite_aggregate(remaining criteria, spec) 2229: 5. return groups 2230: 2231: =head3 MESSAGES 2232: 2233: C<error_aggregate_measures_required>, C<error_aggregate_measure_ref>, 2234: C<error_aggregate_fn_unknown>, C<error_aggregate_col_required>, 2235: C<error_aggregate_col_unknown>, C<error_aggregate_as_required>, 2236: C<error_aggregate_as_invalid>, C<error_aggregate_as_duplicate>, 2237: C<error_aggregate_as_collision>, C<error_aggregate_by_invalid>, 2238: C<error_aggregate_having_key>, C<error_aggregate_having_operator>, 2239: C<warn_aggregate_sort_key>, C<warn_aggregate_non_numeric>. 2240: 2241: =cut 2242: 2243: sub aggregate { ●2244 → 2255 → 0 2244: my ($self, @args) = @_; 2245: my $p = get_params(undef, @args) // {}; 2246: 2247: croak $self->_err('error_join_criterion') if exists $p->{join}; 2248: 2249: 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: my $backend = $self->{_backend}; 2254: 2255: if ($backend eq 'array') {

Mutants (Total: 1, Killed: 1, Survived: 0)

2256: # Fetch all matching merged rows without sort/limit/offset — 2257: # those must be applied after grouping. 2258: my $merged = $self->_joined_query_array($p); 2259: my $groups = $self->_fold_aggregate($merged, $spec); 2260: 2261: # Apply HAVING on the folded groups. 2262: if (my $having = $spec->{having}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2263: $groups = [grep { $self->_match_criteria($_, $having) } @{$groups}]; 2264: } 2265: 2266: $self->_normalise_aggregate($groups, $spec->{measures}); 2267: $self->_sort_and_page($groups, $spec); 2268: return $groups;

Mutants (Total: 2, Killed: 2, Survived: 0)

2269: } else { 2270: # SQLite path (including 'auto'): always use SQL, no threshold probe. 2271: return $self->_sqlite_aggregate($p, $spec);

Mutants (Total: 2, Killed: 2, Survived: 0)

2272: } 2273: } 2274: 2275: =head2 each_row 2276: 2277: =head3 SYNOPSIS 2278: 2279: my $count = $join->each_row(sub { my ($row) = @_; ... }); 2280: my $count = $join->each_row(sub { ... }, tier => 'gold'); 2281: my $count = $join->each_row(sub { ... }, sort_by => 'name', limit => 100); 2282: 2283: =head3 DESCRIPTION 2284: 2285: Calls C<\&callback> once for every row in the merged view that matches the 2286: given criteria, then returns the total count of rows visited. 2287: 2288: Accepts the same criteria, C<sort_by>, C<limit>, and C<offset> parameters as 2289: C<selectall_arrayref>. 2290: 2291: B<Note on memory usage>: C<Database::Join> always materialises the complete 2292: merged result set before invoking the callback, because merging rows from 2293: multiple independent sources requires that every source be queried and 2294: cross-referenced first. True constant-memory streaming (as C<Database::Abstraction> 2295: provides on single-source SQL queries) is not possible at the join layer. 2296: For genuinely large result sets use the SQLite backend (C<backend =E<gt> 2297: 'sqlite'>), which keeps peak RAM to approximately one times the source data 2298: size rather than three. 2299: 2300: Any exception thrown inside the callback propagates to the caller after the 2301: current row; subsequent rows are not visited. 2302: 2303: =head3 API SPECIFICATION 2304: 2305: =head4 Input 2306: 2307: \&callback Positional coderef (required). 2308: Called as $callback->($row_hashref) for each merged row. 2309: 2310: Additional arguments follow the same calling conventions as 2311: selectall_arrayref: no args, a single scalar join-column value, 2312: or key-value criteria pairs (including sort_by, limit, offset). 2313: 2314: =head4 Output 2315: 2316: Non-negative integer: the count of rows for which the callback was invoked. 2317: 2318: =head3 EXAMPLE 2319: 2320: # Print every gold-tier customer's name, sorted by name 2321: my $count = $join->each_row( 2322: sub { my ($row) = @_; print "$row->{name}\n" }, 2323: tier => 'gold', 2324: sort_by => 'name', 2325: ); 2326: print "$count gold-tier customers\n"; 2327: 2328: # Accumulate without holding the full result 2329: my $total_score = 0; 2330: $join->each_row(sub { $total_score += $_[0]->{score} // 0 }); 2331: 2332: =head3 MESSAGES 2333: 2334: error_invalid_callback (croak) 2335: -- First argument is not a code reference. 2336: 2337: =cut 2338: 2339: sub each_row { ●2340 → 2348 → 2352 2340: my ($self, $cb, @args) = @_; 2341: 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: my $rows = $self->selectall_arrayref(@args); 2347: my $count = 0; 2348: for my $row (@{$rows}) { 2349: $cb->($row); 2350: $count++; 2351: } 2352: return $count;

Mutants (Total: 2, Killed: 2, Survived: 0)

2353: } 2354: 2355: =head2 dbi_source 2356: 2357: =head3 SYNOPSIS 2358: 2359: # Use a Database::Join object as a zero-copy SQLite source inside a 2360: # parent Database::Join, giving the parent ATTACHed-speed access to 2361: # the child's joined data without iterating through Perl. 2362: my $child = Database::Join->new(databases => [$da, $db], join_column => 'id', backend => 'sqlite'); 2363: my $parent = Database::Join->new(databases => [$child, $dc], join_column => 'id', backend => 'sqlite'); 2364: 2365: =head3 DESCRIPTION 2366: 2367: Returns a hashref C<< { dbh => $sqlite_dbh, table => '_dj_result' } >> that 2368: allows a parent C<Database::Join> (or any other caller that understands the 2369: C<dbi_source()> interface) to ATTACH the child's temporary SQLite database 2370: file and query the materialised join result directly via SQL, without routing 2371: rows through Perl. 2372: 2373: The first call builds the SQLite cache (if not already current) and 2374: materialises the full join result - with C<filters> applied but no query-time 2375: criteria - into a real table named C<_dj_result> inside the cache file. 2376: Subsequent calls within the same cache cycle reuse the existing table. 2377: 2378: Returns C<undef> when the backend is C<'array'> (no SQLite file exists). 2379: 2380: =head3 API SPECIFICATION 2381: 2382: =head4 Input 2383: 2384: None. 2385: 2386: =head4 Output 2387: 2388: On the SQLite/auto backend: 2389: Hashref with keys: 2390: dbh => DBI handle to the child's temporary SQLite database file. 2391: table => '_dj_result' (the materialized join table inside that file). 2392: On the array backend: 2393: undef 2394: 2395: =head3 EXAMPLE 2396: 2397: # The parent automatically ATTACHes the child's SQLite file and queries 2398: # _dj_result for zero-copy composable nested joins. 2399: my $inner = Database::Join->new( 2400: databases => [$customers, $loyalty], 2401: join_column => 'entry', 2402: backend => 'sqlite', 2403: ); 2404: my $outer = Database::Join->new( 2405: databases => [$inner, $scores], 2406: join_column => 'entry', 2407: backend => 'sqlite', 2408: ); 2409: my $rows = $outer->selectall_arrayref(tier => 'gold'); 2410: 2411: =head3 MESSAGES 2412: 2413: error_sqlite_connect (croak) 2414: -- The temporary SQLite join file could not be created. 2415: 2416: =cut 2417: 2418: sub dbi_source { ●2419 → 2434 → 2442 2419: my ($self) = @_; 2420: 2421: # The array backend has no SQLite handle to expose. 2422: return undef if $self->{_backend} eq 'array';

Mutants (Total: 2, Killed: 2, Survived: 0)

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: $self->_build_sqlite_cache() unless $self->_cache_fresh(); 2428: 2429: 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: unless ($cache->{_dj_built}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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: $self->_sqlite_join({}, create_table => '_dj_result'); 2439: $cache->{_dj_built} = 1; 2440: } 2441: 2442: return { dbh => $cache->{dbh}, table => '_dj_result' }; 2443: } 2444: 2445: =head2 columns 2446: 2447: =head3 SYNOPSIS 2448: 2449: my $cols = $join->columns(); 2450: 2451: =head3 DESCRIPTION 2452: 2453: Returns an arrayref of all column names visible in the merged view, 2454: deduplicated and sorted alphabetically. 2455: 2456: The C<join_column> appears exactly once, even if it exists under different 2457: local names in some databases (see C<join_map>). Columns that have been 2458: hidden with C<remove_column> or C<remove_columns> do not appear. 2459: 2460: The result is memoised: repeated calls are cheap. 2461: 2462: =head3 API SPECIFICATION 2463: 2464: =head4 Input 2465: 2466: None. 2467: 2468: =head4 Output 2469: 2470: Arrayref of column name strings, sorted alphabetically. 2471: 2472: =head3 EXAMPLE 2473: 2474: my $cols = $join->columns(); 2475: print join(', ', @{$cols}), "\n"; 2476: # e.g. "entry, name, score, tier" 2477: 2478: =head3 MESSAGES 2479: 2480: C<columns()> does not itself emit any warnings or errors. Any exception thrown 2481: by a component database's C<columns()> method propagates uncaught. 2482: 2483: =cut 2484: 2485: sub columns { ●2486 → 2494 → 2509 2486: my ($self) = @_; 2487: 2488: return $self->{_col_cache} if $self->{_col_cache};

Mutants (Total: 2, Killed: 2, Survived: 0)

2489: 2490: my %seen; 2491: my @cols; 2492: my $join_col = $self->{_join_col}; 2493: 2494: for my $i (0 .. $#{ $self->{_dbs} }) { 2495: my $local_jc = $self->{_join_map}{$i}; 2496: my $renames = $self->{_col_rename}[$i] // {}; 2497: 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: 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: my $pub = $renames->{$col} // $col; 2503: next if $seen{$pub}++; 2504: next if $self->{_removed_cols}{$pub}; 2505: push @cols, $pub; 2506: } 2507: } 2508: 2509: $self->{_col_cache} = [ sort @cols ]; 2510: return $self->{_col_cache};

Mutants (Total: 2, Killed: 2, Survived: 0)

2511: } 2512: 2513: =head2 schema 2514: 2515: =head3 SYNOPSIS 2516: 2517: my $schema = $join->schema(); 2518: 2519: =head3 DESCRIPTION 2520: 2521: Returns a merged schema hashref for all visible columns across all component 2522: databases. Each key is a column name; each value is the schema metadata 2523: hashref returned by C<Database::Abstraction::schema()> for that column 2524: (typically C<{ type, nullable, default, pk }>). 2525: 2526: When the same column name appears in more than one database the I<last> 2527: database's metadata is used. Columns hidden with C<remove_column> are not 2528: included. 2529: 2530: The result is memoised. 2531: 2532: =head3 API SPECIFICATION 2533: 2534: =head4 Input 2535: 2536: None. 2537: 2538: =head4 Output 2539: 2540: Hashref: column_name => { type => ..., nullable => ..., default => ..., pk => ... }. 2541: 2542: =head3 EXAMPLE 2543: 2544: my $schema = $join->schema(); 2545: for my $col (sort keys %{$schema}) { 2546: my $info = $schema->{$col}; 2547: printf "%-15s type=%-10s nullable=%s\n", 2548: $col, $info->{type}, $info->{nullable} ? 'yes' : 'no'; 2549: } 2550: 2551: =head3 MESSAGES 2552: 2553: C<schema()> does not itself emit any warnings or errors. Any exception thrown 2554: by a component database's C<schema()> method propagates uncaught. 2555: 2556: =cut 2557: 2558: sub schema { ●2559 → 2567 → 2583 2559: my ($self) = @_; 2560: 2561: return $self->{_schema_cache} if $self->{_schema_cache};

Mutants (Total: 2, Killed: 2, Survived: 0)

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: my %merged; 2567: for my $i (0 .. $#{ $self->{_dbs} }) { 2568: my $s = $self->{_dbs}[$i]->schema() // {}; 2569: my $local_jc = $self->{_join_map}{$i}; 2570: my $renames = $self->{_col_rename}[$i] // {}; 2571: my $skip_jc = $local_jc && $local_jc ne $self->{_join_col}; 2572: if (!$skip_jc && !%{$renames}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2573: # Fast path: no join-key alias to exclude and no collision renames 2574: @merged{keys %{$s}} = values %{$s}; 2575: } else { 2576: for my $col (keys %{$s}) { 2577: next if $skip_jc && $col eq $local_jc; 2578: $merged{ $renames->{$col} // $col } = $s->{$col}; 2579: } 2580: } 2581: } 2582: 2583: delete @merged{keys %{ $self->{_removed_cols} }} 2584: if %{ $self->{_removed_cols} }; 2585: 2586: $self->{_schema_cache} = \%merged; 2587: return $self->{_schema_cache};

Mutants (Total: 2, Killed: 2, Survived: 0)

2588: } 2589: 2590: =head2 updated 2591: 2592: =head3 SYNOPSIS 2593: 2594: my $ts = $join->updated(); 2595: 2596: =head3 DESCRIPTION 2597: 2598: Returns the Unix timestamp of the most recent modification across all 2599: component databases. This is the maximum of all individual C<updated()> 2600: return values. 2601: 2602: Use this to implement simple cache-invalidation logic: if C<updated()> 2603: has advanced since your last snapshot, re-query. 2604: 2605: =head3 API SPECIFICATION 2606: 2607: =head4 Input 2608: 2609: None. 2610: 2611: =head4 Output 2612: 2613: Unix timestamp (positive integer). 2614: 2615: =head3 EXAMPLE 2616: 2617: my $last_modified = $join->updated(); 2618: if ($last_modified > $my_cache_timestamp) { 2619: $my_cache = $join->selectall_arrayref(); 2620: $my_cache_timestamp = $last_modified; 2621: } 2622: 2623: =head3 MESSAGES 2624: 2625: C<updated()> does not emit any warnings or errors. Component databases that do 2626: not implement C<updated()>, or whose C<updated()> throws, are silently skipped; 2627: only defined return values contribute to the maximum. If no component database 2628: implements C<updated()>, C<undef> is returned (same as C<List::Util::max> on an 2629: empty list). 2630: 2631: =cut 2632: 2633: sub updated { ●2634 → 2636 → 2641 2634: my ($self) = @_; 2635: my @timestamps; 2636: for my $db (@{ $self->{_dbs} }) { 2637: my $ts; 2638: do { local $@; $ts = eval { $db->updated() } }; 2639: push @timestamps, $ts if defined $ts; 2640: } 2641: return max(@timestamps);

Mutants (Total: 2, Killed: 2, Survived: 0)

2642: } 2643: 2644: =head2 set_logger 2645: 2646: =head3 SYNOPSIS 2647: 2648: $join->set_logger($log); 2649: $join->set_logger(logger => $log); # named-pair form also accepted 2650: 2651: =head3 DESCRIPTION 2652: 2653: Attaches a new logger object to the join and propagates it to every component 2654: database. The logger is used for diagnostic output by all component databases. 2655: 2656: Non-blessed values (a log-level string such as C<"debug">, a filename, or a 2657: code reference) are wrapped in C<Log::Abstraction->new(...)> automatically, 2658: matching the behaviour of C<Database::Abstraction::set_logger>. 2659: 2660: =head3 API SPECIFICATION 2661: 2662: =head4 Input 2663: 2664: logger Positional or named: a logger object, log-level string, filename, 2665: or code reference (required). Non-blessed values are wrapped in 2666: Log::Abstraction automatically. 2667: 2668: =head4 Output 2669: 2670: Returns C<$self> for method chaining. 2671: 2672: =head3 EXAMPLE 2673: 2674: # Log::Any is used here as an example; any object that implements 2675: # debug() and info() (or whichever methods your component databases 2676: # call internally) works equally well. 2677: use Log::Any qw($log); 2678: 2679: my $join = Database::Join->new(databases => [$db1, $db2], join_column => 'entry'); 2680: $join->set_logger($log); 2681: # $log is now used by $join and by $db1 and $db2 2682: 2683: # Named-pair form (mirrors Database::Abstraction API): 2684: $join->set_logger(logger => $log); 2685: 2686: =head3 MESSAGES 2687: 2688: (croak) Usage: set_logger(logger => $logger) 2689: -- Called with an undefined argument. Pass a valid logger object. 2690: 2691: =cut 2692: 2693: sub set_logger { 2694: my $self = shift; 2695: my $p = Params::Get::get_params('logger', @_); 2696: my $logger = $p->{'logger'}; 2697: 2698: 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: $logger = Log::Abstraction->new($logger) 2703: unless Scalar::Util::blessed($logger); 2704: 2705: $self->{_logger} = $logger; 2706: $_->set_logger($logger) for @{ $self->{_dbs} }; 2707: 2708: return $self;

Mutants (Total: 2, Killed: 2, Survived: 0)

2709: } 2710: 2711: =head2 add_database 2712: 2713: =head3 SYNOPSIS 2714: 2715: # Positional: database object as first argument 2716: $join->add_database($db); 2717: 2718: # Named: equivalent to the above 2719: $join->add_database(database => $db); 2720: 2721: # With options (mixed positional + named) 2722: $join->add_database($db, remove_columns => ['internal_id']); 2723: $join->add_database($db, join_column => 'local_key_name'); 2724: $join->add_database($db, filter => { score => { '>' => 60 } }); 2725: 2726: # Chainable 2727: $join->add_database($db1)->add_database($db2, remove_columns => ['notes']); 2728: 2729: =head3 DESCRIPTION 2730: 2731: Adds one more C<Database::Abstraction> subclass object to the logical view 2732: and immediately updates the column-ownership index. 2733: 2734: After the call, all query methods return rows that include columns from the 2735: newly added database, and criteria on those new columns are routed to it 2736: automatically. 2737: 2738: When a column name in the new database already exists in an earlier database, 2739: the new database becomes the authoritative source for that column 2740: (last-database-wins, the same rule that applies at construction time). 2741: 2742: The join-column must be present in the new database (or declared via 2743: C<join_column>). The logger is propagated to the new database if one is set. 2744: 2745: C<add_database> is the runtime equivalent of listing the database in the 2746: C<databases> array to C<new>. The optional C<join_column> parameter is 2747: equivalent to a C<join_map> entry; the optional C<filter> parameter is 2748: equivalent to a C<filters> entry. 2749: 2750: =head3 API SPECIFICATION 2751: 2752: =head4 Input 2753: 2754: database => { type => 'object', required => 1 } 2755: # A Database::Abstraction subclass instance. 2756: # 2757: # DOMAIN -- EP valid: blessed object that passes 2758: # isa('Database::Abstraction'). 2759: # DOMAIN -- EP invalid: non-reference, unblessed ref, wrong class, 2760: # or non-reference non-key scalar (the guard at 2761: # the top of add_database rejects it with 2762: # error_invalid_db before validate_strict runs). 2763: 2764: join_column => { type => 'string', optional => 1 } 2765: # The name of the join key in THIS new database, 2766: # when it differs from the canonical join_column. 2767: # 2768: # DOMAIN -- EP valid: any string that exists as a column in the 2769: # new database. 2770: # DOMAIN -- EP invalid: string absent from the new database's columns() 2771: # => croak error_join_col_missing. 2772: 2773: filter => { type => 'hashref', optional => 1 } 2774: # Permanent criteria for this database only. 2775: # Same format as selectall_arrayref. 2776: # 2777: # DOMAIN -- EP valid: hashref of criteria (may be {} for no-op). 2778: # DOMAIN -- EP absent: no permanent filter applied; all rows visible. 2779: # DOMAIN -- Key-set: a non-empty filter makes this DB an inner-join 2780: # partner regardless of the outer join_type. 2781: 2782: remove_columns => { type => 'arrayref', optional => 1 } 2783: # Column names from this database to hide. 2784: # 2785: # DOMAIN -- EP valid: arrayref of strings; non-existent columns silently 2786: # ignored; empty [] is a safe no-op. 2787: # DOMAIN -- EP invalid: join_column itself => croak error_remove_join_col. 2788: 2789: =head4 Output 2790: 2791: Returns C<$self> to support method chaining. 2792: 2793: =head3 EXAMPLE 2794: 2795: my $join = Database::Join->new( 2796: databases => [ $customers ], 2797: join_column => 'entry', 2798: ); 2799: 2800: # Add loyalty data; hide internal columns from it 2801: $join->add_database($loyalty, remove_columns => ['audit_ts']); 2802: 2803: # Add score data; only include rows with score > 60 2804: $join->add_database($scores, filter => { score => { '>' => 60 } }); 2805: 2806: # Add a database whose join key has a different local name 2807: $join->add_database($stnames, join_column => 'state_code'); 2808: 2809: # All three options combined, and chained 2810: $join->add_database($db4, 2811: join_column => 'ref_id', 2812: filter => { active => 1 }, 2813: remove_columns => ['legacy_col'], 2814: ); 2815: 2816: =head3 PSEUDOCODE 2817: 2818: determine the new database's index (length of current _dbs array) 2819: extract the database object from positional or named argument 2820: croak if it is not a Database::Abstraction subclass 2821: register join_column alias in _join_map if different from canonical 2822: register filter in _filters if provided 2823: fetch column list from the new database 2824: croak if the join key is missing from the new database 2825: append the new database to _dbs and _db_cols 2826: update _col_db: for each new column, point it at the new index 2827: (last-database-wins; skip removed columns and the local join alias) 2828: invalidate _col_cache and _schema_cache 2829: propagate logger if set 2830: apply remove_columns if provided 2831: return $self 2832: 2833: =head3 MESSAGES 2834: 2835: error_invalid_db -- argument is not a Database::Abstraction subclass 2836: error_join_col_missing -- join_column not found in the new database 2837: warn_schema_type_mismatch -- (carp) the new database has a shared column whose type 2838: differs from the type already in the view; use 2839: collision_prefix to preserve both values 2840: 2841: =cut 2842: 2843: sub add_database { ●2844 → 2853 → 2862 2844: my ($self, @args) = @_; 2845: 2846: my $idx = scalar @{ $self->{_dbs} }; 2847: 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: if (@args && !ref($args[0])) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2854: croak $self->_err('error_invalid_db', $idx) 2855: 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: $db = shift @args; 2860: } 2861: ●2862 → 2906 → 2924 2862: 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: $db //= $p->{database}; 2877: 2878: 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: my $local_jc = $p->{join_column} // $self->{_join_col}; 2885: $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: $self->{_filters}{$idx} = _copy_criteria($p->{filter}) if $p->{filter}; 2888: 2889: my $cols = $db->columns(); 2890: my %col_presence = map { $_ => 1 } @{$cols}; 2891: 2892: croak $self->_err('error_join_col_missing', $local_jc, $idx, ref($db)) 2893: unless $col_presence{$local_jc}; 2894: 2895: # Register the new database 2896: push @{ $self->{_dbs} }, $db; 2897: 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: my $prefix = $self->{_collision_prefix}{$idx}; 2903: $self->{_col_rename}[$idx] //= {}; 2904: $self->{_col_unrename}[$idx] //= {}; 2905: 2906: for my $col (@{$cols}) { 2907: next if $local_jc ne $self->{_join_col} && $col eq $local_jc; 2908: 2909: my $pub; 2910: if (defined $prefix && exists $self->{_col_db}{$col} && $col ne $self->{_join_col}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2911: # Same guard as _build_col_index: never prefix the join_column itself. 2912: $pub = "$prefix.$col"; 2913: $self->{_col_rename}[$idx]{$col} = $pub; 2914: $self->{_col_unrename}[$idx]{$pub} = $col; 2915: } else { 2916: $pub = $col; 2917: } 2918: 2919: next if $self->{_removed_cols}{$pub}; 2920: $self->{_col_db}{$pub} = $idx; 2921: } 2922: 2923: # Invalidate memoisation caches ●2924 → 2931 → 2937 2924: $self->{_col_cache} = undef; 2925: $self->{_schema_cache} = undef; 2926: 2927: # Warn about schema type mismatches introduced by the new database. 2928: $self->_validate_schema_types(); 2929: 2930: # Invalidate the SQLite join cache: a new source requires a full rebuild. 2931: if (my $old = delete $self->{_sqlite_cache}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2932: local $@; 2933: eval { $old->{dbh}->disconnect } if $old->{dbh}; 2934: } 2935: 2936: # Propagate logger if one is configured ●2937 → 2937 → 2942 2937: if (my $log = $self->{_logger}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2938: $db->set_logger($log); 2939: } 2940: 2941: # Apply any column removals requested for this database ●2942 → 2942 → 2946 2942: if (my $rc = $p->{remove_columns}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2943: $self->remove_column($_) for @{$rc}; 2944: } 2945: 2946: return $self;

Mutants (Total: 2, Killed: 2, Survived: 0)

2947: } 2948: 2949: =head2 remove_column 2950: 2951: =head3 SYNOPSIS 2952: 2953: $join->remove_column('email'); 2954: 2955: # Chainable 2956: $join->remove_column('internal_id')->remove_column('audit_ts'); 2957: 2958: =head3 DESCRIPTION 2959: 2960: Permanently hides a column from the merged view. After this call: 2961: 2962: =over 4 2963: 2964: =item * 2965: 2966: The column does not appear in C<columns()> or C<schema()>. 2967: 2968: =item * 2969: 2970: Returned row hashrefs do not contain the column key. 2971: 2972: =item * 2973: 2974: Any query criterion that references the removed column is silently dropped 2975: (with a C<carp> warning). 2976: 2977: =back 2978: 2979: The C<join_column> cannot be removed; attempting to do so will C<croak>. 2980: Removing a column that does not exist in any database is silently ignored 2981: (the call is idempotent and safe). The C<columns()> and C<schema()> 2982: memoisation caches are cleared automatically. 2983: 2984: =head3 API SPECIFICATION 2985: 2986: =head4 Input 2987: 2988: $col Positional string: the column name to remove. 2989: 2990: DOMAIN -- EP valid: any string; non-existent columns are silently 2991: ignored (idempotent call, returns $self). 2992: DOMAIN -- EP invalid: join_column value => croak error_remove_join_col. 2993: DOMAIN -- BVA: undef and '' are explicit no-ops (returns $self). 2994: These are below the minimum meaningful string 2995: length and are handled without any warning. 2996: 2997: =head4 Output 2998: 2999: Returns C<$self> to support method chaining. 3000: 3001: =head3 EXAMPLE 3002: 3003: # Hide private fields immediately after construction 3004: my $join = Database::Join->new( 3005: databases => [ $customers, $loyalty ], 3006: join_column => 'entry', 3007: )->remove_column('email') 3008: ->remove_column('internal_notes'); 3009: 3010: # Verify they are gone 3011: my $cols = $join->columns(); 3012: # 'email' and 'internal_notes' are absent 3013: 3014: =head3 MESSAGES 3015: 3016: error_remove_join_col -- attempt to remove the join_column itself 3017: 3018: =cut 3019: 3020: sub remove_column { 3021: 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: return $self unless defined $col && length $col;

Mutants (Total: 2, Killed: 2, Survived: 0)

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: if $col eq $self->{_join_col}; 3031: 3032: $self->{_removed_cols}{$col} = 1; 3033: delete $self->{_col_db}{$col}; 3034: $self->{_col_cache} = undef; 3035: $self->{_schema_cache} = undef; 3036: $self->{_removed_list} = undef; # invalidate the cached removed-column list 3037: 3038: return $self;

Mutants (Total: 2, Killed: 2, Survived: 0)

3039: } 3040: 3041: =head2 query 3042: 3043: Not supported. C<Database::Join> does not implement the 3044: C<Database::Abstraction::Query> chained builder because the builder's 3045: C<.all()> / C<.first()> methods would be targeting a single component DA 3046: rather than the merged view. Calling this method will always C<croak>. 3047: 3048: Use C<selectall_arrayref>, C<selectall_array>, C<fetchrow_hashref>, 3049: C<count>, or C<each_row> against the C<Database::Join> object instead. 3050: 3051: =cut 3052: 3053: sub query { 3054: my $self = $_[0]; 3055: croak $self->_err('error_query_unsupported'); 3056: } 3057: 3058: =head2 group_by 3059: 3060: Not supported. C<Database::Join> does not implement the 3061: C<Database::Abstraction::Query> fluent chain entry point because the chain's 3062: C<.all()> / C<.first()> methods would target a single component DA rather 3063: than the merged view. Calling this method will always C<croak>. 3064: 3065: Use C<aggregate()> against the C<Database::Join> object instead. 3066: 3067: =cut 3068: 3069: sub group_by { 3070: my $self = $_[0]; 3071: croak $self->_err('error_group_by_unsupported'); 3072: } 3073: 3074: =head2 execute 3075: 3076: Not supported. Raw SQL cannot span heterogeneous backends that may use 3077: different database engines. Calling this method will always C<croak>. 3078: 3079: Use C<selectall_arrayref> or C<fetchrow_hashref> to query the joined view. 3080: 3081: =cut 3082: 3083: sub execute { 3084: my $self = $_[0]; 3085: croak $self->_err('error_execute_unsupported'); 3086: } 3087: 3088: =head2 AUTOLOAD - column shortcut 3089: 3090: Calling an unknown method whose name matches a visible column name performs 3091: a column lookup across the merged view. 3092: 3093: =head3 SYNOPSIS 3094: 3095: # Scalar context: value from the first matching row 3096: my $name = $join->name(entry => 'C001'); 3097: 3098: # List context: values from every matching row 3099: my @tiers = $join->tier(); 3100: 3101: # With a positional join-key argument (when join_column is 'entry') 3102: my $score = $join->score('C001'); 3103: 3104: =head3 DESCRIPTION 3105: 3106: AUTOLOAD routes the call to the appropriate component database by looking up 3107: the column name in the internal column-ownership index. 3108: 3109: When either C<join_map> or C<filters> is active, AUTOLOAD performs a full 3110: join query instead of delegating directly to the owning database. This is 3111: necessary because: 3112: 3113: =over 4 3114: 3115: =item * 3116: 3117: With C<join_map>, the owning database's primary key may differ from the 3118: canonical join key used in the call arguments. 3119: 3120: =item * 3121: 3122: With C<filters>, bypassing the join would return rows that the filter is 3123: meant to exclude. 3124: 3125: =back 3126: 3127: In list context, every matching merged row contributes one value to the 3128: returned list. In scalar context, only the first row's value is returned. 3129: 3130: Calling a method whose name begins with C<_> (a private method) via AUTOLOAD 3131: will C<croak> with a clear error message rather than being silently ignored. 3132: 3133: =head3 EXAMPLE 3134: 3135: # Lookup a single customer's name (scalar context) 3136: my $name = $join->name('C001'); # 'C001' maps to entry => 'C001' 3137: print "Name: $name\n"; 3138: 3139: # Get every tier value in the view (list context) 3140: my @all_tiers = $join->tier(); 3141: my %freq; 3142: $freq{$_}++ for @all_tiers; 3143: 3144: # join_map active: AUTOLOAD runs a full join so the criteria are 3145: # translated correctly between the canonical and local key names. 3146: my @leesburg_states = sort $join->state('Leesburg'); 3147: # ['Florida', 'Virginia'] if Leesburg appears in two states 3148: 3149: =head3 PSEUDOCODE 3150: 3151: extract column name from $AUTOLOAD 3152: return if DESTROY 3153: croak if column name starts with '_' (private method guard) 3154: croak if column name is not in _col_db (unknown column) 3155: if join_map or filters are active: 3156: parse calling arguments using _parse_query_args 3157: call _joined_query to get all merged rows 3158: return map { $_->{col} } @rows in list context 3159: return $rows[0]{col} in scalar context 3160: else: 3161: delegate directly to the owning database 3162: 3163: =head3 MESSAGES 3164: 3165: (croak) Database::Join: cannot call private method '_NAME' via AUTOLOAD 3166: -- Method name begins with '_'. Private methods must be called directly, 3167: not via AUTOLOAD. This is a programming error. 3168: 3169: (croak) Database::Join: unknown column 'NAME' 3170: -- Method name does not match any visible column in the merged view. 3171: Check spelling, or whether the column was removed with remove_column(). 3172: 3173: =cut 3174: 3175: our $AUTOLOAD; 3176: 3177: sub AUTOLOAD { ●3178 → 3200 → 3212 3178: my $self = shift; 3179: 3180: 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: croak ref($self), ": cannot call private method '$col' via AUTOLOAD" 3192: if substr($col, 0, 1) eq '_'; 3193: 3194: my $db_idx = $self->{_col_db}{$col}; 3195: 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: if (%{ $self->{_join_map} } || %{ $self->{_filters} }) {

Mutants (Total: 1, Killed: 1, Survived: 0)

3201: # _autoload_pk is the autoload_pk constructor param (defaults to join_column). 3202: my $params = $self->_parse_query_args($self->{_autoload_pk}, @_); 3203: my $sort_by = delete $params->{sort_by}; 3204: my $limit = delete $params->{limit}; 3205: my $offset = delete $params->{offset}; 3206: my $rows = $self->_joined_query($params, sort_by => $sort_by, limit => $limit, offset => $offset); 3207: return map { $_->{$col} } @{$rows} if wantarray;

Mutants (Total: 2, Killed: 2, Survived: 0)

3208: return @{$rows} ? $rows->[0]{$col} : undef;

Mutants (Total: 2, Killed: 2, Survived: 0)

3209: } 3210: 3211: # $db is resolved here (not earlier) to avoid a dead store on the join path above. 3212: my $db = $self->{_dbs}[$db_idx]; 3213: return $db->$col(@_);

Mutants (Total: 2, Killed: 2, Survived: 0)

3214: } 3215: 3216: sub DESTROY { ●3217 → 3220 → 0 3217: 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: if (my $cache = delete $self->{_sqlite_cache}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

3221: local $@; 3222: 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. 3237: sub _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]);

Mutants (Total: 1, Killed: 1, Survived: 0)

3245: return get_params(undef, @args) // {};

Mutants (Total: 2, Killed: 2, Survived: 0)

3246: } 3247: 3248: # _err( $self, $msg_key, @sprintf_args ) -> $string 3249: # Convenience wrapper around _msg for use after construction, so callers do 3250: # not have to extract $self->{_i18n} at every error site. 3251: sub _err :Protected { 3252: my ($self, $key, @args) = @_; 3253: return _msg($self->{_i18n}, $key, @args);

Mutants (Total: 2, Killed: 2, Survived: 0)

3254: } 3255: 3256: # _build_col_index() 3257: # Purpose: Populate _col_db (column_name => db_index) and _db_cols 3258: # (per-db column-presence hashrefs) by calling columns() on each 3259: # component database at construction time. 3260: # Entry: _dbs, _join_col, _join_map must already be set. 3261: # Exit: _col_db and _db_cols are set; join_column verified in every db. 3262: # Effects: Croaks if any database is missing its join key column. 3263: sub _build_col_index :Protected { ●3264 → 3273 → 3324 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;

Mutants (Total: 3, Killed: 3, Survived: 0)

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) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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: } 3331: 3332: # _validate_schema_types() 3333: # Purpose: Carp when two databases share a column name (without collision_prefix) 3334: # but disagree on its type, which would cause silent type coercion. 3335: # Entry: _dbs, _col_rename, _join_map, _join_col are all populated. 3336: # Exit: Emits one carp per mismatched column; no other side effects. 3337: sub _validate_schema_types :Protected { ●3338 → 3343 → 3385 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}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

3370: my $prev = $seen{$orig_col}; 3371: if ($prev->{type} ne $type_str) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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: } 3387: 3388: # _partition_criteria( \%params ) -> \@per_db 3389: # Purpose: Split a flat criteria hashref into one slice per component database. 3390: # Entry: $params is a criteria hashref; all keys must be column names or 3391: # join_column. 3392: # Exit: Returns an arrayref of per-database criteria hashrefs. The 3393: # join_column criterion is broadcast to every database using each 3394: # database's local join-key name. Unknown columns trigger a carp. 3395: # Effects: Carps for each unrecognised column name. 3396: sub _partition_criteria :Protected { ●3397 → 3403 → 3430 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) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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;

Mutants (Total: 2, Killed: 2, Survived: 0)

3431: } 3432: 3433: # _select_rows( $db, \%criteria, \%pushdown_or_undef ) -> \@rows 3434: # Purpose: Fetch a component database's rows, asking for only the primary's 3435: # keys when key pushdown applies, and falling back to the plain 3436: # criteria if the database can't answer that. 3437: # Entry: $db is a component database; $criteria is its partitioned criteria; 3438: # $pushdown is undef, or $criteria plus { local_jc => { -in => [...] } }. 3439: # Exit: Returns an arrayref of row hashrefs (never undef). 3440: # Effects: Calls selectall_arrayref once, or twice when the pushdown query 3441: # croaks or returns a non-arrayref. 3442: # Notes: A plain function, not a :Protected method, because the parallel 3443: # path calls it inside a thread closure that deliberately doesn't 3444: # capture $self. The fallback costs only time: rows for keys outside 3445: # the primary's are never merged, so either query gives the same 3446: # result. A genuine error (e.g. a missing file) croaks again from the 3447: # fallback query, so it isn't hidden. local $@ keeps a failed 3448: # pushdown from leaking into the caller's $@. 3449: sub _select_rows { ●3450 → 3452 → 3457 3450: my ($db, $criteria, $pushdown) = @_; 3451: 3452: if ($pushdown) {

Mutants (Total: 1, Killed: 1, Survived: 0)

3453: my $rows = do { local $@; eval { $db->selectall_arrayref($pushdown) } }; 3454: return $rows if ref($rows) eq 'ARRAY';

Mutants (Total: 2, Killed: 2, Survived: 0)

3455: } 3456: 3457: return $db->selectall_arrayref($criteria) // [];

Mutants (Total: 2, Killed: 2, Survived: 0)

3458: } 3459: 3460: # _understands_in( $db ) -> $bool 3461: # Purpose: Whether a component database can be given a { -in => [...] } 3462: # criterion, i.e. whether its selectall_arrayref is 3463: # Database::Abstraction's own. 3464: # Entry: $db is a component database (any object with the DA interface). 3465: # Exit: True or false. 3466: # Effects: None. 3467: # Notes: isa('Database::Abstraction') isn't enough: a subclass that overrides 3468: # selectall_arrayref with plain equality matching would compare each 3469: # row with the hashref and silently return nothing, losing rows from a 3470: # left join. Database::Abstraction->can() is undef when the module 3471: # isn't loaded, so then nothing is pushed down. Plain function, since 3472: # it needs no object state. 3473: sub _understands_in { 3474: my $db = shift; 3475: 3476: my $da_select = Database::Abstraction->can('selectall_arrayref'); 3477: my $db_select = blessed($db) ? $db->can('selectall_arrayref') : undef; 3478: 3479: return ($da_select && $db_select && $db_select == $da_select) ? 1 : 0;

Mutants (Total: 3, Killed: 3, Survived: 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. 3502: sub _pushdown_criteria :Protected { ●3503 → 3510 → 3523 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) {

Mutants (Total: 4, Killed: 1, Survived: 3)
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;

Mutants (Total: 2, Killed: 2, Survived: 0)

3524: } 3525: 3526: # _fetch_indexed( $db_idx, \%criteria [, \%pushdown] ) -> \%join_val_to_\@rows 3527: # Purpose: Query one component database and index its rows by join-key value. 3528: # Entry: $db_idx is the zero-based database index; $criteria is the 3529: # pre-partitioned criteria hashref for this database; $pushdown is 3530: # the optional key-pushdown criteria (see _select_rows). 3531: # Exit: Returns a hashref: join-key value => arrayref of row hashrefs. 3532: # Multiple rows sharing the same join-key value are all preserved 3533: # (important for the primary database when one key maps to many rows). 3534: # Effects: Calls selectall_arrayref on the component database. 3535: sub _fetch_indexed :Protected { ●3536 → 3544 → 3550 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;

Mutants (Total: 2, Killed: 2, Survived: 0)

3551: } 3552: 3553: # _joined_query( \%params, %opts ) -> \@merged_rows 3554: # 3555: # Purpose: Dispatcher — routes to the array (in-memory) or SQLite join backend 3556: # based on $self->{_backend}. %opts are passed through to the backend 3557: # (currently: sort_by, limit, offset). 3558: sub _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';

Mutants (Total: 2, Killed: 2, Survived: 0)

3562: return $self->_sqlite_join($params, %opts);

Mutants (Total: 2, Killed: 2, Survived: 0)

3563: } 3564: 3565: # _joined_query_array( \%params ) -> \@merged_rows 3566: # 3567: # Purpose: Core in-memory join algorithm. Partitions criteria, fetches per-database 3568: # results, resolves the key set, and merges rows. 3569: # 3570: # Key-set resolution (applied for each secondary database after the primary): 3571: # 3572: # If the database had criteria in this query call (after base filter overlay), 3573: # it acts as an INNER-JOIN partner: only keys present in its filtered result 3574: # survive. This gives WHERE-clause semantics even under a LEFT join. 3575: # 3576: # If the database had NO effective criteria: 3577: # inner -> intersect (standard inner join) 3578: # left -> no change (primary defines the key set) 3579: # outer -> union (all keys from any database) 3580: # 3581: # Row merge: for each qualifying primary row, secondary rows are overlaid in 3582: # index order. For duplicate columns, later databases win. Local join-key 3583: # aliases are renamed to the canonical join_column before merging. 3584: # Removed columns are deleted from every merged row. 3585: # _validate_pagination( $limit, $offset ) -> ($validated_limit, $validated_offset) 3586: # 3587: # Purpose: Single source of truth for pagination parameter validation. 3588: # Shared by _joined_query_array (array path) and _sqlite_join (SQLite path). 3589: # Entry: $limit and $offset are raw caller values -- may be undef, negative, 3590: # non-integer, etc. 3591: # Exit: Returns the original values when valid; returns undef (with carp) when 3592: # invalid. Premise: after this call, limit ∈ ℤ+ ∪ {undef} and 3593: # offset ∈ ℤ≥0 ∪ {undef}. All downstream guards may safely rely on this. 3594: sub _validate_pagination :Protected { ●3595 → 3602 → 3611 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) {

Mutants (Total: 1, Killed: 1, Survived: 0)

3603: if ($limit !~ /^\d+\z/a || $limit < 1) {

Mutants (Total: 4, Killed: 4, Survived: 0)

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 → 3611 → 3617 3611: if (defined $offset) {

Mutants (Total: 1, Killed: 1, Survived: 0)

3612: if ($offset !~ /^\d+\z/a) {

Mutants (Total: 1, Killed: 1, Survived: 0)

3613: carp('Database::Join: offset must be a non-negative integer; ignored'); 3614: undef $offset; 3615: } 3616: } 3617: return ($limit, $offset); 3618: } 3619: 3620: sub _joined_query_array :Protected { ●3621 → 3642 → 3649 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 → 3701 → 3766 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) {

Mutants (Total: 4, Killed: 4, Survived: 0)

3702: $HAS_THREADS //= do { local $@; eval { require threads; 1 } ? 1 : 0 }; 3703: if ($HAS_THREADS) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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') {

Mutants (Total: 1, Killed: 0, Survived: 1)
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 → 3767 → 3782 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 → 3789 → 3811 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') {

Mutants (Total: 1, Killed: 1, Survived: 0)

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 → 3812 → 3822 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 → 3831 → 3845 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) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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') {

Mutants (Total: 1, Killed: 1, Survived: 0)

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}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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 → 3854 → 3909 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]) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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 → 3909 → 3916 3909: if (@{ $self->{_mandatory_filters} }) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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 → 3916 → 3928 3916: if ($distinct) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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 → 3928 → 3947 3928: if ($ob_override) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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') {

Mutants (Total: 1, Killed: 1, Survived: 0)

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 → 3947 → 3950 3947: if (defined $offset && $offset > 0) {

Mutants (Total: 4, Killed: 4, Survived: 0)

3948: splice(@result, 0, $offset); 3949: } ●3950 → 3950 → 3954 3950: if (defined $limit && $limit < scalar @result) {

Mutants (Total: 4, Killed: 4, Survived: 0)

3951: splice(@result, $limit); 3952: } 3953: 3954: return \@result;

Mutants (Total: 2, Killed: 2, Survived: 0)

3955: } 3956: 3957: # _cache_fresh() -> bool 3958: # Purpose: Check whether the SQLite join cache is still valid. 3959: # Entry: $self->{_sqlite_cache} may or may not be set. 3960: # Exit: Returns 1 if the cache exists, the DBI handle is active, the source 3961: # count matches, and all source updated() timestamps match. Returns 0 3962: # if any of these conditions fail (caller must rebuild the cache). 3963: sub _cache_fresh :Protected { ●3964 → 3978 → 3986 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;

Mutants (Total: 3, Killed: 3, Survived: 0)

3970: 3971: # Verify the DBI handle is still usable. 3972: return 0 unless do { local $@; eval { $cache->{dbh}{Active} } };

Mutants (Total: 2, Killed: 2, Survived: 0)

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;

Mutants (Total: 3, Killed: 3, Survived: 0)

3984: } 3985: 3986: return 1;

Mutants (Total: 2, Killed: 2, Survived: 0)

3987: } 3988: 3989: # _build_sqlite_cache() 3990: # Purpose: Create (or rebuild) the persistent SQLite join cache. Spills each 3991: # source database into a temp SQLite file using filter-only criteria; 3992: # SQLite-backed sources are zero-copy ATTACHed instead of spilled. 3993: # Query-time criteria are NOT applied here — they become WHERE clauses 3994: # in the per-call SQL generated by _sqlite_join. 3995: # _sql_quote_identifier( $name ) -> $quoted 3996: # Purpose: Produce a properly double-quoted SQL identifier, escaping any 3997: # embedded double-quote characters by doubling them (SQL standard). 3998: # Defence-in-depth: prevents SQL identifier injection when DA-supplied 3999: # column names or table names contain literal double-quote characters. 4000: # SQLite, like all ANSI SQL databases, represents a literal " inside a 4001: # double-quoted identifier as ""; this routine applies that transform. 4002: # Entry: $name — raw identifier string (column name, table name, or alias). 4003: # Exit: Returns the double-quoted, injection-safe SQL identifier string. 4004: sub _sql_quote_identifier { 4005: my ($name) = @_; 4006: (my $safe = $name) =~ s/"/""/g; 4007: return "\"$safe\"";

Mutants (Total: 2, Killed: 2, Survived: 0)

4008: } 4009: 4010: # Entry: _dbs, _join_map, _filters, _tmpdir must be set. 4011: # Exit: $self->{_sqlite_cache} holds {dbh, tmpfile, table_refs, source_cols, 4012: # is_attached, updated, n}. Any previous cache is disconnected first. 4013: # Each spilled table has a B-tree index on its join column. 4014: # Effects: Creates a File::Temp file (SUFFIX='.db', DIR=_tmpdir, UNLINK=1, EXLOCK=0). 4015: # Croaks with error_sqlite_connect if DBI::connect fails. 4016: sub _build_sqlite_cache :Protected { ●4017 → 4020 → 4025 4017: my ($self) = @_; 4018: 4019: # Disconnect any previous cache to release the old temp file. 4020: if (my $old = delete $self->{_sqlite_cache}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

4021: local $@; 4022: eval { $old->{dbh}->disconnect } if $old->{dbh}; 4023: } 4024: ●4025 → 4048 → 4130 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') } }) {

Mutants (Total: 1, Killed: 0, Survived: 1)
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}

Mutants (Total: 1, Killed: 1, Survived: 0)

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}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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) {

Mutants (Total: 4, Killed: 0, Survived: 4)
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 → 4131 → 4137 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: } 4149: 4150: # _sqlite_join( \%params ) -> \@merged_rows 4151: # 4152: # Purpose: Join via a persistent SQLite database cache. The first call (or 4153: # any call after a source updated() changes) spills source data into 4154: # a File::Temp SQLite file via _build_sqlite_cache; subsequent calls 4155: # reuse the same file and handle. A single SQL JOIN with a per-call 4156: # WHERE clause (built from query-time criteria) produces the result. 4157: # For 'auto' mode, uses count() or dbi_source() COUNT(*) to check 4158: # the threshold without fetching rows; falls back to 4159: # _joined_query_array when count <= $self->{_max_array_rows} or when 4160: # no count method is available. 4161: # Entry: $params is the query criteria hashref. 4162: # Exit: Returns arrayref of merged hashrefs sorted by join_column. 4163: # Effects: On the first call (or after cache invalidation), creates a 4164: # File::Temp SQLite file in _tmpdir; the file persists until the 4165: # Database::Join object is destroyed or the source data changes. 4166: sub _sqlite_join :Protected { ●4167 → 4193 → 4242 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) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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') } }) {

Mutants (Total: 1, Killed: 0, Survived: 1)
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}

Mutants (Total: 1, Killed: 1, Survived: 0)

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: if ($pkg && do { no strict 'refs'; defined &{"${pkg}::count"} }) {

Mutants (Total: 1, Killed: 1, Survived: 0)

4222: my ($cnt, $failed); 4223: do { local $@; $cnt = eval { $db->count() }; $failed = $@ }; 4224: if ($failed) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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}) {

Mutants (Total: 4, Killed: 4, Survived: 0)

4235: my $rows = $self->_joined_query_array($params, 4236: sort_by => $sort_by, limit => $limit, offset => $offset); 4237: return $count_only ? scalar @{$rows} : $rows;

Mutants (Total: 2, Killed: 2, Survived: 0)

4238: } 4239: } 4240: 4241: # Ensure the SQLite cache is valid; rebuild if stale or absent. ●4242 → 4263 → 4277 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) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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;

Mutants (Total: 2, Killed: 2, Survived: 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 → 4283 → 4302 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}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

4284: my $jc_expr; 4285: if ($join_type eq 'outer' && $n > 1) {

Mutants (Total: 4, Killed: 4, Survived: 0)

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 → 4302 → 4311 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 → 4311 → 4332 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 → 4332 → 4349 4332: if ($distinct && $columns && @{$columns}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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 → 4349 → 4367 4349: if (defined $create_table) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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 —

Mutants (Total: 1, Killed: 1, Survived: 0)

4366: # SQLite resolves ORDER BY aliases from the SELECT clause. ●4367 → 4368 → 4381 4367: my ($ob_col, $ob_dir) = ($join_col, 'ASC'); 4368: if (defined $sort_by) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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";

Mutants (Total: 1, Killed: 1, Survived: 0)

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: }

Mutants (Total: 3, Killed: 0, Survived: 3)
4380: } ●4381 → 4397 → 4413 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.

Mutants (Total: 1, Killed: 1, Survived: 0)

4395: # OFFSET without LIMIT uses LIMIT -1 (SQLite extension: "all rows from offset"). 4396: my @page_bind; 4397: if (defined $limit) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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.

Mutants (Total: 2, Killed: 2, Survived: 0)

4413: my $sth = $tmpdbh->prepare_cached($sql); 4414: $sth->execute(@bind_vals, @page_bind); 4415: return $sth->fetchall_arrayref({}); 4416: } 4417: 4418: # _sqlite_criteria( \%params ) -> ( $per_db_query, \@per_db_full, \@had_criteria ) 4419: # Purpose: Partition query-time criteria and overlay per-db filters. 4420: # Extracted from _sqlite_join so _sqlite_aggregate can reuse the same logic. 4421: sub _sqlite_criteria :Protected { ●4422 → 4435 → 4444 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)

Mutants (Total: 1, Killed: 1, Survived: 0)

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 → 4445 → 4452 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 → 4453 → 4464 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: } 4466: 4467: # _sqlite_where( $per_db_query, \@per_db_full, \@table_refs, \@is_attached ) 4468: # -> ( $where_sql, \@bind_vals ) 4469: # Purpose: Build the WHERE clause and bind-value list from per-call criteria. 4470: # Extracted from _sqlite_join for reuse by _sqlite_aggregate. 4471: sub _sqlite_where :Protected { ●4472 → 4477 → 4527 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];

Mutants (Total: 3, Killed: 0, Survived: 3)
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}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

4483: next if defined $local_jc_i && $col eq $local_jc_i; 4484: my $val = $crit->{$col};

Mutants (Total: 1, Killed: 1, Survived: 0)

4485: if (ref($val) eq 'HASH') { 4486: for my $op (sort keys %{$val}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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;

Mutants (Total: 1, Killed: 1, Survived: 0)

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;

Mutants (Total: 1, Killed: 1, Survived: 0)

4502: next; 4503: } 4504: if ($SAFE_NOARG_OPS{$op}) { 4505: push @where_parts, 4506: $tref . '.' . _sql_quote_identifier($col) . " $op";

Mutants (Total: 1, Killed: 1, Survived: 0)

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: } 4530: 4531: # _sqlite_join_clause( \@table_refs, \@had_criteria, $local_jc_0 ) -> $join_sql 4532: # Purpose: Build the JOIN … ON … clause string. 4533: # Extracted from _sqlite_join for reuse by _sqlite_aggregate. 4534: sub _sqlite_join_clause :Protected { ●4535 → 4541 → 4550 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)

Mutants (Total: 2, Killed: 2, Survived: 0)

4548: . ' = ' . $table_refs->[$i] . '.' . _sql_quote_identifier($local_jc); 4549: } 4550: return $join_sql; 4551: } 4552: 4553: # _validate_having( \%having, \%valid_keys ) 4554: # Purpose: Recursively validate a having hashref; croak on unknown keys or operators. 4555: # Entry: $having is the caller's having hashref; $valid_keys maps allowed keys to 1. 4556: # Effects: Croaks on first violation; returns normally when the spec is clean. 4557: sub _validate_having :Protected {

Mutants (Total: 1, Killed: 1, Survived: 0)

●4558 → 4559 → 0 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)

Mutants (Total: 1, Killed: 1, Survived: 0)

4570: unless exists $valid_keys->{$key}; 4571: my $val = $having->{$key};

Mutants (Total: 1, Killed: 1, Survived: 0)

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: } 4581: 4582: # _validate_aggregate_spec( \%params ) -> \%spec 4583: # Purpose: Extract and validate aggregate-specific keys from %params, leaving 4584: # criteria keys in place for _partition_criteria to route. 4585: # Entry: $params is the raw caller hashref (mutated: aggregate keys deleted). 4586: # Exit: Returns a spec hashref: 4587: # by => [ { name, owner, db_col }, ... ] 4588: # measures => [ { fn, col, as, owner, db_col, is_numeric }, ... ] 4589: # aliases => { alias => 1, ... } 4590: # having => \%having or undef 4591: # sort => [ col, dir ] or undef 4592: # limit => positive int or undef 4593: # offset => non-neg int or undef 4594: sub _validate_aggregate_spec :Protected { ●4595 → 4615 → 4637 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;

Mutants (Total: 4, Killed: 1, Survived: 3)
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.

Mutants (Total: 1, Killed: 1, Survived: 0)

4623: if ($col ne $join_col && index($col, '.') < 0) {

Mutants (Total: 1, Killed: 1, Survived: 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 → 4643 → 4699 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:

Mutants (Total: 1, Killed: 1, Survived: 0)

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};

Mutants (Total: 4, Killed: 4, Survived: 0)

4655: croak $self->_err('error_aggregate_col_unknown', $col) 4656: unless defined $col_owner;

Mutants (Total: 1, Killed: 1, Survived: 0)

4657: if ($col ne $join_col && index($col, '.') < 0) {

Mutants (Total: 1, Killed: 1, Survived: 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:

Mutants (Total: 1, Killed: 1, Survived: 0)

4698: # having: validate keys and operators recursively. ●4699 → 4700 → 4705 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:

Mutants (Total: 1, Killed: 1, Survived: 0)

4704: # sort_by: name must be a by-column or measure alias; direction ASC/DESC. ●4705 → 4706 → 4725 4705: my ($sort_col, $sort_dir) = (undef, 'ASC');

Mutants (Total: 1, Killed: 1, Survived: 0)

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');

Mutants (Total: 1, Killed: 1, Survived: 0)

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";

Mutants (Total: 1, Killed: 1, Survived: 0)

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: } 4735: 4736: # _normalise_aggregate( \@rows, \@measures ) 4737: # Purpose: Apply empty-set normalisation to fetched/folded group rows. 4738: # sum/count/count_distinct: NULL → 0 4739: # avg/min/max: NULL stays undef 4740: # Called on both SQLite and array paths so they cannot drift. 4741: sub _normalise_aggregate :Protected { ●4742 → 4743 → 0 4742: my ($self, $rows, $measures) = @_; 4743: for my $row (@{$rows}) { 4744: for my $m (@{$measures}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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: } 4753: 4754: # _match_having_criterion( $value, $criterion, $key ) -> bool 4755: # Purpose: Evaluate one leaf HAVING condition on the Perl array path. 4756: # Implements three-valued logic: a NULL (undef) lhs satisfies only IS NULL. 4757: sub _match_having_criterion :Protected { ●4758 → 4763 → 4776 4758: my ($self, $value, $criterion, $key) = @_; 4759: 4760: # Empty-list short-circuits precede three-valued logic:

Mutants (Total: 1, Killed: 1, Survived: 0)

4761: # NOT IN () → always true (vacuously nothing to exclude, including NULL).

Mutants (Total: 1, Killed: 1, Survived: 0)

4762: # IN () → always false. 4763: if (ref($criterion) eq 'HASH') { 4764: if (exists $criterion->{'NOT IN'}

Mutants (Total: 2, Killed: 2, Survived: 0)

4765: && ref($criterion->{'NOT IN'}) eq 'ARRAY' 4766: && !@{ $criterion->{'NOT IN'} }) {

Mutants (Total: 1, Killed: 1, Survived: 0)

4767: return 1; 4768: } 4769: if (exists $criterion->{'IN'}

Mutants (Total: 2, Killed: 2, Survived: 0)

4770: && ref($criterion->{'IN'}) eq 'ARRAY' 4771: && !@{ $criterion->{'IN'} }) { 4772: return 0; 4773: }

Mutants (Total: 1, Killed: 1, Survived: 0)

4774: } 4775:

Mutants (Total: 2, Killed: 2, Survived: 0)

●4776 → 4776 → 4781 4776: if (!defined $value) {

Mutants (Total: 2, Killed: 2, Survived: 0)

4777: # NULL satisfies: (1) bare undef criterion (IS NULL shorthand), or (2) IS NULL. 4778: return 1 unless defined $criterion;

Mutants (Total: 1, Killed: 1, Survived: 0)

4779: return (ref($criterion) eq 'HASH' && exists $criterion->{'IS NULL'}) ? 1 : 0; 4780: }

Mutants (Total: 2, Killed: 2, Survived: 0)

●4781 → 4781 → 4785 4781: if (!defined $criterion) { 4782: # bare undef means IS NULL; value is defined → false

Mutants (Total: 1, Killed: 1, Survived: 0)

4783: return 0; 4784: } ●4785 → 4785 → 4828 4785: if (ref($criterion) eq 'HASH') {

Mutants (Total: 1, Killed: 1, Survived: 0)

4786: for my $op (keys %{$criterion}) {

Mutants (Total: 2, Killed: 0, Survived: 2)
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

Mutants (Total: 1, Killed: 1, Survived: 0)

4791: } elsif ($SAFE_LIST_OPS{$op}) {

Mutants (Total: 2, Killed: 0, Survived: 2)
4792: my @items = ref($rhs) eq 'ARRAY' ? @{$rhs} : (); 4793: if ($op eq 'IN') {
Mutants (Total: 2, Killed: 0, Survived: 2)
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}) {
Mutants (Total: 2, Killed: 1, Survived: 1)
4799: my $num = looks_like_number($value) && looks_like_number($rhs);
Mutants (Total: 1, Killed: 0, Survived: 1)
4800: my $ok;

Mutants (Total: 3, Killed: 3, Survived: 0)

4801: if ($op eq '=') { $ok = $num ? $value == $rhs : $value eq $rhs }

Mutants (Total: 3, Killed: 0, Survived: 3)
4802: elsif ($op eq '!=') { $ok = $num ? $value != $rhs : $value ne $rhs }
Mutants (Total: 3, Killed: 0, Survived: 3)
4803: elsif ($op eq '>') { $ok = $num ? $value > $rhs : $value gt $rhs }
Mutants (Total: 3, Killed: 0, Survived: 3)
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 {

Mutants (Total: 2, Killed: 2, Survived: 0)

4818: $ok = 0; 4819: } 4820: return 0 unless $ok; 4821: } else { 4822: croak $self->_err('error_aggregate_having_operator', $op, $key);

Mutants (Total: 2, Killed: 2, Survived: 0)

4823: } 4824: } 4825: return 1;

Mutants (Total: 2, Killed: 2, Survived: 0)

4826: }

Mutants (Total: 1, Killed: 0, Survived: 1)
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: } 4832: 4833: # _match_criteria( $row, \%criteria ) -> bool 4834: # Purpose: Evaluate a HAVING criteria hashref against a folded group row. 4835: # Supports -or / -and groupings recursively; delegates leaves to 4836: # _match_having_criterion. Used by the array path's aggregate() only. 4837: sub _match_criteria :Protected {

Mutants (Total: 1, Killed: 1, Survived: 0)

●4838 → 4839 → 4855 4838: my ($self, $row, $criteria) = @_; 4839: for my $key (keys %{$criteria}) { 4840: if ($key eq '-or') {

Mutants (Total: 1, Killed: 1, Survived: 0)

4841: my $any = 0; 4842: for my $sub (@{ $criteria->{$key} }) {

Mutants (Total: 2, Killed: 2, Survived: 0)

4843: if ($self->_match_criteria($row, $sub)) { $any = 1; last } 4844: } 4845: return 0 unless $any;

Mutants (Total: 2, Killed: 2, Survived: 0)

4846: } elsif ($key eq '-and') { 4847: for my $sub (@{ $criteria->{$key} }) { 4848: return 0 unless $self->_match_criteria($row, $sub); 4849: }

Mutants (Total: 2, Killed: 2, Survived: 0)

4850: } else { 4851: my $val = exists $row->{$key} ? $row->{$key} : undef; 4852: return 0 unless $self->_match_having_criterion($val, $criteria->{$key}, $key);

Mutants (Total: 2, Killed: 2, Survived: 0)

4853: } 4854: } 4855: return 1; 4856: } 4857: 4858: # _fold_aggregate( \@merged_rows, \%spec ) -> \@groups 4859: # Purpose: Group merged rows and compute aggregate measures in Perl. 4860: # Used by the array backend path of aggregate(). 4861: sub _fold_aggregate :Protected { ●4862 → 4886 → 4946 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: }

Mutants (Total: 1, Killed: 0, Survived: 1)
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 }

Mutants (Total: 2, Killed: 2, Survived: 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)

Mutants (Total: 1, Killed: 1, Survived: 0)

4896: : undef;

Mutants (Total: 1, Killed: 1, Survived: 0)

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;

Mutants (Total: 1, Killed: 1, Survived: 0)

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;

Mutants (Total: 1, Killed: 1, Survived: 0)

4912: } 4913: } elsif ($fn eq 'min') {

Mutants (Total: 1, Killed: 1, Survived: 0)

4914: if (defined $val) { 4915: my $cur = $g->{"${as}__val"}; 4916: if (!defined $cur) { 4917: $g->{"${as}__val"} = $val;

Mutants (Total: 3, Killed: 3, Survived: 0)

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: }

Mutants (Total: 1, Killed: 1, Survived: 0)

4922: } 4923: } elsif ($fn eq 'max') {

Mutants (Total: 1, Killed: 1, Survived: 0)

4924: if (defined $val) { 4925: my $cur = $g->{"${as}__val"}; 4926: if (!defined $cur) { 4927: $g->{"${as}__val"} = $val;

Mutants (Total: 3, Killed: 3, Survived: 0)

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: }

Mutants (Total: 1, Killed: 1, Survived: 0)

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: }

Mutants (Total: 1, Killed: 1, Survived: 0)

4944: 4945: # Grand total with no rows and no by: synthesise one zeroed row. ●4946 → 4946 → 4952 4946: if (!@by && !@order) { 4947: push @order, ''; 4948: $groups{''} = $new_group->({}); 4949: } 4950: 4951: # Finalise accumulators into result rows. ●4952 → 4953 → 4985 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} } }

Mutants (Total: 1, Killed: 1, Survived: 0)

4957: for my $m (@measures) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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: }

Mutants (Total: 1, Killed: 0, Survived: 1)
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: }

Mutants (Total: 2, Killed: 2, Survived: 0)

4983: push @result, \%row; 4984: } 4985: return \@result; 4986: } 4987: 4988: # _sort_and_page( \@rows, \%spec ) 4989: # Purpose: Sort and splice the array-path aggregate result in place. 4990: # Order of operations: sort → offset → limit (matching GROUP BY semantics). 4991: sub _sort_and_page :Protected { ●4992 → 4998 → 5031 4992: my ($self, $rows, $spec) = @_; 4993: my $sort = $spec->{sort}; 4994: my $limit = $spec->{limit}; 4995: my $offset = $spec->{offset};

Mutants (Total: 1, Killed: 1, Survived: 0)

4996: my @by = @{ $spec->{by} }; 4997: 4998: if (defined $sort) { 4999: my ($sc, $sd) = @{$sort}; 5000: @{$rows} = sort {

Mutants (Total: 1, Killed: 0, Survived: 1)
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) {
Mutants (Total: 1, Killed: 0, Survived: 1)
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};

Mutants (Total: 3, Killed: 3, Survived: 0)

5029: }

Mutants (Total: 3, Killed: 3, Survived: 0)

5030: 5031: splice(@{$rows}, 0, $offset) if defined $offset && $offset > 0; 5032: splice(@{$rows}, $limit) if defined $limit && $limit < scalar @{$rows}; 5033: } 5034: 5035: # _having_to_sql( \%having, \%have_map ) -> ( $sql_fragment, \@binds ) 5036: # Purpose: Recursively convert a having hashref to a SQL fragment with bind values. 5037: # $have_map maps every valid key to { expr => SQL_expr, is_agg => bool }. 5038: # is_agg => 1 means the expression is an aggregate function → CAST(? AS REAL) 5039: # is_agg => 0 means it is a group-by column expression → plain ? 5040: # Supports -or / -and recursion; delegates leaves to the same three operator tables 5041: # as _sqlite_where (_sqlite_join's WHERE builder), for vocabulary consistency. 5042: sub _having_to_sql :Protected { ●5043 → 5046 → 5109 5043: my ($self, $having, $have_map) = @_; 5044: my (@parts, @binds);

Mutants (Total: 1, Killed: 1, Survived: 0)

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;

Mutants (Total: 1, Killed: 1, Survived: 0)

5052: push @sb, @{$b}; 5053: } 5054: if (@sp) { 5055: push @parts, '(' . join(' OR ', @sp) . ')'; 5056: push @binds, @sb; 5057: }

Mutants (Total: 1, Killed: 1, Survived: 0)

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;

Mutants (Total: 1, Killed: 1, Survived: 0)

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;

Mutants (Total: 1, Killed: 1, Survived: 0)

5077: my $val = $having->{$key}; 5078: 5079: if (!defined $val) { 5080: push @parts, "$expr IS NULL";

Mutants (Total: 1, Killed: 1, Survived: 0)

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}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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: } 5111: 5112: # _sqlite_aggregate( \%params, \%spec ) -> \@group_rows 5113: # Purpose: Execute an aggregate query against the SQLite spill cache. 5114: # Builds SELECT … GROUP BY … HAVING … ORDER BY … SQL from the spec returned 5115: # by _validate_aggregate_spec, reusing the three extracted _sqlite_* builders 5116: # so criteria semantics stay identical to _sqlite_join. 5117: sub _sqlite_aggregate :Protected { ●5118 → 5143 → 5170 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} }) {

Mutants (Total: 1, Killed: 1, Survived: 0)

5144: my ($bname, $owner, $db_col) = @{$b}{qw(name owner db_col)};

Mutants (Total: 4, Killed: 0, Survived: 4)
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 → 5171 → 5195 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;

Mutants (Total: 1, Killed: 1, Survived: 0)

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 → 5201 → 5210 5195: my $groupby_sql = @by_exprs 5196: ? ' GROUP BY ' . join(', ', @by_exprs) 5197: : ''; 5198:

Mutants (Total: 1, Killed: 1, Survived: 0)

5199: # HAVING clause. 5200: my ($having_sql, $having_binds) = ('', []);

Mutants (Total: 1, Killed: 1, Survived: 0)

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:

Mutants (Total: 1, Killed: 1, Survived: 0)

5209: # ORDER BY: default = by expressions ascending; override via spec->{sort}. ●5210 → 5211 → 5222 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 → 5232 → 5241 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:

Mutants (Total: 1, Killed: 1, Survived: 0)

5230: my @page_bind; 5231: my ($limit, $offset) = ($spec->{limit}, $spec->{offset}); 5232: if (defined $limit) {

Mutants (Total: 1, Killed: 1, Survived: 0)

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 → 5248 → 5254 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});

Mutants (Total: 1, Killed: 1, Survived: 0)

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];

Mutants (Total: 2, Killed: 2, Survived: 0)

5252: } 5253: 5254: return $rows; 5255: } 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.

Mutants (Total: 2, Killed: 2, Survived: 0)

5263: sub _mandatory_op_to_crit { 5264: my ($op, $val) = @_; 5265: return $val if $op eq 'eq'; 5266: return { '!=' => $val } if $op eq 'ne'; 5267: return { '<' => $val } if $op eq 'lt'; 5268: return { '<=' => $val } if $op eq 'lte'; 5269: return { '>' => $val } if $op eq 'gt'; 5270: return { '>=' => $val } if $op eq 'gte';

Mutants (Total: 2, Killed: 0, Survived: 2)
5271: return { LIKE => $val } if $op eq 'like'; 5272: return { LIKE => "%$val%" } if $op eq 'contains'; 5273: return $val; # unreachable: validated at construction 5274: } 5275: 5276: # _pass_mandatory_filters( \%row, \@filters ) -> bool 5277: # Purpose: Test a single merged row against all mandatory_filter predicates. 5278: # Entry: $row is a merged row hashref; $filters is the _mandatory_filters arrayref. 5279: # Exit: Returns 1 if ALL predicates pass, 0 if any fails. 5280: # Perl-side evaluation mirrors the SQL semantics produced by _mandatory_op_to_crit. 5281: sub _pass_mandatory_filters { ●5282 → 5283 → 5299 5282: my ($row, $filters) = @_; 5283: for my $pred (@{$filters}) {
Mutants (Total: 2, Killed: 0, Survived: 2)
5284: my ($col, $op, $val) = @{$pred}{qw(col op val)};

Mutants (Total: 3, Killed: 3, Survived: 0)

5285: my $rv = $row->{$col};

Mutants (Total: 2, Killed: 2, Survived: 0)

5286: return 0 unless defined $rv;

Mutants (Total: 2, Killed: 0, Survived: 2)
5287: if ($op eq 'eq') { return 0 unless $rv eq $val }
Mutants (Total: 2, Killed: 0, Survived: 2)
5288: elsif ($op eq 'ne') { return 0 unless $rv ne $val }

Mutants (Total: 2, Killed: 2, Survived: 0)

5289: elsif ($op eq 'lt') { return 0 unless $rv lt $val }

Mutants (Total: 2, Killed: 0, Survived: 2)
5290: elsif ($op eq 'lte') { return 0 unless $rv le $val }
Mutants (Total: 5, Killed: 2, Survived: 3)
5291: elsif ($op eq 'gt') { return 0 unless $rv gt $val } 5292: elsif ($op eq 'gte') { return 0 unless $rv ge $val } 5293: elsif ($op eq 'contains') { return 0 unless index($rv, $val) >= 0 }

Mutants (Total: 2, Killed: 2, Survived: 0)

5294: elsif ($op eq 'like') { 5295: # _re was pre-compiled at construction time; no per-row regex build. 5296: return 0 unless $rv =~ $pred->{_re};

Mutants (Total: 2, Killed: 2, Survived: 0)

5297: } 5298: } 5299: return 1; 5300: } 5301: 5302: # _apply_distinct_array( \@rows, \@columns ) -> \@deduped_rows 5303: # Purpose: Deduplicate an array of merged row hashrefs. 5304: # Entry: $rows is the full merged result arrayref (already sorted when called 5305: # from _joined_query_array — distinct is applied before sort, but 5306: # that is fine since dedup preserves relative order). 5307: # $columns: when provided, project each row to only those columns and 5308: # deduplicate on their combined value; when absent, deduplicate on all 5309: # columns (full-row equality). 5310: # Exit: Returns a new arrayref; first occurrence of each distinct key wins. 5311: sub _apply_distinct_array { ●5312 → 5315 → 5332 5312: my ($rows, $columns) = @_;

Mutants (Total: 1, Killed: 1, Survived: 0)

5313: my %seen; 5314: my @result; 5315: if ($columns && @{$columns}) { 5316: my @cols = @{$columns}; 5317: for my $row (@{$rows}) { 5318: my $key = join("\0", map { $row->{$_} // '' } @cols); 5319: next if $seen{$key}++; 5320: 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: my @col_order = @{$rows} ? sort keys %{ $rows->[0] } : (); 5326: for my $row (@{$rows}) { 5327: my $key = join("\0", map { ($row->{$_} // '') } @col_order); 5328: next if $seen{$key}++; 5329: push @result, $row;

Mutants (Total: 2, Killed: 2, Survived: 0)

5330: } 5331: } 5332: return \@result; 5333: } 5334: 5335: # _merge_criteria( \%base, \%extra ) -> \%merged 5336: # Purpose: Merge two criteria hashrefs for the same database column set. 5337: # Entry: %base is the permanent filter; %extra is the query-time criteria. 5338: # Exit: Returns a new hashref with both applied. 5339: # Merging rule: when both values for the same column are operator hashrefs 5340: # (e.g. { '>' => 60 } and { '<' => 365 }), the operators are combined 5341: # so both constraints apply simultaneously (AND semantics). 5342: # Otherwise the extra (query-time) value overwrites the base value. 5343: sub _merge_criteria :Protected { ●5344 → 5346 → 5355 5344: my ($base, $extra) = @_;

Mutants (Total: 1, Killed: 1, Survived: 0)

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};

Mutants (Total: 2, Killed: 2, Survived: 0)

5353: } 5354: } 5355: return \%merged; 5356: } 5357: 5358: # _copy_criteria( \%criteria ) -> \%copy 5359: # Purpose: Return a two-level deep copy of a single criteria hashref so that 5360: # post-construction mutation of the caller's hash cannot change the 5361: # stored filter. Operator sub-hashrefs (e.g. { '>' => 80 }) are 5362: # shallow-copied one additional level, matching the broadcast-copy 5363: # idiom used in _partition_criteria for join-column criteria. 5364: # Entry: $criteria is a hashref (may be undef). 5365: # Exit: Returns a new hashref; never returns the input reference itself. 5366: sub _copy_criteria { 5367: my ($criteria) = @_; 5368: return {} unless $criteria && %{$criteria}; 5369: return { 5370: map { 5371: $_ => ref($criteria->{$_}) eq 'HASH' 5372: ? { %{ $criteria->{$_} } } # shallow-copy operator sub-hashref 5373: : $criteria->{$_} 5374: } keys %{$criteria} 5375: }; 5376: } 5377: 5378: # _copy_filters( \%filters ) -> \%copy 5379: # Purpose: Deep-copy the filters hashref (db_index => criteria_hashref) so 5380: # that post-construction mutation of the caller's hash cannot silently 5381: # bypass the inner-join row-security guarantee. 5382: # Entry: $filters may be undef. 5383: # Exit: Returns a new hashref; never returns the input reference itself. 5384: sub _copy_filters { 5385: my ($filters) = @_; 5386: return {} unless $filters && %{$filters}; 5387: return { map { $_ => _copy_criteria($filters->{$_}) } keys %{$filters} }; 5388: } 5389: 5390: # _msg( $i18n, $key, @sprintf_args ) -> $string 5391: # Purpose: Format a user-facing message, routing through the i18n object when 5392: # one is provided. Falls back to the built-in %MESSAGES dictionary. 5393: # Entry: $i18n may be undef. $key must be a key in %MESSAGES. 5394: # Exit: Returns the formatted string. 5395: sub _msg :Protected {

Mutants (Total: 1, Killed: 1, Survived: 0)

●5396 → 5398 → 5402 5396: my ($i18n, $key, @args) = @_;

Mutants (Total: 2, Killed: 2, Survived: 0)

5397: 5398: if ($i18n && $i18n->can('translate')) { 5399: return $i18n->translate($key, @args); 5400: } 5401: 5402: my $fmt = $MESSAGES{$key}

Mutants (Total: 2, Killed: 2, Survived: 0)

5403: // sprintf($MESSAGES{error_unknown_message}, $key); 5404: 5405: return @args ? sprintf($fmt, @args) : $fmt; 5406: } 5407: 5408: 1; 5409: 5410: __END__ 5411: 5412: =head1 ENCODING 5413: 5414: C<Database::Join> is a routing and merge layer written in pure Perl. It never 5415: inspects, re-encodes, or transforms the I<content> of strings -- only their 5416: identity (via C<eq> / hash-key equality) and, on the array backend, their 5417: numeric interpretation (via C<looks_like_number>). 5418: 5419: =over 4 5420: 5421: =item Column names 5422: 5423: Column names are exactly what each component C<Database::Abstraction> object 5424: returns from its own C<columns()> method. C<Database::Join> compares them with 5425: C<eq> (byte-level equality) and builds its internal routing index from them. 5426: ASCII column names (letters, digits, underscore) are safe everywhere. 5427: Non-ASCII column names work as long as every component database returns them 5428: in the same byte encoding and your Perl source file is loaded in the same 5429: encoding. Mixed encodings between component databases are not supported. 5430: 5431: =item Join-key values (the join_column) 5432: 5433: The join-column value is used as a hash key internally (C<$hash{$key}>). 5434: Perl uses byte-level equality for hash keys, so any value that round-trips 5435: correctly through your component databases works as a join key, including 5436: non-ASCII strings, emoji, and other Unicode text, as long as all component 5437: databases return the same bytes for the same conceptual key. 5438: 5439: # A Japanese city name as a join key works fine 5440: my $rows = $join->selectall_arrayref(entry => "\x{6771}\x{4EAC}"); 5441: 5442: =item Criteria values and row data 5443: 5444: Criterion values and merged row values are passed verbatim between the caller 5445: and the component databases. C<Database::Join> does not examine them. Full 5446: UTF-8 text (including multi-byte characters, accented letters, CJK ideographs, 5447: and emoji) round-trips safely provided the underlying component databases handle 5448: UTF-8 correctly. 5449: 5450: # Emoji in a criterion value -- works if the DA supports it 5451: my $rows = $join->selectall_arrayref(mood => "\x{1F600}"); 5452: 5453: =item SQLite backend: UTF-8 round-trip guarantee 5454: 5455: When the SQLite path is active (C<backend =E<gt> 'sqlite'> or C<'auto'>), 5456: values are inserted into the temporary C<DBD::SQLite> database exclusively 5457: through DBI prepared-statement placeholders -- never by string interpolation. 5458: C<DBD::SQLite> operates in UTF-8 mode by default (C<sqlite_unicode =E<gt> 1> 5459: in newer releases), so multi-byte UTF-8 text round-trips without corruption. 5460: Binary blobs containing null bytes may not round-trip correctly; use the array 5461: backend if you need binary-safe joins. 5462: 5463: =item Sorting on the array backend uses Perl string comparison 5464: 5465: The array backend sorts with Perl's C<cmp> (byte-level lexicographic order). 5466: This is correct for pure-ASCII data and for consistently-encoded UTF-8 data 5467: where byte order matches Unicode code-point order (e.g. sorting within a 5468: single script). For locale-aware sorting (e.g. sorting German umlauts in 5469: German alphabetical order) switch to the SQLite backend, which delegates to 5470: SQLite's C<ORDER BY> (locale support depends on how SQLite was compiled). 5471: 5472: =item Measure aliases in aggregate() 5473: 5474: The C<as> alias for each measure must match C</^\w+\z/a> -- ASCII word 5475: characters only (letters, digits, underscore). Full Unicode identifiers 5476: are not supported as aliases. 5477: 5478: =item i18n messages 5479: 5480: All internal error and warning messages route through the optional C<i18n> 5481: object via a C<translate($key, @args)> call. The translation dictionary 5482: controls the final encoding and character set of those user-visible strings. 5483: 5484: =back 5485: 5486: =head1 MESSAGES 5487: 5488: The following messages can be produced by C<Database::Join>. All messages 5489: can be localised by supplying an C<i18n> object to C<new>. 5490: 5491: =over 4 5492: 5493: =item C<error_no_databases> 5494: 5495: B<When:> The C<databases> arrayref passed to C<new> is empty. 5496: 5497: B<Fix:> Pass at least one C<Database::Abstraction> subclass object. 5498: 5499: =item C<error_invalid_db> 5500: 5501: B<When:> An element of the C<databases> array (or the argument to 5502: C<add_database>) is not an object, or is not a C<Database::Abstraction> 5503: subclass. 5504: 5505: B<Fix:> Instantiate the component database with its own C<new> method before 5506: passing it to C<Database::Join>. 5507: 5508: =item C<error_join_col_missing> 5509: 5510: B<When:> The join key column (or its C<join_map> alias) does not exist in one 5511: of the component databases. 5512: 5513: B<Fix:> Either add the column to the database, change C<join_column> to a 5514: column that is present everywhere, or use C<join_map> to declare the local 5515: alias for databases that call it something different. 5516: 5517: =item C<error_remove_join_col> 5518: 5519: B<When:> C<remove_column> is called with the name of the join key column. 5520: 5521: B<Fix:> The join key is required for the merge to work and cannot be hidden. 5522: Remove a different column. 5523: 5524: =item C<error_invalid_prefix> 5525: 5526: B<When:> A value in the C<collision_prefix> hashref is a reference (e.g. a 5527: hashref or arrayref) rather than a plain string. 5528: 5529: B<Fix:> All C<collision_prefix> values must be plain strings. A reference 5530: would be stringified to C<HASH(0x...)> or C<ARRAY(0x...)>, leaking a heap 5531: address into every column name returned by C<columns()>, C<schema()>, and all 5532: query results. Pass a plain string such as C<'db2'> or C<'secondary'>. 5533: 5534: =item C<warn_unknown_column> (carp) 5535: 5536: B<When:> A criterion is passed for a column that does not exist in any 5537: component database (or has been removed with C<remove_column>). 5538: 5539: B<Fix:> Check the column name spelling. The criterion is ignored. 5540: 5541: =item C<error_join_criterion> 5542: 5543: B<When:> A criterion hashref contains a C<join =E<gt>> key (the 5544: C<Database::Abstraction> SQL-JOIN syntax). 5545: 5546: B<Fix:> C<join =E<gt>> targets a single table inside one DA; it cannot be 5547: routed through a merged view. Express multi-table relationships by adding 5548: the joined table as a separate C<Database::Abstraction> object in the 5549: C<databases =E<gt> []> constructor list instead. 5550: 5551: =item C<error_query_unsupported> 5552: 5553: B<When:> C<query()> is called on a C<Database::Join> object. 5554: 5555: B<Fix:> Use C<selectall_arrayref>, C<selectall_array>, C<fetchrow_hashref>, 5556: or C<count> instead. 5557: 5558: =item C<error_group_by_unsupported> 5559: 5560: B<When:> C<group_by()> is called on a C<Database::Join> object. 5561: 5562: B<Fix:> Use C<aggregate()> instead. The fluent C<Database::Abstraction::Query> 5563: chain targets a single component DA, not the merged view. 5564: 5565: =item C<error_execute_unsupported> 5566: 5567: B<When:> C<execute()> is called on a C<Database::Join> object. 5568: 5569: B<Fix:> Use the Perl-level query methods instead. Raw SQL cannot span 5570: heterogeneous database backends. 5571: 5572: =item C<error_invalid_backend> 5573: 5574: B<When:> The C<backend> parameter passed to C<new> is not one of C<'array'>, 5575: C<'sqlite'>, or C<'auto'>. 5576: 5577: B<Fix:> Use exactly one of those three strings. The check is case-sensitive; 5578: C<'SQLite'> or C<'Auto'> will not be accepted. 5579: 5580: =item C<error_sqlite_connect> 5581: 5582: B<When:> The SQLite join backend fails to open the temporary SQLite database 5583: file. Common causes: the C<tmpdir> directory is not writable, the filesystem 5584: has no free space, or C<DBD::SQLite> is not installed. 5585: 5586: B<Fix:> Check that the directory given by C<tmpdir> (or the system temp 5587: directory if C<tmpdir> was not set) is writable and has sufficient free space. 5588: Verify that C<DBD::SQLite> 1.70 or later is installed. 5589: 5590: =item C<error_aggregate_measures_required> 5591: 5592: B<When:> C<aggregate()> is called without a C<measures> key, or with 5593: C<measures => []>. 5594: 5595: B<Fix:> Pass a non-empty arrayref: C<< measures => [{ fn => 'count', as => 'n' }] >>. 5596: 5597: =item C<error_aggregate_measure_ref> 5598: 5599: B<When:> One of the elements in the C<measures> arrayref is not a hashref (it 5600: is a scalar, arrayref, or other non-hash reference). 5601: 5602: B<Fix:> Every element of C<measures> must be a plain hashref with at least 5603: C<fn> and C<as> keys. 5604: 5605: =item C<error_aggregate_fn_unknown> 5606: 5607: B<When:> The C<fn> value in a measure hashref is not one of: C<sum>, C<avg>, 5608: C<min>, C<max>, C<count>, C<count_distinct> (case-insensitive). 5609: 5610: B<Fix:> Use a supported function name. C<median>, C<stddev> and window 5611: functions are not implemented. 5612: 5613: =item C<error_aggregate_col_required> 5614: 5615: B<When:> The C<col> field is missing from a measure whose C<fn> requires a 5616: column (any function except plain C<count>). 5617: 5618: B<Fix:> Add C<< col => 'column_name' >> to the measure hashref. C<count> 5619: without C<col> emits C<COUNT(*)>; all other functions require a column. 5620: 5621: =item C<error_aggregate_col_unknown> 5622: 5623: B<When:> The C<col> in a measure, or a name in C<by>, refers to a column that 5624: is not in the merged view (either never existed or was hidden with 5625: C<remove_column>). 5626: 5627: B<Fix:> Check C<< $join->columns() >> for the correct published name. 5628: C<collision_prefix>-renamed columns are accessed as C<"prefix.col">. 5629: 5630: =item C<error_aggregate_as_required> 5631: 5632: B<When:> A measure hashref has no C<as> key, or its value is C<undef> or the 5633: empty string. 5634: 5635: B<Fix:> Every measure must have a non-empty C<as> alias: C<< as => 'total' >>. 5636: 5637: =item C<error_aggregate_as_invalid> 5638: 5639: B<When:> A measure alias (C<as>) contains characters other than word 5640: characters (C<\w>: letters, digits, underscore). 5641: 5642: B<Fix:> Use a plain word for the alias: C<< as => 'total' >>, not 5643: C<< as => 'total score' >> or C<< as => 'total-score' >>. 5644: 5645: =item C<error_aggregate_as_duplicate> 5646: 5647: B<When:> Two or more measures share the same C<as> alias. 5648: 5649: B<Fix:> Choose a unique alias for each measure. 5650: 5651: =item C<error_aggregate_as_collision> 5652: 5653: B<When:> A measure's C<as> alias is the same as one of the C<by> column names. 5654: 5655: B<Fix:> Choose an alias that does not match any grouping dimension. 5656: 5657: =item C<error_aggregate_by_invalid> 5658: 5659: B<When:> The C<by> parameter is present but is not an arrayref. 5660: 5661: B<Fix:> Pass an arrayref (possibly empty for a grand total): 5662: C<< by => ['region'] >> or C<< by => [] >>. 5663: 5664: =item C<error_aggregate_having_key> 5665: 5666: B<When:> A key in the C<having> hashref is not one of the C<by> column names, 5667: a measure alias, C<-or>, or C<-and>. 5668: 5669: B<Fix:> Only filter on names that appear in the aggregate output. 5670: 5671: =item C<error_aggregate_having_operator> 5672: 5673: B<When:> An operator hashref inside C<having> uses an operator that is not in 5674: C<%SAFE_SQL_OPS>, C<%SAFE_LIST_OPS>, or C<%SAFE_NOARG_OPS>. 5675: 5676: B<Fix:> Use a supported operator. C<BETWEEN> is not supported; write it as 5677: two constraints: C<< { '>=' => $lo, '<=' => $hi } >>. 5678: 5679: =item C<warn_aggregate_sort_key> (carp) 5680: 5681: B<When:> The column or alias named by C<sort_by> in C<aggregate()> is not one 5682: of the C<by> columns or measure aliases. 5683: 5684: B<Fix:> Use a column name from C<by> or a measure alias from C<measures>. 5685: The sort falls back to the default group ordering (C<by> columns ascending). 5686: 5687: =item C<warn_aggregate_non_numeric> (carp) 5688: 5689: B<When:> The array backend encounters one or more non-numeric values in a 5690: column that is the target of a C<sum> or C<avg> measure. The SQLite backend 5691: coerces non-numeric values to C<0.0> via C<CAST> and emits no warning. 5692: 5693: B<Fix:> Clean the data before joining, or switch to the SQLite backend if 5694: coercion to zero is acceptable. 5695: 5696: # Example: the warning names the column, the count, and the first bad value 5697: # "aggregate: column "score" has 2 non-numeric value(s), skipped, e.g. "n/a"" 5698: 5699: =back 5700: 5701: =head1 REPOSITORY 5702: 5703: L<https://github.com/nigelhorne/Database-Join> 5704: 5705: =head1 SUPPORT 5706: 5707: This module is provided as-is without any warranty. 5708: 5709: =head1 SEE ALSO 5710: 5711: =over 4 5712: 5713: =item * L<Configure an Object at Runtime|Object::Configure> 5714: 5715: =item * L<Test Dashboard|https://nigelhorne.github.io/Database-Join/coverage/> 5716: 5717: =item * L<Database::Abstraction> 5718: 5719: =back 5720: 5721: =head1 SECURITY CONSIDERATIONS 5722: 5723: C<Database::Join> is a pure in-memory routing and merge layer. It never 5724: generates SQL strings, never opens files, and never calls C<system()>, 5725: C<exec()>, or C<eval()>. The security properties described below are 5726: architectural guarantees, not run-time checks. 5727: 5728: =head2 What Database::Join guarantees 5729: 5730: =over 4 5731: 5732: =item Criteria partition isolation 5733: 5734: Every criterion you pass to a query method is routed to I<exactly one> 5735: component database (the one that owns that column), or to I<all> databases 5736: when the criterion is on the join key column. A hostile value in a criterion 5737: for column C<name> (owned by database A) will never reach database B. 5738: 5739: =item Unknown columns are rejected before reaching any database 5740: 5741: If a criterion column name is not present in any component database (or has 5742: been hidden with C<remove_column>), C<Database::Join> logs a C<carp> warning 5743: and silently drops the criterion. No database receives the hostile key. 5744: 5745: =item AUTOLOAD only accepts word-character column names 5746: 5747: Perl's method dispatch extracts the column name via C<\w+>, which matches only 5748: C<[A-Za-z0-9_]>. Hostile method names with shell metacharacters, quotes, or 5749: spaces cannot reach the AUTOLOAD dispatch path. Private names (starting with 5750: C<_>) are additionally blocked with an explicit C<croak>. 5751: 5752: =item No value sanitisation (by design) 5753: 5754: C<Database::Join> does I<not> sanitise, HTML-encode, or validate the 5755: I<values> in criteria hashrefs. Preventing SQL injection is the 5756: responsibility of the underlying C<Database::Abstraction> objects (which use 5757: parameterised queries). Preventing XSS or header injection is the 5758: responsibility of the CGI or web layer that renders the output. 5759: 5760: =item Taint-mode compatible (array path) 5761: 5762: The array merge path contains no C<system()>, C<exec()>, backtick, 5763: C<open(PIPE)>, or C<eval STRING> calls. It neither opens files nor constructs 5764: shell commands. The AUTOLOAD regex C</ :: (\w++) \z /x> uses a possessive 5765: quantifier (C<\w++>) and a strict end-of-string anchor (C<\z>) and produces 5766: an I<untainted> capture, so the column name used for dispatch is clean under 5767: C<-T>. Criteria values are passed verbatim to component C<Database::Abstraction> 5768: objects; those objects are responsible for handling tainted values at the SQL 5769: parameterisation layer. 5770: 5771: =item SQLite backend: column names are quoted, values are parametrised 5772: 5773: When the SQLite path is active, C<Database::Join> generates SQL internally. 5774: All column and table names are double-quoted (SQL identifier quoting) before 5775: being embedded in statement strings. All row values are passed to SQLite 5776: exclusively through DBI prepared statement placeholders -- never by string 5777: interpolation. A hostile value in a source row therefore cannot inject SQL 5778: into the temporary database. 5779: 5780: The temporary SQLite file is created by C<File::Temp> using a securely random, 5781: unpredictable filename. No C<system()> or shell command is used to create or 5782: remove it. The connection is made with C<DBI-E<gt>connect(..., { RaiseError =E<gt> 1, 5783: PrintError =E<gt> 0 })> and is closed before the method returns. Column names 5784: in the generated SQL come from C<columns()>, which is produced by 5785: C<Database::Abstraction> at construction time -- they are not derived from 5786: caller-supplied criteria values. 5787: 5788: =item Operator hashref broadcast copy 5789: 5790: When the same join-key criterion (an operator hashref such as 5791: C<< { '>' => 'A' } >>) is broadcast to multiple component databases, each 5792: database receives its own I<shallow copy> of the hashref. A component database 5793: that mutates the hashref's contents at the top level cannot affect what 5794: subsequent databases receive. 5795: 5796: =item collision_prefix value type guard 5797: 5798: C<_build_col_index> rejects any C<collision_prefix> value that is a reference 5799: (hashref, arrayref, coderef, etc.) with an immediate C<croak>. A reference 5800: value would stringify to C<"HASH(0x...)">, leaking a heap address into every 5801: column name, C<columns()> listing, and merged row returned to the caller. The 5802: guard fires before any column name is constructed. 5803: 5804: =item Filter deep-copy isolation 5805: 5806: The C<filters> constructor parameter and the C<filter> option of 5807: C<add_database()> are I<deep-copied> at the point of use. The caller's 5808: original hashrefs are never stored; post-construction mutation of those 5809: hashrefs cannot widen or bypass the configured row-security constraints. 5810: 5811: =item mandatory_filters cannot be overridden or bypassed at query time 5812: 5813: Predicates stored in C<_mandatory_filters> are applied unconditionally to every 5814: query result, after the in-memory merge (array path) or as parameterised SQL 5815: C<WHERE> clauses (SQLite path). There is no query-time parameter that suppresses 5816: or modifies them. Caller-supplied criteria are ANDed with the mandatory 5817: predicates -- they can only further restrict the result set, never widen it. 5818: 5819: Each predicate is a shallow copy of the caller-supplied hashref; post-construction 5820: mutation of the original C<mandatory_filters> arrayref or its elements has no 5821: effect on the stored predicates. 5822: 5823: Values are always passed to the SQLite engine via DBI bind parameters, never by 5824: string interpolation. A hostile C<val> in a predicate cannot inject SQL. 5825: 5826: =back 5827: 5828: =head2 What the caller is responsible for 5829: 5830: =over 4 5831: 5832: =item Sanitise values before building criteria 5833: 5834: DJ passes criterion values verbatim to component databases. If your 5835: application accepts user-supplied filter values (e.g. from a CGI query 5836: string), those values I<must> be validated or sanitised by your application 5837: before being passed to DJ. 5838: 5839: =item Restrict which columns the caller can filter on 5840: 5841: Any column in C<columns()> can be used as a filter criterion. If a column 5842: should not be filterable by end users (e.g. an internal status flag), hide it 5843: with C<remove_column> so that queries on it are silently dropped. 5844: 5845: =item Do not expose the joined view directly to user-supplied criteria 5846: 5847: DJ is not a firewall. It faithfully routes user input to component databases. 5848: Wrap DJ calls in a thin service layer that whitelists the permitted criterion 5849: columns and validates their values. 5850: 5851: =back 5852: 5853: =head3 API SPECIFICATION (security surface) 5854: 5855: Input accepted by all query methods and passed through DJ to component databases: 5856: 5857: Criterion values: 5858: type: scalar string | operator hashref { OP => scalar } 5859: validation: NONE (DJ trusts the caller; component DA is responsible) 5860: max size: unconstrained (OOM risk on very large values) 5861: 5862: Column name keys in criteria: 5863: type: string 5864: validation: must be present in _col_db (else carp + drop) 5865: character set: any Perl string (including control chars); DJ does 5866: not impose a character-set restriction on criteria KEYS 5867: 5868: AUTOLOAD method-name-as-column: 5869: type: \w+ (enforced by Perl regex /::(\w+)$/) 5870: validation: must not start with '_'; must be in _col_db 5871: 5872: =encoding UTF-8 5873: 5874: =head1 FORMAL SPECIFICATION 5875: 5876: Z calculus schemas for the key invariants and operations. 5877: Unicode is used throughout this section as required by Z notation. 5878: 5879: ─── Database_Join ───────────────────────────────────────────────── 5880: dbs : seq DATABASE_ABSTRACTION 5881: join_col : NAME 5882: join_type : {left, inner, outer} 5883: join_map : ℕ ⇸ NAME 5884: filters : ℕ ⇸ CRITERIA 5885: col_db : NAME ⇸ ℕ 5886: removed : ℙ NAME 5887: backend : {array, sqlite, auto} 5888: max_array_rows : ℕ 5889: tmpdir : PATH 5890: ─────────────────────────────────────────────────────────────────── 5891: #dbs ≥ 1 5892: dom join_map ⊆ 0 ‥ (#dbs - 1) 5893: dom filters ⊆ 0 ‥ (#dbs - 1) 5894: dom col_db = (⋃ { i : 0 ‥ #dbs-1 • ran((dbs i).columns) }) \ removed 5895: join_col ∉ removed 5896: ∀ i : 0 ‥ #dbs-1 • 5897: local_jc(i) = if i ∈ dom join_map then join_map(i) else join_col 5898: ∀ i : 0 ‥ #dbs-1 • 5899: local_jc(i) ∈ ran((dbs i).columns) 5900: 5901: ─── Init ────────────────────────────────────────────────────────── 5902: ΔDatabase_Join 5903: dbs? : seq DATABASE_ABSTRACTION 5904: join_col? : NAME 5905: join_type? : {left, inner, outer} 5906: join_map? : ℕ ⇸ NAME 5907: filters? : ℕ ⇸ CRITERIA 5908: base_criteria? : CRITERIA -- optional; column-name keyed 5909: removed? : ℙ NAME 5910: backend? : {array, sqlite, auto} -- default auto 5911: max_array_rows? : ℕ -- default 10000 5912: tmpdir? : PATH -- default File::Spec->tmpdir 5913: ─────────────────────────────────────────────────────────────────── 5914: #dbs? ≥ 1 5915: dbs' = dbs? 5916: join_col' = join_col? 5917: join_type' = join_type? 5918: join_map' = join_map? 5919: -- base_criteria is partitioned by column ownership and merged into filters: 5920: -- bc_slice(i) = partition(base_criteria?, i) 5921: -- filters'(i) = merge_criteria(bc_slice(i), filters?(i)) 5922: -- when bc_slice(i) ≠ ∅; otherwise filters?(i) 5923: -- (filters? wins on plain-scalar conflicts; operator hashrefs are ANDed) 5924: filters' = ∀ i : 0 ‥ #dbs?-1 • 5925: merge_criteria(partition(base_criteria?, i), filters?(i) ∪ ∅) 5926: col_db' = buildColIndex(dbs?, join_col?, join_map?) 5927: removed' = removed? 5928: backend' = backend? 5929: max_array_rows' = max_array_rows? 5930: tmpdir' = tmpdir? 5931: 5932: ─── SelectAllArrayref ───────────────────────────────────────────── 5933: ΞDatabase_Join -- state unchanged 5934: criteria? : CRITERIA 5935: result! : seq MERGED_ROW 5936: ─────────────────────────────────────────────────────────────────── 5937: ∀ c : dom criteria? • c ∈ dom col_db ∪ {join_col} 5938: result! = joinedQuery(criteria?) 5939: result! is sorted ascending by join_col value 5940: 5941: ─── AddDatabase ─────────────────────────────────────────────────── 5942: ΔDatabase_Join 5943: db? : DATABASE_ABSTRACTION 5944: local_jc? : NAME -- optional; defaults to join_col 5945: filter? : CRITERIA -- optional 5946: remove? : ℙ NAME -- optional 5947: ─────────────────────────────────────────────────────────────────── 5948: db?.isa('Database::Abstraction') 5949: local_jc? ∈ ran(db?.columns) 5950: dbs' = dbs ^ ⟨db?⟩ 5951: col_db' = col_db ⊕ { c ↦ #dbs | c ∈ ran(db?.columns) \ {local_jc?} \ removed } 5952: filters' = if filter? ≠ ∅ then filters ⊕ {#dbs ↦ filter?} else filters 5953: join_map' = if local_jc? ≠ join_col 5954: then join_map ⊕ {#dbs ↦ local_jc?} 5955: else join_map 5956: removed' = removed ∪ remove? 5957: 5958: ─── RemoveColumn ────────────────────────────────────────────────── 5959: ΔDatabase_Join 5960: col? : NAME 5961: ─────────────────────────────────────────────────────────────────── 5962: col? ≠ join_col 5963: removed' = removed ∪ {col?} 5964: col_db' = col_db \ {col?} 5965: join_map' = join_map 5966: filters' = filters 5967: dbs' = dbs 5968: 5969: =head2 collision_prefix 5970: 5971: ─── CollisionPrefix ─────────────────────────────────────────────── 5972: collision_prefix : ℕ ⇸ STRING 5973: dbs : seq DATABASE_ABSTRACTION 5974: col_db : NAME ⇸ ℕ 5975: ─────────────────────────────────────────────────────────────────── 5976: -- Only secondary databases (index > 0) carry a meaningful prefix: 5977: dom collision_prefix ⊆ 1 ‥ (#dbs - 1) 5978: 5979: -- Published name for column col from database i: 5980: published(i, col) == 5981: if i ∈ dom collision_prefix ∧ col ∈ dom col_db ∧ col_db(col) < i 5982: then (collision_prefix i) ^ "." ^ col 5983: else col 5984: 5985: -- col_db routes the published name to the owning database: 5986: col_db(published(i, col)) = i 5987: 5988: -- The original column name is never removed from an earlier database: 5989: ∀ i : 1 ‥ #dbs-1; col : columns(dbs i) • 5990: published(i, col) ≠ col ⟹ 5991: ∃ j : 0 ‥ i-1 • col ∈ dom col_db ∧ col_db(col) = j 5992: 5993: =head2 join_map 5994: 5995: ─── JoinMap ─────────────────────────────────────────────────────── 5996: join_map : ℕ ⇸ NAME 5997: dbs : seq DATABASE_ABSTRACTION 5998: join_col : NAME 5999: ─────────────────────────────────────────────────────────────────── 6000: dom join_map ⊆ 0 ‥ (#dbs - 1) 6001: ∀ i : dom join_map • (join_map i) ∈ ran(dbs i).columns 6002: ∀ i : 0 ‥ (#dbs - 1) \ dom join_map • 6003: join_col ∈ ran(dbs i).columns 6004: 6005: -- Resolution of the local join-key name for database i: 6006: local_jc(i) == if i ∈ dom join_map then join_map(i) else join_col 6007: 6008: -- The canonical name is always join_col; local_jc is never exposed. 6009: 6010: =head2 SECURITY INVARIANTS 6011: 6012: ─── PartitionIsolation ───────────────────────────────────────────── 6013: -- For every query call with criteria C and column col ≠ join_col: 6014: ∀ i : 0 ‥ #dbs-1 • 6015: i ≠ _col_db(col) ⟹ col ∉ dom(per_db(i)) 6016: 6017: -- Unknown column is dropped before any database sees it: 6018: col ∉ dom(_col_db) ∧ col ≠ join_col ⟹ 6019: (∀ i : 0 ‥ #dbs-1 • col ∉ dom(per_db(i))) 6020: 6021: ─── NoCodeExecution ──────────────────────────────────────────────── 6022: -- DJ contains no call to system(), exec(), open(PIPE), or eval(). 6023: -- Hostile criterion values therefore cannot achieve code execution 6024: -- within the Database::Join layer. 6025: ∀ v : VALUE • _joined_query({col ↦ v}) ≠ ⊥ due to code injection 6026: 6027: =head2 filters 6028: 6029: ─── Filters ───────────────────────────────────────────────────── 6030: filters : ℕ ⇸ CRITERIA 6031: dbs : seq DATABASE_ABSTRACTION 6032: ───────────────────────────────────────────────────────────────── 6033: dom filters ⊆ 0 ‥ (#dbs - 1) 6034: 6035: -- A filtered database i always contributes to key-set intersection. 6036: -- For each query with criteria C: 6037: effective_criteria(i, C) == 6038: if i ∈ dom filters 6039: then merge_criteria(filters(i), partition(C, i)) 6040: else partition(C, i) 6041: 6042: -- Criteria merging (AND semantics for operator hashrefs): 6043: merge_criteria(base, extra) == 6044: { col : dom base ∪ dom extra • 6045: if col ∈ dom base ∩ dom extra 6046: ∧ base(col) ∈ HASHREF ∧ extra(col) ∈ HASHREF 6047: then col ↦ base(col) ∪ extra(col) -- operator union 6048: else col ↦ (if col ∈ dom extra then extra(col) else base(col)) } 6049: 6050: =head2 base_criteria 6051: 6052: ─── BaseCriteria ──────────────────────────────────────────────── 6053: base_criteria : CRITERIA -- column-name keyed 6054: col_db : NAME ⇸ ℕ 6055: filters : ℕ ⇸ CRITERIA -- after Init 6056: ───────────────────────────────────────────────────────────────── 6057: -- base_criteria is applied once at construction by partitioning 6058: -- its columns into per-db slices and merging into filters: 6059: ∀ i : 0 ‥ #dbs-1 • 6060: bc_slice(i) = partition(base_criteria, i) 6061: filters(i) = merge_criteria(bc_slice(i), filters_explicit(i)) 6062: 6063: -- where filters_explicit is the filters parameter as supplied. 6064: -- merge_criteria semantics: explicit filters win on plain-scalar 6065: -- conflicts; operator hashrefs are combined (AND). 6066: 6067: -- Unknown columns are dropped (warn_unknown_column carp); 6068: -- the join_column is broadcast to all databases. 6069: 6070: -- Key-set semantics: any database that receives a non-empty 6071: -- bc_slice acts as an inner-join partner (same as filters). 6072: 6073: =head2 aggregate 6074: 6075: ─── AggregateSpec ───────────────────────────────────────────────── 6076: MEASURE ::= { fn : AGGFN; col : NAME?; as : ALIAS } 6077: AGGFN ::= sum | avg | min | max | count | count_distinct 6078: ALIAS ::= \w+ 6079: SPEC ::= { by : seq NAME; measures : seq MEASURE; 6080: having : CRITERIA?; 6081: sort_by : NAME × {ASC,DESC}?; limit : ℕ?; offset : ℕ? } 6082: ───────────────────────────────────────────────────────────────── 6083: -- Pre-conditions (checked by _validate_aggregate_spec): 6084: ∀ m : measures • 6085: m.fn ∈ {sum, avg, min, max, count, count_distinct} 6086: ∧ (m.fn ≠ count ∨ m.fn = count_distinct ⟹ m.col ≠ ∅) 6087: ∧ m.as matches /^\w+\z/ 6088: ∀ name : by • name ∈ dom col_db 6089: ∀ m : measures • m.col ≠ ∅ ⟹ m.col ∈ dom col_db 6090: # aliases are unique and do not collide with 'by' names: 6091: ∀ i,j : 0 ‥ #measures-1 • i ≠ j ⟹ measures(i).as ≠ measures(j).as 6092: ∀ m : measures; b : by • m.as ≠ b 6093: 6094: ─── Aggregate ───────────────────────────────────────────────────── 6095: ΞDatabase_Join -- state unchanged (Xi-transition) 6096: criteria? : CRITERIA -- pre-aggregation WHERE 6097: spec? : SPEC 6098: result! : seq GROUP_ROW 6099: ───────────────────────────────────────────────────────────────── 6100: -- GROUP_ROW has exactly the by-columns plus the measure aliases. 6101: -- Group key: tuple of by-column values from a merged row. 6102: group_key(row, by) == { b : by • b ↦ row(b) } 6103: 6104: -- Fold function on the array backend: 6105: fold(rows, spec) == 6106: let G = { k : IMAGE(group_key(r, by) | r : rows) • k ↦ {} } 6107: for r : rows: 6108: G[group_key(r, by)] += r -- accumulate per measure.fn 6109: for g : dom G: 6110: G[g] = { b : by • b ↦ g(b) } 6111: ∪ { m : measures • m.as ↦ apply(m.fn, m.col, G[g].rows) } 6112: result_pre = ran G 6113: 6114: -- apply: maps aggregate function to its computed value. 6115: apply(count, ∅, rows) == #rows 6116: apply(count_distinct, col, rows) == #{ r : rows • r(col) } 6117: apply(sum, col, rows) == Σ { r : rows | is_num(r(col)) • r(col) } 6118: apply(avg, col, rows) == sum(col, rows) / #{ r | is_num(r(col)) } 6119: apply(min, col, rows) == min { r : rows • r(col) } 6120: apply(max, col, rows) == max { r : rows • r(col) } 6121: 6122: -- Post-aggregation HAVING filter: 6123: result_having = [ g : result_pre | matches_having(g, spec.having) ] 6124: 6125: -- Grand total (by = []): 6126: #by = 0 ⟹ #result! = 1 6127: #by > 0 ∧ #result_having = 0 ⟹ result! = [] 6128: 6129: -- Final result: 6130: result! = sort_and_page(result_having, spec) 6131: 6132: -- Backend dispatch: 6133: backend ∈ {sqlite, auto} ⟹ aggregation pushed to SQLite GROUP BY 6134: backend = array ⟹ fold() applied in Perl 6135: 6136: -- Correctness invariant (both paths return identical rows): 6137: ∀ criteria?, spec? • 6138: _sqlite_aggregate(criteria?, spec?) = _fold_aggregate(rows(criteria?), spec?) 6139: 6140: =head2 selectall_arrayref 6141: 6142: selectall_arrayref : CRITERIA → seq MERGED_ROW 6143: pre: ∀ col : dom criteria • col ∈ dom self._col_db ∪ {self._join_col} 6144: post: result = _joined_query(criteria) 6145: result is sorted ascending by join_col value 6146: 6147: =head2 selectall_array 6148: 6149: selectall_array : CRITERIA → seq MERGED_ROW | MERGED_ROW? 6150: pre: same as selectall_arrayref 6151: post: wantarray => result = @{ selectall_arrayref(criteria) } 6152: !wantarray => result = selectall_arrayref(criteria)[0] (or undef) 6153: 6154: =head2 fetchrow_hashref 6155: 6156: fetchrow_hashref : CRITERIA → MERGED_ROW? 6157: post: result = selectall_arrayref(criteria)[0] (or undef if empty) 6158: 6159: =head2 count 6160: 6161: count : CRITERIA → ℕ 6162: post: result = #selectall_arrayref(criteria) 6163: 6164: =head2 columns 6165: 6166: columns : → seq NAME 6167: post: result = sort( 6168: (⋃ { i : 0 ‥ #dbs-1 • ran(dbs(i).columns) } 6169: \ dom removed_cols 6170: \ { local_jc(i) | i ∈ dom join_map ∧ local_jc(i) ≠ join_col }) 6171: ) 6172: 6173: =head2 schema 6174: 6175: schema : → NAME ⇸ SCHEMA_INFO 6176: post: dom(result) = ran(columns()) 6177: ∀ col : dom(result) • 6178: result(col) = (last database containing col).schema()(col) 6179: 6180: =head2 updated 6181: 6182: updated : → ℕ 6183: post: result = max { i : 0 ‥ #dbs-1 • dbs(i).updated() } 6184: 6185: =head2 remove_column 6186: 6187: remove_column : NAME → Database_Join 6188: pre: col ≠ self._join_col 6189: post: self'._removed_cols = self._removed_cols ∪ {col} 6190: self'._col_db = self._col_db \ {col} 6191: self'._col_cache = undef 6192: self'._schema_cache = undef 6193: 6194: =head2 AUTOLOAD 6195: 6196: AUTOLOAD : NAME × CRITERIA → VALUE | seq VALUE 6197: pre: col ∈ dom self._col_db 6198: col does not begin with '_' 6199: post: let rows = _joined_query(criteria) 6200: wantarray => result = { r : rows • r(col) } 6201: !wantarray => result = rows(0)(col) (or undef if rows is empty) 6202: 6203: =head2 backend 6204: 6205: ─── BackendDispatch ─────────────────────────────────────────────── 6206: backend : {array, sqlite, auto} 6207: max_array_rows : ℕ 6208: ─────────────────────────────────────────────────────────────────── 6209: 6210: -- row_count(db): cheaply count rows in a component database. 6211: -- Uses dbi_source() COUNT(*) SQL for SQLite-backed sources, 6212: -- or the DA's own count() method when defined in its own package. 6213: -- Returns ⊥ (bottom / unknown) when neither is available. 6214: row_count(db) == 6215: if (db has dbi_source() returning a SQLite dbh) 6216: then SELECT COUNT(*) FROM source_table 6217: else if (defined &{ref(db) ^ "::count"}) 6218: then db.count() 6219: else ⊥ 6220: 6221: -- Combined row count across all component databases. 6222: -- If any database returns ⊥, total is ⊥ (cannot determine). 6223: total_count == 6224: if ∀ i : 0 ‥ #dbs-1 • row_count(dbs i) ≠ ⊥ 6225: then Σ { i : 0 ‥ #dbs-1 • row_count(dbs i) } 6226: else ⊥ 6227: 6228: -- Dispatch rule for _joined_query: 6229: use_sqlite(C) == 6230: backend = 'sqlite' 6231: ∨ (backend = 'auto' ∧ total_count ≠ ⊥ ∧ total_count > max_array_rows) 6232: 6233: _joined_query(C) == 6234: if use_sqlite(C) 6235: then _sqlite_join(C) 6236: else _joined_query_array(C) 6237: 6238: -- Result identity invariant: both paths return identical rows. 6239: ∀ C : CRITERIA • 6240: _sqlite_join(C) = _joined_query_array(C) 6241: 6242: =head1 STATE DIAGRAM 6243: 6244: C<Database::Join> objects follow three independent finite state machines (FSMs). 6245: Each FSM is described with an ASCII diagram showing valid states (boxes), the 6246: triggers that cause transitions (arrows), and important side-effects. 6247: 6248: =head2 FSM 1: Object Lifecycle 6249: 6250: Governs the structural state of a C<Database::Join> instance. 6251: Query methods (C<selectall_arrayref>, C<selectall_array>, C<fetchrow_hashref>, 6252: C<count>, C<aggregate>, C<each_row>, C<columns>, C<schema>, C<updated>) are 6253: schema-preserving (Xi-transitions) and are not shown because they do not change 6254: state. C<aggregate()> additionally triggers the SQLite cache lifecycle (FSM 2) 6255: when the backend is C<'sqlite'> or C<'auto'>, just like any other query method. 6256: 6257: [pre-creation] 6258: | 6259: | new( databases => [...], join_column => '...' ) 6260: | Side-effect: _col_db routing table built; 6261: | _autoload_pk set from autoload_pk param (default: join_column) 6262: v 6263: [CONSTRUCTED] <-----------------------------------------+ 6264: | | | 6265: | +--------------------------------------------+ | 6266: | (query methods: no structural change) | | 6267: | | | 6268: |-- remove_column( col ) -------> [COL_REMOVED] <--+ | 6269: | | | | 6270: | Side-effect: col removed from | | | 6271: | _col_db; _col_cache and +----+ | 6272: | _schema_cache cleared. (idempotent; | 6273: | Join column cannot be removed.) chainable) | 6274: | | 6275: +-- add_database( db ) ----------> [DB_ADDED] <------+ 6276: | | 6277: Side-effect: new columns added; | | add_database( db ) 6278: _col_db extended; SQLite cache | | (chainable; each 6279: invalidated (if any). +----+ extends the view) 6280: 6281: Note: COL_REMOVED and DB_ADDED are not mutually exclusive. 6282: Both transitions are legal on any valid object, in any order. 6283: 6284: Illegal triggers (always croak; object state is not changed): 6285: 6286: Trigger Error 6287: ----------------------------------- --------------------------------- 6288: new( databases => [] ) error_no_databases 6289: remove_column( join_column ) error_remove_join_column 6290: add_database( non-reference ) error_invalid_database 6291: new() with join_col absent from DB error_join_col_absent 6292: 6293: =head2 FSM 2: SQLite Cache Lifecycle 6294: 6295: Governs the temporary SQLite cache used by the C<backend='sqlite'> and 6296: C<backend='auto'> join paths. The cache does not exist until the first 6297: query on the SQLite path. 6298: 6299: [ABSENT] <----- add_database( db ) 6300: | | 6301: | (no temp file) | Side-effect: old DBI handle disconnected; 6302: | | _sqlite_cache deleted. 6303: | | 6304: | +<-------------------------------------------+ 6305: | | 6306: | first query on SQLite path | 6307: | Side-effect: File::Temp db created in tmpdir; | 6308: | DBI connected; sources ATTACHed or spilled; | 6309: | _sqlite_cache = { dbh, tmpfile, n, updated, ... } | 6310: v | 6311: [FRESH] <--+ | 6312: | | | 6313: | | subsequent queries | 6314: | | (cache reused; refaddr of _sqlite_cache unchanged) | 6315: +--------+ | 6316: | | 6317: | updated() timestamp of any source DA changes | 6318: | -- OR -- source row count changes | 6319: | Side-effect: none yet (_cache_fresh returns false) | 6320: v | 6321: [STALE] | 6322: | | 6323: | next query | 6324: | Side-effect: old DBI handle disconnected; old temp file | 6325: | unlinked; new temp file built from current source data. | 6326: +---------------------------------------------------------------+ 6327: (transitions to FRESH) 6328: 6329: On object DESTROY: 6330: FRESH/STALE: DBI handle disconnected; File::Temp object released 6331: (temp file unlinked by File::Temp DESTROY). 6332: ABSENT: No temp file exists; no-op. 6333: 6334: =head2 FSM 3: Column Visibility (per column) 6335: 6336: Each column in the logical view independently follows a two-state machine. 6337: Transition from VISIBLE to REMOVED is one-way: C<add_database> never 6338: restores a column that is in C<_removed_cols>. 6339: 6340: [VISIBLE] <-- initial state for every column at construction 6341: | | 6342: | | query / columns() / schema() 6343: | | (column present in results; no state change) 6344: +----+ 6345: | 6346: | remove_column( col ) 6347: | Side-effect: col deleted from _col_db; 6348: | _col_cache and _schema_cache cleared. 6349: v 6350: [REMOVED] <---+ 6351: | | 6352: | | remove_column( col ) again 6353: | | (idempotent; no error; no second side-effect) 6354: +---------+ 6355: 6356: One-way invariant: 6357: If col is in _removed_cols, then add_database( db_that_has_col ) 6358: does NOT re-add it. Formal: col_db' = col_db ⊕ { c | c in 6359: ran(db.columns) \ {local_jc} \ removed }. 6360: 6361: Illegal trigger: 6362: remove_column( join_column ) -- error_remove_join_column (croaks; 6363: state unchanged) 6364: 6365: =head1 AUTHOR 6366: 6367: Nigel Horne, C<< <njh@nigelhorne.com> >> 6368: 6369: =head1 LICENSE AND COPYRIGHT 6370: 6371: Copyright (C) 2026 Nigel Horne. 6372: 6373: Usage is subject to the GPL2 licence terms. 6374: If you use it, please let me know. 6375: 6376: =cut