Database-BI

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

	  resolved code has no template directory, as documented.
	[ New Features ]
	- GET /map: ?size=<col> draws bubble markers scaled 6-30 px.
	- GET /map: ?series=<col>&scheme=<name> colours markers by category with
	  a legend.  Mutually exclusive with ?color=.
	[ Documentation ]
	- Complete /map parameter reference; HTML::OSM 0.12 floor;
	  Nominatim search always suppressed.
	- "Command-line tools" section covering all three scripts.
	- Canvas, analyses API, sharing/embedding, catalog, insights, ask,
	  summary and geo endpoints (previously README-only).
	[ Tests ]
	- t/launcher.t: asserts perl shebang on every shipped script.
	- t/map.t and t/integration.t: drive both renderer states via the
	  controller's _map_renderer_version probe.
	- t/edge_cases.t: covers uploads_dir resolution (absolute, relative, unset).
	- t/map.t: covers the canvas in both renderer states.
	- Every test file now gives the app its own model_dir temp directory.
	- t/browser-canvas-map-degraded.t: browser test for the degraded map card.
	- Map-rendering assertions in t/map.t, t/integration.t and t/unit.t now
	  require HTML::OSM 0.12 (not merely installed).

Changes  view on Meta::CPAN

      button to drop a single condition without clearing all filters.
    [ Bug Fixes ]
    - Opening the line graph panel after the pie chart panel (or vice versa)
      now correctly hides the previously open panel.  The graph panel's
      otherPanels list was missing 'pie-panel'.

0.006.0	Tue Sep 15 08:03:20 PM EDT 2026
    [ Enhancements ]
    - Added a 'home' link on the table display page
    - XLSX files are now supported directly via DBD::Excel (each worksheet
      is a separate table).  The upload endpoint, filesystem browser, and
      drag-and-drop drop zone all accept .xlsx files.  DBD::Excel added to
      TEST_REQUIRES.
    - "Combine data" now allows a file to be drag and dropped
    - Multi-table left joins are now delegated to Database::Join (>= 0.003.0)
      instead of the bespoke _left_join helper.  Column collision handling
      (prefixing right-table columns with "label.col" when a name clashes) is
      provided by Database::Join's new collision_prefix parameter.
      DataSource now exposes selectall_arrayref() and an improved columns()
      fallback so that DataSource objects can be passed directly to
      Database::Join as component databases.

Changes  view on Meta::CPAN


    [ Bug Fixes ]
    - When attempting to drag and drop a file larger than MAX_UPLOAD_BYTES,
      a better error message is displayed which stays on the screen for
      3 seconds
    - CSV and PSV files whose first line is blank (e.g. a file containing only
      a single newline character) are now treated as empty files rather than
      croaking "no column with a safe identifier name".  _detect_file_info now
      returns the _file_is_empty sentinel when the parsed first line yields
      zero column names, causing _init_backend to skip Database::Abstraction
      entirely and fetch_all to return [].  The /open endpoint renders the
      standard empty-table view ("No records found") instead of an error page.
      Tests added to t/edge_cases.t.
    - Files whose names contain spaces (e.g. "transactions for Nigel.xlsx")
      now open correctly.  Database::Abstraction validates its dbname argument
      as a SQL identifier and rejected names with spaces with an "unsafe dbname"
      error at fetch time.  DataSource::_init_backend now creates a temporary
      directory with a symlink using the sanitized name whenever the raw
      filename stem contains illegal SQL characters, so D::A sees only the
      safe name.  Regression test added as Transaction 27.
    - The "Line graph..." toolbar button was silently broken: clicking it did

lib/Database/BI/Calc.pm  view on Meta::CPAN

	},
	second => sub {
		my $t = _parse_time($_[0]);
		return undef unless $t && $t->{has_time};
		(Database::BI::Util::local_wall($t->{epoch}))[0] + 0;
	},

	# --- grouping / binning ---
	bin => sub {
		# bin(value, width) -> '[lo,hi)' label for the interval containing value.
		# Width must be a positive number.  Both endpoints use %d when width is
		# an integer, %g otherwise, to avoid spurious ".0" suffixes.
		my ($v, $w) = @_;
		return undef unless defined $v && defined $w;
		return undef unless looks_like_number($v) && looks_like_number($w) && $w > 0;
		# Normalise the quotient to 10 significant digits before flooring: binary
		# representation error (0.3 / 0.1 == 2.9999999999999996) must not move a
		# value one bin to the left.  %.10g is magnitude-independent.
		my $n   = POSIX::floor(sprintf('%.10g', $v / $w) + 0);
		my $lo  = $n * $w;
		my $hi  = $lo + $w;

lib/Database/BI/Controller/Dashboard.pm  view on Meta::CPAN

# The operators an f= filter may name (_apply_filter_spec), as written: an
# operator in capitals is refused with the rest, not read as another one.
# differ (the Delta button) is the one whose value is another column's name:
# f=a:differ:b keeps the rows where a and b do not hold identical text.
Readonly my @FILTER_OPS => qw(eq ne contains starts lt le gt ge empty notempty between in differ);
Readonly my %FILTER_OP  => map { $_ => 1 } @FILTER_OPS;

# How many column names a refusal lists before it says how many more there are.
Readonly my $FILTER_COLUMNS_LISTED => 20;

# Allowed strptime-style date format patterns for the /dates/save endpoint, and
# the two time patterns that may be given beside one of them for a column that
# holds a clock time as well as a date.
Readonly my %ALLOWED_DATE_PATTERNS => map { $_ => 1 }
	qw(%m/%d/%Y %d/%m/%Y %d-%b-%Y);
Readonly my %ALLOWED_TIME_PATTERNS => map { $_ => 1 }
	qw(%H:%M %H:%M:%S);

# Default share token lifetime: 30 days in seconds.
Readonly my $SHARE_TOKEN_TTL => 30 * 86_400;

lib/Database/BI/Controller/Dashboard.pm  view on Meta::CPAN

does not have is a 400 (C<error_extract_col_unknown>).  A row that does not
match is C<(unparseable)> in every column; a group that took no part is C<''>.
The pattern is compiled by L<Database::BI::Calc/Regular expressions>, which
has no timeout.

=cut

=head1 DESCRIPTION

All user-facing routes in C<Database::BI> are handled by this controller.
See the individual action POD above for per-endpoint documentation.

=head2 Filter operators and the quick-filter bar

Filters are expressed as C<f=col:op:val> query parameters and are applied
server-side after all joins.  Multiple C<f=> params are applied in order
(AND semantics).

The colon separator is split with a limit of 3, so values may themselves
contain colons (e.g. C<f=sale_date:eq:2025-01-15>, or a time value like
C<f=start_time:eq:14:30:00>).

t/ask.t  view on Meta::CPAN

		columns   => [{ name => 'region', type => 'string' }],
		ai_config => { api_key => 'k' },
	);
	is($r->{valid}, 1, 'URL build: valid');
	# path:/my data/file.csv -> l=path%3A%2Fmy%20data%2Ffile.csv
	like($r->{url}, qr{l=path%3A}, 'URL build: colon percent-encoded in l=');
	like($r->{url}, qr{%20},       'URL build: space percent-encoded');
}

# ---------------------------------------------------------------------------
# Section 5: HTTP endpoint tests (no ai_api_key configured -> 503)
# ---------------------------------------------------------------------------

{
	# Without ai_api_key the app returns 503
	$t->post_ok('/api/ask', form => { l => 'table:sales', q => 'test' })
	  ->status_is(503)
	  ->json_like('/error', qr/not available/i);
}

# ---------------------------------------------------------------------------
# Section 6: HTTP -- missing parameter guards
# ---------------------------------------------------------------------------

{
	# Set a fake ai_api_key so the endpoint proceeds past the 503 guard
	my $saved = $t->app->config->{ai_api_key};
	$t->app->config->{ai_api_key} = 'fake-test-key';

	$t->post_ok('/api/ask', form => { q => 'test question' })
	  ->status_is(400)
	  ->json_like('/error', qr/l/i, 'missing l= -> 400');

	$t->post_ok('/api/ask', form => { l => 'table:sales' })
	  ->status_is(400)
	  ->json_like('/error', qr/question/i, 'missing q= -> 400');

t/cgi_security.t  view on Meta::CPAN

subtest '/import -- http://127.0.0.1/ is rejected (SSRF loopback)' => sub {
	# Exploit mechanism: bare loopback IPv4 bypasses hostname-based blocklists.
	# Proof: $host =~ /\A127\./ check in _is_safe_url() catches all of 127/8.
	$t->get_ok('/import?url=' . url_escape('http://127.0.0.1/'))
	  ->status_is(200)
	  ->content_like(qr/private or reserved/i,
	     '127.0.0.1 is rejected as a loopback address');
};

subtest '/import -- http://169.254.169.254/ is rejected (SSRF cloud metadata)' => sub {
	# Exploit mechanism: AWS/GCP/Azure metadata endpoint returns IAM credentials
	# and instance metadata; no authentication is required from the instance.
	# Proof: 169.254/16 is in the link-local block checked by _is_safe_url().
	$t->get_ok('/import?url=' . url_escape('http://169.254.169.254/latest/meta-data/'))
	  ->status_is(200)
	  ->content_like(qr/private or reserved/i,
	     '169.254.169.254 (cloud metadata) is rejected');
};

# ---------------------------------------------------------------------------
# Attack vector 6: Join left-spec injection

t/cgi_security.t  view on Meta::CPAN

	# Proof: /\b([a-z]{2})\b/ extracts at most 2 chars; "<script>" has no
	# two-letter match in a word-boundary context => $lang is undef => $default.
	$t->get_ok('/', {
		'Accept-Language' => '<script>alert(1)</script>'
	})->status_is(200)
	  ->content_unlike(qr/<script>alert\(1\)<\/script>/,
	     'XSS in Accept-Language is not reflected');
};

# ---------------------------------------------------------------------------
# Attack vector 11: API endpoint parameter hardening
# ---------------------------------------------------------------------------

subtest 'GET /api/stat -- null byte path returns exists:false, not a crash' => sub {
	# Exploit mechanism: "/tmp/file.csv\x00../../etc" -- C-library realpath(3)
	# truncates at null; Perl 5.12+ eval catches the exception or the truncated
	# path is non-existent.  Either way, defined $file is false => {exists:false}.
	# Proof: response is HTTP 200 (no crash) with JSON exists:false.
	my $null = "/tmp/file.csv\x00../../etc";
	$t->get_ok('/api/stat?path=' . url_escape($null))
	  ->status_is(200)

t/edge_cases.t  view on Meta::CPAN

	};

	$t->get_ok('/open?path=' . url_escape($path->to_string))
	  ->status_is(200)
	  ->content_like(qr/Could not open/i, 'error_file_open message in error page');

	restore_all();
};

# ---------------------------------------------------------------------------
# Section 10: SSRF via GET /import endpoint -- HTTP-level verification
#
# For blocked IPs the controller short-circuits before any LWP call, so
# these are fast and deterministic (no network required).
# ---------------------------------------------------------------------------

subtest 'GET /import -- private IP in URL triggers SSRF error response' => sub {
	for my $ip ('127.0.0.1', '10.0.0.1', '192.168.1.1', '172.16.0.1', '169.254.169.254', '100.64.0.0') {
		$t->get_ok("/import?url=" . url_escape("http://$ip/"))
		  ->status_is(200)
		  ->content_like(qr/private or reserved address/i,

t/edge_cases.t  view on Meta::CPAN

	my $dir = tempdir(CLEANUP => 1);
	Mojo::File->new("$dir/newlinepsv.psv")->spew("\n");
	my $src;
	lives_ok {
		$src = Database::BI::Model::DataSource->new(directory => $dir, table => 'newlinepsv');
	} 'newline-only PSV: constructor succeeds (no croak)';
	my $rows = $src->fetch_all;
	is_deeply $rows, [], 'newline-only PSV: fetch_all returns []';
};

# 0-byte CSV via HTTP /open endpoint
subtest 'HTTP -- 0-byte CSV via /open: 200 with empty-table message' => sub {
	my $dir  = tempdir(CLEANUP => 1);
	my $path = "$dir/emptyhttp.csv";
	Mojo::File->new($path)->spew('');
	$t->get_ok('/open?path=' . url_escape($path))
	  ->status_is(200, '0-byte CSV: /open returns 200')
	  ->content_like(qr/No records found/i, '0-byte CSV: empty-state message present');
};

# 0-byte PSV via HTTP /open endpoint
subtest 'HTTP -- 0-byte PSV via /open: 200 with empty-table message' => sub {
	my $dir  = tempdir(CLEANUP => 1);
	my $path = "$dir/emptyhttppsv.psv";
	Mojo::File->new($path)->spew('');
	$t->get_ok('/open?path=' . url_escape($path))
	  ->status_is(200, '0-byte PSV: /open returns 200')
	  ->content_like(qr/No records found/i, '0-byte PSV: empty-state message present');
};

# Newline-only CSV via HTTP /open endpoint
subtest 'HTTP -- newline-only CSV via /open: 200 with empty-table message' => sub {
	# Regression guard: before the _file_is_empty fix, a blank first line caused
	# _init_backend to croak "no safe identifier", and the controller rendered a
	# 200 error page — but the error message was confusing for what is simply an
	# empty file.  After the fix, the response is a clean empty-table view.
	my $dir  = tempdir(CLEANUP => 1);
	my $path = "$dir/nlcsv.csv";
	Mojo::File->new($path)->spew("\n");
	$t->get_ok('/open?path=' . url_escape($path))
	  ->status_is(200, 'newline-only CSV: /open returns 200')
	  ->content_like(qr/No records found/i, 'newline-only CSV: empty-state message present');
};

# Newline-only PSV via HTTP /open endpoint
subtest 'HTTP -- newline-only PSV via /open: 200 with empty-table message' => sub {
	my $dir  = tempdir(CLEANUP => 1);
	my $path = "$dir/nlpsv.psv";
	Mojo::File->new($path)->spew("\n");
	$t->get_ok('/open?path=' . url_escape($path))
	  ->status_is(200, 'newline-only PSV: /open returns 200')
	  ->content_like(qr/No records found/i, 'newline-only PSV: empty-state message present');
};

# ---------------------------------------------------------------------------

t/function.t  view on Meta::CPAN

	ok !$fn->('http://10.255.255.255/'),      '10.255.255.255 blocked (10/8 boundary)';
	ok !$fn->('http://172.16.0.1/'),          '172.16.0.1 blocked (172.16/12)';
	ok !$fn->('http://172.31.255.255/'),      '172.31.255.255 blocked (172.16/12 boundary)';
	ok !$fn->('http://192.168.0.1/'),         '192.168.0.1 blocked (192.168/16)';
	ok !$fn->('http://192.168.255.255/'),     '192.168.255.255 blocked (192.168/16 boundary)';
};

subtest '_is_safe_url -- link-local and CGNAT ranges are blocked' => sub {
	my $fn = \&Database::BI::Controller::Dashboard::_is_safe_url;

	ok !$fn->('http://169.254.169.254/'),     'AWS metadata endpoint blocked (169.254/16)';
	ok !$fn->('http://169.254.0.1/'),         '169.254.0.1 blocked (link-local)';
	ok !$fn->('http://100.64.0.1/'),          '100.64.0.1 blocked (CGNAT 100.64/10)';
	ok !$fn->('http://100.127.255.255/'),     '100.127.255.255 blocked (CGNAT boundary)';
};

subtest '_is_safe_url -- public addresses are allowed' => sub {
	my $fn = \&Database::BI::Controller::Dashboard::_is_safe_url;

	ok $fn->('http://8.8.8.8/'),              '8.8.8.8 (Google DNS) allowed';
	ok $fn->('http://1.1.1.1/'),              '1.1.1.1 (Cloudflare) allowed';

t/function.t  view on Meta::CPAN

	# that would prevent garbage collection.
	my $c = Database::BI::Calc->new(
		expr    => 'if(amount > 0, round(amount * 1.1, 2), 0)',
		columns => ['amount'],
	);
	ok !$c->has_error, 'expression compiles for memory-cycle check';
	memory_cycle_ok($c, 'no reference cycles in compiled Calc object');
};

# ============================================================================
# PART 4: new chart-view endpoints (scatter / stacked / combo / treemap / histogram)
# ============================================================================
# All tests use the $t Test::Mojo instance and data/sales.csv (6 rows:
# product, region, amount, date) as the data source.  Only the error-path
# tests and basic smoke tests are included here; full pipeline tests live in
# t/integration.t.  The primary goal is 60%+ negative coverage.

{
	use Mojo::Util qw(url_escape);
	Readonly my $SALES_SPEC => url_escape('table:sales');

t/function.t  view on Meta::CPAN

		$t->get_ok("/histogram?l=$SALES_SPEC&col=amount&bins=5")
		  ->status_is(200)
		  ->content_like(qr/<svg/i,
			'valid histogram request renders an SVG element');
	}
};

} # end url_escape scope

# ============================================================================
# PART 5: calc / groups / dates CRUD endpoints
# ============================================================================
# Isolate the model store in a fresh tempdir so these tests never touch
# .bi/models.json in the working directory.

{
	my $MODEL_DIR = tempdir(CLEANUP => 1);
	$t->app->config->{model_dir} = $MODEL_DIR;

	Readonly my $TEST_SPEC => 'table:sales';

t/insights.t  view on Meta::CPAN

	my $insights = Database::BI::Insights::compute(
		records  => \@rows,
		columns  => [qw(sale_date amount)],
		spec_key => 'table:few_periods',
	);
	my @season = grep { $_->{kind} eq 'seasonality' } @$insights;
	is(scalar(@season), 0, 'no seasonality insight with fewer than 8 periods');
}

# ---------------------------------------------------------------------------
# Section 4: HTTP endpoint tests (GET /insights)
# ---------------------------------------------------------------------------

{
	my $enc = url_escape("path:$FIXTURE");

	# Basic smoke: 200, page renders, no crash.
	$t->get_ok("/insights?l=path:${\url_escape($FIXTURE)}")
	  ->status_is(200)
	  ->content_like(qr/Automatic insights/i, 'page title present')
	  ->content_like(qr/insight-card/, 'at least one insight card rendered');

t/integration.t  view on Meta::CPAN

# Focus: cross-module, multi-step workflows where Database::BI (routing/config),
# Database::BI::Controller::Dashboard (HTTP actions), and
# Database::BI::Model::DataSource (data access) all interact.
#
# Sections 60 onward hold the workflows that cross every layer, independent
# objects in one process, every combination of the optional modules, permissions
# revoked under a running app, and upstreams that fail.
#
# What is NOT here (covered by dedicated suites):
#   - Individual filter operators             -> t/filter.t
#   - Single-endpoint status codes            -> t/unit.t
#   - Internal helpers (white-box)            -> t/function.t
#   - Security / hostile inputs               -> t/cgi_security.t
# ---------------------------------------------------------------------------

use Test::Most;
use Test::Mojo;
use Test::Without::Module;
use Test::Mockingbird qw(mock_scoped spy restore_all);
use Test::Permissions qw(can_revoke_create can_revoke_search with_revoked);
use Test::Returns;

t/model.t  view on Meta::CPAN

		'and none of it dies');
};

# ---------------------------------------------------------------------------
# A card is never filtered by its own cross-filter
#
# A click on a card marks it as the filter's source (?cv=), and every other
# card is narrowed by what was clicked (?cf=).  The source is not narrowed: it
# stays whole, which is what makes the click readable -- you see the thing you
# clicked, beside everything it changed.  Two places draw a card -- the page's
# loop, and the endpoint that adds or repairs one -- so both are read here, and
# so is the context both share: the specs are handed out unapplied, because a
# context that applied them could not know which card, if any, is the source.
# ---------------------------------------------------------------------------

subtest '3.3: a card is never filtered by its own cross-filter' => sub {
	plan skip_all => 'the controller source is not in this checkout'
		unless -f $src->{file};

	# -- the page's loop ---------------------------------------------------
	my $canvas = _sub_code($src, 'canvas_render');

t/model.t  view on Meta::CPAN

	}
	else {
		fail('the renderer call has an argument list to read');
	}

	# The page still has to know which card made the filter: that is how the
	# source is drawn as the source rather than as a card that failed to narrow.
	is scalar @{	_lines_like($canvas, qr/cf_source\s*=>\s*\(\$i == \$cf_source \? 1 : 0\)/) },
		1, 'the card that made the filter is marked as its source, once';

	# -- the endpoint that draws one card ----------------------------------
	my $patch = _sub_code($src, 'analyses_update_visual');
	ok($patch, 'the endpoint that draws a single card is there to read');

	my $patch_applied =	_lines_like($patch, qr/_canvas_cross_filter\(/);
	is scalar @$patch_applied, 1, 'it narrows a card in one place too';
	my ($guard_at) = grep {$patch->[$_] =~ /\$ctx->\{cf_source\}\s*!=\s*\$index\b/}
		0 .. $#$patch;
	ok(defined $guard_at, 'and asks whether the card it is drawing is the source');
	if (@$patch_applied && defined $guard_at) {
		is(_guard_of($patch, $patch_applied->[0]), $patch->[$guard_at],
			'narrowing it only on the branch where it is not');

t/model.t  view on Meta::CPAN

		# card nothing had narrowed.
		my ($indent) = $patch->[$guard_at] =~ /\A(\s*)/;
		my ($block_end) = grep { $_ > $guard_at && $patch->[$_] =~ /\A\Q$indent\E\}/ }
			0 .. $#$patch;
		my ($flag_at) = @{	_lines_like($patch, qr/^\s*\$prefiltered = 1;/) };
		ok(defined $block_end && defined $flag_at
				&& $flag_at > $guard_at && $flag_at < $block_end,
			'and only there is the renderer told the rows are narrowed');
	}
	else {
		fail('the endpoint applies the cross-filter under a guard');
	}

	# -- the context both of them draw through -----------------------------
	# cf_specs is returned unapplied on purpose: the caller is the only thing
	# that knows which card is the source, so a context that narrowed the rows
	# would narrow the source's too, with no way to put them back.
	my $ctx = _sub_code($src, '_canvas_render_context');
	ok($ctx, 'the context a card is drawn through is there to read');
	is scalar @{	_lines_like($ctx, qr/_apply_filter_spec\(/) }, 0,
		'and hands the cross-filters out unapplied, for the caller to place';

t/model.t  view on Meta::CPAN

	my $spec = {
		name     => 'BmSave',
		datasets => [ { spec => "path:$sales_path", alias => 'left' } ],
		visuals  => [ { kind => 'table', encode => {}, title => 'T' } ],
	};
	my $cid = $t->post_ok('/api/analyses',
		{ 'Content-Type' => 'application/json' },
		encode_json($spec)
	)->status_is(201)->tx->res->json->{id};

	# Save a bookmark by PATCHing the analyses endpoint directly
	# (mirrors what the JS patchBookmarks() function does).
	my $bm = { name => 'My view', state => '?f=region:eq:North', created => 1234567890 };
	$t->patch_ok("/api/analyses/$cid",
		{ 'Content-Type' => 'application/json' },
		encode_json({ bookmarks => [$bm] })
	)->status_is(200);

	# Verify the bookmark is persisted in the stored analysis.
	$t->get_ok("/api/analyses/$cid")->status_is(200);
	my $stored = $t->tx->res->json;

t/path.t  view on Meta::CPAN

subtest '_is_safe_url path-I: 172.16-31.x.x (RFC 1918) -> 0' => sub {
	ok !$IS_SAFE->('http://172.16.0.1/'), 'path I: 172.16.x.x blocked';
	ok !$IS_SAFE->('http://172.31.255.254/'), 'path I: 172.31.x.x upper bound blocked';
};

subtest '_is_safe_url path-J: 192.168.x.x (RFC 1918) -> 0' => sub {
	ok !$IS_SAFE->('http://192.168.0.1/'), 'path J: 192.168.x.x blocked';
};

subtest '_is_safe_url path-K: 169.254.x.x (link-local / metadata) -> 0' => sub {
	ok !$IS_SAFE->('http://169.254.169.254/latest/meta-data/'), 'path K: AWS metadata endpoint blocked';
};

subtest '_is_safe_url path-L: 100.64.x.x (CGNAT / Tailscale) -> 0' => sub {
	ok !$IS_SAFE->('http://100.64.0.1/'), 'path L: CGNAT range blocked';
};

subtest '_is_safe_url path-M: public IP 8.8.8.8 -> 1 (no private range matches)' => sub {
	ok $IS_SAFE->('http://8.8.8.8/'), 'path M: public IP 8.8.8.8 allowed';
};

t/summary.t  view on Meta::CPAN

		row_count => 20,
		use_ai    => 1,
		ai_config => { provider => 'anthropic', api_key => 'sk-test-key', model => 'claude-haiku-5-5' },
	);

	is($result->{source}, 'llm',     'AI path returns source=llm');
	is($result->{text},   $mocked_text, 'AI path returns mocked response text');
	is($result->{cached}, 0,            'AI path: cached=0 on first call');
	ok(scalar @call_args == 1,          'LWP::UserAgent::request called exactly once');
	like($call_args[0]{url}, qr{anthropic\.com/v1/messages},
		'request sent to Anthropic Messages API endpoint');
}

# ---------------------------------------------------------------------------
# Section 6: LLM failure falls back to template_fallback
# ---------------------------------------------------------------------------

SKIP: {
	eval { require LWP::UserAgent; require HTTP::Response; require HTTP::Headers }
		or skip 'LWP not available', 3;

t/summary.t  view on Meta::CPAN

		use_ai    => 1,
		ai_config => { provider => 'anthropic', api_key => 'sk-test-key', model => 'claude-haiku-5-5' },
	);

	is($result->{source}, 'template_fallback', 'LLM error falls back to template_fallback');
	ok(defined $result->{text} && length $result->{text}, 'fallback still produces text');
	like($result->{text}, qr/fallback_test/, 'fallback text mentions label');
}

# ---------------------------------------------------------------------------
# Section 7: HTTP endpoint tests (POST /api/summary)
# ---------------------------------------------------------------------------

{
	my $enc = url_escape($FIXTURE);

	# Missing l= returns 400.
	$t->post_ok('/api/summary', form => {})->status_is(400)
	  ->json_like('/error', qr/./, 'missing l= gives error key in JSON');

	# Valid request returns 200 with text, source, cached.

t/summary.t  view on Meta::CPAN

	  ->json_has('/text', 'response has text key')
	  ->json_has('/source', 'response has source key')
	  ->json_has('/cached', 'response has cached key');

	my $text = $t->tx->res->json->{text};
	ok(defined $text && length $text > 5, 'text field is non-trivial');

	my $source = $t->tx->res->json->{source};
	like($source, qr/\Atemplate/, 'source starts with "template" when AI not configured');

	# Filter forwarding: the endpoint accepts f= and returns 200.
	$t->post_ok('/api/summary', form => {
		l => "path:$FIXTURE",
		f => 'region:eq:North',
	})->status_is(200)
	  ->json_has('/text', 'filtered request returns text key');

	# Unknown table returns 404.
	$t->post_ok('/api/summary', form => { l => 'table:does_not_exist_xyz' })
	  ->status_is(404)
	  ->json_like('/error', qr/./, '404 has error key');

t/summary.t  view on Meta::CPAN

# ---------------------------------------------------------------------------
# Section 9: Insights page now contains Summarize button
# ---------------------------------------------------------------------------

{
	my $enc = url_escape($FIXTURE);
	$t->get_ok("/insights?l=path:$enc")
	  ->status_is(200)
	  ->content_like(qr/btn-summarize/, 'insights page has btn-summarize element')
	  ->content_like(qr/summary-box/,   'insights page has summary-box element')
	  ->content_like(qr/\/api\/summary/, 'insights page references /api/summary endpoint');
}

done_testing;

t/transaction.t  view on Meta::CPAN

	$t->get_ok('/export?l=table:sales&format=csv&f=amount:gt:1500&f=region:eq:North')
		->status_is(200);

	is count_csv_rows($t->tx->res->body), $NORTH_GT1500,
		'Commutativity: reversed filter order produces same S2 count';
};

# ======================================================================
# TRANSACTION 7: Columns API -> Join coordination
#
# The columns_api endpoint feeds the join panel UI with column names.
# This transaction verifies that:
#   Phase 1  GET /api/columns?table=sales  -> columns list
#   Phase 2  The "region" column from the API can serve as a join key
#   Phase 3  GET /join using that key -> merged result
#   Phase 4  Column count in result is correct
# ======================================================================

subtest 'Transaction 7: Columns API -> join coordination' => sub {
	# ------------------------------------------------------------------
	# Phase 1: fetch columns for the sales table.

t/transaction.t  view on Meta::CPAN

	# Verify alpha records do not contain beta values and vice versa.
	ok !(grep { ($_->{value} // '') =~ /^X/ } @$alpha_recs),
		'alpha: records contain no XXX values from beta';
	ok !(grep { ($_->{value} // '') =~ /^A/ } @$beta_recs),
		'beta: records contain no AAA values from alpha';
};

# ======================================================================
# TRANSACTION 11: Combine data lifecycle (cats + dogs)
#
# Verifies the /combine endpoint stacks rows from two heterogeneous files
# into a single unified view with the union of all columns.
#
# cats.csv columns: Species,Name,Color,Breed,Eye Color,Environment
# dogs.csv columns: Species,Name,Color,Breed,Eye Color,Sex,Fixed
# combined columns: Species,Name,Color,Breed,Eye Color,Environment,Sex,Fixed
#
# State invariant:
#   combined_rows  = cat_rows  + dog_rows
#   combined_cols  = union(cat_cols, dog_cols) = 8
#   cat rows have blank Sex,Fixed; dog rows have blank Environment

t/transaction.t  view on Meta::CPAN

# Dashboard.pm passes backend => 'auto' to every Database::Join->new()
# call (added in 0.008.0).  For datasets larger than max_array_rows
# (default 10,000 combined rows) Database::Join spills to a temporary
# SQLite file; smaller datasets use the existing in-memory array path.
#
# Phase 1   Create left/right CSV fixtures in tempdir
# Phase 2   Database::Join backend => 'array' (control group)
# Phase 3   Database::Join backend => 'sqlite' (SQLite disk-spill path)
# Phase 4   Results from Phases 2 and 3 are identical (sorted by row)
# Phase 5   columns() output identical on both backends
# Phase 6   GET /join endpoint returns 200 with merged data
#           (backend => 'auto' is active via Dashboard.pm)
# Phase 7   Source-code guard: Dashboard.pm passes backend => 'auto'
#           in all 3 Database::Join->new() call sites
# ======================================================================

subtest 'Transaction 32 -- Database::Join backend => auto in join pipeline' => sub {
	my $has_dj = eval { require Database::Join; 1 };

	SKIP: {
		skip 'Database::Join not available', 9 unless $has_dj;

t/unit.t  view on Meta::CPAN

	'GET./histogram.400.missing_param'=> 'GET /histogram missing col= -> 400',
	'GET./histogram.404.no_source'    => 'GET /histogram with col= but invalid l= -> 404',

	# HTTP: pivot / stats views
	'GET./pivot.200'           => 'GET /pivot?l=...&rows=...&m=col:sum:total -> 200 HTML',
	'GET./pivot.400.no_rows'   => 'GET /pivot without rows= -> 400',
	'GET./pivot.400.no_source' => 'GET /pivot no l= -> 400',
	'GET./stats.200'           => 'GET /stats?l=... -> 200 HTML',
	'GET./stats.400.no_source' => 'GET /stats no l= -> 400',

	# HTTP: Phase 5 endpoints
	'GET./insights.200'          => 'GET /insights?l=... -> 200 HTML insights page',
	'GET./insights.400.no_l'     => 'GET /insights without l= -> 400',
	'POST./api_summary.200'      => 'POST /api/summary?l=... -> 200 JSON {text,source,cached}',
	'POST./api_summary.400.no_l' => 'POST /api/summary without l= -> 400',
	'POST./api_ask.503.no_key'   => 'POST /api/ask without ai_api_key configured -> 503 JSON {error}',
	'POST./api_ask.400.no_l'     => 'POST /api/ask missing l= -> 400 JSON {error}',
	'POST./api_ask.400.no_q'     => 'POST /api/ask missing q= -> 400 JSON {error}',
	'POST./api_ask.200'          => 'POST /api/ask with mocked LLM -> 200 JSON {spec,url,valid}',
);

t/unit.t  view on Meta::CPAN


	subtest 'GET /stats -- valid l= returns 200 HTML stats page' => sub {
		$t->get_ok('/stats?l=table:sales')
		  ->status_is(200, '200 for valid stats l=')
		  ->content_type_like(qr{text/html}, 'response is HTML');
		delete $ledger{'GET./stats.200'};
	};
}

# ---------------------------------------------------------------------------
# HTTP: Phase 5 endpoints (/insights, /api/summary, /api/ask)
# ---------------------------------------------------------------------------
{
	subtest 'GET /insights -- no l= returns 400' => sub {
		$t->get_ok('/insights')
		  ->status_is(400, '400 when l= absent from /insights');
		delete $ledger{'GET./insights.400.no_l'};
	};

	subtest 'GET /insights -- valid l= returns 200 HTML insights page' => sub {
		$t->get_ok('/insights?l=table:sales')

website/html/api.html  view on Meta::CPAN

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>API &mdash; Database::BI</title>
<meta name="description" content="The JSON API behind Database::BI: saved canvases, their visuals, and the endpoints for columns, directories, statistics, questions and stored fields.">
<meta name="theme-color" content="#fbfaf7" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#12161b" media="(prefers-color-scheme: dark)">
<link rel="canonical" href="api.html">
<meta property="og:type" content="article">
<meta property="og:site_name" content="Database::BI">
<meta property="og:title" content="API &mdash; Database::BI">
<meta property="og:description" content="The JSON API behind Database::BI: saved canvases, their visuals, and the endpoints for columns, directories, statistics, questions and stored fields.">
<meta name="twitter:card" content="summary">
<link rel="stylesheet" href="../css/site.css">
</head>
<body>
<a class="skip" href="#main">Skip to content</a>

<header class="site-header">
	<div class="wrap header-inner">
		<a class="brand" href="index.html">
			<span class="brand-name">Database::BI</span>

website/html/api.html  view on Meta::CPAN


<main id="main" class="wrap">

<div class="hero">
	<p class="eyebrow">JSON, same process, same files</p>
	<h1>API</h1>
	<p class="lead">
		Every page is built from the same pipeline, and the interesting parts are
		available as JSON: saved canvases, their cards, the columns of a source,
		the filesystem, stored calculated fields and the optional question and
		summary endpoints.
	</p>
</div>

<p>
	With <a href="install.html#login"><code>password_hash</code></a> set, every
	endpoint here needs the login: a request without the session cookie gets 401
	<code>{ "error": ... }</code>. A write sent by another site's page is refused
	with 403 either way (<a href="install.html#other-sites">Requests from other
	sites</a>).
</p>

<h2 id="canvases">Saved canvases</h2>
<div class="table-wrap">
<table>
	<thead>
		<tr><th>Method and path</th><th>Does</th><th>Answers</th></tr>

website/html/api.html  view on Meta::CPAN

		optional polished version when <code>ai=1</code> and a key is set. Cached
		for an hour. Past <code>ai_calls_per_hour</code> it gives the deterministic
		text, with <code>source</code> <code>template_limited</code>, uncached.
	</dd>
</dl>

<h2 id="stored">Stored fields</h2>
<p>
	The definitions saved beside the data &mdash; calculated fields, value groups,
	date patterns, lookups, extractions and coordinate columns &mdash; have a list, a save and a delete
	endpoint each, all keyed by <code>l=&lt;spec&gt;</code>:
</p>
<div class="table-wrap">
<table>
	<thead>
		<tr><th>Area</th><th>List</th><th>Save</th><th>Delete</th></tr>
	</thead>
	<tbody>
		<tr>
			<td>Calculated fields</td>
			<td><code>GET /calc/list</code></td>

website/html/canvas.html  view on Meta::CPAN

	JSON</b> saves it, and <b>Import canvas</b> on the Canvases page (<code>/canvases</code>, the
	main navigation's Canvases link) makes a new canvas
	from that file, on this server or another.
</p>

<div class="note">
	<p>
		Canvases live in <code>analyses.json</code> under the model directory, not
		in a database. The JSON API can list, create, patch, import and export them,
		and can append a visual without a browser &mdash; see
		<a href="api.html#visuals">the visuals endpoint</a>.
	</p>
</div>

<h2>Where the numbers come from</h2>
<p>
	A canvas stores datasets, joins, calculated fields and visuals, not rows. Each
	card runs the same pipeline as the page it was saved from
	(<a href="data.html">Data</a> describes the stages), which is why a canvas
	over a file that changed overnight shows this morning's figures, and why the
	same canvas can be narrowed by a range without storing the dates it resolved

website/html/index.html  view on Meta::CPAN

		refuses to store a choice, the page says so and the choice lasts only until
		the next page.
	</p>
</div>

<h2>Where to go next</h2>
<ul class="plain">
	<li><a href="charts.html">Charts</a> &mdash; the nine chart pages, maps and word clouds.</li>
	<li><a href="canvas.html">Canvases</a> &mdash; cards, layout, cross-filtering, sharing.</li>
	<li><a href="data.html">Data</a> &mdash; sources, joins, filters, ranges, calculated fields.</li>
	<li><a href="api.html">API</a> &mdash; the JSON endpoints behind every page.</li>
	<li><a href="install.html">Install</a> &mdash; requirements, configuration, command-line tools.</li>
</ul>

</main>

<footer class="site-footer">
	<div class="wrap">
		<p>Database::BI by Nigel Horne. Released under the GPL2.</p>
		<p>
			<a href="https://metacpan.org/dist/Database-BI">MetaCPAN</a> &middot;

website/html/install.html  view on Meta::CPAN

			<td>unset</td>
			<td>
				Other sites that may show a canvas's <code>/embed/</code> page in a frame.
				See <a href="#embed">Embedding a canvas on another site</a>.
			</td>
		</tr>
		<tr>
			<td><code>ai_api_key</code></td>
			<td>unset</td>
			<td>
				Enables the natural-language question and summary endpoints. Off
				unless you set it; prompts carry column names and aggregate text only.
			</td>
		</tr>
		<tr>
			<td><code>ai_calls_per_hour</code></td>
			<td><code>60</code></td>
			<td>
				The most calls each server process makes to the AI provider in any hour,
				questions and summaries together, since each spends <code>ai_api_key</code>;
				<code>0</code> for no limit. Questions are at most 500 characters.



( run in 3.040 seconds using v1.01-cache-2.11-cpan-eb134014566 )