| File: | blib/lib/Database/BI/Model/DataSource.pm |
| Coverage: | 93.6% |
| line | stmt | bran | cond | sub | time | code |
|---|---|---|---|---|---|---|
| 1 | package Database::BI::Model::DataSource; | |||||
| 2 | ||||||
| 3 | 188 188 188 | 454016 177 1310 | use strict; | |||
| 4 | 188 188 188 | 197 120 2611 | use warnings; | |||
| 5 | 188 188 188 | 8425 319932 478 | use autodie qw(:all); | |||
| 6 | ||||||
| 7 | 188 188 188 | 538575 128 2954 | use Carp qw(croak carp); | |||
| 8 | 188 188 188 | 224 137 733 | use File::Spec (); | |||
| 9 | 188 188 188 | 515 118 736 | use Database::BI::I18N (); | |||
| 10 | 188 188 188 | 427 323 2108 | use Readonly; | |||
| 11 | 188 188 188 | 201 130 1742 | use Scalar::Util qw(blessed); | |||
| 12 | 188 188 188 | 24135 957669 356 | use Sub::Protected; | |||
| 13 | 188 188 188 | 16945 127 2227 | use Params::Validate::Strict qw(validate_strict); | |||
| 14 | 188 188 188 | 218 131 51091 | use Params::Get (); | |||
| 15 | ||||||
| 16 | our $VERSION = '0.025.0'; | |||||
| 17 | ||||||
| 18 - 191 | =head1 NAME
Database::BI::Model::DataSource - Table-agnostic adapter around Database::Abstraction
=head1 VERSION
0.025.0
=head1 SYNOPSIS
B<Read all rows from a CSV file:>
use Database::BI::Model::DataSource;
my $source = Database::BI::Model::DataSource->new(
directory => '/path/to/data',
table => 'sales', # looks for data/sales.csv, tsv, .psv, .sql, .xml, etc.
);
my $records = $source->fetch_all; # arrayref of hashrefs -- one hashref per row
for my $row (@{$records}) {
printf "Product: %s, Amount: %s\n", $row->{product}, $row->{amount};
}
B<Get column names in the original file order (CSV/PSV/TSV only):>
my $cols = $source->columns; # returns undef for SQLite and XML
if ($cols) {
print join(', ', @{$cols}), "\n";
}
B<Find out which column is the primary key:>
print "Primary key column: ", $source->id_column, "\n";
B<Open a SQLite file (.sql extension):>
my $source = Database::BI::Model::DataSource->new(
directory => '/var/data',
table => 'inventory', # looks for /var/data/inventory.sql
);
B<Open a pipe-separated file (.psv extension):>
my $source = Database::BI::Model::DataSource->new(
directory => '/var/data',
table => 'products', # looks for /var/data/products.psv
);
B<Open a tab-separated file (.tsv extension):>
my $source = Database::BI::Model::DataSource->new(
directory => '/var/data',
table => 'products', # looks for /var/data/products.tsv
);
B<Use a custom i18n object to translate error messages:>
# The i18n object must have a maketext($key, @args) method.
my $source = Database::BI::Model::DataSource->new(
directory => '/path/to/data',
table => 'sales',
i18n => My::I18N::Handle->new,
);
B<Open a remote HTML table from a URL:>
# Requires LWP::UserAgent::Cached and HTML::TableExtract.
# The table is fetched and cached in memory; no file is saved to disk.
my $source = Database::BI::Model::DataSource->new(
url => 'https://example.com/data-page.html',
);
my $records = $source->fetch_all;
B<Select a specific table when a page has more than one HTML table:>
my $source = Database::BI::Model::DataSource->new(
url => 'https://example.com/page.html',
html_table_index => 2, # zero-based: 0 = first table, 2 = third table
);
B<Fetch from an intranet host, which resolves to a private address:>
my $source = Database::BI::Model::DataSource->new(
url => 'https://reports.corp.example/sales.html',
private_hosts => ['*.corp.example'],
);
B<Open one specific internal table from a multi-table SQLite database:>
# A SQLite file may contain more than one table.
# Use internal_table to say which one you want.
my $source = Database::BI::Model::DataSource->new(
directory => '/var/data',
table => 'store', # looks for store.db, store.sql, etc.
internal_table => 'customer', # open just the "customer" table inside
);
my $records = $source->fetch_all;
B<Check whether a SQLite file has more than one table:>
my $source = Database::BI::Model::DataSource->new(
directory => '/var/data',
table => 'store',
);
my $tbl_list = $source->sqlite_tables; # undef unless it is a multi-table SQLite
if ($tbl_list && @{$tbl_list} > 1) {
# let the user choose which table to open
for my $name (@{$tbl_list}) {
printf " table: %s\n", $name;
}
}
B<Open a remote file over SSH (SFTP):>
# Requires Net::SFTP::Foreign.
my $source = Database::BI::Model::DataSource->new(
directory => '/remote/data',
table => 'report',
host => 'deploy@dbserver.example.com',
file_ext => 'log', # hint: try report.log first, then other exts
);
my $records = $source->fetch_all;
B<Handle errors gracefully:>
my $source = eval {
Database::BI::Model::DataSource->new(
directory => $dir,
table => $table,
);
};
if ($@) {
carp "Could not open table: $@";
# $@ contains a translated message from %MESSAGES
}
my $records = eval { $source->fetch_all };
if ($@) {
carp "Could not read records: $@";
}
=head1 DESCRIPTION
C<Database::BI::Model::DataSource> is a thin, table-agnostic adapter that
wraps L<Database::Abstraction> and exposes three accessors (C<fetch_all>,
C<columns>, C<id_column>) used by the controller.
L<Database::Abstraction> is a read-only ORM that discovers data files
(CSV, PSV, TSV, SQLite, XML, etc.) automatically from a directory based on the
calling class name. C<DataSource> generates an ephemeral subclass at
construction time so callers never interact with L<Database::Abstraction>
directly. To swap the backend for L<Database::Join> in Phase 2, only the
C<open_table> helper in C<Database::BI> needs to change; the controller and
C<DataSource> are untouched.
C<_detect_file_info> peeks at the first header line of CSV/PSV/TSV files to
extract the correct separator character, the primary-key column name, and
the full ordered column list. Without this, two silent L<Database::Abstraction>
defaults corrupt every result: C<sep_char> defaults to C<'!'> (turning a
comma-separated file into a single-field table) and C<id> defaults to
C<'entry'> (causing every row to be discarded when no C<entry> column
exists).
Result filtering (C<eq>, C<contains>, C<gt>, etc.) is performed at the
controller layer by C<Dashboard::_apply_filter_spec> after C<fetch_all>
returns. C<DataSource> itself is filter-unaware.
All user-visible strings and exception messages are keyed through the
C<%MESSAGES> dictionary and routed via C<_msg()>, making every diagnostic
replaceable by an i18n object at instantiation time.
=cut | |||||
| 192 | ||||||
| 193 - 255 | =head1 ENCODING =head2 What is safe to put in cell values Cell values (the actual data inside rows) are passed through as Perl character strings exactly as C<Database::Abstraction> and the underlying DBI driver return them. Full Unicode -- including non-ASCII letters, accented characters, CJK ideographs, and emoji -- is supported in cell values, provided the source file is encoded in UTF-8 (or the encoding declared in its HTTP headers for URL-backed tables). =head2 What must stay ASCII The following structural items must contain B<only ASCII characters>: =over 4 =item C<table> constructor argument The bare file stem used to look up the file on disk. Non-ASCII characters are not valid SQL identifiers and will be silently replaced with underscores (C<_>) by the sanitization step in C<new()>. =item Column header names (CSV / TSV / PSV first line) Column names are used as hash keys and as SQL identifiers inside C<Database::Abstraction>. Non-ASCII headers cause C<DBD::CSV> to fail or produce garbage keys. If your source file has non-ASCII column headers, rename them before opening via C<DataSource>. =item C<host> argument The hostname or C<user@hostname> string for SFTP access. Must match C<[A-Za-z0-9._@-]>; anything outside that character set is rejected by the host-validation regex and produces C<error_backend_init>. =back =head2 URL-backed tables URL-backed tables (the C<url =E<gt>> constructor path) are fetched with L<Database::BI::SafeUA>, which refuses (C<403>, so the read croaks C<error_fetch_failed>) any request or redirect whose host resolves to this machine, a private network or a link-local address such as a cloud metadata service, and connects to the address it checked. C<private_hosts =E<gt> [...]> names the hosts (exact, or C<*.suffix>) that may resolve privately: an intranet. If the remote server declares a charset in its HTTP headers or in an HTML C<meta> tag, L<Database::Abstraction> uses it to decode the response body. If the charset declaration is absent or wrong, cell values may arrive as raw bytes rather than character strings, and multi-byte sequences will look garbled. =head2 File-backed tables (CSV / TSV / PSV) For files smaller than 16 KB, L<Text::xSV::Slurp> reads bytes and returns them without re-encoding; for larger files the L<DBD::CSV> path is used instead. In both cases C<DataSource> forces the slurp path (by passing C<max_slurp_size =E<gt> -s $file>) so that column names with spaces are preserved as-is. The caller (the Mojolicious controller) is responsible for setting the correct C<Content-Type: text/html; charset=UTF-8> response header. =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 | 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 | error_sheet_not_found => 'DataSource: workbook "%s" has no sheet called "%s"; its sheets are: %s', | |||||
| 293 | warn_empty_result => 'DataSource: fetch_all returned no records for table "%s"', | |||||
| 294 | warn_data_normalised => 'DataSource: result from backend was a hashref; converted to arrayref for table "%s"', | |||||
| 295 | ); | |||||
| 296 | ||||||
| 297 | # A table name is a bare SQL-safe identifier: starts with a letter or | |||||
| 298 | # underscore, followed by zero or more alphanumeric/underscore characters. | |||||
| 299 | Readonly my $XML_SCAN_BLOCK => 65_536; | |||||
| 300 | Readonly my $XML_MARKER_OVERLAP => 7; # one byte less than '<!ENTITY' | |||||
| 301 | Readonly my $TABLE_NAME_RE => qr/\A[A-Za-z_][A-Za-z0-9_]*\z/; | |||||
| 302 | ||||||
| 303 | # What may go into a MariaDB DSN. A ';' would start another DSN attribute. | |||||
| 304 | Readonly my $MARIADB_HOST_RE => qr/\A[A-Za-z0-9._-]+\z/; | |||||
| 305 | Readonly my $MARIADB_DATABASE_RE => qr/\A[A-Za-z0-9_\$-]+\z/; | |||||
| 306 | Readonly my $MARIADB_PORT_RE => qr/\A[0-9]+\z/; | |||||
| 307 | # A page should not hang on a server that has gone away. | |||||
| 308 | Readonly my $MARIADB_CONNECT_TIMEOUT => 5; | |||||
| 309 | # Text::CSV's error_diag code for the plain end of a file. | |||||
| 310 | Readonly my $CSV_EOF => 2012; | |||||
| 311 | ||||||
| 312 | # count() remembers each file table's row count until the file changes (see | |||||
| 313 | # _count_key): a SQLite table paged in SQL shows its number of pages, and a | |||||
| 314 | # COUNT(*) on every page of a big file would cost what the N+1 paging saves. | |||||
| 315 | # Emptied when it reaches $COUNT_MEMO_MAX entries. | |||||
| 316 | my %COUNT_MEMO; | |||||
| 317 | Readonly my $COUNT_MEMO_MAX => 256; | |||||
| 318 | ||||||
| 319 | # The extensions D::A looks for before .json; a file with one of them is the | |||||
| 320 | # table, and a .json beside it is not read. | |||||
| 321 | # JSON Lines: one JSON object a line. Read after .json, as a stream. | |||||
| 322 | Readonly my @JSON_LINES_EXT => qw(jsonl ndjson); | |||||
| 323 | Readonly my @NON_JSON_EXT => qw(sql sqlite sqlite3 db psv tsv xls xlsx csv xml); | |||||
| 324 | # A .json file over this many bytes that is a list of objects is read as a | |||||
| 325 | # stream, one row at a time, instead of as one string and one parsed tree; a | |||||
| 326 | # JSON Lines file always is. The chunk is how much is read at a time. | |||||
| 327 | Readonly my $JSON_STREAM_BYTES => 16 * 1_048_576; | |||||
| 328 | Readonly my $JSON_CHUNK_BYTES => 1_048_576; | |||||
| 329 | # The sort columns D::A accepts; it ignores any other, with a warning. | |||||
| 330 | Readonly my $DA_SORTABLE_RE => qr/\A[a-zA-Z_][a-zA-Z0-9_.]*\z/; | |||||
| 331 | ||||||
| 332 | # --------------------------------------------------------------------------- | |||||
| 333 | # Protected helpers | |||||
| 334 | # --------------------------------------------------------------------------- | |||||
| 335 | ||||||
| 336 | # _safe_table_name( $name ) -> $string | |||||
| 337 | # | |||||
| 338 | # The name to suggest for a table whose own name Database::Abstraction refuses: | |||||
| 339 | # each illegal character becomes an underscore, and a leading digit gets one. | |||||
| 340 | sub _safe_table_name { | |||||
| 341 | 35 | 2158 | my $name = $_[0]; | |||
| 342 | 35 | 58 | $name =~ s/[^A-Za-z0-9_]/_/g; | |||
| 343 | 35 | 74 | $name = "_$name" unless $name =~ /\A[A-Za-z_]/; | |||
| 344 | 35 | 73 | return $name; | |||
| 345 | } | |||||
| 346 | ||||||
| 347 | # _url_label( $url ) -> $string | |||||
| 348 | # | |||||
| 349 | # Derive a safe, lowercase identifier from a URL for use as the table label. | |||||
| 350 | # Takes the last non-empty path component, strips the extension, then replaces | |||||
| 351 | # non-alphanumeric characters with underscores. Falls back to the hostname | |||||
| 352 | # when the path component is absent or starts with a digit. | |||||
| 353 | sub _url_label { | |||||
| 354 | 80 | 10323 | my $url = $_[0]; | |||
| 355 | 80 | 205 | my ($path) = $url =~ m{https?://[^/?#]+(.*)}i; | |||
| 356 | 80 162 | 188 151 | my @parts = grep { length } split m{/}, ($path // ''); | |||
| 357 | 80 | 127 | my $last = @parts ? $parts[-1] : ''; | |||
| 358 | # /s: . must cross \n in case a percent-decoded newline hides inside the URL. | |||||
| 359 | 80 | 93 | $last =~ s/[?#].*//s; # strip query / fragment | |||
| 360 | 80 | 87 | $last =~ s/\.[^.]+\z//; # strip file extension (\z: no trailing-\n loophole) | |||
| 361 | 80 | 88 | $last =~ s/[^A-Za-z0-9_]/_/g; # sanitize | |||
| 362 | 80 | 239 | unless (length $last && $last =~ /\A[A-Za-z_]/) { | |||
| 363 | # No usable path component -- fall back to hostname | |||||
| 364 | 10 | 15 | my ($host) = $url =~ m{https?://([^/:?#]+)}; | |||
| 365 | 10 9 9 | 10 15 7 | $last = defined $host ? do { (my $h = $host) =~ s/[^A-Za-z0-9_]/_/g; $h } : 'html'; | |||
| 366 | } | |||||
| 367 | # $last is always non-empty here: the unless-block sets it to either | |||||
| 368 | # the sanitized hostname (>= 1 char) or the literal 'html'. | |||||
| 369 | 80 | 445 | return lc($last); | |||
| 370 | } | |||||
| 371 | ||||||
| 372 | # _fmt( $key [, @sprintf_args] ) -> $string | |||||
| 373 | # | |||||
| 374 | # Package-level (not a method) i18n formatter. Looks up $key in %MESSAGES and | |||||
| 375 | # applies sprintf if positional arguments are supplied. This function is used | |||||
| 376 | # in new() before the object exists; instance methods should use _msg() instead | |||||
| 377 | # so that a caller-supplied i18n object can override the built-in strings. | |||||
| 378 | sub _fmt :Protected { | |||||
| 379 | my ($key, @args) = @_; | |||||
| 380 | my $tmpl = Database::BI::I18N::text(__PACKAGE__, \%MESSAGES, $key) // "Internal error: unknown message key '$key'"; | |||||
| 381 | return @args ? sprintf($tmpl, @args) : $tmpl; | |||||
| 382 | 188 188 188 | 314 153 1393 | } | |||
| 383 | ||||||
| 384 | # _msg( $self, $key [, @sprintf_args] ) -> $string | |||||
| 385 | # | |||||
| 386 | # Instance-level i18n formatter. Delegates to the caller-supplied i18n object | |||||
| 387 | # (if any) before falling back to _fmt(). The i18n object must implement | |||||
| 388 | # maketext($key, @args). | |||||
| 389 | sub _msg :Protected { | |||||
| 390 | my ($self, $key, @args) = @_; | |||||
| 391 | if (my $i18n = $self->{_i18n}) { | |||||
| 392 | return $i18n->maketext($key, @args); | |||||
| 393 | } | |||||
| 394 | return _fmt($key, @args); | |||||
| 395 | 188 188 188 | 255183 140 1301 | } | |||
| 396 | ||||||
| 397 | # --------------------------------------------------------------------------- | |||||
| 398 | # Constructor | |||||
| 399 | # --------------------------------------------------------------------------- | |||||
| 400 | ||||||
| 401 - 554 | =head1 CONSTRUCTOR
=head2 new
Creates and returns a new C<Database::BI::Model::DataSource> instance.
=head3 API SPECIFICATION
=head4 INPUT
{
directory => 'string', # required; local dir, or remote dir when host is set
table => 'string', # required; bare file stem (no extension)
host => 'string', # optional; "hostname" or "user@hostname" for SFTP access
file_ext => 'string', # optional; extension hint when remote file has non-standard suffix (e.g. "log")
internal_table => 'string', # optional; a SQLite file's table, or a JSON file's list, to open
column_order => \@names, # optional; the order columns() gives, when the backend has none
json_flatten => 1, # optional; JSON: an object is a column for each value, not text
cache => 'object', # optional; CHI cache object for result caching
cache_ttl_url => 'string', # optional; CHI TTL string for URL-backed tables (default "15 min")
mariadb => \%settings, # optional; a mariadb_servers entry; needs server and table
server => 'string', # the name of that entry
i18n => 'object', # optional; must implement maketext($key, @args) for i18n
}
C<internal_table> selects a named table inside a multi-table SQLite file.
When omitted, C<DataSource> auto-selects the first user table whose name
matches the filename stem; if no match, it picks the first table found.
Supplying a name that does not exist in the file croaks C<error_table_not_found>.
An C<.xlsx> workbook with two or more sheets works the same way: each sheet
is a table, C<internal_table> names one (the sheet named after the file, else
the first, is read without it), C<sqlite_tables> lists them and C<xlsx_sheets>
describes them. A sheet that does not exist croaks C<error_sheet_not_found>.
A C<.json> file is read as a table when it is a list of objects, an object
of objects (each key a row, kept in a column C<id>, or C<key> when the rows
have an C<id>), or an object holding lists of objects. Each such list is a
table, as a SQLite file's are: C<internal_table> names one, the first in the
file is read without it, and C<sqlite_tables> lists them. A cell holding an
object or a list is shown as its JSON text, C<true> and C<false> as words and
C<null> as an empty cell; the columns are in the order the file first names
them. A C<.csv> (or any other format's file) beside it with the same name is
the one read. Not JSON croaks C<error_json_invalid>; JSON with no table in
it, C<error_json_no_rows>; a list it does not have, C<error_json_list_not_found>.
A C<.jsonl> or C<.ndjson> file (JSON Lines: one object a line, blank lines
skipped, C<\r\n> and a BOM allowed) is a table with a row for each line,
read like a C<.json> list of objects. It is read as a stream: one pass finds
the columns and a second writes the copy, so memory holds a row, not the file.
A C<.json> list of objects over 16 MiB is streamed the same way. A line that
is not JSON croaks C<error_json_invalid>, naming the line; one that is not an
object, C<error_json_no_rows>; a list name (C<internal_table>),
C<error_json_list_not_found>, because there are none. A C<.json> beside it,
or any other format, is the one read.
With C<json_flatten> a nested object is not its JSON text but a column for
each of its values, named by the path to it (C<address.city>,
C<address.geo.lat>), in the order the file names them. A list stays JSON text,
an empty object is a cell (C<{}>), and a name that is taken (a key written
C<a.b> beside an object C<a> holding C<b>) gets C<_> added, so no value is lost.
It is off by default.
C<column_order> is for a caller that knows the columns' order better than the
backend does. A SQLite backend lists its columns alphabetically, so an
extract of an accelerated dataset passes the order its file had. It is used
only when the file itself gives no order (SQLite, XML), and is trusted, not
checked against the columns the backend has.
Accepts a flat key/value list, a hashref, or positional arguments via
C<Params::Get>.
When C<host> is provided, C<directory> is treated as a path on the remote
host and is not checked with C<-d> locally. C<DataSource> downloads the
file via SFTP (L<Net::SFTP::Foreign>) to a process-local temporary directory
and then processes the local copy. The temporary directory persists for the
lifetime of the C<DataSource> object and is cleaned up automatically on
destruction.
When C<file_ext> is provided together with C<host>, it is used as the first
candidate extension when probing the remote host for the file. If the
downloaded file does not have a standard extension (one of C<csv>, C<tsv>,
C<psv>, C<xlsx>, C<xls>, C<sql>, C<sqlite>, C<sqlite3>, C<db>, C<xml>, C<json>,
C<jsonl>, C<ndjson>), the file content is sniffed (SQLite magic bytes, XML preamble, a leading
C<[> or C<{> for JSON, or C<{> with whole objects on the first lines for JSON Lines, or first-line
field separator) and the file is renamed to the correct standard extension
before further processing.
=head4 DOMAIN CONSTRAINTS
=over 4
=item C<directory>
Must satisfy C<-d $directory> (must exist and be a directory). An empty
string, a non-existent path, or the path to a regular file all produce
C<error_directory_missing>.
Valid partition: any existing directory path
Invalid partition: non-existent path, regular file path, empty string ""
=item C<table>
The bare file stem (no extension). Characters that are illegal in SQL
identifiers - hyphens, dots, spaces, etc. - are silently replaced with
underscores before the name is used internally. A stem that starts with a
digit is prefixed with C<_>. Only a completely empty string croaks.
Valid partition: "sales", "_tmp", "report_2024",
"Transactions-2026-09-08" (hyphens sanitized to underscores),
"my.data" (dot sanitized), "1sales" (prefixed to "_1sales")
Invalid partition: "" (empty string)
Boundary values: "a" (length-1 letter, valid), "_" (length-1 underscore,
valid), "" (empty string, croaks error_table_name_invalid)
=back
=head4 OUTPUT
Returns C<$self> (a blessed hashref). Croaks on invalid arguments.
=head3 MESSAGES
error_directory_required -- "directory" argument was not supplied
error_table_required -- "table" argument was not supplied
error_directory_missing -- supplied directory does not exist / is unreadable
error_table_name_invalid -- table name contains illegal characters or is empty
error_table_name_unsafe -- internal_table names a SQLite table whose own name
has illegal characters; says what else to open and
how to rename it
error_no_usable_tables -- every table in a SQLite file has such a name
error_xml_entities -- an .xml file declares an entity (<!ENTITY), or is
not in a form that can be checked for one
error_json_invalid -- a .json file is not valid JSON
error_json_no_rows -- a .json file holds no list of objects, object of
objects or object holding such a list
error_json_list_not_found -- internal_table names no list in a .json file
error_no_safe_id -- no column in the file has a safe SQL identifier name;
rename at least one column header to an alphanumeric name
error_backend_init -- backend initialisation failed; sub-cases:
* Net::SFTP::Foreign is not installed
* could not connect to <host> via SFTP
* could not fetch any supported file from <host>:<dir>/<stem>.*
* Database::Abstraction subclass could not be instantiated
error_no_tables -- SQLite file opened successfully but contains no user-defined tables
error_unsupported_db -- .db file has BerkeleyDB magic bytes but DB_File could not open it
(file likely uses a newer BDB format than the installed libdb supports)
error_fetch_failed -- fetch_all raised an exception (wraps the underlying DBI/D::A error)
error_url_invalid -- URL passed to the url=> constructor path does not begin
with http:// or https://
error_url_fetch -- the backend for a URL could not be set up; a page
that cannot be fetched is error_fetch_failed, from the read
=cut | |||||
| 555 | ||||||
| 556 | sub new { | |||||
| 557 | # Strategy: normalise the argument list with Params::Get so callers may | |||||
| 558 | # pass a hashref or a flat list interchangeably, then validate strictly | |||||
| 559 | # with Params::Validate before touching any value. | |||||
| 560 | # When a "url" key is present, dispatch to the URL/HTML-table path instead. | |||||
| 561 | 3881 | 4038509 | my $class = shift; | |||
| 562 | # Opening a file tries several drivers in turn; what they leave in $@ and $! is | |||||
| 563 | # of no interest to a caller, who may be holding its own. | |||||
| 564 | 3881 | 25594 | local ($@, $!); | |||
| 565 | 3881 | 6560 | local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows | |||
| 566 | 3881 | 8649 | my $raw = Params::Get::get_params(undef, \@_) // {}; | |||
| 567 | 3881 | 52888 | return $class->_new_from_url($raw) if exists $raw->{url}; | |||
| 568 | 3815 | 5558 | return $class->_new_from_redis($raw) if exists $raw->{redis}; | |||
| 569 | 3809 | 5009 | return $class->_new_from_mariadb($raw) if exists $raw->{mariadb}; | |||
| 570 | 3804 | 5017 | croak _fmt('error_table_required') unless defined $raw->{table}; | |||
| 571 | ||||||
| 572 | 3797 | 31531 | my $args = validate_strict( | |||
| 573 | schema => { | |||||
| 574 | directory => { type => 'string' }, | |||||
| 575 | table => { type => 'string' }, | |||||
| 576 | host => { type => 'string', optional => 1, default => undef }, | |||||
| 577 | file_ext => { type => 'string', optional => 1, default => undef }, | |||||
| 578 | internal_table => { type => 'string', optional => 1, default => undef }, | |||||
| 579 | column_order => { type => 'arrayref', optional => 1, default => undef }, | |||||
| 580 | json_flatten => { type => 'boolean', optional => 1, default => 0 }, | |||||
| 581 | i18n => { type => 'object', optional => 1, default => undef, can => 'maketext' }, | |||||
| 582 | cache => { type => 'object', optional => 1, default => undef }, | |||||
| 583 | cache_ttl_url => { type => 'string', optional => 1, default => '15 min' }, | |||||
| 584 | }, | |||||
| 585 | input => $raw, | |||||
| 586 | ); | |||||
| 587 | ||||||
| 588 | # For remote files (host is set), the directory is on the remote host and | |||||
| 589 | # cannot be stat()d locally. Only check local existence when no host is given. | |||||
| 590 | croak _fmt('error_directory_missing', $args->{directory}) | |||||
| 591 | 3738 | 843879 | unless defined $args->{host} || -d $args->{directory}; | |||
| 592 | ||||||
| 593 | # Reject path-traversal characters first: '/', '\', and NUL are the only | |||||
| 594 | # characters that could let _raw_table escape the intended directory when | |||||
| 595 | # D::A constructs "$dir/$dbname.$ext". Everything else is either safe as a | |||||
| 596 | # filename component or will be sanitized below. | |||||
| 597 | croak _fmt('error_table_name_invalid', $args->{table}) | |||||
| 598 | 3722 | 10337 | if !length($args->{table}) || $args->{table} =~ m{[/\\\x00]}; | |||
| 599 | ||||||
| 600 | # Silently sanitize table names derived from file stems: replace characters | |||||
| 601 | # that are illegal in SQL identifiers (hyphens, dots, spaces, etc.) with | |||||
| 602 | # underscores. A leading digit is prefixed with '_'. The original name is | |||||
| 603 | # kept in _raw_table for filesystem lookup (dbname) so the actual file is | |||||
| 604 | # still found; the sanitized name is used only as the internal D::A | |||||
| 605 | # identifier and ephemeral package name. | |||||
| 606 | 3712 | 3052 | my $raw_table = $args->{table}; | |||
| 607 | 3712 | 4746 | (my $safe_table = $raw_table) =~ s/[^A-Za-z0-9_]/_/g; | |||
| 608 | 3712 | 5317 | $safe_table = '_' . $safe_table if $safe_table =~ /\A[0-9]/; | |||
| 609 | ||||||
| 610 | 3712 | 6934 | croak _fmt('error_table_name_invalid', $raw_table) | |||
| 611 | unless $safe_table =~ $TABLE_NAME_RE; | |||||
| 612 | ||||||
| 613 | my $self = bless { | |||||
| 614 | _directory => $args->{directory}, | |||||
| 615 | _table => $safe_table, | |||||
| 616 | _raw_table => $raw_table, | |||||
| 617 | _host => $args->{host}, | |||||
| 618 | _file_ext => $args->{file_ext}, | |||||
| 619 | _internal_table => $args->{internal_table}, | |||||
| 620 | _column_order => $args->{column_order}, | |||||
| 621 | _json_flatten => $args->{json_flatten} ? 1 : 0, | |||||
| 622 | _i18n => $args->{i18n}, | |||||
| 623 | _cache => $args->{cache}, | |||||
| 624 | _cache_ttl_url => $args->{cache_ttl_url}, | |||||
| 625 | 3712 | 29886 | _db => undef, | |||
| 626 | }, $class; | |||||
| 627 | ||||||
| 628 | 3712 | 7627 | $self->_init_backend(); | |||
| 629 | 3636 | 22374 | return $self; | |||
| 630 | ||||||
| 631 | } | |||||
| 632 | ||||||
| 633 | # _new_from_url( $class, \%raw_params ) -> $self | |||||
| 634 | # | |||||
| 635 | # Alternate constructor path for URL-backed HTML tables. | |||||
| 636 | # Validates the URL scheme, derives a display label from the URL path, | |||||
| 637 | # then calls _init_url_backend to build the D::A in-memory table. | |||||
| 638 | # Entry: $raw->{url} must be an http:// or https:// URL. | |||||
| 639 | # $raw->{html_table_index} (optional, default 0): zero-based table index. | |||||
| 640 | # $raw->{private_hosts} (optional): names that may resolve to private | |||||
| 641 | # addresses (Database::BI::SafeUA). | |||||
| 642 | # $raw->{i18n} (optional): Locale::Maketext-compatible object. | |||||
| 643 | # Exit: Returns $self. Croaks on invalid URL scheme or backend init failure. | |||||
| 644 | # Side Effects: None: the URL is fetched by the first read. | |||||
| 645 | sub _new_from_url :Protected { | |||||
| 646 | my ($class, $raw) = @_; | |||||
| 647 | ||||||
| 648 | my $url = $raw->{url} // croak _fmt('error_url_invalid', ''); | |||||
| 649 | croak _fmt('error_url_invalid', $url) | |||||
| 650 | unless $url =~ m{\Ahttps?://}i; | |||||
| 651 | ||||||
| 652 | my $table_idx = $raw->{html_table_index} // 0; | |||||
| 653 | my $self = bless { | |||||
| 654 | _url => $url, | |||||
| 655 | _table => _url_label($url), | |||||
| 656 | _i18n => $raw->{i18n}, | |||||
| 657 | _cache => $raw->{cache}, | |||||
| 658 | _cache_ttl_url => $raw->{cache_ttl_url} // '15 min', | |||||
| 659 | _html_table_index => $table_idx, | |||||
| 660 | _private_hosts => ref($raw->{private_hosts}) eq 'ARRAY' ? $raw->{private_hosts} : [], | |||||
| 661 | _id_col => undef, | |||||
| 662 | _columns => undef, | |||||
| 663 | _db => undef, | |||||
| 664 | }, $class; | |||||
| 665 | ||||||
| 666 | $self->_init_url_backend($table_idx); | |||||
| 667 | return $self; | |||||
| 668 | 188 188 188 | 63869 141 803 | } | |||
| 669 | ||||||
| 670 | # _init_url_backend( $self, $table_index ) -> void | |||||
| 671 | # | |||||
| 672 | # Purpose: Construct the Database::Abstraction backend for URL/HTML-table mode. | |||||
| 673 | # No request is made here. On the first read D::A fetches the page via | |||||
| 674 | # LWP::UserAgent, parses it with | |||||
| 675 | # HTML::TableExtract, and stores all rows (including headers from row 0) | |||||
| 676 | # as an in-memory arrayref. Column order is not recoverable after | |||||
| 677 | # construction (hash keys lose order), so _columns stays undef and | |||||
| 678 | # _get_columns in the controller falls back to alphabetical sorting. | |||||
| 679 | # Entry: $self->{_url} is a valid http(s) URL; $table_index is a non-negative int. | |||||
| 680 | # Exit: Sets $self->{_db}. Croaks if the backend object cannot be built; a | |||||
| 681 | # failure to fetch or parse the page comes from the first read instead. | |||||
| 682 | sub _init_url_backend :Protected { | |||||
| 683 | my ($self, $table_index) = @_; | |||||
| 684 | my $url = $self->{_url}; | |||||
| 685 | ||||||
| 686 | require Database::Abstraction; | |||||
| 687 | ||||||
| 688 | # Reuse a single generic package for all URL-backed instances. | |||||
| 689 | # The package name is irrelevant for the URL code path -- D::A branches on | |||||
| 690 | # the presence of $self->{'url'}, not on the class name. | |||||
| 691 | my $pkg = 'Database::BI::_DB::HtmlUrl'; | |||||
| 692 | { | |||||
| 693 | 188 188 188 | 29730 147 9215 | no strict 'refs'; | |||
| 694 | push @{"${pkg}::ISA"}, 'Database::Abstraction' | |||||
| 695 | unless $pkg->isa('Database::Abstraction'); | |||||
| 696 | } | |||||
| 697 | ||||||
| 698 | # D::A fetches with the ua it is given: one that will not reach this | |||||
| 699 | # machine or a private network, however the URL or its DNS is dressed up. | |||||
| 700 | require Database::BI::SafeUA; | |||||
| 701 | my $db = eval { | |||||
| 702 | $pkg->new({ | |||||
| 703 | url => $url, | |||||
| 704 | html_table_index => $table_index, | |||||
| 705 | no_entry => 1, | |||||
| 706 | ua => Database::BI::SafeUA->new(private_hosts => $self->{_private_hosts}), | |||||
| 707 | }) | |||||
| 708 | }; | |||||
| 709 | croak $self->_msg('error_url_fetch', $url, $@) if $@; | |||||
| 710 | ||||||
| 711 | $self->{_db} = $db; | |||||
| 712 | return; | |||||
| 713 | 188 188 188 | 227 114 675 | } | |||
| 714 | ||||||
| 715 | # _new_from_redis( $class, \%raw_params ) -> $self | |||||
| 716 | # | |||||
| 717 | # Alternate constructor path for Redis-backed tables. | |||||
| 718 | # Entry: $raw->{redis} must be a redis:// URL. | |||||
| 719 | # $raw->{table} (required): table name -- becomes the Redis key prefix | |||||
| 720 | # (keys in Redis must follow the pattern tablename:*). | |||||
| 721 | # $raw->{i18n} (optional): Locale::Maketext-compatible object. | |||||
| 722 | # Exit: Returns $self. Croaks on invalid URL or table name. | |||||
| 723 | sub _new_from_redis :Protected { | |||||
| 724 | my ($class, $raw) = @_; | |||||
| 725 | ||||||
| 726 | my $redis_url = $raw->{redis} // croak _fmt('error_redis_invalid', ''); | |||||
| 727 | croak _fmt('error_redis_invalid', $redis_url) | |||||
| 728 | unless $redis_url =~ m{\Aredis://}i; | |||||
| 729 | ||||||
| 730 | my $table = $raw->{table} // croak _fmt('error_table_required'); | |||||
| 731 | croak _fmt('error_table_name_invalid', $table) | |||||
| 732 | if !length($table) || $table =~ m{[/\\\x00]}; | |||||
| 733 | ||||||
| 734 | my $raw_table = $table; | |||||
| 735 | (my $safe_table = $raw_table) =~ s/[^A-Za-z0-9_]/_/g; | |||||
| 736 | $safe_table = '_' . $safe_table if $safe_table =~ /\A[0-9]/; | |||||
| 737 | croak _fmt('error_table_name_invalid', $raw_table) | |||||
| 738 | unless $safe_table =~ $TABLE_NAME_RE; | |||||
| 739 | ||||||
| 740 | my $self = bless { | |||||
| 741 | _table => $safe_table, | |||||
| 742 | _raw_table => $raw_table, | |||||
| 743 | _redis_url => $redis_url, | |||||
| 744 | _i18n => $raw->{i18n}, | |||||
| 745 | _cache => $raw->{cache}, | |||||
| 746 | _cache_ttl_url => $raw->{cache_ttl_url} // '15 min', | |||||
| 747 | _id_col => 'entry', | |||||
| 748 | _columns => undef, | |||||
| 749 | _db => undef, | |||||
| 750 | }, $class; | |||||
| 751 | ||||||
| 752 | $self->_init_redis_backend(); | |||||
| 753 | return $self; | |||||
| 754 | 188 188 188 | 41142 118 654 | } | |||
| 755 | ||||||
| 756 | # _init_redis_backend( $self ) -> void | |||||
| 757 | # | |||||
| 758 | # Purpose: Construct the Database::Abstraction backend for Redis mode. | |||||
| 759 | # D::A connects to the Redis server lazily (on first data access). | |||||
| 760 | # We pass redis_key => $raw_table so D::A uses the original key name | |||||
| 761 | # (which may contain colons, hyphens, etc.) for Redis lookups, while | |||||
| 762 | # the sanitized $table is used only as the Perl package-name suffix. | |||||
| 763 | # no_entry => 1 requests array-style rows (no id-keyed hash). | |||||
| 764 | # Entry: $self->{_redis_url} is a valid redis:// URL. | |||||
| 765 | # $self->{_table} is a safe SQL identifier (sanitized key name). | |||||
| 766 | # $self->{_raw_table} is the original Redis key name. | |||||
| 767 | # Exit: Sets $self->{_db}. Croaks when D::A construction fails. | |||||
| 768 | sub _init_redis_backend :Protected { | |||||
| 769 | my $self = shift; | |||||
| 770 | my $table = $self->{_table}; | |||||
| 771 | ||||||
| 772 | require Database::Abstraction; | |||||
| 773 | ||||||
| 774 | my $pkg = 'Database::BI::_DB::' . ucfirst($table); | |||||
| 775 | { | |||||
| 776 | 188 188 188 | 29893 108 7249 | no strict 'refs'; | |||
| 777 | push @{"${pkg}::ISA"}, 'Database::Abstraction' | |||||
| 778 | unless $pkg->isa('Database::Abstraction'); | |||||
| 779 | } | |||||
| 780 | ||||||
| 781 | my $db = eval { $pkg->new( | |||||
| 782 | database => $self->{_redis_url}, | |||||
| 783 | table => $table, | |||||
| 784 | redis_key => $self->{_raw_table}, | |||||
| 785 | ) }; | |||||
| 786 | croak $self->_msg('error_backend_init', $table, $@) if $@; | |||||
| 787 | ||||||
| 788 | $self->{_db} = $db; | |||||
| 789 | return; | |||||
| 790 | 188 188 188 | 196 116 572 | } | |||
| 791 | ||||||
| 792 | # _mariadb_dsn( $server, \%settings ) -> ($dsn, $username, $password) | |||||
| 793 | # | |||||
| 794 | # Purpose: What connects to one entry of the mariadb_servers configuration. | |||||
| 795 | # Nothing is connected here: Database::Join::Catalog does that, and | |||||
| 796 | # Database::Abstraction for the rows. An error names the server; it | |||||
| 797 | # never holds the password. | |||||
| 798 | # Entry: $server is the entry's name, for messages. \%settings holds database | |||||
| 799 | # and optionally host, port, username and password. | |||||
| 800 | # Exit: The data source and credentials. Croaks on settings that are not | |||||
| 801 | # valid, or when no MariaDB or MySQL driver is installed. | |||||
| 802 | sub _mariadb_dsn { | |||||
| 803 | 26 | 5964 | my ($server, $settings) = @_; | |||
| 804 | ||||||
| 805 | 26 | 50 | croak _fmt('error_mariadb_unknown_server', $server) unless ref $settings eq 'HASH'; | |||
| 806 | ||||||
| 807 | 23 | 30 | my $database = $settings->{database} // ''; | |||
| 808 | 23 | 36 | my $host = $settings->{host} // 'localhost'; | |||
| 809 | 23 | 22 | my $port = $settings->{port}; | |||
| 810 | 23 | 28 | croak _fmt('error_mariadb_settings', $server, 'database') unless $database =~ $MARIADB_DATABASE_RE; | |||
| 811 | 19 | 62 | croak _fmt('error_mariadb_settings', $server, 'host') unless $host =~ $MARIADB_HOST_RE; | |||
| 812 | 17 | 53 | croak _fmt('error_mariadb_settings', $server, 'port') if defined $port && $port !~ $MARIADB_PORT_RE; | |||
| 813 | ||||||
| 814 | # The driver is optional, so it is looked for only now. | |||||
| 815 | 15 | 25 | require Database::Join::Catalog; | |||
| 816 | 15 | 34 | my $driver = Database::Join::Catalog->available_driver(qw(MariaDB mysql)); | |||
| 817 | 15 | 184 | croak _fmt('error_mariadb_no_driver', $server) unless defined $driver; | |||
| 818 | ||||||
| 819 | 13 | 33 | my $dsn = "dbi:${driver}:database=$database;host=$host" | |||
| 820 | . (defined $port ? ";port=$port" : '') | |||||
| 821 | . ';' . lc($driver) . "_connect_timeout=$MARIADB_CONNECT_TIMEOUT"; | |||||
| 822 | 13 13 | 32 19 | return ($dsn, @{$settings}{qw(username password)}); | |||
| 823 | } | |||||
| 824 | ||||||
| 825 | # _new_from_mariadb( $class, \%raw_params ) -> $self | |||||
| 826 | # | |||||
| 827 | # Alternate constructor path for a table on a MariaDB or MySQL server. | |||||
| 828 | # Entry: $raw->{mariadb} is the server's entry from mariadb_servers. | |||||
| 829 | # $raw->{server} is that entry's name; $raw->{table} is the table. | |||||
| 830 | # Exit: Returns $self. Croaks when the server or the table cannot be reached, | |||||
| 831 | # so a caller finds out here and not from the first read. | |||||
| 832 | # Note: Rows are not cached: a table's contents can change with nothing to say | |||||
| 833 | # so, which is what a file's mtime says for a file. | |||||
| 834 | sub _new_from_mariadb :Protected { | |||||
| 835 | my ($class, $raw) = @_; | |||||
| 836 | ||||||
| 837 | my $table = $raw->{table} // croak _fmt('error_table_required'); | |||||
| 838 | croak _fmt('error_table_name_invalid', $table) unless $table =~ $TABLE_NAME_RE; | |||||
| 839 | my $server = $raw->{server} // ''; | |||||
| 840 | croak _fmt('error_mariadb_unknown_server', $server) unless $server =~ $TABLE_NAME_RE; | |||||
| 841 | ||||||
| 842 | my ($dsn, $username, $password) = _mariadb_dsn($server, $raw->{mariadb}); | |||||
| 843 | ||||||
| 844 | # D::A's columns() is alphabetical; table_info gives the declared order. | |||||
| 845 | my $info = eval { | |||||
| 846 | Database::Join::Catalog->table_info(dsn => $dsn, username => $username, password => $password, table => $table); | |||||
| 847 | }; | |||||
| 848 | unless ($info) { | |||||
| 849 | my $err = $@; | |||||
| 850 | croak _fmt('error_mariadb_table', $table, $server, "$err") | |||||
| 851 | if blessed($err) && $err->can('stage') && $err->stage eq 'query'; | |||||
| 852 | croak _fmt('error_mariadb_connect', $server, "$err"); | |||||
| 853 | } | |||||
| 854 | my $columns = $info->{columns}; | |||||
| 855 | my @primary = @{ $info->{primary_key} }; | |||||
| 856 | ||||||
| 857 | # Two servers may each have an "orders". | |||||
| 858 | my $pkg = 'Database::BI::_DB::Mariadb_' . $server . '_' . $table; | |||||
| 859 | { | |||||
| 860 | 188 188 188 | 51250 126 11556 | no strict 'refs'; | |||
| 861 | push @{"${pkg}::ISA"}, 'Database::Abstraction' | |||||
| 862 | unless $pkg->isa('Database::Abstraction'); | |||||
| 863 | } | |||||
| 864 | require Database::Abstraction; | |||||
| 865 | my $db = eval { $pkg->new( | |||||
| 866 | dsn => $dsn, | |||||
| 867 | username => $username, | |||||
| 868 | password => $password, | |||||
| 869 | table => $table, | |||||
| 870 | no_entry => 1, | |||||
| 871 | ) }; | |||||
| 872 | croak _fmt('error_backend_init', $table, $@) unless $db; | |||||
| 873 | ||||||
| 874 | return bless { | |||||
| 875 | _table => $table, | |||||
| 876 | _raw_table => $table, | |||||
| 877 | _mariadb => $server, | |||||
| 878 | # Pages taken with LIMIT need an order that does not change between them. | |||||
| 879 | _order_col => (@primary == 1 && $primary[0] =~ $TABLE_NAME_RE) ? $primary[0] : undef, | |||||
| 880 | _id_col => $primary[0] // $columns->[0], | |||||
| 881 | _columns => $columns, | |||||
| 882 | _i18n => $raw->{i18n}, | |||||
| 883 | _db => $db, | |||||
| 884 | }, $class; | |||||
| 885 | 188 188 188 | 237 126 632 | } | |||
| 886 | ||||||
| 887 | # --------------------------------------------------------------------------- | |||||
| 888 | # Protected initialisation | |||||
| 889 | # --------------------------------------------------------------------------- | |||||
| 890 | ||||||
| 891 | # _csv_escape_char($path) -> '"' | '\\' | |||||
| 892 | # | |||||
| 893 | # Purpose: The escape character a delimited file is written with, chosen as | |||||
| 894 | # Database::Abstraction (>= 0.56) chooses it, so this module parses a | |||||
| 895 | # file as D::A will. | |||||
| 896 | # Entry: $path names a CSV, TSV or PSV file. | |||||
| 897 | # Exit: '\\' when the file holds a backslash before a quote anywhere (or | |||||
| 898 | # will not open); else '"' when it holds two quotes in a row (RFC | |||||
| 899 | # 4180's "Adeste ""Overture"""); else '\\'. | |||||
| 900 | sub _csv_escape_char { | |||||
| 901 | 2988 | 68106 | my ($path) = @_; | |||
| 902 | 2988 | 16877 | local ($@, $!); | |||
| 903 | 2988 | 4547 | local $/ = "\n"; | |||
| 904 | ||||||
| 905 | 2988 | 2575 | my $fh; | |||
| 906 | 188 188 188 2988 2988 | 29821 124 521 2366 19467 | { no autodie 'open'; open($fh, '<:raw', $path) or return '\\' } | |||
| 907 | 2986 | 2701 | my $doubled = 0; | |||
| 908 | 2986 | 9060 | while (my $line = <$fh>) { | |||
| 909 | 77557 | 35414 | if ($line =~ /\\"/) { | |||
| 910 | 6 | 13 | close $fh; | |||
| 911 | 6 | 182 | return '\\'; | |||
| 912 | } | |||||
| 913 | 77551 | 60028 | $doubled ||= ($line =~ /""/); | |||
| 914 | } | |||||
| 915 | 2980 | 7018 | close $fh; | |||
| 916 | 2980 | 112457 | return $doubled ? '"' : '\\'; | |||
| 917 | } | |||||
| 918 | ||||||
| 919 | # _best_id_column($fh, $sep, \@header_fields, $escape) -> $column_name | undef | |||||
| 920 | # | |||||
| 921 | # Purpose: The column Database::Abstraction should key rows on. | |||||
| 922 | # Entry: $fh is open just after the header line; @header_fields is the header | |||||
| 923 | # split and stripped, in file order (empty names included, so indexes | |||||
| 924 | # match the data). | |||||
| 925 | # Exit: The safe-identifier column with the fewest rows D::A would drop | |||||
| 926 | # (an empty cell, or one starting with '#', which D::A reads as a | |||||
| 927 | # comment), the earliest on a tie; undef when no header name is safe. | |||||
| 928 | # Reads $fh to its end. The file is parsed as D::A's slurp parses it | |||||
| 929 | # (with $escape, from _csv_escape_char), or a row like "Joe\"s Bar" | |||||
| 930 | # would end the count there; a line that still will not parse is | |||||
| 931 | # skipped, not the end. | |||||
| 932 | sub _best_id_column { | |||||
| 933 | 2982 | 43080 | my ($fh, $sep, $fields, $escape) = @_; | |||
| 934 | ||||||
| 935 | 2982 14328 2982 | 3309 30664 3651 | my @safe = grep { defined($fields->[$_]) && $fields->[$_] =~ $TABLE_NAME_RE } 0 .. $#{$fields}; | |||
| 936 | 2982 | 8560 | return undef unless @safe; | |||
| 937 | ||||||
| 938 | 2926 | 3411 | require Text::CSV; | |||
| 939 | 2926 | 9212 | my $csv = Text::CSV->new({ | |||
| 940 | binary => 1, sep_char => $sep, escape_char => $escape // '\\', | |||||
| 941 | allow_loose_quotes => 1, allow_whitespace => 1, | |||||
| 942 | }); | |||||
| 943 | 2926 14138 | 148920 12198 | my %dropped = map { $_ => 0 } @safe; | |||
| 944 | 2926 | 2611 | while (1) { | |||
| 945 | 127459 | 47554 | my $at = tell($fh); | |||
| 946 | 127459 | 138892 | my $row = $csv->getline($fh); | |||
| 947 | 127458 | 58621 | if (!$row) { | |||
| 948 | # The end, or a line that will not parse: go on from the next one, | |||||
| 949 | # unless nothing was read, which would loop for ever. | |||||
| 950 | 2925 | 4484 | last if $csv->eof() || eof($fh) || tell($fh) == $at; | |||
| 951 | 0 | 0 | next; | |||
| 952 | } | |||||
| 953 | 124533 313716 124533 | 40628 180570 48937 | next unless grep { defined($_) && length($_) } @{$row}; # a blank line is not a row | |||
| 954 | 124524 | 47052 | for my $i (@safe) { | |||
| 955 | 313037 | 114136 | my $cell = $row->[$i]; | |||
| 956 | 313037 | 287429 | $dropped{$i}++ if !defined($cell) || $cell !~ /\S/ || $cell =~ /\A\s*#/; | |||
| 957 | } | |||||
| 958 | } | |||||
| 959 | ||||||
| 960 | 2925 17265 | 12378 13226 | my ($best) = sort { $dropped{$a} <=> $dropped{$b} || $a <=> $b } @safe; | |||
| 961 | 2925 | 8935 | return $fields->[$best]; | |||
| 962 | } | |||||
| 963 | ||||||
| 964 | # _detect_file_info( $dir, $table ) -> \%info | |||||
| 965 | # | |||||
| 966 | # Peek at the first header line of a CSV, TSV or PSV file and return a hashref: | |||||
| 967 | # sep_char => field separator character (',' or '|') | |||||
| 968 | # id => first column name (used as Database::Abstraction's id key) | |||||
| 969 | # columns => arrayref of all column names in file order | |||||
| 970 | # | |||||
| 971 | # Two non-obvious defaults in Database::Abstraction make this necessary: | |||||
| 972 | # 1. sep_char defaults to '!' -- so a plain CSV is read as one giant field | |||||
| 973 | # per row, producing a single comma-joined string instead of columns. | |||||
| 974 | # 2. id defaults to 'entry' -- the slurp filter greps on that column; if it | |||||
| 975 | # doesn't exist every row is silently discarded. | |||||
| 976 | # Returns an empty hashref for non-CSV/TSV/PSV/XLSX/SQLite formats (XML, etc.). | |||||
| 977 | # For SQLite/.db files that can be opened, returns { sqlite_tables => [...] }. | |||||
| 978 | sub _detect_file_info :Protected { | |||||
| 979 | my ($dir, $table, $want, $flatten) = @_; | |||||
| 980 | ||||||
| 981 | # XLSX: D::A reads the rows. This parse is for what D::A cannot say: an | |||||
| 982 | # empty workbook makes it croak, and its columns() is alphabetical, not the | |||||
| 983 | # order of the sheet. | |||||
| 984 | { | |||||
| 985 | my $path = File::Spec->catfile($dir, "$table.xlsx"); | |||||
| 986 | if (-r $path) { | |||||
| 987 | my $ok = eval { require Spreadsheet::ParseXLSX; 1 }; | |||||
| 988 | if ($ok) { | |||||
| 989 | my $parser = Spreadsheet::ParseXLSX->new; | |||||
| 990 | my $wb = $parser->parse($path); | |||||
| 991 | ||||||
| 992 | # A workbook's sheets are its tables, as a JSON file's lists are: | |||||
| 993 | # with two or more, _init_backend lists them (so /open offers the | |||||
| 994 | # picker) and $want, the internal_table, names the one to read. | |||||
| 995 | my @sheets = $wb ? map { $_->get_name } $wb->worksheets : (); | |||||
| 996 | my %multi = @sheets > 1 ? (_json_lists => [ @sheets ]) : (); | |||||
| 997 | ||||||
| 998 | # The sheet to read: the one asked for, else the one named after | |||||
| 999 | # the table, else the first. | |||||
| 1000 | my $ws; | |||||
| 1001 | if (defined $want) { | |||||
| 1002 | ($ws) = grep { $_->get_name eq $want } $wb->worksheets if $wb; | |||||
| 1003 | croak _fmt('error_sheet_not_found', $table, $want, join(', ', @sheets)) | |||||
| 1004 | unless $ws; | |||||
| 1005 | } else { | |||||
| 1006 | my $sheet_name = _safe_table_name($table); | |||||
| 1007 | ($ws) = $wb ? grep { $_->get_name eq $sheet_name } $wb->worksheets : (); | |||||
| 1008 | $ws //= $wb ? $wb->worksheet(0) : undef; | |||||
| 1009 | } | |||||
| 1010 | ||||||
| 1011 | unless ($ws) { | |||||
| 1012 | # Empty workbook or parse failure: sentinel so _init_backend | |||||
| 1013 | # skips D::A (which would fail with "(no error string)"). | |||||
| 1014 | return { _file_is_empty => 1, file_size => -s $path }; | |||||
| 1015 | } | |||||
| 1016 | ||||||
| 1017 | my ($rmin, $rmax) = $ws->row_range; | |||||
| 1018 | my ($cmin, $cmax) = $ws->col_range; | |||||
| 1019 | ||||||
| 1020 | # No rows at all (blank worksheet). | |||||
| 1021 | return { _file_is_empty => 1, file_size => -s $path, %multi } | |||||
| 1022 | if $rmax < $rmin; | |||||
| 1023 | ||||||
| 1024 | # Row 0 = column headers, spelt as D::A will key the rows. A | |||||
| 1025 | # column with no name stays out of the list, so it is not shown. | |||||
| 1026 | my @cols; | |||||
| 1027 | for my $c ($cmin .. $cmax) { | |||||
| 1028 | my $cell = $ws->get_cell($rmin, $c); | |||||
| 1029 | my $name = defined $cell ? ($cell->value // '') : ''; | |||||
| 1030 | push @cols, $name if $name =~ /[^\s"]/; | |||||
| 1031 | } | |||||
| 1032 | ||||||
| 1033 | # No parseable column names. | |||||
| 1034 | return { _file_is_empty => 1, file_size => -s $path, %multi } | |||||
| 1035 | unless @cols; | |||||
| 1036 | ||||||
| 1037 | # D::A names a worksheet in SQL and refuses one whose name is not | |||||
| 1038 | # a safe identifier ("Q1 Sales"), so a chosen sheet like that is | |||||
| 1039 | # read here and handed over as a flat JSON copy, as a JSON file is. | |||||
| 1040 | if (defined $want && $ws->get_name !~ $TABLE_NAME_RE) { | |||||
| 1041 | my @rows; | |||||
| 1042 | my %keep = map { $_ => 1 } @cols; | |||||
| 1043 | for my $r ($rmin + 1 .. $rmax) { | |||||
| 1044 | my %row; | |||||
| 1045 | my $any; | |||||
| 1046 | for my $c ($cmin .. $cmax) { | |||||
| 1047 | my $h = $ws->get_cell($rmin, $c); | |||||
| 1048 | my $hn = defined $h ? ($h->value // '') : ''; | |||||
| 1049 | next unless $keep{$hn}; | |||||
| 1050 | my $cell = $ws->get_cell($r, $c); | |||||
| 1051 | my $v = defined $cell ? $cell->value : undef; | |||||
| 1052 | $any = 1 if defined $v && length $v; | |||||
| 1053 | $row{$hn} = defined $v ? "$v" : ''; | |||||
| 1054 | } | |||||
| 1055 | push @rows, \%row if $any; | |||||
| 1056 | } | |||||
| 1057 | return { _file_is_empty => 1, file_size => -s $path, %multi } unless @rows; | |||||
| 1058 | return { _json => { rows => \@rows, columns => \@cols, list => $ws->get_name }, | |||||
| 1059 | columns => \@cols, id => (grep({ $_ =~ $TABLE_NAME_RE } @cols))[0] // 'entry', | |||||
| 1060 | file_size => -s $path, %multi }; | |||||
| 1061 | } | |||||
| 1062 | ||||||
| 1063 | my ($safe_id) = grep { $_ =~ $TABLE_NAME_RE } @cols; | |||||
| 1064 | ||||||
| 1065 | # With no_entry D::A does not use the id for a workbook, so | |||||
| 1066 | # headers that are all unsafe ("First Name") need no id of their own. | |||||
| 1067 | return { | |||||
| 1068 | columns => \@cols, | |||||
| 1069 | id => $safe_id // 'entry', | |||||
| 1070 | file_size => -s $path, | |||||
| 1071 | (defined $want ? (_sheet => $ws->get_name) : ()), | |||||
| 1072 | %multi, | |||||
| 1073 | }; | |||||
| 1074 | } | |||||
| 1075 | } | |||||
| 1076 | } | |||||
| 1077 | ||||||
| 1078 | for my $ext (qw(csv psv tsv)) { | |||||
| 1079 | my $path = File::Spec->catfile($dir, "$table.$ext"); | |||||
| 1080 | next unless -r $path; | |||||
| 1081 | # "use autodie" makes open() die on failure, so "or next" would be dead | |||||
| 1082 | # code. Disable autodie for this open so a vanishing file (race between | |||||
| 1083 | # the -r probe and the open) results in a clean skip rather than a croak. | |||||
| 1084 | my $fh; | |||||
| 1085 | 188 188 188 | 82865 131 248 | { no autodie 'open'; open $fh, '<', $path or next } | |||
| 1086 | my $line = <$fh>; | |||||
| 1087 | # 0-byte file: no header, no rows. Return a sentinel so _init_backend | |||||
| 1088 | # can skip Database::Abstraction entirely. If we let D::A see an empty | |||||
| 1089 | # file it falls through to the DBD::CSV path, whose error handling on | |||||
| 1090 | # an empty SELECT corrupts DBI's internal Errstr SV; on a DEBUGGING perl | |||||
| 1091 | # (DBI 1.651 + perl 5.44.0) this triggers an XS assertion at cleanup. | |||||
| 1092 | unless (defined $line) { | |||||
| 1093 | close $fh; | |||||
| 1094 | return { _file_is_empty => 1, file_size => 0 }; | |||||
| 1095 | } | |||||
| 1096 | chomp $line; | |||||
| 1097 | $line =~ s/\r\z//; # strip CR from CRLF files before any split | |||||
| 1098 | # A UTF-8 byte-order mark, which Excel's "CSV UTF-8" writes, is not | |||||
| 1099 | # part of the first column's name. D::A would keep it there, so it | |||||
| 1100 | # reads a copy without it (see _init_backend). | |||||
| 1101 | my $bom = $line =~ s/\A\xEF\xBB\xBF//; | |||||
| 1102 | ||||||
| 1103 | my $sep; | |||||
| 1104 | if($ext eq 'psv') { | |||||
| 1105 | $sep = '|'; | |||||
| 1106 | } elsif($ext eq 'tsv') { | |||||
| 1107 | $sep = "\t"; | |||||
| 1108 | } else { | |||||
| 1109 | # Sniff the separator: Database::Abstraction uses '!' natively and | |||||
| 1110 | # sometimes stores those files with a .csv extension. If splitting | |||||
| 1111 | # on ',' yields a single field that itself contains '!', the real | |||||
| 1112 | # separator is almost certainly '!'. | |||||
| 1113 | my @probe = split /,/, $line, -1; | |||||
| 1114 | $sep = (@probe == 1 && $line =~ /!/) ? '!' : ','; | |||||
| 1115 | } | |||||
| 1116 | ||||||
| 1117 | my @fields = _split_csv_line($line, $sep); | |||||
| 1118 | # Two separate substitutions: the /g on an anchored alternation wastes | |||||
| 1119 | # O(N) engine cycles retrying \A (which can only match at position 0). | |||||
| 1120 | for (@fields) { s/\A[\s"]+//; s/[\s"]+\z// } # strip whitespace and quotes | |||||
| 1121 | pop @fields while @fields && !length $fields[-1]; # a trailing separator | |||||
| 1122 | my @cols = grep { length } @fields; | |||||
| 1123 | ||||||
| 1124 | # A blank first line (e.g. a file containing only "\n") produces an | |||||
| 1125 | # empty column list. Treat that the same as a 0-byte file: return the | |||||
| 1126 | # _file_is_empty sentinel so _init_backend skips D::A entirely. | |||||
| 1127 | # Attempting to construct D::A with id => undef and an empty columns | |||||
| 1128 | # list would croak error_no_safe_id -- misleading for what is effectively | |||||
| 1129 | # an empty file. | |||||
| 1130 | if (!@cols) { | |||||
| 1131 | close $fh; | |||||
| 1132 | return { _file_is_empty => 1, file_size => -s $path }; | |||||
| 1133 | } | |||||
| 1134 | ||||||
| 1135 | # Database::Abstraction validates id against $SAFE_IDENTIFIER | |||||
| 1136 | # (/\A[a-zA-Z_][a-zA-Z0-9_]*\z/) at construction time and uses it as | |||||
| 1137 | # a row-existence sentinel: every data row must have a defined, non-# | |||||
| 1138 | # value in the id column or D::A drops it (empty_is_undef => 1 makes | |||||
| 1139 | # truly empty cells undef). | |||||
| 1140 | # | |||||
| 1141 | # Strategy: of the safe columns, the one with the fewest empty cells | |||||
| 1142 | # across the whole file, the earliest on a tie. Choosing by the first | |||||
| 1143 | # data row alone lost rows: a bank export whose first transaction had a | |||||
| 1144 | # cheque number made Check the id, and D::A then dropped the 358 of 362 | |||||
| 1145 | # rows that had none. D::A reads the whole file anyway (max_slurp_size | |||||
| 1146 | # is the file's size), so one more pass costs no more than that. With | |||||
| 1147 | # no data rows, the first safe column in the header. | |||||
| 1148 | my $safe_id = _best_id_column($fh, $sep, \@fields, _csv_escape_char($path)); | |||||
| 1149 | ||||||
| 1150 | # If no safe identifier was found in the header, check whether the first | |||||
| 1151 | # row looks like data values rather than column names. A CSV exported | |||||
| 1152 | # from a bank or accounting system often has no header row at all -- the | |||||
| 1153 | # first line is already a transaction record. When that is the case, | |||||
| 1154 | # synthesize safe column names by inferring the type of each value | |||||
| 1155 | # (date, amount, description); _init_backend then gives D::A a copy of | |||||
| 1156 | # the file with those names as its header. | |||||
| 1157 | unless (defined $safe_id) { | |||||
| 1158 | if (_values_are_data_like(\@cols)) { | |||||
| 1159 | my @synth = _synthesize_col_names(\@fields); | |||||
| 1160 | close $fh; | |||||
| 1161 | return { | |||||
| 1162 | sep_char => $sep, | |||||
| 1163 | id => $synth[0], | |||||
| 1164 | columns => \@synth, | |||||
| 1165 | _headerless => { path => $path, ext => $ext }, # its copy drops a BOM | |||||
| 1166 | file_size => -s $path, | |||||
| 1167 | }; | |||||
| 1168 | } | |||||
| 1169 | } | |||||
| 1170 | ||||||
| 1171 | close $fh; | |||||
| 1172 | ||||||
| 1173 | # Return file_size so _init_backend can pass it as max_slurp_size to | |||||
| 1174 | # Database::Abstraction. Without this, files larger than D::A's default | |||||
| 1175 | # 16 KB threshold go through the DBI/DBD::CSV path, which lowercases | |||||
| 1176 | # column names and replaces spaces with underscores ("Account Number" -> | |||||
| 1177 | # "account_number"). The slurp path (Text::xSV::Slurp) preserves the | |||||
| 1178 | # original header names, so forcing it avoids the mismatch. | |||||
| 1179 | return { | |||||
| 1180 | sep_char => $sep, | |||||
| 1181 | id => $safe_id, | |||||
| 1182 | columns => \@cols, | |||||
| 1183 | ($bom ? (_bom => { path => $path, ext => $ext }) : ()), | |||||
| 1184 | file_size => -s $path, | |||||
| 1185 | }; | |||||
| 1186 | } | |||||
| 1187 | ||||||
| 1188 | # SQLite / Berkeley DB: peek at sqlite_master to discover the internal table | |||||
| 1189 | # names. _init_backend uses this list to auto-select the correct table when | |||||
| 1190 | # the filename stem (dbname) differs from the table name inside the file -- | |||||
| 1191 | # e.g. obituaries.sql whose internal table is called "deceased". If the | |||||
| 1192 | # file is not a valid SQLite database (e.g. a Berkeley DB file) the eval | |||||
| 1193 | # fails; for .db files we then check for BerkeleyDB magic so we can read | |||||
| 1194 | # the data directly (or return an error sentinel) instead of letting D::A | |||||
| 1195 | # fall through to its CSV path, which would read a large binary file as text. | |||||
| 1196 | # .sqlite and .sqlite3 are common alternative SQLite extensions -- treated identically to .sql. | |||||
| 1197 | my $non_sqlite_db; # set to path when a .db file fails the SQLite probe | |||||
| 1198 | for my $ext (qw(sql sqlite sqlite3 db)) { | |||||
| 1199 | my $path = File::Spec->catfile($dir, "$table.$ext"); | |||||
| 1200 | next unless -r $path; | |||||
| 1201 | my $tables = eval { | |||||
| 1202 | require Database::Join::Catalog; | |||||
| 1203 | Database::Join::Catalog->tables(file => $path); | |||||
| 1204 | }; | |||||
| 1205 | # defined $tables means the eval succeeded (even an empty list is valid) | |||||
| 1206 | return { sqlite_tables => ($tables // []), file_size => -s $path } | |||||
| 1207 | if defined $tables; | |||||
| 1208 | $non_sqlite_db = $path if $ext eq 'db'; | |||||
| 1209 | last; # file found but not SQLite -- do not try the other ext | |||||
| 1210 | } | |||||
| 1211 | ||||||
| 1212 | # A .db file that is not SQLite: check for BerkeleyDB magic bytes. | |||||
| 1213 | # BerkeleyDB Hash/Btree/Queue files begin with a 32-bit magic number either | |||||
| 1214 | # at offset 0 (big-endian files) or at offset 12 (little-endian files). | |||||
| 1215 | # If found, try to open via DB_File under a 10-second alarm so a version- | |||||
| 1216 | # incompatible file does not block the server for minutes. | |||||
| 1217 | if (defined $non_sqlite_db) { | |||||
| 1218 | my $magic_ok = 0; | |||||
| 1219 | if (open(my $fh, '<:raw', $non_sqlite_db)) { | |||||
| 1220 | my $buf = ''; | |||||
| 1221 | if (read($fh, $buf, 4) == 4) { | |||||
| 1222 | my %MAGIC = map { $_ => 1 } | |||||
| 1223 | (0x00061561, 0x00053162, 0x00042253, 0x00052444); | |||||
| 1224 | $magic_ok = 1 if $MAGIC{unpack('N', $buf)} || $MAGIC{unpack('V', $buf)}; | |||||
| 1225 | } | |||||
| 1226 | unless ($magic_ok) { | |||||
| 1227 | if (seek $fh, 12, 0) { | |||||
| 1228 | my $b12 = ''; | |||||
| 1229 | if (read($fh, $b12, 4) == 4) { | |||||
| 1230 | my $hex = substr(unpack('H*', $b12), 0, 4); | |||||
| 1231 | $magic_ok = 1 if $hex eq '6115' || $hex eq '1561'; | |||||
| 1232 | } | |||||
| 1233 | } | |||||
| 1234 | } | |||||
| 1235 | close $fh; | |||||
| 1236 | } | |||||
| 1237 | if ($magic_ok) { | |||||
| 1238 | my $fsize = -s $non_sqlite_db; | |||||
| 1239 | # BerkeleyDB magic confirmed. Check that DB_File can open it, | |||||
| 1240 | # so that D::A never reads a file it cannot as CSV text, | |||||
| 1241 | # but only for reasonably-sized files (<= 100 MB). Opening a | |||||
| 1242 | # multi-GB BerkeleyDB file with an incompatible library version | |||||
| 1243 | # causes multi-minute disk I/O that cannot be interrupted with | |||||
| 1244 | # alarm() (XS I/O in libdb-5.x ignores SIGALRM via SA_RESTART). | |||||
| 1245 | # For large files, return the unsupported sentinel immediately. | |||||
| 1246 | Readonly my $BDB_MAX_BYTES => 100 * 1024 * 1024; # 100 MB | |||||
| 1247 | if (defined $fsize && $fsize > $BDB_MAX_BYTES) { | |||||
| 1248 | return { _unknown_binary_db => 1, file_size => $fsize }; | |||||
| 1249 | } | |||||
| 1250 | my $opens = eval { | |||||
| 1251 | require DB_File; | |||||
| 1252 | my %bdb; | |||||
| 1253 | # Capture the tie object so we can undef it before untie -- | |||||
| 1254 | # DB_File warns "untie while N inner references" if the object | |||||
| 1255 | # reference count is > 0 when untie fires. | |||||
| 1256 | my $db_obj = tie %bdb, 'DB_File', $non_sqlite_db, | |||||
| 1257 | 188 188 188 | 55421 126 38528 | Fcntl::O_RDONLY(), 0644, do { no warnings "once"; $DB_File::DB_HASH }; | |||
| 1258 | return 0 unless $db_obj; | |||||
| 1259 | undef $db_obj; | |||||
| 1260 | untie %bdb; | |||||
| 1261 | 1; | |||||
| 1262 | }; | |||||
| 1263 | if ($opens) { | |||||
| 1264 | return { | |||||
| 1265 | columns => ['entry', 'value'], | |||||
| 1266 | id => 'entry', | |||||
| 1267 | file_size => $fsize, | |||||
| 1268 | }; | |||||
| 1269 | } | |||||
| 1270 | # tie failed: return a sentinel so _init_backend can show a proper | |||||
| 1271 | # error instead of letting D::A read the binary file as CSV text. | |||||
| 1272 | return { _unknown_binary_db => 1, file_size => $fsize }; | |||||
| 1273 | } | |||||
| 1274 | } | |||||
| 1275 | ||||||
| 1276 | # XML that is a document, not a list of rows (a DMARC report: a few | |||||
| 1277 | # one-off elements and a repeating <record>): D::A reads one repeating | |||||
| 1278 | # element of a flat document and croaks on the rest, so write the rows as | |||||
| 1279 | # a flat JSON copy, as for a .json file. A file D::A can read is left to it. | |||||
| 1280 | { | |||||
| 1281 | my $path = File::Spec->catfile($dir, "$table.xml"); | |||||
| 1282 | if (-r $path && !grep { -f File::Spec->catfile($dir, "$table.$_") } grep { $_ ne 'xml' } @NON_JSON_EXT) { | |||||
| 1283 | # Before either reader: D::A's own XML::Simple would resolve an | |||||
| 1284 | # external entity just as _xml_table's does. | |||||
| 1285 | _refuse_xml_entities($path); | |||||
| 1286 | my $xml = _xml_table($path); | |||||
| 1287 | if ($xml) { | |||||
| 1288 | my ($safe_id) = grep { $_ =~ $TABLE_NAME_RE } @{ $xml->{columns} }; | |||||
| 1289 | return { | |||||
| 1290 | columns => $xml->{columns}, | |||||
| 1291 | id => $safe_id // 'entry', | |||||
| 1292 | _json => $xml, | |||||
| 1293 | }; | |||||
| 1294 | } | |||||
| 1295 | } | |||||
| 1296 | } | |||||
| 1297 | ||||||
| 1298 | # JSON comes last, as it does in D::A's own search: a table.csv beside | |||||
| 1299 | # table.json is the file D::A opens. JSON Lines is read the same way, after | |||||
| 1300 | # .json. | |||||
| 1301 | for my $ext ('json', @JSON_LINES_EXT) { | |||||
| 1302 | my $path = File::Spec->catfile($dir, "$table.$ext"); | |||||
| 1303 | next unless -r $path && !grep { -f File::Spec->catfile($dir, "$table.$_") } (@NON_JSON_EXT, $ext eq 'json' ? () : ('json')); | |||||
| 1304 | my $json = $ext eq 'json' | |||||
| 1305 | ? _json_table($path, $want, $flatten) | |||||
| 1306 | : _jsonl_table($path, $want, $flatten); | |||||
| 1307 | return { _file_is_empty => 1, file_size => -s $path, _json_lists => $json->{lists} } | |||||
| 1308 | unless $json->{count}; | |||||
| 1309 | my ($safe_id) = grep { $_ =~ $TABLE_NAME_RE } @{ $json->{columns} }; | |||||
| 1310 | return { | |||||
| 1311 | columns => $json->{columns}, | |||||
| 1312 | id => $safe_id // 'entry', | |||||
| 1313 | _json => $json, | |||||
| 1314 | _json_lists => $json->{lists}, | |||||
| 1315 | }; | |||||
| 1316 | } | |||||
| 1317 | return {}; | |||||
| 1318 | 188 188 188 | 246 129 979 | } | |||
| 1319 | ||||||
| 1320 | # _refuse_xml_entities( $path ) -> () | croaks error_xml_entities | |||||
| 1321 | # | |||||
| 1322 | # Purpose: Stop an XML file from making the parser read something it was not | |||||
| 1323 | # given. <!ENTITY x SYSTEM "file:///etc/passwd"> in the prolog, then | |||||
| 1324 | # &x; in a cell, puts that file in the table (and bypasses file_roots, | |||||
| 1325 | # because the parser, not this code, opens it); a SYSTEM "http://..." | |||||
| 1326 | # one makes the server fetch an address. | |||||
| 1327 | # Premise 1: an entity can only be declared with the token "<!ENTITY". | |||||
| 1328 | # Premise 2: a flat data file has no use for one. | |||||
| 1329 | # Premise 3: a UTF-16 file spells that token with NUL bytes, which the match | |||||
| 1330 | # would miss, and a document with a NUL in it is not text XML. | |||||
| 1331 | # Conclusion: a file holding the token, a NUL or a UTF-16 byte-order mark is | |||||
| 1332 | # refused before any parser sees it. | |||||
| 1333 | # Entry: $path is a readable .xml file. | |||||
| 1334 | sub _refuse_xml_entities { | |||||
| 1335 | 870 | 25595 | my ($path) = @_; | |||
| 1336 | 870 | 630 | local ($@, $!); | |||
| 1337 | # Premise 1: only a plain file can be read to its end; a named pipe blocks | |||||
| 1338 | # the open until something writes to it. Conclusion: leave anything else | |||||
| 1339 | # to the reader, which reports it. | |||||
| 1340 | 870 | 1289 | return unless defined $path && -f $path; | |||
| 1341 | # A file that cannot be read is the reader's to report; autodie would throw here. | |||||
| 1342 | 466 | 181 | my $fh; | |||
| 1343 | 188 188 188 466 466 | 36541 130 444 178 1466 | { no autodie 'open'; open $fh, '<:raw', $path or return; } | |||
| 1344 | # Read in blocks, not the whole file: a gigabyte of XML must not be held to | |||||
| 1345 | # look for eight bytes. The last bytes of one block are kept in front of | |||||
| 1346 | # the next, so a marker cut by a block boundary is still found. | |||||
| 1347 | 466 | 235 | my ($tail, $bom_checked) = ('', 0); | |||
| 1348 | 466 | 220 | my $found = 0; | |||
| 1349 | 466 | 347 | while (read($fh, my $block, $XML_SCAN_BLOCK)) { | |||
| 1350 | 555 | 13019 | my $window = $tail . $block; | |||
| 1351 | 555 | 15840 | $found = 1, last if $window =~ /<!ENTITY|\0/ || (!$bom_checked && $window =~ /\A(?:\xFF\xFE|\xFE\xFF)/); | |||
| 1352 | 322 | 144 | $bom_checked = 1; | |||
| 1353 | 322 | 213 | $tail = substr($window, -$XML_MARKER_OVERLAP); | |||
| 1354 | } | |||||
| 1355 | 466 | 3945 | close $fh; | |||
| 1356 | 466 | 5536 | croak _fmt('error_xml_entities', $path) if $found; | |||
| 1357 | 233 | 197 | return; | |||
| 1358 | } | |||||
| 1359 | ||||||
| 1360 | # _xml_table( $path ) -> { rows, columns, list } | undef | |||||
| 1361 | # | |||||
| 1362 | # Purpose: Read an XML document that holds more than one kind of top-level | |||||
| 1363 | # element (a DMARC report: report_metadata, policy_published, a | |||||
| 1364 | # repeating record) as a table. | |||||
| 1365 | # Entry: $path is a readable .xml file. | |||||
| 1366 | # Exit: undef when the file is not such a document (it does not parse, or | |||||
| 1367 | # has fewer than two kinds of child element under the root, or none | |||||
| 1368 | # repeats as hashes): D::A reads it as it always did. Otherwise | |||||
| 1369 | # rows: flat hashes, columns: in the order the file first names them. | |||||
| 1370 | # Notes: The row element is the child element that occurs most often, the | |||||
| 1371 | # one with the most values on a tie, then the first by name. Each | |||||
| 1372 | # row has its own values (a child's name is the column, nested ones | |||||
| 1373 | # joined by "_": row_source_ip) and every other top-level value | |||||
| 1374 | # (report_metadata_org_name, version), repeated on every row, so a | |||||
| 1375 | # report's rows still say whose report they came from. A repeated | |||||
| 1376 | # element inside a row becomes a list in one cell, "a, b", or its | |||||
| 1377 | # JSON text when its members are not plain values. Attributes | |||||
| 1378 | # are columns beside the child elements. KeyAttr is empty so that | |||||
| 1379 | # XML::Simple does not fold name/id/key elements (see the POD). | |||||
| 1380 | sub _xml_table { | |||||
| 1381 | 22 | 28 | my ($path) = @_; | |||
| 1382 | 22 | 74 | local ($@, $!); | |||
| 1383 | 22 | 36 | local $/ = "\n"; | |||
| 1384 | 22 | 36 | require XML::Simple; | |||
| 1385 | 22 | 38 | open my $fh, '<:raw', $path or return undef; | |||
| 1386 | 22 22 22 | 1559 25 86 | my $text = do { local $/; <$fh> }; | |||
| 1387 | 22 | 24 | close $fh; | |||
| 1388 | 22 | 310 | return undef unless defined $text && length $text; | |||
| 1389 | ||||||
| 1390 | 22 | 14 | my $doc = eval { | |||
| 1391 | 22 | 55 | XML::Simple::XMLin(\$text, ForceArray => 1, KeyAttr => [], SuppressEmpty => ''); | |||
| 1392 | }; | |||||
| 1393 | 22 | 89894 | return undef unless ref $doc eq 'HASH'; | |||
| 1394 | ||||||
| 1395 | 21 49 21 | 20 57 31 | my @kinds = grep { ref $doc->{$_} eq 'ARRAY' } keys %{$doc}; | |||
| 1396 | 21 | 91 | return undef if @kinds < 2; | |||
| 1397 | ||||||
| 1398 | # The row element: repeated, and every occurrence an element with parts. | |||||
| 1399 | 10 | 8 | my ($row_key, @best); | |||
| 1400 | 10 | 21 | for my $k (sort @kinds) { | |||
| 1401 | 38 | 20 | my $list = $doc->{$k}; | |||
| 1402 | 38 47 38 | 16 36 19 | next if grep { ref $_ ne 'HASH' } @{$list}; | |||
| 1403 | 28 | 8 | my $values = 0; | |||
| 1404 | 28 28 | 17 13 | for my $one (@{$list}) { | |||
| 1405 | 37 | 18 | my %flat; | |||
| 1406 | 37 | 28 | _xml_flat($one, '', \%flat); | |||
| 1407 | 37 | 30 | $values += keys %flat; | |||
| 1408 | } | |||||
| 1409 | 28 28 | 13 21 | my @score = (scalar @{$list}, $values); | |||
| 1410 | 28 | 44 | if (!defined $row_key || $score[0] > $best[0] || ($score[0] == $best[0] && $score[1] > $best[1])) { | |||
| 1411 | 19 | 17 | ($row_key, @best) = ($k, @score); | |||
| 1412 | } | |||||
| 1413 | } | |||||
| 1414 | 10 | 7 | return undef unless defined $row_key; | |||
| 1415 | ||||||
| 1416 | 10 | 7 | my %context; | |||
| 1417 | 10 10 | 6 11 | for my $k (keys %{$doc}) { | |||
| 1418 | 38 | 19 | next if $k eq $row_key; | |||
| 1419 | 28 | 23 | _xml_flat($doc->{$k}, $k, \%context); | |||
| 1420 | } | |||||
| 1421 | 10 | 10 | my @rows; | |||
| 1422 | 10 10 | 3 9 | for my $one (@{ $doc->{$row_key} }) { | |||
| 1423 | 19 | 7 | my %row; | |||
| 1424 | 19 | 17 | _xml_flat($one, '', \%row); | |||
| 1425 | 19 | 78 | push @rows, { %context, %row }; | |||
| 1426 | } | |||||
| 1427 | ||||||
| 1428 | # Column order: where each name first appears in the text. The parse | |||||
| 1429 | # keeps none. A tag's path below the root names its column, without the | |||||
| 1430 | # row element's own name. | |||||
| 1431 | 10 | 64 | (my $scan = $text) =~ s/<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>|<!DOCTYPE[^>\[]*(?:\[.*?\])?>//gs; | |||
| 1432 | 10 | 8 | my (@stack, @columns, %seen); | |||
| 1433 | 10 | 31 | while ($scan =~ /<(\/?)([^\s\/>!?]+)[^>]*?(\/?)>/g) { | |||
| 1434 | 768 | 423 | my ($close, $name, $self_close) = ($1, $2, $3); | |||
| 1435 | 768 | 352 | if ($close) { | |||
| 1436 | 384 | 137 | pop @stack; | |||
| 1437 | 384 | 280 | next; | |||
| 1438 | } | |||||
| 1439 | 384 | 161 | push @stack, $name; | |||
| 1440 | 384 | 217 | my @parts = @stack[ 1 .. $#stack ]; | |||
| 1441 | 384 | 274 | shift @parts if @parts && $parts[0] eq $row_key; | |||
| 1442 | 384 | 182 | my $col = join '_', @parts; | |||
| 1443 | 384 | 297 | if (length $col && !$seen{$col}++) { | |||
| 1444 | 229 | 104 | push @columns, $col; | |||
| 1445 | } | |||||
| 1446 | 384 | 362 | pop @stack if $self_close; | |||
| 1447 | } | |||||
| 1448 | 10 255 19 19 | 6 137 7 38 | my %known = map { $_ => 1 } map { keys %{$_} } @rows; | |||
| 1449 | 10 229 | 20 105 | @columns = grep { $known{$_} } @columns; | |||
| 1450 | 10 139 | 6 67 | my %placed = map { $_ => 1 } @columns; | |||
| 1451 | 10 139 | 29 70 | push @columns, grep { !$placed{$_} } sort keys %known; | |||
| 1452 | ||||||
| 1453 | 10 | 7 | for my $row (@rows) { | |||
| 1454 | 19 | 65 | $row->{$_} //= '' for @columns; | |||
| 1455 | } | |||||
| 1456 | 10 | 112 | return { rows => \@rows, columns => \@columns, list => undef }; | |||
| 1457 | } | |||||
| 1458 | ||||||
| 1459 | # _xml_flat( $node, $name, \%out ) | |||||
| 1460 | # | |||||
| 1461 | # Purpose: Flatten one node of an XML::Simple (ForceArray) tree into cells. | |||||
| 1462 | # Entry: $name is the column so far ('' at the top of a row). | |||||
| 1463 | sub _xml_flat { | |||||
| 1464 | 1222 | 547 | my ($node, $name, $out) = @_; | |||
| 1465 | 1222 | 579 | if (ref $node eq 'ARRAY') { | |||
| 1466 | 592 592 | 213 265 | if (@{$node} == 1) { | |||
| 1467 | 574 | 247 | _xml_flat($node->[0], $name, $out); | |||
| 1468 | 36 18 | 23 12 | } elsif (!grep { ref $_ } @{$node}) { | |||
| 1469 | 0 0 | 0 0 | $out->{$name} = join ', ', @{$node}; | |||
| 1470 | } else { | |||||
| 1471 | 18 | 26 | require Mojo::JSON; | |||
| 1472 | 18 | 26 | $out->{$name} = Mojo::JSON::to_json($node); | |||
| 1473 | } | |||||
| 1474 | } elsif (ref $node eq 'HASH') { | |||||
| 1475 | 262 262 | 91 186 | for my $k (sort keys %{$node}) { | |||
| 1476 | 564 | 349 | _xml_flat($node->{$k}, length $name ? "${name}_$k" : $k, $out); | |||
| 1477 | } | |||||
| 1478 | } elsif (length $name) { | |||||
| 1479 | 368 | 210 | $out->{$name} = $node; | |||
| 1480 | } | |||||
| 1481 | 1222 | 599 | return; | |||
| 1482 | } | |||||
| 1483 | ||||||
| 1484 | # _json_read( $path ) -> ($text, $data) | |||||
| 1485 | # | |||||
| 1486 | # Purpose: A JSON file's bytes and what they parse to. | |||||
| 1487 | # Exit: ('', undef) for a zero-byte or blank file. Croaks | |||||
| 1488 | # error_json_invalid when the text is not JSON. | |||||
| 1489 | sub _json_read { | |||||
| 1490 | 54 | 35 | my $path = shift; | |||
| 1491 | 54 | 269 | local ($@, $!); | |||
| 1492 | 54 | 29 | my $text = do { | |||
| 1493 | 54 | 79 | open my $fh, '<:raw', $path; | |||
| 1494 | 54 | 2737 | local $/; | |||
| 1495 | 54 | 347 | my $t = <$fh>; | |||
| 1496 | 54 | 87 | close $fh; | |||
| 1497 | 54 | 1108 | $t // ''; | |||
| 1498 | }; | |||||
| 1499 | 54 | 83 | return ('', undef) if $text !~ /\S/; | |||
| 1500 | ||||||
| 1501 | 52 | 76 | require Mojo::JSON; | |||
| 1502 | 52 | 32 | my $data; | |||
| 1503 | 52 52 49 | 32 81 296 | unless (eval { $data = Mojo::JSON::decode_json($text); 1 }) { | |||
| 1504 | 3 | 35 | (my $why = $@ // '') =~ s/\s+at \S+ line \d+\.?\s*\z//; | |||
| 1505 | 3 | 6 | croak _fmt('error_json_invalid', $path, $why); | |||
| 1506 | } | |||||
| 1507 | 49 | 68 | return ($text, $data); | |||
| 1508 | } | |||||
| 1509 | ||||||
| 1510 | # _json_list_keys( $text, $data ) -> @keys | |||||
| 1511 | # | |||||
| 1512 | # Purpose: The top-level keys of a JSON object that hold a list of objects, in | |||||
| 1513 | # the order the file gives them: each is a table. | |||||
| 1514 | # Notes: A list holding anything but objects is not a table. An empty list | |||||
| 1515 | # counts only when no list has rows, so { "items": [], "rows": [...] } | |||||
| 1516 | # is one table. | |||||
| 1517 | sub _json_list_keys { | |||||
| 1518 | 49 | 43 | my ($text, $data) = @_; | |||
| 1519 | 49 | 67 | return () unless ref $data eq 'HASH'; | |||
| 1520 | my @lists = grep { | |||||
| 1521 | 89 | 44 | my $v = $data->{$_}; | |||
| 1522 | 89 58 46 | 76 56 29 | ref $v eq 'ARRAY' && !grep { ref $_ ne 'HASH' } @{$v} | |||
| 1523 | 26 26 | 23 28 | } @{ _json_key_order($text, 1) }; | |||
| 1524 | 26 45 45 | 20 21 33 | my @full = grep { @{ $data->{$_} } } @lists; | |||
| 1525 | 26 | 41 | return @full ? @full : @lists; | |||
| 1526 | } | |||||
| 1527 | ||||||
| 1528 | # _json_columns( $text, $rows, $depth, $list ) -> \@names | |||||
| 1529 | # | |||||
| 1530 | # Purpose: The columns of rows read from a JSON text, in the order the text | |||||
| 1531 | # first names them, then any it did not (sorted). | |||||
| 1532 | sub _json_columns { | |||||
| 1533 | 42 | 37 | my ($text, $rows, $depth, $list, $flatten) = @_; | |||
| 1534 | 42 42 | 30 33 | my @columns = @{ _json_key_order($text, $depth, $list, $flatten) }; | |||
| 1535 | 42 90 | 33 75 | my %named = map { $_ => 1 } @columns; | |||
| 1536 | 42 133 55 55 42 | 36 117 27 51 25 | push @columns, sort grep { !$named{$_}++ } map { keys %{$_} } @{$rows}; | |||
| 1537 | 42 | 71 | return \@columns; | |||
| 1538 | } | |||||
| 1539 | ||||||
| 1540 | # _json_table( $path, $want ) -> { rows, columns, list, lists } | |||||
| 1541 | # | |||||
| 1542 | # Purpose: Read a JSON file as a table, for D::A to read a flat copy of. | |||||
| 1543 | # Entry: $path is a readable .json file. $want, when defined, names the | |||||
| 1544 | # list to read (internal_table). | |||||
| 1545 | # Exit: rows: flat hashes. columns: in the order the file first names | |||||
| 1546 | # them. list: the key the rows were under (undef when none). | |||||
| 1547 | # lists: every list of objects in the file (empty when the file is | |||||
| 1548 | # not an object holding lists). A zero-byte or blank file is no rows. | |||||
| 1549 | # Croaks error_json_invalid, error_json_no_rows or | |||||
| 1550 | # error_json_list_not_found. | |||||
| 1551 | # Notes: Three shapes are tables: | |||||
| 1552 | # [ {row}, ... ] each object a row | |||||
| 1553 | # { "findings": [ {row}, ... ] } each list of objects under a key | |||||
| 1554 | # a table, the first the default; | |||||
| 1555 | # other values (a count, a date) | |||||
| 1556 | # are left out | |||||
| 1557 | # { "a1": {row}, "b2": {row} } each key a row, kept in a column | |||||
| 1558 | # "id" ("key" when "id" is taken) | |||||
| 1559 | # A cell holding an object or a list becomes its compact JSON text, | |||||
| 1560 | # true and false the words, null an empty cell. The column order is | |||||
| 1561 | # read from the text: a parsed object has no order. | |||||
| 1562 | sub _json_table { | |||||
| 1563 | 48 | 54 | my ($path, $want, $flatten) = @_; | |||
| 1564 | ||||||
| 1565 | # A big list of objects is read a row at a time (_json_stream), not as one | |||||
| 1566 | # string and one tree. Only that shape: the others need the whole document | |||||
| 1567 | # to find their lists. | |||||
| 1568 | 48 | 133 | if (!defined $want && (-s $path // 0) > $JSON_STREAM_BYTES && _json_starts_with($path, '[')) { | |||
| 1569 | 3 | 7 | return _json_stream($path, 'array', $flatten); | |||
| 1570 | } | |||||
| 1571 | ||||||
| 1572 | 45 | 131 | my ($text, $data) = _json_read($path); | |||
| 1573 | 43 | 49 | unless (length $text) { | |||
| 1574 | 2 | 3 | croak _fmt('error_json_list_not_found', $path, $want) if defined $want; | |||
| 1575 | 2 | 4 | return { rows => [], columns => [], list => undef, lists => [], count => 0 }; | |||
| 1576 | } | |||||
| 1577 | ||||||
| 1578 | 41 | 92 | my @lists = _json_list_keys($text, $data); | |||
| 1579 | 41 | 43 | if (defined $want) { | |||
| 1580 | croak _fmt('error_json_list_not_found', $path, $want) | |||||
| 1581 | 10 20 | 8 25 | unless grep { $_ eq $want } @lists; | |||
| 1582 | } | |||||
| 1583 | ||||||
| 1584 | 37 | 26 | my ($rows, $list, $key_col, $depth); | |||
| 1585 | 37 | 54 | if (ref $data eq 'ARRAY') { | |||
| 1586 | 19 28 19 | 14 31 16 | croak _fmt('error_json_no_rows', $path) if grep { ref $_ ne 'HASH' } @{$data}; | |||
| 1587 | 16 | 18 | ($rows, $depth) = ($data, 2); | |||
| 1588 | } elsif (@lists) { | |||||
| 1589 | 13 | 19 | $list = $want // $lists[0]; | |||
| 1590 | 13 | 11 | ($rows, $depth) = ($data->{$list}, 3); | |||
| 1591 | 4 7 4 | 5 6 3 | } elsif (ref $data eq 'HASH' && %{$data} && !grep { ref $_ ne 'HASH' } values %{$data}) { | |||
| 1592 | 3 | 3 | $depth = 2; | |||
| 1593 | 3 5 5 3 | 53 2 7 3 | my @inner = map { keys %{$_} } values %{$data}; | |||
| 1594 | 3 6 | 2 8 | $key_col = (grep { $_ eq 'id' } @inner) ? 'key' : 'id'; | |||
| 1595 | 3 6 | 1 6 | $key_col .= '_' while grep { $_ eq $key_col } @inner; | |||
| 1596 | 3 5 5 3 | 1 2 7 4 | $rows = [ map { { %{ $data->{$_} }, $key_col => $_ } } @{ _json_key_order($text, 1) } ]; | |||
| 1597 | } else { | |||||
| 1598 | 2 | 2 | croak _fmt('error_json_no_rows', $path); | |||
| 1599 | } | |||||
| 1600 | ||||||
| 1601 | 32 42 32 | 24 41 23 | my @flat = map { _json_cells($_, $flatten) } @{$rows}; | |||
| 1602 | 32 | 40 | my $columns = _json_columns($text, \@flat, $depth, $list, $flatten); | |||
| 1603 | 32 3 7 3 | 29 2 4 3 | @{$columns} = ($key_col, grep { $_ ne $key_col } @{$columns}) if defined $key_col; | |||
| 1604 | ||||||
| 1605 | 32 | 131 | return { rows => \@flat, columns => $columns, list => $list, lists => \@lists, count => scalar @flat }; | |||
| 1606 | } | |||||
| 1607 | ||||||
| 1608 | # _json_cells( $row, $flatten ) -> \%cells | |||||
| 1609 | # | |||||
| 1610 | # Purpose: One JSON object as one flat row of cells. | |||||
| 1611 | # Notes: A value that is an object or a list becomes its compact JSON text, | |||||
| 1612 | # true and false the words, null an empty cell. With $flatten an | |||||
| 1613 | # object is not text but a cell for each of its own values, named by | |||||
| 1614 | # the path to it (address.city); only a list is still text. A name | |||||
| 1615 | # that is taken (a key written "a.b" beside the object "a" holding | |||||
| 1616 | # "b") gets "_" added, so no cell is lost. | |||||
| 1617 | sub _json_cells { | |||||
| 1618 | 74084 | 30274 | my ($row, $flatten) = @_; | |||
| 1619 | 74084 | 25092 | my %cells; | |||
| 1620 | 74084 | 39647 | _json_cells_into(\%cells, $row, '', $flatten); | |||
| 1621 | 74084 | 32647 | return \%cells; | |||
| 1622 | } | |||||
| 1623 | ||||||
| 1624 | sub _json_cells_into { | |||||
| 1625 | 114109 | 49284 | my ($cells, $node, $prefix, $flatten) = @_; | |||
| 1626 | 114109 114109 | 39316 64378 | for my $k (sort keys %{$node}) { | |||
| 1627 | 228279 | 91340 | my $v = $node->{$k}; | |||
| 1628 | 228279 | 93407 | my $name = length $prefix ? "$prefix.$k" : $k; | |||
| 1629 | 228279 40027 | 142113 23327 | if ($flatten && ref $v eq 'HASH' && %{$v}) { | |||
| 1630 | 40025 | 21256 | _json_cells_into($cells, $v, $name, $flatten); | |||
| 1631 | 40025 | 16914 | next; | |||
| 1632 | } | |||||
| 1633 | 188254 | 114512 | if (blessed($v) && $v->isa('JSON::PP::Boolean')) { | |||
| 1634 | 16 | 234 | $v = $v ? 'true' : 'false'; | |||
| 1635 | } elsif (ref $v) { | |||||
| 1636 | 41 | 38 | $v = Mojo::JSON::to_json($v); | |||
| 1637 | } | |||||
| 1638 | 188254 | 83792 | $name .= '_' while exists $cells->{$name}; | |||
| 1639 | 188254 | 85391 | $cells->{$name} = $v; | |||
| 1640 | } | |||||
| 1641 | 114109 | 50180 | return; | |||
| 1642 | } | |||||
| 1643 | ||||||
| 1644 | # _json_starts_with( $path, $char ) -> bool | |||||
| 1645 | # | |||||
| 1646 | # Whether the first character of the file that is not white space (or a BOM) | |||||
| 1647 | # is $char. | |||||
| 1648 | sub _json_starts_with { | |||||
| 1649 | 3 | 15 | my ($path, $char) = @_; | |||
| 1650 | 3 | 16 | local ($@, $!); | |||
| 1651 | 3 | 9 | open my $fh, '<:raw', $path or return 0; | |||
| 1652 | 3 | 182 | read $fh, my $head, 4_096; | |||
| 1653 | 3 | 519 | close $fh; | |||
| 1654 | 3 | 68 | return 0 unless defined $head; | |||
| 1655 | 3 | 4 | $head =~ s/\A\xEF\xBB\xBF//; | |||
| 1656 | 3 | 40 | return $head =~ /\A\s*\Q$char\E/ ? 1 : 0; | |||
| 1657 | } | |||||
| 1658 | ||||||
| 1659 | # _jsonl_table( $path, $want, $flatten ) -> { rows|stream, columns, count, ... } | |||||
| 1660 | # | |||||
| 1661 | # Purpose: A JSON Lines file (one object a line) as a table. Read as a stream. | |||||
| 1662 | # Croaks: error_json_invalid (a line that is not JSON, with its number), | |||||
| 1663 | # error_json_no_rows (a line that is not an object), | |||||
| 1664 | # error_json_list_not_found ($want names a list: there are none). | |||||
| 1665 | sub _jsonl_table { | |||||
| 1666 | 16 | 18 | my ($path, $want, $flatten) = @_; | |||
| 1667 | 16 | 19 | croak _fmt('error_json_list_not_found', $path, $want) if defined $want; | |||
| 1668 | 16 | 22 | return _json_stream($path, 'lines', $flatten); | |||
| 1669 | } | |||||
| 1670 | ||||||
| 1671 | # _json_each_row( $path, $kind, $code ) -> $count | |||||
| 1672 | # | |||||
| 1673 | # Purpose: Call $code->($row_text, $row_hash) for each object in a file, one at | |||||
| 1674 | # a time, so memory holds one row and a chunk, not the file. | |||||
| 1675 | # Entry: $kind is 'lines' (JSON Lines: one object a line, blank lines | |||||
| 1676 | # skipped) or 'array' (a JSON list of objects). | |||||
| 1677 | sub _json_each_row { | |||||
| 1678 | 31 | 26 | my ($path, $kind, $code) = @_; | |||
| 1679 | 31 | 219 | local ($@, $!); | |||
| 1680 | 31 | 42 | require Mojo::JSON; | |||
| 1681 | 31 | 20 | my $count = 0; | |||
| 1682 | my $row = sub { | |||||
| 1683 | 74045 | 37851 | my ($text, $where) = @_; | |||
| 1684 | 74045 | 26943 | my $data; | |||
| 1685 | 74045 74045 74044 | 27386 37336 123760 | unless (eval { $data = Mojo::JSON::decode_json($text); 1 }) { | |||
| 1686 | 1 | 9 | (my $why = $@ // '') =~ s/\s+at \S+ line \d+\.?\s*\z//; | |||
| 1687 | 1 | 3 | croak _fmt('error_json_invalid', $path, "$where: $why"); | |||
| 1688 | } | |||||
| 1689 | 74044 | 39319 | croak _fmt('error_json_no_rows', $path) unless ref $data eq 'HASH'; | |||
| 1690 | 74042 | 26134 | $count++; | |||
| 1691 | 74042 | 30748 | $code->($text, $data); | |||
| 1692 | 31 | 44 | }; | |||
| 1693 | ||||||
| 1694 | 31 | 45 | open my $fh, '<:raw', $path; | |||
| 1695 | 31 | 1293 | if ($kind eq 'lines') { | |||
| 1696 | 27 | 14 | my $n = 0; | |||
| 1697 | 27 | 167 | while (defined(my $line = <$fh>)) { | |||
| 1698 | 61 | 31 | $n++; | |||
| 1699 | 61 | 52 | $line =~ s/\A\xEF\xBB\xBF// if $n == 1; | |||
| 1700 | 61 | 70 | next unless $line =~ /\S/; | |||
| 1701 | 45 | 39 | $row->($line, "line $n"); | |||
| 1702 | } | |||||
| 1703 | 24 | 25 | close $fh; | |||
| 1704 | 24 | 701 | return $count; | |||
| 1705 | } | |||||
| 1706 | ||||||
| 1707 | # A list of objects: cut each top-level element out of the text by counting | |||||
| 1708 | # brackets (strings skipped), and hand it on. A string or an element that | |||||
| 1709 | # runs past the end of a chunk is kept and scanned again with the next one. | |||||
| 1710 | 4 | 8 | my ($buf, $opened, $closed, $eof) = ('', 0, 0, 0); | |||
| 1711 | 4 | 4 | until ($eof) { | |||
| 1712 | 73 | 76 | my $more; | |||
| 1713 | 73 | 152 | my $got = read $fh, $more, $JSON_CHUNK_BYTES; | |||
| 1714 | 73 | 17474 | $eof = $got ? 0 : 1; | |||
| 1715 | 73 | 16139 | $buf .= $more if $got; | |||
| 1716 | 73 | 140 | $buf =~ s/\A\xEF\xBB\xBF// unless $opened; | |||
| 1717 | 73 | 91 | my ($depth, $from) = (0, undef); | |||
| 1718 | 73 | 107 | pos($buf) = 0; | |||
| 1719 | 73 | 1103 | while ($buf =~ /\G(?:("(?:[^"\\]|\\.)*")|([{}\[\]])|([^"{}\[\]]+))/gc) { | |||
| 1720 | 872340 | 2538950 | if (defined $2) { | |||
| 1721 | 228072 | 94097 | my $c = $2; | |||
| 1722 | 228072 | 99866 | if ($depth) { | |||
| 1723 | 154000 | 109762 | if ($c eq '{' || $c eq '[') { | |||
| 1724 | 40000 | 25991 | $depth++; | |||
| 1725 | } elsif (!--$depth) { | |||||
| 1726 | 74000 | 52594 | $row->(substr($buf, $from, pos($buf) - $from), 'item ' . ($count + 1)); | |||
| 1727 | 74000 | 61193 | $from = undef; | |||
| 1728 | } | |||||
| 1729 | } elsif (!$opened) { | |||||
| 1730 | 4 | 6 | croak _fmt('error_json_no_rows', $path) unless $c eq '['; | |||
| 1731 | 4 | 6 | $opened = 1; | |||
| 1732 | } elsif ($c eq '{') { | |||||
| 1733 | 74066 | 55137 | ($depth, $from) = (1, pos($buf) - 1); | |||
| 1734 | } elsif ($c eq ']') { | |||||
| 1735 | 2 | 2 | $closed = 1; | |||
| 1736 | 2 | 4 | last; | |||
| 1737 | } else { | |||||
| 1738 | 0 | 0 | croak _fmt('error_json_no_rows', $path); | |||
| 1739 | } | |||||
| 1740 | } elsif (defined $3 && !$depth && $3 =~ /[^\s,]/) { | |||||
| 1741 | 1 | 4 | croak _fmt('error_json_no_rows', $path); | |||
| 1742 | } | |||||
| 1743 | } | |||||
| 1744 | 72 | 75 | last if $closed; | |||
| 1745 | 70 | 179 | $buf = defined $from ? substr($buf, $from) : substr($buf, pos($buf) // 0); | |||
| 1746 | } | |||||
| 1747 | 3 | 7 | close $fh; | |||
| 1748 | 3 | 111 | croak _fmt('error_json_invalid', $path, 'the list is not closed') | |||
| 1749 | if $opened && !$closed; | |||||
| 1750 | 2 | 22 | return $count; | |||
| 1751 | } | |||||
| 1752 | ||||||
| 1753 | # _json_stream( $path, $kind, $flatten ) -> \%table | |||||
| 1754 | # | |||||
| 1755 | # Purpose: The table of a JSON Lines file, or of a big list of objects, without | |||||
| 1756 | # holding its rows: one pass finds the columns (in the order the text | |||||
| 1757 | # first names them) and the count, and the flat copy D::A reads is | |||||
| 1758 | # written by a second pass (the table's "emit"). | |||||
| 1759 | sub _json_stream { | |||||
| 1760 | 19 | 21 | my ($path, $kind, $flatten) = @_; | |||
| 1761 | 19 | 10 | my (@columns, %seen); | |||
| 1762 | my $count = _json_each_row($path, $kind, sub { | |||||
| 1763 | 54022 | 22817 | my ($text, $data) = @_; | |||
| 1764 | 54022 | 22850 | my $cells = _json_cells($data, $flatten); | |||
| 1765 | # The order of keys in the text is read only when this row has a name not | |||||
| 1766 | # seen yet: a parsed object has no order. | |||||
| 1767 | 54022 128079 54022 | 19010 69061 25108 | return unless grep { !$seen{$_} } keys %{$cells}; | |||
| 1768 | 23 23 23 | 19 26 25 | for my $name (@{ _json_key_order($text, 1, undef, $flatten) }, sort keys %{$cells}) { | |||
| 1769 | 165 | 209 | push @columns, $name if exists $cells->{$name} && !$seen{$name}++; | |||
| 1770 | } | |||||
| 1771 | 19 | 51 | }); | |||
| 1772 | my $emit = sub { | |||||
| 1773 | 12 | 12 | my ($fh) = @_; | |||
| 1774 | 12 12 | 7 26 | print {$fh} '['; | |||
| 1775 | 12 | 9 | my $first = 1; | |||
| 1776 | _json_each_row($path, $kind, sub { | |||||
| 1777 | 20020 20020 | 7052 10049 | print {$fh} ($first ? '' : ','), Mojo::JSON::encode_json(_json_cells($_[1], $flatten)); | |||
| 1778 | 20020 | 51503 | $first = 0; | |||
| 1779 | 12 | 24 | }); | |||
| 1780 | 12 12 | 14 11 | print {$fh} ']'; | |||
| 1781 | 12 | 6 | return; | |||
| 1782 | 14 | 52 | }; | |||
| 1783 | 14 | 45 | return { emit => $emit, columns => \@columns, list => undef, lists => [], count => $count }; | |||
| 1784 | } | |||||
| 1785 | ||||||
| 1786 | # _json_key_order( $text, $depth, $under ) -> \@keys | |||||
| 1787 | # | |||||
| 1788 | # Purpose: The keys of the objects $depth levels down in a JSON text, in the | |||||
| 1789 | # order they first appear (a parsed object keeps none). | |||||
| 1790 | # Entry: $text is valid JSON (the caller has parsed it). $depth counts the | |||||
| 1791 | # object itself: a row of a top-level list is 2, a row of a list under | |||||
| 1792 | # a key 3, a key of the top-level object 1. $under, when defined, | |||||
| 1793 | # keeps only what is under that top-level key. | |||||
| 1794 | # Exit: The keys, each once, decoded. | |||||
| 1795 | sub _json_key_order { | |||||
| 1796 | 94 | 76 | my ($text, $depth, $under, $flatten) = @_; | |||
| 1797 | 94 | 54 | my (@stack, @order, %seen, %parent, $top); | |||
| 1798 | 94 | 140 | while ($text =~ /\G\s*(?:("(?:[^"\\]|\\.)*")|([{}\[\]:,])|[^\s{}\[\]:,"]+)/gcs) { | |||
| 1799 | 3479 | 1819 | if (defined $1) { | |||
| 1800 | 1055 | 393 | my $frame = $stack[-1]; | |||
| 1801 | 1055 | 1096 | next unless $frame && $frame->{object} && $frame->{want_key}; | |||
| 1802 | 738 | 311 | $frame->{want_key} = 0; | |||
| 1803 | 738 | 500 | my $key = Mojo::JSON::decode_json("[$1]")->[0]; | |||
| 1804 | 738 | 813 | $frame->{key} = $key; | |||
| 1805 | 738 | 376 | $top = $key if @stack == 1; | |||
| 1806 | 738 44 | 428 33 | if ($flatten && @stack > $depth && !grep { !$_->{object} } @stack[ $depth - 1 .. $#stack ]) { | |||
| 1807 | # A key inside an object inside a row: its path is a column, and | |||||
| 1808 | # the object's own path is not (it is what holds these). | |||||
| 1809 | 20 | 21 | next if defined $under && !(defined $top && $top eq $under); | |||
| 1810 | 20 24 | 14 23 | my @path = ((map { $_->{key} } @stack[ $depth - 1 .. $#stack - 1 ]), $key); | |||
| 1811 | 20 | 20 | $parent{ join '.', @path[ 0 .. $#path - 1 ] } = 1; | |||
| 1812 | 20 | 11 | my $name = join '.', @path; | |||
| 1813 | 20 | 21 | push @order, $name unless $seen{$name}++; | |||
| 1814 | 20 | 19 | next; | |||
| 1815 | } | |||||
| 1816 | 718 | 482 | next unless @stack == $depth; | |||
| 1817 | 386 | 351 | next if defined $under && !(defined $top && $top eq $under); | |||
| 1818 | 301 | 316 | push @order, $key unless $seen{$key}++; | |||
| 1819 | } elsif (defined $2) { | |||||
| 1820 | 2141 | 862 | my $c = $2; | |||
| 1821 | 2141 | 2302 | if ($c eq '{') { | |||
| 1822 | 297 | 351 | push @stack, { object => 1, want_key => 1 }; | |||
| 1823 | } elsif ($c eq '[') { | |||||
| 1824 | 147 | 133 | push @stack, { object => 0 }; | |||
| 1825 | } elsif ($c eq '}' || $c eq ']') { | |||||
| 1826 | 444 | 348 | pop @stack; | |||
| 1827 | } elsif ($c eq ',' && @stack && $stack[-1]{object}) { | |||||
| 1828 | 442 | 375 | $stack[-1]{want_key} = 1; | |||
| 1829 | } | |||||
| 1830 | } | |||||
| 1831 | } | |||||
| 1832 | 94 56 | 69 42 | return [ grep { !$parent{$_} } @order ] if %parent; | |||
| 1833 | 83 | 108 | return \@order; | |||
| 1834 | } | |||||
| 1835 | ||||||
| 1836 | # _values_are_data_like( \@vals ) -> bool | |||||
| 1837 | # | |||||
| 1838 | # Return true when the values look like actual data (dates, numbers, free text) | |||||
| 1839 | # _sniff_data_ext( $path ) -> $ext | |||||
| 1840 | # | |||||
| 1841 | # Peek at the content of $path and return the standard file extension that best | |||||
| 1842 | # describes its format. Used when a remote file has a non-standard extension | |||||
| 1843 | # (e.g. ".log") and we need to rename it so that _detect_file_info and | |||||
| 1844 | # Database::Abstraction can discover it automatically. | |||||
| 1845 | # | |||||
| 1846 | # Detection order: | |||||
| 1847 | # 1. SQLite magic bytes ("SQLite format 3") -> 'db' | |||||
| 1848 | # 2. XML preamble ("<?xml" or "<" as first non-space character) -> 'xml' | |||||
| 1849 | # 2a. "[" or "{" as first non-space character -> 'json'; a "{" whose | |||||
| 1850 | # first lines are each one whole object -> 'jsonl' | |||||
| 1851 | # 3. First data line contains tabs -> 'tsv' | |||||
| 1852 | # 4. First data line contains pipes -> 'psv' | |||||
| 1853 | # 5. Fallback -> 'csv' | |||||
| 1854 | sub _sniff_data_ext { | |||||
| 1855 | 19 | 10567 | my $path = $_[0]; | |||
| 1856 | 19 | 32 | open(my $fh, '<:raw', $path) or return 'csv'; | |||
| 1857 | 19 | 551 | my $header = ''; | |||
| 1858 | 19 | 30 | read $fh, $header, 20; | |||
| 1859 | 19 | 330 | close $fh; | |||
| 1860 | 19 | 257 | return 'db' if $header =~ /\ASQLite format/; | |||
| 1861 | 17 | 23 | return 'xml' if $header =~ /\A\s*<\?xml/i; | |||
| 1862 | 15 | 22 | return 'xml' if $header =~ /\A\s*</; | |||
| 1863 | 13 | 19 | if ($header =~ /\A\s*\{/) { | |||
| 1864 | # One object a line, and another after it: JSON Lines, not one document. | |||||
| 1865 | 3 | 4 | open(my $jh, '<:raw', $path) or return 'json'; | |||
| 1866 | 3 6 9 | 47 6 17 | my @lines = grep { /\S/ } map { scalar <$jh> // () } 1 .. 3; | |||
| 1867 | 3 | 4 | close $jh; | |||
| 1868 | 3 5 | 38 10 | return 'jsonl' if @lines > 1 && !grep { !/\A\s*\{.*\}\s*\z/ } @lines; | |||
| 1869 | 2 | 5 | return 'json'; | |||
| 1870 | } | |||||
| 1871 | 10 | 14 | return 'json' if $header =~ /\A\s*\[/; | |||
| 1872 | 10 | 12 | open(my $lh, '<', $path) or return 'csv'; | |||
| 1873 | 10 | 248 | my $line = <$lh>; | |||
| 1874 | 10 | 12 | close $lh; | |||
| 1875 | 10 | 115 | return 'csv' unless defined $line; | |||
| 1876 | 9 | 16 | return 'tsv' if $line =~ /\t/; | |||
| 1877 | 6 | 12 | return 'psv' if $line =~ /\|/; | |||
| 1878 | 4 | 11 | return 'csv'; | |||
| 1879 | } | |||||
| 1880 | ||||||
| 1881 | # _values_are_data_like( \@vals ) -> bool | |||||
| 1882 | # | |||||
| 1883 | # Returns true when the values look like a row of real data (dates / numbers) | |||||
| 1884 | # rather than column headers. Used to detect header-less CSV files where the | |||||
| 1885 | # first line is a data row. At least one value must match a date or numeric | |||||
| 1886 | # pattern -- a row of plain hyphenated identifiers (e.g. "First-Name") is NOT | |||||
| 1887 | # considered data-like. | |||||
| 1888 | sub _values_are_data_like { | |||||
| 1889 | 71 | 8498 | my $vals = $_[0]; | |||
| 1890 | 71 71 | 58 79 | for my $v (@{$vals}) { | |||
| 1891 | 94 | 209 | return 1 if $v =~ /\A\d{4}-\d{2}-\d{2}\z/; # YYYY-MM-DD | |||
| 1892 | 58 | 62 | return 1 if $v =~ /\A\d{1,2}\/\d{1,2}\/\d{4}\z/; # M/D/YYYY or D/M/YYYY | |||
| 1893 | 54 | 74 | return 1 if $v =~ /\A[+\-]\d[\d,]*(?:\.\d+)?\z/; # signed numeric (e.g. -1,075.13) | |||
| 1894 | 48 | 60 | return 1 if $v =~ /\A\(\d[\d,]*(?:\.\d+)?\)\z/; # accounting negative (e.g. (75.13)) | |||
| 1895 | } | |||||
| 1896 | 21 | 34 | return 0; | |||
| 1897 | } | |||||
| 1898 | ||||||
| 1899 | # _unsafe_sort( @args ) -> (\%rest, $col, $dir, $limit, $offset) | () | |||||
| 1900 | # | |||||
| 1901 | # Purpose: Recognise a selectall_arrayref call that sorts on a column D::A will | |||||
| 1902 | # not sort on, such as "First Name". | |||||
| 1903 | # Entry: The call's arguments: a flat list or one hashref (Database::Join's | |||||
| 1904 | # spill path), or anything else, which is not ours to take apart. | |||||
| 1905 | # Exit: The remaining criteria, the column, ASC or DESC, and the page. Empty | |||||
| 1906 | # for every other call. | |||||
| 1907 | sub _unsafe_sort { | |||||
| 1908 | 2334 | 5016 | my @args = @_; | |||
| 1909 | 2334 122 | 6155 144 | my $opts = (@args == 1 && ref $args[0] eq 'HASH') ? { %{ $args[0] } } | |||
| 1910 | : (@args && @args % 2 == 0) ? { @args } | |||||
| 1911 | : undef; | |||||
| 1912 | 2334 | 5874 | return unless $opts && defined $opts->{sort_by}; | |||
| 1913 | my ($col, $dir) = ref $opts->{sort_by} eq 'ARRAY' | |||||
| 1914 | 33 23 | 61 30 | ? @{ $opts->{sort_by} }[0, 1] : ($opts->{sort_by}, undef); | |||
| 1915 | 33 | 89 | return unless defined $col && $col !~ $DA_SORTABLE_RE; | |||
| 1916 | 13 13 | 51 17 | my ($limit, $offset) = delete @{$opts}{qw(limit offset)}; | |||
| 1917 | 13 | 7 | delete $opts->{sort_by}; | |||
| 1918 | 13 | 58 | return ($opts, $col, uc($dir // 'ASC'), $limit, $offset); | |||
| 1919 | } | |||||
| 1920 | ||||||
| 1921 | # _sorted_page( \@rows, $col, $dir, $limit, $offset ) -> \@rows | |||||
| 1922 | # | |||||
| 1923 | # Purpose: Do what D::A would have done for an _unsafe_sort call: sort as | |||||
| 1924 | # strings, then take the page. | |||||
| 1925 | # Notes: exists, because SQL-backed rows are locked hashes and a read of a | |||||
| 1926 | # column they do not have would croak. An unknown column does not sort. | |||||
| 1927 | # A new array, because the rows may be D::A's own cached list. | |||||
| 1928 | sub _sorted_page { | |||||
| 1929 | 24 | 2886 | my ($rows, $col, $dir, $limit, $offset) = @_; | |||
| 1930 | 24 24 | 15 33 | my @page = @{ $rows // [] }; | |||
| 1931 | 24 | 43 | if (@page && exists $page[0]{$col}) { | |||
| 1932 | @page = $dir eq 'DESC' | |||||
| 1933 | 9 | 15 | ? sort { ($b->{$col} // '') cmp ($a->{$col} // '') } @page | |||
| 1934 | 17 29 | 33 39 | : sort { ($a->{$col} // '') cmp ($b->{$col} // '') } @page; | |||
| 1935 | } | |||||
| 1936 | 24 | 35 | splice @page, 0, $offset if $offset && $offset =~ /\A\d+\z/; | |||
| 1937 | 24 | 54 | splice @page, $limit if defined $limit && $limit =~ /\A\d+\z/ && $limit < @page; | |||
| 1938 | 24 | 41 | return \@page; | |||
| 1939 | } | |||||
| 1940 | ||||||
| 1941 | # _split_csv_line( $line, $sep ) -> @fields | |||||
| 1942 | # | |||||
| 1943 | # One line of a delimited file as its fields, so that a separator inside quotes | |||||
| 1944 | # does not end a field. A line that does not parse (a quoted field carrying on | |||||
| 1945 | # over the next line) is split on the separator instead: this is only used to | |||||
| 1946 | # look at the shape of a file. | |||||
| 1947 | sub _split_csv_line { | |||||
| 1948 | 2960 | 7215 | my ($line, $sep) = @_; | |||
| 1949 | 2960 | 26249 | require Text::CSV; | |||
| 1950 | 2960 | 397992 | my $csv = Text::CSV->new({ binary => 1, sep_char => $sep, allow_loose_quotes => 1 }); | |||
| 1951 | 2960 | 215279 | return $csv->fields if $csv && $csv->parse($line); | |||
| 1952 | 5 | 135 | return split /\Q$sep\E/, $line, -1; | |||
| 1953 | } | |||||
| 1954 | ||||||
| 1955 | # _synthesize_col_names( \@vals ) -> @names | |||||
| 1956 | # | |||||
| 1957 | # Infer a safe SQL identifier for each positional value by examining its | |||||
| 1958 | # content: ISO dates become "Date", numeric/currency values become "Amount", | |||||
| 1959 | # and free text becomes "Description". Duplicate types are disambiguated with | |||||
| 1960 | # a numeric suffix (Date, Date2, Date3, ...). | |||||
| 1961 | sub _synthesize_col_names { | |||||
| 1962 | 49 | 4419 | my $vals = $_[0]; | |||
| 1963 | 49 | 52 | my %type_count; | |||
| 1964 | my @names; | |||||
| 1965 | 49 49 | 35 55 | for my $v (@{$vals}) { | |||
| 1966 | 130 | 60 | my $type; | |||
| 1967 | 130 | 392 | if ($v =~ /\A\d{4}-\d{2}-\d{2}\z/ || $v =~ /\A\d{1,2}\/\d{1,2}\/\d{4}\z/) { | |||
| 1968 | 47 | 62 | $type = 'Date'; | |||
| 1969 | } elsif ($v =~ /\A[+\-]?\d[\d,]*(?:\.\d+)?\z/ || $v =~ /\A\(\d[\d,]*(?:\.\d+)?\)\z/) { | |||||
| 1970 | 45 | 41 | $type = 'Amount'; | |||
| 1971 | } else { | |||||
| 1972 | 38 | 30 | $type = 'Description'; | |||
| 1973 | } | |||||
| 1974 | 130 | 104 | $type_count{$type}++; | |||
| 1975 | 130 | 162 | push @names, $type_count{$type} == 1 ? $type : $type . $type_count{$type}; | |||
| 1976 | } | |||||
| 1977 | 49 | 78 | return @names; | |||
| 1978 | } | |||||
| 1979 | ||||||
| 1980 | # _copy_with_header( $self, \%headerless, \@names, $sep, $stem ) -> ($dir, $id, $size) | |||||
| 1981 | # | |||||
| 1982 | # Purpose: Give D::A a file it can read for one that has no header: a copy in a | |||||
| 1983 | # temporary directory, under the same name, starting with @names. | |||||
| 1984 | # Entry: \%headerless is _detect_file_info's { path, ext }. | |||||
| 1985 | # Exit: The temporary directory, the column to use as D::A's id and the | |||||
| 1986 | # copy's size. Croaks error_backend_init if the file does not parse. | |||||
| 1987 | # Notes: Rows are parsed, not copied as text, so each has one value per name: | |||||
| 1988 | # a short row is padded, and a long one's extra fields go back into the | |||||
| 1989 | # last value, so an unquoted comma in a description is not lost. | |||||
| 1990 | # D::A drops a row whose id is empty or starts with '#', so the id is | |||||
| 1991 | # the column with the fewest such values, and normally has none. | |||||
| 1992 | # The copy is read and written with the escape the file uses | |||||
| 1993 | # (_csv_escape_char), so D::A, which chooses the same way, reads the | |||||
| 1994 | # copy with it too. | |||||
| 1995 | sub _copy_with_header :Protected { | |||||
| 1996 | my ($self, $headerless, $names, $sep, $stem) = @_; | |||||
| 1997 | require File::Temp; | |||||
| 1998 | require Text::CSV; | |||||
| 1999 | ||||||
| 2000 | my $tmp = File::Temp->newdir(CLEANUP => 1); | |||||
| 2001 | my $copy = File::Spec->catfile("$tmp", "$stem.$headerless->{ext}"); | |||||
| 2002 | my $escape = _csv_escape_char($headerless->{path}); | |||||
| 2003 | my $in = Text::CSV->new({ binary => 1, sep_char => $sep, allow_loose_quotes => 1, escape_char => $escape }); | |||||
| 2004 | my $out = Text::CSV->new({ binary => 1, sep_char => $sep, eol => "\n", escape_char => $escape }); | |||||
| 2005 | ||||||
| 2006 | open my $ifh, '<:raw', $headerless->{path}; | |||||
| 2007 | open my $ofh, '>:raw', $copy; | |||||
| 2008 | $out->print($ofh, $names); | |||||
| 2009 | ||||||
| 2010 | my @unusable = (0) x @{$names}; | |||||
| 2011 | my $first = 1; | |||||
| 2012 | while (my $row = $in->getline($ifh)) { | |||||
| 2013 | # A byte-order mark: Text::CSV gives it back decoded (U+FEFF), and the | |||||
| 2014 | # rest of the row with it, or as its three bytes. | |||||
| 2015 | $row->[0] =~ s/\A(?:\x{FEFF}|\xEF\xBB\xBF)// if $first-- > 0 && defined $row->[0]; | |||||
| 2016 | next if @{$row} == 1 && $row->[0] !~ /\S/; # a blank line | |||||
| 2017 | if (@{$row} > @{$names}) { | |||||
| 2018 | my @extra = splice @{$row}, @{$names} - 1; | |||||
| 2019 | push @{$row}, join($sep, @extra); | |||||
| 2020 | } | |||||
| 2021 | push @{$row}, ('') x (@{$names} - @{$row}); | |||||
| 2022 | for (@{$row}) { s/\A\s+//; s/\s+\z// } | |||||
| 2023 | $out->print($ofh, $row); | |||||
| 2024 | for my $i (0 .. $#{$names}) { | |||||
| 2025 | $unusable[$i]++ if $row->[$i] !~ /\S/ || $row->[$i] =~ /\A#/; | |||||
| 2026 | } | |||||
| 2027 | } | |||||
| 2028 | # eof alone is no proof: it is also true after an unterminated quote. Code | |||||
| 2029 | # 2012 is the plain end of the file. | |||||
| 2030 | my ($code, $why) = $in->error_diag; | |||||
| 2031 | close $ifh; | |||||
| 2032 | close $ofh; | |||||
| 2033 | croak $self->_msg('error_backend_init', $stem, "cannot parse $headerless->{path}: $why") | |||||
| 2034 | if $code && $code != $CSV_EOF; | |||||
| 2035 | ||||||
| 2036 | my ($best) = sort { $unusable[$a] <=> $unusable[$b] || $a <=> $b } 0 .. $#{$names}; | |||||
| 2037 | return ($tmp, $names->[$best], -s $copy); | |||||
| 2038 | 188 188 188 | 353347 165 1549 | } | |||
| 2039 | ||||||
| 2040 | # _cache_key( $self ) -> $key | undef | |||||
| 2041 | # | |||||
| 2042 | # Purpose: Derive a stable cache key for this DataSource's full result set. | |||||
| 2043 | # URL tables use a fixed key (TTL handles invalidation). | |||||
| 2044 | # File tables encode the file's mtime in the key so a changed file | |||||
| 2045 | # naturally produces a miss -- the stale entry is orphaned and evicts | |||||
| 2046 | # passively when the CHI driver reclaims memory. | |||||
| 2047 | # Entry: $self->{_cache} must be defined (caller checks this before calling). | |||||
| 2048 | # Exit: Returns a non-empty string key, or undef when no key is derivable | |||||
| 2049 | # (no URL, no file path on disk). | |||||
| 2050 | sub _cache_key :Protected { | |||||
| 2051 | my $self = shift; | |||||
| 2052 | ||||||
| 2053 | if (defined $self->{_url}) { | |||||
| 2054 | my $idx = $self->{_html_table_index} // 0; | |||||
| 2055 | # Include the table index in the key: a different index on the same URL | |||||
| 2056 | # selects a different table from the page and must not share a cache entry. | |||||
| 2057 | return 'bi:url:' . $self->{_url} . ':' . $idx; | |||||
| 2058 | } | |||||
| 2059 | ||||||
| 2060 | if (defined $self->{_file_path} && -f $self->{_file_path}) { | |||||
| 2061 | my $mtime = (stat($self->{_file_path}))[9]; | |||||
| 2062 | return defined $mtime | |||||
| 2063 | ? 'bi:file:' . $self->{_file_path} . ':' . $mtime | |||||
| 2064 | # Another table or sheet of one file is other rows. | |||||
| 2065 | . (defined $self->{_internal_table} ? ':' . $self->{_internal_table} : '') | |||||
| 2066 | : undef; | |||||
| 2067 | } | |||||
| 2068 | ||||||
| 2069 | return undef; | |||||
| 2070 | 188 188 188 | 49349 184 746 | } | |||
| 2071 | ||||||
| 2072 | # _init_backend( $self ) -> void | |||||
| 2073 | # | |||||
| 2074 | # Strategy: Database::Abstraction is designed as a base class where the | |||||
| 2075 | # lowercased package name maps to the data file in the directory | |||||
| 2076 | # (e.g. "Database::BI::_DB::Sales" -> data/sales.csv or data/sales.db). | |||||
| 2077 | # We synthesise an ephemeral subclass at runtime so DataSource remains | |||||
| 2078 | # fully table-agnostic and callers never need to touch Database::Abstraction | |||||
| 2079 | # directly. In Phase 2, this method can be replaced with Database::Join | |||||
| 2080 | # instantiation without any change to the public API. | |||||
| 2081 | # | |||||
| 2082 | # no_entry => 1: a BI viewer wants every row; we do not need O(1) keyed | |||||
| 2083 | # lookups on a primary key. This stores data as an arrayref instead of a | |||||
| 2084 | # hashref, which the fast-track path in selectall_arrayref returns directly. | |||||
| 2085 | sub _init_backend :Protected { | |||||
| 2086 | my $self = shift; | |||||
| 2087 | my $table = $self->{_table}; # sanitized: used for pkg name and D::A table param | |||||
| 2088 | my $raw_table = $self->{_raw_table} // $table; # original: used for file lookup and dbname | |||||
| 2089 | my $dir = $self->{_directory}; | |||||
| 2090 | ||||||
| 2091 | # Remote file path (host is set): download via SFTP to a local temp directory, | |||||
| 2092 | # then proceed with normal local processing on the downloaded copy. | |||||
| 2093 | # Net::SFTP::Foreign is loaded lazily so non-remote usage has no extra deps. | |||||
| 2094 | if (defined $self->{_host}) { | |||||
| 2095 | eval { require Net::SFTP::Foreign } | |||||
| 2096 | or croak $self->_msg('error_backend_init', $table, | |||||
| 2097 | 'Net::SFTP::Foreign is not installed (required for remote file access)'); | |||||
| 2098 | require File::Temp; | |||||
| 2099 | # Split optional user@host into ($user, $host). | |||||
| 2100 | my ($user, $host) = $self->{_host} =~ /\A([^@]+)\@(.+)\z/ | |||||
| 2101 | ? ($1, $2) : (undef, $self->{_host}); | |||||
| 2102 | my $tmpdir = File::Temp->newdir(CLEANUP => 1); | |||||
| 2103 | my @remote_exts = qw(csv tsv psv xlsx xls sql sqlite sqlite3 db xml json jsonl ndjson); | |||||
| 2104 | # Try the caller-supplied extension first (e.g. .log), then fall back. | |||||
| 2105 | if (defined $self->{_file_ext}) { | |||||
| 2106 | my $hint = lc $self->{_file_ext}; | |||||
| 2107 | @remote_exts = ($hint, grep { $_ ne $hint } @remote_exts); | |||||
| 2108 | } | |||||
| 2109 | # One SFTP connection shared across all extension attempts. | |||||
| 2110 | my $sftp = eval { Net::SFTP::Foreign->new($host, | |||||
| 2111 | defined $user ? (user => $user) : (), | |||||
| 2112 | timeout => 10, | |||||
| 2113 | ) }; | |||||
| 2114 | croak $self->_msg('error_backend_init', $table, | |||||
| 2115 | "could not connect to $host via SFTP: " . ($@ || ($sftp ? $sftp->error : 'unknown'))) | |||||
| 2116 | unless defined $sftp && !$sftp->error; | |||||
| 2117 | my $fetched_ext; | |||||
| 2118 | for my $ext (@remote_exts) { | |||||
| 2119 | my $remote_path = "$dir/$raw_table.$ext"; | |||||
| 2120 | my $local_file = File::Spec->catfile("$tmpdir", "$raw_table.$ext"); | |||||
| 2121 | $sftp->get($remote_path, $local_file); | |||||
| 2122 | # Verify the file landed on disk; sftp->error may be set on ENOENT. | |||||
| 2123 | next if $sftp->error || !-f $local_file || !-s $local_file; | |||||
| 2124 | $fetched_ext = $ext; | |||||
| 2125 | last; | |||||
| 2126 | } | |||||
| 2127 | croak $self->_msg('error_backend_init', $table, | |||||
| 2128 | "could not fetch any supported file from $self->{_host}:$dir/$raw_table.*") | |||||
| 2129 | unless defined $fetched_ext; | |||||
| 2130 | $self->{_remote_tmpdir} = $tmpdir; # prevents cleanup until $self is destroyed | |||||
| 2131 | ||||||
| 2132 | # If the downloaded file has a non-standard extension (e.g. .log), rename | |||||
| 2133 | # it to one that _detect_file_info and D::A can discover automatically. | |||||
| 2134 | # We do this by sniffing the first bytes/line for format signatures. | |||||
| 2135 | my %KNOWN_EXT = map { $_ => 1 } | |||||
| 2136 | qw(csv tsv psv xlsx xls sql sqlite sqlite3 db xml json jsonl ndjson); | |||||
| 2137 | unless ($KNOWN_EXT{lc $fetched_ext}) { | |||||
| 2138 | my $orig_file = File::Spec->catfile("$tmpdir", "$raw_table.$fetched_ext"); | |||||
| 2139 | my $std_ext = _sniff_data_ext($orig_file); | |||||
| 2140 | if ($std_ext ne lc $fetched_ext) { | |||||
| 2141 | my $new_file = File::Spec->catfile("$tmpdir", "$raw_table.$std_ext"); | |||||
| 2142 | 188 188 188 | 61447 157 354 | { no autodie; rename $orig_file, $new_file } | |||
| 2143 | $fetched_ext = $std_ext; | |||||
| 2144 | } | |||||
| 2145 | } | |||||
| 2146 | ||||||
| 2147 | $dir = "$tmpdir"; # switch to local temp dir for all subsequent processing | |||||
| 2148 | } | |||||
| 2149 | ||||||
| 2150 | require Database::Abstraction; | |||||
| 2151 | ||||||
| 2152 | my $pkg = 'Database::BI::_DB::' . ucfirst($table); | |||||
| 2153 | { | |||||
| 2154 | 188 188 188 | 161018 142 38199 | no strict 'refs'; | |||
| 2155 | push @{"${pkg}::ISA"}, 'Database::Abstraction' | |||||
| 2156 | unless $pkg->isa('Database::Abstraction'); | |||||
| 2157 | } | |||||
| 2158 | ||||||
| 2159 | my $info = _detect_file_info($dir, $raw_table, $self->{_internal_table}, $self->{_json_flatten}); | |||||
| 2160 | ||||||
| 2161 | # Probe for the actual file on disk so _cache_key can compute its mtime. | |||||
| 2162 | # This runs before the early-return paths so even empty files get a path. | |||||
| 2163 | for my $e (qw(csv tsv psv sql sqlite sqlite3 xml db xlsx xls json jsonl ndjson)) { | |||||
| 2164 | my $p = File::Spec->catfile($dir, "$raw_table.$e"); | |||||
| 2165 | if (-f $p) { | |||||
| 2166 | $self->{_file_path} = File::Spec->rel2abs($p); | |||||
| 2167 | last; | |||||
| 2168 | } | |||||
| 2169 | } | |||||
| 2170 | ||||||
| 2171 | # A JSON file's lists of objects are its tables, as a SQLite file's are. | |||||
| 2172 | $self->{_sqlite_tables} = $info->{_json_lists} | |||||
| 2173 | if $info->{_json_lists} && @{ $info->{_json_lists} }; | |||||
| 2174 | ||||||
| 2175 | # BerkeleyDB file detected by magic bytes, but tie() failed (version | |||||
| 2176 | # incompatibility -- e.g. the file uses BDB format 9 but the installed | |||||
| 2177 | # libdb only supports an older format). Croak now so D::A never falls | |||||
| 2178 | # through to its CSV path and reads the entire binary file as text. | |||||
| 2179 | if ($info->{_unknown_binary_db}) { | |||||
| 2180 | croak $self->_msg('error_unsupported_db', $raw_table); | |||||
| 2181 | } | |||||
| 2182 | ||||||
| 2183 | # 0-byte file: skip D::A/DBI entirely. D::A on an empty file falls through | |||||
| 2184 | # to DBD::CSV, whose error handling corrupts DBI's Errstr SV and triggers an | |||||
| 2185 | # XS assertion failure at cleanup on DEBUGGING perls (DBI 1.651, perl 5.44). | |||||
| 2186 | if ($info->{_file_is_empty}) { | |||||
| 2187 | $self->{_columns} = []; | |||||
| 2188 | $self->{_id_col} = 'entry'; | |||||
| 2189 | $self->{_file_is_empty} = 1; | |||||
| 2190 | return; | |||||
| 2191 | } | |||||
| 2192 | ||||||
| 2193 | # Header-less CSV/PSV: D::A needs a header, so it reads a copy that has one. | |||||
| 2194 | # $self->{_file_path} stays the real file, whose mtime is what counts. | |||||
| 2195 | if (my $headerless = $info->{_headerless}) { | |||||
| 2196 | my ($tmp, $id, $size) = $self->_copy_with_header( | |||||
| 2197 | $headerless, $info->{columns}, $info->{sep_char}, $raw_table); | |||||
| 2198 | $self->{_headerless_tmpdir} = $tmp; # prevents cleanup until $self is destroyed | |||||
| 2199 | $info->{id} = $id; | |||||
| 2200 | $info->{file_size} = $size; | |||||
| 2201 | $dir = "$tmp"; | |||||
| 2202 | } | |||||
| 2203 | ||||||
| 2204 | # A byte-order mark: D::A reads a copy without it, or the first column's | |||||
| 2205 | # name would start with it and match nothing a reader types. | |||||
| 2206 | # $self->{_file_path} stays the real file, whose mtime is what counts. | |||||
| 2207 | if (my $bom = delete $info->{_bom}) { | |||||
| 2208 | require File::Temp; | |||||
| 2209 | my $tmp = File::Temp->newdir(CLEANUP => 1); | |||||
| 2210 | my $copy = File::Spec->catfile("$tmp", "$raw_table.$bom->{ext}"); | |||||
| 2211 | open my $ifh, '<:raw', $bom->{path}; | |||||
| 2212 | open my $ofh, '>:raw', $copy; | |||||
| 2213 | read $ifh, my $mark, 3; | |||||
| 2214 | while (read $ifh, my $chunk, 65_536) { print {$ofh} $chunk } | |||||
| 2215 | close $ifh; | |||||
| 2216 | close $ofh; | |||||
| 2217 | $self->{_bom_tmpdir} = $tmp; # prevents cleanup until $self is destroyed | |||||
| 2218 | $info->{file_size} = -s $copy; | |||||
| 2219 | $dir = "$tmp"; | |||||
| 2220 | } | |||||
| 2221 | ||||||
| 2222 | # JSON: D::A reads a flat copy, a list of rows, whatever shape the file | |||||
| 2223 | # had (see _json_table). $self->{_file_path} stays the real file. | |||||
| 2224 | if (my $json = delete $info->{_json}) { | |||||
| 2225 | require File::Temp; | |||||
| 2226 | require Mojo::JSON; | |||||
| 2227 | my $tmp = File::Temp->newdir(CLEANUP => 1); | |||||
| 2228 | my $copy = File::Spec->catfile("$tmp", "$raw_table.json"); | |||||
| 2229 | open my $ofh, '>:raw', $copy; | |||||
| 2230 | if ($json->{emit}) { | |||||
| 2231 | $json->{emit}->($ofh); | |||||
| 2232 | } else { | |||||
| 2233 | print {$ofh} Mojo::JSON::encode_json($json->{rows}); | |||||
| 2234 | } | |||||
| 2235 | close $ofh; | |||||
| 2236 | $self->{_json_tmpdir} = $tmp; # prevents cleanup until $self is destroyed | |||||
| 2237 | $self->{_json_list} = $json->{list}; | |||||
| 2238 | $dir = "$tmp"; | |||||
| 2239 | } | |||||
| 2240 | ||||||
| 2241 | # _detect_file_info returns undef for id when every column header contains | |||||
| 2242 | # characters that are not safe SQL identifiers (spaces, hyphens, etc.). | |||||
| 2243 | # Falling back to the D::A default ('entry') would silently return 0 rows | |||||
| 2244 | # since no 'entry' column exists. Croak with a human-readable message. | |||||
| 2245 | # This guard applies only to CSV/TSV/PSV/SQLite/XML: the header-less and XLSX | |||||
| 2246 | # paths always give an id. | |||||
| 2247 | croak $self->_msg('error_no_safe_id', $table) | |||||
| 2248 | if exists $info->{columns} && !defined $info->{id}; | |||||
| 2249 | my $id_col = $info->{id} // 'entry'; | |||||
| 2250 | $self->{_id_col} = $id_col; | |||||
| 2251 | $self->{_columns} = $info->{columns}; # undef for SQLite/XML | |||||
| 2252 | ||||||
| 2253 | # D::A validates dbname as a SQL identifier and rejects names that contain | |||||
| 2254 | # spaces or other characters that are illegal in SQL (e.g. "transactions for | |||||
| 2255 | # Nigel"). This check fires at query time (inside selectall_arrayref) for | |||||
| 2256 | # the DBI path used by XLSX, SQLite, and XML files -- after construction | |||||
| 2257 | # succeeds -- so the error surfaces as error_fetch_failed, not error_backend_init. | |||||
| 2258 | # | |||||
| 2259 | # Fix: when the original filename stem was sanitized (raw_table != table), | |||||
| 2260 | # create a temporary directory with a symlink that uses the safe name. | |||||
| 2261 | # D::A opens the symlink, sees a space-free dbname, and builds valid SQL. | |||||
| 2262 | # The temp-dir object is kept in $self so the symlink persists for the full | |||||
| 2263 | # lifetime of this DataSource instance and is cleaned up automatically when | |||||
| 2264 | # $self is destroyed. | |||||
| 2265 | my $dbname = $raw_table; | |||||
| 2266 | my $da_dir = $dir; | |||||
| 2267 | if ($raw_table ne $table) { | |||||
| 2268 | my $safe_ext; | |||||
| 2269 | for my $e (qw(xlsx xls db sql sqlite sqlite3 xml csv tsv psv json jsonl ndjson)) { | |||||
| 2270 | $safe_ext = $e, last | |||||
| 2271 | if -f File::Spec->catfile($dir, "$raw_table.$e"); | |||||
| 2272 | } | |||||
| 2273 | if (defined $safe_ext) { | |||||
| 2274 | require File::Temp; | |||||
| 2275 | my $tmp = File::Temp->newdir(CLEANUP => 1); | |||||
| 2276 | my $abs_src = File::Spec->rel2abs( | |||||
| 2277 | File::Spec->catfile($dir, "$raw_table.$safe_ext")); | |||||
| 2278 | my $link = File::Spec->catfile("$tmp", "$table.$safe_ext"); | |||||
| 2279 | { | |||||
| 2280 | 188 188 188 | 235 132 234 | no autodie; # symlink failure gives our message, not autodie's | |||
| 2281 | symlink($abs_src, $link) | |||||
| 2282 | or croak $self->_msg('error_backend_init', $table, | |||||
| 2283 | "cannot create safe-name symlink for '$raw_table.$safe_ext': $!"); | |||||
| 2284 | } | |||||
| 2285 | $self->{_tmpdir} = $tmp; # prevents cleanup until $self is destroyed | |||||
| 2286 | $dbname = $table; | |||||
| 2287 | $da_dir = "$tmp"; | |||||
| 2288 | } | |||||
| 2289 | } | |||||
| 2290 | ||||||
| 2291 | # SQLite: _detect_file_info probed sqlite_master and returned the internal | |||||
| 2292 | # table names. When $dbname (the filename stem or its safe alias) is not | |||||
| 2293 | # among those names, auto-select the first user table (or use the caller- | |||||
| 2294 | # supplied internal_table) and create a symlink from <target>.<ext> to the | |||||
| 2295 | # original file so D::A can issue SQL against the real table name. | |||||
| 2296 | # D::A uses 'dbname' to find the file and 'table' for the SELECT statement, | |||||
| 2297 | # so both must be set to the actual table name when a mismatch is corrected. | |||||
| 2298 | my $da_table = $table; # D::A 'table' param -- controls the SQL table name | |||||
| 2299 | # A workbook: D::A reads the worksheet named by 'table', and dbname alone | |||||
| 2300 | # finds the file, so the sheet chosen above is passed as the table. | |||||
| 2301 | $da_table = $info->{_sheet} if defined $info->{_sheet}; | |||||
| 2302 | if (exists $info->{sqlite_tables}) { | |||||
| 2303 | my @tbls = @{ $info->{sqlite_tables} }; | |||||
| 2304 | croak $self->_msg('error_no_tables', $raw_table) unless @tbls; | |||||
| 2305 | ||||||
| 2306 | # Store the full table list so callers (e.g. the tables_view action) | |||||
| 2307 | # can detect multi-table databases after construction. | |||||
| 2308 | $self->{_sqlite_tables} = \@tbls; | |||||
| 2309 | ||||||
| 2310 | # Determine target table: caller-specified or auto-detected. | |||||
| 2311 | my $desired = $self->{_internal_table}; | |||||
| 2312 | my $target; | |||||
| 2313 | if (defined $desired) { | |||||
| 2314 | my ($found) = grep { $_ eq $desired } @tbls; | |||||
| 2315 | croak $self->_msg('error_table_not_found', $raw_table, $desired) | |||||
| 2316 | unless defined $found; | |||||
| 2317 | if ($desired !~ $TABLE_NAME_RE) { | |||||
| 2318 | my @others = grep { $_ =~ $TABLE_NAME_RE } @tbls; | |||||
| 2319 | croak $self->_msg('error_table_name_unsafe', $desired, $raw_table, | |||||
| 2320 | (@others ? $self->_msg('error_table_name_others', join(', ', @others)) : ''), | |||||
| 2321 | $desired, _safe_table_name($desired)); | |||||
| 2322 | } | |||||
| 2323 | $target = $desired; | |||||
| 2324 | } else { | |||||
| 2325 | # D::A refuses a table name that is not a safe identifier, so the | |||||
| 2326 | # first table it can open is chosen, not simply the first table. | |||||
| 2327 | my @usable = grep { $_ =~ $TABLE_NAME_RE } @tbls; | |||||
| 2328 | croak $self->_msg('error_no_usable_tables', $raw_table, join(', ', @tbls), | |||||
| 2329 | $tbls[0], _safe_table_name($tbls[0])) unless @usable; | |||||
| 2330 | my ($match) = grep { $_ eq $dbname } @usable; | |||||
| 2331 | $target = defined $match ? $match : $usable[0]; | |||||
| 2332 | } | |||||
| 2333 | ||||||
| 2334 | # When the target differs from dbname, create a symlink so D::A can | |||||
| 2335 | # find the file by target name and issue SELECT * FROM <target>. | |||||
| 2336 | # Always use a D::A-recognised SQLite extension (.sql, .sqlite, .sqlite3) | |||||
| 2337 | # for the symlink name -- D::A does not use the DBI/SQLite backend for | |||||
| 2338 | # .db files, so a customer.db symlink would be read as CSV. For the same | |||||
| 2339 | # reason a SQLite .db file needs the symlink even when its table is named | |||||
| 2340 | # after the file: orders.db holding a table called orders. | |||||
| 2341 | my ($src_ext) = grep { -f File::Spec->catfile($dir, "$raw_table.$_") } | |||||
| 2342 | qw(sql sqlite sqlite3 db); | |||||
| 2343 | $src_ext //= 'sql'; | |||||
| 2344 | if ($target ne $dbname || $src_ext eq 'db') { | |||||
| 2345 | my $link_ext = ($src_ext eq 'db') ? 'sql' : $src_ext; | |||||
| 2346 | require File::Temp; | |||||
| 2347 | my $tmp = File::Temp->newdir(CLEANUP => 1); | |||||
| 2348 | my $abs_src = File::Spec->rel2abs( | |||||
| 2349 | File::Spec->catfile($dir, "$raw_table.$src_ext")); | |||||
| 2350 | my $link = File::Spec->catfile("$tmp", "$target.$link_ext"); | |||||
| 2351 | { | |||||
| 2352 | 188 188 188 | 173023 134 202 | no autodie; | |||
| 2353 | symlink($abs_src, $link) | |||||
| 2354 | or croak $self->_msg('error_backend_init', $raw_table, | |||||
| 2355 | "cannot create table-name symlink for '$raw_table.$src_ext': $!"); | |||||
| 2356 | } | |||||
| 2357 | $self->{_tmpdir} = $tmp; | |||||
| 2358 | $dbname = $target; # D::A uses this for the filename stem | |||||
| 2359 | $da_table = $target; # D::A uses this for SELECT * FROM <table> | |||||
| 2360 | $da_dir = "$tmp"; | |||||
| 2361 | } | |||||
| 2362 | } | |||||
| 2363 | ||||||
| 2364 | my $db = eval { | |||||
| 2365 | $pkg->new({ | |||||
| 2366 | directory => $da_dir, | |||||
| 2367 | table => $da_table, | |||||
| 2368 | # D::A >= 0.41 uses the class-name suffix as dbname, not the table | |||||
| 2369 | # parameter, so a package like Database::BI::_DB::Orders would look | |||||
| 2370 | # for Orders.csv on a case-sensitive filesystem even when table => | |||||
| 2371 | # 'orders' is passed. Passing dbname explicitly keeps the filename | |||||
| 2372 | # stem correct regardless of the package name or D::A version. | |||||
| 2373 | # When the table name was sanitized (spaces, hyphens -> underscores), | |||||
| 2374 | # $dbname is the safe name so D::A never sees illegal SQL characters, | |||||
| 2375 | # and D::A finds the file via the symlink in $da_dir. | |||||
| 2376 | dbname => $dbname, | |||||
| 2377 | id => $id_col, | |||||
| 2378 | no_entry => 1, | |||||
| 2379 | defined($info->{sep_char}) ? (sep_char => $info->{sep_char}) : (), | |||||
| 2380 | # Force the Text::xSV::Slurp path for CSV/TSV/PSV files: D::A's default | |||||
| 2381 | # slurp threshold is 16 KB; larger files fall back to DBD::CSV, which | |||||
| 2382 | # sanitizes column names (lowercases and replaces spaces with | |||||
| 2383 | # underscores). Passing the actual file size ensures the slurp path | |||||
| 2384 | # is always taken, so "Account Number" stays "Account Number" rather | |||||
| 2385 | # than becoming "account_number". | |||||
| 2386 | defined($info->{file_size}) ? (max_slurp_size => $info->{file_size}) : (), | |||||
| 2387 | }); | |||||
| 2388 | }; | |||||
| 2389 | if ($@) { | |||||
| 2390 | croak $self->_msg('error_backend_init', $table, $@); | |||||
| 2391 | } | |||||
| 2392 | ||||||
| 2393 | $self->{_db} = $db; | |||||
| 2394 | return; | |||||
| 2395 | 188 188 188 | 177772 952 1847 | } | |||
| 2396 | ||||||
| 2397 | # --------------------------------------------------------------------------- | |||||
| 2398 | # Public accessors | |||||
| 2399 | # --------------------------------------------------------------------------- | |||||
| 2400 | ||||||
| 2401 - 2421 | =head1 ACCESSORS =head2 table_name Returns the (lowercased) table name this instance was opened against. =head3 API SPECIFICATION =head4 INPUT None. =head4 OUTPUT Returns a C<SCALAR> string. =head3 MESSAGES None. =cut | |||||
| 2422 | ||||||
| 2423 | sub table_name { | |||||
| 2424 | 59 | 6194 | my $self = shift; | |||
| 2425 | 59 | 132 | return $self->{_table}; | |||
| 2426 | } | |||||
| 2427 | ||||||
| 2428 - 2468 | =head2 sqlite_tables
Returns an arrayref of internal table names when the backing file is a
SQLite database, or of the lists of objects in a JSON file that is an object
holding them (C<{"findings": [...], "hosts": [...]}>), or C<undef> for other
sources. Set during C<_init_backend>.
When the return value is a reference to a list with B<more than one
element>, the caller should redirect the user to the schema browser
(C</tables>) so they can pick which table to open, rather than
silently opening the first one.
Example:
my $tbls = $source->sqlite_tables;
if ($tbls && @{$tbls} > 1) {
# multiple tables -- let the user choose
print "Tables: ", join(', ', @{$tbls}), "\n";
}
=head3 API SPECIFICATION
=head4 INPUT
None.
=head4 OUTPUT
ARRAYREF of SCALAR # ['customer', 'product', 'sales'] for a 3-table SQLite file
ARRAYREF of SCALAR # ['findings', 'hosts'] for a JSON file holding two lists
undef # for CSV, TSV, PSV, XML, URL-backed, and a JSON list or keyed object
A SQLite file's names are in the order returned by C<sqlite_master>
(alphabetical), a JSON file's in the order the file gives them. It is set
once during construction and never changes.
=head3 MESSAGES
None.
=cut | |||||
| 2469 | ||||||
| 2470 | sub sqlite_tables { | |||||
| 2471 | 1140 | 5629 | my $self = shift; | |||
| 2472 | 1140 | 2815 | return $self->{_sqlite_tables}; | |||
| 2473 | } | |||||
| 2474 | ||||||
| 2475 - 2509 | =head2 split_path
my ($file, $table) = Database::BI::Model::DataSource::split_path('/data/scan.json#hosts');
# ('/data/scan.json', 'hosts')
What a C<path:> spec names: a file and, after a C<#>, one of its tables (a
SQLite file's table, or a JSON file's list). C<path:/data/store.db#sales> is
the C<sales> table of C<store.db>, as C<table:store/sales> is when the file is
in C<data_dir>. When the whole text names a file that exists, it is that
file, so a file whose name has a C<#> in it still opens; and a remote path
(C</../host/...>) is split the same way, since there is no file here to look
for.
=head3 API SPECIFICATION
=head4 INPUT
$path SCALAR what follows "path:" in a spec
=head4 OUTPUT
($file, $table) $table undef when none is named; ('', undef) for undef
=head3 MESSAGES
None.
=head3 FORMAL SPECIFICATION
split_path == lambda p .
if exists(p) then (p, undef)
else if p = f ++ "#" ++ t /\ t /= "" /\ "#" not in t then (f, t)
else (p, undef)
=cut | |||||
| 2510 | ||||||
| 2511 | sub split_path { | |||||
| 2512 | 4677 | 6742 | my ($path) = @_; | |||
| 2513 | 4677 | 3980 | return ('', undef) unless defined $path; | |||
| 2514 | # A NUL or a newline cannot be in a Windows file name, and stat on one warns | |||||
| 2515 | # there ("Invalid \0 character in pathname", "filename containing newline"). | |||||
| 2516 | 188 188 188 4676 4674 | 44443 178 119794 5310 13524 | return ($path, undef) if CORE::index($path, "\0") < 0 && do { no warnings 'newline'; -e $path }; | |||
| 2517 | 431 | 634 | return ($1, $2) if $path =~ /\A(.+)#([^#\n]+)\z/s; | |||
| 2518 | 395 | 412 | return ($path, undef); | |||
| 2519 | } | |||||
| 2520 | ||||||
| 2521 - 2564 | =head2 json_lists
my $lists = Database::BI::Model::DataSource->json_lists('/data/scan.json');
# [ { name => 'findings', columns => ['detail', 'host', ...] },
# { name => 'hosts', columns => ['base', 'host', ...] } ]
The tables of a JSON file that is an object holding lists of objects: one
entry per list, in the order the file gives them, with its columns in the
order the file first names them. The schema browser (C</tables>) shows a
card for each; C<< new(internal_table => $name) >> opens one.
A list holding anything but objects is not a table, and an empty list counts
only when no list has rows. Other values beside the lists (a count, a date,
an object of totals) are not tables.
=head3 API SPECIFICATION
=head4 INPUT
$class SCALAR the class (called as a class method)
$path SCALAR a readable .json file
=head4 OUTPUT
ARRAYREF of HASHREF { name => SCALAR, columns => ARRAYREF of SCALAR }
empty when the file holds no lists (a list of rows,
an object of rows, a blank file)
Croaks C<error_json_invalid> when the file is not JSON.
=head3 MESSAGES
C<error_json_invalid>.
=head3 FORMAL SPECIFICATION
json_lists == lambda path .
let (text, data) = parse(path) in
[ { name => k, columns => key_order(text, data.k) } | k <- list_keys(text, data) ]
pre readable(path)
post forall e in result . data.(e.name) : seq HASH
=cut | |||||
| 2565 | ||||||
| 2566 | sub json_lists { | |||||
| 2567 | 9 | 2284 | my ($class, $path) = @_; | |||
| 2568 | 9 | 18 | local ($@, $!); | |||
| 2569 | 9 | 11 | my ($text, $data) = _json_read($path); | |||
| 2570 | 8 | 13 | return [] unless length $text; | |||
| 2571 | return [ map { | |||||
| 2572 | 8 10 | 11 14 | { name => $_, columns => _json_columns($text, $data->{$_}, 3, $_) } | |||
| 2573 | } _json_list_keys($text, $data) ]; | |||||
| 2574 | } | |||||
| 2575 | ||||||
| 2576 - 2602 | =head2 xlsx_sheets
my $sheets = Database::BI::Model::DataSource->xlsx_sheets('/data/budget.xlsx');
# [ { name => 'Q1 Sales', columns => ['region', 'amount'] }, { name => 'Costs', ... } ]
The worksheets of a workbook, in the workbook's order, each with the first
cells of its header row, for the C</tables> picker -- the cards a SQLite file's
tables and a JSON file's lists have. C<< new(internal_table => $name) >> opens
one.
=head3 API SPECIFICATION
=head4 INPUT
$path : string, a .xlsx file
=head4 OUTPUT
An array reference of C<< { name => STRING, columns => ARRAYREF } >>; C<[]> when
the file cannot be read, has no sheets, or L<Spreadsheet::ParseXLSX> is not
installed. A blank sheet has no columns.
=head3 MESSAGES
None.
=cut | |||||
| 2603 | ||||||
| 2604 | sub xlsx_sheets { | |||||
| 2605 | 4 | 2597 | my ($class, $path) = @_; | |||
| 2606 | 4 | 15 | local ($@, $!); | |||
| 2607 | 4 | 60 | return [] unless defined $path && -r $path; | |||
| 2608 | 3 3 3 | 4 9 4 | return [] unless eval { require Spreadsheet::ParseXLSX; 1 }; | |||
| 2609 | 3 3 | 5 15 | my $wb = eval { Spreadsheet::ParseXLSX->new->parse($path) } or return []; | |||
| 2610 | 3 | 126547 | my @out; | |||
| 2611 | 3 | 13 | for my $ws ($wb->worksheets) { | |||
| 2612 | 8 | 28 | my @cols; | |||
| 2613 | 8 | 18 | my ($rmin, $rmax) = $ws->row_range; | |||
| 2614 | 8 | 31 | my ($cmin, $cmax) = $ws->col_range; | |||
| 2615 | 8 | 27 | if ($rmax >= $rmin) { | |||
| 2616 | 6 | 8 | for my $c ($cmin .. $cmax) { | |||
| 2617 | 10 | 12 | my $cell = $ws->get_cell($rmin, $c); | |||
| 2618 | 10 | 47 | my $name = defined $cell ? ($cell->value // '') : ''; | |||
| 2619 | 10 | 29 | push @cols, $name if $name =~ /[^\s"]/; | |||
| 2620 | 10 | 11 | last if @cols >= 3; | |||
| 2621 | } | |||||
| 2622 | } | |||||
| 2623 | 8 | 14 | push @out, { name => $ws->get_name, columns => \@cols }; | |||
| 2624 | } | |||||
| 2625 | 3 | 25 | return \@out; | |||
| 2626 | } | |||||
| 2627 | ||||||
| 2628 - 2689 | =head2 columns
Returns an arrayref of column names in file order, or C<undef> when no order
is available.
=over 4
=item CSV / TSV / PSV / XLSX
Column names come from the file header (first row). They are returned in
the order they appear in the file. For header-less files (detected
automatically) the synthesized names (C<Date>, C<Amount>, C<Description>,
etc.) are returned in the same synthesized order.
=item SQLite / XML
Falls back to the underlying C<Database::Abstraction> object's C<columns()>
method. This is useful when a C<DataSource> is passed directly to
C<Database::Join> as a component database.
=item URL-backed tables
Always returns C<undef>. C<Database::Abstraction> fetches URL data lazily,
so calling C<_db-E<gt>columns()> here would trigger a live network request even
when the data came from the CHI cache. The controller derives column order
from the data records instead (alphabetical fallback).
=item Redis-backed tables
Delegates to the underlying C<Database::Abstraction> C<columns()>, which
triggers a lazy open of the Redis connection on first call and returns the
column names derived from the first stored row (alphabetical order, includes
C<entry>). This is required so that C<Database::Join> can validate the
join column at construction time.
=back
Always check the return value before dereferencing:
my $cols = $source->columns;
if ($cols) {
print join(', ', @{$cols}), "\n";
} else {
# URL-backed tables: derive columns from the first data row
}
=head3 API SPECIFICATION
=head4 INPUT
None.
=head4 OUTPUT
ARRAYREF of SCALAR # ['id', 'name', 'price', ...] -- original header order
undef # SQLite, XML, URL-backed tables
=head3 MESSAGES
None.
=cut | |||||
| 2690 | ||||||
| 2691 | sub columns { | |||||
| 2692 | 3176 | 82699 | my $self = shift; | |||
| 2693 | 3176 | 10828 | local ($@, $!); # the backend opens lazily, and uses both on the way | |||
| 2694 | 3176 | 3884 | local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows | |||
| 2695 | 3176 | 7648 | return $self->{_columns} if defined $self->{_columns}; | |||
| 2696 | # A caller that knows the order (an extract, which records its file's) says | |||||
| 2697 | # so; a SQLite backend would otherwise list the columns alphabetically. | |||||
| 2698 | 223 14 14 | 551 30 32 | return [ @{ $self->{_column_order} } ] if $self->{_column_order} && @{ $self->{_column_order} }; | |||
| 2699 | # URL-backed tables have no canonical column order at construction time; | |||||
| 2700 | # calling _db->columns() would trigger a live HTTP request which may fail. | |||||
| 2701 | # Return undef so _get_columns derives column names from fetched data. | |||||
| 2702 | 209 | 373 | return undef if defined $self->{_url}; | |||
| 2703 | # Redis-backed tables: delegate to _db->columns() which triggers the lazy | |||||
| 2704 | # open() on first call. D::J requires a real column list at construction | |||||
| 2705 | # time so returning undef here would make join validation always fail. | |||||
| 2706 | # D::A builds its Redis column list from hgetall fields only and omits the | |||||
| 2707 | # entry key (the suffix of the Redis key pattern tablename:entryid). | |||||
| 2708 | # Prepend the id column so callers and D::J see a complete column list. | |||||
| 2709 | 189 | 308 | if (defined $self->{_redis_url} && $self->{_db}) { | |||
| 2710 | 1 | 3 | my $da_cols = $self->{_db}->columns() // []; | |||
| 2711 | 1 | 3 | my $id = $self->{_id_col} // 'entry'; | |||
| 2712 | 1 3 1 | 1 3 2 | my @full = ($id, grep { $_ ne $id } @{$da_cols}); | |||
| 2713 | 1 | 1 | $self->{_columns} = \@full; | |||
| 2714 | 1 | 3 | return $self->{_columns}; | |||
| 2715 | } | |||||
| 2716 | 188 | 581 | return $self->{_db} ? $self->{_db}->columns() : undef; | |||
| 2717 | } | |||||
| 2718 | ||||||
| 2719 - 2762 | =head2 dbi_source
Returns a hashref C<{ dbh =E<gt> $dbh, table =E<gt> $name }> for SQLite-backed
instances, and C<undef> for everything else.
C<Database::Join> 0.009.0 probes C<dbi_source> at join-construction time to
decide whether it can take the zero-copy C<ATTACH> path (avoiding a row-by-row
spill into a temporary SQLite file). Without this method, every C</join> on a
SQLite-backed C<DataSource> uses the spill path regardless of row count.
Returns C<undef> for:
=over 4
=item *
0-byte files (C<_file_is_empty> set).
=item *
Redis-backed and URL-backed sources (no DBI handle).
=item *
Any backend that does not itself implement C<dbi_source>.
=back
=head3 API SPECIFICATION
=head4 INPUT
None.
=head4 OUTPUT
{ dbh => $dbh_object, table => 'table_name' } # SQLite-backed
undef # all other backends
=head3 MESSAGES
None.
=cut | |||||
| 2763 | ||||||
| 2764 | sub dbi_source { | |||||
| 2765 | 815 | 126512 | my $self = shift; | |||
| 2766 | 815 | 1577 | return undef if $self->{_file_is_empty}; | |||
| 2767 | 806 | 1946 | return undef unless $self->{_db}; | |||
| 2768 | 805 | 1991 | return undef unless $self->{_db}->can('dbi_source'); | |||
| 2769 | 804 804 | 3317 1812 | my $result = eval { $self->{_db}->dbi_source() }; | |||
| 2770 | 804 | 2609787 | return undef if $@; | |||
| 2771 | 787 | 4089 | return $result; | |||
| 2772 | } | |||||
| 2773 | ||||||
| 2774 - 2806 | =head2 aggregate Delegates to the inner C<Database::Abstraction> backend's C<aggregate()> method (requires C<Database::Abstraction> E<gt>= 0.49). Returns C<[]> for in-memory backends (headerless CSV, XLSX, empty files) and for URL-backed sources where aggregation is not available. Accepts the same C<by>, C<measures>, C<having>, C<sort_by>, C<limit>, C<offset>, and WHERE-criteria parameters as C<Database::Abstraction::aggregate()>. =head3 API SPECIFICATION =head4 INPUT by arrayref Column names to GROUP BY. measures arrayref Measure descriptors (see Database::Abstraction::aggregate). having hashref Optional HAVING criteria. sort_by string Optional ORDER BY column. limit integer Optional result limit. offset integer Optional result offset. (any other key) WHERE column criteria passed through to D::A. =head4 OUTPUT arrayref of hashrefs -- one row per group. [] -- in-memory / empty / URL-backed sources. =head3 MESSAGES None. =cut | |||||
| 2807 | ||||||
| 2808 | sub aggregate { | |||||
| 2809 | 549 | 1911 | my ($self, @args) = @_; | |||
| 2810 | 549 | 3016 | local ($@, $!); # the backend opens lazily, and uses both on the way | |||
| 2811 | 549 | 828 | local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows | |||
| 2812 | 549 | 801 | return [] if $self->{_file_is_empty}; | |||
| 2813 | 548 | 820 | return [] unless $self->{_db}; | |||
| 2814 | 548 | 1445 | return [] unless $self->{_db}->can('aggregate'); | |||
| 2815 | 548 | 2661 | return $self->{_db}->aggregate(@args); | |||
| 2816 | } | |||||
| 2817 | ||||||
| 2818 - 2840 | =head2 pages_on_server Returns true when C<selectall_arrayref> with C<limit> and C<offset> runs on a database server without reading the whole table, as it does for MariaDB. C<dbi_source> cannot say this: it answers only for SQLite, because C<Database::Join> takes it to mean that a file can be attached. =head3 API SPECIFICATION =head4 INPUT None. =head4 OUTPUT SCALAR boolean =head3 MESSAGES None. =cut | |||||
| 2841 | ||||||
| 2842 | sub pages_on_server { | |||||
| 2843 | 610 | 8899 | my $self = shift; | |||
| 2844 | 610 | 1911 | return defined $self->{_mariadb} ? 1 : 0; | |||
| 2845 | } | |||||
| 2846 | ||||||
| 2847 - 2873 | =head2 mariadb_tables
Class method. Lists the tables and views of one MariaDB or MySQL database, with
their columns in the table's own order.
my $tables = Database::BI::Model::DataSource->mariadb_tables('shop', {
host => 'db.example.com', database => 'shop',
username => 'bi', password => 'secret',
});
=head3 API SPECIFICATION
=head4 INPUT
$server SCALAR string the name of the server, for messages
$settings HASHREF { database, host?, port?, username?, password? }
=head4 OUTPUT
ARRAYREF of { name => string, columns => [ string, ... ] }, sorted by name
=head3 MESSAGES
Croaks with C<error_mariadb_unknown_server>, C<error_mariadb_settings>,
C<error_mariadb_no_driver> or C<error_mariadb_connect>.
=cut | |||||
| 2874 | ||||||
| 2875 | sub mariadb_tables { | |||||
| 2876 | 5 | 3270 | my ($class, $server, $settings) = @_; | |||
| 2877 | 5 | 28 | local ($@, $!); | |||
| 2878 | 5 | 8 | local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows | |||
| 2879 | ||||||
| 2880 | 5 | 7 | my ($dsn, $username, $password) = _mariadb_dsn($server, $settings); | |||
| 2881 | 4 | 4 | my $tables = eval { | |||
| 2882 | 4 | 7 | Database::Join::Catalog->schema(dsn => $dsn, username => $username, password => $password); | |||
| 2883 | }; | |||||
| 2884 | 4 | 719 | croak _fmt('error_mariadb_connect', $server, "$@") unless $tables; | |||
| 2885 | 1 | 2 | return $tables; | |||
| 2886 | } | |||||
| 2887 | ||||||
| 2888 - 2917 | =head2 id_column Returns the name of the column used as the primary key and as C<Database::Abstraction>'s row-existence anchor. For file-backed tables this is the first column in the CSV/TSV/PSV header whose name is a valid SQL identifier (letters, digits, underscores only, not starting with a digit) B<and> whose value in the first data row is non-empty. C<DataSource> detects this automatically to avoid the C<Database::Abstraction> default of C<'entry'>, which would silently discard every row in a file that has no C<entry> column. Returns C<undef> for URL/HTML-table backends (no primary-key concept applies). =head3 API SPECIFICATION =head4 INPUT None. =head4 OUTPUT SCALAR string # e.g. 'id', 'date', 'sku' -- the first safe-identifier column undef # URL-backed (HTML table import) sources =head3 MESSAGES None. =cut | |||||
| 2918 | ||||||
| 2919 | sub id_column { | |||||
| 2920 | 17 | 463 | my $self = shift; | |||
| 2921 | 17 | 31 | return $self->{_id_col}; | |||
| 2922 | } | |||||
| 2923 | ||||||
| 2924 - 2948 | =head2 source_url Returns the source URL for URL/HTML-table-backed instances. Returns C<undef> for all file-backed instances (local files and SFTP-fetched remote files). Use this to distinguish a URL-backed C<DataSource> from a file-backed one when you need to decide whether to show a "re-fetch" button to the user. =head3 API SPECIFICATION =head4 INPUT None. =head4 OUTPUT SCALAR string # 'https://example.com/data.html' -- the original URL undef # file-backed (local or SFTP) sources =head3 MESSAGES None. =cut | |||||
| 2949 | ||||||
| 2950 | sub source_url { | |||||
| 2951 | 4 | 148 | my $self = shift; | |||
| 2952 | 4 | 10 | return $self->{_url}; | |||
| 2953 | } | |||||
| 2954 | ||||||
| 2955 - 2981 | =head2 updated Returns the Unix epoch timestamp (mtime) of the backing data file, or C<undef> for URL-backed tables and for sources whose file cannot be C<stat()>-ed. C<Database::Join> calls C<updated()> on each component database to detect whether its SQLite spill cache is stale. When a source file changes on disk, the mtime increases, the join detects the change, and re-runs the join rather than serving stale cached data. =head3 API SPECIFICATION =head4 INPUT None. =head4 OUTPUT SCALAR integer # Unix epoch seconds, e.g. 1728601234 undef # URL-backed tables, or file cannot be stat()-ed =head3 MESSAGES None. =cut | |||||
| 2982 | ||||||
| 2983 | sub updated { | |||||
| 2984 | 280 | 91475 | my $self = shift; | |||
| 2985 | # The file itself comes first. D::A only learns an mtime when it opens the file, | |||||
| 2986 | # which it does lazily, so before the first read it answers undef, and after it | |||||
| 2987 | # goes on answering the time of that read however the file has changed since. | |||||
| 2988 | 280 | 1855 | return (stat($self->{_file_path}))[9] if defined $self->{_file_path} && -f $self->{_file_path}; | |||
| 2989 | 5 | 12 | return $self->{_db}->updated() if $self->{_db} && $self->{_db}->can('updated'); | |||
| 2990 | 3 | 5 | return undef; | |||
| 2991 | } | |||||
| 2992 | ||||||
| 2993 - 3022 | =head2 schema
Delegates to the inner C<Database::Abstraction> backend's C<schema()> method.
The join routes compare the declared types of columns that appear in more than
one joined table, and the panel keeps no schema of its own. Without this
delegation a DataSource was schema-less, so every comparison found nothing and
a TEXT/INTEGER mismatch across a join went unreported; the controller's
C<_schema_type_warnings> uses this method to fill the schema-warnings banner.
Returns a hashref of C<< column => { type => ..., nullable => ..., ... } >>.
File formats that C<Database::Abstraction> reads as text (CSV, TSV, PSV, XML,
XLSX) report C<TEXT>; SQLite reports the declared column types. Returns an
empty hashref when the inner backend cannot provide a schema.
=head3 API SPECIFICATION
=head4 INPUT
None.
=head4 OUTPUT
HASHREF column name => schema metadata hashref (possibly empty)
=head3 MESSAGES
None.
=cut | |||||
| 3023 | ||||||
| 3024 | sub schema { | |||||
| 3025 | 155 | 2976 | my $self = shift; | |||
| 3026 | 155 | 446 | local ($@, $!); # the backend opens lazily, and uses both on the way | |||
| 3027 | 155 | 176 | local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows | |||
| 3028 | ||||||
| 3029 | 155 | 589 | return {} unless $self->{_db} && $self->{_db}->can('schema'); | |||
| 3030 | ||||||
| 3031 | 152 152 | 613 224 | my $schema = eval { $self->{_db}->schema() }; | |||
| 3032 | 152 | 155739 | return {} if $@ || ref($schema) ne 'HASH'; | |||
| 3033 | ||||||
| 3034 | 147 | 350 | return $schema; | |||
| 3035 | } | |||||
| 3036 | ||||||
| 3037 | # --------------------------------------------------------------------------- | |||||
| 3038 | # Public data-access methods | |||||
| 3039 | # --------------------------------------------------------------------------- | |||||
| 3040 | ||||||
| 3041 - 3096 | =head1 METHODS =head2 fetch_all Returns every record in the table as an arrayref of hashrefs (one hashref per row; keys are the column names). This is the primary data-retrieval method. It is equivalent to calling C<selectall_arrayref> with no arguments and normalising the result to an arrayref. Prefer C<selectall_arrayref> when passing to C<Database::Join> (it is the method that C<Database::Join> calls internally). Filtering (C<eq>, C<contains>, C<gt>, C<lt>, etc.) is applied at the controller layer by C<Dashboard::_apply_filter_spec> after C<fetch_all> returns. C<DataSource> itself is filter-unaware. Three fast-path shortcuts are checked before touching the DBI backend, in this order: =over 4 =item 1. C<_file_is_empty> is set (0-byte or blank-first-line file) -- returns C<[]> immediately, no DBI connection. =item 2. A matching CHI cache entry exists -- returns the cached arrayref without calling C<Database::Abstraction>. =back =head3 API SPECIFICATION =head4 INPUT None. Filtering is applied at the controller layer, not inside C<DataSource>. =head4 OUTPUT ARRAYREF of HASHREF # one hashref per row; keys are column names [] # empty arrayref when the file is empty or has no data rows Croaks (via C<croak>) when the backend raises an exception. Emits a warning via C<carp> (non-fatal) when the result set is empty, so the caller can distinguish "opened successfully, no data" from a silent failure. =head3 MESSAGES error_fetch_failed -- backend threw an exception during retrieval warn_empty_result -- query succeeded but returned zero records warn_data_normalised -- backend returned a hashref; converted to arrayref =cut | |||||
| 3097 | ||||||
| 3098 - 3152 | =head2 selectall_arrayref C<Database::Abstraction>-compatible alias that allows a C<DataSource> object to be passed directly to C<Database::Join> as a component database. When called with no arguments (the normal path for a full-table scan), results are served from the CHI cache when available. When called with arguments (e.g. C<limit =E<gt> N, offset =E<gt> M> for server-side pagination), the cache is bypassed -- narrowed results must not pollute the full-table cache entry. Three fast-path shortcuts are checked before touching the DBI backend: =over 4 =item 1. C<_file_is_empty> is set -- returns C<[]> immediately. =item 2. The call sorts on a column whose name is not a safe identifier, such as C<First Name>. L<Database::Abstraction> ignores such a column, so this method fetches the rows and sorts and pages them itself, comparing as strings as L<Database::Abstraction> does. =item 3. A matching CHI cache entry exists for the full-table scan -- returns the cached arrayref. =back =head3 API SPECIFICATION =head4 INPUT Optional flat key/value list passed through to C<Database::Abstraction>: limit => N # return at most N rows (used by pagination) offset => M # skip the first M rows (used by pagination) When no arguments are given, the full table is returned (and cached). =head4 OUTPUT ARRAYREF of HASHREF # one hashref per row; keys are column names [] # empty arrayref when the file is empty or no rows match =head3 MESSAGES None. Errors from the DBI backend propagate as uncaught exceptions; wrap calls in C<eval> if you need to recover. =cut | |||||
| 3153 | ||||||
| 3154 | sub selectall_arrayref { | |||||
| 3155 | 2337 | 19942 | my ($self, @args) = @_; | |||
| 3156 | 2337 | 12634 | local ($@, $!); # the backend opens lazily, and uses both on the way | |||
| 3157 | 2337 | 3684 | local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows | |||
| 3158 | 2337 | 3801 | return [] if $self->{_file_is_empty}; | |||
| 3159 | ||||||
| 3160 | # A server gives LIMIT rows in no promised order, so pages could overlap. | |||||
| 3161 | 2320 | 4356 | if (defined $self->{_order_col} && @args && !ref $args[0]) { | |||
| 3162 | 0 | 0 | my %asked = @args; | |||
| 3163 | push @args, sort_by => [ $self->{_order_col}, 'asc' ] | |||||
| 3164 | 0 | 0 | if exists $asked{limit} && !$asked{sort_by}; | |||
| 3165 | } | |||||
| 3166 | ||||||
| 3167 | # D::A ignores a sort column whose name is not a safe identifier. | |||||
| 3168 | 2320 | 4979 | if (my ($rest, @page) = _unsafe_sort(@args)) { | |||
| 3169 | 8 8 | 6 12 | return _sorted_page($self->selectall_arrayref(%{$rest}), @page); | |||
| 3170 | } | |||||
| 3171 | ||||||
| 3172 | # Cache only plain unfiltered calls -- Database::Join passes no args for the | |||||
| 3173 | # full table scan; a non-empty @args means a narrowed query whose result must | |||||
| 3174 | # not be mistaken for the full-table cache entry. | |||||
| 3175 | 2312 | 2189 | my $cache = $self->{_cache}; | |||
| 3176 | 2312 | 4620 | if ($cache && !@args) { | |||
| 3177 | 2125 | 4864 | my $key = $self->_cache_key; | |||
| 3178 | 2125 | 2882 | if (defined $key) { | |||
| 3179 | 2108 | 7007 | my $hit = $cache->get($key); | |||
| 3180 | 2108 | 226956 | return $hit if defined $hit; | |||
| 3181 | } | |||||
| 3182 | } | |||||
| 3183 | ||||||
| 3184 | 564 | 2090 | my $data = $self->{_db}->selectall_arrayref(@args); | |||
| 3185 | ||||||
| 3186 | # As in fetch_all: what a URL answers with need not be a table. | |||||
| 3187 | croak $self->_msg('error_fetch_failed', $self->{_table}, $self->_msg('error_rows_not_records')) | |||||
| 3188 | 538 8 4 | 1324547 15 6 | if defined $self->{_url} && ref $data eq 'ARRAY' && grep { ref $_ ne 'HASH' } @{$data}; | |||
| 3189 | ||||||
| 3190 | 535 | 2009 | if ($cache && !@args && defined $data) { | |||
| 3191 | 345 | 658 | my $key = $self->_cache_key; | |||
| 3192 | 345 | 624 | if (defined $key) { | |||
| 3193 | defined $self->{_url} | |||||
| 3194 | ? $cache->set($key, $data, $self->{_cache_ttl_url}) | |||||
| 3195 | 344 | 1632 | : $cache->set($key, $data); | |||
| 3196 | } | |||||
| 3197 | } | |||||
| 3198 | ||||||
| 3199 | 535 | 64579 | return $data; | |||
| 3200 | } | |||||
| 3201 | ||||||
| 3202 | sub fetch_all { | |||||
| 3203 | 686 | 25012 | my $self = shift; | |||
| 3204 | 686 | 2619 | local ($@, $!); # the backend opens lazily, and uses both on the way | |||
| 3205 | 686 | 922 | local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows | |||
| 3206 | 686 | 668 | my $table = $self->{_table}; | |||
| 3207 | ||||||
| 3208 | # 0-byte file: no backend was created; nothing to fetch. | |||||
| 3209 | 685 | 969 | return [] if $self->{_file_is_empty}; | |||
| 3210 | ||||||
| 3211 | # Cache check: URL tables benefit from avoiding repeated HTTP round-trips; | |||||
| 3212 | # file tables benefit from skipping disk I/O and CSV/TSV/PSV parsing. | |||||
| 3213 | 664 | 551 | my $cache = $self->{_cache}; | |||
| 3214 | 664 | 844 | if ($cache) { | |||
| 3215 | 309 | 642 | my $key = $self->_cache_key; | |||
| 3216 | 309 | 476 | if (defined $key) { | |||
| 3217 | 307 | 1018 | my $hit = $cache->get($key); | |||
| 3218 | 307 | 18313 | return $hit if defined $hit; | |||
| 3219 | } | |||||
| 3220 | } | |||||
| 3221 | ||||||
| 3222 | 558 558 | 398 1444 | my $data = eval { $self->{_db}->selectall_hashref() }; | |||
| 3223 | 558 | 2839907 | if ($@) { | |||
| 3224 | 39 | 166 | croak $self->_msg('error_fetch_failed', $table, $@); | |||
| 3225 | } | |||||
| 3226 | ||||||
| 3227 | 519 | 685 | return [] unless defined $data; | |||
| 3228 | ||||||
| 3229 | # Strategy: Database::Abstraction can return either an arrayref (when the | |||||
| 3230 | # underlying driver iterates rows) or a hashref keyed by primary key (when | |||||
| 3231 | # it mirrors DBI's selectall_hashref semantics). We normalise to arrayref | |||||
| 3232 | # here so every caller above this layer sees a uniform structure. | |||||
| 3233 | 513 | 723 | if (ref $data eq 'HASH') { | |||
| 3234 | 6 | 13 | carp $self->_msg('warn_data_normalised', $table); | |||
| 3235 | 6 6 | 547 8 | $data = [ values %{$data} ]; | |||
| 3236 | } | |||||
| 3237 | ||||||
| 3238 | 513 513 | 344 647 | if (!@{$data}) { | |||
| 3239 | 6 | 11 | carp $self->_msg('warn_empty_result', $table); | |||
| 3240 | } | |||||
| 3241 | ||||||
| 3242 | # A JSON URL may answer with an array of anything; every layer above reads | |||||
| 3243 | # each row as a hash, and would die on the first scalar. | |||||
| 3244 | croak $self->_msg('error_fetch_failed', $table, $self->_msg('error_rows_not_records')) | |||||
| 3245 | 513 21 11 | 1268 51 13 | if defined $self->{_url} && grep { ref $_ ne 'HASH' } @{$data}; | |||
| 3246 | ||||||
| 3247 | # Cache store: URL tables use a TTL so stale pages expire automatically; | |||||
| 3248 | # file tables encode mtime in the key so a changed file produces a natural | |||||
| 3249 | # miss without any explicit invalidation. | |||||
| 3250 | 508 | 560 | if ($cache) { | |||
| 3251 | 175 | 282 | my $key = $self->_cache_key; | |||
| 3252 | 175 | 225 | if (defined $key) { | |||
| 3253 | defined $self->{_url} | |||||
| 3254 | ? $cache->set($key, $data, $self->{_cache_ttl_url}) | |||||
| 3255 | 174 | 521 | : $cache->set($key, $data); | |||
| 3256 | } | |||||
| 3257 | } | |||||
| 3258 | ||||||
| 3259 | 508 | 23636 | return $data; | |||
| 3260 | } | |||||
| 3261 | ||||||
| 3262 - 3291 | =head2 count Returns the total number of rows in the table. For empty-file sentinels it returns C<0> immediately. For all DBI-backed sources (SQLite, large CSV via DBD::CSV) it delegates to C<Database::Abstraction::count()>, which issues a C<SELECT COUNT(*) FROM E<lt>tableE<gt>> query against the file. The count of a file's table is remembered for the life of the process, keyed by the file, the table, and the file's modification time and size, so asking again costs nothing until the file changes. A URL or MariaDB source is counted on every call. The first count of a very large SQLite file still reads the whole table. =head3 API SPECIFICATION =head4 INPUT None. =head4 OUTPUT SCALAR non-negative integer # total row count, 0 for empty files =head3 MESSAGES None. =cut | |||||
| 3292 | ||||||
| 3293 | sub count { | |||||
| 3294 | 96 | 5602 | my ($self) = @_; | |||
| 3295 | 96 | 395 | local ($@, $!); # the backend opens lazily, and uses both on the way | |||
| 3296 | 96 | 159 | local $/ = "\n"; # a caller's slurp mode (undef $/) read the file as one line: 0 rows | |||
| 3297 | 96 | 145 | return 0 if $self->{_file_is_empty}; | |||
| 3298 | ||||||
| 3299 | 87 | 148 | my $key = $self->_count_key; | |||
| 3300 | 87 | 240 | return $COUNT_MEMO{$key} if defined $key && exists $COUNT_MEMO{$key}; | |||
| 3301 | ||||||
| 3302 | 46 | 170 | my $n = $self->{_db}->count(); | |||
| 3303 | 46 | 6824 | if (defined $key) { | |||
| 3304 | 45 | 106 | %COUNT_MEMO = () if keys(%COUNT_MEMO) >= $COUNT_MEMO_MAX; | |||
| 3305 | 45 | 143 | $COUNT_MEMO{$key} = $n; | |||
| 3306 | } | |||||
| 3307 | 46 | 79 | return $n; | |||
| 3308 | } | |||||
| 3309 | ||||||
| 3310 | # _count_key( $self ) -> $key | undef | |||||
| 3311 | # | |||||
| 3312 | # What count() remembers its answer under: the file, the table in it, and the | |||||
| 3313 | # file's mtime and size, so a changed file is counted again. undef (count every | |||||
| 3314 | # time) for a URL or a database server, which have no file to stat. | |||||
| 3315 | sub _count_key { | |||||
| 3316 | 87 | 72 | my $self = shift; | |||
| 3317 | 87 | 223 | return undef if defined $self->{_url} || defined $self->{_mariadb}; | |||
| 3318 | 87 | 85 | my $file = $self->{_file_path}; | |||
| 3319 | 87 | 162 | return undef unless defined $file; | |||
| 3320 | 86 | 231 | my @st = stat $file; | |||
| 3321 | 86 | 111 | return undef unless @st; | |||
| 3322 | 86 | 334 | return join "\0", $file, $self->{_table} // '', $self->{_internal_table} // '', $st[9], $st[7]; | |||
| 3323 | } | |||||
| 3324 | ||||||
| 3325 | 1; | |||||
| 3326 | ||||||