blib/lib/Database/BI/Model/DataSource.pm

filter: Statementstmt 73.9% 867 / 1173 Branchbran 65.8% 408 / 620 Conditioncond 58.7% 228 / 388 MC/DCmcdc 45.3% 102 / 225 Subroutinesub 88.0% 81 / 92 Podpod 100% 16 / 16 totaltotal 67.7% 1702 / 2514 CC 475 SCAR 46.4
CC
475
Cov
69%
_json_each_row
756.0
_xml_table
419.6
_detect_file_info
218.6
CRAP 104.0
« blib/lib/Database/BI/Util.pm ↑ Summary blib/lib/Database/BI.pm »
1 package Database::BI::Model::DataSource;
2  
3 13 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 13 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 13 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 13 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 13 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 13 ▶use Database::BI::I18N ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 13 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 13 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 13 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 13 ▶use Params::Validate::Strict qw(validate_strict);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 13 ▶use Params::Get ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 13 our $VERSION = '0.024.0';
17  
18 =head1 NAME
19  
20 Database::BI::Model::DataSource - Table-agnostic adapter around Database::Abstraction
21  
22 =head1 VERSION
23  
24 0.024.0
25  
26 =head1 SYNOPSIS
27  
28 B<Read all rows from a CSV file:>
29  
30 use Database::BI::Model::DataSource;
31  
32 my $source = Database::BI::Model::DataSource->new(
33 directory => '/path/to/data',
34 table => 'sales', # looks for data/sales.csv, tsv, .psv, .sql, .xml, etc.
35 );
36  
37 my $records = $source->fetch_all; # arrayref of hashrefs -- one hashref per row
38  
39 for my $row (@{$records}) {
40 printf "Product: %s, Amount: %s\n", $row->{product}, $row->{amount};
41 }
42  
43 B<Get column names in the original file order (CSV/PSV/TSV only):>
44  
45 my $cols = $source->columns; # returns undef for SQLite and XML
46 if ($cols) {
47 print join(', ', @{$cols}), "\n";
48 }
49  
50 B<Find out which column is the primary key:>
51  
52 print "Primary key column: ", $source->id_column, "\n";
53  
54 B<Open a SQLite file (.sql extension):>
55  
56 my $source = Database::BI::Model::DataSource->new(
57 directory => '/var/data',
58 table => 'inventory', # looks for /var/data/inventory.sql
59 );
60  
61 B<Open a pipe-separated file (.psv extension):>
62  
63 my $source = Database::BI::Model::DataSource->new(
64 directory => '/var/data',
65 table => 'products', # looks for /var/data/products.psv
66 );
67  
68 B<Open a tab-separated file (.tsv extension):>
69  
70 my $source = Database::BI::Model::DataSource->new(
71 directory => '/var/data',
72 table => 'products', # looks for /var/data/products.tsv
73 );
74  
75 B<Use a custom i18n object to translate error messages:>
76  
77 # The i18n object must have a maketext($key, @args) method.
78 my $source = Database::BI::Model::DataSource->new(
79 directory => '/path/to/data',
80 table => 'sales',
81 i18n => My::I18N::Handle->new,
82 );
83  
84 B<Open a remote HTML table from a URL:>
85  
86 # Requires LWP::UserAgent::Cached and HTML::TableExtract.
87 # The table is fetched and cached in memory; no file is saved to disk.
88 my $source = Database::BI::Model::DataSource->new(
89 url => 'https://example.com/data-page.html',
90 );
91 my $records = $source->fetch_all;
92  
93 B<Select a specific table when a page has more than one HTML table:>
94  
95 my $source = Database::BI::Model::DataSource->new(
96 url => 'https://example.com/page.html',
97 html_table_index => 2, # zero-based: 0 = first table, 2 = third table
98 );
99  
100 B<Fetch from an intranet host, which resolves to a private address:>
101  
102 my $source = Database::BI::Model::DataSource->new(
103 url => 'https://reports.corp.example/sales.html',
104 private_hosts => ['*.corp.example'],
105 );
106  
107 B<Open one specific internal table from a multi-table SQLite database:>
108  
109 # A SQLite file may contain more than one table.
110 # Use internal_table to say which one you want.
111 my $source = Database::BI::Model::DataSource->new(
112 directory => '/var/data',
113 table => 'store', # looks for store.db, store.sql, etc.
114 internal_table => 'customer', # open just the "customer" table inside
115 );
116 my $records = $source->fetch_all;
117  
118 B<Check whether a SQLite file has more than one table:>
119  
120 my $source = Database::BI::Model::DataSource->new(
121 directory => '/var/data',
122 table => 'store',
123 );
124 my $tbl_list = $source->sqlite_tables; # undef unless it is a multi-table SQLite
125 if ($tbl_list && @{$tbl_list} > 1) {
126 # let the user choose which table to open
127 for my $name (@{$tbl_list}) {
128 printf " table: %s\n", $name;
129 }
130 }
131  
132 B<Open a remote file over SSH (SFTP):>
133  
134 # Requires Net::SFTP::Foreign.
135 my $source = Database::BI::Model::DataSource->new(
136 directory => '/remote/data',
137 table => 'report',
138 host => 'deploy@dbserver.example.com',
139 file_ext => 'log', # hint: try report.log first, then other exts
140 );
141 my $records = $source->fetch_all;
142  
143 B<Handle errors gracefully:>
144  
145 my $source = eval {
146 Database::BI::Model::DataSource->new(
147 directory => $dir,
148 table => $table,
149 );
150 };
151 if ($@) {
152 carp "Could not open table: $@";
153 # $@ contains a translated message from %MESSAGES
154 }
155  
156 my $records = eval { $source->fetch_all };
157 if ($@) {
158 carp "Could not read records: $@";
159 }
160  
161 =head1 DESCRIPTION
162  
163 C<Database::BI::Model::DataSource> is a thin, table-agnostic adapter that
164 wraps L<Database::Abstraction> and exposes three accessors (C<fetch_all>,
165 C<columns>, C<id_column>) used by the controller.
166  
167 L<Database::Abstraction> is a read-only ORM that discovers data files
168 (CSV, PSV, TSV, SQLite, XML, etc.) automatically from a directory based on the
169 calling class name. C<DataSource> generates an ephemeral subclass at
170 construction time so callers never interact with L<Database::Abstraction>
171 directly. To swap the backend for L<Database::Join> in Phase 2, only the
172 C<open_table> helper in C<Database::BI> needs to change; the controller and
173 C<DataSource> are untouched.
174  
175 C<_detect_file_info> peeks at the first header line of CSV/PSV/TSV files to
176 extract the correct separator character, the primary-key column name, and
177 the full ordered column list. Without this, two silent L<Database::Abstraction>
178 defaults corrupt every result: C<sep_char> defaults to C<'!'> (turning a
179 comma-separated file into a single-field table) and C<id> defaults to
180 C<'entry'> (causing every row to be discarded when no C<entry> column
181 exists).
182  
183 Result filtering (C<eq>, C<contains>, C<gt>, etc.) is performed at the
184 controller layer by C<Dashboard::_apply_filter_spec> after C<fetch_all>
185 returns. C<DataSource> itself is filter-unaware.
186  
187 All user-visible strings and exception messages are keyed through the
188 C<%MESSAGES> dictionary and routed via C<_msg()>, making every diagnostic
189 replaceable by an i18n object at instantiation time.
190  
191 =cut
192  
193 =head1 ENCODING
194  
195 =head2 What is safe to put in cell values
196  
197 Cell values (the actual data inside rows) are passed through as Perl
198 character strings exactly as C<Database::Abstraction> and the underlying
199 DBI driver return them. Full Unicode -- including non-ASCII letters,
200 accented characters, CJK ideographs, and emoji -- is supported in cell
201 values, provided the source file is encoded in UTF-8 (or the encoding
202 declared in its HTTP headers for URL-backed tables).
203  
204 =head2 What must stay ASCII
205  
206 The following structural items must contain B<only ASCII characters>:
207  
208 =over 4
209  
210 =item C<table> constructor argument
211  
212 The bare file stem used to look up the file on disk. Non-ASCII characters
213 are not valid SQL identifiers and will be silently replaced with underscores
214 (C<_>) by the sanitization step in C<new()>.
215  
216 =item Column header names (CSV / TSV / PSV first line)
217  
218 Column names are used as hash keys and as SQL identifiers inside
219 C<Database::Abstraction>. Non-ASCII headers cause C<DBD::CSV> to
220 fail or produce garbage keys. If your source file has non-ASCII
221 column headers, rename them before opening via C<DataSource>.
222  
223 =item C<host> argument
224  
225 The hostname or C<user@hostname> string for SFTP access. Must match
226 C<[A-Za-z0-9._@-]>; anything outside that character set is rejected by
227 the host-validation regex and produces C<error_backend_init>.
228  
229 =back
230  
231 =head2 URL-backed tables
232  
233 URL-backed tables (the C<url =E<gt>> constructor path) are fetched with
234 L<Database::BI::SafeUA>, which refuses (C<403>, so the read croaks
235 C<error_fetch_failed>) any request or redirect whose host resolves to this
236 machine, a private network or a link-local address such as a cloud metadata
237 service, and connects to the address it checked. C<private_hosts =E<gt> [...]>
238 names the hosts (exact, or C<*.suffix>) that may resolve privately: an
239 intranet. If the remote server declares a charset in its
240 HTTP headers or in an HTML C<meta> tag, L<Database::Abstraction> uses it
241 to decode the response body. If the charset declaration is absent or wrong,
242 cell values may arrive as raw bytes rather than character strings, and
243 multi-byte sequences will look garbled.
244  
245 =head2 File-backed tables (CSV / TSV / PSV)
246  
247 For files smaller than 16 KB, L<Text::xSV::Slurp> reads bytes and returns
248 them without re-encoding; for larger files the L<DBD::CSV> path is used
249 instead. In both cases C<DataSource> forces the slurp path (by passing
250 C<max_slurp_size =E<gt> -s $file>) so that column names with spaces are
251 preserved as-is. The caller (the Mojolicious controller) is responsible
252 for setting the correct C<Content-Type: text/html; charset=UTF-8> response
253 header.
254  
255 =cut
256  
257 # ---------------------------------------------------------------------------
258 # I18N message dictionary.
259 # All user-visible strings and exception messages are keyed here.
260 # To plug in a real i18n backend (e.g. Locale::Maketext), pass an object
261 # that responds to maketext($key, @args) as the "i18n" constructor argument;
262 # it will be called in preference to this table.
263 # ---------------------------------------------------------------------------
264  
265 13 Readonly our %MESSAGES => (
266 error_directory_required => 'DataSource: argument "directory" is required',
267 error_table_required => 'DataSource: argument "table" is required',
268 error_directory_missing => 'DataSource: directory "%s" does not exist or is not readable',
269 error_table_name_invalid => 'DataSource: table name "%s" contains illegal characters (alphanumeric and underscore only)',
270 error_backend_init => 'DataSource: failed to initialise database backend for table "%s": %s',
271 error_fetch_failed => 'DataSource: fetch_all failed for table "%s": %s',
272 error_rows_not_records => 'the source did not return a table of rows',
273 error_url_invalid => 'DataSource: URL "%s" must begin with http:// or https://',
274 error_url_fetch => 'DataSource: failed to open HTML table at "%s": %s',
275 error_no_safe_id => 'DataSource: table "%s" has no column with a safe identifier name (letters, digits, underscore); rename at least one column header',
276 error_no_tables => 'DataSource: SQLite file "%s" contains no user-defined tables',
277 error_table_not_found => 'DataSource: SQLite file "%s" does not contain a table named "%s"',
278 error_table_name_unsafe => 'The table "%s" in "%s" cannot be opened, because its name contains characters other than letters, digits and underscores. %s To open this one, rename it in a copy of the file, for example with sqlite3: ALTER TABLE "%s" RENAME TO %s;',
279 error_table_name_others => 'Open another table in the file instead: %s.',
280 error_no_usable_tables => 'No table in "%s" can be opened, because their names contain characters other than letters, digits and underscores: %s. To open one, rename it in a copy of the file, for example with sqlite3: ALTER TABLE "%s" RENAME TO %s;',
281 error_unsupported_db => 'DataSource: "%s" is a Berkeley DB file but the installed DB_File library cannot open it (file may use a newer Berkeley DB format)',
282 error_redis_invalid => 'DataSource: Redis URL "%s" must begin with redis://',
283 error_mariadb_unknown_server => 'DataSource: no MariaDB server is called "%s"; add it to mariadb_servers in the configuration',
284 error_mariadb_settings => 'DataSource: MariaDB server "%s" needs a valid %s in mariadb_servers in the configuration',
285 error_mariadb_no_driver => 'DataSource: DBD::MariaDB or DBD::mysql must be installed to open MariaDB server "%s"',
286 error_mariadb_connect => 'DataSource: cannot connect to MariaDB server "%s": %s',
287 error_mariadb_table => 'DataSource: cannot read table "%s" on MariaDB server "%s": %s',
288 error_xml_entities => 'DataSource: "%s" declares XML entities, which are not read: an entity can pull in another file or address',
289 error_json_invalid => 'DataSource: "%s" is not valid JSON: %s',
290 error_json_no_rows => 'DataSource: "%s" holds no table: it needs a list of objects, an object of objects, or an object holding one list of objects',
291 error_json_list_not_found => 'DataSource: JSON file "%s" has no list of objects called "%s"',
292 warn_empty_result => 'DataSource: fetch_all returned no records for table "%s"',
293 warn_data_normalised => 'DataSource: result from backend was a hashref; converted to arrayref for table "%s"',
294 );
295  
296 # A table name is a bare SQL-safe identifier: starts with a letter or
297 # underscore, followed by zero or more alphanumeric/underscore characters.
298 13 Readonly my $XML_SCAN_BLOCK => 65_536;
299 13 Readonly my $XML_MARKER_OVERLAP => 7; # one byte less than '<!ENTITY'
300 13 Readonly my $TABLE_NAME_RE => qr/\A[A-Za-z_][A-Za-z0-9_]*\z/;
301  
302 # What may go into a MariaDB DSN. A ';' would start another DSN attribute.
303 13 Readonly my $MARIADB_HOST_RE => qr/\A[A-Za-z0-9._-]+\z/;
304 13 Readonly my $MARIADB_DATABASE_RE => qr/\A[A-Za-z0-9_\$-]+\z/;
305 13 Readonly my $MARIADB_PORT_RE => qr/\A[0-9]+\z/;
306 # A page should not hang on a server that has gone away.
307 13 Readonly my $MARIADB_CONNECT_TIMEOUT => 5;
308 # Text::CSV's error_diag code for the plain end of a file.
309 13 Readonly my $CSV_EOF => 2012;
310  
311 # count() remembers each file table's row count until the file changes (see
312 # _count_key): a SQLite table paged in SQL shows its number of pages, and a
313 # COUNT(*) on every page of a big file would cost what the N+1 paging saves.
314 # Emptied when it reaches $COUNT_MEMO_MAX entries.
315 13 my %COUNT_MEMO;
316 13 Readonly my $COUNT_MEMO_MAX => 256;
317  
318 # The extensions D::A looks for before .json; a file with one of them is the
319 # table, and a .json beside it is not read.
320 # JSON Lines: one JSON object a line. Read after .json, as a stream.
321 13 Readonly my @JSON_LINES_EXT => qw(jsonl ndjson);
322 13 Readonly my @NON_JSON_EXT => qw(sql sqlite sqlite3 db psv tsv xls xlsx csv xml);
323 # A .json file over this many bytes that is a list of objects is read as a
324 # stream, one row at a time, instead of as one string and one parsed tree; a
325 # JSON Lines file always is. The chunk is how much is read at a time.
326 13 Readonly my $JSON_STREAM_BYTES => 16 * 1_048_576;
327 13 Readonly my $JSON_CHUNK_BYTES => 1_048_576;
328 # The sort columns D::A accepts; it ignores any other, with a warning.
329 13 Readonly my $DA_SORTABLE_RE => qr/\A[a-zA-Z_][a-zA-Z0-9_.]*\z/;
330  
331 # ---------------------------------------------------------------------------
332 # Protected helpers
333 # ---------------------------------------------------------------------------
334  
335 # _safe_table_name( $name ) -> $string
336 #
337 # The name to suggest for a table whose own name Database::Abstraction refuses:
338 # each illegal character becomes an underscore, and a leading digit gets one.
339 12 ▶sub _safe_table_name {
Subroutine _safe_table_name: called CC=2 SCAR=6.9
340 12 my $name = $_[0];
341 12 $name =~ s/[^A-Za-z0-9_]/_/g;
342 12 ▶ $name = "_$name" unless $name =~ /\A[A-Za-z_]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /\A[A-Za-z_]/ 2 10 12
343 12 return $name;
344 }
345  
346 # _url_label( $url ) -> $string
347 #
348 # Derive a safe, lowercase identifier from a URL for use as the table label.
349 # Takes the last non-empty path component, strips the extension, then replaces
350 # non-alphanumeric characters with underscores. Falls back to the hostname
351 # when the path component is absent or starts with a digit.
352 61 ▶sub _url_label {
Subroutine _url_label: called CC=6 SCAR=17.9
353 61 my $url = $_[0];
354 61 my ($path) = $url =~ m{https?://[^/?#]+(.*)}i;
355 61 ▶ my @parts = grep { length } split m{/}, ($path // '');
Condition100%2/2
$path // ""
l!l
601
MC/DC100%1/1
$path // ""
$path
Truth table100%2/2
A
A= $path
Aresult
11
00
356 61 ▶ my $last = @parts ? $parts[-1] : '';
Branch: 1 branch
BranchTrueFalseTotal
@parts ? : 57 4 61
357 # /s: . must cross \n in case a percent-decoded newline hides inside the URL.
358 61 $last =~ s/[?#].*//s; # strip query / fragment
359 61 $last =~ s/\.[^.]+\z//; # strip file extension (\z: no trailing-\n loophole)
360 61 $last =~ s/[^A-Za-z0-9_]/_/g; # sanitize
361 61 ▶ unless (length $last && $last =~ /\A[A-Za-z_]/) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $last and $last =~ /\A[A-Za-z_]/) 7 54 61
Condition100%3/3
length $last and $last =~ /\A[A-Za-z_]/
!ll&&!rl&&r
5254
MC/DC100%2/2
length $last and $last =~ /\A[A-Za-z_]/
length $last $last =~ /\A[A-Za-z_]/
Truth table100%3/3
A and B
A= length $lastB= $last =~ /\A[A-Za-z_]/
ABresult
0X0
100
111
362 # No usable path component -- fall back to hostname
363 7 my ($host) = $url =~ m{https?://([^/:?#]+)};
364 7 ▶ $last = defined $host ? do { (my $h = $host) =~ s/[^A-Za-z0-9_]/_/g; $h } : 'html';
Branch: 1 branch
BranchTrueFalseTotal
defined $host ? : 6 1 7
365 }
366 # $last is always non-empty here: the unless-block sets it to either
367 # the sanitized hostname (>= 1 char) or the literal 'html'.
368 61 return lc($last);
369 }
370  
371 # _fmt( $key [, @sprintf_args] ) -> $string
372 #
373 # Package-level (not a method) i18n formatter. Looks up $key in %MESSAGES and
374 # applies sprintf if positional arguments are supplied. This function is used
375 # in new() before the object exists; instance methods should use _msg() instead
376 # so that a caller-supplied i18n object can override the built-in strings.
377 153 ▶sub _fmt :Protected {
Subroutine _fmt: called CC=3 SCAR=11.0
378 153 my ($key, @args) = @_;
379 153 ▶ my $tmpl = Database::BI::I18N::text(__PACKAGE__, \%MESSAGES, $key) // "Internal error: unknown message key '$key'";
Condition100%2/2
Database::BI::I18N::text(__PACKAGE__, \%Database::BI::Model::DataSource::MESSAGES, $key) // "Internal error: unknown message key '${key}'"
l!l
1512
MC/DC100%1/1
Database::BI::I18N::text(__PACKAGE__, \%Database::BI::Model::DataSource::MESSAGES, $key) // "Internal error: unknown message key '${key}'"
Database::BI::I18N::text(__PACKAGE__, \%Database::BI::Model::DataSource::MESSAGES, $key)
Truth table100%2/2
A
A= Database::BI::I18N::text(__PACKAGE__, \%Database::BI::Model::DataSource::MESSAGES, $key)
Aresult
11
00
380 153 ▶ return @args ? sprintf($tmpl, @args) : $tmpl;
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 136 17 153
381 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
382  
383 # _msg( $self, $key [, @sprintf_args] ) -> $string
384 #
385 # Instance-level i18n formatter. Delegates to the caller-supplied i18n object
386 # (if any) before falling back to _fmt(). The i18n object must implement
387 # maketext($key, @args).
388 74 ▶sub _msg :Protected {
Subroutine _msg: called CC=2 SCAR=6.9
389 74 my ($self, $key, @args) = @_;
390 74 ▶ if (my $i18n = $self->{_i18n}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $i18n = $self->{"_i18n"}) 2 72 74
391 2 return $i18n->maketext($key, @args);
392 }
393 72 return _fmt($key, @args);
394 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
395  
396 # ---------------------------------------------------------------------------
397 # Constructor
398 # ---------------------------------------------------------------------------
399  
400 =head1 CONSTRUCTOR
401  
402 =head2 new
403  
404 Creates and returns a new C<Database::BI::Model::DataSource> instance.
405  
406 =head3 API SPECIFICATION
407  
408 =head4 INPUT
409  
410 {
411 directory => 'string', # required; local dir, or remote dir when host is set
412 table => 'string', # required; bare file stem (no extension)
413 host => 'string', # optional; "hostname" or "user@hostname" for SFTP access
414 file_ext => 'string', # optional; extension hint when remote file has non-standard suffix (e.g. "log")
415 internal_table => 'string', # optional; a SQLite file's table, or a JSON file's list, to open
416 column_order => \@names, # optional; the order columns() gives, when the backend has none
417 json_flatten => 1, # optional; JSON: an object is a column for each value, not text
418 cache => 'object', # optional; CHI cache object for result caching
419 cache_ttl_url => 'string', # optional; CHI TTL string for URL-backed tables (default "15 min")
420 mariadb => \%settings, # optional; a mariadb_servers entry; needs server and table
421 server => 'string', # the name of that entry
422 i18n => 'object', # optional; must implement maketext($key, @args) for i18n
423 }
424  
425 C<internal_table> selects a named table inside a multi-table SQLite file.
426 When omitted, C<DataSource> auto-selects the first user table whose name
427 matches the filename stem; if no match, it picks the first table found.
428 Supplying a name that does not exist in the file croaks C<error_table_not_found>.
429  
430 A C<.json> file is read as a table when it is a list of objects, an object
431 of objects (each key a row, kept in a column C<id>, or C<key> when the rows
432 have an C<id>), or an object holding lists of objects. Each such list is a
433 table, as a SQLite file's are: C<internal_table> names one, the first in the
434 file is read without it, and C<sqlite_tables> lists them. A cell holding an
435 object or a list is shown as its JSON text, C<true> and C<false> as words and
436 C<null> as an empty cell; the columns are in the order the file first names
437 them. A C<.csv> (or any other format's file) beside it with the same name is
438 the one read. Not JSON croaks C<error_json_invalid>; JSON with no table in
439 it, C<error_json_no_rows>; a list it does not have, C<error_json_list_not_found>.
440  
441 A C<.jsonl> or C<.ndjson> file (JSON Lines: one object a line, blank lines
442 skipped, C<\r\n> and a BOM allowed) is a table with a row for each line,
443 read like a C<.json> list of objects. It is read as a stream: one pass finds
444 the columns and a second writes the copy, so memory holds a row, not the file.
445 A C<.json> list of objects over 16 MiB is streamed the same way. A line that
446 is not JSON croaks C<error_json_invalid>, naming the line; one that is not an
447 object, C<error_json_no_rows>; a list name (C<internal_table>),
448 C<error_json_list_not_found>, because there are none. A C<.json> beside it,
449 or any other format, is the one read.
450  
451 With C<json_flatten> a nested object is not its JSON text but a column for
452 each of its values, named by the path to it (C<address.city>,
453 C<address.geo.lat>), in the order the file names them. A list stays JSON text,
454 an empty object is a cell (C<{}>), and a name that is taken (a key written
455 C<a.b> beside an object C<a> holding C<b>) gets C<_> added, so no value is lost.
456 It is off by default.
457  
458 C<column_order> is for a caller that knows the columns' order better than the
459 backend does. A SQLite backend lists its columns alphabetically, so an
460 extract of an accelerated dataset passes the order its file had. It is used
461 only when the file itself gives no order (SQLite, XML), and is trusted, not
462 checked against the columns the backend has.
463  
464 Accepts a flat key/value list, a hashref, or positional arguments via
465 C<Params::Get>.
466  
467 When C<host> is provided, C<directory> is treated as a path on the remote
468 host and is not checked with C<-d> locally. C<DataSource> downloads the
469 file via SFTP (L<Net::SFTP::Foreign>) to a process-local temporary directory
470 and then processes the local copy. The temporary directory persists for the
471 lifetime of the C<DataSource> object and is cleaned up automatically on
472 destruction.
473  
474 When C<file_ext> is provided together with C<host>, it is used as the first
475 candidate extension when probing the remote host for the file. If the
476 downloaded file does not have a standard extension (one of C<csv>, C<tsv>,
477 C<psv>, C<xlsx>, C<xls>, C<sql>, C<sqlite>, C<sqlite3>, C<db>, C<xml>, C<json>,
478 C<jsonl>, C<ndjson>), the file content is sniffed (SQLite magic bytes, XML preamble, a leading
479 C<[> or C<{> for JSON, or C<{> with whole objects on the first lines for JSON Lines, or first-line
480 field separator) and the file is renamed to the correct standard extension
481 before further processing.
482  
483 =head4 DOMAIN CONSTRAINTS
484  
485 =over 4
486  
487 =item C<directory>
488  
489 Must satisfy C<-d $directory> (must exist and be a directory). An empty
490 string, a non-existent path, or the path to a regular file all produce
491 C<error_directory_missing>.
492  
493 Valid partition: any existing directory path
494 Invalid partition: non-existent path, regular file path, empty string ""
495  
496 =item C<table>
497  
498 The bare file stem (no extension). Characters that are illegal in SQL
499 identifiers - hyphens, dots, spaces, etc. - are silently replaced with
500 underscores before the name is used internally. A stem that starts with a
501 digit is prefixed with C<_>. Only a completely empty string croaks.
502  
503 Valid partition: "sales", "_tmp", "report_2024",
504 "Transactions-2026-09-08" (hyphens sanitized to underscores),
505 "my.data" (dot sanitized), "1sales" (prefixed to "_1sales")
506 Invalid partition: "" (empty string)
507 Boundary values: "a" (length-1 letter, valid), "_" (length-1 underscore,
508 valid), "" (empty string, croaks error_table_name_invalid)
509  
510 =back
511  
512 =head4 OUTPUT
513  
514 Returns C<$self> (a blessed hashref). Croaks on invalid arguments.
515  
516 =head3 MESSAGES
517  
518 error_directory_required -- "directory" argument was not supplied
519 error_table_required -- "table" argument was not supplied
520 error_directory_missing -- supplied directory does not exist / is unreadable
521 error_table_name_invalid -- table name contains illegal characters or is empty
522 error_table_name_unsafe -- internal_table names a SQLite table whose own name
523 has illegal characters; says what else to open and
524 how to rename it
525 error_no_usable_tables -- every table in a SQLite file has such a name
526 error_xml_entities -- an .xml file declares an entity (<!ENTITY), or is
527 not in a form that can be checked for one
528 error_json_invalid -- a .json file is not valid JSON
529 error_json_no_rows -- a .json file holds no list of objects, object of
530 objects or object holding such a list
531 error_json_list_not_found -- internal_table names no list in a .json file
532 error_no_safe_id -- no column in the file has a safe SQL identifier name;
533 rename at least one column header to an alphanumeric name
534 error_backend_init -- backend initialisation failed; sub-cases:
535 * Net::SFTP::Foreign is not installed
536 * could not connect to <host> via SFTP
537 * could not fetch any supported file from <host>:<dir>/<stem>.*
538 * Database::Abstraction subclass could not be instantiated
539 error_no_tables -- SQLite file opened successfully but contains no user-defined tables
540 error_unsupported_db -- .db file has BerkeleyDB magic bytes but DB_File could not open it
541 (file likely uses a newer BDB format than the installed libdb supports)
542 error_fetch_failed -- fetch_all raised an exception (wraps the underlying DBI/D::A error)
543 error_url_invalid -- URL passed to the url=> constructor path does not begin
544 with http:// or https://
545 error_url_fetch -- the backend for a URL could not be set up; a page
546 that cannot be fetched is error_fetch_failed, from the read
547  
548 =cut
549  
550 2347 ▶sub new {
Subroutine new: called CC=13 SCAR=25.7
Pod documented
551 # Strategy: normalise the argument list with Params::Get so callers may
552 # pass a hashref or a flat list interchangeably, then validate strictly
553 # with Params::Validate before touching any value.
554 # When a "url" key is present, dispatch to the URL/HTML-table path instead.
555 2347 my $class = shift;
556 # Opening a file tries several drivers in turn; what they leave in $@ and $! is
557 # of no interest to a caller, who may be holding its own.
558 2347 local ($@, $!);
559 2347 local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows
560 2347 ▶ my $raw = Params::Get::get_params(undef, \@_) // {};
Condition100%2/2
Params::Get::get_params(undef, \@_) // {}
l!l
23452
MC/DC100%1/1
Params::Get::get_params(undef, \@_) // {}
Params::Get::get_params(undef, \@_)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
561 2347 ▶ return $class->_new_from_url($raw) if exists $raw->{url};
Branch: 1 branch
BranchTrueFalseTotal
if exists $raw->{"url"} 52 2295 2347
562 2295 ▶ return $class->_new_from_redis($raw) if exists $raw->{redis};
Branch: 1 branch
BranchTrueFalseTotal
if exists $raw->{"redis"} 1 2294 2295
563 2294 ▶ return $class->_new_from_mariadb($raw) if exists $raw->{mariadb};
Branch: 1 branch
BranchTrueFalseTotal
if exists $raw->{"mariadb"} 5 2289 2294
564 2289 ▶ croak _fmt('error_table_required') unless defined $raw->{table};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw->{"table"} 4 2285 2289
565  
566 2285 my $args = validate_strict(
567 schema => {
568 directory => { type => 'string' },
569 table => { type => 'string' },
570 host => { type => 'string', optional => 1, default => undef },
571 file_ext => { type => 'string', optional => 1, default => undef },
572 internal_table => { type => 'string', optional => 1, default => undef },
573 column_order => { type => 'arrayref', optional => 1, default => undef },
574 json_flatten => { type => 'boolean', optional => 1, default => 0 },
575 i18n => { type => 'object', optional => 1, default => undef, can => 'maketext' },
576 cache => { type => 'object', optional => 1, default => undef },
577 cache_ttl_url => { type => 'string', optional => 1, default => '15 min' },
578 },
579 input => $raw,
580 );
581  
582 # For remote files (host is set), the directory is on the remote host and
583 # cannot be stat()d locally. Only check local existence when no host is given.
584 croak _fmt('error_directory_missing', $args->{directory})
585 2284 ▶ unless defined $args->{host} || -d $args->{directory};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args->{"host"} or -d $args->{"directory"} 11 2273 2284
Condition100%3/3
defined $args->{"host"} or -d $args->{"directory"}
l!l&&r!l&&!r
14225911
MC/DC100%2/2
defined $args->{"host"} or -d $args->{"directory"}
defined $args->{"host"} -d $args->{"directory"}
Truth table100%3/3
A or B
A= defined $args->{"host"}B= -d $args->{"directory"}
ABresult
1X1
011
000
586  
587 # Reject path-traversal characters first: '/', '\', and NUL are the only
588 # characters that could let _raw_table escape the intended directory when
589 # D::A constructs "$dir/$dbname.$ext". Everything else is either safe as a
590 # filename component or will be sanitized below.
591 croak _fmt('error_table_name_invalid', $args->{table})
592 2273 ▶ if !length($args->{table}) || $args->{table} =~ m{[/\\\x00]};
Branch: 1 branch
BranchTrueFalseTotal
if not length $args->{"table"} or $args->{"table"} =~ m[[/\\\x00]] 6 2267 2273
Condition100%3/3
not length $args->{"table"} or $args->{"table"} =~ m[[/\\\x00]]
l!l&&r!l&&!r
152267
MC/DC100%2/2
not length $args->{"table"} or $args->{"table"} =~ m[[/\\\x00]]
not length $args->{"table"} $args->{"table"} =~ m[[/\\\x00]]
Truth table100%3/3
not(A) or B
A= not length $args->{"table"}B= $args->{"table"} =~ m[[/\\\x00]]
ABresult
1X1
011
000
593  
594 # Silently sanitize table names derived from file stems: replace characters
595 # that are illegal in SQL identifiers (hyphens, dots, spaces, etc.) with
596 # underscores. A leading digit is prefixed with '_'. The original name is
597 # kept in _raw_table for filesystem lookup (dbname) so the actual file is
598 # still found; the sanitized name is used only as the internal D::A
599 # identifier and ephemeral package name.
600 2267 my $raw_table = $args->{table};
601 2267 (my $safe_table = $raw_table) =~ s/[^A-Za-z0-9_]/_/g;
602 2267 ▶ $safe_table = '_' . $safe_table if $safe_table =~ /\A[0-9]/;
Branch: 1 branch
BranchTrueFalseTotal
if $safe_table =~ /\A[0-9]/ 5 2262 2267
603  
604 2267 ▶ croak _fmt('error_table_name_invalid', $raw_table)
Branch: 1 branch
BranchTrueFalseTotal
unless $safe_table =~ /$TABLE_NAME_RE/ 0 2267 2267
605 unless $safe_table =~ $TABLE_NAME_RE;
606  
607 my $self = bless {
608 _directory => $args->{directory},
609 _table => $safe_table,
610 _raw_table => $raw_table,
611 _host => $args->{host},
612 _file_ext => $args->{file_ext},
613 _internal_table => $args->{internal_table},
614 _column_order => $args->{column_order},
615 _json_flatten => $args->{json_flatten} ? 1 : 0,
616 _i18n => $args->{i18n},
617 _cache => $args->{cache},
618 _cache_ttl_url => $args->{cache_ttl_url},
619 2267 ▶ _db => undef,
Branch: 1 branch
BranchTrueFalseTotal
$args->{'json_flatten'} ? : 0 2267 2267
620 }, $class;
621  
622 2267 $self->_init_backend();
623 2237 return $self;
624  
625 }
626  
627 # _new_from_url( $class, \%raw_params ) -> $self
628 #
629 # Alternate constructor path for URL-backed HTML tables.
630 # Validates the URL scheme, derives a display label from the URL path,
631 # then calls _init_url_backend to build the D::A in-memory table.
632 # Entry: $raw->{url} must be an http:// or https:// URL.
633 # $raw->{html_table_index} (optional, default 0): zero-based table index.
634 # $raw->{private_hosts} (optional): names that may resolve to private
635 # addresses (Database::BI::SafeUA).
636 # $raw->{i18n} (optional): Locale::Maketext-compatible object.
637 # Exit: Returns $self. Croaks on invalid URL scheme or backend init failure.
638 # Side Effects: None: the URL is fetched by the first read.
639 52 ▶sub _new_from_url :Protected {
Subroutine _new_from_url: called CC=6 SCAR=17.9
640 52 my ($class, $raw) = @_;
641  
642 52 ▶ my $url = $raw->{url} // croak _fmt('error_url_invalid', '');
Condition50%1/2
$raw->{"url"} // croak(_fmt("error_url_invalid", ""))
l!l
520
MC/DC0%0/1
$raw->{"url"} // croak(_fmt("error_url_invalid", ""))
$raw->{"url"}
Truth table50%1/2
A
A= $raw->{"url"}
Aresult
11
00
643 52 ▶ croak _fmt('error_url_invalid', $url)
Branch: 1 branch
BranchTrueFalseTotal
unless $url =~ m[\Ahttps?://]i 5 47 52
644 unless $url =~ m{\Ahttps?://}i;
645  
646 47 ▶ my $table_idx = $raw->{html_table_index} // 0;
Condition100%2/2
$raw->{"html_table_index"} // 0
l!l
2621
MC/DC100%1/1
$raw->{"html_table_index"} // 0
$raw->{"html_table_index"}
Truth table100%2/2
A
A= $raw->{"html_table_index"}
Aresult
11
00
647 my $self = bless {
648 _url => $url,
649 _table => _url_label($url),
650 _i18n => $raw->{i18n},
651 _cache => $raw->{cache},
652 _cache_ttl_url => $raw->{cache_ttl_url} // '15 min',
653 _html_table_index => $table_idx,
654 47 ▶ _private_hosts => ref($raw->{private_hosts}) eq 'ARRAY' ? $raw->{private_hosts} : [],
Branch: 1 branch
BranchTrueFalseTotal
ref $raw->{'private_hosts'} eq 'ARRAY' ? : 46 1 47
Condition100%2/2
$raw->{"cache_ttl_url"} // "15 min"
l!l
461
MC/DC100%1/1
$raw->{"cache_ttl_url"} // "15 min"
$raw->{"cache_ttl_url"}
Truth table100%2/2
A
A= $raw->{"cache_ttl_url"}
Aresult
11
00
655 _id_col => undef,
656 _columns => undef,
657 _db => undef,
658 }, $class;
659  
660 47 $self->_init_url_backend($table_idx);
661 46 return $self;
662 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
663  
664 # _init_url_backend( $self, $table_index ) -> void
665 #
666 # Purpose: Construct the Database::Abstraction backend for URL/HTML-table mode.
667 # No request is made here. On the first read D::A fetches the page via
668 # LWP::UserAgent, parses it with
669 # HTML::TableExtract, and stores all rows (including headers from row 0)
670 # as an in-memory arrayref. Column order is not recoverable after
671 # construction (hash keys lose order), so _columns stays undef and
672 # _get_columns in the controller falls back to alphabetical sorting.
673 # Entry: $self->{_url} is a valid http(s) URL; $table_index is a non-negative int.
674 # Exit: Sets $self->{_db}. Croaks if the backend object cannot be built; a
675 # failure to fetch or parse the page comes from the first read instead.
676 49 ▶sub _init_url_backend :Protected {
Subroutine _init_url_backend: called CC=3 SCAR=11.0
677 49 my ($self, $table_index) = @_;
678 49 my $url = $self->{_url};
679  
680 49 require Database::Abstraction;
681  
682 # Reuse a single generic package for all URL-backed instances.
683 # The package name is irrelevant for the URL code path -- D::A branches on
684 # the presence of $self->{'url'}, not on the class name.
685 49 my $pkg = 'Database::BI::_DB::HtmlUrl';
686 {
687 13 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
688 49 ▶ push @{"${pkg}::ISA"}, 'Database::Abstraction'
Branch: 1 branch
BranchTrueFalseTotal
unless $pkg->isa("Database::Abstraction") 4 45 49
689 unless $pkg->isa('Database::Abstraction');
690 }
691  
692 # D::A fetches with the ua it is given: one that will not reach this
693 # machine or a private network, however the URL or its DNS is dressed up.
694 49 require Database::BI::SafeUA;
695 49 my $db = eval {
696 $pkg->new({
697 url => $url,
698 html_table_index => $table_index,
699 no_entry => 1,
700 49 ua => Database::BI::SafeUA->new(private_hosts => $self->{_private_hosts}),
701 })
702 };
703 49 ▶ croak $self->_msg('error_url_fetch', $url, $@) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 2 47 49
704  
705 47 $self->{_db} = $db;
706 47 return;
707 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
708  
709 # _new_from_redis( $class, \%raw_params ) -> $self
710 #
711 # Alternate constructor path for Redis-backed tables.
712 # Entry: $raw->{redis} must be a redis:// URL.
713 # $raw->{table} (required): table name -- becomes the Redis key prefix
714 # (keys in Redis must follow the pattern tablename:*).
715 # $raw->{i18n} (optional): Locale::Maketext-compatible object.
716 # Exit: Returns $self. Croaks on invalid URL or table name.
717 11 ▶sub _new_from_redis :Protected {
Subroutine _new_from_redis: called CC=9 SCAR=22.0
718 11 my ($class, $raw) = @_;
719  
720 11 ▶ my $redis_url = $raw->{redis} // croak _fmt('error_redis_invalid', '');
Condition100%2/2
$raw->{"redis"} // croak(_fmt("error_redis_invalid", ""))
l!l
101
MC/DC100%1/1
$raw->{"redis"} // croak(_fmt("error_redis_invalid", ""))
$raw->{"redis"}
Truth table100%2/2
A
A= $raw->{"redis"}
Aresult
11
00
721 10 ▶ croak _fmt('error_redis_invalid', $redis_url)
Branch: 1 branch
BranchTrueFalseTotal
unless $redis_url =~ m[\Aredis://]i 3 7 10
722 unless $redis_url =~ m{\Aredis://}i;
723  
724 7 ▶ my $table = $raw->{table} // croak _fmt('error_table_required');
Condition100%2/2
$raw->{"table"} // croak(_fmt("error_table_required"))
l!l
61
MC/DC100%1/1
$raw->{"table"} // croak(_fmt("error_table_required"))
$raw->{"table"}
Truth table100%2/2
A
A= $raw->{"table"}
Aresult
11
00
725 6 ▶ croak _fmt('error_table_name_invalid', $table)
Branch: 1 branch
BranchTrueFalseTotal
if not length $table or $table =~ m[[/\\\x00]] 4 2 6
Condition100%3/3
not length $table or $table =~ m[[/\\\x00]]
l!l&&r!l&&!r
132
MC/DC100%2/2
not length $table or $table =~ m[[/\\\x00]]
not length $table $table =~ m[[/\\\x00]]
Truth table100%3/3
not(A) or B
A= not length $tableB= $table =~ m[[/\\\x00]]
ABresult
1X1
011
000
726 if !length($table) || $table =~ m{[/\\\x00]};
727  
728 2 my $raw_table = $table;
729 2 (my $safe_table = $raw_table) =~ s/[^A-Za-z0-9_]/_/g;
730 2 ▶ $safe_table = '_' . $safe_table if $safe_table =~ /\A[0-9]/;
Branch: 1 branch
BranchTrueFalseTotal
if $safe_table =~ /\A[0-9]/ 1 1 2
731 2 ▶ croak _fmt('error_table_name_invalid', $raw_table)
Branch: 1 branch
BranchTrueFalseTotal
unless $safe_table =~ /$TABLE_NAME_RE/ 0 2 2
732 unless $safe_table =~ $TABLE_NAME_RE;
733  
734 my $self = bless {
735 _table => $safe_table,
736 _raw_table => $raw_table,
737 _redis_url => $redis_url,
738 _i18n => $raw->{i18n},
739 _cache => $raw->{cache},
740 2 ▶ _cache_ttl_url => $raw->{cache_ttl_url} // '15 min',
Condition50%1/2
$raw->{"cache_ttl_url"} // "15 min"
l!l
02
MC/DC0%0/1
$raw->{"cache_ttl_url"} // "15 min"
$raw->{"cache_ttl_url"}
Truth table50%1/2
A
A= $raw->{"cache_ttl_url"}
Aresult
11
00
741 _id_col => 'entry',
742 _columns => undef,
743 _db => undef,
744 }, $class;
745  
746 2 $self->_init_redis_backend();
747 2 return $self;
748 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
749  
750 # _init_redis_backend( $self ) -> void
751 #
752 # Purpose: Construct the Database::Abstraction backend for Redis mode.
753 # D::A connects to the Redis server lazily (on first data access).
754 # We pass redis_key => $raw_table so D::A uses the original key name
755 # (which may contain colons, hyphens, etc.) for Redis lookups, while
756 # the sanitized $table is used only as the Perl package-name suffix.
757 # no_entry => 1 requests array-style rows (no id-keyed hash).
758 # Entry: $self->{_redis_url} is a valid redis:// URL.
759 # $self->{_table} is a safe SQL identifier (sanitized key name).
760 # $self->{_raw_table} is the original Redis key name.
761 # Exit: Sets $self->{_db}. Croaks when D::A construction fails.
762 2 ▶sub _init_redis_backend :Protected {
Subroutine _init_redis_backend: called CC=3 SCAR=11.0
763 2 my $self = shift;
764 2 my $table = $self->{_table};
765  
766 2 require Database::Abstraction;
767  
768 2 my $pkg = 'Database::BI::_DB::' . ucfirst($table);
769 {
770 13 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
771 2 ▶ push @{"${pkg}::ISA"}, 'Database::Abstraction'
Branch: 1 branch
BranchTrueFalseTotal
unless $pkg->isa("Database::Abstraction") 1 1 2
772 unless $pkg->isa('Database::Abstraction');
773 }
774  
775 2 my $db = eval { $pkg->new(
776 database => $self->{_redis_url},
777 table => $table,
778 redis_key => $self->{_raw_table},
779 2 ) };
780 2 ▶ croak $self->_msg('error_backend_init', $table, $@) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 1 2
781  
782 1 $self->{_db} = $db;
783 1 return;
784 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
785  
786 # _mariadb_dsn( $server, \%settings ) -> ($dsn, $username, $password)
787 #
788 # Purpose: What connects to one entry of the mariadb_servers configuration.
789 # Nothing is connected here: Database::Join::Catalog does that, and
790 # Database::Abstraction for the rows. An error names the server; it
791 # never holds the password.
792 # Entry: $server is the entry's name, for messages. \%settings holds database
793 # and optionally host, port, username and password.
794 # Exit: The data source and credentials. Croaks on settings that are not
795 # valid, or when no MariaDB or MySQL driver is installed.
796 26 ▶sub _mariadb_dsn {
Subroutine _mariadb_dsn: called CC=10 SCAR=23.0
797 26 my ($server, $settings) = @_;
798  
799 26 ▶ croak _fmt('error_mariadb_unknown_server', $server) unless ref $settings eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $settings eq "HASH" 3 23 26
800  
801 23 ▶ my $database = $settings->{database} // '';
Condition100%2/2
$settings->{"database"} // ""
l!l
221
MC/DC100%1/1
$settings->{"database"} // ""
$settings->{"database"}
Truth table100%2/2
A
A= $settings->{"database"}
Aresult
11
00
802 23 ▶ my $host = $settings->{host} // 'localhost';
Condition100%2/2
$settings->{"host"} // "localhost"
l!l
221
MC/DC100%1/1
$settings->{"host"} // "localhost"
$settings->{"host"}
Truth table100%2/2
A
A= $settings->{"host"}
Aresult
11
00
803 23 my $port = $settings->{port};
804 23 ▶ croak _fmt('error_mariadb_settings', $server, 'database') unless $database =~ $MARIADB_DATABASE_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $database =~ /$MARIADB_DATABASE_RE/ 4 19 23
805 19 ▶ croak _fmt('error_mariadb_settings', $server, 'host') unless $host =~ $MARIADB_HOST_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $host =~ /$MARIADB_HOST_RE/ 2 17 19
806 17 ▶ croak _fmt('error_mariadb_settings', $server, 'port') if defined $port && $port !~ $MARIADB_PORT_RE;
Branch: 1 branch
BranchTrueFalseTotal
if defined $port and not $port =~ /$MARIADB_PORT_RE/ 2 15 17
Condition66%2/3
defined $port and not $port =~ /$MARIADB_PORT_RE/
!ll&&!rl&&r
1502
MC/DC50%1/2
defined $port and not $port =~ /$MARIADB_PORT_RE/
defined $port not $port =~ /$MARIADB_PORT_RE/
Truth table66%2/3
A and not(B)
A= defined $portB= not $port =~ /$MARIADB_PORT_RE/
ABresult
0X0
100
111
807  
808 # The driver is optional, so it is looked for only now.
809 15 require Database::Join::Catalog;
810 15 my $driver = Database::Join::Catalog->available_driver(qw(MariaDB mysql));
811 15 ▶ croak _fmt('error_mariadb_no_driver', $server) unless defined $driver;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $driver 2 13 15
812  
813 13 ▶ my $dsn = "dbi:${driver}:database=$database;host=$host"
Branch: 1 branch
BranchTrueFalseTotal
defined $port ? : 0 13 13
814 . (defined $port ? ";port=$port" : '')
815 . ';' . lc($driver) . "_connect_timeout=$MARIADB_CONNECT_TIMEOUT";
816 13 return ($dsn, @{$settings}{qw(username password)});
817 }
818  
819 # _new_from_mariadb( $class, \%raw_params ) -> $self
820 #
821 # Alternate constructor path for a table on a MariaDB or MySQL server.
822 # Entry: $raw->{mariadb} is the server's entry from mariadb_servers.
823 # $raw->{server} is that entry's name; $raw->{table} is the table.
824 # Exit: Returns $self. Croaks when the server or the table cannot be reached,
825 # so a caller finds out here and not from the first read.
826 # Note: Rows are not cached: a table's contents can change with nothing to say
827 # so, which is what a file's mtime says for a file.
828 14 ▶sub _new_from_mariadb :Protected {
Subroutine _new_from_mariadb: called CC=14 SCAR=26.5
829 14 my ($class, $raw) = @_;
830  
831 14 ▶ my $table = $raw->{table} // croak _fmt('error_table_required');
Condition100%2/2
$raw->{"table"} // croak(_fmt("error_table_required"))
l!l
131
MC/DC100%1/1
$raw->{"table"} // croak(_fmt("error_table_required"))
$raw->{"table"}
Truth table100%2/2
A
A= $raw->{"table"}
Aresult
11
00
832 13 ▶ croak _fmt('error_table_name_invalid', $table) unless $table =~ $TABLE_NAME_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /$TABLE_NAME_RE/ 1 12 13
833 12 ▶ my $server = $raw->{server} // '';
Condition50%1/2
$raw->{"server"} // ""
l!l
120
MC/DC0%0/1
$raw->{"server"} // ""
$raw->{"server"}
Truth table50%1/2
A
A= $raw->{"server"}
Aresult
11
00
834 12 ▶ croak _fmt('error_mariadb_unknown_server', $server) unless $server =~ $TABLE_NAME_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $server =~ /$TABLE_NAME_RE/ 1 11 12
835  
836 11 my ($dsn, $username, $password) = _mariadb_dsn($server, $raw->{mariadb});
837  
838 # D::A's columns() is alphabetical; table_info gives the declared order.
839 8 my $info = eval {
840 8 Database::Join::Catalog->table_info(dsn => $dsn, username => $username, password => $password, table => $table);
841 };
842 8 ▶ unless ($info) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($info) 3 5 8
843 3 my $err = $@;
844 3 ▶ croak _fmt('error_mariadb_table', $table, $server, "$err")
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($err) and $err->can("stage") and $err->stage eq "query" 2 1 3
Condition50%3/6
builtin::blessed($err) and $err->can("stage") and $err->stage eq "query"
!ll&&!rl&&r
012
builtin::blessed($err) and $err->can("stage")
!ll&&!rl&&r
003
MC/DC33%1/3
builtin::blessed($err) and $err->can("stage") and $err->stage eq "query"
builtin::blessed($err) $err->can("stage") $err->stage eq "query"
Truth table50%2/4
A and B and C
A= builtin::blessed($err)B= $err->can("stage")C= $err->stage eq "query"
ABCresult
0XX0
10X0
1100
1111
845 if blessed($err) && $err->can('stage') && $err->stage eq 'query';
846 1 croak _fmt('error_mariadb_connect', $server, "$err");
847 }
848 5 my $columns = $info->{columns};
849 5 my @primary = @{ $info->{primary_key} };
850  
851 # Two servers may each have an "orders".
852 5 my $pkg = 'Database::BI::_DB::Mariadb_' . $server . '_' . $table;
853 {
854 13 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
855 5 ▶ push @{"${pkg}::ISA"}, 'Database::Abstraction'
Branch: 1 branch
BranchTrueFalseTotal
unless $pkg->isa("Database::Abstraction") 1 4 5
856 unless $pkg->isa('Database::Abstraction');
857 }
858 5 require Database::Abstraction;
859 5 my $db = eval { $pkg->new(
860 dsn => $dsn,
861 username => $username,
862 password => $password,
863 table => $table,
864 no_entry => 1,
865 ) };
866 5 ▶ croak _fmt('error_backend_init', $table, $@) unless $db;
Branch: 1 branch
BranchTrueFalseTotal
unless $db 1 4 5
867  
868 return bless {
869 _table => $table,
870 _raw_table => $table,
871 _mariadb => $server,
872 # Pages taken with LIMIT need an order that does not change between them.
873 _order_col => (@primary == 1 && $primary[0] =~ $TABLE_NAME_RE) ? $primary[0] : undef,
874 _id_col => $primary[0] // $columns->[0],
875 _columns => $columns,
876 _i18n => $raw->{i18n},
877 4 ▶ _db => $db,
Branch: 1 branch
BranchTrueFalseTotal
@primary == 1 && $primary[0] =~ /$TABLE_NAME_RE/ ? : 1 3 4
Condition83%5/6
@primary == 1 and $primary[0] =~ /$TABLE_NAME_RE/
!ll&&!rl&&r
211
$primary[0] // $columns->[0]
l!l&&r!l&&!r
310
MC/DC100%2/2
@primary == 1 and $primary[0] =~ /$TABLE_NAME_RE/
@primary == 1 $primary[0] =~ /$TABLE_NAME_RE/
MC/DC0%0/2
$primary[0] // $columns->[0]
$primary[0] $columns->[0]
Truth table100%3/3
A and B
A= @primary == 1B= $primary[0] =~ /$TABLE_NAME_RE/
ABresult
0X0
100
111
Truth table66%2/3
A // B
A= $primary[0]B= $columns->[0]
ABresult
1X1
011
000
878 }, $class;
879 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
880  
881 # ---------------------------------------------------------------------------
882 # Protected initialisation
883 # ---------------------------------------------------------------------------
884  
885 # _csv_escape_char($path) -> '"' | '\\'
886 #
887 # Purpose: The escape character a delimited file is written with, chosen as
888 # Database::Abstraction (>= 0.56) chooses it, so this module parses a
889 # file as D::A will.
890 # Entry: $path names a CSV, TSV or PSV file.
891 # Exit: '\\' when the file holds a backslash before a quote anywhere (or
892 # will not open); else '"' when it holds two quotes in a row (RFC
893 # 4180's "Adeste ""Overture"""); else '\\'.
894 1860 ▶sub _csv_escape_char {
Subroutine _csv_escape_char: called CC=6 SCAR=17.9
895 1860 my ($path) = @_;
896 1860 local ($@, $!);
897 1860 local $/ = "\n";
898  
899 1860 my $fh;
900 13 ▶ { no autodie 'open'; open($fh, '<:raw', $path) or return '\\' }
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<:raw", $path or return "\\" 1859 1 1860
901 1859 my $doubled = 0;
902 1859 ▶ while (my $line = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 11090 1858 12948
903 11090 ▶ if ($line =~ /\\"/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\\"/) 1 11089 11090
904 1 close $fh;
905 1 return '\\';
906 }
907 11089 ▶ $doubled ||= ($line =~ /""/);
Condition100%3/3
$doubled ||= $line =~ /""/
l!l&&r!l&&!r
8211079
MC/DC100%2/2
$doubled ||= $line =~ /""/
$doubled $line =~ /""/
Truth table100%3/3
A ||= B
A= $doubledB= $line =~ /""/
ABresult
1X1
011
000
908 }
909 1858 close $fh;
910 1858 ▶ return $doubled ? '"' : '\\';
Branch: 1 branch
BranchTrueFalseTotal
$doubled ? : 2 1856 1858
911 }
912  
913 # _best_id_column($fh, $sep, \@header_fields, $escape) -> $column_name | undef
914 #
915 # Purpose: The column Database::Abstraction should key rows on.
916 # Entry: $fh is open just after the header line; @header_fields is the header
917 # split and stripped, in file order (empty names included, so indexes
918 # match the data).
919 # Exit: The safe-identifier column with the fewest rows D::A would drop
920 # (an empty cell, or one starting with '#', which D::A reads as a
921 # comment), the earliest on a tie; undef when no header name is safe.
922 # Reads $fh to its end. The file is parsed as D::A's slurp parses it
923 # (with $escape, from _csv_escape_char), or a row like "Joe\"s Bar"
924 # would end the count there; a line that still will not parse is
925 # skipped, not the end.
926 1875 ▶sub _best_id_column {
Subroutine _best_id_column: called CC=15 SCAR=27.3
927 1875 my ($fh, $sep, $fields, $escape) = @_;
928  
929 1875 ▶ my @safe = grep { defined($fields->[$_]) && $fields->[$_] =~ $TABLE_NAME_RE } 0 .. $#{$fields};
Condition100%3/3
defined $fields->[$_] && $fields->[$_] =~ /$TABLE_NAME_RE/
!ll&&!rl&&r
112110877
MC/DC100%2/2
defined $fields->[$_] && $fields->[$_] =~ /$TABLE_NAME_RE/
defined $fields->[$_] $fields->[$_] =~ /$TABLE_NAME_RE/
Truth table100%3/3
A && B
A= defined $fields->[$_]B= $fields->[$_] =~ /$TABLE_NAME_RE/
ABresult
0X0
100
111
930 1875 ▶ return undef unless @safe;
Branch: 1 branch
BranchTrueFalseTotal
unless @safe 34 1841 1875
931  
932 1841 require Text::CSV;
933 1841 ▶ my $csv = Text::CSV->new({
Condition100%2/2
$escape // "\\"
l!l
180734
MC/DC100%1/1
$escape // "\\"
$escape
Truth table100%2/2
A
A= $escape
Aresult
11
00
934 binary => 1, sep_char => $sep, escape_char => $escape // '\\',
935 allow_loose_quotes => 1, allow_whitespace => 1,
936 });
937 1841 my %dropped = map { $_ => 0 } @safe;
938 1841 while (1) {
939 61073 my $at = tell($fh);
940 61073 my $row = $csv->getline($fh);
941 61072 ▶ if (!$row) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($row) 1840 59232 61072
942 # The end, or a line that will not parse: go on from the next one,
943 # unless nothing was read, which would loop for ever.
944 1840 ▶ last if $csv->eof() || eof($fh) || tell($fh) == $at;
Branch: 1 branch
BranchTrueFalseTotal
if $csv->eof or eof $fh or tell $fh == $at 1840 0 1840
Condition66%4/6
$csv->eof or eof $fh or tell $fh == $at
l!l&&r!l&&!r
183910
$csv->eof or eof $fh
l!l&&r!l&&!r
183901
MC/DC0%0/3
$csv->eof or eof $fh or tell $fh == $at
$csv->eof eof $fh tell $fh == $at
Truth table50%2/4
A or B or C
A= $csv->eofB= eof $fhC= tell $fh == $at
ABCresult
1XX1
01X1
0011
0000
945 0 next;
946 }
947 59232 ▶ next unless grep { defined($_) && length($_) } @{$row}; # a blank line is not a row
Branch: 1 branch
BranchTrueFalseTotal
unless grep {defined $_ and length $_;} @{$row;} 7 59225 59232
Condition66%2/3
defined $_ && length $_
!ll&&!rl&&r
05581699571
MC/DC50%1/2
defined $_ && length $_
defined $_ length $_
Truth table66%2/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
948 59225 for my $i (@safe) {
949 155182 my $cell = $row->[$i];
950 155182 ▶ $dropped{$i}++ if !defined($cell) || $cell !~ /\S/ || $cell =~ /\A\s*#/;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $cell && $cell =~ /\S/ or $cell =~ /\A\s*#/ 55820 99362 155182
Condition100%6/6
not defined $cell && $cell =~ /\S/ or $cell =~ /\A\s*#/
l!l&&r!l&&!r
55812899362
defined $cell && $cell =~ /\S/
!ll&&!rl&&r
55580799370
MC/DC100%3/3
not defined $cell && $cell =~ /\S/ or $cell =~ /\A\s*#/
defined $cell $cell =~ /\S/ $cell =~ /\A\s*#/
Truth table100%4/4
not(A && B) or C
A= defined $cellB= $cell =~ /\S/C= $cell =~ /\A\s*#/
ABCresult
0XX1
10X1
1111
1100
951 }
952 }
953  
954 1840 ▶ my ($best) = sort { $dropped{$a} <=> $dropped{$b} || $a <=> $b } @safe;
Condition66%2/3
$dropped{$a} <=> $dropped{$b} || $a <=> $b
l!l&&r!l&&!r
286139280
MC/DC0%0/2
$dropped{$a} <=> $dropped{$b} || $a <=> $b
$dropped{$a} <=> $dropped{$b} $a <=> $b
Truth table66%2/3
A || B
A= $dropped{$a} <=> $dropped{$b}B= $a <=> $b
ABresult
1X1
011
000
955 1840 return $fields->[$best];
956 }
957  
958 # _detect_file_info( $dir, $table ) -> \%info
959 #
960 # Peek at the first header line of a CSV, TSV or PSV file and return a hashref:
961 # sep_char => field separator character (',' or '|')
962 # id => first column name (used as Database::Abstraction's id key)
963 # columns => arrayref of all column names in file order
964 #
965 # Two non-obvious defaults in Database::Abstraction make this necessary:
966 # 1. sep_char defaults to '!' -- so a plain CSV is read as one giant field
967 # per row, producing a single comma-joined string instead of columns.
968 # 2. id defaults to 'entry' -- the slurp filter greps on that column; if it
969 # doesn't exist every row is silently discarded.
970 # Returns an empty hashref for non-CSV/TSV/PSV/XLSX/SQLite formats (XML, etc.).
971 # For SQLite/.db files that can be opened, returns { sqlite_tables => [...] }.
972 2282 ▶sub _detect_file_info :Protected {
Subroutine _detect_file_info: called CC=60 SCAR=53.9
973 2282 my ($dir, $table, $want, $flatten) = @_;
974  
975 # XLSX: D::A reads the rows. This parse is for what D::A cannot say: an
976 # empty workbook makes it croak, and its columns() is alphabetical, not the
977 # order of the sheet.
978 {
979 2282 my $path = File::Spec->catfile($dir, "$table.xlsx");
980 2282 ▶ if (-r $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $path) 2 2280 2282
981 0 my $ok = eval { require Spreadsheet::ParseXLSX; 1 };
982 2 ▶ if ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) 0 2 2
983 0 my $parser = Spreadsheet::ParseXLSX->new;
984 0 my $wb = $parser->parse($path);
985 # The sheet D::A will read: the one named after the table, or
986 # failing that the first.
987 0 my $sheet_name = _safe_table_name($table);
988 0 ▶ my ($ws) = $wb ? grep { $_->get_name eq $sheet_name } $wb->worksheets : ();
Branch: 1 branch
BranchTrueFalseTotal
$wb ? : 0 0 0
989 0 ▶ $ws //= $wb ? $wb->worksheet(0) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$wb ? : 0 0 0
Condition0%0/3
$ws //= $wb ? $wb->worksheet(0) : undef
l!l&&r!l&&!r
000
MC/DC0%0/2
$ws //= $wb ? $wb->worksheet(0) : undef
$ws $wb ? $wb->worksheet(0) : undef
Truth table0%0/3
A //= B
A= $wsB= $wb ? $wb->worksheet(0) : undef
ABresult
1X1
011
000
990  
991 0 ▶ unless ($ws) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ws) 0 0 0
992 # Empty workbook or parse failure: sentinel so _init_backend
993 # skips D::A (which would fail with "(no error string)").
994 0 return { _file_is_empty => 1, file_size => -s $path };
995 }
996  
997 0 my ($rmin, $rmax) = $ws->row_range;
998 0 my ($cmin, $cmax) = $ws->col_range;
999  
1000 # No rows at all (blank worksheet).
1001 0 ▶ return { _file_is_empty => 1, file_size => -s $path }
Branch: 1 branch
BranchTrueFalseTotal
if $rmax < $rmin 0 0 0
1002 if $rmax < $rmin;
1003  
1004 # Row 0 = column headers, spelt as D::A will key the rows. A
1005 # column with no name stays out of the list, so it is not shown.
1006 0 my @cols;
1007 0 for my $c ($cmin .. $cmax) {
1008 0 my $cell = $ws->get_cell($rmin, $c);
1009 0 ▶ my $name = defined $cell ? ($cell->value // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $cell ? : 0 0 0
Condition0%0/2
$cell->value // ""
l!l
00
MC/DC0%0/1
$cell->value // ""
$cell->value
Truth table0%0/2
A
A= $cell->value
Aresult
11
00
1010 0 ▶ push @cols, $name if $name =~ /[^\s"]/;
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /[^\s"]/ 0 0 0
1011 }
1012  
1013 # No parseable column names.
1014 0 ▶ return { _file_is_empty => 1, file_size => -s $path }
Branch: 1 branch
BranchTrueFalseTotal
unless @cols 0 0 0
1015 unless @cols;
1016  
1017 0 my ($safe_id) = grep { $_ =~ $TABLE_NAME_RE } @cols;
1018  
1019 # With no_entry D::A does not use the id for a workbook, so
1020 # headers that are all unsafe ("First Name") need no id of their own.
1021 return {
1022 0 ▶ columns => \@cols,
Condition0%0/2
$safe_id // "entry"
l!l
00
MC/DC0%0/1
$safe_id // "entry"
$safe_id
Truth table0%0/2
A
A= $safe_id
Aresult
11
00
1023 id => $safe_id // 'entry',
1024 file_size => -s $path,
1025 };
1026 }
1027 }
1028 }
1029  
1030 2282 for my $ext (qw(csv psv tsv)) {
1031 3177 my $path = File::Spec->catfile($dir, "$table.$ext");
1032 3177 ▶ next unless -r $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $path 1326 1851 3177
1033 # "use autodie" makes open() die on failure, so "or next" would be dead
1034 # code. Disable autodie for this open so a vanishing file (race between
1035 # the -r probe and the open) results in a clean skip rather than a croak.
1036 1851 my $fh;
1037 13 ▶ { no autodie 'open'; open $fh, '<', $path or next }
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<", $path or next 1851 0 1851
1038 1851 my $line = <$fh>;
1039 # 0-byte file: no header, no rows. Return a sentinel so _init_backend
1040 # can skip Database::Abstraction entirely. If we let D::A see an empty
1041 # file it falls through to the DBD::CSV path, whose error handling on
1042 # an empty SELECT corrupts DBI's internal Errstr SV; on a DEBUGGING perl
1043 # (DBI 1.651 + perl 5.44.0) this triggers an XS assertion at cleanup.
1044 1851 ▶ unless (defined $line) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $line) 9 1842 1851
1045 9 close $fh;
1046 9 return { _file_is_empty => 1, file_size => 0 };
1047 }
1048 1842 chomp $line;
1049 1842 $line =~ s/\r\z//; # strip CR from CRLF files before any split
1050 # A UTF-8 byte-order mark, which Excel's "CSV UTF-8" writes, is not
1051 # part of the first column's name. D::A would keep it there, so it
1052 # reads a copy without it (see _init_backend).
1053 1842 my $bom = $line =~ s/\A\xEF\xBB\xBF//;
1054  
1055 1842 my $sep;
1056 1842 ▶ if($ext eq 'psv') {
Branch: 2 branches
BranchTrueFalseTotal
if ($ext eq 'psv') { } 19 1823 1842
elsif ($ext eq 'tsv') { } 6 1817 1823
1057 19 $sep = '|';
1058 } elsif($ext eq 'tsv') {
1059 6 $sep = "\t";
1060 } else {
1061 # Sniff the separator: Database::Abstraction uses '!' natively and
1062 # sometimes stores those files with a .csv extension. If splitting
1063 # on ',' yields a single field that itself contains '!', the real
1064 # separator is almost certainly '!'.
1065 1817 my @probe = split /,/, $line, -1;
1066 1817 ▶ $sep = (@probe == 1 && $line =~ /!/) ? '!' : ',';
Branch: 1 branch
BranchTrueFalseTotal
@probe == 1 && $line =~ /!/ ? : 1 1816 1817
Condition100%3/3
@probe == 1 and $line =~ /!/
!ll&&!rl&&r
181331
MC/DC100%2/2
@probe == 1 and $line =~ /!/
@probe == 1 $line =~ /!/
Truth table100%3/3
A and B
A= @probe == 1B= $line =~ /!/
ABresult
0X0
100
111
1067 }
1068  
1069 1842 my @fields = _split_csv_line($line, $sep);
1070 # Two separate substitutions: the /g on an anchored alternation wastes
1071 # O(N) engine cycles retrying \A (which can only match at position 0).
1072 1842 for (@fields) { s/\A[\s"]+//; s/[\s"]+\z// } # strip whitespace and quotes
1073 1842 ▶ pop @fields while @fields && !length $fields[-1]; # a trailing separator
Branch: 1 branch
BranchTrueFalseTotal
@fields and not length $fields[-1] and do { pop @fields } 4 1842 1846
Condition100%3/3
@fields and not length $fields[-1]
!ll&&!rl&&r
418384
MC/DC100%2/2
@fields and not length $fields[-1]
@fields not length $fields[-1]
Truth table100%3/3
A and not(B)
A= @fieldsB= not length $fields[-1]
ABresult
0X0
100
111
1074 1842 my @cols = grep { length } @fields;
1075  
1076 # A blank first line (e.g. a file containing only "\n") produces an
1077 # empty column list. Treat that the same as a 0-byte file: return the
1078 # _file_is_empty sentinel so _init_backend skips D::A entirely.
1079 # Attempting to construct D::A with id => undef and an empty columns
1080 # list would croak error_no_safe_id -- misleading for what is effectively
1081 # an empty file.
1082 1842 ▶ if (!@cols) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@cols) 4 1838 1842
1083 4 close $fh;
1084 4 return { _file_is_empty => 1, file_size => -s $path };
1085 }
1086  
1087 # Database::Abstraction validates id against $SAFE_IDENTIFIER
1088 # (/\A[a-zA-Z_][a-zA-Z0-9_]*\z/) at construction time and uses it as
1089 # a row-existence sentinel: every data row must have a defined, non-#
1090 # value in the id column or D::A drops it (empty_is_undef => 1 makes
1091 # truly empty cells undef).
1092 #
1093 # Strategy: of the safe columns, the one with the fewest empty cells
1094 # across the whole file, the earliest on a tie. Choosing by the first
1095 # data row alone lost rows: a bank export whose first transaction had a
1096 # cheque number made Check the id, and D::A then dropped the 358 of 362
1097 # rows that had none. D::A reads the whole file anyway (max_slurp_size
1098 # is the file's size), so one more pass costs no more than that. With
1099 # no data rows, the first safe column in the header.
1100 1838 my $safe_id = _best_id_column($fh, $sep, \@fields, _csv_escape_char($path));
1101  
1102 # If no safe identifier was found in the header, check whether the first
1103 # row looks like data values rather than column names. A CSV exported
1104 # from a bank or accounting system often has no header row at all -- the
1105 # first line is already a transaction record. When that is the case,
1106 # synthesize safe column names by inferring the type of each value
1107 # (date, amount, description); _init_backend then gives D::A a copy of
1108 # the file with those names as its header.
1109 1837 ▶ unless (defined $safe_id) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $safe_id) 31 1806 1837
1110 31 ▶ if (_values_are_data_like(\@cols)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_values_are_data_like(\@cols)) 23 8 31
1111 23 my @synth = _synthesize_col_names(\@fields);
1112 23 close $fh;
1113 return {
1114 23 sep_char => $sep,
1115 id => $synth[0],
1116 columns => \@synth,
1117 _headerless => { path => $path, ext => $ext }, # its copy drops a BOM
1118 file_size => -s $path,
1119 };
1120 }
1121 }
1122  
1123 1814 close $fh;
1124  
1125 # Return file_size so _init_backend can pass it as max_slurp_size to
1126 # Database::Abstraction. Without this, files larger than D::A's default
1127 # 16 KB threshold go through the DBI/DBD::CSV path, which lowercases
1128 # column names and replaces spaces with underscores ("Account Number" ->
1129 # "account_number"). The slurp path (Text::xSV::Slurp) preserves the
1130 # original header names, so forcing it avoids the mismatch.
1131 return {
1132 1814 ▶ sep_char => $sep,
Branch: 1 branch
BranchTrueFalseTotal
$bom ? : 0 1814 1814
1133 id => $safe_id,
1134 columns => \@cols,
1135 ($bom ? (_bom => { path => $path, ext => $ext }) : ()),
1136 file_size => -s $path,
1137 };
1138 }
1139  
1140 # SQLite / Berkeley DB: peek at sqlite_master to discover the internal table
1141 # names. _init_backend uses this list to auto-select the correct table when
1142 # the filename stem (dbname) differs from the table name inside the file --
1143 # e.g. obituaries.sql whose internal table is called "deceased". If the
1144 # file is not a valid SQLite database (e.g. a Berkeley DB file) the eval
1145 # fails; for .db files we then check for BerkeleyDB magic so we can read
1146 # the data directly (or return an error sentinel) instead of letting D::A
1147 # fall through to its CSV path, which would read a large binary file as text.
1148 # .sqlite and .sqlite3 are common alternative SQLite extensions -- treated identically to .sql.
1149 431 my $non_sqlite_db; # set to path when a .db file fails the SQLite probe
1150 431 for my $ext (qw(sql sqlite sqlite3 db)) {
1151 1588 my $path = File::Spec->catfile($dir, "$table.$ext");
1152 1588 ▶ next unless -r $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $path 1177 411 1588
1153 411 my $tables = eval {
1154 411 require Database::Join::Catalog;
1155 411 Database::Join::Catalog->tables(file => $path);
1156 };
1157 # defined $tables means the eval succeeded (even an empty list is valid)
1158 411 ▶ return { sqlite_tables => ($tables // []), file_size => -s $path }
Branch: 1 branch
BranchTrueFalseTotal
if defined $tables 406 5 411
Condition50%1/2
$tables // []
l!l
4060
MC/DC0%0/1
$tables // []
$tables
Truth table50%1/2
A
A= $tables
Aresult
11
00
1159 if defined $tables;
1160 5 ▶ $non_sqlite_db = $path if $ext eq 'db';
Branch: 1 branch
BranchTrueFalseTotal
if $ext eq "db" 2 3 5
1161 5 last; # file found but not SQLite -- do not try the other ext
1162 }
1163  
1164 # A .db file that is not SQLite: check for BerkeleyDB magic bytes.
1165 # BerkeleyDB Hash/Btree/Queue files begin with a 32-bit magic number either
1166 # at offset 0 (big-endian files) or at offset 12 (little-endian files).
1167 # If found, try to open via DB_File under a 10-second alarm so a version-
1168 # incompatible file does not block the server for minutes.
1169 25 ▶ if (defined $non_sqlite_db) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $non_sqlite_db) 2 23 25
1170 2 my $magic_ok = 0;
1171 2 ▶ if (open(my $fh, '<:raw', $non_sqlite_db)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Database::BI::Model::DataSource::open(my $fh, "<:raw", $non_sqlite_db)) 2 0 2
1172 2 my $buf = '';
1173 2 ▶ if (read($fh, $buf, 4) == 4) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Database::BI::Model::DataSource::read($fh, \$buf, 4) == 4) 2 0 2
1174 2 my %MAGIC = map { $_ => 1 }
1175 (0x00061561, 0x00053162, 0x00042253, 0x00052444);
1176 2 ▶ $magic_ok = 1 if $MAGIC{unpack('N', $buf)} || $MAGIC{unpack('V', $buf)};
Branch: 1 branch
BranchTrueFalseTotal
if $MAGIC{unpack "N", $buf} or $MAGIC{unpack "V", $buf} 0 2 2
Condition33%1/3
$MAGIC{unpack "N", $buf} or $MAGIC{unpack "V", $buf}
l!l&&r!l&&!r
002
MC/DC0%0/2
$MAGIC{unpack "N", $buf} or $MAGIC{unpack "V", $buf}
$MAGIC{unpack "N", $buf} $MAGIC{unpack "V", $buf}
Truth table33%1/3
A or B
A= $MAGIC{unpack "N", $buf}B= $MAGIC{unpack "V", $buf}
ABresult
1X1
011
000
1177 }
1178 2 ▶ unless ($magic_ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($magic_ok) 2 0 2
1179 2 ▶ if (seek $fh, 12, 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Database::BI::Model::DataSource::seek($fh, 12, 0)) 2 0 2
1180 2 my $b12 = '';
1181 2 ▶ if (read($fh, $b12, 4) == 4) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Database::BI::Model::DataSource::read($fh, \$b12, 4) == 4) 2 0 2
1182 2 my $hex = substr(unpack('H*', $b12), 0, 4);
1183 2 ▶ $magic_ok = 1 if $hex eq '6115' || $hex eq '1561';
Branch: 1 branch
BranchTrueFalseTotal
if $hex eq 6115 or $hex eq 1561 1 1 2
Condition66%2/3
$hex eq 6115 or $hex eq 1561
l!l&&r!l&&!r
101
MC/DC50%1/2
$hex eq 6115 or $hex eq 1561
$hex eq 6115 $hex eq 1561
Truth table66%2/3
A or B
A= $hex eq 6115B= $hex eq 1561
ABresult
1X1
011
000
1184 }
1185 }
1186 }
1187 2 close $fh;
1188 }
1189 2 ▶ if ($magic_ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($magic_ok) 1 1 2
1190 1 my $fsize = -s $non_sqlite_db;
1191 # BerkeleyDB magic confirmed. Check that DB_File can open it,
1192 # so that D::A never reads a file it cannot as CSV text,
1193 # but only for reasonably-sized files (<= 100 MB). Opening a
1194 # multi-GB BerkeleyDB file with an incompatible library version
1195 # causes multi-minute disk I/O that cannot be interrupted with
1196 # alarm() (XS I/O in libdb-5.x ignores SIGALRM via SA_RESTART).
1197 # For large files, return the unsupported sentinel immediately.
1198 1 Readonly my $BDB_MAX_BYTES => 100 * 1024 * 1024; # 100 MB
1199 1 ▶ if (defined $fsize && $fsize > $BDB_MAX_BYTES) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $fsize and $fsize > $BDB_MAX_BYTES) 0 1 1
Condition33%1/3
defined $fsize and $fsize > $BDB_MAX_BYTES
!ll&&!rl&&r
010
MC/DC0%0/2
defined $fsize and $fsize > $BDB_MAX_BYTES
defined $fsize $fsize > $BDB_MAX_BYTES
Truth table33%1/3
A and B
A= defined $fsizeB= $fsize > $BDB_MAX_BYTES
ABresult
0X0
100
111
1200 0 return { _unknown_binary_db => 1, file_size => $fsize };
1201 }
1202 1 my $opens = eval {
1203 1 require DB_File;
1204 0 my %bdb;
1205 # Capture the tie object so we can undef it before untie --
1206 # DB_File warns "untie while N inner references" if the object
1207 # reference count is > 0 when untie fires.
1208 my $db_obj = tie %bdb, 'DB_File', $non_sqlite_db,
1209 0 ▶ Fcntl::O_RDONLY(), 0644, do { no warnings "once"; $DB_File::DB_HASH };
Subroutine BEGIN: called CC=1 SCAR=0.6
1210 0 ▶ return 0 unless $db_obj;
Branch: 1 branch
BranchTrueFalseTotal
unless $db_obj 0 0 0
1211 0 undef $db_obj;
1212 0 untie %bdb;
1213 0 1;
1214 };
1215 1 ▶ if ($opens) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opens) 0 1 1
1216 return {
1217 0 columns => ['entry', 'value'],
1218 id => 'entry',
1219 file_size => $fsize,
1220 };
1221 }
1222 # tie failed: return a sentinel so _init_backend can show a proper
1223 # error instead of letting D::A read the binary file as CSV text.
1224 1 return { _unknown_binary_db => 1, file_size => $fsize };
1225 }
1226 }
1227  
1228 # XML that is a document, not a list of rows (a DMARC report: a few
1229 # one-off elements and a repeating <record>): D::A reads one repeating
1230 # element of a flat document and croaks on the rest, so write the rows as
1231 # a flat JSON copy, as for a .json file. A file D::A can read is left to it.
1232 {
1233 24 my $path = File::Spec->catfile($dir, "$table.xml");
1234 24 ▶ if (-r $path && !grep { -f File::Spec->catfile($dir, "$table.$_") } grep { $_ ne 'xml' } @NON_JSON_EXT) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $path and not grep({-f "File::Spec"->catfile($dir, "$table.$_");} grep({$_ ne "xml";} @NON_JSON_EXT))) 4 20 24
Condition100%3/3
-r $path and not grep({-f "File::Spec"->catfile($dir, "$table.$_");} grep({$_ ne "xml";} @NON_JSON_EXT))
!ll&&!rl&&r
1914
MC/DC100%2/2
-r $path and not grep({-f "File::Spec"->catfile($dir, "$table.$_");} grep({$_ ne "xml";} @NON_JSON_EXT))
-r $path not grep({-f "File::Spec"->catfile($dir, "$table.$_");} grep({$_ ne "xml";} @NON_JSON_EXT))
Truth table100%3/3
A and not(B)
A= -r $pathB= not grep({-f "File::Spec"->catfile($dir, "$table.$_");} grep({$_ ne "xml";} @NON_JSON_EXT))
ABresult
0X0
100
111
1235 # Before either reader: D::A's own XML::Simple would resolve an
1236 # external entity just as _xml_table's does.
1237 4 _refuse_xml_entities($path);
1238 3 my $xml = _xml_table($path);
1239 3 ▶ if ($xml) {
Branch: 1 branch
BranchTrueFalseTotal
if ($xml) 0 3 3
1240 0 my ($safe_id) = grep { $_ =~ $TABLE_NAME_RE } @{ $xml->{columns} };
1241 return {
1242 columns => $xml->{columns},
1243 0 ▶ id => $safe_id // 'entry',
Condition0%0/2
$safe_id // "entry"
l!l
00
MC/DC0%0/1
$safe_id // "entry"
$safe_id
Truth table0%0/2
A
A= $safe_id
Aresult
11
00
1244 _json => $xml,
1245 };
1246 }
1247 }
1248 }
1249  
1250 # JSON comes last, as it does in D::A's own search: a table.csv beside
1251 # table.json is the file D::A opens. JSON Lines is read the same way, after
1252 # .json.
1253 23 for my $ext ('json', @JSON_LINES_EXT) {
1254 63 my $path = File::Spec->catfile($dir, "$table.$ext");
1255 63 ▶ next unless -r $path && !grep { -f File::Spec->catfile($dir, "$table.$_") } (@NON_JSON_EXT, $ext eq 'json' ? () : ('json'));
Branch: 2 branches
BranchTrueFalseTotal
unless -r $path and not grep({-f "File::Spec"->catfile($dir, "$table.$_");} @NON_JSON_EXT, $ext eq "json" ? () : "json") 60 3 63
$ext eq 'json' ? : 3 0 3
Condition66%2/3
-r $path and not grep({-f "File::Spec"->catfile($dir, "$table.$_");} @NON_JSON_EXT, $ext eq "json" ? () : "json")
!ll&&!rl&&r
6003
MC/DC50%1/2
-r $path and not grep({-f "File::Spec"->catfile($dir, "$table.$_");} @NON_JSON_EXT, $ext eq "json" ? () : "json")
-r $path not grep({-f "File::Spec"->catfile($dir, "$table.$_");} @NON_JSON_EXT, $ext eq "json" ? () : "json")
Truth table66%2/3
A and not(B)
A= -r $pathB= not grep({-f "File::Spec"->catfile($dir, "$table.$_");} @NON_JSON_EXT, $ext eq "json" ? () : "json")
ABresult
0X0
100
111
1256 3 ▶ my $json = $ext eq 'json'
Branch: 1 branch
BranchTrueFalseTotal
$ext eq 'json' ? : 3 0 3
1257 ? _json_table($path, $want, $flatten)
1258 : _jsonl_table($path, $want, $flatten);
1259 return { _file_is_empty => 1, file_size => -s $path, _json_lists => $json->{lists} }
1260 0 ▶ unless $json->{count};
Branch: 1 branch
BranchTrueFalseTotal
unless $json->{"count"} 0 0 0
1261 0 my ($safe_id) = grep { $_ =~ $TABLE_NAME_RE } @{ $json->{columns} };
1262 return {
1263 columns => $json->{columns},
1264 id => $safe_id // 'entry',
1265 _json => $json,
1266 _json_lists => $json->{lists},
1267 0 ▶ };
Condition0%0/2
$safe_id // "entry"
l!l
00
MC/DC0%0/1
$safe_id // "entry"
$safe_id
Truth table0%0/2
A
A= $safe_id
Aresult
11
00
1268 }
1269 20 return {};
1270 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1271  
1272 # _refuse_xml_entities( $path ) -> () | croaks error_xml_entities
1273 #
1274 # Purpose: Stop an XML file from making the parser read something it was not
1275 # given. <!ENTITY x SYSTEM "file:///etc/passwd"> in the prolog, then
1276 # &x; in a cell, puts that file in the table (and bypasses file_roots,
1277 # because the parser, not this code, opens it); a SYSTEM "http://..."
1278 # one makes the server fetch an address.
1279 # Premise 1: an entity can only be declared with the token "<!ENTITY".
1280 # Premise 2: a flat data file has no use for one.
1281 # Premise 3: a UTF-16 file spells that token with NUL bytes, which the match
1282 # would miss, and a document with a NUL in it is not text XML.
1283 # Conclusion: a file holding the token, a NUL or a UTF-16 byte-order mark is
1284 # refused before any parser sees it.
1285 # Entry: $path is a readable .xml file.
1286 22 ▶sub _refuse_xml_entities {
Subroutine _refuse_xml_entities: called CC=9 SCAR=22.1
1287 22 my ($path) = @_;
1288 22 local ($@, $!);
1289 # Premise 1: only a plain file can be read to its end; a named pipe blocks
1290 # the open until something writes to it. Conclusion: leave anything else
1291 # to the reader, which reports it.
1292 22 ▶ return unless defined $path && -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and -f $path 1 21 22
Condition66%2/3
defined $path and -f $path
!ll&&!rl&&r
0121
MC/DC50%1/2
defined $path and -f $path
defined $path -f $path
Truth table66%2/3
A and B
A= defined $pathB= -f $path
ABresult
0X0
100
111
1293 # A file that cannot be read is the reader's to report; autodie would throw here.
1294 21 my $fh;
1295 13 ▶ { no autodie 'open'; open $fh, '<:raw', $path or return; }
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<:raw", $path or return 21 0 21
1296 # Read in blocks, not the whole file: a gigabyte of XML must not be held to
1297 # look for eight bytes. The last bytes of one block are kept in front of
1298 # the next, so a marker cut by a block boundary is still found.
1299 21 my ($tail, $bom_checked) = ('', 0);
1300 21 my $found = 0;
1301 21 ▶ while (read($fh, my $block, $XML_SCAN_BLOCK)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Database::BI::Model::DataSource::read($fh, \my $block, $XML_SCAN_BLOCK)) 78 9 87
1302 78 my $window = $tail . $block;
1303 78 ▶ $found = 1, last if $window =~ /<!ENTITY|\0/ || (!$bom_checked && $window =~ /\A(?:\xFF\xFE|\xFE\xFF)/);
Branch: 1 branch
BranchTrueFalseTotal
if $window =~ /<!ENTITY|\0/ or not $bom_checked and $window =~ /\A(?:\xFF\xFE|\xFE\xFF)/ 12 66 78
Condition66%4/6
$window =~ /<!ENTITY|\0/ or not $bom_checked and $window =~ /\A(?:\xFF\xFE|\xFE\xFF)/
l!l&&r!l&&!r
12066
not $bom_checked and $window =~ /\A(?:\xFF\xFE|\xFE\xFF)/
!ll&&!rl&&r
5790
MC/DC33%1/3
$window =~ /<!ENTITY|\0/ or not $bom_checked and $window =~ /\A(?:\xFF\xFE|\xFE\xFF)/
$window =~ /<!ENTITY|\0/ not $bom_checked $window =~ /\A(?:\xFF\xFE|\xFE\xFF)/
Truth table75%3/4
A or not(B) and C
A= $window =~ /<!ENTITY|\0/B= not $bom_checkedC= $window =~ /\A(?:\xFF\xFE|\xFE\xFF)/
ABCresult
1XX1
0111
00X0
0100
1304 66 $bom_checked = 1;
1305 66 $tail = substr($window, -$XML_MARKER_OVERLAP);
1306 }
1307 21 close $fh;
1308 21 ▶ croak _fmt('error_xml_entities', $path) if $found;
Branch: 1 branch
BranchTrueFalseTotal
if $found 12 9 21
1309 9 return;
1310 }
1311  
1312 # _xml_table( $path ) -> { rows, columns, list } | undef
1313 #
1314 # Purpose: Read an XML document that holds more than one kind of top-level
1315 # element (a DMARC report: report_metadata, policy_published, a
1316 # repeating record) as a table.
1317 # Entry: $path is a readable .xml file.
1318 # Exit: undef when the file is not such a document (it does not parse, or
1319 # has fewer than two kinds of child element under the root, or none
1320 # repeats as hashes): D::A reads it as it always did. Otherwise
1321 # rows: flat hashes, columns: in the order the file first names them.
1322 # Notes: The row element is the child element that occurs most often, the
1323 # one with the most values on a tie, then the first by name. Each
1324 # row has its own values (a child's name is the column, nested ones
1325 # joined by "_": row_source_ip) and every other top-level value
1326 # (report_metadata_org_name, version), repeated on every row, so a
1327 # report's rows still say whose report they came from. A repeated
1328 # element inside a row becomes a list in one cell, "a, b", or its
1329 # JSON text when its members are not plain values. Attributes
1330 # are columns beside the child elements. KeyAttr is empty so that
1331 # XML::Simple does not fold name/id/key elements (see the POD).
1332 3 ▶sub _xml_table {
Subroutine _xml_table: called CC=27 SCAR=60.4
1333 3 my ($path) = @_;
1334 3 local ($@, $!);
1335 3 local $/ = "\n";
1336 3 require XML::Simple;
1337 3 ▶ open my $fh, '<:raw', $path or return undef;
Branch: 1 branch
BranchTrueFalseTotal
&Database::BI::Model::DataSource::open(my $fh, "<:raw", $path) or return undef 3 0 3
1338 3 my $text = do { local $/; <$fh> };
1339 3 close $fh;
1340 3 ▶ return undef unless defined $text && length $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text and length $text 0 3 3
Condition33%1/3
defined $text and length $text
!ll&&!rl&&r
003
MC/DC0%0/2
defined $text and length $text
defined $text length $text
Truth table33%1/3
A and B
A= defined $textB= length $text
ABresult
0X0
100
111
1341  
1342 3 my $doc = eval {
1343 3 XML::Simple::XMLin(\$text, ForceArray => 1, KeyAttr => [], SuppressEmpty => '');
1344 };
1345 3 ▶ return undef unless ref $doc eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc eq "HASH" 0 3 3
1346  
1347 3 my @kinds = grep { ref $doc->{$_} eq 'ARRAY' } keys %{$doc};
1348 3 ▶ return undef if @kinds < 2;
Branch: 1 branch
BranchTrueFalseTotal
if @kinds < 2 3 0 3
1349  
1350 # The row element: repeated, and every occurrence an element with parts.
1351 0 my ($row_key, @best);
1352 0 for my $k (sort @kinds) {
1353 0 my $list = $doc->{$k};
1354 0 ▶ next if grep { ref $_ ne 'HASH' } @{$list};
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_ ne "HASH";} @{$list;} 0 0 0
1355 0 my $values = 0;
1356 0 for my $one (@{$list}) {
1357 0 my %flat;
1358 0 _xml_flat($one, '', \%flat);
1359 0 $values += keys %flat;
1360 }
1361 0 my @score = (scalar @{$list}, $values);
1362 0 ▶ if (!defined $row_key || $score[0] > $best[0] || ($score[0] == $best[0] && $score[1] > $best[1])) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $row_key or $score[0] > $best[0] or $score[0] == $best[0] and $score[1] > $best[1]) 0 0 0
Condition0%0/9
not defined $row_key or $score[0] > $best[0] or $score[0] == $best[0] and $score[1] > $best[1]
l!l&&r!l&&!r
000
not defined $row_key or $score[0] > $best[0]
l!l&&r!l&&!r
000
$score[0] == $best[0] and $score[1] > $best[1]
!ll&&!rl&&r
000
MC/DC0%0/4
not defined $row_key or $score[0] > $best[0] or $score[0] == $best[0] and $score[1] > $best[1]
not defined $row_key $score[0] > $best[0] $score[0] == $best[0] $score[1] > $best[1]
Truth table0%0/5
not(A) or B or C and D
A= not defined $row_keyB= $score[0] > $best[0]C= $score[0] == $best[0]D= $score[1] > $best[1]
ABCDresult
1XXX1
01XX1
00111
000X0
00100
1363 0 ($row_key, @best) = ($k, @score);
1364 }
1365 }
1366 0 ▶ return undef unless defined $row_key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_key 0 0 0
1367  
1368 0 my %context;
1369 0 for my $k (keys %{$doc}) {
1370 0 ▶ next if $k eq $row_key;
Branch: 1 branch
BranchTrueFalseTotal
if $k eq $row_key 0 0 0
1371 0 _xml_flat($doc->{$k}, $k, \%context);
1372 }
1373 0 my @rows;
1374 0 for my $one (@{ $doc->{$row_key} }) {
1375 0 my %row;
1376 0 _xml_flat($one, '', \%row);
1377 0 push @rows, { %context, %row };
1378 }
1379  
1380 # Column order: where each name first appears in the text. The parse
1381 # keeps none. A tag's path below the root names its column, without the
1382 # row element's own name.
1383 0 (my $scan = $text) =~ s/<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>|<!DOCTYPE[^>\[]*(?:\[.*?\])?>//gs;
1384 0 my (@stack, @columns, %seen);
1385 0 ▶ while ($scan =~ /<(\/?)([^\s\/>!?]+)[^>]*?(\/?)>/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($scan =~ m[<(/?)([^\s/>!?]+)[^>]*?(/?)>]g) 0 0 0
1386 0 my ($close, $name, $self_close) = ($1, $2, $3);
1387 0 ▶ if ($close) {
Branch: 1 branch
BranchTrueFalseTotal
if ($close) 0 0 0
1388 0 pop @stack;
1389 0 next;
1390 }
1391 0 push @stack, $name;
1392 0 my @parts = @stack[ 1 .. $#stack ];
1393 0 ▶ shift @parts if @parts && $parts[0] eq $row_key;
Branch: 1 branch
BranchTrueFalseTotal
if @parts and $parts[0] eq $row_key 0 0 0
Condition0%0/3
@parts and $parts[0] eq $row_key
!ll&&!rl&&r
000
MC/DC0%0/2
@parts and $parts[0] eq $row_key
@parts $parts[0] eq $row_key
Truth table0%0/3
A and B
A= @partsB= $parts[0] eq $row_key
ABresult
0X0
100
111
1394 0 my $col = join '_', @parts;
1395 0 ▶ if (length $col && !$seen{$col}++) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $col and not $seen{$col}++) 0 0 0
Condition0%0/3
length $col and not $seen{$col}++
!ll&&!rl&&r
000
MC/DC0%0/2
length $col and not $seen{$col}++
length $col not $seen{$col}++
Truth table0%0/3
A and not(B)
A= length $colB= not $seen{$col}++
ABresult
0X0
100
111
1396 0 push @columns, $col;
1397 }
1398 0 ▶ pop @stack if $self_close;
Branch: 1 branch
BranchTrueFalseTotal
if $self_close 0 0 0
1399 }
1400 0 my %known = map { $_ => 1 } map { keys %{$_} } @rows;
1401 0 @columns = grep { $known{$_} } @columns;
1402 0 my %placed = map { $_ => 1 } @columns;
1403 0 push @columns, grep { !$placed{$_} } sort keys %known;
1404  
1405 0 for my $row (@rows) {
1406 0 ▶ $row->{$_} //= '' for @columns;
Condition0%0/2
$row->{$_} //= ""
l!l
00
MC/DC0%0/1
$row->{$_} //= ""
$row->{$_}
Truth table0%0/2
A
A= $row->{$_}
Aresult
11
00
1407 }
1408 0 return { rows => \@rows, columns => \@columns, list => undef };
1409 }
1410  
1411 # _xml_flat( $node, $name, \%out )
1412 #
1413 # Purpose: Flatten one node of an XML::Simple (ForceArray) tree into cells.
1414 # Entry: $name is the column so far ('' at the top of a row).
1415 0 ▶sub _xml_flat {
Subroutine _xml_flat: not called CC=8 SCAR=42.8
1416 0 my ($node, $name, $out) = @_;
1417 0 ▶ if (ref $node eq 'ARRAY') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $node eq 'ARRAY') { } 0 0 0
elsif (ref $node eq 'HASH') { } 0 0 0
elsif (length $name) { } 0 0 0
1418 0 ▶ if (@{$node} == 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (@{$node;} == 1) { } 0 0 0
elsif (not grep({ref $_;} @{$node;})) { } 0 0 0
1419 0 _xml_flat($node->[0], $name, $out);
1420 0 } elsif (!grep { ref $_ } @{$node}) {
1421 0 $out->{$name} = join ', ', @{$node};
1422 } else {
1423 0 require Mojo::JSON;
1424 0 $out->{$name} = Mojo::JSON::to_json($node);
1425 }
1426 } elsif (ref $node eq 'HASH') {
1427 0 for my $k (sort keys %{$node}) {
1428 0 ▶ _xml_flat($node->{$k}, length $name ? "${name}_$k" : $k, $out);
Branch: 1 branch
BranchTrueFalseTotal
length $name ? : 0 0 0
1429 }
1430 } elsif (length $name) {
1431 0 $out->{$name} = $node;
1432 }
1433 0 return;
1434 }
1435  
1436 # _json_read( $path ) -> ($text, $data)
1437 #
1438 # Purpose: A JSON file's bytes and what they parse to.
1439 # Exit: ('', undef) for a zero-byte or blank file. Croaks
1440 # error_json_invalid when the text is not JSON.
1441 5 ▶sub _json_read {
Subroutine _json_read: called CC=5 SCAR=16.2
1442 5 my $path = shift;
1443 5 local ($@, $!);
1444 5 my $text = do {
1445 5 open my $fh, '<:raw', $path;
1446 5 local $/;
1447 5 my $t = <$fh>;
1448 5 close $fh;
1449 5 ▶ $t // '';
Condition50%1/2
$t // ""
l!l
50
MC/DC0%0/1
$t // ""
$t
Truth table50%1/2
A
A= $t
Aresult
11
00
1450 };
1451 5 ▶ return ('', undef) if $text !~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $text =~ /\S/ 0 5 5
1452  
1453 5 require Mojo::JSON;
1454 5 my $data;
1455 5 ▶ unless (eval { $data = Mojo::JSON::decode_json($text); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $data = Mojo::JSON::decode_json($text); 1 } }) 1 4 5
1456 1 ▶ (my $why = $@ // '') =~ s/\s+at \S+ line \d+\.?\s*\z//;
Condition50%1/2
$@ // ""
l!l
10
MC/DC0%0/1
$@ // ""
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1457 1 croak _fmt('error_json_invalid', $path, $why);
1458 }
1459 4 return ($text, $data);
1460 }
1461  
1462 # _json_list_keys( $text, $data ) -> @keys
1463 #
1464 # Purpose: The top-level keys of a JSON object that hold a list of objects, in
1465 # the order the file gives them: each is a table.
1466 # Notes: A list holding anything but objects is not a table. An empty list
1467 # counts only when no list has rows, so { "items": [], "rows": [...] }
1468 # is one table.
1469 4 ▶sub _json_list_keys {
Subroutine _json_list_keys: called CC=4 SCAR=14.0
1470 4 my ($text, $data) = @_;
1471 4 ▶ return () unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 2 2 4
1472 my @lists = grep {
1473 4 my $v = $data->{$_};
1474 4 ▶ ref $v eq 'ARRAY' && !grep { ref $_ ne 'HASH' } @{$v}
Condition33%1/3
ref $v eq 'ARRAY' && !grep({ref $_ ne 'HASH';} @{$v;})
!ll&&!rl&&r
004
MC/DC0%0/2
ref $v eq 'ARRAY' && !grep({ref $_ ne 'HASH';} @{$v;})
ref $v eq 'ARRAY' !grep({ref $_ ne 'HASH';} @{$v;})
Truth table33%1/3
A && not(B)
A= ref $v eq 'ARRAY'B= !grep({ref $_ ne 'HASH';} @{$v;})
ABresult
0X0
100
111
1475 2 } @{ _json_key_order($text, 1) };
1476 2 my @full = grep { @{ $data->{$_} } } @lists;
1477 2 ▶ return @full ? @full : @lists;
Branch: 1 branch
BranchTrueFalseTotal
@full ? : 2 0 2
1478 }
1479  
1480 # _json_columns( $text, $rows, $depth, $list ) -> \@names
1481 #
1482 # Purpose: The columns of rows read from a JSON text, in the order the text
1483 # first names them, then any it did not (sorted).
1484 2 ▶sub _json_columns {
Subroutine _json_columns: called CC=1 SCAR=0.0
1485 2 my ($text, $rows, $depth, $list, $flatten) = @_;
1486 2 my @columns = @{ _json_key_order($text, $depth, $list, $flatten) };
1487 2 my %named = map { $_ => 1 } @columns;
1488 2 push @columns, sort grep { !$named{$_}++ } map { keys %{$_} } @{$rows};
1489 2 return \@columns;
1490 }
1491  
1492 # _json_table( $path, $want ) -> { rows, columns, list, lists }
1493 #
1494 # Purpose: Read a JSON file as a table, for D::A to read a flat copy of.
1495 # Entry: $path is a readable .json file. $want, when defined, names the
1496 # list to read (internal_table).
1497 # Exit: rows: flat hashes. columns: in the order the file first names
1498 # them. list: the key the rows were under (undef when none).
1499 # lists: every list of objects in the file (empty when the file is
1500 # not an object holding lists). A zero-byte or blank file is no rows.
1501 # Croaks error_json_invalid, error_json_no_rows or
1502 # error_json_list_not_found.
1503 # Notes: Three shapes are tables:
1504 # [ {row}, ... ] each object a row
1505 # { "findings": [ {row}, ... ] } each list of objects under a key
1506 # a table, the first the default;
1507 # other values (a count, a date)
1508 # are left out
1509 # { "a1": {row}, "b2": {row} } each key a row, kept in a column
1510 # "id" ("key" when "id" is taken)
1511 # A cell holding an object or a list becomes its compact JSON text,
1512 # true and false the words, null an empty cell. The column order is
1513 # read from the text: a parsed object has no order.
1514 3 ▶sub _json_table {
Subroutine _json_table: called CC=19 SCAR=50.4
1515 3 my ($path, $want, $flatten) = @_;
1516  
1517 # A big list of objects is read a row at a time (_json_stream), not as one
1518 # string and one tree. Only that shape: the others need the whole document
1519 # to find their lists.
1520 3 ▶ if (!defined $want && (-s $path // 0) > $JSON_STREAM_BYTES && _json_starts_with($path, '[')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $want and (-s $path // 0) > $JSON_STREAM_BYTES and _json_starts_with($path, "[")) 0 3 3
Condition50%4/8
not defined $want and (-s $path // 0) > $JSON_STREAM_BYTES and _json_starts_with($path, "[")
!ll&&!rl&&r
300
not defined $want and (-s $path // 0) > $JSON_STREAM_BYTES
!ll&&!rl&&r
120
-s $path // 0
l!l
20
MC/DC0%0/3
not defined $want and (-s $path // 0) > $JSON_STREAM_BYTES and _json_starts_with($path, "[")
not defined $want -s $path _json_starts_with($path, "[")
Truth table25%1/4
not(A) and B and C
A= not defined $wantB= -s $pathC= _json_starts_with($path, "[")
ABCresult
0XX0
10X0
1100
1111
1521 0 return _json_stream($path, 'array', $flatten);
1522 }
1523  
1524 3 my ($text, $data) = _json_read($path);
1525 2 ▶ unless (length $text) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $text) 0 2 2
1526 0 ▶ croak _fmt('error_json_list_not_found', $path, $want) if defined $want;
Branch: 1 branch
BranchTrueFalseTotal
if defined $want 0 0 0
1527 0 return { rows => [], columns => [], list => undef, lists => [], count => 0 };
1528 }
1529  
1530 2 my @lists = _json_list_keys($text, $data);
1531 2 ▶ if (defined $want) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $want) 1 1 2
1532 croak _fmt('error_json_list_not_found', $path, $want)
1533 1 ▶ unless grep { $_ eq $want } @lists;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $want;} @lists 1 0 1
1534 }
1535  
1536 1 my ($rows, $list, $key_col, $depth);
1537 1 ▶ if (ref $data eq 'ARRAY') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $data eq 'ARRAY') { } 1 0 1
elsif (@lists) { } 0 0 0
elsif (ref $data eq 'HASH' and %{$data;} and not grep({ref $_ ne 'HASH';} values %{$data;})) { } 0 0 0
1538 1 ▶ croak _fmt('error_json_no_rows', $path) if grep { ref $_ ne 'HASH' } @{$data};
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_ ne "HASH";} @{$data;} 1 0 1
1539 0 ($rows, $depth) = ($data, 2);
1540 } elsif (@lists) {
1541 0 ▶ $list = $want // $lists[0];
Condition0%0/3
$want // $lists[0]
l!l&&r!l&&!r
000
MC/DC0%0/2
$want // $lists[0]
$want $lists[0]
Truth table0%0/3
A // B
A= $wantB= $lists[0]
ABresult
1X1
011
000
1542 0 ($rows, $depth) = ($data->{$list}, 3);
1543 0 ▶ } elsif (ref $data eq 'HASH' && %{$data} && !grep { ref $_ ne 'HASH' } values %{$data}) {
Condition0%0/6
ref $data eq "HASH" and %{$data;} and not grep({ref $_ ne "HASH";} values %{$data;})
!ll&&!rl&&r
000
ref $data eq "HASH" and %{$data;}
!ll&&!rl&&r
000
MC/DC0%0/3
ref $data eq "HASH" and %{$data;} and not grep({ref $_ ne "HASH";} values %{$data;})
ref $data eq "HASH" %{$data;} not grep({ref $_ ne "HASH";} values %{$data;})
Truth table0%0/4
A and B and not(C)
A= ref $data eq "HASH"B= %{$data;}C= not grep({ref $_ ne "HASH";} values %{$data;})
ABCresult
0XX0
10X0
1100
1111
1544 0 $depth = 2;
1545 0 my @inner = map { keys %{$_} } values %{$data};
1546 0 ▶ $key_col = (grep { $_ eq 'id' } @inner) ? 'key' : 'id';
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ eq 'id';} @inner) ? : 0 0 0
1547 0 ▶ $key_col .= '_' while grep { $_ eq $key_col } @inner;
Branch: 1 branch
BranchTrueFalseTotal
grep {$_ eq $key_col;} @inner and do { $key_col .= '_' } 0 0 0
1548 0 $rows = [ map { { %{ $data->{$_} }, $key_col => $_ } } @{ _json_key_order($text, 1) } ];
1549 } else {
1550 0 croak _fmt('error_json_no_rows', $path);
1551 }
1552  
1553 0 my @flat = map { _json_cells($_, $flatten) } @{$rows};
1554 0 my $columns = _json_columns($text, \@flat, $depth, $list, $flatten);
1555 0 ▶ @{$columns} = ($key_col, grep { $_ ne $key_col } @{$columns}) if defined $key_col;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key_col 0 0 0
1556  
1557 0 return { rows => \@flat, columns => $columns, list => $list, lists => \@lists, count => scalar @flat };
1558 }
1559  
1560 # _json_cells( $row, $flatten ) -> \%cells
1561 #
1562 # Purpose: One JSON object as one flat row of cells.
1563 # Notes: A value that is an object or a list becomes its compact JSON text,
1564 # true and false the words, null an empty cell. With $flatten an
1565 # object is not text but a cell for each of its own values, named by
1566 # the path to it (address.city); only a list is still text. A name
1567 # that is taken (a key written "a.b" beside the object "a" holding
1568 # "b") gets "_" added, so no cell is lost.
1569 0 ▶sub _json_cells {
Subroutine _json_cells: not called CC=1 SCAR=6.9
1570 0 my ($row, $flatten) = @_;
1571 0 my %cells;
1572 0 _json_cells_into(\%cells, $row, '', $flatten);
1573 0 return \%cells;
1574 }
1575  
1576 0 ▶sub _json_cells_into {
Subroutine _json_cells_into: not called CC=11 SCAR=48.8
1577 0 my ($cells, $node, $prefix, $flatten) = @_;
1578 0 for my $k (sort keys %{$node}) {
1579 0 my $v = $node->{$k};
1580 0 ▶ my $name = length $prefix ? "$prefix.$k" : $k;
Branch: 1 branch
BranchTrueFalseTotal
length $prefix ? : 0 0 0
1581 0 ▶ if ($flatten && ref $v eq 'HASH' && %{$v}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flatten and ref $v eq "HASH" and %{$v;}) 0 0 0
Condition0%0/6
$flatten and ref $v eq "HASH" and %{$v;}
!ll&&!rl&&r
000
$flatten and ref $v eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/3
$flatten and ref $v eq "HASH" and %{$v;}
$flatten ref $v eq "HASH" %{$v;}
Truth table0%0/4
A and B and C
A= $flattenB= ref $v eq "HASH"C= %{$v;}
ABCresult
0XX0
10X0
1100
1111
1582 0 _json_cells_into($cells, $v, $name, $flatten);
1583 0 next;
1584 }
1585 0 ▶ if (blessed($v) && $v->isa('JSON::PP::Boolean')) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($v) and $v->isa('JSON::PP::Boolean')) { } 0 0 0
elsif (ref $v) { } 0 0 0
Condition0%0/3
builtin::blessed($v) and $v->isa("JSON::PP::Boolean")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($v) and $v->isa("JSON::PP::Boolean")
builtin::blessed($v) $v->isa("JSON::PP::Boolean")
Truth table0%0/3
A and B
A= builtin::blessed($v)B= $v->isa("JSON::PP::Boolean")
ABresult
0X0
100
111
1586 0 ▶ $v = $v ? 'true' : 'false';
Branch: 1 branch
BranchTrueFalseTotal
$v ? : 0 0 0
1587 } elsif (ref $v) {
1588 0 $v = Mojo::JSON::to_json($v);
1589 }
1590 0 ▶ $name .= '_' while exists $cells->{$name};
Branch: 1 branch
BranchTrueFalseTotal
exists $cells->{$name} and do { $name .= '_' } 0 0 0
1591 0 $cells->{$name} = $v;
1592 }
1593 0 return;
1594 }
1595  
1596 # _json_starts_with( $path, $char ) -> bool
1597 #
1598 # Whether the first character of the file that is not white space (or a BOM)
1599 # is $char.
1600 0 ▶sub _json_starts_with {
Subroutine _json_starts_with: not called CC=4 SCAR=30.0
1601 0 my ($path, $char) = @_;
1602 0 local ($@, $!);
1603 0 ▶ open my $fh, '<:raw', $path or return 0;
Branch: 1 branch
BranchTrueFalseTotal
&Database::BI::Model::DataSource::open(my $fh, "<:raw", $path) or return 0 0 0 0
1604 0 read $fh, my $head, 4_096;
1605 0 close $fh;
1606 0 ▶ return 0 unless defined $head;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $head 0 0 0
1607 0 $head =~ s/\A\xEF\xBB\xBF//;
1608 0 ▶ return $head =~ /\A\s*\Q$char\E/ ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$head =~ /\A\s*\Q$char\E/ ? : 0 0 0
1609 }
1610  
1611 # _jsonl_table( $path, $want, $flatten ) -> { rows|stream, columns, count, ... }
1612 #
1613 # Purpose: A JSON Lines file (one object a line) as a table. Read as a stream.
1614 # Croaks: error_json_invalid (a line that is not JSON, with its number),
1615 # error_json_no_rows (a line that is not an object),
1616 # error_json_list_not_found ($want names a list: there are none).
1617 0 ▶sub _jsonl_table {
Subroutine _jsonl_table: not called CC=2 SCAR=17.9
1618 0 my ($path, $want, $flatten) = @_;
1619 0 ▶ croak _fmt('error_json_list_not_found', $path, $want) if defined $want;
Branch: 1 branch
BranchTrueFalseTotal
if defined $want 0 0 0
1620 0 return _json_stream($path, 'lines', $flatten);
1621 }
1622  
1623 # _json_each_row( $path, $kind, $code ) -> $count
1624 #
1625 # Purpose: Call $code->($row_text, $row_hash) for each object in a file, one at
1626 # a time, so memory holds one row and a chunk, not the file.
1627 # Entry: $kind is 'lines' (JSON Lines: one object a line, blank lines
1628 # skipped) or 'array' (a JSON list of objects).
1629 0 ▶sub _json_each_row {
Subroutine _json_each_row: not called CC=27 SCAR=66.3
1630 0 my ($path, $kind, $code) = @_;
1631 0 local ($@, $!);
1632 0 require Mojo::JSON;
1633 0 my $count = 0;
1634 0 ▶ my $row = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
1635 0 my ($text, $where) = @_;
1636 0 my $data;
1637 0 ▶ unless (eval { $data = Mojo::JSON::decode_json($text); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $data = Mojo::JSON::decode_json($text); 1 } }) 0 0 0
1638 0 ▶ (my $why = $@ // '') =~ s/\s+at \S+ line \d+\.?\s*\z//;
Condition0%0/2
$@ // ""
l!l
00
MC/DC0%0/1
$@ // ""
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
1639 0 croak _fmt('error_json_invalid', $path, "$where: $why");
1640 }
1641 0 ▶ croak _fmt('error_json_no_rows', $path) unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 0 0
1642 0 $count++;
1643 0 $code->($text, $data);
1644 0 };
1645  
1646 0 open my $fh, '<:raw', $path;
1647 0 ▶ if ($kind eq 'lines') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "lines") 0 0 0
1648 0 my $n = 0;
1649 0 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 0 0 0
1650 0 $n++;
1651 0 ▶ $line =~ s/\A\xEF\xBB\xBF// if $n == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $n == 1 0 0 0
1652 0 ▶ next unless $line =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\S/ 0 0 0
1653 0 $row->($line, "line $n");
1654 }
1655 0 close $fh;
1656 0 return $count;
1657 }
1658  
1659 # A list of objects: cut each top-level element out of the text by counting
1660 # brackets (strings skipped), and hand it on. A string or an element that
1661 # runs past the end of a chunk is kept and scanned again with the next one.
1662 0 my ($buf, $opened, $closed, $eof) = ('', 0, 0, 0);
1663 0 ▶ until ($eof) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($eof) 0 0 0
1664 0 my $more;
1665 0 my $got = read $fh, $more, $JSON_CHUNK_BYTES;
1666 0 ▶ $eof = $got ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$got ? : 0 0 0
1667 0 ▶ $buf .= $more if $got;
Branch: 1 branch
BranchTrueFalseTotal
if $got 0 0 0
1668 0 ▶ $buf =~ s/\A\xEF\xBB\xBF// unless $opened;
Branch: 1 branch
BranchTrueFalseTotal
unless $opened 0 0 0
1669 0 my ($depth, $from) = (0, undef);
1670 0 pos($buf) = 0;
1671 0 ▶ while ($buf =~ /\G(?:("(?:[^"\\]|\\.)*")|([{}\[\]])|([^"{}\[\]]+))/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($buf =~ /\G(?:("(?:[^"\\]|\\.)*")|([{}\[\]])|([^"{}\[\]]+))/cg) 0 0 0
1672 0 ▶ if (defined $2) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $2) { } 0 0 0
elsif (defined $3 and not $depth and $3 =~ /[^\s,]/) { } 0 0 0
1673 0 my $c = $2;
1674 0 ▶ if ($depth) {
Branch: 4 branches
BranchTrueFalseTotal
if ($depth) { } 0 0 0
elsif (not $opened) { } 0 0 0
elsif ($c eq '{') { } 0 0 0
elsif ($c eq ']') { } 0 0 0
1675 0 ▶ if ($c eq '{' || $c eq '[') {
Branch: 2 branches
BranchTrueFalseTotal
if ($c eq '{' or $c eq '[') { } 0 0 0
elsif (not --$depth) { } 0 0 0
Condition0%0/3
$c eq "{" or $c eq "["
l!l&&r!l&&!r
000
MC/DC0%0/2
$c eq "{" or $c eq "["
$c eq "{" $c eq "["
Truth table0%0/3
A or B
A= $c eq "{"B= $c eq "["
ABresult
1X1
011
000
1676 0 $depth++;
1677 } elsif (!--$depth) {
1678 0 $row->(substr($buf, $from, pos($buf) - $from), 'item ' . ($count + 1));
1679 0 $from = undef;
1680 }
1681 } elsif (!$opened) {
1682 0 ▶ croak _fmt('error_json_no_rows', $path) unless $c eq '[';
Branch: 1 branch
BranchTrueFalseTotal
unless $c eq "[" 0 0 0
1683 0 $opened = 1;
1684 } elsif ($c eq '{') {
1685 0 ($depth, $from) = (1, pos($buf) - 1);
1686 } elsif ($c eq ']') {
1687 0 $closed = 1;
1688 0 last;
1689 } else {
1690 0 croak _fmt('error_json_no_rows', $path);
1691 }
1692 ▶ } elsif (defined $3 && !$depth && $3 =~ /[^\s,]/) {
Condition0%0/6
defined $3 and not $depth and $3 =~ /[^\s,]/
!ll&&!rl&&r
000
defined $3 and not $depth
!ll&&!rl&&r
000
MC/DC0%0/3
defined $3 and not $depth and $3 =~ /[^\s,]/
defined $3 not $depth $3 =~ /[^\s,]/
Truth table0%0/4
A and not(B) and C
A= defined $3B= not $depthC= $3 =~ /[^\s,]/
ABCresult
0XX0
10X0
1100
1111
1693 0 croak _fmt('error_json_no_rows', $path);
1694 }
1695 }
1696 0 ▶ last if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 0 0 0
1697 0 ▶ $buf = defined $from ? substr($buf, $from) : substr($buf, pos($buf) // 0);
Branch: 1 branch
BranchTrueFalseTotal
defined $from ? : 0 0 0
Condition0%0/2
pos $buf // 0
l!l
00
MC/DC0%0/1
pos $buf // 0
pos $buf
Truth table0%0/2
A
A= pos $buf
Aresult
11
00
1698 }
1699 0 close $fh;
1700 0 ▶ croak _fmt('error_json_invalid', $path, 'the list is not closed')
Branch: 1 branch
BranchTrueFalseTotal
if $opened and not $closed 0 0 0
Condition0%0/3
$opened and not $closed
!ll&&!rl&&r
000
MC/DC0%0/2
$opened and not $closed
$opened not $closed
Truth table0%0/3
A and not(B)
A= $openedB= not $closed
ABresult
0X0
100
111
1701 if $opened && !$closed;
1702 0 return $count;
1703 }
1704  
1705 # _json_stream( $path, $kind, $flatten ) -> \%table
1706 #
1707 # Purpose: The table of a JSON Lines file, or of a big list of objects, without
1708 # holding its rows: one pass finds the columns (in the order the text
1709 # first names them) and the count, and the flat copy D::A reads is
1710 # written by a second pass (the table's "emit").
1711 0 ▶sub _json_stream {
Subroutine _json_stream: not called CC=1 SCAR=6.9
1712 0 my ($path, $kind, $flatten) = @_;
1713 0 my (@columns, %seen);
1714 0 ▶ my $count = _json_each_row($path, $kind, sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
1715 0 my ($text, $data) = @_;
1716 0 my $cells = _json_cells($data, $flatten);
1717 # The order of keys in the text is read only when this row has a name not
1718 # seen yet: a parsed object has no order.
1719 0 ▶ return unless grep { !$seen{$_} } keys %{$cells};
Branch: 1 branch
BranchTrueFalseTotal
unless grep {not $seen{$_};} keys %{$cells;} 0 0 0
1720 0 for my $name (@{ _json_key_order($text, 1, undef, $flatten) }, sort keys %{$cells}) {
1721 0 ▶ push @columns, $name if exists $cells->{$name} && !$seen{$name}++;
Branch: 1 branch
BranchTrueFalseTotal
if exists $cells->{$name} and not $seen{$name}++ 0 0 0
Condition0%0/3
exists $cells->{$name} and not $seen{$name}++
!ll&&!rl&&r
000
MC/DC0%0/2
exists $cells->{$name} and not $seen{$name}++
exists $cells->{$name} not $seen{$name}++
Truth table0%0/3
A and not(B)
A= exists $cells->{$name}B= not $seen{$name}++
ABresult
0X0
100
111
1722 }
1723 0 });
1724 0 ▶ my $emit = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1725 0 my ($fh) = @_;
1726 0 print {$fh} '[';
1727 0 my $first = 1;
1728 0 ▶ _json_each_row($path, $kind, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1729 0 ▶ print {$fh} ($first ? '' : ','), Mojo::JSON::encode_json(_json_cells($_[1], $flatten));
Branch: 1 branch
BranchTrueFalseTotal
$first ? : 0 0 0
1730 0 $first = 0;
1731 0 });
1732 0 print {$fh} ']';
1733 0 return;
1734 0 };
1735 0 return { emit => $emit, columns => \@columns, list => undef, lists => [], count => $count };
1736 }
1737  
1738 # _json_key_order( $text, $depth, $under ) -> \@keys
1739 #
1740 # Purpose: The keys of the objects $depth levels down in a JSON text, in the
1741 # order they first appear (a parsed object keeps none).
1742 # Entry: $text is valid JSON (the caller has parsed it). $depth counts the
1743 # object itself: a row of a top-level list is 2, a row of a list under
1744 # a key 3, a key of the top-level object 1. $under, when defined,
1745 # keeps only what is under that top-level key.
1746 # Exit: The keys, each once, decoded.
1747 4 ▶sub _json_key_order {
Subroutine _json_key_order: called CC=28 SCAR=41.4
1748 4 my ($text, $depth, $under, $flatten) = @_;
1749 4 my (@stack, @order, %seen, %parent, $top);
1750 4 ▶ while ($text =~ /\G\s*(?:("(?:[^"\\]|\\.)*")|([{}\[\]:,])|[^\s{}\[\]:,"]+)/gcs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /\G\s*(?:("(?:[^"\\]|\\.)*")|([{}\[\]:,])|[^\s{}\[\]:,"]+)/cgs) 84 4 88
1751 84 ▶ if (defined $1) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $1) { } 16 68 84
elsif (defined $2) { } 60 8 68
1752 16 my $frame = $stack[-1];
1753 16 ▶ next unless $frame && $frame->{object} && $frame->{want_key};
Branch: 1 branch
BranchTrueFalseTotal
unless $frame and $frame->{"object"} and $frame->{"want_key"} 0 16 16
Condition33%2/6
$frame and $frame->{"object"} and $frame->{"want_key"}
!ll&&!rl&&r
0016
$frame and $frame->{"object"}
!ll&&!rl&&r
0016
MC/DC0%0/3
$frame and $frame->{"object"} and $frame->{"want_key"}
$frame $frame->{"object"} $frame->{"want_key"}
Truth table25%1/4
A and B and C
A= $frameB= $frame->{"object"}C= $frame->{"want_key"}
ABCresult
0XX0
10X0
1100
1111
1754 16 $frame->{want_key} = 0;
1755 16 my $key = Mojo::JSON::decode_json("[$1]")->[0];
1756 16 $frame->{key} = $key;
1757 16 ▶ $top = $key if @stack == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @stack == 1 8 8 16
1758 0 ▶ if ($flatten && @stack > $depth && !grep { !$_->{object} } @stack[ $depth - 1 .. $#stack ]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flatten and @stack > $depth and not grep({not $_->{"object"};} @stack[$depth - 1 .. $#stack])) 0 16 16
Condition33%2/6
$flatten and @stack > $depth and not grep({not $_->{"object"};} @stack[$depth - 1 .. $#stack])
!ll&&!rl&&r
1600
$flatten and @stack > $depth
!ll&&!rl&&r
1600
MC/DC0%0/3
$flatten and @stack > $depth and not grep({not $_->{"object"};} @stack[$depth - 1 .. $#stack])
$flatten @stack > $depth not grep({not $_->{"object"};} @stack[$depth - 1 .. $#stack])
Truth table25%1/4
A and B and not(C)
A= $flattenB= @stack > $depthC= not grep({not $_->{"object"};} @stack[$depth - 1 .. $#stack])
ABCresult
0XX0
10X0
1100
1111
1759 # A key inside an object inside a row: its path is a column, and
1760 # the object's own path is not (it is what holds these).
1761 0 ▶ next if defined $under && !(defined $top && $top eq $under);
Branch: 1 branch
BranchTrueFalseTotal
if defined $under and not defined $top && $top eq $under 0 0 0
Condition0%0/6
defined $under and not defined $top && $top eq $under
!ll&&!rl&&r
000
defined $top && $top eq $under
!ll&&!rl&&r
000
MC/DC0%0/3
defined $under and not defined $top && $top eq $under
defined $under defined $top $top eq $under
Truth table0%0/4
A and not(B && C)
A= defined $underB= defined $topC= $top eq $under
ABCresult
0XX0
1110
10X1
1101
1762 0 my @path = ((map { $_->{key} } @stack[ $depth - 1 .. $#stack - 1 ]), $key);
1763 0 $parent{ join '.', @path[ 0 .. $#path - 1 ] } = 1;
1764 0 my $name = join '.', @path;
1765 0 ▶ push @order, $name unless $seen{$name}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$name}++ 0 0 0
1766 0 next;
1767 }
1768 16 ▶ next unless @stack == $depth;
Branch: 1 branch
BranchTrueFalseTotal
unless @stack == $depth 8 8 16
1769 8 ▶ next if defined $under && !(defined $top && $top eq $under);
Branch: 1 branch
BranchTrueFalseTotal
if defined $under and not defined $top && $top eq $under 2 6 8
Condition83%5/6
defined $under and not defined $top && $top eq $under
!ll&&!rl&&r
422
defined $top && $top eq $under
!ll&&!rl&&r
022
MC/DC66%2/3
defined $under and not defined $top && $top eq $under
defined $under defined $top $top eq $under
Truth table75%3/4
A and not(B && C)
A= defined $underB= defined $topC= $top eq $under
ABCresult
0XX0
1110
10X1
1101
1770 6 ▶ push @order, $key unless $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$key}++ 6 0 6
1771 } elsif (defined $2) {
1772 60 my $c = $2;
1773 60 ▶ if ($c eq '{') {
Branch: 4 branches
BranchTrueFalseTotal
if ($c eq '{') { } 12 48 60
elsif ($c eq '[') { } 8 40 48
elsif ($c eq '}' or $c eq ']') { } 20 20 40
elsif ($c eq ',' and @stack and $stack[-1]{'object'}) { } 4 32 36
1774 12 push @stack, { object => 1, want_key => 1 };
1775 } elsif ($c eq '[') {
1776 8 push @stack, { object => 0 };
1777 ▶ } elsif ($c eq '}' || $c eq ']') {
Condition100%3/3
$c eq "}" or $c eq "]"
l!l&&r!l&&!r
12820
MC/DC100%2/2
$c eq "}" or $c eq "]"
$c eq "}" $c eq "]"
Truth table100%3/3
A or B
A= $c eq "}"B= $c eq "]"
ABresult
1X1
011
000
1778 20 pop @stack;
1779 ▶ } elsif ($c eq ',' && @stack && $stack[-1]{object}) {
Condition66%4/6
$c eq "," and @stack and $stack[-1]{"object"}
!ll&&!rl&&r
1604
$c eq "," and @stack
!ll&&!rl&&r
1604
MC/DC33%1/3
$c eq "," and @stack and $stack[-1]{"object"}
$c eq "," @stack $stack[-1]{"object"}
Truth table50%2/4
A and B and C
A= $c eq ","B= @stackC= $stack[-1]{"object"}
ABCresult
0XX0
10X0
1100
1111
1780 4 $stack[-1]{want_key} = 1;
1781 }
1782 }
1783 }
1784 0 ▶ return [ grep { !$parent{$_} } @order ] if %parent;
Branch: 1 branch
BranchTrueFalseTotal
if %parent 0 4 4
1785 4 return \@order;
1786 }
1787  
1788 # _values_are_data_like( \@vals ) -> bool
1789 #
1790 # Return true when the values look like actual data (dates, numbers, free text)
1791 # _sniff_data_ext( $path ) -> $ext
1792 #
1793 # Peek at the content of $path and return the standard file extension that best
1794 # describes its format. Used when a remote file has a non-standard extension
1795 # (e.g. ".log") and we need to rename it so that _detect_file_info and
1796 # Database::Abstraction can discover it automatically.
1797 #
1798 # Detection order:
1799 # 1. SQLite magic bytes ("SQLite format 3") -> 'db'
1800 # 2. XML preamble ("<?xml" or "<" as first non-space character) -> 'xml'
1801 # 2a. "[" or "{" as first non-space character -> 'json'; a "{" whose
1802 # first lines are each one whole object -> 'jsonl'
1803 # 3. First data line contains tabs -> 'tsv'
1804 # 4. First data line contains pipes -> 'psv'
1805 # 5. Fallback -> 'csv'
1806 8 ▶sub _sniff_data_ext {
Subroutine _sniff_data_ext: called CC=15 SCAR=34.5
1807 8 my $path = $_[0];
1808 8 ▶ open(my $fh, '<:raw', $path) or return 'csv';
Branch: 1 branch
BranchTrueFalseTotal
&Database::BI::Model::DataSource::open(my $fh, "<:raw", $path) or return "csv" 8 0 8
1809 8 my $header = '';
1810 8 read $fh, $header, 20;
1811 8 close $fh;
1812 8 ▶ return 'db' if $header =~ /\ASQLite format/;
Branch: 1 branch
BranchTrueFalseTotal
if $header =~ /\ASQLite format/ 1 7 8
1813 7 ▶ return 'xml' if $header =~ /\A\s*<\?xml/i;
Branch: 1 branch
BranchTrueFalseTotal
if $header =~ /\A\s*<\?xml/i 1 6 7
1814 6 ▶ return 'xml' if $header =~ /\A\s*</;
Branch: 1 branch
BranchTrueFalseTotal
if $header =~ /\A\s*</ 1 5 6
1815 5 ▶ if ($header =~ /\A\s*\{/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($header =~ /\A\s*\{/) 0 5 5
1816 # One object a line, and another after it: JSON Lines, not one document.
1817 0 ▶ open(my $jh, '<:raw', $path) or return 'json';
Branch: 1 branch
BranchTrueFalseTotal
&Database::BI::Model::DataSource::open(my $jh, "<:raw", $path) or return "json" 0 0 0
1818 0 ▶ my @lines = grep { /\S/ } map { scalar <$jh> // () } 1 .. 3;
Condition0%0/3
scalar readline $jh // ()
l!l&&r!l&&!r
000
MC/DC0%0/2
scalar readline $jh // ()
scalar readline $jh ()
Truth table0%0/3
A // B
A= scalar readline $jhB= ()
ABresult
1X1
011
000
1819 0 close $jh;
1820 0 ▶ return 'jsonl' if @lines > 1 && !grep { !/\A\s*\{.*\}\s*\z/ } @lines;
Branch: 1 branch
BranchTrueFalseTotal
if @lines > 1 and not grep({not /\A\s*\{.*\}\s*\z/;} @lines) 0 0 0
Condition0%0/3
@lines > 1 and not grep({not /\A\s*\{.*\}\s*\z/;} @lines)
!ll&&!rl&&r
000
MC/DC0%0/2
@lines > 1 and not grep({not /\A\s*\{.*\}\s*\z/;} @lines)
@lines > 1 not grep({not /\A\s*\{.*\}\s*\z/;} @lines)
Truth table0%0/3
A and not(B)
A= @lines > 1B= not grep({not /\A\s*\{.*\}\s*\z/;} @lines)
ABresult
0X0
100
111
1821 0 return 'json';
1822 }
1823 5 ▶ return 'json' if $header =~ /\A\s*\[/;
Branch: 1 branch
BranchTrueFalseTotal
if $header =~ /\A\s*\[/ 0 5 5
1824 5 ▶ open(my $lh, '<', $path) or return 'csv';
Branch: 1 branch
BranchTrueFalseTotal
&Database::BI::Model::DataSource::open(my $lh, "<", $path) or return "csv" 5 0 5
1825 5 my $line = <$lh>;
1826 5 close $lh;
1827 5 ▶ return 'csv' unless defined $line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 0 5 5
1828 5 ▶ return 'tsv' if $line =~ /\t/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /\t/ 1 4 5
1829 4 ▶ return 'psv' if $line =~ /\|/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /\|/ 1 3 4
1830 3 return 'csv';
1831 }
1832  
1833 # _values_are_data_like( \@vals ) -> bool
1834 #
1835 # Returns true when the values look like a row of real data (dates / numbers)
1836 # rather than column headers. Used to detect header-less CSV files where the
1837 # first line is a data row. At least one value must match a date or numeric
1838 # pattern -- a row of plain hyphenated identifiers (e.g. "First-Name") is NOT
1839 # considered data-like.
1840 37 ▶sub _values_are_data_like {
Subroutine _values_are_data_like: called CC=6 SCAR=17.9
1841 37 my $vals = $_[0];
1842 37 for my $v (@{$vals}) {
1843 50 ▶ return 1 if $v =~ /\A\d{4}-\d{2}-\d{2}\z/; # YYYY-MM-DD
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /\A\d{4}-\d{2}-\d{2}\z/ 22 28 50
1844 28 ▶ return 1 if $v =~ /\A\d{1,2}\/\d{1,2}\/\d{4}\z/; # M/D/YYYY or D/M/YYYY
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ m[\A\d{1,2}/\d{1,2}/\d{4}\z] 1 27 28
1845 27 ▶ return 1 if $v =~ /\A[+\-]\d[\d,]*(?:\.\d+)?\z/; # signed numeric (e.g. -1,075.13)
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /\A[+\-]\d[\d,]*(?:\.\d+)?\z/ 3 24 27
1846 24 ▶ return 1 if $v =~ /\A\(\d[\d,]*(?:\.\d+)?\)\z/; # accounting negative (e.g. (75.13))
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /\A\(\d[\d,]*(?:\.\d+)?\)\z/ 1 23 24
1847 }
1848 10 return 0;
1849 }
1850  
1851 # _unsafe_sort( @args ) -> (\%rest, $col, $dir, $limit, $offset) | ()
1852 #
1853 # Purpose: Recognise a selectall_arrayref call that sorts on a column D::A will
1854 # not sort on, such as "First Name".
1855 # Entry: The call's arguments: a flat list or one hashref (Database::Join's
1856 # spill path), or anything else, which is not ours to take apart.
1857 # Exit: The remaining criteria, the column, ASC or DESC, and the page. Empty
1858 # for every other call.
1859 1495 ▶sub _unsafe_sort {
Subroutine _unsafe_sort: called CC=11 SCAR=24.0
1860 1495 my @args = @_;
1861 1495 ▶ my $opts = (@args == 1 && ref $args[0] eq 'HASH') ? { %{ $args[0] } }
Branch: 2 branches
BranchTrueFalseTotal
@args == 1 && ref $args[0] eq 'HASH' ? : 55 1440 1495
@args && @args % 2 == 0 ? : 35 1405 1440
Condition100%6/6
@args == 1 and ref $args[0] eq "HASH"
!ll&&!rl&&r
1438255
@args and @args % 2 == 0
!ll&&!rl&&r
1403235
MC/DC100%2/2
@args == 1 and ref $args[0] eq "HASH"
@args == 1 ref $args[0] eq "HASH"
MC/DC100%2/2
@args and @args % 2 == 0
@args @args % 2 == 0
Truth table100%3/3
A and B
A= @args == 1B= ref $args[0] eq "HASH"
ABresult
0X0
100
111
Truth table100%3/3
A and B
A= @argsB= @args % 2 == 0
ABresult
0X0
100
111
1862 : (@args && @args % 2 == 0) ? { @args }
1863 : undef;
1864 1495 ▶ return unless $opts && defined $opts->{sort_by};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts and defined $opts->{"sort_by"} 1477 18 1495
Condition100%3/3
$opts and defined $opts->{"sort_by"}
!ll&&!rl&&r
14057218
MC/DC100%2/2
$opts and defined $opts->{"sort_by"}
$opts defined $opts->{"sort_by"}
Truth table100%3/3
A and B
A= $optsB= defined $opts->{"sort_by"}
ABresult
0X0
100
111
1865 my ($col, $dir) = ref $opts->{sort_by} eq 'ARRAY'
1866 18 ▶ ? @{ $opts->{sort_by} }[0, 1] : ($opts->{sort_by}, undef);
Branch: 1 branch
BranchTrueFalseTotal
ref $opts->{'sort_by'} eq 'ARRAY' ? : 14 4 18
1867 18 ▶ return unless defined $col && $col !~ $DA_SORTABLE_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col and not $col =~ /$DA_SORTABLE_RE/ 13 5 18
Condition100%3/3
defined $col and not $col =~ /$DA_SORTABLE_RE/
!ll&&!rl&&r
1125
MC/DC100%2/2
defined $col and not $col =~ /$DA_SORTABLE_RE/
defined $col not $col =~ /$DA_SORTABLE_RE/
Truth table100%3/3
A and not(B)
A= defined $colB= not $col =~ /$DA_SORTABLE_RE/
ABresult
0X0
100
111
1868 5 my ($limit, $offset) = delete @{$opts}{qw(limit offset)};
1869 5 delete $opts->{sort_by};
1870 5 ▶ return ($opts, $col, uc($dir // 'ASC'), $limit, $offset);
Condition100%2/2
$dir // "ASC"
l!l
23
MC/DC100%1/1
$dir // "ASC"
$dir
Truth table100%2/2
A
A= $dir
Aresult
11
00
1871 }
1872  
1873 # _sorted_page( \@rows, $col, $dir, $limit, $offset ) -> \@rows
1874 #
1875 # Purpose: Do what D::A would have done for an _unsafe_sort call: sort as
1876 # strings, then take the page.
1877 # Notes: exists, because SQL-backed rows are locked hashes and a read of a
1878 # column they do not have would croak. An unknown column does not sort.
1879 # A new array, because the rows may be D::A's own cached list.
1880 11 ▶sub _sorted_page {
Subroutine _sorted_page: called CC=14 SCAR=26.7
1881 11 my ($rows, $col, $dir, $limit, $offset) = @_;
1882 11 ▶ my @page = @{ $rows // [] };
Condition100%2/2
$rows // []
l!l
101
MC/DC100%1/1
$rows // []
$rows
Truth table100%2/2
A
A= $rows
Aresult
11
00
1883 11 ▶ if (@page && exists $page[0]{$col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@page and exists $page[0]{$col}) 7 4 11
Condition100%3/3
@page and exists $page[0]{$col}
!ll&&!rl&&r
137
MC/DC100%2/2
@page and exists $page[0]{$col}
@page exists $page[0]{$col}
Truth table100%3/3
A and B
A= @pageB= exists $page[0]{$col}
ABresult
0X0
100
111
1884 @page = $dir eq 'DESC'
1885 3 ▶ ? sort { ($b->{$col} // '') cmp ($a->{$col} // '') } @page
Condition50%2/4
$Database::BI::Model::DataSource::b->{$col} // ""
l!l
30
$Database::BI::Model::DataSource::a->{$col} // ""
l!l
30
MC/DC0%0/1
$Database::BI::Model::DataSource::b->{$col} // ""
$Database::BI::Model::DataSource::b->{$col}
MC/DC0%0/1
$Database::BI::Model::DataSource::a->{$col} // ""
$Database::BI::Model::DataSource::a->{$col}
Truth table50%1/2
A
A= $Database::BI::Model::DataSource::b->{$col}
Aresult
11
00
Truth table50%1/2
A
A= $Database::BI::Model::DataSource::a->{$col}
Aresult
11
00
1886 7 ▶ : sort { ($a->{$col} // '') cmp ($b->{$col} // '') } @page;
Branch: 1 branch
BranchTrueFalseTotal
$dir eq 'DESC' ? : 1 6 7
Condition50%2/4
$Database::BI::Model::DataSource::a->{$col} // ""
l!l
180
$Database::BI::Model::DataSource::b->{$col} // ""
l!l
180
MC/DC0%0/1
$Database::BI::Model::DataSource::a->{$col} // ""
$Database::BI::Model::DataSource::a->{$col}
MC/DC0%0/1
$Database::BI::Model::DataSource::b->{$col} // ""
$Database::BI::Model::DataSource::b->{$col}
Truth table50%1/2
A
A= $Database::BI::Model::DataSource::a->{$col}
Aresult
11
00
Truth table50%1/2
A
A= $Database::BI::Model::DataSource::b->{$col}
Aresult
11
00
1887 }
1888 11 ▶ splice @page, 0, $offset if $offset && $offset =~ /\A\d+\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $offset and $offset =~ /\A\d+\z/ 2 9 11
Condition100%3/3
$offset and $offset =~ /\A\d+\z/
!ll&&!rl&&r
812
MC/DC100%2/2
$offset and $offset =~ /\A\d+\z/
$offset $offset =~ /\A\d+\z/
Truth table100%3/3
A and B
A= $offsetB= $offset =~ /\A\d+\z/
ABresult
0X0
100
111
1889 11 ▶ splice @page, $limit if defined $limit && $limit =~ /\A\d+\z/ && $limit < @page;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit and $limit =~ /\A\d+\z/ and $limit < @page 4 7 11
Condition83%5/6
defined $limit and $limit =~ /\A\d+\z/ and $limit < @page
!ll&&!rl&&r
704
defined $limit and $limit =~ /\A\d+\z/
!ll&&!rl&&r
614
MC/DC66%2/3
defined $limit and $limit =~ /\A\d+\z/ and $limit < @page
defined $limit $limit =~ /\A\d+\z/ $limit < @page
Truth table75%3/4
A and B and C
A= defined $limitB= $limit =~ /\A\d+\z/C= $limit < @page
ABCresult
0XX0
10X0
1100
1111
1890 11 return \@page;
1891 }
1892  
1893 # _split_csv_line( $line, $sep ) -> @fields
1894 #
1895 # One line of a delimited file as its fields, so that a separator inside quotes
1896 # does not end a field. A line that does not parse (a quoted field carrying on
1897 # over the next line) is split on the separator instead: this is only used to
1898 # look at the shape of a file.
1899 1848 ▶sub _split_csv_line {
Subroutine _split_csv_line: called CC=3 SCAR=11.0
1900 1848 my ($line, $sep) = @_;
1901 1848 require Text::CSV;
1902 1848 my $csv = Text::CSV->new({ binary => 1, sep_char => $sep, allow_loose_quotes => 1 });
1903 1848 ▶ return $csv->fields if $csv && $csv->parse($line);
Branch: 1 branch
BranchTrueFalseTotal
if $csv and $csv->parse($line) 1846 2 1848
Condition66%2/3
$csv and $csv->parse($line)
!ll&&!rl&&r
021846
MC/DC50%1/2
$csv and $csv->parse($line)
$csv $csv->parse($line)
Truth table66%2/3
A and B
A= $csvB= $csv->parse($line)
ABresult
0X0
100
111
1904 2 return split /\Q$sep\E/, $line, -1;
1905 }
1906  
1907 # _synthesize_col_names( \@vals ) -> @names
1908 #
1909 # Infer a safe SQL identifier for each positional value by examining its
1910 # content: ISO dates become "Date", numeric/currency values become "Amount",
1911 # and free text becomes "Description". Duplicate types are disambiguated with
1912 # a numeric suffix (Date, Date2, Date3, ...).
1913 28 ▶sub _synthesize_col_names {
Subroutine _synthesize_col_names: called CC=7 SCAR=19.5
1914 28 my $vals = $_[0];
1915 28 my %type_count;
1916 my @names;
1917 28 for my $v (@{$vals}) {
1918 79 my $type;
1919 79 ▶ if ($v =~ /\A\d{4}-\d{2}-\d{2}\z/ || $v =~ /\A\d{1,2}\/\d{1,2}\/\d{4}\z/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($v =~ /\A\d{4}-\d{2}-\d{2}\z/ or $v =~ m[\A\d{1,2}/\d{1,2}/\d{4}\z]) { } 25 54 79
elsif ($v =~ /\A[+\-]?\d[\d,]*(?:\.\d+)?\z/ or $v =~ /\A\(\d[\d,]*(?:\.\d+)?\)\z/) { } 29 25 54
Condition100%3/3
$v =~ /\A\d{4}-\d{2}-\d{2}\z/ or $v =~ m[\A\d{1,2}/\d{1,2}/\d{4}\z]
l!l&&r!l&&!r
24154
MC/DC100%2/2
$v =~ /\A\d{4}-\d{2}-\d{2}\z/ or $v =~ m[\A\d{1,2}/\d{1,2}/\d{4}\z]
$v =~ /\A\d{4}-\d{2}-\d{2}\z/ $v =~ m[\A\d{1,2}/\d{1,2}/\d{4}\z]
Truth table100%3/3
A or B
A= $v =~ /\A\d{4}-\d{2}-\d{2}\z/B= $v =~ m[\A\d{1,2}/\d{1,2}/\d{4}\z]
ABresult
1X1
011
000
1920 25 $type = 'Date';
1921 ▶ } elsif ($v =~ /\A[+\-]?\d[\d,]*(?:\.\d+)?\z/ || $v =~ /\A\(\d[\d,]*(?:\.\d+)?\)\z/) {
Condition66%2/3
$v =~ /\A[+\-]?\d[\d,]*(?:\.\d+)?\z/ or $v =~ /\A\(\d[\d,]*(?:\.\d+)?\)\z/
l!l&&r!l&&!r
29025
MC/DC50%1/2
$v =~ /\A[+\-]?\d[\d,]*(?:\.\d+)?\z/ or $v =~ /\A\(\d[\d,]*(?:\.\d+)?\)\z/
$v =~ /\A[+\-]?\d[\d,]*(?:\.\d+)?\z/ $v =~ /\A\(\d[\d,]*(?:\.\d+)?\)\z/
Truth table66%2/3
A or B
A= $v =~ /\A[+\-]?\d[\d,]*(?:\.\d+)?\z/B= $v =~ /\A\(\d[\d,]*(?:\.\d+)?\)\z/
ABresult
1X1
011
000
1922 29 $type = 'Amount';
1923 } else {
1924 25 $type = 'Description';
1925 }
1926 79 $type_count{$type}++;
1927 79 ▶ push @names, $type_count{$type} == 1 ? $type : $type . $type_count{$type};
Branch: 1 branch
BranchTrueFalseTotal
$type_count{$type} == 1 ? : 72 7 79
1928 }
1929 28 return @names;
1930 }
1931  
1932 # _copy_with_header( $self, \%headerless, \@names, $sep, $stem ) -> ($dir, $id, $size)
1933 #
1934 # Purpose: Give D::A a file it can read for one that has no header: a copy in a
1935 # temporary directory, under the same name, starting with @names.
1936 # Entry: \%headerless is _detect_file_info's { path, ext }.
1937 # Exit: The temporary directory, the column to use as D::A's id and the
1938 # copy's size. Croaks error_backend_init if the file does not parse.
1939 # Notes: Rows are parsed, not copied as text, so each has one value per name:
1940 # a short row is padded, and a long one's extra fields go back into the
1941 # last value, so an unquoted comma in a description is not lost.
1942 # D::A drops a row whose id is empty or starts with '#', so the id is
1943 # the column with the fewest such values, and normally has none.
1944 # The copy is read and written with the escape the file uses
1945 # (_csv_escape_char), so D::A, which chooses the same way, reads the
1946 # copy with it too.
1947 23 ▶sub _copy_with_header :Protected {
Subroutine _copy_with_header: called CC=14 SCAR=26.4
1948 23 my ($self, $headerless, $names, $sep, $stem) = @_;
1949 23 require File::Temp;
1950 23 require Text::CSV;
1951  
1952 23 my $tmp = File::Temp->newdir(CLEANUP => 1);
1953 22 my $copy = File::Spec->catfile("$tmp", "$stem.$headerless->{ext}");
1954 22 my $escape = _csv_escape_char($headerless->{path});
1955 22 my $in = Text::CSV->new({ binary => 1, sep_char => $sep, allow_loose_quotes => 1, escape_char => $escape });
1956 22 my $out = Text::CSV->new({ binary => 1, sep_char => $sep, eol => "\n", escape_char => $escape });
1957  
1958 22 open my $ifh, '<:raw', $headerless->{path};
1959 21 open my $ofh, '>:raw', $copy;
1960 21 $out->print($ofh, $names);
1961  
1962 21 my @unusable = (0) x @{$names};
1963 21 my $first = 1;
1964 21 ▶ while (my $row = $in->getline($ifh)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $in->getline($ifh)) 43 21 64
1965 # A byte-order mark: Text::CSV gives it back decoded (U+FEFF), and the
1966 # rest of the row with it, or as its three bytes.
1967 43 ▶ $row->[0] =~ s/\A(?:\x{FEFF}|\xEF\xBB\xBF)// if $first-- > 0 && defined $row->[0];
Branch: 1 branch
BranchTrueFalseTotal
if $first-- > 0 and defined $row->[0] 19 24 43
Condition66%2/3
$first-- > 0 and defined $row->[0]
!ll&&!rl&&r
24019
MC/DC50%1/2
$first-- > 0 and defined $row->[0]
$first-- > 0 defined $row->[0]
Truth table66%2/3
A and B
A= $first-- > 0B= defined $row->[0]
ABresult
0X0
100
111
1968 43 ▶ next if @{$row} == 1 && $row->[0] !~ /\S/; # a blank line
Branch: 1 branch
BranchTrueFalseTotal
if @{$row;} == 1 and not $row->[0] =~ /\S/ 2 41 43
Condition100%3/3
@{$row;} == 1 and not $row->[0] =~ /\S/
!ll&&!rl&&r
3832
MC/DC100%2/2
@{$row;} == 1 and not $row->[0] =~ /\S/
@{$row;} == 1 not $row->[0] =~ /\S/
Truth table100%3/3
A and not(B)
A= @{$row;} == 1B= not $row->[0] =~ /\S/
ABresult
0X0
100
111
1969 41 ▶ if (@{$row} > @{$names}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$row;} > @{$names;}) 2 39 41
1970 2 my @extra = splice @{$row}, @{$names} - 1;
1971 2 push @{$row}, join($sep, @extra);
1972 }
1973 41 push @{$row}, ('') x (@{$names} - @{$row});
1974 41 for (@{$row}) { s/\A\s+//; s/\s+\z// }
1975 41 $out->print($ofh, $row);
1976 41 for my $i (0 .. $#{$names}) {
1977 117 ▶ $unusable[$i]++ if $row->[$i] !~ /\S/ || $row->[$i] =~ /\A#/;
Branch: 1 branch
BranchTrueFalseTotal
if not $row->[$i] =~ /\S/ or $row->[$i] =~ /\A#/ 5 112 117
Condition100%3/3
not $row->[$i] =~ /\S/ or $row->[$i] =~ /\A#/
l!l&&r!l&&!r
41112
MC/DC100%2/2
not $row->[$i] =~ /\S/ or $row->[$i] =~ /\A#/
not $row->[$i] =~ /\S/ $row->[$i] =~ /\A#/
Truth table100%3/3
not(A) or B
A= not $row->[$i] =~ /\S/B= $row->[$i] =~ /\A#/
ABresult
1X1
011
000
1978 }
1979 }
1980 # eof alone is no proof: it is also true after an unterminated quote. Code
1981 # 2012 is the plain end of the file.
1982 21 my ($code, $why) = $in->error_diag;
1983 21 close $ifh;
1984 21 close $ofh;
1985 21 ▶ croak $self->_msg('error_backend_init', $stem, "cannot parse $headerless->{path}: $why")
Branch: 1 branch
BranchTrueFalseTotal
if $code and $code != $CSV_EOF 3 18 21
Condition66%2/3
$code and $code != $CSV_EOF
!ll&&!rl&&r
0183
MC/DC50%1/2
$code and $code != $CSV_EOF
$code $code != $CSV_EOF
Truth table66%2/3
A and B
A= $codeB= $code != $CSV_EOF
ABresult
0X0
100
111
1986 if $code && $code != $CSV_EOF;
1987  
1988 18 ▶ my ($best) = sort { $unusable[$a] <=> $unusable[$b] || $a <=> $b } 0 .. $#{$names};
Condition66%2/3
$unusable[$a] <=> $unusable[$b] || $a <=> $b
l!l&&r!l&&!r
5450
MC/DC0%0/2
$unusable[$a] <=> $unusable[$b] || $a <=> $b
$unusable[$a] <=> $unusable[$b] $a <=> $b
Truth table66%2/3
A || B
A= $unusable[$a] <=> $unusable[$b]B= $a <=> $b
ABresult
1X1
011
000
1989 18 return ($tmp, $names->[$best], -s $copy);
1990 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1991  
1992 # _cache_key( $self ) -> $key | undef
1993 #
1994 # Purpose: Derive a stable cache key for this DataSource's full result set.
1995 # URL tables use a fixed key (TTL handles invalidation).
1996 # File tables encode the file's mtime in the key so a changed file
1997 # naturally produces a miss -- the stale entry is orphaned and evicts
1998 # passively when the CHI driver reclaims memory.
1999 # Entry: $self->{_cache} must be defined (caller checks this before calling).
2000 # Exit: Returns a non-empty string key, or undef when no key is derivable
2001 # (no URL, no file path on disk).
2002 1642 ▶sub _cache_key :Protected {
Subroutine _cache_key: called CC=6 SCAR=18.0
2003 1642 my $self = shift;
2004  
2005 1642 ▶ if (defined $self->{_url}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"_url"}) 40 1602 1642
2006 40 ▶ my $idx = $self->{_html_table_index} // 0;
Condition50%1/2
$self->{"_html_table_index"} // 0
l!l
400
MC/DC0%0/1
$self->{"_html_table_index"} // 0
$self->{"_html_table_index"}
Truth table50%1/2
A
A= $self->{"_html_table_index"}
Aresult
11
00
2007 # Include the table index in the key: a different index on the same URL
2008 # selects a different table from the page and must not share a cache entry.
2009 40 return 'bi:url:' . $self->{_url} . ':' . $idx;
2010 }
2011  
2012 1602 ▶ if (defined $self->{_file_path} && -f $self->{_file_path}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"_file_path"} and -f $self->{"_file_path"}) 1596 6 1602
Condition100%3/3
defined $self->{"_file_path"} and -f $self->{"_file_path"}
!ll&&!rl&&r
511596
MC/DC100%2/2
defined $self->{"_file_path"} and -f $self->{"_file_path"}
defined $self->{"_file_path"} -f $self->{"_file_path"}
Truth table100%3/3
A and B
A= defined $self->{"_file_path"}B= -f $self->{"_file_path"}
ABresult
0X0
100
111
2013 1596 my $mtime = (stat($self->{_file_path}))[9];
2014 return defined $mtime
2015 1596 ▶ ? 'bi:file:' . $self->{_file_path} . ':' . $mtime
Branch: 1 branch
BranchTrueFalseTotal
defined $mtime ? : 1596 0 1596
2016 : undef;
2017 }
2018  
2019 6 return undef;
2020 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2021  
2022 # _init_backend( $self ) -> void
2023 #
2024 # Strategy: Database::Abstraction is designed as a base class where the
2025 # lowercased package name maps to the data file in the directory
2026 # (e.g. "Database::BI::_DB::Sales" -> data/sales.csv or data/sales.db).
2027 # We synthesise an ephemeral subclass at runtime so DataSource remains
2028 # fully table-agnostic and callers never need to touch Database::Abstraction
2029 # directly. In Phase 2, this method can be replaced with Database::Join
2030 # instantiation without any change to the public API.
2031 #
2032 # no_entry => 1: a BI viewer wants every row; we do not need O(1) keyed
2033 # lookups on a primary key. This stores data as an arrayref instead of a
2034 # hashref, which the fast-track path in selectall_arrayref returns directly.
2035 2267 ▶sub _init_backend :Protected {
Subroutine _init_backend: called CC=54 SCAR=42.2
2036 2267 my $self = shift;
2037 2267 my $table = $self->{_table}; # sanitized: used for pkg name and D::A table param
2038 2267 ▶ my $raw_table = $self->{_raw_table} // $table; # original: used for file lookup and dbname
Condition33%1/3
$self->{"_raw_table"} // $table
l!l&&r!l&&!r
226700
MC/DC0%0/2
$self->{"_raw_table"} // $table
$self->{"_raw_table"} $table
Truth table33%1/3
A // B
A= $self->{"_raw_table"}B= $table
ABresult
1X1
011
000
2039 2267 my $dir = $self->{_directory};
2040  
2041 # Remote file path (host is set): download via SFTP to a local temp directory,
2042 # then proceed with normal local processing on the downloaded copy.
2043 # Net::SFTP::Foreign is loaded lazily so non-remote usage has no extra deps.
2044 2267 ▶ if (defined $self->{_host}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"_host"}) 14 2253 2267
2045 14 ▶ eval { require Net::SFTP::Foreign }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Net::SFTP::Foreign } } or croak($self->_msg("error_backend_init", $table, "Net::SFTP::Foreign is not installed (required for remote file access)")) 13 1 14
2046 or croak $self->_msg('error_backend_init', $table,
2047 'Net::SFTP::Foreign is not installed (required for remote file access)');
2048 13 require File::Temp;
2049 # Split optional user@host into ($user, $host).
2050 my ($user, $host) = $self->{_host} =~ /\A([^@]+)\@(.+)\z/
2051 13 ▶ ? ($1, $2) : (undef, $self->{_host});
Branch: 1 branch
BranchTrueFalseTotal
$self->{'_host'} =~ /\A([^\@]+)\@(.+)\z/ ? : 2 11 13
2052 13 my $tmpdir = File::Temp->newdir(CLEANUP => 1);
2053 13 my @remote_exts = qw(csv tsv psv xlsx xls sql sqlite sqlite3 db xml json jsonl ndjson);
2054 # Try the caller-supplied extension first (e.g. .log), then fall back.
2055 13 ▶ if (defined $self->{_file_ext}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"_file_ext"}) 9 4 13
2056 9 my $hint = lc $self->{_file_ext};
2057 9 @remote_exts = ($hint, grep { $_ ne $hint } @remote_exts);
2058 }
2059 # One SFTP connection shared across all extension attempts.
2060 13 ▶ my $sftp = eval { Net::SFTP::Foreign->new($host,
Branch: 1 branch
BranchTrueFalseTotal
defined $user ? : 2 11 13
2061 defined $user ? (user => $user) : (),
2062 timeout => 10,
2063 ) };
2064 13 ▶ croak $self->_msg('error_backend_init', $table,
Branch: 2 branches
BranchTrueFalseTotal
unless defined $sftp and not $sftp->error 5 8 13
$sftp ? : 2 0 2
Condition83%5/6
defined $sftp and not $sftp->error
!ll&&!rl&&r
328
$@ || ($sftp ? $sftp->error : 'unknown')
l!l&&r!l&&!r
320
MC/DC100%2/2
defined $sftp and not $sftp->error
defined $sftp not $sftp->error
MC/DC0%0/2
$@ || ($sftp ? $sftp->error : 'unknown')
$@ ($sftp ? $sftp->error : 'unknown')
Truth table100%3/3
A and not(B)
A= defined $sftpB= not $sftp->error
ABresult
0X0
100
111
Truth table66%2/3
A || B
A= $@B= ($sftp ? $sftp->error : 'unknown')
ABresult
1X1
011
000
2065 "could not connect to $host via SFTP: " . ($@ || ($sftp ? $sftp->error : 'unknown')))
2066 unless defined $sftp && !$sftp->error;
2067 8 my $fetched_ext;
2068 8 for my $ext (@remote_exts) {
2069 45 my $remote_path = "$dir/$raw_table.$ext";
2070 45 my $local_file = File::Spec->catfile("$tmpdir", "$raw_table.$ext");
2071 45 $sftp->get($remote_path, $local_file);
2072 # Verify the file landed on disk; sftp->error may be set on ENOENT.
2073 45 ▶ next if $sftp->error || !-f $local_file || !-s $local_file;
Branch: 1 branch
BranchTrueFalseTotal
if $sftp->error or not -f $local_file or not -s $local_file 40 5 45
Condition83%5/6
$sftp->error or not -f $local_file or not -s $local_file
l!l&&r!l&&!r
4005
$sftp->error or not -f $local_file
l!l&&r!l&&!r
26145
MC/DC66%2/3
$sftp->error or not -f $local_file or not -s $local_file
$sftp->error not -f $local_file not -s $local_file
Truth table75%3/4
A or not(B) or not(C)
A= $sftp->errorB= not -f $local_fileC= not -s $local_file
ABCresult
1XX1
01X1
0011
0000
2074 5 $fetched_ext = $ext;
2075 5 last;
2076 }
2077 8 ▶ croak $self->_msg('error_backend_init', $table,
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fetched_ext 3 5 8
2078 "could not fetch any supported file from $self->{_host}:$dir/$raw_table.*")
2079 unless defined $fetched_ext;
2080 5 $self->{_remote_tmpdir} = $tmpdir; # prevents cleanup until $self is destroyed
2081  
2082 # If the downloaded file has a non-standard extension (e.g. .log), rename
2083 # it to one that _detect_file_info and D::A can discover automatically.
2084 # We do this by sniffing the first bytes/line for format signatures.
2085 5 my %KNOWN_EXT = map { $_ => 1 }
2086 qw(csv tsv psv xlsx xls sql sqlite sqlite3 db xml json jsonl ndjson);
2087 5 ▶ unless ($KNOWN_EXT{lc $fetched_ext}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($KNOWN_EXT{lc $fetched_ext}) 1 4 5
2088 1 my $orig_file = File::Spec->catfile("$tmpdir", "$raw_table.$fetched_ext");
2089 1 my $std_ext = _sniff_data_ext($orig_file);
2090 1 ▶ if ($std_ext ne lc $fetched_ext) {
Branch: 1 branch
BranchTrueFalseTotal
if ($std_ext ne lc $fetched_ext) 1 0 1
2091 1 my $new_file = File::Spec->catfile("$tmpdir", "$raw_table.$std_ext");
2092 13 ▶ { no autodie; rename $orig_file, $new_file }
Subroutine BEGIN: called CC=1 SCAR=0.0
2093 1 $fetched_ext = $std_ext;
2094 }
2095 }
2096  
2097 5 $dir = "$tmpdir"; # switch to local temp dir for all subsequent processing
2098 }
2099  
2100 2258 require Database::Abstraction;
2101  
2102 2258 my $pkg = 'Database::BI::_DB::' . ucfirst($table);
2103 {
2104 13 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
2105 2258 ▶ push @{"${pkg}::ISA"}, 'Database::Abstraction'
Branch: 1 branch
BranchTrueFalseTotal
unless $pkg->isa("Database::Abstraction") 232 2026 2258
2106 unless $pkg->isa('Database::Abstraction');
2107 }
2108  
2109 2258 my $info = _detect_file_info($dir, $raw_table, $self->{_internal_table}, $self->{_json_flatten});
2110  
2111 # Probe for the actual file on disk so _cache_key can compute its mtime.
2112 # This runs before the early-return paths so even empty files get a path.
2113 2253 for my $e (qw(csv tsv psv sql sqlite sqlite3 xml db xlsx xls json jsonl ndjson)) {
2114 5107 my $p = File::Spec->catfile($dir, "$raw_table.$e");
2115 5107 ▶ if (-f $p) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $p) 2244 2863 5107
2116 2244 $self->{_file_path} = File::Spec->rel2abs($p);
2117 2244 last;
2118 }
2119 }
2120  
2121 # A JSON file's lists of objects are its tables, as a SQLite file's are.
2122 $self->{_sqlite_tables} = $info->{_json_lists}
2123 0 ▶ if $info->{_json_lists} && @{ $info->{_json_lists} };
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"_json_lists"} and @{$info->{"_json_lists"};} 0 2253 2253
Condition33%1/3
$info->{"_json_lists"} and @{$info->{"_json_lists"};}
!ll&&!rl&&r
225300
MC/DC0%0/2
$info->{"_json_lists"} and @{$info->{"_json_lists"};}
$info->{"_json_lists"} @{$info->{"_json_lists"};}
Truth table33%1/3
A and B
A= $info->{"_json_lists"}B= @{$info->{"_json_lists"};}
ABresult
0X0
100
111
2124  
2125 # BerkeleyDB file detected by magic bytes, but tie() failed (version
2126 # incompatibility -- e.g. the file uses BDB format 9 but the installed
2127 # libdb only supports an older format). Croak now so D::A never falls
2128 # through to its CSV path and reads the entire binary file as text.
2129 2253 ▶ if ($info->{_unknown_binary_db}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($info->{"_unknown_binary_db"}) 1 2252 2253
2130 1 croak $self->_msg('error_unsupported_db', $raw_table);
2131 }
2132  
2133 # 0-byte file: skip D::A/DBI entirely. D::A on an empty file falls through
2134 # to DBD::CSV, whose error handling corrupts DBI's Errstr SV and triggers an
2135 # XS assertion failure at cleanup on DEBUGGING perls (DBI 1.651, perl 5.44).
2136 2252 ▶ if ($info->{_file_is_empty}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($info->{"_file_is_empty"}) 12 2240 2252
2137 12 $self->{_columns} = [];
2138 12 $self->{_id_col} = 'entry';
2139 12 $self->{_file_is_empty} = 1;
2140 12 return;
2141 }
2142  
2143 # Header-less CSV/PSV: D::A needs a header, so it reads a copy that has one.
2144 # $self->{_file_path} stays the real file, whose mtime is what counts.
2145 2240 ▶ if (my $headerless = $info->{_headerless}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $headerless = $info->{"_headerless"}) 20 2220 2240
2146 my ($tmp, $id, $size) = $self->_copy_with_header(
2147 20 $headerless, $info->{columns}, $info->{sep_char}, $raw_table);
2148 17 $self->{_headerless_tmpdir} = $tmp; # prevents cleanup until $self is destroyed
2149 17 $info->{id} = $id;
2150 17 $info->{file_size} = $size;
2151 17 $dir = "$tmp";
2152 }
2153  
2154 # A byte-order mark: D::A reads a copy without it, or the first column's
2155 # name would start with it and match nothing a reader types.
2156 # $self->{_file_path} stays the real file, whose mtime is what counts.
2157 2237 ▶ if (my $bom = delete $info->{_bom}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bom = delete $info->{"_bom"}) 0 2237 2237
2158 0 require File::Temp;
2159 0 my $tmp = File::Temp->newdir(CLEANUP => 1);
2160 0 my $copy = File::Spec->catfile("$tmp", "$raw_table.$bom->{ext}");
2161 0 open my $ifh, '<:raw', $bom->{path};
2162 0 open my $ofh, '>:raw', $copy;
2163 0 read $ifh, my $mark, 3;
2164 0 ▶ while (read $ifh, my $chunk, 65_536) { print {$ofh} $chunk }
Branch: 1 branch
BranchTrueFalseTotal
if (&Database::BI::Model::DataSource::read($ifh, \my $chunk, 65536)) 0 0 0
2165 0 close $ifh;
2166 0 close $ofh;
2167 0 $self->{_bom_tmpdir} = $tmp; # prevents cleanup until $self is destroyed
2168 0 $info->{file_size} = -s $copy;
2169 0 $dir = "$tmp";
2170 }
2171  
2172 # JSON: D::A reads a flat copy, a list of rows, whatever shape the file
2173 # had (see _json_table). $self->{_file_path} stays the real file.
2174 2237 ▶ if (my $json = delete $info->{_json}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $json = delete $info->{"_json"}) 0 2237 2237
2175 0 require File::Temp;
2176 0 require Mojo::JSON;
2177 0 my $tmp = File::Temp->newdir(CLEANUP => 1);
2178 0 my $copy = File::Spec->catfile("$tmp", "$raw_table.json");
2179 0 open my $ofh, '>:raw', $copy;
2180 0 ▶ if ($json->{emit}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($json->{'emit'}) { } 0 0 0
2181 0 $json->{emit}->($ofh);
2182 } else {
2183 0 print {$ofh} Mojo::JSON::encode_json($json->{rows});
2184 }
2185 0 close $ofh;
2186 0 $self->{_json_tmpdir} = $tmp; # prevents cleanup until $self is destroyed
2187 0 $self->{_json_list} = $json->{list};
2188 0 $dir = "$tmp";
2189 }
2190  
2191 # _detect_file_info returns undef for id when every column header contains
2192 # characters that are not safe SQL identifiers (spaces, hyphens, etc.).
2193 # Falling back to the D::A default ('entry') would silently return 0 rows
2194 # since no 'entry' column exists. Croak with a human-readable message.
2195 # This guard applies only to CSV/TSV/PSV/SQLite/XML: the header-less and XLSX
2196 # paths always give an id.
2197 croak $self->_msg('error_no_safe_id', $table)
2198 2237 ▶ if exists $info->{columns} && !defined $info->{id};
Branch: 1 branch
BranchTrueFalseTotal
if exists $info->{"columns"} and not defined $info->{"id"} 5 2232 2237
Condition100%3/3
exists $info->{"columns"} and not defined $info->{"id"}
!ll&&!rl&&r
42318095
MC/DC100%2/2
exists $info->{"columns"} and not defined $info->{"id"}
exists $info->{"columns"} not defined $info->{"id"}
Truth table100%3/3
A and not(B)
A= exists $info->{"columns"}B= not defined $info->{"id"}
ABresult
0X0
100
111
2199 2232 ▶ my $id_col = $info->{id} // 'entry';
Condition100%2/2
$info->{"id"} // "entry"
l!l
1809423
MC/DC100%1/1
$info->{"id"} // "entry"
$info->{"id"}
Truth table100%2/2
A
A= $info->{"id"}
Aresult
11
00
2200 2232 $self->{_id_col} = $id_col;
2201 2232 $self->{_columns} = $info->{columns}; # undef for SQLite/XML
2202  
2203 # D::A validates dbname as a SQL identifier and rejects names that contain
2204 # spaces or other characters that are illegal in SQL (e.g. "transactions for
2205 # Nigel"). This check fires at query time (inside selectall_arrayref) for
2206 # the DBI path used by XLSX, SQLite, and XML files -- after construction
2207 # succeeds -- so the error surfaces as error_fetch_failed, not error_backend_init.
2208 #
2209 # Fix: when the original filename stem was sanitized (raw_table != table),
2210 # create a temporary directory with a symlink that uses the safe name.
2211 # D::A opens the symlink, sees a space-free dbname, and builds valid SQL.
2212 # The temp-dir object is kept in $self so the symlink persists for the full
2213 # lifetime of this DataSource instance and is cleaned up automatically when
2214 # $self is destroyed.
2215 2232 my $dbname = $raw_table;
2216 2232 my $da_dir = $dir;
2217 2232 ▶ if ($raw_table ne $table) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw_table ne $table) 14 2218 2232
2218 14 my $safe_ext;
2219 14 for my $e (qw(xlsx xls db sql sqlite sqlite3 xml csv tsv psv json jsonl ndjson)) {
2220 123 ▶ $safe_ext = $e, last
Branch: 1 branch
BranchTrueFalseTotal
if -f "File::Spec"->catfile($dir, "$raw_table.$e") 9 114 123
2221 if -f File::Spec->catfile($dir, "$raw_table.$e");
2222 }
2223 14 ▶ if (defined $safe_ext) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $safe_ext) 9 5 14
2224 9 require File::Temp;
2225 9 my $tmp = File::Temp->newdir(CLEANUP => 1);
2226 9 my $abs_src = File::Spec->rel2abs(
2227 File::Spec->catfile($dir, "$raw_table.$safe_ext"));
2228 9 my $link = File::Spec->catfile("$tmp", "$table.$safe_ext");
2229 {
2230 13 ▶ no autodie; # symlink failure gives our message, not autodie's
Subroutine BEGIN: called CC=1 SCAR=0.0
2231 9 ▶ symlink($abs_src, $link)
Branch: 1 branch
BranchTrueFalseTotal
symlink $abs_src, $link or croak($self->_msg("error_backend_init", $table, "cannot create safe-name symlink for '$raw_table.${safe_ext}': $!")) 9 0 9
2232 or croak $self->_msg('error_backend_init', $table,
2233 "cannot create safe-name symlink for '$raw_table.$safe_ext': $!");
2234 }
2235 9 $self->{_tmpdir} = $tmp; # prevents cleanup until $self is destroyed
2236 9 $dbname = $table;
2237 9 $da_dir = "$tmp";
2238 }
2239 }
2240  
2241 # SQLite: _detect_file_info probed sqlite_master and returned the internal
2242 # table names. When $dbname (the filename stem or its safe alias) is not
2243 # among those names, auto-select the first user table (or use the caller-
2244 # supplied internal_table) and create a symlink from <target>.<ext> to the
2245 # original file so D::A can issue SQL against the real table name.
2246 # D::A uses 'dbname' to find the file and 'table' for the SELECT statement,
2247 # so both must be set to the actual table name when a mismatch is corrected.
2248 2232 my $da_table = $table; # D::A 'table' param -- controls the SQL table name
2249 2232 ▶ if (exists $info->{sqlite_tables}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $info->{"sqlite_tables"}) 406 1826 2232
2250 406 my @tbls = @{ $info->{sqlite_tables} };
2251 406 ▶ croak $self->_msg('error_no_tables', $raw_table) unless @tbls;
Branch: 1 branch
BranchTrueFalseTotal
unless @tbls 1 405 406
2252  
2253 # Store the full table list so callers (e.g. the tables_view action)
2254 # can detect multi-table databases after construction.
2255 405 $self->{_sqlite_tables} = \@tbls;
2256  
2257 # Determine target table: caller-specified or auto-detected.
2258 405 my $desired = $self->{_internal_table};
2259 405 my $target;
2260 405 ▶ if (defined $desired) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $desired) { } 5 400 405
2261 5 my ($found) = grep { $_ eq $desired } @tbls;
2262 5 ▶ croak $self->_msg('error_table_not_found', $raw_table, $desired)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $found 2 3 5
2263 unless defined $found;
2264 3 ▶ if ($desired !~ $TABLE_NAME_RE) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($desired =~ /$TABLE_NAME_RE/) 1 2 3
2265 1 my @others = grep { $_ =~ $TABLE_NAME_RE } @tbls;
2266 1 ▶ croak $self->_msg('error_table_name_unsafe', $desired, $raw_table,
Branch: 1 branch
BranchTrueFalseTotal
@others ? : 1 0 1
2267 (@others ? $self->_msg('error_table_name_others', join(', ', @others)) : ''),
2268 $desired, _safe_table_name($desired));
2269 }
2270 2 $target = $desired;
2271 } else {
2272 # D::A refuses a table name that is not a safe identifier, so the
2273 # first table it can open is chosen, not simply the first table.
2274 400 my @usable = grep { $_ =~ $TABLE_NAME_RE } @tbls;
2275 400 ▶ croak $self->_msg('error_no_usable_tables', $raw_table, join(', ', @tbls),
Branch: 1 branch
BranchTrueFalseTotal
unless @usable 1 399 400
2276 $tbls[0], _safe_table_name($tbls[0])) unless @usable;
2277 399 my ($match) = grep { $_ eq $dbname } @usable;
2278 399 ▶ $target = defined $match ? $match : $usable[0];
Branch: 1 branch
BranchTrueFalseTotal
defined $match ? : 44 355 399
2279 }
2280  
2281 # When the target differs from dbname, create a symlink so D::A can
2282 # find the file by target name and issue SELECT * FROM <target>.
2283 # Always use a D::A-recognised SQLite extension (.sql, .sqlite, .sqlite3)
2284 # for the symlink name -- D::A does not use the DBI/SQLite backend for
2285 # .db files, so a customer.db symlink would be read as CSV. For the same
2286 # reason a SQLite .db file needs the symlink even when its table is named
2287 # after the file: orders.db holding a table called orders.
2288 401 my ($src_ext) = grep { -f File::Spec->catfile($dir, "$raw_table.$_") }
2289 qw(sql sqlite sqlite3 db);
2290 401 ▶ $src_ext //= 'sql';
Condition50%1/2
$src_ext //= "sql"
l!l
4010
MC/DC0%0/1
$src_ext //= "sql"
$src_ext
Truth table50%1/2
A
A= $src_ext
Aresult
11
00
2291 401 ▶ if ($target ne $dbname || $src_ext eq 'db') {
Branch: 1 branch
BranchTrueFalseTotal
if ($target ne $dbname or $src_ext eq "db") 364 37 401
Condition100%3/3
$target ne $dbname or $src_ext eq "db"
l!l&&r!l&&!r
357737
MC/DC100%2/2
$target ne $dbname or $src_ext eq "db"
$target ne $dbname $src_ext eq "db"
Truth table100%3/3
A or B
A= $target ne $dbnameB= $src_ext eq "db"
ABresult
1X1
011
000
2292 364 ▶ my $link_ext = ($src_ext eq 'db') ? 'sql' : $src_ext;
Branch: 1 branch
BranchTrueFalseTotal
$src_ext eq 'db' ? : 356 8 364
2293 364 require File::Temp;
2294 364 my $tmp = File::Temp->newdir(CLEANUP => 1);
2295 363 my $abs_src = File::Spec->rel2abs(
2296 File::Spec->catfile($dir, "$raw_table.$src_ext"));
2297 363 my $link = File::Spec->catfile("$tmp", "$target.$link_ext");
2298 {
2299 13 ▶ no autodie;
Subroutine BEGIN: called CC=1 SCAR=0.0
2300 363 ▶ symlink($abs_src, $link)
Branch: 1 branch
BranchTrueFalseTotal
symlink $abs_src, $link or croak($self->_msg("error_backend_init", $raw_table, "cannot create table-name symlink for '$raw_table.${src_ext}': $!")) 363 0 363
2301 or croak $self->_msg('error_backend_init', $raw_table,
2302 "cannot create table-name symlink for '$raw_table.$src_ext': $!");
2303 }
2304 363 $self->{_tmpdir} = $tmp;
2305 363 $dbname = $target; # D::A uses this for the filename stem
2306 363 $da_table = $target; # D::A uses this for SELECT * FROM <table>
2307 363 $da_dir = "$tmp";
2308 }
2309 }
2310  
2311 2226 my $db = eval {
2312 $pkg->new({
2313 directory => $da_dir,
2314 table => $da_table,
2315 # D::A >= 0.41 uses the class-name suffix as dbname, not the table
2316 # parameter, so a package like Database::BI::_DB::Orders would look
2317 # for Orders.csv on a case-sensitive filesystem even when table =>
2318 # 'orders' is passed. Passing dbname explicitly keeps the filename
2319 # stem correct regardless of the package name or D::A version.
2320 # When the table name was sanitized (spaces, hyphens -> underscores),
2321 # $dbname is the safe name so D::A never sees illegal SQL characters,
2322 # and D::A finds the file via the symlink in $da_dir.
2323 dbname => $dbname,
2324 id => $id_col,
2325 no_entry => 1,
2326 defined($info->{sep_char}) ? (sep_char => $info->{sep_char}) : (),
2327 # Force the Text::xSV::Slurp path for CSV/TSV/PSV files: D::A's default
2328 # slurp threshold is 16 KB; larger files fall back to DBD::CSV, which
2329 # sanitizes column names (lowercases and replaces spaces with
2330 # underscores). Passing the actual file size ensures the slurp path
2331 # is always taken, so "Account Number" stays "Account Number" rather
2332 # than becoming "account_number".
2333 2226 ▶ defined($info->{file_size}) ? (max_slurp_size => $info->{file_size}) : (),
Branch: 2 branches
BranchTrueFalseTotal
defined $info->{'sep_char'} ? : 1809 417 2226
defined $info->{'file_size'} ? : 2209 17 2226
2334 });
2335 };
2336 2226 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 2225 2226
2337 1 croak $self->_msg('error_backend_init', $table, $@);
2338 }
2339  
2340 2225 $self->{_db} = $db;
2341 2225 return;
2342 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2343  
2344 # ---------------------------------------------------------------------------
2345 # Public accessors
2346 # ---------------------------------------------------------------------------
2347  
2348 =head1 ACCESSORS
2349  
2350 =head2 table_name
2351  
2352 Returns the (lowercased) table name this instance was opened against.
2353  
2354 =head3 API SPECIFICATION
2355  
2356 =head4 INPUT
2357  
2358 None.
2359  
2360 =head4 OUTPUT
2361  
2362 Returns a C<SCALAR> string.
2363  
2364 =head3 MESSAGES
2365  
2366 None.
2367  
2368 =cut
2369  
2370 42 ▶sub table_name {
Subroutine table_name: called CC=1 SCAR=0.0
Pod documented
2371 42 my $self = shift;
2372 42 return $self->{_table};
2373 }
2374  
2375 =head2 sqlite_tables
2376  
2377 Returns an arrayref of internal table names when the backing file is a
2378 SQLite database, or of the lists of objects in a JSON file that is an object
2379 holding them (C<{"findings": [...], "hosts": [...]}>), or C<undef> for other
2380 sources. Set during C<_init_backend>.
2381  
2382 When the return value is a reference to a list with B<more than one
2383 element>, the caller should redirect the user to the schema browser
2384 (C</tables>) so they can pick which table to open, rather than
2385 silently opening the first one.
2386  
2387 Example:
2388  
2389 my $tbls = $source->sqlite_tables;
2390 if ($tbls && @{$tbls} > 1) {
2391 # multiple tables -- let the user choose
2392 print "Tables: ", join(', ', @{$tbls}), "\n";
2393 }
2394  
2395 =head3 API SPECIFICATION
2396  
2397 =head4 INPUT
2398  
2399 None.
2400  
2401 =head4 OUTPUT
2402  
2403 ARRAYREF of SCALAR # ['customer', 'product', 'sales'] for a 3-table SQLite file
2404 ARRAYREF of SCALAR # ['findings', 'hosts'] for a JSON file holding two lists
2405 undef # for CSV, TSV, PSV, XML, URL-backed, and a JSON list or keyed object
2406  
2407 A SQLite file's names are in the order returned by C<sqlite_master>
2408 (alphabetical), a JSON file's in the order the file gives them. It is set
2409 once during construction and never changes.
2410  
2411 =head3 MESSAGES
2412  
2413 None.
2414  
2415 =cut
2416  
2417 606 ▶sub sqlite_tables {
Subroutine sqlite_tables: called CC=1 SCAR=0.0
Pod documented
2418 606 my $self = shift;
2419 606 return $self->{_sqlite_tables};
2420 }
2421  
2422 =head2 split_path
2423  
2424 my ($file, $table) = Database::BI::Model::DataSource::split_path('/data/scan.json#hosts');
2425 # ('/data/scan.json', 'hosts')
2426  
2427 What a C<path:> spec names: a file and, after a C<#>, one of its tables (a
2428 SQLite file's table, or a JSON file's list). C<path:/data/store.db#sales> is
2429 the C<sales> table of C<store.db>, as C<table:store/sales> is when the file is
2430 in C<data_dir>. When the whole text names a file that exists, it is that
2431 file, so a file whose name has a C<#> in it still opens; and a remote path
2432 (C</../host/...>) is split the same way, since there is no file here to look
2433 for.
2434  
2435 =head3 API SPECIFICATION
2436  
2437 =head4 INPUT
2438  
2439 $path SCALAR what follows "path:" in a spec
2440  
2441 =head4 OUTPUT
2442  
2443 ($file, $table) $table undef when none is named; ('', undef) for undef
2444  
2445 =head3 MESSAGES
2446  
2447 None.
2448  
2449 =head3 FORMAL SPECIFICATION
2450  
2451 split_path == lambda p .
2452 if exists(p) then (p, undef)
2453 else if p = f ++ "#" ++ t /\ t /= "" /\ "#" not in t then (f, t)
2454 else (p, undef)
2455  
2456 =cut
2457  
2458 2087 ▶sub split_path {
Subroutine split_path: called CC=5 SCAR=16.1
Pod documented
2459 2087 my ($path) = @_;
2460 2087 ▶ return ('', undef) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 2087 2087
2461 # A NUL or a newline cannot be in a Windows file name, and stat on one warns
2462 # there ("Invalid \0 character in pathname", "filename containing newline").
2463 13 ▶ return ($path, undef) if CORE::index($path, "\0") < 0 && do { no warnings 'newline'; -e $path };
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if index($path, "\0") == -1 and do { BEGIN {${^WARNING_BITS} = "\x55\x55\x51\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} -e $path } 1717 370 2087
Condition100%3/3
index($path, "\0") == -1 and do { BEGIN {${^WARNING_BITS} = "\x55\x55\x51\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} -e $path }
!ll&&!rl&&r
13691717
MC/DC100%2/2
index($path, "\0") == -1 and do { BEGIN {${^WARNING_BITS} = "\x55\x55\x51\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} -e $path }
index($path, "\0") == -1 do { BEGIN {${^WARNING_BITS} = "\x55\x55\x51\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} -e $path }
Truth table100%3/3
A and B
A= index($path, "\0") == -1B= do { BEGIN {${^WARNING_BITS} = "\x55\x55\x51\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} -e $path }
ABresult
0X0
100
111
2464 370 ▶ return ($1, $2) if $path =~ /\A(.+)#([^#\n]+)\z/s;
Branch: 1 branch
BranchTrueFalseTotal
if $path =~ /\A(.+)#([^#\n]+)\z/s 2 368 370
2465 368 return ($path, undef);
2466 }
2467  
2468 =head2 json_lists
2469  
2470 my $lists = Database::BI::Model::DataSource->json_lists('/data/scan.json');
2471 # [ { name => 'findings', columns => ['detail', 'host', ...] },
2472 # { name => 'hosts', columns => ['base', 'host', ...] } ]
2473  
2474 The tables of a JSON file that is an object holding lists of objects: one
2475 entry per list, in the order the file gives them, with its columns in the
2476 order the file first names them. The schema browser (C</tables>) shows a
2477 card for each; C<< new(internal_table => $name) >> opens one.
2478  
2479 A list holding anything but objects is not a table, and an empty list counts
2480 only when no list has rows. Other values beside the lists (a count, a date,
2481 an object of totals) are not tables.
2482  
2483 =head3 API SPECIFICATION
2484  
2485 =head4 INPUT
2486  
2487 $class SCALAR the class (called as a class method)
2488 $path SCALAR a readable .json file
2489  
2490 =head4 OUTPUT
2491  
2492 ARRAYREF of HASHREF { name => SCALAR, columns => ARRAYREF of SCALAR }
2493 empty when the file holds no lists (a list of rows,
2494 an object of rows, a blank file)
2495  
2496 Croaks C<error_json_invalid> when the file is not JSON.
2497  
2498 =head3 MESSAGES
2499  
2500 C<error_json_invalid>.
2501  
2502 =head3 FORMAL SPECIFICATION
2503  
2504 json_lists == lambda path .
2505 let (text, data) = parse(path) in
2506 [ { name => k, columns => key_order(text, data.k) } | k <- list_keys(text, data) ]
2507  
2508 pre readable(path)
2509 post forall e in result . data.(e.name) : seq HASH
2510  
2511 =cut
2512  
2513 2 ▶sub json_lists {
Subroutine json_lists: called CC=2 SCAR=7.0
Pod documented
2514 2 my ($class, $path) = @_;
2515 2 local ($@, $!);
2516 2 my ($text, $data) = _json_read($path);
2517 2 ▶ return [] unless length $text;
Branch: 1 branch
BranchTrueFalseTotal
unless length $text 0 2 2
2518 return [ map {
2519 2 { name => $_, columns => _json_columns($text, $data->{$_}, 3, $_) }
2520 } _json_list_keys($text, $data) ];
2521 }
2522  
2523 =head2 columns
2524  
2525 Returns an arrayref of column names in file order, or C<undef> when no order
2526 is available.
2527  
2528 =over 4
2529  
2530 =item CSV / TSV / PSV / XLSX
2531  
2532 Column names come from the file header (first row). They are returned in
2533 the order they appear in the file. For header-less files (detected
2534 automatically) the synthesized names (C<Date>, C<Amount>, C<Description>,
2535 etc.) are returned in the same synthesized order.
2536  
2537 =item SQLite / XML
2538  
2539 Falls back to the underlying C<Database::Abstraction> object's C<columns()>
2540 method. This is useful when a C<DataSource> is passed directly to
2541 C<Database::Join> as a component database.
2542  
2543 =item URL-backed tables
2544  
2545 Always returns C<undef>. C<Database::Abstraction> fetches URL data lazily,
2546 so calling C<_db-E<gt>columns()> here would trigger a live network request even
2547 when the data came from the CHI cache. The controller derives column order
2548 from the data records instead (alphabetical fallback).
2549  
2550 =item Redis-backed tables
2551  
2552 Delegates to the underlying C<Database::Abstraction> C<columns()>, which
2553 triggers a lazy open of the Redis connection on first call and returns the
2554 column names derived from the first stored row (alphabetical order, includes
2555 C<entry>). This is required so that C<Database::Join> can validate the
2556 join column at construction time.
2557  
2558 =back
2559  
2560 Always check the return value before dereferencing:
2561  
2562 my $cols = $source->columns;
2563 if ($cols) {
2564 print join(', ', @{$cols}), "\n";
2565 } else {
2566 # URL-backed tables: derive columns from the first data row
2567 }
2568  
2569 =head3 API SPECIFICATION
2570  
2571 =head4 INPUT
2572  
2573 None.
2574  
2575 =head4 OUTPUT
2576  
2577 ARRAYREF of SCALAR # ['id', 'name', 'price', ...] -- original header order
2578 undef # SQLite, XML, URL-backed tables
2579  
2580 =head3 MESSAGES
2581  
2582 None.
2583  
2584 =cut
2585  
2586 1715 ▶sub columns {
Subroutine columns: called CC=10 SCAR=28.1
Pod documented
2587 1715 my $self = shift;
2588 1715 local ($@, $!); # the backend opens lazily, and uses both on the way
2589 1715 local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows
2590 1715 ▶ return $self->{_columns} if defined $self->{_columns};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_columns"} 1627 88 1715
2591 # A caller that knows the order (an extract, which records its file's) says
2592 # so; a SQLite backend would otherwise list the columns alphabetically.
2593 88 ▶ return [ @{ $self->{_column_order} } ] if $self->{_column_order} && @{ $self->{_column_order} };
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_column_order"} and @{$self->{"_column_order"};} 1 87 88
Condition66%2/3
$self->{"_column_order"} and @{$self->{"_column_order"};}
!ll&&!rl&&r
8701
MC/DC50%1/2
$self->{"_column_order"} and @{$self->{"_column_order"};}
$self->{"_column_order"} @{$self->{"_column_order"};}
Truth table66%2/3
A and B
A= $self->{"_column_order"}B= @{$self->{"_column_order"};}
ABresult
0X0
100
111
2594 # URL-backed tables have no canonical column order at construction time;
2595 # calling _db->columns() would trigger a live HTTP request which may fail.
2596 # Return undef so _get_columns derives column names from fetched data.
2597 87 ▶ return undef if defined $self->{_url};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_url"} 14 73 87
2598 # Redis-backed tables: delegate to _db->columns() which triggers the lazy
2599 # open() on first call. D::J requires a real column list at construction
2600 # time so returning undef here would make join validation always fail.
2601 # D::A builds its Redis column list from hgetall fields only and omits the
2602 # entry key (the suffix of the Redis key pattern tablename:entryid).
2603 # Prepend the id column so callers and D::J see a complete column list.
2604 73 ▶ if (defined $self->{_redis_url} && $self->{_db}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"_redis_url"} and $self->{"_db"}) 0 73 73
Condition33%1/3
defined $self->{"_redis_url"} and $self->{"_db"}
!ll&&!rl&&r
7300
MC/DC0%0/2
defined $self->{"_redis_url"} and $self->{"_db"}
defined $self->{"_redis_url"} $self->{"_db"}
Truth table33%1/3
A and B
A= defined $self->{"_redis_url"}B= $self->{"_db"}
ABresult
0X0
100
111
2605 0 ▶ my $da_cols = $self->{_db}->columns() // [];
Condition0%0/2
$self->{"_db"}->columns // []
l!l
00
MC/DC0%0/1
$self->{"_db"}->columns // []
$self->{"_db"}->columns
Truth table0%0/2
A
A= $self->{"_db"}->columns
Aresult
11
00
2606 0 ▶ my $id = $self->{_id_col} // 'entry';
Condition0%0/2
$self->{"_id_col"} // "entry"
l!l
00
MC/DC0%0/1
$self->{"_id_col"} // "entry"
$self->{"_id_col"}
Truth table0%0/2
A
A= $self->{"_id_col"}
Aresult
11
00
2607 0 my @full = ($id, grep { $_ ne $id } @{$da_cols});
2608 0 $self->{_columns} = \@full;
2609 0 return $self->{_columns};
2610 }
2611 73 ▶ return $self->{_db} ? $self->{_db}->columns() : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'_db'} ? : 69 4 73
2612 }
2613  
2614 =head2 dbi_source
2615  
2616 Returns a hashref C<{ dbh =E<gt> $dbh, table =E<gt> $name }> for SQLite-backed
2617 instances, and C<undef> for everything else.
2618  
2619 C<Database::Join> 0.009.0 probes C<dbi_source> at join-construction time to
2620 decide whether it can take the zero-copy C<ATTACH> path (avoiding a row-by-row
2621 spill into a temporary SQLite file). Without this method, every C</join> on a
2622 SQLite-backed C<DataSource> uses the spill path regardless of row count.
2623  
2624 Returns C<undef> for:
2625  
2626 =over 4
2627  
2628 =item *
2629  
2630 0-byte files (C<_file_is_empty> set).
2631  
2632 =item *
2633  
2634 Redis-backed and URL-backed sources (no DBI handle).
2635  
2636 =item *
2637  
2638 Any backend that does not itself implement C<dbi_source>.
2639  
2640 =back
2641  
2642 =head3 API SPECIFICATION
2643  
2644 =head4 INPUT
2645  
2646 None.
2647  
2648 =head4 OUTPUT
2649  
2650 { dbh => $dbh_object, table => 'table_name' } # SQLite-backed
2651 undef # all other backends
2652  
2653 =head3 MESSAGES
2654  
2655 None.
2656  
2657 =cut
2658  
2659 369 ▶sub dbi_source {
Subroutine dbi_source: called CC=5 SCAR=16.2
Pod documented
2660 369 my $self = shift;
2661 369 ▶ return undef if $self->{_file_is_empty};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_file_is_empty"} 7 362 369
2662 362 ▶ return undef unless $self->{_db};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_db"} 0 362 362
2663 362 ▶ return undef unless $self->{_db}->can('dbi_source');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_db"}->can("dbi_source") 0 362 362
2664 362 my $result = eval { $self->{_db}->dbi_source() };
2665 362 ▶ return undef if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 4 358 362
2666 358 return $result;
2667 }
2668  
2669 =head2 aggregate
2670  
2671 Delegates to the inner C<Database::Abstraction> backend's C<aggregate()> method
2672 (requires C<Database::Abstraction> E<gt>= 0.49).
2673  
2674 Returns C<[]> for in-memory backends (headerless CSV, XLSX, empty files) and for
2675 URL-backed sources where aggregation is not available.
2676  
2677 Accepts the same C<by>, C<measures>, C<having>, C<sort_by>, C<limit>, C<offset>,
2678 and WHERE-criteria parameters as C<Database::Abstraction::aggregate()>.
2679  
2680 =head3 API SPECIFICATION
2681  
2682 =head4 INPUT
2683  
2684 by arrayref Column names to GROUP BY.
2685 measures arrayref Measure descriptors (see Database::Abstraction::aggregate).
2686 having hashref Optional HAVING criteria.
2687 sort_by string Optional ORDER BY column.
2688 limit integer Optional result limit.
2689 offset integer Optional result offset.
2690 (any other key) WHERE column criteria passed through to D::A.
2691  
2692 =head4 OUTPUT
2693  
2694 arrayref of hashrefs -- one row per group.
2695 [] -- in-memory / empty / URL-backed sources.
2696  
2697 =head3 MESSAGES
2698  
2699 None.
2700  
2701 =cut
2702  
2703 560 ▶sub aggregate {
Subroutine aggregate: called CC=4 SCAR=14.0
Pod documented
2704 560 my ($self, @args) = @_;
2705 560 local ($@, $!); # the backend opens lazily, and uses both on the way
2706 560 local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows
2707 560 ▶ return [] if $self->{_file_is_empty};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_file_is_empty"} 1 559 560
2708 559 ▶ return [] unless $self->{_db};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_db"} 0 559 559
2709 559 ▶ return [] unless $self->{_db}->can('aggregate');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_db"}->can("aggregate") 0 559 559
2710 559 return $self->{_db}->aggregate(@args);
2711 }
2712  
2713 =head2 pages_on_server
2714  
2715 Returns true when C<selectall_arrayref> with C<limit> and C<offset> runs on a
2716 database server without reading the whole table, as it does for MariaDB.
2717  
2718 C<dbi_source> cannot say this: it answers only for SQLite, because
2719 C<Database::Join> takes it to mean that a file can be attached.
2720  
2721 =head3 API SPECIFICATION
2722  
2723 =head4 INPUT
2724  
2725 None.
2726  
2727 =head4 OUTPUT
2728  
2729 SCALAR boolean
2730  
2731 =head3 MESSAGES
2732  
2733 None.
2734  
2735 =cut
2736  
2737 287 ▶sub pages_on_server {
Subroutine pages_on_server: called CC=2 SCAR=6.9
Pod documented
2738 287 my $self = shift;
2739 287 ▶ return defined $self->{_mariadb} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'_mariadb'} ? : 5 282 287
2740 }
2741  
2742 =head2 mariadb_tables
2743  
2744 Class method. Lists the tables and views of one MariaDB or MySQL database, with
2745 their columns in the table's own order.
2746  
2747 my $tables = Database::BI::Model::DataSource->mariadb_tables('shop', {
2748 host => 'db.example.com', database => 'shop',
2749 username => 'bi', password => 'secret',
2750 });
2751  
2752 =head3 API SPECIFICATION
2753  
2754 =head4 INPUT
2755  
2756 $server SCALAR string the name of the server, for messages
2757 $settings HASHREF { database, host?, port?, username?, password? }
2758  
2759 =head4 OUTPUT
2760  
2761 ARRAYREF of { name => string, columns => [ string, ... ] }, sorted by name
2762  
2763 =head3 MESSAGES
2764  
2765 Croaks with C<error_mariadb_unknown_server>, C<error_mariadb_settings>,
2766 C<error_mariadb_no_driver> or C<error_mariadb_connect>.
2767  
2768 =cut
2769  
2770 5 ▶sub mariadb_tables {
Subroutine mariadb_tables: called CC=2 SCAR=6.9
Pod documented
2771 5 my ($class, $server, $settings) = @_;
2772 5 local ($@, $!);
2773 5 local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows
2774  
2775 5 my ($dsn, $username, $password) = _mariadb_dsn($server, $settings);
2776 4 my $tables = eval {
2777 4 Database::Join::Catalog->schema(dsn => $dsn, username => $username, password => $password);
2778 };
2779 4 ▶ croak _fmt('error_mariadb_connect', $server, "$@") unless $tables;
Branch: 1 branch
BranchTrueFalseTotal
unless $tables 3 1 4
2780 1 return $tables;
2781 }
2782  
2783 =head2 id_column
2784  
2785 Returns the name of the column used as the primary key and as
2786 C<Database::Abstraction>'s row-existence anchor.
2787  
2788 For file-backed tables this is the first column in the CSV/TSV/PSV header
2789 whose name is a valid SQL identifier (letters, digits, underscores only,
2790 not starting with a digit) B<and> whose value in the first data row is
2791 non-empty. C<DataSource> detects this automatically to avoid the
2792 C<Database::Abstraction> default of C<'entry'>, which would silently
2793 discard every row in a file that has no C<entry> column.
2794  
2795 Returns C<undef> for URL/HTML-table backends (no primary-key concept applies).
2796  
2797 =head3 API SPECIFICATION
2798  
2799 =head4 INPUT
2800  
2801 None.
2802  
2803 =head4 OUTPUT
2804  
2805 SCALAR string # e.g. 'id', 'date', 'sku' -- the first safe-identifier column
2806 undef # URL-backed (HTML table import) sources
2807  
2808 =head3 MESSAGES
2809  
2810 None.
2811  
2812 =cut
2813  
2814 8 ▶sub id_column {
Subroutine id_column: called CC=1 SCAR=0.0
Pod documented
2815 8 my $self = shift;
2816 8 return $self->{_id_col};
2817 }
2818  
2819 =head2 source_url
2820  
2821 Returns the source URL for URL/HTML-table-backed instances.
2822 Returns C<undef> for all file-backed instances (local files and SFTP-fetched
2823 remote files).
2824  
2825 Use this to distinguish a URL-backed C<DataSource> from a file-backed one
2826 when you need to decide whether to show a "re-fetch" button to the user.
2827  
2828 =head3 API SPECIFICATION
2829  
2830 =head4 INPUT
2831  
2832 None.
2833  
2834 =head4 OUTPUT
2835  
2836 SCALAR string # 'https://example.com/data.html' -- the original URL
2837 undef # file-backed (local or SFTP) sources
2838  
2839 =head3 MESSAGES
2840  
2841 None.
2842  
2843 =cut
2844  
2845 2 ▶sub source_url {
Subroutine source_url: called CC=1 SCAR=0.0
Pod documented
2846 2 my $self = shift;
2847 2 return $self->{_url};
2848 }
2849  
2850 =head2 updated
2851  
2852 Returns the Unix epoch timestamp (mtime) of the backing data file, or
2853 C<undef> for URL-backed tables and for sources whose file cannot be
2854 C<stat()>-ed.
2855  
2856 C<Database::Join> calls C<updated()> on each component database to
2857 detect whether its SQLite spill cache is stale. When a source file changes
2858 on disk, the mtime increases, the join detects the change, and re-runs the
2859 join rather than serving stale cached data.
2860  
2861 =head3 API SPECIFICATION
2862  
2863 =head4 INPUT
2864  
2865 None.
2866  
2867 =head4 OUTPUT
2868  
2869 SCALAR integer # Unix epoch seconds, e.g. 1728601234
2870 undef # URL-backed tables, or file cannot be stat()-ed
2871  
2872 =head3 MESSAGES
2873  
2874 None.
2875  
2876 =cut
2877  
2878 85 ▶sub updated {
Subroutine updated: called CC=5 SCAR=16.1
Pod documented
2879 85 my $self = shift;
2880 # The file itself comes first. D::A only learns an mtime when it opens the file,
2881 # which it does lazily, so before the first read it answers undef, and after it
2882 # goes on answering the time of that read however the file has changed since.
2883 85 ▶ return (stat($self->{_file_path}))[9] if defined $self->{_file_path} && -f $self->{_file_path};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_file_path"} and -f $self->{"_file_path"} 82 3 85
Condition100%3/3
defined $self->{"_file_path"} and -f $self->{"_file_path"}
!ll&&!rl&&r
2182
MC/DC100%2/2
defined $self->{"_file_path"} and -f $self->{"_file_path"}
defined $self->{"_file_path"} -f $self->{"_file_path"}
Truth table100%3/3
A and B
A= defined $self->{"_file_path"}B= -f $self->{"_file_path"}
ABresult
0X0
100
111
2884 3 ▶ return $self->{_db}->updated() if $self->{_db} && $self->{_db}->can('updated');
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_db"} and $self->{"_db"}->can("updated") 1 2 3
Condition66%2/3
$self->{"_db"} and $self->{"_db"}->can("updated")
!ll&&!rl&&r
201
MC/DC50%1/2
$self->{"_db"} and $self->{"_db"}->can("updated")
$self->{"_db"} $self->{"_db"}->can("updated")
Truth table66%2/3
A and B
A= $self->{"_db"}B= $self->{"_db"}->can("updated")
ABresult
0X0
100
111
2885 2 return undef;
2886 }
2887  
2888 =head2 schema
2889  
2890 Delegates to the inner C<Database::Abstraction> backend's C<schema()> method.
2891  
2892 The join routes compare the declared types of columns that appear in more than
2893 one joined table, and the panel keeps no schema of its own. Without this
2894 delegation a DataSource was schema-less, so every comparison found nothing and
2895 a TEXT/INTEGER mismatch across a join went unreported; the controller's
2896 C<_schema_type_warnings> uses this method to fill the schema-warnings banner.
2897  
2898 Returns a hashref of C<< column => { type => ..., nullable => ..., ... } >>.
2899 File formats that C<Database::Abstraction> reads as text (CSV, TSV, PSV, XML,
2900 XLSX) report C<TEXT>; SQLite reports the declared column types. Returns an
2901 empty hashref when the inner backend cannot provide a schema.
2902  
2903 =head3 API SPECIFICATION
2904  
2905 =head4 INPUT
2906  
2907 None.
2908  
2909 =head4 OUTPUT
2910  
2911 HASHREF column name => schema metadata hashref (possibly empty)
2912  
2913 =head3 MESSAGES
2914  
2915 None.
2916  
2917 =cut
2918  
2919 77 ▶sub schema {
Subroutine schema: called CC=5 SCAR=16.1
Pod documented
2920 77 my $self = shift;
2921 77 local ($@, $!); # the backend opens lazily, and uses both on the way
2922 77 local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows
2923  
2924 77 ▶ return {} unless $self->{_db} && $self->{_db}->can('schema');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_db"} and $self->{"_db"}->can("schema") 2 75 77
Condition100%3/3
$self->{"_db"} and $self->{"_db"}->can("schema")
!ll&&!rl&&r
1175
MC/DC100%2/2
$self->{"_db"} and $self->{"_db"}->can("schema")
$self->{"_db"} $self->{"_db"}->can("schema")
Truth table100%3/3
A and B
A= $self->{"_db"}B= $self->{"_db"}->can("schema")
ABresult
0X0
100
111
2925  
2926 75 my $schema = eval { $self->{_db}->schema() };
2927 75 ▶ return {} if $@ || ref($schema) ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if $@ or ref $schema ne "HASH" 3 72 75
Condition100%3/3
$@ or ref $schema ne "HASH"
l!l&&r!l&&!r
1272
MC/DC100%2/2
$@ or ref $schema ne "HASH"
$@ ref $schema ne "HASH"
Truth table100%3/3
A or B
A= $@B= ref $schema ne "HASH"
ABresult
1X1
011
000
2928  
2929 72 return $schema;
2930 }
2931  
2932 # ---------------------------------------------------------------------------
2933 # Public data-access methods
2934 # ---------------------------------------------------------------------------
2935  
2936 =head1 METHODS
2937  
2938 =head2 fetch_all
2939  
2940 Returns every record in the table as an arrayref of hashrefs (one hashref
2941 per row; keys are the column names).
2942  
2943 This is the primary data-retrieval method. It is equivalent to calling
2944 C<selectall_arrayref> with no arguments and normalising the result to an
2945 arrayref. Prefer C<selectall_arrayref> when passing to C<Database::Join>
2946 (it is the method that C<Database::Join> calls internally).
2947  
2948 Filtering (C<eq>, C<contains>, C<gt>, C<lt>, etc.) is applied at the
2949 controller layer by C<Dashboard::_apply_filter_spec> after C<fetch_all>
2950 returns. C<DataSource> itself is filter-unaware.
2951  
2952 Three fast-path shortcuts are checked before touching the DBI backend,
2953 in this order:
2954  
2955 =over 4
2956  
2957 =item 1.
2958  
2959 C<_file_is_empty> is set (0-byte or blank-first-line file) -- returns C<[]>
2960 immediately, no DBI connection.
2961  
2962 =item 2.
2963  
2964 A matching CHI cache entry exists -- returns the cached arrayref without
2965 calling C<Database::Abstraction>.
2966  
2967 =back
2968  
2969 =head3 API SPECIFICATION
2970  
2971 =head4 INPUT
2972  
2973 None. Filtering is applied at the controller layer, not inside C<DataSource>.
2974  
2975 =head4 OUTPUT
2976  
2977 ARRAYREF of HASHREF # one hashref per row; keys are column names
2978 [] # empty arrayref when the file is empty or has no data rows
2979  
2980 Croaks (via C<croak>) when the backend raises an exception. Emits a
2981 warning via C<carp> (non-fatal) when the result set is empty, so the
2982 caller can distinguish "opened successfully, no data" from a silent
2983 failure.
2984  
2985 =head3 MESSAGES
2986  
2987 error_fetch_failed -- backend threw an exception during retrieval
2988 warn_empty_result -- query succeeded but returned zero records
2989 warn_data_normalised -- backend returned a hashref; converted to arrayref
2990  
2991 =cut
2992  
2993 =head2 selectall_arrayref
2994  
2995 C<Database::Abstraction>-compatible alias that allows a C<DataSource> object
2996 to be passed directly to C<Database::Join> as a component database.
2997  
2998 When called with no arguments (the normal path for a full-table scan),
2999 results are served from the CHI cache when available. When called with
3000 arguments (e.g. C<limit =E<gt> N, offset =E<gt> M> for server-side
3001 pagination), the cache is bypassed -- narrowed results must not pollute
3002 the full-table cache entry.
3003  
3004 Three fast-path shortcuts are checked before touching the DBI backend:
3005  
3006 =over 4
3007  
3008 =item 1.
3009  
3010 C<_file_is_empty> is set -- returns C<[]> immediately.
3011  
3012 =item 2.
3013  
3014 The call sorts on a column whose name is not a safe identifier, such as
3015 C<First Name>. L<Database::Abstraction> ignores such a column, so this method
3016 fetches the rows and sorts and pages them itself, comparing as strings as
3017 L<Database::Abstraction> does.
3018  
3019 =item 3.
3020  
3021 A matching CHI cache entry exists for the full-table scan -- returns the
3022 cached arrayref.
3023  
3024 =back
3025  
3026 =head3 API SPECIFICATION
3027  
3028 =head4 INPUT
3029  
3030 Optional flat key/value list passed through to C<Database::Abstraction>:
3031  
3032 limit => N # return at most N rows (used by pagination)
3033 offset => M # skip the first M rows (used by pagination)
3034  
3035 When no arguments are given, the full table is returned (and cached).
3036  
3037 =head4 OUTPUT
3038  
3039 ARRAYREF of HASHREF # one hashref per row; keys are column names
3040 [] # empty arrayref when the file is empty or no rows match
3041  
3042 =head3 MESSAGES
3043  
3044 None. Errors from the DBI backend propagate as uncaught exceptions; wrap
3045 calls in C<eval> if you need to recover.
3046  
3047 =cut
3048  
3049 1493 ▶sub selectall_arrayref {
Subroutine selectall_arrayref: called CC=20 SCAR=32.0
3050 1493 my ($self, @args) = @_;
3051 1493 local ($@, $!); # the backend opens lazily, and uses both on the way
3052 1493 local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows
3053 1493 ▶ return [] if $self->{_file_is_empty};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_file_is_empty"} 7 1486 1493
3054  
3055 # A server gives LIMIT rows in no promised order, so pages could overlap.
3056 1486 ▶ if (defined $self->{_order_col} && @args && !ref $args[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"_order_col"} and @args and not ref $args[0]) 0 1486 1486
Condition33%2/6
defined $self->{"_order_col"} and @args and not ref $args[0]
!ll&&!rl&&r
148600
defined $self->{"_order_col"} and @args
!ll&&!rl&&r
148600
MC/DC0%0/3
defined $self->{"_order_col"} and @args and not ref $args[0]
defined $self->{"_order_col"} @args not ref $args[0]
Truth table25%1/4
A and B and not(C)
A= defined $self->{"_order_col"}B= @argsC= not ref $args[0]
ABCresult
0XX0
10X0
1100
1111
3057 0 my %asked = @args;
3058 push @args, sort_by => [ $self->{_order_col}, 'asc' ]
3059 0 ▶ if exists $asked{limit} && !$asked{sort_by};
Branch: 1 branch
BranchTrueFalseTotal
if exists $asked{"limit"} and not $asked{"sort_by"} 0 0 0
Condition0%0/3
exists $asked{"limit"} and not $asked{"sort_by"}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $asked{"limit"} and not $asked{"sort_by"}
exists $asked{"limit"} not $asked{"sort_by"}
Truth table0%0/3
A and not(B)
A= exists $asked{"limit"}B= not $asked{"sort_by"}
ABresult
0X0
100
111
3060 }
3061  
3062 # D::A ignores a sort column whose name is not a safe identifier.
3063 1486 ▶ if (my ($rest, @page) = _unsafe_sort(@args)) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = _unsafe_sort(@args)) 2 1484 1486
3064 2 return _sorted_page($self->selectall_arrayref(%{$rest}), @page);
3065 }
3066  
3067 # Cache only plain unfiltered calls -- Database::Join passes no args for the
3068 # full table scan; a non-empty @args means a narrowed query whose result must
3069 # not be mistaken for the full-table cache entry.
3070 1484 my $cache = $self->{_cache};
3071 1484 ▶ if ($cache && !@args) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache and not @args) 1399 85 1484
Condition100%3/3
$cache and not @args
!ll&&!rl&&r
18671399
MC/DC100%2/2
$cache and not @args
$cache not @args
Truth table100%3/3
A and not(B)
A= $cacheB= not @args
ABresult
0X0
100
111
3072 1399 my $key = $self->_cache_key;
3073 1399 ▶ if (defined $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 1395 4 1399
3074 1395 my $hit = $cache->get($key);
3075 1395 ▶ return $hit if defined $hit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $hit 1218 177 1395
3076 }
3077 }
3078  
3079 266 my $data = $self->{_db}->selectall_arrayref(@args);
3080  
3081 # As in fetch_all: what a URL answers with need not be a table.
3082 croak $self->_msg('error_fetch_failed', $self->{_table}, $self->_msg('error_rows_not_records'))
3083 251 ▶ if defined $self->{_url} && ref $data eq 'ARRAY' && grep { ref $_ ne 'HASH' } @{$data};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_url"} and ref $data eq "ARRAY" and grep {ref $_ ne "HASH";} @{$data;} 2 249 251
Condition66%4/6
defined $self->{"_url"} and ref $data eq "ARRAY" and grep {ref $_ ne "HASH";} @{$data;}
!ll&&!rl&&r
24902
defined $self->{"_url"} and ref $data eq "ARRAY"
!ll&&!rl&&r
24902
MC/DC33%1/3
defined $self->{"_url"} and ref $data eq "ARRAY" and grep {ref $_ ne "HASH";} @{$data;}
defined $self->{"_url"} ref $data eq "ARRAY" grep {ref $_ ne "HASH";} @{$data;}
Truth table50%2/4
A and B and C
A= defined $self->{"_url"}B= ref $data eq "ARRAY"C= grep {ref $_ ne "HASH";} @{$data;}
ABCresult
0XX0
10X0
1100
1111
3084  
3085 249 ▶ if ($cache && !@args && defined $data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache and not @args and defined $data) 165 84 249
Condition100%6/6
$cache and not @args and defined $data
!ll&&!rl&&r
822165
$cache and not @args
!ll&&!rl&&r
1864167
MC/DC100%3/3
$cache and not @args and defined $data
$cache not @args defined $data
Truth table100%4/4
A and not(B) and C
A= $cacheB= not @argsC= defined $data
ABCresult
0XX0
10X0
1100
1111
3086 165 my $key = $self->_cache_key;
3087 165 ▶ if (defined $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 165 0 165
3088 defined $self->{_url}
3089 ? $cache->set($key, $data, $self->{_cache_ttl_url})
3090 165 ▶ : $cache->set($key, $data);
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'_url'} ? : 0 165 165
3091 }
3092 }
3093  
3094 249 return $data;
3095 }
3096  
3097 319 ▶sub fetch_all {
Subroutine fetch_all: called CC=14 SCAR=26.4
Pod documented
3098 319 my $self = shift;
3099 319 local ($@, $!); # the backend opens lazily, and uses both on the way
3100 319 local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows
3101 319 my $table = $self->{_table};
3102  
3103 # 0-byte file: no backend was created; nothing to fetch.
3104 319 ▶ return [] if $self->{_file_is_empty};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_file_is_empty"} 5 314 319
3105  
3106 # Cache check: URL tables benefit from avoiding repeated HTTP round-trips;
3107 # file tables benefit from skipping disk I/O and CSV/TSV/PSV parsing.
3108 314 my $cache = $self->{_cache};
3109 314 ▶ if ($cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache) 58 256 314
3110 58 my $key = $self->_cache_key;
3111 58 ▶ if (defined $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 58 0 58
3112 58 my $hit = $cache->get($key);
3113 58 ▶ return $hit if defined $hit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $hit 22 36 58
3114 }
3115 }
3116  
3117 292 my $data = eval { $self->{_db}->selectall_hashref() };
3118 292 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 24 268 292
3119 24 croak $self->_msg('error_fetch_failed', $table, $@);
3120 }
3121  
3122 268 ▶ return [] unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 2 266 268
3123  
3124 # Strategy: Database::Abstraction can return either an arrayref (when the
3125 # underlying driver iterates rows) or a hashref keyed by primary key (when
3126 # it mirrors DBI's selectall_hashref semantics). We normalise to arrayref
3127 # here so every caller above this layer sees a uniform structure.
3128 266 ▶ if (ref $data eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "HASH") 4 262 266
3129 4 carp $self->_msg('warn_data_normalised', $table);
3130 4 $data = [ values %{$data} ];
3131 }
3132  
3133 266 ▶ if (!@{$data}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@{$data;}) 4 262 266
3134 4 carp $self->_msg('warn_empty_result', $table);
3135 }
3136  
3137 # A JSON URL may answer with an array of anything; every layer above reads
3138 # each row as a hash, and would die on the first scalar.
3139 croak $self->_msg('error_fetch_failed', $table, $self->_msg('error_rows_not_records'))
3140 266 ▶ if defined $self->{_url} && grep { ref $_ ne 'HASH' } @{$data};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_url"} and grep {ref $_ ne "HASH";} @{$data;} 3 263 266
Condition100%3/3
defined $self->{"_url"} and grep {ref $_ ne "HASH";} @{$data;}
!ll&&!rl&&r
26123
MC/DC100%2/2
defined $self->{"_url"} and grep {ref $_ ne "HASH";} @{$data;}
defined $self->{"_url"} grep {ref $_ ne "HASH";} @{$data;}
Truth table100%3/3
A and B
A= defined $self->{"_url"}B= grep {ref $_ ne "HASH";} @{$data;}
ABresult
0X0
100
111
3141  
3142 # Cache store: URL tables use a TTL so stale pages expire automatically;
3143 # file tables encode mtime in the key so a changed file produces a natural
3144 # miss without any explicit invalidation.
3145 263 ▶ if ($cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache) 13 250 263
3146 13 my $key = $self->_cache_key;
3147 13 ▶ if (defined $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 13 0 13
3148 defined $self->{_url}
3149 ? $cache->set($key, $data, $self->{_cache_ttl_url})
3150 13 ▶ : $cache->set($key, $data);
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'_url'} ? : 2 11 13
3151 }
3152 }
3153  
3154 263 return $data;
3155 }
3156  
3157 =head2 count
3158  
3159 Returns the total number of rows in the table.
3160  
3161 For empty-file sentinels it returns C<0> immediately. For all DBI-backed
3162 sources (SQLite, large CSV via DBD::CSV) it delegates to
3163 C<Database::Abstraction::count()>, which issues a
3164 C<SELECT COUNT(*) FROM E<lt>tableE<gt>> query against the file.
3165  
3166 The count of a file's table is remembered for the life of the process, keyed
3167 by the file, the table, and the file's modification time and size, so asking
3168 again costs nothing until the file changes. A URL or MariaDB source is counted
3169 on every call. The first count of a very large SQLite file still reads the
3170 whole table.
3171  
3172 =head3 API SPECIFICATION
3173  
3174 =head4 INPUT
3175  
3176 None.
3177  
3178 =head4 OUTPUT
3179  
3180 SCALAR non-negative integer # total row count, 0 for empty files
3181  
3182 =head3 MESSAGES
3183  
3184 None.
3185  
3186 =cut
3187  
3188 41 ▶sub count {
Subroutine count: called CC=6 SCAR=18.1
Pod documented
3189 41 my ($self) = @_;
3190 41 local ($@, $!); # the backend opens lazily, and uses both on the way
3191 41 local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows
3192 41 ▶ return 0 if $self->{_file_is_empty};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_file_is_empty"} 1 40 41
3193  
3194 40 my $key = $self->_count_key;
3195 40 ▶ return $COUNT_MEMO{$key} if defined $key && exists $COUNT_MEMO{$key};
Branch: 1 branch
BranchTrueFalseTotal
if defined $key and exists $COUNT_MEMO{$key} 19 21 40
Condition66%2/3
defined $key and exists $COUNT_MEMO{$key}
!ll&&!rl&&r
02119
MC/DC50%1/2
defined $key and exists $COUNT_MEMO{$key}
defined $key exists $COUNT_MEMO{$key}
Truth table66%2/3
A and B
A= defined $keyB= exists $COUNT_MEMO{$key}
ABresult
0X0
100
111
3196  
3197 21 my $n = $self->{_db}->count();
3198 21 ▶ if (defined $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 21 0 21
3199 21 ▶ %COUNT_MEMO = () if keys(%COUNT_MEMO) >= $COUNT_MEMO_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if keys %COUNT_MEMO >= $COUNT_MEMO_MAX 0 21 21
3200 21 $COUNT_MEMO{$key} = $n;
3201 }
3202 21 return $n;
3203 }
3204  
3205 # _count_key( $self ) -> $key | undef
3206 #
3207 # What count() remembers its answer under: the file, the table in it, and the
3208 # file's mtime and size, so a changed file is counted again. undef (count every
3209 # time) for a URL or a database server, which have no file to stat.
3210 40 ▶sub _count_key {
Subroutine _count_key: called CC=7 SCAR=22.1
3211 40 my $self = shift;
3212 40 ▶ return undef if defined $self->{_url} || defined $self->{_mariadb};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_url"} or defined $self->{"_mariadb"} 0 40 40
Condition33%1/3
defined $self->{"_url"} or defined $self->{"_mariadb"}
l!l&&r!l&&!r
0040
MC/DC0%0/2
defined $self->{"_url"} or defined $self->{"_mariadb"}
defined $self->{"_url"} defined $self->{"_mariadb"}
Truth table33%1/3
A or B
A= defined $self->{"_url"}B= defined $self->{"_mariadb"}
ABresult
1X1
011
000
3213 40 my $file = $self->{_file_path};
3214 40 ▶ return undef unless defined $file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file 0 40 40
3215 40 my @st = stat $file;
3216 40 ▶ return undef unless @st;
Branch: 1 branch
BranchTrueFalseTotal
unless @st 0 40 40
3217 40 ▶ return join "\0", $file, $self->{_table} // '', $self->{_internal_table} // '', $st[9], $st[7];
Condition50%2/4
$self->{"_table"} // ""
l!l
400
$self->{"_internal_table"} // ""
l!l
040
MC/DC0%0/1
$self->{"_table"} // ""
$self->{"_table"}
MC/DC0%0/1
$self->{"_internal_table"} // ""
$self->{"_internal_table"}
Truth table50%1/2
A
A= $self->{"_table"}
Aresult
11
00
Truth table50%1/2
A
A= $self->{"_internal_table"}
Aresult
11
00
3218 }
3219  
3220 13 1;
3221  
3222 __END__
« blib/lib/Database/BI/Util.pm ↑ Summary blib/lib/Database/BI.pm »