blib/lib/Database/BI/Controller/Dashboard.pm

filter: Statementstmt 88.0% 6040 / 6864 Branchbran 74.2% 3143 / 4236 Conditioncond 64.0% 2574 / 4018 MC/DCmcdc 44.3% 972 / 2191 Subroutinesub 98.1% 466 / 475 Podpod 98.8% 82 / 83 totaltotal 74.3% 13277 / 17867 CC 4020 SCAR 77.1
CC
4020
Cov
78%
_render_visual_markup
31583.8
pivot_view
1417.6
canvas_render
1292.4
CRAP 2220.1
↑ Summary blib/lib/Database/BI/Util.pm »
1 package Database::BI::Controller::Dashboard;
2  
3 10 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 10 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 10 our $VERSION = '0.024.0';
7  
8 10 ▶use Mojo::Base 'Mojolicious::Controller', -strict, -signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 10 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 10 ▶use Cwd qw(realpath);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 10 ▶use List::Util qw(min max sum);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 10 ▶use CGI::Info;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 10 ▶use CGI::Lingua;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 10 ▶use Database::BI::I18N ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 10 ▶use Unicode::Normalize ();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 10 ▶use Database::BI::Tutorial;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 10 ▶use Database::BI::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 10 ▶use Mojo::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 10 ▶use Mojo::JSON qw(encode_json decode_json from_json to_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 10 ▶use Mojo::Parameters;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 10 ▶use Mojo::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 10 ▶use Mojo::Util qw(url_escape encode xml_escape secure_compare);
Subroutine BEGIN: called CC=1 SCAR=0.0
24 10 ▶use Digest::SHA qw(hmac_sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
25 10 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
26 10 ▶use Database::BI::Password ();
Subroutine BEGIN: called CC=1 SCAR=0.0
27 10 ▶use File::Path qw(remove_tree);
Subroutine BEGIN: called CC=1 SCAR=0.0
28 10 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 10 ▶use Fcntl qw(:flock);
Subroutine BEGIN: called CC=1 SCAR=0.0
30 10 ▶use File::Temp qw(tempfile tempdir);
Subroutine BEGIN: called CC=1 SCAR=0.0
31 10 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
32 10 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 10 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 10 ▶use version ();
Subroutine BEGIN: called CC=1 SCAR=0.0
35  
36 # ---------------------------------------------------------------------------
37 # Constants
38 # ---------------------------------------------------------------------------
39  
40 # File extensions that Database::Abstraction can probe, in probe order.
41 # .sql, .sqlite, and .sqlite3 are all SQLite databases; .db is Berkeley DB.
42 # As many digits as a request parameter may have and still be exact in a Perl
43 # number. More than this is not a page number or a limit, it is someone probing.
44 10 Readonly my $MAX_WHOLE_NUMBER_DIGITS => 15;
45 10 Readonly my %ANALYSIS_KEYS => map { $_ => 1 } qw(id version created updated name datasets joins combines fields measures params visuals layout bookmarks hierarchies);
46 10 Readonly my $MAX_HISTOGRAM_BINS => 200;
47  
48 # What a text card on a canvas may be styled with. The fonts are ones browsers
49 # already have, so a card needs no CDN, and a stored card names a font by its
50 # key: only the CSS written here ever reaches a style attribute.
51 10 Readonly my @TEXT_FONTS => (
52 { value => '', label => 'Same as the page', css => '' },
53 { value => 'arial', label => 'Arial', css => 'Arial, Helvetica, sans-serif' },
54 { value => 'georgia', label => 'Georgia', css => 'Georgia, "Times New Roman", serif' },
55 { value => 'times', label => 'Times New Roman', css => '"Times New Roman", Times, serif' },
56 { value => 'verdana', label => 'Verdana', css => 'Verdana, Geneva, sans-serif' },
57 { value => 'trebuchet', label => 'Trebuchet MS', css => '"Trebuchet MS", Helvetica, sans-serif' },
58 { value => 'courier', label => 'Courier New', css => '"Courier New", Courier, monospace' },
59 );
60 10 Readonly my %TEXT_FONT_CSS => map { $_->{value} => $_->{css} } grep { length $_->{value} } @TEXT_FONTS;
61 10 Readonly my %TEXT_ALIGNS => map { $_ => 1 } qw(left center right);
62 10 Readonly my $MIN_TEXT_POINTS => 8;
63 10 Readonly my $MAX_TEXT_POINTS => 96;
64 10 Readonly my $MAX_TEXT_CHARS => 20_000;
65 10 Readonly my $TEXT_TITLE_CHARS => 60;
66  
67 # What HTML::D3 calls its heatmap colour scales.
68 10 Readonly my %SEQUENTIAL_SCHEMES => map { $_ => 1 } qw(YlOrRd Blues Greens Purples RdPu YlGnBu);
69 10 Readonly my $DEFAULT_SEQUENTIAL_SCHEME => 'YlOrRd';
70 10 Readonly my $DEFAULT_CATEGORICAL_SCHEME => 'tableau10';
71  
72 10 Readonly my @SUPPORTED_EXT => qw( csv db sql sqlite sqlite3 xml tsv psv xlsx json jsonl ndjson );
73 # Use \z (absolute end-of-string) not $ (which permits a trailing \n before \z).
74 # A query param decoded from "file.csv%0A" has basename "sales.csv\n"; without \z
75 # that passes the extension guard and reaches realpath with an embedded newline.
76 10 Readonly my $EXT_RE => do { my $p = join '|', @SUPPORTED_EXT; qr/\.(?:$p)\z/i };
77  
78 # Table name safe-identifier pattern -- must match DataSource's TABLE_NAME_RE
79 # exactly: first character must be a letter or underscore (not a digit), so
80 # that every table name the controller accepts can also be opened by DataSource
81 # without an unhandled croak.
82 # srccol=: the name of the column that says which file a stacked row came from.
83 10 Readonly my $SOURCE_COL_RE => qr/\A[A-Za-z_][A-Za-z0-9_]{0,63}\z/;
84 10 Readonly my $TABLE_NAME_RE => qr/\A[A-Za-z_][A-Za-z0-9_]*\z/;
85  
86 # URL spec pattern shared by _open_spec and _spec_to_url.
87 # qr{} delimiter avoids the \/ escaping noise required by the // form.
88 # /s: makes . match \n so a percent-decoded newline inside a URL does not
89 # silently truncate the captured URL before the \z end-of-string anchor.
90 10 Readonly my $URL_SPEC_RE => qr{\Aurl:(https?://.+)\z}si;
91  
92 # Redis spec pattern: redis:tablename|redis://[password@]host[:port][/db_index]
93 # The pipe separates the table name from the connection URL so the URL's own
94 # colons and slashes do not require extra quoting.
95 10 Readonly my $REDIS_SPEC_RE => qr{\Aredis:([^|]+)\|(redis://.+)\z}si;
96  
97 # Bare Redis URL -- no table name -- used to list available keys.
98 # Excludes '|' so it cannot match the redis:table|redis://... full spec.
99 10 Readonly my $REDIS_URL_RE => qr{\Aredis://[^\s|]+\z}si;
100  
101 # MariaDB spec: mariadb:server/table, where server names an entry in the
102 # mariadb_servers configuration. A spec travels in URLs, links and saved
103 # canvases, so it holds no address or password. It has no '|', which also lets
104 # it be the right side of a j= join.
105 10 Readonly my $MARIADB_SPEC_RE => qr{\Amariadb:([A-Za-z_][A-Za-z0-9_]*)/([A-Za-z_][A-Za-z0-9_]*)\z};
106  
107 # A server with no table: lists its tables.
108 10 Readonly my $MARIADB_SERVER_RE => qr{\Amariadb:([A-Za-z_][A-Za-z0-9_]*)\z};
109  
110 # Hostname pattern accepted in /../hostname/... remote paths.
111 # Mirrors Database::Abstraction's own host validation regex.
112 # Accepts 'hostname', 'user@hostname', and IPv4 addresses (IPv6 is excluded
113 # because the [...] notation would be ambiguous in the path syntax).
114 10 Readonly my $REMOTE_HOST_RE => qr/\A(?:[a-zA-Z0-9][a-zA-Z0-9._-]*\@)?[a-zA-Z0-9][a-zA-Z0-9._-]*\z/;
115  
116 # The tile layer HTML::OSM 0.10 hardcodes. HTML::OSM >= 0.14 is required;
117 # 0.12 introduced search => 0, max_zoom, and tile_url (0.11), 0.13 the scale
118 # bar, the key on the map and fit, and 0.14 the nonce on its scripts.
119 10 Readonly my $DEFAULT_TILE_URL => 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
120  
121 # The language the distribution ships templates for. It is what a request falls
122 # back to when the language it resolved has no template directory of its own;
123 # see _resolve_language. Keep it equal to Database::BI's $DEFAULT_LANGUAGE.
124 10 Readonly my $DEFAULT_LANGUAGE => 'en';
125  
126 # The floor this controller passes options for. HTML::OSM validates its
127 # constructor arguments strictly, so an older install does not ignore the new
128 # keys - it croaks on them. _map_data therefore checks the version before
129 # building a map, and reports a missing or old renderer instead of a 500.
130 # 0.13 draws the scale bar and the key on the map, listing only what is in view
131 # (scale, legend, and group on each marker), and opens on every marker (fit).
132 # 0.14 puts the Content-Security-Policy nonce on its scripts (nonce).
133 10 Readonly my $MIN_HTML_OSM_VERSION => '0.14';
134  
135 # ---------------------------------------------------------------------------
136 # I18N message dictionary for all user-visible strings in this controller.
137 # To plug in a Locale::Maketext backend, extend _i18n() below.
138 # ---------------------------------------------------------------------------
139  
140 10 Readonly my %MESSAGES => (
141 error_table_invalid => 'Invalid table name "%s"',
142 error_table_open => 'Could not open table "%s": %s',
143 error_table_missing => 'There is no table called "%s".',
144 error_file_open => 'Could not open "%s": %s',
145 error_no_path => 'No path specified',
146 error_not_found => 'File or directory not found: %s',
147 error_dir_not_found => 'Directory not found: %s',
148 error_login_required => 'Log in first: this server asks for a password.',
149 error_login_failed => 'That is not the password.',
150 error_login_locked => 'Too many wrong passwords from this address. Try again in %d minutes.',
151 error_hidden_target => 'Refused to save into "%s": a hidden file or folder (one whose name starts with a dot) holds settings, not exports.',
152 error_outside_roots => 'Refused: "%s" is outside the folders this server may use (file_roots in database_bi.conf).',
153 error_outside_export_dirs => 'Refused: exports are saved only in the export folders (export_dirs in database_bi.conf), and "%s" is not one of them.',
154 error_export_not_file => 'Refused: "%s" is already there and is not a plain file, so an export does not replace it.',
155 error_remote_needs_password => 'Refused: this server has no password, so it answers only the machine it runs on. Whoever runs it can set one with "script/database-bi password".',
156 error_cross_site => 'Refused: this request came from another site (%s). Only pages of this application can change what it keeps or write files.',
157 error_host_refused => 'Refused: this server does not answer to the name "%s". Open it as localhost or by its IP address, or add the name to allowed_hosts in database_bi.conf.',
158 error_write_failed => 'Write failed: %s',
159 error_ext_required => 'Use a .csv, .sql, or .json filename extension',
160 error_upload_none => 'No file received',
161 error_upload_ext => 'Unsupported file type. Accepted: CSV, TSV, PSV, XML, JSON, SQLite (.sql, .sqlite, .sqlite3), Berkeley DB (.db), XLSX',
162 error_upload_too_large => 'File too large (maximum %s MiB)',
163 error_upload_save => 'Could not save uploaded file',
164 error_uploads_clear => 'Could not clear the uploaded files',
165 error_export_sqlite => 'Could not build the SQLite export; the server log has the reason',
166 error_path_required => '"path" parameter is required',
167 error_url_required => 'Please enter a URL',
168 error_url_invalid => '"%s" is not a valid http:// or https:// URL',
169 error_url_fetch => 'Could not load HTML table from "%s": %s',
170 error_url_ssrf => '"%s" resolves to a private or reserved address and cannot be fetched',
171 warn_combine_sort => 'Sorting is applied in memory for /combine; result order may differ from a backend sort',
172 error_sort_column => 'Unknown sort column "%s"',
173 warn_measure_fallback => 'Measure "%s" on column "%s" is not uniformly numeric; totalled in Perl',
174 error_measure_column => 'Measure column "%s" is not in the view',
175 error_pivot_rows_required => 'At least one rows= dimension is required',
176 error_pivot_measure_req => 'At least one m= measure (col:fn:as) is required',
177 error_pivot_measure_invalid => 'Invalid measure spec "%s"; expected col:fn:as where fn is one of: %s, or p1 to p100 for a percentile',
178 error_stats_percentile => 'The percentile must be a whole number from 1 to 100; "%s" is not',
179 error_pivot_dim_not_found => 'Row/column dimension "%s" is not in the view',
180 error_pivot_dim_comma => 'Dimension name "%s" must not contain a comma',
181 error_calc_compile => 'Calculated field "%s": %s',
182 error_calc_name => 'Calculated field name "%s" is not a valid identifier',
183 error_topn_col => 'Top-N column "%s" is not a measure alias in this view',
184 warn_calc_undef => 'Calculated field "%s" returned undef for %d row(s)',
185 error_date_pattern => 'Unsupported date format pattern "%s"; allowed: %%m/%%d/%%Y, %%d/%%m/%%Y, %%d-%%b-%%Y',
186 error_date_time_pattern => 'Unsupported time format pattern "%s"; allowed: %%H:%%M, %%H:%%M:%%S',
187 error_date_as => 'as= must be "timestamp" or absent; "%s" is neither',
188 error_lookup_name => 'Lookup name "%s" is not a valid identifier',
189 error_lookup_unknown => 'Lookup "%s" is not stored for any dataset',
190 error_lookup_remote => 'Lookup "%s": "%s" is not a file; a lookup reads a file under data_dir (use Import for a URL)',
191 error_lookup_outside => 'Lookup "%s": "%s" is not under data_dir',
192 error_lookup_not_found => 'Lookup "%s": file "%s" not found, or not a supported data file',
193 error_lookup_too_large => 'Lookup "%s": "%s" is %d bytes, more than a lookup may be (%d)',
194 error_lookup_unreadable => 'Lookup "%s": cannot read "%s": %s',
195 error_lookup_key_unknown => 'Lookup "%s": key column "%s" is not in "%s"',
196 error_lookup_field_unknown => 'Lookup "%s": field "%s" is not in "%s"',
197 error_lookup_col_unknown => 'Lookup "%s": column "%s" is not in this dataset (nolk=%s skips the lookup)',
198 error_lookup_name_taken => 'Lookup "%s": field "%s" cannot be added, because "%s" is a column already',
199 warn_lookup_duplicate_key => 'Lookup "%s": %d duplicate key(s) in "%s"; the first row of each is used',
200 error_extract_name => 'Extraction name "%s" is not a valid identifier',
201 error_extract_pattern => 'Extraction "%s": %s',
202 error_extract_no_names => 'Extraction "%s": the pattern names no group; write one as (?<name>...) for each column',
203 error_extract_field => 'Extraction "%s": the pattern has no group named "%s"',
204 error_extract_col_unknown => 'Extraction "%s": column "%s" is not in this dataset',
205 error_extract_name_taken => 'Extraction "%s": group "%s" cannot be added, because "%s" is a column already',
206 error_accel_spec => 'Cannot accelerate "%s": it must be a table: or path: spec naming a local file that exists',
207 error_accel_sqlite => 'Cannot accelerate "%s": it is a SQLite database already',
208 error_accel_open => 'Cannot accelerate "%s": the file cannot be opened: %s',
209 error_accel_store => 'Cannot accelerate "%s": the model store cannot be written (model_dir inside data_dir, or not writable)',
210 error_accel_build => 'Cannot accelerate "%s": %s',
211 error_analysis_not_found => 'Analysis "%s" not found',
212 error_analysis_invalid => 'Invalid analysis spec: %s',
213 error_analysis_version => 'Unsupported analysis version %s; please upgrade the application',
214 error_analysis_storage => 'Analysis storage is not writable; use import/export instead',
215 error_analysis_json => 'Invalid JSON body: %s',
216 error_analysis_id_invalid => 'Invalid analysis id',
217 error_text_card_empty => 'A text card needs some text',
218 error_text_card_long => 'A text card can hold at most %d characters',
219 error_text_card_font => 'That font is not one of the choices',
220 error_text_card_size => 'The size must be a whole number of points from %d to %d',
221 error_text_card_colour => 'A colour must be written #rrggbb',
222 error_text_card_align => 'The alignment must be left, center or right',
223 error_text_card_options => 'options must be given as an object',
224 error_text_card_columns => 'A text card has no columns to change',
225 error_text_card_no_data => 'A text card has no data to download',
226 error_visual_not_text => 'Only a text card can be removed',
227 error_param_range => "Parameter '%s' is out of range (min %s, max %s)",
228 error_param_type => "Parameter '%s' must be a number",
229 error_map_source => 'A map needs loc=<column> to geocode, or both lat= and lon= coordinate columns',
230 error_map_coordinates => 'A map with lat= needs lon= as well, and a map with lon= needs lat=',
231 error_map_loc_column => 'Column "%s" is not in this view, so there is nothing to geocode',
232 error_map_coordinate_range => 'Column "%s" holds only values outside the range of %s; check that lat= and lon= are not swapped',
233 error_map_coordinate_numeric => 'Columns "%s" and "%s" hold no numeric coordinate pairs; a map needs numbers, or loc=<column> to geocode places',
234 error_map_no_markers => 'No row has a location that could be plotted',
235 error_map_renderer_missing => 'Drawing a map needs HTML::OSM 0.14 or later, and it is not installed',
236 error_map_renderer_failed => 'The map could not be drawn; the server log has the reason',
237 error_map_renderer_old => 'Drawing a map needs HTML::OSM 0.14 or later, but the installed HTML::OSM is %s',
238 warn_join_schema_mismatch => 'Column "%s" has type %s in %s but %s in %s; the join keeps both columns, so check which one a calculation uses',
239 warn_map_coordinate_rows => 'Plotted %d of %d rows; %d hold no usable coordinate',
240 warn_map_markers_capped => 'Showing the first %d of %d markers; add f= filters to see the rest',
241 map_legend_empty => 'Nothing in this view',
242 map_bounds_layer => '%s boundaries',
243 map_bounds_noun_country => 'country',
244 map_bounds_noun_state => 'state',
245 map_bounds_noun_region => 'region',
246 map_bounds_noun_county => 'county',
247 map_bounds_noun_city => 'city',
248 map_bounds_noun_town => 'town',
249 map_bounds_noun_neighbourhood => 'neighbourhood',
250 map_bounds_noun_district => 'district',
251 map_bounds_noun_province => 'province',
252 map_bounds_noun_prefecture => 'prefecture',
253 map_bounds_noun_department => 'department',
254 map_bounds_noun_area => 'area',
255 map_bounds_total => '%s: %s %s',
256 map_bounds_row => '%s: 1 row',
257 map_bounds_rows => '%s: %s rows',
258 map_bounds_key_total => '%s in each %s',
259 map_bounds_key_rows => 'Rows in each %s',
260 map_bounds_key_range => '%s to %s',
261 warn_map_cache_unwritten => 'The resolved places could not be remembered in the model store, so the next request will look them up again',
262 error_map_tiles_unknown => 'Unknown tile source "%s"; define it under tile_sources in database_bi.conf',
263 error_map_geocode_mode => 'geocode= must be "wait" (look places up before the page is sent) or "cached" (look nothing up), not "%s"',
264 error_geo_lookup_place => 'A lookup needs place= and the sig= the map page gave it',
265 error_geo_lookup_unsigned => 'This place was not listed by a map page, or the server has restarted since; open the map again',
266 error_map_loc_text => 'loc_text= is the text added to the end of each place, at most %d characters on one line, not "%s"',
267 error_map_bounds_unknown => 'bounds= must be one of %s, not "%s"',
268 warn_map_bounds_pending => '%d of %d places have no %s outline yet',
269 warn_map_bounds_pending_one => '%d of %d places has no %s outline yet',
270 warn_map_bounds_offline => '%d of %d places have no %s outline: outlines come from OpenStreetMap, which this server does not ask (map_geocode_online is off, or LWP::UserAgent::Throttled is not installed)',
271 warn_map_bounds_offline_one => '%d of %d places has no %s outline: outlines come from OpenStreetMap, which this server does not ask (map_geocode_online is off, or LWP::UserAgent::Throttled is not installed)',
272 warn_map_bounds_failed => 'OpenStreetMap did not answer, so %d of %d places have no %s outline; they are tried again next time',
273 warn_map_bounds_failed_one => 'OpenStreetMap did not answer, so %d of %d places has no %s outline; it is tried again next time',
274 error_geo_boundary_point => 'A lookup needs point= and the sig= the map page gave it',
275 error_geo_boundary_unsigned => 'This point was not listed by a map page, or the server has restarted since; open the map again',
276 error_insights_no_data => 'No data available to analyse',
277 insights_insufficient_data => 'Insufficient data for this insight type (need more rows or periods)',
278 ask_unavailable => 'Ask a question is not available: no AI provider is configured',
279 ask_no_question => 'Please enter a question',
280 ask_question_too_long => 'The question is longer than %d characters; please shorten it',
281 ai_limit_reached => 'The AI provider has been asked %d times in the last hour, the most this server allows (ai_calls_per_hour); please try again later',
282 ask_provider_error => 'AI provider error; could not generate an analysis',
283 ask_unparseable => 'Could not parse a valid visualization from the response; please rephrase your question',
284 ask_invalid_spec => 'Generated spec contains an unknown column: %s',
285 summary_consent_required => 'AI consent is required before sending data to an external provider',
286 summary_ai_unavailable => 'AI provider not configured; using template summary',
287 summary_provider_error => 'AI provider error; using template summary',
288 error_token_invalid => 'Share token is invalid or has expired',
289 error_token_missing => 'A share token is required to view this analysis',
290 freshness_stale_msg => 'Source data has changed since this analysis was last saved',
291 error_agg_fn => 'Unknown aggregate function "%s"; expected one of: %s, or p1 to p100 for a percentile',
292 error_range_name => 'Unknown time range "%s"; expected one of: %s',
293 error_range_column => 'A time range is applied to one column: add rcol=<column> to the URL',
294 error_filter_op => 'Unknown filter operator "%s" in f=%s; expected one of: %s',
295 error_filter_column => 'There is no column called "%s" to filter on (f=%s); the columns are: %s',
296 error_range_column_unknown => 'There is no column called "%s" for the time range (rcol=%s); the columns are: %s',
297 error_span_interval => 'Unknown time bucket "%s" for span=; use a count and one of s, m, h, d, w, mon, q or y, for example 1h or 15m',
298 error_span_no_column => 'A time bucket needs one column to bucket: add tcol=<column>, or name exactly one of the dimensions this page already takes',
299 error_span_tcol_orphan => 'tcol=%s names the column to bucket, but span=<interval> is missing',
300 error_span_tcol_unknown => 'Column "%s" is not in this view, so there is nothing to bucket',
301 error_span_conflict => 'The bucket column "%s" is already defined by a calculated field; add as=<name> to bucket under a name of its own',
302 error_span_name => 'Bucket column name "%s" is not a usable column name; add as=<name>',
303 error_cs_spec => 'cs=%s must be <column>:<function>:<alias>, optionally followed by :<parameter>',
304 error_cs_column => 'cs=%s names the column "%s", which is not in this view',
305 error_cs_fn => 'Unknown cross-row function "%s"; use one of: %s',
306 error_cs_alias => 'Cross-row alias "%s" is not a usable column name',
307 error_cs_conflict => 'Cross-row alias "%s" is already a column of this view, or another cs= already writes it; choose another name',
308 error_cs_arg => 'cs=%s: %s takes a whole number greater than zero, as in %s:%s:ma7:7',
309 error_cs_no_arg => 'cs=%s: %s takes no parameter',
310 error_cs_by => 'by=%s names "%s", which is not a column of this view',
311 error_cs_order => 'order=%s must be <column>, <column>:asc or <column>:desc',
312 error_cs_order_col => 'order=%s names "%s", which is not a column of this view',
313 error_cs_order_need => 'cs=%s needs order=: %s reads its rows in order, so the order has to be named',
314 );
315  
316 # Maximum accepted upload body size. Enforced both here (application layer)
317 # and via Mojolicious max_request_size (transport layer) set in startup().
318 # Must match $MAX_REQUEST_SIZE in BI.pm.
319 10 Readonly my $MAX_UPLOAD_MIB => 50;
320 10 Readonly my $MAX_UPLOAD_BYTES => $MAX_UPLOAD_MIB * 1_048_576;
321 10 Readonly my $DEFAULT_JOIN_MAX_ROWS => 10_000;
322 10 Readonly my $LOOKUP_MAX_BYTES => 8 * 1_048_576; # a bigger file is a join, not a lookup
323 10 Readonly my $LOOKUP_NAME_RE => qr/\A[A-Za-z_][A-Za-z0-9_]*\z/;
324 10 Readonly my $DEFAULT_MAP_GEOCODE_MAX => 500; # new lookups per request (map_geocode_max)
325 # Places looked up online (OpenStreetMap's Nominatim) per request. Nominatim
326 # allows one request a second, so this is roughly the seconds a page can wait
327 # for it: twenty keeps a page well inside hypnotoad's 50-second heartbeat, and
328 # script/bi-geocode, which has no page to hold, asks without a limit.
329 10 Readonly my $DEFAULT_MAP_GEOCODE_ONLINE_MAX => 20; # map_geocode_online_max
330 10 Readonly my $DEFAULT_MAP_MAX_MARKERS => 2_000; # markers drawn per request (map_max_markers)
331 10 Readonly my $DEFAULT_MAP_POPUP_ROWS => 10; # rows listed in one marker's popup (map_popup_rows)
332 10 Readonly my $DEFAULT_MARKER_COLOR => '#3388ff'; # Leaflet default blue
333 # A bubble map's size key: the bubbles' own colour when they have one, and
334 # this grey when the colour says something else (a colour column)
335 10 Readonly my $MAP_SIZE_KEY_COLOR => '#888888';
336 10 Readonly my %NAMED_COLORS => map { $_ => 1 } qw(
337 red orange yellow green teal cyan blue navy purple
338 magenta pink brown maroon olive silver gray grey gold lime white black
339 );
340 10 Readonly my $MAX_PREFIX_LEN => 20;
341 10 Readonly my $DEFAULT_PER_PAGE => 200;
342 10 Readonly my $MAX_PER_PAGE => 2_000;
343 # The page sizes offered under a table or pivot and on /preferences; 0 is every
344 # row on one page. The preference is the cookie $PAGE_SIZE_COOKIE (the server
345 # must see it before it reads the page), and only these values are taken from it.
346 10 Readonly my @PAGE_SIZES => (25, 50, 100, 200, 0);
347 10 Readonly my %PAGE_SIZE_OK => map { $_ => 1 } @PAGE_SIZES;
348 10 Readonly my $PAGE_SIZE_COOKIE => 'bi_per_page';
349 # per_page=0 (all rows) as a page size the arithmetic can use: one page that
350 # holds any table this application can read.
351 10 Readonly my $ALL_ROWS => 2_000_000_000;
352 10 Readonly my %SCATTER_SCHEMES => map { $_ => 1 } qw(tableau10 category10 set2 set3 paired);
353  
354 # Categorical palettes for map series colouring, matching the D3 schemes the
355 # chart pages offer. The map draws per-marker icons rather than D3 marks, so
356 # the hexes live here instead of in a template.
357 10 Readonly my %CATEGORY_PALETTES => (
358 tableau10 => [ '#4e79a7', '#f28e2c', '#e15759', '#76b7b2', '#59a14f',
359 '#edc949', '#af7aa1', '#ff9da7', '#9c755f', '#bab0ab' ],
360 category10 => [ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
361 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf' ],
362 set2 => [ '#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854',
363 '#ffd92f', '#e5c494', '#b3b3b3' ],
364 set3 => [ '#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3',
365 '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd',
366 '#ccebc5', '#ffed6f' ],
367 paired => [ '#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99',
368 '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a',
369 '#ffff99', '#b15928' ],
370 );
371  
372 # add_circle_marker() accepts only hex colours, while the icon path also takes
373 # the named colours _parse_color() allows. Map the names once, here.
374 10 Readonly my %NAMED_COLOR_HEX => (
375 red => '#ff0000', orange => '#ffa500', yellow => '#ffff00',
376 green => '#008000', teal => '#008080', cyan => '#00ffff',
377 blue => '#0000ff', navy => '#000080', purple => '#800080',
378 magenta => '#ff00ff', pink => '#ffc0cb', brown => '#a52a2a',
379 maroon => '#800000', olive => '#808000', silver => '#c0c0c0',
380 gray => '#808080', grey => '#808080', gold => '#ffd700',
381 lime => '#00ff00', white => '#ffffff', black => '#000000',
382 );
383  
384 # The aggregate function vocabulary shared by _measure, _grouped_totals, the
385 # /pivot measure-spec parser and the /stats view.
386 #
387 # It has two halves. @PUSHED_MEASURE_FNS are the functions
388 # Database::Abstraction's aggregate() computes in the backend: adding one here
389 # means adding it there as well. @PERL_MEASURE_FNS are computed by the Perl
390 # fold in _grouped_totals from all the values in a group, because a subtotal has
391 # to be recomputed from the rows rather than combined out of the cells (a median
392 # is not the sum of the medians of its parts), and because the app already holds
393 # the rows: the fold is one pass over records that are in memory, with no second
394 # implementation of the same statistic to agree with. Database::Abstraction
395 # does accept a median and a stddev measure, computing them in Perl over rows it
396 # materialises itself -- close enough to be tempting, and exactly the second
397 # implementation to avoid, so _measure_pushable refuses to send them.
398 #
399 # A percentile is spelled p<N>, for N from 1 to 100: p90, p99, p1. The level
400 # rides in the function name because the spec dialect is col:fn:as, with no
401 # room for a parameter in it; p50 is the median, and median is kept as its own
402 # name because that is what a reader looks for.
403 10 Readonly my @PUSHED_MEASURE_FNS => qw(sum avg min max count count_distinct);
404 10 Readonly my @PERL_MEASURE_FNS => qw(median stdev first last range);
405 10 Readonly my @MEASURE_FNS => (@PUSHED_MEASURE_FNS, @PERL_MEASURE_FNS);
406 10 Readonly my %PUSHED_MEASURE_FN_OK => map { $_ => 1 } @PUSHED_MEASURE_FNS;
407 10 Readonly my %MEASURE_FN_OK => map { $_ => 1 } @MEASURE_FNS;
408  
409 # _measure_percentile($fn) -> $level | undef
410 #
411 # The percentile level a measure function names, or undef when it names none:
412 # 'p95' -> 95, 'p50' -> 50, 'percentile' -> undef, 'sum' -> undef. A level
413 # outside 1..100 is not a percentile, so an unknown function still fails as an
414 # unknown function rather than as a percentile of -40.
415 102 ▶sub _measure_percentile {
Subroutine _measure_percentile: called CC=6 SCAR=17.9
416 102 my $fn = shift;
417 102 ▶ return undef unless defined $fn && length $fn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fn and length $fn 2 100 102
Condition100%3/3
defined $fn and length $fn
!ll&&!rl&&r
11100
MC/DC100%2/2
defined $fn and length $fn
defined $fn length $fn
Truth table100%3/3
A and B
A= defined $fnB= length $fn
ABresult
0X0
100
111
418 100 my ($level) = $fn =~ /\Ap(\d{1,3})\z/;
419 100 ▶ return undef unless defined $level;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $level 47 53 100
420 53 ▶ return ($level >= 1 && $level <= 100) ? $level + 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$level >= 1 && $level <= 100 ? : 47 6 53
Condition100%3/3
$level >= 1 and $level <= 100
!ll&&!rl&&r
3347
MC/DC100%2/2
$level >= 1 and $level <= 100
$level >= 1 $level <= 100
Truth table100%3/3
A and B
A= $level >= 1B= $level <= 100
ABresult
0X0
100
111
421 }
422  
423 # _measure_fn_ok($fn) -> bool
424 #
425 # True for every function _grouped_totals can compute: the named ones and any
426 # percentile level. This is the single answer to "is this a measure function?"
427 # for the parser, and the vocabulary the 400 message prints comes from the same
428 # two lists, so a message can never list a function the fold cannot compute.
429 88 ▶sub _measure_fn_ok {
Subroutine _measure_fn_ok: called CC=5 SCAR=16.1
430 88 my $fn = shift;
431 88 ▶ return 0 unless defined $fn && length $fn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fn and length $fn 2 86 88
Condition100%3/3
defined $fn and length $fn
!ll&&!rl&&r
1186
MC/DC100%2/2
defined $fn and length $fn
defined $fn length $fn
Truth table100%3/3
A and B
A= defined $fnB= length $fn
ABresult
0X0
100
111
432 86 ▶ return 1 if $MEASURE_FN_OK{$fn};
Branch: 1 branch
BranchTrueFalseTotal
if $MEASURE_FN_OK{$fn} 60 26 86
433 26 ▶ return defined _measure_percentile($fn) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined _measure_percentile($fn) ? : 12 14 26
434 }
435  
436 # ---------------------------------------------------------------------------
437 # Relative time ranges
438 #
439 # A relative time range is a named window worked out from the clock when the
440 # request arrives -- "the last 30 days", "this quarter" -- so a link, a
441 # bookmark or a saved canvas that carries one keeps meaning the same thing
442 # every time it is opened instead of freezing the dates it first resolved to.
443 #
444 # The range is named in the URL (?range=<name>&rcol=<column>) and resolved to
445 # two f= filters on that column, which every data route already applies, so the
446 # table view, the charts, the pivot, the stats page, the insights page, the
447 # exports and a saved canvas all see the same rows.
448 #
449 # The vocabulary is day-granular except last_24_hours, which is to the second.
450 # ---------------------------------------------------------------------------
451  
452 10 Readonly my @TIME_RANGES => (
453 { name => 'last_24_hours', label => 'Last 24 hours', hours => 24 },
454 { name => 'today', label => 'Today', day => 0 },
455 { name => 'yesterday', label => 'Yesterday', day => -1 },
456 { name => 'last_7_days', label => 'Last 7 days', days => 7 },
457 { name => 'last_30_days', label => 'Last 30 days', days => 30 },
458 { name => 'last_90_days', label => 'Last 90 days', days => 90 },
459 { name => 'this_month', label => 'This month', month => 0 },
460 { name => 'last_month', label => 'Last month', month => -1 },
461 { name => 'this_quarter', label => 'This quarter', quarter => 0 },
462 { name => 'last_quarter', label => 'Last quarter', quarter => -1 },
463 { name => 'this_year', label => 'This year', year => 0 },
464 { name => 'last_year', label => 'Last year', year => -1 },
465 );
466 10 Readonly my %TIME_RANGE => map { $_->{name} => $_ } @TIME_RANGES;
467  
468 # The operators an f= filter may name (_apply_filter_spec), as written: an
469 # operator in capitals is refused with the rest, not read as another one.
470 # differ (the Delta button) is the one whose value is another column's name:
471 # f=a:differ:b keeps the rows where a and b do not hold identical text.
472 10 Readonly my @FILTER_OPS => qw(eq ne contains starts lt le gt ge empty notempty between in differ);
473 10 Readonly my %FILTER_OP => map { $_ => 1 } @FILTER_OPS;
474  
475 # How many column names a refusal lists before it says how many more there are.
476 10 Readonly my $FILTER_COLUMNS_LISTED => 20;
477  
478 # Allowed strptime-style date format patterns for the /dates/save endpoint, and
479 # the two time patterns that may be given beside one of them for a column that
480 # holds a clock time as well as a date.
481 10 Readonly my %ALLOWED_DATE_PATTERNS => map { $_ => 1 }
482 qw(%m/%d/%Y %d/%m/%Y %d-%b-%Y);
483 10 Readonly my %ALLOWED_TIME_PATTERNS => map { $_ => 1 }
484 qw(%H:%M %H:%M:%S);
485  
486 # Default share token lifetime: 30 days in seconds.
487 10 Readonly my $SHARE_TOKEN_TTL => 30 * 86_400;
488  
489 # The AI routes spend the configured ai_api_key on every call. A question is
490 # at most this long, and each server process makes at most ai_calls_per_hour
491 # provider calls in any hour (0: no limit).
492 10 Readonly my $ASK_MAX_QUESTION => 500;
493 10 Readonly my $AI_CALLS_PER_HOUR => 60;
494 10 Readonly my $AI_WINDOW_S => 3600;
495  
496 # ---------------------------------------------------------------------------
497 # Protected helpers
498 # ---------------------------------------------------------------------------
499  
500 # _whole_number($value) -> $integer | undef
501 #
502 # A request parameter as an integer, or undef if it does not spell one. int()
503 # on the raw text warns on 'abc' and turns it into 0, and reads a long run of
504 # digits or '1e400' as infinity, which no LIMIT or OFFSET can use.
505 1227 ▶sub _whole_number {
Subroutine _whole_number: called CC=3 SCAR=11.0
506 1227 my $value = $_[0];
507 1227 ▶ return undef unless defined($value) && $value =~ /\A-?[0-9]{1,$MAX_WHOLE_NUMBER_DIGITS}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value =~ /\A-?[0-9]{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u 1140 87 1227
Condition100%3/3
defined $value and $value =~ /\A-?[0-9]{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u
!ll&&!rl&&r
10905087
MC/DC100%2/2
defined $value and $value =~ /\A-?[0-9]{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u
defined $value $value =~ /\A-?[0-9]{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u
Truth table100%3/3
A and B
A= defined $valueB= $value =~ /\A-?[0-9]{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u
ABresult
0X0
100
111
508 87 return $value + 0;
509 }
510  
511 # _categorical_scheme($name) -> $name
512 # _sequential_scheme($name) -> $name
513 #
514 # A colour scheme the chart can use, or the default. These must be checked here:
515 # HTML::D3 writes a categorical name into its script as SCHEMES['name'], so an
516 # unchecked value is script on the page, and it dies on a sequential name it does
517 # not know, which is a 500. An unknown name has always drawn the default colours.
518 148 ▶sub _categorical_scheme {
Subroutine _categorical_scheme: called CC=4 SCAR=13.9
519 148 my $name = $_[0];
520 148 ▶ return (defined($name) && !ref($name) && $SCATTER_SCHEMES{$name}) ? $name : $DEFAULT_CATEGORICAL_SCHEME;
Branch: 1 branch
BranchTrueFalseTotal
defined $name && !ref($name) && $SCATTER_SCHEMES{$name} ? : 1 147 148
Condition100%6/6
defined $name and not ref $name and $SCATTER_SCHEMES{$name}
!ll&&!rl&&r
135121
defined $name and not ref $name
!ll&&!rl&&r
134113
MC/DC100%3/3
defined $name and not ref $name and $SCATTER_SCHEMES{$name}
defined $name not ref $name $SCATTER_SCHEMES{$name}
Truth table100%4/4
A and not(B) and C
A= defined $nameB= not ref $nameC= $SCATTER_SCHEMES{$name}
ABCresult
0XX0
10X0
1100
1111
521 }
522  
523 133 ▶sub _sequential_scheme {
Subroutine _sequential_scheme: called CC=4 SCAR=13.9
524 133 my $name = $_[0];
525 133 ▶ return (defined($name) && !ref($name) && $SEQUENTIAL_SCHEMES{$name}) ? $name : $DEFAULT_SEQUENTIAL_SCHEME;
Branch: 1 branch
BranchTrueFalseTotal
defined $name && !ref($name) && $SEQUENTIAL_SCHEMES{$name} ? : 1 132 133
Condition100%6/6
defined $name and not ref $name and $SEQUENTIAL_SCHEMES{$name}
!ll&&!rl&&r
122101
defined $name and not ref $name
!ll&&!rl&&r
121111
MC/DC100%3/3
defined $name and not ref $name and $SEQUENTIAL_SCHEMES{$name}
defined $name not ref $name $SEQUENTIAL_SCHEMES{$name}
Truth table100%4/4
A and not(B) and C
A= defined $nameB= not ref $nameC= $SEQUENTIAL_SCHEMES{$name}
ABCresult
0XX0
10X0
1100
1111
526 }
527  
528 # _optional_scheme($name) -> $name | undef
529 #
530 # A categorical scheme for a chart that draws its own colours without one:
531 # a histogram's bars are steelblue, a combo's bars and line steelblue and red,
532 # and a scheme replaces them with its first colours. Unlike
533 # _categorical_scheme there is no scheme by default, so a name that is not one
534 # of the five is undef and the chart keeps the colours it had before scheme=
535 # existed. /histogram, /combo and their canvas cards all read it here.
536 124 ▶sub _optional_scheme {
Subroutine _optional_scheme: called CC=4 SCAR=13.9
537 124 my $name = $_[0];
538 124 ▶ return (defined($name) && !ref($name) && $SCATTER_SCHEMES{$name}) ? $name : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $name && !ref($name) && $SCATTER_SCHEMES{$name} ? : 5 119 124
Condition100%6/6
defined $name and not ref $name and $SCATTER_SCHEMES{$name}
!ll&&!rl&&r
11095
defined $name and not ref $name
!ll&&!rl&&r
109114
MC/DC100%3/3
defined $name and not ref $name and $SCATTER_SCHEMES{$name}
defined $name not ref $name $SCATTER_SCHEMES{$name}
Truth table100%4/4
A and not(B) and C
A= defined $nameB= not ref $nameC= $SCATTER_SCHEMES{$name}
ABCresult
0XX0
10X0
1100
1111
539 }
540  
541 # _scatter_radii($min, $max) -> ($min, $max)
542 #
543 # A scatter's bubble radius range in pixels: each value a whole number clamped
544 # to 1..40, anything else (absent, empty, 0, text) the default 3 or 15, and the
545 # pair put in order rather than refused. /scatter and a canvas scatter card
546 # both read it here, so a card saved from the page draws the same bubbles.
547 59 ▶sub _scatter_radii {
Subroutine _scatter_radii: called CC=8 SCAR=20.8
548 59 ▶ my ($min, $max) = map { _whole_number(ref $_ ? undef : $_) } @_[0, 1];
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 1 117 118
549 59 ▶ $min = 3 unless $min;
Branch: 1 branch
BranchTrueFalseTotal
unless $min 57 2 59
550 59 ▶ $max = 15 unless $max;
Branch: 1 branch
BranchTrueFalseTotal
unless $max 57 2 59
551 59 for ($min, $max) {
552 118 ▶ $_ = 1 if $_ < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $_ < 1 1 117 118
553 118 ▶ $_ = 40 if $_ > 40;
Branch: 1 branch
BranchTrueFalseTotal
if $_ > 40 1 117 118
554 }
555 59 ▶ return $min > $max ? ($max, $min) : ($min, $max);
Branch: 1 branch
BranchTrueFalseTotal
$min > $max ? : 1 58 59
556 }
557  
558 # _pagination($self) -> ($page, $per_page, $offset)
559 #
560 # Reads ?page= and ?per_page= from the current request, clamps them to sane
561 # ranges, and returns the 1-based page number, the page size, and the
562 # 0-based row offset. Without per_page= the size is the reader's preference
563 # (_page_size_preference), else DEFAULT_PER_PAGE. 0 is every row: one page of
564 # $ALL_ROWS, so it bypasses MAX_PER_PAGE, which bounds only a number typed in
565 # the URL.
566 #
567 # Also stashes, for layouts/page_size.html.tt: page_size (0 for every row),
568 # page_size_asked (the URL named one) and page_size_choices.
569 443 ▶sub _pagination {
Subroutine _pagination: called CC=12 SCAR=25.1
570 443 my $self = $_[0];
571  
572 443 ▶ my $asked_in_url = defined $self->param('per_page') && length $self->param('per_page');
Condition100%3/3
defined $self->param('per_page') && length $self->param('per_page')
!ll&&!rl&&r
412328
MC/DC100%2/2
defined $self->param('per_page') && length $self->param('per_page')
defined $self->param('per_page') length $self->param('per_page')
Truth table100%3/3
A && B
A= defined $self->param('per_page')B= length $self->param('per_page')
ABresult
0X0
100
111
573 443 my $asked = _whole_number($self->param('per_page'));
574 443 ▶ $asked = _page_size_preference($self) unless defined $asked;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $asked 428 15 443
575  
576 443 my ($per_page, $page);
577 443 ▶ if (defined $asked && $asked == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $asked and $asked == 0) { } 0 443 443
Condition66%2/3
defined $asked and $asked == 0
!ll&&!rl&&r
428150
MC/DC0%0/2
defined $asked and $asked == 0
defined $asked $asked == 0
Truth table66%2/3
A and B
A= defined $askedB= $asked == 0
ABresult
0X0
100
111
578 0 ($per_page, $page) = ($ALL_ROWS, 1);
579 } else {
580 443 ▶ $per_page = $asked || $DEFAULT_PER_PAGE;
Condition66%2/3
$asked || $DEFAULT_PER_PAGE
l!l&&r!l&&!r
154280
MC/DC0%0/2
$asked || $DEFAULT_PER_PAGE
$asked $DEFAULT_PER_PAGE
Truth table66%2/3
A || B
A= $askedB= $DEFAULT_PER_PAGE
ABresult
1X1
011
000
581 443 ▶ $per_page = 1 if $per_page < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $per_page < 1 1 442 443
582 443 ▶ $per_page = $MAX_PER_PAGE if $per_page > $MAX_PER_PAGE;
Branch: 1 branch
BranchTrueFalseTotal
if $per_page > $MAX_PER_PAGE 1 442 443
583 443 ▶ $page = _whole_number($self->param('page')) || 1;
Condition100%2/2
_whole_number($self->param('page')) || 1
l!l
14429
MC/DC100%1/1
_whole_number($self->param('page')) || 1
_whole_number($self->param('page'))
Truth table100%2/2
A
A= _whole_number($self->param('page'))
Aresult
11
00
584 443 ▶ $page = 1 if $page < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $page < 1 1 442 443
585 }
586 443 my $offset = ($page - 1) * $per_page;
587  
588 443 ▶ $self->stash(
Branch: 2 branches
BranchTrueFalseTotal
$per_page == $ALL_ROWS ? : 0 443 443
$asked_in_url ? : 28 415 443
589 page_size => ($per_page == $ALL_ROWS ? 0 : $per_page),
590 page_size_asked => ($asked_in_url ? 1 : 0),
591 page_size_choices => [ @PAGE_SIZES ],
592 );
593 443 return ($page, $per_page, $offset);
594 }
595  
596 # _page_size_preference($self) -> $size | undef
597 #
598 # The page size set on /preferences, from the bi_per_page cookie: one of
599 # @PAGE_SIZES (0 = every row), or undef when there is none or it is anything
600 # else.
601 429 ▶sub _page_size_preference {
Subroutine _page_size_preference: called CC=4 SCAR=19.7
602 429 my $self = $_[0];
603 429 my $value = $self->cookie($PAGE_SIZE_COOKIE);
604 429 ▶ return undef unless defined $value && $value =~ /\A[0-9]{1,4}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value =~ /\A[0-9]{1,4}\z/u 429 0 429
Condition33%1/3
defined $value and $value =~ /\A[0-9]{1,4}\z/u
!ll&&!rl&&r
42900
MC/DC0%0/2
defined $value and $value =~ /\A[0-9]{1,4}\z/u
defined $value $value =~ /\A[0-9]{1,4}\z/u
Truth table33%1/3
A and B
A= defined $valueB= $value =~ /\A[0-9]{1,4}\z/u
ABresult
0X0
100
111
605 0 $value += 0;
606 0 ▶ return $PAGE_SIZE_OK{$value} ? $value : undef;
Branch: 1 branch
BranchTrueFalseTotal
$PAGE_SIZE_OK{$value} ? : 0 0 0
607 }
608  
609 # _message_text($key) -> $template | undef
610 #
611 # The %MESSAGES template for $key in the reader's language (Database::BI::I18N,
612 # which CGI::Lingua chose from the request's Accept-Language). A plain function:
613 # the package-level checks (request_refusal, _outside_roots) have no $self.
614 1199 ▶sub _message_text ($key) {
Subroutine _message_text: called CC=1 SCAR=0.0
615 1199 return Database::BI::I18N::text(__PACKAGE__, \%MESSAGES, $key);
616 }
617  
618 # _i18n($self, $key, @sprintf_args) -> $string
619 #
620 # Purpose: Look up a user-visible string from %MESSAGES and apply sprintf
621 # for positional arguments. The entry point for future i18n
622 # backend integration (e.g. Locale::Maketext).
623 # Entry: $key must be a key in %MESSAGES; @args are sprintf positionals.
624 # Exit: Returns the formatted string, or a fallback containing $key.
625 675 ▶sub _i18n :Protected ($self, $key, @args) {
Subroutine _i18n: called CC=3 SCAR=11.0
626 675 ▶ my $tmpl = _message_text($key) // return "Internal error: unknown message key '$key'";
Condition100%2/2
_message_text($key) // (return "Internal error: unknown message key '${key}'")
l!l
6741
MC/DC100%1/1
_message_text($key) // (return "Internal error: unknown message key '${key}'")
_message_text($key)
Truth table100%2/2
A
A= _message_text($key)
Aresult
11
00
627 674 ▶ return @args ? sprintf($tmpl, @args) : $tmpl;
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 373 301 674
628 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
629  
630 # _file_roots($self) -> @roots
631 #
632 # Purpose: The folders a reader may browse, open files in and export to.
633 # Entry: Config file_roots: unset or [] for the whole filesystem, else a list
634 # of folders (a relative one is under the application home).
635 # Exit: () when unrestricted; otherwise the realpath of each root that
636 # exists, plus data_dir and uploads_dir, which the application itself
637 # uses (the home page lists data_dir; dropped files go to uploads_dir).
638 764 ▶sub _file_roots :Protected ($self) {
Subroutine _file_roots: called CC=3 SCAR=11.0
639 764 my $roots = $self->app->config('file_roots');
640 764 ▶ return () unless ref($roots) eq 'ARRAY' && @{$roots};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $roots eq "ARRAY" and @{$roots;} 763 1 764
Condition66%2/3
ref $roots eq "ARRAY" and @{$roots;}
!ll&&!rl&&r
76301
MC/DC50%1/2
ref $roots eq "ARRAY" and @{$roots;}
ref $roots eq "ARRAY" @{$roots;}
Truth table66%2/3
A and B
A= ref $roots eq "ARRAY"B= @{$roots;}
ABresult
0X0
100
111
641 1 return _real_folders($self, $roots, _data_dir_for($self->app), $self->app->_uploads_dir);
642 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
643  
644 # _export_dirs($self) -> @realpaths
645 #
646 # Config export_dirs, as realpaths: the only folders POST /export may write
647 # in, and the Export panel may list, when set. Empty when unset.
648 62 ▶sub _export_dirs :Protected ($self) {
Subroutine _export_dirs: called CC=3 SCAR=11.0
649 62 my $dirs = $self->app->config('export_dirs');
650 62 ▶ return () unless ref($dirs) eq 'ARRAY' && @{$dirs};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $dirs eq "ARRAY" and @{$dirs;} 61 1 62
Condition66%2/3
ref $dirs eq "ARRAY" and @{$dirs;}
!ll&&!rl&&r
6101
MC/DC50%1/2
ref $dirs eq "ARRAY" and @{$dirs;}
ref $dirs eq "ARRAY" @{$dirs;}
Truth table66%2/3
A and B
A= ref $dirs eq "ARRAY"B= @{$dirs;}
ABresult
0X0
100
111
651 1 return _real_folders($self, $dirs);
652 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
653  
654 # _real_folders($self, \@configured, @always) -> @realpaths
655 #
656 # The configured folders (relative ones under the application home) and
657 # @always, resolved, without repeats. A list none of which resolves gives a
658 # folder that cannot exist, so that it fences everything out rather than
659 # nothing. Resolved as a requested path is (_resolved_path), so a folder
660 # configured through a link is compared as the folder it leads to: on
661 # Windows realpath keeps the link, while _resolved_path follows it, and every
662 # path inside such a folder was refused.
663 2 ▶sub _real_folders {
Subroutine _real_folders: called CC=9 SCAR=24.6
664 2 my ($self, $list, @always) = @_;
665 2 my $home = $self->app->home;
666 2 ▶ my @dirs = map { File::Spec->file_name_is_absolute($_) ? Mojo::File->new($_) : $home->child($_) }
Branch: 1 branch
BranchTrueFalseTotal
'File::Spec'->file_name_is_absolute($_) ? : 2 0 2
667 2 ▶ grep { defined && !ref && length } @{$list};
Condition33%2/6
defined $_ && !ref($_) && length $_
!ll&&!rl&&r
002
defined $_ and not ref $_
!ll&&!rl&&r
002
MC/DC0%0/3
defined $_ && !ref($_) && length $_
defined $_ not ref $_ length $_
Truth table25%1/4
A and not(B) && C
A= defined $_B= not ref $_C= length $_
ABCresult
0XX0
10X0
1100
1111
668 2 my (%seen, @real);
669 2 for my $dir (@dirs, @always) {
670 4 ▶ next unless -e "$dir";
Branch: 1 branch
BranchTrueFalseTotal
unless -e "$dir" 0 4 4
671 4 ▶ my $real = _resolved_path("$dir") // next;
Condition50%1/2
_resolved_path("$dir") // (next)
l!l
40
MC/DC0%0/1
_resolved_path("$dir") // (next)
_resolved_path("$dir")
Truth table50%1/2
A
A= _resolved_path("$dir")
Aresult
11
00
672 4 ▶ push @real, $real unless $seen{$real}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$real}++ 4 0 4
673 }
674 2 ▶ return @real ? @real : ('/nonexistent-file-root');
Branch: 1 branch
BranchTrueFalseTotal
@real ? : 2 0 2
675 }
676  
677 # _inside_any($path, @folders) -> 1 | 0
678 #
679 # Whether a path, resolved as _resolved_path does, is one of the folders or
680 # inside one.
681 4 ▶sub _inside_any {
Subroutine _inside_any: called CC=9 SCAR=24.6
682 4 my ($path, @folders) = @_;
683 4 ▶ my $abs = defined $path && length $path ? _resolved_path($path) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $path && length $path ? : 4 0 4
Condition33%1/3
defined $path and length $path
!ll&&!rl&&r
004
MC/DC0%0/2
defined $path and length $path
defined $path length $path
Truth table33%1/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
684 4 ▶ return 0 unless defined $abs;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $abs 0 4 4
685 4 $abs = _path_key($abs);
686 4 for my $root (map { _path_key($_) } @folders) {
687 6 ▶ return 1 if $root eq '/' || $abs eq $root
Branch: 2 branches
BranchTrueFalseTotal
if $root eq "/" or $abs eq $root or CORE::index($abs, $root =~ m[/\z]u ? $root : "$root/") == 0 1 5 6
$root =~ m[/\z]u ? : 0 6 6
Condition50%3/6
$root eq "/" or $abs eq $root or CORE::index($abs, $root =~ m[/\z]u ? $root : "$root/") == 0
l!l&&r!l&&!r
015
$root eq "/" or $abs eq $root
l!l&&r!l&&!r
006
MC/DC33%1/3
$root eq "/" or $abs eq $root or CORE::index($abs, $root =~ m[/\z]u ? $root : "$root/") == 0
$root eq "/" $abs eq $root CORE::index($abs, $root =~ m[/\z]u ? $root : "$root/") == 0
Truth table50%2/4
A or B or C
A= $root eq "/"B= $abs eq $rootC= CORE::index($abs, $root =~ m[/\z]u ? $root : "$root/") == 0
ABCresult
1XX1
01X1
0011
0000
688 || index($abs, $root =~ m{/\z} ? $root : "$root/") == 0;
689 }
690 3 return 0;
691 }
692  
693 # _path_key($path) -> $string
694 #
695 # A path in the form two spellings of one place share, for comparing. On
696 # Windows, Cwd::realpath gives C:/dir while File::Spec gives C:\dir, and names
697 # are not case-sensitive, so separators become / and letters lower case.
698 10 ▶sub _path_key {
Subroutine _path_key: called CC=2 SCAR=6.9
699 10 my ($path) = @_;
700 10 ▶ return $path unless $^O eq 'MSWin32';
Branch: 1 branch
BranchTrueFalseTotal
unless $^O eq "MSWin32" 6 4 10
701 4 (my $key = $path) =~ tr{\\}{/};
702 4 return lc $key;
703 }
704  
705 # _outside_export_dirs($self, $path) -> $message | undef
706 #
707 # Purpose: Refuse an export folder outside config export_dirs.
708 # Exit: undef when export_dirs is unset or the folder is inside one.
709 60 ▶sub _outside_export_dirs :Protected ($self, $path) {
Subroutine _outside_export_dirs: called CC=4 SCAR=14.3
710 60 ▶ my @dirs = _export_dirs($self) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my(@dirs) = _export_dirs($self) or return undef 1 59 60
711 1 ▶ return undef if _inside_any($path, @dirs);
Branch: 1 branch
BranchTrueFalseTotal
if _inside_any($path, @dirs) 0 1 1
712 1 ▶ return sprintf(_message_text('error_outside_export_dirs'), $path // '');
Condition50%1/2
$path // ""
l!l
10
MC/DC0%0/1
$path // ""
$path
Truth table50%1/2
A
A= $path
Aresult
11
00
713 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
714  
715 # _resolved_path($path) -> $absolute | undef
716 #
717 # Purpose: Where a path really leads, whether or not it exists, so that a
718 # path outside the roots is refused the same way whether it names
719 # something or not (else the refusal would say what exists there).
720 # Entry: A path as given.
721 # Exit: The realpath of its longest existing part, with the rest appended;
722 # undef when the rest climbs with '..', which cannot be followed
723 # without the folders it would climb out of, or when, on Windows,
724 # the links it goes through loop.
725 12 ▶sub _resolved_path {
Subroutine _resolved_path: called CC=9 SCAR=22.3
726 12 my ($path) = @_;
727 12 my $abs = File::Spec->rel2abs($path);
728 # Cwd::realpath on Windows leaves a symlink as it is (Strawberry Perl
729 # 5.42 gives the link's own path back), so a link inside file_roots or
730 # export_dirs that points outside would be taken as inside. The links are
731 # followed first, as _canonical_path does; a chain that loops is refused.
732 12 ▶ if ($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq "MSWin32") 5 7 12
733 5 ▶ $abs = _follow_links($abs) // return undef;
Condition100%2/2
_follow_links($abs) // (return undef)
l!l
41
MC/DC100%1/1
_follow_links($abs) // (return undef)
_follow_links($abs)
Truth table100%2/2
A
A= _follow_links($abs)
Aresult
11
00
734 }
735 11 my @parts = File::Spec->splitdir($abs);
736 11 my @rest;
737 11 ▶ while (@parts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parts) 13 0 13
738 13 my $try = File::Spec->catdir(@parts);
739 13 ▶ $try = File::Spec->rootdir unless length $try;
Branch: 1 branch
BranchTrueFalseTotal
unless length $try 0 13 13
740 13 ▶ if (-e $try) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $try) 11 2 13
741 11 ▶ my $real = eval { Mojo::File->new($try)->realpath->to_string } // return undef;
Condition50%1/2
eval { do { "Mojo::File"->new($try)->realpath->to_string } } // (return undef)
l!l
110
MC/DC0%0/1
eval { do { "Mojo::File"->new($try)->realpath->to_string } } // (return undef)
eval { do { "Mojo::File"->new($try)->realpath->to_string } }
Truth table50%1/2
A
A= eval { do { "Mojo::File"->new($try)->realpath->to_string } }
Aresult
11
00
742 11 ▶ return undef if grep { $_ eq '..' } @rest;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_ eq "..";} @rest 0 11 11
743 11 ▶ return @rest ? File::Spec->catdir($real, @rest) : $real;
Branch: 1 branch
BranchTrueFalseTotal
@rest ? : 1 10 11
744 }
745 2 unshift @rest, pop @parts;
746 }
747 0 return undef;
748 }
749  
750 # _outside_roots($self, $path) -> $message | undef
751 #
752 # Purpose: Refuse a local path outside config file_roots.
753 # Entry: A path a request named (a file or a folder).
754 # Exit: undef when there are no roots or the path is inside one; otherwise
755 # error_outside_roots naming the path as it was given.
756 764 ▶sub _outside_roots :Protected ($self, $path) {
Subroutine _outside_roots: called CC=4 SCAR=14.3
757 764 ▶ my @roots = _file_roots($self) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my(@roots) = _file_roots($self) or return undef 1 763 764
758 1 ▶ return undef if _inside_any($path, @roots);
Branch: 1 branch
BranchTrueFalseTotal
if _inside_any($path, @roots) 0 1 1
759 1 ▶ return sprintf(_message_text('error_outside_roots'), $path // '');
Condition50%1/2
$path // ""
l!l
10
MC/DC0%0/1
$path // ""
$path
Truth table50%1/2
A
A= $path
Aresult
11
00
760 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
761  
762 # _first_root($self) -> $folder
763 #
764 # Where /browse and /api/dirs start with no path=: the home folder, unless
765 # that is outside the roots, when the first root is.
766 46 ▶sub _first_root :Protected ($self) {
Subroutine _first_root: called CC=3 SCAR=14.2
767 46 ▶ my $home = $ENV{HOME} // File::Spec->rootdir;
Condition33%1/3
$ENV{"HOME"} // "File::Spec"->rootdir
l!l&&r!l&&!r
4600
MC/DC0%0/2
$ENV{"HOME"} // "File::Spec"->rootdir
$ENV{"HOME"} "File::Spec"->rootdir
Truth table33%1/3
A // B
A= $ENV{"HOME"}B= "File::Spec"->rootdir
ABresult
1X1
011
000
768 46 ▶ return $home unless _outside_roots($self, $home);
Branch: 1 branch
BranchTrueFalseTotal
unless _outside_roots($self, $home) 46 0 46
769 0 return (_file_roots($self))[0];
770 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
771  
772 # request_refusal($c) -> $message | undef
773 #
774 # Purpose: Refuse a request that a hostile web page made through the reader's
775 # browser. The application has no login, so whatever can reach it
776 # can write files (POST /export) and read any file (/open); listening
777 # on 127.0.0.1 keeps other machines out but not other sites' pages.
778 # Entry: A controller of the application, before dispatch.
779 # Exit: The refusal message, or undef to let the request through.
780 #
781 # Three checks:
782 # * No password, so only this machine: a request from an address that is
783 # not loopback (as a trusted proxy reports it) is refused.
784 # * DNS rebinding. A page on evil.example whose name is made to resolve to
785 # 127.0.0.1 is the same origin as this server to the browser, so it can
786 # read the replies too. It still names its own host, so the Host must be
787 # localhost, *.localhost, an IP address, or a name in config allowed_hosts
788 # (['*'] lets every name in). Behind a trusted reverse proxy, whose Host is
789 # whatever the proxy sends, only allowed_hosts is checked, when it is set.
790 # * Cross-site writes. A form POST from another site needs no preflight.
791 # For any method but GET, HEAD and OPTIONS, Sec-Fetch-Site (set by the
792 # browser, not the page) must be same-origin or none; without it, an
793 # Origin must name this host and port. A request with neither is a
794 # script or an old browser, and is let through: it is not a page of
795 # another site acting with the reader's browser.
796 3294 ▶sub request_refusal {
Subroutine request_refusal: called CC=35 SCAR=50.4
Pod documented
797 3294 my ($c) = @_;
798 3294 my $req = $c->req;
799  
800 # With no password, only this machine. Startup already refuses to listen
801 # anywhere else, but a reverse proxy on this machine can still bring other
802 # machines' requests in; trusted, it names them in X-Forwarded-For, which
803 # is what remote_address then reads. A Unix socket has no address, and is
804 # this machine.
805 3294 my $hash = $c->app->config('password_hash');
806 3294 ▶ unless (defined $hash && length $hash) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $hash and length $hash) 3282 12 3294
Condition66%2/3
defined $hash and length $hash
!ll&&!rl&&r
3282012
MC/DC50%1/2
defined $hash and length $hash
defined $hash length $hash
Truth table66%2/3
A and B
A= defined $hashB= length $hash
ABresult
0X0
100
111
807 3282 ▶ my $from = $c->tx->remote_address // '';
Condition50%1/2
$c->tx->remote_address // ""
l!l
32820
MC/DC0%0/1
$c->tx->remote_address // ""
$c->tx->remote_address
Truth table50%1/2
A
A= $c->tx->remote_address
Aresult
11
00
808 3282 ▶ return _message_text('error_remote_needs_password')
Branch: 1 branch
BranchTrueFalseTotal
unless $from eq "" or $from =~ /\A(?:::ffff:)?127\./iu or $from eq "::1" 1 3281 3282
Condition66%4/6
$from eq "" or $from =~ /\A(?:::ffff:)?127\./iu or $from eq "::1"
l!l&&r!l&&!r
328101
$from eq "" or $from =~ /\A(?:::ffff:)?127\./iu
l!l&&r!l&&!r
032811
MC/DC33%1/3
$from eq "" or $from =~ /\A(?:::ffff:)?127\./iu or $from eq "::1"
$from eq "" $from =~ /\A(?:::ffff:)?127\./iu $from eq "::1"
Truth table50%2/4
A or B or C
A= $from eq ""B= $from =~ /\A(?:::ffff:)?127\./iuC= $from eq "::1"
ABCresult
1XX1
01X1
0011
0000
809 unless $from eq '' || $from =~ /\A(?:::ffff:)?127\./i || $from eq '::1';
810 }
811  
812 3293 ▶ my $host = lc($req->url->to_abs->host // '');
Condition50%1/2
$req->url->to_abs->host // ""
l!l
32930
MC/DC0%0/1
$req->url->to_abs->host // ""
$req->url->to_abs->host
Truth table50%1/2
A
A= $req->url->to_abs->host
Aresult
11
00
813 3293 ▶ if (length $host) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $host) 3293 0 3293
814 3293 my $allowed = $c->app->config('allowed_hosts');
815 0 ▶ my @allowed = ref($allowed) eq 'ARRAY' ? map { lc } grep { defined && !ref } @{$allowed} : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $allowed eq 'ARRAY' ? : 0 3293 3293
Condition0%0/3
defined $_ && !ref($_)
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_ && !ref($_)
defined $_ !ref($_)
Truth table0%0/3
A && not(B)
A= defined $_B= !ref($_)
ABresult
0X0
100
111
816 0 ▶ my $listed = grep { $_ eq '*' || $_ eq $host || (/\A\*(\..+)\z/ && substr($host, -length $1) eq $1) } @allowed;
Condition0%0/9
$_ eq '*' || $_ eq $host || /\A\*(\..+)\z/u && substr($host, -length($1)) eq $1
l!l&&r!l&&!r
000
$_ eq "*" or $_ eq $host
l!l&&r!l&&!r
000
/\A\*(\..+)\z/u and substr($host, -length($1)) eq $1
!ll&&!rl&&r
000
MC/DC0%0/4
$_ eq '*' || $_ eq $host || /\A\*(\..+)\z/u && substr($host, -length($1)) eq $1
$_ eq "*" $_ eq $host /\A\*(\..+)\z/u substr($host, -length($1)) eq $1
Truth table0%0/5
A or B || C and D
A= $_ eq "*"B= $_ eq $hostC= /\A\*(\..+)\z/uD= substr($host, -length($1)) eq $1
ABCDresult
1XXX1
01XX1
00111
000X0
00100
817 3293 ▶ my $local = $host eq 'localhost' || $host =~ /\.localhost\z/
Condition55%5/9
$host eq 'localhost' || $host =~ /\.localhost\z/u || $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/u || $host =~ /[:\[]/u
l!l&&r!l&&!r
329201
$host eq "localhost" or $host =~ /\.localhost\z/u or $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/u
l!l&&r!l&&!r
032921
$host eq "localhost" or $host =~ /\.localhost\z/u
l!l&&r!l&&!r
003293
MC/DC25%1/4
$host eq 'localhost' || $host =~ /\.localhost\z/u || $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/u || $host =~ /[:\[]/u
$host eq "localhost" $host =~ /\.localhost\z/u $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/u $host =~ /[:\[]/u
Truth table40%2/5
A or B or C || D
A= $host eq "localhost"B= $host =~ /\.localhost\z/uC= $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/uD= $host =~ /[:\[]/u
ABCDresult
1XXX1
01XX1
001X1
00011
00000
818 || $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/ || $host =~ /[:\[]/;
819 3293 ▶ my $ok = $req->reverse_proxy ? (!@allowed || $listed) : ($local || $listed);
Branch: 1 branch
BranchTrueFalseTotal
$req->reverse_proxy ? : 0 3293 3293
Condition33%2/6
not @allowed or $listed
l!l&&r!l&&!r
000
$local or $listed
l!l&&r!l&&!r
329201
MC/DC0%0/2
not @allowed or $listed
not @allowed $listed
MC/DC50%1/2
$local or $listed
$local $listed
Truth table0%0/3
not(A) or B
A= not @allowedB= $listed
ABresult
1X1
011
000
Truth table66%2/3
A or B
A= $localB= $listed
ABresult
1X1
011
000
820 3293 ▶ return sprintf(_message_text('error_host_refused'), $host) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 1 3292 3293
821 }
822  
823 3292 ▶ return if $req->method =~ /\A(?:GET|HEAD|OPTIONS)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $req->method =~ /\A(?:GET|HEAD|OPTIONS)\z/u 2686 606 3292
824  
825 606 my $headers = $req->headers;
826 606 ▶ my $site = lc($headers->header('Sec-Fetch-Site') // '');
Condition50%1/2
$headers->header("Sec-Fetch-Site") // ""
l!l
0606
MC/DC0%0/1
$headers->header("Sec-Fetch-Site") // ""
$headers->header("Sec-Fetch-Site")
Truth table50%1/2
A
A= $headers->header("Sec-Fetch-Site")
Aresult
11
00
827 606 ▶ if (length $site) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $site) 0 606 606
828 0 ▶ return if $site eq 'same-origin' || $site eq 'none';
Branch: 1 branch
BranchTrueFalseTotal
if $site eq "same-origin" or $site eq "none" 0 0 0
Condition0%0/3
$site eq "same-origin" or $site eq "none"
l!l&&r!l&&!r
000
MC/DC0%0/2
$site eq "same-origin" or $site eq "none"
$site eq "same-origin" $site eq "none"
Truth table0%0/3
A or B
A= $site eq "same-origin"B= $site eq "none"
ABresult
1X1
011
000
829 0 return sprintf(_message_text('error_cross_site'), $site);
830 }
831 606 my $origin = $headers->origin;
832 606 ▶ return unless defined $origin;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $origin 605 1 606
833 1 ▶ my $from = lc(Mojo::URL->new($origin)->host_port // '');
Condition50%1/2
"Mojo::URL"->new($origin)->host_port // ""
l!l
10
MC/DC0%0/1
"Mojo::URL"->new($origin)->host_port // ""
"Mojo::URL"->new($origin)->host_port
Truth table50%1/2
A
A= "Mojo::URL"->new($origin)->host_port
Aresult
11
00
834 1 ▶ my $to = lc($req->url->to_abs->host_port // '');
Condition50%1/2
$req->url->to_abs->host_port // ""
l!l
10
MC/DC0%0/1
$req->url->to_abs->host_port // ""
$req->url->to_abs->host_port
Truth table50%1/2
A
A= $req->url->to_abs->host_port
Aresult
11
00
835 1 ▶ my $fwd = $req->reverse_proxy ? lc($headers->header('X-Forwarded-Host') // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
$req->reverse_proxy ? : 0 1 1
Condition0%0/2
$headers->header("X-Forwarded-Host") // ""
l!l
00
MC/DC0%0/1
$headers->header("X-Forwarded-Host") // ""
$headers->header("X-Forwarded-Host")
Truth table0%0/2
A
A= $headers->header("X-Forwarded-Host")
Aresult
11
00
836 1 ▶ return if length($from) && ($from eq $to || (length($fwd) && $from eq $fwd));
Branch: 1 branch
BranchTrueFalseTotal
if length $from and $from eq $to || length $fwd && $from eq $fwd 0 1 1
Condition33%3/9
length $from and $from eq $to || length $fwd && $from eq $fwd
!ll&&!rl&&r
010
$from eq $to or length $fwd and $from eq $fwd
l!l&&r!l&&!r
001
length $fwd and $from eq $fwd
!ll&&!rl&&r
100
MC/DC0%0/4
length $from and $from eq $to || length $fwd && $from eq $fwd
length $from $from eq $to length $fwd $from eq $fwd
Truth table20%1/5
A and B or C and D
A= length $fromB= $from eq $toC= length $fwdD= $from eq $fwd
ABCDresult
0XXX0
100X0
10100
11XX1
10111
837 1 return sprintf(_message_text('error_cross_site'), $origin);
838 }
839  
840 # _is_safe_url($url) -> bool
841 #
842 # Purpose: The quick SSRF check on a URL a request names (/import, url:
843 # specs), before anything is fetched, so the reader is told at once.
844 # Entry: The URL.
845 # Exit: 0 for anything but http(s), no host, localhost or *.localhost, or a
846 # host written as an address that is not public; else 1.
847 #
848 # It reads the URL as LWP will (URI: so http://user@127.0.0.1/ is host
849 # 127.0.0.1), and an address in every spelling the resolver accepts
850 # (2130706433, 0x7f000001, 0177.0.0.1, 127.1, [::ffff:127.0.0.1]). It does not
851 # look names up: a name such as localtest.me, or one whose DNS answers
852 # 127.0.0.1, is refused when it is fetched, by Database::BI::SafeUA, which
853 # resolves each request (and each redirect), checks every address, and
854 # connects to the one it checked, so a second DNS answer cannot differ.
855 145 ▶sub _is_safe_url {
Subroutine _is_safe_url: called CC=13 SCAR=25.9
856 145 my ($url) = @_;
857 145 ▶ return 0 unless defined $url && $url =~ m{\Ahttps?://}i;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and $url =~ m[\Ahttps?://]iu 9 136 145
Condition66%2/3
defined $url and $url =~ m[\Ahttps?://]iu
!ll&&!rl&&r
09136
MC/DC50%1/2
defined $url and $url =~ m[\Ahttps?://]iu
defined $url $url =~ m[\Ahttps?://]iu
Truth table66%2/3
A and B
A= defined $urlB= $url =~ m[\Ahttps?://]iu
ABresult
0X0
100
111
858 136 require URI;
859 136 require Database::BI::SafeUA;
860 136 my $uri = URI->new($url);
861 136 ▶ my $host = eval { lc($uri->host // '') } // '';
Condition50%2/4
eval { do { lc($uri->host // "") } } // ""
l!l
1360
$uri->host // ""
l!l
1360
MC/DC0%0/1
eval { do { lc($uri->host // "") } } // ""
eval { do { lc($uri->host // "") } }
MC/DC0%0/1
$uri->host // ""
$uri->host
Truth table50%1/2
A
A= eval { do { lc($uri->host // "") } }
Aresult
11
00
Truth table50%1/2
A
A= $uri->host
Aresult
11
00
862 136 $host =~ s/\.\z//;
863 136 ▶ return 0 unless length $host;
Branch: 1 branch
BranchTrueFalseTotal
unless length $host 0 136 136
864 # A host that is neither a name nor an IPv6 address is not a URL LWP
865 # would read the same way (http://::1/ has the host ':').
866 136 ▶ return 0 unless $host =~ /\A[a-z0-9_](?:[a-z0-9_.-]*[a-z0-9_])?\z/
Branch: 1 branch
BranchTrueFalseTotal
unless $host =~ /\A[a-z0-9_](?:[a-z0-9_.-]*[a-z0-9_])?\z/u or $host =~ /:/u and defined Database::BI::SafeUA::numeric_host($host) 1 135 136
Condition83%5/6
$host =~ /\A[a-z0-9_](?:[a-z0-9_.-]*[a-z0-9_])?\z/u or $host =~ /:/u and defined Database::BI::SafeUA::numeric_host($host)
l!l&&r!l&&!r
13051
$host =~ /:/u and defined Database::BI::SafeUA::numeric_host($host)
!ll&&!rl&&r
015
MC/DC66%2/3
$host =~ /\A[a-z0-9_](?:[a-z0-9_.-]*[a-z0-9_])?\z/u or $host =~ /:/u and defined Database::BI::SafeUA::numeric_host($host)
$host =~ /\A[a-z0-9_](?:[a-z0-9_.-]*[a-z0-9_])?\z/u $host =~ /:/u defined Database::BI::SafeUA::numeric_host($host)
Truth table75%3/4
A or B and C
A= $host =~ /\A[a-z0-9_](?:[a-z0-9_.-]*[a-z0-9_])?\z/uB= $host =~ /:/uC= defined Database::BI::SafeUA::numeric_host($host)
ABCresult
1XX1
0111
00X0
0100
867 || ($host =~ /:/ && defined Database::BI::SafeUA::numeric_host($host));
868 135 ▶ return 0 if $host eq 'localhost' || $host =~ /\.localhost\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $host eq "localhost" or $host =~ /\.localhost\z/u 12 123 135
Condition100%3/3
$host eq "localhost" or $host =~ /\.localhost\z/u
l!l&&r!l&&!r
111123
MC/DC100%2/2
$host eq "localhost" or $host =~ /\.localhost\z/u
$host eq "localhost" $host =~ /\.localhost\z/u
Truth table100%3/3
A or B
A= $host eq "localhost"B= $host =~ /\.localhost\z/u
ABresult
1X1
011
000
869 123 my $ip = Database::BI::SafeUA::numeric_host($host);
870 123 ▶ return 0 if defined $ip && Database::BI::SafeUA::blocked_address($ip);
Branch: 1 branch
BranchTrueFalseTotal
if defined $ip and Database::BI::SafeUA::blocked_address($ip) 55 68 123
Condition100%3/3
defined $ip and Database::BI::SafeUA::blocked_address($ip)
!ll&&!rl&&r
551355
MC/DC100%2/2
defined $ip and Database::BI::SafeUA::blocked_address($ip)
defined $ip Database::BI::SafeUA::blocked_address($ip)
Truth table100%3/3
A and B
A= defined $ipB= Database::BI::SafeUA::blocked_address($ip)
ABresult
0X0
100
111
871 68 return 1;
872 }
873  
874 # _safe_back_url($url) -> $url | undef
875 #
876 # Purpose: Sanitise a user-supplied back-link URL before it is passed to the
877 # template and rendered inside an href="" attribute. Template Toolkit's
878 # | html filter encodes <>&" but does NOT block the javascript: or
879 # data: URI schemes, so a raw param('back') = "javascript:alert(1)"
880 # would be rendered verbatim inside the href and execute on click.
881 #
882 # Rule: Only absolute http(s) URLs and root-relative paths (starting with /)
883 # are permitted. Anything else (javascript:, data:, vbscript:, empty
884 # strings, undef) returns undef so the template renders no href.
885 #
886 6916 ▶sub _safe_back_url {
Subroutine _safe_back_url: called CC=4 SCAR=13.9
887 6916 my ($url) = @_;
888 6916 ▶ return undef unless defined $url && length($url);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and length $url 5526 1390 6916
Condition100%3/3
defined $url and length $url
!ll&&!rl&&r
5480461390
MC/DC100%2/2
defined $url and length $url
defined $url length $url
Truth table100%3/3
A and B
A= defined $urlB= length $url
ABresult
0X0
100
111
889 1390 ▶ return $url if $url =~ m{\A(?:/(?!/)|https?://)}i;
Branch: 1 branch
BranchTrueFalseTotal
if $url =~ m[\A(?:/(?!/)|https?://)]iu 1298 92 1390
890 92 return undef;
891 }
892  
893 # ---------------------------------------------------------------------------
894 # Breadcrumb trail
895 # ---------------------------------------------------------------------------
896 #
897 # Every page shows Home > ... > the page itself. The trail is not passed in:
898 # each page's URL already names the page it was opened from (a chart's back=,
899 # a table's back2= when it was drilled into from a chart), and that URL names
900 # its own, so the whole path is recovered by following the links up. Each
901 # step is named from its own URL by one function, so a crumb always reads the
902 # same whichever page it appears on.
903  
904 # The chart and analysis routes, which name their parent with back=.
905 10 Readonly my %CRUMB_KIND => (
906 graph => 'Line graph', line => 'Line graph',
907 pie => 'Pie chart', heatmap => 'Heatmap',
908 bar => 'Bar chart', stacked => 'Stacked bar chart',
909 scatter => 'Scatter plot', combo => 'Combo chart',
910 treemap => 'Treemap', histogram => 'Histogram',
911 wordcloud => 'Word cloud', map => 'Map',
912 pivot => 'Pivot table', stats => 'Column stats',
913 insights => 'Insights', folder => 'Folder view',
914 );
915  
916 # How a filter reads in a crumb: "region = East".
917 10 Readonly my %CRUMB_OP => (
918 eq => '=', ne => '!=', contains => 'contains', starts => 'starts with',
919 lt => '<', le => '<=', gt => '>', ge => '>=', between => 'between',
920 empty => 'is empty', notempty => 'is not empty', in => 'is one of',
921 differ => 'differs from',
922 );
923  
924 # A trail is never longer than this, whatever the URLs say.
925 10 Readonly my $CRUMB_MAX_DEPTH => 8;
926  
927 # A column name or filter value that a crumb will repeat. The URL is the
928 # user's, so a crafted one could put any text in the trail; markup and
929 # over-long values are left out and the crumb names the page more generally.
930 10 Readonly my $CRUMB_TEXT_RE => qr/\A[^<>"\x00-\x1f]{1,64}\z/;
931  
932 # _breadcrumb_trail($c) -> \@crumbs
933 #
934 # Purpose: The pages between Home and this one, this one last: a list of
935 # { label, url }. Home itself is not in the list; the template
936 # always puts it first.
937 # Entry: $c -- the controller for the request. A plain function, called
938 # from the before_render hook in Database::BI, so every page gets a
939 # trail without per-action code.
940 # Exit: An arrayref, empty for Home and for a controller that is not this
941 # class (a 404 page rendered by Mojolicious itself).
942 # Notes: A parent is followed only when _safe_back_url accepts it and it is
943 # on this host; a loop or the depth cap ends the trail, so a crafted
944 # URL can make it short but never wrong or endless.
945 3313 ▶sub _breadcrumb_trail {
Subroutine _breadcrumb_trail: called CC=8 SCAR=20.8
946 3313 my ($c) = @_;
947 3313 ▶ return [] unless ref $c && $c->isa(__PACKAGE__);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $c and $c->isa(__PACKAGE__) 234 3079 3313
Condition100%3/3
ref $c and $c->isa(__PACKAGE__)
!ll&&!rl&&r
22323079
MC/DC100%2/2
ref $c and $c->isa(__PACKAGE__)
ref $c $c->isa(__PACKAGE__)
Truth table100%3/3
A and B
A= ref $cB= $c->isa(__PACKAGE__)
ABresult
0X0
100
111
948  
949 3079 my @trail;
950 my %seen;
951 3079 my $url = Mojo::URL->new($c->req->url->path_query);
952 3079 ▶ while ($url && @trail < $CRUMB_MAX_DEPTH) {
Branch: 1 branch
BranchTrueFalseTotal
if ($url and @trail < $CRUMB_MAX_DEPTH) 4677 1760 6437
Condition100%3/3
$url and @trail < $CRUMB_MAX_DEPTH
!ll&&!rl&&r
175914677
MC/DC100%2/2
$url and @trail < $CRUMB_MAX_DEPTH
$url @trail < $CRUMB_MAX_DEPTH
Truth table100%3/3
A and B
A= $urlB= @trail < $CRUMB_MAX_DEPTH
ABresult
0X0
100
111
953 4677 my $key = $url->path_query;
954 4677 ▶ last if $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$key}++ 0 4677 4677
955 4677 my $label = $c->_crumb_label($url);
956 4677 ▶ last unless defined $label && length $label;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $label and length $label 1319 3358 4677
Condition100%3/3
defined $label and length $label
!ll&&!rl&&r
131813358
MC/DC100%2/2
defined $label and length $label
defined $label length $label
Truth table100%3/3
A and B
A= defined $labelB= length $label
ABresult
0X0
100
111
957 3358 unshift @trail, { label => $label, url => $key };
958 3358 $url = $c->_crumb_parent($url);
959 }
960 3079 return \@trail;
961 }
962  
963 # _preferences_url($c) -> $href
964 #
965 # Where the nav's Preferences link goes: /preferences?back=<this page>, so
966 # the preferences page's trail ends with a way back here. This page is the
967 # last crumb of its trail; a page with no trail (Home, an error page) gets the
968 # plain link, and so does the preferences page, which keeps its own back=.
969 # A plain function, called from the before_render hook in Database::BI.
970 3296 ▶sub _preferences_url {
Subroutine _preferences_url: called CC=8 SCAR=21.1
971 3296 my ($c) = @_;
972 3296 my $plain = '/preferences';
973 3296 ▶ return $plain unless ref $c && $c->isa(__PACKAGE__);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $c and $c->isa(__PACKAGE__) 232 3064 3296
Condition66%2/3
ref $c and $c->isa(__PACKAGE__)
!ll&&!rl&&r
02323064
MC/DC50%1/2
ref $c and $c->isa(__PACKAGE__)
ref $c $c->isa(__PACKAGE__)
Truth table66%2/3
A and B
A= ref $cB= $c->isa(__PACKAGE__)
ABresult
0X0
100
111
974 3064 my $trail = $c->stash('trail');
975 3064 ▶ return $plain unless ref $trail eq 'ARRAY' && @$trail;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $trail eq "ARRAY" and @$trail 1318 1746 3064
Condition66%2/3
ref $trail eq "ARRAY" and @$trail
!ll&&!rl&&r
013181746
MC/DC50%1/2
ref $trail eq "ARRAY" and @$trail
ref $trail eq "ARRAY" @$trail
Truth table66%2/3
A and B
A= ref $trail eq "ARRAY"B= @$trail
ABresult
0X0
100
111
976 1746 ▶ my $here = $trail->[-1]{url} // '';
Condition50%1/2
$trail->[-1]{"url"} // ""
l!l
17460
MC/DC0%0/1
$trail->[-1]{"url"} // ""
$trail->[-1]{"url"}
Truth table50%1/2
A
A= $trail->[-1]{"url"}
Aresult
11
00
977 1746 ▶ return $plain if !length($here) || Mojo::URL->new($here)->path->to_string eq $plain;
Branch: 1 branch
BranchTrueFalseTotal
if not length $here or "Mojo::URL"->new($here)->path->to_string eq $plain 1 1745 1746
Condition66%2/3
not length $here or "Mojo::URL"->new($here)->path->to_string eq $plain
l!l&&r!l&&!r
011745
MC/DC50%1/2
not length $here or "Mojo::URL"->new($here)->path->to_string eq $plain
not length $here "Mojo::URL"->new($here)->path->to_string eq $plain
Truth table66%2/3
not(A) or B
A= not length $hereB= "Mojo::URL"->new($here)->path->to_string eq $plain
ABresult
1X1
011
000
978 1745 return "$plain?back=" . url_escape(encode('UTF-8', $here));
979 }
980  
981 # _crumb_local($self, $raw) -> Mojo::URL | undef
982 #
983 # A parent link as a URL on this site, or undef when there is none to follow:
984 # empty, refused by _safe_back_url, on another host, or Home (which the trail
985 # shows anyway). Absolute links -- the panels pass window.location.href --
986 # are reduced to their path and query.
987 4394 ▶sub _crumb_local :Protected ($self, $raw) {
Subroutine _crumb_local: called CC=8 SCAR=21.0
988 4394 ▶ my $safe = _safe_back_url($raw) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $safe = _safe_back_url($raw) or return undef 1268 3126 4394
989 1268 my $url = Mojo::URL->new($safe);
990 1268 ▶ if (defined $url->host) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $url->host) 4 1264 1268
991 4 my $here = $self->req->url->to_abs;
992 4 ▶ return undef unless lc($url->host_port // '') eq lc($here->host_port // '');
Branch: 1 branch
BranchTrueFalseTotal
unless lc($url->host_port // "") eq lc($here->host_port // "") 3 1 4
Condition50%2/4
$url->host_port // ""
l!l
40
$here->host_port // ""
l!l
40
MC/DC0%0/1
$url->host_port // ""
$url->host_port
MC/DC0%0/1
$here->host_port // ""
$here->host_port
Truth table50%1/2
A
A= $url->host_port
Aresult
11
00
Truth table50%1/2
A
A= $here->host_port
Aresult
11
00
993 }
994 1265 my $path = $url->path->to_string;
995 1265 ▶ return undef if $path eq '' || $path eq '/';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "" or $path eq "/" 66 1199 1265
Condition66%2/3
$path eq "" or $path eq "/"
l!l&&r!l&&!r
0661199
MC/DC50%1/2
$path eq "" or $path eq "/"
$path eq "" $path eq "/"
Truth table66%2/3
A or B
A= $path eq ""B= $path eq "/"
ABresult
1X1
011
000
996 1199 return Mojo::URL->new($url->path_query);
997 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
998  
999 # _crumb_parent($self, $url) -> Mojo::URL | undef
1000 #
1001 # The page $url was opened from. A chart names it with back=. A table page
1002 # names it with back2= when it was drilled into from a chart, and otherwise
1003 # has a natural parent: the left table for a merge or a combine, the schema
1004 # page or the folder for a file, nothing for a table in data_dir.
1005 3371 ▶sub _crumb_parent :Protected ($self, $url) {
Subroutine _crumb_parent: called CC=23 SCAR=31.4
1006 3371 my $path = $url->path->to_string;
1007 3371 my $q = $url->query;
1008  
1009 3371 ▶ if ($path =~ m{\A/([a-z]+)\z} && $CRUMB_KIND{$1}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ m[\A/([a-z]+)\z]u and $CRUMB_KIND{$1}) 1119 2252 3371
Condition100%3/3
$path =~ m[\A/([a-z]+)\z]u and $CRUMB_KIND{$1}
!ll&&!rl&&r
116710851119
MC/DC100%2/2
$path =~ m[\A/([a-z]+)\z]u and $CRUMB_KIND{$1}
$path =~ m[\A/([a-z]+)\z]u $CRUMB_KIND{$1}
Truth table100%3/3
A and B
A= $path =~ m[\A/([a-z]+)\z]uB= $CRUMB_KIND{$1}
ABresult
0X0
100
111
1010 1119 ▶ return $self->_crumb_local($q->param('back'))
Condition100%5/5
$self->_crumb_local($q->param("back")) // $self->_crumb_local($self->_spec_to_url($q->param("l") // ""))
l!l&&r!l&&!r
19103565
$q->param("l") // ""
l!l
108218
MC/DC100%2/2
$self->_crumb_local($q->param("back")) // $self->_crumb_local($self->_spec_to_url($q->param("l") // ""))
$self->_crumb_local($q->param("back")) $self->_crumb_local($self->_spec_to_url($q->param("l") // ""))
MC/DC100%1/1
$q->param("l") // ""
$q->param("l")
Truth table100%3/3
A // B
A= $self->_crumb_local($q->param("back"))B= $self->_crumb_local($self->_spec_to_url($q->param("l") // ""))
ABresult
1X1
011
000
Truth table100%2/2
A
A= $q->param("l")
Aresult
11
00
1011 // $self->_crumb_local($self->_spec_to_url($q->param('l') // ''));
1012 }
1013 2252 ▶ if ($path =~ m{\A/view/} || $path eq '/import') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ m[\A/view/]u or $path eq "/import") 1148 1104 2252
Condition100%3/3
$path =~ m[\A/view/]u or $path eq "/import"
l!l&&r!l&&!r
1095531104
MC/DC100%2/2
$path =~ m[\A/view/]u or $path eq "/import"
$path =~ m[\A/view/]u $path eq "/import"
Truth table100%3/3
A or B
A= $path =~ m[\A/view/]uB= $path eq "/import"
ABresult
1X1
011
000
1014 1148 return $self->_crumb_local($q->param('back2'));
1015 }
1016 1104 ▶ if ($path eq '/join' || $path eq '/combine') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/join" or $path eq "/combine") 133 971 1104
Condition100%3/3
$path eq "/join" or $path eq "/combine"
l!l&&r!l&&!r
7657971
MC/DC100%2/2
$path eq "/join" or $path eq "/combine"
$path eq "/join" $path eq "/combine"
Truth table100%3/3
A or B
A= $path eq "/join"B= $path eq "/combine"
ABresult
1X1
011
000
1017 133 ▶ return $self->_crumb_local($q->param('back2'))
Condition60%3/5
$self->_crumb_local($q->param("back2")) // $self->_crumb_local($self->_spec_to_url($q->param("l") // ""))
l!l&&r!l&&!r
21310
$q->param("l") // ""
l!l
1310
MC/DC0%0/2
$self->_crumb_local($q->param("back2")) // $self->_crumb_local($self->_spec_to_url($q->param("l") // ""))
$self->_crumb_local($q->param("back2")) $self->_crumb_local($self->_spec_to_url($q->param("l") // ""))
MC/DC0%0/1
$q->param("l") // ""
$q->param("l")
Truth table66%2/3
A // B
A= $self->_crumb_local($q->param("back2"))B= $self->_crumb_local($self->_spec_to_url($q->param("l") // ""))
ABresult
1X1
011
000
Truth table50%1/2
A
A= $q->param("l")
Aresult
11
00
1018 // $self->_crumb_local($self->_spec_to_url($q->param('l') // ''));
1019 }
1020 971 ▶ if ($path eq '/open') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/open") 341 630 971
1021 341 ▶ my $parent = $self->_crumb_local($q->param('back2'))
Condition100%3/3
$self->_crumb_local($q->param("back2")) // $self->_crumb_local($q->param("back"))
l!l&&r!l&&!r
21338
MC/DC100%2/2
$self->_crumb_local($q->param("back2")) // $self->_crumb_local($q->param("back"))
$self->_crumb_local($q->param("back2")) $self->_crumb_local($q->param("back"))
Truth table100%3/3
A // B
A= $self->_crumb_local($q->param("back2"))B= $self->_crumb_local($q->param("back"))
ABresult
1X1
011
000
1022 // $self->_crumb_local($q->param('back'));
1023 341 ▶ return $parent if $parent;
Branch: 1 branch
BranchTrueFalseTotal
if $parent 3 338 341
1024 338 ▶ my $file = $q->param('path') // '';
Condition50%1/2
$q->param("path") // ""
l!l
3380
MC/DC0%0/1
$q->param("path") // ""
$q->param("path")
Truth table50%1/2
A
A= $q->param("path")
Aresult
11
00
1025 338 ▶ return undef unless length $file && $file !~ m{\A/\.\./};
Branch: 1 branch
BranchTrueFalseTotal
unless length $file and not $file =~ m[\A/\.\./]u 9 329 338
Condition100%3/3
length $file and not $file =~ m[\A/\.\./]u
!ll&&!rl&&r
18329
MC/DC100%2/2
length $file and not $file =~ m[\A/\.\./]u
length $file not $file =~ m[\A/\.\./]u
Truth table100%3/3
A and not(B)
A= length $fileB= not $file =~ m[\A/\.\./]u
ABresult
0X0
100
111
1026 329 return Mojo::URL->new('/browse?path=' . url_escape(Mojo::File->new($file)->dirname->to_string));
1027 }
1028 630 ▶ if ($path eq '/tables') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/tables") 58 572 630
1029 58 ▶ my $spec = $q->param('l') // '';
Condition50%1/2
$q->param("l") // ""
l!l
580
MC/DC0%0/1
$q->param("l") // ""
$q->param("l")
Truth table50%1/2
A
A= $q->param("l")
Aresult
11
00
1030 58 ▶ return undef unless $spec =~ /\Apath:(.+)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $spec =~ /\Apath:(.+)\z/u 50 8 58
1031 8 my ($file) = _split_path($1);
1032 8 return Mojo::URL->new('/browse?path=' . url_escape(Mojo::File->new($file)->dirname->to_string));
1033 }
1034 # Preferences came from the page whose nav link opened it (_preferences_url).
1035 572 ▶ if ($path eq '/preferences') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/preferences") 1 571 572
1036 1 return $self->_crumb_local($q->param('back'));
1037 }
1038 # A canvas came from where its back= says, else from the list of canvases.
1039 571 ▶ if ($path =~ m{\A/a/}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ m[\A/a/]u) 72 499 571
1040 72 ▶ return $self->_crumb_local($q->param('back')) // Mojo::URL->new('/canvases');
Condition66%2/3
$self->_crumb_local($q->param("back")) // "Mojo::URL"->new("/canvases")
l!l&&r!l&&!r
1710
MC/DC0%0/2
$self->_crumb_local($q->param("back")) // "Mojo::URL"->new("/canvases")
$self->_crumb_local($q->param("back")) "Mojo::URL"->new("/canvases")
Truth table66%2/3
A // B
A= $self->_crumb_local($q->param("back"))B= "Mojo::URL"->new("/canvases")
ABresult
1X1
011
000
1041 }
1042 499 return undef;
1043 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1044  
1045 # _crumb_label($self, $url) -> $text | undef
1046 #
1047 # What a page is called in a trail. undef for a page that has no place in
1048 # one, which ends the trail there.
1049 4695 ▶sub _crumb_label :Protected ($self, $url) {
Subroutine _crumb_label: called CC=34 SCAR=35.3
1050 4695 my $path = $url->path->to_string;
1051 4695 my $q = $url->query;
1052 4695 my $view = _crumb_view_suffix($q);
1053  
1054 4695 ▶ return _crumb_spec_name("table:$1") . $view if $path =~ m{\A/view/([^/]+)\z};
Branch: 1 branch
BranchTrueFalseTotal
if $path =~ m[\A/view/([^/]+)\z]u 1094 3601 4695
1055  
1056 3601 ▶ if ($path eq '/open') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/open") 387 3214 3601
1057 387 ▶ my $file = $q->param('path') // '';
Condition100%2/2
$q->param("path") // ""
l!l
34245
MC/DC100%1/1
$q->param("path") // ""
$q->param("path")
Truth table100%2/2
A
A= $q->param("path")
Aresult
11
00
1058 387 ▶ return undef unless length $file;
Branch: 1 branch
BranchTrueFalseTotal
unless length $file 47 340 387
1059 340 my $name = Mojo::File->new($file)->basename;
1060 340 my $it = $q->param('it');
1061 340 ▶ $name .= ": $it" if defined $it && length $it;
Branch: 1 branch
BranchTrueFalseTotal
if defined $it and length $it 2 338 340
Condition66%2/3
defined $it and length $it
!ll&&!rl&&r
33802
MC/DC50%1/2
defined $it and length $it
defined $it length $it
Truth table66%2/3
A and B
A= defined $itB= length $it
ABresult
0X0
100
111
1062 340 ▶ return length $name ? "$name$view" : undef;
Branch: 1 branch
BranchTrueFalseTotal
length $name ? : 340 0 340
1063 }
1064 # Either route takes both joins and combined files.
1065 3214 ▶ if ($path eq '/join' || $path eq '/combine') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/join" or $path eq "/combine") 146 3068 3214
Condition100%3/3
$path eq "/join" or $path eq "/combine"
l!l&&r!l&&!r
82643068
MC/DC100%2/2
$path eq "/join" or $path eq "/combine"
$path eq "/join" $path eq "/combine"
Truth table100%3/3
A or B
A= $path eq "/join"B= $path eq "/combine"
ABresult
1X1
011
000
1066 171 ▶ my @names = map { _crumb_spec_name($_) } grep { /\A(?:table|path|url|redis|mariadb):/i }
Condition100%2/2
$q->param("l") // ""
l!l
1406
MC/DC100%1/1
$q->param("l") // ""
$q->param("l")
Truth table100%2/2
A
A= $q->param("l")
Aresult
11
00
1067 ($q->param('l') // ''),
1068 27 ▶ (map { (split /\|/, $_, 2)[0] // '' } @{ $q->every_param('j') }),
Condition100%2/2
(split(/\|/u, $_, 2))[0] // ""
l!l
252
MC/DC100%1/1
(split(/\|/u, $_, 2))[0] // ""
(split(/\|/u, $_, 2))[0]
Truth table100%2/2
A
A= (split(/\|/u, $_, 2))[0]
Aresult
11
00
1069 146 @{ $q->every_param('c') };
1070 146 ▶ return @names ? _names_summary(\@names) . $view : undef;
Branch: 1 branch
BranchTrueFalseTotal
@names ? : 135 11 146
1071 }
1072 3068 ▶ if ($path eq '/import') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/import") 103 2965 3068
1073 103 ▶ my $src = Mojo::URL->new($q->param('url') // '');
Condition100%2/2
$q->param("url") // ""
l!l
5449
MC/DC100%1/1
$q->param("url") // ""
$q->param("url")
Truth table100%2/2
A
A= $q->param("url")
Aresult
11
00
1074 103 ▶ return defined $src->host ? $src->host . $view : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $src->host ? : 54 49 103
1075 }
1076 2965 ▶ if ($path =~ m{\A/([a-z]+)\z} && $CRUMB_KIND{$1}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ m[\A/([a-z]+)\z]u and $CRUMB_KIND{$1}) 1117 1848 2965
Condition100%3/3
$path =~ m[\A/([a-z]+)\z]u and $CRUMB_KIND{$1}
!ll&&!rl&&r
10747741117
MC/DC100%2/2
$path =~ m[\A/([a-z]+)\z]u and $CRUMB_KIND{$1}
$path =~ m[\A/([a-z]+)\z]u $CRUMB_KIND{$1}
Truth table100%3/3
A and B
A= $path =~ m[\A/([a-z]+)\z]uB= $CRUMB_KIND{$1}
ABresult
0X0
100
111
1077 1117 my $what = _crumb_chart_subject($1, $q);
1078 1117 ▶ return $CRUMB_KIND{$1} . (length $what ? ": $what" : '');
Branch: 1 branch
BranchTrueFalseTotal
length $what ? : 896 221 1117
1079 }
1080 1848 ▶ if ($path eq '/tables') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/tables") 62 1786 1848
1081 62 ▶ my $spec = $q->param('l') // '';
Condition100%2/2
$q->param("l") // ""
l!l
593
MC/DC100%1/1
$q->param("l") // ""
$q->param("l")
Truth table100%2/2
A
A= $q->param("l")
Aresult
11
00
1082 62 ▶ return length $spec ? _crumb_spec_name($spec) . ' schema' : undef;
Branch: 1 branch
BranchTrueFalseTotal
length $spec ? : 57 5 62
1083 }
1084 1786 ▶ if ($path eq '/browse') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/browse") 390 1396 1786
1085 390 ▶ my $dir = $q->param('path') // '';
Condition100%2/2
$q->param("path") // ""
l!l
34545
MC/DC100%1/1
$q->param("path") // ""
$q->param("path")
Truth table100%2/2
A
A= $q->param("path")
Aresult
11
00
1086 390 ▶ return length $dir ? 'Files: ' . Mojo::File->new($dir)->basename : 'Files';
Branch: 1 branch
BranchTrueFalseTotal
length $dir ? : 343 47 390
1087 }
1088 1396 ▶ return 'Catalog' if $path eq '/catalog';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/catalog" 20 1376 1396
1089 1376 ▶ return 'Canvases' if $path eq '/canvases';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/canvases" 73 1303 1376
1090 1303 ▶ return 'Tutorial' if $path eq '/tutorial';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/tutorial" 8 1295 1303
1091 1295 ▶ return 'Preferences' if $path eq '/preferences';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/preferences" 1 1294 1295
1092 1294 ▶ return 'Log in' if $path eq '/login';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/login" 11 1283 1294
1093 1283 ▶ if ($path =~ m{\A/a/([A-Za-z0-9_-]+)}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ m[\A/a/([A-Za-z0-9_-]+)]u) 72 1211 1283
1094 72 my $a = $self->_read_analyses->{$1};
1095 72 ▶ return (ref $a eq 'HASH' && length($a->{name} // '')) ? $a->{name} : 'Canvas';
Branch: 1 branch
BranchTrueFalseTotal
ref $a eq 'HASH' && length($a->{'name'} // '') ? : 60 12 72
Condition100%5/5
ref $a eq "HASH" and length($a->{"name"} // "")
!ll&&!rl&&r
10260
$a->{"name"} // ""
l!l
602
MC/DC100%2/2
ref $a eq "HASH" and length($a->{"name"} // "")
ref $a eq "HASH" $a->{"name"}
Truth table100%3/3
A and B
A= ref $a eq "HASH"B= $a->{"name"}
ABresult
0X0
100
111
1096 }
1097 1211 return undef;
1098 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1099  
1100 # _names_summary(\@names) -> $text
1101 #
1102 # "a + b + c", or for a folder of reports stacked, the first few and a count:
1103 # "a + b + c + 297 more". Used for the trail and the page title.
1104 187 ▶sub _names_summary {
Subroutine _names_summary: called CC=2 SCAR=8.4
1105 187 my ($names) = @_;
1106 187 my $keep = 3;
1107 187 ▶ return join(' + ', @$names) if @$names <= $keep + 1;
Branch: 1 branch
BranchTrueFalseTotal
if @$names <= $keep + 1 187 0 187
1108 0 return join(' + ', @{$names}[0 .. $keep - 1], (@$names - $keep) . ' more');
1109 }
1110  
1111 # _crumb_spec_name($spec) -> $name
1112 #
1113 # A data source as a person would name it: "sales" for table:sales,
1114 # "store: orders" for an internal table, the file name for path:, the host
1115 # for a web page.
1116 1330 ▶sub _crumb_spec_name {
Subroutine _crumb_spec_name: called CC=4 SCAR=13.9
1117 1330 my ($spec) = @_;
1118 1330 ▶ $spec //= '';
Condition100%2/2
$spec //= ""
l!l
13291
MC/DC100%1/1
$spec //= ""
$spec
Truth table100%2/2
A
A= $spec
Aresult
11
00
1119 1330 ▶ if ($spec =~ m{\Apath:(.+)\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ /\Apath:(.+)\z/u) 44 1286 1330
1120 44 my ($file, $internal) = _split_path($1);
1121 44 my $name = Mojo::File->new($file)->basename;
1122 44 ▶ return defined $internal ? "$name: $internal" : $name;
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 0 44 44
1123 }
1124 1286 return _crumb_spec_name_other($spec);
1125 }
1126  
1127 # _split_path($path) -> ($file, $internal)
1128 #
1129 # Purpose: What follows "path:" in a spec: the file, and the table it names
1130 # after a "#" (Database::BI::Model::DataSource::split_path).
1131 2083 ▶sub _split_path {
Subroutine _split_path: called CC=1 SCAR=0.0
1132 2083 my ($path) = @_;
1133 2083 require Database::BI::Model::DataSource;
1134 2083 return Database::BI::Model::DataSource::split_path($path);
1135 }
1136  
1137 1286 ▶sub _crumb_spec_name_other {
Subroutine _crumb_spec_name_other: called CC=9 SCAR=22.5
1138 1286 my ($spec) = @_;
1139 1286 ▶ $spec //= '';
Condition50%1/2
$spec //= ""
l!l
12860
MC/DC0%0/1
$spec //= ""
$spec
Truth table50%1/2
A
A= $spec
Aresult
11
00
1140 1286 ▶ return "$1: $2" if $spec =~ m{\Atable:([^/]+)/(.+)\z};
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ m[\Atable:([^/]+)/(.+)\z]u 1 1285 1286
1141 1285 ▶ return $1 if $spec =~ m{\Atable:(.+)\z};
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /\Atable:(.+)\z/u 1264 21 1285
1142 21 ▶ if ($spec =~ m{\Aurl:(.+)\z}i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ /\Aurl:(.+)\z/iu) 13 8 21
1143 13 my $host = Mojo::URL->new($1)->host;
1144 13 ▶ return $host // $1;
Condition33%1/3
$host // $1
l!l&&r!l&&!r
1300
MC/DC0%0/2
$host // $1
$host $1
Truth table33%1/3
A // B
A= $hostB= $1
ABresult
1X1
011
000
1145 }
1146 8 ▶ return 'Redis' if $spec =~ /\Aredis:/i;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /\Aredis:/iu 3 5 8
1147 5 ▶ return "$1: $2" if $spec =~ $MARIADB_SPEC_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /$MARIADB_SPEC_RE/u 0 5 5
1148 5 ▶ return $1 if $spec =~ $MARIADB_SERVER_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /$MARIADB_SERVER_RE/u 0 5 5
1149 5 return $spec;
1150 }
1151  
1152 # _crumb_view_suffix($query) -> " (region = East, last 90 days)" | ''
1153 #
1154 # The part of a table's view that makes it a different page from the whole
1155 # table: its filters and its time range. Two filters are shown; more are
1156 # counted, so a crumb stays short.
1157 4708 ▶sub _crumb_view_suffix {
Subroutine _crumb_view_suffix: called CC=22 SCAR=31.0
1158 4708 my ($q) = @_;
1159 4708 my @bits;
1160 4708 for my $spec (@{ $q->every_param('f') }) {
1161 172 my ($col, $op, $val) = split /:/, $spec, 3;
1162 172 ▶ next unless length($col // '') && length($op // '');
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and length($op // "") 65 107 172
Condition100%7/7
length($col // "") and length($op // "")
!ll&&!rl&&r
4421107
$col // ""
l!l
13141
$op // ""
l!l
10721
MC/DC100%2/2
length($col // "") and length($op // "")
$col $op
Truth table100%3/3
A and B
A= $colB= $op
ABresult
0X0
100
111
1163 107 ▶ next unless $col =~ $CRUMB_TEXT_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $col =~ /$CRUMB_TEXT_RE/u 2 105 107
1164 # A list is JSON, which the crumb text pattern refuses: say how long it is.
1165 105 ▶ if ($op eq 'in') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "in") 2 103 105
1166 2 my $n = () = _filter_in_values($val);
1167 2 ▶ push @bits, "$col $CRUMB_OP{in} $n value" . ($n == 1 ? '' : 's');
Branch: 1 branch
BranchTrueFalseTotal
$n == 1 ? : 0 2 2
1168 2 next;
1169 }
1170 103 ▶ next if length($val // '') && $val !~ $CRUMB_TEXT_RE;
Branch: 1 branch
BranchTrueFalseTotal
if length($val // "") and not $val =~ /$CRUMB_TEXT_RE/u 1 102 103
Condition100%5/5
length($val // "") and not $val =~ /$CRUMB_TEXT_RE/u
!ll&&!rl&&r
5971
$val // ""
l!l
1012
MC/DC100%2/2
length($val // "") and not $val =~ /$CRUMB_TEXT_RE/u
$val not $val =~ /$CRUMB_TEXT_RE/u
Truth table100%3/3
A and not(B)
A= $valB= not $val =~ /$CRUMB_TEXT_RE/u
ABresult
0X0
100
111
1171 102 ▶ my $word = $CRUMB_OP{$op} // $op;
Condition33%1/3
$CRUMB_OP{$op} // $op
l!l&&r!l&&!r
10200
MC/DC0%0/2
$CRUMB_OP{$op} // $op
$CRUMB_OP{$op} $op
Truth table33%1/3
A // B
A= $CRUMB_OP{$op}B= $op
ABresult
1X1
011
000
1172 102 ▶ push @bits, ($op eq 'empty' || $op eq 'notempty')
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'empty' || $op eq 'notempty' ? : 5 97 102
Condition80%4/5
$op eq "empty" or $op eq "notempty"
l!l&&r!l&&!r
3297
$val // ""
l!l
970
MC/DC100%2/2
$op eq "empty" or $op eq "notempty"
$op eq "empty" $op eq "notempty"
MC/DC0%0/1
$val // ""
$val
Truth table100%3/3
A or B
A= $op eq "empty"B= $op eq "notempty"
ABresult
1X1
011
000
Truth table50%1/2
A
A= $val
Aresult
11
00
1173 ? "$col $word" : "$col $word " . (($val // '') =~ s/:/ and /r);
1174 }
1175 4708 ▶ my $extra = @bits > 2 ? @bits - 2 : 0;
Branch: 1 branch
BranchTrueFalseTotal
@bits > 2 ? : 2 4706 4708
1176 4708 ▶ splice @bits, 2 if $extra;
Branch: 1 branch
BranchTrueFalseTotal
if $extra 2 4706 4708
1177 4708 ▶ push @bits, "+$extra more" if $extra;
Branch: 1 branch
BranchTrueFalseTotal
if $extra 2 4706 4708
1178 4708 ▶ if (my $range = $TIME_RANGE{ $q->param('range') // '' }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $range = $TIME_RANGE{$q->param("range") // ""}) 2 4706 4708
Condition100%2/2
$q->param("range") // ""
l!l
434665
MC/DC100%1/1
$q->param("range") // ""
$q->param("range")
Truth table100%2/2
A
A= $q->param("range")
Aresult
11
00
1179 2 push @bits, lc $range->{label};
1180 }
1181 4708 ▶ return @bits ? ' (' . join(', ', @bits) . ')' : '';
Branch: 1 branch
BranchTrueFalseTotal
@bits ? : 49 4659 4708
1182 }
1183  
1184 # _crumb_chart_subject($kind, $query) -> $text
1185 #
1186 # What a chart shows, from its own parameters: "amount by region",
1187 # "Count by region", "amount". Empty for the pages that are about the
1188 # whole table (stats, insights).
1189 1131 ▶sub _crumb_chart_subject {
Subroutine _crumb_chart_subject: called CC=28 SCAR=33.3
1190 1131 my ($kind, $q) = @_;
1191 my %p = map {
1192 # loc= may repeat, for a place spread over columns (address, country).
1193 1131 ▶ my $v = ($_ eq 'loc') ? join(', ', grep { length } @{ $q->every_param('loc') }) : ($q->param($_) // '');
Branch: 1 branch
BranchTrueFalseTotal
$_ eq 'loc' ? : 1131 12441 13572
Condition100%2/2
$q->param($_) // ""
l!l
33889053
MC/DC100%1/1
$q->param($_) // ""
$q->param($_)
Truth table100%2/2
A
A= $q->param($_)
Aresult
11
00
1194 13572 ▶ ($_ => ($v =~ $CRUMB_TEXT_RE ? $v : ''));
Branch: 1 branch
BranchTrueFalseTotal
$v =~ /$CRUMB_TEXT_RE/u ? : 3240 10332 13572
1195 } qw(x y cat val seg col rows bar_val line_val loc lat lon);
1196  
1197 1131 ▶ return "$p{y} by $p{x}" if ($kind eq 'graph' || $kind eq 'line' || $kind eq 'scatter') && length $p{x} && length $p{y};
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "graph" || $kind eq "line" || $kind eq "scatter" and length $p{"x"} and length $p{"y"} 158 973 1131
Condition100%12/12
$kind eq "graph" || $kind eq "line" || $kind eq "scatter" and length $p{"x"} and length $p{"y"}
!ll&&!rl&&r
9694158
$kind eq "graph" || $kind eq "line" || $kind eq "scatter" and length $p{"x"}
!ll&&!rl&&r
95811162
$kind eq "graph" or $kind eq "line" or $kind eq "scatter"
l!l&&r!l&&!r
11855958
$kind eq "graph" or $kind eq "line"
l!l&&r!l&&!r
73451013
MC/DC100%5/5
$kind eq "graph" || $kind eq "line" || $kind eq "scatter" and length $p{"x"} and length $p{"y"}
$kind eq "graph" $kind eq "line" $kind eq "scatter" length $p{"x"} length $p{"y"}
Truth table90%9/10
A or B or C and D and E
A= $kind eq "graph"B= $kind eq "line"C= $kind eq "scatter"D= length $p{"x"}E= length $p{"y"}
ABCDEresult
000XX0
1XX0X0
01X0X0
0010X0
1XX100
01X100
001100
1XX111
01X111
001111
1198 973 ▶ return "$p{x} by $p{y}" if $kind eq 'heatmap' && length $p{x} && length $p{y};
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "heatmap" and length $p{"x"} and length $p{"y"} 60 913 973
Condition100%6/6
$kind eq "heatmap" and length $p{"x"} and length $p{"y"}
!ll&&!rl&&r
911260
$kind eq "heatmap" and length $p{"x"}
!ll&&!rl&&r
906562
MC/DC100%3/3
$kind eq "heatmap" and length $p{"x"} and length $p{"y"}
$kind eq "heatmap" length $p{"x"} length $p{"y"}
Truth table100%4/4
A and B and C
A= $kind eq "heatmap"B= length $p{"x"}C= length $p{"y"}
ABCresult
0XX0
10X0
1100
1111
1199 913 ▶ return "$p{cat} by $p{seg}" if $kind eq 'stacked' && length $p{cat} && length $p{seg};
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "stacked" and length $p{"cat"} and length $p{"seg"} 7 906 913
Condition100%6/6
$kind eq "stacked" and length $p{"cat"} and length $p{"seg"}
!ll&&!rl&&r
856507
$kind eq "stacked" and length $p{"cat"}
!ll&&!rl&&r
851557
MC/DC100%3/3
$kind eq "stacked" and length $p{"cat"} and length $p{"seg"}
$kind eq "stacked" length $p{"cat"} length $p{"seg"}
Truth table100%4/4
A and B and C
A= $kind eq "stacked"B= length $p{"cat"}C= length $p{"seg"}
ABCresult
0XX0
10X0
1100
1111
1200 906 ▶ return $p{rows} =~ s/,/, /gr if $kind eq 'pivot';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "pivot" 95 811 906
1201 811 ▶ return length $p{loc} ? $p{loc} : (length $p{lat} ? "$p{lat}, $p{lon}" : '') if $kind eq 'map';
Branch: 3 branches
BranchTrueFalseTotal
if $kind eq "map" 116 695 811
length $p{'loc'} ? : 25 91 116
length $p{'lat'} ? : 41 50 91
1202  
1203 695 ▶ my $dim = (grep { length } @p{qw(cat x col)})[0] // '';
Condition100%2/2
(grep {length $_;} @p{"cat", "x", "col"})[0] // ""
l!l
567128
MC/DC100%1/1
(grep {length $_;} @p{"cat", "x", "col"})[0] // ""
(grep {length $_;} @p{"cat", "x", "col"})[0]
Truth table100%2/2
A
A= (grep {length $_;} @p{"cat", "x", "col"})[0]
Aresult
11
00
1204 695 ▶ my $measure = (grep { length } @p{qw(val bar_val y)})[0] // '';
Condition100%2/2
(grep {length $_;} @p{"val", "bar_val", "y"})[0] // ""
l!l
489206
MC/DC100%1/1
(grep {length $_;} @p{"val", "bar_val", "y"})[0] // ""
(grep {length $_;} @p{"val", "bar_val", "y"})[0]
Truth table100%2/2
A
A= (grep {length $_;} @p{"val", "bar_val", "y"})[0]
Aresult
11
00
1205 695 ▶ $measure = 'Count' if $measure eq '__count__';
Branch: 1 branch
BranchTrueFalseTotal
if $measure eq "__count__" 7 688 695
1206 695 ▶ $measure = 'Count' if !length $measure && ($kind eq 'pie' || $kind eq 'bar' || $kind eq 'treemap');
Branch: 1 branch
BranchTrueFalseTotal
if not length $measure and $kind eq "pie" || $kind eq "bar" || $kind eq "treemap" 61 634 695
Condition100%9/9
not length $measure and $kind eq "pie" || $kind eq "bar" || $kind eq "treemap"
!ll&&!rl&&r
48914561
$kind eq "pie" or $kind eq "bar" or $kind eq "treemap"
l!l&&r!l&&!r
4516145
$kind eq "pie" or $kind eq "bar"
l!l&&r!l&&!r
540161
MC/DC100%4/4
not length $measure and $kind eq "pie" || $kind eq "bar" || $kind eq "treemap"
not length $measure $kind eq "pie" $kind eq "bar" $kind eq "treemap"
Truth table100%5/5
not(A) and B or C or D
A= not length $measureB= $kind eq "pie"C= $kind eq "bar"D= $kind eq "treemap"
ABCDresult
0XXX0
10000
11XX1
101X1
10011
1207 695 ▶ return length $measure && length $dim ? "$measure by $dim" : $dim;
Branch: 1 branch
BranchTrueFalseTotal
length $measure && length $dim ? : 510 185 695
Condition100%3/3
length $measure and length $dim
!ll&&!rl&&r
14540510
MC/DC100%2/2
length $measure and length $dim
length $measure length $dim
Truth table100%3/3
A and B
A= length $measureB= length $dim
ABresult
0X0
100
111
1208 }
1209  
1210 # _resolve_template($self) -> ($platform, $language)
1211 #
1212 # Purpose: Read platform and language from config, then resolve the Accept-Language
1213 # header to a language code -- falling back to the config language, and
1214 # then to the default language, when no template directory exists for
1215 # the code that was resolved.
1216 # Exit: Returns ($platform, $language) -- both guaranteed non-empty strings.
1217 1401 ▶sub _resolve_template :Protected ($self) {
Subroutine _resolve_template: called CC=5 SCAR=16.1
1218 1401 my $conf = $self->app->config();
1219 1401 ▶ my $cfg_platform = $conf->{platform} // 'web';
Condition100%2/2
$conf->{"platform"} // "web"
l!l
1258143
MC/DC100%1/1
$conf->{"platform"} // "web"
$conf->{"platform"}
Truth table100%2/2
A
A= $conf->{"platform"}
Aresult
11
00
1220 1401 ▶ my $cfg_language = $conf->{language} // 'en';
Condition100%2/2
$conf->{"language"} // "en"
l!l
1258143
MC/DC100%1/1
$conf->{"language"} // "en"
$conf->{"language"}
Truth table100%2/2
A
A= $conf->{"language"}
Aresult
11
00
1221  
1222 # Detect platform from the request User-Agent via CGI::Info.
1223 # Falls back to the configured platform when:
1224 # (a) CGI::Info is unavailable or throws, or
1225 # (b) no templates/<detected>/ directory exists.
1226 1401 ▶ my $platform = _detect_platform(
Condition100%2/2
$self->req->headers->user_agent // ""
l!l
13992
MC/DC100%1/1
$self->req->headers->user_agent // ""
$self->req->headers->user_agent
Truth table100%2/2
A
A= $self->req->headers->user_agent
Aresult
11
00
1227 $self->req->headers->user_agent // '',
1228 $cfg_platform,
1229 );
1230 1401 ▶ unless (-d $self->app->home->child("templates/$platform")) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $self->app->home->child("templates/$platform")) 2 1399 1401
1231 2 $platform = $cfg_platform;
1232 }
1233  
1234 1401 my $language = $self->_resolve_language($platform, $cfg_language);
1235 1401 return ($platform, $language);
1236 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1237  
1238 # _detect_platform($user_agent, $fallback) -> $platform_string
1239 #
1240 # Purpose: Map a raw User-Agent string to a VWF platform dimension
1241 # ('mobile', 'tablet', or 'web') via CGI::Info.
1242 # Entry: $user_agent -- the raw HTTP User-Agent header value (may be empty).
1243 # $fallback -- value to return if detection fails.
1244 # Exit: Returns 'mobile', 'tablet', 'web', or $fallback.
1245 # Side Effects: temporarily sets $ENV{HTTP_USER_AGENT} with local().
1246 1405 ▶sub _detect_platform ($user_agent, $fallback) {
Subroutine _detect_platform: called CC=4 SCAR=14.5
1247 1405 my $platform = eval {
1248 1405 local $ENV{HTTP_USER_AGENT} = $user_agent;
1249 1405 my $info = CGI::Info->new();
1250 1405 ▶ $info->is_mobile() ? 'mobile'
Branch: 2 branches
BranchTrueFalseTotal
$info->is_mobile ? : 4 1401 1405
$info->is_tablet ? : 0 1401 1401
1251 : $info->is_tablet() ? 'tablet'
1252 : 'web';
1253 };
1254 1405 ▶ return $platform // $fallback;
Condition33%1/3
$platform // $fallback
l!l&&r!l&&!r
140500
MC/DC0%0/2
$platform // $fallback
$platform $fallback
Truth table33%1/3
A // B
A= $platformB= $fallback
ABresult
1X1
011
000
1255 }
1256  
1257 # _resolve_language($self, $platform, $default) -> $language_code
1258 #
1259 # Purpose: Determine the best ISO 639-1 language code for this request.
1260 # When Accept-Language is present, CGI::Lingua selects the best
1261 # match from the languages that have a template directory under
1262 # templates/<platform>/. $default answers when the header is absent,
1263 # no templates exist for the matched language, or CGI::Lingua is
1264 # unavailable. The result has a template directory whenever one
1265 # exists: a code without one - the configured language included -
1266 # becomes the default language, and only when that has no directory
1267 # either is the resolved code returned, so the missing template names
1268 # what was asked for.
1269 # Entry: $platform is the resolved VWF platform string.
1270 # $default is a non-empty fallback language code (e.g. 'en').
1271 # Exit: Returns a two-letter ISO 639-1 language code string, or a code
1272 # and region (en-us) when the browser names that region and
1273 # templates/<platform>/<code>-<region>/ exists.
1274 # Side Effects: filesystem stats for template directories;
1275 # temporarily sets $ENV{HTTP_ACCEPT_LANGUAGE} with local().
1276 1413 ▶sub _resolve_language :Protected ($self, $platform, $default) {
Subroutine _resolve_language: called CC=7 SCAR=19.5
1277 1413 ▶ my $accept = $self->req->headers->accept_language() // '';
Condition100%2/2
$self->req->headers->accept_language // ""
l!l
301383
MC/DC100%1/1
$self->req->headers->accept_language // ""
$self->req->headers->accept_language
Truth table100%2/2
A
A= $self->req->headers->accept_language
Aresult
11
00
1278  
1279 1413 my $language = $default;
1280 1413 ▶ if ($accept) {
Branch: 1 branch
BranchTrueFalseTotal
if ($accept) 29 1384 1413
1281 # Discover supported languages from template directories so CGI::Lingua
1282 # only returns a code we can actually serve. The configured language is
1283 # offered as well, so a request that asks for it gets it, whether or not
1284 # it can be served - the check below decides that.
1285 29 my @supported = _template_languages($self->app->home, $platform);
1286 29 ▶ push @supported, $default unless grep { $_ eq $default } @supported;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $default;} @supported 1 28 29
1287  
1288 # A regional variant (templates/web/en-us/ for a browser asking for
1289 # en-US) is chosen when it has a directory, otherwise the language
1290 # itself: en-GB, en-CA and plain en get en. Database::BI::I18N makes
1291 # the same CGI::Lingua call for the messages, so the two agree.
1292 29 my $chosen = Database::BI::I18N::lingua_choice($accept, \@supported);
1293 29 ▶ $language = $chosen if defined $chosen;
Branch: 1 branch
BranchTrueFalseTotal
if defined $chosen 21 8 29
1294 }
1295  
1296 # Confirm a template directory exists for the language we are about to
1297 # render from. Naming a language does not give it templates, and rendering
1298 # a directory that is not there is a 500 rather than a translation. This
1299 # covers the configured language itself and not just the one Accept-Language
1300 # produced: the documented fallback used to happen only when the two
1301 # differed, so the ordinary case - an operator setting language => 'de'
1302 # before adding templates/web/de/ - reached the renderer unchecked.
1303 1413 my $home = $self->app->home;
1304 1413 ▶ return $language if _has_templates($home, $platform, $language);
Branch: 1 branch
BranchTrueFalseTotal
if _has_templates($home, $platform, $language) 1410 3 1413
1305 3 ▶ return $DEFAULT_LANGUAGE
Branch: 1 branch
BranchTrueFalseTotal
if _has_templates($home, $platform, $DEFAULT_LANGUAGE) 3 0 3
1306 if _has_templates($home, $platform, $DEFAULT_LANGUAGE);
1307  
1308 # Neither exists. Keep what was resolved, so the missing template names the
1309 # language the request asked for rather than one nobody configured.
1310 0 return $language;
1311 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1312  
1313 # _template_languages($home, $platform) -> @codes
1314 #
1315 # The languages that have a template directory for the platform, sorted so that
1316 # the answer does not depend on the order the filesystem returns entries in.
1317 # Plain functions taking the application home rather than methods: the tests
1318 # call _resolve_language with a mock controller, and a method call on it would
1319 # look for the helper in the mock's package rather than this one.
1320 31 ▶sub _template_languages ($home, $platform) {
Subroutine _template_languages: called CC=2 SCAR=6.9
1321 31 my $base = $home->child("templates/$platform");
1322 31 ▶ return () unless -d $base;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $base 1 30 31
1323  
1324 60 return sort map { Mojo::File->new($_)->basename }
1325 30 grep { -d $_ } @{ $base->list({ dir => 1 }) };
1326 }
1327  
1328 # _has_templates($home, $platform, $language) -> 1 | 0
1329 #
1330 # Whether the application can render a language: the controller builds template
1331 # names as "<platform>/<language>/<page>", so a language without a directory
1332 # under templates/<platform>/ cannot be served at all.
1333 1421 ▶sub _has_templates ($home, $platform, $language) {
Subroutine _has_templates: called CC=4 SCAR=13.9
1334 1421 ▶ return 0 unless defined $language && length $language;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $language and length $language 2 1419 1421
Condition100%3/3
defined $language and length $language
!ll&&!rl&&r
111419
MC/DC100%2/2
defined $language and length $language
defined $language length $language
Truth table100%3/3
A and B
A= defined $languageB= length $language
ABresult
0X0
100
111
1335  
1336 1419 ▶ return -d $home->child("templates/$platform/$language") ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
-d $home->child("templates/$platform/$language") ? : 1414 5 1419
1337 }
1338  
1339 # _data_dir_for($app) -> Mojo::File
1340 #
1341 # The configured data directory. A relative value is resolved against the
1342 # application home, which is the historical behaviour; an absolute one is used
1343 # as given, because Mojo::File->child() appends an absolute path rather than
1344 # replacing the base. It takes the app rather than $self because the unit
1345 # tests call the scanning helpers with a bare controller.
1346 12368 ▶sub _data_dir_for ($app) {
Subroutine _data_dir_for: called CC=3 SCAR=11.0
1347 12368 ▶ my $dir = $app->config->{data_dir} // 'data';
Condition100%2/2
$app->config->{"data_dir"} // "data"
l!l
109241444
MC/DC100%1/1
$app->config->{"data_dir"} // "data"
$app->config->{"data_dir"}
Truth table100%2/2
A
A= $app->config->{"data_dir"}
Aresult
11
00
1348 12368 my $file = Mojo::File->new($dir);
1349 12368 ▶ return $file if $file->is_abs;
Branch: 1 branch
BranchTrueFalseTotal
if $file->is_abs 746 11622 12368
1350 11622 return $app->home->child($dir);
1351 }
1352  
1353 # _scan_data_dir($self) -> \@table_list
1354 #
1355 # Purpose: Return an arrayref of { name, file } hashrefs for every supported
1356 # data file in the configured data_dir. Used by the index action; the
1357 # join panel uses _scan_join_tables, which also lists internal tables.
1358 # Entry: None.
1359 # Exit: Returns [] when data_dir does not exist or contains no supported files.
1360 # Side Effects: Filesystem directory read.
1361 #
1362 # Optimisation: single-pass map replaces a two-pass grep+map chain, and calls
1363 # basename() only once per entry (the original chain called it twice: once in
1364 # grep to check the extension and again in map to extract the stem).
1365 # ->to_array avoids the extra flat-list expansion that ->each produced.
1366 501 ▶sub _scan_data_dir :Protected ($self) {
Subroutine _scan_data_dir: called CC=3 SCAR=11.0
1367 501 my $dir = _data_dir_for($self->app);
1368 501 ▶ return [] unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 2 499 501
1369  
1370 # A directory that exists but may not be read holds nothing this application
1371 # can show, and must not take the home page with it.
1372 499 my $files = eval { $dir->list };
1373 499 ▶ unless ($files) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($files) 1 498 499
1374 1 $self->app->log->error("Cannot read data_dir $dir: " . _tidy_error($@));
1375 1 return [];
1376 }
1377 5408 ▶ return $files->map(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1378 5408 my $base = $_->basename;
1379 5408 ▶ return unless $base =~ $EXT_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $base =~ /$EXT_RE/u 0 5408 5408
1380 5408 (my $name = $base) =~ s/\.[^.]+\z//;
1381 5408 { name => $name, file => $base, path => $_->to_string }
1382 498 })->to_array;
1383 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1384  
1385 # _scan_join_tables($self) -> \@table_list
1386 #
1387 # Purpose: Like _scan_data_dir, but each multi-table SQLite file contributes
1388 # one entry per internal table as well as the file entry. The join
1389 # and combine panels need this: "table:store/customer" names a table
1390 # inside store.db, which a plain file name cannot do.
1391 # Entry: None.
1392 # Exit: Returns [] when data_dir does not exist or has no supported files.
1393 # Every entry has a spec suitable for the panel's option value.
1394 # Side Effects: Reads data_dir and opens each SQLite file to list its tables.
1395 350 ▶sub _scan_join_tables :Protected ($self) {
Subroutine _scan_join_tables: called CC=8 SCAR=20.8
1396 350 my $dir = _data_dir_for($self->app);
1397 350 my $tables = $self->_scan_data_dir;
1398 350 my @all;
1399  
1400 350 for my $table (@$tables) {
1401 3769 push @all, { %$table, spec => "table:$table->{name}" };
1402 3769 ▶ next unless $table->{file} =~ /\.(?:db|sql|sqlite|sqlite3)\z/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $table->{"file"} =~ /\.(?:db|sql|sqlite|sqlite3)\z/iu 3426 343 3769
1403  
1404 343 my $source = eval { $self->open_table($table->{name}, directory => $dir->to_string) };
1405 343 ▶ next unless $source;
Branch: 1 branch
BranchTrueFalseTotal
unless $source 1 342 343
1406  
1407 342 my $internal_tables = eval { $source->sqlite_tables };
1408 342 ▶ next unless $internal_tables && @$internal_tables > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $internal_tables and @$internal_tables > 1 1 341 342
Condition66%2/3
$internal_tables and @$internal_tables > 1
!ll&&!rl&&r
01341
MC/DC50%1/2
$internal_tables and @$internal_tables > 1
$internal_tables @$internal_tables > 1
Truth table66%2/3
A and B
A= $internal_tablesB= @$internal_tables > 1
ABresult
0X0
100
111
1409  
1410 341 my @internal = @$internal_tables;
1411  
1412 341 for my $name (@internal) {
1413 1023 ▶ next unless $name =~ $TABLE_NAME_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$TABLE_NAME_RE/u 0 1023 1023
1414 1023 push @all, {
1415 %$table,
1416 name => "$table->{name} / $name",
1417 internal => $name,
1418 spec => "table:$table->{name}/$name",
1419 };
1420 }
1421 }
1422  
1423 350 return \@all;
1424 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1425  
1426 # _tidy_error($error) -> $string
1427 #
1428 # Purpose: A backend error as a reader should see it: without the "at FILE line N"
1429 # that croak adds each time the error is passed up, or the list of
1430 # library directories perl adds when a module is missing.
1431 143 ▶sub _tidy_error {
Subroutine _tidy_error: called CC=2 SCAR=6.9
1432 143 ▶ my $error = $_[0] // '';
Condition100%2/2
$_[0] // ""
l!l
1412
MC/DC100%1/1
$_[0] // ""
$_[0]
Truth table100%2/2
A
A= $_[0]
Aresult
11
00
1433 143 $error =~ s/\s*\(\@INC (?:contains|entries checked):.*?\)(?=\s+at\s|\s*\z)//sg;
1434 143 $error =~ s/(?:\s+at \S.*? line \d+\.?)+\s*\z//;
1435 143 return $error;
1436 }
1437  
1438 # _analysis_json_error($error) -> $string
1439 #
1440 # Purpose: The message for a canvas request whose body is not a JSON object.
1441 # Entry: the error from decode_json, which is empty when the body parsed
1442 # but was an array or a scalar, and otherwise ends in a library's path.
1443 63 ▶sub _analysis_json_error {
Subroutine _analysis_json_error: called CC=2 SCAR=6.9
1444 63 my $reason = _tidy_error($_[0]);
1445 63 ▶ return sprintf(_message_text('error_analysis_json'), length($reason) ? $reason : 'expected a JSON object');
Branch: 1 branch
BranchTrueFalseTotal
length $reason ? : 29 34 63
1446 }
1447  
1448 # ---------------------------------------------------------------------------
1449 # Accelerated views (Phase 7 item 7.5)
1450 #
1451 # A dataset marked in models.json accelerated.<spec> is read from a SQLite copy
1452 # of itself, built by script/bi-extract through Database::BI::Extract, as long
1453 # as the copy's fingerprint (the spec, and the file's mtime and size) still
1454 # matches the file. When it does not, the file itself is read and the table
1455 # page says the extract is stale: stale numbers are never served. An extract is
1456 # a cache. Deleting <model_dir>/extracts/ only makes every accelerated dataset
1457 # read its file again, and nothing is ever written under data_dir.
1458 # ---------------------------------------------------------------------------
1459  
1460 # _model_dir_of($app) -> Mojo::File
1461 #
1462 # Purpose: model_dir as a path: absolute as configured, or under the app home.
1463 # Nothing is created and nothing is checked; the writers check.
1464 9 ▶sub _model_dir_of {
Subroutine _model_dir_of: called CC=3 SCAR=11.0
1465 9 my ($app) = @_;
1466 9 ▶ my $cfg = Mojo::File->new($app->config('model_dir') // '.bi');
Condition100%2/2
$app->config("model_dir") // ".bi"
l!l
81
MC/DC100%1/1
$app->config("model_dir") // ".bi"
$app->config("model_dir")
Truth table100%2/2
A
A= $app->config("model_dir")
Aresult
11
00
1467 9 ▶ return $cfg->is_abs ? $cfg : $app->home->child($cfg->to_string);
Branch: 1 branch
BranchTrueFalseTotal
$cfg->is_abs ? : 7 2 9
1468 }
1469  
1470 # _table_stem($data_dir, $name, @exts) -> $stem | undef
1471 #
1472 # Purpose: The file stem table:<name> means in data_dir: the name as written
1473 # when a file has it, else in lower case, which is what every reader
1474 # once looked for (so table:Orders still opens orders.csv); undef
1475 # when neither has a file with one of @exts (default @SUPPORTED_EXT).
1476 # Reading only the lower case made a file named with a capital,
1477 # BandMusic.csv, open on its own page (/view/BandMusic) and nowhere
1478 # else: a pivot, chart or merge of table:BandMusic was a 404.
1479 1123 ▶sub _table_stem ($data_dir, $name, @exts) {
Subroutine _table_stem: called CC=4 SCAR=13.9
1480 1123 ▶ @exts = @SUPPORTED_EXT unless @exts;
Branch: 1 branch
BranchTrueFalseTotal
unless @exts 1079 44 1123
1481 1123 for my $stem ($name, lc $name) {
1482 1191 ▶ return $stem if grep { -f $data_dir->child("$stem.$_") } @exts;
Branch: 1 branch
BranchTrueFalseTotal
if grep {-f $data_dir->child("$stem.$_");} @exts 1055 136 1191
1483 }
1484 68 return undef; ## no critic (ProhibitExplicitReturnUndef)
1485 }
1486  
1487 # _accel_file($self, $spec) -> $path | undef
1488 #
1489 # Purpose: The local file a spec can be accelerated from: table:<name> in
1490 # data_dir, or path:<file>. An internal table, a remote path and
1491 # every other kind of spec have none.
1492 22 ▶sub _accel_file :Protected ($self, $spec) {
Subroutine _accel_file: called CC=9 SCAR=22.0
1493 22 ▶ $spec //= '';
Condition100%2/2
$spec //= ""
l!l
211
MC/DC100%1/1
$spec //= ""
$spec
Truth table100%2/2
A
A= $spec
Aresult
11
00
1494 22 ▶ if ($spec =~ m{\Atable:([A-Za-z0-9_]+)\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ /\Atable:([A-Za-z0-9_]+)\z/u) 8 14 22
1495 8 my $data_dir = _data_dir_for($self->app);
1496 8 ▶ my $stem = _table_stem($data_dir, $1) // return undef;
Condition100%2/2
_table_stem($data_dir, $1) // (return undef)
l!l
62
MC/DC100%1/1
_table_stem($data_dir, $1) // (return undef)
_table_stem($data_dir, $1)
Truth table100%2/2
A
A= _table_stem($data_dir, $1)
Aresult
11
00
1497 6 my ($file) = grep { -f } map { $data_dir->child("$stem.$_")->to_string } @SUPPORTED_EXT;
1498 6 return $file;
1499 }
1500 14 ▶ if ($spec =~ m{\Apath:(?!/\.\./)(.+)\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ m[\Apath:(?!/\.\./)(.+)\z]u) 8 6 14
1501 8 my ($path) = _split_path($1);
1502 8 ▶ return undef if _outside_roots($self, $path);
Branch: 1 branch
BranchTrueFalseTotal
if _outside_roots($self, $path) 0 8 8
1503 8 my $file = eval { Mojo::File->new($path)->realpath };
1504 8 ▶ return (defined $file && -f $file && $file->basename =~ $EXT_RE) ? $file->to_string : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $file && -f $file && $file->basename =~ /$EXT_RE/u ? : 6 2 8
Condition66%4/6
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
!ll&&!rl&&r
206
defined $file and -f $file
!ll&&!rl&&r
026
MC/DC33%1/3
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
defined $file -f $file $file->basename =~ /$EXT_RE/u
Truth table50%2/4
A and B and C
A= defined $fileB= -f $fileC= $file->basename =~ /$EXT_RE/u
ABCresult
0XX0
10X0
1100
1111
1505 }
1506 6 return undef;
1507 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1508  
1509 # _accelerated_source($self, $spec) -> $DataSource | undef
1510 #
1511 # Purpose: The extract of an accelerated dataset, when it still matches the file.
1512 # Exit: The extract opened as a source, or undef: the spec is not accelerated,
1513 # or its extract is missing or stale, and the caller reads the file.
1514 # The first call in a request stashes acceleration => { state =>
1515 # 'fresh' | 'stale', built => epoch, spec => $spec } for the table page.
1516 1705 ▶sub _accelerated_source :Protected ($self, $spec) {
Subroutine _accelerated_source: called CC=14 SCAR=26.8
1517 1705 ▶ return undef if $self->stash('_no_acceleration');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_no_acceleration") 5 1700 1705
1518 1700 ▶ return undef unless defined $spec && length $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec and length $spec 17 1683 1700
Condition66%2/3
defined $spec and length $spec
!ll&&!rl&&r
0171683
MC/DC50%1/2
defined $spec and length $spec
defined $spec length $spec
Truth table66%2/3
A and B
A= defined $specB= length $spec
ABresult
0X0
100
111
1519 # Only this application's controller has a model store; a bare controller
1520 # (a test's, calling _open_spec as a function) has nothing accelerated.
1521 1683 ▶ return undef unless $self->isa(__PACKAGE__);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->isa(__PACKAGE__) 7 1676 1683
1522 1676 $spec = canonical_spec($spec);
1523 1676 my $entry = $self->_read_models->{accelerated}{$spec};
1524 1676 ▶ return undef unless ref $entry eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 1674 2 1676
1525 2 ▶ my $file = $self->_accel_file($spec) // return undef;
Condition50%1/2
$self->_accel_file($spec) // (return undef)
l!l
20
MC/DC0%0/1
$self->_accel_file($spec) // (return undef)
$self->_accel_file($spec)
Truth table50%1/2
A
A= $self->_accel_file($spec)
Aresult
11
00
1526  
1527 2 my @st = stat $file;
1528 2 my $cache = _extract_store($self->app);
1529 2 my $path = $cache->get($spec, $st[9], $st[7]);
1530 2 my $src;
1531 2 ▶ if (defined $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $path) 1 1 2
1532 1 my $x = Mojo::File->new($path);
1533 1 $src = eval { $self->open_table($x->basename =~ s/\.db\z//r, directory => $x->dirname->to_string,
1534 1 ▶ (ref $entry->{columns} eq 'ARRAY' ? (column_order => $entry->{columns}) : ())) };
Branch: 1 branch
BranchTrueFalseTotal
ref $entry->{'columns'} eq 'ARRAY' ? : 1 0 1
1535 }
1536 2 require POSIX;
1537 2 ▶ my $built = $src ? (stat $path)[9] : $entry->{built};
Branch: 1 branch
BranchTrueFalseTotal
$src ? : 1 1 2
1538 2 ▶ $self->stash(acceleration => {
Branch: 3 branches
BranchTrueFalseTotal
unless $self->stash("acceleration") 2 0 2
$src ? : 1 1 2
defined $built && $built =~ /\A\d+\z/u ? : 2 0 2
Condition33%1/3
defined $built and $built =~ /\A\d+\z/u
!ll&&!rl&&r
002
MC/DC0%0/2
defined $built and $built =~ /\A\d+\z/u
defined $built $built =~ /\A\d+\z/u
Truth table33%1/3
A and B
A= defined $builtB= $built =~ /\A\d+\z/u
ABresult
0X0
100
111
1539 spec => $spec,
1540 state => ($src ? 'fresh' : 'stale'),
1541 built => $built,
1542 built_text => (defined $built && $built =~ /\A\d+\z/ ? Database::BI::Util::minute_stamp(localtime $built) : ''),
1543 }) unless $self->stash('acceleration');
1544 2 return $src;
1545 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1546  
1547 # _extract_store($app) -> Database::BI::Extract
1548 #
1549 # Purpose: The extract store, in the cache directory Database::BI::CacheDir
1550 # chooses (Object::Configure, CACHEDIR, CACHE_DIR, cache_dir in the
1551 # config), else in <model_dir>/extracts as before. A cache directory
1552 # inside data_dir is not used for them: each extract is a .db file,
1553 # which the home page would list as a table of the user's own, and
1554 # nothing is written under data_dir. They then go in model_dir, whose
1555 # own check (_calc_models_path) stops a store inside data_dir.
1556 6 ▶sub _extract_store {
Subroutine _extract_store: called CC=2 SCAR=7.5
1557 6 my ($app) = @_;
1558 6 require Database::BI::Extract;
1559 6 my $model_dir = _model_dir_of($app);
1560 6 my $store = Database::BI::Extract->new(
1561 model_dir => $model_dir->to_string,
1562 config => $app->config,
1563 home => $app->home->to_string,
1564 );
1565 6 ▶ if (_inside_dir(_canonical_path(Mojo::File->new($store->dir)), _canonical_path(_data_dir_for($app)))) {
Branch: 1 branch
BranchTrueFalseTotal
if (_inside_dir(_canonical_path("Mojo::File"->new($store->dir)), _canonical_path(_data_dir_for($app)))) 0 6 6
1566 0 carp 'The cache directory is inside data_dir; extracts are kept in model_dir instead';
1567 0 $store = Database::BI::Extract->new(dir => $model_dir->child('extracts')->to_string);
1568 }
1569 6 return $store;
1570 }
1571  
1572 # _is_sqlite_file($path) -> $bool
1573 #
1574 # Purpose: True for a SQLite database, whatever its extension (a .db may be one).
1575 13 ▶sub _is_sqlite_file {
Subroutine _is_sqlite_file: called CC=4 SCAR=13.9
1576 13 my ($path) = @_;
1577 13 ▶ open my $fh, '<:raw', $path or return 0;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or return 0 11 2 13
1578 11 my $n = read $fh, my $head, 16;
1579 11 close $fh;
1580 11 ▶ return ($n && $head eq "SQLite format 3\0") ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$n && $head eq "SQLite format 3\000" ? : 2 9 11
Condition100%3/3
$n and $head eq "SQLite format 3\0"
!ll&&!rl&&r
272
MC/DC100%2/2
$n and $head eq "SQLite format 3\0"
$n $head eq "SQLite format 3\0"
Truth table100%3/3
A and B
A= $nB= $head eq "SQLite format 3\0"
ABresult
0X0
100
111
1581 }
1582  
1583 # accelerate($c, $spec) -> \%built
1584 #
1585 # Purpose: Mark a dataset accelerated and build its extract: the rows its file
1586 # gives, in a SQLite file in the extract store (_extract_store). Called by
1587 # script/bi-extract; not a route.
1588 # Entry: $c is a controller of the application (Mojolicious build_controller);
1589 # $spec is a table: or path: spec naming a local, non-SQLite file.
1590 # Exit: { spec, path, rows, columns, built } -- the extract written and when.
1591 # The model store records accelerated.<spec> = { built, file, rows }.
1592 # Croaks error_accel_spec, error_accel_sqlite, error_accel_open,
1593 # error_accel_store or error_accel_build.
1594 # Side Effects: Writes the extract, removes the one it replaces, and writes
1595 # models.json.
1596 11 ▶sub accelerate {
Subroutine accelerate: called CC=17 SCAR=29.4
Pod documented
1597 11 my ($c, $spec) = @_;
1598 11 ▶ croak 'accelerate() needs a controller and a spec' unless ref $c && defined $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $c and defined $spec 1 10 11
Condition66%2/3
ref $c and defined $spec
!ll&&!rl&&r
1010
MC/DC50%1/2
ref $c and defined $spec
ref $c defined $spec
Truth table66%2/3
A and B
A= ref $cB= defined $spec
ABresult
0X0
100
111
1599 # Filed under the resolved spec, which is what the file's page asks for;
1600 # messages name the spec as the caller wrote it.
1601 10 my $key = canonical_spec($spec);
1602 10 ▶ my $file = $c->_accel_file($spec)
Condition100%2/2
$c->_accel_file($spec) // croak($c->_i18n("error_accel_spec", $spec))
l!l
82
MC/DC100%1/1
$c->_accel_file($spec) // croak($c->_i18n("error_accel_spec", $spec))
$c->_accel_file($spec)
Truth table100%2/2
A
A= $c->_accel_file($spec)
Aresult
11
00
1603 // croak $c->_i18n('error_accel_spec', $spec);
1604 8 ▶ croak $c->_i18n('error_accel_sqlite', $spec) if $file =~ /\.(?:sql|sqlite3?)\z/i || _is_sqlite_file($file);
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /\.(?:sql|sqlite3?)\z/iu or _is_sqlite_file($file) 2 6 8
Condition100%3/3
$file =~ /\.(?:sql|sqlite3?)\z/iu or _is_sqlite_file($file)
l!l&&r!l&&!r
116
MC/DC100%2/2
$file =~ /\.(?:sql|sqlite3?)\z/iu or _is_sqlite_file($file)
$file =~ /\.(?:sql|sqlite3?)\z/iu _is_sqlite_file($file)
Truth table100%3/3
A or B
A= $file =~ /\.(?:sql|sqlite3?)\z/iuB= _is_sqlite_file($file)
ABresult
1X1
011
000
1605 6 ▶ defined $c->_calc_models_path or croak $c->_i18n('error_accel_store', $spec);
Branch: 1 branch
BranchTrueFalseTotal
defined $c->_calc_models_path or croak($c->_i18n("error_accel_store", $spec)) 4 2 6
1606  
1607 # Read the file itself, not the extract being replaced.
1608 4 local $c->stash->{_no_acceleration} = 1;
1609 4 my @st = stat $file;
1610 4 my ($src) = $c->_open_spec($spec);
1611 4 ▶ croak $c->_i18n('error_accel_open', $spec, _tidy_error($c->stash('open_spec_error') // 'unreadable')) unless $src;
Branch: 1 branch
BranchTrueFalseTotal
unless $src 1 3 4
Condition50%1/2
$c->stash("open_spec_error") // "unreadable"
l!l
01
MC/DC0%0/1
$c->stash("open_spec_error") // "unreadable"
$c->stash("open_spec_error")
Truth table50%1/2
A
A= $c->stash("open_spec_error")
Aresult
11
00
1612 3 my ($records, @columns);
1613 3 my $ok = eval {
1614 3 $records = $src->fetch_all;
1615 3 @columns = _get_columns($src, $records);
1616 3 1;
1617 };
1618 3 ▶ croak $c->_i18n('error_accel_open', $spec, _tidy_error($@)) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 3 3
1619 3 my $bytes = eval { $c->_write_sqlite_db($records, \@columns, 'extract') };
1620 3 ▶ croak $c->_i18n('error_accel_build', $spec, _tidy_error($@)) unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 1 2 3
1621  
1622 2 my $cache = _extract_store($c->app);
1623 2 my $path = eval { $cache->put($key, $st[9], $st[7], $bytes) };
1624 2 ▶ croak $c->_i18n('error_accel_build', $spec, _tidy_error($@)) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 2 2
1625  
1626 2 my $lock = $c->_models_lock;
1627 2 my $models = $c->_read_models;
1628 2 my $old = $models->{accelerated}{$key};
1629 2 my $name = Mojo::File->new($path)->basename;
1630 2 ▶ if (ref $old eq 'HASH' && defined $old->{file} && $old->{file} ne $name && $old->{file} =~ /\A[0-9a-f]{32}\.db\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $old eq "HASH" and defined $old->{"file"} and $old->{"file"} ne $name and $old->{"file"} =~ /\A[0-9a-f]{32}\.db\z/u) 0 2 2
Condition33%3/9
ref $old eq "HASH" and defined $old->{"file"} and $old->{"file"} ne $name and $old->{"file"} =~ /\A[0-9a-f]{32}\.db\z/u
!ll&&!rl&&r
200
ref $old eq "HASH" and defined $old->{"file"} and $old->{"file"} ne $name
!ll&&!rl&&r
200
ref $old eq "HASH" and defined $old->{"file"}
!ll&&!rl&&r
200
MC/DC0%0/4
ref $old eq "HASH" and defined $old->{"file"} and $old->{"file"} ne $name and $old->{"file"} =~ /\A[0-9a-f]{32}\.db\z/u
ref $old eq "HASH" defined $old->{"file"} $old->{"file"} ne $name $old->{"file"} =~ /\A[0-9a-f]{32}\.db\z/u
Truth table20%1/5
A and B and C and D
A= ref $old eq "HASH"B= defined $old->{"file"}C= $old->{"file"} ne $nameD= $old->{"file"} =~ /\A[0-9a-f]{32}\.db\z/u
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1631 0 unlink Mojo::File->new($path)->dirname->child($old->{file})->to_string;
1632 }
1633 2 my $built = time;
1634 # The file's own column order: the extract would list its columns alphabetically.
1635 2 $models->{accelerated}{$key} = { built => $built, file => $name, rows => scalar(@$records), columns => \@columns };
1636 2 ▶ $c->_write_models($models) or croak $c->_i18n('error_accel_store', $spec);
Branch: 1 branch
BranchTrueFalseTotal
$c->_write_models($models) or croak($c->_i18n("error_accel_store", $spec)) 2 0 2
1637 2 return { spec => $key, path => $path, rows => scalar(@$records), columns => scalar(@columns), built => $built };
1638 }
1639  
1640 # unaccelerate($c, $spec) -> $bool
1641 #
1642 # Purpose: Stop reading a dataset from an extract, and remove its extract.
1643 # Exit: True when the spec was accelerated.
1644 5 ▶sub unaccelerate {
Subroutine unaccelerate: called CC=6 SCAR=18.2
Pod documented
1645 5 my ($c, $spec) = @_;
1646 5 ▶ croak 'unaccelerate() needs a controller and a spec' unless ref $c && defined $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $c and defined $spec 1 4 5
Condition66%2/3
ref $c and defined $spec
!ll&&!rl&&r
014
MC/DC50%1/2
ref $c and defined $spec
ref $c defined $spec
Truth table66%2/3
A and B
A= ref $cB= defined $spec
ABresult
0X0
100
111
1647 4 $spec = canonical_spec($spec); # unaccelerate names no spec in a message
1648 4 my $lock = $c->_models_lock;
1649 4 my $models = $c->_read_models;
1650 4 my $entry = delete $models->{accelerated}{$spec};
1651 4 ▶ return 0 unless ref $entry eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 2 2 4
1652 2 ▶ if (defined $entry->{file} && $entry->{file} =~ /\A[0-9a-f]{32}\.db\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry->{"file"} and $entry->{"file"} =~ /\A[0-9a-f]{32}\.db\z/u) 2 0 2
Condition33%1/3
defined $entry->{"file"} and $entry->{"file"} =~ /\A[0-9a-f]{32}\.db\z/u
!ll&&!rl&&r
002
MC/DC0%0/2
defined $entry->{"file"} and $entry->{"file"} =~ /\A[0-9a-f]{32}\.db\z/u
defined $entry->{"file"} $entry->{"file"} =~ /\A[0-9a-f]{32}\.db\z/u
Truth table33%1/3
A and B
A= defined $entry->{"file"}B= $entry->{"file"} =~ /\A[0-9a-f]{32}\.db\z/u
ABresult
0X0
100
111
1653 2 unlink Mojo::File->new(_extract_store($c->app)->dir)->child($entry->{file})->to_string;
1654 }
1655 2 $c->_write_models($models);
1656 2 return 1;
1657 }
1658  
1659 # accelerated_specs($c) -> @specs
1660 #
1661 # Purpose: Every spec marked accelerated, sorted, for script/bi-extract --all.
1662 4 ▶sub accelerated_specs {
Subroutine accelerated_specs: called CC=2 SCAR=6.9
Pod documented
1663 4 my ($c) = @_;
1664 4 ▶ croak 'accelerated_specs() needs a controller' unless ref $c;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $c 1 3 4
1665 3 return sort keys %{ $c->_read_models->{accelerated} };
1666 }
1667  
1668 # _open_spec($self, $spec) -> ($DataSource, $label) or ()
1669 #
1670 # Purpose: Parse a "table:name", "table:file/table" or "path:/abs/path" spec,
1671 # verify the underlying file exists (Database::Abstraction creates empty objects silently for
1672 # missing files, so we must check ourselves), and return a live
1673 # DataSource object and a display label.
1674 # Entry: $spec is a non-empty string.
1675 # Exit: Returns ($datasource, $label) on success; an empty list on any failure
1676 # (invalid spec format, file missing, DataSource init error).
1677 # Side Effects: Filesystem stat; DataSource construction (reads file header).
1678 1461 ▶sub _open_spec :Protected ($self, $spec) {
Subroutine _open_spec: called CC=38 SCAR=48.0
1679 # An accelerated dataset whose extract still matches its file is read from
1680 # the extract, under the file's own label.
1681 1461 ▶ if (my $fast = _accelerated_source($self, $spec)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fast = _accelerated_source($self, $spec)) 0 1461 1461
1682 my $label = $spec =~ m{\Atable:(.+)\z} ? (_table_stem(_data_dir_for($self->app), $1) // $1)
1683 0 ▶ : do { my ($f, $i) = _split_path($spec =~ s/\Apath://r); $i // Mojo::File->new($f)->basename };
Branch: 1 branch
BranchTrueFalseTotal
$spec =~ /\Atable:(.+)\z/u ? : 0 0 0
Condition0%0/6
_table_stem(_data_dir_for($self->app), $1) // $1
l!l&&r!l&&!r
000
$i // "Mojo::File"->new($f)->basename
l!l&&r!l&&!r
000
MC/DC0%0/2
_table_stem(_data_dir_for($self->app), $1) // $1
_table_stem(_data_dir_for($self->app), $1) $1
MC/DC0%0/2
$i // "Mojo::File"->new($f)->basename
$i "Mojo::File"->new($f)->basename
Truth table0%0/3
A // B
A= _table_stem(_data_dir_for($self->app), $1)B= $1
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= $iB= "Mojo::File"->new($f)->basename
ABresult
1X1
011
000
1684 0 return ($fast, $label);
1685 }
1686 1461 ▶ if ($spec =~ m{\Atable:([A-Za-z0-9_]+)(?:/([A-Za-z0-9_]+))?\z}) {
Branch: 5 branches
BranchTrueFalseTotal
if ($spec =~ m[\Atable:([A-Za-z0-9_]+)(?:/([A-Za-z0-9_]+))?\z]u) { } 1059 402 1461
elsif ($spec =~ /\Apath:(.+)\z/u) { } 317 85 402
elsif ($spec =~ /$URL_SPEC_RE/u) { } 22 63 85
elsif ($spec =~ /$REDIS_SPEC_RE/u) { } 0 63 63
elsif ($spec =~ /$MARIADB_SPEC_RE/u) { } 0 63 63
1687 1059 my ($name, $internal) = ($1, $2);
1688 1059 my $data_dir = _data_dir_for($self->app);
1689 1059 ▶ my $table = _table_stem($data_dir, $name) // return ();
Condition100%2/2
_table_stem($data_dir, $name) // (return ())
l!l
103821
MC/DC100%1/1
_table_stem($data_dir, $name) // (return ())
_table_stem($data_dir, $name)
Truth table100%2/2
A
A= _table_stem($data_dir, $name)
Aresult
11
00
1690 1038 my $src = eval {
1691 1038 ▶ $self->open_table($table, directory => $data_dir->to_string,
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 0 1038 1038
1692 defined $internal ? (internal_table => $internal) : ())
1693 };
1694 1038 ▶ return ($src, defined $internal ? $internal : $table) if $src && !$@;
Branch: 2 branches
BranchTrueFalseTotal
if $src and not $@ 1037 1 1038
defined $internal ? : 0 1037 1037
Condition66%2/3
$src and not $@
!ll&&!rl&&r
101037
MC/DC50%1/2
$src and not $@
$src not $@
Truth table66%2/3
A and not(B)
A= $srcB= not $@
ABresult
0X0
100
111
1695 } elsif ($spec =~ /\Apath:(.+)\z/) {
1696 # path:<file>#<table> names one table of the file, as table:<file>/<table>
1697 # does in data_dir.
1698 317 my ($path_arg, $internal) = _split_path($1);
1699 317 ▶ my @it = defined $internal ? (internal_table => $internal) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 0 317 317
1700 # Remote path: /../hostname/dir/file -- delegate to DataSource with host param.
1701 # No EXT_RE check: security comes from REMOTE_HOST_RE. The original
1702 # extension (if any) is passed as file_ext so _init_backend tries it first.
1703 317 ▶ if ($path_arg =~ m{\A/\.\./([^/]+)((?:/.+)?)/([^/]+)\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path_arg =~ m[\A/\.\./([^/]+)((?:/.+)?)/([^/]+)\z]u) 8 309 317
1704 8 ▶ my ($host, $dir_part, $file) = ($1, $2 // '', $3);
Condition50%1/2
$2 // ""
l!l
80
MC/DC0%0/1
$2 // ""
$2
Truth table50%1/2
A
A= $2
Aresult
11
00
1705 8 ▶ $dir_part = '/' unless length $dir_part;
Branch: 1 branch
BranchTrueFalseTotal
unless length $dir_part 0 8 8
1706 8 ▶ return () unless $host =~ $REMOTE_HOST_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $host =~ /$REMOTE_HOST_RE/u 1 7 8
1707 7 ▶ my ($table, $ext) = $file =~ /\A(.+)\.([^.]+)\z/ ? ($1, $2) : ($file, undef);
Branch: 1 branch
BranchTrueFalseTotal
$file =~ /\A(.+)\.([^.]+)\z/u ? : 7 0 7
1708 7 ▶ my $src = eval { $self->open_table($table, directory => $dir_part, host => $host,
Branch: 1 branch
BranchTrueFalseTotal
defined $ext ? : 7 0 7
1709 defined $ext ? (file_ext => $ext) : (), @it) };
1710 7 ▶ return ($src, $internal // $file) if $src && !$@;
Branch: 1 branch
BranchTrueFalseTotal
if $src and not $@ 3 4 7
Condition50%3/6
$src and not $@
!ll&&!rl&&r
403
$internal // $file
l!l&&r!l&&!r
030
MC/DC50%1/2
$src and not $@
$src not $@
MC/DC0%0/2
$internal // $file
$internal $file
Truth table66%2/3
A and not(B)
A= $srcB= not $@
ABresult
0X0
100
111
Truth table33%1/3
A // B
A= $internalB= $file
ABresult
1X1
011
000
1711 4 return ();
1712 }
1713 309 ▶ return () if _outside_roots($self, $path_arg);
Branch: 1 branch
BranchTrueFalseTotal
if _outside_roots($self, $path_arg) 0 309 309
1714 309 my $file = eval { Mojo::File->new($path_arg)->realpath };
1715 309 ▶ if (defined $file && -f $file && $file->basename =~ $EXT_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file and -f $file and $file->basename =~ /$EXT_RE/u) 289 20 309
Condition100%6/6
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
!ll&&!rl&&r
164289
defined $file and -f $file
!ll&&!rl&&r
133293
MC/DC100%3/3
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
defined $file -f $file $file->basename =~ /$EXT_RE/u
Truth table100%4/4
A and B and C
A= defined $fileB= -f $fileC= $file->basename =~ /$EXT_RE/u
ABCresult
0XX0
10X0
1100
1111
1716 289 my $dir = $file->dirname->to_string;
1717 289 (my $table = $file->basename) =~ s/\.[^.]+\z//;
1718 289 my $src = eval { $self->open_table($table, directory => $dir, @it) };
1719 289 ▶ return ($src, $internal // $file->basename) if $src && !$@;
Branch: 1 branch
BranchTrueFalseTotal
if $src and not $@ 289 0 289
Condition33%2/6
$src and not $@
!ll&&!rl&&r
00289
$internal // $file->basename
l!l&&r!l&&!r
02890
MC/DC0%0/2
$src and not $@
$src not $@
MC/DC0%0/2
$internal // $file->basename
$internal $file->basename
Truth table33%1/3
A and not(B)
A= $srcB= not $@
ABresult
0X0
100
111
Truth table33%1/3
A // B
A= $internalB= $file->basename
ABresult
1X1
011
000
1720 }
1721 } elsif($spec =~ $URL_SPEC_RE) {
1722 22 my $url = $1;
1723 22 ▶ return () unless _is_safe_url($url);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_safe_url($url) 2 20 22
1724 20 my $src = eval { $self->open_table('', url => $url) };
1725 20 ▶ return ($src, $src->table_name) if $src && !$@;
Branch: 1 branch
BranchTrueFalseTotal
if $src and not $@ 20 0 20
Condition33%1/3
$src and not $@
!ll&&!rl&&r
0020
MC/DC0%0/2
$src and not $@
$src not $@
Truth table33%1/3
A and not(B)
A= $srcB= not $@
ABresult
0X0
100
111
1726 } elsif($spec =~ $REDIS_SPEC_RE) {
1727 0 my ($table, $redis_url) = ($1, $2);
1728 0 my $src = eval { $self->open_table($table, redis => $redis_url) };
1729 0 ▶ return ($src, $table) if $src && !$@;
Branch: 1 branch
BranchTrueFalseTotal
if $src and not $@ 0 0 0
Condition0%0/3
$src and not $@
!ll&&!rl&&r
000
MC/DC0%0/2
$src and not $@
$src not $@
Truth table0%0/3
A and not(B)
A= $srcB= not $@
ABresult
0X0
100
111
1730 } elsif($spec =~ $MARIADB_SPEC_RE) {
1731 0 my ($server, $table) = ($1, $2);
1732 0 my $src = eval { $self->open_table($table, mariadb => $server) };
1733 0 ▶ return ($src, $table) if $src;
Branch: 1 branch
BranchTrueFalseTotal
if $src 0 0 0
1734 # A server has more ways to fail than a file has; /open says which.
1735 0 $self->stash(open_spec_error => _tidy_error($@));
1736 }
1737 84 return ();
1738 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1739  
1740 # _schema_type_name($entry) -> $type
1741 #
1742 # Purpose: Normalise one schema() entry to an upper-case type name.
1743 # Entry: A hashref such as { type => 'INTEGER' }, a plain string, or undef.
1744 # Exit: The type name, or '' when the backend did not declare one.
1745 32 ▶sub _schema_type_name {
Subroutine _schema_type_name: called CC=6 SCAR=17.9
1746 32 my ($entry) = @_;
1747 32 ▶ return '' unless defined $entry;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry 1 31 32
1748  
1749 31 ▶ my $type = ref($entry) eq 'HASH' ? $entry->{type} : $entry;
Branch: 1 branch
BranchTrueFalseTotal
ref $entry eq 'HASH' ? : 23 8 31
1750 31 ▶ return '' unless defined($type) && !ref($type) && length($type);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type and not ref $type and length $type 6 25 31
Condition100%6/6
defined $type and not ref $type and length $type
!ll&&!rl&&r
3325
defined $type and not ref $type
!ll&&!rl&&r
2128
MC/DC100%3/3
defined $type and not ref $type and length $type
defined $type not ref $type length $type
Truth table100%4/4
A and not(B) and C
A= defined $typeB= not ref $typeC= length $type
ABCresult
0XX0
10X0
1100
1111
1751  
1752 25 return uc $type;
1753 }
1754  
1755 # _schema_type_warnings($self, $left, $right, $left_label, $right_label,
1756 # $left_key, $right_key) -> @warning_text
1757 #
1758 # Purpose: Describe columns whose declared types disagree across one join step.
1759 # Entry: $left and $right are open sources; the labels name them in the message.
1760 # The two join keys are excluded: Database::Join itself treats their
1761 # types as free to differ, because the key is not a data column.
1762 # Exit: Zero or more formatted warning strings for the schema_warnings banner.
1763 #
1764 # Database::Join's warn_schema_type_mismatch cannot fire here: every join this
1765 # controller builds passes a collision_prefix for the right table, so the
1766 # mismatched columns are published under distinct names and the check correctly
1767 # stays quiet. The difference still matters to a reader - a sum over a text
1768 # column yields nothing - so the comparison is made here, on the two sides as
1769 # the user sees them in the join panel.
1770 22 ▶sub _schema_type_warnings :Protected ($self, $left, $right, $left_label, $right_label,
Subroutine _schema_type_warnings: called CC=15 SCAR=27.4
1771 $left_key, $right_key) {
1772 22 ▶ my $left_schema = eval { $left->schema } // {};
Condition100%2/2
eval { do { $left->schema } } // {}
l!l
211
MC/DC100%1/1
eval { do { $left->schema } } // {}
eval { do { $left->schema } }
Truth table100%2/2
A
A= eval { do { $left->schema } }
Aresult
11
00
1773 22 ▶ my $right_schema = eval { $right->schema } // {};
Condition50%1/2
eval { do { $right->schema } } // {}
l!l
220
MC/DC0%0/1
eval { do { $right->schema } } // {}
eval { do { $right->schema } }
Truth table50%1/2
A
A= eval { do { $right->schema } }
Aresult
11
00
1774 22 ▶ return () unless %{ $left_schema // {} } && %{ $right_schema // {} };
Branch: 1 branch
BranchTrueFalseTotal
unless %{$left_schema // {};} and %{$right_schema // {};} 2 20 22
Condition57%4/7
%{$left_schema // {};} and %{$right_schema // {};}
!ll&&!rl&&r
2020
$left_schema // {}
l!l
220
$right_schema // {}
l!l
200
MC/DC50%1/2
%{$left_schema // {};} and %{$right_schema // {};}
%{$left_schema // {};} %{$right_schema // {};}
MC/DC0%0/1
$left_schema // {}
$left_schema
MC/DC0%0/1
$right_schema // {}
$right_schema
Truth table66%2/3
A and B
A= %{$left_schema // {};}B= %{$right_schema // {};}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $left_schema
Aresult
11
00
Truth table50%1/2
A
A= $right_schema
Aresult
11
00
1775  
1776 20 ▶ my %is_key = map { (defined($_) && length($_)) ? ($_ => 1) : () }
Branch: 1 branch
BranchTrueFalseTotal
defined $_ && length $_ ? : 34 6 40
Condition66%2/3
defined $_ and length $_
!ll&&!rl&&r
0634
MC/DC50%1/2
defined $_ and length $_
defined $_ length $_
Truth table66%2/3
A and B
A= defined $_B= length $_
ABresult
0X0
100
111
1777 ($left_key, $right_key);
1778  
1779 20 my @warnings;
1780 20 for my $col (sort keys %$right_schema) {
1781 51 ▶ next if $is_key{$col};
Branch: 1 branch
BranchTrueFalseTotal
if $is_key{$col} 17 34 51
1782 34 ▶ next unless exists $left_schema->{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $left_schema->{$col} 22 12 34
1783  
1784 12 my $left_type = _schema_type_name($left_schema->{$col});
1785 12 my $right_type = _schema_type_name($right_schema->{$col});
1786 12 ▶ next unless length($left_type) && length($right_type);
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_type and length $right_type 1 11 12
Condition66%2/3
length $left_type and length $right_type
!ll&&!rl&&r
1011
MC/DC50%1/2
length $left_type and length $right_type
length $left_type length $right_type
Truth table66%2/3
A and B
A= length $left_typeB= length $right_type
ABresult
0X0
100
111
1787 11 ▶ next if $left_type eq $right_type;
Branch: 1 branch
BranchTrueFalseTotal
if $left_type eq $right_type 9 2 11
1788  
1789 2 push @warnings, $self->_i18n('warn_join_schema_mismatch',
1790 $col, $left_type, $left_label, $right_type, $right_label);
1791 }
1792  
1793 20 return @warnings;
1794 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1795  
1796 # _spec_to_url($self, $spec) -> $url_string
1797 #
1798 # Purpose: Convert a table/path spec back to a browseable URL (used for the
1799 # back-link on join and export views).
1800 # Entry: $spec is a "table:name", "table:file/table" or "path:/abs" string.
1801 # Exit: Returns a URL string beginning with '/'.
1802 1492 ▶sub _spec_to_url :Protected ($self, $spec) {
Subroutine _spec_to_url: called CC=10 SCAR=27.3
1803 1492 ▶ if ($spec =~ m{\Atable:([A-Za-z0-9_]+)(?:/([A-Za-z0-9_]+))?\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ m[\Atable:([A-Za-z0-9_]+)(?:/([A-Za-z0-9_]+))?\z]u) 1088 404 1492
1804 1088 my ($table, $internal) = ($1, $2);
1805 1088 ▶ return "/view/$table" unless defined $internal;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $internal 1088 0 1088
1806  
1807 0 my $data_dir = _data_dir_for($self->app);
1808 0 for my $ext (@SUPPORTED_EXT) {
1809 0 my $file = $data_dir->child("$table.$ext");
1810 0 ▶ next unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 0 0 0
1811 0 return '/open?path=' . url_escape($file->to_string) . '&it=' . url_escape($internal);
1812 }
1813 0 return "/view/$table";
1814 }
1815 404 ▶ if ($spec =~ /\Apath:(.+)\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ /\Apath:(.+)\z/u) 322 82 404
1816 322 my ($file, $internal) = _split_path($1);
1817 322 ▶ return '/open?path=' . url_escape($file) . (defined $internal ? '&it=' . url_escape($internal) : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 0 322 322
1818 }
1819 82 ▶ return '/import?url=' . url_escape($1) if $spec =~ $URL_SPEC_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /$URL_SPEC_RE/u 13 69 82
1820 69 ▶ return '/' if $spec =~ $REDIS_SPEC_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /$REDIS_SPEC_RE/u 0 69 69
1821 69 ▶ return '/open?path=' . url_escape($spec) if $spec =~ $MARIADB_SPEC_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /$MARIADB_SPEC_RE/u 0 69 69
1822 69 return '/';
1823 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1824  
1825 # _url_attribution($self) -> ($url_string, $date_string) or (undef, undef)
1826 #
1827 # Purpose: Return source URL and access date for chart attribution when the
1828 # left table was imported from a web URL. The date is the time of
1829 # the current request (which is when the data is being accessed),
1830 # formatted as "D Month YYYY".
1831 # Entry: Reads the 'l' query param.
1832 # Exit: ($url, $date) when the spec matches $URL_SPEC_RE; (undef, undef)
1833 # for table: and path: specs.
1834 408 ▶sub _url_attribution :Protected ($self) {
Subroutine _url_attribution: called CC=3 SCAR=11.0
1835 408 ▶ my $spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
4071
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
1836 408 ▶ return (undef, undef) unless $spec =~ $URL_SPEC_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $spec =~ /$URL_SPEC_RE/u 407 1 408
1837 1 my $url = $1;
1838 1 my @MON = qw(January February March April May June July August
1839 September October November December);
1840 1 my (undef, undef, undef, $mday, $mon, $year) = localtime;
1841 1 return ($url, sprintf('%d %s %d', $mday, $MON[$mon], $year + 1900));
1842 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1843  
1844 # _get_columns($source, $records) -> @column_names
1845 #
1846 # Purpose: Return an ordered column list from a DataSource object.
1847 # For CSV/TSV/PSV the DataSource stores the original file-header order.
1848 # For SQLite/XML where no file-header order is available, the fallback
1849 # is: id_column first (only if it actually appears in the data), then
1850 # the remaining columns sorted alphabetically.
1851 # Entry: $source is a DataSource; $records is an arrayref of hashrefs (may be empty).
1852 # Exit: Returns a flat list of column-name strings (may be empty).
1853 #
1854 # Reduction: columns() is a pure accessor -- cache once to avoid a redundant
1855 # method dispatch on the second reference.
1856 1552 ▶sub _get_columns {
Subroutine _get_columns: called CC=5 SCAR=16.1
1857 1552 my ($source, $records) = @_;
1858 1552 my $cols = $source->columns;
1859 1552 ▶ return @$cols if $cols;
Branch: 1 branch
BranchTrueFalseTotal
if $cols 1543 9 1552
1860 9 ▶ return () unless $records->[0];
Branch: 1 branch
BranchTrueFalseTotal
unless $records->[0] 3 6 9
1861 6 my %all = map { $_ => 1 } keys %{ $records->[0] };
1862 6 my $c = $source->id_column;
1863 6 ▶ my $id = ($c && $all{$c}) ? $c : (sort keys %all)[0];
Branch: 1 branch
BranchTrueFalseTotal
$c && $all{$c} ? : 2 4 6
Condition100%3/3
$c and $all{$c}
!ll&&!rl&&r
312
MC/DC100%2/2
$c and $all{$c}
$c $all{$c}
Truth table100%3/3
A and B
A= $cB= $all{$c}
ABresult
0X0
100
111
1864 6 delete $all{$id};
1865 6 return ($id, sort keys %all);
1866 }
1867  
1868 # _apply_filter_spec($records, $spec) -> \@filtered_records
1869 #
1870 # Purpose: Apply one "col:op:val" filter to an arrayref of record hashrefs and
1871 # return a new (possibly shorter) arrayref. The original is not mutated.
1872 # Value may contain colons: "col:op:val:with:colons" -- split limit 3
1873 # puts everything after the second colon into $val.
1874 # Unknown operators fall through to 1 (all rows pass) so new operators
1875 # added in future do not break existing callers.
1876 # Entry: $records is an arrayref of hashrefs; $spec is a colon-delimited string.
1877 # Exit: Returns filtered arrayref (same reference if spec is invalid/unparseable).
1878 #
1879 # Domain Constraints (operator names):
1880 # Operator names are CASE-SENSITIVE. Only the exact lowercase forms below are
1881 # recognised; an uppercase or mixed-case name (e.g. "EQ", "Lt") falls through
1882 # to the default `1` branch and all rows pass unfiltered.
1883 # Valid operators:
1884 # String (value comparison is case-insensitive via lc()):
1885 # eq, ne, contains, starts
1886 # Numeric (Perl <, <=, >, >= coercion):
1887 # lt (strict), le (inclusive), gt (strict), ge (inclusive)
1888 # Unary (val is ignored):
1889 # empty (cell eq ''), notempty (cell ne '')
1890 # List (val = a JSON array of strings; compared as eq is):
1891 # in -- lc(cell) is one of them; a val that is not such an array matches nothing
1892 # Range (val = lo:hi, both ends included, whichever is written first;
1893 # see _between_bounds for where a timestamp's colons leave it):
1894 # between -- two numbers compare as numbers, two dates or timestamps
1895 # as times (at the precision of the bounds), anything else as text,
1896 # case-insensitively
1897 # Boundary rules for numeric operators:
1898 # le/ge include the boundary value; lt/gt exclude it.
1899 # contains/starts with empty val ('') match every record (index always 0).
1900 #
1901 # Reduction: split(/:/, $spec, 3) always produces at least one defined element,
1902 # so "defined $col" is structurally guaranteed true and is removed.
1903 # "$_->{$col} // ''" replaces the equivalent ternary form.
1904 #
1905 # Optimisation: $lval = lc($val) is computed once before the grep. Without this
1906 # precompute, every case-insensitive operator (eq, ne, contains, starts) would
1907 # call lc($val) O(N) times for N records -- a pure O(N) waste since $val is
1908 # constant within a single filter application.
1909 # _is_iso_date($value) -> bool
1910 #
1911 # Purpose: Report whether a filter value names a point in time rather than a
1912 # plain string, so the date comparisons can be used instead of the
1913 # string ones. A bare date (YYYY-MM-DD) qualifies, and so does an ISO
1914 # timestamp (YYYY-MM-DDTHH:MM:SS) or the same with a space separator,
1915 # which is what CSV exports and SQLite text columns usually hold, and
1916 # one with a fraction of a second or a zone (Z, +01:00), which is what
1917 # JSON APIs write. A zone is applied when config time_zone is set
1918 # (Util::iso_datetime).
1919 3364 ▶sub _is_iso_date {
Subroutine _is_iso_date: called CC=2 SCAR=6.9
1920 3364 ▶ return scalar(() = Database::BI::Util::iso_datetime($_[0])) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
scalar(() = Database::BI::Util::iso_datetime($_[0])) ? : 1503 1861 3364
1921 }
1922  
1923 # Convert M/D/YYYY or YYYY-MM-DD to YYYY-MM-DD; returns undef for other formats.
1924 # A value that is already ISO is returned unchanged, including its time part: a
1925 # timestamp cell is the caller's to compare, not this sub's to truncate.
1926 2970 ▶sub _to_iso_date {
Subroutine _to_iso_date: called CC=4 SCAR=13.9
1927 2970 my ($v) = @_;
1928 2970 ▶ return unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 1 2969 2970
1929 2969 ▶ return $v if _is_iso_date($v);
Branch: 1 branch
BranchTrueFalseTotal
if _is_iso_date($v) 1457 1512 2969
1930 1512 ▶ if (my ($m, $d, $y) = $v =~ m{\A(\d{1,2})/(\d{1,2})/(\d{4})\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = $v =~ m[\A(\d{1,2})/(\d{1,2})/(\d{4})\z]u) 13 1499 1512
1931 13 return sprintf '%04d-%02d-%02d', $y, $m, $d;
1932 }
1933 1499 return;
1934 }
1935  
1936 # _time_columns(\@columns, \@records) -> \@names
1937 #
1938 # Purpose: The columns a time range can be applied to: those whose every
1939 # non-empty cell on the page is a date or a date and time that the
1940 # range filter reads (_to_iso_date: YYYY-MM-DD, with an optional
1941 # "THH:MM[:SS]" or " HH:MM[:SS]", or M/D/YYYY), with a month and day
1942 # that can exist, and at least one such cell. The dashboard offers
1943 # Time range only when this is not empty, and lists only these.
1944 # Entry: $columns is the page's column order; $records its rows (hashes).
1945 # Exit: Returns the qualifying names, in column order; [] when there are
1946 # none, no rows, or either argument is not an array.
1947 # Notes: It reads the rows drawn on the page, as the table's own date
1948 # detection does: reading every row of the view for this would cost a
1949 # second pass over the data on every page.
1950 348 ▶sub _time_columns {
Subroutine _time_columns: called CC=15 SCAR=29.0
1951 348 my ($columns, $records) = @_;
1952 348 ▶ return [] unless ref($columns) eq 'ARRAY' && ref($records) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $columns eq "ARRAY" and ref $records eq "ARRAY" 0 348 348
Condition33%1/3
ref $columns eq "ARRAY" and ref $records eq "ARRAY"
!ll&&!rl&&r
00348
MC/DC0%0/2
ref $columns eq "ARRAY" and ref $records eq "ARRAY"
ref $columns eq "ARRAY" ref $records eq "ARRAY"
Truth table33%1/3
A and B
A= ref $columns eq "ARRAY"B= ref $records eq "ARRAY"
ABresult
0X0
100
111
1953 348 my @found;
1954 348 COLUMN: for my $col (@{$columns}) {
1955 1779 ▶ next unless defined $col;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col 0 1779 1779
1956 1779 my $seen = 0;
1957 1779 for my $row (@{$records}) {
1958 3076 ▶ next unless ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 0 3076 3076
1959 3076 my $v = $row->{$col};
1960 3076 ▶ next unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 39 3037 3076
1961 3037 $v =~ s/\A\s+//;
1962 3037 $v =~ s/\s+\z//;
1963 3037 ▶ next unless length $v;
Branch: 1 branch
BranchTrueFalseTotal
unless length $v 72 2965 3037
1964 2965 my $iso = _to_iso_date($v);
1965 2965 ▶ next COLUMN unless defined $iso;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $iso 1498 1467 2965
1966 1467 my ($m, $d) = $iso =~ /\A\d{4}-(\d{2})-(\d{2})/;
1967 1467 ▶ next COLUMN unless $m >= 1 && $m <= 12 && $d >= 1 && $d <= 31;
Branch: 1 branch
BranchTrueFalseTotal
unless $m >= 1 and $m <= 12 and $d >= 1 and $d <= 31 0 1467 1467
Condition33%3/9
$m >= 1 and $m <= 12 and $d >= 1 and $d <= 31
!ll&&!rl&&r
001467
$m >= 1 and $m <= 12 and $d >= 1
!ll&&!rl&&r
001467
$m >= 1 and $m <= 12
!ll&&!rl&&r
001467
MC/DC0%0/4
$m >= 1 and $m <= 12 and $d >= 1 and $d <= 31
$m >= 1 $m <= 12 $d >= 1 $d <= 31
Truth table20%1/5
A and B and C and D
A= $m >= 1B= $m <= 12C= $d >= 1D= $d <= 31
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1968 1467 $seen = 1;
1969 }
1970 281 ▶ push @found, $col if $seen;
Branch: 1 branch
BranchTrueFalseTotal
if $seen 260 21 281
1971 }
1972 348 return \@found;
1973 }
1974  
1975 # _date_key($value, $precision) -> comparable key | undef
1976 #
1977 # Purpose: Put a cell and a filter bound on the same footing so that a
1978 # lexicographic comparison answers the question the filter asked.
1979 # $precision is 10 for a day and 19 for a second: a cell holding a
1980 # timestamp is compared at the day it falls in when the bound is a
1981 # day, and to the second when the bound carries a time. A value that
1982 # is not date-shaped at all returns undef, and the caller keeps the
1983 # raw cell instead.
1984 25 ▶sub _date_key {
Subroutine _date_key: called CC=7 SCAR=19.5
1985 25 my ($value, $precision) = @_;
1986 25 ▶ return undef unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 24 25
1987 24 my ($day, $hour, $min, $sec) = Database::BI::Util::iso_datetime($value);
1988 24 ▶ return undef unless defined $day;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $day 1 23 24
1989 23 ▶ return $day if $precision < 19;
Branch: 1 branch
BranchTrueFalseTotal
if $precision < 19 15 8 23
1990 8 ▶ return sprintf '%sT%s:%s:%s', $day, $hour // '00', $min // '00', $sec // '00';
Condition100%6/6
$hour // "00"
l!l
62
$min // "00"
l!l
62
$sec // "00"
l!l
44
MC/DC100%1/1
$hour // "00"
$hour
MC/DC100%1/1
$min // "00"
$min
MC/DC100%1/1
$sec // "00"
$sec
Truth table100%2/2
A
A= $hour
Aresult
11
00
Truth table100%2/2
A
A= $min
Aresult
11
00
Truth table100%2/2
A
A= $sec
Aresult
11
00
1991 }
1992  
1993 # ---------------------------------------------------------------------------
1994 # Relative time ranges
1995 # ---------------------------------------------------------------------------
1996  
1997 # _iso_day($epoch) -> 'YYYY-MM-DD' in local time
1998 72520 ▶sub _iso_day {
Subroutine _iso_day: called CC=1 SCAR=0.0
1999 72520 my @lt = localtime($_[0]);
2000 72520 return sprintf '%04d-%02d-%02d', $lt[5] + 1900, $lt[4] + 1, $lt[3];
2001 }
2002  
2003 # _iso_second($epoch) -> 'YYYY-MM-DDTHH:MM:SS' in local time
2004 6593 ▶sub _iso_second {
Subroutine _iso_second: called CC=1 SCAR=0.0
2005 6593 my @lt = localtime($_[0]);
2006 6593 return sprintf '%04d-%02d-%02dT%02d:%02d:%02d',
2007 $lt[5] + 1900, $lt[4] + 1, $lt[3], $lt[2], $lt[1], $lt[0];
2008 }
2009  
2010 # _midday($mday, $mon, $year) -> epoch
2011 #
2012 # Noon, so a boundary never lands in a daylight-saving gap, and mktime's own
2013 # normalisation (day 0 is the last day of the previous month, month -1 is
2014 # December, and so on) is what makes the month, quarter and year arithmetic
2015 # below one line each. $mon is 0-based, $year is years since 1900, matching
2016 # localtime's own convention.
2017 82409 ▶sub _midday {
Subroutine _midday: called CC=1 SCAR=0.0
2018 82409 require POSIX;
2019 82409 return POSIX::mktime(12, 0, 0, $_[0], $_[1], $_[2]);
2020 }
2021  
2022 # _time_range_bounds($preset, $now) -> ($lo, $hi)
2023 #
2024 # Purpose: Resolve one preset to the window it names, as two strings that the
2025 # filter engine can compare against: 'YYYY-MM-DD' for a day-granular
2026 # window, 'YYYY-MM-DDTHH:MM:SS' for last_24_hours.
2027 # Entry: $preset -- one entry of @TIME_RANGES.
2028 # $now -- epoch second; defaults to the clock, and a caller may
2029 # pass one so a test can name the day it is asking about.
2030 # Exit: Two-element list, or an empty list for a preset with no window.
2031 # Notes: "This month" and "this quarter" end today rather than at the end of
2032 # the period, which is what the same names mean in a search bar; the
2033 # completed period is last_month / last_quarter.
2034 39555 ▶sub _time_range_bounds {
Subroutine _time_range_bounds: called CC=11 SCAR=24.0
2035 39555 my ($preset, $now) = @_;
2036 39555 ▶ $now = time() unless defined $now;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $now 39530 25 39555
2037 # On the configured zone's clock (Util::frame_epoch), not the server's.
2038 39555 $now = Database::BI::Util::frame_epoch($now);
2039  
2040 39555 my @lt = localtime($now);
2041 39555 my ($mday, $mon, $year) = @lt[3, 4, 5]; # mon is 0-based
2042  
2043 39555 ▶ if ($preset->{hours}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($preset->{"hours"}) 3296 36259 39555
2044 3296 return (_iso_second($now - $preset->{hours} * 3600), _iso_second($now));
2045 }
2046  
2047 36259 my $today = _midday($mday, $mon, $year);
2048  
2049 36259 ▶ if (defined $preset->{day}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $preset->{"day"}) 6592 29667 36259
2050 6592 my $day = _midday($mday + $preset->{day}, $mon, $year);
2051 6592 return (_iso_day($day), _iso_day($day));
2052 }
2053  
2054 29667 ▶ if (defined $preset->{days}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $preset->{"days"}) 9888 19779 29667
2055 9888 return (_iso_day(_midday($mday - $preset->{days} + 1, $mon, $year)),
2056 _iso_day($today));
2057 }
2058  
2059 19779 ▶ if (defined $preset->{month}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $preset->{"month"}) 6593 13186 19779
2060 6593 my $m = $mon + $preset->{month};
2061 6593 ▶ return $preset->{month} == 0
Branch: 1 branch
BranchTrueFalseTotal
$preset->{'month'} == 0 ? : 3296 3297 6593
2062 ? (_iso_day(_midday(1, $mon, $year)), _iso_day($today))
2063 : (_iso_day(_midday(1, $m, $year)), _iso_day(_midday(0, $m + 1, $year)));
2064 }
2065  
2066 13186 ▶ if (defined $preset->{quarter}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $preset->{"quarter"}) 6593 6593 13186
2067 6593 my $q = int($mon / 3) * 3 + 3 * $preset->{quarter};
2068 6593 ▶ return $preset->{quarter} == 0
Branch: 1 branch
BranchTrueFalseTotal
$preset->{'quarter'} == 0 ? : 3296 3297 6593
2069 ? (_iso_day(_midday(1, $q, $year)), _iso_day($today))
2070 : (_iso_day(_midday(1, $q, $year)), _iso_day(_midday(0, $q + 3, $year)));
2071 }
2072  
2073 6593 ▶ if (defined $preset->{year}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $preset->{"year"}) 6592 1 6593
2074 6592 my $y = $preset->{year}; # 0 = this year, -1 = last year
2075 6592 my $start = _midday(1, 0, $year + $y);
2076 6592 ▶ return $preset->{year} == 0
Branch: 1 branch
BranchTrueFalseTotal
$preset->{'year'} == 0 ? : 3296 3296 6592
2077 ? (_iso_day($start), _iso_day($today))
2078 : (_iso_day($start), _iso_day(_midday(31, 11, $year + $y)));
2079 }
2080  
2081 1 return ();
2082 }
2083  
2084 # _time_range_specs($col, $lo, $hi) -> \@specs
2085 #
2086 # Purpose: Express a window as the f= filters the pipeline applies.
2087 # Notes: Two bounds -- col:ge:lo and col:le:hi -- rather than one between
2088 # spec. A between value is "lo:hi", and its colon has to be found
2089 # among a timestamp's own (_between_bounds; last_24_hours ends in
2090 # HH:MM:SS); one bound per spec needs no such search. Two specs are
2091 # inclusive at both ends exactly once, whatever precision the bounds
2092 # carry.
2093 7 ▶sub _time_range_specs {
Subroutine _time_range_specs: called CC=7 SCAR=19.6
2094 7 my ($col, $lo, $hi) = @_;
2095 7 ▶ return [] unless length($col // '') && length($lo // '') && length($hi // '');
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and length($lo // "") and length($hi // "") 4 3 7
Condition83%10/12
length($col // "") and length($lo // "") and length($hi // "")
!ll&&!rl&&r
313
length($col // "") and length($lo // "")
!ll&&!rl&&r
214
$col // ""
l!l
61
$lo // ""
l!l
50
$hi // ""
l!l
40
MC/DC33%1/3
length($col // "") and length($lo // "") and length($hi // "")
$col $lo $hi
Truth table50%2/4
A and B and C
A= $colB= $loC= $hi
ABCresult
0XX0
10X0
1100
1111
2096 3 return [ "$col:ge:$lo", "$col:le:$hi" ];
2097 }
2098  
2099 # _time_range_preset($name) -> \%preset | undef
2100 #
2101 # The named entry of the vocabulary above, or undef for a name that is not in
2102 # it. A URL value reaches this, so it answers undef rather than croaking.
2103 17 ▶sub _time_range_preset {
Subroutine _time_range_preset: called CC=2 SCAR=6.9
2104 17 my ($name) = @_;
2105 17 ▶ return $TIME_RANGE{$name // ''};
Condition100%2/2
$name // ""
l!l
161
MC/DC100%1/1
$name // ""
$name
Truth table100%2/2
A
A= $name
Aresult
11
00
2106 }
2107  
2108 # _time_range_presets($now) -> \@presets
2109 #
2110 # Purpose: The menu a filter bar offers, with the dates each entry currently
2111 # resolves to, so the page can show a range and, where it has asked
2112 # for the dataset's own extent, disable an entry the data cannot
2113 # answer.
2114 3295 ▶sub _time_range_presets {
Subroutine _time_range_presets: called CC=1 SCAR=0.0
2115 3295 my ($now) = @_;
2116 return [ map {
2117 3295 my ($lo, $hi) = _time_range_bounds($_, $now);
2118 39540 { name => $_->{name}, label => $_->{label}, lo => $lo, hi => $hi }
2119 } @TIME_RANGES ];
2120 }
2121  
2122 # _apply_time_range($records, $name, $col) -> \@records
2123 #
2124 # Purpose: Apply a named relative range to a record set. Used by the canvas,
2125 # which renders its cards from its own pipeline rather than through a
2126 # route's f= params.
2127 # Entry: $name and $col are the URL values; neither is trusted. An unknown
2128 # name or an unusable column leaves the records alone, so a stale
2129 # bookmark shows unfiltered data rather than an error page.
2130 42 ▶sub _apply_time_range {
Subroutine _apply_time_range: called CC=7 SCAR=19.5
2131 42 my ($records, $name, $col) = @_;
2132 42 ▶ my $preset = $TIME_RANGE{$name // ''} or return $records;
Branch: 1 branch
BranchTrueFalseTotal
my $preset = $TIME_RANGE{$name // ""} or return $records 4 38 42
Condition100%2/2
$name // ""
l!l
636
MC/DC100%1/1
$name // ""
$name
Truth table100%2/2
A
A= $name
Aresult
11
00
2133 4 ▶ return $records unless defined $col && length $col && $col !~ /:/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col and length $col and not $col =~ /:/u 3 1 4
Condition100%6/6
defined $col and length $col and not $col =~ /:/u
!ll&&!rl&&r
211
defined $col and length $col
!ll&&!rl&&r
112
MC/DC100%3/3
defined $col and length $col and not $col =~ /:/u
defined $col length $col not $col =~ /:/u
Truth table100%4/4
A and B and not(C)
A= defined $colB= length $colC= not $col =~ /:/u
ABCresult
0XX0
10X0
1100
1111
2134 1 my ($lo, $hi) = _time_range_bounds($preset);
2135 1 for my $spec (@{ _time_range_specs($col, $lo, $hi) }) {
2136 2 $records = _apply_filter_spec($records, $spec);
2137 }
2138 1 return $records;
2139 }
2140  
2141 # _time_range_request($c) -> bool
2142 #
2143 # Purpose: Turn the relative time range a request names -- ?range=<name> and
2144 # ?rcol=<column> -- into the f= filters every data route already
2145 # applies, and describe the range on the stash so a template can show
2146 # a chip and the preset menu. Registered as a before_dispatch hook in
2147 # Database::BI::startup, so one implementation covers the table view,
2148 # every chart, the pivot, stats, insights, the exports and the canvas,
2149 # and a request that carries a range needs no per-route code.
2150 # Entry: $c -- the controller for the request.
2151 # Exit: Records the resolved bounds on the stash, where _filter_specs picks
2152 # them up for whichever pipeline the route runs, and returns true --
2153 # or renders 400 for a range that cannot be honoured and returns
2154 # false, which stops the route from running against the wrong rows.
2155 # The bounds are not written back into the request's f= params, so the
2156 # reader's own filter list -- the chips, the panel forms and the
2157 # filter UI -- never shows a range as dates it did not choose.
2158 3294 ▶sub _time_range_request ($c) {
Subroutine _time_range_request: called CC=7 SCAR=19.5
2159 3294 my $name = $c->param('range');
2160 3294 my $col = $c->param('rcol');
2161  
2162 3294 $c->stash(time_range_presets => _time_range_presets());
2163 3294 $c->stash(range_specs => []);
2164  
2165 3294 ▶ return 1 unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 3074 220 3294
Condition100%3/3
defined $name and length $name
!ll&&!rl&&r
303440220
MC/DC100%2/2
defined $name and length $name
defined $name length $name
Truth table100%3/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
2166  
2167 220 my $preset = $TIME_RANGE{$name};
2168 220 ▶ unless ($preset) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($preset) 218 2 220
2169 $c->render(
2170 text => sprintf(_message_text('error_range_name'), $name,
2171 218 join(', ', map { $_->{name} } @TIME_RANGES)),
2172 status => 400,
2173 );
2174 218 return 0;
2175 }
2176 2 ▶ unless (defined $col && length $col && $col !~ /:/) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $col and length $col and not $col =~ /:/u) 1 1 2
Condition66%4/6
defined $col and length $col and not $col =~ /:/u
!ll&&!rl&&r
101
defined $col and length $col
!ll&&!rl&&r
101
MC/DC33%1/3
defined $col and length $col and not $col =~ /:/u
defined $col length $col not $col =~ /:/u
Truth table50%2/4
A and B and not(C)
A= defined $colB= length $colC= not $col =~ /:/u
ABCresult
0XX0
10X0
1100
1111
2177 1 $c->render(text => _message_text('error_range_column'), status => 400);
2178 1 return 0;
2179 }
2180  
2181 1 my ($lo, $hi) = _time_range_bounds($preset);
2182 1 my $specs = _time_range_specs($col, $lo, $hi);
2183  
2184 $c->stash(
2185 time_range => {
2186 name => $preset->{name},
2187 label => $preset->{label},
2188 1 col => $col,
2189 lo => $lo,
2190 hi => $hi,
2191 },
2192 range_specs => $specs,
2193 );
2194 1 return 1;
2195 }
2196  
2197 # _filter_request($c) -> bool
2198 #
2199 # Purpose: Refuse an f= filter whose operator is not one _apply_filter_spec
2200 # knows. Until 0.021.0 such a filter kept every row, with nothing to
2201 # say it had done nothing (f=amount:GT:5, f=amount:gtx:5). Registered
2202 # as a before_dispatch hook in Database::BI::startup beside the time
2203 # range's, so every route that reads f= refuses it the same way.
2204 # Entry: $c -- the controller for the request.
2205 # Exit: True when every filter names a known operator, or has no column or
2206 # operator at all (such a spec has always been skipped); otherwise
2207 # renders 400 (error_filter_op, which lists the operators) and
2208 # returns false.
2209 # Notes: A filter on a column the view does not have is refused later, once
2210 # the columns are known (_unknown_filter_column). A canvas card's own
2211 # stored filters never come through here: they are ignored when stale,
2212 # by design.
2213 3072 ▶sub _filter_request ($c) {
Subroutine _filter_request: called CC=8 SCAR=20.9
2214 3072 ▶ for my $spec (@{ $c->every_param('f') // [] }) {
Condition50%1/2
$c->every_param("f") // []
l!l
30720
MC/DC0%0/1
$c->every_param("f") // []
$c->every_param("f")
Truth table50%1/2
A
A= $c->every_param("f")
Aresult
11
00
2215 165 my ($col, $op) = split /:/, $spec, 3;
2216 165 ▶ next unless length($col // '') && defined $op && length $op;
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and defined $op and length $op 63 102 165
Condition87%7/8
length($col // "") and defined $op and length $op
!ll&&!rl&&r
630102
length($col // "") and defined $op
!ll&&!rl&&r
4320102
$col // ""
l!l
12441
MC/DC66%2/3
length($col // "") and defined $op and length $op
$col defined $op length $op
Truth table75%3/4
A and B and C
A= $colB= defined $opC= length $op
ABCresult
0XX0
10X0
1100
1111
2217 102 ▶ next if $FILTER_OP{$op};
Branch: 1 branch
BranchTrueFalseTotal
if $FILTER_OP{$op} 96 6 102
2218 6 $c->render(
2219 text => sprintf(_message_text('error_filter_op'), $op, $spec, join(', ', @FILTER_OPS)),
2220 status => 400,
2221 );
2222 6 return 0;
2223 }
2224 3066 return 1;
2225 }
2226  
2227 # _unknown_filter_column($self, \@columns, \%later) -> $message | undef
2228 #
2229 # Purpose: The refusal for a filter, or the time range, on a column the view
2230 # does not have. Such a filter used to read every cell as empty and
2231 # keep no rows (or every row, for ne and empty), so a mistyped name
2232 # looked like an empty file.
2233 # Entry: \@columns -- the view's columns at the filter stage; \%later -- the
2234 # columns stages 6 and 7 will add (a filter on one waits for them).
2235 # Exit: undef when every filter names a column there, or when the columns
2236 # are not known (no list, or an empty one: a URL source's cache, or
2237 # a view with no rows); else the error_filter_column message (or
2238 # error_range_column_unknown for rcol=), naming the columns there.
2239 # Notes: A plain function, like _reduce_records, which calls it; _fetch_page
2240 # calls it too, for the table pages.
2241 949 ▶sub _unknown_filter_column {
Subroutine _unknown_filter_column: called CC=16 SCAR=29.3
2242 949 my ($self, $columns, $later) = @_;
2243 949 ▶ return undef unless ref $columns eq 'ARRAY' && @{$columns};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $columns eq "ARRAY" and @{$columns;} 10 939 949
Condition66%2/3
ref $columns eq "ARRAY" and @{$columns;}
!ll&&!rl&&r
100939
MC/DC50%1/2
ref $columns eq "ARRAY" and @{$columns;}
ref $columns eq "ARRAY" @{$columns;}
Truth table66%2/3
A and B
A= ref $columns eq "ARRAY"B= @{$columns;}
ABresult
0X0
100
111
2244 939 ▶ my %known = ((map { $_ => 1 } @{$columns}), %{ $later // {} });
Condition50%1/2
$later // {}
l!l
9390
MC/DC0%0/1
$later // {}
$later
Truth table50%1/2
A
A= $later
Aresult
11
00
2245 4 ▶ my $listed = sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
2246 4 my @names = @{$columns};
2247 4 ▶ return join(', ', @names) if @names <= $FILTER_COLUMNS_LISTED;
Branch: 1 branch
BranchTrueFalseTotal
if @names <= $FILTER_COLUMNS_LISTED 4 0 4
2248 0 return join(', ', @names[0 .. $FILTER_COLUMNS_LISTED - 1])
2249 . sprintf(' and %d more', @names - $FILTER_COLUMNS_LISTED);
2250 939 };
2251 939 ▶ for my $spec (@{ $self->every_param('f') // [] }) {
Condition50%1/2
$self->every_param("f") // []
l!l
9390
MC/DC0%0/1
$self->every_param("f") // []
$self->every_param("f")
Truth table50%1/2
A
A= $self->every_param("f")
Aresult
11
00
2252 110 my ($col, $op, $val) = split /:/, $spec, 3;
2253 110 ▶ next unless length($col // '') && defined $op && length $op;
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and defined $op and length $op 11 99 110
Condition62%5/8
length($col // "") and defined $op and length $op
!ll&&!rl&&r
11099
length($col // "") and defined $op
!ll&&!rl&&r
01199
$col // ""
l!l
1100
MC/DC33%1/3
length($col // "") and defined $op and length $op
$col defined $op length $op
Truth table50%2/4
A and B and C
A= $colB= defined $opC= length $op
ABCresult
0XX0
10X0
1100
1111
2254 # A differ filter names a second column, in its value.
2255 99 ▶ my @named = ($op eq 'differ') ? ($col, $val // '') : ($col);
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'differ' ? : 0 99 99
Condition0%0/2
$val // ""
l!l
00
MC/DC0%0/1
$val // ""
$val
Truth table0%0/2
A
A= $val
Aresult
11
00
2256 99 my ($missing) = grep { !$known{$_} } @named;
2257 99 ▶ next unless defined $missing;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $missing 96 3 99
2258 3 return sprintf(_message_text('error_filter_column'), $missing, $spec, $listed->());
2259 }
2260 936 my $range = $self->stash('time_range');
2261 936 ▶ if (ref $range eq 'HASH' && !$known{ $range->{col} // '' }) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $range eq "HASH" and not $known{$range->{"col"} // ""}) 1 935 936
Condition60%3/5
ref $range eq "HASH" and not $known{$range->{"col"} // ""}
!ll&&!rl&&r
93501
$range->{"col"} // ""
l!l
10
MC/DC50%1/2
ref $range eq "HASH" and not $known{$range->{"col"} // ""}
ref $range eq "HASH" not $known{$range->{"col"} // ""}
MC/DC0%0/1
$range->{"col"} // ""
$range->{"col"}
Truth table66%2/3
A and not(B)
A= ref $range eq "HASH"B= not $known{$range->{"col"} // ""}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $range->{"col"}
Aresult
11
00
2262 1 return sprintf(_message_text('error_range_column_unknown'), $range->{col}, $range->{col}, $listed->());
2263 }
2264 935 return undef;
2265 }
2266  
2267 # _filter_in_values($val) -> @strings
2268 #
2269 # The values an f=col:in:<val> filter lists: $val is a JSON array, and only its
2270 # plain scalars count (a null is the empty cell). Anything else lists nothing,
2271 # so a damaged link matches no row rather than every row.
2272 62 ▶sub _filter_in_values {
Subroutine _filter_in_values: called CC=5 SCAR=16.1
2273 62 my ($val) = @_;
2274 62 local $@;
2275 62 my $list;
2276 62 ▶ return () unless eval { $list = from_json($val // q{}); 1 };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $list = from_json($val // ""); 1 } } 7 55 62
Condition100%2/2
$val // ""
l!l
611
MC/DC100%1/1
$val // ""
$val
Truth table100%2/2
A
A= $val
Aresult
11
00
2277 55 ▶ return () unless ref($list) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" 4 51 55
2278 51 ▶ return map { $_ // '' } grep { !ref } @{$list};
Condition100%2/2
$_ // ""
l!l
962
MC/DC100%1/1
$_ // ""
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
2279 }
2280  
2281 # _between_bounds($val) -> ($lo, $hi) | ()
2282 #
2283 # Purpose: Split a between value, "lo:hi", into its two bounds. The
2284 # separator is a colon, and a timestamp holds colons of its own, so
2285 # the split is made where both sides read as dates or timestamps if
2286 # there is such a place, and at the first colon otherwise.
2287 # Input: $val - the filter value.
2288 # Output: The two bounds, both non-empty, in the order written; the empty
2289 # list when there is no colon or either side is empty.
2290 26 ▶sub _between_bounds {
Subroutine _between_bounds: called CC=9 SCAR=22.0
2291 26 my ($val) = @_;
2292 26 ▶ return () unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 1 25 26
2293 25 my @at;
2294 25 my $pos = -1;
2295 25 ▶ push @at, $pos while ($pos = index($val, ':', $pos + 1)) != -1;
Branch: 1 branch
BranchTrueFalseTotal
($pos = CORE::index($val, ":", $pos + 1)) != -1 and do { push @at, $pos } 35 25 60
2296 25 ▶ return () unless @at;
Branch: 1 branch
BranchTrueFalseTotal
unless @at 3 22 25
2297 22 for my $i (@at) {
2298 30 my ($lo, $hi) = (substr($val, 0, $i), substr($val, $i + 1));
2299 30 ▶ return ($lo, $hi) if _is_iso_date($lo) && _is_iso_date($hi);
Branch: 1 branch
BranchTrueFalseTotal
if _is_iso_date($lo) and _is_iso_date($hi) 10 20 30
Condition100%3/3
_is_iso_date($lo) and _is_iso_date($hi)
!ll&&!rl&&r
17310
MC/DC100%2/2
_is_iso_date($lo) and _is_iso_date($hi)
_is_iso_date($lo) _is_iso_date($hi)
Truth table100%3/3
A and B
A= _is_iso_date($lo)B= _is_iso_date($hi)
ABresult
0X0
100
111
2300 }
2301 12 my ($lo, $hi) = (substr($val, 0, $at[0]), substr($val, $at[0] + 1));
2302 12 ▶ return () unless length $lo && length $hi;
Branch: 1 branch
BranchTrueFalseTotal
unless length $lo and length $hi 3 9 12
Condition100%3/3
length $lo and length $hi
!ll&&!rl&&r
219
MC/DC100%2/2
length $lo and length $hi
length $lo length $hi
Truth table100%3/3
A and B
A= length $loB= length $hi
ABresult
0X0
100
111
2303 9 return ($lo, $hi);
2304 }
2305  
2306 # _filter_date_key($cell, $precision) -> $key
2307 #
2308 # The comparable form of a cell in a date filter: what
2309 # _date_key(_to_iso_date($cell) // $cell, $precision) // $cell gives, read with
2310 # one pattern match instead of two.
2311 #
2312 # Premise 1: _to_iso_date returns an ISO cell unchanged, and _date_key then
2313 # reads that same cell again.
2314 # Premise 2: reading a cell twice gives the same answer both times.
2315 # Conclusion: an ISO cell is read once and keyed at once. Only a M/D/YYYY cell
2316 # is rewritten first, and a cell that is neither is its own key.
2317 63 ▶sub _filter_date_key {
Subroutine _filter_date_key: called CC=9 SCAR=22.0
2318 63 my ($cell, $precision) = @_;
2319 63 my @part = Database::BI::Util::iso_datetime($cell);
2320 63 ▶ if (!@part && defined $cell && $cell =~ m{\A(\d{1,2})/(\d{1,2})/(\d{4})\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @part and defined $cell and $cell =~ m[\A(\d{1,2})/(\d{1,2})/(\d{4})\z]u) 5 58 63
Condition100%6/6
not @part and defined $cell and $cell =~ m[\A(\d{1,2})/(\d{1,2})/(\d{4})\z]u
!ll&&!rl&&r
47115
not @part and defined $cell
!ll&&!rl&&r
46116
MC/DC100%3/3
not @part and defined $cell and $cell =~ m[\A(\d{1,2})/(\d{1,2})/(\d{4})\z]u
not @part defined $cell $cell =~ m[\A(\d{1,2})/(\d{1,2})/(\d{4})\z]u
Truth table100%4/4
not(A) and B and C
A= not @partB= defined $cellC= $cell =~ m[\A(\d{1,2})/(\d{1,2})/(\d{4})\z]u
ABCresult
0XX0
10X0
1100
1111
2321 5 @part = Database::BI::Util::iso_datetime(sprintf '%04d-%02d-%02d', $3, $1, $2);
2322 }
2323 63 ▶ return $cell unless @part;
Branch: 1 branch
BranchTrueFalseTotal
unless @part 12 51 63
2324 51 my ($day, $hour, $min, $sec) = @part;
2325 51 ▶ return $day if $precision < 19;
Branch: 1 branch
BranchTrueFalseTotal
if $precision < 19 33 18 51
2326 18 ▶ return sprintf '%sT%s:%s:%s', $day, $hour // '00', $min // '00', $sec // '00';
Condition100%6/6
$hour // "00"
l!l
171
$min // "00"
l!l
171
$sec // "00"
l!l
162
MC/DC100%1/1
$hour // "00"
$hour
MC/DC100%1/1
$min // "00"
$min
MC/DC100%1/1
$sec // "00"
$sec
Truth table100%2/2
A
A= $hour
Aresult
11
00
Truth table100%2/2
A
A= $min
Aresult
11
00
Truth table100%2/2
A
A= $sec
Aresult
11
00
2327 }
2328  
2329 354 ▶sub _apply_filter_spec {
Subroutine _apply_filter_spec: called CC=62 SCAR=41.6
2330 354 my ($records, $spec) = @_;
2331 354 my ($col, $op, $val) = split /:/, $spec, 3;
2332 354 ▶ return $records unless length($col // '') && defined $op && length $op;
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and defined $op and length $op 17 337 354
Condition100%8/8
length($col // "") and defined $op and length $op
!ll&&!rl&&r
161337
length($col // "") and defined $op
!ll&&!rl&&r
313338
$col // ""
l!l
3531
MC/DC100%3/3
length($col // "") and defined $op and length $op
$col defined $op length $op
Truth table100%4/4
A and B and C
A= $colB= defined $opC= length $op
ABCresult
0XX0
10X0
1100
1111
2333 337 ▶ $val //= '';
Condition50%1/2
$val //= ""
l!l
3370
MC/DC0%0/1
$val //= ""
$val
Truth table50%1/2
A
A= $val
Aresult
11
00
2334 # differ: the value is a column name, and a row stays when its two cells do
2335 # not hold identical text. A row that lacks a column counts as empty there,
2336 # which also keeps a locked SQL row from croaking on a key it does not have.
2337 #
2338 # Premise 1: a differ compares two cells as text and nothing else.
2339 # Premise 2: the date, number, between and in set-up below is read only by
2340 # the other operators.
2341 # Conclusion: a differ returns here, before paying for any of it.
2342 337 ▶ if ($op eq 'differ') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "differ") 2 335 337
2343 2 ▶ my $text = sub { exists $_[0]{ $_[1] } ? ($_[0]{ $_[1] } // '') : '' };
Subroutine __ANON__: called CC=3 SCAR=11.1
Branch: 1 branch
BranchTrueFalseTotal
exists $_[0]{$_[1]} ? : 20 0 20
Condition100%2/2
$_[0]{$_[1]} // ""
l!l
182
MC/DC100%1/1
$_[0]{$_[1]} // ""
$_[0]{$_[1]}
Truth table100%2/2
A
A= $_[0]{$_[1]}
Aresult
11
00
2344 2 return [grep { $text->($_, $col) ne $text->($_, $val) } @{$records}];
2345 }
2346 335 my $lval = lc $val; # precompute once; avoids O(N) redundant lc() inside grep
2347 335 my $between = $op eq 'between';
2348 335 ▶ my ($lo, $hi) = $between ? _between_bounds($val) : ();
Branch: 1 branch
BranchTrueFalseTotal
$between ? : 21 314 335
2349 # A between is about times only when both its bounds are.
2350 335 ▶ my $is_date = $between
Branch: 1 branch
BranchTrueFalseTotal
$between ? : 21 314 335
Condition83%5/6
defined $lo and _is_iso_date($lo) and _is_iso_date($hi)
!ll&&!rl&&r
1209
defined $lo and _is_iso_date($lo)
!ll&&!rl&&r
489
MC/DC66%2/3
defined $lo and _is_iso_date($lo) and _is_iso_date($hi)
defined $lo _is_iso_date($lo) _is_iso_date($hi)
Truth table75%3/4
A and B and C
A= defined $loB= _is_iso_date($lo)C= _is_iso_date($hi)
ABCresult
0XX0
10X0
1100
1111
2351 ? (defined $lo && _is_iso_date($lo) && _is_iso_date($hi))
2352 : _is_iso_date($val);
2353 # Compare at the precision the bound names: a bound with a time in it asks
2354 # about the second, a bare date asks about the day. Without this, a date
2355 # bound compared against a column of timestamps drops every row on the
2356 # boundary day, because the cell string carries more characters than the
2357 # bound and "2026-10-27T09:15:00" sorts after "2026-10-27".
2358 335 ▶ my $prec = ($is_date && (grep { defined((Database::BI::Util::iso_datetime($_))[1]) }
Branch: 2 branches
BranchTrueFalseTotal
$is_date && grep({defined((Database::BI::Util::iso_datetime($_))[1]);} $between ? ($lo, $hi) : $val) ? : 3 332 335
$between ? : 9 2 11
Condition100%3/3
$is_date and grep {defined((Database::BI::Util::iso_datetime($_))[1]);} $between ? ($lo, $hi) : $val
!ll&&!rl&&r
32483
MC/DC100%2/2
$is_date and grep {defined((Database::BI::Util::iso_datetime($_))[1]);} $between ? ($lo, $hi) : $val
$is_date grep {defined((Database::BI::Util::iso_datetime($_))[1]);} $between ? ($lo, $hi) : $val
Truth table100%3/3
A and B
A= $is_dateB= grep {defined((Database::BI::Util::iso_datetime($_))[1]);} $between ? ($lo, $hi) : $val
ABresult
0X0
100
111
2359 $between ? ($lo, $hi) : ($val))) ? 19 : 10;
2360 335 ▶ my $nval = $is_date && !$between ? (_date_key($val, $prec) // $val) : $val;
Branch: 1 branch
BranchTrueFalseTotal
$is_date && !$between ? : 2 333 335
Condition66%4/6
$is_date and not $between
!ll&&!rl&&r
32492
_date_key($val, $prec) // $val
l!l&&r!l&&!r
200
MC/DC100%2/2
$is_date and not $between
$is_date not $between
MC/DC0%0/2
_date_key($val, $prec) // $val
_date_key($val, $prec) $val
Truth table100%3/3
A and not(B)
A= $is_dateB= not $between
ABresult
0X0
100
111
Truth table33%1/3
A // B
A= _date_key($val, $prec)B= $val
ABresult
1X1
011
000
2361 # An order is a statement about numbers. A blank or a word has no place in
2362 # one, so it matches none of the four, rather than counting as zero.
2363 335 ▶ my $by_number = !$is_date && $op =~ /\A(?:lt|le|gt|ge)\z/;
Condition100%3/3
!$is_date && $op =~ /\A(?:lt|le|gt|ge)\z/u
!ll&&!rl&&r
1129826
MC/DC100%2/2
!$is_date && $op =~ /\A(?:lt|le|gt|ge)\z/u
!$is_date $op =~ /\A(?:lt|le|gt|ge)\z/u
Truth table100%3/3
not(A) && B
A= !$is_dateB= $op =~ /\A(?:lt|le|gt|ge)\z/u
ABresult
0X0
100
111
2364 335 ▶ my $num_val = $by_number ? _numeric_cell($val) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$by_number ? : 26 309 335
2365 # A between of two numbers (a range of years, of prices) compares as
2366 # numbers, inclusive at both ends and whichever bound is written first;
2367 # "9" sorts after "10" as text. Anything else keeps the text comparison.
2368 # Dates and text likewise: the bounds are put in order before they are
2369 # used, so "2026-12-31:2026-01-01" is the year, not nothing.
2370 335 my ($num_lo, $num_hi);
2371 335 ▶ if ($between && defined $lo) {
Branch: 1 branch
BranchTrueFalseTotal
if ($between and defined $lo) 17 318 335
Condition100%3/3
$between and defined $lo
!ll&&!rl&&r
314417
MC/DC100%2/2
$between and defined $lo
$between defined $lo
Truth table100%3/3
A and B
A= $betweenB= defined $lo
ABresult
0X0
100
111
2372 17 ▶ if ($is_date) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_date) { } 9 8 17
2373 9 ▶ ($lo, $hi) = map { _date_key($_, $prec) // $_ } $lo, $hi;
Condition33%1/3
_date_key($_, $prec) // $_
l!l&&r!l&&!r
1800
MC/DC0%0/2
_date_key($_, $prec) // $_
_date_key($_, $prec) $_
Truth table33%1/3
A // B
A= _date_key($_, $prec)B= $_
ABresult
1X1
011
000
2374 } else {
2375 8 ($num_lo, $num_hi) = (_numeric_cell($lo), _numeric_cell($hi));
2376 8 ▶ ($num_lo, $num_hi) = (undef, undef) unless defined $num_lo && defined $num_hi;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $num_lo and defined $num_hi 4 4 8
Condition66%2/3
defined $num_lo and defined $num_hi
!ll&&!rl&&r
404
MC/DC50%1/2
defined $num_lo and defined $num_hi
defined $num_lo defined $num_hi
Truth table66%2/3
A and B
A= defined $num_loB= defined $num_hi
ABresult
0X0
100
111
2377 8 ($lo, $hi) = (lc $lo, lc $hi);
2378 }
2379 17 ▶ ($num_lo, $num_hi) = ($num_hi, $num_lo) if defined $num_lo && $num_lo > $num_hi;
Branch: 1 branch
BranchTrueFalseTotal
if defined $num_lo and $num_lo > $num_hi 1 16 17
Condition100%3/3
defined $num_lo and $num_lo > $num_hi
!ll&&!rl&&r
1331
MC/DC100%2/2
defined $num_lo and $num_lo > $num_hi
defined $num_lo $num_lo > $num_hi
Truth table100%3/3
A and B
A= defined $num_loB= $num_lo > $num_hi
ABresult
0X0
100
111
2380 17 ▶ ($lo, $hi) = ($hi, $lo) if $lo gt $hi;
Branch: 1 branch
BranchTrueFalseTotal
if $lo gt $hi 8 9 17
2381 }
2382 335 ▶ my %in_set = $op eq 'in' ? (map { lc($_) => 1 } _filter_in_values($val)) : ();
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'in' ? : 50 285 335
2383 return [grep {
2384 335 ▶ my $cell = $_->{$col} // '';
Condition100%2/2
$_->{$col} // ""
l!l
97137
MC/DC100%1/1
$_->{$col} // ""
$_->{$col}
Truth table100%2/2
A
A= $_->{$col}
Aresult
11
00
2385 1008 ▶ my $num = $by_number ? _numeric_cell($cell) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$by_number ? : 84 924 1008
2386 1008 ▶ my $both = defined $num && defined $num_val;
Condition100%3/3
defined $num && defined $num_val
!ll&&!rl&&r
925182
MC/DC100%2/2
defined $num && defined $num_val
defined $num defined $num_val
Truth table100%3/3
A && B
A= defined $numB= defined $num_val
ABresult
0X0
100
111
2387 # Normalise M/D/YYYY cells to ISO for date comparisons so that the
2388 # ISO values produced by <input type="date"> match against either format.
2389 1008 ▶ my $ncell = $is_date ? _filter_date_key($cell, $prec) : $cell;
Branch: 1 branch
BranchTrueFalseTotal
$is_date ? : 43 965 1008
2390 $op eq 'eq' ? ($is_date ? $ncell eq $nval : lc($cell) eq $lval) :
2391 $op eq 'ne' ? ($is_date ? $ncell ne $nval : lc($cell) ne $lval) :
2392 $op eq 'contains' ? index(lc($cell), $lval) != -1 :
2393 $op eq 'starts' ? index(lc($cell), $lval) == 0 :
2394 $op eq 'lt' ? ($is_date ? $ncell lt $nval : $both && $num < $num_val) :
2395 $op eq 'le' ? ($is_date ? $ncell le $nval : $both && $num <= $num_val) :
2396 $op eq 'gt' ? ($is_date ? $ncell gt $nval : $both && $num > $num_val) :
2397 $op eq 'ge' ? ($is_date ? $ncell ge $nval : $both && $num >= $num_val) :
2398 $op eq 'empty' ? $cell eq '' :
2399 $op eq 'notempty' ? $cell ne '' :
2400 $op eq 'in' ? $in_set{ lc($cell) } :
2401 $op eq 'between' && defined $num_lo ? do {
2402 40 my $n = _numeric_cell($cell);
2403 40 ▶ defined $n && $n >= $num_lo && $n <= $num_hi
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'between' ? : 82 11 93
Condition100%6/6
defined $n && $n >= $num_lo && $n <= $num_hi
!ll&&!rl&&r
20128
defined $n and $n >= $num_lo
!ll&&!rl&&r
81220
MC/DC100%3/3
defined $n && $n >= $num_lo && $n <= $num_hi
defined $n $n >= $num_lo $n <= $num_hi
Truth table100%4/4
A and B && C
A= defined $nB= $n >= $num_loC= $n <= $num_hi
ABCresult
0XX0
10X0
1100
1111
2404 } :
2405 1008 ▶ $op eq 'between' ? do {
Branch: 18 branches
BranchTrueFalseTotal
$op eq 'eq' ? : 453 555 1008
$is_date ? : 0 453 453
$op eq 'ne' ? : 22 533 555
$is_date ? : 0 22 22
$op eq 'contains' ? : 7 526 533
$op eq 'starts' ? : 10 516 526
$op eq 'lt' ? : 11 505 516
$is_date ? : 0 11 11
$op eq 'le' ? : 14 491 505
$is_date ? : 1 13 14
$op eq 'gt' ? : 42 449 491
$is_date ? : 0 42 42
$op eq 'ge' ? : 20 429 449
$is_date ? : 2 18 20
$op eq 'empty' ? : 22 407 429
$op eq 'notempty' ? : 23 384 407
$op eq 'in' ? : 251 133 384
$op eq 'between' && defined $num_lo ? : 40 93 133
Condition80%12/15
$both and $num < $num_val
!ll&&!rl&&r
074
$both and $num <= $num_val
!ll&&!rl&&r
076
$both and $num > $num_val
!ll&&!rl&&r
21327
$both and $num >= $num_val
!ll&&!rl&&r
0810
$op eq "between" and defined $num_lo
!ll&&!rl&&r
118240
MC/DC50%1/2
$both and $num < $num_val
$both $num < $num_val
MC/DC50%1/2
$both and $num <= $num_val
$both $num <= $num_val
MC/DC100%2/2
$both and $num > $num_val
$both $num > $num_val
MC/DC50%1/2
$both and $num >= $num_val
$both $num >= $num_val
MC/DC100%2/2
$op eq "between" and defined $num_lo
$op eq "between" defined $num_lo
Truth table66%2/3
A and B
A= $bothB= $num < $num_val
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= $bothB= $num <= $num_val
ABresult
0X0
100
111
Truth table100%3/3
A and B
A= $bothB= $num > $num_val
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= $bothB= $num >= $num_val
ABresult
0X0
100
111
Truth table100%3/3
A and B
A= $op eq "between"B= defined $num_lo
ABresult
0X0
100
111
2406 82 ▶ my $key = $is_date ? $ncell : lc $cell;
Branch: 1 branch
BranchTrueFalseTotal
$is_date ? : 40 42 82
2407 82 ▶ defined $lo && $key ge $lo && $key le $hi
Condition100%6/6
defined $lo && $key ge $lo && $key le $hi
!ll&&!rl&&r
361432
defined $lo and $key ge $lo
!ll&&!rl&&r
241246
MC/DC100%3/3
defined $lo && $key ge $lo && $key le $hi
defined $lo $key ge $lo $key le $hi
Truth table100%4/4
A and B && C
A= defined $loB= $key ge $loC= $key le $hi
ABCresult
0XX0
10X0
1100
1111
2408 } :
2409 1
2410 } @$records];
2411 }
2412  
2413 # ---------------------------------------------------------------------------
2414 # The cross-row pass (BI-Phase-7.md item 7.2)
2415 # ---------------------------------------------------------------------------
2416 #
2417 # A measure folds a group into one number and a calculated field computes one
2418 # row from that row. This is the third shape: one row from many rows, written
2419 # back onto every row -- a running total, a moving average, a rank, a share of
2420 # the whole. None of them can be a measure (the answer is per row, not per
2421 # group) and none can be a calc field (it needs its neighbours), which is why
2422 # they are a pass of their own.
2423 #
2424 # The functions follow Splunk's split, because it is also the natural one:
2425 # the eventstats family is order-free (pct_of_total, rank, zscore), the
2426 # streamstats family is incremental and therefore needs an order (running_*,
2427 # window_*, lag, delta, pct_change).
2428  
2429 # The same vocabulary as a menu, for the panel that adds a cross-row column.
2430 # It is data rather than a list written into the template so the function
2431 # names, their labels and the two facts the form needs -- whether a function
2432 # takes a window, and whether it needs an order -- cannot drift from the
2433 # validator above.
2434 10 Readonly my @CROSS_ROW_MENU => (
2435 { name => 'running_total', label => 'Running total', arg => 0, order => 1 },
2436 { name => 'running_count', label => 'Running count', arg => 0, order => 1 },
2437 { name => 'running_pct', label => 'Running percent', arg => 0, order => 1 },
2438 { name => 'window_sum', label => 'Moving sum', arg => 1, order => 1 },
2439 { name => 'window_avg', label => 'Moving average', arg => 1, order => 1 },
2440 { name => 'lag', label => 'Previous row', arg => 0, order => 1 },
2441 { name => 'delta', label => 'Change from previous', arg => 0, order => 1 },
2442 { name => 'pct_change', label => 'Percent change', arg => 0, order => 1 },
2443 { name => 'pct_of_total', label => 'Percent of total', arg => 0, order => 0 },
2444 { name => 'rank', label => 'Rank, largest first', arg => 0, order => 0 },
2445 { name => 'zscore', label => 'Z-score', arg => 0, order => 0 },
2446 );
2447  
2448 10 Readonly my %CROSS_ROW_FNS => (
2449 running_total => { family => 'stream' },
2450 running_count => { family => 'stream' },
2451 running_pct => { family => 'stream' },
2452 window_sum => { family => 'stream', arg => 'count' },
2453 window_avg => { family => 'stream', arg => 'count' },
2454 lag => { family => 'stream' },
2455 delta => { family => 'stream' },
2456 pct_change => { family => 'stream' },
2457 pct_of_total => { family => 'event' },
2458 rank => { family => 'event' },
2459 zscore => { family => 'event' },
2460 );
2461  
2462 # _cross_row_specs($self, \@columns, $params) -> \%plan | { error => $message } | undef
2463 #
2464 # Purpose: Read cs=/by=/order= and turn them into a plan the pass can run:
2465 # which function writes which column, partitioned by what, ordered by
2466 # what. Nothing is evaluated here, so a request that names a column
2467 # or a function that does not exist is refused before a single row is
2468 # touched, and the refusal is a 400 rather than a chart of something
2469 # else.
2470 # Entry: \@columns -- the columns of this view, so a cs=/by=/order= column is
2471 # checked against what the reader can actually see.
2472 # $params -- where the three parameters are read from, or undef for
2473 # this request. Anything with param()/every_param() will
2474 # do: the canvas reads them from the canvas page's own query
2475 # string, because its cards are drawn against the canvas's
2476 # state rather than against whatever URL fetched them.
2477 # Exit: undef when the request names no cross-row column. Otherwise
2478 # { specs => [ { col, fn, as, arg } ], by => [col ...],
2479 # order => [ { col, dir } ] }, or { error => $message } for a
2480 # request that cannot be honoured.
2481 # Notes: The streamstats family reads its rows in order, so order= is
2482 # required for it and refused as missing by name. The eventstats
2483 # family does not care and does not require it.
2484 104 ▶sub _cross_row_specs :Protected ($self, $columns, $params = undef) {
Subroutine _cross_row_specs: called CC=6 SCAR=18.5
2485 104 ▶ my $p = $params // $self;
Condition66%2/3
$params // $self
l!l&&r!l&&!r
35690
MC/DC0%0/2
$params // $self
$params $self
Truth table66%2/3
A // B
A= $paramsB= $self
ABresult
1X1
011
000
2486  
2487 # The three values are the URL's spelling of a plan, read once here so the
2488 # parser below serves a canvas card too - a card stores its own plan as
2489 # { cs, by, order } rather than as a query string.
2490 return $self->_cross_row_specs_from($columns, {
2491 104 ▶ cs => [ @{ $p->every_param('cs') // [] } ],
Condition75%3/4
$p->every_param("cs") // []
l!l
1040
$p->param("by") // ""
l!l
2102
MC/DC0%0/1
$p->every_param("cs") // []
$p->every_param("cs")
MC/DC100%1/1
$p->param("by") // ""
$p->param("by")
Truth table50%1/2
A
A= $p->every_param("cs")
Aresult
11
00
Truth table100%2/2
A
A= $p->param("by")
Aresult
11
00
2492 by => ($p->param('by') // ''),
2493 104 ▶ order => [ @{ $p->every_param('order') // [] } ],
Condition50%1/2
$p->every_param("order") // []
l!l
1040
MC/DC0%0/1
$p->every_param("order") // []
$p->every_param("order")
Truth table50%1/2
A
A= $p->every_param("order")
Aresult
11
00
2494 });
2495 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2496  
2497 # _cross_row_specs_from($self, \@columns, \%raw) -> \%plan | { error } | undef
2498 #
2499 # Purpose: The same validation, from a plan as a saved canvas card stores it.
2500 # Entry: \%raw -- { cs => [spec ...], by => 'a,b', order => ['col:dir' ...] },
2501 # in the spelling cs=/by=/order= use.
2502 # Exit: As _cross_row_specs.
2503 121 ▶sub _cross_row_specs_from :Protected ($self, $columns, $raw) {
Subroutine _cross_row_specs_from: called CC=44 SCAR=38.8
2504 121 ▶ my @texts = grep { defined $_ && !ref $_ && length } @{ $raw->{cs} // [] };
Condition100%8/8
defined $_ && !ref($_) && length $_
!ll&&!rl&&r
2145
defined $_ and not ref $_
!ll&&!rl&&r
1146
$raw->{"cs"} // []
l!l
1201
MC/DC100%3/3
defined $_ && !ref($_) && length $_
defined $_ not ref $_ length $_
MC/DC100%1/1
$raw->{"cs"} // []
$raw->{"cs"}
Truth table100%4/4
A and not(B) && C
A= defined $_B= not ref $_C= length $_
ABCresult
0XX0
10X0
1100
1111
Truth table100%2/2
A
A= $raw->{"cs"}
Aresult
11
00
2505 121 ▶ return undef unless @texts;
Branch: 1 branch
BranchTrueFalseTotal
unless @texts 77 44 121
2506  
2507 44 ▶ my %col_set = map { $_ => 1 } @{ $columns // [] };
Condition50%1/2
$columns // []
l!l
440
MC/DC0%0/1
$columns // []
$columns
Truth table50%1/2
A
A= $columns
Aresult
11
00
2508 44 my %taken;
2509 my @specs;
2510  
2511 44 for my $text (@texts) {
2512 45 my ($col, $fn, $as, $arg) = split /:/, $text, 4;
2513 45 ▶ return { error => $self->_i18n('error_cs_spec', $text) }
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col and length $col and defined $fn and length $fn and defined $as and length $as 16 29 45
Condition80%12/15
defined $col and length $col and defined $fn and length $fn and defined $as and length $as
!ll&&!rl&&r
16029
defined $col and length $col and defined $fn and length $fn and defined $as
!ll&&!rl&&r
13329
defined $col and length $col and defined $fn and length $fn
!ll&&!rl&&r
13032
defined $col and length $col and defined $fn
!ll&&!rl&&r
11232
defined $col and length $col
!ll&&!rl&&r
0144
MC/DC50%3/6
defined $col and length $col and defined $fn and length $fn and defined $as and length $as
defined $col length $col defined $fn length $fn defined $as length $as
Truth table57%4/7
A and B and C and D and E and F
A= defined $colB= length $colC= defined $fnD= length $fnE= defined $asF= length $as
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
2514 unless defined $col && length $col
2515 && defined $fn && length $fn
2516 && defined $as && length $as;
2517  
2518 return { error => $self->_i18n('error_cs_column', $text, $col) }
2519 29 ▶ unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 3 26 29
2520  
2521 return { error => $self->_i18n('error_cs_fn', $fn, join(' ', sort keys %CROSS_ROW_FNS)) }
2522 26 ▶ unless $CROSS_ROW_FNS{$fn};
Branch: 1 branch
BranchTrueFalseTotal
unless $CROSS_ROW_FNS{$fn} 2 24 26
2523  
2524 24 ▶ return { error => $self->_i18n('error_cs_alias', $as) }
Branch: 1 branch
BranchTrueFalseTotal
unless $as =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/u 2 22 24
2525 unless $as =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/;
2526  
2527 return { error => $self->_i18n(q{error_cs_conflict}, $as) }
2528 22 ▶ if $col_set{$as} || $taken{$as};
Branch: 1 branch
BranchTrueFalseTotal
if $col_set{$as} or $taken{$as} 3 19 22
Condition100%3/3
$col_set{$as} or $taken{$as}
l!l&&r!l&&!r
2119
MC/DC100%2/2
$col_set{$as} or $taken{$as}
$col_set{$as} $taken{$as}
Truth table100%3/3
A or B
A= $col_set{$as}B= $taken{$as}
ABresult
1X1
011
000
2529 19 $taken{$as} = 1;
2530  
2531 19 my $decl = $CROSS_ROW_FNS{$fn};
2532 19 ▶ if ($decl->{arg}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($decl->{'arg'}) { } 4 15 19
elsif (defined $arg and length $arg) { } 2 26 28
2533 4 ▶ return { error => $self->_i18n('error_cs_arg', $text, $fn, $col, $fn) }
Branch: 1 branch
BranchTrueFalseTotal
unless defined $arg and $arg =~ /\A\d+\z/u and $arg > 0 4 0 4
Condition83%5/6
defined $arg and $arg =~ /\A\d+\z/u and $arg > 0
!ll&&!rl&&r
310
defined $arg and $arg =~ /\A\d+\z/u
!ll&&!rl&&r
211
MC/DC0%0/3
defined $arg and $arg =~ /\A\d+\z/u and $arg > 0
defined $arg $arg =~ /\A\d+\z/u $arg > 0
Truth table75%3/4
A and B and C
A= defined $argB= $arg =~ /\A\d+\z/uC= $arg > 0
ABCresult
0XX0
10X0
1100
1111
2534 unless defined $arg && $arg =~ /\A\d+\z/ && $arg > 0;
2535 }
2536 ▶ elsif (defined $arg && length $arg) {
Condition66%2/3
defined $arg and length $arg
!ll&&!rl&&r
1302
MC/DC50%1/2
defined $arg and length $arg
defined $arg length $arg
Truth table66%2/3
A and B
A= defined $argB= length $arg
ABresult
0X0
100
111
2537 2 return { error => $self->_i18n('error_cs_no_arg', $text, $fn) };
2538 }
2539  
2540 13 ▶ push @specs, {
Branch: 1 branch
BranchTrueFalseTotal
defined $arg && length $arg ? : 0 13 13
Condition33%1/3
defined $arg and length $arg
!ll&&!rl&&r
1300
MC/DC0%0/2
defined $arg and length $arg
defined $arg length $arg
Truth table33%1/3
A and B
A= defined $argB= length $arg
ABresult
0X0
100
111
2541 col => $col,
2542 fn => $fn,
2543 as => $as,
2544 arg => (defined $arg && length $arg) ? $arg + 0 : undef,
2545 };
2546 }
2547  
2548 # by= is the partition. An empty value is its own partition rather than a
2549 # dropped row: a windowed column has to cover every displayed row, which is
2550 # not the rule the pivot uses for a cell -- see the POD.
2551 12 ▶ my $by_text = (!ref $raw->{by} && defined $raw->{by}) ? "$raw->{by}" : '';
Branch: 1 branch
BranchTrueFalseTotal
!ref($raw->{'by'}) && defined $raw->{'by'} ? : 9 3 12
Condition66%2/3
not ref $raw->{"by"} and defined $raw->{"by"}
!ll&&!rl&&r
039
MC/DC50%1/2
not ref $raw->{"by"} and defined $raw->{"by"}
not ref $raw->{"by"} defined $raw->{"by"}
Truth table66%2/3
not(A) and B
A= not ref $raw->{"by"}B= defined $raw->{"by"}
ABresult
0X0
100
111
2552 12 my @by = grep { length } map { _trim($_) } split /,/, $by_text, -1;
2553 12 for my $c (@by) {
2554 4 ▶ return { error => $self->_i18n('error_cs_by', $by_text, $c) } unless $col_set{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$c} 2 2 4
2555 }
2556  
2557 10 my @order;
2558 10 ▶ for my $text (@{ $raw->{order} // [] }) {
Condition100%2/2
$raw->{"order"} // []
l!l
91
MC/DC100%1/1
$raw->{"order"} // []
$raw->{"order"}
Truth table100%2/2
A
A= $raw->{"order"}
Aresult
11
00
2559 7 ▶ my $spec = _trim((!ref $text && defined $text) ? $text : '');
Branch: 1 branch
BranchTrueFalseTotal
!ref($text) && defined $text ? : 7 0 7
Condition33%1/3
not ref $text and defined $text
!ll&&!rl&&r
007
MC/DC0%0/2
not ref $text and defined $text
not ref $text defined $text
Truth table33%1/3
not(A) and B
A= not ref $textB= defined $text
ABresult
0X0
100
111
2560 7 ▶ next unless length $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 0 7 7
2561 7 my ($c, $dir) = split /:/, $spec, 2;
2562 7 ▶ $c = _trim($c // '');
Condition50%1/2
$c // ""
l!l
70
MC/DC0%0/1
$c // ""
$c
Truth table50%1/2
A
A= $c
Aresult
11
00
2563 7 ▶ $dir = defined $dir && length $dir ? lc _trim($dir) : 'asc';
Branch: 1 branch
BranchTrueFalseTotal
defined $dir && length $dir ? : 3 4 7
Condition66%2/3
defined $dir and length $dir
!ll&&!rl&&r
403
MC/DC50%1/2
defined $dir and length $dir
defined $dir length $dir
Truth table66%2/3
A and B
A= defined $dirB= length $dir
ABresult
0X0
100
111
2564 7 ▶ return { error => $self->_i18n('error_cs_order', $spec) }
Branch: 1 branch
BranchTrueFalseTotal
unless length $c and $dir =~ /\A(?:asc|desc)\z/u 2 5 7
Condition66%2/3
length $c and $dir =~ /\A(?:asc|desc)\z/u
!ll&&!rl&&r
025
MC/DC50%1/2
length $c and $dir =~ /\A(?:asc|desc)\z/u
length $c $dir =~ /\A(?:asc|desc)\z/u
Truth table66%2/3
A and B
A= length $cB= $dir =~ /\A(?:asc|desc)\z/u
ABresult
0X0
100
111
2565 unless length $c && $dir =~ /\A(?:asc|desc)\z/;
2566 return { error => $self->_i18n('error_cs_order_col', $spec, $c) }
2567 5 ▶ unless $col_set{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$c} 2 3 5
2568 3 push @order, { col => $c, dir => $dir };
2569 }
2570  
2571 6 for my $spec (@specs) {
2572 6 ▶ next unless $CROSS_ROW_FNS{ $spec->{fn} }{family} eq 'stream';
Branch: 1 branch
BranchTrueFalseTotal
unless $CROSS_ROW_FNS{$spec->{"fn"}}{"family"} eq "stream" 2 4 6
2573 return {
2574 error => $self->_i18n('error_cs_order_need',
2575 join(':', $spec->{col}, $spec->{fn}, $spec->{as}), $spec->{fn})
2576 4 ▶ } unless @order;
Branch: 1 branch
BranchTrueFalseTotal
unless @order 2 2 4
2577 }
2578  
2579 4 return { specs => \@specs, by => \@by, order => \@order };
2580 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2581  
2582 # _card_plan($raw) -> \%plan | { error }
2583 #
2584 # Purpose: The cross-row plan a saved canvas card carries, in the spelling
2585 # cs=/by=/order= use, so a card added and a card repaired store the
2586 # same shape and the one parser above reads them both.
2587 # Entry: $raw -- the request's cross_row value. A hash that names no cs is
2588 # the card saying it runs no plan of its own; _cross_row_specs_from
2589 # reads that as no pass at all, and so does the renderer.
2590 # Exit: { cs => [...], by => '', order => [...] } -- only the shape is
2591 # checked here. Which columns exist is a fact about the data file and
2592 # is checked again on every render, so a plan written today is read
2593 # against the columns the canvas has today.
2594 # Notes: A part of the plan that is the wrong kind is an error rather than a
2595 # silently empty list: a repair that stores nothing still answers 200,
2596 # and the caller would have no way to know the card had not changed.
2597 7 ▶sub _card_plan {
Subroutine _card_plan: called CC=11 SCAR=24.0
2598 7 my ($raw) = @_;
2599  
2600 7 for my $key (qw(cs order)) {
2601 11 ▶ next unless defined $raw->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw->{$key} 5 6 11
2602 return { error => "cross_row.$key must be a list" }
2603 6 ▶ if ref $raw->{$key} ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $raw->{$key} ne "ARRAY" 3 3 6
2604 return { error => "cross_row.$key must be a list of strings" }
2605 3 ▶ if grep { ref } @{ $raw->{$key} };
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_;} @{$$raw{$key};} 1 2 3
2606 }
2607 3 ▶ return { error => 'cross_row.by must be a column name' } if ref $raw->{by};
Branch: 1 branch
BranchTrueFalseTotal
if ref $raw->{"by"} 1 2 3
2608  
2609 return {
2610 3 ▶ cs => [ grep { defined $_ && length } @{ $raw->{cs} // [] } ],
Branch: 1 branch
BranchTrueFalseTotal
defined $raw->{'by'} ? : 1 1 2
Condition100%5/5
defined $_ && length $_
!ll&&!rl&&r
111
$raw->{"cs"} // []
l!l
11
MC/DC100%2/2
defined $_ && length $_
defined $_ length $_
MC/DC100%1/1
$raw->{"cs"} // []
$raw->{"cs"}
Truth table100%3/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
Truth table100%2/2
A
A= $raw->{"cs"}
Aresult
11
00
2611 by => (defined $raw->{by} ? "$raw->{by}" : ''),
2612 2 ▶ order => [ grep { defined $_ && length } @{ $raw->{order} // [] } ],
Condition60%3/5
defined $_ && length $_
!ll&&!rl&&r
001
$raw->{"order"} // []
l!l
11
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
MC/DC100%1/1
$raw->{"order"} // []
$raw->{"order"}
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
Truth table100%2/2
A
A= $raw->{"order"}
Aresult
11
00
2613 };
2614 }
2615  
2616 # _cross_row_ui_state($c) -> %stash_pairs
2617 #
2618 # Purpose: The cross-row state the table page shows: the specs it puts in
2619 # chips, the partition and order its chart panels carry, and the
2620 # panel's own menu. Also the rest of the query string, because the
2621 # panel edits three parameters and must submit the others unchanged.
2622 # Entry: $c -- the controller, for its query string only.
2623 # Exit: A list suitable for stash(): cross_row_specs, cross_row_by,
2624 # cross_row_order, cross_row_menu, cross_row_hidden.
2625 # Notes: cs=/by=/order= are deliberately absent from cross_row_hidden. The
2626 # panel writes them from its own controls, and a hidden by= as well
2627 # would send two values; param('by') reads the first, so the reader's
2628 # choice would be silently ignored in favour of the old one.
2629 # Only the query string is read -- never the body -- because this runs
2630 # before dispatch on every request, including JSON posts.
2631 3296 ▶sub _cross_row_ui_state {
Subroutine _cross_row_ui_state: called CC=9 SCAR=22.0
2632 3296 my ($c) = @_;
2633  
2634 3296 my $query = $c->req->query_params;
2635 3296 ▶ my @specs = grep { length } @{ $query->every_param('cs') // [] };
Condition50%1/2
$query->every_param("cs") // []
l!l
32960
MC/DC0%0/1
$query->every_param("cs") // []
$query->every_param("cs")
Truth table50%1/2
A
A= $query->every_param("cs")
Aresult
11
00
2636 3296 ▶ my @orders = grep { length } @{ $query->every_param('order') // [] };
Condition50%1/2
$query->every_param("order") // []
l!l
32960
MC/DC0%0/1
$query->every_param("order") // []
$query->every_param("order")
Truth table50%1/2
A
A= $query->every_param("order")
Aresult
11
00
2637  
2638 3296 my @hidden;
2639 # names() is a list in some Mojo releases and an arrayref in others; taking
2640 # the arrayref is what both accept.
2641 3296 for my $name (@{ $query->names }) {
2642 18756 ▶ next if $name eq 'cs' || $name eq 'by' || $name eq 'order';
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "cs" or $name eq "by" or $name eq "order" 784 17972 18756
Condition100%6/6
$name eq "cs" or $name eq "by" or $name eq "order"
l!l&&r!l&&!r
52525917972
$name eq "cs" or $name eq "by"
l!l&&r!l&&!r
26825718231
MC/DC100%3/3
$name eq "cs" or $name eq "by" or $name eq "order"
$name eq "cs" $name eq "by" $name eq "order"
Truth table100%4/4
A or B or C
A= $name eq "cs"B= $name eq "by"C= $name eq "order"
ABCresult
1XX1
01X1
0011
0000
2643 18163 push @hidden, map { { name => $name, value => $_ } }
2644 17972 ▶ @{ $query->every_param($name) // [] };
Condition50%1/2
$query->every_param($name) // []
l!l
179720
MC/DC0%0/1
$query->every_param($name) // []
$query->every_param($name)
Truth table50%1/2
A
A= $query->every_param($name)
Aresult
11
00
2645 }
2646  
2647 return (
2648 3296 ▶ cross_row_specs => \@specs,
Condition100%2/2
$query->param("by") // ""
l!l
2573039
MC/DC100%1/1
$query->param("by") // ""
$query->param("by")
Truth table100%2/2
A
A= $query->param("by")
Aresult
11
00
2649 cross_row_by => ($query->param('by') // ''),
2650 cross_row_order => \@orders,
2651 cross_row_menu => \@CROSS_ROW_MENU,
2652 cross_row_hidden => \@hidden,
2653 );
2654 }
2655  
2656 # _apply_cross_row($self, $records, \@columns, $plan) -> ($records, \@columns)
2657 #
2658 # Purpose: Stage 6 of the pipeline: run every cs= spec over the rows and write
2659 # the answer onto each row as a column of its own. Called from
2660 # _reduce_records (the routes that reduce there) and from _fetch_page
2661 # after its own filtering (the routes that paginate), always before
2662 # anything slices a page, so page 2 continues page 1's running total.
2663 # Entry: $records -- arrayref of hashrefs, already filtered.
2664 # \@columns -- the columns list, or undef where the caller has none in
2665 # scope; then it is derived from the first row.
2666 # $plan -- an already validated plan from _cross_row_specs($columns,
2667 # $params), or undef to read this request's cs=. A canvas
2668 # validates once and runs the plan once per card, on each
2669 # card's own rows; re-reading cs= there would work today only
2670 # because the canvas page carries it, and would silently stop
2671 # working for a card redrawn by an API call.
2672 # Exit: ($records, \@columns) with the produced columns appended, or the
2673 # arguments untouched when the request names no cs=. Croaks with an
2674 # i18n message when a spec cannot be honoured; the caller renders 400.
2675 # Notes: Rows are grouped into partitions by by=, each partition is sorted
2676 # once (stable, ties in arrival order, so two runs over the same file
2677 # agree), and each spec is then one pass over each partition. A
2678 # partition total is accumulated in that pass, never per row.
2679 #
2680 # The rows keep the order they arrived in: order= says which order the
2681 # window is read along, not which order the table is shown in. The
2682 # table has its own sort controls, and a reader may well want them to
2683 # disagree (a ledger sorted by amount, running totals following the
2684 # date), so the pass writes values in place rather than reordering.
2685 #
2686 # A cell that is not numeric yields undef in the produced column rather
2687 # than a placeholder: there is no previous row for the first row of a
2688 # partition, and a chart skips undef while the measure fold does too,
2689 # so an undef window cannot silently become a zero.
2690 30 ▶sub _apply_cross_row :Protected ($self, $records, $columns, $plan = undef) {
Subroutine _apply_cross_row: called CC=23 SCAR=31.7
2691 30 my $cols = $columns;
2692 30 ▶ unless (defined $cols) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cols) 1 29 30
2693 1 ▶ $cols = [ sort keys %{ $records->[0] // {} } ];
Condition50%1/2
$records->[0] // {}
l!l
10
MC/DC0%0/1
$records->[0] // {}
$records->[0]
Truth table50%1/2
A
A= $records->[0]
Aresult
11
00
2694 }
2695  
2696 30 ▶ $plan //= $self->_cross_row_specs($cols);
Condition66%2/3
$plan //= $self->_cross_row_specs($cols)
l!l&&r!l&&!r
0291
MC/DC50%1/2
$plan //= $self->_cross_row_specs($cols)
$plan $self->_cross_row_specs($cols)
Truth table66%2/3
A //= B
A= $planB= $self->_cross_row_specs($cols)
ABresult
1X1
011
000
2697 30 ▶ return ($records, $columns) unless $plan;
Branch: 1 branch
BranchTrueFalseTotal
unless $plan 1 29 30
2698 29 ▶ croak $plan->{error} if $plan->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $plan->{"error"} 26 3 29
2699  
2700 # Partitions, in first-appearance order so a report reads in file order.
2701 3 my (@part_keys, %parts);
2702 3 for my $i (0 .. $#$records) {
2703 5 ▶ my $row = $records->[$i] // {};
Condition50%1/2
$records->[$i] // {}
l!l
50
MC/DC0%0/1
$records->[$i] // {}
$records->[$i]
Truth table50%1/2
A
A= $records->[$i]
Aresult
11
00
2704 5 ▶ my $key = join("\x00", map { defined $row->{$_} ? "$row->{$_}" : '' } @{ $plan->{by} });
Branch: 1 branch
BranchTrueFalseTotal
defined $row->{$_} ? : 3 0 3
2705 5 ▶ push @part_keys, $key unless exists $parts{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $parts{$key} 4 1 5
2706 5 push @{ $parts{$key} }, $i;
2707 }
2708  
2709 # One sort per partition, whatever the number of specs. The index is the
2710 # tie-break, so the sort is stable even where the keys are equal.
2711 3 ▶ if (my @order = @{ $plan->{order} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@order) = @{$plan->{"order"};}) 1 2 3
2712 1 for my $key (@part_keys) {
2713 2 my $idx = $parts{$key};
2714 2 ▶ next unless @$idx > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @$idx > 1 1 1 2
2715 $parts{$key} = [ sort {
2716 1 my $cmp = 0;
2717 1 for my $o (@order) {
2718 1 $cmp = _cross_row_cmp($records->[$a]{ $o->{col} }, $records->[$b]{ $o->{col} });
2719 1 ▶ $cmp = -$cmp if $o->{dir} eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"dir"} eq "desc" 0 1 1
2720 1 ▶ last if $cmp;
Branch: 1 branch
BranchTrueFalseTotal
if $cmp 1 0 1
2721 }
2722 1 ▶ $cmp || $a <=> $b;
Condition33%1/3
$cmp || $a <=> $b
l!l&&r!l&&!r
100
MC/DC0%0/2
$cmp || $a <=> $b
$cmp $a <=> $b
Truth table33%1/3
A || B
A= $cmpB= $a <=> $b
ABresult
1X1
011
000
2723 } @$idx ];
2724 }
2725 }
2726  
2727 3 my @names;
2728 3 for my $spec (@{ $plan->{specs} }) {
2729 3 my ($fn, $as, $col) = @{$spec}{qw(fn as col)};
2730 3 for my $key (@part_keys) {
2731 4 my $idx = $parts{$key};
2732 4 my @vals = map { _numeric_cell($records->[$_]{$col}) } @$idx;
2733 4 my @out = _cross_row_values($fn, \@vals, $spec->{arg});
2734 4 for my $j (0 .. $#$idx) {
2735 5 my $i = $idx->[$j];
2736 5 $records->[$i] = _extend_row($records->[$i], $as, $out[$j]);
2737 }
2738 }
2739 3 push @names, $as;
2740 }
2741  
2742 3 my @extended = (@$cols, @names);
2743 3 ▶ $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->stash("_virtual_columns") 3 0 3
2744 3 $self->stash('_virtual_columns')->{$_} = 1 for @names;
2745 # The routes that paginate ask for their columns separately, after the page
2746 # is sliced, so the names are left where they can be picked up.
2747 3 $self->stash('_cross_row_columns' => \@names);
2748  
2749 3 return ($records, \@extended);
2750 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2751  
2752 # _cross_row_values($fn, \@values, $arg) -> @values
2753 #
2754 # The arithmetic of one spec over one partition: @values is the source column
2755 # of each row in order, numeric or undef, and the answer is aligned with it.
2756 # A plain function, so the pass has one place where the functions are defined
2757 # and the tests can drive them without a controller.
2758 24 ▶sub _cross_row_values {
Subroutine _cross_row_values: called CC=44 SCAR=37.8
2759 24 my ($fn, $vals, $arg) = @_;
2760 24 my @out;
2761 24 my $n = scalar @$vals;
2762 24 ▶ return @out unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 1 23 24
2763  
2764 23 ▶ if ($fn eq 'running_count') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "running_count") 1 22 23
2765 1 return map { $_ + 1 } 0 .. $n - 1;
2766 }
2767  
2768 22 ▶ if ($fn eq 'running_total') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "running_total") 4 18 22
2769 4 my $run = 0;
2770 4 for my $v (@$vals) {
2771 9 ▶ $run += $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 8 1 9
2772 9 ▶ push @out, defined $v ? $run : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 8 1 9
2773 }
2774 4 return @out;
2775 }
2776  
2777 18 ▶ if ($fn eq 'running_pct') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "running_pct") 2 16 18
2778 2 my $total = 0;
2779 2 $total += $_ for grep { defined } @$vals;
2780 2 my $run = 0;
2781 2 for my $v (@$vals) {
2782 4 ▶ $run += $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 4 0 4
2783 4 ▶ push @out, ($total && defined $v) ? $run / $total : undef;
Branch: 1 branch
BranchTrueFalseTotal
$total && defined $v ? : 2 2 4
Condition66%2/3
$total and defined $v
!ll&&!rl&&r
202
MC/DC50%1/2
$total and defined $v
$total defined $v
Truth table66%2/3
A and B
A= $totalB= defined $v
ABresult
0X0
100
111
2784 }
2785 2 return @out;
2786 }
2787  
2788 16 ▶ if ($fn eq 'window_sum' || $fn eq 'window_avg') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "window_sum" or $fn eq "window_avg") 4 12 16
Condition100%3/3
$fn eq "window_sum" or $fn eq "window_avg"
l!l&&r!l&&!r
3112
MC/DC100%2/2
$fn eq "window_sum" or $fn eq "window_avg"
$fn eq "window_sum" $fn eq "window_avg"
Truth table100%3/3
A or B
A= $fn eq "window_sum"B= $fn eq "window_avg"
ABresult
1X1
011
000
2789 4 for my $i (0 .. $n - 1) {
2790 10 my $lo = $i - $arg + 1;
2791 10 ▶ $lo = 0 if $lo < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $lo < 0 5 5 10
2792 10 my @win = grep { defined } @{$vals}[$lo .. $i];
2793 10 ▶ unless (@win) { push @out, undef; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (@win) 2 8 10
2794 8 my $sum = 0;
2795 8 $sum += $_ for @win;
2796 8 ▶ push @out, $fn eq 'window_sum' ? $sum : $sum / scalar @win;
Branch: 1 branch
BranchTrueFalseTotal
$fn eq 'window_sum' ? : 5 3 8
2797 }
2798 4 return @out;
2799 }
2800  
2801 12 ▶ if ($fn eq 'lag') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "lag") 1 11 12
2802 1 my $prev;
2803 1 for my $v (@$vals) {
2804 3 push @out, $prev;
2805 3 $prev = $v;
2806 }
2807 1 return @out;
2808 }
2809  
2810 11 ▶ if ($fn eq 'delta' || $fn eq 'pct_change') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "delta" or $fn eq "pct_change") 2 9 11
Condition100%3/3
$fn eq "delta" or $fn eq "pct_change"
l!l&&r!l&&!r
119
MC/DC100%2/2
$fn eq "delta" or $fn eq "pct_change"
$fn eq "delta" $fn eq "pct_change"
Truth table100%3/3
A or B
A= $fn eq "delta"B= $fn eq "pct_change"
ABresult
1X1
011
000
2811 2 my $prev;
2812 2 for my $v (@$vals) {
2813 8 my $d;
2814 8 ▶ if (defined $v && defined $prev) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $v and defined $prev) 4 4 8
Condition100%3/3
defined $v and defined $prev
!ll&&!rl&&r
134
MC/DC100%2/2
defined $v and defined $prev
defined $v defined $prev
Truth table100%3/3
A and B
A= defined $vB= defined $prev
ABresult
0X0
100
111
2815 4 ▶ $d = $fn eq 'delta' ? $v - $prev : ($prev ? ($v - $prev) / $prev : undef);
Branch: 2 branches
BranchTrueFalseTotal
$fn eq 'delta' ? : 1 3 4
$prev ? : 2 1 3
2816 }
2817 8 push @out, $d;
2818 8 $prev = $v;
2819 }
2820 2 return @out;
2821 }
2822  
2823 9 my @nums = grep { defined } @$vals;
2824  
2825 9 ▶ if ($fn eq 'pct_of_total') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "pct_of_total") 2 7 9
2826 2 my $total = 0;
2827 2 $total += $_ for @nums;
2828 2 for my $v (@$vals) {
2829 5 ▶ push @out, ($total && defined $v) ? $v / $total : undef;
Branch: 1 branch
BranchTrueFalseTotal
$total && defined $v ? : 2 3 5
Condition100%3/3
$total and defined $v
!ll&&!rl&&r
212
MC/DC100%2/2
$total and defined $v
$total defined $v
Truth table100%3/3
A and B
A= $totalB= defined $v
ABresult
0X0
100
111
2830 }
2831 2 return @out;
2832 }
2833  
2834 7 ▶ if ($fn eq 'rank') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "rank") 3 4 7
2835 # SQL RANK(): ties share a rank and the next rank skips, which counting
2836 # the values strictly greater gives for free.
2837 3 for my $v (@$vals) {
2838 7 ▶ push @out, defined $v ? 1 + scalar(grep { $_ > $v } @nums) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 6 1 7
2839 }
2840 3 return @out;
2841 }
2842  
2843 4 ▶ if ($fn eq 'zscore') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "zscore") 3 1 4
2844 3 my ($mean, $sd);
2845 3 ▶ if (@nums >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@nums >= 2) 2 1 3
2846 2 $mean = 0;
2847 2 $mean += $_ for @nums;
2848 2 $mean /= scalar @nums;
2849 2 $sd = _stdev_of(\@nums);
2850 }
2851 3 for my $v (@$vals) {
2852 5 ▶ push @out, (defined $v && defined $sd && $sd > 0) ? ($v - $mean) / $sd : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $v && defined $sd && $sd > 0 ? : 2 3 5
Condition83%5/6
defined $v and defined $sd and $sd > 0
!ll&&!rl&&r
122
defined $v and defined $sd
!ll&&!rl&&r
014
MC/DC66%2/3
defined $v and defined $sd and $sd > 0
defined $v defined $sd $sd > 0
Truth table75%3/4
A and B and C
A= defined $vB= defined $sdC= $sd > 0
ABCresult
0XX0
10X0
1100
1111
2853 }
2854 3 return @out;
2855 }
2856  
2857 1 croak "Unknown cross-row function '$fn'"; # unreachable: validated above
2858 }
2859  
2860 # _cross_row_cmp($x, $y) -> -1 | 0 | 1
2861 #
2862 # The order= comparator: numeric when both cells are numbers, case-sensitive
2863 # string otherwise. Numbers sort as numbers because an order= on an amount is
2864 # meant to put 100 after 20, and a mixed column still has to be total.
2865 8 ▶sub _cross_row_cmp {
Subroutine _cross_row_cmp: called CC=5 SCAR=16.1
2866 8 my ($x, $y) = @_;
2867 8 my ($nx, $ny) = (_numeric_cell($x), _numeric_cell($y));
2868 8 ▶ return $nx <=> $ny if defined $nx && defined $ny;
Branch: 1 branch
BranchTrueFalseTotal
if defined $nx and defined $ny 3 5 8
Condition100%3/3
defined $nx and defined $ny
!ll&&!rl&&r
413
MC/DC100%2/2
defined $nx and defined $ny
defined $nx defined $ny
Truth table100%3/3
A and B
A= defined $nxB= defined $ny
ABresult
0X0
100
111
2869 5 ▶ return ($x // '') cmp($y // '');
Condition100%4/4
$x // ""
l!l
32
$y // ""
l!l
41
MC/DC100%1/1
$x // ""
$x
MC/DC100%1/1
$y // ""
$y
Truth table100%2/2
A
A= $x
Aresult
11
00
Truth table100%2/2
A
A= $y
Aresult
11
00
2870 }
2871  
2872 # _trim($text) -> $text
2873 26 ▶sub _trim {
Subroutine _trim: called CC=2 SCAR=6.9
2874 26 ▶ my $s = defined $_[0] ? $_[0] : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 25 1 26
2875 26 $s =~ s/\A\s+//;
2876 26 $s =~ s/\s+\z//;
2877 26 return $s;
2878 }
2879  
2880 # _reduce_records($self, $records, $columns, $opts) -> ($records, $columns)
2881 #
2882 # Purpose: The reduce half of every data pipeline, in one place: the request's
2883 # filters -- the reader's own f= params, then the two bounds of the
2884 # relative time range -- run over $records in order, with the columns
2885 # list threaded through so a later stage can add columns and hand back
2886 # the extended list. Every route that reads rows and then filters
2887 # them calls this rather than writing the loop out again, so a stage
2888 # added here reaches all of them at once.
2889 # Entry: $records -- arrayref of hashrefs, after the calculated-field pass.
2890 # $columns -- arrayref of column names, or undef where the caller has
2891 # no list in scope; a stage that adds columns needs one,
2892 # so undef is only for the filters-only callers.
2893 # $opts -- optional hashref. chips_only => 1 says the caller's rows
2894 # have already been reduced and it is here only for the
2895 # chip list _apply_filters returns: the stage is skipped
2896 # and both arguments come back as they arrived.
2897 # no_cross_row => 1 runs the filters only, for a caller
2898 # that wants the rows without stage 6 (_apply_filters,
2899 # whose callers are after the chip list).
2900 # Exit: ($records, $columns), reduced -- or untouched, when chips_only is
2901 # set. A malformed f= spec leaves the records alone rather than
2902 # croaking, as _apply_filter_spec always has.
2903 # Notes: This is stage 5 of the stage order in BI-Phase-7.md section 3, and
2904 # it is where that document's stages 6 and 7 are meant to land: the
2905 # cross-row pass and the second calculated-field pass. Both belong
2906 # here rather than at a call site, because they have to see *filtered*
2907 # rows and have to run before pagination (an exported or second page
2908 # then carries the same numbers as the first).
2909 #
2910 # Three kinds of row-reading route deliberately do not reduce here,
2911 # and each is a different case: the canvas builds its own per-card
2912 # pipeline and runs stage 6 per card, after that card's filters
2913 # (_canvas_render_context, _render_visual_html), /view's table action
2914 # filters inside _fetch_page before it paginates, and /api/ask samples
2915 # rows without filtering them at all.
2916 #
2917 # chips_only exists for the routes that filter somewhere else and then
2918 # call _apply_filters for its chip list: /view, the three /open
2919 # branches and /join reduce inside _fetch_page, before they paginate,
2920 # and /combine reduces through this function before slicing its page.
2921 # Re-running the stage on that page would still give the right answer
2922 # today, because every stage in it is idempotent -- filtering a
2923 # filtered set changes nothing. It stops being harmless as soon as a
2924 # stage is not: a cross-row pass (running totals, differences) or a
2925 # time-fill that adds rows would double-apply to a page that has
2926 # already been through it, and would do so only on non-first pages.
2927 # So the option is not a micro-optimisation; it is what keeps those
2928 # six call sites correct once such a stage lands here.
2929 #
2930 # A plain function rather than a method, like _filter_specs and
2931 # _apply_filter_spec beside it: the tests drive the reduce stage with a
2932 # controller-shaped mock (build_controller), and only every_param and
2933 # stash are ever wanted of $self.
2934 1260 ▶sub _reduce_records {
Subroutine _reduce_records: called CC=15 SCAR=27.5
2935 1260 my ($self, $records, $columns, $opts) = @_;
2936  
2937 # Already reduced: hand the rows and the columns back exactly as they came,
2938 # ahead of the first stage, so a stage that is not idempotent cannot see
2939 # these rows a second time.
2940 1260 ▶ return ($records, $columns) if $opts && $opts->{chips_only};
Branch: 1 branch
BranchTrueFalseTotal
if $opts and $opts->{"chips_only"} 349 911 1260
Condition100%3/3
$opts and $opts->{"chips_only"}
!ll&&!rl&&r
9029349
MC/DC100%2/2
$opts and $opts->{"chips_only"}
$opts $opts->{"chips_only"}
Truth table100%3/3
A and B
A= $optsB= $opts->{"chips_only"}
ABresult
0X0
100
111
2941  
2942 # A filter on a column stage 6 or 7 will write has to wait for it: f=ytd:gt:50
2943 # selects rows by their running total, and must not change those totals. So
2944 # every filter that can run first does, and the rest run last.
2945 911 ▶ my $crossing = (!$opts || !$opts->{no_cross_row}) && length($self->param('cs') // '');
Condition87%7/8
!($opts && $opts->{'no_cross_row'}) && length($self->param('cs') // '')
!ll&&!rl&&r
987923
$opts && $opts->{'no_cross_row'}
!ll&&!rl&&r
90209
$self->param("cs") // ""
l!l
24878
MC/DC66%2/3
!($opts && $opts->{'no_cross_row'}) && length($self->param('cs') // '')
$opts $opts->{'no_cross_row'} $self->param("cs")
Truth table60%3/5
not(A && B) && C
A= $optsB= $opts->{'no_cross_row'}C= $self->param("cs")
ABCresult
11X0
0X00
1000
0X11
1011
2946 911 ▶ my %written = $crossing ? map { $_ => 1 } _cross_row_written($self) : ();
Branch: 1 branch
BranchTrueFalseTotal
$crossing ? : 23 888 911
2947 911 ▶ if (defined(my $why = _unknown_filter_column($self, $columns, \%written))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $why = _unknown_filter_column($self, $columns, \%written))) 1 910 911
2948 1 croak $why;
2949 }
2950 910 my @late;
2951 910 for my $s (@{ _filter_specs($self) }) {
2952 41 ▶ if ($written{ (split /:/, $s, 2)[0] // '' }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($written{(split(/:/u, $s, 2))[0] // ""}) 0 41 41
Condition50%1/2
(split(/:/u, $s, 2))[0] // ""
l!l
410
MC/DC0%0/1
(split(/:/u, $s, 2))[0] // ""
(split(/:/u, $s, 2))[0]
Truth table50%1/2
A
A= (split(/:/u, $s, 2))[0]
Aresult
11
00
2953 0 push @late, $s;
2954 0 next;
2955 }
2956 41 $records = _apply_filter_spec($records, $s);
2957 }
2958  
2959 # d=1 removes duplicate rows after the filters and before the cross-row
2960 # pass, the order _fetch_page uses for the table view, so a chart of a
2961 # de-duplicated view counts the rows the table shows. Only callers with a
2962 # columns list run the whole stage; the filters-only entry point does not.
2963 910 ▶ $records = _dedup_records($records, $columns)
Branch: 1 branch
BranchTrueFalseTotal
if $columns and _dedup_requested($self) 3 907 910
Condition100%3/3
$columns and _dedup_requested($self)
!ll&&!rl&&r
108973
MC/DC100%2/2
$columns and _dedup_requested($self)
$columns _dedup_requested($self)
Truth table100%3/3
A and B
A= $columnsB= _dedup_requested($self)
ABresult
0X0
100
111
2964 if $columns && _dedup_requested($self);
2965  
2966 # Stage 6: the cross-row pass, and only when the request asks for one. It
2967 # has to see filtered rows -- a window is over what the filters left -- and it
2968 # has to run before anything paginates, which is why the routes that slice
2969 # their own page call it again (once) inside _fetch_page.
2970 910 ▶ if ($crossing) {
Branch: 1 branch
BranchTrueFalseTotal
if ($crossing) 23 887 910
2971 23 ($records, $columns) = $self->_apply_cross_row($records, $columns);
2972 # Stage 7: the calculated fields stage 4 held back for these columns.
2973 0 ($records, $columns) = $self->_apply_held_calc_fields($records, $columns);
2974 0 $records = _apply_filter_spec($records, $_) for @late;
2975 }
2976  
2977 887 return ($records, $columns);
2978 }
2979  
2980 # _reduce_or_render($self, \$records, \$columns) -> $ok
2981 #
2982 # Purpose: Run _reduce_records and turn a cross-row spec that cannot be
2983 # honoured into the 400 it deserves, in the one shape every route
2984 # already uses for a calculated field that will not compile.
2985 # Entry: References to the route's own lexicals: on success they are updated
2986 # in place, so a call site is one line.
2987 # Exit: True when the records are ready. False after rendering a 400 -- the
2988 # caller returns straight away, because nothing has been produced.
2989 # Notes: A method, unlike _reduce_records itself, because the failure needs
2990 # a controller to render through. The error text is the i18n message
2991 # the pass croaked with, with the "at File line N" tail removed so a
2992 # reader sees the fault rather than the interpreter's location.
2993 897 ▶sub _reduce_or_render :Protected ($self, $recs_ref, $cols_ref) {
Subroutine _reduce_or_render: called CC=2 SCAR=6.9
2994 897 my @reduced = eval { _reduce_records($self, $$recs_ref, $$cols_ref) };
2995 897 ▶ if (@reduced) {
Branch: 1 branch
BranchTrueFalseTotal
if (@reduced) 873 24 897
2996 873 ($$recs_ref, $$cols_ref) = @reduced;
2997 873 return 1;
2998 }
2999  
3000 24 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
3001 24 $self->render(text => $e, status => 400);
3002 # Recorded because the callers that answer a missing table with a 404 get
3003 # their rows back empty here, and the 400 has already been rendered.
3004 24 $self->stash('_reduce_error' => 1);
3005 24 return 0;
3006 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3007  
3008 # _apply_filters($self, $records, $opts) -> ($filtered_records, \@raw_specs, $json_string)
3009 #
3010 # Purpose: Read all "f=" query params, apply them in order via _apply_filter_spec,
3011 # and return: the filtered arrayref, the raw spec strings (for building
3012 # export URLs), and a script-safe JSON string for pre-populating the UI.
3013 # Entry: $records is an arrayref of hashrefs. $opts is passed straight to
3014 # _reduce_records: chips_only => 1 for the routes whose rows are
3015 # already reduced and which are here only for the chips.
3016 # Exit: Three-element list; never croaks. $json_string has '</' escaped to
3017 # '<\/' so it is safe to embed directly in a <script> block.
3018 #
3019 # Reduction: the original code had two sequential loops over @specs -- one to
3020 # apply filters, one to parse them for JSON. By Modus Ponens, _apply_filter_spec
3021 # returns $records unchanged for a malformed spec (same guard condition), so
3022 # skipping the call for malformed specs is equivalent. Merging into one loop
3023 # eliminates a full O(n) pass and the redundant split() on every spec.
3024 357 ▶sub _apply_filters :Protected ($self, $records, $opts = undef) {
Subroutine _apply_filters: called CC=10 SCAR=23.1
3025 357 ▶ my @specs = @{ $self->every_param('f') // [] };
Condition50%1/2
$self->every_param("f") // []
l!l
3570
MC/DC0%0/1
$self->every_param("f") // []
$self->every_param("f")
Truth table50%1/2
A
A= $self->every_param("f")
Aresult
11
00
3026 357 my @parsed;
3027 357 for my $s (@specs) {
3028 91 my ($col, $op, $val) = split /:/, $s, 3;
3029 91 ▶ next unless length($col // '') && defined $op && length $op;
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and defined $op and length $op 6 85 91
Condition87%7/8
length($col // "") and defined $op and length $op
!ll&&!rl&&r
6085
length($col // "") and defined $op
!ll&&!rl&&r
3385
$col // ""
l!l
892
MC/DC66%2/3
length($col // "") and defined $op and length $op
$col defined $op length $op
Truth table75%3/4
A and B and C
A= $colB= defined $opC= length $op
ABCresult
0XX0
10X0
1100
1111
3030 85 ▶ push @parsed, { col => $col, op => $op, val => $val // '' };
Condition50%1/2
$val // ""
l!l
850
MC/DC0%0/1
$val // ""
$val
Truth table50%1/2
A
A= $val
Aresult
11
00
3031 }
3032  
3033 # The range joins the request's own filters here, but it is not one of them:
3034 # @specs -- which the page shows as chips, keeps in its panel forms and
3035 # offers to its filter UI -- stays the reader's own list, so a relative range
3036 # cannot be submitted as a frozen pair of dates and a reopened link cannot
3037 # narrow twice. The application itself is _reduce_records, so this entry
3038 # point and the routes that call it directly cannot drift apart; the columns
3039 # list is not in scope here and every caller holds its own, so none is
3040 # threaded through. $opts travels with the records for the same reason:
3041 # a caller that has already reduced asks for the chips alone here, and the
3042 # seam, not this wrapper, is where that is decided.
3043 # no_cross_row: this entry point is the chip list, and its callers either
3044 # skip the stage entirely (chips_only) or want the rows without stage 6.
3045 357 ▶ ($records) = _reduce_records($self, $records, undef, { %{ $opts // {} }, no_cross_row => 1 });
Condition100%2/2
$opts // {}
l!l
3489
MC/DC100%1/1
$opts // {}
$opts
Truth table100%2/2
A
A= $opts
Aresult
11
00
3046  
3047 357 my $json = encode_json(\@parsed);
3048 357 $json =~ s{</}{<\\/}g;
3049 357 return ($records, \@specs, $json);
3050 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3051  
3052 # _filter_specs($self) -> \@specs
3053 #
3054 # Purpose: Every filter that applies to this request: the f= params the reader
3055 # wrote, followed by the two bounds of the relative time range the
3056 # request names, if any. This is the list the data pipelines fold over
3057 # -- charts, pivots, stats, insights and the exports as well as the
3058 # table view -- so a range narrows all of them through one call site
3059 # each, and a route that never heard of ranges still honours one.
3060 # Entry: $self -- the controller; it needs only every_param() and stash().
3061 # Exit: Returns an arrayref of "col:op:val" strings; possibly empty.
3062 1866 ▶sub _filter_specs {
Subroutine _filter_specs: called CC=3 SCAR=11.0
3063 1866 my ($self) = @_;
3064 return [
3065 1866 ▶ @{ $self->every_param('f') // [] },
Condition50%1/2
$self->every_param("f") // []
l!l
18660
MC/DC0%0/1
$self->every_param("f") // []
$self->every_param("f")
Truth table50%1/2
A
A= $self->every_param("f")
Aresult
11
00
3066 1866 ▶ @{ $self->stash('range_specs') // [] },
Condition100%2/2
$self->stash("range_specs") // []
l!l
185214
MC/DC100%1/1
$self->stash("range_specs") // []
$self->stash("range_specs")
Truth table100%2/2
A
A= $self->stash("range_specs")
Aresult
11
00
3067 ];
3068 }
3069  
3070 # _dedup_requested($self) -> $bool
3071 #
3072 # Purpose: True when the request asks for duplicate rows to be removed (d=1).
3073 # The SQL aggregate push paths check it too, because the backend
3074 # would count the duplicates the Perl fold has already dropped.
3075 1536 ▶sub _dedup_requested {
Subroutine _dedup_requested: called CC=2 SCAR=6.9
3076 1536 my ($self) = @_;
3077 1536 ▶ return $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 4 1532 1536
3078 }
3079  
3080 # _dedup_records(\@records, \@columns) -> \@unique_records
3081 #
3082 # Purpose: Remove duplicate rows from $records. Two rows are duplicates when
3083 # every column value is identical (string comparison, undef treated as '').
3084 # Preserves the order of first occurrence.
3085 # Entry: $records is an arrayref of hashrefs; $columns is an arrayref of names.
3086 # Exit: Returns a new arrayref; the input is not modified.
3087 10 ▶sub _dedup_records {
Subroutine _dedup_records: called CC=4 SCAR=13.9
3088 10 my ($records, $columns) = @_;
3089 10 my (%seen, @out);
3090 10 for my $row (@$records) {
3091 34 ▶ my $key = join "\x00", map { $row->{$_} // '' } @$columns;
Condition100%2/2
$row->{$_} // ""
l!l
791
MC/DC100%1/1
$row->{$_} // ""
$row->{$_}
Truth table100%2/2
A
A= $row->{$_}
Aresult
11
00
3092 34 ▶ push @out, $row unless $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$key}++ 20 14 34
3093 }
3094 10 return \@out;
3095 }
3096  
3097 # _filter_specs_to_criteria( \@specs, $source ) -> ( \%criteria, \@residual_specs )
3098 #
3099 # Purpose: Map the f= filter vocabulary onto Database::Abstraction / Database::Join
3100 # criteria hashrefs so the backend can apply pushable filters before
3101 # paginating. Specs that cannot be safely pushed are returned as
3102 # @residual_specs for subsequent in-memory application.
3103 #
3104 # Pushdown is only performed when $source->dbi_source() confirms a SQL (SQLite)
3105 # backend. For CSV (slurp path), in-memory, XLSX, BerkeleyDB and URL sources
3106 # everything is placed in @residual_specs so the existing _apply_filter_spec
3107 # Perl path handles them.
3108 #
3109 # Pushable mapping (SQLite only):
3110 # eq / ne -- LIKE / NOT LIKE without wildcards. SQLite LIKE is
3111 # case-insensitive for ASCII, matching the existing Perl
3112 # lc() semantics. Values containing % or _ are pushed to
3113 # residual to avoid LIKE metacharacter conflicts.
3114 # contains -- LIKE '%val%'. Residual when value contains % or _.
3115 # starts -- LIKE 'val%'. Residual when value contains % or _.
3116 # lt / le / gt / ge -- SQL numeric comparison. Residual when the value is
3117 # not a plain number (avoids column-affinity surprises
3118 # with currency or comma-formatted values).
3119 # in -- Always residual (a list of values, matched as eq is).
3120 # differ -- Always residual (compares two columns of one row).
3121 # empty / notempty -- Always residual. Must match both SQL NULL and the
3122 # literal empty string; cannot be expressed as a single
3123 # D::A criterion without an -or grouping.
3124 #
3125 # Column collision: if a column already has a pushable criterion, the second
3126 # spec for that column is placed in @residual_specs. This keeps the AND logic
3127 # simple and safe; callers with multiple conditions on one column (e.g. a range)
3128 # still get correct results via the in-memory fallback.
3129 35 ▶sub _filter_specs_to_criteria {
Subroutine _filter_specs_to_criteria: called CC=28 SCAR=33.3
3130 35 my ($specs, $source) = @_;
3131  
3132 # Only push when the source has a live SQL (SQLite) backend.
3133 35 ▶ my $is_sql = $source
Condition100%6/6
$source && $source->can('dbi_source') && $source->dbi_source
!ll&&!rl&&r
21023
$source and $source->can("dbi_source")
!ll&&!rl&&r
1133
MC/DC100%3/3
$source && $source->can('dbi_source') && $source->dbi_source
$source $source->can("dbi_source") $source->dbi_source
Truth table100%4/4
A and B && C
A= $sourceB= $source->can("dbi_source")C= $source->dbi_source
ABCresult
0XX0
10X0
1100
1111
3134 && $source->can('dbi_source')
3135 && $source->dbi_source();
3136 35 ▶ return ({}, [@$specs]) unless $is_sql;
Branch: 1 branch
BranchTrueFalseTotal
unless $is_sql 12 23 35
3137  
3138 23 require Scalar::Util;
3139 23 my (%criteria, @residual);
3140  
3141 23 for my $spec (@$specs) {
3142 27 my ($col, $op, $val) = split /:/, $spec, 3;
3143 27 ▶ next unless length($col // '') && defined $op && length $op;
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and defined $op and length $op 4 23 27
Condition100%8/8
length($col // "") and defined $op and length $op
!ll&&!rl&&r
3123
length($col // "") and defined $op
!ll&&!rl&&r
2124
$col // ""
l!l
261
MC/DC100%3/3
length($col // "") and defined $op and length $op
$col defined $op length $op
Truth table100%4/4
A and B and C
A= $colB= defined $opC= length $op
ABCresult
0XX0
10X0
1100
1111
3144 23 ▶ $val //= '';
Condition100%2/2
$val //= ""
l!l
212
MC/DC100%1/1
$val //= ""
$val
Truth table100%2/2
A
A= $val
Aresult
11
00
3145  
3146 # A second spec on the same column goes to residual.
3147 23 ▶ if (exists $criteria{$col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $criteria{$col}) 1 22 23
3148 1 push @residual, $spec;
3149 1 next;
3150 }
3151  
3152 22 ▶ if ($op eq 'eq' || $op eq 'ne') {
Branch: 7 branches
BranchTrueFalseTotal
if ($op eq 'eq' or $op eq 'ne') { } 5 17 22
elsif ($op eq 'contains') { } 2 15 17
elsif ($op eq 'starts') { } 2 13 15
elsif ($op eq 'lt') { } 2 11 13
elsif ($op eq 'le') { } 2 9 11
elsif ($op eq 'gt') { } 3 6 9
elsif ($op eq 'ge') { } 2 4 6
Condition100%3/3
$op eq "eq" or $op eq "ne"
l!l&&r!l&&!r
3217
MC/DC100%2/2
$op eq "eq" or $op eq "ne"
$op eq "eq" $op eq "ne"
Truth table100%3/3
A or B
A= $op eq "eq"B= $op eq "ne"
ABresult
1X1
011
000
3153 # A date compares by the day in Perl (a timestamp cell is on the
3154 # day it names); LIKE would want the cell to be the date exactly.
3155 5 ▶ if ($val =~ /[%_]/ || _is_iso_date($val)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val =~ /[%_]/u or _is_iso_date($val)) { } 3 2 5
Condition66%2/3
$val =~ /[%_]/u or _is_iso_date($val)
l!l&&r!l&&!r
302
MC/DC50%1/2
$val =~ /[%_]/u or _is_iso_date($val)
$val =~ /[%_]/u _is_iso_date($val)
Truth table66%2/3
A or B
A= $val =~ /[%_]/uB= _is_iso_date($val)
ABresult
1X1
011
000
3156 3 push @residual, $spec;
3157 } else {
3158 2 ▶ $criteria{$col} = ($op eq 'eq')
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'eq' ? : 1 1 2
3159 ? { -like => $val }
3160 : { -not_like => $val };
3161 }
3162 } elsif ($op eq 'contains') {
3163 2 ▶ if ($val =~ /[%_]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val =~ /[%_]/u) { } 1 1 2
3164 1 push @residual, $spec;
3165 } else {
3166 1 $criteria{$col} = { -like => "%${val}%" };
3167 }
3168 } elsif ($op eq 'starts') {
3169 2 ▶ if ($val =~ /[%_]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val =~ /[%_]/u) { } 1 1 2
3170 1 push @residual, $spec;
3171 } else {
3172 1 $criteria{$col} = { -like => "${val}%" };
3173 }
3174 } elsif ($op eq 'lt') {
3175 Scalar::Util::looks_like_number($val)
3176 2 ▶ ? ($criteria{$col} = { '<' => $val })
Branch: 1 branch
BranchTrueFalseTotal
&Scalar::Util::looks_like_number($val) ? : 1 1 2
3177 : push @residual, $spec;
3178 } elsif ($op eq 'le') {
3179 Scalar::Util::looks_like_number($val)
3180 2 ▶ ? ($criteria{$col} = { '<=' => $val })
Branch: 1 branch
BranchTrueFalseTotal
&Scalar::Util::looks_like_number($val) ? : 1 1 2
3181 : push @residual, $spec;
3182 } elsif ($op eq 'gt') {
3183 Scalar::Util::looks_like_number($val)
3184 3 ▶ ? ($criteria{$col} = { '>' => $val })
Branch: 1 branch
BranchTrueFalseTotal
&Scalar::Util::looks_like_number($val) ? : 2 1 3
3185 : push @residual, $spec;
3186 } elsif ($op eq 'ge') {
3187 Scalar::Util::looks_like_number($val)
3188 2 ▶ ? ($criteria{$col} = { '>=' => $val })
Branch: 1 branch
BranchTrueFalseTotal
&Scalar::Util::looks_like_number($val) ? : 1 1 2
3189 : push @residual, $spec;
3190 } else {
3191 # empty, notempty, between, unknown operator: always residual.
3192 4 push @residual, $spec;
3193 }
3194 }
3195  
3196 23 return (\%criteria, \@residual);
3197 }
3198  
3199 # _measure($fn, $col, $as) -> \%measure
3200 #
3201 # Build one measure descriptor in the vocabulary shared by Database::Abstraction
3202 # and Database::Join (sum|avg|min|max|count|count_distinct). $col is the
3203 # source column name, or undef for COUNT(*). $as is the result-row key.
3204 # The returned hashref is consumed directly by aggregate(measures => [...]).
3205 710 ▶sub _measure {
Subroutine _measure: called CC=2 SCAR=6.9
3206 710 my ($fn, $col, $as) = @_;
3207 710 ▶ return { fn => $fn, (defined $col ? (col => $col) : ()), as => $as };
Branch: 1 branch
BranchTrueFalseTotal
defined $col ? : 321 389 710
3208 }
3209  
3210 # _numeric_cell($v) -> $number | undef
3211 #
3212 # Extract a numeric value from a raw cell, handling currency prefixes
3213 # (e.g. $1,234.56) and accounting-notation negatives ((1,234.56) -> -1234.56).
3214 # Returns undef for empty, undef, or non-numeric input.
3215 # Used by the Perl fold path of _grouped_totals so all four chart routes
3216 # share one extraction function.
3217 4337 ▶sub _numeric_cell {
Subroutine _numeric_cell: called CC=1 SCAR=0.0
3218 4337 return Database::BI::Util::parse_number($_[0]);
3219 }
3220  
3221 # _percentile_of(\@sorted, $level) -> $number | undef
3222 #
3223 # The value at the given percentile of an already sorted list of numbers, by
3224 # linear interpolation between closest ranks (R's type 7, Excel's
3225 # PERCENTILE.INC). $level is 1..100. The empty list has no percentile, so it
3226 # returns undef rather than a made-up 0.
3227 #
3228 # At level 50 this is the median the column-stats view has always shown: the
3229 # middle value when the count is odd, the mean of the two middle values when it
3230 # is even. That is the point of it, and the reason median is defined in terms
3231 # of it below -- one arithmetic, so a p50 measure, a median measure and the
3232 # median column of the stats page cannot disagree.
3233 247 ▶sub _percentile_of {
Subroutine _percentile_of: called CC=4 SCAR=13.9
3234 247 my ($sorted, $level) = @_;
3235 247 my $n = scalar @$sorted;
3236 247 ▶ return undef unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 1 246 247
3237 246 my $h = ($n - 1) * $level / 100;
3238 246 my $lo = int $h;
3239 246 ▶ return $sorted->[$lo] if $h == $lo || $lo >= $n - 1;
Branch: 1 branch
BranchTrueFalseTotal
if $h == $lo or $lo >= $n - 1 41 205 246
Condition66%2/3
$h == $lo or $lo >= $n - 1
l!l&&r!l&&!r
410205
MC/DC50%1/2
$h == $lo or $lo >= $n - 1
$h == $lo $lo >= $n - 1
Truth table66%2/3
A or B
A= $h == $loB= $lo >= $n - 1
ABresult
1X1
011
000
3240 205 return $sorted->[$lo] + ($h - $lo) * ($sorted->[ $lo + 1 ] - $sorted->[$lo]);
3241 }
3242  
3243 # _median_of(\@sorted) -> $number | undef
3244 108 ▶sub _median_of {
Subroutine _median_of: called CC=1 SCAR=0.0
3245 108 return _percentile_of($_[0], 50);
3246 }
3247  
3248 # _stdev_of(\@nums) -> $number | undef
3249 #
3250 # Sample standard deviation, the n-1 denominator: what Splunk's stdev() and
3251 # Excel's STDEV.S report. One value has no spread to measure, so fewer than
3252 # two values give undef rather than a reassuring 0.
3253 102 ▶sub _stdev_of {
Subroutine _stdev_of: called CC=4 SCAR=13.9
3254 102 my $nums = shift;
3255 102 my $n = scalar @$nums;
3256 102 ▶ return undef unless $n >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless $n >= 2 2 100 102
3257 100 my $mean = 0;
3258 100 $mean += $_ for @$nums;
3259 100 $mean /= $n;
3260 100 my $sum_sq = 0;
3261 100 $sum_sq += ($_ - $mean) ** 2 for @$nums;
3262 100 return sqrt($sum_sq / ($n - 1));
3263 }
3264  
3265 # _range_of(\@sorted) -> $number | undef
3266 #
3267 # Largest minus smallest, on the already sorted list: the spread a reader means
3268 # by "range", which is not min/max in the sense the SQL backend could push.
3269 99 ▶sub _range_of {
Subroutine _range_of: called CC=2 SCAR=6.9
3270 99 my $sorted = shift;
3271 99 ▶ return undef unless @$sorted;
Branch: 1 branch
BranchTrueFalseTotal
unless @$sorted 1 98 99
3272 98 return $sorted->[-1] - $sorted->[0];
3273 }
3274  
3275 # _measure_value($fn, \@sorted_values) -> $number | undef
3276 #
3277 # The function from @PERL_MEASURE_FNS (or a percentile) applied to the sorted
3278 # values of one group. It takes the values rather than a group key so that the
3279 # caller decides what a group is: the pivot's fold has one list per group, and
3280 # the stats page measures a whole column with the same four functions.
3281 62 ▶sub _measure_value {
Subroutine _measure_value: called CC=5 SCAR=16.1
3282 62 my ($fn, $sorted) = @_;
3283 62 my $level = _measure_percentile($fn);
3284 62 ▶ return _percentile_of($sorted, $level) if defined $level;
Branch: 1 branch
BranchTrueFalseTotal
if defined $level 31 31 62
3285 31 ▶ return _median_of($sorted) if $fn eq 'median';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "median" 13 18 31
3286 18 ▶ return _stdev_of($sorted) if $fn eq 'stdev';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "stdev" 8 10 18
3287 10 ▶ return _range_of($sorted) if $fn eq 'range';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "range" 8 2 10
3288 2 return undef;
3289 }
3290  
3291 # _column_is_numeric($records, $col) -> bool
3292 #
3293 # Says whether a column can be used as a chart measure. It samples the first
3294 # non-empty cells rather than the whole table: the canvas needs a quick answer
3295 # for the column picker, and a column with a non-numeric value in its first 20
3296 # rows is not a safe measure anyway.
3297 232 ▶sub _column_is_numeric {
Subroutine _column_is_numeric: called CC=8 SCAR=20.8
3298 232 my ($records, $col) = @_;
3299 232 my $seen = 0;
3300 232 ▶ for my $row (@{ $records // [] }) {
Condition100%2/2
$records // []
l!l
2311
MC/DC100%1/1
$records // []
$records
Truth table100%2/2
A
A= $records
Aresult
11
00
3301 620 my $v = $row->{$col};
3302 620 ▶ next unless defined $v && length $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and length $v 5 615 620
Condition100%3/3
defined $v and length $v
!ll&&!rl&&r
32615
MC/DC100%2/2
defined $v and length $v
defined $v length $v
Truth table100%3/3
A and B
A= defined $vB= length $v
ABresult
0X0
100
111
3303 615 ▶ return 0 unless defined _numeric_cell($v);
Branch: 1 branch
BranchTrueFalseTotal
unless defined _numeric_cell($v) 150 465 615
3304 465 ▶ last if ++$seen >= 20;
Branch: 1 branch
BranchTrueFalseTotal
if ++$seen >= 20 1 464 465
3305 }
3306 82 ▶ return $seen ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$seen ? : 79 3 82
3307 }
3308  
3309 # _measure_pushable($source, $fn, $col, \@records) -> bool
3310 #
3311 # Returns true when the measure can be computed by aggregate() on $source and
3312 # the result will be identical to the Perl fold. False means use the Perl fold.
3313 #
3314 # Decision table:
3315 # Not in the pushed vocabulary -- never pushable. None of median, a
3316 # percentile, stdev, first, last or range is a sum
3317 # of its parts, and the backend would either refuse
3318 # the spec or quietly answer with its own idea of
3319 # the statistic (it has one for median and stddev).
3320 # count / count_distinct -- always pushable (no numeric coercion).
3321 # sum / avg / min / max -- only when every sampled value in $col is either
3322 # a plain number (looks_like_number) or empty/undef.
3323 # Currency symbols or accounting parentheses in any
3324 # value force the Perl fold, which strips them
3325 # correctly; SQLite CAST would coerce them to 0.
3326 # Missing $source -- never pushable.
3327 # Missing $col -- sum/avg/min/max are not pushable without a column.
3328 617 ▶sub _measure_pushable {
Subroutine _measure_pushable: called CC=13 SCAR=25.9
3329 617 my ($source, $fn, $col, $records) = @_;
3330 617 ▶ return 0 unless $source && $source->can('aggregate');
Branch: 1 branch
BranchTrueFalseTotal
unless $source and $source->can("aggregate") 1 616 617
Condition66%2/3
$source and $source->can("aggregate")
!ll&&!rl&&r
01616
MC/DC50%1/2
$source and $source->can("aggregate")
$source $source->can("aggregate")
Truth table66%2/3
A and B
A= $sourceB= $source->can("aggregate")
ABresult
0X0
100
111
3331 616 ▶ return 0 unless defined $fn && $PUSHED_MEASURE_FN_OK{$fn};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fn and $PUSHED_MEASURE_FN_OK{$fn} 42 574 616
Condition66%2/3
defined $fn and $PUSHED_MEASURE_FN_OK{$fn}
!ll&&!rl&&r
042574
MC/DC50%1/2
defined $fn and $PUSHED_MEASURE_FN_OK{$fn}
defined $fn $PUSHED_MEASURE_FN_OK{$fn}
Truth table66%2/3
A and B
A= defined $fnB= $PUSHED_MEASURE_FN_OK{$fn}
ABresult
0X0
100
111
3332 574 ▶ return 1 if $fn eq 'count' || $fn eq 'count_distinct';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "count" or $fn eq "count_distinct" 389 185 574
Condition100%3/3
$fn eq "count" or $fn eq "count_distinct"
l!l&&r!l&&!r
3881185
MC/DC100%2/2
$fn eq "count" or $fn eq "count_distinct"
$fn eq "count" $fn eq "count_distinct"
Truth table100%3/3
A or B
A= $fn eq "count"B= $fn eq "count_distinct"
ABresult
1X1
011
000
3333 185 ▶ return 0 unless defined $col;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col 0 185 185
3334 # For sum/avg/min/max, only push when at least one value is a plain number
3335 # and every non-null/non-blank value passes looks_like_number.
3336 #
3337 # Two cases where both paths must agree:
3338 # - All values undef/blank: Perl fold produces no rows; SQL SUM(NULL)
3339 # produces NULL, normalised to 0 by D::A -> discrepancy. Return 0 so
3340 # the Perl fold runs and yields the expected "No plottable data" result.
3341 # - Currency/accounting notation (e.g. ($1,234)): _numeric_cell strips
3342 # these correctly; SQL sees non-numeric text -> SUM = NULL -> 0. Return 0
3343 # so _numeric_cell is used on every value.
3344 185 require Scalar::Util;
3345 185 my $found = 0;
3346 185 ▶ for my $row (@{ $records // [] }) {
Condition50%1/2
$records // []
l!l
1850
MC/DC0%0/1
$records // []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
3347 956 my $v = $row->{$col};
3348 956 ▶ next unless defined $v && length($v); # undef/blank: same effect as NULL
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and length $v 2 954 956
Condition66%2/3
defined $v and length $v
!ll&&!rl&&r
20954
MC/DC50%1/2
defined $v and length $v
defined $v length $v
Truth table66%2/3
A and B
A= defined $vB= length $v
ABresult
0X0
100
111
3349 954 ▶ return 0 unless Scalar::Util::looks_like_number($v);
Branch: 1 branch
BranchTrueFalseTotal
unless &Scalar::Util::looks_like_number($v) 12 942 954
3350 942 $found = 1;
3351 }
3352 173 return $found; # 0 (false) when every sampled value was undef or blank
3353 }
3354  
3355 # _parse_measure_param($spec_str) -> \%measure | undef
3356 #
3357 # Parse 'col:fn:as' into { col => ..., fn => ..., as => ... }.
3358 # Shared dialect for /pivot so it does not invent a second format.
3359 # $fn is lower-cased first, so SUM and P90 are the same measures as sum and
3360 # p90. Returns undef for an invalid or unrecognised spec.
3361 63 ▶sub _parse_measure_param {
Subroutine _parse_measure_param: called CC=8 SCAR=21.1
3362 63 my $str = shift;
3363 63 ▶ return undef unless defined $str && length($str);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str and length $str 0 63 63
Condition33%1/3
defined $str and length $str
!ll&&!rl&&r
0063
MC/DC0%0/2
defined $str and length $str
defined $str length $str
Truth table33%1/3
A and B
A= defined $strB= length $str
ABresult
0X0
100
111
3364 63 my ($col, $fn, $as) = split /:/, $str, 3;
3365 63 ▶ return undef unless defined $fn && defined $as && length($fn) && length($as);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fn and defined $as and length $fn and length $as 3 60 63
Condition88%8/9
defined $fn and defined $as and length $fn and length $as
!ll&&!rl&&r
3060
defined $fn and defined $as and length $fn
!ll&&!rl&&r
2160
defined $fn and defined $as
!ll&&!rl&&r
1161
MC/DC75%3/4
defined $fn and defined $as and length $fn and length $as
defined $fn defined $as length $fn length $as
Truth table80%4/5
A and B and C and D
A= defined $fnB= defined $asC= length $fnD= length $as
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3366 60 $fn = lc $fn;
3367 60 ▶ return undef unless _measure_fn_ok($fn);
Branch: 1 branch
BranchTrueFalseTotal
unless _measure_fn_ok($fn) 8 52 60
3368 52 return { col => $col, fn => $fn, as => $as };
3369 }
3370  
3371 # _grouped_totals($self, \%pipeline, \%spec) -> \@rows
3372 #
3373 # Single GROUP BY entry point for all four chart routes. Returns an arrayref
3374 # of hashrefs, each containing the 'by' column values and the aggregate result
3375 # under $spec->{as}.
3376 #
3377 # $pipeline = { source => $src_or_undef, records => \@rows }
3378 # source -- a DataSource or Database::Join for the push path; undef when
3379 # the pipeline is a /combine union (must fold in Perl).
3380 # records -- the already-fetched rows (pre-filtered by the caller).
3381 #
3382 # $spec = { by => [...], fn => ..., val => ..., as => ..., [sort_by, having, limit, offset] }
3383 #
3384 # Dispatch:
3385 # Push path -- $source is defined, measure is pushable (checked by
3386 # _measure_pushable), and either no active f= filters or all
3387 # active filters are SQL-pushable (via _filter_specs_to_criteria).
3388 # Calls $source->aggregate() with pushable criteria when present.
3389 # Perl fold -- Iterates $pipeline->{records} (pre-filtered by the caller)
3390 # when the push path is unavailable (combine union, non-SQL
3391 # source, non-pushable measure, or residual filters that cannot
3392 # be expressed as SQL criteria).
3393 #
3394 # $ENV{BI_FORCE_PERL_AGG}: set to a true value in tests to force the Perl fold
3395 # regardless of source type, enabling cross-backend equivalence assertions.
3396 557 ▶sub _grouped_totals :Protected ($self, $pipeline, $spec) {
Subroutine _grouped_totals: called CC=79 SCAR=52.4
3397 557 my $source = $pipeline->{source};
3398 557 ▶ my $records = $pipeline->{records} // [];
Condition50%1/2
$pipeline->{"records"} // []
l!l
5570
MC/DC0%0/1
$pipeline->{"records"} // []
$pipeline->{"records"}
Truth table50%1/2
A
A= $pipeline->{"records"}
Aresult
11
00
3399 557 ▶ my $by = $spec->{by} // [];
Condition50%1/2
$spec->{"by"} // []
l!l
5570
MC/DC0%0/1
$spec->{"by"} // []
$spec->{"by"}
Truth table50%1/2
A
A= $spec->{"by"}
Aresult
11
00
3400 557 ▶ my $fn = lc($spec->{fn} // 'count');
Condition50%1/2
$spec->{"fn"} // "count"
l!l
5570
MC/DC0%0/1
$spec->{"fn"} // "count"
$spec->{"fn"}
Truth table50%1/2
A
A= $spec->{"fn"}
Aresult
11
00
3401 557 my $val_col = $spec->{val};
3402 557 ▶ my $as = $spec->{as} // 'value';
Condition50%1/2
$spec->{"as"} // "value"
l!l
5570
MC/DC0%0/1
$spec->{"as"} // "value"
$spec->{"as"}
Truth table50%1/2
A
A= $spec->{"as"}
Aresult
11
00
3403  
3404 # Push path: use backend aggregate() when safe.
3405 # When f= filters are active, _filter_specs_to_criteria translates as many
3406 # specs as possible to SQL criteria. The push path is used only when ALL
3407 # specs are SQL-pushable (no residual); otherwise the Perl fold handles the
3408 # pre-filtered records the caller already passed in.
3409 557 my @f_specs = grep { /\S/ } @{ _filter_specs($self) };
3410 557 my $has_filter = !!@f_specs;
3411  
3412 # SQL::Statement 1.414 (the SQL engine under DBD::CSV) uses
3413 # "use warnings FATAL => 'all'" and calls join("\0", @row[@keycols])
3414 # inside getAffectedResult without guarding against undef. When a GROUP BY
3415 # column contains blank CSV cells (empty_is_undef => 1 converts them to
3416 # undef), the join triggers a fatal "uninitialized value" exception and the
3417 # execute() call dies. The correct fix is to use
3418 # map { $_ // '' } @row[@keycols]
3419 # in SQL::Statement::getAffectedResult, but the module has been unmaintained
3420 # since 2020 (21 open RT tickets as of 2026-10).
3421 # See: https://rt.cpan.org/Ticket/Display.html?id=181946
3422 # Skip the push path whenever any 'by' column has a blank or undef value so
3423 # DBD::CSV/SQL::Statement is never asked to GROUP BY a null key.
3424 # TODO: remove this guard once SQL-Statement RT#181946 is fixed (last checked: 1.414, still the latest release, 2026-11-06).
3425 557 ▶ my $has_null_by_key = @$by && do {
Condition100%3/3
@$by && do { my $found; KEY_SCAN: foreach my $row (@$records) { foreach my $col (@$by) { my $v = $row->{$col}; unless (defined $v and length $v) { $found = 1; last KEY_SCAN; } ; } ; } ; $found }
!ll&&!rl&&r
165392
MC/DC100%2/2
@$by && do { my $found; KEY_SCAN: foreach my $row (@$records) { foreach my $col (@$by) { my $v = $row->{$col}; unless (defined $v and length $v) { $found = 1; last KEY_SCAN; } ; } ; } ; $found }
@$by do { my $found; KEY_SCAN: foreach my $row (@$records) { foreach my $col (@$by) { my $v = $row->{$col}; unless (defined $v and length $v) { $found = 1; last KEY_SCAN; } ; } ; } ; $found }
Truth table100%3/3
A && B
A= @$byB= do { my $found; KEY_SCAN: foreach my $row (@$records) { foreach my $col (@$by) { my $v = $row->{$col}; unless (defined $v and length $v) { $found = 1; last KEY_SCAN; } ; } ; } ; $found }
ABresult
0X0
100
111
3426 541 my $found;
3427 541 KEY_SCAN: for my $row (@$records) {
3428 3133 for my $col (@$by) {
3429 3424 my $v = $row->{$col};
3430 3424 ▶ if (!defined($v) || !length($v)) { $found = 1; last KEY_SCAN; }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $v and length $v) 2 3422 3424
Condition66%2/3
defined $v and length $v
!ll&&!rl&&r
203422
MC/DC50%1/2
defined $v and length $v
defined $v length $v
Truth table66%2/3
A and B
A= defined $vB= length $v
ABresult
0X0
100
111
3431 }
3432 }
3433 541 $found;
3434 };
3435  
3436 # When filters are active, translate them to SQL criteria for the push path.
3437 # If any spec has no SQL equivalent (@residual is non-empty), the push path
3438 # is skipped and the Perl fold uses the already-filtered $records.
3439 557 ▶ my ($push_crit, $push_residual) = ($has_filter && $source)
Branch: 1 branch
BranchTrueFalseTotal
$has_filter && $source ? : 9 548 557
Condition66%2/3
$has_filter and $source
!ll&&!rl&&r
54809
MC/DC50%1/2
$has_filter and $source
$has_filter $source
Truth table66%2/3
A and B
A= $has_filterB= $source
ABresult
0X0
100
111
3440 ? _filter_specs_to_criteria(\@f_specs, $source)
3441 : ({}, []);
3442 557 ▶ my $can_push_filters = !$has_filter || (!@$push_residual && %$push_crit);
Condition50%3/6
!$has_filter || !@$push_residual && %$push_crit
l!l&&r!l&&!r
54809
not @$push_residual and %$push_crit
!ll&&!rl&&r
900
MC/DC33%1/3
!$has_filter || !@$push_residual && %$push_crit
!$has_filter not @$push_residual %$push_crit
Truth table50%2/4
not(A) || not(B) and C
A= !$has_filterB= not @$push_residualC= %$push_crit
ABCresult
1XX1
0111
00X0
0100
3443  
3444 # Skip the push path when any 'by' or 'val' column is virtual (added by
3445 # _apply_calc_fields or named-group loader). Virtual columns do not exist in
3446 # the backend and would cause a "No such column" SQL error before the fold fallback.
3447 557 ▶ my $virt = $self->stash('_virtual_columns') // {};
Condition100%2/2
$self->stash("_virtual_columns") // {}
l!l
8549
MC/DC100%1/1
$self->stash("_virtual_columns") // {}
$self->stash("_virtual_columns")
Truth table100%2/2
A
A= $self->stash("_virtual_columns")
Aresult
11
00
3448 763 ▶ my $has_virtual = grep { $virt->{$_} }
Branch: 1 branch
BranchTrueFalseTotal
defined $val_col ? : 157 400 557
3449 557 ▶ (@$by, (defined $val_col ? $val_col : ()), map { (split /:/, $_, 2)[0] // () } @f_specs);
Condition33%1/3
(split(/:/u, $_, 2))[0] // ()
l!l&&r!l&&!r
900
MC/DC0%0/2
(split(/:/u, $_, 2))[0] // ()
(split(/:/u, $_, 2))[0] ()
Truth table33%1/3
A // B
A= (split(/:/u, $_, 2))[0]B= ()
ABresult
1X1
011
000
3450  
3451 557 ▶ unless ($ENV{BI_FORCE_PERL_AGG} || _dedup_requested($self) || $has_virtual || !$can_push_filters || $has_null_by_key || !$source
Branch: 1 branch
BranchTrueFalseTotal
unless ($ENV{"BI_FORCE_PERL_AGG"} or _dedup_requested($self) or $has_virtual or not $can_push_filters or $has_null_by_key or not $source or not _measure_pushable($source, $fn, $val_col, $records)) 483 74 557
Condition94%17/18
$ENV{"BI_FORCE_PERL_AGG"} or _dedup_requested($self) or $has_virtual or not $can_push_filters or $has_null_by_key or not $source or not _measure_pushable($source, $fn, $val_col, $records)
l!l&&r!l&&!r
3143483
$ENV{"BI_FORCE_PERL_AGG"} or _dedup_requested($self) or $has_virtual or not $can_push_filters or $has_null_by_key or not $source
l!l&&r!l&&!r
247526
$ENV{"BI_FORCE_PERL_AGG"} or _dedup_requested($self) or $has_virtual or not $can_push_filters or $has_null_by_key
l!l&&r!l&&!r
222533
$ENV{"BI_FORCE_PERL_AGG"} or _dedup_requested($self) or $has_virtual or not $can_push_filters
l!l&&r!l&&!r
139535
$ENV{"BI_FORCE_PERL_AGG"} or _dedup_requested($self) or $has_virtual
l!l&&r!l&&!r
58544
$ENV{"BI_FORCE_PERL_AGG"} or _dedup_requested($self)
l!l&&r!l&&!r
50552
MC/DC85%6/7
$ENV{"BI_FORCE_PERL_AGG"} or _dedup_requested($self) or $has_virtual or not $can_push_filters or $has_null_by_key or not $source or not _measure_pushable($source, $fn, $val_col, $records)
$ENV{"BI_FORCE_PERL_AGG"} _dedup_requested($self) $has_virtual not $can_push_filters $has_null_by_key not $source not _measure_pushable($source, $fn, $val_col, $records)
Truth table87%7/8
A or B or C or not(D) or E or not(F) or not(G)
A= $ENV{"BI_FORCE_PERL_AGG"}B= _dedup_requested($self)C= $has_virtualD= not $can_push_filtersE= $has_null_by_keyF= not $sourceG= not _measure_pushable($source, $fn, $val_col, $records)
ABCDEFGresult
1XXXXXX1
01XXXXX1
001XXXX1
0001XXX1
00001XX1
000001X1
00000011
00000000
3452 || !_measure_pushable($source, $fn, $val_col, $records)) {
3453 483 my $m = _measure($fn, $val_col, $as);
3454 483 my $agg_rows = eval {
3455 $source->aggregate(
3456 by => $by,
3457 measures => [$m],
3458 ($has_filter && %$push_crit ? (%$push_crit) : ()),
3459 ($spec->{sort_by} ? (sort_by => $spec->{sort_by}) : ()),
3460 ($spec->{having} ? (having => $spec->{having}) : ()),
3461 ($spec->{limit} ? (limit => $spec->{limit}) : ()),
3462 483 ▶ ($spec->{offset} ? (offset => $spec->{offset}) : ()),
Branch: 5 branches
BranchTrueFalseTotal
$has_filter && %$push_crit ? : 0 483 483
$spec->{'sort_by'} ? : 0 483 483
$spec->{'having'} ? : 0 483 483
$spec->{'limit'} ? : 0 483 483
$spec->{'offset'} ? : 0 483 483
Condition33%1/3
$has_filter and %$push_crit
!ll&&!rl&&r
48300
MC/DC0%0/2
$has_filter and %$push_crit
$has_filter %$push_crit
Truth table33%1/3
A and B
A= $has_filterB= %$push_crit
ABresult
0X0
100
111
3463 )
3464 };
3465 483 ▶ unless ($@) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($@) 483 0 483
3466 483 ▶ return $agg_rows // [];
Condition50%1/2
$agg_rows // []
l!l
4830
MC/DC0%0/1
$agg_rows // []
$agg_rows
Truth table50%1/2
A
A= $agg_rows
Aresult
11
00
3467 }
3468 0 $self->app->log->debug("aggregate() push failed: $@; falling back to Perl fold");
3469 }
3470  
3471 # Perl fold over pre-filtered records.
3472 #
3473 # The fold keeps a running total for the functions that are sums of their
3474 # parts (sum, avg, min, max) and the values themselves for the ones that are
3475 # not (median, a percentile, stdev, range), which are resolved once the group
3476 # is complete. first and last are order-dependent, so they are taken as the
3477 # rows arrive and need no list at all.
3478 74 my (%seen_warned, %seen_key, @key_order);
3479 74 my (%totals, %count_map, %distinct_vals, %values);
3480  
3481 74 for my $row (@$records) {
3482 # Skip rows where any 'by' column is empty/undef (mirrors SQL GROUP BY NULL exclusion).
3483 # Note: calc field columns store '(unparseable)' (not undef) for failed expressions,
3484 # so those rows pass this guard and appear in the (unparseable) group instead.
3485 452 ▶ my @key_parts = map { $row->{$_} // '' } @$by;
Condition100%2/2
$row->{$_} // ""
l!l
3546
MC/DC100%1/1
$row->{$_} // ""
$row->{$_}
Truth table100%2/2
A
A= $row->{$_}
Aresult
11
00
3486 452 ▶ next if @$by && grep { !length($_) } @key_parts;
Branch: 1 branch
BranchTrueFalseTotal
if @$by and grep {not length $_;} @key_parts 4 448 452
Condition100%3/3
@$by and grep {not length $_;} @key_parts
!ll&&!rl&&r
1073414
MC/DC100%2/2
@$by and grep {not length $_;} @key_parts
@$by grep {not length $_;} @key_parts
Truth table100%3/3
A and B
A= @$byB= grep {not length $_;} @key_parts
ABresult
0X0
100
111
3487 448 my $key = join("\x00", @key_parts);
3488  
3489 448 ▶ if ($fn eq 'count') {
Branch: 3 branches
BranchTrueFalseTotal
if ($fn eq 'count') { } 63 385 448
elsif ($fn eq 'count_distinct') { } 0 385 385
elsif ($fn eq 'first' or $fn eq 'last') { } 108 277 385
3490 63 ▶ push @key_order, $key unless $seen_key{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_key{$key}++ 48 15 63
3491 63 $totals{$key}++;
3492 } elsif ($fn eq 'count_distinct') {
3493 0 ▶ push @key_order, $key unless $seen_key{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_key{$key}++ 0 0 0
3494 0 ▶ my $dv = defined $val_col ? ($row->{$val_col} // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $val_col ? : 0 0 0
Condition0%0/2
$row->{$val_col} // ""
l!l
00
MC/DC0%0/1
$row->{$val_col} // ""
$row->{$val_col}
Truth table0%0/2
A
A= $row->{$val_col}
Aresult
11
00
3495 0 $distinct_vals{$key}{$dv}++;
3496 ▶ } elsif ($fn eq 'first' || $fn eq 'last') {
Condition100%3/3
$fn eq "first" or $fn eq "last"
l!l&&r!l&&!r
5454277
MC/DC100%2/2
$fn eq "first" or $fn eq "last"
$fn eq "first" $fn eq "last"
Truth table100%3/3
A or B
A= $fn eq "first"B= $fn eq "last"
ABresult
1X1
011
000
3497 # first/last read any column, not only a numeric one, and they
3498 # report the value as it appears: the number a cell holds when it
3499 # holds a number, the text it holds otherwise. A blank cell is
3500 # not a value, so it is passed over -- the first row that has
3501 # something in the column is the first value.
3502 108 ▶ my $v = defined $val_col ? $row->{$val_col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $val_col ? : 108 0 108
3503 108 ▶ next unless defined $v && length $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and length $v 0 108 108
Condition33%1/3
defined $v and length $v
!ll&&!rl&&r
00108
MC/DC0%0/2
defined $v and length $v
defined $v length $v
Truth table33%1/3
A and B
A= defined $vB= length $v
ABresult
0X0
100
111
3504 108 ▶ push @key_order, $key unless $seen_key{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_key{$key}++ 28 80 108
3505 108 ▶ $totals{$key} = $v if $fn eq 'last' || !exists $totals{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "last" or not exists $totals{$key} 68 40 108
Condition100%3/3
$fn eq "last" or not exists $totals{$key}
l!l&&r!l&&!r
541440
MC/DC100%2/2
$fn eq "last" or not exists $totals{$key}
$fn eq "last" not exists $totals{$key}
Truth table100%3/3
A or not(B)
A= $fn eq "last"B= not exists $totals{$key}
ABresult
1X1
011
000
3506 } else {
3507 277 ▶ my $v = defined $val_col ? ($row->{$val_col} // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $val_col ? : 277 0 277
Condition100%2/2
$row->{$val_col} // ""
l!l
2752
MC/DC100%1/1
$row->{$val_col} // ""
$row->{$val_col}
Truth table100%2/2
A
A= $row->{$val_col}
Aresult
11
00
3508 277 my $n = _numeric_cell($v);
3509 277 ▶ unless (defined $n) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $n) 6 271 277
3510 6 ▶ unless ($seen_warned{"$fn\x01" . ($val_col // '')}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($seen_warned{"$fn\cA" . ($val_col // "")}++) 4 2 6
Condition50%1/2
$val_col // ""
l!l
60
MC/DC0%0/1
$val_col // ""
$val_col
Truth table50%1/2
A
A= $val_col
Aresult
11
00
3511 4 ▶ carp $self->_i18n('warn_measure_fallback', $fn, $val_col // '(none)');
Condition50%1/2
$val_col // "(none)"
l!l
40
MC/DC0%0/1
$val_col // "(none)"
$val_col
Truth table50%1/2
A
A= $val_col
Aresult
11
00
3512 }
3513 6 next; # skip: do NOT add key to order for non-numeric rows
3514 }
3515 271 ▶ push @key_order, $key unless $seen_key{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_key{$key}++ 100 171 271
3516 271 ▶ if ($fn eq 'sum') { $totals{$key} += $n }
Branch: 4 branches
BranchTrueFalseTotal
if ($fn eq 'sum') { } 58 213 271
elsif ($fn eq 'avg') { } 3 210 213
elsif ($fn eq 'min') { } 0 210 210
elsif ($fn eq 'max') { } 0 210 210
3517 3 elsif ($fn eq 'avg') { $totals{$key} += $n; $count_map{$key}++ }
3518 0 ▶ elsif ($fn eq 'min') { $totals{$key} = (!exists $totals{$key} || $n < $totals{$key}) ? $n : $totals{$key} }
Branch: 1 branch
BranchTrueFalseTotal
!exists $totals{$key} || $n < $totals{$key} ? : 0 0 0
Condition0%0/3
not exists $totals{$key} or $n < $totals{$key}
l!l&&r!l&&!r
000
MC/DC0%0/2
not exists $totals{$key} or $n < $totals{$key}
not exists $totals{$key} $n < $totals{$key}
Truth table0%0/3
not(A) or B
A= not exists $totals{$key}B= $n < $totals{$key}
ABresult
1X1
011
000
3519 0 ▶ elsif ($fn eq 'max') { $totals{$key} = (!exists $totals{$key} || $n > $totals{$key}) ? $n : $totals{$key} }
Branch: 1 branch
BranchTrueFalseTotal
!exists $totals{$key} || $n > $totals{$key} ? : 0 0 0
Condition0%0/3
not exists $totals{$key} or $n > $totals{$key}
l!l&&r!l&&!r
000
MC/DC0%0/2
not exists $totals{$key} or $n > $totals{$key}
not exists $totals{$key} $n > $totals{$key}
Truth table0%0/3
not(A) or B
A= not exists $totals{$key}B= $n > $totals{$key}
ABresult
1X1
011
000
3520 210 else { push @{ $values{$key} }, $n }
3521 }
3522 }
3523  
3524 74 ▶ if ($fn eq 'avg') {
Branch: 3 branches
BranchTrueFalseTotal
if ($fn eq 'avg') { } 2 72 74
elsif ($fn eq 'count_distinct') { } 0 72 72
elsif (%values) { } 24 48 72
3525 2 for my $k (keys %totals) {
3526 2 ▶ $totals{$k} = $count_map{$k} ? $totals{$k} / $count_map{$k} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$count_map{$k} ? : 2 0 2
3527 }
3528 } elsif ($fn eq 'count_distinct') {
3529 0 for my $k (@key_order) {
3530 0 ▶ $totals{$k} = scalar keys %{ $distinct_vals{$k} // {} };
Condition0%0/2
$distinct_vals{$k} // {}
l!l
00
MC/DC0%0/1
$distinct_vals{$k} // {}
$distinct_vals{$k}
Truth table0%0/2
A
A= $distinct_vals{$k}
Aresult
11
00
3531 }
3532 } elsif (%values) {
3533 # median / p<N> / stdev / range: resolved from the group's values, and
3534 # through the same arithmetic the stats view uses for a whole column.
3535 24 for my $k (keys %values) {
3536 56 my @sorted = sort { $a <=> $b } @{ $values{$k} };
3537 56 $totals{$k} = _measure_value($fn, \@sorted);
3538 }
3539 }
3540  
3541 # Assemble result rows in ascending key order (matching the SQL push path)
3542 # unless the caller requested an explicit sort.
3543 74 ▶ unless ($spec->{sort_by}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($spec->{"sort_by"}) 74 0 74
3544 74 @key_order = sort @key_order;
3545 }
3546 74 my @result;
3547 74 for my $key (@key_order) {
3548 176 ▶ my @parts = @$by ? (split /\x00/, $key, scalar @$by) : ();
Branch: 1 branch
BranchTrueFalseTotal
@$by ? : 162 14 176
3549 176 my %row;
3550 176 for my $i (0 .. $#$by) {
3551 175 $row{$by->[$i]} = $parts[$i];
3552 }
3553 176 ▶ $row{$as} = $totals{$key} // ($fn =~ /\A(?:sum|count|count_distinct)\z/ ? 0 : undef);
Branch: 1 branch
BranchTrueFalseTotal
$fn =~ /\A(?:sum|count|count_distinct)\z/u ? : 0 0 0
Condition50%1/2
$totals{$key} // ($fn =~ /\A(?:sum|count|count_distinct)\z/u ? 0 : undef)
l!l
1760
MC/DC0%0/1
$totals{$key} // ($fn =~ /\A(?:sum|count|count_distinct)\z/u ? 0 : undef)
$totals{$key}
Truth table50%1/2
A
A= $totals{$key}
Aresult
11
00
3554 176 push @result, \%row;
3555 }
3556  
3557 74 return \@result;
3558 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3559  
3560 # _rows_of_page(\@rows, $offset, $per_page) -> \@page
3561 #
3562 # One page of rows, in an array of its own. The rows may be a backend's own
3563 # read-only array, as they are from a DBI handle that is not SQLite, so they are
3564 # copied and never spliced.
3565 341 ▶sub _rows_of_page {
Subroutine _rows_of_page: called CC=3 SCAR=11.0
3566 341 my ($rows, $offset, $per_page) = @_;
3567 # A negative offset would count from the end of the rows.
3568 341 ▶ $offset = 0 if $offset < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $offset < 0 1 340 341
3569 341 my $last = $offset + $per_page - 1;
3570 341 ▶ $last = $#$rows if $last > $#$rows;
Branch: 1 branch
BranchTrueFalseTotal
if $last > $rows->$#* 331 10 341
3571 341 return [ @{$rows}[$offset .. $last] ];
3572 }
3573  
3574 # _page_count($total, $per_page) -> $pages
3575 #
3576 # How many pages $total rows make, for the table's "Page N of M". No rows is
3577 # still one page, the empty one the table shows.
3578 359 ▶sub _page_count {
Subroutine _page_count: called CC=4 SCAR=14.1
3579 359 my ($total, $per_page) = @_;
3580 359 ▶ return 1 unless $total && $per_page && $per_page > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $total and $per_page and $per_page > 0 9 350 359
Condition66%4/6
$total and $per_page and $per_page > 0
!ll&&!rl&&r
90350
$total and $per_page
!ll&&!rl&&r
90350
MC/DC33%1/3
$total and $per_page and $per_page > 0
$total $per_page $per_page > 0
Truth table50%2/4
A and B and C
A= $totalB= $per_pageC= $per_page > 0
ABCresult
0XX0
10X0
1100
1111
3581 350 return int(($total + $per_page - 1) / $per_page);
3582 }
3583  
3584 # Where a cell with no date or number sorts: first, ascending, as -Infinity
3585 # does in the browser.
3586 10 Readonly my $NO_NUMBER => -9**9**9;
3587  
3588 # _sort_records(\@rows, $column, $dir) -> \@sorted
3589 #
3590 # Every row, in the order the table's own header sort gives a page of them
3591 # (biValueComparator in dashboard.html.tt), so the first page of a table too
3592 # long for one page is the first page of the sorted rows rather than the first
3593 # rows sorted. The column sorts as dates when every non-empty cell is one
3594 # (YYYY-MM-DD, or M/D/YYYY unless a cell shows the day comes first), else as
3595 # numbers when every non-empty cell holds one (Util::parse_number, which the
3596 # browser's parseAccounting copies: "$1,000" and "(5)" are numbers, "T27" is
3597 # text), else as text the way localeCompare(..., { numeric: true, sensitivity:
3598 # 'base' }) does: case and accents ignored, a run of digits compared as a
3599 # number. An empty cell sorts first, ascending. Rows that compare equal keep
3600 # their order, in either direction. A new array: the rows may be read-only.
3601 11 ▶sub _sort_records ($rows, $column, $dir) {
Subroutine _sort_records: called CC=14 SCAR=33.5
3602 my @text = map {
3603 11 ▶ my $v = $_->{$column} // '';
Condition50%1/2
$_->{$column} // ""
l!l
330
MC/DC0%0/1
$_->{$column} // ""
$_->{$column}
Truth table50%1/2
A
A= $_->{$column}
Aresult
11
00
3604 33 $v =~ s/\A\s+//;
3605 33 $v =~ s/\s+\z//;
3606 33 $v;
3607 } @$rows;
3608 11 my @filled = grep { length } @text;
3609  
3610 11 my $key_of; # cell text -> number; text sorts when there is none
3611 11 ▶ if (@filled && !(grep { !m{\A(?:\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})\z} } @filled)) {
Branch: 2 branches
BranchTrueFalseTotal
if (@filled and not grep({not m[\A(?:\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})\z]u;} @filled)) { } 2 9 11
elsif (@filled and not grep({not defined Database::BI::Util::parse_number($_);} @filled)) { } 0 9 9
Condition66%2/3
@filled and not grep({not m[\A(?:\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})\z]u;} @filled)
!ll&&!rl&&r
092
MC/DC50%1/2
@filled and not grep({not m[\A(?:\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})\z]u;} @filled)
@filled not grep({not m[\A(?:\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})\z]u;} @filled)
Truth table66%2/3
A and not(B)
A= @filledB= not grep({not m[\A(?:\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})\z]u;} @filled)
ABresult
0X0
100
111
3612 2 my $month_first = 1;
3613 2 for (@filled) {
3614 4 ▶ my ($p1, $p2) = m{\A(\d{1,2})/(\d{1,2})/} or next;
Branch: 1 branch
BranchTrueFalseTotal
() = m[\A(\d{1,2})/(\d{1,2})/]u or next 0 4 4
3615 0 ▶ if ($p1 > 12) { $month_first = 0; last }
Branch: 1 branch
BranchTrueFalseTotal
if ($p1 > 12) 0 0 0
3616 0 ▶ if ($p2 > 12) { last }
Branch: 1 branch
BranchTrueFalseTotal
if ($p2 > 12) 0 0 0
3617 }
3618 4 ▶ $key_of = sub ($v) {
Subroutine __ANON__: called CC=4 SCAR=25.0
3619 4 ▶ return $1 * 10_000 + $2 * 100 + $3 if $v =~ /\A(\d{4})-(\d{2})-(\d{2})\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /\A(\d{4})-(\d{2})-(\d{2})\z/u 4 0 4
3620 0 ▶ if ($v =~ m{\A(\d{1,2})/(\d{1,2})/(\d{4})\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v =~ m[\A(\d{1,2})/(\d{1,2})/(\d{4})\z]u) 0 0 0
3621 0 ▶ return $month_first ? $3 * 10_000 + $1 * 100 + $2 : $3 * 10_000 + $2 * 100 + $1;
Branch: 1 branch
BranchTrueFalseTotal
$month_first ? : 0 0 0
3622 }
3623 0 return $NO_NUMBER;
3624 2 };
3625 29 ▶ } elsif (@filled && !(grep { !defined Database::BI::Util::parse_number($_) } @filled)) {
Condition33%1/3
@filled and not grep({not defined Database::BI::Util::parse_number($_);} @filled)
!ll&&!rl&&r
090
MC/DC0%0/2
@filled and not grep({not defined Database::BI::Util::parse_number($_);} @filled)
@filled not grep({not defined Database::BI::Util::parse_number($_);} @filled)
Truth table33%1/3
A and not(B)
A= @filledB= not grep({not defined Database::BI::Util::parse_number($_);} @filled)
ABresult
0X0
100
111
3626 0 ▶ $key_of = sub ($v) { Database::BI::Util::parse_number($v) // $NO_NUMBER };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Condition0%0/3
Database::BI::Util::parse_number($v) // $NO_NUMBER
l!l&&r!l&&!r
000
MC/DC0%0/2
Database::BI::Util::parse_number($v) // $NO_NUMBER
Database::BI::Util::parse_number($v) $NO_NUMBER
Truth table0%0/3
A // B
A= Database::BI::Util::parse_number($v)B= $NO_NUMBER
ABresult
1X1
011
000
3627 }
3628  
3629 # Equal rows keep their order in either direction, as the browser's stable
3630 # sort of -cmp does: the direction turns the comparison, not the result.
3631 11 ▶ my $sign = $dir eq 'desc' ? -1 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$dir eq 'desc' ? : 10 1 11
3632 11 my @order;
3633 11 ▶ if ($key_of) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key_of) { } 2 9 11
3634 2 my @key = map { $key_of->($_) } @text;
3635 2 ▶ @order = sort { $sign * ($key[$a] <=> $key[$b]) || $a <=> $b } 0 .. $#$rows;
Condition33%1/3
$sign * ($key[$a] <=> $key[$b]) || $a <=> $b
l!l&&r!l&&!r
200
MC/DC0%0/2
$sign * ($key[$a] <=> $key[$b]) || $a <=> $b
$sign * ($key[$a] <=> $key[$b]) $a <=> $b
Truth table33%1/3
A || B
A= $sign * ($key[$a] <=> $key[$b])B= $a <=> $b
ABresult
1X1
011
000
3636 } else {
3637 9 my @key = map { _collation_key($_) } @text;
3638 9 ▶ @order = sort { $sign * _collate($key[$a], $key[$b]) || $a <=> $b } 0 .. $#$rows;
Condition33%1/3
$sign * _collate($key[$a], $key[$b]) || $a <=> $b
l!l&&r!l&&!r
3200
MC/DC0%0/2
$sign * _collate($key[$a], $key[$b]) || $a <=> $b
$sign * _collate($key[$a], $key[$b]) $a <=> $b
Truth table33%1/3
A || B
A= $sign * _collate($key[$a], $key[$b])B= $a <=> $b
ABresult
1X1
011
000
3639 }
3640 11 return [ @{$rows}[@order] ];
3641 }
3642  
3643 # _collation_key($text) -> \@tokens
3644 #
3645 # The text as localeCompare with sensitivity 'base' and numeric sees it: case
3646 # and accents folded away, each run of digits one number, every other
3647 # character ranked as ICU's root collation does -- spaces, then punctuation and
3648 # symbols, then digits, then letters.
3649 29 ▶sub _collation_key ($text) {
Subroutine _collation_key: called CC=5 SCAR=16.7
3650 29 my $folded = CORE::fc(Unicode::Normalize::NFD($text));
3651 29 $folded =~ s/\p{Mn}+//g;
3652 29 my @tokens;
3653 29 ▶ while ($folded =~ /(\d+)|(.)/gs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($folded =~ /(\d+)|(.)/gsu) 138 29 167
3654 138 ▶ if (defined $1) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $1) { } 0 138 138
3655 0 push @tokens, [2, $1 + 0];
3656 } else {
3657 138 my $c = $2;
3658 138 ▶ push @tokens, [ $c =~ /\s/ ? 0 : $c =~ /\p{L}/ ? 3 : 1, $c ];
Branch: 2 branches
BranchTrueFalseTotal
$c =~ /\s/u ? : 0 138 138
$c =~ /\p{L}/u ? : 138 0 138
3659 }
3660 }
3661 29 return \@tokens;
3662 }
3663  
3664 # _collate(\@a, \@b) -> -1 | 0 | 1
3665 32 ▶sub _collate ($x, $y) {
Subroutine _collate: called CC=6 SCAR=19.9
3666 32 ▶ my $n = @$x < @$y ? @$x : @$y;
Branch: 1 branch
BranchTrueFalseTotal
@$x < @$y ? : 12 20 32
3667 32 for my $i (0 .. $n - 1) {
3668 32 my ($p, $q) = ($x->[$i], $y->[$i]);
3669 32 ▶ my $c = $p->[0] <=> $q->[0]
Branch: 1 branch
BranchTrueFalseTotal
$p->[0] == 2 ? : 0 32 32
Condition33%1/3
$p->[0] <=> $q->[0] || ($p->[0] == 2 ? $p->[1] <=> $q->[1] : $p->[1] cmp $q->[1])
l!l&&r!l&&!r
0320
MC/DC0%0/2
$p->[0] <=> $q->[0] || ($p->[0] == 2 ? $p->[1] <=> $q->[1] : $p->[1] cmp $q->[1])
$p->[0] <=> $q->[0] ($p->[0] == 2 ? $p->[1] <=> $q->[1] : $p->[1] cmp $q->[1])
Truth table33%1/3
A || B
A= $p->[0] <=> $q->[0]B= ($p->[0] == 2 ? $p->[1] <=> $q->[1] : $p->[1] cmp $q->[1])
ABresult
1X1
011
000
3670 || ($p->[0] == 2 ? $p->[1] <=> $q->[1] : $p->[1] cmp $q->[1]);
3671 32 ▶ return $c if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 32 0 32
3672 }
3673 0 return @$x <=> @$y;
3674 }
3675  
3676 # _fetch_page( $self, $source, \%params ) -> ( $records, $has_next )
3677 # (also stashes page_count, the number of pages: from the rows read, or on
3678 # the SQL fast path, which reads one page and a row, from the source's count)
3679 # params: per_page -- page size (required)
3680 # offset -- 0-based row offset (required)
3681 # dedup -- truthy when ?d=1 dedup is requested
3682 # sort_col -- column name to sort by (optional; default the request's
3683 # sort= parameter)
3684 # sort_dir -- 'asc' or 'desc' (default the request's dir=, else 'asc')
3685 #
3686 # Purpose: Fetch and reduce one page of records from $source, honouring the
3687 # reduce-before-paginate ordering contract. Two modes:
3688 #
3689 # Fast path (no f= filters, no dedup): uses the N+1 trick
3690 # selectall_arrayref(limit => per_page+1, offset => offset). has_next is
3691 # determined by the extra row before it is popped.
3692 #
3693 # Reduction path (f= filters or dedup present): materialises the full result
3694 # in memory, applies all f= filters with _apply_filter_spec (case-insensitive),
3695 # applies dedup if requested, then paginates in Perl. This guarantees that
3696 # the Nth page contains the Nth page of the *reduced* set, not the Nth page
3697 # of the raw set reduced to fewer rows. Memory cost: the full reduced set.
3698 #
3699 # Sort: a sort column takes the reduction path, and every row is sorted by
3700 # _sort_records -- after the fields, filters and cross-row columns, so any
3701 # column the table shows can be sorted on -- before the page is cut. The
3702 # table's header sort works on the rows it was given, so on a table longer
3703 # than a page it sorted only those, and the page was not the first of the
3704 # sorted table; the page asks for sort= instead whenever there is more than
3705 # one page. The backend's sort_by is not used: it compares as text, and
3706 # ignores a column whose name is not a safe identifier. When the sort is
3707 # applied, stash sorted_by => { col, dir } tells the page what it shows.
3708 #
3709 # Returns (undef, 0) when the underlying fetch throws; the caller must handle
3710 # $records being undef.
3711 313 ▶sub _fetch_page :Protected ($self, $source, $params) {
Subroutine _fetch_page: called CC=57 SCAR=48.4
3712 313 my $per_page = $params->{per_page};
3713 313 my $offset = $params->{offset};
3714 313 my $dedup = $params->{dedup};
3715 313 ▶ my $sort_col = $params->{sort_col} // $self->param('sort');
Condition100%3/3
$params->{"sort_col"} // $self->param("sort")
l!l&&r!l&&!r
72304
MC/DC100%2/2
$params->{"sort_col"} // $self->param("sort")
$params->{"sort_col"} $self->param("sort")
Truth table100%3/3
A // B
A= $params->{"sort_col"}B= $self->param("sort")
ABresult
1X1
011
000
3716 313 ▶ $sort_col = undef unless defined $sort_col && length $sort_col;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sort_col and length $sort_col 305 8 313
Condition100%3/3
defined $sort_col and length $sort_col
!ll&&!rl&&r
30418
MC/DC100%2/2
defined $sort_col and length $sort_col
defined $sort_col length $sort_col
Truth table100%3/3
A and B
A= defined $sort_colB= length $sort_col
ABresult
0X0
100
111
3717 313 ▶ my $sort_dir = ($params->{sort_dir} // $self->param('dir') // 'asc') =~ /\Adesc\z/i ? 'desc' : 'asc';
Branch: 1 branch
BranchTrueFalseTotal
(($params->{'sort_dir'} // $self->param('dir')) // 'asc') =~ /\Adesc\z/iu ? : 5 308 313
Condition80%4/5
($params->{"sort_dir"} // $self->param("dir")) // "asc"
l!l
75238
$params->{"sort_dir"} // $self->param("dir")
l!l&&r!l&&!r
750238
MC/DC50%1/2
($params->{"sort_dir"} // $self->param("dir")) // "asc"
$params->{"sort_dir"} $self->param("dir")
Truth table66%2/3
A // B
A= $params->{"sort_dir"}B= $self->param("dir")
ABresult
1X1
011
000
3718  
3719 # Collect and validate the filters, the range's bounds included.
3720 my @f_specs = grep {
3721 84 my ($c, $o) = split /:/, $_, 3;
3722 84 ▶ length($c // '') && defined $o && length $o;
Condition87%7/8
length($c // '') && defined $o && length $o
!ll&&!rl&&r
4080
length($c // "") and defined $o
!ll&&!rl&&r
3180
$c // ""
l!l
822
MC/DC66%2/3
length($c // '') && defined $o && length $o
$c defined $o length $o
Truth table75%3/4
A and B && C
A= $cB= defined $oC= length $o
ABCresult
0XX0
10X0
1100
1111
3723 313 } @{ _filter_specs($self) };
3724  
3725 # Determine whether the source has a SQL backend that supports LIMIT/OFFSET.
3726 # DBD::CSV / SQL::Statement do not implement LIMIT/OFFSET; passing them emits
3727 # a "Bad limit clause" error at the D::A layer before falling back to a Perl
3728 # approach. Avoid the noise by only using the N+1 fast path for SQL-backed
3729 # sources. For non-SQL sources (CSV, XLSX, in-memory) the reduction path
3730 # below materialises the full set and paginates in Perl.
3731 313 ▶ my $is_sql = ($source->can('dbi_source') && $source->dbi_source)
Condition55%5/9
$source->can('dbi_source') && $source->dbi_source || $source->can('pages_on_server') && $source->pages_on_server
l!l&&r!l&&!r
320281
$source->can("dbi_source") and $source->dbi_source
!ll&&!rl&&r
028132
$source->can("pages_on_server") and $source->pages_on_server
!ll&&!rl&&r
02810
MC/DC25%1/4
$source->can('dbi_source') && $source->dbi_source || $source->can('pages_on_server') && $source->pages_on_server
$source->can("dbi_source") $source->dbi_source $source->can("pages_on_server") $source->pages_on_server
Truth table28%2/7
A and B || C and D
A= $source->can("dbi_source")B= $source->dbi_sourceC= $source->can("pages_on_server")D= $source->pages_on_server
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
3732 || ($source->can('pages_on_server') && $source->pages_on_server);
3733  
3734 # A cross-row column is a column of the whole filtered set, so a request that
3735 # names one cannot take the N+1 fast path: it would see one page of rows and
3736 # restart every running total on page 2.
3737 313 ▶ my $cross = length($self->param('cs') // '') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length($self->param('cs') // '') ? : 2 311 313
Condition100%2/2
$self->param("cs") // ""
l!l
3310
MC/DC100%1/1
$self->param("cs") // ""
$self->param("cs")
Truth table100%2/2
A
A= $self->param("cs")
Aresult
11
00
3738  
3739 313 ▶ unless (@f_specs || $dedup || $cross || defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@f_specs or $dedup or $cross or defined $sort_col) 275 38 313
Condition100%9/9
@f_specs or $dedup or $cross or defined $sort_col
l!l&&r!l&&!r
308275
@f_specs or $dedup or $cross
l!l&&r!l&&!r
282283
@f_specs or $dedup
l!l&&r!l&&!r
271285
MC/DC100%4/4
@f_specs or $dedup or $cross or defined $sort_col
@f_specs $dedup $cross defined $sort_col
Truth table100%5/5
A or B or C or D
A= @f_specsB= $dedupC= $crossD= defined $sort_col
ABCDresult
1XXX1
01XX1
001X1
00011
00000
3740 275 ▶ if ($is_sql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_sql) 24 251 275
3741 # Fast path (SQL-backed): delegate LIMIT/OFFSET to the backend N+1 trick.
3742 # Copy before pop: D::A may return a read-only ref to its internal cache.
3743 24 ▶ my @records = @{ $source->selectall_arrayref(
Condition50%1/2
$source->selectall_arrayref("limit", $per_page + 1, "offset", $offset) // []
l!l
210
MC/DC0%0/1
$source->selectall_arrayref("limit", $per_page + 1, "offset", $offset) // []
$source->selectall_arrayref("limit", $per_page + 1, "offset", $offset)
Truth table50%1/2
A
A= $source->selectall_arrayref("limit", $per_page + 1, "offset", $offset)
Aresult
11
00
3744 limit => $per_page + 1, offset => $offset,
3745 ) // [] };
3746 21 ▶ my $has_next = (@records > $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
@records > $per_page ? : 0 21 21
3747 21 ▶ pop @records if $has_next;
Branch: 1 branch
BranchTrueFalseTotal
if $has_next 0 21 21
3748 # The number of pages needs the number of rows. count() remembers a
3749 # file's until it changes, so only the first page of a big SQLite
3750 # file pays for the COUNT(*). Only when there is more than one page:
3751 # a short table shows no pagination. A count that fails costs the
3752 # page its "of M", never the page.
3753 21 ▶ if ($has_next || $offset > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_next or $offset > 0) 0 21 21
Condition33%1/3
$has_next or $offset > 0
l!l&&r!l&&!r
0021
MC/DC0%0/2
$has_next or $offset > 0
$has_next $offset > 0
Truth table33%1/3
A or B
A= $has_nextB= $offset > 0
ABresult
1X1
011
000
3754 0 my $total;
3755 0 my $ok = eval { $total = $source->count; 1 };
3756 0 ▶ $self->stash(page_count => _page_count($total, $per_page))
Branch: 1 branch
BranchTrueFalseTotal
if $ok and defined $total and $total =~ /\A\d+\z/u 0 0 0
Condition0%0/6
$ok and defined $total and $total =~ /\A\d+\z/u
!ll&&!rl&&r
000
$ok and defined $total
!ll&&!rl&&r
000
MC/DC0%0/3
$ok and defined $total and $total =~ /\A\d+\z/u
$ok defined $total $total =~ /\A\d+\z/u
Truth table0%0/4
A and B and C
A= $okB= defined $totalC= $total =~ /\A\d+\z/u
ABCresult
0XX0
10X0
1100
1111
3757 if $ok && defined $total && $total =~ /\A\d+\z/;
3758 }
3759 21 return (\@records, $has_next);
3760 }
3761 # Non-SQL fast path: fetch all, then paginate. Every row is in hand, so
3762 # the number of pages costs nothing.
3763 251 ▶ my $all = $source->selectall_arrayref() // [];
Condition100%2/2
$source->selectall_arrayref // []
l!l
2412
MC/DC100%1/1
$source->selectall_arrayref // []
$source->selectall_arrayref
Truth table100%2/2
A
A= $source->selectall_arrayref
Aresult
11
00
3764 243 ▶ my $has_next = (@$all > $offset + $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
@$all > $offset + $per_page ? : 2 241 243
3765 243 $self->stash(page_count => _page_count(scalar(@$all), $per_page));
3766 243 return (_rows_of_page($all, $offset, $per_page), $has_next);
3767 }
3768  
3769 # Always fetch all rows in Perl and filter with _apply_filter_spec.
3770 # SQL criteria pushdown (passing %criteria to selectall_arrayref) is
3771 # intentionally avoided: on some Perl/D::A version combinations the WHERE
3772 # clause is silently dropped, returning the full unfiltered set. The Perl
3773 # path is correct on every supported version. Memory cost: bounded by the
3774 # source file size (the same as the dedup path already accepted).
3775 38 ▶ my $all = $source->selectall_arrayref() // [];
Condition50%1/2
$source->selectall_arrayref // []
l!l
380
MC/DC0%0/1
$source->selectall_arrayref // []
$source->selectall_arrayref
Truth table50%1/2
A
A= $source->selectall_arrayref
Aresult
11
00
3776  
3777 # A stored date or time pattern is what makes a patterned column comparable
3778 # with the ISO bounds a relative time range carries, and it belongs to stage 2
3779 # of the pipeline -- before the filters of stage 5. The rest of the
3780 # application reaches the filters through that order already; this path, which
3781 # filters before it paginates, is the one call site that would otherwise
3782 # compare the reader's format, so it normalises first, on exactly the rows the
3783 # specs are about to be applied to.
3784 38 $self->_apply_date_normalization($all, [_get_columns($source, $all)],
3785 $self->_calc_spec_key);
3786  
3787 # A failure below is a 400 about the request. It is rendered here, and the
3788 # caller sees the stash and returns rather than drawing a page over it.
3789 5 ▶ my $refuse = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3790 5 my ($why) = @_;
3791 5 $why =~ s/ at \S+ line \d+\.?\n?$//;
3792 5 $self->render(text => $why, status => 400);
3793 5 $self->stash('_cross_row_error' => $why);
3794 5 return;
3795 38 };
3796  
3797 # Stage 4. The page's own fields run on the sliced page (_page_columns), which
3798 # is enough to show them, but a filter or a window that reads one needs it on
3799 # every row, and before them. That pass then only repeats these, on one page.
3800 38 $all = [ @$all ]; # the backend's own array can be read-only
3801 38 my @cols_so_far;
3802 38 ▶ if (defined $params->{calc_spec_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"calc_spec_key"}) 38 0 38
3803 38 my @before = _get_columns($source, $all);
3804 38 ▶ my $span = @before ? $self->_span_calc_spec(\@before, ()) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@before ? : 38 0 38
3805 38 ▶ if ($span && $span->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($span and $span->{"error"}) 0 38 38
Condition33%1/3
$span and $span->{"error"}
!ll&&!rl&&r
3800
MC/DC0%0/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table33%1/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
3806 0 $refuse->($span->{error});
3807 0 return ();
3808 }
3809 38 my ($r, $c) = eval {
3810 $self->_calc_for_page($all, \@before, {
3811 spec_key => $params->{calc_spec_key},
3812 38 ▶ ($span ? (calc => $span->{calc}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 38 38
3813 })
3814 };
3815 38 ▶ unless ($r) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($r) 0 38 38
3816 0 $refuse->($@);
3817 0 return ();
3818 }
3819 38 ($all, @cols_so_far) = ($r, @$c);
3820 }
3821  
3822 # A filter on a column stages 6 and 7 write waits for them. See _reduce_records.
3823 0 ▶ my %written = $cross ? map { $_ => 1 } _cross_row_written($self) : ();
Branch: 1 branch
BranchTrueFalseTotal
$cross ? : 2 36 38
3824 38 ▶ my @filter_cols = @cols_so_far ? @cols_so_far : _get_columns($source, $all);
Branch: 1 branch
BranchTrueFalseTotal
@cols_so_far ? : 38 0 38
3825 38 ▶ if (defined(my $why = _unknown_filter_column($self, \@filter_cols, \%written))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $why = _unknown_filter_column($self, \@filter_cols, \%written))) 3 35 38
3826 3 $refuse->($why);
3827 3 return ();
3828 }
3829 35 my @late = grep { $written{ (split /:/, $_, 2)[0] } } @f_specs;
3830 35 $all = _apply_filter_spec($all, $_) for grep { !$written{ (split /:/, $_, 2)[0] } } @f_specs;
3831  
3832 35 ▶ if ($dedup) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dedup) 1 34 35
3833 1 my $cols = $source->columns;
3834 0 ▶ my @dcols = $cols ? @$cols : (keys %{ $all->[0] // {} });
Branch: 1 branch
BranchTrueFalseTotal
$cols ? : 1 0 1
Condition0%0/2
$all->[0] // {}
l!l
00
MC/DC0%0/1
$all->[0] // {}
$all->[0]
Truth table0%0/2
A
A= $all->[0]
Aresult
11
00
3835 1 $all = _dedup_records($all, \@dcols);
3836 }
3837  
3838 # Stages 6 and 7, before the slice: a running total has to see every filtered
3839 # row, or page 2 would start again from zero.
3840 35 ▶ if ($cross) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cross) 2 33 35
3841 2 my $cols = $source->columns;
3842 my @xcols = @cols_so_far ? @cols_so_far
3843 0 ▶ : $cols ? @$cols : (sort keys %{ $all->[0] // {} });
Branch: 2 branches
BranchTrueFalseTotal
@cols_so_far ? : 2 0 2
$cols ? : 0 0 0
Condition0%0/2
$all->[0] // {}
l!l
00
MC/DC0%0/1
$all->[0] // {}
$all->[0]
Truth table0%0/2
A
A= $all->[0]
Aresult
11
00
3844 2 my $done = eval {
3845 2 my ($r, $c) = $self->_apply_cross_row($all, \@xcols);
3846 0 ($all) = $self->_apply_held_calc_fields($r, $c);
3847 0 1;
3848 };
3849 2 ▶ unless ($done) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($done) 2 0 2
3850 2 $refuse->($@);
3851 2 return ();
3852 }
3853 0 $all = _apply_filter_spec($all, $_) for @late;
3854 }
3855  
3856 # The whole reduced set, sorted, before the page is cut. A column the view
3857 # does not have is left alone (the order is the file's), as the header sort
3858 # ignores one it cannot find.
3859 33 ▶ if (defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 8 25 33
3860 8 ▶ my %known = map { $_ => 1 } (@cols_so_far ? @cols_so_far : _get_columns($source, $all)), keys %written;
Branch: 1 branch
BranchTrueFalseTotal
@cols_so_far ? : 8 0 8
3861 8 ▶ $known{$sort_col} = 1 if $cross && @$all && exists $all->[0]{$sort_col};
Branch: 1 branch
BranchTrueFalseTotal
if $cross and @$all and exists $all->[0]{$sort_col} 0 8 8
Condition33%2/6
$cross and @$all and exists $all->[0]{$sort_col}
!ll&&!rl&&r
800
$cross and @$all
!ll&&!rl&&r
800
MC/DC0%0/3
$cross and @$all and exists $all->[0]{$sort_col}
$cross @$all exists $all->[0]{$sort_col}
Truth table25%1/4
A and B and C
A= $crossB= @$allC= exists $all->[0]{$sort_col}
ABCresult
0XX0
10X0
1100
1111
3862 8 ▶ if ($known{$sort_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($known{$sort_col}) 6 2 8
3863 6 $all = _sort_records($all, $sort_col, $sort_dir);
3864 6 $self->stash(sorted_by => { col => $sort_col, dir => $sort_dir });
3865 }
3866 }
3867  
3868 33 my $total = scalar @$all;
3869 33 ▶ my $has_next = ($total > $offset + $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$total > $offset + $per_page ? : 0 33 33
3870 33 my @page = @{ _rows_of_page($all, $offset, $per_page) };
3871 33 $self->stash(page_count => _page_count($total, $per_page));
3872  
3873 33 return (\@page, $has_next);
3874 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3875  
3876 # _combine_tables(\@sources, $source_col) -> (\@merged_records, \@merged_columns)
3877 #
3878 # Purpose: Perform a vertical stack (UNION ALL equivalent) of two or more
3879 # record sets. The merged column list is the union of all source
3880 # column lists: the first source's columns appear first (in their
3881 # original order), then each subsequent source contributes any new
3882 # column names it introduces, in order. Where a source does not
3883 # have a particular column, its rows receive an empty string for
3884 # that column.
3885 # Entry: $sources is an arrayref of [$records_aref, $columns_aref, $label]
3886 # triples. $source_col, when given, names an added last column that
3887 # holds each row's $label (the file or table it came from); a name a
3888 # source already uses gets underscores until it is free.
3889 # At least one element is required; a single-element call returns
3890 # that element's data unchanged (no allocation beyond the column copy).
3891 # Exit: Returns (\@merged_records, \@merged_columns).
3892 # Side Effects: None; allocates new record hashrefs (original rows are not mutated).
3893 19 ▶sub _combine_tables {
Subroutine _combine_tables: called CC=13 SCAR=27.8
3894 19 my ($sources, $source_col) = @_;
3895  
3896 # Build the unified column order: first source's columns first, then any
3897 # new columns introduced by each subsequent source in their file order.
3898 19 my (@all_cols, %seen);
3899 19 for my $src (@$sources) {
3900 37 for my $col (@{ $src->[1] }) {
3901 133 ▶ push @all_cols, $col unless $seen{$col}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$col}++ 76 57 133
3902 }
3903 }
3904  
3905 # $source_col names a column that says which source each row came from; it
3906 # goes last, and takes a name no source column has.
3907 19 ▶ if (defined $source_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $source_col) 0 19 19
3908 0 ▶ $source_col .= '_' while $seen{$source_col};
Branch: 1 branch
BranchTrueFalseTotal
$seen{$source_col} and do { $source_col .= '_' } 0 0 0
3909 0 push @all_cols, $source_col;
3910 }
3911  
3912 19 my @merged;
3913 19 for my $src (@$sources) {
3914 37 my ($recs, $cols, $label) = @$src;
3915 37 my %has_col = map { $_ => 1 } @$cols;
3916 37 for my $row (@$recs) {
3917 164 my %new_row;
3918 $new_row{$_} = $has_col{$_} ? ($row->{$_} // '') : ''
3919 164 ▶ for @all_cols;
Branch: 1 branch
BranchTrueFalseTotal
$has_col{$_} ? : 884 150 1034
Condition50%1/2
$row->{$_} // ""
l!l
8840
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table50%1/2
A
A= $row->{$_}
Aresult
11
00
3920 164 ▶ $new_row{$source_col} = $label // '' if defined $source_col;
Branch: 1 branch
BranchTrueFalseTotal
if defined $source_col 0 164 164
Condition0%0/2
$label // ""
l!l
00
MC/DC0%0/1
$label // ""
$label
Truth table0%0/2
A
A= $label
Aresult
11
00
3921 164 push @merged, \%new_row;
3922 }
3923 }
3924  
3925 19 return (\@merged, \@all_cols);
3926 }
3927  
3928 # _csv_row(@fields) -> $csv_line_with_crlf
3929 #
3930 # Purpose: Format one row as an RFC 4180 CSV line. Fields containing commas,
3931 # double-quotes, or newlines are enclosed in double-quotes; embedded
3932 # double-quotes are doubled. The line ends with CRLF.
3933 # Entry: @fields may contain undef (treated as empty string).
3934 # Exit: Returns a string ending with "\r\n".
3935 674 ▶sub _csv_row {
Subroutine _csv_row: called CC=3 SCAR=11.0
3936 return join(',', map {
3937 674 ▶ my $f = $_ // '';
Condition100%2/2
$_ // ""
l!l
377510
MC/DC100%1/1
$_ // ""
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
3938 3785 ▶ $f =~ /[,"\r\n]/ ? do { (my $q = $f) =~ s/"/""/g; qq{"$q"} } : $f;
Branch: 1 branch
BranchTrueFalseTotal
$f =~ /[,"\r\n]/u ? : 15 3770 3785
3939 } @_) . "\r\n";
3940 }
3941  
3942 # _build_export_url($self, $left_spec, \@join_specs, \@filter_specs) -> $url_string
3943 #
3944 # Purpose: Assemble a /export?l=...&j=...&f=... URL string for the current
3945 # logical view. The caller must apply | html in TT to escape & as &amp;.
3946 # Entry: All args non-undef; spec arrays may be empty.
3947 # Exit: Returns a relative URL string beginning with '/export'.
3948 357 ▶sub _build_export_url :Protected ($self, $left_spec, $join_specs, $filter_specs, $combine_specs = undef, $dedup = 0, $extra = undef) {
Subroutine _build_export_url: called CC=13 SCAR=25.6
3949 357 my $u = '/export?l=' . url_escape($left_spec);
3950 357 $u .= '&j=' . url_escape($_) for @$join_specs;
3951 357 ▶ $u .= '&c=' . url_escape($_) for @{ $combine_specs // [] };
Condition100%2/2
$combine_specs // []
l!l
53304
MC/DC100%1/1
$combine_specs // []
$combine_specs
Truth table100%2/2
A
A= $combine_specs
Aresult
11
00
3952 357 $u .= '&f=' . url_escape($_) for @$filter_specs;
3953 357 ▶ $u .= '&d=1' if $dedup;
Branch: 1 branch
BranchTrueFalseTotal
if $dedup 2 355 357
3954 # Parameters that shape the columns rather than the rows travel with the
3955 # export, so the file holds the column the page shows -- a time bucket, for
3956 # one -- and not the raw values behind it.
3957 357 ▶ for my $key (sort keys %{ $extra // {} }) {
Condition100%2/2
$extra // {}
l!l
145212
MC/DC100%1/1
$extra // {}
$extra
Truth table100%2/2
A
A= $extra
Aresult
11
00
3958 435 my $val = $extra->{$key};
3959 435 ▶ next unless defined $val && length $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val and length $val 434 1 435
Condition100%3/3
defined $val and length $val
!ll&&!rl&&r
43131
MC/DC100%2/2
defined $val and length $val
defined $val length $val
Truth table100%3/3
A and B
A= defined $valB= length $val
ABresult
0X0
100
111
3960 1 $u .= "&$key=" . url_escape($val);
3961 }
3962 357 return $u;
3963 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3964  
3965 # _list_dir($self, $dir, $want_files) -> { dirs => [...], files => [...] }
3966 #
3967 # Purpose: Shared directory-listing kernel used by browse (which needs files)
3968 # and dirs_api (which needs only subdirectories). Hidden entries
3969 # (names starting with ".") are excluded. Entries are sorted
3970 # case-insensitively.
3971 # Entry: $dir is a Mojo::File pointing to an existing readable directory.
3972 # $want_files: if true, populate 'files' with entries matching $EXT_RE.
3973 # Exit: Returns a hashref with 'dirs' and 'files' arrayrefs (files is always
3974 # present but empty when $want_files is false).
3975 # Side Effects: Filesystem directory read.
3976 69 ▶sub _list_dir :Protected ($self, $dir, $want_files) {
Subroutine _list_dir: called CC=9 SCAR=22.0
3977 69 my (@dirs, @files);
3978 69 ▶ if (opendir my $dh, $dir->to_string) {
Branch: 1 branch
BranchTrueFalseTotal
if (opendir my $dh, $dir->to_string) 67 2 69
3979 67 ▶ while (my $entry = readdir $dh) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $entry = readdir $dh)) 507 67 574
3980 507 ▶ next if $entry eq '.' || $entry eq '..' || $entry =~ /\A\./;
Branch: 1 branch
BranchTrueFalseTotal
if $entry eq "." or $entry eq ".." or $entry =~ /\A\./u 326 181 507
Condition100%6/6
$entry eq "." or $entry eq ".." or $entry =~ /\A\./u
l!l&&r!l&&!r
134192181
$entry eq "." or $entry eq ".."
l!l&&r!l&&!r
6767373
MC/DC100%3/3
$entry eq "." or $entry eq ".." or $entry =~ /\A\./u
$entry eq "." $entry eq ".." $entry =~ /\A\./u
Truth table100%4/4
A or B or C
A= $entry eq "."B= $entry eq ".."C= $entry =~ /\A\./u
ABCresult
1XX1
01X1
0011
0000
3981 181 my $f = $dir->child($entry);
3982 181 ▶ if (-d $f) {
Branch: 2 branches
BranchTrueFalseTotal
if (-d $f) { } 103 78 181
elsif ($want_files and $entry =~ /$EXT_RE/u) { } 25 82 107
3983 103 push @dirs, { name => $entry, path => $f->to_string };
3984 }
3985 ▶ elsif ($want_files && $entry =~ $EXT_RE) {
Condition100%3/3
$want_files and $entry =~ /$EXT_RE/u
!ll&&!rl&&r
292425
MC/DC100%2/2
$want_files and $entry =~ /$EXT_RE/u
$want_files $entry =~ /$EXT_RE/u
Truth table100%3/3
A and B
A= $want_filesB= $entry =~ /$EXT_RE/u
ABresult
0X0
100
111
3986 25 push @files, { name => $entry, path => $f->to_string };
3987 }
3988 }
3989 67 closedir $dh;
3990 }
3991 return {
3992 84 dirs => [ sort { lc($a->{name}) cmp lc($b->{name}) } @dirs ],
3993 69 files => [ sort { lc($a->{name}) cmp lc($b->{name}) } @files ],
3994 };
3995 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3996  
3997 # _write_sqlite_db($self, $records, $columns, $table) -> $raw_bytes
3998 #
3999 # Purpose: $records as a SQLite database of one table, every column TEXT, as
4000 # the file's bytes. Used by both _render_sqlite (HTTP download) and
4001 # export_write (filesystem write); Database::Join::Catalog writes it.
4002 # Entry: $records is an arrayref of hashrefs; $columns is an arrayref of names;
4003 # $table names the table, "data" unless given. An extract passes
4004 # "extract", which Database::Abstraction before 0.54 needed (it could
4005 # not read a table called "data"); extracts already built use it.
4006 # Exit: Returns scalar binary string. Croaks when it cannot be written.
4007 # Side Effects: Catalog makes and removes one temporary file under tmpdir.
4008 18 ▶sub _write_sqlite_db :Protected ($self, $records, $columns, $table = 'data') {
Subroutine _write_sqlite_db: called CC=3 SCAR=11.0
4009 # D~ fix: an empty column list would be "CREATE TABLE data ()", which is
4010 # invalid SQLite syntax; this message is the one readers have seen.
4011 18 ▶ croak 'Cannot export SQLite: result set has no columns'
Branch: 1 branch
BranchTrueFalseTotal
unless @$columns 3 15 18
4012 unless @$columns;
4013  
4014 15 require Database::Join::Catalog;
4015 15 return Database::Join::Catalog->sqlite_bytes(table => $table, columns => $columns, rows => $records);
4016 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4017  
4018 # _run_pipeline_source($self) -> ($src, $records, \@columns, $left_label) or ()
4019 #
4020 # Purpose: Inner pipeline: opens the left spec, builds the join chain, fetches
4021 # all rows, and runs any c= combine step. Does NOT apply f= filters,
4022 # dedup, or pagination -- that is the caller's responsibility.
4023 # Chart routes call this directly so they can access $src for the
4024 # aggregate() push path. Row-viewing routes and export routes
4025 # call the thin _run_export_pipeline wrapper instead.
4026 # Exit: On success: ($src_or_undef, $records_aref, $columns_aref, $label).
4027 # $src is undef when a c= combine makes the result non-aggregatable.
4028 # On failure: empty list (left table not found / fetch error).
4029 1101 ▶sub _run_pipeline_source :Protected ($self) {
Subroutine _run_pipeline_source: called CC=29 SCAR=34.5
4030 1101 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
10929
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
4031 1101 my ($left_src, $left_label) = $self->_open_spec($left_spec);
4032 1101 ▶ return () unless $left_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $left_src 53 1048 1101
4033  
4034 # Build the join chain lazily.
4035 1048 ▶ my $max_rows = $self->app->config('join_max_rows') // $DEFAULT_JOIN_MAX_ROWS;
Condition66%2/3
$self->app->config("join_max_rows") // $DEFAULT_JOIN_MAX_ROWS
l!l&&r!l&&!r
010435
MC/DC50%1/2
$self->app->config("join_max_rows") // $DEFAULT_JOIN_MAX_ROWS
$self->app->config("join_max_rows") $DEFAULT_JOIN_MAX_ROWS
Truth table66%2/3
A // B
A= $self->app->config("join_max_rows")B= $DEFAULT_JOIN_MAX_ROWS
ABresult
1X1
011
000
4036 1048 ▶ my $join_type = $self->param('jtype') // 'left';
Condition100%2/2
$self->param("jtype") // "left"
l!l
151033
MC/DC100%1/1
$self->param("jtype") // "left"
$self->param("jtype")
Truth table100%2/2
A
A= $self->param("jtype")
Aresult
11
00
4037 1048 ▶ $join_type = 'left' unless $join_type =~ /\A(?:left|inner|outer)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $join_type =~ /\A(?:left|inner|outer)\z/u 14 1034 1048
4038 1048 my $src = $left_src;
4039 1048 my (@schema_warnings, @joined, @combined);
4040 1048 for my $jspec (@{ $self->every_param('j') }) {
4041 23 my ($right_spec, $left_key, $right_key) = split /\|/, $jspec, 3;
4042 23 ▶ next unless defined $right_spec && defined $left_key && defined $right_key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $right_spec and defined $left_key and defined $right_key 14 9 23
Condition66%4/6
defined $right_spec and defined $left_key and defined $right_key
!ll&&!rl&&r
1409
defined $right_spec and defined $left_key
!ll&&!rl&&r
0149
MC/DC33%1/3
defined $right_spec and defined $left_key and defined $right_key
defined $right_spec defined $left_key defined $right_key
Truth table50%2/4
A and B and C
A= defined $right_specB= defined $left_keyC= defined $right_key
ABCresult
0XX0
10X0
1100
1111
4043  
4044 9 my $cur_cols = $src->columns;
4045 9 ▶ next unless $cur_cols;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_cols 0 9 9
4046 9 ▶ next unless +{ map { $_ => 1 } @$cur_cols }->{$left_key};
Branch: 1 branch
BranchTrueFalseTotal
unless {map({$_, 1;} @$cur_cols)}->{$left_key} 0 9 9
4047  
4048 9 my ($right_src, $right_label) = $self->_open_spec($right_spec);
4049 9 ▶ next unless $right_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_src 1 8 9
4050  
4051 8 my $right_cols = $right_src->columns;
4052 8 ▶ next unless $right_cols;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_cols 0 8 8
4053 8 ▶ next unless +{ map { $_ => 1 } @$right_cols }->{$right_key};
Branch: 1 branch
BranchTrueFalseTotal
unless {map({$_, 1;} @$right_cols)}->{$right_key} 0 8 8
4054  
4055 # Types are compared while the two sides are still separate sources;
4056 # after the join is built the mismatched columns are already published
4057 # under different names. See _schema_type_warnings.
4058 8 push @schema_warnings, $self->_schema_type_warnings(
4059 $src, $right_src, $left_label, $right_label, $left_key, $right_key);
4060  
4061 8 require Database::Join;
4062 0 ▶ local $SIG{__WARN__} = sub { push @schema_warnings, $_[0] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
4063 8 ▶ $src = Database::Join->new(
Branch: 2 branches
BranchTrueFalseTotal
$left_key ne $right_key ? : 1 7 8
$right_label ? : 8 0 8
4064 databases => [$src, $right_src],
4065 join_column => $left_key,
4066 backend => 'auto',
4067 max_array_rows => $max_rows,
4068 join_type => $join_type,
4069 ($left_key ne $right_key ? (join_map => {1 => $right_key}) : ()),
4070 ($right_label ? (collision_prefix => {1 => $right_label}) : ()),
4071 );
4072 8 push @joined, { label => $right_label, left_key => $left_key, right_key => $right_key };
4073 }
4074  
4075 1048 ▶ $self->stash(schema_warnings => \@schema_warnings) if @schema_warnings;
Branch: 1 branch
BranchTrueFalseTotal
if @schema_warnings 1 1047 1048
4076  
4077 1048 my $records = eval { $src->selectall_arrayref };
4078 1048 ▶ return () if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 10 1038 1048
4079 1038 ▶ $records //= [];
Condition50%1/2
$records //= []
l!l
10380
MC/DC0%0/1
$records //= []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
4080 1038 my @columns = _get_columns($src, $records);
4081  
4082 # Combine (vertical stack): sets $src = undef since the result is a union
4083 # with no single aggregatable object.
4084 1038 ▶ my @cspecs = @{ $self->every_param('c') // [] };
Condition50%1/2
$self->every_param("c") // []
l!l
10380
MC/DC0%0/1
$self->every_param("c") // []
$self->every_param("c")
Truth table50%1/2
A
A= $self->every_param("c")
Aresult
11
00
4085 1038 ▶ if (@cspecs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cspecs) 44 994 1038
4086 44 my @sources = ([$records, \@columns, $left_label]);
4087 44 for my $cspec (@cspecs) {
4088 44 my ($csrc, $clabel) = $self->_open_spec($cspec);
4089 44 ▶ next unless $csrc;
Branch: 1 branch
BranchTrueFalseTotal
unless $csrc 30 14 44
4090 14 ▶ my $crecs = eval { $csrc->fetch_all } // [];
Condition50%1/2
eval { do { $csrc->fetch_all } } // []
l!l
140
MC/DC0%0/1
eval { do { $csrc->fetch_all } } // []
eval { do { $csrc->fetch_all } }
Truth table50%1/2
A
A= eval { do { $csrc->fetch_all } }
Aresult
11
00
4091 14 ▶ next if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 14 14
4092 14 my @ccols = _get_columns($csrc, $crecs);
4093 14 push @sources, [$crecs, \@ccols, $clabel];
4094 14 push @combined, { label => $clabel };
4095 }
4096 44 ▶ if (@sources > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sources > 1) 14 30 44
4097 14 my $srccol = $self->param('srccol');
4098 14 ▶ $srccol = undef unless defined $srccol && $srccol =~ $SOURCE_COL_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $srccol and $srccol =~ /$SOURCE_COL_RE/u 14 0 14
Condition33%1/3
defined $srccol and $srccol =~ /$SOURCE_COL_RE/u
!ll&&!rl&&r
1400
MC/DC0%0/2
defined $srccol and $srccol =~ /$SOURCE_COL_RE/u
defined $srccol $srccol =~ /$SOURCE_COL_RE/u
Truth table33%1/3
A and B
A= defined $srccolB= $srccol =~ /$SOURCE_COL_RE/u
ABresult
0X0
100
111
4099 14 ($records, my $new_cols) = _combine_tables(\@sources, $srccol);
4100 14 @columns = @$new_cols;
4101 14 $src = undef; # union: no single aggregatable source
4102 }
4103 }
4104  
4105 # What was actually joined and stacked, for the page that shows the rows.
4106 1038 $self->stash(pipeline_joined => \@joined, pipeline_combined => \@combined);
4107  
4108 1038 return ($src, $records, \@columns, $left_label);
4109 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4110  
4111 # _calc_spec_key($self) -> $spec
4112 #
4113 # Purpose: The key the stored calc fields, groups and date patterns are filed
4114 # under for this request: the l= spec, or the table a /view route is
4115 # addressed by, which names its spec explicitly because it has no l=.
4116 47 ▶sub _calc_spec_key :Protected ($self) {
Subroutine _calc_spec_key: called CC=5 SCAR=16.1
4117 47 ▶ my $l = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
1532
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
4118 47 ▶ return canonical_spec($l) if length $l;
Branch: 1 branch
BranchTrueFalseTotal
if length $l 15 32 47
4119 32 my $table = $self->stash('table');
4120 32 ▶ return (defined $table && $table =~ /$TABLE_NAME_RE/) ? "table:$table" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $table && $table =~ /$TABLE_NAME_RE/u ? : 17 15 32
Condition100%3/3
defined $table and $table =~ /$TABLE_NAME_RE/u
!ll&&!rl&&r
14117
MC/DC100%2/2
defined $table and $table =~ /$TABLE_NAME_RE/u
defined $table $table =~ /$TABLE_NAME_RE/u
Truth table100%3/3
A and B
A= defined $tableB= $table =~ /$TABLE_NAME_RE/u
ABresult
0X0
100
111
4121 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4122  
4123 # _span_calc_spec($self, \@columns, @dimension_params) -> \%span | undef
4124 #
4125 # Purpose: Turn span=/tcol=/as= into the c= calculated field a reader could have
4126 # typed, so bucketing a dimension is one code path with one set of
4127 # semantics (Calc.pm's span()) rather than a second pipeline of its
4128 # own, and so a bucket works on every route at once.
4129 # Entry: \@columns -- the source's columns, so the column to bucket and the
4130 # name of the bucket are both checked before anything is
4131 # evaluated.
4132 # @dimension_params -- the params that name this route's dimension
4133 # (cat, x, rows, ...), in the order they should be tried.
4134 # Exit: undef when the request says nothing about bucketing. Otherwise
4135 # { calc => [ '<col>_span:span(<col>,<interval>)' ],
4136 # src => <column to bucket>, col => '<bucket column>' },
4137 # or { error => <message> } for a request that cannot be honoured,
4138 # which the caller renders as a 400 rather than drawing a chart of
4139 # something the reader did not ask for.
4140 # Notes: An ambiguous dimension is refused, not guessed: with rows=at,region
4141 # only tcol= knows which column the reader meant, and bucketing the
4142 # wrong one silently is worse than an error that says so. A name that
4143 # is already a column, or already a calculated field, is refused too,
4144 # because two definitions of one name is the bug that rule prevents.
4145 982 ▶sub _span_calc_spec :Protected ($self, $columns, @dimension_params) {
Subroutine _span_calc_spec: called CC=25 SCAR=32.3
4146 982 ▶ my $interval = $self->param('span') // '';
Condition100%2/2
$self->param("span") // ""
l!l
35947
MC/DC100%1/1
$self->param("span") // ""
$self->param("span")
Truth table100%2/2
A
A= $self->param("span")
Aresult
11
00
4147 982 ▶ my $tcol = $self->param('tcol') // '';
Condition100%2/2
$self->param("tcol") // ""
l!l
28954
MC/DC100%1/1
$self->param("tcol") // ""
$self->param("tcol")
Truth table100%2/2
A
A= $self->param("tcol")
Aresult
11
00
4148 982 ▶ my $as = $self->param('as') // '';
Condition100%2/2
$self->param("as") // ""
l!l
21961
MC/DC100%1/1
$self->param("as") // ""
$self->param("as")
Truth table100%2/2
A
A= $self->param("as")
Aresult
11
00
4149 982 ▶ return undef unless length($interval) || length($tcol);
Branch: 1 branch
BranchTrueFalseTotal
unless length $interval or length $tcol 937 45 982
Condition100%3/3
length $interval or length $tcol
l!l&&r!l&&!r
3312937
MC/DC100%2/2
length $interval or length $tcol
length $interval length $tcol
Truth table100%3/3
A or B
A= length $intervalB= length $tcol
ABresult
1X1
011
000
4150  
4151 45 ▶ return { error => $self->_i18n('error_span_tcol_orphan', $tcol) }
Branch: 1 branch
BranchTrueFalseTotal
if length $tcol and not length $interval 12 33 45
Condition100%3/3
length $tcol and not length $interval
!ll&&!rl&&r
181512
MC/DC100%2/2
length $tcol and not length $interval
length $tcol not length $interval
Truth table100%3/3
A and not(B)
A= length $tcolB= not length $interval
ABresult
0X0
100
111
4152 if length($tcol) && !length($interval);
4153  
4154 33 require Database::BI::Calc;
4155 33 ▶ return { error => $self->_i18n('error_span_interval', $interval) }
Branch: 1 branch
BranchTrueFalseTotal
unless Database::BI::Calc::span_interval($interval) 16 17 33
4156 unless Database::BI::Calc::span_interval($interval);
4157  
4158 17 my %col_set = map { $_ => 1 } @$columns;
4159  
4160 17 my $col;
4161 17 ▶ if (length $tcol) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $tcol) { } 13 4 17
4162 return { error => $self->_i18n('error_span_tcol_unknown', $tcol) }
4163 13 ▶ unless $col_set{$tcol};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$tcol} 2 11 13
4164 11 $col = $tcol;
4165 } else {
4166 3 my @named = grep { length }
4167 4 ▶ map { split /,/, ($self->param($_) // ''), -1 } @dimension_params;
Condition100%2/2
$self->param($_) // ""
l!l
25
MC/DC100%1/1
$self->param($_) // ""
$self->param($_)
Truth table100%2/2
A
A= $self->param($_)
Aresult
11
00
4168 4 ▶ return { error => $self->_i18n('error_span_no_column') } unless @named == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @named == 1 3 1 4
4169 1 $col = $named[0];
4170 }
4171  
4172 # A bucket column is written in the calc grammar, so spaces in the column's
4173 # name arrive as underscores, exactly as a reader typing the expression
4174 # would have to write them.
4175 12 (my $expr_col = $col) =~ s/ /_/g;
4176 12 ▶ my $name = length($as) ? $as : "${expr_col}_span";
Branch: 1 branch
BranchTrueFalseTotal
length $as ? : 10 2 12
4177 12 ▶ return { error => $self->_i18n('error_span_name', $name) }
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/u 6 6 12
4178 unless $name =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/;
4179  
4180 6 ▶ my $taken = $col_set{$name} || do {
Condition100%3/3
$col_set{$name} || do { my $found = 0; my $sk = $self->_calc_spec_key; my $stored = length $sk ? $self->_read_models->{'fields'}{$sk} // {} : {}; $found = 1 if $stored->{$name}; foreach my $spec (@{$self->every_param('c') // [];}) { next if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/iu; my($n) = $spec =~ /\A([A-Za-z_][A-Za-z0-9_]*):/u; $found = 1 if defined $n and $n eq $name; } ; $found }
l!l&&r!l&&!r
123
MC/DC100%2/2
$col_set{$name} || do { my $found = 0; my $sk = $self->_calc_spec_key; my $stored = length $sk ? $self->_read_models->{'fields'}{$sk} // {} : {}; $found = 1 if $stored->{$name}; foreach my $spec (@{$self->every_param('c') // [];}) { next if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/iu; my($n) = $spec =~ /\A([A-Za-z_][A-Za-z0-9_]*):/u; $found = 1 if defined $n and $n eq $name; } ; $found }
$col_set{$name} do { my $found = 0; my $sk = $self->_calc_spec_key; my $stored = length $sk ? $self->_read_models->{'fields'}{$sk} // {} : {}; $found = 1 if $stored->{$name}; foreach my $spec (@{$self->every_param('c') // [];}) { next if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/iu; my($n) = $spec =~ /\A([A-Za-z_][A-Za-z0-9_]*):/u; $found = 1 if defined $n and $n eq $name; } ; $found }
Truth table100%3/3
A || B
A= $col_set{$name}B= do { my $found = 0; my $sk = $self->_calc_spec_key; my $stored = length $sk ? $self->_read_models->{'fields'}{$sk} // {} : {}; $found = 1 if $stored->{$name}; foreach my $spec (@{$self->every_param('c') // [];}) { next if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/iu; my($n) = $spec =~ /\A([A-Za-z_][A-Za-z0-9_]*):/u; $found = 1 if defined $n and $n eq $name; } ; $found }
ABresult
1X1
011
000
4181 5 my $found = 0;
4182 5 my $sk = $self->_calc_spec_key;
4183 5 ▶ my $stored = length($sk) ? (($self->_read_models)->{fields}{$sk} // {}) : {};
Branch: 1 branch
BranchTrueFalseTotal
length $sk ? : 1 4 5
Condition50%1/2
$self->_read_models->{"fields"}{$sk} // {}
l!l
01
MC/DC0%0/1
$self->_read_models->{"fields"}{$sk} // {}
$self->_read_models->{"fields"}{$sk}
Truth table50%1/2
A
A= $self->_read_models->{"fields"}{$sk}
Aresult
11
00
4184 5 ▶ $found = 1 if $stored->{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $stored->{$name} 0 5 5
4185 5 ▶ for my $spec (@{ $self->every_param('c') // [] }) {
Condition50%1/2
$self->every_param("c") // []
l!l
50
MC/DC0%0/1
$self->every_param("c") // []
$self->every_param("c")
Truth table50%1/2
A
A= $self->every_param("c")
Aresult
11
00
4186 2 ▶ next if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/i;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/iu 0 2 2
4187 2 my ($n) = $spec =~ /\A([A-Za-z_][A-Za-z0-9_]*):/;
4188 2 ▶ $found = 1 if defined $n && $n eq $name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $n and $n eq $name 2 0 2
Condition33%1/3
defined $n and $n eq $name
!ll&&!rl&&r
002
MC/DC0%0/2
defined $n and $n eq $name
defined $n $n eq $name
Truth table33%1/3
A and B
A= defined $nB= $n eq $name
ABresult
0X0
100
111
4189 }
4190 5 $found;
4191 };
4192 6 ▶ return { error => $self->_i18n('error_span_conflict', $name) } if $taken;
Branch: 1 branch
BranchTrueFalseTotal
if $taken 3 3 6
4193  
4194 return {
4195 3 src => $col,
4196 col => $name,
4197 calc => [ "$name:span($expr_col,'$interval')" ],
4198 };
4199 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4200  
4201 # _apply_date_normalization($self, $records, \@columns, $spec_key) -> void
4202 #
4203 # Reads date_patterns from .bi/models.json for $spec_key and normalises each
4204 # configured column's values to ISO-8601 in-place. A value that does not match
4205 # the stored pattern is left unchanged so YEAR/MONTH/etc. return undef (and the
4206 # row falls into the '(unparseable)' bucket in _grouped_totals).
4207 # Called at the top of _apply_calc_fields so registered patterns are applied
4208 # before any calc expression is evaluated.
4209 1417 ▶sub _apply_date_normalization :Protected ($self, $records, $columns, $spec_key) {
Subroutine _apply_date_normalization: called CC=11 SCAR=24.0
4210 1417 ▶ return unless defined $spec_key && length $spec_key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec_key and length $spec_key 18 1399 1417
Condition100%3/3
defined $spec_key and length $spec_key
!ll&&!rl&&r
1171399
MC/DC100%2/2
defined $spec_key and length $spec_key
defined $spec_key length $spec_key
Truth table100%3/3
A and B
A= defined $spec_keyB= length $spec_key
ABresult
0X0
100
111
4211 1399 my $models = $self->_read_models;
4212 1399 my $patterns = $models->{date_patterns}{$spec_key};
4213 1399 ▶ return unless $patterns && %{$patterns};
Branch: 1 branch
BranchTrueFalseTotal
unless $patterns and %{$patterns;} 1395 4 1399
Condition66%2/3
$patterns and %{$patterns;}
!ll&&!rl&&r
139504
MC/DC50%1/2
$patterns and %{$patterns;}
$patterns %{$patterns;}
Truth table66%2/3
A and B
A= $patternsB= %{$patterns;}
ABresult
0X0
100
111
4214 4 my %col_set = map { $_ => 1 } @{$columns};
4215 4 require Database::BI::Calc;
4216 4 for my $col (keys %{$patterns}) {
4217 4 ▶ next unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 1 3 4
4218 3 my $pat = $patterns->{$col};
4219 3 for my $row (@{$records}) {
4220 9 my $v = $row->{$col};
4221 9 ▶ next unless defined $v && length $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and length $v 2 7 9
Condition100%3/3
defined $v and length $v
!ll&&!rl&&r
117
MC/DC100%2/2
defined $v and length $v
defined $v length $v
Truth table100%3/3
A and B
A= defined $vB= length $v
ABresult
0X0
100
111
4222 # Only overwrite when normalisation succeeds; leave unchanged on
4223 # mismatch so the row lands in the '(unparseable)' group.
4224 7 my $iso = Database::BI::Calc::date_normalise($v, $pat);
4225 7 ▶ $row->{$col} = $iso if defined $iso;
Branch: 1 branch
BranchTrueFalseTotal
if defined $iso 4 3 7
4226 }
4227 }
4228 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4229  
4230 # _lookups_of_request($self, $spec_key) -> @lookups
4231 #
4232 # Purpose: The lookups this request applies, in order: those stored for
4233 # $spec_key, by name, then each lk=<name> stored for another dataset,
4234 # less every nolk=<name>.
4235 # Entry: $spec_key files the stored lookups (the l= spec, or a canvas's).
4236 # Exit: A list of { name => $name, %definition }. Croaks error_lookup_unknown
4237 # for an lk= that names no stored lookup, and error_lookup_name for one
4238 # that is not an identifier.
4239 1379 ▶sub _lookups_of_request :Protected ($self, $spec_key) {
Subroutine _lookups_of_request: called CC=14 SCAR=26.4
4240 1379 my $all = $self->_read_models->{lookups};
4241 1379 ▶ my %skip = map { $_ => 1 } @{ $self->every_param('nolk') // [] };
Condition50%1/2
$self->every_param("nolk") // []
l!l
13790
MC/DC0%0/1
$self->every_param("nolk") // []
$self->every_param("nolk")
Truth table50%1/2
A
A= $self->every_param("nolk")
Aresult
11
00
4242 1379 ▶ my $own = (length($spec_key // '') && ref $all->{$spec_key} eq 'HASH') ? $all->{$spec_key} : {};
Branch: 1 branch
BranchTrueFalseTotal
length($spec_key // '') && ref $all->{$spec_key} eq 'HASH' ? : 11 1368 1379
Condition100%5/5
length($spec_key // "") and ref $all->{$spec_key} eq "HASH"
!ll&&!rl&&r
8136011
$spec_key // ""
l!l
13781
MC/DC100%2/2
length($spec_key // "") and ref $all->{$spec_key} eq "HASH"
$spec_key ref $all->{$spec_key} eq "HASH"
Truth table100%3/3
A and B
A= $spec_keyB= ref $all->{$spec_key} eq "HASH"
ABresult
0X0
100
111
4243  
4244 1379 my (@lookups, %seen);
4245 1379 for my $name (sort keys %$own) {
4246 15 ▶ next if $skip{$name} || ref $own->{$name} ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if $skip{$name} or ref $own->{$name} ne "HASH" 5 10 15
Condition100%3/3
$skip{$name} or ref $own->{$name} ne "HASH"
l!l&&r!l&&!r
1410
MC/DC100%2/2
$skip{$name} or ref $own->{$name} ne "HASH"
$skip{$name} ref $own->{$name} ne "HASH"
Truth table100%3/3
A or B
A= $skip{$name}B= ref $own->{$name} ne "HASH"
ABresult
1X1
011
000
4247 10 push @lookups, { %{ $own->{$name} }, name => $name };
4248 10 $seen{$name} = 1;
4249 }
4250 1379 ▶ for my $name (@{ $self->every_param('lk') // [] }) {
Condition50%1/2
$self->every_param("lk") // []
l!l
13790
MC/DC0%0/1
$self->every_param("lk") // []
$self->every_param("lk")
Truth table50%1/2
A
A= $self->every_param("lk")
Aresult
11
00
4251 22 ▶ next if $seen{$name}++ || $skip{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$name}++ or $skip{$name} 2 20 22
Condition66%2/3
$seen{$name}++ or $skip{$name}
l!l&&r!l&&!r
0220
MC/DC50%1/2
$seen{$name}++ or $skip{$name}
$seen{$name}++ $skip{$name}
Truth table66%2/3
A or B
A= $seen{$name}++B= $skip{$name}
ABresult
1X1
011
000
4252 20 ▶ croak $self->_i18n('error_lookup_name', $name) unless $name =~ $LOOKUP_NAME_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$LOOKUP_NAME_RE/u 15 5 20
4253 # Another dataset's lookup, the first by the order of the specs, so the
4254 # choice does not depend on how the store happens to be read.
4255 6 my ($def) = grep { ref $_ eq 'HASH' }
4256 5 map { $all->{$_}{$name} } sort keys %$all;
4257 5 ▶ croak $self->_i18n('error_lookup_unknown', $name) unless $def;
Branch: 1 branch
BranchTrueFalseTotal
unless $def 3 2 5
4258 2 push @lookups, { %$def, name => $name };
4259 }
4260 1361 return @lookups;
4261 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4262  
4263 # _lookup_file($self, $name, $file) -> $path
4264 #
4265 # Purpose: Resolve a lookup's file= to the file it reads. A relative path is
4266 # under data_dir; an absolute one must be, after symlinks are resolved,
4267 # so a link inside data_dir cannot reach outside it.
4268 # Entry: $name names the lookup in the messages.
4269 # Exit: The resolved path as a string. Croaks error_lookup_remote (a URL or
4270 # another source spec, or a remote /../host/ path), error_lookup_outside,
4271 # error_lookup_not_found (missing, or not a supported extension) or
4272 # error_lookup_too_large (over $LOOKUP_MAX_BYTES).
4273 39 ▶sub _lookup_file :Protected ($self, $name, $file) {
Subroutine _lookup_file: called CC=10 SCAR=23.0
4274 39 ▶ $file //= '';
Condition100%2/2
$file //= ""
l!l
381
MC/DC100%1/1
$file //= ""
$file
Truth table100%2/2
A
A= $file
Aresult
11
00
4275 # Two letters at least before the colon, so C:\data is still a path.
4276 39 ▶ croak $self->_i18n('error_lookup_remote', $name, $file)
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ m[\A(?:[A-Za-z][A-Za-z0-9+.-]+:|/\.\./)]u 6 33 39
4277 if $file =~ m{\A(?:[A-Za-z][A-Za-z0-9+.-]+:|/\.\./)};
4278 33 ▶ croak $self->_i18n('error_lookup_not_found', $name, $file) unless length $file;
Branch: 1 branch
BranchTrueFalseTotal
unless length $file 2 31 33
4279  
4280 31 my $data_dir = _data_dir_for($self->app);
4281 31 my $given = Mojo::File->new($file);
4282 31 ▶ my $path = $given->is_abs ? $given : $data_dir->child($file);
Branch: 1 branch
BranchTrueFalseTotal
$given->is_abs ? : 3 28 31
4283 31 ▶ croak $self->_i18n('error_lookup_outside', $name, $file)
Branch: 1 branch
BranchTrueFalseTotal
unless _inside_dir(_canonical_path($path), _canonical_path($data_dir)) 5 26 31
4284 unless _inside_dir(_canonical_path($path), _canonical_path($data_dir));
4285 26 ▶ croak $self->_i18n('error_lookup_not_found', $name, $file)
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path and $path->basename =~ /$EXT_RE/u 4 22 26
Condition100%3/3
-f $path and $path->basename =~ /$EXT_RE/u
!ll&&!rl&&r
3122
MC/DC100%2/2
-f $path and $path->basename =~ /$EXT_RE/u
-f $path $path->basename =~ /$EXT_RE/u
Truth table100%3/3
A and B
A= -f $pathB= $path->basename =~ /$EXT_RE/u
ABresult
0X0
100
111
4286 unless -f $path && $path->basename =~ $EXT_RE;
4287 22 ▶ my $size = -s $path // 0;
Condition50%1/2
-s $path // 0
l!l
220
MC/DC0%0/1
-s $path // 0
-s $path
Truth table50%1/2
A
A= -s $path
Aresult
11
00
4288 22 ▶ croak $self->_i18n('error_lookup_too_large', $name, $file, $size, $LOOKUP_MAX_BYTES)
Branch: 1 branch
BranchTrueFalseTotal
if $size > $LOOKUP_MAX_BYTES 2 20 22
4289 if $size > $LOOKUP_MAX_BYTES;
4290 20 return _canonical_path($path);
4291 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4292  
4293 # _load_lookup($self, $lookup) -> \%entry
4294 #
4295 # Purpose: Read a lookup's file into a map from key to row, once per request.
4296 # Entry: $lookup is one entry of _lookups_of_request.
4297 # Exit: { map => { key => \%row }, fields => \@names, file => $basename }.
4298 # Keys are compared as strings after trimming, case-sensitively; a
4299 # duplicate key keeps its first row and is logged once. Croaks one of
4300 # _lookup_file's errors, error_lookup_unreadable, error_lookup_key_unknown
4301 # or error_lookup_field_unknown.
4302 # Side Effects: Caches the entry in the stash, keyed by name, path and mtime.
4303 24 ▶sub _load_lookup :Protected ($self, $lookup) {
Subroutine _load_lookup: called CC=18 SCAR=29.1
4304 24 my $name = $lookup->{name};
4305 24 my $path = $self->_lookup_file($name, $lookup->{file});
4306 18 my $file = Mojo::File->new($path)->basename;
4307 18 ▶ my $memo = $self->stash('_lookup_maps') // {};
Condition100%2/2
$self->stash("_lookup_maps") // {}
l!l
315
MC/DC100%1/1
$self->stash("_lookup_maps") // {}
$self->stash("_lookup_maps")
Truth table100%2/2
A
A= $self->stash("_lookup_maps")
Aresult
11
00
4308 my $tag = join "\0", $name, $path, (stat $path)[9] // 0,
4309 18 ▶ $lookup->{key} // '', @{ ref $lookup->{fields} eq 'ARRAY' ? $lookup->{fields} : [] };
Branch: 1 branch
BranchTrueFalseTotal
ref $lookup->{'fields'} eq 'ARRAY' ? : 12 6 18
Condition50%2/4
(stat $path)[9] // 0
l!l
180
$lookup->{"key"} // ""
l!l
180
MC/DC0%0/1
(stat $path)[9] // 0
(stat $path)[9]
MC/DC0%0/1
$lookup->{"key"} // ""
$lookup->{"key"}
Truth table50%1/2
A
A= (stat $path)[9]
Aresult
11
00
Truth table50%1/2
A
A= $lookup->{"key"}
Aresult
11
00
4310 18 ▶ return $memo->{$tag} if $memo->{$tag};
Branch: 1 branch
BranchTrueFalseTotal
if $memo->{$tag} 1 17 18
4311  
4312 17 (my $table = $file) =~ s/\.[^.]+\z//;
4313 17 my ($src, $rows);
4314 17 my $ok = eval {
4315 17 $src = $self->open_table($table, directory => Mojo::File->new($path)->dirname->to_string);
4316 16 $rows = $src->fetch_all;
4317 16 1;
4318 };
4319 17 ▶ croak $self->_i18n('error_lookup_unreadable', $name, $file, _tidy_error($@)) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 1 16 17
4320  
4321 16 my @columns = _get_columns($src, $rows);
4322 16 my %has = map { $_ => 1 } @columns;
4323 16 ▶ my $key = $lookup->{key} // '';
Condition50%1/2
$lookup->{"key"} // ""
l!l
160
MC/DC0%0/1
$lookup->{"key"} // ""
$lookup->{"key"}
Truth table50%1/2
A
A= $lookup->{"key"}
Aresult
11
00
4324 16 ▶ croak $self->_i18n('error_lookup_key_unknown', $name, $key, $file) unless $has{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $has{$key} 2 14 16
4325  
4326 12 my @fields = ref $lookup->{fields} eq 'ARRAY' && @{ $lookup->{fields} }
4327 12 ? @{ $lookup->{fields} }
4328 14 ▶ : grep { $_ ne $key } @columns;
Branch: 1 branch
BranchTrueFalseTotal
ref $lookup->{'fields'} eq 'ARRAY' && @{$lookup->{'fields'};} ? : 12 2 14
Condition66%2/3
ref $lookup->{"fields"} eq "ARRAY" and @{$lookup->{"fields"};}
!ll&&!rl&&r
2012
MC/DC50%1/2
ref $lookup->{"fields"} eq "ARRAY" and @{$lookup->{"fields"};}
ref $lookup->{"fields"} eq "ARRAY" @{$lookup->{"fields"};}
Truth table66%2/3
A and B
A= ref $lookup->{"fields"} eq "ARRAY"B= @{$lookup->{"fields"};}
ABresult
0X0
100
111
4329 14 for my $f (@fields) {
4330 16 ▶ croak $self->_i18n('error_lookup_field_unknown', $name, $f, $file) unless $has{$f};
Branch: 1 branch
BranchTrueFalseTotal
unless $has{$f} 2 14 16
4331 }
4332  
4333 12 my (%map, $duplicates);
4334 12 for my $row (@$rows) {
4335 29 my $k = _lookup_key($row->{$key});
4336 29 ▶ next unless defined $k && length $k;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $k and length $k 0 29 29
Condition33%1/3
defined $k and length $k
!ll&&!rl&&r
0029
MC/DC0%0/2
defined $k and length $k
defined $k length $k
Truth table33%1/3
A and B
A= defined $kB= length $k
ABresult
0X0
100
111
4337 29 ▶ if (exists $map{$k}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $map{$k}) 11 18 29
4338 11 $duplicates++;
4339 11 next;
4340 }
4341 18 $map{$k} = { map { $_ => $row->{$_} } @fields };
4342 }
4343 12 ▶ $self->app->log->warn($self->_i18n('warn_lookup_duplicate_key', $name, $duplicates, $file))
Branch: 1 branch
BranchTrueFalseTotal
if $duplicates 11 1 12
4344 if $duplicates;
4345  
4346 12 $memo->{$tag} = { map => \%map, fields => \@fields, file => $file };
4347 12 $self->stash('_lookup_maps' => $memo);
4348 12 return $memo->{$tag};
4349 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4350  
4351 # _lookup_key($value) -> $key | undef
4352 #
4353 # Purpose: The form in which a lookup compares a key: the string, trimmed. Case
4354 # and everything else are left as they are, so "ab" and "AB" are two keys.
4355 43 ▶sub _lookup_key {
Subroutine _lookup_key: called CC=3 SCAR=11.0
4356 43 my ($v) = @_;
4357 43 ▶ return undef unless defined $v && !ref $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and not ref $v 2 41 43
Condition100%3/3
defined $v and not ref $v
!ll&&!rl&&r
1141
MC/DC100%2/2
defined $v and not ref $v
defined $v not ref $v
Truth table100%3/3
A and not(B)
A= defined $vB= not ref $v
ABresult
0X0
100
111
4358 41 (my $k = $v) =~ s/\A\s+//;
4359 41 $k =~ s/\s+\z//;
4360 41 return $k;
4361 }
4362  
4363 # _apply_lookups($self, $records, \@cols, $spec_key) -> void
4364 #
4365 # Purpose: Stage 3 of the pipeline: each lookup the request applies adds its
4366 # fields to every row, read from the lookup file's row whose key equals
4367 # the row's own (col=, which defaults to the key's name). A row whose
4368 # key is missing gets the lookup's default, or undef.
4369 # Entry: \@cols is the column list so far; it gains the new columns.
4370 # Exit: Rows are replaced through _extend_row where they must be. The new
4371 # columns are virtual, so an aggregate that groups by one is folded in
4372 # Perl. Croaks with a message for a bad lookup or a missing column.
4373 # Notes: A field lands under its own name unless a column has it, and then
4374 # under <lookup>_<field>; a source column is never overwritten. The
4375 # columns this pass wrote do not count as taken when it runs again in
4376 # the same request, so the names a page gets do not depend on how
4377 # many times the stage has run over it.
4378 1374 ▶sub _apply_lookups :Protected ($self, $records, $cols, $spec_key) {
Subroutine _apply_lookups: called CC=17 SCAR=28.4
4379 1374 my @lookups = $self->_lookups_of_request($spec_key);
4380 1358 ▶ return unless @lookups;
Branch: 1 branch
BranchTrueFalseTotal
unless @lookups 1351 7 1358
4381  
4382 7 ▶ my $written = $self->stash('_lookup_written') // {};
Condition50%1/2
$self->stash("_lookup_written") // {}
l!l
07
MC/DC0%0/1
$self->stash("_lookup_written") // {}
$self->stash("_lookup_written")
Truth table50%1/2
A
A= $self->stash("_lookup_written")
Aresult
11
00
4383 7 my %taken = map { $_ => 1 } grep { !$written->{$_} } @$cols;
4384 7 for my $lookup (@lookups) {
4385 7 my $name = $lookup->{name};
4386 7 my $entry = $self->_load_lookup($lookup);
4387 7 ▶ my $col = length($lookup->{col} // '') ? $lookup->{col} : $lookup->{key};
Branch: 1 branch
BranchTrueFalseTotal
length($lookup->{'col'} // '') ? : 3 4 7
Condition100%2/2
$lookup->{"col"} // ""
l!l
34
MC/DC100%1/1
$lookup->{"col"} // ""
$lookup->{"col"}
Truth table100%2/2
A
A= $lookup->{"col"}
Aresult
11
00
4388 croak $self->_i18n('error_lookup_col_unknown', $name, $col, $name)
4389 7 ▶ unless $taken{$col} || $written->{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $taken{$col} or $written->{$col} 2 5 7
Condition66%2/3
$taken{$col} or $written->{$col}
l!l&&r!l&&!r
502
MC/DC50%1/2
$taken{$col} or $written->{$col}
$taken{$col} $written->{$col}
Truth table66%2/3
A or B
A= $taken{$col}B= $written->{$col}
ABresult
1X1
011
000
4390  
4391 5 my @out;
4392 5 for my $f (@{ $entry->{fields} }) {
4393 5 ▶ my $as = $taken{$f} ? "${name}_$f" : $f;
Branch: 1 branch
BranchTrueFalseTotal
$taken{$f} ? : 3 2 5
4394 5 ▶ croak $self->_i18n('error_lookup_name_taken', $name, $f, $as) if $taken{$as};
Branch: 1 branch
BranchTrueFalseTotal
if $taken{$as} 2 3 5
4395 3 $taken{$as} = 1;
4396 3 push @out, [ $f, $as ];
4397 }
4398  
4399 3 my $default = $lookup->{default};
4400 3 my $map = $entry->{map};
4401 3 for my $i (0 .. $#$records) {
4402 7 my $k = _lookup_key($records->[$i]{$col});
4403 7 ▶ my $hit = defined $k ? $map->{$k} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $k ? : 7 0 7
4404 7 for my $pair (@out) {
4405 $records->[$i] = _extend_row($records->[$i], $pair->[1],
4406 7 ▶ $hit ? $hit->{ $pair->[0] } : $default);
Branch: 1 branch
BranchTrueFalseTotal
$hit ? : 5 2 7
4407 }
4408 }
4409  
4410 3 my %have = map { $_ => 1 } @$cols;
4411 3 push @$cols, grep { !$have{$_} } map { $_->[1] } @out;
4412 3 ▶ $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->stash("_virtual_columns") 3 0 3
4413 3 for my $pair (@out) {
4414 3 $self->stash('_virtual_columns')->{ $pair->[1] } = 1;
4415 3 $written->{ $pair->[1] } = 1;
4416 }
4417 }
4418 3 $self->stash('_lookup_written' => $written);
4419 3 return;
4420 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4421  
4422 # _compile_extraction($self, $name, \%definition) -> (\%compiled, \@fields)
4423 #
4424 # Purpose: Check a stored extraction and compile its pattern, the same way on
4425 # save and on every request.
4426 # Exit: The compiled pattern (Calc::compile_pattern) and the named groups it
4427 # writes: fields= when it was given, else every named group, in order.
4428 # Croaks error_extract_pattern (wrapping Calc's reason),
4429 # error_extract_no_names or error_extract_field.
4430 22 ▶sub _compile_extraction :Protected ($self, $name, $def) {
Subroutine _compile_extraction: called CC=7 SCAR=19.5
4431 22 require Database::BI::Calc;
4432 22 my $compiled = eval { Database::BI::Calc::compile_pattern($def->{pattern}) };
4433 22 ▶ croak $self->_i18n('error_extract_pattern', $name, _tidy_error($@)) unless $compiled;
Branch: 1 branch
BranchTrueFalseTotal
unless $compiled 5 17 22
4434 17 my @names = @{ $compiled->{names} };
4435 17 ▶ croak $self->_i18n('error_extract_no_names', $name) unless @names;
Branch: 1 branch
BranchTrueFalseTotal
unless @names 3 14 17
4436 14 my %named = map { $_ => 1 } @names;
4437 14 ▶ my @fields = ref $def->{fields} eq 'ARRAY' && @{ $def->{fields} } ? @{ $def->{fields} } : @names;
Branch: 1 branch
BranchTrueFalseTotal
ref $def->{'fields'} eq 'ARRAY' && @{$def->{'fields'};} ? : 6 8 14
Condition66%2/3
ref $def->{"fields"} eq "ARRAY" and @{$def->{"fields"};}
!ll&&!rl&&r
806
MC/DC50%1/2
ref $def->{"fields"} eq "ARRAY" and @{$def->{"fields"};}
ref $def->{"fields"} eq "ARRAY" @{$def->{"fields"};}
Truth table66%2/3
A and B
A= ref $def->{"fields"} eq "ARRAY"B= @{$def->{"fields"};}
ABresult
0X0
100
111
4438 14 for my $f (@fields) {
4439 15 ▶ croak $self->_i18n('error_extract_field', $name, $f) unless $named{$f};
Branch: 1 branch
BranchTrueFalseTotal
unless $named{$f} 2 13 15
4440 }
4441 12 return ($compiled, \@fields);
4442 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4443  
4444 # _apply_extractions($self, $records, \@cols, $spec_key) -> void
4445 #
4446 # Purpose: The stored extractions of $spec_key, after the lookups in stage 3:
4447 # each named group of a pattern becomes a column, read from the column
4448 # the extraction names. A row the pattern does not match, or whose
4449 # cell is empty, gets '(unparseable)', so it groups visibly rather than
4450 # vanishing; a group that took no part in a match is ''.
4451 # Entry: \@cols is the column list so far; it gains the new columns.
4452 # Exit: Croaks with a message for a bad pattern or a missing column.
4453 # Notes: Columns are named as a lookup's are: the group's own name unless a
4454 # column has it, then <extraction>_<group>. A capture is cut to 200
4455 # characters (Calc::capture_of).
4456 1356 ▶sub _apply_extractions :Protected ($self, $records, $cols, $spec_key) {
Subroutine _apply_extractions: called CC=19 SCAR=29.5
4457 1356 ▶ return unless length($spec_key // '');
Branch: 1 branch
BranchTrueFalseTotal
unless length($spec_key // "") 8 1348 1356
Condition100%2/2
$spec_key // ""
l!l
13551
MC/DC100%1/1
$spec_key // ""
$spec_key
Truth table100%2/2
A
A= $spec_key
Aresult
11
00
4458 1348 my $stored = $self->_read_models->{extractions}{$spec_key};
4459 1348 ▶ return unless ref $stored eq 'HASH' && %$stored;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $stored eq "HASH" and %$stored 1341 7 1348
Condition66%2/3
ref $stored eq "HASH" and %$stored
!ll&&!rl&&r
134107
MC/DC50%1/2
ref $stored eq "HASH" and %$stored
ref $stored eq "HASH" %$stored
Truth table66%2/3
A and B
A= ref $stored eq "HASH"B= %$stored
ABresult
0X0
100
111
4460  
4461 7 ▶ my $written = $self->stash('_extract_written') // {};
Condition50%1/2
$self->stash("_extract_written") // {}
l!l
07
MC/DC0%0/1
$self->stash("_extract_written") // {}
$self->stash("_extract_written")
Truth table50%1/2
A
A= $self->stash("_extract_written")
Aresult
11
00
4462 7 my %taken = map { $_ => 1 } grep { !$written->{$_} } @$cols;
4463 7 for my $name (sort keys %$stored) {
4464 7 my $def = $stored->{$name};
4465 7 ▶ next unless ref $def eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $def eq "HASH" 1 6 7
4466 6 my ($compiled, $fields) = $self->_compile_extraction($name, $def);
4467 6 ▶ my $col = $def->{col} // '';
Condition50%1/2
$def->{"col"} // ""
l!l
60
MC/DC0%0/1
$def->{"col"} // ""
$def->{"col"}
Truth table50%1/2
A
A= $def->{"col"}
Aresult
11
00
4468 croak $self->_i18n('error_extract_col_unknown', $name, $col)
4469 6 ▶ unless $taken{$col} || $written->{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $taken{$col} or $written->{$col} 2 4 6
Condition66%2/3
$taken{$col} or $written->{$col}
l!l&&r!l&&!r
402
MC/DC50%1/2
$taken{$col} or $written->{$col}
$taken{$col} $written->{$col}
Truth table66%2/3
A or B
A= $taken{$col}B= $written->{$col}
ABresult
1X1
011
000
4470  
4471 4 my @out;
4472 4 for my $f (@$fields) {
4473 4 ▶ my $as = $taken{$f} ? "${name}_$f" : $f;
Branch: 1 branch
BranchTrueFalseTotal
$taken{$f} ? : 2 2 4
4474 4 ▶ croak $self->_i18n('error_extract_name_taken', $name, $f, $as) if $taken{$as};
Branch: 1 branch
BranchTrueFalseTotal
if $taken{$as} 2 2 4
4475 2 $taken{$as} = 1;
4476 2 push @out, [ $f, $as ];
4477 }
4478  
4479 # The groups were checked against the pattern, so undef is a row it
4480 # does not match, and a group that took no part is ''.
4481 2 for my $i (0 .. $#$records) {
4482 4 my $v = $records->[$i]{$col};
4483 4 for my $pair (@out) {
4484 4 my $got = Database::BI::Calc::capture_of($compiled, $v, $pair->[0]);
4485 4 ▶ $records->[$i] = _extend_row($records->[$i], $pair->[1], $got // '(unparseable)');
Condition100%2/2
$got // "(unparseable)"
l!l
31
MC/DC100%1/1
$got // "(unparseable)"
$got
Truth table100%2/2
A
A= $got
Aresult
11
00
4486 }
4487 }
4488  
4489 2 my %have = map { $_ => 1 } @$cols;
4490 2 push @$cols, grep { !$have{$_} } map { $_->[1] } @out;
4491 2 ▶ $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->stash("_virtual_columns") 2 0 2
4492 2 for my $pair (@out) {
4493 2 $self->stash('_virtual_columns')->{ $pair->[1] } = 1;
4494 2 $written->{ $pair->[1] } = 1;
4495 }
4496 }
4497 3 $self->stash('_extract_written' => $written);
4498 3 return;
4499 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4500  
4501 # _extend_row($row, $name, $value) -> $row | \%copy
4502 #
4503 # Purpose: Write a virtual column into a row that came out of a source. A row
4504 # from a SQL-backed source arrives with its key set locked (the backend
4505 # locks it so that reading a column that is not there fails loudly),
4506 # and a locked row cannot take a new key in place: the assignment raises
4507 # "Attempt to access disallowed key". Such a row is replaced by an
4508 # unlocked copy of itself carrying the new cell, which the rest of the
4509 # pipeline reads exactly as it reads any other row.
4510 # Entry: $row -- the row hashref; $name -- the column to add; $value -- its value.
4511 # Exit: $row itself when it can take the key (already present, or writable),
4512 # otherwise a new hashref.
4513 # Notes: Only a *new* key is a problem -- writing a key a locked row already
4514 # has is allowed -- so the common case (a CSV-backed source, and any
4515 # repeated evaluation) copies nothing.
4516 115 ▶sub _extend_row {
Subroutine _extend_row: called CC=3 SCAR=11.0
4517 115 my ($row, $name, $value) = @_;
4518 115 ▶ return $row if ref $row ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $row ne "HASH" 2 113 115
4519 113 require Hash::Util;
4520 113 ▶ unless (Hash::Util::hashref_locked($row)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (Hash::Util::hashref_locked($row)) 110 3 113
4521 110 $row->{$name} = $value;
4522 110 return $row;
4523 }
4524 3 return { %$row, $name => $value };
4525 }
4526  
4527 # _write_calc_column($self, $records, \@cols, $name, $calc)
4528 #
4529 # Purpose: Evaluate one compiled calculated field over the rows and write it as
4530 # a column, recording it as virtual so _grouped_totals skips the SQL
4531 # push path. \@cols gains the name if it is new.
4532 25 ▶sub _write_calc_column :Protected ($self, $records, $cols, $name, $calc) {
Subroutine _write_calc_column: called CC=7 SCAR=19.5
4533 25 my $undef_count = 0;
4534 25 for my $i (0 .. $#$records) {
4535 77 my $row = $records->[$i];
4536 77 my $val = $calc->evaluate($row);
4537 77 ▶ $undef_count++ unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 11 66 77
4538 # Store '(unparseable)' rather than undef so that pivot/bar
4539 # grouping (which skips empty-string keys) keeps these rows in a
4540 # visible '(unparseable)' bucket rather than silently dropping them.
4541 # See _extend_row for why the row may have to be replaced.
4542 77 ▶ $records->[$i] = _extend_row($row, $name,
Branch: 1 branch
BranchTrueFalseTotal
defined $val ? : 66 11 77
4543 defined $val ? $val : '(unparseable)');
4544 }
4545 25 ▶ if ($undef_count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($undef_count) 4 21 25
4546 4 $self->app->log->warn($self->_i18n('warn_calc_undef', $name, $undef_count));
4547 }
4548 25 ▶ push @$cols, $name unless grep { $_ eq $name } @$cols;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $name;} @$cols 24 1 25
4549 25 ▶ $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->stash("_virtual_columns") 20 5 25
4550 25 $self->stash('_virtual_columns')->{$name} = 1;
4551 25 return;
4552 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4553  
4554 # _apply_held_calc_fields($self, $records, \@columns, $card) -> ($records, \@columns)
4555 #
4556 # Purpose: Stage 7 of the pipeline: the calculated fields stage 4 held back,
4557 # now that the cross-row columns they name exist. Each was checked
4558 # against those names when it was held, so a failure here is reported
4559 # as any other compile failure is.
4560 # Entry: $card is true for a canvas card. A canvas holds a field for any
4561 # card's plan, so a field that does not compile against this card's
4562 # columns belongs to another card, and this card goes without it.
4563 # Exit: The rows and columns, extended. The list is a new array, and both
4564 # come back as they arrived when nothing is held.
4565 3 ▶sub _apply_held_calc_fields :Protected ($self, $records, $columns, $card = 0) {
Subroutine _apply_held_calc_fields: called CC=9 SCAR=22.5
4566 3 my $held = $self->stash('_held_calc_fields');
4567 3 ▶ return ($records, $columns) unless $held && @$held;
Branch: 1 branch
BranchTrueFalseTotal
unless $held and @$held 1 2 3
Condition66%2/3
$held and @$held
!ll&&!rl&&r
102
MC/DC50%1/2
$held and @$held
$held @$held
Truth table66%2/3
A and B
A= $heldB= @$held
ABresult
0X0
100
111
4568  
4569 2 require Database::BI::Calc;
4570 0 ▶ my @cols = @{ $columns // [ sort keys %{ $records->[0] // {} } ] };
Condition25%1/4
$columns // [sort(keys %{$records->[0] // {};})]
l!l
20
$records->[0] // {}
l!l
00
MC/DC0%0/1
$columns // [sort(keys %{$records->[0] // {};})]
$columns
MC/DC0%0/1
$records->[0] // {}
$records->[0]
Truth table50%1/2
A
A= $columns
Aresult
11
00
Truth table0%0/2
A
A= $records->[0]
Aresult
11
00
4571 2 for my $cs (@$held) {
4572 my $calc = Database::BI::Calc->new(
4573 expr => $cs->{expr},
4574 columns => \@cols,
4575 params => $cs->{params},
4576 4 );
4577 4 ▶ if ($calc->has_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($calc->has_error) 2 2 4
4578 2 ▶ next if $card;
Branch: 1 branch
BranchTrueFalseTotal
if $card 1 1 2
4579 1 croak $self->_i18n('error_calc_compile', $cs->{name}, $calc->error);
4580 }
4581 2 $self->_write_calc_column($records, \@cols, $cs->{name}, $calc);
4582 }
4583 1 return ($records, \@cols);
4584 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4585  
4586 # _cross_row_aliases(@specs) -> @names
4587 #
4588 # Purpose: The columns a list of cs= specs will add: the third field of each.
4589 # Only names are wanted, so a malformed spec simply has none; refusing
4590 # it is the work of _cross_row_specs_from.
4591 1382 ▶sub _cross_row_aliases {
Subroutine _cross_row_aliases: called CC=4 SCAR=13.9
4592 1382 ▶ return map { (split /:/, $_, 4)[2] // () } grep { defined && !ref && length } @_;
Condition88%8/9
(split(/:/u, $_, 4))[2] // ()
l!l&&r!l&&!r
28320
defined $_ && !ref($_) && length $_
!ll&&!rl&&r
2360
defined $_ and not ref $_
!ll&&!rl&&r
1163
MC/DC0%0/2
(split(/:/u, $_, 4))[2] // ()
(split(/:/u, $_, 4))[2] ()
MC/DC100%3/3
defined $_ && !ref($_) && length $_
defined $_ not ref $_ length $_
Truth table66%2/3
A // B
A= (split(/:/u, $_, 4))[2]B= ()
ABresult
1X1
011
000
Truth table100%4/4
A and not(B) && C
A= defined $_B= not ref $_C= length $_
ABCresult
0XX0
10X0
1100
1111
4593 }
4594  
4595 # _cross_row_written($self) -> @names
4596 #
4597 # Purpose: The columns this request writes at stages 6 and 7: the cs= aliases and
4598 # the calculated fields held back for them. A filter on one of these
4599 # has to run after them.
4600 27 ▶sub _cross_row_written {
Subroutine _cross_row_written: called CC=3 SCAR=11.0
4601 27 my ($self) = @_;
4602 return (
4603 27 ▶ _cross_row_aliases(@{ $self->every_param('cs') // [] }),
Condition50%1/2
$self->every_param("cs") // []
l!l
270
MC/DC0%0/1
$self->every_param("cs") // []
$self->every_param("cs")
Truth table50%1/2
A
A= $self->every_param("cs")
Aresult
11
00
4604 27 ▶ map { $_->{name} } @{ $self->stash('_held_calc_fields') // [] },
Condition100%2/2
$self->stash("_held_calc_fields") // []
l!l
261
MC/DC100%1/1
$self->stash("_held_calc_fields") // []
$self->stash("_held_calc_fields")
Truth table100%2/2
A
A= $self->stash("_held_calc_fields")
Aresult
11
00
4605 );
4606 }
4607  
4608 # _canvas_window_columns($analysis, $params, \@more) -> \@names
4609 #
4610 # Purpose: Every column a cross-row plan may add on this canvas: the page's cs=,
4611 # read from $params, and each card's own plan. \@more holds cards that
4612 # are not on the canvas yet: one being added, or being given a new plan.
4613 77 ▶sub _canvas_window_columns {
Subroutine _canvas_window_columns: called CC=8 SCAR=20.8
4614 77 my ($analysis, $params, $more) = @_;
4615 77 ▶ my @specs = @{ $params->every_param('cs') // [] };
Condition50%1/2
$params->every_param("cs") // []
l!l
770
MC/DC0%0/1
$params->every_param("cs") // []
$params->every_param("cs")
Truth table50%1/2
A
A= $params->every_param("cs")
Aresult
11
00
4616 77 ▶ for my $vis (@{ $analysis->{visuals} // [] }, @{ $more // [] }) {
Condition100%4/4
$analysis->{"visuals"} // []
l!l
743
$more // []
l!l
1166
MC/DC100%1/1
$analysis->{"visuals"} // []
$analysis->{"visuals"}
MC/DC100%1/1
$more // []
$more
Truth table100%2/2
A
A= $analysis->{"visuals"}
Aresult
11
00
Truth table100%2/2
A
A= $more
Aresult
11
00
4617 next unless ref $vis eq 'HASH' && ref $vis->{cross_row} eq 'HASH'
4618 94 ▶ && ref $vis->{cross_row}{cs} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $vis eq "HASH" and ref $vis->{"cross_row"} eq "HASH" and ref $vis->{"cross_row"}{"cs"} eq "ARRAY" 92 2 94
Condition100%6/6
ref $vis eq "HASH" and ref $vis->{"cross_row"} eq "HASH" and ref $vis->{"cross_row"}{"cs"} eq "ARRAY"
!ll&&!rl&&r
9112
ref $vis eq "HASH" and ref $vis->{"cross_row"} eq "HASH"
!ll&&!rl&&r
1903
MC/DC100%3/3
ref $vis eq "HASH" and ref $vis->{"cross_row"} eq "HASH" and ref $vis->{"cross_row"}{"cs"} eq "ARRAY"
ref $vis eq "HASH" ref $vis->{"cross_row"} eq "HASH" ref $vis->{"cross_row"}{"cs"} eq "ARRAY"
Truth table100%4/4
A and B and C
A= ref $vis eq "HASH"B= ref $vis->{"cross_row"} eq "HASH"C= ref $vis->{"cross_row"}{"cs"} eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
4619 2 push @specs, @{ $vis->{cross_row}{cs} };
4620 }
4621 77 return [ _cross_row_aliases(@specs) ];
4622 }
4623  
4624 # _canvas_cross_filter($self, $records, \@columns, \@specs) -> ($records, \@late)
4625 #
4626 # Purpose: Apply a canvas's cross-filter to a card's rows, except any spec on a
4627 # column a cross-row plan writes. That column does not exist yet, so
4628 # the spec comes back for _render_visual_html to apply after the pass.
4629 11 ▶sub _canvas_cross_filter :Protected ($self, $records, $columns, $specs) {
Subroutine _canvas_cross_filter: called CC=6 SCAR=17.9
4630 3 my %written = map { $_ => 1 }
4631 11 ▶ @{ $self->stash('_canvas_window_names') // [] },
Condition100%2/2
$self->stash("_canvas_window_names") // []
l!l
101
MC/DC100%1/1
$self->stash("_canvas_window_names") // []
$self->stash("_canvas_window_names")
Truth table100%2/2
A
A= $self->stash("_canvas_window_names")
Aresult
11
00
4632 11 ▶ map { $_->{name} } @{ $self->stash('_held_calc_fields') // [] };
Condition100%2/2
$self->stash("_held_calc_fields") // []
l!l
101
MC/DC100%1/1
$self->stash("_held_calc_fields") // []
$self->stash("_held_calc_fields")
Truth table100%2/2
A
A= $self->stash("_held_calc_fields")
Aresult
11
00
4633 11 delete @written{ @$columns };
4634 11 my @late;
4635 11 for my $spec (@$specs) {
4636 6 ▶ if ($written{ (split /:/, $spec, 2)[0] // '' }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($written{(split(/:/u, $spec, 2))[0] // ""}) 2 4 6
Condition50%1/2
(split(/:/u, $spec, 2))[0] // ""
l!l
60
MC/DC0%0/1
(split(/:/u, $spec, 2))[0] // ""
(split(/:/u, $spec, 2))[0]
Truth table50%1/2
A
A= (split(/:/u, $spec, 2))[0]
Aresult
11
00
4637 2 push @late, $spec;
4638 2 next;
4639 }
4640 4 $records = _apply_filter_spec($records, $spec);
4641 }
4642 11 return ($records, \@late);
4643 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4644  
4645 # _calc_specs_of_request($self) -> @specs
4646 #
4647 # Purpose: The calculated fields among the request's c= params, leaving out the
4648 # files it stacks, which share that parameter.
4649 374 ▶sub _calc_specs_of_request :Protected ($self) {
Subroutine _calc_specs_of_request: called CC=2 SCAR=7.1
4650 374 ▶ return grep { !/\A(?:path|table|url|redis|mariadb):/i } @{ $self->every_param('c') // [] };
Condition50%1/2
$self->every_param("c") // []
l!l
3740
MC/DC0%0/1
$self->every_param("c") // []
$self->every_param("c")
Truth table50%1/2
A
A= $self->every_param("c")
Aresult
11
00
4651 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4652  
4653 # _page_columns($self, $source, $records, $spec_key) -> ($records, \@columns) | ()
4654 #
4655 # Purpose: The columns of a table page from _fetch_page, with the calculated
4656 # fields and any span= bucket drawn on its rows. A page is one slice,
4657 # so _fetch_page has already run them over the whole set if a filter or
4658 # a window needed them; this pass is what puts them on the page.
4659 # Entry: $spec_key files the stored fields: the page's left_spec.
4660 # Exit: The rows and columns; or the empty list after rendering a 400, and the
4661 # caller returns.
4662 301 ▶sub _page_columns :Protected ($self, $source, $records, $spec_key) {
Subroutine _page_columns: called CC=7 SCAR=19.6
4663 301 my @columns = _get_columns($source, $records);
4664 301 my %seen_col = map { $_ => 1 } @columns;
4665 # Stage 6 wrote its columns onto the rows before the page was sliced, so the
4666 # list is what makes the table show them, and lets a field below read one.
4667 0 ▶ push @columns, grep { !$seen_col{$_}++ } @{ $self->stash('_cross_row_columns') // [] };
Condition50%1/2
$self->stash("_cross_row_columns") // []
l!l
0301
MC/DC0%0/1
$self->stash("_cross_row_columns") // []
$self->stash("_cross_row_columns")
Truth table50%1/2
A
A= $self->stash("_cross_row_columns")
Aresult
11
00
4668 # Nothing to draw a field from: a source with no declared columns and no rows.
4669 301 ▶ return ($records, \@columns) unless @columns;
Branch: 1 branch
BranchTrueFalseTotal
unless @columns 7 294 301
4670  
4671 # span= adds a bucket column to the table rather than grouping it: a table has
4672 # no dimension to bucket *into*, so the reader gets the column and the raw
4673 # value beside it. See _span_calc_spec.
4674 294 my $span = $self->_span_calc_spec(\@columns, ());
4675 294 ▶ if ($span && $span->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($span and $span->{"error"}) 5 289 294
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
28905
MC/DC50%1/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table66%2/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
4676 5 $self->render(text => $span->{error}, status => 400);
4677 5 return ();
4678 }
4679  
4680 289 my ($calc_records, $calc_columns) = eval {
4681 $self->_calc_for_page($records, \@columns, {
4682 spec_key => $spec_key,
4683 289 ▶ ($span ? (calc => $span->{calc}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 289 289
4684 })
4685 };
4686 289 ▶ unless ($calc_records) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($calc_records) 1 288 289
4687 # Every location croak added on the way up, not only the last.
4688 1 $self->render(text => _tidy_error($@), status => 400);
4689 1 return ();
4690 }
4691 288 return ($calc_records, $calc_columns);
4692 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4693  
4694 # _calc_for_page($self, $records, \@columns, \%extra) -> ($records, \@columns)
4695 #
4696 # Purpose: _apply_calc_fields for a table page, which must still be drawn when a
4697 # definition saved for its data cannot be applied -- a lookup file that
4698 # is gone, a column an extraction or a field reads that the file no
4699 # longer has. Every chart and export of that data refuses with the
4700 # reason, and the panels that mend a definition are on the table page,
4701 # so a page that refused too would leave the reader no way back.
4702 # Entry: As _apply_calc_fields; $extra->{spec_key} files the definitions.
4703 # Exit: As _apply_calc_fields. When the first pass croaks and a second one
4704 # without the saved fields, lookups and extractions succeeds, returns
4705 # that, with stash stored_error holding the first pass's reason and
4706 # _skip_stored set for the rest of the request. Otherwise croaks with
4707 # the first pass's error, so a mistake in the request's own c= is the
4708 # 400 it always was.
4709 # Side Effects: The first pass runs on a copy of the rows when anything is
4710 # saved, so a pass that failed half way leaves nothing on them.
4711 329 ▶sub _calc_for_page :Protected ($self, $records, $columns, $extra) {
Subroutine _calc_for_page: called CC=9 SCAR=23.0
4712 329 ▶ my $stored = !$self->stash('_skip_stored') && $self->_has_stored_columns($extra->{spec_key});
Condition66%2/3
!$self->stash('_skip_stored') && $self->_has_stored_columns($extra->{'spec_key'})
!ll&&!rl&&r
03236
MC/DC50%1/2
!$self->stash('_skip_stored') && $self->_has_stored_columns($extra->{'spec_key'})
!$self->stash('_skip_stored') $self->_has_stored_columns($extra->{'spec_key'})
Truth table66%2/3
not(A) && B
A= !$self->stash('_skip_stored')B= $self->_has_stored_columns($extra->{'spec_key'})
ABresult
0X0
100
111
4713 329 ▶ my $rows = $stored ? [ map { ref $_ eq 'HASH' ? { %$_ } : $_ } @$records ] : $records;
Branch: 2 branches
BranchTrueFalseTotal
$stored ? : 6 323 329
ref $_ eq 'HASH' ? : 33 0 33
4714 329 my @got = eval { $self->_apply_calc_fields($rows, $columns, $extra) };
4715 329 ▶ return @got if @got && $got[0];
Branch: 1 branch
BranchTrueFalseTotal
if @got and $got[0] 324 5 329
Condition66%2/3
@got and $got[0]
!ll&&!rl&&r
50324
MC/DC50%1/2
@got and $got[0]
@got $got[0]
Truth table66%2/3
A and B
A= @gotB= $got[0]
ABresult
0X0
100
111
4716 5 my $error = $@;
4717 5 ▶ croak $error unless $stored;
Branch: 1 branch
BranchTrueFalseTotal
unless $stored 2 3 5
4718  
4719 3 $self->stash('_skip_stored' => 1);
4720 3 @got = eval { $self->_apply_calc_fields($records, $columns, $extra) };
4721 3 ▶ unless (@got && $got[0]) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@got and $got[0]) 0 3 3
Condition33%1/3
@got and $got[0]
!ll&&!rl&&r
003
MC/DC0%0/2
@got and $got[0]
@got $got[0]
Truth table33%1/3
A and B
A= @gotB= $got[0]
ABresult
0X0
100
111
4722 0 $self->stash('_skip_stored' => 0);
4723 0 croak $error;
4724 }
4725 3 $self->stash(stored_error => _tidy_error($error));
4726 3 return @got;
4727 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4728  
4729 # _has_stored_columns($self, $spec_key) -> $bool
4730 #
4731 # Purpose: Whether anything saved for $spec_key adds columns that can fail: a
4732 # calculated field, a lookup (its own, or another's through lk=) or an
4733 # extraction.
4734 # Entry: $spec_key may be undef, when the request's l= is the key.
4735 # Exit: True or false.
4736 334 ▶sub _has_stored_columns :Protected ($self, $spec_key) {
Subroutine _has_stored_columns: called CC=9 SCAR=22.3
4737 334 ▶ $spec_key = canonical_spec($spec_key // $self->param('l') // '');
Condition60%3/5
($spec_key // $self->param("l")) // ""
l!l
3340
$spec_key // $self->param("l")
l!l&&r!l&&!r
33310
MC/DC0%0/2
($spec_key // $self->param("l")) // ""
$spec_key $self->param("l")
Truth table66%2/3
A // B
A= $spec_keyB= $self->param("l")
ABresult
1X1
011
000
4738 334 ▶ return 1 if @{ $self->every_param('lk') // [] };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->every_param("lk") // [];} 4 330 334
Condition50%1/2
$self->every_param("lk") // []
l!l
3340
MC/DC0%0/1
$self->every_param("lk") // []
$self->every_param("lk")
Truth table50%1/2
A
A= $self->every_param("lk")
Aresult
11
00
4739 330 ▶ return 0 unless length $spec_key;
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec_key 1 329 330
4740 329 my $models = $self->_read_models;
4741 329 for my $kind (qw(fields lookups extractions)) {
4742 977 my $set = $models->{$kind}{$spec_key};
4743 977 ▶ return 1 if ref $set eq 'HASH' && %$set;
Branch: 1 branch
BranchTrueFalseTotal
if ref $set eq "HASH" and %$set 5 972 977
Condition66%2/3
ref $set eq "HASH" and %$set
!ll&&!rl&&r
97205
MC/DC50%1/2
ref $set eq "HASH" and %$set
ref $set eq "HASH" %$set
Truth table66%2/3
A and B
A= ref $set eq "HASH"B= %$set
ABresult
0X0
100
111
4744 }
4745 324 return 0;
4746 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4747  
4748 # _apply_calc_fields($self, $records, \@columns, \%extra) -> ($records, \@columns)
4749 #
4750 # Reads ?c=<name>:<expression> params (those NOT matching a path:/table:/url:/redis:/mariadb:
4751 # source spec) and compiles each via Database::BI::Calc. Evaluates per row,
4752 # appending the virtual column to each row hashref. Croaks on compile error
4753 # (caller renders 400); runtime undef values are logged at warn level.
4754 # Later ?c= specs may reference names defined by earlier ones (evaluated in order).
4755 #
4756 # Optional \%extra keys:
4757 # params => \%hash -- named parameter values bound from the URL (?p.name=val)
4758 # passed to Calc->new so expressions may reference them.
4759 # spec_key => $str -- override the l= spec key used to look up stored calc
4760 # fields (canvas context where ?l= is absent).
4761 # calc => \@specs -- additional ?c=-style specs, for a canvas whose query
4762 # string arrived with the request rather than as the
4763 # request's own parameters.
4764 # window_columns => \@names -- the columns the cross-row pass will add, for a
4765 # canvas, whose plans are not the request's own cs=.
4766 #
4767 # A field that needs a cross-row column cannot run yet: stage 6 comes after the
4768 # filters this stage feeds. So a field that fails to compile, and would compile
4769 # once those columns exist, is held back for _apply_held_calc_fields. Any other
4770 # failure is still the error it always was, a mistyped name included, so holding
4771 # cannot hide a mistake, and with no cs= nothing is ever held.
4772 1372 ▶sub _apply_calc_fields :Protected ($self, $records, $columns, $extra = undef) {
Subroutine _apply_calc_fields: called CC=41 SCAR=37.7
4773 1372 ▶ my $bound_params = ($extra // {})->{params} // {};
Condition100%4/4
+($extra // {})->{"params"} // {}
l!l
761296
$extra // {}
l!l
408964
MC/DC100%1/1
+($extra // {})->{"params"} // {}
$extra
Truth table100%2/2
A
A= $extra
Aresult
11
00
4774 1372 ▶ my $spec_key_override = ($extra // {})->{spec_key};
Condition100%2/2
$extra // {}
l!l
408964
MC/DC100%1/1
$extra // {}
$extra
Truth table100%2/2
A
A= $extra
Aresult
11
00
4775 1372 ▶ my $extra_calc = ($extra // {})->{calc} // [];
Condition100%4/4
+($extra // {})->{"calc"} // []
l!l
371335
$extra // {}
l!l
408964
MC/DC100%1/1
+($extra // {})->{"calc"} // []
$extra
Truth table100%2/2
A
A= $extra
Aresult
11
00
4776  
4777 # Normalise date columns before evaluating expressions so that date
4778 # functions (YEAR, MONTH, etc.) see ISO-8601 values even when the source
4779 # file uses a non-ISO format (e.g. M/D/YYYY).
4780 1372 ▶ my $date_spec = defined $spec_key_override
Branch: 1 branch
BranchTrueFalseTotal
defined $spec_key_override ? : 407 965 1372
Condition100%2/2
$self->param("l") // ""
l!l
9587
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
4781 ? $spec_key_override : ($self->param('l') // '');
4782 # A canvas dataset's spec comes from the stored canvas, not the request,
4783 # so the hook that spells the request's specs one way has not seen it.
4784 1372 $date_spec = canonical_spec($date_spec);
4785 1372 $self->_apply_date_normalization($records, $columns, $date_spec);
4786  
4787 # Stage 3: the stored lookups, so that a field, a filter, a bucket or a window
4788 # can read a looked-up column. They join the column list from here on.
4789 # _skip_stored is set by _calc_for_page when one of them cannot be applied:
4790 # the table page is drawn without them, so its panels can mend them.
4791 1372 my $skip_stored = $self->stash('_skip_stored');
4792 1372 my @cols = @{$columns};
4793 1372 ▶ unless ($skip_stored) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($skip_stored) 1369 3 1372
4794 1369 $self->_apply_lookups($records, \@cols, $date_spec);
4795 1351 $self->_apply_extractions($records, \@cols, $date_spec);
4796 }
4797  
4798 # Build calc spec list: stored fields from models.json first (lower priority),
4799 # then URL ?c= params (higher priority -- they override stored fields of the
4800 # same name so the user can test a new expression without permanently saving).
4801 1352 my (@calc_specs, %seen_calc);
4802 {
4803 1352 my $sk = $date_spec;
4804 1352 ▶ if (length $sk && !$skip_stored) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $sk and not $skip_stored) 1342 10 1352
Condition100%3/3
length $sk and not $skip_stored
!ll&&!rl&&r
731342
MC/DC100%2/2
length $sk and not $skip_stored
length $sk not $skip_stored
Truth table100%3/3
A and not(B)
A= length $skB= not $skip_stored
ABresult
0X0
100
111
4805 1342 ▶ my $stored = ($self->_read_models)->{fields}{$sk} // {};
Condition100%2/2
$self->_read_models->{"fields"}{$sk} // {}
l!l
81334
MC/DC100%1/1
$self->_read_models->{"fields"}{$sk} // {}
$self->_read_models->{"fields"}{$sk}
Truth table100%2/2
A
A= $self->_read_models->{"fields"}{$sk}
Aresult
11
00
4806 1342 for my $n (sort keys %{$stored}) {
4807 5 push @calc_specs, { name => $n, expr => $stored->{$n} };
4808 5 $seen_calc{$n} = $#calc_specs;
4809 }
4810 }
4811 }
4812 1352 ▶ for my $spec (@{ $self->every_param('c') // [] }, @$extra_calc) {
Condition50%1/2
$self->every_param("c") // []
l!l
13520
MC/DC0%0/1
$self->every_param("c") // []
$self->every_param("c")
Truth table50%1/2
A
A= $self->every_param("c")
Aresult
11
00
4813 # Skip source specs handled by _run_pipeline_source.
4814 61 ▶ next if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/i;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/iu 19 42 61
4815 42 my ($name, $expr) = ($spec =~ /\A([A-Za-z_][A-Za-z0-9_]*):(.+)\z/s);
4816 42 ▶ next unless defined $name && defined $expr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and defined $expr 15 27 42
Condition66%2/3
defined $name and defined $expr
!ll&&!rl&&r
15027
MC/DC50%1/2
defined $name and defined $expr
defined $name defined $expr
Truth table66%2/3
A and B
A= defined $nameB= defined $expr
ABresult
0X0
100
111
4817 27 ▶ if (exists $seen_calc{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $seen_calc{$name}) { } 1 26 27
4818 1 $calc_specs[$seen_calc{$name}]{expr} = $expr; # URL overrides stored
4819 } else {
4820 26 push @calc_specs, { name => $name, expr => $expr };
4821 26 $seen_calc{$name} = $#calc_specs;
4822 }
4823 }
4824  
4825 my @window = $extra && $extra->{window_columns}
4826 75 ? @{ $extra->{window_columns} }
4827 1352 ▶ : _cross_row_aliases(@{ $self->every_param('cs') // [] });
Branch: 1 branch
BranchTrueFalseTotal
$extra && $extra->{'window_columns'} ? : 75 1277 1352
Condition80%4/5
$extra and $extra->{"window_columns"}
!ll&&!rl&&r
94633175
$self->every_param("cs") // []
l!l
12770
MC/DC100%2/2
$extra and $extra->{"window_columns"}
$extra $extra->{"window_columns"}
MC/DC0%0/1
$self->every_param("cs") // []
$self->every_param("cs")
Truth table100%3/3
A and B
A= $extraB= $extra->{"window_columns"}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $self->every_param("cs")
Aresult
11
00
4828 1352 my @held;
4829  
4830 1352 ▶ if (@calc_specs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@calc_specs) 29 1323 1352
4831 29 require Database::BI::Calc;
4832 29 for my $cs (@calc_specs) {
4833 31 my $name = $cs->{name};
4834 my $calc = Database::BI::Calc->new(
4835 expr => $cs->{expr},
4836 31 columns => \@cols,
4837 params => $bound_params,
4838 );
4839 31 ▶ if ($calc->has_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($calc->has_error) 11 20 31
4840 # The names of fields already held count too, so that a field
4841 # can build on one that is waiting.
4842 my $later = @window && Database::BI::Calc->new(
4843 expr => $cs->{expr},
4844 0 ▶ columns => [ @cols, @window, map { $_->{name} } @held ],
Condition33%1/3
@window && 'Database::BI::Calc'->new('expr', $cs->{'expr'}, 'columns', [@cols, @window, map({$_->{'name'};} @held)], 'params', $bound_params)
!ll&&!rl&&r
1100
MC/DC0%0/2
@window && 'Database::BI::Calc'->new('expr', $cs->{'expr'}, 'columns', [@cols, @window, map({$_->{'name'};} @held)], 'params', $bound_params)
@window 'Database::BI::Calc'->new('expr', $cs->{'expr'}, 'columns', [@cols, @window, map({$_->{'name'};} @held)], 'params', $bound_params)
Truth table33%1/3
A && B
A= @windowB= 'Database::BI::Calc'->new('expr', $cs->{'expr'}, 'columns', [@cols, @window, map({$_->{'name'};} @held)], 'params', $bound_params)
ABresult
0X0
100
111
4845 params => $bound_params,
4846 );
4847 11 ▶ if ($later && !$later->has_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($later and not $later->has_error) 0 11 11
Condition33%1/3
$later and not $later->has_error
!ll&&!rl&&r
1100
MC/DC0%0/2
$later and not $later->has_error
$later not $later->has_error
Truth table33%1/3
A and not(B)
A= $laterB= not $later->has_error
ABresult
0X0
100
111
4848 0 push @held, { %$cs, params => $bound_params };
4849 0 next;
4850 }
4851 11 croak $self->_i18n('error_calc_compile', $name, $calc->error);
4852 }
4853  
4854 20 $self->_write_calc_column($records, \@cols, $name, $calc);
4855 }
4856 }
4857 1341 $self->stash('_held_calc_fields' => \@held);
4858  
4859 # Apply named value groups from models.json.
4860 # For each source column that has groups registered under the current l=
4861 # spec, add a virtual "${col}_group" column to every row. Each row's value
4862 # is mapped to its group label; values not in any group become '(other)'.
4863 # The spec is the one the stored fields use, so a table page, which names
4864 # its spec rather than taking l=, shows the column its charts can draw.
4865 {
4866 1341 my $spec_key = $date_spec;
4867 1341 ▶ if (length $spec_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $spec_key) 1335 6 1341
4868 1335 my $models = $self->_read_models;
4869 1335 my $grps = $models->{groups}{$spec_key};
4870 1335 ▶ if ($grps && %{$grps}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($grps and %{$grps;}) 4 1331 1335
Condition66%2/3
$grps and %{$grps;}
!ll&&!rl&&r
133104
MC/DC50%1/2
$grps and %{$grps;}
$grps %{$grps;}
Truth table66%2/3
A and B
A= $grpsB= %{$grps;}
ABresult
0X0
100
111
4871 4 my %col_set = map { $_ => 1 } @cols;
4872 4 for my $col (sort keys %{$grps}) {
4873 4 ▶ next unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 0 4 4
4874 # Build reverse map: value -> group label.
4875 4 my %val2group;
4876 4 for my $gname (keys %{$grps->{$col}}) {
4877 8 for my $v (@{$grps->{$col}{$gname}}) {
4878 14 $val2group{$v} = $gname;
4879 }
4880 }
4881 4 my $vcol = "${col}_group";
4882 4 for my $i (0 .. $#$records) {
4883 18 my $row = $records->[$i];
4884 18 ▶ my $v = $row->{$col} // '';
Condition50%1/2
$row->{$col} // ""
l!l
180
MC/DC0%0/1
$row->{$col} // ""
$row->{$col}
Truth table50%1/2
A
A= $row->{$col}
Aresult
11
00
4885 $records->[$i] = _extend_row(
4886 18 ▶ $row, $vcol, $val2group{$v} // '(other)');
Condition100%2/2
$val2group{$v} // "(other)"
l!l
153
MC/DC100%1/1
$val2group{$v} // "(other)"
$val2group{$v}
Truth table100%2/2
A
A= $val2group{$v}
Aresult
11
00
4887 }
4888 4 ▶ push @cols, $vcol unless grep { $_ eq $vcol } @cols;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $vcol;} @cols 4 0 4
4889 # Record group column as virtual.
4890 4 ▶ $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->stash("_virtual_columns") 4 0 4
4891 4 $self->stash('_virtual_columns')->{$vcol} = 1;
4892 }
4893 }
4894 }
4895 }
4896  
4897 1341 return ($records, \@cols);
4898 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4899  
4900 # ---------------------------------------------------------------------------
4901 # Calculated-field model storage (.bi/models.json)
4902 # ---------------------------------------------------------------------------
4903  
4904 # _canonical_path($path) -> $string
4905 #
4906 # The absolute, symlink-resolved form of a path, for the data_dir guard. Two
4907 # spellings of one directory have to compare equal, or the guard can be walked
4908 # around: a model_dir reached through a symlink is still inside the directory it
4909 # points at, and a data_dir that is itself a symlink is still where the user
4910 # keeps their data. Cwd::realpath resolves the whole path when it exists; a
4911 # store directory usually does not exist yet -- deciding whether to create it is
4912 # what the guard is for -- so the deepest ancestor that does exist is resolved
4913 # and the names below it are re-attached.
4914 20753 ▶sub _canonical_path {
Subroutine _canonical_path: called CC=9 SCAR=22.4
4915 20753 my ($path) = @_;
4916  
4917 20753 ▶ my $abs = eval { $path->to_abs } // $path;
Condition33%1/3
eval { do { $path->to_abs } } // $path
l!l&&r!l&&!r
2075300
MC/DC0%0/2
eval { do { $path->to_abs } } // $path
eval { do { $path->to_abs } } $path
Truth table33%1/3
A // B
A= eval { do { $path->to_abs } }B= $path
ABresult
1X1
011
000
4918 # Cwd::realpath on Windows does not follow symlinks: it gives undef for a
4919 # path through one, which would send the loop below to the link's parent
4920 # and keep the link's own name. So the links are followed first.
4921 20753 ▶ if ($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq "MSWin32") 3 20750 20753
4922 3 my $followed = _follow_links($abs->to_string);
4923 3 ▶ $abs = Mojo::File->new($followed) if defined $followed;
Branch: 1 branch
BranchTrueFalseTotal
if defined $followed 3 0 3
4924 }
4925 20753 my @tail;
4926 20753 my $probe = $abs;
4927 20753 while (1) {
4928 20769 my $string = $probe->to_string;
4929 20769 ▶ my $real = -e $string ? realpath($string) : undef;
Branch: 1 branch
BranchTrueFalseTotal
-e $string ? : 20753 16 20769
4930 20769 ▶ if (defined $real && length $real) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $real and length $real) 20753 16 20769
Condition66%2/3
defined $real and length $real
!ll&&!rl&&r
16020753
MC/DC50%1/2
defined $real and length $real
defined $real length $real
Truth table66%2/3
A and B
A= defined $realB= length $real
ABresult
0X0
100
111
4931 20753 ▶ return File::Spec->canonpath(
Branch: 1 branch
BranchTrueFalseTotal
@tail ? : 13 20740 20753
4932 @tail ? Mojo::File->new($real, @tail)->to_string : $real
4933 );
4934 }
4935 16 my $parent = $probe->dirname;
4936 16 ▶ last if $parent->to_string eq $string; # the root: nothing left to resolve
Branch: 1 branch
BranchTrueFalseTotal
if $parent->to_string eq $string 0 16 16
4937 16 unshift @tail, $probe->basename;
4938 16 $probe = $parent;
4939 }
4940  
4941 # Nothing on the path exists at all, so the lexical absolute form is all
4942 # there is to compare.
4943 0 return File::Spec->canonpath($abs->to_string);
4944 }
4945  
4946 # _follow_links($path) -> $path | undef
4947 #
4948 # Purpose: $path with every symlink in it replaced by what it points at, one
4949 # component at a time, as realpath does where it can. For Windows,
4950 # whose realpath leaves links alone; it works the same anywhere, which
4951 # is how it is tested.
4952 # Entry: An absolute path.
4953 # Exit: The resolved absolute path; undef after 40 links, which is a loop.
4954 21 ▶sub _follow_links {
Subroutine _follow_links: called CC=10 SCAR=23.2
4955 21 my ($path) = @_;
4956 21 my ($vol, $dirs, $file) = File::Spec->splitpath($path);
4957 21 my @todo = grep { length } File::Spec->splitdir($dirs), $file;
4958 21 my @done;
4959 21 my $hops = 0;
4960 21 ▶ while (@todo) {
Branch: 1 branch
BranchTrueFalseTotal
if (@todo) 219 19 238
4961 219 my $part = shift @todo;
4962 219 ▶ next if $part eq '.';
Branch: 1 branch
BranchTrueFalseTotal
if $part eq "." 0 219 219
4963 219 ▶ if ($part eq '..') { pop @done; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($part eq "..") 3 216 219
4964 216 my $here = File::Spec->catpath($vol, File::Spec->catdir(File::Spec->rootdir, @done, $part), '');
4965 216 ▶ if (-l $here) {
Branch: 1 branch
BranchTrueFalseTotal
if (-l $here) 102 114 216
4966 102 ▶ return undef if ++$hops > 40;
Branch: 1 branch
BranchTrueFalseTotal
if ++$hops > 40 2 100 102
4967 100 my $target = readlink $here;
4968 100 ▶ return undef unless defined $target && length $target;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $target and length $target 0 100 100
Condition33%1/3
defined $target and length $target
!ll&&!rl&&r
00100
MC/DC0%0/2
defined $target and length $target
defined $target length $target
Truth table33%1/3
A and B
A= defined $targetB= length $target
ABresult
0X0
100
111
4969 # Windows perls can give the NT form of an absolute target,
4970 # \??\C:\dir, or the long-path form \\?\C:\dir.
4971 100 $target =~ s{\A(?:\\\?\?\\|\\\\\?\\)}{};
4972 100 my ($tvol, $tdirs, $tfile) = File::Spec->splitpath($target);
4973 100 ▶ if (File::Spec->file_name_is_absolute($target)) {
Branch: 1 branch
BranchTrueFalseTotal
if ("File::Spec"->file_name_is_absolute($target)) 12 88 100
4974 12 ▶ $vol = $tvol if length $tvol;
Branch: 1 branch
BranchTrueFalseTotal
if length $tvol 0 12 12
4975 12 @done = ();
4976 }
4977 100 unshift @todo, grep { length } File::Spec->splitdir($tdirs), $tfile;
4978 100 next;
4979 }
4980 114 push @done, $part;
4981 }
4982 19 return File::Spec->catpath($vol, File::Spec->catdir(File::Spec->rootdir, @done), '');
4983 }
4984  
4985 # canonical_spec($spec) -> $spec
4986 #
4987 # Purpose: The one spelling of a path: spec that the model store files things
4988 # under. /open names its file by its realpath, so a definition saved,
4989 # or an extract built, under a path reached through a symlink (macOS's
4990 # /var is /private/var) would never be found by the page it is for.
4991 # Entry: Any spec, or undef.
4992 # Exit: path:<realpath> when the spec is path:<file> and the file exists
4993 # locally; anything else -- another kind of spec, a remote /../host
4994 # path, a file that is not there, a name with a newline -- unchanged.
4995 4092 ▶sub canonical_spec {
Subroutine canonical_spec: called CC=9 SCAR=22.2
Pod documented
4996 4092 my ($spec) = @_;
4997 4092 ▶ return $spec unless defined $spec && $spec =~ m{\Apath:(?!/\.\./)([^\n]+)\z};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec and $spec =~ m[\Apath:(?!/\.\./)([^\n]+)\z]u 2816 1276 4092
Condition100%3/3
defined $spec and $spec =~ m[\Apath:(?!/\.\./)([^\n]+)\z]u
!ll&&!rl&&r
128151276
MC/DC100%2/2
defined $spec and $spec =~ m[\Apath:(?!/\.\./)([^\n]+)\z]u
defined $spec $spec =~ m[\Apath:(?!/\.\./)([^\n]+)\z]u
Truth table100%3/3
A and B
A= defined $specB= $spec =~ m[\Apath:(?!/\.\./)([^\n]+)\z]u
ABresult
0X0
100
111
4998 1276 my ($path, $internal) = _split_path($1);
4999 1276 ▶ my $tail = defined $internal ? "#$internal" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 2 1274 1276
5000 # Windows' realpath leaves a symlink as it is, so a file reached through
5001 # one would be filed under a second key; follow the links first, as
5002 # _canonical_path does.
5003 1276 ▶ if ($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq "MSWin32") 1 1275 1276
5004 1 my $followed = eval { _follow_links(Mojo::File->new($path)->to_abs->to_string) };
5005 1 ▶ $path = $followed if defined $followed;
Branch: 1 branch
BranchTrueFalseTotal
if defined $followed 1 0 1
5006 }
5007 1276 ▶ return $spec unless -e $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $path 304 972 1276
5008 972 my $real = eval { Mojo::File->new($path)->realpath->to_string };
5009 972 ▶ return (defined $real && length $real) ? "path:$real$tail" : $spec;
Branch: 1 branch
BranchTrueFalseTotal
defined $real && length $real ? : 972 0 972
Condition33%1/3
defined $real and length $real
!ll&&!rl&&r
00972
MC/DC0%0/2
defined $real and length $real
defined $real length $real
Truth table33%1/3
A and B
A= defined $realB= length $real
ABresult
0X0
100
111
5010 }
5011  
5012 # _inside_dir($path, $dir) -> $bool
5013 #
5014 # True when $path names $dir itself or something below it. abs2rel asks the
5015 # file system what the relationship between the two is, so a textual prefix
5016 # cannot make ".../data-archive" look like it is inside ".../data", and the
5017 # comparison is made with the platform's separator rather than a hard-coded
5018 # slash.
5019 10372 ▶sub _inside_dir {
Subroutine _inside_dir: called CC=9 SCAR=22.3
5020 10372 my ($path, $dir) = @_;
5021 10372 ▶ return 0 unless length $path && length $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless length $path and length $dir 2 10370 10372
Condition100%3/3
length $path and length $dir
!ll&&!rl&&r
1110370
MC/DC100%2/2
length $path and length $dir
length $path length $dir
Truth table100%3/3
A and B
A= length $pathB= length $dir
ABresult
0X0
100
111
5022 10370 ▶ return 1 if $path eq $dir;
Branch: 1 branch
BranchTrueFalseTotal
if $path eq $dir 11 10359 10370
5023  
5024 10359 my $rel = eval { File::Spec->abs2rel($path, $dir) };
5025 10359 ▶ return 0 unless defined $rel && length $rel;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rel and length $rel 0 10359 10359
Condition33%1/3
defined $rel and length $rel
!ll&&!rl&&r
0010359
MC/DC0%0/2
defined $rel and length $rel
defined $rel length $rel
Truth table33%1/3
A and B
A= defined $relB= length $rel
ABresult
0X0
100
111
5026 10359 ▶ return 0 if File::Spec->file_name_is_absolute($rel);
Branch: 1 branch
BranchTrueFalseTotal
if "File::Spec"->file_name_is_absolute($rel) 0 10359 10359
5027 10359 ▶ return $rel eq '..' || $rel =~ m{\A\.\.[\\/]} ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$rel eq '..' || $rel =~ m[\A\.\.[\\/]]u ? : 10328 31 10359
Condition100%3/3
$rel eq ".." or $rel =~ m[\A\.\.[\\/]]u
l!l&&r!l&&!r
11032731
MC/DC100%2/2
$rel eq ".." or $rel =~ m[\A\.\.[\\/]]u
$rel eq ".." $rel =~ m[\A\.\.[\\/]]u
Truth table100%3/3
A or B
A= $rel eq ".."B= $rel =~ m[\A\.\.[\\/]]u
ABresult
1X1
011
000
5028 }
5029  
5030 # _calc_models_path($self) -> $path_string_or_undef
5031 #
5032 # Returns the path to .bi/models.json (creating .bi/ on first call), or undef
5033 # when the write must be skipped (data_dir safety guard, mkdir failure).
5034 9378 ▶sub _calc_models_path :Protected ($self) {
Subroutine _calc_models_path: called CC=6 SCAR=18.0
5035 9378 my $app = $self->app;
5036 9378 my $home = $app->home;
5037 9378 ▶ my $cfg_dir = $app->config('model_dir') // '.bi';
Condition50%1/2
$app->config("model_dir") // ".bi"
l!l
93780
MC/DC0%0/1
$app->config("model_dir") // ".bi"
$app->config("model_dir")
Truth table50%1/2
A
A= $app->config("model_dir")
Aresult
11
00
5038 # Support absolute paths in model_dir (e.g. when tests redirect to a temp dir).
5039 9378 ▶ my $bi_dir = Mojo::File->new($cfg_dir)->is_abs
Branch: 1 branch
BranchTrueFalseTotal
'Mojo::File'->new($cfg_dir)->is_abs ? : 9378 0 9378
5040 ? Mojo::File->new($cfg_dir)
5041 : $home->child($cfg_dir);
5042 9378 my $data_dir = _data_dir_for($app);
5043  
5044 # A store inside data_dir is refused, not created: the file would sit beside
5045 # the user's data, in a directory they chose for something else. The test is
5046 # on canonical paths, so it holds however the two are spelled -- an absolute
5047 # path, a relative one, or either of them reached through a symlink.
5048 9378 ▶ if (_inside_dir(_canonical_path($bi_dir), _canonical_path($data_dir))) {
Branch: 1 branch
BranchTrueFalseTotal
if (_inside_dir(_canonical_path($bi_dir), _canonical_path($data_dir))) 12 9366 9378
5049 12 carp 'model_dir is inside data_dir; skipping model file write';
5050 12 return undef;
5051 }
5052 9366 ▶ unless (-d $bi_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $bi_dir) 11 9355 9366
5053 mkdir $bi_dir->to_string
5054 11 ▶ or do { $app->log->warn("Cannot create $bi_dir: $!"); return undef };
Branch: 1 branch
BranchTrueFalseTotal
mkdir $bi_dir->to_string or do { $app->log->warn("Cannot create ${bi_dir}: $!"); return undef } 1 10 11
5055 }
5056 9356 return $bi_dir->child('models.json')->to_string;
5057 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5058  
5059 # _read_models($self) -> \%models
5060 #
5061 # Returns the parsed models hashref from .bi/models.json, or an empty scaffold.
5062 9017 ▶sub _read_models :Protected ($self) {
Subroutine _read_models: called CC=9 SCAR=22.0
5063 9017 my $path = $self->_calc_models_path;
5064 9017 my $scaffold = { version => 1, fields => {}, groups => {}, date_patterns => {}, lookups => {}, extractions => {}, accelerated => {} };
5065 9017 ▶ return $scaffold unless defined $path && -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and -f $path 8203 814 9017
Condition100%3/3
defined $path and -f $path
!ll&&!rl&&r
148189814
MC/DC100%2/2
defined $path and -f $path
defined $path -f $path
Truth table100%3/3
A and B
A= defined $pathB= -f $path
ABresult
0X0
100
111
5066 814 my $json = eval { Mojo::File->new($path)->slurp };
5067 814 ▶ return $scaffold unless $json && !$@;
Branch: 1 branch
BranchTrueFalseTotal
unless $json and not $@ 1 813 814
Condition66%2/3
$json and not $@
!ll&&!rl&&r
10813
MC/DC50%1/2
$json and not $@
$json not $@
Truth table66%2/3
A and not(B)
A= $jsonB= not $@
ABresult
0X0
100
111
5068 813 my $data = eval { decode_json($json) };
5069 813 ▶ return $scaffold unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 15 798 813
5070 # Callers go straight to ->{fields}{$spec}{$name}, so a hand-edited section of
5071 # the wrong shape would otherwise be a strict-refs crash on every page.
5072 798 for my $section (qw(fields groups date_patterns lookups extractions accelerated)) {
5073 4788 ▶ $data->{$section} = {} unless ref $data->{$section} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data->{$section} eq "HASH" 246 4542 4788
5074 4788 my $by_spec = $data->{$section};
5075 4788 delete @{$by_spec}{ grep { ref $by_spec->{$_} ne 'HASH' } keys %$by_spec };
5076 }
5077 798 _canonical_store_keys($data->{$_}) for grep { ref $data->{$_} eq 'HASH' }
5078 qw(fields groups date_patterns lookups extractions accelerated geo);
5079 798 return $data;
5080 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5081  
5082 # _canonical_store_keys(\%by_spec) -> void
5083 #
5084 # Purpose: File every path: entry of one section of the model store under
5085 # canonical_spec of its key, so that a reader asking with the resolved
5086 # spec finds an entry written under a symlinked spelling, by a version
5087 # before specs were resolved or by hand. The next write persists it.
5088 # Notes: A geo key is <spec>|loc=<column>; only the spec part is resolved.
5089 # When both spellings are present the resolved one's names win.
5090 5002 ▶sub _canonical_store_keys {
Subroutine _canonical_store_keys: called CC=7 SCAR=19.6
5091 5002 my ($by_spec) = @_;
5092 5002 for my $key (grep { /\Apath:/ } keys %$by_spec) {
5093 354 my ($spec, $rest) = split /\|/, $key, 2;
5094 354 ▶ my $new = canonical_spec($spec) . (defined $rest ? "|$rest" : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $rest ? : 1 353 354
5095 354 ▶ next if $new eq $key;
Branch: 1 branch
BranchTrueFalseTotal
if $new eq $key 352 2 354
5096 2 my $old = delete $by_spec->{$key};
5097 2 my $cur = $by_spec->{$new};
5098 2 ▶ $by_spec->{$new} = (ref $cur eq 'HASH' && ref $old eq 'HASH') ? { %$old, %$cur } : ($cur // $old);
Branch: 1 branch
BranchTrueFalseTotal
ref $cur eq 'HASH' && ref $old eq 'HASH' ? : 1 1 2
Condition50%3/6
ref $cur eq "HASH" and ref $old eq "HASH"
!ll&&!rl&&r
101
$cur // $old
l!l&&r!l&&!r
010
MC/DC50%1/2
ref $cur eq "HASH" and ref $old eq "HASH"
ref $cur eq "HASH" ref $old eq "HASH"
MC/DC0%0/2
$cur // $old
$cur $old
Truth table66%2/3
A and B
A= ref $cur eq "HASH"B= ref $old eq "HASH"
ABresult
0X0
100
111
Truth table33%1/3
A // B
A= $curB= $old
ABresult
1X1
011
000
5099 }
5100 5002 return;
5101 }
5102  
5103 # _write_models($self, \%models) -> $bool
5104 #
5105 # Persists models to .bi/models.json. Returns false when the store could not be
5106 # written - because the data_dir guard refused it, or because the write failed -
5107 # so a caller whose result is only an optimisation (the geocode cache: it
5108 # degrades to a per-request cache) can say so rather than pretend.
5109 133 ▶sub _write_models :Protected ($self, $models) {
Subroutine _write_models: called CC=5 SCAR=16.1
5110 133 my $path = $self->_calc_models_path;
5111 133 ▶ return 0 unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 2 131 133
5112 131 $self->_set_aside_corrupt_store($path);
5113 # Premise 1: a reader treats a file that does not parse as empty. Premise 2:
5114 # a write in place that stops half way (disk full, a killed worker) leaves
5115 # exactly such a file. Conclusion: write beside it and rename, so the store
5116 # is the old one or the new one, never a torn one (as _write_analyses does).
5117 131 my $ok = eval { _write_file_atomically($path, encode_json($models)); 1 };
5118 131 ▶ $self->app->log->warn("Cannot write $path: $@") if !$ok && $@;
Branch: 1 branch
BranchTrueFalseTotal
if not $ok and $@ 7 124 131
Condition66%2/3
not $ok and $@
!ll&&!rl&&r
12407
MC/DC50%1/2
not $ok and $@
not $ok $@
Truth table66%2/3
not(A) and B
A= not $okB= $@
ABresult
0X0
100
111
5119 131 ▶ return $ok ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 124 7 131
5120 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5121  
5122 # _write_file_atomically($path, $bytes) -> void
5123 #
5124 # Writes $bytes to a temporary file in the same folder and renames it over
5125 # $path, keeping the mode of the file it replaces. Croaks, after removing its
5126 # temporary file, when any step fails.
5127 131 ▶sub _write_file_atomically {
Subroutine _write_file_atomically: called CC=6 SCAR=17.9
5128 131 my ($path, $bytes) = @_;
5129 131 my $dir = Mojo::File->new($path)->dirname->to_string;
5130 131 my ($fh, $temp) = tempfile('.bi-store-XXXXXXXX', DIR => $dir, UNLINK => 0);
5131 128 my $ok = eval {
5132 128 binmode $fh;
5133 128 ▶ print {$fh} $bytes or croak "print: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $bytes or croak("print: $!") 128 0 128
5134 128 ▶ close $fh or croak "close: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("close: $!") 127 1 128
5135 127 ▶ my $mode = -e $path ? (stat $path)[2] & 07777 : (0666 & ~umask);
Branch: 1 branch
BranchTrueFalseTotal
-e $path ? : 88 39 127
5136 127 chmod $mode, $temp;
5137 127 ▶ rename($temp, $path) or croak "rename: $!";
Branch: 1 branch
BranchTrueFalseTotal
rename $temp, $path or croak("rename: $!") 124 3 127
5138 124 1;
5139 };
5140 128 my $why = $@;
5141 128 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 4 124 128
5142 4 unlink $temp;
5143 4 croak $why;
5144 }
5145 124 return;
5146 }
5147  
5148 # _models_lock($self) / _analyses_lock($self) -> a guard, held until it is let go
5149 #
5150 # Purpose: Make a save's read, change and write one step among the server's
5151 # worker processes. Without it two workers read the same store, each
5152 # adds its own change, and the second to write erases the first's.
5153 # Method: An exclusive flock on <store>.lock, kept for as long as the returned
5154 # guard lives (a handler writes `my $lock = $self->_models_lock;` and
5155 # the lock goes when the handler returns, or dies). A second call in
5156 # the same process, which would wait for itself, gets a guard that
5157 # holds nothing.
5158 # Failure: A lock file that cannot be opened, or a holder that does not let go
5159 # within $LOCK_WAIT_TRIES tries, is logged and the save goes ahead
5160 # unlocked: a stuck lock must not take the application down.
5161 10 Readonly my $LOCK_WAIT_TRIES => 100;
5162 10 Readonly my $LOCK_WAIT_SECONDS => 0.1;
5163 10 my %STORE_LOCKS_HELD; # path => 1 while this process holds that lock
5164  
5165 173 ▶sub _models_lock :Protected ($self) {
Subroutine _models_lock: called CC=1 SCAR=0.0
5166 173 return _store_lock($self, $self->_calc_models_path);
5167 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5168  
5169 246 ▶sub _analyses_lock :Protected ($self) {
Subroutine _analyses_lock: called CC=1 SCAR=0.0
5170 246 return _store_lock($self, $self->_analyses_path);
5171 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5172  
5173 419 ▶sub _store_lock {
Subroutine _store_lock: called CC=7 SCAR=19.5
5174 419 my ($self, $path) = @_;
5175 return bless({}, 'Database::BI::Controller::Dashboard::StoreLock')
5176 419 ▶ if !defined($path) || $STORE_LOCKS_HELD{$path};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $path or $STORE_LOCKS_HELD{$path} 2 417 419
Condition66%2/3
not defined $path or $STORE_LOCKS_HELD{$path}
l!l&&r!l&&!r
20417
MC/DC50%1/2
not defined $path or $STORE_LOCKS_HELD{$path}
not defined $path $STORE_LOCKS_HELD{$path}
Truth table66%2/3
not(A) or B
A= not defined $pathB= $STORE_LOCKS_HELD{$path}
ABresult
1X1
011
000
5177  
5178 417 my $lock_path = "$path.lock";
5179 417 my $fh;
5180 {
5181 417 local ($@, $!);
5182 10 ▶ my $opened = eval { no autodie; open($fh, '>>', $lock_path) };
Subroutine BEGIN: called CC=1 SCAR=0.0
5183 417 ▶ unless ($opened) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opened) 1 416 417
5184 1 $self->app->log->warn("Cannot open $lock_path, so saving without a lock: $!");
5185 1 return bless({}, 'Database::BI::Controller::Dashboard::StoreLock');
5186 }
5187 }
5188 416 my $locked = 0;
5189 416 for (1 .. $LOCK_WAIT_TRIES) {
5190 515 ▶ $locked = flock($fh, LOCK_EX | LOCK_NB) and last;
Branch: 1 branch
BranchTrueFalseTotal
$locked = flock($fh, 6) and last 415 100 515
5191 100 Time::HiRes::sleep($LOCK_WAIT_SECONDS);
5192 }
5193 416 ▶ unless ($locked) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($locked) 1 415 416
5194 1 $self->app->log->warn("Waited for $lock_path and gave up, so saving without it");
5195 1 return bless({}, 'Database::BI::Controller::Dashboard::StoreLock');
5196 }
5197 415 $STORE_LOCKS_HELD{$path} = 1;
5198 415 return bless({ fh => $fh, path => $path, held => \%STORE_LOCKS_HELD }, 'Database::BI::Controller::Dashboard::StoreLock');
5199 }
5200  
5201 # The guard: letting go of it unlocks and closes the file.
5202 {
5203 package Database::BI::Controller::Dashboard::StoreLock;
5204 419 ▶ sub DESTROY {
Subroutine DESTROY: called CC=2 SCAR=6.9
5205 419 my $self = shift;
5206 419 ▶ return unless $self->{fh};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"fh"} 4 415 419
5207 415 delete $self->{held}{ $self->{path} };
5208 415 flock($self->{fh}, Fcntl::LOCK_UN());
5209 415 close $self->{fh};
5210 415 return;
5211 }
5212 }
5213  
5214 # _set_aside_corrupt_store($self, $path) -> void
5215 #
5216 # Purpose: Keep a store that cannot be parsed from being overwritten. A reader
5217 # treats such a file as empty, so without this the next save would
5218 # replace every saved canvas or model with the one change it carries.
5219 # Entry: $path is the store about to be written; it need not exist.
5220 # Exit: A file holding anything but a JSON object is renamed to
5221 # <path>.corrupt.<time>, for its owner to repair.
5222 # Only a plain file: a folder (or anything else) of that name is left
5223 # where it is, and the write then fails as it should. Linux will not
5224 # read a folder, but the BSDs read its raw entries, which never parse,
5225 # so a folder was moved aside there and the write went ahead.
5226 # Side Effects: Renames the file and logs where it went.
5227 10 ▶sub _set_aside_corrupt_store :Protected ($self, $path) {
Subroutine _set_aside_corrupt_store: called CC=6 SCAR=18.0
5228 249 ▶ return unless -f $path && -s _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path and -s _ 84 165 249
Condition100%3/3
-f $path and -s _
!ll&&!rl&&r
831165
MC/DC100%2/2
-f $path and -s _
-f $path -s _
Truth table100%3/3
A and B
A= -f $pathB= -s _
ABresult
0X0
100
111
5229  
5230 165 my $json = eval { Mojo::File->new($path)->slurp };
5231 165 ▶ return unless defined $json;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $json 0 165 165
5232 165 ▶ return if ref(eval { decode_json($json) }) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref eval { do { decode_json($json) } } eq "HASH" 158 7 165
5233  
5234 7 my $aside = "$path.corrupt." . time();
5235 7 ▶ if (rename $path, $aside) {
Branch: 1 branch
BranchTrueFalseTotal
if (rename $path, $aside) { } 7 0 7
5236 7 $self->app->log->error("$path could not be parsed; kept it as $aside");
5237 } else {
5238 0 $self->app->log->error("$path could not be parsed, and could not be kept as $aside: $!");
5239 }
5240 7 return;
5241 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5242  
5243 # _analyses_path($self) -> $path_string_or_undef
5244 #
5245 # Returns the path to model_dir/analyses.json (creating model_dir on first call),
5246 # or undef when the write must be skipped (data_dir safety guard, mkdir failure).
5247 948 ▶sub _analyses_path :Protected ($self) {
Subroutine _analyses_path: called CC=7 SCAR=21.0
5248 948 my $app = $self->app;
5249 948 my $home = $app->home;
5250 948 ▶ my $cfg_dir = $app->config('model_dir') // '.bi';
Condition50%1/2
$app->config("model_dir") // ".bi"
l!l
9480
MC/DC0%0/1
$app->config("model_dir") // ".bi"
$app->config("model_dir")
Truth table50%1/2
A
A= $app->config("model_dir")
Aresult
11
00
5251 948 ▶ my $bi_dir = Mojo::File->new($cfg_dir)->is_abs
Branch: 1 branch
BranchTrueFalseTotal
'Mojo::File'->new($cfg_dir)->is_abs ? : 948 0 948
5252 ? Mojo::File->new($cfg_dir)
5253 : $home->child($cfg_dir);
5254 948 my $data_dir = _data_dir_for($app);
5255  
5256 # The same refusal as the model store, with its own message: see
5257 # _canonical_path for why the comparison is on resolved paths.
5258 948 ▶ if (_inside_dir(_canonical_path($bi_dir), _canonical_path($data_dir))) {
Branch: 1 branch
BranchTrueFalseTotal
if (_inside_dir(_canonical_path($bi_dir), _canonical_path($data_dir))) 1 947 948
5259 1 carp 'model_dir is inside data_dir; skipping analyses file write';
5260 1 return undef;
5261 }
5262 947 ▶ unless (-d $bi_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $bi_dir) 0 947 947
5263 mkdir $bi_dir->to_string
5264 0 ▶ or do { $app->log->warn("Cannot create $bi_dir: $!"); return undef };
Branch: 1 branch
BranchTrueFalseTotal
mkdir $bi_dir->to_string or do { $app->log->warn("Cannot create ${bi_dir}: $!"); return undef } 0 0 0
5265 }
5266 947 ▶ unless (-w $bi_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-w $bi_dir) 7 940 947
5267 7 carp 'model_dir is not writable; analysis storage disabled';
5268 7 return undef;
5269 }
5270 940 return $bi_dir->child('analyses.json')->to_string;
5271 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5272  
5273 # _read_analyses($self) -> \%analyses (keyed by id)
5274 527 ▶sub _read_analyses :Protected ($self) {
Subroutine _read_analyses: called CC=6 SCAR=17.9
5275 527 my $path = $self->_analyses_path;
5276 527 ▶ return {} unless defined $path && -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and -f $path 52 475 527
Condition100%3/3
defined $path and -f $path
!ll&&!rl&&r
349475
MC/DC100%2/2
defined $path and -f $path
defined $path -f $path
Truth table100%3/3
A and B
A= defined $pathB= -f $path
ABresult
0X0
100
111
5277 475 my $json = eval { Mojo::File->new($path)->slurp };
5278 475 ▶ return {} unless $json && !$@;
Branch: 1 branch
BranchTrueFalseTotal
unless $json and not $@ 1 474 475
Condition66%2/3
$json and not $@
!ll&&!rl&&r
10474
MC/DC50%1/2
$json and not $@
$json not $@
Truth table66%2/3
A and not(B)
A= $jsonB= not $@
ABresult
0X0
100
111
5279 474 my $data = eval { decode_json($json) };
5280 474 ▶ return {} unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 6 468 474
5281 468 return { map { $_ => _tidy_analysis($data->{$_}) } grep { ref $data->{$_} eq 'HASH' } keys %$data };
5282 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5283  
5284 # _tidy_analysis(\%doc) -> \%doc
5285 #
5286 # A stored canvas can hold anything: it may be hand-edited or older than a rule.
5287 # Every page that reads one goes straight to ->{visuals}[0]{encode}{cat}, so the
5288 # shape is put right here, once, and a part of the wrong shape is treated as
5289 # absent: a canvas with one bad part still shows the rest, not a 500. A visual
5290 # of the wrong shape becomes an empty one rather than going away, because a
5291 # visual's index is its identity in the layout and in /a/:id/visual/:n.
5292 622 ▶sub _tidy_analysis {
Subroutine _tidy_analysis: called CC=16 SCAR=27.7
5293 622 my $doc = $_[0];
5294  
5295 622 delete $doc->{$_} for grep { ref $doc->{$_} ne 'ARRAY' } qw(datasets visuals joins measures combines bookmarks layout hierarchies);
5296 622 delete $doc->{$_} for grep { ref $doc->{$_} ne 'HASH' } qw(fields params);
5297 622 delete $doc->{$_} for grep { ref $doc->{$_} } qw(name updated);
5298  
5299 622 ▶ if ($doc->{datasets}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($doc->{"datasets"}) 584 38 622
5300 584 ▶ $doc->{datasets} = [ grep { ref $_ eq 'HASH' && defined $_->{spec} && !ref $_->{spec} } @{ $doc->{datasets} } ];
Condition100%6/6
ref $_ eq 'HASH' && defined $_->{'spec'} && !ref($_->{'spec'})
!ll&&!rl&&r
21584
ref $_ eq "HASH" and defined $_->{"spec"}
!ll&&!rl&&r
11585
MC/DC100%3/3
ref $_ eq 'HASH' && defined $_->{'spec'} && !ref($_->{'spec'})
ref $_ eq "HASH" defined $_->{"spec"} !ref($_->{'spec'})
Truth table100%4/4
A and B && not(C)
A= ref $_ eq "HASH"B= defined $_->{"spec"}C= !ref($_->{'spec'})
ABCresult
0XX0
10X0
1100
1111
5301 584 for my $ds (@{ $doc->{datasets} }) {
5302 584 ▶ delete $ds->{filters} if ref $ds->{filters} ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $ds->{"filters"} ne "ARRAY" 583 1 584
5303 }
5304 }
5305 622 for my $key (grep { $doc->{$_} } qw(joins layout)) {
5306 20 $doc->{$key} = [ grep { ref $_ eq 'HASH' } @{ $doc->{$key} } ];
5307 }
5308 622 ▶ if ($doc->{visuals}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($doc->{"visuals"}) 420 202 622
5309 420 ▶ $doc->{visuals} = [ map { ref $_ eq 'HASH' ? $_ : {} } @{ $doc->{visuals} } ];
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 499 13 512
5310 420 _tidy_visual($_) for @{ $doc->{visuals} };
5311 }
5312 622 ▶ if ($doc->{params}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($doc->{"params"}) 17 605 622
5313 17 for my $def (values %{ $doc->{params} }) {
5314 18 ▶ $def = {} unless ref $def eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $def eq "HASH" 12 6 18
5315 }
5316 }
5317 622 return $doc;
5318 }
5319  
5320 # _tidy_visual(\%visual) -> \%visual
5321 #
5322 # The same for one card, whose parts are read as blindly as the document's.
5323 512 ▶sub _tidy_visual {
Subroutine _tidy_visual: called CC=4 SCAR=13.9
5324 512 my $vis = $_[0];
5325  
5326 512 delete $vis->{$_} for grep { ref $vis->{$_} ne 'HASH' } qw(encode options);
5327 512 ▶ delete $vis->{filters} if ref $vis->{filters} ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $vis->{"filters"} ne "ARRAY" 508 4 512
5328 512 delete $vis->{$_} for grep { ref $vis->{$_} } qw(kind title);
5329 512 return $vis;
5330 }
5331  
5332 # _write_analyses($self, \%analyses) -> 1 | 0 | nothing -- atomic write (temp + rename)
5333 # Nothing means the store is switched off (see _analyses_path).
5334 113 ▶sub _write_analyses :Protected ($self, $analyses) {
Subroutine _write_analyses: called CC=9 SCAR=23.5
5335 113 my $path = $self->_analyses_path;
5336 113 ▶ return unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 113 113
5337 113 $self->_set_aside_corrupt_store($path);
5338 113 my $dir = Mojo::File->new($path)->dirname->to_string;
5339 113 my ($fh, $tmpfile) = eval { tempfile(DIR => $dir, UNLINK => 0) };
5340 113 ▶ if ($@ || !$fh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $fh) 0 113 113
Condition33%1/3
$@ or not $fh
l!l&&r!l&&!r
00113
MC/DC0%0/2
$@ or not $fh
$@ not $fh
Truth table33%1/3
A or not(B)
A= $@B= not $fh
ABresult
1X1
011
000
5341 0 ▶ $self->app->log->warn("Cannot create temp file in $dir: " . ($@ // $!));
Condition0%0/3
$@ // $!
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ // $!
$@ $!
Truth table0%0/3
A // B
A= $@B= $!
ABresult
1X1
011
000
5342 0 return;
5343 }
5344 113 my $ok = eval {
5345 113 ▶ print {$fh} encode_json($analyses) or croak "print: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} encode_json($analyses) or croak("print: $!") 113 0 113
5346 113 ▶ close $fh or croak "close: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("close: $!") 112 1 113
5347 112 ▶ rename($tmpfile, $path) or croak "rename: $!";
Branch: 1 branch
BranchTrueFalseTotal
rename $tmpfile, $path or croak("rename: $!") 110 2 112
5348 110 1;
5349 };
5350 113 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 3 110 113
5351 3 $self->app->log->warn("Cannot write $path: $@");
5352 3 unlink $tmpfile;
5353 3 return 0;
5354 }
5355 110 return 1;
5356 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5357  
5358 # _gen_analysis_id($self) -> $id_string
5359 #
5360 # Returns a 10-character URL-safe alphanumeric random ID from the system's
5361 # random generator.
5362 10 Readonly my $ID_LENGTH => 10;
5363 10 Readonly my $_ID_CHARS => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
5364  
5365 565 ▶sub _gen_analysis_id :Protected ($self) {
Subroutine _gen_analysis_id: called CC=3 SCAR=11.0
5366 # Premise 1: perl's rand is a seeded linear generator, so its outputs can be
5367 # predicted from a few of them.
5368 # Premise 2: an id that names a canvas should not be guessable from another.
5369 # Conclusion: draw the bytes from the system's generator (Crypt::URandom, which
5370 # the password salt already needs).
5371 565 require Crypt::URandom;
5372 565 my $bytes = Crypt::URandom::urandom($ID_LENGTH);
5373 # A short answer would make a short id, and an empty one a canvas with no name.
5374 565 ▶ croak 'The system random generator gave too few bytes for an id'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes and length $bytes == $ID_LENGTH 4 561 565
Condition100%3/3
defined $bytes and length $bytes == $ID_LENGTH
!ll&&!rl&&r
13561
MC/DC100%2/2
defined $bytes and length $bytes == $ID_LENGTH
defined $bytes length $bytes == $ID_LENGTH
Truth table100%3/3
A and B
A= defined $bytesB= length $bytes == $ID_LENGTH
ABresult
0X0
100
111
5375 unless defined $bytes && length($bytes) == $ID_LENGTH;
5376 561 my $count = length $_ID_CHARS;
5377 561 return join '', map { substr($_ID_CHARS, ord($_) % $count, 1) } split //, $bytes;
5378 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5379  
5380 # The canvas is a 12-column CSS grid; a layout entry addresses cells in it.
5381 # Shared by _validate_layout and by the layout precompute in canvas_render.
5382 10 Readonly my $GRID_COLUMNS => 12;
5383  
5384 # How many grid rows one visual may span. A row is at least 15rem tall (see
5385 # grid-auto-rows in templates/web/en/canvas.html.tt), so this is also a cap on
5386 # how tall a single visual can be made from the canvas.
5387 10 Readonly my $MAX_ROW_SPAN => 6;
5388  
5389 # _save_analyses_or_503($self, \%analyses) -> $bool
5390 #
5391 # Writes the store, or answers 503 and returns false, so that no route tells a
5392 # client something was saved when it was not.
5393 106 ▶sub _save_analyses_or_503 :Protected ($self, $analyses) {
Subroutine _save_analyses_or_503: called CC=2 SCAR=6.9
5394 106 ▶ return 1 if $self->_write_analyses($analyses);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_write_analyses($analyses) 95 11 106
5395  
5396 11 $self->render(json => { error => _message_text('error_analysis_storage') }, status => 503);
5397 11 return 0;
5398 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5399  
5400 # _validate_layout($self, $layout_or_undef) -> $error_string_or_undef
5401 #
5402 # A layout entry is { visual, x, y, w, h } -- the grid position of one visual
5403 # on the canvas. The canvas PATCHes these straight out of a drag, so they are
5404 # untrusted input like every other field: reject anything that is not a whole
5405 # number of columns or rows inside the grid, rather than store a position that
5406 # renders as "span 0" or runs off the right-hand edge.
5407 108 ▶sub _validate_layout :Protected ($self, $layout) {
Subroutine _validate_layout: called CC=22 SCAR=31.0
5408 108 ▶ return undef unless defined $layout;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $layout 87 21 108
5409 21 ▶ return 'layout must be an array' unless ref $layout eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $layout eq "ARRAY" 1 20 21
5410  
5411 20 my $n = 0;
5412 20 my @placed; # the cells already spoken for, to reject an overlap
5413 20 for my $lp (@$layout) {
5414 23 $n++;
5415 23 ▶ return "layout entry $n must be a hash" unless ref $lp eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $lp eq "HASH" 2 21 23
5416 21 for my $f (qw( visual x y w h )) {
5417 94 ▶ return "layout entry $n is missing $f" unless defined $lp->{$f};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lp->{$f} 2 92 94
5418 return "layout entry $n: $f must be a whole number"
5419 92 ▶ if ref $lp->{$f} || $lp->{$f} !~ /\A\d+\z/;
Branch: 1 branch
BranchTrueFalseTotal
if ref $lp->{$f} or not $lp->{$f} =~ /\A\d+\z/u 4 88 92
Condition100%3/3
ref $lp->{$f} or not $lp->{$f} =~ /\A\d+\z/u
l!l&&r!l&&!r
1388
MC/DC100%2/2
ref $lp->{$f} or not $lp->{$f} =~ /\A\d+\z/u
ref $lp->{$f} not $lp->{$f} =~ /\A\d+\z/u
Truth table100%3/3
A or not(B)
A= ref $lp->{$f}B= not $lp->{$f} =~ /\A\d+\z/u
ABresult
1X1
011
000
5420 }
5421 return "layout entry $n: x must be between 1 and $GRID_COLUMNS"
5422 15 ▶ unless $lp->{x} >= 1 && $lp->{x} <= $GRID_COLUMNS;
Branch: 1 branch
BranchTrueFalseTotal
unless $lp->{"x"} >= 1 and $lp->{"x"} <= $GRID_COLUMNS 2 13 15
Condition100%3/3
$lp->{"x"} >= 1 and $lp->{"x"} <= $GRID_COLUMNS
!ll&&!rl&&r
1113
MC/DC100%2/2
$lp->{"x"} >= 1 and $lp->{"x"} <= $GRID_COLUMNS
$lp->{"x"} >= 1 $lp->{"x"} <= $GRID_COLUMNS
Truth table100%3/3
A and B
A= $lp->{"x"} >= 1B= $lp->{"x"} <= $GRID_COLUMNS
ABresult
0X0
100
111
5423 return "layout entry $n: y must be at least 1"
5424 13 ▶ unless $lp->{y} >= 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $lp->{"y"} >= 1 1 12 13
5425 return "layout entry $n: w must be between 1 and $GRID_COLUMNS"
5426 12 ▶ unless $lp->{w} >= 1 && $lp->{w} <= $GRID_COLUMNS;
Branch: 1 branch
BranchTrueFalseTotal
unless $lp->{"w"} >= 1 and $lp->{"w"} <= $GRID_COLUMNS 1 11 12
Condition66%2/3
$lp->{"w"} >= 1 and $lp->{"w"} <= $GRID_COLUMNS
!ll&&!rl&&r
1011
MC/DC50%1/2
$lp->{"w"} >= 1 and $lp->{"w"} <= $GRID_COLUMNS
$lp->{"w"} >= 1 $lp->{"w"} <= $GRID_COLUMNS
Truth table66%2/3
A and B
A= $lp->{"w"} >= 1B= $lp->{"w"} <= $GRID_COLUMNS
ABresult
0X0
100
111
5427 return "layout entry $n: h must be between 1 and $MAX_ROW_SPAN"
5428 11 ▶ unless $lp->{h} >= 1 && $lp->{h} <= $MAX_ROW_SPAN;
Branch: 1 branch
BranchTrueFalseTotal
unless $lp->{"h"} >= 1 and $lp->{"h"} <= $MAX_ROW_SPAN 2 9 11
Condition100%3/3
$lp->{"h"} >= 1 and $lp->{"h"} <= $MAX_ROW_SPAN
!ll&&!rl&&r
119
MC/DC100%2/2
$lp->{"h"} >= 1 and $lp->{"h"} <= $MAX_ROW_SPAN
$lp->{"h"} >= 1 $lp->{"h"} <= $MAX_ROW_SPAN
Truth table100%3/3
A and B
A= $lp->{"h"} >= 1B= $lp->{"h"} <= $MAX_ROW_SPAN
ABresult
0X0
100
111
5429 return "layout entry $n: x + w - 1 must not exceed $GRID_COLUMNS"
5430 9 ▶ if $lp->{x} + $lp->{w} - 1 > $GRID_COLUMNS;
Branch: 1 branch
BranchTrueFalseTotal
if $lp->{"x"} + $lp->{"w"} - 1 > $GRID_COLUMNS 1 8 9
5431  
5432 # Two visuals cannot hold the same cell: the canvas is a grid of positions,
5433 # and an overlapping layout renders one visual on top of another. The
5434 # canvas pushes the cards a drop lands on out of the way before it PATCHes,
5435 # so this rejects a hand-written or stale layout rather than a drag.
5436 8 for my $p (@placed) {
5437 4 ▶ next unless $p->{x} < $lp->{x} + $lp->{w} && $lp->{x} < $p->{x} + $p->{w};
Branch: 1 branch
BranchTrueFalseTotal
unless $p->{"x"} < $lp->{"x"} + $lp->{"w"} and $lp->{"x"} < $p->{"x"} + $p->{"w"} 2 2 4
Condition66%2/3
$p->{"x"} < $lp->{"x"} + $lp->{"w"} and $lp->{"x"} < $p->{"x"} + $p->{"w"}
!ll&&!rl&&r
022
MC/DC50%1/2
$p->{"x"} < $lp->{"x"} + $lp->{"w"} and $lp->{"x"} < $p->{"x"} + $p->{"w"}
$p->{"x"} < $lp->{"x"} + $lp->{"w"} $lp->{"x"} < $p->{"x"} + $p->{"w"}
Truth table66%2/3
A and B
A= $p->{"x"} < $lp->{"x"} + $lp->{"w"}B= $lp->{"x"} < $p->{"x"} + $p->{"w"}
ABresult
0X0
100
111
5438 return "layout entry $n overlaps an earlier entry"
5439 2 ▶ if $p->{y} < $lp->{y} + $lp->{h} && $lp->{y} < $p->{y} + $p->{h};
Branch: 1 branch
BranchTrueFalseTotal
if $p->{"y"} < $lp->{"y"} + $lp->{"h"} and $lp->{"y"} < $p->{"y"} + $p->{"h"} 2 0 2
Condition33%1/3
$p->{"y"} < $lp->{"y"} + $lp->{"h"} and $lp->{"y"} < $p->{"y"} + $p->{"h"}
!ll&&!rl&&r
002
MC/DC0%0/2
$p->{"y"} < $lp->{"y"} + $lp->{"h"} and $lp->{"y"} < $p->{"y"} + $p->{"h"}
$p->{"y"} < $lp->{"y"} + $lp->{"h"} $lp->{"y"} < $p->{"y"} + $p->{"h"}
Truth table33%1/3
A and B
A= $p->{"y"} < $lp->{"y"} + $lp->{"h"}B= $lp->{"y"} < $p->{"y"} + $p->{"h"}
ABresult
0X0
100
111
5440 }
5441 6 push @placed, { x => $lp->{x}, y => $lp->{y}, w => $lp->{w}, h => $lp->{h} };
5442 }
5443  
5444 3 return undef;
5445 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5446  
5447 # _validate_analysis($self, \%doc) -> $error_string_or_undef
5448 #
5449 # Structural validation of a saved-analysis document. Called on create, on
5450 # replace and on import; analyses_patch validates the keys it is given instead,
5451 # so that a PATCH of one field cannot fail because of another field it never
5452 # read.
5453 118 ▶sub _validate_analysis :Protected ($self, $doc) {
Subroutine _validate_analysis: called CC=3 SCAR=11.0
5454 118 for my $required (qw(name datasets)) {
5455 234 ▶ return "Missing required field: $required" unless defined $doc->{$required};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $doc->{$required} 5 229 234
5456 }
5457 113 return $self->_validate_analysis_parts($doc);
5458 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5459  
5460 # _drop_unknown_keys(\%doc) -> void
5461 #
5462 # Only these keys are ever read back, so anything else a client sends is not kept
5463 # on any write: the POD promises this, and a store should not grow what nothing uses.
5464 85 ▶sub _drop_unknown_keys {
Subroutine _drop_unknown_keys: called CC=1 SCAR=0.0
5465 85 my $doc = $_[0];
5466  
5467 85 delete @{$doc}{ grep { !$ANALYSIS_KEYS{$_} } keys %$doc };
5468 }
5469  
5470 # _validate_analysis_parts($self, \%doc) -> $error_string_or_undef
5471 #
5472 # Checks only the keys present, which is all a PATCH may be judged on. This body
5473 # is whatever a client sent, so nothing about the shape of a value is assumed.
5474 134 ▶sub _validate_analysis_parts :Protected ($self, $doc) {
Subroutine _validate_analysis_parts: called CC=30 SCAR=34.0
5475 134 ▶ if (exists $doc->{name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $doc->{"name"}) 120 14 134
5476 return 'Missing required field: name'
5477 120 ▶ unless defined $doc->{name} && !ref $doc->{name} && length $doc->{name};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $doc->{"name"} and not ref $doc->{"name"} and length $doc->{"name"} 7 113 120
Condition83%5/6
defined $doc->{"name"} and not ref $doc->{"name"} and length $doc->{"name"}
!ll&&!rl&&r
52113
defined $doc->{"name"} and not ref $doc->{"name"}
!ll&&!rl&&r
05115
MC/DC66%2/3
defined $doc->{"name"} and not ref $doc->{"name"} and length $doc->{"name"}
defined $doc->{"name"} not ref $doc->{"name"} length $doc->{"name"}
Truth table75%3/4
A and not(B) and C
A= defined $doc->{"name"}B= not ref $doc->{"name"}C= length $doc->{"name"}
ABCresult
0XX0
10X0
1100
1111
5478 }
5479 127 ▶ if (exists $doc->{datasets}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $doc->{"datasets"}) 108 19 127
5480 return 'Missing required field: datasets'
5481 108 ▶ unless ref $doc->{datasets} eq 'ARRAY' && @{ $doc->{datasets} };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc->{"datasets"} eq "ARRAY" and @{$doc->{"datasets"};} 3 105 108
Condition100%3/3
ref $doc->{"datasets"} eq "ARRAY" and @{$doc->{"datasets"};}
!ll&&!rl&&r
12105
MC/DC100%2/2
ref $doc->{"datasets"} eq "ARRAY" and @{$doc->{"datasets"};}
ref $doc->{"datasets"} eq "ARRAY" @{$doc->{"datasets"};}
Truth table100%3/3
A and B
A= ref $doc->{"datasets"} eq "ARRAY"B= @{$doc->{"datasets"};}
ABresult
0X0
100
111
5482 105 for my $ds (@{ $doc->{datasets} }) {
5483 return 'Each dataset entry must have a spec field'
5484 105 ▶ unless ref $ds eq 'HASH' && defined $ds->{spec} && !ref $ds->{spec} && length $ds->{spec};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ds eq "HASH" and defined $ds->{"spec"} and not ref $ds->{"spec"} and length $ds->{"spec"} 15 90 105
Condition88%8/9
ref $ds eq "HASH" and defined $ds->{"spec"} and not ref $ds->{"spec"} and length $ds->{"spec"}
!ll&&!rl&&r
15090
ref $ds eq "HASH" and defined $ds->{"spec"} and not ref $ds->{"spec"}
!ll&&!rl&&r
11490
ref $ds eq "HASH" and defined $ds->{"spec"}
!ll&&!rl&&r
10194
MC/DC75%3/4
ref $ds eq "HASH" and defined $ds->{"spec"} and not ref $ds->{"spec"} and length $ds->{"spec"}
ref $ds eq "HASH" defined $ds->{"spec"} not ref $ds->{"spec"} length $ds->{"spec"}
Truth table80%4/5
A and B and not(C) and D
A= ref $ds eq "HASH"B= defined $ds->{"spec"}C= not ref $ds->{"spec"}D= length $ds->{"spec"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
5485 return qq{"$ds->{spec}" is not a valid spec (must start with table:, path:, url:, or redis:, or be mariadb:server/table)}
5486 90 ▶ unless $ds->{spec} =~ m{\A(?:table:|path:|url:|redis:)} || $ds->{spec} =~ $MARIADB_SPEC_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $ds->{"spec"} =~ /\A(?:table:|path:|url:|redis:)/u or $ds->{"spec"} =~ /$MARIADB_SPEC_RE/u 1 89 90
Condition66%2/3
$ds->{"spec"} =~ /\A(?:table:|path:|url:|redis:)/u or $ds->{"spec"} =~ /$MARIADB_SPEC_RE/u
l!l&&r!l&&!r
8901
MC/DC50%1/2
$ds->{"spec"} =~ /\A(?:table:|path:|url:|redis:)/u or $ds->{"spec"} =~ /$MARIADB_SPEC_RE/u
$ds->{"spec"} =~ /\A(?:table:|path:|url:|redis:)/u $ds->{"spec"} =~ /$MARIADB_SPEC_RE/u
Truth table66%2/3
A or B
A= $ds->{"spec"} =~ /\A(?:table:|path:|url:|redis:)/uB= $ds->{"spec"} =~ /$MARIADB_SPEC_RE/u
ABresult
1X1
011
000
5487 }
5488 }
5489 108 ▶ if (defined $doc->{version}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $doc->{"version"}) 11 97 108
5490 return sprintf(_message_text('error_analysis_version'), $doc->{version})
5491 11 ▶ unless !ref $doc->{version} && $doc->{version} =~ /\A\d+\z/ && $doc->{version} <= 1;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $doc->{"version"} and $doc->{"version"} =~ /\A\d+\z/u and $doc->{"version"} <= 1 4 7 11
Condition100%6/6
not ref $doc->{"version"} and $doc->{"version"} =~ /\A\d+\z/u and $doc->{"version"} <= 1
!ll&&!rl&&r
227
not ref $doc->{"version"} and $doc->{"version"} =~ /\A\d+\z/u
!ll&&!rl&&r
119
MC/DC100%3/3
not ref $doc->{"version"} and $doc->{"version"} =~ /\A\d+\z/u and $doc->{"version"} <= 1
not ref $doc->{"version"} $doc->{"version"} =~ /\A\d+\z/u $doc->{"version"} <= 1
Truth table100%4/4
not(A) and B and C
A= not ref $doc->{"version"}B= $doc->{"version"} =~ /\A\d+\z/uC= $doc->{"version"} <= 1
ABCresult
0XX0
10X0
1100
1111
5492 }
5493 104 for my $key (qw( visuals joins measures combines bookmarks layout hierarchies )) {
5494 682 ▶ if (defined $doc->{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $doc->{$key}) 84 598 682
5495 return "$key must be an array"
5496 84 ▶ unless ref $doc->{$key} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc->{$key} eq "ARRAY" 12 72 84
5497 }
5498 }
5499 92 for my $key (qw( visuals joins )) {
5500 182 ▶ next unless defined $doc->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $doc->{$key} 116 66 182
5501 return "Each entry in $key must be an object"
5502 66 ▶ if grep { ref $_ ne 'HASH' } @{ $doc->{$key} };
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_ ne "HASH";} @{$$doc{$key};} 3 63 66
5503 }
5504 89 my $lerr = $self->_validate_layout($doc->{layout});
5505 89 ▶ return $lerr if $lerr;
Branch: 1 branch
BranchTrueFalseTotal
if $lerr 2 87 89
5506 87 ▶ if (defined $doc->{fields}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $doc->{"fields"}) 1 86 87
5507 return 'fields must be a hash'
5508 1 ▶ unless ref $doc->{fields} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc->{"fields"} eq "HASH" 1 0 1
5509 }
5510 86 ▶ if (defined $doc->{params}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $doc->{"params"}) 3 83 86
5511 return 'params must be a hash'
5512 3 ▶ unless ref $doc->{params} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc->{"params"} eq "HASH" 2 1 3
5513 }
5514 84 return undef;
5515 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5516  
5517 # _analysis_to_url($self, \%analysis) -> $url_string_or_undef
5518 #
5519 # Reconstructs a /join?l=...&j=...&f=... URL from a saved analysis.
5520 # Used by canvas_render to redirect when no visuals exist yet.
5521 52 ▶sub _analysis_to_url :Protected ($self, $a) {
Subroutine _analysis_to_url: called CC=18 SCAR=29.0
5522 52 ▶ my @datasets = @{ $a->{datasets} // [] };
Condition100%2/2
$a->{"datasets"} // []
l!l
484
MC/DC100%1/1
$a->{"datasets"} // []
$a->{"datasets"}
Truth table100%2/2
A
A= $a->{"datasets"}
Aresult
11
00
5523 52 ▶ return undef unless @datasets;
Branch: 1 branch
BranchTrueFalseTotal
unless @datasets 4 48 52
5524  
5525 48 ▶ my $left_spec = $datasets[0]{spec} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $left_spec = $datasets[0]{"spec"} or return undef 47 1 48
5526 47 my @params = ('l=' . url_escape($left_spec));
5527  
5528 # Build an alias->spec lookup for join resolution
5529 47 my %spec_by_alias;
5530 47 for my $ds (@datasets) {
5531 48 ▶ $spec_by_alias{ $ds->{alias} // '' } = $ds->{spec} // '';
Condition75%3/4
$ds->{"spec"} // ""
l!l
480
$ds->{"alias"} // ""
l!l
840
MC/DC0%0/1
$ds->{"spec"} // ""
$ds->{"spec"}
MC/DC100%1/1
$ds->{"alias"} // ""
$ds->{"alias"}
Truth table50%1/2
A
A= $ds->{"spec"}
Aresult
11
00
Truth table100%2/2
A
A= $ds->{"alias"}
Aresult
11
00
5532 }
5533  
5534 47 ▶ for my $j (@{ $a->{joins} // [] }) {
Condition100%2/2
$a->{"joins"} // []
l!l
344
MC/DC100%1/1
$a->{"joins"} // []
$a->{"joins"}
Truth table100%2/2
A
A= $a->{"joins"}
Aresult
11
00
5535 3 ▶ next unless ref $j eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $j eq "HASH" 1 2 3
5536 2 ▶ my $right_spec = $spec_by_alias{ $j->{right} // '' } // '';
Condition75%3/4
$spec_by_alias{$j->{"right"} // ""} // ""
l!l
11
$j->{"right"} // ""
l!l
20
MC/DC100%1/1
$spec_by_alias{$j->{"right"} // ""} // ""
$spec_by_alias{$j->{"right"} // ""}
MC/DC0%0/1
$j->{"right"} // ""
$j->{"right"}
Truth table100%2/2
A
A= $spec_by_alias{$j->{"right"} // ""}
Aresult
11
00
Truth table50%1/2
A
A= $j->{"right"}
Aresult
11
00
5537 2 ▶ next unless $right_spec;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_spec 1 1 2
5538 push @params, 'j=' . url_escape(
5539 1 ▶ join('|', $right_spec, $j->{left_key}//'', $j->{right_key}//'')
Condition50%2/4
$j->{"left_key"} // ""
l!l
10
$j->{"right_key"} // ""
l!l
10
MC/DC0%0/1
$j->{"left_key"} // ""
$j->{"left_key"}
MC/DC0%0/1
$j->{"right_key"} // ""
$j->{"right_key"}
Truth table50%1/2
A
A= $j->{"left_key"}
Aresult
11
00
Truth table50%1/2
A
A= $j->{"right_key"}
Aresult
11
00
5540 );
5541 }
5542  
5543 # Filters from all datasets
5544 47 for my $ds (@datasets) {
5545 48 ▶ next unless ref $ds->{filters} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ds->{"filters"} eq "ARRAY" 47 1 48
5546 1 for my $f (@{ $ds->{filters} }) {
5547 1 push @params, 'f=' . url_escape(encode('UTF-8', $f));
5548 }
5549 }
5550  
5551 47 return '/join?' . join('&', @params);
5552 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5553  
5554 # GET /api/analyses
5555 28 ▶sub analyses_list ($self) {
Subroutine analyses_list: called CC=1 SCAR=0.0
Pod documented
5556 28 my $analyses = $self->_read_analyses;
5557 my @list = map {
5558 28 my $a = $analyses->{$_};
5559 { id => $_, name => $a->{name}, datasets => $a->{datasets},
5560 updated => $a->{updated} }
5561 18 } sort keys %$analyses;
5562 28 $self->render(json => { analyses => \@list });
5563 }
5564  
5565 # POST /api/analyses
5566 74 ▶sub analyses_create ($self) {
Subroutine analyses_create: called CC=8 SCAR=20.9
Pod documented
5567 74 my $lock = $self->_analyses_lock; # read, change and write as one step
5568 74 my $body = eval { decode_json($self->req->body) };
5569 74 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 15 59 74
5570 unless ref $body eq 'HASH';
5571  
5572 59 my $err = $self->_validate_analysis($body);
5573 59 ▶ return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $err) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if $err 8 51 59
5574 if $err;
5575  
5576 51 my $analyses = $self->_read_analyses;
5577 51 ▶ unless ($self->_analyses_path) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_analyses_path) 2 49 51
5578 2 return $self->render(json => { error => _message_text('error_analysis_storage') }, status => 503);
5579 }
5580  
5581 49 my $id;
5582 49 my $tries = 0;
5583 49 do { $id = $self->_gen_analysis_id; $tries++ }
5584 49 ▶ while (exists $analyses->{$id} && $tries < 100);
Branch: 1 branch
BranchTrueFalseTotal
exists $analyses->{$id} and $tries < 100 and do { do { $id = $self->_gen_analysis_id; ++$tries } } 0 49 49
Condition33%1/3
exists $analyses->{$id} and $tries < 100
!ll&&!rl&&r
4900
MC/DC0%0/2
exists $analyses->{$id} and $tries < 100
exists $analyses->{$id} $tries < 100
Truth table33%1/3
A and B
A= exists $analyses->{$id}B= $tries < 100
ABresult
0X0
100
111
5585  
5586 49 $body->{id} = $id;
5587 49 ▶ $body->{version} //= 1;
Condition50%1/2
$body->{"version"} //= 1
l!l
049
MC/DC0%0/1
$body->{"version"} //= 1
$body->{"version"}
Truth table50%1/2
A
A= $body->{"version"}
Aresult
11
00
5588 49 $body->{created} = time();
5589 49 $body->{updated} = time();
5590  
5591 # Strip caller-supplied immutable fields except id/version/created/updated
5592 49 _drop_unknown_keys($body);
5593  
5594 49 $analyses->{$id} = $body;
5595 49 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 47 2 49
5596  
5597 47 $self->res->headers->location("/api/analyses/$id");
5598 47 $self->render(json => { id => $id, created => 1 }, status => 201);
5599 }
5600  
5601 # GET /api/analyses/:id
5602 66 ▶sub analyses_get ($self) {
Subroutine analyses_get: called CC=4 SCAR=13.9
Pod documented
5603 66 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
660
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5604 66 ▶ return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 4 62 66
5605 unless $id =~ /\A[A-Za-z0-9]+\z/;
5606  
5607 62 my $analyses = $self->_read_analyses;
5608 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5609 62 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 9 53 62
5610  
5611 53 $self->render(json => $analyses->{$id});
5612 }
5613  
5614 # PUT /api/analyses/:id (full replace)
5615 37 ▶sub analyses_update ($self) {
Subroutine analyses_update: called CC=9 SCAR=22.0
Pod documented
5616 37 my $lock = $self->_analyses_lock; # read, change and write as one step
5617 37 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
370
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5618 37 ▶ return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 3 34 37
5619 unless $id =~ /\A[A-Za-z0-9]+\z/;
5620  
5621 34 my $analyses = $self->_read_analyses;
5622 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5623 34 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 3 31 34
5624  
5625 31 my $body = eval { decode_json($self->req->body) };
5626 31 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 13 18 31
5627 unless ref $body eq 'HASH';
5628  
5629 18 my $err = $self->_validate_analysis($body);
5630 18 ▶ return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $err) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if $err 5 13 18
5631 if $err;
5632  
5633 13 _drop_unknown_keys($body);
5634 13 $body->{id} = $id;
5635 13 ▶ $body->{version} //= 1;
Condition50%1/2
$body->{"version"} //= 1
l!l
013
MC/DC0%0/1
$body->{"version"} //= 1
$body->{"version"}
Truth table50%1/2
A
A= $body->{"version"}
Aresult
11
00
5636 13 ▶ $body->{created} = $analyses->{$id}{created} // time();
Condition50%1/2
$analyses->{$id}{"created"} // time
l!l
130
MC/DC0%0/1
$analyses->{$id}{"created"} // time
$analyses->{$id}{"created"}
Truth table50%1/2
A
A= $analyses->{$id}{"created"}
Aresult
11
00
5637 13 $body->{updated} = time();
5638  
5639 13 $analyses->{$id} = $body;
5640 13 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 12 1 13
5641  
5642 12 $self->render(json => { id => $id, updated => 1 });
5643 }
5644  
5645 # PATCH /api/analyses/:id (partial update -- merges supplied keys)
5646 27 ▶sub analyses_patch ($self) {
Subroutine analyses_patch: called CC=10 SCAR=23.0
Pod documented
5647 27 my $lock = $self->_analyses_lock; # read, change and write as one step
5648 27 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
270
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5649 27 ▶ return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 3 24 27
5650 unless $id =~ /\A[A-Za-z0-9]+\z/;
5651  
5652 24 my $analyses = $self->_read_analyses;
5653 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5654 24 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 3 21 24
5655  
5656 21 my $body = eval { decode_json($self->req->body) };
5657 21 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 8 13 21
5658 unless ref $body eq 'HASH';
5659  
5660 # Only the keys actually supplied are validated here: the canvas PATCHes
5661 # nothing but the layout (a drag) or the bookmarks, and a document that
5662 # fails on some other field it never mentioned is not this request's fault.
5663 13 my $perr = $self->_validate_analysis_parts($body);
5664 13 ▶ return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $perr) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if $perr 5 8 13
5665 if $perr;
5666  
5667 8 _drop_unknown_keys($body);
5668 8 my $existing = { %{ $analyses->{$id} } };
5669 8 for my $key (keys %$body) {
5670 10 ▶ next if $key eq 'id' || $key eq 'created'; # immutable
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "id" or $key eq "created" 2 8 10
Condition100%3/3
$key eq "id" or $key eq "created"
l!l&&r!l&&!r
118
MC/DC100%2/2
$key eq "id" or $key eq "created"
$key eq "id" $key eq "created"
Truth table100%3/3
A or B
A= $key eq "id"B= $key eq "created"
ABresult
1X1
011
000
5671 8 $existing->{$key} = $body->{$key};
5672 }
5673 8 $existing->{updated} = time();
5674  
5675 8 $analyses->{$id} = $existing;
5676 8 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 6 2 8
5677  
5678 6 $self->render(json => { id => $id, updated => 1 });
5679 }
5680  
5681 # DELETE /api/analyses/:id
5682 21 ▶sub analyses_delete ($self) {
Subroutine analyses_delete: called CC=5 SCAR=16.1
Pod documented
5683 21 my $lock = $self->_analyses_lock; # read, change and write as one step
5684 21 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
210
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5685 21 ▶ return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 4 17 21
5686 unless $id =~ /\A[A-Za-z0-9]+\z/;
5687  
5688 17 my $analyses = $self->_read_analyses;
5689 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5690 17 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 5 12 17
5691  
5692 12 delete $analyses->{$id};
5693 12 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 10 2 12
5694  
5695 10 $self->render(json => { deleted => 1 });
5696 }
5697  
5698 # POST /api/analyses/:id/visuals (append one table or chart)
5699 #
5700 # Adds a visual to a saved canvas without sending the reader back to the table
5701 # or chart page it came from. The request is { kind, encode, options, title }
5702 # and the visual is rendered here, with the same pipeline and renderer the
5703 # canvas itself uses, before it is stored: a column that does not exist is a
5704 # 400 rather than a broken card the reader only discovers after a reload.
5705 #
5706 # The new card is deliberately left out of the saved layout. An auto-placed
5707 # card is ordered after the saved ones and stays there without pinning a
5708 # position that the next drag would have to fight; the canvas writes a layout
5709 # entry once the reader moves or resizes it.
5710 40 ▶sub analyses_add_visual ($self) {
Subroutine analyses_add_visual: called CC=35 SCAR=37.1
Pod documented
5711 40 my $lock = $self->_analyses_lock; # read, change and write as one step
5712 40 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
400
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5713 40 ▶ return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 3 37 40
5714 unless $id =~ /\A[A-Za-z0-9]+\z/;
5715  
5716 37 my $analyses = $self->_read_analyses;
5717 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5718 37 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 3 34 37
5719 34 my $a = $analyses->{$id};
5720  
5721 34 my $body = eval { decode_json($self->req->body) };
5722 34 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 8 26 34
5723 unless ref $body eq 'HASH';
5724  
5725 26 ▶ my $kind = $body->{kind} // '';
Condition50%1/2
$body->{"kind"} // ""
l!l
260
MC/DC0%0/1
$body->{"kind"} // ""
$body->{"kind"}
Truth table50%1/2
A
A= $body->{"kind"}
Aresult
11
00
5726 26 my %supported = map { $_ => 1 }
5727 qw( table bar pie line graph scatter heatmap stacked combo treemap histogram map wordcloud text );
5728 return $self->render(json => { error => 'Unsupported visual kind' }, status => 400)
5729 26 ▶ unless $supported{$kind};
Branch: 1 branch
BranchTrueFalseTotal
unless $supported{$kind} 2 24 26
5730  
5731 24 for my $key (qw( encode options cross_row )) {
5732 return $self->render(json => { error => "$key must be an object" }, status => 400)
5733 72 ▶ if defined $body->{$key} && ref $body->{$key} ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if defined $body->{$key} and ref $body->{$key} ne "HASH" 1 71 72
Condition100%3/3
defined $body->{$key} and ref $body->{$key} ne "HASH"
!ll&&!rl&&r
48231
MC/DC100%2/2
defined $body->{$key} and ref $body->{$key} ne "HASH"
defined $body->{$key} ref $body->{$key} ne "HASH"
Truth table100%3/3
A and B
A= defined $body->{$key}B= ref $body->{$key} ne "HASH"
ABresult
0X0
100
111
5734 }
5735  
5736 # A text card reads no data, so it can be added whatever state the canvas's
5737 # source is in.
5738 23 ▶ if ($kind eq 'text') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "text") 13 10 23
5739 13 my ($options, $errors) = _text_card_options($body->{options});
5740 13 ▶ return $self->render(json => { error => $errors->[0] }, status => 400) if @$errors;
Branch: 1 branch
BranchTrueFalseTotal
if @$errors 11 2 13
5741  
5742 2 my $vis = { kind => 'text', encode => {}, options => $options };
5743 $vis->{title} = $body->{title}
5744 2 ▶ if defined $body->{title} && !ref $body->{title} && length $body->{title};
Branch: 1 branch
BranchTrueFalseTotal
if defined $body->{"title"} and not ref $body->{"title"} and length $body->{"title"} 0 2 2
Condition33%2/6
defined $body->{"title"} and not ref $body->{"title"} and length $body->{"title"}
!ll&&!rl&&r
200
defined $body->{"title"} and not ref $body->{"title"}
!ll&&!rl&&r
200
MC/DC0%0/3
defined $body->{"title"} and not ref $body->{"title"} and length $body->{"title"}
defined $body->{"title"} not ref $body->{"title"} length $body->{"title"}
Truth table25%1/4
A and not(B) and C
A= defined $body->{"title"}B= not ref $body->{"title"}C= length $body->{"title"}
ABCresult
0XX0
10X0
1100
1111
5745  
5746 2 ▶ my $index = scalar @{ $a->{visuals} // [] };
Condition50%1/2
$a->{"visuals"} // []
l!l
20
MC/DC0%0/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table50%1/2
A
A= $a->{"visuals"}
Aresult
11
00
5747 2 ▶ push @{ $a->{visuals} //= [] }, $vis;
Condition50%1/2
$a->{"visuals"} //= []
l!l
20
MC/DC0%0/1
$a->{"visuals"} //= []
$a->{"visuals"}
Truth table50%1/2
A
A= $a->{"visuals"}
Aresult
11
00
5748 2 $a->{updated} = time();
5749 2 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 2 0 2
5750  
5751 2 return $self->render(json => _text_card_reply($id, $index, $vis), status => 201);
5752 }
5753  
5754 my $vis = {
5755 kind => $kind,
5756 encode => ($body->{encode} // {}),
5757 10 ▶ options => ($body->{options} // {}),
Condition75%3/4
$body->{"encode"} // {}
l!l
91
$body->{"options"} // {}
l!l
010
MC/DC100%1/1
$body->{"encode"} // {}
$body->{"encode"}
MC/DC0%0/1
$body->{"options"} // {}
$body->{"options"}
Truth table100%2/2
A
A= $body->{"encode"}
Aresult
11
00
Truth table50%1/2
A
A= $body->{"options"}
Aresult
11
00
5758 };
5759  
5760 # A card may bring a cross-row plan of its own; it is stored in the same
5761 # spelling cs=/by=/order= use -- { cs => [...], by => '...', order => [...] }
5762 # -- so the pass reads it through the one parser, with the page's plan left
5763 # out of it. Only the shape is checked here: which columns exist is a fact
5764 # about the data file, and it is checked again on every render for the same
5765 # reason a saved canvas is.
5766 10 ▶ if (my $raw = $body->{cross_row}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $raw = $body->{"cross_row"}) 1 9 10
5767 1 my $plan = _card_plan($raw);
5768 return $self->render(json => { error => $plan->{error} }, status => 400)
5769 1 ▶ if $plan->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $plan->{"error"} 1 0 1
5770 0 $vis->{cross_row} = $plan;
5771 }
5772  
5773 $vis->{title} = $body->{title}
5774 9 ▶ if defined $body->{title} && !ref $body->{title} && length $body->{title};
Branch: 1 branch
BranchTrueFalseTotal
if defined $body->{"title"} and not ref $body->{"title"} and length $body->{"title"} 3 6 9
Condition66%4/6
defined $body->{"title"} and not ref $body->{"title"} and length $body->{"title"}
!ll&&!rl&&r
603
defined $body->{"title"} and not ref $body->{"title"}
!ll&&!rl&&r
603
MC/DC33%1/3
defined $body->{"title"} and not ref $body->{"title"} and length $body->{"title"}
defined $body->{"title"} not ref $body->{"title"} length $body->{"title"}
Truth table50%2/4
A and not(B) and C
A= defined $body->{"title"}B= not ref $body->{"title"}C= length $body->{"title"}
ABCresult
0XX0
10X0
1100
1111
5775  
5776 # The card is added without a page reload, so the canvas's own URL state has
5777 # to come with the request: a reader who adds a card while a chart is
5778 # cross-filtering the canvas, with calculated columns on the URL, or with a
5779 # what-if parameter set, gets a card drawn like the ones beside it rather
5780 # than against the unfiltered table.
5781 9 my $ctx = $self->_canvas_render_context($a, $body->{query}, [$vis]);
5782 return $self->render(json => { error => $ctx->{error} }, status => $ctx->{status})
5783 9 ▶ if $ctx->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"error"} 2 7 9
5784  
5785 # The new card is never the cross-filter source: it did not exist when the
5786 # filter was made, so every cf applies to it, as it does to every card but
5787 # the source.
5788 7 my ($records, $late_cf) = $self->_canvas_cross_filter($ctx->{records}, $ctx->{columns}, $ctx->{cf_specs});
5789  
5790 # The index is known before the render, so the card's SVG and Leaflet ids
5791 # match the ones a later page load will give it.
5792 7 ▶ my $index = scalar @{ $a->{visuals} // [] };
Condition100%2/2
$a->{"visuals"} // []
l!l
52
MC/DC100%1/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
5793  
5794 my $rendered = $self->_render_visual_html(
5795 $vis, $records, $ctx->{columns}, $ctx->{src}, $index, $ctx->{spec_key},
5796 7 (@{ $ctx->{cf_specs} } ? 1 : 0),
5797 $ctx->{cross_row},
5798 7 ▶ $late_cf,
Branch: 1 branch
BranchTrueFalseTotal
@{$ctx->{'cf_specs'};} ? : 0 7 7
5799 );
5800 return $self->render(json => { error => $rendered->{error} }, status => 400)
5801 7 ▶ if $rendered->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $rendered->{"error"} 2 5 7
5802  
5803 5 ▶ push @{ $a->{visuals} //= [] }, $vis;
Condition100%2/2
$a->{"visuals"} //= []
l!l
32
MC/DC100%1/1
$a->{"visuals"} //= []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
5804 5 $a->{updated} = time();
5805 5 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 4 1 5
5806  
5807 return $self->render(
5808 json => {
5809 id => $id,
5810 visual => $index,
5811 kind => $kind,
5812 title => ($vis->{title} // $rendered->{title} // 'Visual ' . ($index + 1)),
5813 html => $rendered->{html},
5814 4 ▶ head => ($rendered->{head} // ''),
Condition55%5/9
($vis->{"title"} // $rendered->{"title"}) // 'Visual ' . ($index + 1)
l!l
40
$vis->{"title"} // $rendered->{"title"}
l!l&&r!l&&!r
310
$rendered->{"head"} // ""
l!l
04
_vis_cf_col($vis) // ""
l!l
40
MC/DC0%0/2
($vis->{"title"} // $rendered->{"title"}) // 'Visual ' . ($index + 1)
$vis->{"title"} $rendered->{"title"}
MC/DC0%0/1
$rendered->{"head"} // ""
$rendered->{"head"}
MC/DC0%0/1
_vis_cf_col($vis) // ""
_vis_cf_col($vis)
Truth table66%2/3
A // B
A= $vis->{"title"}B= $rendered->{"title"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $rendered->{"head"}
Aresult
11
00
Truth table50%1/2
A
A= _vis_cf_col($vis)
Aresult
11
00
5815 # The nonce the card's scripts were written with: the page runs
5816 # only those that carry it (runCardScripts in canvas.html.tt).
5817 nonce => $self->csp_nonce,
5818 # The column a chart's marks filter by, so the card appended in
5819 # place is a cross-filter control like the cards around it.
5820 cf_col => (_vis_cf_col($vis) // ''),
5821 },
5822 status => 201,
5823 );
5824 }
5825  
5826 # PATCH /api/analyses/:id/visuals/:visual (change a saved visual's columns)
5827 #
5828 # A map card that plotted the wrong column should not have to be deleted and
5829 # added again: the visual keeps its index - and with it its place in the
5830 # layout, its size, its title and the Leaflet ids a re-render reuses - while
5831 # its C<encode> is replaced. Like the append above, the replacement is drawn
5832 # before it is stored, so an unknown column is a 400 and the saved visual is
5833 # left alone. The optional C<query> is the canvas page's URL state, so a card
5834 # edited while the canvas is cross-filtered is redrawn with the others.
5835 #
5836 # C<cross_row> is repaired the same way, and on the same request: a card's plan
5837 # is stored data like its columns, so a card that was saved with a plan this
5838 # canvas cannot honour - or with none where one is now wanted - is fixed in
5839 # place, keeping its layout slot, its size and its title. The two keys are
5840 # independent, so a repair that renames the column the pass produces writes
5841 # both in one request rather than leaving the card drawn against a column that
5842 # no longer exists. A JSON C<null> is the card giving up its plan and taking
5843 # the page's again, which is the state a card added without one is in; an
5844 # empty plan (C<{ cs => [] }>) is the card running no pass even where the page
5845 # runs one, and leaving the key out is no request to change it at all.
5846 12 ▶sub analyses_update_visual ($self) {
Subroutine analyses_update_visual: called CC=34 SCAR=45.4
Pod documented
5847 12 my $lock = $self->_analyses_lock; # read, change and write as one step
5848 12 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
120
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5849 12 ▶ return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 0 12 12
5850 unless $id =~ /\A[A-Za-z0-9]+\z/;
5851  
5852 12 my $analyses = $self->_read_analyses;
5853 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5854 12 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 1 11 12
5855 11 my $a = $analyses->{$id};
5856  
5857 11 ▶ my $index = $self->stash('visual') // '';
Condition50%1/2
$self->stash("visual") // ""
l!l
110
MC/DC0%0/1
$self->stash("visual") // ""
$self->stash("visual")
Truth table50%1/2
A
A= $self->stash("visual")
Aresult
11
00
5858 11 ▶ return $self->render(json => { error => 'Visual index must be a number' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $index =~ /\A\d+\z/u 2 9 11
5859 unless $index =~ /\A\d+\z/;
5860 9 $index += 0;
5861 return $self->render(json => { error => "No visual at index $index" }, status => 404)
5862 9 ▶ unless $index < scalar @{ $a->{visuals} // [] };
Branch: 1 branch
BranchTrueFalseTotal
unless $index < scalar @{$a->{"visuals"} // [];} 2 7 9
Condition50%1/2
$a->{"visuals"} // []
l!l
90
MC/DC0%0/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table50%1/2
A
A= $a->{"visuals"}
Aresult
11
00
5863  
5864 7 my $body = eval { decode_json($self->req->body) };
5865 7 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 1 6 7
5866 unless ref $body eq 'HASH';
5867  
5868 # A text card's only settings are its options, and it reads no data.
5869 6 ▶ if (($a->{visuals}[$index]{kind} // '') eq 'text') {
Branch: 1 branch
BranchTrueFalseTotal
if (($a->{"visuals"}[$index]{"kind"} // "") eq "text") 2 4 6
Condition50%1/2
$a->{"visuals"}[$index]{"kind"} // ""
l!l
60
MC/DC0%0/1
$a->{"visuals"}[$index]{"kind"} // ""
$a->{"visuals"}[$index]{"kind"}
Truth table50%1/2
A
A= $a->{"visuals"}[$index]{"kind"}
Aresult
11
00
5870 return $self->render(json => { error => _message_text('error_text_card_columns') }, status => 400)
5871 2 ▶ if exists $body->{encode} || exists $body->{cross_row};
Branch: 1 branch
BranchTrueFalseTotal
if exists $body->{"encode"} or exists $body->{"cross_row"} 1 1 2
Condition66%2/3
exists $body->{"encode"} or exists $body->{"cross_row"}
l!l&&r!l&&!r
101
MC/DC50%1/2
exists $body->{"encode"} or exists $body->{"cross_row"}
exists $body->{"encode"} exists $body->{"cross_row"}
Truth table66%2/3
A or B
A= exists $body->{"encode"}B= exists $body->{"cross_row"}
ABresult
1X1
011
000
5872 return $self->render(json => { error => _message_text('error_text_card_options') }, status => 400)
5873 1 ▶ unless ref $body->{options} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body->{"options"} eq "HASH" 1 0 1
5874  
5875 0 my ($options, $errors) = _text_card_options($body->{options});
5876 0 ▶ return $self->render(json => { error => $errors->[0] }, status => 400) if @$errors;
Branch: 1 branch
BranchTrueFalseTotal
if @$errors 0 0 0
5877  
5878 0 my $vis = { %{ $a->{visuals}[$index] }, options => $options };
5879 0 $a->{visuals}[$index] = $vis;
5880 0 $a->{updated} = time();
5881 0 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 0 0 0
5882  
5883 0 return $self->render(json => _text_card_reply($id, $index, $vis));
5884 }
5885  
5886 4 my $has_encode = exists $body->{encode};
5887 4 my $has_plan = exists $body->{cross_row};
5888 4 ▶ return $self->render(json => { error => 'encode or cross_row must be given' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $has_encode or $has_plan 1 3 4
Condition66%2/3
$has_encode or $has_plan
l!l&&r!l&&!r
301
MC/DC50%1/2
$has_encode or $has_plan
$has_encode $has_plan
Truth table66%2/3
A or B
A= $has_encodeB= $has_plan
ABresult
1X1
011
000
5889 unless $has_encode || $has_plan;
5890  
5891 3 my $vis = { %{ $a->{visuals}[$index] } };
5892  
5893 3 ▶ if ($has_encode) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_encode) 3 0 3
5894 return $self->render(json => { error => 'encode must be an object' }, status => 400)
5895 3 ▶ unless ref $body->{encode} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body->{"encode"} eq "HASH" 0 3 3
5896 3 $vis->{encode} = { %{ $body->{encode} } };
5897 }
5898  
5899 3 ▶ if ($has_plan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_plan) 0 3 3
5900 0 ▶ if (defined $body->{cross_row}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $body->{'cross_row'}) { } 0 0 0
5901 return $self->render(json => { error => 'cross_row must be an object or null' }, status => 400)
5902 0 ▶ unless ref $body->{cross_row} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body->{"cross_row"} eq "HASH" 0 0 0
5903 0 my $plan = _card_plan($body->{cross_row});
5904 return $self->render(json => { error => $plan->{error} }, status => 400)
5905 0 ▶ if $plan->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $plan->{"error"} 0 0 0
5906 0 $vis->{cross_row} = $plan;
5907 }
5908 else {
5909 0 delete $vis->{cross_row};
5910 }
5911 }
5912  
5913 3 my $ctx = $self->_canvas_render_context($a, $body->{query}, [$vis]);
5914 return $self->render(json => { error => $ctx->{error} }, status => $ctx->{status})
5915 3 ▶ if $ctx->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"error"} 0 3 3
5916  
5917 # The card is drawn as it is on this page: a cross-filter applies to every
5918 # card but the one that made it, and this card may be that one.
5919 3 my $records = $ctx->{records};
5920 3 my $prefiltered = 0;
5921 3 my $late_cf = [];
5922 3 ▶ if (@{ $ctx->{cf_specs} } && $ctx->{cf_source} != $index) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ctx->{"cf_specs"};} and $ctx->{"cf_source"} != $index) 0 3 3
Condition33%1/3
@{$ctx->{"cf_specs"};} and $ctx->{"cf_source"} != $index
!ll&&!rl&&r
300
MC/DC0%0/2
@{$ctx->{"cf_specs"};} and $ctx->{"cf_source"} != $index
@{$ctx->{"cf_specs"};} $ctx->{"cf_source"} != $index
Truth table33%1/3
A and B
A= @{$ctx->{"cf_specs"};}B= $ctx->{"cf_source"} != $index
ABresult
0X0
100
111
5923 0 ($records, $late_cf) = $self->_canvas_cross_filter($records, $ctx->{columns}, $ctx->{cf_specs});
5924 0 $prefiltered = 1;
5925 }
5926  
5927 my $rendered = $self->_render_visual_html(
5928 $vis, $records, $ctx->{columns}, $ctx->{src}, $index, $ctx->{spec_key},
5929 $prefiltered,
5930 $ctx->{cross_row},
5931 3 $late_cf,
5932 );
5933 return $self->render(json => { error => $rendered->{error} }, status => 400)
5934 3 ▶ if $rendered->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $rendered->{"error"} 0 3 3
5935  
5936 3 $a->{visuals}[$index] = $vis;
5937 3 $a->{updated} = time();
5938 3 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 2 1 3
5939  
5940 return $self->render(
5941 json => {
5942 id => $id,
5943 visual => $index,
5944 kind => ($vis->{kind} // ''),
5945 title => ($vis->{title} // $rendered->{title} // 'Visual ' . ($index + 1)),
5946 html => $rendered->{html},
5947 2 ▶ head => ($rendered->{head} // ''),
Condition54%6/11
$vis->{"kind"} // ""
l!l
20
($vis->{"title"} // $rendered->{"title"}) // 'Visual ' . ($index + 1)
l!l
20
$vis->{"title"} // $rendered->{"title"}
l!l&&r!l&&!r
110
$rendered->{"head"} // ""
l!l
02
_vis_cf_col($vis) // ""
l!l
20
MC/DC0%0/1
$vis->{"kind"} // ""
$vis->{"kind"}
MC/DC0%0/2
($vis->{"title"} // $rendered->{"title"}) // 'Visual ' . ($index + 1)
$vis->{"title"} $rendered->{"title"}
MC/DC0%0/1
$rendered->{"head"} // ""
$rendered->{"head"}
MC/DC0%0/1
_vis_cf_col($vis) // ""
_vis_cf_col($vis)
Truth table50%1/2
A
A= $vis->{"kind"}
Aresult
11
00
Truth table66%2/3
A // B
A= $vis->{"title"}B= $rendered->{"title"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $rendered->{"head"}
Aresult
11
00
Truth table50%1/2
A
A= _vis_cf_col($vis)
Aresult
11
00
5948 # The nonce the card's scripts were written with: the page runs
5949 # only those that carry it (runCardScripts in canvas.html.tt).
5950 nonce => $self->csp_nonce,
5951 cf_col => (_vis_cf_col($vis) // ''),
5952 },
5953 );
5954 }
5955  
5956 # DELETE /api/analyses/:id/visuals/:visual (remove a text card)
5957 #
5958 # A visual's index is its identity in the layout and in a cross-filter's cv=, so
5959 # everything that names a later card moves down by one with it. The page reloads
5960 # afterwards, because the cards on screen carry the old numbers.
5961 8 ▶sub analyses_delete_visual ($self) {
Subroutine analyses_delete_visual: called CC=22 SCAR=32.1
Pod documented
5962 8 my $lock = $self->_analyses_lock; # read, change and write as one step
5963 8 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
80
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5964 8 ▶ return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 0 8 8
5965 unless $id =~ /\A[A-Za-z0-9]+\z/;
5966  
5967 8 my $analyses = $self->_read_analyses;
5968 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5969 8 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 1 7 8
5970 7 my $a = $analyses->{$id};
5971  
5972 7 ▶ my $index = $self->stash('visual') // '';
Condition50%1/2
$self->stash("visual") // ""
l!l
70
MC/DC0%0/1
$self->stash("visual") // ""
$self->stash("visual")
Truth table50%1/2
A
A= $self->stash("visual")
Aresult
11
00
5973 7 ▶ return $self->render(json => { error => 'Visual index must be a number' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $index =~ /\A\d+\z/u 1 6 7
5974 unless $index =~ /\A\d+\z/;
5975 6 $index += 0;
5976 return $self->render(json => { error => "No visual at index $index" }, status => 404)
5977 6 ▶ unless $index < scalar @{ $a->{visuals} // [] };
Branch: 1 branch
BranchTrueFalseTotal
unless $index < scalar @{$a->{"visuals"} // [];} 1 5 6
Condition50%1/2
$a->{"visuals"} // []
l!l
60
MC/DC0%0/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table50%1/2
A
A= $a->{"visuals"}
Aresult
11
00
5978 return $self->render(json => { error => _message_text('error_visual_not_text') }, status => 400)
5979 5 ▶ unless ($a->{visuals}[$index]{kind} // '') eq 'text';
Branch: 1 branch
BranchTrueFalseTotal
unless ($a->{"visuals"}[$index]{"kind"} // "") eq "text" 2 3 5
Condition50%1/2
$a->{"visuals"}[$index]{"kind"} // ""
l!l
50
MC/DC0%0/1
$a->{"visuals"}[$index]{"kind"} // ""
$a->{"visuals"}[$index]{"kind"}
Truth table50%1/2
A
A= $a->{"visuals"}[$index]{"kind"}
Aresult
11
00
5980  
5981 3 $a->{visuals} = [ @{ $a->{visuals} }[ grep { $_ != $index } 0 .. $#{ $a->{visuals} } ] ];
5982  
5983 3 my @layout;
5984 3 ▶ for my $entry (@{ $a->{layout} // [] }) {
Condition100%2/2
$a->{"layout"} // []
l!l
12
MC/DC100%1/1
$a->{"layout"} // []
$a->{"layout"}
Truth table100%2/2
A
A= $a->{"layout"}
Aresult
11
00
5985 2 ▶ my $n = $entry->{visual} // '';
Condition50%1/2
$entry->{"visual"} // ""
l!l
20
MC/DC0%0/1
$entry->{"visual"} // ""
$entry->{"visual"}
Truth table50%1/2
A
A= $entry->{"visual"}
Aresult
11
00
5986 2 ▶ if ($n =~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n =~ /\A\d+\z/u) 2 0 2
5987 2 ▶ next if $n == $index;
Branch: 1 branch
BranchTrueFalseTotal
if $n == $index 1 1 2
5988 1 ▶ $entry = { %$entry, visual => $n - 1 } if $n > $index;
Branch: 1 branch
BranchTrueFalseTotal
if $n > $index 0 1 1
5989 }
5990 1 push @layout, $entry;
5991 }
5992 3 ▶ $a->{layout} = \@layout if $a->{layout};
Branch: 1 branch
BranchTrueFalseTotal
if $a->{"layout"} 1 2 3
5993  
5994 3 ▶ for my $bm (grep { ref $_ eq 'HASH' && defined $_->{state} && !ref $_->{state} } @{ $a->{bookmarks} // [] }) {
Condition50%4/8
ref $_ eq 'HASH' && defined $_->{'state'} && !ref($_->{'state'})
!ll&&!rl&&r
002
ref $_ eq "HASH" and defined $_->{"state"}
!ll&&!rl&&r
002
$a->{"bookmarks"} // []
l!l
21
MC/DC0%0/3
ref $_ eq 'HASH' && defined $_->{'state'} && !ref($_->{'state'})
ref $_ eq "HASH" defined $_->{"state"} !ref($_->{'state'})
MC/DC100%1/1
$a->{"bookmarks"} // []
$a->{"bookmarks"}
Truth table25%1/4
A and B && not(C)
A= ref $_ eq "HASH"B= defined $_->{"state"}C= !ref($_->{'state'})
ABCresult
0XX0
10X0
1100
1111
Truth table100%2/2
A
A= $a->{"bookmarks"}
Aresult
11
00
5995 2 $bm->{state} = _shift_card_param($bm->{state}, $index);
5996 }
5997  
5998 3 $a->{updated} = time();
5999 3 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 3 0 3
6000  
6001 3 return $self->render(json => { deleted => 1 });
6002 }
6003  
6004 # _shift_card_param($search, $removed) -> $search
6005 #
6006 # A saved query string with its cv= moved down if the card it names came after
6007 # the one removed. The canvas never makes a text card a cross-filter's source,
6008 # but a bookmark is stored as PATCHed, so a cv= naming the removed card is
6009 # dropped: kept, it would name the card that moved into its place. A cv= of
6010 # more than nine digits names no card (_cross_filter_source), so it is left
6011 # as it is: arithmetic on it came back as cv=1e+20. A search or index that is
6012 # not one is returned unchanged.
6013 32 ▶sub _shift_card_param {
Subroutine _shift_card_param: called CC=9 SCAR=22.0
6014 32 my ($search, $removed) = @_;
6015 32 ▶ return $search unless defined($search) && !ref($search)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $search and not ref $search and defined $removed and not ref $removed and $removed =~ /\A[0-9]{1,9}\z/u 7 25 32
Condition100%12/12
defined $search and not ref $search and defined $removed and not ref $removed and $removed =~ /\A[0-9]{1,9}\z/u
!ll&&!rl&&r
4325
defined $search and not ref $search and defined $removed and not ref $removed
!ll&&!rl&&r
3128
defined $search and not ref $search and defined $removed
!ll&&!rl&&r
2129
defined $search and not ref $search
!ll&&!rl&&r
1130
MC/DC100%5/5
defined $search and not ref $search and defined $removed and not ref $removed and $removed =~ /\A[0-9]{1,9}\z/u
defined $search not ref $search defined $removed not ref $removed $removed =~ /\A[0-9]{1,9}\z/u
Truth table100%6/6
A and not(B) and C and not(D) and E
A= defined $searchB= not ref $searchC= defined $removedD= not ref $removedE= $removed =~ /\A[0-9]{1,9}\z/u
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
6016 && defined($removed) && !ref($removed) && $removed =~ /\A[0-9]{1,9}\z/;
6017 25 $search =~ s{(?<![^?&])cv=(\d+)(&?)}{
6018 20019 ▶ length($1) > 9 ? "cv=$1$2"
Branch: 3 branches
BranchTrueFalseTotal
length $1 > 9 ? : 2 20017 20019
$1 == $removed ? : 6 20011 20017
$1 > $removed ? : 20009 2 20011
6019 : $1 == $removed ? ''
6020 : ('cv=' . ($1 > $removed ? $1 - 1 : $1) . $2)
6021 }ge;
6022 25 $search =~ s{&\z}{};
6023 25 return $search;
6024 }
6025  
6026 # _text_card_options($raw) -> (\%options, \@errors)
6027 #
6028 # Purpose: The one reader of a text card's settings.
6029 # Entry: Whatever is stored or was sent; it may be any shape.
6030 # Exit: The settings that are allowed, each in its one spelling, and a message
6031 # for each that was not. Settings not asked for are absent.
6032 # Notes: A write refuses a card with errors. A render ignores them and draws
6033 # what is left, because PUT, PATCH and import can store a card that
6034 # never came through here, and nothing else stands between a stored
6035 # value and a style attribute.
6036 51 ▶sub _text_card_options {
Subroutine _text_card_options: called CC=27 SCAR=33.0
6037 51 my ($raw) = @_;
6038 51 ▶ $raw = {} unless ref $raw eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw eq "HASH" 5 46 51
6039  
6040 51 my (%clean, @errors);
6041  
6042 51 ▶ my $text = (defined $raw->{text} && !ref $raw->{text}) ? $raw->{text} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $raw->{'text'} && !ref($raw->{'text'}) ? : 45 6 51
Condition100%3/3
defined $raw->{"text"} and not ref $raw->{"text"}
!ll&&!rl&&r
5145
MC/DC100%2/2
defined $raw->{"text"} and not ref $raw->{"text"}
defined $raw->{"text"} not ref $raw->{"text"}
Truth table100%3/3
A and not(B)
A= defined $raw->{"text"}B= not ref $raw->{"text"}
ABresult
0X0
100
111
6043 51 $text =~ s/\r\n?/\n/g;
6044 51 ▶ if ($text !~ /\S/) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $text =~ /\S/u) { } 9 42 51
elsif (length $text > $MAX_TEXT_CHARS) { } 2 40 42
6045 9 push @errors, _message_text('error_text_card_empty');
6046 }
6047 elsif (length($text) > $MAX_TEXT_CHARS) {
6048 2 push @errors, sprintf(_message_text('error_text_card_long'), $MAX_TEXT_CHARS);
6049 }
6050 51 $clean{text} = $text;
6051  
6052 51 ▶ if (length(my $font = $raw->{font} // '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (length(my $font = $raw->{"font"} // "")) 6 45 51
Condition100%2/2
$raw->{"font"} // ""
l!l
645
MC/DC100%1/1
$raw->{"font"} // ""
$raw->{"font"}
Truth table100%2/2
A
A= $raw->{"font"}
Aresult
11
00
6053 6 ▶ if (!ref $font && exists $TEXT_FONT_CSS{$font}) { $clean{font} = $font }
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $font and exists $TEXT_FONT_CSS{$font}) { } 2 4 6
Condition100%3/3
not ref $font and exists $TEXT_FONT_CSS{$font}
!ll&&!rl&&r
132
MC/DC100%2/2
not ref $font and exists $TEXT_FONT_CSS{$font}
not ref $font exists $TEXT_FONT_CSS{$font}
Truth table100%3/3
not(A) and B
A= not ref $fontB= exists $TEXT_FONT_CSS{$font}
ABresult
0X0
100
111
6054 4 else { push @errors, _message_text('error_text_card_font') }
6055 }
6056  
6057 51 ▶ if (length(my $size = $raw->{size} // '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (length(my $size = $raw->{"size"} // "")) 9 42 51
Condition100%2/2
$raw->{"size"} // ""
l!l
942
MC/DC100%1/1
$raw->{"size"} // ""
$raw->{"size"}
Truth table100%2/2
A
A= $raw->{"size"}
Aresult
11
00
6058 9 ▶ if (!ref $size && $size =~ /\A\d{1,3}\z/ && $size >= $MIN_TEXT_POINTS && $size <= $MAX_TEXT_POINTS) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $size and $size =~ /\A\d{1,3}\z/u and $size >= $MIN_TEXT_POINTS and $size <= $MAX_TEXT_POINTS) { } 1 8 9
Condition100%9/9
not ref $size and $size =~ /\A\d{1,3}\z/u and $size >= $MIN_TEXT_POINTS and $size <= $MAX_TEXT_POINTS
!ll&&!rl&&r
711
not ref $size and $size =~ /\A\d{1,3}\z/u and $size >= $MIN_TEXT_POINTS
!ll&&!rl&&r
522
not ref $size and $size =~ /\A\d{1,3}\z/u
!ll&&!rl&&r
144
MC/DC100%4/4
not ref $size and $size =~ /\A\d{1,3}\z/u and $size >= $MIN_TEXT_POINTS and $size <= $MAX_TEXT_POINTS
not ref $size $size =~ /\A\d{1,3}\z/u $size >= $MIN_TEXT_POINTS $size <= $MAX_TEXT_POINTS
Truth table100%5/5
not(A) and B and C and D
A= not ref $sizeB= $size =~ /\A\d{1,3}\z/uC= $size >= $MIN_TEXT_POINTSD= $size <= $MAX_TEXT_POINTS
ABCDresult
0XXX0
10XX0
110X0
11100
11111
6059 1 $clean{size} = $size + 0;
6060 }
6061 else {
6062 8 push @errors, sprintf(_message_text('error_text_card_size'), $MIN_TEXT_POINTS, $MAX_TEXT_POINTS);
6063 }
6064 }
6065  
6066 51 for my $key (qw(colour background)) {
6067 102 ▶ my $value = $raw->{$key} // '';
Condition100%2/2
$raw->{$key} // ""
l!l
1290
MC/DC100%1/1
$raw->{$key} // ""
$raw->{$key}
Truth table100%2/2
A
A= $raw->{$key}
Aresult
11
00
6068 102 ▶ next unless length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless length $value 90 12 102
6069 12 ▶ if (!ref $value && $value =~ /\A#[0-9a-fA-F]{6}\z/) { $clean{$key} = lc $value }
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $value and $value =~ /\A#[0-9a-fA-F]{6}\z/u) { } 2 10 12
Condition100%3/3
not ref $value and $value =~ /\A#[0-9a-fA-F]{6}\z/u
!ll&&!rl&&r
192
MC/DC100%2/2
not ref $value and $value =~ /\A#[0-9a-fA-F]{6}\z/u
not ref $value $value =~ /\A#[0-9a-fA-F]{6}\z/u
Truth table100%3/3
not(A) and B
A= not ref $valueB= $value =~ /\A#[0-9a-fA-F]{6}\z/u
ABresult
0X0
100
111
6070 10 else { push @errors, _message_text('error_text_card_colour') }
6071 }
6072  
6073 51 ▶ if (length(my $align = $raw->{align} // '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (length(my $align = $raw->{"align"} // "")) 3 48 51
Condition100%2/2
$raw->{"align"} // ""
l!l
348
MC/DC100%1/1
$raw->{"align"} // ""
$raw->{"align"}
Truth table100%2/2
A
A= $raw->{"align"}
Aresult
11
00
6074 3 ▶ if (!ref $align && $TEXT_ALIGNS{$align}) { $clean{align} = $align }
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $align and $TEXT_ALIGNS{$align}) { } 1 2 3
Condition66%2/3
not ref $align and $TEXT_ALIGNS{$align}
!ll&&!rl&&r
021
MC/DC50%1/2
not ref $align and $TEXT_ALIGNS{$align}
not ref $align $TEXT_ALIGNS{$align}
Truth table66%2/3
not(A) and B
A= not ref $alignB= $TEXT_ALIGNS{$align}
ABresult
0X0
100
111
6075 2 else { push @errors, _message_text('error_text_card_align') }
6076 }
6077  
6078 51 for my $key (qw(bold italic plain)) {
6079 153 ▶ $clean{$key} = 1 if $raw->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $raw->{$key} 4 149 153
6080 }
6081  
6082 51 return (\%clean, \@errors);
6083 }
6084  
6085 # _text_card_markup(\%visual) -> $html
6086 #
6087 # The body of a text card. The text is escaped and the style holds only values
6088 # _text_card_options has checked. Spaces and line ends are written as entities
6089 # and <br>, not left to CSS, because the response minifier collapses whitespace
6090 # and the embed page has none of this page's styles.
6091 9 ▶sub _text_card_markup {
Subroutine _text_card_markup: called CC=9 SCAR=22.3
6092 9 my ($vis) = @_;
6093 9 my ($o) = _text_card_options($vis->{options});
6094  
6095 9 my @style;
6096 9 ▶ push @style, "font-family:$TEXT_FONT_CSS{$o->{font}}" if $o->{font};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"font"} 1 8 9
6097 9 ▶ push @style, "font-size:$o->{size}pt" if $o->{size};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"size"} 0 9 9
6098 9 ▶ push @style, "color:$o->{colour}" if $o->{colour};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"colour"} 0 9 9
6099 9 ▶ push @style, "background-color:$o->{background}" if $o->{background};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"background"} 0 9 9
6100 9 ▶ push @style, 'font-weight:bold' if $o->{bold};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"bold"} 1 8 9
6101 9 ▶ push @style, 'font-style:italic' if $o->{italic};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"italic"} 0 9 9
6102 9 ▶ push @style, "text-align:$o->{align}" if $o->{align};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"align"} 0 9 9
6103 9 ▶ my $style = @style ? ' style="' . xml_escape(join ';', @style) . '"' : '';
Branch: 1 branch
BranchTrueFalseTotal
@style ? : 1 8 9
6104  
6105 9 my $text = xml_escape($o->{text});
6106 9 $text =~ s/\t/ /g;
6107 9 $text =~ s/^ /&#160;/mg;
6108 9 $text =~ s/ (?= )/&#160;/g;
6109 9 $text =~ s/\n/<br>/g;
6110  
6111 9 return qq{<div class="text-card-text"$style>$text</div>};
6112 }
6113  
6114 # _text_card_title(\%visual) -> $title
6115 #
6116 # What names a text card to the controls on it and to a screen reader: the start
6117 # of its first line that has anything on it.
6118 9 ▶sub _text_card_title {
Subroutine _text_card_title: called CC=3 SCAR=11.0
6119 9 my ($vis) = @_;
6120 9 my ($o) = _text_card_options($vis->{options});
6121 9 my ($line) = $o->{text} =~ /^[ \t]*(\S[^\n]*)/m;
6122 9 ▶ return 'Text' unless defined $line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 2 7 9
6123 7 $line =~ s/\s+\z//;
6124 7 ▶ return length($line) > $TEXT_TITLE_CHARS ? substr($line, 0, $TEXT_TITLE_CHARS) . '...' : $line;
Branch: 1 branch
BranchTrueFalseTotal
length $line > $TEXT_TITLE_CHARS ? : 1 6 7
6125 }
6126  
6127 # _text_card_plain(\%visual) -> $bool
6128 #
6129 # Whether the card hides its frame and header until it is pointed at.
6130 63 ▶sub _text_card_plain {
Subroutine _text_card_plain: called CC=4 SCAR=13.9
6131 63 my ($vis) = @_;
6132 63 ▶ return 0 unless ($vis->{kind} // '') eq 'text';
Branch: 1 branch
BranchTrueFalseTotal
unless ($vis->{"kind"} // "") eq "text" 58 5 63
Condition100%2/2
$vis->{"kind"} // ""
l!l
549
MC/DC100%1/1
$vis->{"kind"} // ""
$vis->{"kind"}
Truth table100%2/2
A
A= $vis->{"kind"}
Aresult
11
00
6133 5 my ($o) = _text_card_options($vis->{options});
6134 5 ▶ return $o->{plain} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$o->{'plain'} ? : 1 4 5
6135 }
6136  
6137 # _text_card_reply($id, $index, \%visual) -> \%json
6138 4 ▶sub _text_card_reply {
Subroutine _text_card_reply: called CC=2 SCAR=7.1
6139 4 my ($id, $index, $vis) = @_;
6140 return {
6141 id => $id,
6142 visual => $index,
6143 kind => 'text',
6144 4 ▶ title => ($vis->{title} // _text_card_title($vis)),
Condition66%2/3
$vis->{"title"} // _text_card_title($vis)
l!l&&r!l&&!r
130
MC/DC0%0/2
$vis->{"title"} // _text_card_title($vis)
$vis->{"title"} _text_card_title($vis)
Truth table66%2/3
A // B
A= $vis->{"title"}B= _text_card_title($vis)
ABresult
1X1
011
000
6145 html => _text_card_markup($vis),
6146 head => '',
6147 cf_col => '',
6148 plain => _text_card_plain($vis),
6149 };
6150 }
6151  
6152 # GET /api/analyses/:id/export
6153 27 ▶sub analyses_export ($self) {
Subroutine analyses_export: called CC=4 SCAR=13.9
Pod documented
6154 27 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
270
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
6155 27 ▶ return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 3 24 27
6156 unless $id =~ /\A[A-Za-z0-9]+\z/;
6157  
6158 24 my $analyses = $self->_read_analyses;
6159 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
6160 24 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 5 19 24
6161  
6162 19 my $json = encode_json($analyses->{$id});
6163 19 $self->res->headers->content_disposition("attachment; filename=\"analysis-$id.json\"");
6164 19 $self->render(data => $json, format => 'json');
6165 }
6166  
6167 # POST /api/analyses/import (create from uploaded JSON or raw body)
6168 27 ▶sub analyses_import ($self) {
Subroutine analyses_import: called CC=9 SCAR=22.2
Pod documented
6169 27 my $lock = $self->_analyses_lock; # read, change and write as one step
6170 27 my $upload = $self->req->upload('file');
6171 27 ▶ my $body_json = $upload ? $upload->slurp : $self->req->body;
Branch: 1 branch
BranchTrueFalseTotal
$upload ? : 0 27 27
6172  
6173 27 my $body = eval { decode_json($body_json) };
6174 27 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 14 13 27
6175 unless ref $body eq 'HASH';
6176  
6177 # Strip any id/timestamps from imported document; assign fresh ones below
6178 13 delete @{$body}{qw( id created updated )};
6179 13 _drop_unknown_keys($body);
6180  
6181 13 my $err = $self->_validate_analysis($body);
6182 13 ▶ return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $err) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if $err 4 9 13
6183 if $err;
6184  
6185 9 ▶ unless ($self->_analyses_path) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_analyses_path) 0 9 9
6186 0 return $self->render(json => { error => _message_text('error_analysis_storage') }, status => 503);
6187 }
6188  
6189 9 my $analyses = $self->_read_analyses;
6190  
6191 9 my $id;
6192 9 my $tries = 0;
6193 9 do { $id = $self->_gen_analysis_id; $tries++ }
6194 9 ▶ while (exists $analyses->{$id} && $tries < 100);
Branch: 1 branch
BranchTrueFalseTotal
exists $analyses->{$id} and $tries < 100 and do { do { $id = $self->_gen_analysis_id; ++$tries } } 0 9 9
Condition33%1/3
exists $analyses->{$id} and $tries < 100
!ll&&!rl&&r
900
MC/DC0%0/2
exists $analyses->{$id} and $tries < 100
exists $analyses->{$id} $tries < 100
Truth table33%1/3
A and B
A= exists $analyses->{$id}B= $tries < 100
ABresult
0X0
100
111
6195  
6196 9 $body->{id} = $id;
6197 9 ▶ $body->{version} //= 1;
Condition100%2/2
$body->{"version"} //= 1
l!l
72
MC/DC100%1/1
$body->{"version"} //= 1
$body->{"version"}
Truth table100%2/2
A
A= $body->{"version"}
Aresult
11
00
6198 9 $body->{created} = time();
6199 9 $body->{updated} = time();
6200  
6201 9 $analyses->{$id} = $body;
6202 9 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 8 1 9
6203  
6204 8 $self->res->headers->location("/api/analyses/$id");
6205 8 $self->render(json => { id => $id, imported => 1 }, status => 201);
6206 }
6207  
6208 # _cross_filter_source($cv) -> Int
6209 #
6210 # The index of the card a cross-filter came from (cv=), or -1 for none. Only
6211 # a whole number names a card: int('abc') is 0, which would draw the first
6212 # card unfiltered as if it were the source.
6213 107 ▶sub _cross_filter_source {
Subroutine _cross_filter_source: called CC=3 SCAR=11.0
6214 107 my $cv = shift;
6215 107 ▶ return (defined($cv) && $cv =~ /\A[0-9]{1,9}\z/) ? int($cv) : -1;
Branch: 1 branch
BranchTrueFalseTotal
defined $cv && $cv =~ /\A[0-9]{1,9}\z/u ? : 7 100 107
Condition100%3/3
defined $cv and $cv =~ /\A[0-9]{1,9}\z/u
!ll&&!rl&&r
66347
MC/DC100%2/2
defined $cv and $cv =~ /\A[0-9]{1,9}\z/u
defined $cv $cv =~ /\A[0-9]{1,9}\z/u
Truth table100%3/3
A and B
A= defined $cvB= $cv =~ /\A[0-9]{1,9}\z/u
ABresult
0X0
100
111
6216 }
6217  
6218 # _build_canvas_pipeline($self, \%analysis) -> ($src, $records, \@cols) or ()
6219 #
6220 # Opens the first dataset from a saved analysis and chains any declared joins.
6221 # Returns the base pipeline triple for _render_visual_html.
6222 # Returns an empty list on any error so canvas_render can respond 422.
6223 # _canvas_render_context($self, \%analysis, $query) -> \%ctx | { error, status }
6224 #
6225 # The state a card is drawn through when it is rendered outside canvas_render:
6226 # the base pipeline, calculated columns, bound parameters and the cross-filters
6227 # named by a canvas page's query string. C<cf_specs> are returned unapplied so
6228 # the caller can decide which card, if any, is their source; C<cf_source> is
6229 # the C<cv> index, or -1 when the page names none. C<cross_row> is the
6230 # validated cs= plan, undef when the page names none, which the caller passes to
6231 # _render_visual_html so each card runs it over its own rows. Only C<cf>,
6232 # C<cv>, C<c>, C<cs>, C<by>, C<order>, C<range>, C<rcol> and C<p.<name>> are read
6233 # from C<$query> - the same keys canvas_render reads from its own URL - so a
6234 # page's state is not a way to reach anything else.
6235 42 ▶sub _canvas_render_context :Protected ($self, $a, $query, $more_cards = undef) {
Subroutine _canvas_render_context: called CC=21 SCAR=31.0
6236 42 my $params;
6237 42 ▶ if (defined $query) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query) 31 11 42
6238 31 ▶ return { error => 'query must be a string', status => 400 }
Branch: 1 branch
BranchTrueFalseTotal
if ref $query or length $query > 4096 2 29 31
Condition100%3/3
ref $query or length $query > 4096
l!l&&r!l&&!r
1129
MC/DC100%2/2
ref $query or length $query > 4096
ref $query length $query > 4096
Truth table100%3/3
A or B
A= ref $queryB= length $query > 4096
ABresult
1X1
011
000
6239 if ref $query || length($query) > 4096;
6240 29 (my $qs = $query) =~ s/\A\?//;
6241 29 $params = Mojo::Parameters->new($qs);
6242 }
6243  
6244 40 my ($src, $records, $columns) = $self->_build_canvas_pipeline($a);
6245 40 ▶ return { error => 'Cannot open data source for this canvas', status => 422 }
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 2 38 40
6246 unless defined $records;
6247  
6248 my ($bound_ref, $p_errors) = $self->_bound_canvas_params(
6249 4 ▶ $a, sub { $params ? $params->param($_[0]) : undef },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$params ? : 4 0 4
6250 38 );
6251 38 ▶ return { error => join('; ', @$p_errors), status => 400 }
Branch: 1 branch
BranchTrueFalseTotal
if @$p_errors 2 36 38
6252 if @$p_errors;
6253 36 my %param_values = %$bound_ref;
6254  
6255 36 ▶ my $window_names = _canvas_window_columns($a, $params || Mojo::Parameters->new, $more_cards);
Condition66%2/3
$params || 'Mojo::Parameters'->new
l!l&&r!l&&!r
25110
MC/DC0%0/2
$params || 'Mojo::Parameters'->new
$params 'Mojo::Parameters'->new
Truth table66%2/3
A || B
A= $paramsB= 'Mojo::Parameters'->new
ABresult
1X1
011
000
6256 36 $self->stash('_canvas_window_names' => $window_names);
6257  
6258 36 eval {
6259 ($records, $columns) = $self->_apply_calc_fields(
6260 $records, $columns,
6261 {
6262 params => \%param_values,
6263 spec_key => ($a->{datasets}[0]{spec} // ''),
6264 36 ▶ calc => [ $params ? @{ $params->every_param('c') // [] } : () ],
Branch: 1 branch
BranchTrueFalseTotal
$params ? : 25 11 36
Condition50%2/4
$a->{"datasets"}[0]{"spec"} // ""
l!l
360
$params->every_param("c") // []
l!l
250
MC/DC0%0/1
$a->{"datasets"}[0]{"spec"} // ""
$a->{"datasets"}[0]{"spec"}
MC/DC0%0/1
$params->every_param("c") // []
$params->every_param("c")
Truth table50%1/2
A
A= $a->{"datasets"}[0]{"spec"}
Aresult
11
00
Truth table50%1/2
A
A= $params->every_param("c")
Aresult
11
00
6265 window_columns => $window_names,
6266 }
6267 );
6268 };
6269 36 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 35 36
6270 1 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
6271 1 return { error => $e, status => 400 };
6272 }
6273  
6274 # The canvas names cs= once and every card runs the same plan over its own
6275 # rows (see _render_visual_html). Validated here, against the columns the
6276 # cards will be drawn from, so a card added or edited in place fails with
6277 # the same 400 the page itself would give.
6278 35 ▶ my $cross_row = $self->_cross_row_specs($columns, $params || Mojo::Parameters->new);
Condition66%2/3
$params || 'Mojo::Parameters'->new
l!l&&r!l&&!r
24110
MC/DC0%0/2
$params || 'Mojo::Parameters'->new
$params 'Mojo::Parameters'->new
Truth table66%2/3
A || B
A= $paramsB= 'Mojo::Parameters'->new
ABresult
1X1
011
000
6279 return { error => $cross_row->{error}, status => 400 }
6280 35 ▶ if $cross_row && $cross_row->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $cross_row and $cross_row->{"error"} 0 35 35
Condition33%1/3
$cross_row and $cross_row->{"error"}
!ll&&!rl&&r
3500
MC/DC0%0/2
$cross_row and $cross_row->{"error"}
$cross_row $cross_row->{"error"}
Truth table33%1/3
A and B
A= $cross_rowB= $cross_row->{"error"}
ABresult
0X0
100
111
6281  
6282 35 ▶ my @cf_specs = $params ? grep { /\S/ } @{ $params->every_param('cf') // [] } : ();
Branch: 1 branch
BranchTrueFalseTotal
$params ? : 24 11 35
Condition50%1/2
$params->every_param("cf") // []
l!l
240
MC/DC0%0/1
$params->every_param("cf") // []
$params->every_param("cf")
Truth table50%1/2
A
A= $params->every_param("cf")
Aresult
11
00
6283 35 ▶ my $cf_source = _cross_filter_source($params ? $params->param('cv') : undef);
Branch: 1 branch
BranchTrueFalseTotal
$params ? : 24 11 35
6284  
6285 # The relative time range the canvas page names in its query string is part
6286 # of the state a card is drawn through, like cf= and the bound parameters,
6287 # so a visual added while a range is active shows the same rows as the
6288 # cards already on screen.
6289 35 ▶ $records = _apply_time_range(
Branch: 2 branches
BranchTrueFalseTotal
$params ? : 24 11 35
$params ? : 24 11 35
6290 $records,
6291 $params ? $params->param('range') : undef,
6292 $params ? $params->param('rcol') : undef,
6293 );
6294  
6295 return {
6296 src => $src,
6297 records => $records,
6298 columns => $columns,
6299 35 ▶ spec_key => ($a->{datasets}[0]{spec} // ''),
Condition50%1/2
$a->{"datasets"}[0]{"spec"} // ""
l!l
350
MC/DC0%0/1
$a->{"datasets"}[0]{"spec"} // ""
$a->{"datasets"}[0]{"spec"}
Truth table50%1/2
A
A= $a->{"datasets"}[0]{"spec"}
Aresult
11
00
6300 cf_specs => \@cf_specs,
6301 cf_source => $cf_source,
6302 cross_row => $cross_row,
6303 };
6304 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
6305  
6306 86 ▶sub _build_canvas_pipeline :Protected ($self, $analysis) {
Subroutine _build_canvas_pipeline: called CC=21 SCAR=33.5
6307 86 ▶ my @datasets = @{ $analysis->{datasets} // [] };
Condition100%2/2
$analysis->{"datasets"} // []
l!l
851
MC/DC100%1/1
$analysis->{"datasets"} // []
$analysis->{"datasets"}
Truth table100%2/2
A
A= $analysis->{"datasets"}
Aresult
11
00
6308 86 ▶ return () unless @datasets;
Branch: 1 branch
BranchTrueFalseTotal
unless @datasets 2 84 86
6309  
6310 84 ▶ my $left_spec = $datasets[0]{spec} or return ();
Branch: 1 branch
BranchTrueFalseTotal
my $left_spec = $datasets[0]{"spec"} or return () 83 1 84
6311 83 my ($left_src) = $self->_open_spec($left_spec);
6312 83 ▶ return () unless $left_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $left_src 3 80 83
6313  
6314 80 ▶ my $max_rows = $self->app->config('join_max_rows') // $DEFAULT_JOIN_MAX_ROWS;
Condition33%1/3
$self->app->config("join_max_rows") // $DEFAULT_JOIN_MAX_ROWS
l!l&&r!l&&!r
0800
MC/DC0%0/2
$self->app->config("join_max_rows") // $DEFAULT_JOIN_MAX_ROWS
$self->app->config("join_max_rows") $DEFAULT_JOIN_MAX_ROWS
Truth table33%1/3
A // B
A= $self->app->config("join_max_rows")B= $DEFAULT_JOIN_MAX_ROWS
ABresult
1X1
011
000
6315 80 my $src = $left_src;
6316  
6317 # Build alias -> spec lookup for join resolution.
6318 80 my %spec_by_alias;
6319 80 for my $ds (@datasets) {
6320 81 ▶ $spec_by_alias{ $ds->{alias} // '' } = $ds->{spec} // '';
Condition75%3/4
$ds->{"spec"} // ""
l!l
810
$ds->{"alias"} // ""
l!l
1566
MC/DC0%0/1
$ds->{"spec"} // ""
$ds->{"spec"}
MC/DC100%1/1
$ds->{"alias"} // ""
$ds->{"alias"}
Truth table50%1/2
A
A= $ds->{"spec"}
Aresult
11
00
Truth table100%2/2
A
A= $ds->{"alias"}
Aresult
11
00
6321 }
6322  
6323 80 ▶ for my $j (@{ $analysis->{joins} // [] }) {
Condition100%2/2
$analysis->{"joins"} // []
l!l
179
MC/DC100%1/1
$analysis->{"joins"} // []
$analysis->{"joins"}
Truth table100%2/2
A
A= $analysis->{"joins"}
Aresult
11
00
6324 2 ▶ my $right_spec = $spec_by_alias{ $j->{right} // '' } // '';
Condition100%4/4
$spec_by_alias{$j->{"right"} // ""} // ""
l!l
11
$j->{"right"} // ""
l!l
11
MC/DC100%1/1
$spec_by_alias{$j->{"right"} // ""} // ""
$spec_by_alias{$j->{"right"} // ""}
MC/DC100%1/1
$j->{"right"} // ""
$j->{"right"}
Truth table100%2/2
A
A= $spec_by_alias{$j->{"right"} // ""}
Aresult
11
00
Truth table100%2/2
A
A= $j->{"right"}
Aresult
11
00
6325 2 ▶ next unless length $right_spec;
Branch: 1 branch
BranchTrueFalseTotal
unless length $right_spec 1 1 2
6326 1 ▶ my $left_key = $j->{left_key} // '';
Condition50%1/2
$j->{"left_key"} // ""
l!l
01
MC/DC0%0/1
$j->{"left_key"} // ""
$j->{"left_key"}
Truth table50%1/2
A
A= $j->{"left_key"}
Aresult
11
00
6327 1 ▶ my $right_key = $j->{right_key} // $left_key;
Condition33%1/3
$j->{"right_key"} // $left_key
l!l&&r!l&&!r
010
MC/DC0%0/2
$j->{"right_key"} // $left_key
$j->{"right_key"} $left_key
Truth table33%1/3
A // B
A= $j->{"right_key"}B= $left_key
ABresult
1X1
011
000
6328 1 ▶ next unless length $left_key;
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_key 1 0 1
6329  
6330 0 my ($right_src) = $self->_open_spec($right_spec);
6331 0 ▶ next unless $right_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_src 0 0 0
6332  
6333 0 require Database::Join;
6334 0 ▶ $src = Database::Join->new(
Branch: 1 branch
BranchTrueFalseTotal
$left_key ne $right_key ? : 0 0 0
6335 databases => [$src, $right_src],
6336 join_column => $left_key,
6337 backend => 'auto',
6338 max_array_rows => $max_rows,
6339 ($left_key ne $right_key ? (join_map => {1 => $right_key}) : ()),
6340 );
6341 }
6342  
6343 80 my $records = eval { $src->selectall_arrayref };
6344 80 ▶ return () if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 80 80
6345 80 ▶ $records //= [];
Condition50%1/2
$records //= []
l!l
800
MC/DC0%0/1
$records //= []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
6346 80 my @columns = _get_columns($src, $records);
6347  
6348 80 return ($src, $records, \@columns);
6349 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
6350  
6351 # _chart_json($self, \%chart_spec) -> $json_for_a_data_attribute
6352 #
6353 # The chart templates put this in the New canvas panel's data-chart attribute
6354 # so the canvas buttons can save the chart exactly as it is drawn, including
6355 # options the URL does not carry. Escape '<' as well, so the value is inert
6356 # even if a title or column name contains markup.
6357 406 ▶sub _chart_json :Protected ($self, $chart) {
Subroutine _chart_json: called CC=1 SCAR=0.0
6358 406 my $json = encode_json($chart);
6359 406 $json =~ s{<}{\\u003c}g;
6360 406 return $json;
6361 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
6362  
6363 # _chart_orientation(\%options) -> 'horizontal' | 'vertical'
6364 #
6365 # The chart pages store a bar's direction as options.orientation, the spelling
6366 # their URL uses, while the canvas used to read options.orient; both are read
6367 # here. The values the pages emit are v/h and vertical/horizontal.
6368 48 ▶sub _chart_orientation {
Subroutine _chart_orientation: called CC=4 SCAR=13.9
6369 48 my ($options) = @_;
6370  
6371 48 ▶ my $orient = $options->{orientation} // $options->{orient} // '';
Condition100%5/5
($options->{"orientation"} // $options->{"orient"}) // ""
l!l
741
$options->{"orientation"} // $options->{"orient"}
l!l&&r!l&&!r
6141
MC/DC100%2/2
($options->{"orientation"} // $options->{"orient"}) // ""
$options->{"orientation"} $options->{"orient"}
Truth table100%3/3
A // B
A= $options->{"orientation"}B= $options->{"orient"}
ABresult
1X1
011
000
6372 48 ▶ return ($orient =~ /\A(?:h|horizontal)\z/i) ? 'horizontal' : 'vertical';
Branch: 1 branch
BranchTrueFalseTotal
$orient =~ /\A(?:h|horizontal)\z/iu ? : 4 44 48
6373 }
6374  
6375 # _visual_measure($agg_fn, $val_col) -> \%measure
6376 #
6377 # The measure a canvas card aggregates a value column with: C<{ fn, val,
6378 # label }> when the card can be drawn, or C<{ error }> when it cannot, which
6379 # the card reports in place of its chart.
6380 #
6381 # A card that names no function keeps the default it has always had: count the
6382 # rows when it names no value column, sum it when it does. A named function is
6383 # the measure vocabulary the pivot and the stats page share, with a percentile
6384 # riding in the name as p<N> -- p90, p50 -- exactly as a pivot's measure spells
6385 # it, so a card needs no second key to keep in step. 'count' counts rows, so it
6386 # ignores the value column and needs none.
6387 #
6388 # label is what the card's title calls the result: 'Count', the column's own
6389 # name for a plain sum, and "fn(col)" for anything else, so two cards over one
6390 # column do not read alike when one of them is a median. An explicit sum keeps
6391 # the plain name, because naming the default should not change a card.
6392 #
6393 # The name itself is not checked here: _render_visual_html validates it once,
6394 # before the dispatch, so that a card of any kind reports a function it cannot
6395 # compute -- including the kinds that never call this.
6396 74 ▶sub _visual_measure {
Subroutine _visual_measure: called CC=14 SCAR=26.4
6397 74 my ($agg_fn, $val_col) = @_;
6398 74 ▶ my $count_col = (!defined $val_col || !length $val_col || $val_col eq '__count__');
Condition100%6/6
!(defined $val_col && length $val_col) || $val_col eq '__count__'
l!l&&r!l&&!r
20252
defined $val_col && length $val_col
!ll&&!rl&&r
41654
MC/DC100%3/3
!(defined $val_col && length $val_col) || $val_col eq '__count__'
defined $val_col length $val_col $val_col eq '__count__'
Truth table100%4/4
not(A && B) || C
A= defined $val_colB= length $val_colC= $val_col eq '__count__'
ABCresult
0XX1
10X1
1111
1100
6399 # An absent name and an empty one are the same non-choice, so the default is
6400 # one branch rather than two.
6401 74 ▶ my $named = (defined $agg_fn && !ref $agg_fn && length $agg_fn) ? $agg_fn : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $agg_fn && !ref($agg_fn) && length $agg_fn ? : 27 47 74
Condition83%5/6
defined $agg_fn and not ref $agg_fn and length $agg_fn
!ll&&!rl&&r
46127
defined $agg_fn and not ref $agg_fn
!ll&&!rl&&r
46028
MC/DC66%2/3
defined $agg_fn and not ref $agg_fn and length $agg_fn
defined $agg_fn not ref $agg_fn length $agg_fn
Truth table75%3/4
A and not(B) and C
A= defined $agg_fnB= not ref $agg_fnC= length $agg_fn
ABCresult
0XX0
10X0
1100
1111
6402  
6403 74 ▶ return { fn => 'count', val => undef, label => 'Count' }
Branch: 1 branch
BranchTrueFalseTotal
if defined $named and $named eq "count" 2 72 74
Condition100%3/3
defined $named and $named eq "count"
!ll&&!rl&&r
47252
MC/DC100%2/2
defined $named and $named eq "count"
defined $named $named eq "count"
Truth table100%3/3
A and B
A= defined $namedB= $named eq "count"
ABresult
0X0
100
111
6404 if defined $named && $named eq 'count';
6405 72 ▶ return { fn => 'count', val => undef, label => 'Count' }
Branch: 1 branch
BranchTrueFalseTotal
if not defined $named and $count_col 16 56 72
Condition100%3/3
not defined $named and $count_col
!ll&&!rl&&r
253116
MC/DC100%2/2
not defined $named and $count_col
not defined $named $count_col
Truth table100%3/3
not(A) and B
A= not defined $namedB= $count_col
ABresult
0X0
100
111
6406 if !defined $named && $count_col;
6407 56 ▶ return { error => "Aggregate '$named' needs a value column" }
Branch: 1 branch
BranchTrueFalseTotal
if defined $named and $count_col 5 51 56
Condition100%3/3
defined $named and $count_col
!ll&&!rl&&r
31205
MC/DC100%2/2
defined $named and $count_col
defined $named $count_col
Truth table100%3/3
A and B
A= defined $namedB= $count_col
ABresult
0X0
100
111
6408 if defined $named && $count_col;
6409  
6410 51 ▶ my $fn = defined $named ? $named : 'sum';
Branch: 1 branch
BranchTrueFalseTotal
defined $named ? : 20 31 51
6411 return {
6412 51 ▶ fn => $fn,
Branch: 1 branch
BranchTrueFalseTotal
$fn eq 'sum' ? : 34 17 51
6413 val => $val_col,
6414 label => ($fn eq 'sum' ? $val_col : "$fn($val_col)"),
6415 };
6416 }
6417  
6418 # _render_visual_html($self, \%vis, $records, \@columns, $src, $vis_id, $spec_key,
6419 # $prefiltered, $cross_row)
6420 # -> { html => Str, title => Str, head => Str } | { error => Str }
6421 #
6422 # Renders one canvas visual spec to an HTML snippet without touching
6423 # $self->render(), with each of the card's inline scripts closed over a
6424 # function of its own (see _scope_card_scripts). The scoping is done here
6425 # rather than by the callers because every card passes through here and every
6426 # caller wants the same thing: a card's script and the page's are separate
6427 # programs, whether the card is drawn on a canvas of its own kind or returned
6428 # to a page that is about to insert it.
6429 72 ▶sub _render_visual_html :Protected ($self, $vis, $records, $columns, $src, $vis_id, $spec_key, $prefiltered, $cross_row = undef, $late_cf = undef) {
Subroutine _render_visual_html: called CC=4 SCAR=13.9
6430 72 my $rendered = $self->_render_visual_markup(
6431 $vis, $records, $columns, $src, $vis_id, $spec_key, $prefiltered, $cross_row, $late_cf,
6432 );
6433 72 ▶ return $rendered unless defined $rendered->{html};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rendered->{"html"} 26 46 72
6434  
6435 46 $rendered->{html} = _scope_card_scripts($rendered->{html});
6436 46 return $rendered;
6437 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
6438  
6439 # _render_visual_markup($self, \%vis, $records, \@columns, $src, $vis_id,
6440 # $spec_key, $prefiltered, $cross_row)
6441 # -> { html => Str, title => Str, head => Str } | { error => Str }
6442 #
6443 # The card itself, without the scope _render_visual_html puts around its
6444 # scripts. Applies any per-visual filters, then dispatches by
6445 # kind to the appropriate renderer. $vis_id gives a map's Leaflet element
6446 # ids a page-unique suffix; $spec_key is the dataset whose older per-dataset
6447 # geocode entry may still be read while the shared cache is migrated.
6448 # $cross_row is the canvas's validated cs= plan, run here so that each card's
6449 # window is over that card's own rows: see the note at the pass below. A card
6450 # that saved a plan of its own uses that one instead. $late_cf holds the
6451 # cross-filter specs on columns a plan writes (_canvas_cross_filter); a card
6452 # whose plan does not write the column has nothing to filter by, and ignores it.
6453 72 ▶sub _render_visual_markup :Protected ($self, $vis, $records, $columns, $src, $vis_id, $spec_key, $prefiltered, $cross_row = undef, $late_cf = undef) {
Subroutine _render_visual_markup: called CC=290 SCAR=103.6
6454 72 ▶ my $kind = $vis->{kind} // '';
Condition100%2/2
$vis->{"kind"} // ""
l!l
657
MC/DC100%1/1
$vis->{"kind"} // ""
$vis->{"kind"}
Truth table100%2/2
A
A= $vis->{"kind"}
Aresult
11
00
6455 72 ▶ return { html => _text_card_markup($vis), title => _text_card_title($vis) }
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "text" 2 70 72
6456 if $kind eq 'text';
6457  
6458 # A stored card is not checked part by part (PUT and import keep a visual
6459 # as sent), so a part of the wrong shape is read as absent here rather than
6460 # dereferenced.
6461 70 ▶ my $encode = ref($vis->{encode}) eq 'HASH' ? $vis->{encode} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $vis->{'encode'} eq 'HASH' ? : 55 15 70
6462 70 ▶ my $options = ref($vis->{options}) eq 'HASH' ? $vis->{options} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $vis->{'options'} eq 'HASH' ? : 15 55 70
6463 70 ▶ my $filters = ref($vis->{filters}) eq 'ARRAY' ? [ grep { defined && !ref } @{ $vis->{filters} } ] : [];
Branch: 1 branch
BranchTrueFalseTotal
ref $vis->{'filters'} eq 'ARRAY' ? : 1 69 70
Condition100%3/3
defined $_ && !ref($_)
!ll&&!rl&&r
121
MC/DC100%2/2
defined $_ && !ref($_)
defined $_ !ref($_)
Truth table100%3/3
A && not(B)
A= defined $_B= !ref($_)
ABresult
0X0
100
111
6464 70 ▶ my $title = $vis->{title} // '';
Condition100%2/2
$vis->{"title"} // ""
l!l
1951
MC/DC100%1/1
$vis->{"title"} // ""
$vis->{"title"}
Truth table100%2/2
A
A= $vis->{"title"}
Aresult
11
00
6465  
6466 # Every chart on a canvas needs an element id of its own: HTML::D3 names the
6467 # SVG after the chart kind by default, so two bar cards both write #bar_chart
6468 # and the second card's script draws into the first. The id carries the
6469 # visual's index, which is stable across renders, so a saved canvas and a
6470 # card appended in place agree; the chart pages render one chart and keep
6471 # HTML::D3's default.
6472 70 ▶ my $svg_id = 'vis-' . (defined($vis_id) ? $vis_id : 'chart');
Branch: 1 branch
BranchTrueFalseTotal
defined $vis_id ? : 70 0 70
6473  
6474 # A card that carries a cross-row plan of its own (visual.cross_row) runs that
6475 # plan instead of the page's: putting a running total on one card is not a
6476 # request to put one on every card, and a card whose plan is empty has none
6477 # at all rather than the page's. Its plan is validated here rather than
6478 # when it was saved, because the columns a saved canvas has are the columns
6479 # its data file has today. A card's own plan is its own fault, so a bad one
6480 # is that card's error while the page's bad plan is the page's 400.
6481 70 my $plan = $cross_row;
6482 70 ▶ if (ref $vis->{cross_row} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $vis->{"cross_row"} eq "HASH") 0 70 70
6483 0 $plan = $self->_cross_row_specs_from($columns, $vis->{cross_row});
6484 return { error => $plan->{error} }
6485 0 ▶ if $plan && $plan->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $plan and $plan->{"error"} 0 0 0
Condition0%0/3
$plan and $plan->{"error"}
!ll&&!rl&&r
000
MC/DC0%0/2
$plan and $plan->{"error"}
$plan $plan->{"error"}
Truth table0%0/3
A and B
A= $planB= $plan->{"error"}
ABresult
0X0
100
111
6486 }
6487  
6488 # Apply per-visual filters on top of the base pipeline records. One on a column
6489 # this card's plan writes waits for the pass, as it does on a table page.
6490 my %written = $plan
6491 0 ? (map({ $_->{as} => 1 } @{ $plan->{specs} }),
6492 0 ▶ map({ $_->{name} => 1 } @{ $self->stash('_held_calc_fields') // [] }))
Branch: 1 branch
BranchTrueFalseTotal
$plan ? : 0 70 70
Condition0%0/2
$self->stash("_held_calc_fields") // []
l!l
00
MC/DC0%0/1
$self->stash("_held_calc_fields") // []
$self->stash("_held_calc_fields")
Truth table0%0/2
A
A= $self->stash("_held_calc_fields")
Aresult
11
00
6493 : ();
6494 70 my $vis_recs = $records;
6495 70 my @late_filters;
6496 70 for my $f (@$filters) {
6497 1 ▶ if ($written{ (split /:/, $f, 2)[0] // '' }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($written{(split(/:/u, $f, 2))[0] // ""}) 0 1 1
Condition50%1/2
(split(/:/u, $f, 2))[0] // ""
l!l
10
MC/DC0%0/1
(split(/:/u, $f, 2))[0] // ""
(split(/:/u, $f, 2))[0]
Truth table50%1/2
A
A= (split(/:/u, $f, 2))[0]
Aresult
11
00
6498 0 push @late_filters, $f;
6499 0 next;
6500 }
6501 1 $vis_recs = _apply_filter_spec($vis_recs, $f);
6502 }
6503  
6504 # Stage 6, per card. A canvas names cs= once, but by the time the pass runs
6505 # the card has already been narrowed by its own filters and by the page's
6506 # cross-filter, so a running total is over the rows that card is drawn from:
6507 # two cards showing different regions show different running totals. The
6508 # pass therefore cannot be hoisted above the card loop -- one shared pass
6509 # would give every card the same numbers, and those are the numbers of
6510 # neither card. A fault is this card's error, not the page's: the plan was
6511 # validated once, and only the arithmetic can still fail here.
6512 70 ▶ if ($plan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plan) 0 70 70
6513 # The pass writes its column onto the rows it is handed, and a card is
6514 # handed the canvas's rows -- the same hashrefs every card draws from. The
6515 # numbers a pass produces are that card's, so it runs on copies: without
6516 # them one card's running total is written into its neighbour's rows, and a
6517 # card that asked for no plan at all reads a column it never asked for.
6518 0 ▶ my $own = [ map { ref $_ eq 'HASH' ? { %$_ } : $_ } @$vis_recs ];
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 0 0 0
6519 0 my ($crossed, $crossed_cols) = eval {
6520 0 my ($r, $c) = $self->_apply_cross_row($own, $columns, $plan);
6521 0 $self->_apply_held_calc_fields($r, $c, 1);
6522 };
6523 0 ▶ if (my $e = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $e = $@) 0 0 0
6524 0 $e =~ s/ at \S+ line \d+\.?\n?$//;
6525 0 return { error => $e };
6526 }
6527 0 ($vis_recs, $columns) = ($crossed, $crossed_cols);
6528 }
6529  
6530 70 my %col_set = map { $_ => 1 } @$columns;
6531  
6532 $vis_recs = _apply_filter_spec($vis_recs, $_)
6533 0 ▶ for @late_filters, grep { $col_set{ (split /:/, $_, 2)[0] // '' } } @{ $late_cf // [] };
Condition50%2/4
(split(/:/u, $_, 2))[0] // ""
l!l
00
$late_cf // []
l!l
5317
MC/DC0%0/1
(split(/:/u, $_, 2))[0] // ""
(split(/:/u, $_, 2))[0]
MC/DC100%1/1
$late_cf // []
$late_cf
Truth table0%0/2
A
A= (split(/:/u, $_, 2))[0]
Aresult
11
00
Truth table100%2/2
A
A= $late_cf
Aresult
11
00
6534  
6535 # The aggregate function this card picked for itself, if any (encode.agg).
6536 # It is read and checked here, before the dispatch, so a misspelt function
6537 # is this card's error whatever kind it is, rather than a chart quietly
6538 # drawn some other way; the kinds that aggregate then honour it below. A
6539 # percentile rides in the name (p90, p50), as it does in a pivot measure, so
6540 # there is no second key to keep in step.
6541 70 my $agg_fn = $encode->{agg};
6542 70 ▶ if (defined $agg_fn && !ref $agg_fn && length $agg_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $agg_fn and not ref $agg_fn and length $agg_fn) { } 0 70 70
Condition33%2/6
defined $agg_fn and not ref $agg_fn and length $agg_fn
!ll&&!rl&&r
7000
defined $agg_fn and not ref $agg_fn
!ll&&!rl&&r
7000
MC/DC0%0/3
defined $agg_fn and not ref $agg_fn and length $agg_fn
defined $agg_fn not ref $agg_fn length $agg_fn
Truth table25%1/4
A and not(B) and C
A= defined $agg_fnB= not ref $agg_fnC= length $agg_fn
ABCresult
0XX0
10X0
1100
1111
6543 0 ▶ return { error => "Unknown aggregate function '$agg_fn'; expected one of: "
Branch: 1 branch
BranchTrueFalseTotal
unless _measure_fn_ok($agg_fn) 0 0 0
6544 . join(' ', @MEASURE_FNS) . ', or p1 to p100 for a percentile' }
6545 unless _measure_fn_ok($agg_fn);
6546 } else {
6547 70 $agg_fn = undef;
6548 }
6549  
6550 # A chart aggregates the rows it is given. The SQL push path in
6551 # _grouped_totals re-reads the source, which has none of the filters the
6552 # caller already applied (a cross-filter, or this visual's own filters), so
6553 # those rows have to be folded in Perl. Passing no source is how the
6554 # pipeline says so.
6555 70 ▶ my $agg_src = (@$filters || $prefiltered) ? undef : $src;
Branch: 1 branch
BranchTrueFalseTotal
@$filters || $prefiltered ? : 2 68 70
Condition100%3/3
@$filters or $prefiltered
l!l&&r!l&&!r
1168
MC/DC100%2/2
@$filters or $prefiltered
@$filters $prefiltered
Truth table100%3/3
A or B
A= @$filtersB= $prefiltered
ABresult
1X1
011
000
6556  
6557 70 require HTML::D3;
6558  
6559 # ------------------------------------------------------------------ bar --
6560 70 ▶ if ($kind eq 'bar') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "bar") 53 17 70
6561 53 ▶ my $cat_col = $encode->{cat} // '';
Condition100%2/2
$encode->{"cat"} // ""
l!l
485
MC/DC100%1/1
$encode->{"cat"} // ""
$encode->{"cat"}
Truth table100%2/2
A
A= $encode->{"cat"}
Aresult
11
00
6562 53 ▶ my $val_col = $encode->{value} // '';
Condition100%2/2
$encode->{"value"} // ""
l!l
3023
MC/DC100%1/1
$encode->{"value"} // ""
$encode->{"value"}
Truth table100%2/2
A
A= $encode->{"value"}
Aresult
11
00
6563 53 ▶ return { error => 'Missing cat column for bar visual' } unless length $cat_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col 5 48 53
6564 48 ▶ return { error => "Column not found: $cat_col" } unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 8 40 48
6565 40 ▶ my $count_mode = ($val_col eq '__count__' || !length $val_col);
Condition66%2/3
$val_col eq '__count__' || !length($val_col)
l!l&&r!l&&!r
01327
MC/DC50%1/2
$val_col eq '__count__' || !length($val_col)
$val_col eq '__count__' !length($val_col)
Truth table66%2/3
A || not(B)
A= $val_col eq '__count__'B= !length($val_col)
ABresult
1X1
011
000
6566 return { error => "Column not found: $val_col" }
6567 40 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 0 40 40
Condition66%2/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
13270
MC/DC0%0/2
$count_mode or $col_set{$val_col}
$count_mode $col_set{$val_col}
Truth table66%2/3
A or B
A= $count_modeB= $col_set{$val_col}
ABresult
1X1
011
000
6568  
6569 40 my $m = _visual_measure($agg_fn, $val_col);
6570 40 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 40 40
6571  
6572 my $agg = $self->_grouped_totals(
6573 { source => $agg_src, records => $vis_recs },
6574 { by => [$cat_col], fn => $m->{fn},
6575 40 val => $m->{val}, as => 'value' },
6576 );
6577 40 ▶ return { error => 'No plottable data' } unless @$agg;
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg 0 40 40
6578  
6579 40 ▶ $title ||= "$m->{label} by $cat_col";
Condition100%2/2
$title ||= qq[$m->{"label"} by $cat_col]
l!l
1723
MC/DC100%1/1
$title ||= qq[$m->{"label"} by $cat_col]
$title
Truth table100%2/2
A
A= $title
Aresult
11
00
6580 40 my @bars = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg;
6581 40 my $orient = _chart_orientation($options);
6582 # The bar page caps its bars as max_bars and stores the cap as
6583 # max_items; the seed has to carry it or a seeded canvas draws every
6584 # category where the page drew the top few and Other.
6585 40 ▶ my $max_bars = int($options->{max_items} // $options->{max_bars} // 0);
Condition40%2/5
($options->{"max_items"} // $options->{"max_bars"}) // 0
l!l
040
$options->{"max_items"} // $options->{"max_bars"}
l!l&&r!l&&!r
0040
MC/DC0%0/2
($options->{"max_items"} // $options->{"max_bars"}) // 0
$options->{"max_items"} $options->{"max_bars"}
Truth table33%1/3
A // B
A= $options->{"max_items"}B= $options->{"max_bars"}
ABresult
1X1
011
000
6586 40 ▶ my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
Branch: 1 branch
BranchTrueFalseTotal
$max_bars > 0 ? : 0 40 40
6587 ->render_bar_chart_snippet(\@bars, {
6588 orientation => $orient,
6589 x_label => $cat_col,
6590 id => $svg_id,
6591 ($max_bars > 0 ? (max_bars => $max_bars) : ()),
6592 });
6593 40 my $html = $sn->{html};
6594 40 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 40 40
6595 40 return { html => $html, title => $title };
6596 }
6597  
6598 # ------------------------------------------------------------------ pie --
6599 17 ▶ if ($kind eq 'pie') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "pie") 2 15 17
6600 2 ▶ my $cat_col = $encode->{cat} // '';
Condition50%1/2
$encode->{"cat"} // ""
l!l
20
MC/DC0%0/1
$encode->{"cat"} // ""
$encode->{"cat"}
Truth table50%1/2
A
A= $encode->{"cat"}
Aresult
11
00
6601 2 ▶ my $val_col = $encode->{value} // '';
Condition50%1/2
$encode->{"value"} // ""
l!l
20
MC/DC0%0/1
$encode->{"value"} // ""
$encode->{"value"}
Truth table50%1/2
A
A= $encode->{"value"}
Aresult
11
00
6602 2 ▶ return { error => 'Missing cat or val column for pie visual' }
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col and length $val_col 0 2 2
Condition33%1/3
length $cat_col and length $val_col
!ll&&!rl&&r
002
MC/DC0%0/2
length $cat_col and length $val_col
length $cat_col length $val_col
Truth table33%1/3
A and B
A= length $cat_colB= length $val_col
ABresult
0X0
100
111
6603 unless length($cat_col) && length($val_col);
6604 2 ▶ return { error => "Column not found: $cat_col" } unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 1 1 2
6605 1 my $count_mode = ($val_col eq '__count__');
6606 return { error => "Column not found: $val_col" }
6607 1 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 0 1 1
Condition33%1/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
010
MC/DC0%0/2
$count_mode or $col_set{$val_col}
$count_mode $col_set{$val_col}
Truth table33%1/3
A or B
A= $count_modeB= $col_set{$val_col}
ABresult
1X1
011
000
6608  
6609 1 my $m = _visual_measure($agg_fn, $val_col);
6610 1 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 1 1
6611  
6612 my $agg = $self->_grouped_totals(
6613 { source => $agg_src, records => $vis_recs },
6614 { by => [$cat_col], fn => $m->{fn},
6615 1 val => $m->{val}, as => 'value' },
6616 );
6617 1 ▶ return { error => 'No plottable data' } unless @$agg;
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg 0 1 1
6618  
6619 1 ▶ $title ||= "$m->{label} by $cat_col";
Condition50%1/2
$title ||= qq[$m->{"label"} by $cat_col]
l!l
01
MC/DC0%0/1
$title ||= qq[$m->{"label"} by $cat_col]
$title
Truth table50%1/2
A
A= $title
Aresult
11
00
6620 1 my @slices = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg;
6621 1 my $scheme = _categorical_scheme($options->{scheme});
6622 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6623 ->render_pie_chart_snippet(\@slices, {
6624 1 ▶ donut => $options->{donut} ? 1 : 0,
Branch: 1 branch
BranchTrueFalseTotal
$options->{'donut'} ? : 0 1 1
6625 legend => 1,
6626 color_scheme => $scheme,
6627 id => $svg_id,
6628 });
6629 1 my $html = $sn->{html};
6630 1 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 1 1
6631 1 return { html => $html, title => $title };
6632 }
6633  
6634 # -------------------------------------------------------------- line/graph --
6635 15 ▶ if ($kind eq 'line' || $kind eq 'graph') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "line" or $kind eq "graph") 0 15 15
Condition33%1/3
$kind eq "line" or $kind eq "graph"
l!l&&r!l&&!r
0015
MC/DC0%0/2
$kind eq "line" or $kind eq "graph"
$kind eq "line" $kind eq "graph"
Truth table33%1/3
A or B
A= $kind eq "line"B= $kind eq "graph"
ABresult
1X1
011
000
6636 0 ▶ my $x_col = $encode->{x} // '';
Condition0%0/2
$encode->{"x"} // ""
l!l
00
MC/DC0%0/1
$encode->{"x"} // ""
$encode->{"x"}
Truth table0%0/2
A
A= $encode->{"x"}
Aresult
11
00
6637 0 ▶ my $y_col = $encode->{y} // '';
Condition0%0/2
$encode->{"y"} // ""
l!l
00
MC/DC0%0/1
$encode->{"y"} // ""
$encode->{"y"}
Truth table0%0/2
A
A= $encode->{"y"}
Aresult
11
00
6638 0 ▶ return { error => 'Missing x or y column for line visual' }
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col and length $y_col 0 0 0
Condition0%0/3
length $x_col and length $y_col
!ll&&!rl&&r
000
MC/DC0%0/2
length $x_col and length $y_col
length $x_col length $y_col
Truth table0%0/3
A and B
A= length $x_colB= length $y_col
ABresult
0X0
100
111
6639 unless length($x_col) && length($y_col);
6640 0 ▶ return { error => "Column not found: $x_col" } unless $col_set{$x_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$x_col} 0 0 0
6641 0 ▶ return { error => "Column not found: $y_col" } unless $col_set{$y_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$y_col} 0 0 0
6642  
6643 # encode.series is what /graph's "Add to canvas" saves from series=: one
6644 # line per value of that column, as on the page. Without it every row
6645 # is one line, which runs through all the groups' points in turn.
6646 0 ▶ my $series_col = $encode->{series} // '';
Condition0%0/2
$encode->{"series"} // ""
l!l
00
MC/DC0%0/1
$encode->{"series"} // ""
$encode->{"series"}
Truth table0%0/2
A
A= $encode->{"series"}
Aresult
11
00
6647 0 ▶ $series_col = '' if ref $series_col;
Branch: 1 branch
BranchTrueFalseTotal
if ref $series_col 0 0 0
6648 return { error => "Column not found: $series_col" }
6649 0 ▶ if length $series_col && !$col_set{$series_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $series_col and not $col_set{$series_col} 0 0 0
Condition0%0/3
length $series_col and not $col_set{$series_col}
!ll&&!rl&&r
000
MC/DC0%0/2
length $series_col and not $col_set{$series_col}
length $series_col not $col_set{$series_col}
Truth table0%0/3
A and not(B)
A= length $series_colB= not $col_set{$series_col}
ABresult
0X0
100
111
6650  
6651 # A card whose spec names a measure plots one point per x value rather
6652 # than one per row: the shape /graph?agg= draws, and the only shape that
6653 # makes sense when the x axis is a bucket. The fold writes its result
6654 # back under the y column's own name, so the loop below is the same one
6655 # an unaggregated card runs, and the groups arrive in label order, which
6656 # for an ISO bucket is chronological order. With a series the fold is
6657 # per x value and series value, so each line has its own totals.
6658 0 my $rows = $vis_recs;
6659 0 my $m;
6660 0 ▶ if (defined $agg_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $agg_fn) 0 0 0
6661 0 $m = _visual_measure($agg_fn, $y_col);
6662 0 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 0 0
6663 my $agg = $self->_grouped_totals(
6664 { source => undef, records => $vis_recs },
6665 { by => [ $x_col, (length $series_col ? $series_col : ()) ],
6666 0 ▶ fn => $m->{fn}, val => $m->{val}, as => 'value' },
Branch: 1 branch
BranchTrueFalseTotal
length $series_col ? : 0 0 0
6667 );
6668 0 $rows = [ map { { %$_, $y_col => $_->{value} } } @$agg ];
6669 }
6670  
6671 0 my $sn;
6672 0 ▶ if (length $series_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col) { } 0 0 0
6673 # The order /graph draws, so each line has the page's colour:
6674 # aggregated, lines by name and points by label; unaggregated, lines
6675 # as first met and each keeping its rows' order.
6676 0 my (%points_of, @names);
6677 0 for my $row (@$rows) {
6678 0 ▶ my $xv = $row->{$x_col} // ''; next unless length $xv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $xv 0 0 0
Condition0%0/2
$row->{$x_col} // ""
l!l
00
MC/DC0%0/1
$row->{$x_col} // ""
$row->{$x_col}
Truth table0%0/2
A
A= $row->{$x_col}
Aresult
11
00
6679 0 ▶ my $name = $row->{$series_col} // ''; next unless length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless length $name 0 0 0
Condition0%0/2
$row->{$series_col} // ""
l!l
00
MC/DC0%0/1
$row->{$series_col} // ""
$row->{$series_col}
Truth table0%0/2
A
A= $row->{$series_col}
Aresult
11
00
6680 0 ▶ my $yn = _numeric_cell($row->{$y_col} // ''); next unless defined $yn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $yn 0 0 0
Condition0%0/2
$row->{$y_col} // ""
l!l
00
MC/DC0%0/1
$row->{$y_col} // ""
$row->{$y_col}
Truth table0%0/2
A
A= $row->{$y_col}
Aresult
11
00
6681 0 $name = _decode_cell($name);
6682 0 ▶ push @names, $name unless $points_of{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless $points_of{$name} 0 0 0
6683 0 push @{ $points_of{$name} }, { label => _decode_cell($xv), value => $yn };
6684 }
6685 0 ▶ return { error => 'No plottable data' } unless @names;
Branch: 1 branch
BranchTrueFalseTotal
unless @names 0 0 0
6686 my @series_data = map {
6687 0 my $points = $points_of{$_};
6688 0 ▶ $points = [ sort { $a->{label} cmp $b->{label} } @$points ] if $m;
Branch: 1 branch
BranchTrueFalseTotal
if $m 0 0 0
6689 0 ▶ { name => $_, data => $points };
Branch: 1 branch
BranchTrueFalseTotal
$m ? : 0 0 0
6690 } ($m ? sort @names : @names);
6691  
6692 0 ▶ $title ||= $m ? "$m->{label} by $x_col and $series_col" : "$y_col vs $x_col by $series_col";
Branch: 1 branch
BranchTrueFalseTotal
$m ? : 0 0 0
Condition0%0/3
$title ||= $m ? qq[$m->{"label"} by $x_col and $series_col] : "$y_col vs $x_col by $series_col"
l!l&&r!l&&!r
000
MC/DC0%0/2
$title ||= $m ? qq[$m->{"label"} by $x_col and $series_col] : "$y_col vs $x_col by $series_col"
$title $m ? qq[$m->{"label"} by $x_col and $series_col] : "$y_col vs $x_col by $series_col"
Truth table0%0/3
A ||= B
A= $titleB= $m ? qq[$m->{"label"} by $x_col and $series_col] : "$y_col vs $x_col by $series_col"
ABresult
1X1
011
000
6693 0 $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6694 ->render_multi_series_line_chart_snippet(\@series_data, { id => $svg_id });
6695 } else {
6696 0 my @pairs;
6697 0 for my $row (@$rows) {
6698 0 ▶ my $xv = $row->{$x_col} // ''; next unless length $xv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $xv 0 0 0
Condition0%0/2
$row->{$x_col} // ""
l!l
00
MC/DC0%0/1
$row->{$x_col} // ""
$row->{$x_col}
Truth table0%0/2
A
A= $row->{$x_col}
Aresult
11
00
6699 0 ▶ my $yn = _numeric_cell($row->{$y_col} // ''); next unless defined $yn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $yn 0 0 0
Condition0%0/2
$row->{$y_col} // ""
l!l
00
MC/DC0%0/1
$row->{$y_col} // ""
$row->{$y_col}
Truth table0%0/2
A
A= $row->{$y_col}
Aresult
11
00
6700 0 push @pairs, [_decode_cell($xv), $yn];
6701 }
6702 0 ▶ return { error => 'No plottable data' } unless @pairs;
Branch: 1 branch
BranchTrueFalseTotal
unless @pairs 0 0 0
6703  
6704 0 ▶ $title ||= $m ? "$m->{label} by $x_col" : "$y_col vs $x_col";
Branch: 1 branch
BranchTrueFalseTotal
$m ? : 0 0 0
Condition0%0/3
$title ||= $m ? qq[$m->{"label"} by $x_col] : "$y_col vs $x_col"
l!l&&r!l&&!r
000
MC/DC0%0/2
$title ||= $m ? qq[$m->{"label"} by $x_col] : "$y_col vs $x_col"
$title $m ? qq[$m->{"label"} by $x_col] : "$y_col vs $x_col"
Truth table0%0/3
A ||= B
A= $titleB= $m ? qq[$m->{"label"} by $x_col] : "$y_col vs $x_col"
ABresult
1X1
011
000
6705 0 $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6706 ->render_zoomable_line_chart_snippet(\@pairs, { id => $svg_id });
6707 }
6708 0 my $html = $sn->{html};
6709 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
6710 0 return { html => $html, title => $title };
6711 }
6712  
6713 # --------------------------------------------------------------- scatter --
6714 15 ▶ if ($kind eq 'scatter') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "scatter") 0 15 15
6715 0 ▶ my $x_col = $encode->{x} // '';
Condition0%0/2
$encode->{"x"} // ""
l!l
00
MC/DC0%0/1
$encode->{"x"} // ""
$encode->{"x"}
Truth table0%0/2
A
A= $encode->{"x"}
Aresult
11
00
6716 0 ▶ my $y_col = $encode->{y} // '';
Condition0%0/2
$encode->{"y"} // ""
l!l
00
MC/DC0%0/1
$encode->{"y"} // ""
$encode->{"y"}
Truth table0%0/2
A
A= $encode->{"y"}
Aresult
11
00
6717 0 ▶ return { error => 'Missing x or y column for scatter visual' }
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col and length $y_col 0 0 0
Condition0%0/3
length $x_col and length $y_col
!ll&&!rl&&r
000
MC/DC0%0/2
length $x_col and length $y_col
length $x_col length $y_col
Truth table0%0/3
A and B
A= length $x_colB= length $y_col
ABresult
0X0
100
111
6718 unless length($x_col) && length($y_col);
6719 0 ▶ return { error => "Column not found: $x_col" } unless $col_set{$x_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$x_col} 0 0 0
6720 0 ▶ return { error => "Column not found: $y_col" } unless $col_set{$y_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$y_col} 0 0 0
6721  
6722 # series and size are what /scatter's "Add to canvas" saves from series=
6723 # and size=; scheme, min_r and max_r come with them in options. A
6724 # canvas stores a visual unchecked (PUT, PATCH, import), so the scheme
6725 # goes through _categorical_scheme -- HTML::D3 writes it into the script
6726 # -- and an unknown one draws the default colours, as on a pie card.
6727 0 ▶ my $series_col = $encode->{series} // '';
Condition0%0/2
$encode->{"series"} // ""
l!l
00
MC/DC0%0/1
$encode->{"series"} // ""
$encode->{"series"}
Truth table0%0/2
A
A= $encode->{"series"}
Aresult
11
00
6728 0 ▶ my $size_col = $encode->{size} // '';
Condition0%0/2
$encode->{"size"} // ""
l!l
00
MC/DC0%0/1
$encode->{"size"} // ""
$encode->{"size"}
Truth table0%0/2
A
A= $encode->{"size"}
Aresult
11
00
6729 0 ▶ $series_col = '' if ref $series_col;
Branch: 1 branch
BranchTrueFalseTotal
if ref $series_col 0 0 0
6730 0 ▶ $size_col = '' if ref $size_col;
Branch: 1 branch
BranchTrueFalseTotal
if ref $size_col 0 0 0
6731 return { error => "Column not found: $series_col" }
6732 0 ▶ if length $series_col && !$col_set{$series_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $series_col and not $col_set{$series_col} 0 0 0
Condition0%0/3
length $series_col and not $col_set{$series_col}
!ll&&!rl&&r
000
MC/DC0%0/2
length $series_col and not $col_set{$series_col}
length $series_col not $col_set{$series_col}
Truth table0%0/3
A and not(B)
A= length $series_colB= not $col_set{$series_col}
ABresult
0X0
100
111
6733 return { error => "Column not found: $size_col" }
6734 0 ▶ if length $size_col && !$col_set{$size_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $size_col and not $col_set{$size_col} 0 0 0
Condition0%0/3
length $size_col and not $col_set{$size_col}
!ll&&!rl&&r
000
MC/DC0%0/2
length $size_col and not $col_set{$size_col}
length $size_col not $col_set{$size_col}
Truth table0%0/3
A and not(B)
A= length $size_colB= not $col_set{$size_col}
ABresult
0X0
100
111
6735  
6736 0 my @points;
6737 0 for my $row (@$vis_recs) {
6738 0 ▶ my $xv = _numeric_cell($row->{$x_col} // ''); next unless defined $xv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $xv 0 0 0
Condition0%0/2
$row->{$x_col} // ""
l!l
00
MC/DC0%0/1
$row->{$x_col} // ""
$row->{$x_col}
Truth table0%0/2
A
A= $row->{$x_col}
Aresult
11
00
6739 0 ▶ my $yv = _numeric_cell($row->{$y_col} // ''); next unless defined $yv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $yv 0 0 0
Condition0%0/2
$row->{$y_col} // ""
l!l
00
MC/DC0%0/1
$row->{$y_col} // ""
$row->{$y_col}
Truth table0%0/2
A
A= $row->{$y_col}
Aresult
11
00
6740 0 my %meta;
6741 0 ▶ $meta{series} = _decode_cell($row->{$series_col} // '') if length $series_col;
Branch: 1 branch
BranchTrueFalseTotal
if length $series_col 0 0 0
Condition0%0/2
$row->{$series_col} // ""
l!l
00
MC/DC0%0/1
$row->{$series_col} // ""
$row->{$series_col}
Truth table0%0/2
A
A= $row->{$series_col}
Aresult
11
00
6742 0 ▶ if (length $size_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $size_col) 0 0 0
6743 0 ▶ my $sv = _numeric_cell($row->{$size_col} // '');
Condition0%0/2
$row->{$size_col} // ""
l!l
00
MC/DC0%0/1
$row->{$size_col} // ""
$row->{$size_col}
Truth table0%0/2
A
A= $row->{$size_col}
Aresult
11
00
6744 0 ▶ $meta{size} = $sv if defined $sv;
Branch: 1 branch
BranchTrueFalseTotal
if defined $sv 0 0 0
6745 }
6746 0 ▶ push @points, [$xv, $yv, {}, (%meta ? \%meta : ())];
Branch: 1 branch
BranchTrueFalseTotal
%meta ? : 0 0 0
6747 }
6748 0 ▶ return { error => 'No plottable data' } unless @points;
Branch: 1 branch
BranchTrueFalseTotal
unless @points 0 0 0
6749  
6750 0 ▶ $title ||= "$y_col vs $x_col";
Condition0%0/2
$title ||= "$y_col vs $x_col"
l!l
00
MC/DC0%0/1
$title ||= "$y_col vs $x_col"
$title
Truth table0%0/2
A
A= $title
Aresult
11
00
6751 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6752 ->render_scatter_chart_snippet(\@points, {
6753 x_label => $x_col,
6754 y_label => $y_col,
6755 id => $svg_id,
6756 (length $series_col
6757 ? (colour_by_series => 1, series_col => $series_col,
6758 scheme => _categorical_scheme($options->{scheme}))
6759 : ()),
6760 (length $size_col
6761 ? (size_col => $size_col,
6762 0 ▶ radius_range => [ _scatter_radii($options->{min_r}, $options->{max_r}) ])
Branch: 2 branches
BranchTrueFalseTotal
length $series_col ? : 0 0 0
length $size_col ? : 0 0 0
6763 : ()),
6764 });
6765 0 my $html = $sn->{html};
6766 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
6767 0 return { html => $html, title => $title };
6768 }
6769  
6770 # -------------------------------------------------------------- heatmap --
6771 15 ▶ if ($kind eq 'heatmap') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "heatmap") 1 14 15
6772 1 ▶ my $x_col = $encode->{x} // '';
Condition50%1/2
$encode->{"x"} // ""
l!l
10
MC/DC0%0/1
$encode->{"x"} // ""
$encode->{"x"}
Truth table50%1/2
A
A= $encode->{"x"}
Aresult
11
00
6773 1 ▶ my $y_col = $encode->{y} // '';
Condition50%1/2
$encode->{"y"} // ""
l!l
10
MC/DC0%0/1
$encode->{"y"} // ""
$encode->{"y"}
Truth table50%1/2
A
A= $encode->{"y"}
Aresult
11
00
6774 1 ▶ my $val_col = $encode->{value} // '';
Condition50%1/2
$encode->{"value"} // ""
l!l
10
MC/DC0%0/1
$encode->{"value"} // ""
$encode->{"value"}
Truth table50%1/2
A
A= $encode->{"value"}
Aresult
11
00
6775 1 ▶ return { error => 'Missing x or y column for heatmap visual' }
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col and length $y_col 0 1 1
Condition33%1/3
length $x_col and length $y_col
!ll&&!rl&&r
001
MC/DC0%0/2
length $x_col and length $y_col
length $x_col length $y_col
Truth table33%1/3
A and B
A= length $x_colB= length $y_col
ABresult
0X0
100
111
6776 unless length($x_col) && length($y_col);
6777 1 ▶ return { error => "Column not found: $x_col" } unless $col_set{$x_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$x_col} 0 1 1
6778 1 ▶ return { error => "Column not found: $y_col" } unless $col_set{$y_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$y_col} 0 1 1
6779 return { error => "Column not found: $val_col" }
6780 1 ▶ if length($val_col) && !$col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $val_col and not $col_set{$val_col} 0 1 1
Condition33%1/3
length $val_col and not $col_set{$val_col}
!ll&&!rl&&r
010
MC/DC0%0/2
length $val_col and not $col_set{$val_col}
length $val_col not $col_set{$val_col}
Truth table33%1/3
A and not(B)
A= length $val_colB= not $col_set{$val_col}
ABresult
0X0
100
111
6781  
6782 1 my (@x_order, @y_order, %seen_x, %seen_y);
6783 1 for my $row (@$vis_recs) {
6784 6 ▶ my $xv = $row->{$x_col} // ''; next unless length $xv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $xv 0 6 6
Condition50%1/2
$row->{$x_col} // ""
l!l
60
MC/DC0%0/1
$row->{$x_col} // ""
$row->{$x_col}
Truth table50%1/2
A
A= $row->{$x_col}
Aresult
11
00
6785 6 ▶ my $yv = $row->{$y_col} // ''; next unless length $yv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $yv 0 6 6
Condition50%1/2
$row->{$y_col} // ""
l!l
60
MC/DC0%0/1
$row->{$y_col} // ""
$row->{$y_col}
Truth table50%1/2
A
A= $row->{$y_col}
Aresult
11
00
6786 6 ▶ push @x_order, $xv unless $seen_x{$xv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_x{$xv}++ 4 2 6
6787 6 ▶ push @y_order, $yv unless $seen_y{$yv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_y{$yv}++ 3 3 6
6788 }
6789 1 my $m = _visual_measure($agg_fn, $val_col);
6790 1 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 1 1
6791  
6792 my $agg = $self->_grouped_totals(
6793 { source => $agg_src, records => $vis_recs },
6794 { by => [$x_col, $y_col],
6795 fn => $m->{fn},
6796 val => $m->{val},
6797 1 as => 'value' },
6798 );
6799 1 my %grid;
6800 1 for my $r (@$agg) {
6801 6 $grid{$r->{$x_col}}{$r->{$y_col}} = $r->{value};
6802 }
6803 my @triples = map {
6804 1 my ($raw_x, $xv) = ($_, _decode_cell($_));
6805 4 ▶ map { [$xv, _decode_cell($_), $grid{$raw_x}{$_} // 0] } @y_order
Condition100%2/2
$grid{$raw_x}{$_} // 0
l!l
66
MC/DC100%1/1
$grid{$raw_x}{$_} // 0
$grid{$raw_x}{$_}
Truth table100%2/2
A
A= $grid{$raw_x}{$_}
Aresult
11
00
6806 } @x_order;
6807 1 ▶ return { error => 'No plottable data' } unless @triples;
Branch: 1 branch
BranchTrueFalseTotal
unless @triples 0 1 1
6808  
6809 1 ▶ $title ||= "$m->{label} by $x_col and $y_col";
Condition50%1/2
$title ||= qq[$m->{"label"} by $x_col and $y_col]
l!l
01
MC/DC0%0/1
$title ||= qq[$m->{"label"} by $x_col and $y_col]
$title
Truth table50%1/2
A
A= $title
Aresult
11
00
6810 1 my $scheme = _sequential_scheme($options->{scheme});
6811 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6812 ->render_heatmap_snippet(\@triples, {
6813 x_label => $x_col,
6814 y_label => $y_col,
6815 val_label => $m->{label},
6816 color_scheme => $scheme,
6817 1 ▶ show_values => ($options->{show_values} ? 1 : 0),
Branch: 1 branch
BranchTrueFalseTotal
$options->{'show_values'} ? : 0 1 1
6818 id => $svg_id,
6819 });
6820 1 my $html = $sn->{html};
6821 1 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 1 1
6822 1 return { html => $html, title => $title };
6823 }
6824  
6825 # --------------------------------------------------------------- stacked --
6826 14 ▶ if ($kind eq 'stacked') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "stacked") 0 14 14
6827 0 ▶ my $cat_col = $encode->{cat} // '';
Condition0%0/2
$encode->{"cat"} // ""
l!l
00
MC/DC0%0/1
$encode->{"cat"} // ""
$encode->{"cat"}
Truth table0%0/2
A
A= $encode->{"cat"}
Aresult
11
00
6828 0 ▶ my $seg_col = $encode->{series} // '';
Condition0%0/2
$encode->{"series"} // ""
l!l
00
MC/DC0%0/1
$encode->{"series"} // ""
$encode->{"series"}
Truth table0%0/2
A
A= $encode->{"series"}
Aresult
11
00
6829 0 ▶ my $val_col = $encode->{value} // '';
Condition0%0/2
$encode->{"value"} // ""
l!l
00
MC/DC0%0/1
$encode->{"value"} // ""
$encode->{"value"}
Truth table0%0/2
A
A= $encode->{"value"}
Aresult
11
00
6830 0 ▶ return { error => 'Missing cat or series column for stacked visual' }
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col and length $seg_col 0 0 0
Condition0%0/3
length $cat_col and length $seg_col
!ll&&!rl&&r
000
MC/DC0%0/2
length $cat_col and length $seg_col
length $cat_col length $seg_col
Truth table0%0/3
A and B
A= length $cat_colB= length $seg_col
ABresult
0X0
100
111
6831 unless length($cat_col) && length($seg_col);
6832 0 ▶ return { error => "Column not found: $cat_col" } unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 0 0 0
6833 0 ▶ return { error => "Column not found: $seg_col" } unless $col_set{$seg_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$seg_col} 0 0 0
6834 0 ▶ my $count_mode = (!length $val_col || $val_col eq '__count__');
Condition0%0/3
!length($val_col) || $val_col eq '__count__'
l!l&&r!l&&!r
000
MC/DC0%0/2
!length($val_col) || $val_col eq '__count__'
!length($val_col) $val_col eq '__count__'
Truth table0%0/3
not(A) || B
A= !length($val_col)B= $val_col eq '__count__'
ABresult
1X1
011
000
6835 return { error => "Column not found: $val_col" }
6836 0 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 0 0 0
Condition0%0/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
000
MC/DC0%0/2
$count_mode or $col_set{$val_col}
$count_mode $col_set{$val_col}
Truth table0%0/3
A or B
A= $count_modeB= $col_set{$val_col}
ABresult
1X1
011
000
6837  
6838 0 my $m = _visual_measure($agg_fn, $val_col);
6839 0 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 0 0
6840  
6841 my $agg = $self->_grouped_totals(
6842 { source => $agg_src, records => $vis_recs },
6843 { by => [$cat_col, $seg_col],
6844 fn => $m->{fn},
6845 val => $m->{val},
6846 0 as => 'value' },
6847 );
6848 my @data = map {
6849 0 ▶ my ($c, $s) = ($_->{$cat_col}//'', $_->{$seg_col}//'');
Condition0%0/4
$_->{$cat_col} // ""
l!l
00
$_->{$seg_col} // ""
l!l
00
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
MC/DC0%0/1
$_->{$seg_col} // ""
$_->{$seg_col}
Truth table0%0/2
A
A= $_->{$cat_col}
Aresult
11
00
Truth table0%0/2
A
A= $_->{$seg_col}
Aresult
11
00
6850 (length $c && length $s)
6851 ? { cat => $c, seg => $s, val => $_->{value} }
6852 : ()
6853 0 ▶ } @$agg;
Branch: 1 branch
BranchTrueFalseTotal
length $c && length $s ? : 0 0 0
Condition0%0/3
length $c and length $s
!ll&&!rl&&r
000
MC/DC0%0/2
length $c and length $s
length $c length $s
Truth table0%0/3
A and B
A= length $cB= length $s
ABresult
0X0
100
111
6854 0 ▶ return { error => 'No plottable data' } unless @data;
Branch: 1 branch
BranchTrueFalseTotal
unless @data 0 0 0
6855  
6856 0 ▶ $title ||= "$m->{label} by $cat_col and $seg_col";
Condition0%0/2
$title ||= qq[$m->{"label"} by $cat_col and $seg_col]
l!l
00
MC/DC0%0/1
$title ||= qq[$m->{"label"} by $cat_col and $seg_col]
$title
Truth table0%0/2
A
A= $title
Aresult
11
00
6857 0 my $scheme = _categorical_scheme($options->{scheme});
6858 0 ▶ my $orient = (_chart_orientation($options) eq 'horizontal') ? 'h' : 'v';
Branch: 1 branch
BranchTrueFalseTotal
_chart_orientation($options) eq 'horizontal' ? : 0 0 0
6859 0 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6860 ->render_stacked_bar_snippet(\@data, {
6861 scheme => $scheme,
6862 x_label => $cat_col,
6863 orient => $orient,
6864 id => $svg_id,
6865 });
6866 0 my $html = $sn->{html};
6867 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
6868 0 return { html => $html, title => $title };
6869 }
6870  
6871 # ---------------------------------------------------------------- combo --
6872 14 ▶ if ($kind eq 'combo') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "combo") 0 14 14
6873 0 ▶ my $x_col = $encode->{cat} // $encode->{x} // '';
Condition0%0/5
($encode->{"cat"} // $encode->{"x"}) // ""
l!l
00
$encode->{"cat"} // $encode->{"x"}
l!l&&r!l&&!r
000
MC/DC0%0/2
($encode->{"cat"} // $encode->{"x"}) // ""
$encode->{"cat"} $encode->{"x"}
Truth table0%0/3
A // B
A= $encode->{"cat"}B= $encode->{"x"}
ABresult
1X1
011
000
6874 0 ▶ my $bar_col = $encode->{bar_val} // $encode->{bar} // '';
Condition0%0/5
($encode->{"bar_val"} // $encode->{"bar"}) // ""
l!l
00
$encode->{"bar_val"} // $encode->{"bar"}
l!l&&r!l&&!r
000
MC/DC0%0/2
($encode->{"bar_val"} // $encode->{"bar"}) // ""
$encode->{"bar_val"} $encode->{"bar"}
Truth table0%0/3
A // B
A= $encode->{"bar_val"}B= $encode->{"bar"}
ABresult
1X1
011
000
6875 0 ▶ my $line_col = $encode->{line_val} // $encode->{line} // '';
Condition0%0/5
($encode->{"line_val"} // $encode->{"line"}) // ""
l!l
00
$encode->{"line_val"} // $encode->{"line"}
l!l&&r!l&&!r
000
MC/DC0%0/2
($encode->{"line_val"} // $encode->{"line"}) // ""
$encode->{"line_val"} $encode->{"line"}
Truth table0%0/3
A // B
A= $encode->{"line_val"}B= $encode->{"line"}
ABresult
1X1
011
000
6876 0 ▶ return { error => 'Missing cat, bar_val, or line_val for combo visual' }
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col and length $bar_col and length $line_col 0 0 0
Condition0%0/6
length $x_col and length $bar_col and length $line_col
!ll&&!rl&&r
000
length $x_col and length $bar_col
!ll&&!rl&&r
000
MC/DC0%0/3
length $x_col and length $bar_col and length $line_col
length $x_col length $bar_col length $line_col
Truth table0%0/4
A and B and C
A= length $x_colB= length $bar_colC= length $line_col
ABCresult
0XX0
10X0
1100
1111
6877 unless length($x_col) && length($bar_col) && length($line_col);
6878 0 ▶ return { error => "Column not found: $x_col" } unless $col_set{$x_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$x_col} 0 0 0
6879 0 ▶ return { error => "Column not found: $bar_col" } unless $col_set{$bar_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$bar_col} 0 0 0
6880 0 ▶ return { error => "Column not found: $line_col" } unless $col_set{$line_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$line_col} 0 0 0
6881  
6882 # One card, one function: a combo aggregates both its series the same
6883 # way, so the two cannot be read against different arithmetic by
6884 # accident.
6885 0 my $bar_m = _visual_measure($agg_fn, $bar_col);
6886 0 my $line_m = _visual_measure($agg_fn, $line_col);
6887 0 ▶ return { error => $bar_m->{error} } if $bar_m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $bar_m->{"error"} 0 0 0
6888 0 ▶ return { error => $line_m->{error} } if $line_m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $line_m->{"error"} 0 0 0
6889  
6890 my $bar_rows = $self->_grouped_totals(
6891 { source => $agg_src, records => $vis_recs },
6892 0 { by => [$x_col], fn => $bar_m->{fn}, val => $bar_m->{val}, as => 'bar_val' },
6893 );
6894 my $line_rows = $self->_grouped_totals(
6895 { source => $agg_src, records => $vis_recs },
6896 0 { by => [$x_col], fn => $line_m->{fn}, val => $line_m->{val}, as => 'line_val' },
6897 );
6898 0 my (%bar_map, %line_map, @x_order, %x_seen);
6899 0 for my $r (@$bar_rows) {
6900 0 ▶ my $xv = _decode_cell($r->{$x_col} // ''); next unless length $xv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $xv 0 0 0
Condition0%0/2
$r->{$x_col} // ""
l!l
00
MC/DC0%0/1
$r->{$x_col} // ""
$r->{$x_col}
Truth table0%0/2
A
A= $r->{$x_col}
Aresult
11
00
6901 0 ▶ push @x_order, $xv unless $x_seen{$xv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $x_seen{$xv}++ 0 0 0
6902 0 $bar_map{$xv} = $r->{bar_val};
6903 }
6904 0 for my $r (@$line_rows) {
6905 0 ▶ my $xv = _decode_cell($r->{$x_col} // ''); next unless length $xv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $xv 0 0 0
Condition0%0/2
$r->{$x_col} // ""
l!l
00
MC/DC0%0/1
$r->{$x_col} // ""
$r->{$x_col}
Truth table0%0/2
A
A= $r->{$x_col}
Aresult
11
00
6906 0 ▶ push @x_order, $xv unless $x_seen{$xv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $x_seen{$xv}++ 0 0 0
6907 0 $line_map{$xv} = $r->{line_val};
6908 }
6909 0 ▶ return { error => 'No plottable data' } unless @x_order;
Branch: 1 branch
BranchTrueFalseTotal
unless @x_order 0 0 0
6910  
6911 0 my @data = map { { x => $_, bar_val => $bar_map{$_}, line_val => $line_map{$_} } }
6912 @x_order;
6913 # Sum keeps the columns in the title because that is what the card has
6914 # always said; count needs no column, so it reads as the tally it is.
6915 $title ||= ($bar_m->{fn} eq 'sum')
6916 ? "$bar_col and $line_col by $x_col"
6917 0 ▶ : ($bar_m->{fn} eq 'count')
Branch: 2 branches
BranchTrueFalseTotal
$bar_m->{'fn'} eq 'sum' ? : 0 0 0
$bar_m->{'fn'} eq 'count' ? : 0 0 0
Condition0%0/3
$title ||= $bar_m->{"fn"} eq "sum" ? "$bar_col and $line_col by $x_col" : ($bar_m->{"fn"} eq "count" ? "Count by $x_col" : qq[$bar_m->{"fn"} of $bar_col and $line_col by $x_col])
l!l&&r!l&&!r
000
MC/DC0%0/2
$title ||= $bar_m->{"fn"} eq "sum" ? "$bar_col and $line_col by $x_col" : ($bar_m->{"fn"} eq "count" ? "Count by $x_col" : qq[$bar_m->{"fn"} of $bar_col and $line_col by $x_col])
$title $bar_m->{"fn"} eq "sum" ? "$bar_col and $line_col by $x_col" : ($bar_m->{"fn"} eq "count" ? "Count by $x_col" : qq[$bar_m->{"fn"} of $bar_col and $line_col by $x_col])
Truth table0%0/3
A ||= B
A= $titleB= $bar_m->{"fn"} eq "sum" ? "$bar_col and $line_col by $x_col" : ($bar_m->{"fn"} eq "count" ? "Count by $x_col" : qq[$bar_m->{"fn"} of $bar_col and $line_col by $x_col])
ABresult
1X1
011
000
6918 ? "Count by $x_col"
6919 : "$bar_m->{fn} of $bar_col and $line_col by $x_col";
6920 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6921 ->render_combo_snippet(\@data, {
6922 bar_label => $bar_col,
6923 line_label => $line_col,
6924 id => $svg_id,
6925 # What /combo saves from scheme=, checked again: a canvas stores it
6926 # unchecked.
6927 0 ▶ (_optional_scheme($options->{scheme}) ? (scheme => $options->{scheme}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
_optional_scheme($options->{'scheme'}) ? : 0 0 0
6928 });
6929 0 my $html = $sn->{html};
6930 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
6931 0 return { html => $html, title => $title };
6932 }
6933  
6934 # --------------------------------------------------------------- treemap --
6935 14 ▶ if ($kind eq 'treemap') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "treemap") 0 14 14
6936 0 ▶ my $cat_col = $encode->{group} // $encode->{cat} // '';
Condition0%0/5
($encode->{"group"} // $encode->{"cat"}) // ""
l!l
00
$encode->{"group"} // $encode->{"cat"}
l!l&&r!l&&!r
000
MC/DC0%0/2
($encode->{"group"} // $encode->{"cat"}) // ""
$encode->{"group"} $encode->{"cat"}
Truth table0%0/3
A // B
A= $encode->{"group"}B= $encode->{"cat"}
ABresult
1X1
011
000
6937 0 ▶ my $val_col = $encode->{size} // $encode->{value} // '';
Condition0%0/5
($encode->{"size"} // $encode->{"value"}) // ""
l!l
00
$encode->{"size"} // $encode->{"value"}
l!l&&r!l&&!r
000
MC/DC0%0/2
($encode->{"size"} // $encode->{"value"}) // ""
$encode->{"size"} $encode->{"value"}
Truth table0%0/3
A // B
A= $encode->{"size"}B= $encode->{"value"}
ABresult
1X1
011
000
6938 0 ▶ return { error => 'Missing group column for treemap visual' } unless length $cat_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col 0 0 0
6939 0 ▶ return { error => "Column not found: $cat_col" } unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 0 0 0
6940 0 ▶ my $count_mode = (!length $val_col || $val_col eq '__count__');
Condition0%0/3
!length($val_col) || $val_col eq '__count__'
l!l&&r!l&&!r
000
MC/DC0%0/2
!length($val_col) || $val_col eq '__count__'
!length($val_col) $val_col eq '__count__'
Truth table0%0/3
not(A) || B
A= !length($val_col)B= $val_col eq '__count__'
ABresult
1X1
011
000
6941 return { error => "Column not found: $val_col" }
6942 0 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 0 0 0
Condition0%0/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
000
MC/DC0%0/2
$count_mode or $col_set{$val_col}
$count_mode $col_set{$val_col}
Truth table0%0/3
A or B
A= $count_modeB= $col_set{$val_col}
ABresult
1X1
011
000
6943  
6944 0 my $m = _visual_measure($agg_fn, $val_col);
6945 0 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 0 0
6946  
6947 # encode.color and options.color_agg / color_scheme are what /treemap
6948 # saves from color=, color_agg= and color_scheme=. The function is
6949 # checked by _tile_colour_measure, as the page's is; the scheme falls back as the
6950 # heatmap's does, since HTML::D3 refuses a name it does not know.
6951 0 ▶ my $color_col = $encode->{color} // '';
Condition0%0/2
$encode->{"color"} // ""
l!l
00
MC/DC0%0/1
$encode->{"color"} // ""
$encode->{"color"}
Truth table0%0/2
A
A= $encode->{"color"}
Aresult
11
00
6952 0 ▶ $color_col = '' if ref $color_col;
Branch: 1 branch
BranchTrueFalseTotal
if ref $color_col 0 0 0
6953 0 my $color_m;
6954 0 ▶ if (length $color_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $color_col) 0 0 0
6955 0 ▶ return { error => "Column not found: $color_col" } unless $col_set{$color_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$color_col} 0 0 0
6956 0 $color_m = $self->_tile_colour_measure($options->{color_agg}, $color_col);
6957 0 ▶ return { error => $color_m->{error} } if $color_m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $color_m->{"error"} 0 0 0
6958 }
6959  
6960 my $agg = $self->_grouped_totals(
6961 { source => $agg_src, records => $vis_recs },
6962 { by => [$cat_col],
6963 fn => $m->{fn},
6964 val => $m->{val},
6965 0 as => 'value' },
6966 );
6967 0 ▶ return { error => 'No plottable data' } unless @$agg;
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg 0 0 0
6968 0 ▶ my $colour_of = $color_m
Branch: 1 branch
BranchTrueFalseTotal
$color_m ? : 0 0 0
6969 ? $self->_tile_colours($agg_src, $vis_recs, $cat_col, $color_m)
6970 : {};
6971  
6972 0 ▶ $title ||= "$m->{label} by $cat_col" . ($color_m ? " coloured by $color_m->{label}" : q{});
Branch: 1 branch
BranchTrueFalseTotal
$color_m ? : 0 0 0
Condition0%0/3
$title ||= qq[$m->{"label"} by $cat_col] . ($color_m ? qq[ coloured by $color_m->{"label"}] : "")
l!l&&r!l&&!r
000
MC/DC0%0/2
$title ||= qq[$m->{"label"} by $cat_col] . ($color_m ? qq[ coloured by $color_m->{"label"}] : "")
$title qq[$m->{"label"} by $cat_col] . ($color_m ? qq[ coloured by $color_m->{"label"}] : "")
Truth table0%0/3
A ||= B
A= $titleB= qq[$m->{"label"} by $cat_col] . ($color_m ? qq[ coloured by $color_m->{"label"}] : "")
ABresult
1X1
011
000
6973 0 my $scheme = _categorical_scheme($options->{scheme});
6974 # The snippet takes one row per tile as { path, value }, the shape the
6975 # treemap page builds; a [label, value] pair is not a path and croaks.
6976 my @tiles = map {
6977 0 ▶ my $cv = $colour_of->{ $_->{$cat_col} // '' };
Condition0%0/2
$_->{$cat_col} // ""
l!l
00
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
Truth table0%0/2
A
A= $_->{$cat_col}
Aresult
11
00
6978 +{ path => 'Root/' . _decode_cell($_->{$cat_col}), value => $_->{value},
6979 0 ▶ (defined $cv ? (color_value => $cv) : ()) }
Branch: 1 branch
BranchTrueFalseTotal
defined $cv ? : 0 0 0
6980 } @$agg;
6981 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6982 ->render_treemap_snippet(\@tiles, {
6983 scheme => $scheme,
6984 id => $svg_id,
6985 ($color_m
6986 ? (color_scheme => _sequential_scheme($options->{color_scheme}),
6987 color_label => $color_m->{label})
6988 0 ▶ : ()),
Branch: 1 branch
BranchTrueFalseTotal
$color_m ? : 0 0 0
6989 });
6990 0 my $html = $sn->{html};
6991 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
6992 0 return { html => $html, title => $title };
6993 }
6994  
6995 # ------------------------------------------------------------ histogram --
6996 14 ▶ if ($kind eq 'histogram') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "histogram") 0 14 14
6997 0 ▶ my $col = $encode->{value} // $encode->{col} // '';
Condition0%0/5
($encode->{"value"} // $encode->{"col"}) // ""
l!l
00
$encode->{"value"} // $encode->{"col"}
l!l&&r!l&&!r
000
MC/DC0%0/2
($encode->{"value"} // $encode->{"col"}) // ""
$encode->{"value"} $encode->{"col"}
Truth table0%0/3
A // B
A= $encode->{"value"}B= $encode->{"col"}
ABresult
1X1
011
000
6998 0 ▶ return { error => 'Missing col for histogram visual' } unless length $col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 0 0 0
6999 0 ▶ return { error => "Column not found: $col" } unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 0 0 0
7000  
7001 0 my @values;
7002 0 for my $row (@$vis_recs) {
7003 0 ▶ my $v = _numeric_cell($row->{$col} // '');
Condition0%0/2
$row->{$col} // ""
l!l
00
MC/DC0%0/1
$row->{$col} // ""
$row->{$col}
Truth table0%0/2
A
A= $row->{$col}
Aresult
11
00
7004 0 ▶ push @values, $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 0 0 0
7005 }
7006 0 ▶ return { error => 'No plottable data' } unless @values;
Branch: 1 branch
BranchTrueFalseTotal
unless @values 0 0 0
7007  
7008 0 ▶ my $bins = _whole_number($options->{bins}) // 10;
Condition0%0/2
_whole_number($options->{"bins"}) // 10
l!l
00
MC/DC0%0/1
_whole_number($options->{"bins"}) // 10
_whole_number($options->{"bins"})
Truth table0%0/2
A
A= _whole_number($options->{"bins"})
Aresult
11
00
7009 0 ▶ $bins = 1 if $bins < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $bins < 1 0 0 0
7010 0 ▶ $bins = $MAX_HISTOGRAM_BINS if $bins > $MAX_HISTOGRAM_BINS;
Branch: 1 branch
BranchTrueFalseTotal
if $bins > $MAX_HISTOGRAM_BINS 0 0 0
7011 0 my $min_v = min(@values);
7012 0 my $max_v = max(@values);
7013 0 my @bin_data;
7014 0 ▶ if ($min_v == $max_v) {
Branch: 1 branch
BranchTrueFalseTotal
if ($min_v == $max_v) { } 0 0 0
7015 0 push @bin_data, { label => "$min_v", count => scalar @values,
7016 lo => $min_v, hi => $min_v };
7017 } else {
7018 0 my $raw_w = ($max_v - $min_v) / $bins;
7019 0 my $width = sprintf('%.10g', $raw_w) + 0;
7020 0 ▶ $width = $raw_w if $width <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $width <= 0 0 0 0
7021 0 ▶ my $fmt = ($width == int($width)) ? '%d' : '%g';
Branch: 1 branch
BranchTrueFalseTotal
$width == int $width ? : 0 0 0
7022 0 my (@bin_counts, @bin_los);
7023 0 for my $i (0 .. $bins - 1) {
7024 0 push @bin_los, $min_v + $i * $width;
7025 0 push @bin_counts, 0;
7026 }
7027 0 for my $v (@values) {
7028 0 my $idx = POSIX::floor(sprintf('%.10g', ($v - $min_v) / $width) + 0);
7029 0 ▶ $idx = $bins - 1 if $idx >= $bins;
Branch: 1 branch
BranchTrueFalseTotal
if $idx >= $bins 0 0 0
7030 0 ▶ $idx = 0 if $idx < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $idx < 0 0 0 0
7031 0 $bin_counts[$idx]++;
7032 }
7033 0 for my $i (0 .. $bins - 1) {
7034 0 ▶ next unless $bin_counts[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless $bin_counts[$i] 0 0 0
7035 0 my $lo = $bin_los[$i];
7036 0 my $hi = $lo + $width;
7037 0 push @bin_data, {
7038 label => sprintf("[${fmt},${fmt})", $lo, $hi),
7039 count => $bin_counts[$i],
7040 lo => $lo,
7041 hi => $hi,
7042 };
7043 }
7044 }
7045  
7046 0 ▶ $title ||= "Distribution of $col";
Condition0%0/2
$title ||= "Distribution of $col"
l!l
00
MC/DC0%0/1
$title ||= "Distribution of $col"
$title
Truth table0%0/2
A
A= $title
Aresult
11
00
7047 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
7048 ->render_histogram_snippet(\@bin_data, {
7049 binned => 1,
7050 x_label => $col,
7051 id => $svg_id,
7052 # What /histogram saves from scheme=. Stored unchecked, so it
7053 # goes through the same check as the page's.
7054 0 ▶ (_optional_scheme($options->{scheme}) ? (scheme => $options->{scheme}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
_optional_scheme($options->{'scheme'}) ? : 0 0 0
7055 });
7056 0 my $html = $sn->{html};
7057 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
7058 0 return { html => $html, title => $title };
7059 }
7060  
7061 # ------------------------------------------------------------------- map --
7062 14 ▶ if ($kind eq 'map') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "map") 2 12 14
7063 2 my $map = $self->_map_data(
7064 $vis_recs, $columns, $encode, $options, $spec_key, $vis_id,
7065 );
7066 2 ▶ return { error => $map->{error} } if $map->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $map->{"error"} 1 1 2
7067  
7068 1 my $html = '';
7069 1 ▶ if ($map->{map_body}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($map->{"map_body"}) 0 1 1
7070 0 $html .= '<div class="canvas-map-wrap">' . $map->{map_body} . '</div>';
7071 }
7072 1 ▶ if ($map->{marker_count}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($map->{"marker_count"}) 0 1 1
7073 $html .= '<p class="map-summary">Plotting '
7074 . $map->{marker_count} . ' marker' . ($map->{marker_count} == 1 ? '' : 's')
7075 . ' for ' . $map->{row_count} . ' of ' . $map->{source_rows}
7076 0 ▶ . ' row' . ($map->{source_rows} == 1 ? '' : 's') . '.</p>';
Branch: 2 branches
BranchTrueFalseTotal
$map->{'marker_count'} == 1 ? : 0 0 0
$map->{'source_rows'} == 1 ? : 0 0 0
7077 }
7078 1 ▶ if (@{ $map->{messages} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$map->{"messages"};}) 1 0 1
7079 $html .= '<div class="map-notes" role="status"><ul>'
7080 . join('', map {
7081 '<li class="map-note" data-key="' . xml_escape($_->{key} // '') . '">'
7082 3 ▶ . xml_escape($_->{text} // '') . '</li>'
Condition50%2/4
$_->{"key"} // ""
l!l
30
$_->{"text"} // ""
l!l
30
MC/DC0%0/1
$_->{"key"} // ""
$_->{"key"}
MC/DC0%0/1
$_->{"text"} // ""
$_->{"text"}
Truth table50%1/2
A
A= $_->{"key"}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"text"}
Aresult
11
00
7083 1 } @{ $map->{messages} })
7084 . '</ul></div>';
7085 }
7086  
7087 return {
7088 html => $html,
7089 title => $title || $map->{title},
7090 1 ▶ head => ($map->{map_head} // ''),
Condition40%2/5
$title || $map->{'title'}
l!l&&r!l&&!r
010
$map->{"map_head"} // ""
l!l
01
MC/DC0%0/2
$title || $map->{'title'}
$title $map->{'title'}
MC/DC0%0/1
$map->{"map_head"} // ""
$map->{"map_head"}
Truth table33%1/3
A || B
A= $titleB= $map->{'title'}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $map->{"map_head"}
Aresult
11
00
7091 };
7092 }
7093  
7094 # ------------------------------------------------------------ word cloud --
7095 # A card that draws the words of a text column, the way GET /wordcloud does,
7096 # from the same counted and ranked words (see _wordcloud_counts). It is the
7097 # one kind with no value column and no measure: the size of a word is how
7098 # many of the card's own rows contain it, so a card the reader has filtered
7099 # shows the words of those rows.
7100 12 ▶ if ($kind eq 'wordcloud') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "wordcloud") 0 12 12
7101 0 ▶ my $col = $encode->{col} // '';
Condition0%0/2
$encode->{"col"} // ""
l!l
00
MC/DC0%0/1
$encode->{"col"} // ""
$encode->{"col"}
Truth table0%0/2
A
A= $encode->{"col"}
Aresult
11
00
7102 0 ▶ return { error => 'Missing col for word cloud visual' } unless length $col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 0 0 0
7103 0 ▶ return { error => "Column not found: $col" } unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 0 0 0
7104  
7105 0 my $topn = _wordcloud_option($options->{topn}, 50, 1, 500);
7106 0 my $minlen = _wordcloud_option($options->{minlen}, 3, 1, 64);
7107  
7108 my $cloud = _wordcloud_counts(
7109 $vis_recs, $col, $topn, $minlen, $options->{stop},
7110 0 );
7111 0 my @tags = @{ $cloud->{words} };
7112  
7113 0 ▶ $title ||= "Words in $col";
Condition0%0/2
$title ||= "Words in $col"
l!l
00
MC/DC0%0/1
$title ||= "Words in $col"
$title
Truth table0%0/2
A
A= $title
Aresult
11
00
7114 my $summary = $cloud->{distinct}
7115 ? scalar(@tags) . ' of ' . $cloud->{distinct} . ' different word'
7116 . ($cloud->{distinct} == 1 ? '' : 's')
7117 . ' &middot; ' . $cloud->{total} . ' word'
7118 . ($cloud->{total} == 1 ? '' : 's')
7119 . ' in ' . $cloud->{rows} . ' row'
7120 0 ▶ . ($cloud->{rows} == 1 ? '' : 's')
Branch: 4 branches
BranchTrueFalseTotal
$cloud->{'distinct'} ? : 0 0 0
$cloud->{'distinct'} == 1 ? : 0 0 0
$cloud->{'total'} == 1 ? : 0 0 0
$cloud->{'rows'} == 1 ? : 0 0 0
7121 : '';
7122  
7123 0 ▶ if (!@tags) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@tags) 0 0 0
7124 return {
7125 0 html => '<div class="wordcloud-card"><p class="wordcloud-empty">'
7126 . 'No words: no row in this view has text in '
7127 . xml_escape($col) . ' at least ' . $minlen
7128 . ' characters long.</p></div>',
7129 title => $title,
7130 };
7131 }
7132  
7133 # HTML::TagCloud ranks the words and works out each one's level; the size
7134 # it would give that level is 12px plus the level. The size is written on
7135 # the word here instead of using the module's style sheet, because that
7136 # sheet scopes itself through #htmltagcloud -- an id only one element on a
7137 # page may carry, and a canvas may hold two word-cloud cards. The level,
7138 # the part that is actually arithmetic, stays the module's. The module is
7139 # handed the word as it is and the escaping happens on the way out, because
7140 # the same word is both what the reader reads and, unescaped, the filter a
7141 # click on it asks for.
7142 0 require HTML::TagCloud;
7143 0 my $ranked = HTML::TagCloud->new(levels => 18);
7144 0 $ranked->add_static($_->{word}, $_->{count}) for @tags;
7145  
7146 # A word is a control, not a label. Clicking one cross-filters the canvas
7147 # the way a chart mark does -- ?cf=...&cv=<card>, so every other card is
7148 # narrowed and this one stays drawn in full -- but with C<contains> rather
7149 # than C<eq>: a word is a token inside a cell, not the cell's whole value,
7150 # so no row equals it. The href carries the whole URL the click asks for,
7151 # so a word filters even before the page's script runs; the script takes
7152 # the click over only to keep the rest of the query string (a bound
7153 # parameter, a drill path) and to record the undo step, as it does for a
7154 # mark. A card drawn with no index -- by anything that is not a canvas
7155 # render -- names no source, so the filter applies to every card.
7156 0 ▶ my $cv = (defined $vis_id && $vis_id =~ /\A\d+\z/) ? "&cv=$vis_id" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $vis_id && $vis_id =~ /\A\d+\z/u ? : 0 0 0
Condition0%0/3
defined $vis_id and $vis_id =~ /\A\d+\z/u
!ll&&!rl&&r
000
MC/DC0%0/2
defined $vis_id and $vis_id =~ /\A\d+\z/u
defined $vis_id $vis_id =~ /\A\d+\z/u
Truth table0%0/3
A and B
A= defined $vis_idB= $vis_id =~ /\A\d+\z/u
ABresult
0X0
100
111
7157 my $spans = join(' ', map {
7158 0 my $word = $_->{name};
7159 0 my $label = xml_escape("Filter by $col: $word");
7160 # aria-describedby names the canvas's cross-filter help, which covers
7161 # a word as well as a chart mark: the label says which word this is,
7162 # the help says what pressing Enter on it does.
7163 '<a class="wordcloud-word" href="?cf='
7164 . _percent_encode("$col:contains:$word") . $cv . '"'
7165 . ' data-cf-value="' . xml_escape($word) . '"'
7166 0 . ' style="font-size:' . (12 + $_->{level}) . 'px"'
7167 . ' aria-label="' . $label . '" title="' . $label . '"'
7168 . ' aria-describedby="cf-help">'
7169 . xml_escape($word) . '</a>'
7170 } $ranked->tags(scalar @tags));
7171  
7172 return {
7173 0 html => '<div class="wordcloud-card" data-col="' . xml_escape($col) . '">'
7174 . '<p class="wordcloud-cloud">' . $spans . '</p>'
7175 . '<p class="wordcloud-summary">' . $summary . '</p></div>',
7176 title => $title,
7177 };
7178 }
7179  
7180 # ----------------------------------------------------------------- table --
7181 12 ▶ if ($kind eq 'table') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "table") 1 11 12
7182 1 ▶ return { error => 'No data to display' } unless @$vis_recs;
Branch: 1 branch
BranchTrueFalseTotal
unless @$vis_recs 0 1 1
7183 1 my @cols = @$columns;
7184 0 ▶ if (ref $encode->{columns} eq 'ARRAY' && @{ $encode->{columns} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $encode->{"columns"} eq "ARRAY" and @{$encode->{"columns"};}) 0 1 1
Condition33%1/3
ref $encode->{"columns"} eq "ARRAY" and @{$encode->{"columns"};}
!ll&&!rl&&r
100
MC/DC0%0/2
ref $encode->{"columns"} eq "ARRAY" and @{$encode->{"columns"};}
ref $encode->{"columns"} eq "ARRAY" @{$encode->{"columns"};}
Truth table33%1/3
A and B
A= ref $encode->{"columns"} eq "ARRAY"B= @{$encode->{"columns"};}
ABresult
0X0
100
111
7185 # A table names the columns it shows, and it is the one kind that
7186 # could name a column nothing produces: the heading printed and
7187 # every cell under it was empty, which reads as missing data rather
7188 # than as a card drawn against a column that is not there. Whether
7189 # a plan produces a name is not something a reader can see from the
7190 # card, so the name is refused here as the charts below refuse it.
7191 0 for my $c (@{ $encode->{columns} }) {
7192 0 ▶ next if ref $c || !length $c;
Branch: 1 branch
BranchTrueFalseTotal
if ref $c or not length $c 0 0 0
Condition0%0/3
ref $c or not length $c
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $c or not length $c
ref $c not length $c
Truth table0%0/3
A or not(B)
A= ref $cB= not length $c
ABresult
1X1
011
000
7193 0 ▶ return { error => "Column not found: $c" } unless $col_set{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$c} 0 0 0
7194 }
7195 0 @cols = @{ $encode->{columns} };
7196 }
7197  
7198 1 ▶ $title ||= 'Table';
Condition50%1/2
$title ||= "Table"
l!l
01
MC/DC0%0/1
$title ||= "Table"
$title
Truth table50%1/2
A
A= $title
Aresult
11
00
7199 1 ▶ my $max_rows_t = int($options->{rows} // 50);
Condition50%1/2
$options->{"rows"} // 50
l!l
01
MC/DC0%0/1
$options->{"rows"} // 50
$options->{"rows"}
Truth table50%1/2
A
A= $options->{"rows"}
Aresult
11
00
7200 1 ▶ $max_rows_t = 200 if $max_rows_t > 200;
Branch: 1 branch
BranchTrueFalseTotal
if $max_rows_t > 200 0 1 1
7201 1 ▶ $max_rows_t = 1 if $max_rows_t < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $max_rows_t < 1 0 1 1
7202  
7203 1 my $html = '<div class="visual-table-wrap"><table class="data-table">'
7204 . '<thead><tr>';
7205 1 for my $c (@cols) {
7206 6 (my $ch = $c) =~ s/&/&amp;/g; $ch =~ s/</&lt;/g; $ch =~ s/>/&gt;/g;
7207 6 $html .= "<th>$ch</th>";
7208 }
7209 1 $html .= '</tr></thead><tbody>';
7210 1 my $count = 0;
7211 1 for my $row (@$vis_recs) {
7212 6 ▶ last if $count++ >= $max_rows_t;
Branch: 1 branch
BranchTrueFalseTotal
if $count++ >= $max_rows_t 0 6 6
7213 6 $html .= '<tr>';
7214 6 for my $c (@cols) {
7215 36 ▶ my $v = $row->{$c} // '';
Condition50%1/2
$row->{$c} // ""
l!l
360
MC/DC0%0/1
$row->{$c} // ""
$row->{$c}
Truth table50%1/2
A
A= $row->{$c}
Aresult
11
00
7216 36 $v =~ s/&/&amp;/g; $v =~ s/</&lt;/g; $v =~ s/>/&gt;/g;
7217 36 $html .= "<td>$v</td>";
7218 }
7219 6 $html .= '</tr>';
7220 }
7221 1 $html .= '</tbody></table></div>';
7222 1 return { html => $html, title => $title };
7223 }
7224  
7225 11 return { error => "Unknown visual kind: $kind" };
7226 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7227  
7228 # _vis_cf_col(\%vis) -> $col_name | undef
7229 #
7230 # Returns the primary categorical dimension of a visual -- the column that
7231 # makes sense to cross-filter on when the user clicks a mark.
7232 # Priority: cat > group > x > col (histogram). Series/size/val are measures,
7233 # not dimensions, so they are intentionally excluded.
7234 55 ▶sub _vis_cf_col {
Subroutine _vis_cf_col: called CC=5 SCAR=16.1
7235 55 my ($vis) = @_;
7236 55 ▶ my $enc = $vis->{encode} // {};
Condition100%2/2
$vis->{"encode"} // {}
l!l
4411
MC/DC100%1/1
$vis->{"encode"} // {}
$vis->{"encode"}
Truth table100%2/2
A
A= $vis->{"encode"}
Aresult
11
00
7237 55 for my $key (qw(cat group x col)) {
7238 106 ▶ return $enc->{$key} if length($enc->{$key} // '');
Branch: 1 branch
BranchTrueFalseTotal
if length($enc->{$key} // "") 40 66 106
Condition100%2/2
$enc->{$key} // ""
l!l
4165
MC/DC100%1/1
$enc->{$key} // ""
$enc->{$key}
Truth table100%2/2
A
A= $enc->{$key}
Aresult
11
00
7239 }
7240 15 return undef;
7241 }
7242  
7243 # GET /a/:id -- render a saved canvas
7244 #
7245 # redirects to the reconstructed data-view URL when the
7246 # canvas has no visuals array.
7247 # renders N visuals in a CSS grid when visuals are present.
7248 # _bound_canvas_params($self, $a, $lookup) -> (\%bound, \@errors)
7249 #
7250 # Resolve the canvas's declared parameters against URL values. $lookup takes a
7251 # parameter name ("p.<name>") and returns the raw string from the request or
7252 # undef; the default is used when it returns undef. Numbers are coerced and
7253 # range-checked, and an error is reported rather than a value bound, so the
7254 # canvas page and a card appended to it draw the same parameter values.
7255 94 ▶sub _bound_canvas_params :Protected ($self, $a, $lookup) {
Subroutine _bound_canvas_params: called CC=16 SCAR=27.7
7256 94 ▶ my %param_defs = %{ $a->{params} // {} };
Condition100%2/2
$a->{"params"} // {}
l!l
2173
MC/DC100%1/1
$a->{"params"} // {}
$a->{"params"}
Truth table100%2/2
A
A= $a->{"params"}
Aresult
11
00
7257 94 my (%bound_params, @errors);
7258  
7259 94 for my $pname (sort keys %param_defs) {
7260 22 ▶ my $def = ref $param_defs{$pname} eq 'HASH' ? $param_defs{$pname} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $param_defs{$pname} eq 'HASH' ? : 19 3 22
7261 22 ▶ my $type = $def->{type} // 'string';
Condition100%2/2
$def->{"type"} // "string"
l!l
139
MC/DC100%1/1
$def->{"type"} // "string"
$def->{"type"}
Truth table100%2/2
A
A= $def->{"type"}
Aresult
11
00
7262 22 ▶ my $default = $def->{default} // '';
Condition100%2/2
$def->{"default"} // ""
l!l
418
MC/DC100%1/1
$def->{"default"} // ""
$def->{"default"}
Truth table100%2/2
A
A= $def->{"default"}
Aresult
11
00
7263 22 my $raw = $lookup->("p.$pname");
7264 22 ▶ my $val = defined $raw ? $raw : $default;
Branch: 1 branch
BranchTrueFalseTotal
defined $raw ? : 13 9 22
7265  
7266 22 ▶ if ($type eq 'number') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "number") 13 9 22
7267 13 require Scalar::Util;
7268 # looks_like_number accepts these, and every comparison with NaN is
7269 # false, so it would walk straight past min and max below.
7270 13 ▶ unless (Scalar::Util::looks_like_number($val) && $val !~ /\A\s*[-+]?(?:nan|inf)/i) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&Scalar::Util::looks_like_number($val) and not $val =~ /\A\s*[-+]?(?:nan|inf)/iu) 7 6 13
Condition100%3/3
&Scalar::Util::looks_like_number($val) and not $val =~ /\A\s*[-+]?(?:nan|inf)/iu
!ll&&!rl&&r
256
MC/DC100%2/2
&Scalar::Util::looks_like_number($val) and not $val =~ /\A\s*[-+]?(?:nan|inf)/iu
&Scalar::Util::looks_like_number($val) not $val =~ /\A\s*[-+]?(?:nan|inf)/iu
Truth table100%3/3
A and not(B)
A= &Scalar::Util::looks_like_number($val)B= not $val =~ /\A\s*[-+]?(?:nan|inf)/iu
ABresult
0X0
100
111
7271 7 push @errors, sprintf(_message_text('error_param_type'), $pname);
7272 7 next;
7273 }
7274 6 $val = $val + 0;
7275 6 my ($lo, $hi) = ($def->{min}, $def->{max});
7276 6 ▶ if (defined $lo && $val < $lo) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lo and $val < $lo) 1 5 6
Condition100%3/3
defined $lo and $val < $lo
!ll&&!rl&&r
321
MC/DC100%2/2
defined $lo and $val < $lo
defined $lo $val < $lo
Truth table100%3/3
A and B
A= defined $loB= $val < $lo
ABresult
0X0
100
111
7277 1 ▶ push @errors, sprintf(_message_text('error_param_range'),
Branch: 1 branch
BranchTrueFalseTotal
defined $hi ? : 0 1 1
7278 $pname, $lo, defined $hi ? $hi : '+inf');
7279 1 next;
7280 }
7281 5 ▶ if (defined $hi && $val > $hi) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hi and $val > $hi) 3 2 5
Condition66%2/3
defined $hi and $val > $hi
!ll&&!rl&&r
203
MC/DC50%1/2
defined $hi and $val > $hi
defined $hi $val > $hi
Truth table66%2/3
A and B
A= defined $hiB= $val > $hi
ABresult
0X0
100
111
7282 3 ▶ push @errors, sprintf(_message_text('error_param_range'),
Branch: 1 branch
BranchTrueFalseTotal
defined $lo ? : 2 1 3
7283 $pname, defined $lo ? $lo : '-inf', $hi);
7284 3 next;
7285 }
7286 }
7287 11 $bound_params{$pname} = $val;
7288 }
7289  
7290 94 return (\%bound_params, \@errors);
7291 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7292  
7293 50 ▶sub canvas_render ($self) {
Subroutine canvas_render: called CC=125 SCAR=71.6
Pod documented
7294 50 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
500
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
7295 50 ▶ return $self->render(text => _message_text('error_analysis_id_invalid'), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 0 50 50
7296 unless $id =~ /\A[A-Za-z0-9]+\z/;
7297  
7298 50 my $analyses = $self->_read_analyses;
7299 50 ▶ unless (exists $analyses->{$id}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $analyses->{$id}) 4 46 50
7300 # An HTML page, not plain text, so the user keeps the breadcrumb and
7301 # the site navigation. No canvas_id: there is nothing to delete.
7302 4 my ($platform, $language) = $self->_resolve_template;
7303 4 return $self->render(
7304 handler => 'tt',
7305 template => "$platform/$language/canvas_error",
7306 format => 'html',
7307 status => 404,
7308 title => 'Canvas not found',
7309 canvas_name => $id,
7310 error_msg => sprintf(_message_text('error_analysis_not_found'), $id),
7311 error_specs => [],
7312 language => $language,
7313 );
7314 }
7315 46 my $a = $analyses->{$id};
7316  
7317 # freshness: compare each dataset's current mtime against
7318 # the analysis's saved updated timestamp. Flag stale when any source
7319 # is newer. Non-fatal: the canvas renders with a stale banner.
7320 46 my ($freshness_stale, $freshness_msg, $freshness_source_mtime) = (0, '', '');
7321 {
7322 46 ▶ my $analysis_updated = $a->{updated} // 0;
Condition100%2/2
$a->{"updated"} // 0
l!l
2620
MC/DC100%1/1
$a->{"updated"} // 0
$a->{"updated"}
Truth table100%2/2
A
A= $a->{"updated"}
Aresult
11
00
7323 # Parse ISO-8601 to epoch for comparison if needed.
7324 46 ▶ if ($analysis_updated && $analysis_updated =~ /
Branch: 1 branch
BranchTrueFalseTotal
if ($analysis_updated and $analysis_updated =~ / \A (\d{4}) - (\d{2}) - (\d{2}) # $1 yr $2 mon $3 day T (\d{2}) : (\d{2}) : (\d{2}) # $4 hr $5 min $6 sec Z? \z /ux) 0 46 46
Condition66%2/3
$analysis_updated and $analysis_updated =~ / \A (\d{4}) - (\d{2}) - (\d{2}) # $1 yr $2 mon $3 day T (\d{2}) : (\d{2}) : (\d{2}) # $4 hr $5 min $6 sec Z? \z /ux
!ll&&!rl&&r
20260
MC/DC0%0/2
$analysis_updated and $analysis_updated =~ / \A (\d{4}) - (\d{2}) - (\d{2}) # $1 yr $2 mon $3 day T (\d{2}) : (\d{2}) : (\d{2}) # $4 hr $5 min $6 sec Z? \z /ux
$analysis_updated $analysis_updated =~ / \A (\d{4}) - (\d{2}) - (\d{2}) # $1 yr $2 mon $3 day T (\d{2}) : (\d{2}) : (\d{2}) # $4 hr $5 min $6 sec Z? \z /ux
Truth table66%2/3
A and B
A= $analysis_updatedB= $analysis_updated =~ / \A (\d{4}) - (\d{2}) - (\d{2}) # $1 yr $2 mon $3 day T (\d{2}) : (\d{2}) : (\d{2}) # $4 hr $5 min $6 sec Z? \z /ux
ABresult
0X0
100
111
7325 \A
7326 (\d{4}) - (\d{2}) - (\d{2}) # $1 yr $2 mon $3 day
7327 T
7328 (\d{2}) : (\d{2}) : (\d{2}) # $4 hr $5 min $6 sec
7329 Z? \z
7330 /x) {
7331 0 require POSIX;
7332 0 $analysis_updated = POSIX::mktime($6, $5, $4, $3, $2 - 1, $1 - 1900);
7333 }
7334 46 my $newest_src_mtime = 0;
7335 46 ▶ for my $ds (@{ $a->{datasets} // [] }) {
Condition100%2/2
$a->{"datasets"} // []
l!l
433
MC/DC100%1/1
$a->{"datasets"} // []
$a->{"datasets"}
Truth table100%2/2
A
A= $a->{"datasets"}
Aresult
11
00
7336 43 ▶ my $spec = $ds->{spec} // '';
Condition50%1/2
$ds->{"spec"} // ""
l!l
430
MC/DC0%0/1
$ds->{"spec"} // ""
$ds->{"spec"}
Truth table50%1/2
A
A= $ds->{"spec"}
Aresult
11
00
7337 43 ▶ next unless $spec =~ /\A(?:table|path):/;
Branch: 1 branch
BranchTrueFalseTotal
unless $spec =~ /\A(?:table|path):/u 0 43 43
7338 43 my ($src) = eval { $self->_open_spec($spec) };
7339 43 ▶ next unless $src && $src->can('updated');
Branch: 1 branch
BranchTrueFalseTotal
unless $src and $src->can("updated") 1 42 43
Condition66%2/3
$src and $src->can("updated")
!ll&&!rl&&r
1042
MC/DC50%1/2
$src and $src->can("updated")
$src $src->can("updated")
Truth table66%2/3
A and B
A= $srcB= $src->can("updated")
ABresult
0X0
100
111
7340 42 ▶ my $mt = eval { $src->updated } // 0;
Condition50%1/2
eval { do { $src->updated } } // 0
l!l
420
MC/DC0%0/1
eval { do { $src->updated } } // 0
eval { do { $src->updated } }
Truth table50%1/2
A
A= eval { do { $src->updated } }
Aresult
11
00
7341 42 ▶ $newest_src_mtime = $mt if $mt > $newest_src_mtime;
Branch: 1 branch
BranchTrueFalseTotal
if $mt > $newest_src_mtime 42 0 42
7342 }
7343 46 ▶ if ($newest_src_mtime && $analysis_updated && $newest_src_mtime > $analysis_updated) {
Branch: 1 branch
BranchTrueFalseTotal
if ($newest_src_mtime and $analysis_updated and $newest_src_mtime > $analysis_updated) 1 45 46
Condition100%6/6
$newest_src_mtime and $analysis_updated and $newest_src_mtime > $analysis_updated
!ll&&!rl&&r
21241
$newest_src_mtime and $analysis_updated
!ll&&!rl&&r
41725
MC/DC100%3/3
$newest_src_mtime and $analysis_updated and $newest_src_mtime > $analysis_updated
$newest_src_mtime $analysis_updated $newest_src_mtime > $analysis_updated
Truth table100%4/4
A and B and C
A= $newest_src_mtimeB= $analysis_updatedC= $newest_src_mtime > $analysis_updated
ABCresult
0XX0
10X0
1100
1111
7344 1 $freshness_stale = 1;
7345 1 $freshness_msg = _message_text('freshness_stale_msg');
7346 1 require POSIX;
7347 1 $freshness_source_mtime = Database::BI::Util::minute_stamp(gmtime($newest_src_mtime)) . ' UTC';
7348 }
7349 }
7350  
7351 # if visuals array is non-empty, render the canvas.
7352 46 ▶ my @visuals = @{ $a->{visuals} // [] };
Condition100%2/2
$a->{"visuals"} // []
l!l
406
MC/DC100%1/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
7353 46 ▶ if (@visuals) {
Branch: 1 branch
BranchTrueFalseTotal
if (@visuals) 40 6 46
7354  
7355 # bound parameters from URL ?p.<name>=<value>.
7356 # Parameter definitions live in the analysis: params => { name => { type, default, min, max } }.
7357 # URL values are type-coerced and range-checked; out-of-range returns 400.
7358 my ($bound_ref, $p_errors) = $self->_bound_canvas_params(
7359 2 ▶ $a, sub { $self->param($_[0]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
7360 40 );
7361 40 my %bound_params = %$bound_ref;
7362 40 ▶ if (@$p_errors) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$p_errors) 0 40 40
7363 0 return $self->render(
7364 text => join('; ', @$p_errors),
7365 status => 400,
7366 );
7367 }
7368  
7369 # Build stash list for parameter bar: sorted by name.
7370 40 ▶ my %param_defs = %{ $a->{params} // {} };
Condition100%2/2
$a->{"params"} // {}
l!l
238
MC/DC100%1/1
$a->{"params"} // {}
$a->{"params"}
Truth table100%2/2
A
A= $a->{"params"}
Aresult
11
00
7371 my @canvas_params = map {
7372 40 my $def = $param_defs{$_};
7373 {
7374 name => $_,
7375 type => ($def->{type} // 'string'),
7376 value => $bound_params{$_},
7377 default => ($def->{default} // ''),
7378 min => (defined $def->{min} ? $def->{min} : ''),
7379 2 ▶ max => (defined $def->{max} ? $def->{max} : ''),
Branch: 2 branches
BranchTrueFalseTotal
defined $def->{'min'} ? : 0 2 2
defined $def->{'max'} ? : 0 2 2
Condition50%2/4
$def->{"type"} // "string"
l!l
02
$def->{"default"} // ""
l!l
02
MC/DC0%0/1
$def->{"type"} // "string"
$def->{"type"}
MC/DC0%0/1
$def->{"default"} // ""
$def->{"default"}
Truth table50%1/2
A
A= $def->{"type"}
Aresult
11
00
Truth table50%1/2
A
A= $def->{"default"}
Aresult
11
00
7380 }
7381 } sort keys %param_defs;
7382  
7383 # Everything else the canvas is showing has to survive a change of time
7384 # range, so the control carries the rest of this page's query string: the
7385 # cross-filter (cf/vc), the drill path (dd/dl), the calculated columns
7386 # (c) and the what-if parameter values (p.<name>).
7387 40 my @canvas_range_hidden;
7388 {
7389 40 my $q = $self->req->query_params;
7390 40 for my $name ($q->names) {
7391 40 ▶ next if $name eq 'range' || $name eq 'rcol';
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "range" or $name eq "rcol" 0 40 40
Condition33%1/3
$name eq "range" or $name eq "rcol"
l!l&&r!l&&!r
0040
MC/DC0%0/2
$name eq "range" or $name eq "rcol"
$name eq "range" $name eq "rcol"
Truth table33%1/3
A or B
A= $name eq "range"B= $name eq "rcol"
ABresult
1X1
011
000
7392 push @canvas_range_hidden,
7393 0 ▶ map { { name => $name, value => $_ } } @{ $q->every_param($name) // [] };
Condition50%1/2
$q->every_param($name) // []
l!l
400
MC/DC0%0/1
$q->every_param($name) // []
$q->every_param($name)
Truth table50%1/2
A
A= $q->every_param($name)
Aresult
11
00
7394 }
7395 }
7396  
7397 40 my ($src, $records, $columns) = $self->_build_canvas_pipeline($a);
7398 40 ▶ unless (defined $records) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $records) 1 39 40
7399 1 my ($platform, $language) = $self->_resolve_template;
7400 1 ▶ my @specs = map { $_->{spec} // '' } @{ $a->{datasets} // [] };
Condition50%2/4
$_->{"spec"} // ""
l!l
10
$a->{"datasets"} // []
l!l
10
MC/DC0%0/1
$_->{"spec"} // ""
$_->{"spec"}
MC/DC0%0/1
$a->{"datasets"} // []
$a->{"datasets"}
Truth table50%1/2
A
A= $_->{"spec"}
Aresult
11
00
Truth table50%1/2
A
A= $a->{"datasets"}
Aresult
11
00
7401 return $self->render(
7402 handler => 'tt',
7403 template => "$platform/$language/canvas_error",
7404 format => 'html',
7405 status => 422,
7406 title => 'Canvas unavailable',
7407 canvas_id => $id,
7408 1 ▶ canvas_name => ($a->{name} // $id),
Condition33%1/3
$a->{"name"} // $id
l!l&&r!l&&!r
100
MC/DC0%0/2
$a->{"name"} // $id
$a->{"name"} $id
Truth table33%1/3
A // B
A= $a->{"name"}B= $id
ABresult
1X1
011
000
7409 error_msg => 'The data source for this canvas could not be opened.',
7410 error_specs => \@specs,
7411 language => $language,
7412 );
7413 }
7414  
7415 # Apply calc fields with bound params so expressions may reference them.
7416 39 ▶ my $canvas_spec_key = ($a->{datasets}[0]{spec} // '');
Condition50%1/2
$a->{"datasets"}[0]{"spec"} // ""
l!l
390
MC/DC0%0/1
$a->{"datasets"}[0]{"spec"} // ""
$a->{"datasets"}[0]{"spec"}
Truth table50%1/2
A
A= $a->{"datasets"}[0]{"spec"}
Aresult
11
00
7417 39 my $window_names = _canvas_window_columns($a, $self);
7418 39 $self->stash('_canvas_window_names' => $window_names);
7419 39 eval {
7420 39 ($records, $columns) = $self->_apply_calc_fields(
7421 $records, $columns,
7422 {
7423 params => \%bound_params,
7424 spec_key => $canvas_spec_key,
7425 window_columns => $window_names,
7426 }
7427 );
7428 };
7429 39 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 39 39
7430 0 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
7431 0 return $self->render(text => $e, status => 400);
7432 }
7433  
7434 # cs= belongs to the page, not to a card: one plan, run per card on that
7435 # card's own rows (see _render_visual_html). A fault is the page's 400 --
7436 # the same message repeated on every card would be noise, not a report.
7437 39 my $cross_row = $self->_cross_row_specs($columns);
7438 39 ▶ if ($cross_row && $cross_row->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cross_row and $cross_row->{"error"}) 0 39 39
Condition33%1/3
$cross_row and $cross_row->{"error"}
!ll&&!rl&&r
3900
MC/DC0%0/2
$cross_row and $cross_row->{"error"}
$cross_row $cross_row->{"error"}
Truth table33%1/3
A and B
A= $cross_rowB= $cross_row->{"error"}
ABresult
0X0
100
111
7439 0 return $self->render(text => $cross_row->{error}, status => 400);
7440 }
7441  
7442 # The relative time range the page names (?range=/?rcol=) narrows every
7443 # card, before the per-card cross-filter. The before_dispatch hook has
7444 # already resolved it into the f= params the routes apply, but the canvas
7445 # builds its own pipeline, so it applies the range itself from the same
7446 # two specs.
7447 39 ▶ if (my $range = $self->stash('time_range')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $range = $self->stash("time_range")) 0 39 39
7448 0 ▶ for my $spec (@{ $self->stash('range_specs') // [] }) {
Condition0%0/2
$self->stash("range_specs") // []
l!l
00
MC/DC0%0/1
$self->stash("range_specs") // []
$self->stash("range_specs")
Truth table0%0/2
A
A= $self->stash("range_specs")
Aresult
11
00
7449 0 $records = _apply_filter_spec($records, $spec);
7450 }
7451 }
7452  
7453 # cross-filter state from URL params.
7454 # ?cf=col:op:val (repeatable) filters all visuals except the source.
7455 # ?cv=N identifies the source visual (shown unfiltered but highlighted).
7456 # Semantics: self-highlighting (source shown in full; others filtered).
7457 # Multiple simultaneous selections are not supported in this version.
7458 39 ▶ my @cf_specs = grep { /\S/ } @{ $self->every_param('cf') // [] };
Condition50%1/2
$self->every_param("cf") // []
l!l
390
MC/DC0%0/1
$self->every_param("cf") // []
$self->every_param("cf")
Truth table50%1/2
A
A= $self->every_param("cf")
Aresult
11
00
7459 39 my $cf_source = _cross_filter_source($self->param('cv'));
7460 39 my $cf_active = !!@cf_specs;
7461  
7462 # Build the "clear cross-filter" URL for the chip close button.
7463 39 my $cf_clear_url = $self->req->url->clone;
7464 39 $cf_clear_url->query->remove('cf')->remove('cv');
7465 39 $cf_clear_url = $cf_clear_url->to_string;
7466  
7467 # Human-readable summary for the cross-filter chip, e.g. "region = North".
7468 39 my $cf_display = '';
7469 39 ▶ if ($cf_active) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cf_active) 1 38 39
7470 1 my @parts;
7471 1 for my $spec (@cf_specs) {
7472 1 my ($col, $op, $val) = split /:/, $spec, 3;
7473 1 ▶ $val //= '';
Condition50%1/2
$val //= ""
l!l
10
MC/DC0%0/1
$val //= ""
$val
Truth table50%1/2
A
A= $val
Aresult
11
00
7474 1 ▶ my $sym = ($op eq 'eq') ? '=' : ($op eq 'ne') ? '!='
Branch: 8 branches
BranchTrueFalseTotal
$op eq 'eq' ? : 1 0 1
$op eq 'ne' ? : 0 0 0
$op eq 'lt' ? : 0 0 0
$op eq 'le' ? : 0 0 0
$op eq 'gt' ? : 0 0 0
$op eq 'ge' ? : 0 0 0
$op eq 'contains' ? : 0 0 0
$op eq 'starts' ? : 0 0 0
7475 : ($op eq 'lt') ? '<' : ($op eq 'le') ? '<='
7476 : ($op eq 'gt') ? '>' : ($op eq 'ge') ? '>='
7477 : ($op eq 'contains') ? 'contains'
7478 : ($op eq 'starts') ? 'starts with'
7479 : $op;
7480 1 push @parts, "$col $sym $val";
7481 }
7482 1 $cf_display = join(' AND ', @parts);
7483 }
7484  
7485 # drill-through and drill-down.
7486 #
7487 # Drill-through: when cross-filters are active, build a URL to the
7488 # primary data source with those filters applied as ?f= params so the
7489 # user can inspect the raw rows behind the selection.
7490 39 my $drillthrough_url = '';
7491 39 ▶ if (@cf_specs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cf_specs) 1 38 39
7492 1 ▶ my $ds0 = ($a->{datasets} // [])->[0];
Condition50%1/2
$a->{"datasets"} // []
l!l
10
MC/DC0%0/1
$a->{"datasets"} // []
$a->{"datasets"}
Truth table50%1/2
A
A= $a->{"datasets"}
Aresult
11
00
7493 1 ▶ my $spec0 = ($ds0 // {})->{spec} // '';
Condition50%2/4
+($ds0 // {})->{"spec"} // ""
l!l
10
$ds0 // {}
l!l
10
MC/DC0%0/1
+($ds0 // {})->{"spec"} // ""
$ds0
Truth table50%1/2
A
A= $ds0
Aresult
11
00
7494 1 my $base = $self->_spec_to_url($spec0);
7495 1 ▶ if ($base ne '/') {
Branch: 1 branch
BranchTrueFalseTotal
if ($base ne "/") 1 0 1
7496 1 ▶ my $sep = ($base =~ /\?/) ? '&' : '?';
Branch: 1 branch
BranchTrueFalseTotal
$base =~ /\?/u ? : 1 0 1
7497 1 for my $cf (@cf_specs) {
7498 1 $base .= $sep . 'f=' . url_escape(encode('UTF-8', $cf));
7499 1 $sep = '&';
7500 }
7501 1 $drillthrough_url = $base;
7502 }
7503 }
7504  
7505 # Drill-down: navigate a named hierarchy one level at a time.
7506 # ?dd=<name> names the active hierarchy; ?dl=<N> is the current level
7507 # (0-based); accumulated ?cf= params carry the drill path.
7508 39 ▶ my $dd_name = $self->param('dd') // '';
Condition50%1/2
$self->param("dd") // ""
l!l
039
MC/DC0%0/1
$self->param("dd") // ""
$self->param("dd")
Truth table50%1/2
A
A= $self->param("dd")
Aresult
11
00
7509 39 my $dl_raw = $self->param('dl');
7510 39 ▶ my $dd_level = (defined $dl_raw && length $dl_raw) ? int($dl_raw) : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $dl_raw && length $dl_raw ? : 0 39 39
Condition33%1/3
defined $dl_raw and length $dl_raw
!ll&&!rl&&r
3900
MC/DC0%0/2
defined $dl_raw and length $dl_raw
defined $dl_raw length $dl_raw
Truth table33%1/3
A and B
A= defined $dl_rawB= length $dl_raw
ABresult
0X0
100
111
7511 39 ▶ $dd_level = 0 if $dd_level < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $dd_level < 0 0 39 39
7512  
7513 0 ▶ my ($dd_hier) = grep { ($_->{name} // '') eq $dd_name }
Condition0%0/2
$_->{"name"} // ""
l!l
00
MC/DC0%0/1
$_->{"name"} // ""
$_->{"name"}
Truth table0%0/2
A
A= $_->{"name"}
Aresult
11
00
7514 39 ▶ @{ $a->{hierarchies} // [] };
Condition50%1/2
$a->{"hierarchies"} // []
l!l
039
MC/DC0%0/1
$a->{"hierarchies"} // []
$a->{"hierarchies"}
Truth table50%1/2
A
A= $a->{"hierarchies"}
Aresult
11
00
7515  
7516 # A drill needs a first level to name: a hierarchy with none answers no
7517 # press, and #cf-help has no column it could call the one that drills.
7518 my $drill_active = ($dd_hier && length $dd_name
7519 0 ▶ && @{ $dd_hier->{levels} // [] }) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$dd_hier && length $dd_name && @{$dd_hier->{'levels'} // [];} ? : 0 39 39
Condition25%2/8
$dd_hier and length $dd_name and @{$dd_hier->{"levels"} // [];}
!ll&&!rl&&r
3900
$dd_hier and length $dd_name
!ll&&!rl&&r
3900
$dd_hier->{"levels"} // []
l!l
00
MC/DC0%0/3
$dd_hier and length $dd_name and @{$dd_hier->{"levels"} // [];}
$dd_hier length $dd_name @{$dd_hier->{"levels"} // [];}
MC/DC0%0/1
$dd_hier->{"levels"} // []
$dd_hier->{"levels"}
Truth table25%1/4
A and B and C
A= $dd_hierB= length $dd_nameC= @{$dd_hier->{"levels"} // [];}
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/2
A
A= $dd_hier->{"levels"}
Aresult
11
00
7520 39 my $drill_col = '';
7521 39 my @drill_crumb = ();
7522 39 my $drill_max = 0;
7523  
7524 39 ▶ if ($drill_active) {
Branch: 1 branch
BranchTrueFalseTotal
if ($drill_active) 0 39 39
7525 0 ▶ my @levels = @{ $dd_hier->{levels} // [] };
Condition0%0/2
$dd_hier->{"levels"} // []
l!l
00
MC/DC0%0/1
$dd_hier->{"levels"} // []
$dd_hier->{"levels"}
Truth table0%0/2
A
A= $dd_hier->{"levels"}
Aresult
11
00
7526 0 $drill_max = $#levels;
7527 # Allow dl up to scalar(@levels) -- one past the last valid level
7528 # means "all levels drilled through" (drill-through mode).
7529 0 my $dl_cap = scalar @levels;
7530 0 ▶ $dd_level = $dl_cap if $dd_level > $dl_cap;
Branch: 1 branch
BranchTrueFalseTotal
if $dd_level > $dl_cap 0 0 0
7531 0 ▶ $drill_col = $levels[$dd_level] // '';
Condition0%0/2
$levels[$dd_level] // ""
l!l
00
MC/DC0%0/1
$levels[$dd_level] // ""
$levels[$dd_level]
Truth table0%0/2
A
A= $levels[$dd_level]
Aresult
11
00
7532  
7533 # Extract drilled values: each crossed level contributes a
7534 # cf=<col>:eq:<val> param in the URL.
7535 0 my %cf_by_col;
7536 0 for my $cf (@cf_specs) {
7537 0 my ($col, $op, $val) = split /:/, $cf, 3;
7538 0 ▶ $cf_by_col{$col} = ($val // '')
Branch: 1 branch
BranchTrueFalseTotal
if length($col // "") and ($op // "") eq "eq" 0 0 0
Condition0%0/9
length($col // "") and ($op // "") eq "eq"
!ll&&!rl&&r
000
$col // ""
l!l
00
$op // ""
l!l
00
$val // ""
l!l
00
MC/DC0%0/2
length($col // "") and ($op // "") eq "eq"
$col $op
MC/DC0%0/1
$val // ""
$val
Truth table0%0/3
A and B
A= $colB= $op
ABresult
0X0
100
111
Truth table0%0/2
A
A= $val
Aresult
11
00
7539 if length($col // '') && ($op // '') eq 'eq';
7540 }
7541  
7542 # "All" crumb -- keep ?dd=, remove dl/cf/cv.
7543 0 my $all_url = $self->req->url->clone;
7544 0 $all_url->query->remove('dl')->remove('cf')->remove('cv');
7545 0 ▶ push @drill_crumb, {
Branch: 2 branches
BranchTrueFalseTotal
$dd_level > 0 ? : 0 0 0
$dd_level == 0 ? : 0 0 0
7546 label => 'All',
7547 url => ($dd_level > 0 ? $all_url->to_string : ''),
7548 cur => ($dd_level == 0 ? 1 : 0),
7549 };
7550  
7551 # One crumb per drilled value (levels 0 .. dd_level-1).
7552 0 for my $i (0 .. $dd_level - 1) {
7553 0 my $col_i = $levels[$i];
7554 0 ▶ my $val_i = $cf_by_col{$col_i} // '';
Condition0%0/2
$cf_by_col{$col_i} // ""
l!l
00
MC/DC0%0/1
$cf_by_col{$col_i} // ""
$cf_by_col{$col_i}
Truth table0%0/2
A
A= $cf_by_col{$col_i}
Aresult
11
00
7555 0 my $is_last = ($i == $dd_level - 1);
7556  
7557 # Back-link: keep ?dd=, cf for levels 0..i, dl=i+1.
7558 0 my $back_url = '';
7559 0 ▶ unless ($is_last) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_last) 0 0 0
7560 0 my $u = $self->req->url->clone;
7561 0 $u->query->remove('dl')->remove('cf')->remove('cv');
7562 0 $u->query->append('dl' => $i + 1);
7563 0 for my $j (0 .. $i) {
7564 0 my $val_j = $cf_by_col{ $levels[$j] };
7565 0 ▶ $u->query->append('cf' => "$levels[$j]:eq:$val_j")
Branch: 1 branch
BranchTrueFalseTotal
if defined $val_j 0 0 0
7566 if defined $val_j;
7567 }
7568 0 $back_url = $u->to_string;
7569 }
7570  
7571 0 ▶ push @drill_crumb, {
Branch: 1 branch
BranchTrueFalseTotal
$is_last ? : 0 0 0
7572 label => $val_i,
7573 url => $back_url,
7574 cur => $is_last ? 1 : 0,
7575 };
7576 }
7577 }
7578  
7579 # Pre-build CSS grid position strings to avoid TT hash-key lookups, and
7580 # keep the two spans of a saved card so the page can print the card's size
7581 # on the card before the script has measured anything.
7582 39 my %layout_pos;
7583 my %layout_size;
7584 39 ▶ for my $lp (@{ $a->{layout} // [] }) {
Condition50%1/2
$a->{"layout"} // []
l!l
039
MC/DC0%0/1
$a->{"layout"} // []
$a->{"layout"}
Truth table50%1/2
A
A= $a->{"layout"}
Aresult
11
00
7585 0 my ($x, $y, $w, $h) = @{$lp}{qw(x y w h)};
7586 0 ▶ next unless defined $x && defined $y && defined $w && defined $h;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x and defined $y and defined $w and defined $h 0 0 0
Condition0%0/9
defined $x and defined $y and defined $w and defined $h
!ll&&!rl&&r
000
defined $x and defined $y and defined $w
!ll&&!rl&&r
000
defined $x and defined $y
!ll&&!rl&&r
000
MC/DC0%0/4
defined $x and defined $y and defined $w and defined $h
defined $x defined $y defined $w defined $h
Truth table0%0/5
A and B and C and D
A= defined $xB= defined $yC= defined $wD= defined $h
ABCDresult
0XXX0
10XX0
110X0
11100
11111
7587 0 ▶ $layout_pos{ $lp->{visual} // '' } =
Condition0%0/2
$lp->{"visual"} // ""
l!l
00
MC/DC0%0/1
$lp->{"visual"} // ""
$lp->{"visual"}
Truth table0%0/2
A
A= $lp->{"visual"}
Aresult
11
00
7588 "grid-column:${x}/span ${w};grid-row:${y}/span ${h}";
7589 0 ▶ $layout_size{ $lp->{visual} // '' } = [$w, $h];
Condition0%0/2
$lp->{"visual"} // ""
l!l
00
MC/DC0%0/1
$lp->{"visual"} // ""
$lp->{"visual"}
Truth table0%0/2
A
A= $lp->{"visual"}
Aresult
11
00
7590 }
7591  
7592 39 my @rendered;
7593 39 my $canvas_map_head = '';
7594 39 for my $i (0 .. $#visuals) {
7595 44 my $vis = $visuals[$i];
7596  
7597 # Apply cross-filter to every visual except the source (self-highlighting).
7598 44 my $vis_recs = $records;
7599 44 my $late_cf = [];
7600 44 ▶ if ($cf_active && $i != $cf_source) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cf_active and $i != $cf_source) 2 42 44
Condition66%2/3
$cf_active and $i != $cf_source
!ll&&!rl&&r
4202
MC/DC50%1/2
$cf_active and $i != $cf_source
$cf_active $i != $cf_source
Truth table66%2/3
A and B
A= $cf_activeB= $i != $cf_source
ABresult
0X0
100
111
7601 2 ($vis_recs, $late_cf) = $self->_canvas_cross_filter($records, $columns, \@cf_specs);
7602 }
7603  
7604 44 ▶ my $result = $self->_render_visual_html(
Branch: 1 branch
BranchTrueFalseTotal
$cf_active && $i != $cf_source ? : 2 42 44
Condition66%2/3
$cf_active and $i != $cf_source
!ll&&!rl&&r
4202
MC/DC50%1/2
$cf_active and $i != $cf_source
$cf_active $i != $cf_source
Truth table66%2/3
A and B
A= $cf_activeB= $i != $cf_source
ABresult
0X0
100
111
7605 $vis, $vis_recs, $columns, $src, $i, $canvas_spec_key,
7606 ($cf_active && $i != $cf_source ? 1 : 0),
7607 $cross_row,
7608 $late_cf,
7609 );
7610 44 ▶ $canvas_map_head ||= $result->{head} // '';
Condition40%2/5
$canvas_map_head ||= $result->{"head"} // ""
l!l&&r!l&&!r
0044
$result->{"head"} // ""
l!l
044
MC/DC0%0/2
$canvas_map_head ||= $result->{"head"} // ""
$canvas_map_head $result->{"head"}
Truth table33%1/3
A ||= B
A= $canvas_map_headB= $result->{"head"}
ABresult
1X1
011
000
7611 push @rendered, {
7612 id => $i,
7613 title => ($vis->{title} // $result->{title} // ('Visual ' . ($i + 1))),
7614 html => $result->{html} // '',
7615 error => $result->{error} // '',
7616 kind => $vis->{kind} // '',
7617 plain => _text_card_plain($vis),
7618 style => $layout_pos{$i} // '',
7619 # The saved spans, or nothing: a card with no saved position is
7620 # placed by the browser, and only the script can measure that.
7621 w => (defined $layout_size{$i} ? $layout_size{$i}[0] : undef),
7622 44 ▶ h => (defined $layout_size{$i} ? $layout_size{$i}[1] : undef),
Branch: 3 branches
BranchTrueFalseTotal
defined $layout_size{$i} ? : 0 44 44
defined $layout_size{$i} ? : 0 44 44
$i == $cf_source ? : 0 44 44
Condition93%14/15
($vis->{"title"} // $result->{"title"}) // 'Visual ' . ($i + 1)
l!l
3014
$vis->{"title"} // $result->{"title"}
l!l&&r!l&&!r
111914
$result->{"html"} // ""
l!l
2816
$result->{"error"} // ""
l!l
1628
$vis->{"kind"} // ""
l!l
395
$layout_pos{$i} // ""
l!l
044
_vis_cf_col($vis) // ""
l!l
3113
MC/DC100%2/2
($vis->{"title"} // $result->{"title"}) // 'Visual ' . ($i + 1)
$vis->{"title"} $result->{"title"}
MC/DC100%1/1
$result->{"html"} // ""
$result->{"html"}
MC/DC100%1/1
$result->{"error"} // ""
$result->{"error"}
MC/DC100%1/1
$vis->{"kind"} // ""
$vis->{"kind"}
MC/DC0%0/1
$layout_pos{$i} // ""
$layout_pos{$i}
MC/DC100%1/1
_vis_cf_col($vis) // ""
_vis_cf_col($vis)
Truth table100%3/3
A // B
A= $vis->{"title"}B= $result->{"title"}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $result->{"html"}
Aresult
11
00
Truth table100%2/2
A
A= $result->{"error"}
Aresult
11
00
Truth table100%2/2
A
A= $vis->{"kind"}
Aresult
11
00
Truth table50%1/2
A
A= $layout_pos{$i}
Aresult
11
00
Truth table100%2/2
A
A= _vis_cf_col($vis)
Aresult
11
00
7623 cf_col => (_vis_cf_col($vis) // ''),
7624 cf_source => ($i == $cf_source ? 1 : 0),
7625 };
7626 }
7627  
7628 # bookmarks list for the toolbar panel.
7629 39 ▶ my @canvas_bookmarks = @{ $a->{bookmarks} // [] };
Condition50%1/2
$a->{"bookmarks"} // []
l!l
039
MC/DC0%0/1
$a->{"bookmarks"} // []
$a->{"bookmarks"}
Truth table50%1/2
A
A= $a->{"bookmarks"}
Aresult
11
00
7630 # Pre-encode as JSON for the JS canvasBookmarks variable.
7631 # Escape </ so the array literal cannot prematurely close a <script> tag.
7632 39 (my $bm_json = encode_json(\@canvas_bookmarks)) =~ s{</}{<\\/}g;
7633  
7634 my $canvas_columns_json = encode_json([
7635 39 ▶ map { { name => $_, numeric => _column_is_numeric($records, $_) ? 1 : 0 } }
Branch: 1 branch
BranchTrueFalseTotal
_column_is_numeric($records, $_) ? : 76 147 223
7636 @$columns
7637 ]);
7638 # The JSON is written into a <script> block. Escape '<' so a column
7639 # name containing markup cannot close the tag, as the chart spec is.
7640 39 $canvas_columns_json =~ s{<}{\\u003c}g;
7641  
7642 # The columns the page's own plan produces, for the panel that repairs a
7643 # card's: a card that takes the page's plan plots whatever that plan makes,
7644 # so the panel can only tell a reader what a change would cost it if it
7645 # knows the page's columns too.
7646 my $page_aliases = ($cross_row && ref $cross_row eq 'HASH')
7647 0 ▶ ? [ map { $_->{as} } @{ $cross_row->{specs} // [] } ] : [];
Branch: 1 branch
BranchTrueFalseTotal
$cross_row && ref $cross_row eq 'HASH' ? : 0 39 39
Condition20%1/5
$cross_row and ref $cross_row eq "HASH"
!ll&&!rl&&r
3900
$cross_row->{"specs"} // []
l!l
00
MC/DC0%0/2
$cross_row and ref $cross_row eq "HASH"
$cross_row ref $cross_row eq "HASH"
MC/DC0%0/1
$cross_row->{"specs"} // []
$cross_row->{"specs"}
Truth table33%1/3
A and B
A= $cross_rowB= ref $cross_row eq "HASH"
ABresult
0X0
100
111
Truth table0%0/2
A
A= $cross_row->{"specs"}
Aresult
11
00
7648 39 my $canvas_page_aliases_json = encode_json($page_aliases);
7649 39 $canvas_page_aliases_json =~ s{<}{\\u003c}g;
7650  
7651 39 my ($platform, $language) = $self->_resolve_template;
7652 return $self->render(
7653 handler => 'tt',
7654 template => "$platform/$language/canvas",
7655 format => 'html',
7656 title => $a->{name},
7657 canvas_id => $id,
7658 canvas_name => $a->{name},
7659 # The other sites the Share panel's embed code works on.
7660 embed_origins => [ Database::BI::_embed_frame_ancestors($self->app->config) ],
7661 canvas_data_url => ($self->_analysis_to_url($a) // ''),
7662 canvas_columns_json => $canvas_columns_json,
7663 canvas_page_aliases_json => $canvas_page_aliases_json,
7664 # The same menu the table page's cross-row panel renders, so a card
7665 # can offer the functions the pass actually knows.
7666 cross_row_menu => \@CROSS_ROW_MENU,
7667 text_font_menu => \@TEXT_FONTS,
7668 text_min_points => $MIN_TEXT_POINTS,
7669 text_max_points => $MAX_TEXT_POINTS,
7670 text_max_chars => $MAX_TEXT_CHARS,
7671 visuals => \@rendered,
7672 canvas_params => \@canvas_params,
7673 canvas_bookmarks => \@canvas_bookmarks,
7674 canvas_bookmarks_json => $bm_json,
7675 canvas_time_range => $self->stash('time_range'),
7676 canvas_time_range_col => ($self->stash('time_range') ? $self->stash('time_range')->{col} : ''),
7677 39 ▶ canvas_time_range_clear_url => (do {
Branch: 1 branch
BranchTrueFalseTotal
$self->stash('time_range') ? : 0 39 39
Condition50%1/2
$self->_analysis_to_url($a) // ""
l!l
390
MC/DC0%0/1
$self->_analysis_to_url($a) // ""
$self->_analysis_to_url($a)
Truth table50%1/2
A
A= $self->_analysis_to_url($a)
Aresult
11
00
7678 39 my $u = $self->req->url->clone;
7679 39 $u->query->remove('range')->remove('rcol');
7680 39 ▶ $self->stash('time_range') ? $u->to_string : '';
Branch: 4 branches
BranchTrueFalseTotal
$self->stash('time_range') ? : 0 39 39
$cf_active ? : 1 38 39
$drill_active ? : 0 39 39
$drill_active ? : 0 39 39
7681 }),
7682 canvas_range_cols => [ @$columns ],
7683 canvas_range_hidden => \@canvas_range_hidden,
7684 cf_active => $cf_active ? 1 : 0,
7685 cf_display => $cf_display,
7686 cf_clear_url => $cf_clear_url,
7687 drillthrough_url => $drillthrough_url,
7688 drill_active => $drill_active ? 1 : 0,
7689 # A drill is a hierarchy that exists, not a name in the query string:
7690 # a bookmark can outlive the hierarchy it was saved on, and a page
7691 # that said it was drilled when nothing answered would stop making
7692 # its marks controls and have no column to name in #cf-help.
7693 drill_name => ($drill_active ? $dd_name : ''),
7694 drill_level => $dd_level,
7695 drill_col => $drill_col,
7696 drill_crumb => \@drill_crumb,
7697 drill_max => $drill_max,
7698 extra_head => $canvas_map_head,
7699 back_url => '/',
7700 back_label => 'Home',
7701 freshness_stale => $freshness_stale,
7702 freshness_msg => $freshness_msg,
7703 freshness_source_mtime => $freshness_source_mtime,
7704 language => $language,
7705 );
7706 }
7707  
7708 # no visuals yet -- reconstruct the data-view URL and redirect.
7709 6 my $url = $self->_analysis_to_url($a);
7710 6 ▶ return $self->render(text => 'Cannot reconstruct URL from this analysis', status => 422)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url 3 3 6
7711 unless defined $url;
7712  
7713 3 $self->redirect_to($url);
7714 }
7715  
7716 # _run_export_pipeline($self) -> ($records, \@columns, $left_label) or ()
7717 #
7718 # Purpose: Thin wrapper over _run_pipeline_source that additionally applies
7719 # f= filters, d=1 dedup, and page/per_page pagination. Used by
7720 # export_data, export_write, folder_view, and import_url (row-viewing
7721 # routes that do not need the source object for aggregation).
7722 # Entry: Reads "l=", "j=" (repeatable), "c=" (repeatable), "f=" (repeatable),
7723 # "d=", "page=", "per_page=" query/body params.
7724 # Exit: On success: ($filtered_arrayref, \@column_names, $left_label_string).
7725 # On failure: empty list (left table not found / fetch error).
7726 230 ▶sub _run_export_pipeline :Protected ($self) {
Subroutine _run_export_pipeline: called CC=16 SCAR=27.7
7727 230 my (undef, $records, $columns, $left_label) = $self->_run_pipeline_source;
7728 230 ▶ return () unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 15 215 230
7729  
7730 # The export honours span= like the page it was linked from, and accepts the
7731 # dimension params of the aggregating routes so a chart's own URL can be
7732 # pasted into /export and mean the same thing.
7733 215 my $span = $self->_span_calc_spec($columns, 'cat', 'x', 'rows', 'group');
7734 # The stash says the reply has gone. Without it the caller takes the empty list
7735 # for "no such table" and renders a second time, and the client is left hanging
7736 # on a reply that never finishes.
7737 215 ▶ if ($span && $span->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($span and $span->{"error"}) 16 199 215
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
199016
MC/DC50%1/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table66%2/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
7738 16 $self->stash('_reduce_error' => 1);
7739 16 $self->render(text => $span->{error}, status => 400);
7740 16 return ();
7741 }
7742  
7743 199 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
7744 199 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 199 199
7745 199 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 11 188 199
7746 11 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
7747 11 $self->stash('_reduce_error' => 1);
7748 11 $self->render(text => $e, status => 400);
7749 11 return ();
7750 }
7751  
7752 188 ▶ return () unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 12 176 188
7753  
7754 176 ▶ my @columns = @{ $columns // [] };
Condition50%1/2
$columns // []
l!l
1760
MC/DC0%0/1
$columns // []
$columns
Truth table50%1/2
A
A= $columns
Aresult
11
00
7755  
7756 # d=1 has been applied by _reduce_or_render, before the cross-row pass.
7757  
7758 # Sort support for /export: applied in memory after filtering/dedup.
7759 176 my $sort = $self->param('sort');
7760 176 ▶ my $dir = ($self->param('dir') // 'asc') =~ /\Adesc\z/i ? 'desc' : 'asc';
Branch: 1 branch
BranchTrueFalseTotal
($self->param('dir') // 'asc') =~ /\Adesc\z/iu ? : 5 171 176
Condition100%2/2
$self->param("dir") // "asc"
l!l
31145
MC/DC100%1/1
$self->param("dir") // "asc"
$self->param("dir")
Truth table100%2/2
A
A= $self->param("dir")
Aresult
11
00
7761 176 ▶ if (defined $sort && grep { $_ eq $sort } @columns) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort and grep {$_ eq $sort;} @columns) { } 5 171 176
elsif (defined $sort) { } 3 168 171
Condition100%3/3
defined $sort and grep {$_ eq $sort;} @columns
!ll&&!rl&&r
16835
MC/DC100%2/2
defined $sort and grep {$_ eq $sort;} @columns
defined $sort grep {$_ eq $sort;} @columns
Truth table100%3/3
A and B
A= defined $sortB= grep {$_ eq $sort;} @columns
ABresult
0X0
100
111
7762 # By the same rule as the table pages (_sort_records returns a new
7763 # array: the backend's own can be read-only, as a SQLite one is).
7764 5 $records = _sort_records($records, $sort, $dir);
7765 5 $self->stash(sorted_by => { col => $sort, dir => $dir });
7766 } elsif (defined $sort) {
7767 3 carp $self->_i18n('error_sort_column', $sort);
7768 }
7769  
7770 # Server-side pagination for /export.
7771 176 ▶ if (defined $self->param('page') || defined $self->param('per_page')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->param("page") or defined $self->param("per_page")) 7 169 176
Condition100%3/3
defined $self->param("page") or defined $self->param("per_page")
l!l&&r!l&&!r
52169
MC/DC100%2/2
defined $self->param("page") or defined $self->param("per_page")
defined $self->param("page") defined $self->param("per_page")
Truth table100%3/3
A or B
A= defined $self->param("page")B= defined $self->param("per_page")
ABresult
1X1
011
000
7772 7 my ($page, $per_page, $offset) = $self->_pagination;
7773 7 my $total = scalar @$records;
7774 7 ▶ my $has_next = ($total > $offset + $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$total > $offset + $per_page ? : 3 4 7
7775 7 my @page_recs = @{ _rows_of_page($records, $offset, $per_page) };
7776 7 $records = \@page_recs;
7777 7 $self->stash(export_has_next => $has_next, export_page => $page, export_per_page => $per_page);
7778 }
7779  
7780 176 return ($records, \@columns, $left_label);
7781 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7782  
7783 # _decode_cell($s) -> $character_string
7784 #
7785 # Purpose: Ensure $s is a Perl character string, not raw UTF-8 bytes.
7786 # URL-fetched data (via LWP::UserAgent::Cached + D::A HTML parsing)
7787 # arrives as byte strings without the UTF-8 flag set. encode_json
7788 # then treats each byte as a Latin-1 code point and re-encodes it,
7789 # producing mojibake (e.g. an o-umlaut character displayed as two garbage bytes). This helper
7790 # upgrades the flag in-place on a copy so the original hash key is
7791 # unchanged but the value passed to HTML::D3 is a proper character.
7792 # Entry: $s -- any defined scalar (undef returned as-is).
7793 # Exit: The same string value, but with the UTF-8 flag set if it was absent.
7794 4470 ▶sub _decode_cell {
Subroutine _decode_cell: called CC=3 SCAR=11.0
7795 4470 my $s = shift;
7796 4470 ▶ return $s unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 1 4469 4470
7797 4469 ▶ utf8::decode($s) unless utf8::is_utf8($s);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($s) 4468 1 4469
7798 4469 $s;
7799 }
7800  
7801 # _export_selection($self, $records, \@columns) -> ($records, \@columns)
7802 #
7803 # Purpose: Narrow an export to the columns the reader's table still shows, in
7804 # the table's order. Deleting or dragging a column happens only in
7805 # the browser, so the Export panel sends what is left as repeated
7806 # xcol= and the server applies it here.
7807 # Entry: $self is the controller (called as a function: it only reads
7808 # params); $records are hashrefs, possibly locked (SQL backends), so
7809 # new hashes are built and the originals never written.
7810 # Exit: The same two refs when xcol is absent or names no column of the
7811 # view; otherwise new refs holding only the known, de-duplicated
7812 # names. Unknown names are ignored, not an error.
7813 # Side Effects: None.
7814 115 ▶sub _export_selection {
Subroutine _export_selection: called CC=4 SCAR=19.6
7815 115 my ($self, $records, $columns) = @_;
7816 115 my %known = map { $_ => 1 } @$columns;
7817 115 my %seen;
7818 0 ▶ my @keep = grep { $known{$_} && !$seen{$_}++ }
Condition0%0/3
$known{$_} && !$seen{$_}++
!ll&&!rl&&r
000
MC/DC0%0/2
$known{$_} && !$seen{$_}++
$known{$_} !$seen{$_}++
Truth table0%0/3
A && not(B)
A= $known{$_}B= !$seen{$_}++
ABresult
0X0
100
111
7819 0 ▶ grep { defined && length } @{ $self->every_param('xcol') };
Condition0%0/3
defined $_ && length $_
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table0%0/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
7820 115 ▶ return ($records, $columns) unless @keep;
Branch: 1 branch
BranchTrueFalseTotal
unless @keep 115 0 115
7821 0 return ([ map { _row_subset($_, \@keep) } @$records ], \@keep);
7822 }
7823  
7824 # _row_subset(\%row, \@columns) -> \%new_row
7825 #
7826 # Purpose: Copy the named columns of one row into a plain hash. A column the
7827 # row lacks becomes undef: reading it directly would croak on a
7828 # locked (restricted) hash from a SQL backend.
7829 64 ▶sub _row_subset {
Subroutine _row_subset: called CC=2 SCAR=6.9
7830 64 my ($row, $columns) = @_;
7831 64 ▶ return +{ map { $_ => (exists $row->{$_} ? $row->{$_} : undef) } @$columns };
Branch: 1 branch
BranchTrueFalseTotal
exists $row->{$_} ? : 355 1 356
7832 }
7833  
7834 # _serialize_json($records, \@columns) -> $utf8_bytes
7835 #
7836 # Purpose: A JSON array of row objects whose keys follow @$columns. A hash
7837 # has no order, so encode_json on the rows would list keys in any
7838 # order and a column the reader dragged would not stay put.
7839 # Entry: $records are hashrefs; $columns the names, in the order wanted.
7840 # Exit: UTF-8 bytes. A column a row lacks is written as null.
7841 # Side Effects: None.
7842 16 ▶sub _serialize_json {
Subroutine _serialize_json: called CC=1 SCAR=0.0
7843 16 my ($records, $columns) = @_;
7844 16 my @names = map { encode_json($_) } @$columns;
7845 my @objects = map {
7846 16 my $row = _row_subset($_, $columns);
7847 64 '{' . join(',', map { $names[$_] . ':' . encode_json($row->{ $columns->[$_] }) } 0 .. $#names) . '}';
7848 } @$records;
7849 16 return '[' . join(',', @objects) . ']';
7850 }
7851  
7852 # _serialize_csv($records, \@columns) -> $utf8_string
7853 #
7854 # Purpose: Build a complete RFC 4180 CSV document (header + data rows) from
7855 # $records. Shared by _render_csv (HTTP download) and the csv branch
7856 # of export_write (filesystem write) to eliminate duplicated logic.
7857 # Entry: $records is an arrayref of hashrefs; $columns is an arrayref of names.
7858 # Exit: Returns a UTF-8 Perl string ending with CRLF.
7859 #
7860 # Optimisation: rows are collected in @lines and joined in one operation.
7861 # The previous pattern ($out .= _csv_row(...) per row) triggers O(N) string
7862 # reallocations; joining a pre-built array is a single O(total_bytes) allocation.
7863 # For exports of thousands of rows the difference is measurable.
7864 #
7865 # XS note: for very large exports, replacing _csv_row with Text::CSV_XS
7866 # (available from CPAN) would further reduce serialisation time -- its C-level
7867 # implementation is roughly 5-10x faster than the pure-Perl version here.
7868 107 ▶sub _serialize_csv {
Subroutine _serialize_csv: called CC=2 SCAR=6.9
7869 107 my ($records, $columns) = @_;
7870 107 my @lines = _csv_row(@$columns);
7871 107 for my $row (@$records) {
7872 548 push @lines, _csv_row(map { $row->{$_} } @$columns);
7873 }
7874 107 return encode('UTF-8', join('', @lines));
7875 }
7876  
7877 # _render_csv($self, $records, \@columns, $name) -> void (renders response)
7878 #
7879 # Purpose: Serialise $records to RFC 4180 CSV and emit as a UTF-8 download.
7880 # Entry: $name is a safe filename stem (alphanumeric/underscore).
7881 # Exit: Renders the Mojolicious response; does not return a meaningful value.
7882 # Side Effects: Writes HTTP response headers and body.
7883 72 ▶sub _render_csv :Protected ($self, $records, $columns, $name) {
Subroutine _render_csv: called CC=1 SCAR=0.0
7884 72 $self->stash(buffer => 0);
7885 72 $self->res->headers->content_type('text/csv; charset=UTF-8');
7886 72 $self->res->headers->content_disposition(qq{attachment; filename="${name}.csv"});
7887 72 $self->render(data => _serialize_csv($records, $columns));
7888 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7889  
7890 # _render_sqlite($self, $records, \@columns, $name) -> void (renders response)
7891 #
7892 # Purpose: Write $records to a SQLite database and emit it as a binary download.
7893 # Entry: $name is a safe filename stem.
7894 # Exit: Renders the Mojolicious response.
7895 # Side Effects: Creates and unlinks a temporary file; writes HTTP response.
7896 8 ▶sub _render_sqlite :Protected ($self, $records, $columns, $name) {
Subroutine _render_sqlite: called CC=2 SCAR=6.9
7897 8 $self->stash(buffer => 0);
7898 8 my $data = eval { $self->_write_sqlite_db($records, $columns) };
7899 8 ▶ unless (defined $data) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 2 6 8
7900 2 $self->app->log->error('SQLite export failed: ' . _tidy_error($@));
7901 2 return $self->render(text => $self->_i18n('error_export_sqlite'), status => 500);
7902 }
7903 6 $self->res->headers->content_type('application/vnd.sqlite3');
7904 6 $self->res->headers->content_disposition(qq{attachment; filename="${name}.db"});
7905 6 $self->render(data => $data);
7906 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7907  
7908 # _render_json($self, $records, \@columns, $name) -> void (renders response)
7909 #
7910 # Purpose: Emit $records as a JSON array download.
7911 # Entry: $records is an arrayref of hashrefs; $name is a safe filename stem.
7912 # Exit: Renders the Mojolicious response.
7913 # Side Effects: Writes HTTP response headers and body.
7914 15 ▶sub _render_json :Protected ($self, $records, $columns, $name) {
Subroutine _render_json: called CC=1 SCAR=0.0
7915 15 $self->stash(buffer => 0);
7916 15 $self->res->headers->content_disposition(qq{attachment; filename="${name}.json"});
7917 15 $self->res->headers->content_type('application/json;charset=UTF-8');
7918 15 $self->render(data => _serialize_json($records, $columns));
7919 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7920  
7921 # ---------------------------------------------------------------------------
7922 # Public actions
7923 # ---------------------------------------------------------------------------
7924  
7925 =encoding utf8
7926  
7927 =head1 ACTIONS
7928  
7929 =head2 index
7930  
7931 C<GET /> -- Scan C<data_dir> and present a card grid of available tables.
7932  
7933 =head3 API SPECIFICATION
7934  
7935 =head4 INPUT
7936  
7937 None (reads C<data_dir> from application config, and C<BI_OPEN> and the
7938 C<Referer> header).
7939  
7940 =head4 OUTPUT
7941  
7942 When C<BI_OPEN> is set and the request has no C<Referer> from this server,
7943 redirects to C</open> for that path. Otherwise renders C<home.html.tt> with:
7944  
7945 tables ARRAYREF of { name => $stem, file => $basename }
7946 title 'Choose a Database'
7947  
7948 =head3 MESSAGES
7949  
7950 None produced by this action; any file-scan errors are silently ignored
7951 (empty directory yields an empty card grid).
7952  
7953 =head3 FORMAL SPECIFICATION
7954  
7955 index == lambda self .
7956 let dir = resolve self.app.config.data_dir in
7957 let tbls = { b | b in dir /\ basename(b) =~ EXT_RE } in
7958 post render(home, tables: map(stem, tbls))
7959  
7960 =head3 EXAMPLE
7961  
7962 GET / -> 200 text/html containing a card for each file in data/
7963  
7964 With BI_OPEN=/data/store.db and no Referer from this server:
7965 GET / -> 302 /open?path=%2Fdata%2Fstore.db
7966  
7967 =cut
7968  
7969 61 ▶sub index ($self) {
Subroutine index: called CC=6 SCAR=29.7
Pod documented
7970 # A database named when the server was started is what a reader arriving
7971 # from outside sees first. A Home link within the application carries this
7972 # server as its Referer and gets the list, so that stays reachable. The
7973 # check needs no state, so it survives morbo restarting the application.
7974 61 ▶ if (defined $ENV{BI_OPEN} && length $ENV{BI_OPEN}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{"BI_OPEN"} and length $ENV{"BI_OPEN"}) 0 61 61
Condition33%1/3
defined $ENV{"BI_OPEN"} and length $ENV{"BI_OPEN"}
!ll&&!rl&&r
6100
MC/DC0%0/2
defined $ENV{"BI_OPEN"} and length $ENV{"BI_OPEN"}
defined $ENV{"BI_OPEN"} length $ENV{"BI_OPEN"}
Truth table33%1/3
A and B
A= defined $ENV{"BI_OPEN"}B= length $ENV{"BI_OPEN"}
ABresult
0X0
100
111
7975 0 my $from = $self->req->headers->referrer;
7976 0 my $here = $self->req->url->to_abs->host_port;
7977 0 ▶ return $self->redirect_to('/open?path=' . url_escape($ENV{BI_OPEN}))
Branch: 1 branch
BranchTrueFalseTotal
unless defined $from and ("Mojo::URL"->new($from)->host_port // "") eq $here 0 0 0
Condition0%0/5
defined $from and ("Mojo::URL"->new($from)->host_port // "") eq $here
!ll&&!rl&&r
000
"Mojo::URL"->new($from)->host_port // ""
l!l
00
MC/DC0%0/2
defined $from and ("Mojo::URL"->new($from)->host_port // "") eq $here
defined $from "Mojo::URL"->new($from)->host_port
Truth table0%0/3
A and B
A= defined $fromB= "Mojo::URL"->new($from)->host_port
ABresult
0X0
100
111
7978 unless defined $from && (Mojo::URL->new($from)->host_port // '') eq $here;
7979 }
7980  
7981 61 my ($platform, $language) = $self->_resolve_template;
7982  
7983 # The layout writes the resolved language into <html lang>, so every action
7984 # that renders a template from $platform/$language hands it over; t/html-lang.t
7985 # holds the controller to that. A screen reader, a translation tool and
7986 # anything that indexes the page read the attribute.
7987 61 $self->render(
7988 template => "$platform/$language/home",
7989 handler => 'tt',
7990 format => 'html',
7991 tables => $self->_scan_data_dir,
7992 title => 'Choose a Database',
7993 language => $language,
7994 );
7995 }
7996  
7997 =head2 is_supported_file
7998  
7999 Say whether a file's name has an extension C</open> will read. C<script/database-bi>
8000 asks this to refuse a file before the server starts, rather than show a 404.
8001  
8002 =head3 API SPECIFICATION
8003  
8004 =head4 INPUT
8005  
8006 $path string, a file name or path; undef is allowed
8007  
8008 =head4 OUTPUT
8009  
8010 1 when the name ends in a supported extension (any case), otherwise 0
8011  
8012 =head3 MESSAGES
8013  
8014 None.
8015  
8016 =head3 FORMAL SPECIFICATION
8017  
8018 is_supported_file == lambda path . path =~ EXT_RE
8019  
8020 =head3 EXAMPLE
8021  
8022 is_supported_file('data/store.db') # 1
8023 is_supported_file('LICENSE') # 0
8024  
8025 =cut
8026  
8027 19 ▶sub is_supported_file ($path) {
Subroutine is_supported_file: called CC=3 SCAR=11.0
Pod documented
8028 19 ▶ return (defined $path && $path =~ $EXT_RE) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $path && $path =~ /$EXT_RE/u ? : 11 8 19
Condition100%3/3
defined $path and $path =~ /$EXT_RE/u
!ll&&!rl&&r
1711
MC/DC100%2/2
defined $path and $path =~ /$EXT_RE/u
defined $path $path =~ /$EXT_RE/u
Truth table100%3/3
A and B
A= defined $pathB= $path =~ /$EXT_RE/u
ABresult
0X0
100
111
8029 }
8030  
8031 =head2 require_login / login_form / login / logout
8032  
8033 The login, on only when config C<password_hash> is set (see
8034 L<Database::BI/Logging in>). C<require_login> is the C<under> every route but
8035 C</login>, C</logout>, C</share/:id> and C</embed/:id> passes through; the
8036 others are C<GET /login>, C<POST /login> and C<POST /logout>.
8037  
8038 A session is logged in when its C<login> value is this password's mark (an
8039 HMAC of the hash, keyed by the first secret), so a new password logs every
8040 session out. Wrong passwords are counted per remote address, in each server
8041 process: the tenth within 15 minutes locks that address out for the rest of
8042 the 15 minutes (C<429>), whether or not the next one is right.
8043  
8044 =head3 API SPECIFICATION
8045  
8046 =head4 INPUT
8047  
8048 require_login: any request
8049 GET /login: return= string, optional; a path on this site (default /)
8050 POST /login: password= string; return= as above
8051 POST /logout: none
8052  
8053 =head4 OUTPUT
8054  
8055 require_login: true when login is off or the session is logged in. Otherwise
8056 a browser's GET for a page is redirected (302) to
8057 /login?return=<the page>, and anything else gets
8058 401 application/json { "error": error_login_required }.
8059 GET /login: 200 text/html, the form; 302 to return= when logged in; with
8060 login off, 200 and a page that says no password is set.
8061 POST /login: 302 to return= when the password is right; 401 text/html, the
8062 form with error_login_failed, when not; 429 with
8063 error_login_locked after too many.
8064 POST /logout: 302 to /login (to / when login is off), the session ended.
8065  
8066 return= is followed only when it is a path on this site (one /, not // or /\);
8067 anything else goes to /.
8068  
8069 =cut
8070  
8071 # Wrong passwords per application (a test runs several) and remote address:
8072 # epoch seconds of each, newest last.
8073 10 my %LOGIN_FAILURES;
8074 10 Readonly my $LOGIN_WINDOW => 15 * 60;
8075 10 Readonly my $LOGIN_ATTEMPTS => 10;
8076  
8077 # _login_mark($self, $hash) -> $mark
8078 #
8079 # What a logged-in session holds: not the hash, which the readable cookie
8080 # would hand to anyone who saw it, but an HMAC of it keyed by the secret.
8081 1 ▶sub _login_mark ($self, $hash) {
Subroutine _login_mark: called CC=1 SCAR=0.0
8082 1 return Digest::SHA::hmac_sha256_hex($hash, $self->app->secrets->[0]);
8083 }
8084  
8085 # _login_return($value) -> $path
8086 #
8087 # Where to go after logging in: a path on this site, never another site
8088 # (//evil.example and /\evil.example are other sites to a browser).
8089 11 ▶sub _login_return {
Subroutine _login_return: called CC=5 SCAR=24.5
8090 11 my ($value) = @_;
8091 11 ▶ return '/' unless defined $value && $value =~ m{\A/(?![/\\])} && $value !~ /[\x00-\x20\x7f\\]/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value =~ m(\A/(?![/\\]))u and not $value =~ /[\x00-\x20\x7f\\]/u 11 0 11
Condition33%2/6
defined $value and $value =~ m(\A/(?![/\\]))u and not $value =~ /[\x00-\x20\x7f\\]/u
!ll&&!rl&&r
1100
defined $value and $value =~ m(\A/(?![/\\]))u
!ll&&!rl&&r
1100
MC/DC0%0/3
defined $value and $value =~ m(\A/(?![/\\]))u and not $value =~ /[\x00-\x20\x7f\\]/u
defined $value $value =~ m(\A/(?![/\\]))u not $value =~ /[\x00-\x20\x7f\\]/u
Truth table25%1/4
A and B and not(C)
A= defined $valueB= $value =~ m(\A/(?![/\\]))uC= not $value =~ /[\x00-\x20\x7f\\]/u
ABCresult
0XX0
10X0
1100
1111
8092 0 ▶ return '/' if $value =~ m{\A/log(?:in|out)\b};
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ m[\A/log(?:in|out)\b]u 0 0 0
8093 0 return $value;
8094 }
8095  
8096 # _login_hash($self) -> $hash | undef
8097 3008 ▶sub _login_hash ($self) {
Subroutine _login_hash: called CC=3 SCAR=11.1
8098 3008 my $hash = $self->app->config('password_hash');
8099 3008 ▶ return (defined $hash && length $hash) ? $hash : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $hash && length $hash ? : 13 2995 3008
Condition66%2/3
defined $hash and length $hash
!ll&&!rl&&r
2995013
MC/DC50%1/2
defined $hash and length $hash
defined $hash length $hash
Truth table66%2/3
A and B
A= defined $hashB= length $hash
ABresult
0X0
100
111
8100 }
8101  
8102 1 ▶sub _logged_in ($self) {
Subroutine _logged_in: called CC=4 SCAR=15.8
8103 1 ▶ my $hash = $self->_login_hash // return 1;
Condition50%1/2
$self->_login_hash // (return 1)
l!l
10
MC/DC0%0/1
$self->_login_hash // (return 1)
$self->_login_hash
Truth table50%1/2
A
A= $self->_login_hash
Aresult
11
00
8104 1 ▶ return secure_compare($self->session('login') // '', $self->_login_mark($hash)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
secure_compare($self->session('login') // '', $self->_login_mark($hash)) ? : 0 1 1
Condition50%1/2
$self->session("login") // ""
l!l
01
MC/DC0%0/1
$self->session("login") // ""
$self->session("login")
Truth table50%1/2
A
A= $self->session("login")
Aresult
11
00
8105 }
8106  
8107 2996 ▶sub require_login ($self) {
Subroutine require_login: called CC=7 SCAR=24.7
Pod documented
8108 2996 ▶ return 1 unless defined $self->_login_hash;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->_login_hash 2995 1 2996
8109 1 ▶ if ($self->_logged_in) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_logged_in) 0 1 1
8110 0 $self->stash(logged_in => 1);
8111 0 return 1;
8112 }
8113  
8114 1 my $req = $self->req;
8115 1 $self->stash(buffer => 0);
8116 1 ▶ if ($req->method =~ /\A(?:GET|HEAD)\z/ && ($req->headers->accept // '') =~ m{text/html}
Branch: 1 branch
BranchTrueFalseTotal
if ($req->method =~ /\A(?:GET|HEAD)\z/u and ($req->headers->accept // "") =~ m[text/html]u and not $req->url->path->to_string =~ m[\A/api/]u) 0 1 1
Condition37%3/8
$req->method =~ /\A(?:GET|HEAD)\z/u and ($req->headers->accept // "") =~ m[text/html]u and not $req->url->path->to_string =~ m[\A/api/]u
!ll&&!rl&&r
100
$req->method =~ /\A(?:GET|HEAD)\z/u and ($req->headers->accept // "") =~ m[text/html]u
!ll&&!rl&&r
010
$req->headers->accept // ""
l!l
01
MC/DC0%0/3
$req->method =~ /\A(?:GET|HEAD)\z/u and ($req->headers->accept // "") =~ m[text/html]u and not $req->url->path->to_string =~ m[\A/api/]u
$req->method =~ /\A(?:GET|HEAD)\z/u $req->headers->accept not $req->url->path->to_string =~ m[\A/api/]u
Truth table25%1/4
A and B and not(C)
A= $req->method =~ /\A(?:GET|HEAD)\z/uB= $req->headers->acceptC= not $req->url->path->to_string =~ m[\A/api/]u
ABCresult
0XX0
10X0
1100
1111
8117 && $req->url->path->to_string !~ m{\A/api/}) {
8118 0 my $url = Mojo::URL->new('/login')->query(return => $req->url->path_query);
8119 0 $self->redirect_to($url);
8120 0 return undef;
8121 }
8122 1 $self->render(json => { error => _message_text('error_login_required') }, status => 401);
8123 1 return undef;
8124 }
8125  
8126 11 ▶sub _render_login ($self, %args) {
Subroutine _render_login: called CC=4 SCAR=15.2
8127 11 my ($platform, $language) = $self->_resolve_template;
8128 11 $self->stash(buffer => 0);
8129 return $self->render(
8130 template => "$platform/$language/login",
8131 handler => 'tt',
8132 format => 'html',
8133 title => 'Log in',
8134 language => $language,
8135 return_to => _login_return(scalar $self->param('return')),
8136 login_error => $args{error} // '',
8137 login_off => $args{login_off} ? 1 : 0,
8138 11 ▶ status => $args{status} // 200,
Branch: 1 branch
BranchTrueFalseTotal
$args{'login_off'} ? : 0 11 11
Condition50%2/4
$args{"error"} // ""
l!l
110
$args{"status"} // 200
l!l
110
MC/DC0%0/1
$args{"error"} // ""
$args{"error"}
MC/DC0%0/1
$args{"status"} // 200
$args{"status"}
Truth table50%1/2
A
A= $args{"error"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"status"}
Aresult
11
00
8139 );
8140 }
8141  
8142 0 ▶sub login_form ($self) {
Subroutine login_form: not called CC=3 SCAR=24.8
Pod documented
8143 # With no password set the page says so, rather than offering a form that
8144 # could never succeed.
8145 0 ▶ return $self->_render_login(login_off => 1) unless defined $self->_login_hash;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->_login_hash 0 0 0
8146 0 ▶ return $self->redirect_to(_login_return(scalar $self->param('return'))) if $self->_logged_in;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_logged_in 0 0 0
8147 0 return $self->_render_login;
8148 }
8149  
8150 11 ▶sub login ($self) {
Subroutine login: called CC=12 SCAR=25.8
Pod documented
8151 11 my $hash = $self->_login_hash;
8152 11 ▶ return $self->redirect_to('/') unless defined $hash;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hash 0 11 11
8153  
8154 11 ▶ my $who = $self->tx->remote_address // '';
Condition50%1/2
$self->tx->remote_address // ""
l!l
110
MC/DC0%0/1
$self->tx->remote_address // ""
$self->tx->remote_address
Truth table50%1/2
A
A= $self->tx->remote_address
Aresult
11
00
8155 11 my $now = time;
8156 11 ▶ my $failures = $LOGIN_FAILURES{ Scalar::Util::refaddr($self->app) } //= {};
Condition100%2/2
$LOGIN_FAILURES{builtin::refaddr($self->app)} //= {}
l!l
101
MC/DC100%1/1
$LOGIN_FAILURES{builtin::refaddr($self->app)} //= {}
$LOGIN_FAILURES{builtin::refaddr($self->app)}
Truth table100%2/2
A
A= $LOGIN_FAILURES{builtin::refaddr($self->app)}
Aresult
11
00
8157 11 for my $addr (keys %{$failures}) {
8158 10 $failures->{$addr} = [ grep { $_ > $now - $LOGIN_WINDOW } @{ $failures->{$addr} } ];
8159 10 ▶ delete $failures->{$addr} unless @{ $failures->{$addr} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$failures->{$addr};} 0 10 10
8160 }
8161 11 ▶ my $seen = $failures->{$who} // [];
Condition100%2/2
$failures->{$who} // []
l!l
101
MC/DC100%1/1
$failures->{$who} // []
$failures->{$who}
Truth table100%2/2
A
A= $failures->{$who}
Aresult
11
00
8162 11 ▶ if (@{$seen} >= $LOGIN_ATTEMPTS) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$seen;} >= $LOGIN_ATTEMPTS) 1 10 11
8163 1 ▶ my $minutes = int(($seen->[0] + $LOGIN_WINDOW - $now + 59) / 60) || 1;
Condition50%1/2
int(($seen->[0] + $LOGIN_WINDOW - $now + 59) / 60) || 1
l!l
10
MC/DC0%0/1
int(($seen->[0] + $LOGIN_WINDOW - $now + 59) / 60) || 1
int(($seen->[0] + $LOGIN_WINDOW - $now + 59) / 60)
Truth table50%1/2
A
A= int(($seen->[0] + $LOGIN_WINDOW - $now + 59) / 60)
Aresult
11
00
8164 1 return $self->_render_login(error => sprintf(_message_text('error_login_locked'), $minutes), status => 429);
8165 }
8166  
8167 10 ▶ unless (Database::BI::Password::verify_password(scalar($self->param('password')) // '', $hash)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (Database::BI::Password::verify_password(scalar $self->param("password") // "", $hash)) 10 0 10
Condition50%1/2
scalar $self->param("password") // ""
l!l
100
MC/DC0%0/1
scalar $self->param("password") // ""
scalar $self->param("password")
Truth table50%1/2
A
A= scalar $self->param("password")
Aresult
11
00
8168 10 ▶ push @{ $failures->{$who} //= [] }, $now;
Condition100%2/2
$failures->{$who} //= []
l!l
91
MC/DC100%1/1
$failures->{$who} //= []
$failures->{$who}
Truth table100%2/2
A
A= $failures->{$who}
Aresult
11
00
8169 10 $self->app->log->warn("Wrong password from $who");
8170 10 return $self->_render_login(error => _message_text('error_login_failed'), status => 401);
8171 }
8172  
8173 0 delete $failures->{$who};
8174 0 $self->session(login => $self->_login_mark($hash));
8175 0 return $self->redirect_to(_login_return(scalar $self->param('return')));
8176 }
8177  
8178 0 ▶sub logout ($self) {
Subroutine logout: not called CC=2 SCAR=17.9
Pod documented
8179 0 $self->session(expires => 1);
8180 0 ▶ return $self->redirect_to(defined $self->_login_hash ? '/login' : '/');
Branch: 1 branch
BranchTrueFalseTotal
defined $self->_login_hash ? : 0 0 0
8181 }
8182  
8183 =head2 preferences
8184  
8185 C<GET /preferences> -- Render the page where a reader sets their preferences:
8186 the light or dark theme, and how many rows a table shows on a page.
8187  
8188 Preferences belong to the browser, not to the server, so this action only
8189 renders the form. The theme is kept in C<localStorage>; the script that
8190 stores and applies it is in C<layouts/theme.html.tt>, which every page loads.
8191 The page size is kept in the cookie C<bi_per_page> (25, 50, 100, 200, or 0 for
8192 every row), because the server needs it before it reads the page; this action
8193 reads it to show the current choice.
8194  
8195 =head3 API SPECIFICATION
8196  
8197 =head4 INPUT
8198  
8199 cookie bi_per_page optional; the saved page size, shown as chosen
8200  
8201 =head4 OUTPUT
8202  
8203 200 text/html The preferences page.
8204  
8205 =head3 FORMAL SPECIFICATION
8206  
8207 preferences
8208 response! : HTTP
8209 ──────────
8210 response!.status = 200
8211  
8212 =cut
8213  
8214 1 ▶sub preferences ($self) {
Subroutine preferences: called CC=2 SCAR=8.1
Pod documented
8215 1 my ($platform, $language) = $self->_resolve_template;
8216  
8217 1 ▶ $self->render(
Condition33%1/3
_page_size_preference($self) // $DEFAULT_PER_PAGE
l!l&&r!l&&!r
010
MC/DC0%0/2
_page_size_preference($self) // $DEFAULT_PER_PAGE
_page_size_preference($self) $DEFAULT_PER_PAGE
Truth table33%1/3
A // B
A= _page_size_preference($self)B= $DEFAULT_PER_PAGE
ABresult
1X1
011
000
8218 template => "$platform/$language/preferences",
8219 handler => 'tt',
8220 format => 'html',
8221 title => 'Preferences',
8222 language => $language,
8223 page_size => _page_size_preference($self) // $DEFAULT_PER_PAGE,
8224 page_size_choices => [ @PAGE_SIZES ],
8225 page_size_cookie => $PAGE_SIZE_COOKIE,
8226 );
8227 }
8228  
8229 =head2 tutorial
8230  
8231 C<GET /tutorial> -- Render the tutorial that is part of the application.
8232  
8233 The chapters, questions and glossary are data in L<Database::BI::Tutorial>.
8234 They are not in this module's POD, so adding a feature means adding a chapter
8235 there and no change to this action or to the template.
8236  
8237 =head3 API SPECIFICATION
8238  
8239 =head4 INPUT
8240  
8241 None.
8242  
8243 =head4 OUTPUT
8244  
8245 200 text/html The tutorial page. It is cached when page_cache_dir is set.
8246  
8247 =head3 FORMAL SPECIFICATION
8248  
8249 tutorial
8250 response! : HTTP
8251 ──────────
8252 response!.status = 200
8253  
8254 =cut
8255  
8256 7 ▶sub tutorial ($self) {
Subroutine tutorial: called CC=2 SCAR=7.1
Pod documented
8257 7 ▶ return if $self->buffer_is_cached;
Branch: 1 branch
BranchTrueFalseTotal
if $self->buffer_is_cached 0 7 7
8258 7 my ($platform, $language) = $self->_resolve_template;
8259  
8260 7 $self->render(
8261 template => "$platform/$language/tutorial",
8262 handler => 'tt',
8263 format => 'html',
8264 title => 'Tutorial',
8265 language => $language,
8266 intro => Database::BI::Tutorial->intro,
8267 parts => Database::BI::Tutorial->parts,
8268 faq => Database::BI::Tutorial->faq,
8269 glossary => Database::BI::Tutorial->glossary,
8270 version => $self->app->VERSION,
8271 );
8272 }
8273  
8274 =head2 view
8275  
8276 C<GET /view/:table> -- Open and display the chosen table from C<data_dir>.
8277  
8278 =head3 API SPECIFICATION
8279  
8280 =head4 INPUT
8281  
8282 :table string Table name (alphanumeric + underscore). Returns 404 on
8283 other characters.
8284 ?f= string (repeatable) Filter spec: "col:op:val".
8285  
8286 =head4 DOMAIN CONSTRAINTS: :table
8287  
8288 C<:table> is validated against C<\A[A-Za-z_][A-Za-z0-9_]*\z> before C<open_table>
8289 is ever called. The first character must be a letter (A-Z, a-z) or an
8290 underscore; subsequent characters may also include digits (0-9).
8291  
8292 =over 4
8293  
8294 =item Valid partition
8295  
8296 C<sales> (letters only), C<_temp> (underscore-start), C<report_2024>
8297 (mixed). A name that is valid but has no backing file returns 200 with
8298 an error message -- NOT 404.
8299  
8300 =item Invalid partition
8301  
8302 C<1sales> (digit-start, 404), C<my.data> (dot, 404), C<my-data>
8303 (hyphen, 404), non-ASCII characters (404).
8304  
8305 =item Boundary values
8306  
8307 C<a> (single letter, valid), C<_> (single underscore, valid), C<1>
8308 (single digit, 404), C<a1> (letter then digit, valid), C<1a> (digit
8309 then letter, 404).
8310  
8311 =back
8312  
8313 =head4 OUTPUT
8314  
8315 On success renders C<dashboard.html.tt> with table data.
8316 On error re-renders C<home.html.tt> with an C<error> stash variable.
8317  
8318 =head3 MESSAGES
8319  
8320 error_table_open -- DataSource initialisation or fetch_all threw.
8321  
8322 =head3 FORMAL SPECIFICATION
8323  
8324 view == lambda self .
8325 pre self.stash('table') =~ TABLE_NAME_RE
8326 let src = open_table(table) in
8327 let records = src.fetch_all() in
8328 let cols = get_columns(src, records) in
8329 post render(dashboard, records: filter(records, f_params))
8330  
8331 =head3 EXAMPLE
8332  
8333 GET /view/sales -> 200 HTML table of all sales rows
8334 GET /view/sales?f=region:eq:North -> shows only North region rows
8335 GET /view/../etc -> 404
8336  
8337 =cut
8338  
8339 164 ▶sub view ($self) {
Subroutine view: called CC=16 SCAR=27.8
Pod documented
8340 164 my ($platform, $language) = $self->_resolve_template;
8341 164 my $table = $self->stash('table');
8342  
8343 164 ▶ unless (defined $table && $table =~ $TABLE_NAME_RE) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $table and $table =~ /$TABLE_NAME_RE/u) 5 159 164
Condition66%2/3
defined $table and $table =~ /$TABLE_NAME_RE/u
!ll&&!rl&&r
05159
MC/DC50%1/2
defined $table and $table =~ /$TABLE_NAME_RE/u
defined $table $table =~ /$TABLE_NAME_RE/u
Truth table66%2/3
A and B
A= defined $tableB= $table =~ /$TABLE_NAME_RE/u
ABresult
0X0
100
111
8344 5 return $self->reply->not_found;
8345 }
8346  
8347 159 my ($page, $per_page, $offset) = $self->_pagination;
8348  
8349 159 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 159 159
8350 159 my ($source, $records, $has_next, $is_multi);
8351 159 eval {
8352 159 ▶ $source = $self->_accelerated_source("table:$table") // $self->open_table($table);
Condition66%2/3
$self->_accelerated_source("table:$table") // $self->open_table($table)
l!l&&r!l&&!r
01581
MC/DC0%0/2
$self->_accelerated_source("table:$table") // $self->open_table($table)
$self->_accelerated_source("table:$table") $self->open_table($table)
Truth table33%1/3
A // B
A= $self->_accelerated_source("table:$table")B= $self->open_table($table)
ABresult
1X1
011
000
8353 # Multi-table SQLite: flag redirect without fetching data.
8354 158 ▶ if ($source && $source->sqlite_tables && @{ $source->sqlite_tables } > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($source and $source->sqlite_tables and @{$source->sqlite_tables;} > 1) { } 1 157 158
Condition83%5/6
$source and $source->sqlite_tables and @{$source->sqlite_tables;} > 1
!ll&&!rl&&r
15611
$source and $source->sqlite_tables
!ll&&!rl&&r
01562
MC/DC66%2/3
$source and $source->sqlite_tables and @{$source->sqlite_tables;} > 1
$source $source->sqlite_tables @{$source->sqlite_tables;} > 1
Truth table75%3/4
A and B and C
A= $sourceB= $source->sqlite_tablesC= @{$source->sqlite_tables;} > 1
ABCresult
0XX0
10X0
1100
1111
8355 1 $is_multi = 1;
8356 } else {
8357 # _fetch_page applies reduce-before-paginate: full-fetch + filter + dedup
8358 # + Perl paginate when f= or d=1 are set; N+1 trick otherwise.
8359 157 ($records, $has_next) = $self->_fetch_page($source,
8360 { per_page => $per_page, offset => $offset, dedup => $dedup,
8361 calc_spec_key => "table:$table" });
8362 }
8363 };
8364 159 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 7 152 159
8365 # No file by that name: a 404 that names the table, with the trail
8366 # and the navigation, rather than the home page and the backend's
8367 # message (which gives away the data directory).
8368 # A directory that may not be read has no file by that name to offer either.
8369 7 my $error = $@;
8370 7 ▶ my $stem_of = sub { lc($_[0]->basename =~ s/\.[^.]+\z//r) };
Subroutine __ANON__: called CC=1 SCAR=0.0
8371 7 my $listing = eval { _data_dir_for($self->app)->list };
8372 7 $@ = $error;
8373 7 ▶ unless ($listing && grep { $stem_of->($_) eq lc $table } $listing->each) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($listing and grep {&$stem_of($_) eq lc $table;} $listing->each) 4 3 7
Condition100%3/3
$listing and grep {&$stem_of($_) eq lc $table;} $listing->each
!ll&&!rl&&r
133
MC/DC100%2/2
$listing and grep {&$stem_of($_) eq lc $table;} $listing->each
$listing grep {&$stem_of($_) eq lc $table;} $listing->each
Truth table100%3/3
A and B
A= $listingB= grep {&$stem_of($_) eq lc $table;} $listing->each
ABresult
0X0
100
111
8374 4 return $self->render(
8375 template => "$platform/$language/not_found",
8376 handler => 'tt',
8377 format => 'html',
8378 status => 404,
8379 title => 'Table not found',
8380 error_msg => $self->_i18n('error_table_missing', $table),
8381 language => $language,
8382 );
8383 }
8384 3 return $self->render(
8385 template => "$platform/$language/home",
8386 handler => 'tt',
8387 format => 'html',
8388 tables => [],
8389 title => 'Choose a Database',
8390 error => $self->_i18n('error_table_open', $table, _tidy_error($@)),
8391 language => $language,
8392 );
8393 }
8394  
8395 152 ▶ if ($is_multi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_multi) 1 151 152
8396 1 return $self->redirect_to('/tables?l=' . url_escape("table:$table"));
8397 }
8398  
8399 # A cross-row spec that could not be honoured has already rendered its 400
8400 # inside _fetch_page; drawing the page over it would hide the reason.
8401 151 ▶ return if $self->stash('_cross_row_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_cross_row_error") 4 147 151
8402  
8403 147 ▶ $records //= [];
Condition50%1/2
$records //= []
l!l
1470
MC/DC0%0/1
$records //= []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
8404 # The page from _fetch_page is already reduced; this call is here for the chip
8405 # list only -- filter_specs (for export URLs) and filters_json (for the UI).
8406 147 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
8407  
8408 # Calculated fields belong to the table, not only to its charts. The table
8409 # action is addressed by :table rather than l=, so name the spec explicitly
8410 # when looking up the fields saved for it; otherwise a saved column would
8411 # appear in every chart and not in the table it was made from.
8412 147 my $page_columns;
8413 147 ($records, $page_columns) = $self->_page_columns($source, $records, "table:$table");
8414 147 ▶ return unless $page_columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $page_columns 2 145 147
8415 145 my @columns = @$page_columns;
8416  
8417 145 my $page_url = $self->req->url->clone;
8418 145 $page_url->query->remove('page')->remove('per_page');
8419 145 my $page_base_url = $page_url->to_string;
8420  
8421 145 ▶ $self->render(
Condition100%2/2
$self->param("back2_label") // "Back"
l!l
7138
MC/DC100%1/1
$self->param("back2_label") // "Back"
$self->param("back2_label")
Truth table100%2/2
A
A= $self->param("back2_label")
Aresult
11
00
8422 template => "$platform/$language/dashboard",
8423 handler => 'tt',
8424 format => 'html',
8425 records => $records,
8426 columns => \@columns,
8427 table => $table,
8428 title => ucfirst($table),
8429 left_spec => "table:$table",
8430 combine_specs => [ $self->_calc_specs_of_request ],
8431 current_joins => [],
8432 available_tables => $self->_scan_join_tables,
8433 join_summaries => [],
8434 filter_specs => $filter_specs,
8435 filters_json => $filters_json,
8436 dedup => $dedup,
8437 back_url => _safe_back_url($self->param('back2')),
8438 back_label => $self->param('back2_label') // 'Back',
8439 export_url => $self->_build_export_url("table:$table", [], $filter_specs, undef, $dedup, {
8440 span => $self->param('span'), tcol => $self->param('tcol'), as => $self->param('as'),
8441 }),
8442 page => $page,
8443 per_page => $per_page,
8444 has_next => $has_next,
8445 page_base_url => $page_base_url,
8446 language => $language,
8447 );
8448 }
8449  
8450 =head2 browse
8451  
8452 C<GET /browse> -- Navigate the filesystem and pick a data file.
8453  
8454 =head3 API SPECIFICATION
8455  
8456 =head4 INPUT
8457  
8458 ?path= string Absolute filesystem path to browse (default: $HOME).
8459 Returns 404 when the path does not exist or is not a
8460 directory.
8461  
8462 =head4 OUTPUT
8463  
8464 Renders C<browse.html.tt> with:
8465  
8466 current_path string
8467 parent_href string or undef (undef at filesystem root)
8468 crumbs ARRAYREF of { name, href }
8469 dirs ARRAYREF of { name, href } -- subdirectories, sorted
8470 files ARRAYREF of { name, path, href } -- supported data files, sorted
8471  
8472 With two or more files the page draws a checkbox for each, Select all, and a
8473 Combine selected button. Its script (no server round trip) opens
8474 C</combine?l=path:A&c=path:B&...&srccol=source_file&back2=/browse?path=DIR>.
8475  
8476 =head3 MESSAGES
8477  
8478 None; errors render as 404.
8479  
8480 =head3 FORMAL SPECIFICATION
8481  
8482 browse == lambda self .
8483 let dir = realpath(param('path') // first_root) in
8484 pre inside(dir, file_roots) /\ is_dir(dir)
8485 post render(browse, dirs: subdirs(dir), files: supported_files(dir))
8486  
8487 =head3 EXAMPLE
8488  
8489 GET /browse -> 200, lists $HOME
8490 GET /browse?path=/tmp -> 200, lists /tmp
8491 GET /browse?path=/nonexistent/xyz -> 404
8492  
8493 =cut
8494  
8495 53 ▶sub browse ($self) {
Subroutine browse: called CC=10 SCAR=23.6
Pod documented
8496 53 my ($platform, $language) = $self->_resolve_template;
8497  
8498 53 ▶ my $raw_path = $self->param('path') // _first_root($self);
Condition66%2/3
$self->param("path") // _first_root($self)
l!l&&r!l&&!r
9440
MC/DC0%0/2
$self->param("path") // _first_root($self)
$self->param("path") _first_root($self)
Truth table66%2/3
A // B
A= $self->param("path")B= _first_root($self)
ABresult
1X1
011
000
8499 53 ▶ if (my $refusal = _outside_roots($self, $raw_path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $refusal = _outside_roots($self, $raw_path)) 0 53 53
8500 0 return $self->render(text => $refusal, status => 403);
8501 }
8502 53 my $dir = eval { Mojo::File->new($raw_path)->realpath };
8503 53 ▶ return $self->reply->not_found unless defined $dir && -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir and -d $dir 1 52 53
Condition66%2/3
defined $dir and -d $dir
!ll&&!rl&&r
1052
MC/DC50%1/2
defined $dir and -d $dir
defined $dir -d $dir
Truth table66%2/3
A and B
A= defined $dirB= -d $dir
ABresult
0X0
100
111
8504  
8505 52 my $listing = $self->_list_dir($dir, 1);
8506  
8507 # Add browse hrefs to file entries (dirs already have path; browse needs href).
8508 my @dirs = map {
8509 60 +{ name => $_->{name}, href => '/browse?path=' . url_escape($_->{path}) }
8510 52 } @{ $listing->{dirs} };
8511  
8512 my @files = map {
8513 19 +{ name => $_->{name}, path => $_->{path}, href => '/open?path=' . url_escape($_->{path}) }
8514 52 } @{ $listing->{files} };
8515  
8516 # Build breadcrumb trail from filesystem root down to $dir.
8517 52 my @crumbs;
8518 {
8519 52 my $f = $dir;
8520 52 while (1) {
8521 168 my $name = $f->basename;
8522 168 ▶ $name = '/' unless length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless length $name 0 168 168
8523 168 unshift @crumbs, { name => $name, href => '/browse?path=' . url_escape($f->to_string) };
8524 168 my $parent = $f->dirname;
8525 168 ▶ last if $parent->to_string eq $f->to_string;
Branch: 1 branch
BranchTrueFalseTotal
if $parent->to_string eq $f->to_string 52 116 168
8526 116 ▶ last if _outside_roots($self, $parent->to_string);
Branch: 1 branch
BranchTrueFalseTotal
if _outside_roots($self, $parent->to_string) 0 116 116
8527 116 $f = $parent;
8528 }
8529 }
8530  
8531 52 my $parent = $dir->dirname;
8532 52 ▶ my $parent_href = $parent->to_string ne $dir->to_string && !_outside_roots($self, $parent->to_string)
Branch: 1 branch
BranchTrueFalseTotal
$parent->to_string ne $dir->to_string && !_outside_roots($self, $parent->to_string) ? : 52 0 52
Condition33%1/3
$parent->to_string ne $dir->to_string and not _outside_roots($self, $parent->to_string)
!ll&&!rl&&r
0052
MC/DC0%0/2
$parent->to_string ne $dir->to_string and not _outside_roots($self, $parent->to_string)
$parent->to_string ne $dir->to_string not _outside_roots($self, $parent->to_string)
Truth table33%1/3
A and not(B)
A= $parent->to_string ne $dir->to_stringB= not _outside_roots($self, $parent->to_string)
ABresult
0X0
100
111
8533 ? '/browse?path=' . url_escape($parent->to_string)
8534 : undef;
8535  
8536 52 $self->render(
8537 template => "$platform/$language/browse",
8538 handler => 'tt',
8539 format => 'html',
8540 title => 'Browse Files',
8541 current_path => $dir->to_string,
8542 parent_href => $parent_href,
8543 crumbs => \@crumbs,
8544 dirs => \@dirs,
8545 files => \@files,
8546 language => $language,
8547 );
8548 }
8549  
8550 =head2 open_file
8551  
8552 C<GET /open> -- Open a supported data file from any absolute filesystem path.
8553  
8554 =head3 API SPECIFICATION
8555  
8556 =head4 INPUT
8557  
8558 ?path= string Absolute path to the data file. Returns 404 when missing,
8559 not a regular file, or the extension is not in SUPPORTED_EXT.
8560 ?f= string (repeatable) Filter spec: "col:op:val".
8561  
8562 =head4 DOMAIN CONSTRAINTS: ?path=
8563  
8564 =over 4
8565  
8566 =item Extension filter (C<EXT_RE>)
8567  
8568 The basename must match C<\.(?:csv|db|sql|xml|tsv|psv)\z> (case-insensitive).
8569 The C<\z> anchor (absolute end-of-string) means a URL-encoded trailing
8570 newline (e.g. C<file.csv%0A> decoded to C<file.csv\n>) does NOT pass --
8571 the C<\n> falls after the C<\z> boundary and the extension check fails.
8572  
8573 =item Valid partition
8574  
8575 C</data/sales.csv> (lowercase extension), C</tmp/REPORT.CSV> (uppercase
8576 extension, /i matches), any C<.db>, C<.sql>, C<.xml>, C<.tsv>, C<.psv> regular
8577 file.
8578  
8579 =item Invalid partition
8580  
8581 Absent C<?path=> (404), non-existent file (404), directory instead of
8582 file (404), unsupported extension such as C<.txt> (404), empty string
8583 (404), path containing a C<%0A> (newline) suffix (404).
8584  
8585 =item Double-extension filenames
8586  
8587 A file like C<file.php.csv> passes C<EXT_RE> (last segment is C<.csv>)
8588 but produces table stem C<file.php> which fails C<DataSource>'s
8589 C<TABLE_NAME_RE>. The C<open_table> call is inside C<eval>, so the
8590 croak is caught and the action returns 200 with a friendly error, not
8591 a 500.
8592  
8593 =back
8594  
8595 =head4 OUTPUT
8596  
8597 On success renders C<dashboard.html.tt> with C<back_url> pointing to the
8598 directory's C</browse> page, and C<file_path> set to the resolved absolute
8599 path (used by the template to record the file in C<localStorage>).
8600 On error re-renders C<home.html.tt> with C<error>, C<back_url>, C<back_label>.
8601  
8602 =head3 MESSAGES
8603  
8604 error_file_open -- DataSource threw during initialisation or fetch_all.
8605  
8606 =head3 FORMAL SPECIFICATION
8607  
8608 open_file == lambda self .
8609 let file = realpath(param('path')) in
8610 pre is_file(file) /\ basename(file) =~ EXT_RE
8611 let src = open_table(stem(file), dir=dirname(file)) in
8612 post render(dashboard, file_path: file.to_string)
8613  
8614 =head3 EXAMPLE
8615  
8616 GET /open?path=/data/archive/sales.csv -> 200, table view
8617 GET /open -> 404
8618 GET /open?path=/etc/passwd -> 404
8619  
8620 =cut
8621  
8622 150 ▶sub open_file ($self) {
Subroutine open_file: called CC=62 SCAR=52.4
Pod documented
8623 150 my ($platform, $language) = $self->_resolve_template;
8624 150 my $file_path = $self->param('path');
8625  
8626 150 ▶ return $self->reply->not_found unless defined $file_path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_path 44 106 150
8627  
8628 106 my ($page, $per_page, $offset) = $self->_pagination;
8629  
8630 # Bare redis:// URL (no table name) -- redirect to key-listing page.
8631 106 ▶ if ($file_path =~ $REDIS_URL_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file_path =~ /$REDIS_URL_RE/u) 0 106 106
8632 0 return $self->redirect_to('/tables?l=' . url_escape($file_path));
8633 }
8634  
8635 # A MariaDB server with no table named: list its tables.
8636 106 ▶ if ($file_path =~ $MARIADB_SERVER_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file_path =~ /$MARIADB_SERVER_RE/u) 0 106 106
8637 0 return $self->redirect_to('/tables?l=' . url_escape($file_path));
8638 }
8639  
8640 # Redis spec: redis:tablename|redis://host:port -- delegate to _open_spec.
8641 # MariaDB spec: mariadb:server/table -- likewise.
8642 106 ▶ if ($file_path =~ $REDIS_SPEC_RE || $file_path =~ $MARIADB_SPEC_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file_path =~ /$REDIS_SPEC_RE/u or $file_path =~ /$MARIADB_SPEC_RE/u) 0 106 106
Condition33%1/3
$file_path =~ /$REDIS_SPEC_RE/u or $file_path =~ /$MARIADB_SPEC_RE/u
l!l&&r!l&&!r
00106
MC/DC0%0/2
$file_path =~ /$REDIS_SPEC_RE/u or $file_path =~ /$MARIADB_SPEC_RE/u
$file_path =~ /$REDIS_SPEC_RE/u $file_path =~ /$MARIADB_SPEC_RE/u
Truth table33%1/3
A or B
A= $file_path =~ /$REDIS_SPEC_RE/uB= $file_path =~ /$MARIADB_SPEC_RE/u
ABresult
1X1
011
000
8643 0 my $lspec = $file_path;
8644 0 my ($source, $label) = $self->_open_spec($lspec);
8645 0 ▶ unless ($source) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($source) 0 0 0
8646 0 my $why = $self->stash('open_spec_error');
8647 0 ▶ return $self->reply->not_found unless defined $why;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $why 0 0 0
8648 0 return $self->render(
8649 template => "$platform/$language/home",
8650 handler => 'tt',
8651 format => 'html',
8652 tables => [],
8653 title => 'Error',
8654 error => $self->_i18n('error_file_open', $lspec, $why),
8655 back_url => '/',
8656 back_label => 'Home',
8657 language => $language,
8658 );
8659 }
8660 0 my $table = $label;
8661 0 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 0 0
8662 0 my ($records, $has_next);
8663 0 eval {
8664 0 ($records, $has_next) = $self->_fetch_page($source,
8665 { per_page => $per_page, offset => $offset, dedup => $dedup, calc_spec_key => $lspec });
8666 };
8667 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
8668 0 return $self->render(
8669 template => "$platform/$language/home",
8670 handler => 'tt',
8671 format => 'html',
8672 tables => [],
8673 title => 'Error',
8674 error => $self->_i18n('error_file_open', $label, _tidy_error($@)),
8675 back_url => '/',
8676 back_label => 'Home',
8677 language => $language,
8678 );
8679 }
8680 # A cross-row spec that could not be honoured has already rendered its 400
8681 # inside _fetch_page; the page must not be drawn over it.
8682 0 ▶ return if $self->stash('_cross_row_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_cross_row_error") 0 0 0
8683  
8684 0 ▶ $records //= [];
Condition0%0/2
$records //= []
l!l
00
MC/DC0%0/1
$records //= []
$records
Truth table0%0/2
A
A= $records
Aresult
11
00
8685 0 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
8686 0 my $page_columns;
8687 0 ($records, $page_columns) = $self->_page_columns($source, $records, $lspec);
8688 0 ▶ return unless $page_columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $page_columns 0 0 0
8689 0 my @columns = @$page_columns;
8690 0 my $rpage_url = $self->req->url->clone;
8691 0 $rpage_url->query->remove('page')->remove('per_page');
8692 0 ▶ return $self->render(
Condition0%0/6
_safe_back_url($self->param("back")) // "/"
l!l
00
$self->param("back_label") // "Home"
l!l
00
$self->param("back2_label") // "Back"
l!l
00
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
MC/DC0%0/1
$self->param("back_label") // "Home"
$self->param("back_label")
MC/DC0%0/1
$self->param("back2_label") // "Back"
$self->param("back2_label")
Truth table0%0/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
Truth table0%0/2
A
A= $self->param("back_label")
Aresult
11
00
Truth table0%0/2
A
A= $self->param("back2_label")
Aresult
11
00
8693 template => "$platform/$language/dashboard",
8694 handler => 'tt',
8695 format => 'html',
8696 records => $records,
8697 columns => \@columns,
8698 table => $table,
8699 title => $label,
8700 back_url => _safe_back_url($self->param('back')) // '/',
8701 back_label => $self->param('back_label') // 'Home',
8702 back2_url => _safe_back_url($self->param('back2')),
8703 back2_label => $self->param('back2_label') // 'Back',
8704 file_path => $file_path,
8705 left_spec => $lspec,
8706 combine_specs => [ $self->_calc_specs_of_request ],
8707 current_joins => [],
8708 available_tables => $self->_scan_join_tables,
8709 join_summaries => [],
8710 filter_specs => $filter_specs,
8711 filters_json => $filters_json,
8712 dedup => $dedup,
8713 export_url => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
8714 page => $page,
8715 per_page => $per_page,
8716 has_next => $has_next,
8717 page_base_url => $rpage_url->to_string,
8718 language => $language,
8719 );
8720 }
8721  
8722 # Remote path /../hostname/dir/file.ext: delegate opening to _open_spec
8723 # and render the dashboard directly, bypassing the realpath/local-file path.
8724 106 ▶ if ($file_path =~ m{\A/\.\./}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file_path =~ m[\A/\.\./]u) 7 99 106
8725 7 my $lspec = 'path:' . $file_path;
8726 7 my ($source, $label) = $self->_open_spec($lspec);
8727 7 ▶ return $self->reply->not_found unless $source;
Branch: 1 branch
BranchTrueFalseTotal
unless $source 4 3 7
8728 3 my $filename = $label;
8729 3 (my $table = $filename) =~ s/\.[^.]+\z//;
8730 3 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 3 3
8731 3 my ($records, $has_next);
8732 3 eval {
8733 3 ($records, $has_next) = $self->_fetch_page($source,
8734 { per_page => $per_page, offset => $offset, dedup => $dedup, calc_spec_key => $lspec });
8735 };
8736 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3 3
8737 0 return $self->render(
8738 template => "$platform/$language/home",
8739 handler => 'tt',
8740 format => 'html',
8741 tables => [],
8742 title => 'Error',
8743 error => $self->_i18n('error_file_open', $filename, _tidy_error($@)),
8744 back_url => '/',
8745 back_label => 'Home',
8746 language => $language,
8747 );
8748 }
8749 # A cross-row spec that could not be honoured has already rendered its 400
8750 # inside _fetch_page; the page must not be drawn over it.
8751 3 ▶ return if $self->stash('_cross_row_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_cross_row_error") 0 3 3
8752  
8753 3 ▶ $records //= [];
Condition50%1/2
$records //= []
l!l
30
MC/DC0%0/1
$records //= []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
8754 3 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
8755 3 my $page_columns;
8756 3 ($records, $page_columns) = $self->_page_columns($source, $records, $lspec);
8757 3 ▶ return unless $page_columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $page_columns 0 3 3
8758 3 my @columns = @$page_columns;
8759 3 my $rpage_url = $self->req->url->clone;
8760 3 $rpage_url->query->remove('page')->remove('per_page');
8761 3 ▶ return $self->render(
Condition50%1/2
$self->param("back2_label") // "Back"
l!l
03
MC/DC0%0/1
$self->param("back2_label") // "Back"
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
8762 template => "$platform/$language/dashboard",
8763 handler => 'tt',
8764 format => 'html',
8765 records => $records,
8766 columns => \@columns,
8767 table => $table,
8768 title => $filename,
8769 back_url => '/',
8770 back_label => 'Home',
8771 back2_url => _safe_back_url($self->param('back2')),
8772 back2_label => $self->param('back2_label') // 'Back',
8773 file_path => $file_path,
8774 left_spec => $lspec,
8775 combine_specs => [ $self->_calc_specs_of_request ],
8776 current_joins => [],
8777 available_tables => $self->_scan_join_tables,
8778 join_summaries => [],
8779 filter_specs => $filter_specs,
8780 filters_json => $filters_json,
8781 dedup => $dedup,
8782 export_url => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
8783 page => $page,
8784 per_page => $per_page,
8785 has_next => $has_next,
8786 page_base_url => $rpage_url->to_string,
8787 language => $language,
8788 );
8789 }
8790  
8791 # A path that names a table after a "#", as a spec does, is that table.
8792 99 my ($named_file, $named_it) = _split_path($file_path);
8793 99 ▶ $file_path = $named_file if defined $named_it;
Branch: 1 branch
BranchTrueFalseTotal
if defined $named_it 0 99 99
8794 99 ▶ if (my $refusal = _outside_roots($self, $file_path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $refusal = _outside_roots($self, $file_path)) 0 99 99
8795 0 return $self->render(text => $refusal, status => 403);
8796 }
8797  
8798 99 my $file = eval { Mojo::File->new($file_path)->realpath };
8799 return $self->reply->not_found
8800 10 ▶ unless defined $file && CORE::index($file, "\0") < 0 && do { no warnings 'newline'; -f $file } && $file->basename =~ $EXT_RE;
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file and CORE::index($file, "\0") == -1 and do { BEGIN {${^WARNING_BITS} = "\x55\x55\x51\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} -f $file } and $file->basename =~ /$EXT_RE/u 17 82 99
Condition88%8/9
defined $file and CORE::index($file, "\0") == -1 and do { BEGIN {${^WARNING_BITS} = "\x55\x55\x51\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} -f $file } and $file->basename =~ /$EXT_RE/u
!ll&&!rl&&r
11682
defined $file and CORE::index($file, "\0") == -1 and do { BEGIN {${^WARNING_BITS} = "\x55\x55\x51\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} -f $file }
!ll&&!rl&&r
5688
defined $file and CORE::index($file, "\0") == -1
!ll&&!rl&&r
5094
MC/DC75%3/4
defined $file and CORE::index($file, "\0") == -1 and do { BEGIN {${^WARNING_BITS} = "\x55\x55\x51\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} -f $file } and $file->basename =~ /$EXT_RE/u
defined $file CORE::index($file, "\0") == -1 do { BEGIN {${^WARNING_BITS} = "\x55\x55\x51\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} -f $file } $file->basename =~ /$EXT_RE/u
Truth table80%4/5
A and B and C and D
A= defined $fileB= CORE::index($file, "\0") == -1C= do { BEGIN {${^WARNING_BITS} = "\x55\x55\x51\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} -f $file }D= $file->basename =~ /$EXT_RE/u
ABCDresult
0XXX0
10XX0
110X0
11100
11111
8801  
8802 82 my $dir = $file->dirname;
8803 82 (my $table = $file->basename) =~ s/\.[^.]+\z//;
8804 82 my $back = '/browse?path=' . url_escape($dir->to_string);
8805 82 my $filename = $file->basename;
8806 82 my $lspec = 'path:' . $file->to_string;
8807  
8808 82 ▶ my $it = $self->param('it') // $named_it; # optional: select a specific internal table
Condition66%2/3
$self->param("it") // $named_it
l!l&&r!l&&!r
1081
MC/DC50%1/2
$self->param("it") // $named_it
$self->param("it") $named_it
Truth table66%2/3
A // B
A= $self->param("it")B= $named_it
ABresult
1X1
011
000
8809  
8810 # A table opened from the schema browser belongs to a file in data_dir. Name
8811 # it as table:store/sales so the join, filter and export panels keep the
8812 # chosen internal table instead of dropping back to the file's first table.
8813 82 ▶ if (defined $it && $it =~ $TABLE_NAME_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $it and $it =~ /$TABLE_NAME_RE/u) 1 81 82
Condition66%2/3
defined $it and $it =~ /$TABLE_NAME_RE/u
!ll&&!rl&&r
8101
MC/DC50%1/2
defined $it and $it =~ /$TABLE_NAME_RE/u
defined $it $it =~ /$TABLE_NAME_RE/u
Truth table66%2/3
A and B
A= defined $itB= $it =~ /$TABLE_NAME_RE/u
ABresult
0X0
100
111
8814 1 my $data_dir = eval { _data_dir_for($self->app)->realpath };
8815 1 my $file_dir = eval { $file->dirname->realpath };
8816 1 ▶ $lspec = "table:$table/$it" if $data_dir && $file_dir && "$file_dir" eq "$data_dir";
Branch: 1 branch
BranchTrueFalseTotal
if $data_dir and $file_dir and "$file_dir" eq "$data_dir" 0 1 1
Condition33%2/6
$data_dir and $file_dir and "$file_dir" eq "$data_dir"
!ll&&!rl&&r
010
$data_dir and $file_dir
!ll&&!rl&&r
001
MC/DC0%0/3
$data_dir and $file_dir and "$file_dir" eq "$data_dir"
$data_dir $file_dir "$file_dir" eq "$data_dir"
Truth table25%1/4
A and B and C
A= $data_dirB= $file_dirC= "$file_dir" eq "$data_dir"
ABCresult
0XX0
10X0
1100
1111
8817 }
8818 # Elsewhere the spec names the table after a "#", so the panels and charts
8819 # keep it too.
8820 82 ▶ $lspec .= "#$it" if defined $it && length $it && $it !~ /[#\n]/ && $lspec =~ /\Apath:/;
Branch: 1 branch
BranchTrueFalseTotal
if defined $it and length $it and not $it =~ /[#\n]/u and $lspec =~ /\Apath:/u 1 81 82
Condition66%6/9
defined $it and length $it and not $it =~ /[#\n]/u and $lspec =~ /\Apath:/u
!ll&&!rl&&r
8101
defined $it and length $it and not $it =~ /[#\n]/u
!ll&&!rl&&r
8101
defined $it and length $it
!ll&&!rl&&r
8101
MC/DC25%1/4
defined $it and length $it and not $it =~ /[#\n]/u and $lspec =~ /\Apath:/u
defined $it length $it not $it =~ /[#\n]/u $lspec =~ /\Apath:/u
Truth table40%2/5
A and B and not(C) and D
A= defined $itB= length $itC= not $it =~ /[#\n]/uD= $lspec =~ /\Apath:/u
ABCDresult
0XXX0
10XX0
110X0
11100
11111
8821  
8822 # Allow the tables view to override the default "Back to browser" link.
8823 82 my $back_override = _safe_back_url($self->param('back'));
8824 82 ▶ if ($back_override) {
Branch: 1 branch
BranchTrueFalseTotal
if ($back_override) 1 81 82
8825 1 $back = $back_override;
8826 }
8827 82 ▶ my $back_label_default = $back_override ? ($self->param('back_label') // 'Back') : 'Back to browser';
Branch: 1 branch
BranchTrueFalseTotal
$back_override ? : 1 81 82
Condition50%1/2
$self->param("back_label") // "Back"
l!l
10
MC/DC0%0/1
$self->param("back_label") // "Back"
$self->param("back_label")
Truth table50%1/2
A
A= $self->param("back_label")
Aresult
11
00
8828  
8829 82 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 1 81 82
8830 82 my ($source, $records, $has_next, $is_multi_local);
8831 82 eval {
8832 82 ▶ $source = (defined $it ? undef : $self->_accelerated_source($lspec))
Branch: 2 branches
BranchTrueFalseTotal
defined $it ? : 1 81 82
defined $it ? : 1 81 82
Condition66%2/3
(defined $it ? undef : $self->_accelerated_source($lspec)) // $self->open_table($table, "directory", $dir->to_string, defined $it ? ("internal_table", $it) : ())
l!l&&r!l&&!r
0811
MC/DC0%0/2
(defined $it ? undef : $self->_accelerated_source($lspec)) // $self->open_table($table, "directory", $dir->to_string, defined $it ? ("internal_table", $it) : ())
(defined $it ? undef : $self->_accelerated_source($lspec)) $self->open_table($table, "directory", $dir->to_string, defined $it ? ("internal_table", $it) : ())
Truth table33%1/3
A // B
A= (defined $it ? undef : $self->_accelerated_source($lspec))B= $self->open_table($table, "directory", $dir->to_string, defined $it ? ("internal_table", $it) : ())
ABresult
1X1
011
000
8833 // $self->open_table($table, directory => $dir->to_string,
8834 defined $it ? (internal_table => $it) : ());
8835 # Multi-table SQLite without it=: flag redirect without fetching data.
8836 79 ▶ if (!defined $it && $source && $source->sqlite_tables
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $it and $source and $source->sqlite_tables and @{$source->sqlite_tables;} > 1) { } 1 78 79
Condition88%8/9
not defined $it and $source and $source->sqlite_tables and @{$source->sqlite_tables;} > 1
!ll&&!rl&&r
62161
not defined $it and $source and $source->sqlite_tables
!ll&&!rl&&r
16117
not defined $it and $source
!ll&&!rl&&r
1078
MC/DC75%3/4
not defined $it and $source and $source->sqlite_tables and @{$source->sqlite_tables;} > 1
not defined $it $source $source->sqlite_tables @{$source->sqlite_tables;} > 1
Truth table80%4/5
not(A) and B and C and D
A= not defined $itB= $sourceC= $source->sqlite_tablesD= @{$source->sqlite_tables;} > 1
ABCDresult
0XXX0
10XX0
110X0
11100
11111
8837 17 && @{ $source->sqlite_tables } > 1) {
8838 1 $is_multi_local = 1;
8839 } else {
8840 78 ($records, $has_next) = $self->_fetch_page($source,
8841 { per_page => $per_page, offset => $offset, dedup => $dedup, calc_spec_key => $lspec });
8842 }
8843 };
8844 82 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 8 74 82
8845 # Provide a SQLite-specific hint when the error looks like a table-name
8846 # mismatch or a missing-tables failure so the user knows what to do. A
8847 # table whose name cannot be used has its own advice in the message.
8848 8 my $hint;
8849 8 ▶ if ($filename =~ /\.(?:sql|sqlite|sqlite3|db)\z/i && $@ !~ /cannot be opened|can be opened/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filename =~ /\.(?:sql|sqlite|sqlite3|db)\z/iu and not $@ =~ /cannot be opened|can be opened/u) 1 7 8
Condition66%2/3
$filename =~ /\.(?:sql|sqlite|sqlite3|db)\z/iu and not $@ =~ /cannot be opened|can be opened/u
!ll&&!rl&&r
701
MC/DC50%1/2
$filename =~ /\.(?:sql|sqlite|sqlite3|db)\z/iu and not $@ =~ /cannot be opened|can be opened/u
$filename =~ /\.(?:sql|sqlite|sqlite3|db)\z/iu not $@ =~ /cannot be opened|can be opened/u
Truth table66%2/3
A and not(B)
A= $filename =~ /\.(?:sql|sqlite|sqlite3|db)\z/iuB= not $@ =~ /cannot be opened|can be opened/u
ABresult
0X0
100
111
8850 1 $hint = 'SQLite files must contain at least one user-defined table. '
8851 . 'The table name inside the database does not need to match the '
8852 . 'filename -- the application auto-detects and uses the first table it can open.';
8853 }
8854 8 ▶ return $self->render(
Condition50%1/2
$self->param("back2_label") // "Back"
l!l
08
MC/DC0%0/1
$self->param("back2_label") // "Back"
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
8855 template => "$platform/$language/home",
8856 handler => 'tt',
8857 format => 'html',
8858 tables => [],
8859 title => 'Error',
8860 error => $self->_i18n('error_file_open', $filename, _tidy_error($@)),
8861 hint => $hint,
8862 back_url => $back,
8863 back_label => $back_label_default,
8864 back2_url => _safe_back_url($self->param('back2')),
8865 back2_label => $self->param('back2_label') // 'Back',
8866 language => $language,
8867 );
8868 }
8869  
8870 74 ▶ if ($is_multi_local) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_multi_local) 1 73 74
8871 1 return $self->redirect_to('/tables?l=' . url_escape("path:${\$file->to_string}"));
8872 }
8873  
8874 # A cross-row spec that could not be honoured has already rendered its 400
8875 # inside _fetch_page; the page must not be drawn over it.
8876 73 ▶ return if $self->stash('_cross_row_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_cross_row_error") 0 73 73
8877  
8878 73 ▶ $records //= [];
Condition50%1/2
$records //= []
l!l
730
MC/DC0%0/1
$records //= []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
8879 73 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
8880 73 my $page_columns;
8881 73 ($records, $page_columns) = $self->_page_columns($source, $records, $lspec);
8882 73 ▶ return unless $page_columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $page_columns 0 73 73
8883 73 my @columns = @$page_columns;
8884  
8885 73 my $lpage_url = $self->req->url->clone;
8886 73 $lpage_url->query->remove('page')->remove('per_page');
8887  
8888 73 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
defined $it ? : 1 72 73
defined $it ? : 1 72 73
Condition100%2/2
$self->param("back2_label") // "Back"
l!l
370
MC/DC100%1/1
$self->param("back2_label") // "Back"
$self->param("back2_label")
Truth table100%2/2
A
A= $self->param("back2_label")
Aresult
11
00
8889 template => "$platform/$language/dashboard",
8890 handler => 'tt',
8891 format => 'html',
8892 records => $records,
8893 columns => \@columns,
8894 table => defined $it ? $it : $table,
8895 title => defined $it ? "$filename ($it)" : $filename,
8896 back_url => $back,
8897 back_label => $back_label_default,
8898 back2_url => _safe_back_url($self->param('back2')),
8899 back2_label => $self->param('back2_label') // 'Back',
8900 file_path => $file->to_string,
8901 left_spec => $lspec,
8902 combine_specs => [ $self->_calc_specs_of_request ],
8903 current_joins => [],
8904 available_tables => $self->_scan_join_tables,
8905 join_summaries => [],
8906 filter_specs => $filter_specs,
8907 filters_json => $filters_json,
8908 dedup => $dedup,
8909 export_url => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
8910 page => $page,
8911 per_page => $per_page,
8912 has_next => $has_next,
8913 page_base_url => $lpage_url->to_string,
8914 language => $language,
8915 );
8916 }
8917  
8918 =head2 import_url
8919  
8920 C<GET /import> -- Fetch a remote HTML page, extract the first (or selected)
8921 table, and render it as a sortable data grid.
8922  
8923 =head3 API SPECIFICATION
8924  
8925 =head4 INPUT
8926  
8927 ?url= string Required. Full http:// or https:// URL of the page
8928 that contains the HTML table. Returns home with an
8929 error message if the scheme is wrong, the fetch fails,
8930 or no table is found at the specified index.
8931 ?table_index= integer Zero-based index of the C<< <table> >> to use when
8932 the page contains more than one table (default: 0).
8933 ?f= string (repeatable) Filter spec: "col:op:val".
8934  
8935 =head4 OUTPUT
8936  
8937 On success renders C<dashboard.html.tt> with the same stash shape as C<open_file>,
8938 plus C<source_url> (the original URL) for C<localStorage> tracking.
8939  
8940 On error re-renders C<home.html.tt> with an C<error> stash variable.
8941  
8942 =head3 MESSAGES
8943  
8944 error_url_required -- empty or missing C<url> param
8945 error_url_invalid -- URL does not begin with http:// or https://
8946 error_url_fetch -- LWP fetch failure or no table found at the index
8947  
8948 =head3 EXAMPLE
8949  
8950 GET /import?url=https://matrix.perl-magpie.org/dist/Database-Abstraction/
8951 GET /import?url=https://example.com/data.html&table_index=2
8952  
8953 =cut
8954  
8955 90 ▶sub import_url ($self) {
Subroutine import_url: called CC=12 SCAR=25.0
Pod documented
8956 90 my ($platform, $language) = $self->_resolve_template;
8957  
8958 90 ▶ my $url = $self->param('url') // '';
Condition100%2/2
$self->param("url") // ""
l!l
4248
MC/DC100%1/1
$self->param("url") // ""
$self->param("url")
Truth table100%2/2
A
A= $self->param("url")
Aresult
11
00
8959 90 ▶ my $idx = $self->param('table_index') // 0;
Condition50%1/2
$self->param("table_index") // 0
l!l
090
MC/DC0%0/1
$self->param("table_index") // 0
$self->param("table_index")
Truth table50%1/2
A
A= $self->param("table_index")
Aresult
11
00
8960 90 ▶ $idx = 0 unless $idx =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $idx =~ /\A[0-9]+\z/u 0 90 90
8961  
8962 87 ▶ my $err_home = sub ($key, @args) {
Subroutine __ANON__: called CC=1 SCAR=0.0
8963 87 $self->render(
8964 template => "$platform/$language/home",
8965 handler => 'tt',
8966 format => 'html',
8967 tables => $self->_scan_data_dir,
8968 title => 'Choose a Database',
8969 error => $self->_i18n($key, @args),
8970 language => $language,
8971 );
8972 90 };
8973  
8974 90 ▶ return $err_home->('error_url_required') unless length $url;
Branch: 1 branch
BranchTrueFalseTotal
unless length $url 48 42 90
8975 42 ▶ return $err_home->('error_url_invalid', $url)
Branch: 1 branch
BranchTrueFalseTotal
unless $url =~ m[\Ahttps?://]iu 4 38 42
8976 unless $url =~ m{\Ahttps?://}i;
8977 38 ▶ return $err_home->('error_url_ssrf', $url)
Branch: 1 branch
BranchTrueFalseTotal
unless _is_safe_url($url) 10 28 38
8978 unless _is_safe_url($url);
8979  
8980 28 my ($source, $records);
8981 28 my $ok = eval {
8982 28 $source = $self->open_table('', url => $url, html_table_index => $idx);
8983 26 $records = $source->fetch_all;
8984 3 1;
8985 };
8986 28 ▶ return $err_home->('error_url_fetch', $url, _tidy_error($@)) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 25 3 28
8987  
8988 3 my $label = $source->table_name;
8989 3 my $lspec = "url:$url";
8990 3 my @columns = _get_columns($source, $records);
8991 3 my ($filtered, $filter_specs, $filters_json) = $self->_apply_filters($records);
8992 3 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 3 3
8993 3 ▶ $filtered = _dedup_records($filtered, \@columns) if $dedup;
Branch: 1 branch
BranchTrueFalseTotal
if $dedup 0 3 3
8994  
8995 3 my $self_url = '/import?url=' . url_escape($url);
8996 3 ▶ $self_url .= '&table_index=' . $idx if $idx;
Branch: 1 branch
BranchTrueFalseTotal
if $idx 0 3 3
8997  
8998 3 ▶ $self->render(
Condition100%2/2
$self->param("back2_label") // "Back"
l!l
12
MC/DC100%1/1
$self->param("back2_label") // "Back"
$self->param("back2_label")
Truth table100%2/2
A
A= $self->param("back2_label")
Aresult
11
00
8999 template => "$platform/$language/dashboard",
9000 handler => 'tt',
9001 format => 'html',
9002 records => $filtered,
9003 columns => \@columns,
9004 table => $label,
9005 title => $label,
9006 source_url => $url,
9007 back_url => $self_url,
9008 back_label => $label,
9009 back2_url => _safe_back_url($self->param('back2')),
9010 back2_label => $self->param('back2_label') // 'Back',
9011 left_spec => $lspec,
9012 combine_specs => [],
9013 current_joins => [],
9014 available_tables => $self->_scan_join_tables,
9015 join_summaries => [],
9016 filter_specs => $filter_specs,
9017 filters_json => $filters_json,
9018 dedup => $dedup,
9019 export_url => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
9020 language => $language,
9021 );
9022 }
9023  
9024 =head2 columns_api
9025  
9026 C<GET /api/columns> -- Return column names for a table or file as JSON.
9027  
9028 Used by the join UI to populate the right-key dropdown without a page reload.
9029  
9030 =head3 API SPECIFICATION
9031  
9032 =head4 INPUT
9033  
9034 ?table= string Table name from C<data_dir>, or C<file/table> for a table
9035 inside a multi-table SQLite file.
9036 ?path= string Absolute path to a data file.
9037 ?spec= string Unified spec: C<"table:name">, C<"table:file/table"> or
9038 C<"path:/abs/path">.
9039 Parsed only when C<table> and C<path> are both absent.
9040  
9041 One of C<table>, C<path>, or C<spec> must be present; C<table> takes
9042 precedence over C<path>, and both take precedence over C<spec>.
9043  
9044 =head4 OUTPUT
9045  
9046 200 application/json { "columns": ["col1", "col2", ...] }
9047 404 application/json { "error": "not found" }
9048  
9049 =head3 MESSAGES
9050  
9051 None produced by this action directly; internal errors yield a 404.
9052  
9053 =head3 FORMAL SPECIFICATION
9054  
9055 columns_api == lambda self .
9056 let src = open_spec(table_param or path_param or parse_spec(spec_param)) in
9057 pre src /= undef
9058 post render_json({ columns: get_columns(src) })
9059  
9060 =head3 EXAMPLE
9061  
9062 GET /api/columns?table=sales -> {"columns":["product","region","amount"]}
9063 GET /api/columns?table=store/customer -> {"columns":["id","name","email"]}
9064 GET /api/columns?spec=table:sales -> {"columns":["product","region","amount"]}
9065 GET /api/columns?spec=path:/data/f.csv -> {"columns":[...]}
9066 GET /api/columns?table=noexist -> 404
9067  
9068 =cut
9069  
9070 63 ▶sub columns_api ($self) {
Subroutine columns_api: called CC=28 SCAR=34.8
Pod documented
9071 63 my $table_name = $self->param('table');
9072 63 my $path = $self->param('path');
9073 63 my $path_internal;
9074  
9075 # Accept the unified spec format used by /join and /graph:
9076 # "table:name" or "path:/abs/path" -- mirrors _open_spec's parsing.
9077 63 ▶ if (!defined($table_name) && !defined($path)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $table_name or defined $path) 46 17 63
Condition100%3/3
defined $table_name or defined $path
l!l&&r!l&&!r
13446
MC/DC100%2/2
defined $table_name or defined $path
defined $table_name defined $path
Truth table100%3/3
A or B
A= defined $table_nameB= defined $path
ABresult
1X1
011
000
9078 46 ▶ my $spec = $self->param('spec') // '';
Condition100%2/2
$self->param("spec") // ""
l!l
442
MC/DC100%1/1
$self->param("spec") // ""
$self->param("spec")
Truth table100%2/2
A
A= $self->param("spec")
Aresult
11
00
9079 46 ▶ if ($spec =~ m{\Atable:([A-Za-z_][A-Za-z0-9_]*(?:/[A-Za-z_][A-Za-z0-9_]*)?)\z}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($spec =~ m[\Atable:([A-Za-z_][A-Za-z0-9_]*(?:/[A-Za-z_][A-Za-z0-9_]*)?)\z]u) { } 1 45 46
elsif ($spec =~ /\Apath:(.+)\z/su) { } 3 42 45
9080 1 $table_name = $1;
9081 } elsif ($spec =~ /\Apath:(.+)\z/s) {
9082 3 ($path, $path_internal) = _split_path($1);
9083 }
9084 }
9085  
9086 63 my $source;
9087 63 ▶ if (($self->param('spec') // '') =~ $MARIADB_SPEC_RE) {
Branch: 3 branches
BranchTrueFalseTotal
if (($self->param('spec') // '') =~ /$MARIADB_SPEC_RE/u) { } 0 63 63
elsif (defined $table_name and $table_name =~ m[\A([A-Za-z_][A-Za-z0-9_]*)(?:/([A-Za-z_][A-Za-z0-9_]*))?\z]u) { } 12 51 63
elsif (defined $path) { } 8 43 51
Condition100%2/2
$self->param("spec") // ""
l!l
459
MC/DC100%1/1
$self->param("spec") // ""
$self->param("spec")
Truth table100%2/2
A
A= $self->param("spec")
Aresult
11
00
9088 0 ($source) = $self->_open_spec($self->param('spec'));
9089 }
9090 ▶ elsif (defined $table_name && $table_name =~ m{\A([A-Za-z_][A-Za-z0-9_]*)(?:/([A-Za-z_][A-Za-z0-9_]*))?\z}) {
Condition100%3/3
defined $table_name and $table_name =~ m[\A([A-Za-z_][A-Za-z0-9_]*)(?:/([A-Za-z_][A-Za-z0-9_]*))?\z]u
!ll&&!rl&&r
49212
MC/DC100%2/2
defined $table_name and $table_name =~ m[\A([A-Za-z_][A-Za-z0-9_]*)(?:/([A-Za-z_][A-Za-z0-9_]*))?\z]u
defined $table_name $table_name =~ m[\A([A-Za-z_][A-Za-z0-9_]*)(?:/([A-Za-z_][A-Za-z0-9_]*))?\z]u
Truth table100%3/3
A and B
A= defined $table_nameB= $table_name =~ m[\A([A-Za-z_][A-Za-z0-9_]*)(?:/([A-Za-z_][A-Za-z0-9_]*))?\z]u
ABresult
0X0
100
111
9091 12 my ($table, $internal) = ($1, $2);
9092 12 my $data_dir = _data_dir_for($self->app);
9093 12 my $stem = _table_stem($data_dir, $table);
9094 12 ▶ return $self->render(json => { error => 'not found' }, status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $stem 3 9 12
9095 unless defined $stem;
9096 9 $source = eval {
9097 9 ▶ $self->open_table($stem, directory => $data_dir->to_string,
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 0 9 9
9098 defined $internal ? (internal_table => $internal) : ())
9099 };
9100 }
9101 elsif (defined $path) {
9102 8 ▶ if ($path =~ m{\A/\.\./([^/]+)((?:/.+)?)/([^/]+)\z}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($path =~ m[\A/\.\./([^/]+)((?:/.+)?)/([^/]+)\z]u) { } 2 6 8
elsif (my $refusal = _outside_roots($self, $path)) { } 0 6 6
9103 2 ▶ my ($host, $dir_part, $file) = ($1, $2 // '', $3);
Condition50%1/2
$2 // ""
l!l
20
MC/DC0%0/1
$2 // ""
$2
Truth table50%1/2
A
A= $2
Aresult
11
00
9104 2 ▶ $dir_part = '/' unless length $dir_part;
Branch: 1 branch
BranchTrueFalseTotal
unless length $dir_part 0 2 2
9105 2 ▶ if ($host =~ $REMOTE_HOST_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($host =~ /$REMOTE_HOST_RE/u) 2 0 2
9106 2 ▶ my ($tbl, $ext) = $file =~ /\A(.+)\.([^.]+)\z/ ? ($1, $2) : ($file, undef);
Branch: 1 branch
BranchTrueFalseTotal
$file =~ /\A(.+)\.([^.]+)\z/u ? : 2 0 2
9107 2 ▶ $source = eval { $self->open_table($tbl, directory => $dir_part, host => $host,
Branch: 2 branches
BranchTrueFalseTotal
defined $ext ? : 2 0 2
defined $path_internal ? : 0 2 2
9108 defined $ext ? (file_ext => $ext) : (),
9109 defined $path_internal ? (internal_table => $path_internal) : ()) };
9110 }
9111 } elsif (my $refusal = _outside_roots($self, $path)) {
9112 0 return $self->render(json => { error => $refusal }, status => 403);
9113 } else {
9114 6 my $file = eval { Mojo::File->new($path)->realpath };
9115 6 ▶ if (defined $file && -f $file && $file->basename =~ $EXT_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file and -f $file and $file->basename =~ /$EXT_RE/u) 3 3 6
Condition83%5/6
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
!ll&&!rl&&r
303
defined $file and -f $file
!ll&&!rl&&r
213
MC/DC66%2/3
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
defined $file -f $file $file->basename =~ /$EXT_RE/u
Truth table75%3/4
A and B and C
A= defined $fileB= -f $fileC= $file->basename =~ /$EXT_RE/u
ABCresult
0XX0
10X0
1100
1111
9116 3 my $dir = $file->dirname->to_string;
9117 3 (my $tbl = $file->basename) =~ s/\.[^.]+\z//;
9118 3 ▶ $source = eval { $self->open_table($tbl, directory => $dir,
Branch: 1 branch
BranchTrueFalseTotal
defined $path_internal ? : 0 3 3
9119 defined $path_internal ? (internal_table => $path_internal) : ()) };
9120 }
9121 }
9122 }
9123  
9124 60 ▶ return $self->render(json => { error => 'not found' }, status => 404) unless $source;
Branch: 1 branch
BranchTrueFalseTotal
unless $source 46 14 60
9125  
9126 # Use _get_columns to ensure consistent ordering with the view action.
9127 0 ▶ my $recs = ($source->columns ? [] : eval { $source->fetch_all } // []);
Branch: 1 branch
BranchTrueFalseTotal
$source->columns ? : 14 0 14
Condition0%0/2
eval { do { $source->fetch_all } } // []
l!l
00
MC/DC0%0/1
eval { do { $source->fetch_all } } // []
eval { do { $source->fetch_all } }
Truth table0%0/2
A
A= eval { do { $source->fetch_all } }
Aresult
11
00
9128 14 my @cols = _get_columns($source, $recs);
9129  
9130 14 $self->render(json => { columns => \@cols });
9131 }
9132  
9133 =head2 range_api
9134  
9135 C<GET /api/range> -- Return the min and max ISO date values for one column of
9136 a view. The view is the left source with any joins and combines applied, so
9137 the column may come from a joined table, and an inner join's dropped rows do not
9138 count. Filters are not applied.
9139  
9140 =head3 API SPECIFICATION
9141  
9142 =head4 INPUT
9143  
9144 ?l= string Required. Data source spec ("table:name", "path:/abs/path", etc.).
9145 ?col= string Required. Column name to compute the range for.
9146 ?j= string Optional, repeatable. Join spec "<spec>|<lkey>|<rkey>".
9147 ?jtype= string Optional. left (default), inner or outer.
9148 ?c= string Optional, repeatable. Source spec to stack under the view.
9149  
9150 =head4 OUTPUT
9151  
9152 200 application/json { "min": "YYYY-MM-DD", "max": "YYYY-MM-DD" }
9153 200 application/json { "min": null, "max": null } (no parseable dates)
9154 400 application/json { "error": "..." }
9155  
9156 =head3 FORMAL SPECIFICATION
9157  
9158 range_api == lambda self .
9159 let recs = _run_pipeline_source().records in
9160 pre param('l') /= '' /\ col /= ''
9161 post render_json({ min: min_date(recs, col), max: max_date(recs, col) })
9162  
9163 =cut
9164  
9165 60 ▶sub range_api ($self) {
Subroutine range_api: called CC=13 SCAR=25.7
Pod documented
9166 60 ▶ my $spec_str = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
582
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
9167 60 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
555
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
9168 60 ▶ return $self->render(json => { error => 'l required' }, status => 400) unless length $spec_str;
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec_str 3 57 60
9169 57 ▶ return $self->render(json => { error => 'col required' }, status => 400) unless length $col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 3 54 57
9170  
9171 # The pipeline, so that the range is of the rows the page shows. A join
9172 # that cannot be built croaks; this route answers "no range" instead.
9173 54 my (undef, $records, $columns) = eval { $self->_run_pipeline_source };
9174 return $self->render(json => { min => undef, max => undef })
9175 54 ▶ unless $records && grep { $_ eq $col } @$columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $records and grep {$_ eq $col;} @$columns 6 48 54
Condition100%3/3
$records and grep {$_ eq $col;} @$columns
!ll&&!rl&&r
2448
MC/DC100%2/2
$records and grep {$_ eq $col;} @$columns
$records grep {$_ eq $col;} @$columns
Truth table100%3/3
A and B
A= $recordsB= grep {$_ eq $col;} @$columns
ABresult
0X0
100
111
9176  
9177 48 my $mdy_re = qr|\A(\d{1,2})/(\d{1,2})/(\d{4})\z|;
9178 48 my @dates;
9179 48 for my $rec (@$records) {
9180 268 ▶ my $v = $rec->{$col} // '';
Condition100%2/2
$rec->{$col} // ""
l!l
2671
MC/DC100%1/1
$rec->{$col} // ""
$rec->{$col}
Truth table100%2/2
A
A= $rec->{$col}
Aresult
11
00
9181 268 ▶ next unless length $v;
Branch: 1 branch
BranchTrueFalseTotal
unless length $v 1 267 268
9182 # A timestamp counts as the day it names, as the filters read it.
9183 267 ▶ if (defined(my $day = (Database::BI::Util::iso_datetime($v))[0])) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined(my $day = (Database::BI::Util::iso_datetime($v))[0])) { } 21 246 267
elsif (my(@m) = $v =~ /$mdy_re/u) { } 0 246 246
9184 21 push @dates, $day;
9185 } elsif (my @m = ($v =~ $mdy_re)) {
9186 0 push @dates, sprintf '%04d-%02d-%02d', $m[2], $m[0], $m[1];
9187 }
9188 }
9189  
9190 48 ▶ return $self->render(json => { min => undef, max => undef }) unless @dates;
Branch: 1 branch
BranchTrueFalseTotal
unless @dates 41 7 48
9191 7 @dates = sort @dates;
9192 7 $self->render(json => { min => $dates[0], max => $dates[-1] });
9193 }
9194  
9195 =head2 join_tables
9196  
9197 C<GET /join> -- Perform one or more left joins and render the merged table.
9198  
9199 =head3 API SPECIFICATION
9200  
9201 =head4 INPUT
9202  
9203 ?l= string Required. Left table spec: "table:name", "table:file/table"
9204 or "path:/abs/path". Returns 404 if unresolvable.
9205 ?j= string (repeatable) Join step: "<right-spec>|<left-key>|<right-key>".
9206 Invalid or non-existent steps are silently skipped.
9207 ?f= string (repeatable) Result filter: "col:op:val".
9208  
9209 =head4 OUTPUT
9210  
9211 Renders C<dashboard.html.tt> with the merged/filtered result set.
9212  
9213 =head3 MESSAGES
9214  
9215 error_table_open -- Left table fetch threw (re-renders home with error).
9216  
9217 =head3 FORMAL SPECIFICATION
9218  
9219 join_tables == lambda self .
9220 let left = open_spec(param('l')) in
9221 pre left /= undef
9222 let joined = fold(_left_join, left, param_list('j')) in
9223 let filtered = fold(_apply_filter_spec, joined, param_list('f')) in
9224 post render(dashboard, records: filtered)
9225  
9226 =head3 PSEUDOCODE
9227  
9228 1. Parse and open left table spec; 404 on failure.
9229 2. For each j= param (in order):
9230 a. Parse right-spec, left-key, right-key from "|"-split.
9231 b. Verify left-key exists in current column list.
9232 c. Open right table; skip step on any error.
9233 d. Verify right-key exists in right column list.
9234 e. Call _left_join; update records and columns.
9235 3. Apply all f= filters via _apply_filter_spec.
9236 4. Build stable table key for localStorage ("join:left:right1:...").
9237 5. Render dashboard.
9238  
9239 =head3 EXAMPLE
9240  
9241 GET /join?l=table:sales&j=table:products|product|name
9242 -> merged left join of sales and products on product/name columns
9243  
9244 =cut
9245  
9246 80 ▶sub join_tables ($self) {
Subroutine join_tables: called CC=30 SCAR=34.3
Pod documented
9247 # Rows stacked from other files cannot be paged from one backend; the
9248 # combine route runs joins and combines together. c= also carries calculated
9249 # fields, which do not stack anything and stay on this page.
9250 return $self->combine_tables
9251 80 ▶ if @{ $self->every_param('c') } > $self->_calc_specs_of_request;
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->every_param("c");} > $self->_calc_specs_of_request 0 80 80
9252  
9253 80 my ($platform, $language) = $self->_resolve_template;
9254  
9255 80 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
782
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
9256 80 my ($left_src, $left_label) = $self->_open_spec($left_spec);
9257 80 ▶ return $self->reply->not_found unless $left_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $left_src 5 75 80
9258  
9259 75 my @join_specs = @{ $self->every_param('j') };
9260 75 my @summaries;
9261  
9262 # Build the join chain: each step wraps the previous source in a
9263 # Database::Join. Data is not fetched until after the loop.
9264 75 ▶ my $max_rows = $self->app->config('join_max_rows') // $DEFAULT_JOIN_MAX_ROWS;
Condition66%2/3
$self->app->config("join_max_rows") // $DEFAULT_JOIN_MAX_ROWS
l!l&&r!l&&!r
0741
MC/DC50%1/2
$self->app->config("join_max_rows") // $DEFAULT_JOIN_MAX_ROWS
$self->app->config("join_max_rows") $DEFAULT_JOIN_MAX_ROWS
Truth table66%2/3
A // B
A= $self->app->config("join_max_rows")B= $DEFAULT_JOIN_MAX_ROWS
ABresult
1X1
011
000
9265 75 ▶ my $join_type = $self->param('jtype') // 'left';
Condition100%2/2
$self->param("jtype") // "left"
l!l
273
MC/DC100%1/1
$self->param("jtype") // "left"
$self->param("jtype")
Truth table100%2/2
A
A= $self->param("jtype")
Aresult
11
00
9266 75 ▶ $join_type = 'left' unless $join_type =~ /\A(?:left|inner|outer)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $join_type =~ /\A(?:left|inner|outer)\z/u 1 74 75
9267 75 my $src = $left_src;
9268 75 my @schema_warnings;
9269 75 for my $jspec (@join_specs) {
9270 23 my ($right_spec, $left_key, $right_key) = split /\|/, $jspec, 3;
9271 23 ▶ next unless defined $right_spec && defined $left_key && defined $right_key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $right_spec and defined $left_key and defined $right_key 2 21 23
Condition66%4/6
defined $right_spec and defined $left_key and defined $right_key
!ll&&!rl&&r
2021
defined $right_spec and defined $left_key
!ll&&!rl&&r
0221
MC/DC33%1/3
defined $right_spec and defined $left_key and defined $right_key
defined $right_spec defined $left_key defined $right_key
Truth table50%2/4
A and B and C
A= defined $right_specB= defined $left_keyC= defined $right_key
ABCresult
0XX0
10X0
1100
1111
9272  
9273 21 my $cur_cols = $src->columns;
9274 21 ▶ next unless $cur_cols;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_cols 0 21 21
9275 21 ▶ next unless +{ map { $_ => 1 } @$cur_cols }->{$left_key};
Branch: 1 branch
BranchTrueFalseTotal
unless {map({$_, 1;} @$cur_cols)}->{$left_key} 1 20 21
9276  
9277 20 my ($right_src, $right_label) = $self->_open_spec($right_spec);
9278 20 ▶ next unless $right_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_src 2 18 20
9279  
9280 18 my $right_cols = $right_src->columns;
9281 18 ▶ next unless $right_cols;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_cols 10 8 18
9282 8 ▶ next unless +{ map { $_ => 1 } @$right_cols }->{$right_key};
Branch: 1 branch
BranchTrueFalseTotal
unless {map({$_, 1;} @$right_cols)}->{$right_key} 0 8 8
9283  
9284 # Types are compared while the two sides are still separate sources;
9285 # after the join is built the mismatched columns are already published
9286 # under different names. See _schema_type_warnings.
9287 8 push @schema_warnings, $self->_schema_type_warnings(
9288 $src, $right_src, $left_label, $right_label, $left_key, $right_key);
9289  
9290 8 require Database::Join;
9291 0 ▶ local $SIG{__WARN__} = sub { push @schema_warnings, $_[0] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
9292 8 ▶ $src = Database::Join->new(
Branch: 2 branches
BranchTrueFalseTotal
$left_key ne $right_key ? : 2 6 8
$right_label ? : 8 0 8
9293 databases => [$src, $right_src],
9294 join_column => $left_key,
9295 backend => 'auto',
9296 max_array_rows => $max_rows,
9297 join_type => $join_type,
9298 ($left_key ne $right_key ? (join_map => {1 => $right_key}) : ()),
9299 ($right_label ? (collision_prefix => {1 => $right_label}) : ()),
9300 );
9301 8 push @summaries, { label => $right_label, left_key => $left_key, right_key => $right_key };
9302 }
9303  
9304 75 my ($page, $per_page, $offset) = $self->_pagination;
9305 75 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 75 75
9306 75 my $sort = $self->param('sort');
9307 75 ▶ my $dir = ($self->param('dir') // 'asc') =~ /\Adesc\z/i ? 'desc' : 'asc';
Branch: 1 branch
BranchTrueFalseTotal
($self->param('dir') // 'asc') =~ /\Adesc\z/iu ? : 5 70 75
Condition100%2/2
$self->param("dir") // "asc"
l!l
669
MC/DC100%1/1
$self->param("dir") // "asc"
$self->param("dir")
Truth table100%2/2
A
A= $self->param("dir")
Aresult
11
00
9308  
9309 75 my ($records, $has_next);
9310 75 eval {
9311 75 ($records, $has_next) = $self->_fetch_page($src,
9312 { per_page => $per_page, offset => $offset,
9313 dedup => $dedup, sort_col => $sort,
9314 sort_dir => $dir, calc_spec_key => $left_spec });
9315 };
9316 75 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 75 75
9317 0 return $self->render(
9318 template => "$platform/$language/home",
9319 handler => 'tt',
9320 format => 'html',
9321 tables => [],
9322 title => 'Error',
9323 error => $self->_i18n('error_table_open', $left_label, _tidy_error($@)),
9324 language => $language,
9325 );
9326 }
9327 # A cross-row spec that could not be honoured has already rendered its 400
9328 # inside _fetch_page; the page must not be drawn over it.
9329 75 ▶ return if $self->stash('_cross_row_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_cross_row_error") 1 74 75
9330  
9331 74 ▶ $records //= [];
Condition50%1/2
$records //= []
l!l
740
MC/DC0%0/1
$records //= []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
9332 74 my $page_columns;
9333 74 ($records, $page_columns) = $self->_page_columns($src, $records, $left_spec);
9334 74 ▶ return unless $page_columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $page_columns 2 72 74
9335 72 my @columns = @$page_columns;
9336  
9337 72 ▶ if (defined $sort && !grep { $_ eq $sort } @columns) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort and not grep({$_ eq $sort;} @columns)) 1 71 72
Condition100%3/3
defined $sort and not grep({$_ eq $sort;} @columns)
!ll&&!rl&&r
6561
MC/DC100%2/2
defined $sort and not grep({$_ eq $sort;} @columns)
defined $sort not grep({$_ eq $sort;} @columns)
Truth table100%3/3
A and not(B)
A= defined $sortB= not grep({$_ eq $sort;} @columns)
ABresult
0X0
100
111
9338 1 carp $self->_i18n('error_sort_column', $sort);
9339 }
9340  
9341 72 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
9342  
9343 72 my $title = $left_label;
9344 72 ▶ $title .= ' + ' . join(' + ', map { $_->{label} } @summaries) if @summaries;
Branch: 1 branch
BranchTrueFalseTotal
if @summaries 8 64 72
9345 72 my $table_key = 'join:' . lc($left_label);
9346 72 $table_key .= ':' . lc($_->{label}) for @summaries;
9347  
9348 72 my $page_url = $self->req->url->clone;
9349 72 $page_url->query->remove('page')->remove('per_page');
9350  
9351 72 ▶ $self->render(
Condition100%2/2
$self->param("back2_label") // "Back"
l!l
171
MC/DC100%1/1
$self->param("back2_label") // "Back"
$self->param("back2_label")
Truth table100%2/2
A
A= $self->param("back2_label")
Aresult
11
00
9352 template => "$platform/$language/dashboard",
9353 handler => 'tt',
9354 format => 'html',
9355 records => $records,
9356 columns => \@columns,
9357 table => $table_key,
9358 title => $title,
9359 back_url => $self->_spec_to_url($left_spec),
9360 back_label => "Back to $left_label",
9361 back2_url => _safe_back_url($self->param('back2')),
9362 back2_label => $self->param('back2_label') // 'Back',
9363 left_spec => $left_spec,
9364 combine_specs => [ $self->_calc_specs_of_request ],
9365 current_joins => \@join_specs,
9366 available_tables => $self->_scan_join_tables,
9367 join_summaries => \@summaries,
9368 filter_specs => $filter_specs,
9369 filters_json => $filters_json,
9370 dedup => $dedup,
9371 export_url => $self->_build_export_url($left_spec, \@join_specs, $filter_specs, undef, $dedup),
9372 schema_warnings => \@schema_warnings,
9373 page => $page,
9374 per_page => $per_page,
9375 has_next => $has_next,
9376 page_base_url => $page_url->to_string,
9377 language => $language,
9378 );
9379 }
9380  
9381 =head2 combine_tables
9382  
9383 C<GET /combine> -- Stack rows from two or more tables vertically into a single
9384 unified view.
9385  
9386 Unlike C</join> (which appends columns from a matching row in a second table),
9387 C</combine> appends the I<rows> from a second table beneath the rows of the
9388 first. All columns from all sources appear as headers; where a row has no
9389 value for a particular column (because that column did not exist in its source
9390 file) the cell is left blank.
9391  
9392 This is equivalent to a SQL C<UNION ALL> across heterogeneous schemas.
9393  
9394 =head3 API SPECIFICATION
9395  
9396 =head4 INPUT
9397  
9398 ?l= string (required) Left table spec: "table:name" or "path:/abs/path".
9399 Returns 404 if unresolvable.
9400 ?c= string (repeatable) Additional table spec to stack beneath the
9401 current result. Invalid or non-existent specs are silently
9402 skipped.
9403 ?f= string (repeatable) Result filter: "col:op:val".
9404 ?srccol= string Optional. Adds a last column of this name that holds the
9405 file or table each row came from. An identifier of up to
9406 64 characters; anything else is ignored. A name a source
9407 already uses gets underscores added until it is free.
9408  
9409 =head4 OUTPUT
9410  
9411 Renders C<dashboard.html.tt> with the combined result set.
9412  
9413 =head3 MESSAGES
9414  
9415 error_table_open -- Left table fetch threw (re-renders home with error).
9416  
9417 =head3 FORMAL SPECIFICATION
9418  
9419 combine_tables == lambda self .
9420 let left = open_spec(param('l')) in
9421 pre left /= undef
9422 let sources = [left] ++ map(open_spec, param_list('c')) in
9423 let combined = _combine_tables(sources) in
9424 let filtered = fold(_apply_filter_spec, combined, param_list('f')) in
9425 post render(dashboard, records: filtered)
9426  
9427 =head3 EXAMPLE
9428  
9429 GET /combine?l=table:cats&c=table:dogs
9430 -> unified view: all cat and dog rows; Species/Name/Color/Breed/Eye Color
9431 appear for both; Environment (cats-only) and Sex/Fixed (dogs-only)
9432 are blank where the source file lacks that column.
9433  
9434 =cut
9435  
9436 63 ▶sub combine_tables ($self) {
Subroutine combine_tables: called CC=26 SCAR=33.1
Pod documented
9437 63 my ($platform, $language) = $self->_resolve_template;
9438  
9439 63 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
603
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
9440 63 my ($left_src, $left_label) = $self->_open_spec($left_spec);
9441 63 ▶ return $self->reply->not_found unless $left_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $left_src 7 56 63
9442  
9443 # The same join-then-stack pipeline the charts of this view use, so the
9444 # table shows the rows they draw.
9445 56 my (undef, $records, $cols_ref) = $self->_run_pipeline_source;
9446 56 ▶ unless (defined $records) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $records) 0 56 56
9447 0 return $self->render(
9448 template => "$platform/$language/home",
9449 handler => 'tt',
9450 format => 'html',
9451 tables => [],
9452 title => 'Error',
9453 error => $self->_i18n('error_table_open', $left_label, ''),
9454 language => $language,
9455 );
9456 }
9457 56 my @join_specs = @{ $self->every_param('j') };
9458 56 my @combine_specs = @{ $self->every_param('c') };
9459 56 ▶ my @summaries = (@{ $self->stash('pipeline_joined') // [] },
Condition50%1/2
$self->stash("pipeline_joined") // []
l!l
560
MC/DC0%0/1
$self->stash("pipeline_joined") // []
$self->stash("pipeline_joined")
Truth table50%1/2
A
A= $self->stash("pipeline_joined")
Aresult
11
00
9460 56 ▶ @{ $self->stash('pipeline_combined') // [] });
Condition50%1/2
$self->stash("pipeline_combined") // []
l!l
560
MC/DC0%0/1
$self->stash("pipeline_combined") // []
$self->stash("pipeline_combined")
Truth table50%1/2
A
A= $self->stash("pipeline_combined")
Aresult
11
00
9461  
9462 # Stage 4, for a table of stacked rows as for any other.
9463 56 my $span = $self->_span_calc_spec($cols_ref, ());
9464 56 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 2 54 56
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
5402
MC/DC50%1/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table66%2/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
9465 54 my ($calc_records, $calc_columns) = eval {
9466 54 ▶ $self->_apply_calc_fields($records, $cols_ref, ($span ? { calc => $span->{calc} } : undef))
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 54 54
9467 };
9468 54 ▶ unless ($calc_records) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($calc_records) 1 53 54
9469 1 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
9470 1 return $self->render(text => $e, status => 400);
9471 }
9472 53 ($records, $cols_ref) = ($calc_records, $calc_columns);
9473  
9474 # Apply the filters in memory before paginating (reduce-before-paginate).
9475 53 my @columns;
9476 53 ▶ return unless $self->_reduce_or_render(\$records, \$cols_ref);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$cols_ref) 1 52 53
9477 52 @columns = @$cols_ref;
9478 # _reduce_or_render has removed duplicates for d=1; $dedup is for the page.
9479 52 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 52 52
9480  
9481 # In-memory sort for /combine (no single backend to delegate to).
9482 52 my $sort = $self->param('sort');
9483 52 ▶ my $dir = ($self->param('dir') // 'asc') =~ /\Adesc\z/i ? 'desc' : 'asc';
Branch: 1 branch
BranchTrueFalseTotal
($self->param('dir') // 'asc') =~ /\Adesc\z/iu ? : 1 51 52
Condition100%2/2
$self->param("dir") // "asc"
l!l
250
MC/DC100%1/1
$self->param("dir") // "asc"
$self->param("dir")
Truth table100%2/2
A
A= $self->param("dir")
Aresult
11
00
9484 52 ▶ if (defined $sort && grep { $_ eq $sort } @columns) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort and grep {$_ eq $sort;} @columns) { } 3 49 52
elsif (defined $sort) { } 1 48 49
Condition100%3/3
defined $sort and grep {$_ eq $sort;} @columns
!ll&&!rl&&r
4813
MC/DC100%2/2
defined $sort and grep {$_ eq $sort;} @columns
defined $sort grep {$_ eq $sort;} @columns
Truth table100%3/3
A and B
A= defined $sortB= grep {$_ eq $sort;} @columns
ABresult
0X0
100
111
9485 3 carp $self->_i18n('warn_combine_sort');
9486 # A new array: the backend's own can be read-only, as a SQLite one is.
9487 3 ▶ $records = [ sort { ($a->{$sort} // '') cmp ($b->{$sort} // '') } @$records ];
Condition50%2/4
$Database::BI::Controller::Dashboard::a->{$sort} // ""
l!l
200
$Database::BI::Controller::Dashboard::b->{$sort} // ""
l!l
200
MC/DC0%0/1
$Database::BI::Controller::Dashboard::a->{$sort} // ""
$Database::BI::Controller::Dashboard::a->{$sort}
MC/DC0%0/1
$Database::BI::Controller::Dashboard::b->{$sort} // ""
$Database::BI::Controller::Dashboard::b->{$sort}
Truth table50%1/2
A
A= $Database::BI::Controller::Dashboard::a->{$sort}
Aresult
11
00
Truth table50%1/2
A
A= $Database::BI::Controller::Dashboard::b->{$sort}
Aresult
11
00
9488 3 ▶ $records = [ reverse @$records ] if $dir eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if $dir eq "desc" 1 2 3
9489 } elsif (defined $sort) {
9490 1 carp $self->_i18n('error_sort_column', $sort);
9491 }
9492  
9493 # Server-side pagination: slice the fully-reduced combined set. The page
9494 # below is therefore reduced too, and asks for chips only.
9495 52 my ($page, $per_page, $offset) = $self->_pagination;
9496 52 my $total = scalar @$records;
9497 52 ▶ my $has_next = ($total > $offset + $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$total > $offset + $per_page ? : 1 51 52
9498 52 my @page_recs = @{ _rows_of_page($records, $offset, $per_page) };
9499 52 $records = \@page_recs;
9500 52 $self->stash(page_count => _page_count($total, $per_page));
9501  
9502 52 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
9503  
9504 52 my $title = _names_summary([ $left_label, map { $_->{label} } @summaries ]);
9505 52 ▶ my $table_key = (@join_specs ? 'join+combine:' : 'combine:') . lc($left_label);
Branch: 1 branch
BranchTrueFalseTotal
@join_specs ? : 1 51 52
9506 52 $table_key .= ':' . lc($_->{label}) for @summaries;
9507 # The key names the layout kept in localStorage: a folder's worth of names
9508 # is not a key, so a long one is shortened to its start and a digest.
9509 52 ▶ if (length($table_key) > 120) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $table_key > 120) 0 52 52
9510 0 require Digest::MD5;
9511 0 $table_key = substr($table_key, 0, 80) . ':' . Digest::MD5::md5_hex($table_key);
9512 }
9513  
9514 52 my $page_url = $self->req->url->clone;
9515 52 $page_url->query->remove('page')->remove('per_page');
9516  
9517 52 ▶ $self->render(
Condition75%3/4
$self->param("back2_label") // "Back"
l!l
151
$self->stash("schema_warnings") // []
l!l
052
MC/DC100%1/1
$self->param("back2_label") // "Back"
$self->param("back2_label")
MC/DC0%0/1
$self->stash("schema_warnings") // []
$self->stash("schema_warnings")
Truth table100%2/2
A
A= $self->param("back2_label")
Aresult
11
00
Truth table50%1/2
A
A= $self->stash("schema_warnings")
Aresult
11
00
9518 template => "$platform/$language/dashboard",
9519 handler => 'tt',
9520 format => 'html',
9521 records => $records,
9522 columns => \@columns,
9523 table => $table_key,
9524 title => $title,
9525 back_url => $self->_spec_to_url($left_spec),
9526 back_label => "Back to $left_label",
9527 back2_url => _safe_back_url($self->param('back2')),
9528 back2_label => $self->param('back2_label') // 'Back',
9529 left_spec => $left_spec,
9530 combine_specs => \@combine_specs,
9531 current_joins => \@join_specs,
9532 available_tables => $self->_scan_join_tables,
9533 join_summaries => \@summaries,
9534 filter_specs => $filter_specs,
9535 filters_json => $filters_json,
9536 dedup => $dedup,
9537 export_url => $self->_build_export_url($left_spec, \@join_specs, $filter_specs, \@combine_specs, $dedup),
9538 schema_warnings => $self->stash('schema_warnings') // [],
9539 page => $page,
9540 per_page => $per_page,
9541 has_next => $has_next,
9542 page_base_url => $page_url->to_string,
9543 language => $language,
9544 );
9545 }
9546  
9547 =head2 export_data
9548  
9549 C<GET /export> -- Stream the current logical view as a browser file download.
9550  
9551 =head3 API SPECIFICATION
9552  
9553 =head4 INPUT
9554  
9555 ?l= string (required) Left table spec.
9556 ?j= string (repeatable) Join steps.
9557 ?f= string (repeatable) Filter specs.
9558 ?format= string "csv" (default), "sqlite", or "json".
9559 ?xcol= string (repeatable) Keep only these columns, in this order.
9560  
9561 =head4 DOMAIN CONSTRAINTS: ?xcol=
9562  
9563 Each C<xcol> is the exact name of one column of the view. The file holds
9564 those columns, in the order the C<xcol> values are given.
9565  
9566 =over 4
9567  
9568 =item Valid partitions
9569  
9570 No C<xcol> at all: every column is exported, as before. One or more names the
9571 view has: only those columns. The same name twice: the first one counts.
9572  
9573 =item Ignored, not an error
9574  
9575 A name the view does not have, or an empty value. If no name is left after
9576 this, every column is exported. A column that a filter or a calculated field
9577 uses can still be left out of the file: the rows are worked out first, and the
9578 columns are chosen last.
9579  
9580 =back
9581  
9582 The Export panel sends one C<xcol> for each column its table still shows, in
9583 the table's order. Deleting a column, or dragging it to a new place, changes
9584 only the page in the browser, so this is how the server learns about it.
9585  
9586 =head4 DOMAIN CONSTRAINTS: ?format=
9587  
9588 Exact lowercase string match.
9589  
9590 =over 4
9591  
9592 =item Valid partitions
9593  
9594 C<csv> (explicit CSV), C<sqlite> (SQLite binary), C<json> (JSON array),
9595 absent/undef (defaults to CSV).
9596  
9597 =item Invalid partitions (all fall back to CSV)
9598  
9599 Any value not in the valid set (e.g. C<SQLITE>, C<Json>).
9600  
9601 =back
9602  
9603 =head4 OUTPUT
9604  
9605 200 text/csv Content-Disposition: attachment; filename=<name>.csv
9606 200 application/vnd.sqlite3 Content-Disposition: attachment; filename=<name>.db
9607 200 application/json Content-Disposition: attachment; filename=<name>.json
9608 404 application/json { "error": "Table not found" }
9609 500 text/plain The SQLite file could not be built (no driver, no
9610 temporary space); the reason goes to the log.
9611  
9612 =head3 MESSAGES
9613  
9614 error_export_sqlite -- the SQLite file could not be built.
9615  
9616 =head3 COMMON PITFALLS
9617  
9618 =over 4
9619  
9620 =item *
9621  
9622 A link without C<xcol> exports every column, even if the page it came from had
9623 columns deleted. Only the Export panel adds C<xcol>.
9624  
9625 =item *
9626  
9627 C<xcol> names are matched exactly, including upper and lower case. C<Name> and
9628 C<name> are different columns.
9629  
9630 =item *
9631  
9632 If every C<xcol> is wrong (a typo, or a column that is not in this view), you
9633 get all the columns, not an empty file.
9634  
9635 =item *
9636  
9637 In the JSON file each row is an object whose keys follow the column order. A
9638 row that has no value for a column gets C<null> for it, so every row has the
9639 same keys.
9640  
9641 =back
9642  
9643 =head3 ENCODING
9644  
9645 Column names and cell values may hold any UTF-8 text: accents, Chinese,
9646 Arabic, emoji. C<xcol> values must be sent as UTF-8 and percent-encoded in a
9647 URL (C<caf%C3%A9> for a C<cafe> with an accent on the last letter). CSV and JSON are written as UTF-8.
9648  
9649 =head3 FORMAL SPECIFICATION
9650  
9651 export_data == lambda self .
9652 let (recs, cols, label) = _run_export_pipeline() in
9653 pre recs /= undef
9654 let want = [c in params('xcol') | c /= '' /\ c in cols] in
9655 let keep = if want = [] then cols else dedupe(want) in
9656 post if format = 'sqlite' then render_sqlite(project(recs, keep), keep)
9657 else if format = 'json' then render_json(project(recs, keep), keep)
9658 else render_csv(project(recs, keep), keep)
9659  
9660 =head3 EXAMPLE
9661  
9662 GET /export?l=table:sales&format=csv -> downloads sales.csv
9663 GET /export?l=table:sales&format=sqlite -> downloads sales.db
9664 GET /export?l=table:sales&format=json -> downloads sales.json
9665  
9666 # Only two columns, name first:
9667 GET /export?l=table:sales&format=csv&xcol=name&xcol=id
9668  
9669 =cut
9670  
9671 128 ▶sub export_data ($self) {
Subroutine export_data: called CC=8 SCAR=20.8
Pod documented
9672 128 my ($records, $columns, $left_label) = $self->_run_export_pipeline;
9673 128 ▶ return if $self->stash('_reduce_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_reduce_error") 30 98 128
9674 98 ▶ return $self->reply->not_found unless $records;
Branch: 1 branch
BranchTrueFalseTotal
unless $records 9 89 98
9675  
9676 # Surface schema-type-mismatch warnings in a response header so API
9677 # consumers (and the user via browser dev tools) can see them even
9678 # though exports render no HTML template.
9679 89 ▶ my $warnings = $self->stash('schema_warnings') // [];
Condition100%2/2
$self->stash("schema_warnings") // []
l!l
188
MC/DC100%1/1
$self->stash("schema_warnings") // []
$self->stash("schema_warnings")
Truth table100%2/2
A
A= $self->stash("schema_warnings")
Aresult
11
00
9680 89 ▶ if (@$warnings) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$warnings) 1 88 89
9681 1 my $hdr = join('; ', map { s/\s+/ /gr =~ s/^\s+|\s+$//gr } @$warnings);
9682 1 $self->res->headers->header('X-BI-Warnings' => $hdr);
9683 }
9684  
9685 89 ($records, $columns) = _export_selection($self, $records, $columns);
9686  
9687 89 ▶ my $format = $self->param('format') // 'csv';
Condition100%2/2
$self->param("format") // "csv"
l!l
5039
MC/DC100%1/1
$self->param("format") // "csv"
$self->param("format")
Truth table100%2/2
A
A= $self->param("format")
Aresult
11
00
9688 89 (my $safe_name = lc $left_label) =~ s/[^a-z0-9_]+/_/g;
9689  
9690 89 ▶ return $format eq 'sqlite' ? $self->_render_sqlite($records, $columns, $safe_name)
Branch: 2 branches
BranchTrueFalseTotal
$format eq 'sqlite' ? : 6 83 89
$format eq 'json' ? : 14 69 83
9691 : $format eq 'json' ? $self->_render_json($records, $columns, $safe_name)
9692 : $self->_render_csv($records, $columns, $safe_name);
9693 }
9694  
9695 =head2 export_write
9696  
9697 C<POST /export> -- Write the current logical view to a chosen filesystem path.
9698  
9699 =head3 API SPECIFICATION
9700  
9701 =head4 INPUT
9702  
9703 l= string (required) Left table spec.
9704 j= string (repeatable) Join steps.
9705 f= string (repeatable) Filter specs.
9706 xcol= string (repeatable) Keep only these columns, in this order (the
9707 columns the table still shows). Unknown names are ignored;
9708 none left means every column.
9709 dir= string Target directory (must exist; resolved via realpath). Inside
9710 config file_roots and export_dirs when they are set.
9711 filename= string Output filename including extension. Extension determines
9712 format: C<.csv> -> RFC 4180 CSV; C<.sql> -> SQLite;
9713 C<.json> -> JSON array of row objects.
9714  
9715 =head4 DOMAIN CONSTRAINTS: xcol=
9716  
9717 Same rule as for C<GET /export>. Each C<xcol> names one column of the view.
9718 The file holds those columns, in the order given. Names the view lacks are
9719 ignored, and if none are left every column is written. The Export panel sends
9720 the columns its table still shows, so a column you deleted in the page is not
9721 saved, and a column you dragged to a new place is saved in the new place. A
9722 JSON file has its keys in that order too.
9723  
9724 =head4 DOMAIN CONSTRAINTS: filename=
9725  
9726 The extension check uses C</\.csv\z/i> (CSV), C</\.sql\z/i> (SQLite), or
9727 C</\.json\z/i> (JSON): the C</i> flag makes matching case-insensitive, so
9728 C<.CSV>, C<.SQL>, and C<.JSON> are accepted alongside lowercase forms.
9729 Everything else returns 415.
9730  
9731 Path separator characters (C</> and C<\>) in C<filename> are stripped
9732 first via C<m{([^/\\]+)\z}> -- only the basename is kept, preventing
9733 directory traversal.
9734  
9735 =over 4
9736  
9737 =item Valid partitions
9738  
9739 C<report.csv>, C<report.sql>, C<report.json>, C<REPORT.CSV>, C<report.SQL>.
9740 A single-character stem (C<a.csv>) is also valid.
9741  
9742 =item Invalid partitions (415)
9743  
9744 C<report.txt>, C<report> (no extension), empty string.
9745  
9746 =back
9747  
9748 =head4 OUTPUT
9749  
9750 200 application/json { "saved": "/abs/path/to/file" }
9751 403 application/json { "error": "..." } -- a hidden target; dir outside
9752 file_roots or export_dirs; a name
9753 that is a link, folder or anything
9754 but a plain file; or a request
9755 another site's page made
9756 401 application/json { "error": "..." } -- password_hash set, not logged in
9757 404 application/json { "error": "..." } -- bad dir or table not found
9758 415 application/json { "error": "..." } -- unsupported extension
9759 500 application/json { "error": "..." } -- write failure
9760  
9761 =head3 MESSAGES
9762  
9763 error_dir_not_found -- realpath of dir failed or result is not a directory.
9764 error_ext_required -- filename extension is not .csv, .sql or .json.
9765 error_hidden_target -- the directory, after realpath, or the filename has a
9766 part starting with a dot (~/.config, .vscode/,
9767 .profile.json): those hold settings, and
9768 GET /api/dirs never offers them.
9769 error_outside_roots -- dir is outside config file_roots.
9770 error_outside_export_dirs
9771 -- dir is outside config export_dirs.
9772 error_export_not_file -- the name is already a link, a folder or another
9773 non-file: a link could lead the export anywhere.
9774 error_cross_site, error_host_refused
9775 -- from request_refusal, before this action runs.
9776 error_write_failed -- DBI or filesystem write threw.
9777  
9778 A refusal names the folder as C<dir> spelled it, though the checks are made
9779 on its realpath. The C<saved> path of a success is the realpath: where the
9780 file is.
9781  
9782 The file is written to a temporary file (C<.bi-export-XXXXXXXX>) in C<dir> and
9783 renamed over the name, so a reader never sees half a file and a link made
9784 after the check is replaced, not followed. It gets the replaced file's mode,
9785 or C<0666 & ~umask> for a new one; on failure the temporary file is removed.
9786  
9787 =head3 COMMON PITFALLS
9788  
9789 =over 4
9790  
9791 =item *
9792  
9793 C<xcol> is a list, so send it once for each column (C<xcol=name&xcol=id>), not
9794 as one comma-separated value.
9795  
9796 =item *
9797  
9798 A script that calls C<POST /export> without C<xcol> gets every column.
9799  
9800 =item *
9801  
9802 The file name decides the format. C<report.json> is JSON even if you meant
9803 CSV.
9804  
9805 =item *
9806  
9807 A column that is not in the view is skipped quietly. Check the file if the
9808 columns look wrong.
9809  
9810 =back
9811  
9812 =head3 ENCODING
9813  
9814 C<filename> and the column names may hold any UTF-8 text. The body must be
9815 sent as UTF-8 (C<application/x-www-form-urlencoded>). The file itself is
9816 written as UTF-8, with no byte order mark.
9817  
9818 =head3 FORMAL SPECIFICATION
9819  
9820 export_write == lambda self .
9821 let dir = realpath(param('dir')) in
9822 let file = dir / strip_path(param('filename')) in
9823 pre is_dir(dir) /\ ext(file) in {csv, sql, json}
9824 let (recs, cols, _) = _run_export_pipeline() in
9825 pre recs /= undef
9826 let want = [c in params('xcol') | c /= '' /\ c in cols] in
9827 let keep = if want = [] then cols else dedupe(want) in
9828 post spurt(file, serialise(project(recs, keep), keep))
9829 /\ render_json({ saved: file.to_string })
9830  
9831 =head3 EXAMPLE
9832  
9833 POST /export l=table:sales dir=/home/user/exports filename=report.csv
9834 -> { "saved": "/home/user/exports/report.csv" }
9835  
9836 # Only two columns, in this order:
9837 POST /export l=table:sales dir=/home/user/exports filename=short.json
9838 xcol=name xcol=id
9839 -> { "saved": "/home/user/exports/short.json" }
9840  
9841 =cut
9842  
9843 46 ▶sub export_write ($self) {
Subroutine export_write: called CC=32 SCAR=34.9
Pod documented
9844 46 ▶ my $dir = $self->param('dir') // '';
Condition50%1/2
$self->param("dir") // ""
l!l
460
MC/DC0%0/1
$self->param("dir") // ""
$self->param("dir")
Truth table50%1/2
A
A= $self->param("dir")
Aresult
11
00
9845 46 ▶ my $filename = $self->param('filename') // '';
Condition50%1/2
$self->param("filename") // ""
l!l
460
MC/DC0%0/1
$self->param("filename") // ""
$self->param("filename")
Truth table50%1/2
A
A= $self->param("filename")
Aresult
11
00
9846  
9847 46 ▶ if (my $refusal = _outside_roots($self, $dir) // _outside_export_dirs($self, $dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $refusal = _outside_roots($self, $dir) // _outside_export_dirs($self, $dir)) 1 45 46
Condition66%2/3
_outside_roots($self, $dir) // _outside_export_dirs($self, $dir)
l!l&&r!l&&!r
0145
MC/DC50%1/2
_outside_roots($self, $dir) // _outside_export_dirs($self, $dir)
_outside_roots($self, $dir) _outside_export_dirs($self, $dir)
Truth table66%2/3
A // B
A= _outside_roots($self, $dir)B= _outside_export_dirs($self, $dir)
ABresult
1X1
011
000
9848 1 return $self->render(json => { error => $refusal }, status => 403);
9849 }
9850 45 my $dest_dir = eval { Mojo::File->new($dir)->realpath };
9851 45 ▶ unless (defined $dest_dir && -d $dest_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $dest_dir and -d $dest_dir) 4 41 45
Condition100%3/3
defined $dest_dir and -d $dest_dir
!ll&&!rl&&r
3141
MC/DC100%2/2
defined $dest_dir and -d $dest_dir
defined $dest_dir -d $dest_dir
Truth table100%3/3
A and B
A= defined $dest_dirB= -d $dest_dir
ABresult
0X0
100
111
9852 4 return $self->render(
9853 json => { error => $self->_i18n('error_dir_not_found', $dir) },
9854 status => 404,
9855 );
9856 }
9857  
9858 # A NUL is not part of any file name, only a way of hiding the real extension.
9859 41 ▶ $filename = '' if $filename =~ /\0/;
Branch: 1 branch
BranchTrueFalseTotal
if $filename =~ /\0/u 2 39 41
9860  
9861 # Strip any path separators the browser might include.
9862 41 ($filename) = $filename =~ m{([^/\\]+)\z};
9863  
9864 # A dot-folder or dot-file holds some program's settings (~/.config, a
9865 # .vscode/settings.json), which a .json export could replace. The folder
9866 # list the panel offers (GET /api/dirs) leaves them out too.
9867 # The checks read the resolved folder; a refusal names the one the reader
9868 # asked for, as every other message does (macOS's tempdir is under /var,
9869 # a link to /private/var, so the two differ there).
9870 41 my $asked = Mojo::File->new($dir);
9871 41 ▶ my @names = (File::Spec->splitdir($dest_dir->to_string), $filename // '');
Condition100%2/2
$filename // ""
l!l
383
MC/DC100%1/1
$filename // ""
$filename
Truth table100%2/2
A
A= $filename
Aresult
11
00
9872 41 ▶ if (grep { /\A\./ && $_ ne '.' && $_ ne '..' } @names) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {/\A\./u and $_ ne "." and $_ ne "..";} @names) 1 40 41
Condition100%6/6
/\A\./u && $_ ne '.' && $_ ne '..'
!ll&&!rl&&r
16311
/\A\./u and $_ ne "."
!ll&&!rl&&r
16212
MC/DC100%3/3
/\A\./u && $_ ne '.' && $_ ne '..'
/\A\./u $_ ne "." $_ ne '..'
Truth table100%4/4
A and B && C
A= /\A\./uB= $_ ne "."C= $_ ne '..'
ABCresult
0XX0
10X0
1100
1111
9873 1 ▶ return $self->render(
Condition50%1/2
$filename // ""
l!l
10
MC/DC0%0/1
$filename // ""
$filename
Truth table50%1/2
A
A= $filename
Aresult
11
00
9874 json => { error => $self->_i18n('error_hidden_target', $asked->child($filename // '')->to_string) },
9875 status => 403,
9876 );
9877 }
9878 40 my $format;
9879 40 ▶ if ($filename && $filename =~ /\.csv\z/i) { $format = 'csv'; }
Branch: 3 branches
BranchTrueFalseTotal
if ($filename and $filename =~ /\.csv\z/iu) { } 28 12 40
elsif ($filename and $filename =~ /\.sql\z/iu) { } 2 10 12
elsif ($filename and $filename =~ /\.json\z/iu) { } 1 9 10
Condition100%3/3
$filename and $filename =~ /\.csv\z/iu
!ll&&!rl&&r
3928
MC/DC100%2/2
$filename and $filename =~ /\.csv\z/iu
$filename $filename =~ /\.csv\z/iu
Truth table100%3/3
A and B
A= $filenameB= $filename =~ /\.csv\z/iu
ABresult
0X0
100
111
9880 2 ▶ elsif ($filename && $filename =~ /\.sql\z/i) { $format = 'sqlite'; }
Condition100%3/3
$filename and $filename =~ /\.sql\z/iu
!ll&&!rl&&r
372
MC/DC100%2/2
$filename and $filename =~ /\.sql\z/iu
$filename $filename =~ /\.sql\z/iu
Truth table100%3/3
A and B
A= $filenameB= $filename =~ /\.sql\z/iu
ABresult
0X0
100
111
9881 1 ▶ elsif ($filename && $filename =~ /\.json\z/i) { $format = 'json'; }
Condition100%3/3
$filename and $filename =~ /\.json\z/iu
!ll&&!rl&&r
361
MC/DC100%2/2
$filename and $filename =~ /\.json\z/iu
$filename $filename =~ /\.json\z/iu
Truth table100%3/3
A and B
A= $filenameB= $filename =~ /\.json\z/iu
ABresult
0X0
100
111
9882 else {
9883 9 return $self->render(
9884 json => { error => $self->_i18n('error_ext_required') },
9885 status => 415,
9886 );
9887 }
9888  
9889 31 my ($records, $columns, $left_label) = $self->_run_export_pipeline;
9890 31 ▶ return if $self->stash('_reduce_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_reduce_error") 3 28 31
9891 28 ▶ return $self->render(json => { error => 'Table not found' }, status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless $records 2 26 28
9892 unless $records;
9893  
9894 26 ($records, $columns) = _export_selection($self, $records, $columns);
9895  
9896 26 my $dest = $dest_dir->child($filename);
9897 # A link (or a folder, a pipe) already at the name is not replaced: written
9898 # through, a link inside the folders would put the export wherever it
9899 # points, outside file_roots or export_dirs, or into a dot-file.
9900 26 ▶ if (-l $dest || (-e $dest && !-f $dest)) {
Branch: 1 branch
BranchTrueFalseTotal
if (-l $dest or -e $dest and not -f $dest) 1 25 26
Condition66%4/6
-l $dest or -e $dest and not -f $dest
l!l&&r!l&&!r
1025
-e $dest and not -f $dest
!ll&&!rl&&r
2230
MC/DC33%1/3
-l $dest or -e $dest and not -f $dest
-l $dest -e $dest not -f $dest
Truth table75%3/4
A or B and not(C)
A= -l $destB= -e $destC= not -f $dest
ABCresult
1XX1
0111
00X0
0100
9901 1 return $self->render(json => { error => sprintf(_message_text('error_export_not_file'), $asked->child($filename)->to_string) }, status => 403);
9902 }
9903 25 my $tmp;
9904 25 my $ok = eval {
9905 25 ▶ my $bytes = $format eq 'csv' ? _serialize_csv($records, $columns)
Branch: 2 branches
BranchTrueFalseTotal
$format eq 'csv' ? : 22 3 25
$format eq 'json' ? : 1 2 3
9906 : $format eq 'json' ? _serialize_json($records, $columns)
9907 : $self->_write_sqlite_db($records, $columns);
9908 # Written beside it and renamed over it: a rename replaces whatever
9909 # is at the name, a link made since the check included, and never
9910 # follows it, and a reader never sees half a file.
9911 25 (my $fh, $tmp) = tempfile('.bi-export-XXXXXXXX', DIR => $dest_dir->to_string, UNLINK => 0);
9912 20 binmode $fh;
9913 20 ▶ print {$fh} $bytes or croak "$tmp: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $bytes or croak("${tmp}: $!") 20 0 20
9914 20 ▶ close $fh or croak "$tmp: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${tmp}: $!") 20 0 20
9915 # tempfile makes it 0600: give it the mode of the file it replaces, as
9916 # writing over that one did, or the mode a new file gets.
9917 20 my @old = stat $dest->to_string;
9918 20 ▶ chmod(@old ? $old[2] & oct('7777') : 0666 & ~umask(), $tmp);
Branch: 1 branch
BranchTrueFalseTotal
@old ? : 3 17 20
9919 20 ▶ rename $tmp, $dest->to_string or croak "$dest: $!";
Branch: 1 branch
BranchTrueFalseTotal
rename $tmp, $dest->to_string or croak("${dest}: $!") 20 0 20
9920 20 undef $tmp;
9921 20 1;
9922 };
9923 25 my $err = $@;
9924 25 ▶ unlink $tmp if defined $tmp;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tmp 0 25 25
9925 25 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 5 20 25
9926 json => { error => $self->_i18n('error_write_failed', _tidy_error($err)) },
9927 status => 500,
9928 ) unless $ok;
9929  
9930 20 $self->render(json => { saved => $dest->to_string });
9931 }
9932  
9933 =head2 dirs_api
9934  
9935 C<GET /api/dirs> -- Return a JSON directory listing for the export panel.
9936  
9937 =head3 API SPECIFICATION
9938  
9939 =head4 INPUT
9940  
9941 ?path= string Directory to list. Default: the first config export_dirs
9942 entry, else $HOME if it is inside file_roots, else the first
9943 root. Returns 404 when not a directory. Hidden entries
9944 (names starting with ".") are excluded.
9945  
9946 =head4 OUTPUT
9947  
9948 200 application/json
9949 {
9950 "path": "/abs/path",
9951 "parent": "/abs/parent" or null (at the filesystem root, or when the
9952 parent is outside file_roots or export_dirs),
9953 "dirs": [ { "name": "alpha", "path": "/abs/path/alpha" }, ... ]
9954 }
9955  
9956 403 application/json { "error": "..." } -- path outside file_roots or
9957 export_dirs, whether or not it
9958 exists
9959 404 application/json { "error": "Not a directory" }
9960  
9961 =head3 MESSAGES
9962  
9963 error_outside_roots, error_outside_export_dirs -- the 403 above.
9964  
9965 =head3 FORMAL SPECIFICATION
9966  
9967 dirs_api == lambda self .
9968 let dir = realpath(param('path') // first(export_dirs) // first_root) in
9969 pre inside(dir, file_roots) /\ inside(dir, export_dirs) /\ is_dir(dir)
9970 post render_json({ path: dir, parent: parent(dir), dirs: subdirs(dir) })
9971  
9972 =head3 EXAMPLE
9973  
9974 GET /api/dirs?path=/home/user -> {"path":"/home/user","parent":"/home","dirs":[...]}
9975  
9976 =cut
9977  
9978 10 ▶sub dirs_api ($self) {
Subroutine dirs_api: called CC=10 SCAR=23.3
Pod documented
9979 10 ▶ my $raw = $self->param('path') // (_export_dirs($self))[0] // _first_root($self);
Condition66%4/6
($self->param("path") // (_export_dirs($self))[0]) // _first_root($self)
l!l&&r!l&&!r
820
$self->param("path") // (_export_dirs($self))[0]
l!l&&r!l&&!r
802
MC/DC0%0/3
($self->param("path") // (_export_dirs($self))[0]) // _first_root($self)
$self->param("path") (_export_dirs($self))[0] _first_root($self)
Truth table50%2/4
A // B // C
A= $self->param("path")B= (_export_dirs($self))[0]C= _first_root($self)
ABCresult
1XX1
01X1
0011
0000
9980 10 ▶ if (my $refusal = _outside_roots($self, $raw) // _outside_export_dirs($self, $raw)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $refusal = _outside_roots($self, $raw) // _outside_export_dirs($self, $raw)) 1 9 10
Condition66%2/3
_outside_roots($self, $raw) // _outside_export_dirs($self, $raw)
l!l&&r!l&&!r
109
MC/DC50%1/2
_outside_roots($self, $raw) // _outside_export_dirs($self, $raw)
_outside_roots($self, $raw) _outside_export_dirs($self, $raw)
Truth table66%2/3
A // B
A= _outside_roots($self, $raw)B= _outside_export_dirs($self, $raw)
ABresult
1X1
011
000
9981 1 return $self->render(json => { error => $refusal }, status => 403);
9982 }
9983 9 my $dir = eval { Mojo::File->new($raw)->realpath };
9984 9 ▶ return $self->render(json => { error => 'Not a directory' }, status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir and -d $dir 3 6 9
Condition100%3/3
defined $dir and -d $dir
!ll&&!rl&&r
126
MC/DC100%2/2
defined $dir and -d $dir
defined $dir -d $dir
Truth table100%3/3
A and B
A= defined $dirB= -d $dir
ABresult
0X0
100
111
9985 unless defined $dir && -d $dir;
9986  
9987 6 my $listing = $self->_list_dir($dir, 0);
9988 6 my $parent = $dir->dirname;
9989 6 ▶ my $up = $parent->to_string ne $dir->to_string && !_outside_roots($self, $parent->to_string)
Condition66%4/6
$parent->to_string ne $dir->to_string && !_outside_roots($self, $parent->to_string) && !_outside_export_dirs($self, $parent->to_string)
!ll&&!rl&&r
105
$parent->to_string ne $dir->to_string and not _outside_roots($self, $parent->to_string)
!ll&&!rl&&r
105
MC/DC33%1/3
$parent->to_string ne $dir->to_string && !_outside_roots($self, $parent->to_string) && !_outside_export_dirs($self, $parent->to_string)
$parent->to_string ne $dir->to_string not _outside_roots($self, $parent->to_string) !_outside_export_dirs($self, $parent->to_string)
Truth table50%2/4
A and not(B) && not(C)
A= $parent->to_string ne $dir->to_stringB= not _outside_roots($self, $parent->to_string)C= !_outside_export_dirs($self, $parent->to_string)
ABCresult
0XX0
10X0
1100
1111
9990 && !_outside_export_dirs($self, $parent->to_string);
9991  
9992 $self->render(json => {
9993 path => $dir->to_string,
9994 parent => ($up ? $parent->to_string : undef),
9995 dirs => $listing->{dirs},
9996 6 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
$up ? : 5 1 6
9997 }
9998  
9999 =head2 stat_api
10000  
10001 C<GET /api/stat> -- Return filesystem metadata for a file path.
10002  
10003 Used by the home page tooltip to show modification time and size for recently
10004 opened files without a page reload.
10005  
10006 =head3 API SPECIFICATION
10007  
10008 =head4 INPUT
10009  
10010 ?path= string Absolute path to query. Returns HTTP 400 when absent.
10011  
10012 =head4 OUTPUT
10013  
10014 200 application/json (file exists)
10015 { "exists": true, "path": "/resolved/path", "mtime": 1700000000, "size": 4096 }
10016  
10017 200 application/json (file does not exist)
10018 { "exists": false, "path": "/original/path" }
10019  
10020 400 application/json { "error": "\"path\" parameter is required" }
10021  
10022 C<mtime> is Unix epoch seconds. C<size> is bytes. A missing/unresolvable
10023 path returns HTTP 200 with C<exists: false> (not 404) so the UI can
10024 distinguish "file was deleted" from a request error.
10025  
10026 =head3 MESSAGES
10027  
10028 error_path_required -- the "path" query parameter was not supplied.
10029  
10030 =head3 FORMAL SPECIFICATION
10031  
10032 stat_api == lambda self .
10033 let path = param('path') in
10034 pre path /= undef
10035 let file = realpath(path) in
10036 post if is_file(file) then
10037 render_json({ exists: true, mtime: mtime(file), size: size(file) })
10038 else render_json({ exists: false })
10039  
10040 =head3 EXAMPLE
10041  
10042 GET /api/stat?path=/data/sales.csv
10043 -> { "exists": true, "path": "/data/sales.csv", "mtime": 1700000000, "size": 1234 }
10044  
10045 GET /api/stat?path=/deleted.csv
10046 -> { "exists": false, "path": "/deleted.csv" }
10047  
10048 =cut
10049  
10050 22 ▶sub stat_api ($self) {
Subroutine stat_api: called CC=9 SCAR=22.0
Pod documented
10051 22 my $path = $self->param('path');
10052 22 ▶ unless (defined $path && length $path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $path and length $path) 6 16 22
Condition100%3/3
defined $path and length $path
!ll&&!rl&&r
5116
MC/DC100%2/2
defined $path and length $path
defined $path length $path
Truth table100%3/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
10053 6 return $self->render(
10054 json => { error => $self->_i18n('error_path_required') },
10055 status => 400,
10056 );
10057 }
10058  
10059 16 my $file = eval { Mojo::File->new($path)->realpath };
10060 # Restrict to files with a supported data extension so stat_api cannot be
10061 # used as a filesystem oracle to probe /etc/shadow, /root/.ssh/, etc.; and,
10062 # with file_roots, to files inside them, said the same way.
10063 16 ▶ return $self->render(json => { exists => \0, path => $path })
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file and -f $file and $file->basename =~ /$EXT_RE/u and not _outside_roots($self, $path) 8 8 16
Condition88%8/9
defined $file and -f $file and $file->basename =~ /$EXT_RE/u and not _outside_roots($self, $path)
!ll&&!rl&&r
808
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
!ll&&!rl&&r
718
defined $file and -f $file
!ll&&!rl&&r
349
MC/DC75%3/4
defined $file and -f $file and $file->basename =~ /$EXT_RE/u and not _outside_roots($self, $path)
defined $file -f $file $file->basename =~ /$EXT_RE/u not _outside_roots($self, $path)
Truth table80%4/5
A and B and C and not(D)
A= defined $fileB= -f $fileC= $file->basename =~ /$EXT_RE/uD= not _outside_roots($self, $path)
ABCDresult
0XXX0
10XX0
110X0
11100
11111
10064 unless defined $file && -f $file && $file->basename =~ $EXT_RE && !_outside_roots($self, $path);
10065  
10066 8 my @s = stat $file->to_string;
10067  
10068 # For SQLite files, count user tables so the home-page tooltip can show
10069 # "SQLite database - N tables". Silently omit the count if the file is
10070 # not actually a SQLite file (e.g. a Berkeley DB .db file).
10071 8 my $table_count;
10072 8 ▶ if ($file->basename =~ /\.(?:sql|sqlite|sqlite3|db)\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file->basename =~ /\.(?:sql|sqlite|sqlite3|db)\z/iu) 1 7 8
10073 1 eval {
10074 1 require Database::Join::Catalog;
10075 1 $table_count = scalar @{ Database::Join::Catalog->tables(file => $file->to_string) };
10076 };
10077 }
10078  
10079 8 ▶ $self->render(json => {
Branch: 1 branch
BranchTrueFalseTotal
defined $table_count ? : 1 7 8
10080 exists => \1,
10081 path => $file->to_string,
10082 mtime => $s[9],
10083 size => $s[7],
10084 (defined $table_count ? (table_count => $table_count) : ()),
10085 });
10086 }
10087  
10088 =head2 upload_file
10089  
10090 C<POST /upload> -- Accept a drag-and-dropped data file and return a redirect URL.
10091  
10092 The file is saved under its original filename in a managed subdirectory of
10093 C<< <uploads_dir>/ >>. The subdirectory name is randomised so that
10094 concurrent uploads of files with the same name do not collide.
10095  
10096 =head3 API SPECIFICATION
10097  
10098 =head4 INPUT
10099  
10100 Multipart form upload, field name: C<file>.
10101  
10102 file upload Supported extensions: csv, db, sql, xml, tsv, psv.
10103  
10104 =head4 OUTPUT
10105  
10106 200 application/json { "url": "/open?path=/abs/path/file.csv", "path": "/abs/path/file.csv" }
10107 400 application/json { "error": "No file received" }
10108 413 application/json { "error": "File too large to upload (limit: 50 MB)" }
10109 415 application/json { "error": "Unsupported file type. Accepted: ..." }
10110 500 application/json { "error": "Could not save uploaded file" }
10111  
10112 =head3 MESSAGES
10113  
10114 error_upload_none -- no file was received in the multipart upload.
10115 error_upload_ext -- the file's extension is not in the supported list.
10116 error_upload_too_large -- the upload body exceeded MAX_UPLOAD_MIB (50 MiB).
10117 error_upload_save -- move_to failed or the destination file was not
10118 created (I/O error, full disk, permission error).
10119  
10120 =head3 IMPLEMENTATION NOTES
10121  
10122 The C<move_to> call is wrapped with the C<eval { ...; 1 }> idiom (not
10123 C<eval {}> + C<if ($@)>). Mojolicious dispatch and DESTROY-phase evals can
10124 leave C<$@> set before the action runs; checking C<if ($@)> after a new eval
10125 may fire falsely on that stale value. C<eval { move_to(); 1 }> returns 1 on
10126 success and C<undef> on exception, so the result is independent of any prior
10127 C<$@> value.
10128  
10129 =head3 FORMAL SPECIFICATION
10130  
10131 upload_file == lambda self .
10132 let upload = req.upload('file') in
10133 pre upload /= undef /\ basename(upload.filename) =~ EXT_RE
10134 /\ NOT req->is_limit_exceeded
10135 /\ upload.size <= MAX_UPLOAD_BYTES
10136 let dest = uploads_dir/<random>/<filename> in
10137 let ok = eval { upload.move_to(dest); 1 } in
10138 pre ok /\ -f dest
10139 post render_json({ url: '/open?path=' ++ url_escape(dest), path: dest })
10140  
10141 =head3 EXAMPLE
10142  
10143 POST /upload (multipart: file=@sales.csv)
10144 -> { "url": "/open?path=%2F...%2Fsales.csv", "path": "/.../.uploads/abc123/sales.csv" }
10145  
10146 =cut
10147  
10148 34 ▶sub upload_file ($self) {
Subroutine upload_file: called CC=11 SCAR=24.0
Pod documented
10149 34 my $upload = $self->req->upload('file');
10150 34 ▶ unless ($upload && $upload->filename) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($upload and $upload->filename) 3 31 34
Condition66%2/3
$upload and $upload->filename
!ll&&!rl&&r
3031
MC/DC50%1/2
$upload and $upload->filename
$upload $upload->filename
Truth table66%2/3
A and B
A= $uploadB= $upload->filename
ABresult
0X0
100
111
10151 3 return $self->render(
10152 json => { error => $self->_i18n('error_upload_none') },
10153 status => 400,
10154 );
10155 }
10156  
10157 # Enforce upload size limit. max_request_size in startup() sets the
10158 # transport-layer cap, but Mojolicious still calls the controller when the
10159 # limit fires (with req->is_limit_exceeded true and partial content in the
10160 # upload asset). Check is_limit_exceeded first; fall through to an asset
10161 # size check as a belt-and-braces guard for any bytes that slipped through.
10162 31 ▶ if ($self->req->is_limit_exceeded || $upload->size > $MAX_UPLOAD_BYTES) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->req->is_limit_exceeded or $upload->size > $MAX_UPLOAD_BYTES) 2 29 31
Condition100%3/3
$self->req->is_limit_exceeded or $upload->size > $MAX_UPLOAD_BYTES
l!l&&r!l&&!r
1129
MC/DC100%2/2
$self->req->is_limit_exceeded or $upload->size > $MAX_UPLOAD_BYTES
$self->req->is_limit_exceeded $upload->size > $MAX_UPLOAD_BYTES
Truth table100%3/3
A or B
A= $self->req->is_limit_exceededB= $upload->size > $MAX_UPLOAD_BYTES
ABresult
1X1
011
000
10163 2 return $self->render(
10164 json => { error => $self->_i18n('error_upload_too_large', $MAX_UPLOAD_MIB) },
10165 status => 413,
10166 );
10167 }
10168  
10169 # /s so .* matches \n; a percent-decoded newline inside a browser filename
10170 # must not silently truncate the directory-strip, leaving "dir\ncomponent" in.
10171 29 (my $filename = $upload->filename) =~ s{.*[/\\]}{}s;
10172 29 ▶ unless ($filename && $filename =~ $EXT_RE) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($filename and $filename =~ /$EXT_RE/u) 3 26 29
Condition66%2/3
$filename and $filename =~ /$EXT_RE/u
!ll&&!rl&&r
0326
MC/DC50%1/2
$filename and $filename =~ /$EXT_RE/u
$filename $filename =~ /$EXT_RE/u
Truth table66%2/3
A and B
A= $filenameB= $filename =~ /$EXT_RE/u
ABresult
0X0
100
111
10173 3 return $self->render(
10174 json => { error => $self->_i18n('error_upload_ext') },
10175 status => 415,
10176 );
10177 }
10178  
10179 # Store uploads in <uploads_dir>/<random_subdir>/<original_filename>. The
10180 # staging directory comes from the app (config uploads_dir, default
10181 # <app_home>/.uploads) so a deployment can point it at a writable disc and
10182 # a test can keep its uploads out of the directory another process clears.
10183 # Using the original filename is essential: Database::Abstraction derives
10184 # the table name from the file stem, so "sales.csv" must stay "sales.csv".
10185 # The random subdirectory prevents collisions from concurrent same-name uploads.
10186 26 my $uploads_base = $self->app->_uploads_dir;
10187 26 my $sub_dir = eval {
10188 26 ▶ $uploads_base->make_path unless -d $uploads_base;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $uploads_base 0 26 26
10189 26 tempdir(DIR => $uploads_base->to_string, CLEANUP => 0);
10190 };
10191 26 ▶ unless (defined $sub_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $sub_dir) 1 25 26
10192 1 $self->app->log->error("Cannot stage an upload in $uploads_base: " . _tidy_error($@));
10193 1 return $self->render(
10194 json => { error => $self->_i18n('error_upload_save') },
10195 status => 500,
10196 );
10197 }
10198 25 my $dest = Mojo::File->new($sub_dir)->child($filename)->to_string;
10199  
10200 # move_to returns the destination Mojo::File on success; croaks on I/O
10201 # failure. Wrap in eval so a disk error becomes a 500 JSON response
10202 # rather than a bare Mojolicious exception page.
10203 # Use the "eval { ...; 1 }" idiom: $ok is undef only when THIS eval
10204 # threw, avoiding false positives from a stale $@ left by Mojo's
10205 # internal dispatch code that runs before the controller action.
10206 25 my $ok = eval { $upload->move_to($dest); 1 };
10207 25 ▶ if (!$ok || !-f $dest) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok and -f $dest) 3 22 25
Condition100%3/3
$ok and -f $dest
!ll&&!rl&&r
2122
MC/DC100%2/2
$ok and -f $dest
$ok -f $dest
Truth table100%3/3
A and B
A= $okB= -f $dest
ABresult
0X0
100
111
10208 3 remove_tree($sub_dir);
10209 3 return $self->render(
10210 json => { error => $self->_i18n('error_upload_save') },
10211 status => 500,
10212 );
10213 }
10214  
10215 22 $self->render(json => {
10216 url => '/open?path=' . url_escape($dest),
10217 path => $dest,
10218 });
10219 }
10220  
10221 9 ▶sub clear_uploads ($self) {
Subroutine clear_uploads: called CC=3 SCAR=11.9
Pod documented
10222 9 my $uploads_dir = $self->app->_uploads_dir;
10223  
10224 9 ▶ return $self->render(json => { freed => 0, count => 0 })
Branch: 1 branch
BranchTrueFalseTotal
unless -d $uploads_dir 0 9 9
10225 unless -d $uploads_dir;
10226  
10227 9 my ($freed, $count) = (0, 0);
10228  
10229 # Each upload lands in <uploads_dir>/<random_subdir>/<filename>.
10230 # Iterate the subdirs, tally file sizes, then remove each subdir tree.
10231 9 my $ok = eval {
10232 8 ▶ $uploads_dir->list({ dir => 1 })->each(sub {
Subroutine __ANON__: called CC=4 SCAR=17.5
10233 8 my ($entry) = @_;
10234 8 ▶ if (-d $entry) {
Branch: 2 branches
BranchTrueFalseTotal
if (-d $entry) { } 8 0 8
elsif (-f $entry) { } 0 0 0
10235 8 ▶ $entry->list->each(sub {
Subroutine __ANON__: called CC=3 SCAR=11.4
10236 8 my ($file) = @_;
10237 8 ▶ return unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 0 8 8
10238 8 ▶ $freed += (-s $file) // 0;
Condition50%1/2
-s $file // 0
l!l
80
MC/DC0%0/1
-s $file // 0
-s $file
Truth table50%1/2
A
A= -s $file
Aresult
11
00
10239 8 $count++;
10240 8 });
10241 8 $entry->remove_tree;
10242 } elsif (-f $entry) {
10243 0 ▶ $freed += (-s $entry) // 0;
Condition0%0/2
-s $entry // 0
l!l
00
MC/DC0%0/1
-s $entry // 0
-s $entry
Truth table0%0/2
A
A= -s $entry
Aresult
11
00
10244 0 $count++;
10245 0 unlink $entry->to_string;
10246 }
10247 9 });
10248 7 1;
10249 };
10250 9 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 2 7 9
10251 2 $self->app->log->error("Cannot clear $uploads_dir: " . _tidy_error($@));
10252 2 return $self->render(json => { error => $self->_i18n('error_uploads_clear') }, status => 500);
10253 }
10254  
10255 7 $self->render(json => { freed => $freed, count => $count });
10256 }
10257  
10258 # graph_view
10259 #
10260 # Purpose: Render a D3.js line chart from the current data pipeline.
10261 # Entry: Query params identical to /join (l=, j=, c=, f=, d=) plus:
10262 # x=<column> -- X-axis column name
10263 # y=<column> -- Y-axis column name (values must be numeric)
10264 # back=<url> -- URL for the "Back to table" link (set by JS)
10265 # Exit: Emits a TT-rendered HTML page with a brush-to-zoom HTML::D3 snippet.
10266 # Each data point carries an "extra" hash of every column not used
10267 # as the X or Y axis; HTML::D3 displays these in the hover tooltip.
10268 # A "Reset zoom" button appears after the user brushes to zoom in.
10269 # Returns HTTP 400 for missing/invalid column names, 404 if the
10270 # data source cannot be opened, 200 with an error message when
10271 # no plottable rows exist.
10272 117 ▶sub graph_view ($self) {
Subroutine graph_view: called CC=86 SCAR=62.8
Pod documented
10273 117 ▶ my $x_col = $self->param('x') // '';
Condition100%2/2
$self->param("x") // ""
l!l
1143
MC/DC100%1/1
$self->param("x") // ""
$self->param("x")
Truth table100%2/2
A
A= $self->param("x")
Aresult
11
00
10274 117 ▶ my $y_col = $self->param('y') // '';
Condition100%2/2
$self->param("y") // ""
l!l
1134
MC/DC100%1/1
$self->param("y") // ""
$self->param("y")
Truth table100%2/2
A
A= $self->param("y")
Aresult
11
00
10275 117 ▶ my $series_col = $self->param('series') // '';
Condition100%2/2
$self->param("series") // ""
l!l
3114
MC/DC100%1/1
$self->param("series") // ""
$self->param("series")
Truth table100%2/2
A
A= $self->param("series")
Aresult
11
00
10276 117 ▶ my $agg_fn = lc($self->param('agg') // '');
Condition100%2/2
$self->param("agg") // ""
l!l
1116
MC/DC100%1/1
$self->param("agg") // ""
$self->param("agg")
Truth table100%2/2
A
A= $self->param("agg")
Aresult
11
00
10277 117 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition100%2/2
_safe_back_url($self->param("back")) // "/"
l!l
2115
MC/DC100%1/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table100%2/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
10278 117 my $back2 = _safe_back_url($self->param('back2'));
10279 117 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
0117
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
10280  
10281 117 ▶ return $self->render(text => 'Missing x or y column parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col and length $y_col 6 111 117
Condition100%3/3
length $x_col and length $y_col
!ll&&!rl&&r
51111
MC/DC100%2/2
length $x_col and length $y_col
length $x_col length $y_col
Truth table100%3/3
A and B
A= length $x_colB= length $y_col
ABresult
0X0
100
111
10282 unless length($x_col) && length($y_col);
10283  
10284 # ?agg= is the measure vocabulary the pivot and the stats page already use,
10285 # with no new names: a misspelt one is refused here rather than drawn as
10286 # nothing. Absent, this route behaves exactly as it always has.
10287 111 ▶ if (length $agg_fn && !_measure_fn_ok($agg_fn)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $agg_fn and not _measure_fn_ok($agg_fn)) 1 110 111
Condition66%2/3
length $agg_fn and not _measure_fn_ok($agg_fn)
!ll&&!rl&&r
11001
MC/DC50%1/2
length $agg_fn and not _measure_fn_ok($agg_fn)
length $agg_fn not _measure_fn_ok($agg_fn)
Truth table66%2/3
A and not(B)
A= length $agg_fnB= not _measure_fn_ok($agg_fn)
ABresult
0X0
100
111
10288 1 return $self->render(
10289 text => $self->_i18n('error_agg_fn', $agg_fn, join(' ', @MEASURE_FNS)),
10290 status => 400,
10291 );
10292 }
10293  
10294 110 my ($src, $records, $columns) = $self->_run_pipeline_source;
10295 110 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 4 106 110
10296 unless defined $records;
10297  
10298 106 my $span = $self->_span_calc_spec($columns, 'x');
10299 106 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 4 102 106
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
10204
MC/DC50%1/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table66%2/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
10300  
10301 102 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
10302 102 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 102 102
10303 102 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 100 102
10304  
10305 # Pre-filter before building pairs, same as _run_export_pipeline.
10306 100 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 2 98 100
10307  
10308 98 my %col_set = map { $_ => 1 } @{$columns};
10309 return $self->render(text => "Column not found: $x_col", status => 400)
10310 98 ▶ unless $col_set{$x_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$x_col} 3 95 98
10311 return $self->render(text => "Column not found: $y_col", status => 400)
10312 95 ▶ unless $col_set{$y_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$y_col} 3 92 95
10313 92 ▶ if (length $series_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col) 3 89 92
10314 return $self->render(text => "Column not found: $series_col", status => 400)
10315 3 ▶ unless $col_set{$series_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$series_col} 1 2 3
10316 }
10317  
10318 # The x axis is the dimension span= buckets.
10319 91 ▶ $x_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 91 91
10320  
10321 # --- Aggregated path: ?agg= plots one point per group of the x axis rather
10322 # than one per row, which is what turns a bucketed x into a timechart. ---
10323 91 ▶ if (length $agg_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $agg_fn) 0 91 91
10324 0 my $m = _visual_measure($agg_fn, $y_col);
10325 0 ▶ return $self->render(text => $m->{error}, status => 400) if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 0 0
10326  
10327 my $agg_rows = $self->_grouped_totals(
10328 { source => $src, records => $records },
10329 {
10330 by => [ length($series_col) ? ($x_col, $series_col) : ($x_col) ],
10331 fn => $m->{fn},
10332 val => $m->{val},
10333 0 ▶ as => 'value',
Branch: 1 branch
BranchTrueFalseTotal
length $series_col ? : 0 0 0
10334 },
10335 );
10336  
10337 0 my (%value_of, %series_seen, @series_order, %bucket_seen, @bucket_order);
10338 0 for my $row (@$agg_rows) {
10339 0 ▶ my $bucket = _decode_cell($row->{$x_col} // '');
Condition0%0/2
$row->{$x_col} // ""
l!l
00
MC/DC0%0/1
$row->{$x_col} // ""
$row->{$x_col}
Truth table0%0/2
A
A= $row->{$x_col}
Aresult
11
00
10340 0 ▶ next unless length $bucket;
Branch: 1 branch
BranchTrueFalseTotal
unless length $bucket 0 0 0
10341 0 ▶ push @bucket_order, $bucket unless $bucket_seen{$bucket}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $bucket_seen{$bucket}++ 0 0 0
10342 0 ▶ my $name = length($series_col) ? _decode_cell($row->{$series_col} // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
length $series_col ? : 0 0 0
Condition0%0/2
$row->{$series_col} // ""
l!l
00
MC/DC0%0/1
$row->{$series_col} // ""
$row->{$series_col}
Truth table0%0/2
A
A= $row->{$series_col}
Aresult
11
00
10343 0 ▶ next if length($series_col) && !length $name;
Branch: 1 branch
BranchTrueFalseTotal
if length $series_col and not length $name 0 0 0
Condition0%0/3
length $series_col and not length $name
!ll&&!rl&&r
000
MC/DC0%0/2
length $series_col and not length $name
length $series_col not length $name
Truth table0%0/3
A and not(B)
A= length $series_colB= not length $name
ABresult
0X0
100
111
10344 0 ▶ push @series_order, $name unless $series_seen{$name}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $series_seen{$name}++ 0 0 0
10345 0 $value_of{$bucket}{$name} = $row->{value};
10346 }
10347  
10348 # Buckets in label order: the ISO labels a time bucket produces sort
10349 # chronologically as strings, which is why they are ISO.
10350 0 my @buckets = sort @bucket_order;
10351 0 my @series = sort @series_order;
10352 0 ▶ my $title = "$m->{label} by $x_col" . (length($series_col) ? " and $series_col" : '');
Branch: 1 branch
BranchTrueFalseTotal
length $series_col ? : 0 0 0
10353  
10354 0 require HTML::D3;
10355 0 my ($chart_html, $point_count, @series_data);
10356 0 ▶ if (length $series_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col) { } 0 0 0
10357 @series_data = map {
10358 0 my $name = $_;
10359 my @points = map {
10360 0 defined $value_of{$_}{$name}
10361 0 ▶ ? { label => $_, value => $value_of{$_}{$name} } : ()
Branch: 1 branch
BranchTrueFalseTotal
defined $value_of{$_}{$name} ? : 0 0 0
10362 } @buckets;
10363 0 ▶ @points ? { name => $name, data => \@points } : ();
Branch: 1 branch
BranchTrueFalseTotal
@points ? : 0 0 0
10364 } @series;
10365 0 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @series_data 0 0 0
10366 text => 'No plottable data: no rows have valid numeric values in the Y column.',
10367 status => 200,
10368 ) unless @series_data;
10369 0 $point_count = scalar @series_data;
10370 $chart_html = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
10371 0 ->render_multi_series_line_chart_snippet(\@series_data, { animated => 1 })->{html};
10372 } else {
10373 my @pairs = map {
10374 0 ▶ defined $value_of{$_}{''} ? [ $_, $value_of{$_}{''} ] : ()
Branch: 1 branch
BranchTrueFalseTotal
defined $value_of{$_}{''} ? : 0 0 0
10375 } @buckets;
10376 0 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @pairs 0 0 0
10377 text => 'No plottable data: no rows have valid numeric values in the Y column.',
10378 status => 200,
10379 ) unless @pairs;
10380 0 $point_count = scalar @pairs;
10381 $chart_html = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
10382 0 ->render_zoomable_line_chart_snippet(\@pairs, { animated => 1 })->{html};
10383 }
10384 0 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 0 0
10385  
10386 my %chart_spec = (
10387 kind => 'graph',
10388 title => $title,
10389 encode => {
10390 x => $x_col, y => $y_col,
10391 (length($series_col) ? (series => $series_col) : ()),
10392 agg => $m->{fn},
10393 },
10394 0 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
length $series_col ? : 0 0 0
10395 0 my ($platform, $language) = $self->_resolve_template;
10396 0 my ($source_url, $source_accessed) = $self->_url_attribution;
10397 0 ▶ return $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 0 0
$back2 ? : 0 0 0
Condition0%0/5
$back2 // $back
l!l&&r!l&&!r
000
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table0%0/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
10398 handler => 'tt',
10399 template => "$platform/$language/graph",
10400 format => 'html',
10401 title => $title,
10402 chart_html => $chart_html,
10403 chart => \%chart_spec,
10404 chart_json => $self->_chart_json(\%chart_spec),
10405 back_url => ($back2 // $back),
10406 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10407 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10408 point_count => $point_count,
10409 source_url => $source_url,
10410 source_accessed => $source_accessed,
10411 language => $language,
10412 );
10413 }
10414  
10415 # --- Multi-series path: ?series=<col> groups records into one line per value ---
10416 91 ▶ if (length $series_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col) 2 89 91
10417 2 my %by_series;
10418 my @series_order;
10419 2 for my $row (@{$records}) {
10420 12 ▶ my $x = $row->{$x_col} // '';
Condition50%1/2
$row->{$x_col} // ""
l!l
120
MC/DC0%0/1
$row->{$x_col} // ""
$row->{$x_col}
Truth table50%1/2
A
A= $row->{$x_col}
Aresult
11
00
10421 12 ▶ my $y = $row->{$y_col} // '';
Condition50%1/2
$row->{$y_col} // ""
l!l
120
MC/DC0%0/1
$row->{$y_col} // ""
$row->{$y_col}
Truth table50%1/2
A
A= $row->{$y_col}
Aresult
11
00
10422 12 ▶ my $grp = $row->{$series_col} // '';
Condition50%1/2
$row->{$series_col} // ""
l!l
120
MC/DC0%0/1
$row->{$series_col} // ""
$row->{$series_col}
Truth table50%1/2
A
A= $row->{$series_col}
Aresult
11
00
10423 12 ▶ next unless length($x) && length($y) && length($grp);
Branch: 1 branch
BranchTrueFalseTotal
unless length $x and length $y and length $grp 0 12 12
Condition33%2/6
length $x and length $y and length $grp
!ll&&!rl&&r
0012
length $x and length $y
!ll&&!rl&&r
0012
MC/DC0%0/3
length $x and length $y and length $grp
length $x length $y length $grp
Truth table25%1/4
A and B and C
A= length $xB= length $yC= length $grp
ABCresult
0XX0
10X0
1100
1111
10424 12 my $yn = _numeric_cell($y);
10425 12 ▶ next unless defined $yn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $yn 0 12 12
10426 12 ▶ unless (exists $by_series{$grp}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $by_series{$grp}) 4 8 12
10427 4 push @series_order, $grp;
10428 4 $by_series{$grp} = [];
10429 }
10430 12 push @{$by_series{$grp}}, { label => _decode_cell($x), value => $yn };
10431 }
10432  
10433 2 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @series_order 0 2 2
10434 text => 'No plottable data: no rows have valid numeric values in the Y column.',
10435 status => 200,
10436 ) unless @series_order;
10437  
10438 2 my @series_data = map { { name => $_, data => $by_series{$_} } } @series_order;
10439  
10440 2 my ($source_url, $source_accessed) = $self->_url_attribution;
10441  
10442 2 require HTML::D3;
10443 2 my $title = "$y_col vs $x_col by $series_col";
10444 2 my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
10445 ->render_multi_series_line_chart_snippet(\@series_data, { animated => 1 });
10446  
10447 2 my $chart_html = $snippet->{html};
10448 2 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 2 2
10449  
10450 2 my %chart_spec = (
10451 kind => 'graph',
10452 title => $title,
10453 encode => { x => $x_col, y => $y_col, series => $series_col },
10454 );
10455 2 my ($platform, $language) = $self->_resolve_template;
10456 2 ▶ return $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 2 2
$back2 ? : 0 2 2
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
020
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
10457 handler => 'tt',
10458 template => "$platform/$language/graph",
10459 format => 'html',
10460 title => $title,
10461 chart_html => $chart_html,
10462 chart => \%chart_spec,
10463 chart_json => $self->_chart_json(\%chart_spec),
10464 back_url => ($back2 // $back),
10465 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10466 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10467 point_count => scalar @series_order,
10468 source_url => $source_url,
10469 source_accessed => $source_accessed,
10470 language => $language,
10471 );
10472 }
10473  
10474 # --- Single-series path (original behaviour when ?series= is absent) ---
10475  
10476 # Extract [label, value] pairs; skip rows where Y is missing or non-numeric.
10477 89 my @pairs;
10478 89 for my $row (@{$records}) {
10479 503 ▶ my $x = $row->{$x_col} // '';
Condition50%1/2
$row->{$x_col} // ""
l!l
5030
MC/DC0%0/1
$row->{$x_col} // ""
$row->{$x_col}
Truth table50%1/2
A
A= $row->{$x_col}
Aresult
11
00
10480 503 ▶ my $y = $row->{$y_col} // '';
Condition100%2/2
$row->{$y_col} // ""
l!l
5003
MC/DC100%1/1
$row->{$y_col} // ""
$row->{$y_col}
Truth table100%2/2
A
A= $row->{$y_col}
Aresult
11
00
10481 503 ▶ next unless length($x) && length($y);
Branch: 1 branch
BranchTrueFalseTotal
unless length $x and length $y 3 500 503
Condition66%2/3
length $x and length $y
!ll&&!rl&&r
03500
MC/DC50%1/2
length $x and length $y
length $x length $y
Truth table66%2/3
A and B
A= length $xB= length $y
ABresult
0X0
100
111
10482 500 my $yn = _numeric_cell($y);
10483 500 ▶ next unless defined $yn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $yn 10 490 500
10484 490 ▶ my %extra = map { $_ => _decode_cell($row->{$_}) } grep { $_ ne $x_col && $_ ne $y_col } @{$columns};
Condition100%3/3
$_ ne $x_col && $_ ne $y_col
!ll&&!rl&&r
4904901868
MC/DC100%2/2
$_ ne $x_col && $_ ne $y_col
$_ ne $x_col $_ ne $y_col
Truth table100%3/3
A && B
A= $_ ne $x_colB= $_ ne $y_col
ABresult
0X0
100
111
10485 490 push @pairs, [_decode_cell($x), $yn, \%extra];
10486 }
10487  
10488 89 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @pairs 4 85 89
10489 text => 'No plottable data: no rows have valid numeric values in the Y column.',
10490 status => 200,
10491 ) unless @pairs;
10492  
10493 85 my @y_vals = map { $_->[1] } @pairs;
10494 85 my ($min_y, $max_y, $avg_y);
10495  
10496 # Try aggregate() push path for the global min/max/avg reference lines.
10497 # Falls back to List::Util on the already-extracted @y_vals when push is
10498 # not available (no source, filters active, or non-pushable column).
10499 85 my @f_specs = grep { /\S/ } @{ _filter_specs($self) };
10500 85 my $has_filter = !!@f_specs;
10501 85 ▶ if (!$ENV{BI_FORCE_PERL_AGG} && $src && !$has_filter && !_dedup_requested($self)
Branch: 1 branch
BranchTrueFalseTotal
if (not $ENV{"BI_FORCE_PERL_AGG"} and $src and not $has_filter and not _dedup_requested($self) and _measure_pushable($src, "avg", $y_col, $records)) 75 10 85
Condition83%10/12
not $ENV{"BI_FORCE_PERL_AGG"} and $src and not $has_filter and not _dedup_requested($self) and _measure_pushable($src, "avg", $y_col, $records)
!ll&&!rl&&r
4675
not $ENV{"BI_FORCE_PERL_AGG"} and $src and not $has_filter and not _dedup_requested($self)
!ll&&!rl&&r
4081
not $ENV{"BI_FORCE_PERL_AGG"} and $src and not $has_filter
!ll&&!rl&&r
1381
not $ENV{"BI_FORCE_PERL_AGG"} and $src
!ll&&!rl&&r
0184
MC/DC60%3/5
not $ENV{"BI_FORCE_PERL_AGG"} and $src and not $has_filter and not _dedup_requested($self) and _measure_pushable($src, "avg", $y_col, $records)
not $ENV{"BI_FORCE_PERL_AGG"} $src not $has_filter not _dedup_requested($self) _measure_pushable($src, "avg", $y_col, $records)
Truth table66%4/6
not(A) and B and not(C) and not(D) and E
A= not $ENV{"BI_FORCE_PERL_AGG"}B= $srcC= not $has_filterD= not _dedup_requested($self)E= _measure_pushable($src, "avg", $y_col, $records)
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
10502 && _measure_pushable($src, 'avg', $y_col, $records)) {
10503 75 my $ref = eval {
10504 75 $src->aggregate(
10505 by => [],
10506 measures => [
10507 _measure('min', $y_col, 'lo'),
10508 _measure('max', $y_col, 'hi'),
10509 _measure('avg', $y_col, 'mean'),
10510 ],
10511 )
10512 };
10513 75 ▶ if (!$@ && $ref && @$ref) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $@ and $ref and @$ref) 75 0 75
Condition33%2/6
not $@ and $ref and @$ref
!ll&&!rl&&r
0075
not $@ and $ref
!ll&&!rl&&r
0075
MC/DC0%0/3
not $@ and $ref and @$ref
not $@ $ref @$ref
Truth table25%1/4
not(A) and B and C
A= not $@B= $refC= @$ref
ABCresult
0XX0
10X0
1100
1111
10514 75 $min_y = $ref->[0]{lo};
10515 75 $max_y = $ref->[0]{hi};
10516 75 $avg_y = $ref->[0]{mean};
10517 }
10518 }
10519 # Perl fallback: compute from the already-stripped @y_vals.
10520 85 ▶ unless (defined $min_y) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $min_y) 10 75 85
10521 10 require Statistics::Lite;
10522 10 $min_y = Statistics::Lite::min(@y_vals);
10523 10 $max_y = Statistics::Lite::max(@y_vals);
10524 10 $avg_y = Statistics::Lite::mean(@y_vals);
10525 }
10526  
10527 # The trend line: a least-squares fit of Y against the point's place on the
10528 # axis. The axis is a d3.scalePoint, which spaces the points evenly whatever
10529 # their labels say, so the place (0, 1, 2, ...) is what makes the fit a
10530 # straight line on this chart. The page refits the points in view after a
10531 # zoom, the same way; this is the whole chart's.
10532 85 my $trend = _trend_line(\@y_vals);
10533  
10534 85 my ($source_url, $source_accessed) = $self->_url_attribution;
10535  
10536 85 require HTML::D3;
10537 85 my $title = "$y_col vs $x_col";
10538 85 my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
10539 ->render_zoomable_line_chart_snippet(\@pairs, { animated => 1 });
10540  
10541 85 my $chart_html = $snippet->{html};
10542 85 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 85 85
10543  
10544 85 my %chart_spec = (
10545 kind => 'graph',
10546 title => $title,
10547 encode => { x => $x_col, y => $y_col },
10548 );
10549 85 my ($platform, $language) = $self->_resolve_template;
10550 $self->render(
10551 handler => 'tt',
10552 template => "$platform/$language/graph",
10553 format => 'html',
10554 title => $title,
10555 chart_html => $chart_html,
10556 chart => \%chart_spec,
10557 chart_json => $self->_chart_json(\%chart_spec),
10558 back_url => ($back2 // $back),
10559 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10560 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10561 point_count => scalar @pairs,
10562 ref_min_y => $min_y,
10563 ref_max_y => $max_y,
10564 ref_avg_y => sprintf('%.4g', $avg_y),
10565 ($trend ? (
10566 trend_slope => sprintf('%.4g', $trend->{slope}),
10567 trend_intercept => sprintf('%.6g', $trend->{intercept}),
10568 85 ▶ trend_r2 => sprintf('%.2f', $trend->{r_squared}),
Branch: 3 branches
BranchTrueFalseTotal
$back2 ? : 0 85 85
$back2 ? : 0 85 85
$trend ? : 85 0 85
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0850
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
10569 ) : ()),
10570 source_url => $source_url,
10571 source_accessed => $source_accessed,
10572 language => $language,
10573 );
10574 }
10575  
10576 # _trend_line(\@y) -> { slope, intercept, r_squared } | undef
10577 #
10578 # The least-squares line through the values, each at its place 0, 1, 2, ...
10579 # (Statistics::LineFit). undef for fewer than two values, or when the fit
10580 # fails. A flat series has slope 0 and an R squared of 1 (LineFit's answer:
10581 # the line passes through every point).
10582 85 ▶sub _trend_line {
Subroutine _trend_line: called CC=7 SCAR=22.0
10583 85 my ($ys) = @_;
10584 85 ▶ return undef unless ref $ys eq 'ARRAY' && @$ys >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ys eq "ARRAY" and @$ys >= 2 0 85 85
Condition33%1/3
ref $ys eq "ARRAY" and @$ys >= 2
!ll&&!rl&&r
0085
MC/DC0%0/2
ref $ys eq "ARRAY" and @$ys >= 2
ref $ys eq "ARRAY" @$ys >= 2
Truth table33%1/3
A and B
A= ref $ys eq "ARRAY"B= @$ys >= 2
ABresult
0X0
100
111
10585 85 require Statistics::LineFit;
10586 85 my $fit = Statistics::LineFit->new;
10587 85 ▶ return undef unless $fit->setData([ 0 .. $#$ys ], $ys);
Branch: 1 branch
BranchTrueFalseTotal
unless $fit->setData([0 .. $ys->$#*], $ys) 0 85 85
10588 85 my ($intercept, $slope) = $fit->coefficients;
10589 85 ▶ return undef unless defined $slope && defined $intercept;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $slope and defined $intercept 0 85 85
Condition33%1/3
defined $slope and defined $intercept
!ll&&!rl&&r
0085
MC/DC0%0/2
defined $slope and defined $intercept
defined $slope defined $intercept
Truth table33%1/3
A and B
A= defined $slopeB= defined $intercept
ABresult
0X0
100
111
10590 85 my $r2 = $fit->rSquared;
10591 85 ▶ return { slope => $slope, intercept => $intercept, r_squared => $r2 // 0 };
Condition50%1/2
$r2 // 0
l!l
850
MC/DC0%0/1
$r2 // 0
$r2
Truth table50%1/2
A
A= $r2
Aresult
11
00
10592 }
10593  
10594 72 ▶sub pie_view ($self) {
Subroutine pie_view: called CC=44 SCAR=48.8
Pod documented
10595 72 ▶ my $cat_col = $self->param('cat') // '';
Condition100%2/2
$self->param("cat") // ""
l!l
693
MC/DC100%1/1
$self->param("cat") // ""
$self->param("cat")
Truth table100%2/2
A
A= $self->param("cat")
Aresult
11
00
10596 72 ▶ my $val_col = $self->param('val') // '';
Condition100%2/2
$self->param("val") // ""
l!l
2844
MC/DC100%1/1
$self->param("val") // ""
$self->param("val")
Truth table100%2/2
A
A= $self->param("val")
Aresult
11
00
10597 72 ▶ my $donut = $self->param('donut') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('donut') ? : 1 71 72
10598 72 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition100%2/2
_safe_back_url($self->param("back")) // "/"
l!l
567
MC/DC100%1/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table100%2/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
10599 72 my $back2 = _safe_back_url($self->param('back2'));
10600 72 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
072
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
10601  
10602 72 ▶ return $self->render(text => 'Missing cat or val column parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col and length $val_col 47 25 72
Condition100%3/3
length $cat_col and length $val_col
!ll&&!rl&&r
44325
MC/DC100%2/2
length $cat_col and length $val_col
length $cat_col length $val_col
Truth table100%3/3
A and B
A= length $cat_colB= length $val_col
ABresult
0X0
100
111
10603 unless length($cat_col) && length($val_col);
10604  
10605 25 my ($src, $records, $columns) = $self->_run_pipeline_source;
10606 25 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 24 25
10607 unless defined $records;
10608  
10609 24 my $span = $self->_span_calc_spec($columns, 'cat');
10610 return $self->render(text => $span->{error}, status => 400)
10611 24 ▶ if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 0 24 24
Condition33%1/3
$span and $span->{"error"}
!ll&&!rl&&r
2400
MC/DC0%0/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table33%1/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
10612  
10613 24 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
10614 24 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 24 24
10615 0 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 24 24
10616  
10617 24 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 24 24
10618  
10619 24 my %col_set = map { $_ => 1 } @{$columns};
10620 return $self->render(text => "Column not found: $cat_col", status => 400)
10621 24 ▶ unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 2 22 24
10622  
10623 # '__count__' is the sentinel value sent when the user picks "Count (rows)".
10624 22 my $count_mode = ($val_col eq '__count__');
10625 return $self->render(text => "Column not found: $val_col", status => 400)
10626 22 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 1 21 22
Condition100%3/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
3181
MC/DC100%2/2
$count_mode or $col_set{$val_col}
$count_mode $col_set{$val_col}
Truth table100%3/3
A or B
A= $count_modeB= $col_set{$val_col}
ABresult
1X1
011
000
10627  
10628 21 ▶ $cat_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 21 21
10629  
10630 # Detect the currency symbol from the first non-empty source value.
10631 # This is a display concern; derive from the pre-filtered source rows so the
10632 # $/$GBP/EUR prefix on the legend is unchanged regardless of the push path.
10633 21 my $currency_symbol = '';
10634 21 ▶ if (!$count_mode) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($count_mode) 18 3 21
10635 18 for my $row (@$records) {
10636 69 ▶ my $v = $row->{$val_col} // '';
Condition50%1/2
$row->{$val_col} // ""
l!l
690
MC/DC0%0/1
$row->{$val_col} // ""
$row->{$val_col}
Truth table50%1/2
A
A= $row->{$val_col}
Aresult
11
00
10637 69 ▶ next unless length($v);
Branch: 1 branch
BranchTrueFalseTotal
unless length $v 0 69 69
10638 69 ▶ if ($v =~ /\A\s*\(?\s*([^\d\s.,\-\(])/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v =~ /\A\s*\(?\s*([^\d\s.,\-\(])/u) 4 65 69
10639 4 $currency_symbol = $1;
10640 4 last;
10641 }
10642 }
10643 }
10644  
10645 # Aggregate via _grouped_totals (push path or Perl fold).
10646 21 ▶ my $agg_rows = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 3 18 21
$count_mode ? : 3 18 21
10647 { source => $src, records => $records },
10648 {
10649 by => [$cat_col],
10650 fn => $count_mode ? 'count' : 'sum',
10651 val => $count_mode ? undef : $val_col,
10652 as => 'value',
10653 },
10654 );
10655  
10656 # Top-N: keep the highest-N slices, aggregate the rest as "Other".
10657 21 ▶ my $topn_n = _whole_number($self->param('topn')) // 0;
Condition50%1/2
_whole_number($self->param("topn")) // 0
l!l
021
MC/DC0%0/1
_whole_number($self->param("topn")) // 0
_whole_number($self->param("topn"))
Truth table50%1/2
A
A= _whole_number($self->param("topn"))
Aresult
11
00
10658 21 ▶ if ($topn_n > 0 && @$agg_rows > $topn_n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($topn_n > 0 and @$agg_rows > $topn_n) 0 21 21
Condition33%1/3
$topn_n > 0 and @$agg_rows > $topn_n
!ll&&!rl&&r
2100
MC/DC0%0/2
$topn_n > 0 and @$agg_rows > $topn_n
$topn_n > 0 @$agg_rows > $topn_n
Truth table33%1/3
A and B
A= $topn_n > 0B= @$agg_rows > $topn_n
ABresult
0X0
100
111
10659 0 ▶ my @sorted = sort { ($b->{value} // 0) <=> ($a->{value} // 0) } @$agg_rows;
Condition0%0/4
$Database::BI::Controller::Dashboard::b->{"value"} // 0
l!l
00
$Database::BI::Controller::Dashboard::a->{"value"} // 0
l!l
00
MC/DC0%0/1
$Database::BI::Controller::Dashboard::b->{"value"} // 0
$Database::BI::Controller::Dashboard::b->{"value"}
MC/DC0%0/1
$Database::BI::Controller::Dashboard::a->{"value"} // 0
$Database::BI::Controller::Dashboard::a->{"value"}
Truth table0%0/2
A
A= $Database::BI::Controller::Dashboard::b->{"value"}
Aresult
11
00
Truth table0%0/2
A
A= $Database::BI::Controller::Dashboard::a->{"value"}
Aresult
11
00
10660 0 my @top_agg = @sorted[0 .. $topn_n - 1];
10661 0 ▶ my %top_cats = map { ($_->{$cat_col} // '') => 1 } @top_agg;
Condition0%0/2
$_->{$cat_col} // ""
l!l
00
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
Truth table0%0/2
A
A= $_->{$cat_col}
Aresult
11
00
10662 my $other_rec = [
10663 0 ▶ grep { !$top_cats{$_->{$cat_col} // ''} } @$records
Condition0%0/2
$_->{$cat_col} // ""
l!l
00
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
Truth table0%0/2
A
A= $_->{$cat_col}
Aresult
11
00
10664 ];
10665 0 ▶ if (@$other_rec) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$other_rec) 0 0 0
10666 0 ▶ my $other = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 0 0 0
$count_mode ? : 0 0 0
10667 { source => undef, records => $other_rec },
10668 { by => [], fn => ($count_mode ? 'count' : 'sum'),
10669 val => ($count_mode ? undef : $val_col), as => 'value' },
10670 );
10671 push @top_agg, { $cat_col => 'Other', value => $other->[0]{value} }
10672 0 ▶ if @$other && defined $other->[0]{value};
Branch: 1 branch
BranchTrueFalseTotal
if @$other and defined $other->[0]{"value"} 0 0 0
Condition0%0/3
@$other and defined $other->[0]{"value"}
!ll&&!rl&&r
000
MC/DC0%0/2
@$other and defined $other->[0]{"value"}
@$other defined $other->[0]{"value"}
Truth table0%0/3
A and B
A= @$otherB= defined $other->[0]{"value"}
ABresult
0X0
100
111
10673 }
10674 0 $agg_rows = \@top_agg;
10675 }
10676  
10677 21 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg_rows 1 20 21
10678 text => 'No plottable data: no rows have valid data in the selected columns.',
10679 status => 200,
10680 ) unless @$agg_rows;
10681  
10682 20 my @slices = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg_rows;
10683  
10684 20 my ($source_url, $source_accessed) = $self->_url_attribution;
10685  
10686 20 require HTML::D3;
10687 20 my $scheme = _categorical_scheme($self->param('scheme'));
10688 20 ▶ my $title = $count_mode ? "Count by $cat_col" : "$val_col by $cat_col";
Branch: 1 branch
BranchTrueFalseTotal
$count_mode ? : 3 17 20
10689 20 my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 600, height => 500)
10690 ->render_pie_chart_snippet(\@slices, {
10691 animated => 1,
10692 donut => $donut,
10693 sort_slices => 'value',
10694 max_slices => 12,
10695 legend => 1,
10696 color_scheme => $scheme,
10697 });
10698  
10699 20 my $chart_html = $snippet->{html};
10700 20 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 20 20
10701  
10702 20 my %chart_spec = (
10703 kind => 'pie',
10704 title => $title,
10705 encode => { cat => $cat_col, value => $val_col },
10706 options => { scheme => $scheme, donut => $donut },
10707 );
10708 20 my ($platform, $language) = $self->_resolve_template;
10709 20 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 20 20
$back2 ? : 0 20 20
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0200
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
10710 handler => 'tt',
10711 template => "$platform/$language/pie",
10712 format => 'html',
10713 title => $title,
10714 chart_html => $chart_html,
10715 chart => \%chart_spec,
10716 chart_json => $self->_chart_json(\%chart_spec),
10717 back_url => ($back2 // $back),
10718 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10719 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10720 drill_back_url => $back,
10721 slice_count => scalar @slices,
10722 cat_col => $cat_col,
10723 val_col => $val_col,
10724 currency_symbol => $currency_symbol,
10725 source_url => $source_url,
10726 source_accessed => $source_accessed,
10727 language => $language,
10728 );
10729 }
10730  
10731 =head2 heatmap_view
10732  
10733 C<GET /heatmap> -- Render a D3.js grid heatmap for two categorical axes.
10734  
10735 Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:
10736  
10737 x=<col> X-axis (horizontal) categorical column (required)
10738 y=<col> Y-axis (vertical) categorical column (required)
10739 val=<col> Cell value column (optional; when absent, cells show row count)
10740 scheme=<name> D3 sequential colour scheme name (default: YlOrRd)
10741 show_val=1 Overlay the numeric value inside each cell
10742 back=<url> URL for the "Back to table" breadcrumb link
10743  
10744 =head3 API SPECIFICATION
10745  
10746 =head4 INPUT
10747  
10748 l spec Required. Left table spec (table:name or path:/abs/path).
10749 x string Required. Name of the X-axis categorical column.
10750 y string Required. Name of the Y-axis categorical column.
10751 val string Optional. Name of the value column; omit for count mode.
10752 scheme string Optional. D3 sequential colour scheme name.
10753 show_val flag Optional. Set to 1 to render values inside cells.
10754 back url Optional. Safe back-link URL (sanitised by _safe_back_url).
10755  
10756 =head4 OUTPUT
10757  
10758 200 text/html Rendered heatmap page.
10759 200 text/plain "No plottable data: ..." when grid is empty.
10760 400 text/plain Missing x= or y= parameter.
10761 400 text/plain Column not found: <col>.
10762 404 text/plain "Could not open data source" when l= is absent/invalid.
10763  
10764 =head3 MESSAGES
10765  
10766 error_heatmap_no_data -- no (x,y) pair has a non-empty value.
10767  
10768 =head3 FORMAL SPECIFICATION
10769  
10770 heatmap_view == lambda self .
10771 pre length(x_col) > 0 /\ length(y_col) > 0
10772 /\ x_col in columns /\ y_col in columns
10773 let triples = { (row[x_col], row[y_col], row[val_col]) | row in records,
10774 all three fields non-empty } in
10775 post render(heatmap, triples)
10776  
10777 =head3 EXAMPLE
10778  
10779 GET /heatmap?l=table:sales&x=region&y=product&val=amount
10780 -> 200 HTML page containing D3 heatmap SVG
10781  
10782 =cut
10783  
10784 66 ▶sub heatmap_view ($self) {
Subroutine heatmap_view: called CC=39 SCAR=37.5
Pod documented
10785 66 ▶ my $x_col = $self->param('x') // '';
Condition100%2/2
$self->param("x") // ""
l!l
624
MC/DC100%1/1
$self->param("x") // ""
$self->param("x")
Truth table100%2/2
A
A= $self->param("x")
Aresult
11
00
10786 66 ▶ my $y_col = $self->param('y') // '';
Condition100%2/2
$self->param("y") // ""
l!l
624
MC/DC100%1/1
$self->param("y") // ""
$self->param("y")
Truth table100%2/2
A
A= $self->param("y")
Aresult
11
00
10787 66 ▶ my $val_col = $self->param('val') // '';
Condition100%2/2
$self->param("val") // ""
l!l
1056
MC/DC100%1/1
$self->param("val") // ""
$self->param("val")
Truth table100%2/2
A
A= $self->param("val")
Aresult
11
00
10788 66 my $scheme = _sequential_scheme($self->param('scheme'));
10789 66 ▶ my $show_v = $self->param('show_val') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('show_val') ? : 0 66 66
10790 66 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
066
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table50%1/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
10791 66 my $back2 = _safe_back_url($self->param('back2'));
10792 66 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
066
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
10793  
10794 66 ▶ return $self->render(text => 'Missing x or y column parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col and length $y_col 7 59 66
Condition100%3/3
length $x_col and length $y_col
!ll&&!rl&&r
5259
MC/DC100%2/2
length $x_col and length $y_col
length $x_col length $y_col
Truth table100%3/3
A and B
A= length $x_colB= length $y_col
ABresult
0X0
100
111
10795 unless length($x_col) && length($y_col);
10796  
10797 59 my ($src, $records, $columns) = $self->_run_pipeline_source;
10798 59 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 3 56 59
10799 unless defined $records;
10800  
10801 56 my $span = $self->_span_calc_spec($columns, 'x');
10802 return $self->render(text => $span->{error}, status => 400)
10803 56 ▶ if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 2 54 56
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
5402
MC/DC50%1/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table66%2/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
10804  
10805 54 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
10806 54 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 54 54
10807 54 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 53 54
10808  
10809 53 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 52 53
10810  
10811 52 my %col_set = map { $_ => 1 } @{$columns};
10812 return $self->render(text => "Column not found: $x_col", status => 400)
10813 52 ▶ unless $col_set{$x_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$x_col} 4 48 52
10814 return $self->render(text => "Column not found: $y_col", status => 400)
10815 48 ▶ unless $col_set{$y_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$y_col} 2 46 48
10816 return $self->render(text => "Column not found: $val_col", status => 400)
10817 46 ▶ if length($val_col) && !$col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $val_col and not $col_set{$val_col} 1 45 46
Condition100%3/3
length $val_col and not $col_set{$val_col}
!ll&&!rl&&r
3781
MC/DC100%2/2
length $val_col and not $col_set{$val_col}
length $val_col not $col_set{$val_col}
Truth table100%3/3
A and not(B)
A= length $val_colB= not $col_set{$val_col}
ABresult
0X0
100
111
10818  
10819 # A heatmap's time dimension is its x axis, which is the one span= buckets.
10820 45 ▶ $x_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 45 45
10821  
10822 # Collect first-seen axis order from the filtered source rows.
10823 # The aggregate path returns groups ordered by (x,y) ascending, which
10824 # differs from first-seen. We re-derive the layout order from the source
10825 # so the grid renders in natural data order regardless of backend.
10826 45 my (@x_order, @y_order, %seen_x, %seen_y);
10827 45 for my $row (@$records) {
10828 248 ▶ my $x = $row->{$x_col} // next;
Condition100%2/2
$row->{$x_col} // (next)
l!l
2462
MC/DC100%1/1
$row->{$x_col} // (next)
$row->{$x_col}
Truth table100%2/2
A
A= $row->{$x_col}
Aresult
11
00
10829 246 ▶ my $y = $row->{$y_col} // next;
Condition50%1/2
$row->{$y_col} // (next)
l!l
2460
MC/DC0%0/1
$row->{$y_col} // (next)
$row->{$y_col}
Truth table50%1/2
A
A= $row->{$y_col}
Aresult
11
00
10830 246 ▶ next unless length($x) && length($y);
Branch: 1 branch
BranchTrueFalseTotal
unless length $x and length $y 0 246 246
Condition33%1/3
length $x and length $y
!ll&&!rl&&r
00246
MC/DC0%0/2
length $x and length $y
length $x length $y
Truth table33%1/3
A and B
A= length $xB= length $y
ABresult
0X0
100
111
10831 246 ▶ push @x_order, $x unless $seen_x{$x}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_x{$x}++ 162 84 246
10832 246 ▶ push @y_order, $y unless $seen_y{$y}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_y{$y}++ 227 19 246
10833 }
10834  
10835 # Aggregate with _grouped_totals (push or Perl fold).
10836 45 ▶ my $agg_rows = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
length $val_col ? : 8 37 45
length $val_col ? : 8 37 45
10837 { source => $src, records => $records },
10838 {
10839 by => [$x_col, $y_col],
10840 fn => length($val_col) ? 'sum' : 'count',
10841 val => length($val_col) ? $val_col : undef,
10842 as => 'value',
10843 },
10844 );
10845  
10846 # Index aggregate rows by [x][y] for O(1) lookup.
10847 45 my %grid;
10848 45 for my $row (@$agg_rows) {
10849 246 $grid{$row->{$x_col}}{$row->{$y_col}} = $row->{value};
10850 }
10851  
10852 my @triples = map {
10853 45 my ($raw_x, $xv) = ($_, _decode_cell($_));
10854 162 ▶ map { [$xv, _decode_cell($_), $grid{$raw_x}{$_} // 0] } @y_order
Condition100%2/2
$grid{$raw_x}{$_} // 0
l!l
246634
MC/DC100%1/1
$grid{$raw_x}{$_} // 0
$grid{$raw_x}{$_}
Truth table100%2/2
A
A= $grid{$raw_x}{$_}
Aresult
11
00
10855 } @x_order;
10856  
10857 45 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @triples 1 44 45
10858 text => 'No plottable data: check that x and y columns contain values.',
10859 status => 200,
10860 ) unless @triples;
10861  
10862 44 my ($source_url, $source_accessed) = $self->_url_attribution;
10863  
10864 44 require HTML::D3;
10865 44 ▶ my $title = length($val_col) ? "$val_col by $x_col and $y_col"
Branch: 1 branch
BranchTrueFalseTotal
length $val_col ? : 8 36 44
10866 : "Count by $x_col and $y_col";
10867 44 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 900, height => 500)
Branch: 1 branch
BranchTrueFalseTotal
length $val_col ? : 8 36 44
10868 ->render_heatmap_snippet(\@triples, {
10869 x_label => $x_col,
10870 y_label => $y_col,
10871 val_label => (length($val_col) ? $val_col : 'Count'),
10872 color_scheme => $scheme,
10873 show_values => $show_v,
10874 animated => 1,
10875 });
10876  
10877 44 my $chart_html = $snippet->{html};
10878 44 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 44 44
10879  
10880 44 my %chart_spec = (
10881 kind => 'heatmap',
10882 title => $title,
10883 encode => { x => $x_col, y => $y_col, value => $val_col },
10884 options => { scheme => $scheme, show_values => $show_v },
10885 );
10886 44 my ($platform, $language) = $self->_resolve_template;
10887 44 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 44 44
$back2 ? : 0 44 44
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0440
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
10888 handler => 'tt',
10889 template => "$platform/$language/heatmap",
10890 format => 'html',
10891 title => $title,
10892 chart_html => $chart_html,
10893 chart => \%chart_spec,
10894 chart_json => $self->_chart_json(\%chart_spec),
10895 cell_count => scalar @triples,
10896 back_url => ($back2 // $back),
10897 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10898 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10899 source_url => $source_url,
10900 source_accessed => $source_accessed,
10901 language => $language,
10902 );
10903 }
10904  
10905 =head2 bar_view
10906  
10907 C<GET /bar> -- Render a D3.js bar chart grouped by a categorical column.
10908  
10909 Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:
10910  
10911 cat=<col> Category (X-axis) column (required)
10912 val=<col> Value column to sum per category; omit or use C<__count__>
10913 to count rows instead of summing (optional)
10914 orient=h Horizontal bars (default: vertical)
10915 sort=value|label Sort bars by descending value or ascending label
10916 max=N Collapse bars beyond the top-N into an "Other" bar
10917 back=<url> URL for the "Back to table" breadcrumb link
10918  
10919 =head3 API SPECIFICATION
10920  
10921 =head4 INPUT
10922  
10923 l spec Required. Left table spec (table:name or path:/abs/path).
10924 cat string Required. Name of the category column.
10925 val string Optional. Name of the value column; use __count__ or
10926 omit entirely to count rows per category.
10927 orient string Optional. "h" for horizontal bars; default vertical.
10928 sort string Optional. "value" or "label"; default file order.
10929 max integer Optional. Collapse beyond top-N categories into "Other".
10930 back url Optional. Safe back-link URL (sanitised by _safe_back_url).
10931  
10932 =head4 OUTPUT
10933  
10934 200 text/html Rendered bar chart page (SVG element id="bar_chart").
10935 200 text/plain "No plottable data: ..." when no categories exist.
10936 400 text/plain Missing cat= parameter.
10937 400 text/plain Column not found: <col>.
10938 404 text/plain "Could not open data source" when l= is absent/invalid.
10939  
10940 =head3 MESSAGES
10941  
10942 error_bar_no_data -- no row has a non-empty category value.
10943  
10944 =head3 FORMAL SPECIFICATION
10945  
10946 bar_view == lambda self .
10947 pre length(cat_col) > 0 /\ cat_col in columns
10948 let bars = { (cat, sum(val)) | row in records, row[cat_col] = cat,
10949 val /= undef } in
10950 post render(bar, bars, orientation, sort, max_bars)
10951  
10952 =head3 EXAMPLE
10953  
10954 GET /bar?l=table:sales&cat=region&val=amount&sort=value
10955 -> 200 HTML page with id="bar_chart" SVG element
10956  
10957 =cut
10958  
10959 94 ▶sub bar_view ($self) {
Subroutine bar_view: called CC=47 SCAR=40.8
Pod documented
10960 94 ▶ my $cat_col = $self->param('cat') // '';
Condition100%2/2
$self->param("cat") // ""
l!l
895
MC/DC100%1/1
$self->param("cat") // ""
$self->param("cat")
Truth table100%2/2
A
A= $self->param("cat")
Aresult
11
00
10961 94 ▶ my $val_col = $self->param('val') // '';
Condition100%2/2
$self->param("val") // ""
l!l
2767
MC/DC100%1/1
$self->param("val") // ""
$self->param("val")
Truth table100%2/2
A
A= $self->param("val")
Aresult
11
00
10962 94 ▶ my $orient = $self->param('orient') // 'vertical';
Condition100%2/2
$self->param("orient") // "vertical"
l!l
292
MC/DC100%1/1
$self->param("orient") // "vertical"
$self->param("orient")
Truth table100%2/2
A
A= $self->param("orient")
Aresult
11
00
10963 94 ▶ my $sort = $self->param('sort') // 'none';
Condition100%2/2
$self->param("sort") // "none"
l!l
490
MC/DC100%1/1
$self->param("sort") // "none"
$self->param("sort")
Truth table100%2/2
A
A= $self->param("sort")
Aresult
11
00
10964 94 ▶ my $max_bars = int($self->param('max') || 0);
Condition50%1/2
$self->param('max') || 0
l!l
094
MC/DC0%0/1
$self->param('max') || 0
$self->param('max')
Truth table50%1/2
A
A= $self->param('max')
Aresult
11
00
10965 94 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
094
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table50%1/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
10966 94 my $back2 = _safe_back_url($self->param('back2'));
10967 94 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
094
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
10968  
10969 94 ▶ return $self->render(text => 'Missing cat column parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col 6 88 94
10970 unless length($cat_col);
10971  
10972 88 my ($src, $records, $columns) = $self->_run_pipeline_source;
10973 88 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 15 73 88
10974 unless defined $records;
10975  
10976 # span= buckets the category column by expanding into the calculated field a
10977 # reader could have typed, so the buckets come from the same arithmetic a
10978 # ?c= definition would use. See _span_calc_spec.
10979 73 my $span = $self->_span_calc_spec($columns, 'cat');
10980 return $self->render(text => $span->{error}, status => 400)
10981 73 ▶ if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 3 70 73
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
7003
MC/DC50%1/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table66%2/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
10982  
10983 70 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
10984 70 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 70 70
10985 70 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 69 70
10986  
10987 69 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 2 67 69
10988  
10989 67 my %col_set = map { $_ => 1 } @{$columns};
10990 return $self->render(text => "Column not found: $cat_col", status => 400)
10991 67 ▶ unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 3 64 67
10992  
10993 # '__count__' sentinel: count rows per category instead of summing a column.
10994 64 ▶ my $count_mode = ($val_col eq '__count__' || !length($val_col));
Condition100%3/3
$val_col eq '__count__' || !length($val_col)
l!l&&r!l&&!r
34219
MC/DC100%2/2
$val_col eq '__count__' || !length($val_col)
$val_col eq '__count__' !length($val_col)
Truth table100%3/3
A || not(B)
A= $val_col eq '__count__'B= !length($val_col)
ABresult
1X1
011
000
10995 return $self->render(text => "Column not found: $val_col", status => 400)
10996 64 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 2 62 64
Condition100%3/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
45172
MC/DC100%2/2
$count_mode or $col_set{$val_col}
$count_mode $col_set{$val_col}
Truth table100%3/3
A or B
A= $count_modeB= $col_set{$val_col}
ABresult
1X1
011
000
10997  
10998 # The chart groups by the bucket column the request asked for, if it did.
10999 62 ▶ $cat_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 62 62
11000  
11001 # Aggregate via _grouped_totals (push path or Perl fold).
11002 62 ▶ my $agg_rows = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 45 17 62
$count_mode ? : 45 17 62
11003 { source => $src, records => $records },
11004 {
11005 by => [$cat_col],
11006 fn => $count_mode ? 'count' : 'sum',
11007 val => $count_mode ? undef : $val_col,
11008 as => 'value',
11009 },
11010 );
11011  
11012 # Top-N: keep the highest-N categories, aggregate the rest as "Other".
11013 62 ▶ my $topn_n = _whole_number($self->param('topn')) // 0;
Condition100%2/2
_whole_number($self->param("topn")) // 0
l!l
260
MC/DC100%1/1
_whole_number($self->param("topn")) // 0
_whole_number($self->param("topn"))
Truth table100%2/2
A
A= _whole_number($self->param("topn"))
Aresult
11
00
11014 62 ▶ if ($topn_n > 0 && @$agg_rows > $topn_n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($topn_n > 0 and @$agg_rows > $topn_n) 1 61 62
Condition66%2/3
$topn_n > 0 and @$agg_rows > $topn_n
!ll&&!rl&&r
6101
MC/DC50%1/2
$topn_n > 0 and @$agg_rows > $topn_n
$topn_n > 0 @$agg_rows > $topn_n
Truth table66%2/3
A and B
A= $topn_n > 0B= @$agg_rows > $topn_n
ABresult
0X0
100
111
11015 1 ▶ my @sorted = sort { ($b->{value} // 0) <=> ($a->{value} // 0) } @$agg_rows;
Condition50%2/4
$Database::BI::Controller::Dashboard::b->{"value"} // 0
l!l
80
$Database::BI::Controller::Dashboard::a->{"value"} // 0
l!l
80
MC/DC0%0/1
$Database::BI::Controller::Dashboard::b->{"value"} // 0
$Database::BI::Controller::Dashboard::b->{"value"}
MC/DC0%0/1
$Database::BI::Controller::Dashboard::a->{"value"} // 0
$Database::BI::Controller::Dashboard::a->{"value"}
Truth table50%1/2
A
A= $Database::BI::Controller::Dashboard::b->{"value"}
Aresult
11
00
Truth table50%1/2
A
A= $Database::BI::Controller::Dashboard::a->{"value"}
Aresult
11
00
11016 1 my @top_agg = @sorted[0 .. $topn_n - 1];
11017 1 ▶ my %top_cats = map { ($_->{$cat_col} // '') => 1 } @top_agg;
Condition50%1/2
$_->{$cat_col} // ""
l!l
30
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
Truth table50%1/2
A
A= $_->{$cat_col}
Aresult
11
00
11018 my $other_rec = [
11019 1 ▶ grep { !$top_cats{$_->{$cat_col} // ''} } @$records
Condition50%1/2
$_->{$cat_col} // ""
l!l
50
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
Truth table50%1/2
A
A= $_->{$cat_col}
Aresult
11
00
11020 ];
11021 1 ▶ if (@$other_rec) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$other_rec) 1 0 1
11022 1 ▶ my $other = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 0 1 1
$count_mode ? : 0 1 1
11023 { source => undef, records => $other_rec },
11024 { by => [], fn => ($count_mode ? 'count' : 'sum'),
11025 val => ($count_mode ? undef : $val_col), as => 'value' },
11026 );
11027 push @top_agg, { $cat_col => 'Other', value => $other->[0]{value} }
11028 1 ▶ if @$other && defined $other->[0]{value};
Branch: 1 branch
BranchTrueFalseTotal
if @$other and defined $other->[0]{"value"} 1 0 1
Condition33%1/3
@$other and defined $other->[0]{"value"}
!ll&&!rl&&r
001
MC/DC0%0/2
@$other and defined $other->[0]{"value"}
@$other defined $other->[0]{"value"}
Truth table33%1/3
A and B
A= @$otherB= defined $other->[0]{"value"}
ABresult
0X0
100
111
11029 }
11030 1 $agg_rows = \@top_agg;
11031 }
11032  
11033 62 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg_rows 2 60 62
11034 text => 'No plottable data: no rows have valid data in the selected columns.',
11035 status => 200,
11036 ) unless @$agg_rows;
11037  
11038 60 my @bars = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg_rows;
11039  
11040 60 ▶ my $orientation = ($orient eq 'h') ? 'horizontal' : 'vertical';
Branch: 1 branch
BranchTrueFalseTotal
$orient eq 'h' ? : 2 58 60
11041 60 ▶ my $sort_bars = ($sort eq 'value' || $sort eq 'label') ? $sort : 'none';
Branch: 1 branch
BranchTrueFalseTotal
$sort eq 'value' || $sort eq 'label' ? : 2 58 60
Condition66%2/3
$sort eq "value" or $sort eq "label"
l!l&&r!l&&!r
2058
MC/DC50%1/2
$sort eq "value" or $sort eq "label"
$sort eq "value" $sort eq "label"
Truth table66%2/3
A or B
A= $sort eq "value"B= $sort eq "label"
ABresult
1X1
011
000
11042  
11043 60 my ($source_url, $source_accessed) = $self->_url_attribution;
11044  
11045 60 require HTML::D3;
11046 60 ▶ my $title = $count_mode ? "Count by $cat_col"
Branch: 1 branch
BranchTrueFalseTotal
$count_mode ? : 45 15 60
11047 : "$val_col by $cat_col";
11048 60 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 480)
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 45 15 60
$max_bars > 0 ? : 0 60 60
11049 ->render_bar_chart_snippet(\@bars, {
11050 animated => 1,
11051 orientation => $orientation,
11052 sort_bars => $sort_bars,
11053 color => 'categorical',
11054 show_values => 0,
11055 value_label => ($count_mode ? 'Count' : $val_col),
11056 x_label => $cat_col,
11057 ($max_bars > 0 ? (max_bars => $max_bars) : ()),
11058 });
11059  
11060 60 my $chart_html = $snippet->{html};
11061 60 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 60 60
11062  
11063 60 ▶ my %chart_spec = (
Condition50%1/2
$orient // "v"
l!l
600
MC/DC0%0/1
$orient // "v"
$orient
Truth table50%1/2
A
A= $orient
Aresult
11
00
11064 kind => 'bar',
11065 title => $title,
11066 encode => { cat => $cat_col, value => $val_col },
11067 options => { orientation => ($orient // 'v'), max_items => $max_bars },
11068 );
11069 60 my ($platform, $language) = $self->_resolve_template;
11070 60 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 60 60
$back2 ? : 0 60 60
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0600
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
11071 handler => 'tt',
11072 template => "$platform/$language/bar",
11073 format => 'html',
11074 title => $title,
11075 chart_html => $chart_html,
11076 chart => \%chart_spec,
11077 chart_json => $self->_chart_json(\%chart_spec),
11078 bar_count => scalar @bars,
11079 cat_col => $cat_col,
11080 back_url => ($back2 // $back),
11081 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
11082 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
11083 source_url => $source_url,
11084 source_accessed => $source_accessed,
11085 language => $language,
11086 );
11087 }
11088  
11089 =head2 folder_view
11090  
11091 C<GET /folder> -- Browse a data table grouped by the letter-prefix hierarchy
11092 of an order-number column (e.g. A10, CT4, B3).
11093  
11094 The top level displays one folder icon per initial letter group (A, B, C ...).
11095 Clicking a folder with sub-prefixes (e.g. C contains CA and CB items) shows
11096 the sub-folders; clicking a leaf prefix shows the actual data rows sorted
11097 numerically by the embedded digit sequence.
11098  
11099 Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:
11100  
11101 col=<col> Column whose values contain order codes (optional; auto-
11102 detected when absent by scanning the first 10 rows for
11103 values matching C<[A-Z]{1,4}\d+[A-Z]?>)
11104 prefix=<str> Current drill-down prefix, e.g. "CA" (optional; top-level
11105 when absent)
11106 back=<url> URL for the "Back to table" breadcrumb link (optional;
11107 derived from C<l=> when absent)
11108  
11109 =head3 API SPECIFICATION
11110  
11111 =head4 INPUT
11112  
11113 l spec Required. Left table spec (table:name or path:/abs/path).
11114 col string Optional. Order-code column name.
11115 prefix string Optional. Current letter prefix; max length MAX_PREFIX_LEN.
11116 back url Optional. Safe back-link URL (sanitised by _safe_back_url).
11117  
11118 =head4 OUTPUT
11119  
11120 200 text/html Rendered folder page with folder grid and/or item table.
11121 400 text/plain "Missing l= parameter" when l= is absent.
11122 400 text/plain "Prefix too long" when prefix exceeds MAX_PREFIX_LEN (20).
11123 404 text/plain "Could not open data source" when the data source is unavailable.
11124  
11125 =head3 MESSAGES
11126  
11127 None -- all failure paths render plain text with an HTTP status code.
11128  
11129 =head3 FORMAL SPECIFICATION
11130  
11131 folder_view == lambda self .
11132 pre length(left_spec) > 0 /\ length(prefix) <= MAX_PREFIX_LEN
11133 let records = pipeline(left_spec, joins, filters)
11134 prefix_map = { p -> [row] | row in records, row[col] =~ /[A-Z]+/ -> p } in
11135 IF prefix = "" THEN
11136 post render(folder, folders = first_letters(prefix_map))
11137 ELSE
11138 post render(folder, folders = sub_prefixes(prefix, prefix_map),
11139 items = sort_numeric(prefix_map[prefix]))
11140  
11141 =head3 EXAMPLE
11142  
11143 GET /folder?l=table:orders&col=order_no
11144 -> 200 HTML folder grid showing A (12 items), B (7 items), C (4 items)
11145  
11146 GET /folder?l=table:orders&col=order_no&prefix=A
11147 -> 200 HTML folder grid for sub-prefixes and items directly under "A"
11148  
11149 =cut
11150  
11151 83 ▶sub folder_view ($self) {
Subroutine folder_view: called CC=38 SCAR=36.7
Pod documented
11152 83 ▶ my $key_col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
5627
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
11153 83 ▶ my $prefix = $self->param('prefix') // '';
Condition100%2/2
$self->param("prefix") // ""
l!l
1667
MC/DC100%1/1
$self->param("prefix") // ""
$self->param("prefix")
Truth table100%2/2
A
A= $self->param("prefix")
Aresult
11
00
11154 83 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
776
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
11155  
11156 83 ▶ return $self->render(text => 'Missing l= parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 7 76 83
11157 unless length($left_spec);
11158  
11159 # Guard against DoS: a crafted prefix longer than any real order-code would
11160 # generate O(N) breadcrumb entries and a proportionally large HTML response.
11161 76 ▶ return $self->render(text => 'Prefix too long', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if length $prefix > $MAX_PREFIX_LEN 5 71 76
11162 if length($prefix) > $MAX_PREFIX_LEN;
11163  
11164 # Fall back to the table's own URL when no explicit back= is supplied,
11165 # so the breadcrumb always has a "Back to table" link.
11166 71 ▶ my $back = _safe_back_url($self->param('back'))
Condition33%1/3
_safe_back_url($self->param('back')) || $self->_spec_to_url($left_spec)
l!l&&r!l&&!r
0710
MC/DC0%0/2
_safe_back_url($self->param('back')) || $self->_spec_to_url($left_spec)
_safe_back_url($self->param('back')) $self->_spec_to_url($left_spec)
Truth table33%1/3
A || B
A= _safe_back_url($self->param('back'))B= $self->_spec_to_url($left_spec)
ABresult
1X1
011
000
11167 || $self->_spec_to_url($left_spec);
11168  
11169 71 my ($records, $columns) = $self->_run_export_pipeline;
11170 71 ▶ return if $self->stash('_reduce_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_reduce_error") 6 65 71
11171 65 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless $records 4 61 65
11172 unless $records;
11173  
11174 # Auto-detect key column: find the first column whose sampled values look
11175 # like order-number codes (1-4 uppercase letters followed by digits).
11176 61 ▶ if (!length($key_col)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $key_col) 14 47 61
11177 14 ▶ my $sample_end = $#{$records} < 9 ? $#{$records} : 9;
Branch: 1 branch
BranchTrueFalseTotal
$#{$records;} < 9 ? : 14 0 14
11178 14 OUTER: for my $col (@{$columns}) {
11179 69 for my $row (@{$records}[0 .. $sample_end]) {
11180 399 ▶ if (($row->{$col} // '') =~ /\A[A-Z]{1,4}\d+[A-Z]?\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (($row->{$col} // "") =~ /\A[A-Z]{1,4}\d+[A-Z]?\z/u) 3 396 399
Condition50%1/2
$row->{$col} // ""
l!l
3990
MC/DC0%0/1
$row->{$col} // ""
$row->{$col}
Truth table50%1/2
A
A= $row->{$col}
Aresult
11
00
11181 3 $key_col = $col;
11182 3 last OUTER;
11183 }
11184 }
11185 }
11186 14 ▶ $key_col ||= ($columns->[0] // '');
Condition60%3/5
$key_col ||= $columns->[0] // ""
l!l&&r!l&&!r
3110
$columns->[0] // ""
l!l
110
MC/DC0%0/2
$key_col ||= $columns->[0] // ""
$key_col $columns->[0]
Truth table66%2/3
A ||= B
A= $key_colB= $columns->[0]
ABresult
1X1
011
000
11187 }
11188  
11189 # Build prefix -> [rows] map. Prefix is the leading letter-run of each
11190 # key value: "A10" -> "A", "CT4" -> "CT", "CC30A" -> "CC".
11191 61 my %prefix_to_rows;
11192 61 for my $row (@{$records}) {
11193 354 ▶ my $val = $row->{$key_col} // '';
Condition100%2/2
$row->{$key_col} // ""
l!l
34212
MC/DC100%1/1
$row->{$key_col} // ""
$row->{$key_col}
Truth table100%2/2
A
A= $row->{$key_col}
Aresult
11
00
11194 354 my ($p) = $val =~ /\A([A-Z]+)/;
11195 354 ▶ next unless defined $p;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $p 300 54 354
11196 54 push @{ $prefix_to_rows{$p} }, $row;
11197 }
11198  
11199 # Return the sorted list of "one-step" child prefixes of $par: all known
11200 # prefixes that share the parent as a strict prefix and extend it by
11201 # exactly one letter.
11202 11 ▶ my $sub_prefixes = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
11203 11 my ($par) = @_;
11204 11 my $len = length($par);
11205 11 my %seen;
11206 11 for my $p (keys %prefix_to_rows) {
11207 19 ▶ next if length($p) <= $len;
Branch: 1 branch
BranchTrueFalseTotal
if length $p <= $len 15 4 19
11208 4 ▶ next if substr($p, 0, $len) ne $par;
Branch: 1 branch
BranchTrueFalseTotal
if substr($p, 0, $len) ne $par 2 2 4
11209 2 $seen{ substr($p, 0, $len + 1) } = 1;
11210 }
11211 11 return sort keys %seen;
11212 61 };
11213  
11214 # Count total items underneath a prefix (including all deeper sub-prefixes).
11215 18 ▶ my $deep_count = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
11216 18 my ($par) = @_;
11217 18 my $n = 0;
11218 18 for my $p (keys %prefix_to_rows) {
11219 64 ▶ $n += scalar @{ $prefix_to_rows{$p} }
Branch: 1 branch
BranchTrueFalseTotal
if substr($p, 0, length $par) eq $par 20 44 64
11220 if substr($p, 0, length($par)) eq $par;
11221 }
11222 18 return $n;
11223 61 };
11224  
11225 61 my ($platform, $language) = $self->_resolve_template;
11226  
11227 # Base URL carries the table spec (and optional col=) so every sub-link
11228 # re-uses the same data source without repeating params.
11229 61 my $base_url = '/folder?l=' . url_escape($left_spec);
11230 61 ▶ $base_url .= '&col=' . url_escape($key_col) if length($key_col);
Branch: 1 branch
BranchTrueFalseTotal
if length $key_col 61 0 61
11231 # The table it came from travels too, so a folder level keeps the trail.
11232 61 $base_url .= '&back=' . url_escape($back);
11233  
11234 61 my (@folders, @items, @breadcrumb);
11235  
11236 61 ▶ if (!length($prefix)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not length $prefix) { } 50 11 61
11237 # Top level: group all prefixes by their first letter.
11238 50 my %first_letter;
11239 50 for my $p (keys %prefix_to_rows) {
11240 18 $first_letter{ substr($p, 0, 1) } = 1;
11241 }
11242 50 for my $fl (sort keys %first_letter) {
11243 16 push @folders, {
11244 name => $fl,
11245 count => $deep_count->($fl),
11246 href => $base_url . '&prefix=' . url_escape($fl),
11247 };
11248 }
11249 } else {
11250 # Build breadcrumb: one entry per letter-prefix layer up to current.
11251 # e.g. prefix="CD" -> [ {name="C", href=...}, {name="CD", href=undef} ]
11252 11 for my $i (1 .. length($prefix)) {
11253 47 my $p = substr($prefix, 0, $i);
11254 47 ▶ push @breadcrumb, {
Branch: 1 branch
BranchTrueFalseTotal
$i < length $prefix ? : 36 11 47
11255 name => $p,
11256 href => ($i < length($prefix))
11257 ? ($base_url . '&prefix=' . url_escape($p))
11258 : undef,
11259 };
11260 }
11261  
11262 # One-step child prefixes of the current prefix (sub-folders).
11263 11 for my $sp ($sub_prefixes->($prefix)) {
11264 2 push @folders, {
11265 name => $sp,
11266 count => $deep_count->($sp),
11267 href => $base_url . '&prefix=' . url_escape($sp),
11268 };
11269 }
11270  
11271 # Items whose prefix matches exactly (e.g. prefix="C" shows C1, C3, ...).
11272 11 ▶ @items = @{ $prefix_to_rows{$prefix} // [] };
Condition100%2/2
$prefix_to_rows{$prefix} // []
l!l
65
MC/DC100%1/1
$prefix_to_rows{$prefix} // []
$prefix_to_rows{$prefix}
Truth table100%2/2
A
A= $prefix_to_rows{$prefix}
Aresult
11
00
11273  
11274 # Sort by the numeric part of the key value so A9 < A10.
11275 @items = sort {
11276 11 ▶ my ($an) = ($a->{$key_col} // '') =~ /(\d+)/;
Condition50%1/2
$Database::BI::Controller::Dashboard::a->{$key_col} // ""
l!l
60
MC/DC0%0/1
$Database::BI::Controller::Dashboard::a->{$key_col} // ""
$Database::BI::Controller::Dashboard::a->{$key_col}
Truth table50%1/2
A
A= $Database::BI::Controller::Dashboard::a->{$key_col}
Aresult
11
00
11277 6 ▶ my ($bn) = ($b->{$key_col} // '') =~ /(\d+)/;
Condition50%1/2
$Database::BI::Controller::Dashboard::b->{$key_col} // ""
l!l
60
MC/DC0%0/1
$Database::BI::Controller::Dashboard::b->{$key_col} // ""
$Database::BI::Controller::Dashboard::b->{$key_col}
Truth table50%1/2
A
A= $Database::BI::Controller::Dashboard::b->{$key_col}
Aresult
11
00
11278 ($an // 0) <=> ($bn // 0)
11279 6 ▶ || ($a->{$key_col} // '') cmp ($b->{$key_col} // '');
Condition72%8/11
($an // 0) <=> ($bn // 0) || ($Database::BI::Controller::Dashboard::a->{$key_col} // '') cmp ($Database::BI::Controller::Dashboard::b->{$key_col} // '')
l!l&&r!l&&!r
501
$an // 0
l!l
51
$bn // 0
l!l
51
$Database::BI::Controller::Dashboard::a->{$key_col} // ""
l!l
10
$Database::BI::Controller::Dashboard::b->{$key_col} // ""
l!l
10
MC/DC0%0/2
($an // 0) <=> ($bn // 0) || ($Database::BI::Controller::Dashboard::a->{$key_col} // '') cmp ($Database::BI::Controller::Dashboard::b->{$key_col} // '')
$an $Database::BI::Controller::Dashboard::a->{$key_col}
MC/DC100%1/1
$bn // 0
$bn
MC/DC0%0/1
$Database::BI::Controller::Dashboard::b->{$key_col} // ""
$Database::BI::Controller::Dashboard::b->{$key_col}
Truth table66%2/3
A || B
A= $anB= $Database::BI::Controller::Dashboard::a->{$key_col}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $bn
Aresult
11
00
Truth table50%1/2
A
A= $Database::BI::Controller::Dashboard::b->{$key_col}
Aresult
11
00
11280 } @items;
11281 }
11282  
11283 61 ▶ my $title = length($prefix) ? "Folder: $prefix" : 'Folder view';
Branch: 1 branch
BranchTrueFalseTotal
length $prefix ? : 11 50 61
11284  
11285 $self->render(
11286 handler => 'tt',
11287 template => "$platform/$language/folder",
11288 format => 'html',
11289 title => $title,
11290 folders => \@folders,
11291 items => \@items,
11292 columns => $columns,
11293 key_col => $key_col,
11294 prefix => $prefix,
11295 breadcrumb => \@breadcrumb,
11296 # Inside a folder the trail goes on past this page, so its own crumb
11297 # links to the top of the folder view.
11298 61 ▶ (@breadcrumb ? (trail => do {
Branch: 1 branch
BranchTrueFalseTotal
@breadcrumb ? : 11 50 61
11299 11 my $trail = _breadcrumb_trail($self);
11300 11 ▶ $trail->[-1]{url} = $base_url if @$trail;
Branch: 1 branch
BranchTrueFalseTotal
if @$trail 11 0 11
11301 11 $trail;
11302 }) : ()),
11303 base_url => $base_url,
11304 back_url => $back,
11305 back_label => 'Back to table',
11306 left_spec => $left_spec,
11307 language => $language,
11308 );
11309 }
11310  
11311 =head2 tables_view
11312  
11313 C<GET /tables> -- Schema browser for multi-table databases (SQLite, etc.).
11314 Lists all internal tables with their columns; clicking a table opens it. A
11315 JSON file that is an object holding lists of objects has one table per list
11316 (see L<Database::BI::Model::DataSource/json_lists>).
11317  
11318 =head3 API SPECIFICATION
11319  
11320 =head4 INPUT
11321  
11322 ?l= string Required. Table spec: "table:name" (data_dir) or
11323 "path:/abs/path" (filesystem path). The file must be a
11324 SQLite database or a .json file.
11325  
11326 =head4 OUTPUT
11327  
11328 Renders C<tables.html.tt> with:
11329  
11330 db_label string Short name / stem of the database file
11331 tables ARRAYREF of { name, columns => [...], href }
11332 spec string The raw l= spec (for building back links)
11333 back_url string URL to navigate back one level
11334 back_label string Label for the back link
11335  
11336 =cut
11337  
11338 59 ▶sub tables_view ($self) {
Subroutine tables_view: called CC=41 SCAR=52.6
Pod documented
11339 59 my ($platform, $language) = $self->_resolve_template;
11340 59 my $spec = $self->param('l');
11341 59 ▶ return $self->reply->not_found unless defined $spec && length $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec and length $spec 4 55 59
Condition100%3/3
defined $spec and length $spec
!ll&&!rl&&r
2255
MC/DC100%2/2
defined $spec and length $spec
defined $spec length $spec
Truth table100%3/3
A and B
A= defined $specB= length $spec
ABresult
0X0
100
111
11342  
11343 55 my ($file_path, $db_label, $back_url, $back_label);
11344 55 my @tables;
11345  
11346 55 ▶ if ($spec =~ /\Atable:([A-Za-z0-9_]+)\z/) {
Branch: 4 branches
BranchTrueFalseTotal
if ($spec =~ /\Atable:([A-Za-z0-9_]+)\z/u) { } 44 11 55
elsif ($spec =~ /\Apath:(.+)\z/u) { } 6 5 11
elsif ($spec =~ /$REDIS_URL_RE/u) { } 1 4 5
elsif ($spec =~ /$MARIADB_SERVER_RE/u) { } 0 4 4
11347 44 my $data_dir = _data_dir_for($self->app);
11348 44 my @exts = qw(sql sqlite sqlite3 db json);
11349 44 ▶ my $table_name = _table_stem($data_dir, $1, @exts) // lc $1;
Condition100%2/2
_table_stem($data_dir, $1, @exts) // lc $1
l!l
242
MC/DC100%1/1
_table_stem($data_dir, $1, @exts) // lc $1
_table_stem($data_dir, $1, @exts)
Truth table100%2/2
A
A= _table_stem($data_dir, $1, @exts)
Aresult
11
00
11350 44 for my $ext (@exts) {
11351 218 my $p = $data_dir->child("$table_name.$ext");
11352 218 ▶ if (-f $p) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $p) 2 216 218
11353 2 $file_path = $p->to_string;
11354 2 last;
11355 }
11356 }
11357 44 ▶ return $self->reply->not_found unless defined $file_path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_path 42 2 44
11358 2 $db_label = $table_name;
11359 2 $back_url = '/';
11360 2 $back_label = 'Home';
11361 } elsif ($spec =~ /\Apath:(.+)\z/) {
11362 6 my ($path_arg) = _split_path($1);
11363 6 ▶ if (my $refusal = _outside_roots($self, $path_arg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $refusal = _outside_roots($self, $path_arg)) 0 6 6
11364 0 return $self->render(text => $refusal, status => 403);
11365 }
11366 6 my $file = eval { Mojo::File->new($path_arg)->realpath };
11367 6 ▶ return $self->reply->not_found
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file and -f $file and $file->basename =~ /\.(?:sql|sqlite|sqlite3|db|json)\z/iu 2 4 6
Condition83%5/6
defined $file and -f $file and $file->basename =~ /\.(?:sql|sqlite|sqlite3|db|json)\z/iu
!ll&&!rl&&r
114
defined $file and -f $file
!ll&&!rl&&r
105
MC/DC66%2/3
defined $file and -f $file and $file->basename =~ /\.(?:sql|sqlite|sqlite3|db|json)\z/iu
defined $file -f $file $file->basename =~ /\.(?:sql|sqlite|sqlite3|db|json)\z/iu
Truth table75%3/4
A and B and C
A= defined $fileB= -f $fileC= $file->basename =~ /\.(?:sql|sqlite|sqlite3|db|json)\z/iu
ABCresult
0XX0
10X0
1100
1111
11368 unless defined $file && -f $file && $file->basename =~ /\.(?:sql|sqlite|sqlite3|db|json)\z/i;
11369 4 $file_path = $file->to_string;
11370 4 ($db_label = $file->basename) =~ s/\.[^.]+\z//;
11371 4 $back_url = '/browse?path=' . url_escape($file->dirname->to_string);
11372 4 $back_label = 'Back to browser';
11373 } elsif ($spec =~ $REDIS_URL_RE) {
11374 # Bare redis:// URL -- scan keys and present a picker.
11375 # Parse redis://[:password@]host[:port][/db]
11376 1 my ($password, $hostport, $db_idx);
11377 1 ▶ if ($spec =~ m{\Aredis://(?::([^@]*)@)?([^/]+)(?:/(\d+))?\z}i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ m[\Aredis://(?::([^\@]*)@)?([^/]+)(?:/(\d+))?\z]iu) 1 0 1
11378 1 ($password, $hostport, $db_idx) = ($1, $2, $3);
11379 }
11380 1 ▶ $hostport //= 'localhost:6379';
Condition50%1/2
$hostport //= "localhost:6379"
l!l
10
MC/DC0%0/1
$hostport //= "localhost:6379"
$hostport
Truth table50%1/2
A
A= $hostport
Aresult
11
00
11381 1 $db_label = "redis://$hostport";
11382 1 $back_url = '/';
11383 1 $back_label = 'Home';
11384  
11385 1 eval {
11386 # Load Redis::Fast if available, fall back to Redis.
11387 # Use the file-path form ("Redis/Fast.pm") because require with a
11388 # plain string treats it as a filename, not a module name.
11389 1 my $pkg;
11390 1 for my $mod ('Redis::Fast', 'Redis') {
11391 1 (my $file = $mod) =~ s{::}{/}g;
11392 1 ▶ if (eval { require "$file.pm"; 1 }) { $pkg = $mod; last }
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require "$file.pm"; 1 } }) 1 0 1
11393 }
11394 1 ▶ croak 'Redis or Redis::Fast must be installed to browse a Redis server'
Branch: 1 branch
BranchTrueFalseTotal
unless $pkg 0 1 1
11395 unless $pkg;
11396  
11397 1 my $redis = $pkg->new(
11398 server => $hostport,
11399 cnx_timeout => 5,
11400 read_timeout => 10,
11401 );
11402 0 ▶ $redis->auth($password) if defined $password && length $password;
Branch: 1 branch
BranchTrueFalseTotal
if defined $password and length $password 0 0 0
Condition0%0/3
defined $password and length $password
!ll&&!rl&&r
000
MC/DC0%0/2
defined $password and length $password
defined $password length $password
Truth table0%0/3
A and B
A= defined $passwordB= length $password
ABresult
0X0
100
111
11403 0 ▶ $redis->select(int($db_idx)) if defined $db_idx && int($db_idx) > 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $db_idx and int $db_idx > 0 0 0 0
Condition0%0/3
defined $db_idx and int $db_idx > 0
!ll&&!rl&&r
000
MC/DC0%0/2
defined $db_idx and int $db_idx > 0
defined $db_idx int $db_idx > 0
Truth table0%0/3
A and B
A= defined $db_idxB= int $db_idx > 0
ABresult
0X0
100
111
11404  
11405 # SCAN in a loop; stop at 200 keys -- enough for a picker.
11406 0 my $cursor = 0;
11407 0 my @all_keys;
11408 0 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
$cursor ne 0 and @all_keys < 200 and do { do { () = $redis->scan($cursor, "COUNT", 100); $cursor = $new_cursor; push @all_keys, @{$batch // [];} } } 0 0 0
Condition0%0/3
$cursor ne 0 and @all_keys < 200
!ll&&!rl&&r
000
MC/DC0%0/2
$cursor ne 0 and @all_keys < 200
$cursor ne 0 @all_keys < 200
Truth table0%0/3
A and B
A= $cursor ne 0B= @all_keys < 200
ABresult
0X0
100
111
11409 0 my ($new_cursor, $batch) = $redis->scan($cursor, 'COUNT', 100);
11410 0 $cursor = $new_cursor;
11411 0 ▶ push @all_keys, @{ $batch // [] };
Condition0%0/2
$batch // []
l!l
00
MC/DC0%0/1
$batch // []
$batch
Truth table0%0/2
A
A= $batch
Aresult
11
00
11412 } while ($cursor ne '0' && @all_keys < 200);
11413  
11414 0 my $tables_url = '/tables?l=' . url_escape($spec);
11415 0 for my $key (sort @all_keys) {
11416 0 my $open_url = '/open?path=' . url_escape("redis:$key|$spec")
11417 . '&back=' . url_escape($tables_url)
11418 . '&back_label=Redis+keys';
11419 0 push @tables, { name => $key, columns => [], href => $open_url };
11420 }
11421 };
11422 1 ▶ return $self->reply->not_found if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 0 1
11423 } elsif ($spec =~ $MARIADB_SERVER_RE) {
11424 0 my $server = $1;
11425 0 $db_label = $server;
11426 0 $back_url = '/';
11427 0 $back_label = 'Home';
11428 0 my $found = eval {
11429 Database::BI::Model::DataSource->mariadb_tables($server,
11430 0 ▶ ($self->app->config('mariadb_servers') // {})->{$server});
Condition0%0/2
$self->app->config("mariadb_servers") // {}
l!l
00
MC/DC0%0/1
$self->app->config("mariadb_servers") // {}
$self->app->config("mariadb_servers")
Truth table0%0/2
A
A= $self->app->config("mariadb_servers")
Aresult
11
00
11431 };
11432 0 ▶ unless ($found) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($found) 0 0 0
11433 0 return $self->render(
11434 template => "$platform/$language/home",
11435 handler => 'tt',
11436 format => 'html',
11437 tables => [],
11438 title => 'Error',
11439 error => $self->_i18n('error_file_open', $spec, _tidy_error($@)),
11440 back_url => '/',
11441 back_label => 'Home',
11442 language => $language,
11443 );
11444 }
11445 0 for my $found_table (@{$found}) {
11446 0 my ($name, $cols) = @{$found_table}{qw(name columns)};
11447 # Database::Abstraction refuses this name, so the card says so.
11448 0 ▶ if ($name !~ $TABLE_NAME_RE) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($name =~ /$TABLE_NAME_RE/u) 0 0 0
11449 0 (my $safe = $name) =~ s/[^A-Za-z0-9_]/_/g;
11450 0 ▶ $safe = "_$safe" unless $safe =~ /\A[A-Za-z_]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $safe =~ /\A[A-Za-z_]/u 0 0 0
11451 0 push @tables, { name => $name, columns => $cols, unusable => 1, safe_name => $safe, on_server => 1 };
11452 0 next;
11453 }
11454 0 my $open_url = '/open?path=' . url_escape("mariadb:$server/$name")
11455 . '&back=' . url_escape('/tables?l=' . $spec)
11456 . '&back_label=' . url_escape(ucfirst($db_label) . ' schema');
11457 0 push @tables, { name => $name, columns => $cols, href => $open_url };
11458 }
11459 } else {
11460 4 return $self->reply->not_found;
11461 }
11462  
11463 6 ▶ if (defined $file_path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file_path) 6 0 6
11464 # A JSON file's tables are its lists of objects; a SQLite file's are
11465 # listed by Database::Join.
11466 my $schema = $file_path =~ /\.json\z/i
11467 0 ? eval { Database::BI::Model::DataSource->json_lists($file_path) }
11468 6 ▶ : eval { require Database::Join::Catalog; Database::Join::Catalog->schema(file => $file_path) };
Branch: 1 branch
BranchTrueFalseTotal
$file_path =~ /\.json\z/iu ? : 0 6 6
11469 6 ▶ return $self->reply->not_found unless $schema;
Branch: 1 branch
BranchTrueFalseTotal
unless $schema 0 6 6
11470 6 for my $table_info (@{$schema}) {
11471 14 my $tname = $table_info->{name};
11472 14 my @cols = @{ $table_info->{columns} };
11473 # Database::Abstraction refuses this name, so the card says so
11474 # rather than linking to an error. A JSON list's name never
11475 # reaches SQL, so any name opens.
11476 14 ▶ if ($tname !~ $TABLE_NAME_RE && $file_path !~ /\.json\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tname =~ /$TABLE_NAME_RE/u or $file_path =~ /\.json\z/iu) 0 14 14
Condition33%1/3
$tname =~ /$TABLE_NAME_RE/u or $file_path =~ /\.json\z/iu
l!l&&r!l&&!r
1400
MC/DC0%0/2
$tname =~ /$TABLE_NAME_RE/u or $file_path =~ /\.json\z/iu
$tname =~ /$TABLE_NAME_RE/u $file_path =~ /\.json\z/iu
Truth table33%1/3
A or B
A= $tname =~ /$TABLE_NAME_RE/uB= $file_path =~ /\.json\z/iu
ABresult
1X1
011
000
11477 0 (my $safe = $tname) =~ s/[^A-Za-z0-9_]/_/g;
11478 0 ▶ $safe = "_$safe" unless $safe =~ /\A[A-Za-z_]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $safe =~ /\A[A-Za-z_]/u 0 0 0
11479 0 push @tables, { name => $tname, columns => \@cols, unusable => 1, safe_name => $safe };
11480 0 next;
11481 }
11482 14 my $open_url = '/open?path=' . url_escape($file_path)
11483 . '&it=' . url_escape($tname)
11484 . '&back=' . url_escape('/tables?l=' . $spec)
11485 . '&back_label=' . url_escape(ucfirst($db_label) . ' schema');
11486 14 push @tables, { name => $tname, columns => \@cols, href => $open_url };
11487 }
11488 }
11489  
11490 $self->render(
11491 6 template => "$platform/$language/tables",
11492 handler => 'tt',
11493 format => 'html',
11494 title => ucfirst($db_label) . ' -- Tables',
11495 db_label => $db_label,
11496 tables => \@tables,
11497 spec => $spec,
11498 back_url => $back_url,
11499 back_label => $back_label,
11500 language => $language,
11501 );
11502 }
11503  
11504 =head2 pivot_view
11505  
11506 C<GET /pivot> -- Crosstab / pivot table view.
11507  
11508 Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:
11509  
11510 rows=<col>[,<col>...] Row dimensions (required, comma-separated column names)
11511 cols=<col>[,<col>...] Column dimensions (optional)
11512 m=<col>:<fn>:<as> Measure spec, repeatable (required); col may be empty for count
11513 h=<as>:<op>:<val> Post-aggregation HAVING filter (repeatable, optional)
11514 totals=1 Include row subtotals, column subtotals, and grand total
11515 scheme=<name> Colour scheme for cell shading (optional)
11516 max_cols=<n> Collapse column headers beyond top-N into "Other"
11517 page= / per_page= Pagination over row groups
11518 format=csv|sqlite|json Export the pivot grid
11519  
11520 =head3 API SPECIFICATION
11521  
11522 =head4 INPUT
11523  
11524 The query parameters above, with C<l=> required as well.
11525  
11526 =head4 OUTPUT
11527  
11528 200 text/html (or the export format) The grid.
11529 400 text/plain 'Missing l= parameter', error_pivot_rows_required,
11530 error_pivot_measure_req, error_pivot_measure_invalid,
11531 error_measure_column, error_pivot_dim_not_found or error_topn_col.
11532 404 text/plain The source cannot be opened.
11533  
11534 =head3 FORMAL SPECIFICATION
11535  
11536 pivot_view
11537 l?, rows?, m? : seq Char
11538 response! : HTTP
11539 ──────────
11540 l? = ⟨⟩ ∨ rows? = ⟨⟩ ∨ m? = ⟨⟩ ⇒ response!.status = 400
11541 l? ≠ ⟨⟩ ∧ ¬ opens(l?) ⇒ response!.status = 404
11542  
11543 =cut
11544  
11545 94 ▶sub pivot_view ($self) {
Subroutine pivot_view: called CC=129 SCAR=72.6
Pod documented
11546 94 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
931
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
11547 94 ▶ return $self->render(text => 'Missing l= parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 2 92 94
11548 unless length $left_spec;
11549  
11550 92 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
092
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table50%1/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
11551 92 my $back2 = _safe_back_url($self->param('back2'));
11552 92 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
092
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
11553  
11554 92 ▶ my $rows_str = $self->param('rows') // '';
Condition100%2/2
$self->param("rows") // ""
l!l
4844
MC/DC100%1/1
$self->param("rows") // ""
$self->param("rows")
Truth table100%2/2
A
A= $self->param("rows")
Aresult
11
00
11555 92 ▶ return $self->render(text => $self->_i18n('error_pivot_rows_required'), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $rows_str 44 48 92
11556 unless length $rows_str;
11557  
11558 48 ▶ my @measure_strs = @{ $self->every_param('m') // [] };
Condition50%1/2
$self->every_param("m") // []
l!l
480
MC/DC0%0/1
$self->every_param("m") // []
$self->every_param("m")
Truth table50%1/2
A
A= $self->every_param("m")
Aresult
11
00
11559 48 ▶ return $self->render(text => $self->_i18n('error_pivot_measure_req'), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless @measure_strs 2 46 48
11560 unless @measure_strs;
11561  
11562 # Split dimensions on comma. A dimension name containing a comma
11563 # would produce an ambiguous split; that must be rejected.
11564 46 my @rows = split /,/, $rows_str, -1;
11565 46 ▶ my @cols = split /,/, ($self->param('cols') // ''), -1;
Condition50%1/2
$self->param("cols") // ""
l!l
046
MC/DC0%0/1
$self->param("cols") // ""
$self->param("cols")
Truth table50%1/2
A
A= $self->param("cols")
Aresult
11
00
11566 0 @cols = grep { length $_ } @cols;
11567  
11568 46 my @measures;
11569 46 for my $ms (@measure_strs) {
11570 46 my $m = _parse_measure_param($ms);
11571 46 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless $m 5 41 46
11572 text => $self->_i18n('error_pivot_measure_invalid', $ms, join(' ', @MEASURE_FNS)),
11573 status => 400,
11574 ) unless $m;
11575 41 push @measures, $m;
11576 }
11577  
11578 41 ▶ my $show_totals = ($self->param('totals') // '') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('totals') // '' ? : 13 28 41
Condition100%2/2
$self->param("totals") // ""
l!l
1328
MC/DC100%1/1
$self->param("totals") // ""
$self->param("totals")
Truth table100%2/2
A
A= $self->param("totals")
Aresult
11
00
11579 41 ▶ my $scheme = $self->param('scheme') // '';
Condition50%1/2
$self->param("scheme") // ""
l!l
041
MC/DC0%0/1
$self->param("scheme") // ""
$self->param("scheme")
Truth table50%1/2
A
A= $self->param("scheme")
Aresult
11
00
11580 41 ▶ my $max_cols_n = int($self->param('max_cols') || 0);
Condition50%1/2
$self->param('max_cols') || 0
l!l
041
MC/DC0%0/1
$self->param('max_cols') || 0
$self->param('max_cols')
Truth table50%1/2
A
A= $self->param('max_cols')
Aresult
11
00
11581 41 ▶ my $format = lc($self->param('format') // '');
Condition100%2/2
$self->param("format") // ""
l!l
239
MC/DC100%1/1
$self->param("format") // ""
$self->param("format")
Truth table100%2/2
A
A= $self->param("format")
Aresult
11
00
11582  
11583 # Build the data pipeline.
11584 41 my ($src, $records, $columns) = $self->_run_pipeline_source;
11585 41 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 40 41
11586 unless defined $records;
11587  
11588 # span= buckets one dimension, which for a pivot is one of the rows= columns;
11589 # the dimension itself may be any of them, so with more than one it is tcol=
11590 # that says which. See _span_calc_spec.
11591 40 my $span = $self->_span_calc_spec($columns, 'rows');
11592 40 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 0 40 40
Condition33%1/3
$span and $span->{"error"}
!ll&&!rl&&r
4000
MC/DC0%0/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table33%1/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
11593  
11594 # Calculated fields (?c=name:expr) -- evaluated before aggregation so calc
11595 # columns are available as row/col dimensions and measure columns.
11596 40 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
11597 40 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 40 40
11598 40 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 38 40
11599  
11600 38 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 38 38
11601  
11602 38 my %col_set = map { $_ => 1 } @{$columns};
11603  
11604 38 for my $dim (@rows, @cols) {
11605 return $self->render(
11606 text => $self->_i18n('error_pivot_dim_not_found', $dim),
11607 status => 400,
11608 38 ▶ ) unless $col_set{$dim};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$dim} 2 36 38
11609 }
11610  
11611 36 ▶ if ($span) {
Branch: 1 branch
BranchTrueFalseTotal
if ($span) 0 36 36
11612 0 ▶ @rows = map { $_ eq $span->{src} ? $span->{col} : $_ } @rows;
Branch: 1 branch
BranchTrueFalseTotal
$_ eq $span->{'src'} ? : 0 0 0
11613 0 ▶ @cols = map { $_ eq $span->{src} ? $span->{col} : $_ } @cols;
Branch: 1 branch
BranchTrueFalseTotal
$_ eq $span->{'src'} ? : 0 0 0
11614 }
11615  
11616 36 for my $m (@measures) {
11617 36 ▶ next unless defined $m->{col} && length $m->{col};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $m->{"col"} and length $m->{"col"} 1 35 36
Condition66%2/3
defined $m->{"col"} and length $m->{"col"}
!ll&&!rl&&r
0135
MC/DC50%1/2
defined $m->{"col"} and length $m->{"col"}
defined $m->{"col"} length $m->{"col"}
Truth table66%2/3
A and B
A= defined $m->{"col"}B= length $m->{"col"}
ABresult
0X0
100
111
11618 return $self->render(
11619 text => $self->_i18n('error_measure_column', $m->{col}),
11620 status => 400,
11621 35 ▶ ) unless $col_set{$m->{col}};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$m->{"col"}} 1 34 35
11622 }
11623  
11624 35 my $pipeline = { source => $src, records => $records };
11625  
11626 # -----------------------------------------------------------------------
11627 # Aggregate: one _grouped_totals call per measure, grouped by all
11628 # row AND column dimensions together.
11629 # -----------------------------------------------------------------------
11630 35 my (%cells, %row_combos, %col_combos);
11631 35 my (@row_key_order, @col_key_order);
11632 35 my (%row_seen, %col_seen);
11633  
11634 35 for my $m (@measures) {
11635 35 ▶ my $cv = (defined $m->{col} && length $m->{col}) ? $m->{col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $m->{'col'} && length $m->{'col'} ? : 34 1 35
Condition66%2/3
defined $m->{"col"} and length $m->{"col"}
!ll&&!rl&&r
0134
MC/DC50%1/2
defined $m->{"col"} and length $m->{"col"}
defined $m->{"col"} length $m->{"col"}
Truth table66%2/3
A and B
A= defined $m->{"col"}B= length $m->{"col"}
ABresult
0X0
100
111
11636 my $agg = $self->_grouped_totals($pipeline, {
11637 by => [@rows, @cols],
11638 fn => $m->{fn},
11639 val => $cv,
11640 as => $m->{as},
11641 35 });
11642 35 for my $row (@$agg) {
11643 129 ▶ my $rkey = join("\x00", map { $row->{$_} // '' } @rows);
Condition50%1/2
$row->{$_} // ""
l!l
1290
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table50%1/2
A
A= $row->{$_}
Aresult
11
00
11644 0 ▶ my $ckey = join("\x00", map { $row->{$_} // '' } @cols);
Condition0%0/2
$row->{$_} // ""
l!l
00
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table0%0/2
A
A= $row->{$_}
Aresult
11
00
11645 129 ▶ unless ($row_seen{$rkey}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($row_seen{$rkey}++) 129 0 129
11646 129 push @row_key_order, $rkey;
11647 129 ▶ $row_combos{$rkey} = { map { $_ => ($row->{$_} // '') } @rows };
Condition50%1/2
$row->{$_} // ""
l!l
1290
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table50%1/2
A
A= $row->{$_}
Aresult
11
00
11648 }
11649 129 ▶ unless ($col_seen{$ckey}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($col_seen{$ckey}++) 35 94 129
11650 35 push @col_key_order, $ckey;
11651 0 ▶ $col_combos{$ckey} = { map { $_ => ($row->{$_} // '') } @cols };
Condition0%0/2
$row->{$_} // ""
l!l
00
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table0%0/2
A
A= $row->{$_}
Aresult
11
00
11652 }
11653 129 $cells{$rkey}{$ckey}{$m->{as}} = $row->{$m->{as}};
11654 }
11655 }
11656  
11657 # -----------------------------------------------------------------------
11658 # Post-aggregation HAVING filters (h=<as>:<op>:<val>) applied row-by-row.
11659 # Each filter operates on a virtual row whose keys are the measure aliases.
11660 # -----------------------------------------------------------------------
11661 35 ▶ my @h_specs = @{ $self->every_param('h') // [] };
Condition50%1/2
$self->every_param("h") // []
l!l
350
MC/DC0%0/1
$self->every_param("h") // []
$self->every_param("h")
Truth table50%1/2
A
A= $self->every_param("h")
Aresult
11
00
11662 35 ▶ if (@h_specs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@h_specs) 0 35 35
11663 0 my @keep;
11664 0 for my $rkey (@row_key_order) {
11665 # Build a virtual row containing each measure's cell value
11666 # (using first col-combo as representative, or grand-total style).
11667 # For HAVING, we filter on the *row subtotal* value, not a single cell.
11668 # We'll compute a temp subtotal row for each row key.
11669 0 my %vrow;
11670 0 for my $m (@measures) {
11671 # Sum across cols for this row as representative value.
11672 0 my $v = 0;
11673 0 for my $ck (@col_key_order) {
11674 0 my $cv = $cells{$rkey}{$ck}{$m->{as}};
11675 0 ▶ $v += $cv if defined $cv;
Branch: 1 branch
BranchTrueFalseTotal
if defined $cv 0 0 0
11676 }
11677 0 $vrow{$m->{as}} = $v;
11678 }
11679 0 my $ok = 1;
11680 0 for my $hs (@h_specs) {
11681 0 my $passed = _apply_filter_spec([\%vrow], $hs);
11682 0 ▶ $ok = 0 unless @$passed;
Branch: 1 branch
BranchTrueFalseTotal
unless @$passed 0 0 0
11683 }
11684 0 ▶ push @keep, $rkey if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
11685 }
11686 0 @row_key_order = @keep;
11687 }
11688  
11689 # -----------------------------------------------------------------------
11690 # Top-N rows: keep only the top-N row groups (ranked by measure sum
11691 # across all col combos); aggregate the remaining rows as an "Other" row.
11692 # -----------------------------------------------------------------------
11693 {
11694 35 ▶ my $topn_n = _whole_number($self->param('topn')) // 0;
Condition100%2/2
_whole_number($self->param("topn")) // 0
l!l
332
MC/DC100%1/1
_whole_number($self->param("topn")) // 0
_whole_number($self->param("topn"))
Truth table100%2/2
A
A= _whole_number($self->param("topn"))
Aresult
11
00
11695 35 ▶ my $topn_col = $self->param('topn_col') // '';
Condition100%2/2
$self->param("topn_col") // ""
l!l
233
MC/DC100%1/1
$self->param("topn_col") // ""
$self->param("topn_col")
Truth table100%2/2
A
A= $self->param("topn_col")
Aresult
11
00
11696  
11697 35 ▶ if ($topn_n > 0 && @row_key_order > $topn_n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($topn_n > 0 and @row_key_order > $topn_n) 3 32 35
Condition66%2/3
$topn_n > 0 and @row_key_order > $topn_n
!ll&&!rl&&r
3203
MC/DC50%1/2
$topn_n > 0 and @row_key_order > $topn_n
$topn_n > 0 @row_key_order > $topn_n
Truth table66%2/3
A and B
A= $topn_n > 0B= @row_key_order > $topn_n
ABresult
0X0
100
111
11698 3 my %m_aliases = map { $_->{as} => 1 } @measures;
11699 3 ▶ if (length $topn_col && !$m_aliases{$topn_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $topn_col and not $m_aliases{$topn_col}) 2 1 3
Condition66%2/3
length $topn_col and not $m_aliases{$topn_col}
!ll&&!rl&&r
102
MC/DC50%1/2
length $topn_col and not $m_aliases{$topn_col}
length $topn_col not $m_aliases{$topn_col}
Truth table66%2/3
A and not(B)
A= length $topn_colB= not $m_aliases{$topn_col}
ABresult
0X0
100
111
11700 2 return $self->render(
11701 text => $self->_i18n('error_topn_col', $topn_col),
11702 status => 400,
11703 );
11704 }
11705 1 ▶ my $sort_as = length($topn_col) ? $topn_col : $measures[0]{as};
Branch: 1 branch
BranchTrueFalseTotal
length $topn_col ? : 0 1 1
11706  
11707 # Sort rows by descending sum of sort_as across all column combos.
11708 my @sorted_rkeys = sort {
11709 1 ▶ (do { my $s = 0; $s += ($cells{$b}{$_}{$sort_as} // 0) for @col_key_order; $s })
Condition50%1/2
$cells{$b}{$_}{$sort_as} // 0
l!l
70
MC/DC0%0/1
$cells{$b}{$_}{$sort_as} // 0
$cells{$b}{$_}{$sort_as}
Truth table50%1/2
A
A= $cells{$b}{$_}{$sort_as}
Aresult
11
00
11710 <=>
11711 7 ▶ (do { my $s = 0; $s += ($cells{$a}{$_}{$sort_as} // 0) for @col_key_order; $s })
Condition50%1/2
$cells{$a}{$_}{$sort_as} // 0
l!l
70
MC/DC0%0/1
$cells{$a}{$_}{$sort_as} // 0
$cells{$a}{$_}{$sort_as}
Truth table50%1/2
A
A= $cells{$a}{$_}{$sort_as}
Aresult
11
00
11712 } @row_key_order;
11713  
11714 1 my @top_rkeys = @sorted_rkeys[0 .. $topn_n - 1];
11715 1 my @rest_rkeys = @sorted_rkeys[$topn_n .. $#sorted_rkeys];
11716  
11717 1 ▶ if (@rest_rkeys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rest_rkeys) { } 1 0 1
11718 1 my %top_rkey_set = map { $_ => 1 } @top_rkeys;
11719 my $other_rec = [
11720 grep {
11721 1 my $r = $_;
11722 5 ▶ !$top_rkey_set{ join("\x00", map { $r->{$_} // '' } @rows) }
Condition50%1/2
$r->{$_} // ""
l!l
50
MC/DC0%0/1
$r->{$_} // ""
$r->{$_}
Truth table50%1/2
A
A= $r->{$_}
Aresult
11
00
11723 } @$records
11724 ];
11725 1 ▶ if (@$other_rec) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$other_rec) { } 1 0 1
11726 1 my $ork = '__topn_other__';
11727 1 $row_combos{$ork} = { map { $_ => 'Other' } @rows };
11728 1 for my $m (@measures) {
11729 1 ▶ my $cv = (defined $m->{col} && length $m->{col}) ? $m->{col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $m->{'col'} && length $m->{'col'} ? : 1 0 1
Condition33%1/3
defined $m->{"col"} and length $m->{"col"}
!ll&&!rl&&r
001
MC/DC0%0/2
defined $m->{"col"} and length $m->{"col"}
defined $m->{"col"} length $m->{"col"}
Truth table33%1/3
A and B
A= defined $m->{"col"}B= length $m->{"col"}
ABresult
0X0
100
111
11730 my $oa = $self->_grouped_totals(
11731 { source => undef, records => $other_rec },
11732 { by => [@cols], fn => $m->{fn}, val => $cv, as => $m->{as} },
11733 1 );
11734 1 for my $row (@$oa) {
11735 0 ▶ my $ck = join("\x00", map { $row->{$_} // '' } @cols);
Condition0%0/2
$row->{$_} // ""
l!l
00
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table0%0/2
A
A= $row->{$_}
Aresult
11
00
11736 1 $cells{$ork}{$ck}{$m->{as}} = $row->{$m->{as}};
11737 }
11738 }
11739 1 @row_key_order = (@top_rkeys, $ork);
11740 } else {
11741 0 @row_key_order = @top_rkeys;
11742 }
11743 } else {
11744 0 @row_key_order = @top_rkeys;
11745 }
11746 }
11747 }
11748  
11749 # -----------------------------------------------------------------------
11750 # Subtotals and grand total (three additional _grouped_totals calls
11751 # per measure when totals=1).
11752 # -----------------------------------------------------------------------
11753 33 my (%row_subtotals, %col_subtotals, %grand_total);
11754  
11755 33 ▶ if ($show_totals) {
Branch: 1 branch
BranchTrueFalseTotal
if ($show_totals) 13 20 33
11756 13 for my $m (@measures) {
11757 13 ▶ my $cv = (defined $m->{col} && length $m->{col}) ? $m->{col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $m->{'col'} && length $m->{'col'} ? : 13 0 13
Condition33%1/3
defined $m->{"col"} and length $m->{"col"}
!ll&&!rl&&r
0013
MC/DC0%0/2
defined $m->{"col"} and length $m->{"col"}
defined $m->{"col"} length $m->{"col"}
Truth table33%1/3
A and B
A= defined $m->{"col"}B= length $m->{"col"}
ABresult
0X0
100
111
11758  
11759 # Row subtotals: group by @rows only.
11760 my $rsub = $self->_grouped_totals($pipeline, {
11761 by => [@rows],
11762 fn => $m->{fn},
11763 val => $cv,
11764 as => $m->{as},
11765 13 });
11766 13 for my $r (@$rsub) {
11767 42 ▶ my $rk = join("\x00", map { $r->{$_} // '' } @rows);
Condition50%1/2
$r->{$_} // ""
l!l
420
MC/DC0%0/1
$r->{$_} // ""
$r->{$_}
Truth table50%1/2
A
A= $r->{$_}
Aresult
11
00
11768 42 $row_subtotals{$rk}{$m->{as}} = $r->{$m->{as}};
11769 }
11770  
11771 # Column subtotals: group by @cols only.
11772 13 ▶ if (@cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cols) 0 13 13
11773 my $csub = $self->_grouped_totals($pipeline, {
11774 by => [@cols],
11775 fn => $m->{fn},
11776 val => $cv,
11777 as => $m->{as},
11778 0 });
11779 0 for my $c (@$csub) {
11780 0 ▶ my $ck = join("\x00", map { $c->{$_} // '' } @cols);
Condition0%0/2
$c->{$_} // ""
l!l
00
MC/DC0%0/1
$c->{$_} // ""
$c->{$_}
Truth table0%0/2
A
A= $c->{$_}
Aresult
11
00
11781 0 $col_subtotals{$ck}{$m->{as}} = $c->{$m->{as}};
11782 }
11783 }
11784  
11785 # Grand total: group by nothing (all rows -> one result row).
11786 my $gtot = $self->_grouped_totals($pipeline, {
11787 by => [],
11788 fn => $m->{fn},
11789 val => $cv,
11790 as => $m->{as},
11791 13 });
11792 13 ▶ $grand_total{$m->{as}} = $gtot->[0]{$m->{as}} if @$gtot;
Branch: 1 branch
BranchTrueFalseTotal
if @$gtot 13 0 13
11793 }
11794 }
11795  
11796 # -----------------------------------------------------------------------
11797 # max_cols: collapse the tail of column combos beyond top-N into "Other".
11798 # The top-N are ranked by the first measure's column subtotal (or cell sum).
11799 # -----------------------------------------------------------------------
11800 33 ▶ if ($max_cols_n > 0 && @col_key_order > $max_cols_n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max_cols_n > 0 and @col_key_order > $max_cols_n) 0 33 33
Condition33%1/3
$max_cols_n > 0 and @col_key_order > $max_cols_n
!ll&&!rl&&r
3300
MC/DC0%0/2
$max_cols_n > 0 and @col_key_order > $max_cols_n
$max_cols_n > 0 @col_key_order > $max_cols_n
Truth table33%1/3
A and B
A= $max_cols_n > 0B= @col_key_order > $max_cols_n
ABresult
0X0
100
111
11801 0 my $first_as = $measures[0]{as};
11802 my @sorted_ckeys = sort {
11803 0 ( $show_totals
11804 ? ($col_subtotals{$b}{$first_as} // 0)
11805 0 ▶ : (do { my $s = 0; $s += ($cells{$_}{$b}{$first_as} // 0) for @row_key_order; $s })
Branch: 1 branch
BranchTrueFalseTotal
$show_totals ? : 0 0 0
Condition0%0/4
$cells{$_}{$b}{$first_as} // 0
l!l
00
$col_subtotals{$a}{$first_as} // 0
l!l
00
MC/DC0%0/1
$cells{$_}{$b}{$first_as} // 0
$cells{$_}{$b}{$first_as}
MC/DC0%0/1
$col_subtotals{$a}{$first_as} // 0
$col_subtotals{$a}{$first_as}
Truth table0%0/2
A
A= $cells{$_}{$b}{$first_as}
Aresult
11
00
Truth table0%0/2
A
A= $col_subtotals{$a}{$first_as}
Aresult
11
00
11806 )
11807 <=>
11808 ( $show_totals
11809 ? ($col_subtotals{$a}{$first_as} // 0)
11810 0 ▶ : (do { my $s = 0; $s += ($cells{$_}{$a}{$first_as} // 0) for @row_key_order; $s })
Branch: 1 branch
BranchTrueFalseTotal
$show_totals ? : 0 0 0
Condition0%0/4
$col_subtotals{$b}{$first_as} // 0
l!l
00
$cells{$_}{$a}{$first_as} // 0
l!l
00
MC/DC0%0/1
$col_subtotals{$b}{$first_as} // 0
$col_subtotals{$b}{$first_as}
MC/DC0%0/1
$cells{$_}{$a}{$first_as} // 0
$cells{$_}{$a}{$first_as}
Truth table0%0/2
A
A= $col_subtotals{$b}{$first_as}
Aresult
11
00
Truth table0%0/2
A
A= $cells{$_}{$a}{$first_as}
Aresult
11
00
11811 )
11812 } @col_key_order;
11813 0 my @top_ckeys = @sorted_ckeys[0 .. $max_cols_n - 1];
11814 0 my @rest_ckeys = @sorted_ckeys[$max_cols_n .. $#sorted_ckeys];
11815 0 ▶ if (@rest_ckeys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rest_ckeys) { } 0 0 0
11816 0 my $other_key = '__other__';
11817 0 $col_combos{$other_key} = { map { $_ => 'Other' } @cols };
11818 0 for my $rk (@row_key_order) {
11819 0 for my $m (@measures) {
11820 0 my ($v, $have) = (0, 0);
11821 0 for my $ck (@rest_ckeys) {
11822 0 my $cv = $cells{$rk}{$ck}{$m->{as}};
11823 0 ▶ if (defined $cv) { $v += $cv; $have = 1 }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cv) 0 0 0
11824 }
11825 0 ▶ $cells{$rk}{$other_key}{$m->{as}} = $have ? $v : undef;
Branch: 1 branch
BranchTrueFalseTotal
$have ? : 0 0 0
11826 }
11827 }
11828 0 @col_key_order = (@top_ckeys, $other_key);
11829 } else {
11830 0 @col_key_order = @top_ckeys;
11831 }
11832 }
11833  
11834 # -----------------------------------------------------------------------
11835 # Export path: build flat records from the grid.
11836 # -----------------------------------------------------------------------
11837 33 ▶ if ($format && $format =~ /\A(?:csv|sqlite|sql|json|xlsx)\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($format and $format =~ /\A(?:csv|sqlite|sql|json|xlsx)\z/u) 2 31 33
Condition66%2/3
$format and $format =~ /\A(?:csv|sqlite|sql|json|xlsx)\z/u
!ll&&!rl&&r
3102
MC/DC50%1/2
$format and $format =~ /\A(?:csv|sqlite|sql|json|xlsx)\z/u
$format $format =~ /\A(?:csv|sqlite|sql|json|xlsx)\z/u
Truth table66%2/3
A and B
A= $formatB= $format =~ /\A(?:csv|sqlite|sql|json|xlsx)\z/u
ABresult
0X0
100
111
11838 2 my @grid_records;
11839 2 for my $rk (@row_key_order) {
11840 10 for my $ck (@col_key_order) {
11841 10 my %rec;
11842 10 ▶ $rec{$_} = $row_combos{$rk}{$_} // '' for @rows;
Condition50%1/2
$row_combos{$rk}{$_} // ""
l!l
100
MC/DC0%0/1
$row_combos{$rk}{$_} // ""
$row_combos{$rk}{$_}
Truth table50%1/2
A
A= $row_combos{$rk}{$_}
Aresult
11
00
11843 10 ▶ $rec{$_} = $col_combos{$ck}{$_} // '' for @cols;
Condition0%0/2
$col_combos{$ck}{$_} // ""
l!l
00
MC/DC0%0/1
$col_combos{$ck}{$_} // ""
$col_combos{$ck}{$_}
Truth table0%0/2
A
A= $col_combos{$ck}{$_}
Aresult
11
00
11844 10 ▶ $rec{$_->{as}} = $cells{$rk}{$ck}{$_->{as}} // '' for @measures;
Condition50%1/2
$cells{$rk}{$ck}{$_->{"as"}} // ""
l!l
100
MC/DC0%0/1
$cells{$rk}{$ck}{$_->{"as"}} // ""
$cells{$rk}{$ck}{$_->{"as"}}
Truth table50%1/2
A
A= $cells{$rk}{$ck}{$_->{"as"}}
Aresult
11
00
11845 10 push @grid_records, \%rec;
11846 }
11847 }
11848 2 my @export_cols = (@rows, @cols, map { $_->{as} } @measures);
11849 2 ▶ return $self->_render_csv(\@grid_records, \@export_cols, 'pivot')
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "csv" 2 0 2
11850 if $format eq 'csv';
11851 0 ▶ return $self->_render_sqlite(\@grid_records, \@export_cols, 'pivot')
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "sqlite" or $format eq "sql" 0 0 0
Condition0%0/3
$format eq "sqlite" or $format eq "sql"
l!l&&r!l&&!r
000
MC/DC0%0/2
$format eq "sqlite" or $format eq "sql"
$format eq "sqlite" $format eq "sql"
Truth table0%0/3
A or B
A= $format eq "sqlite"B= $format eq "sql"
ABresult
1X1
011
000
11852 if $format eq 'sqlite' || $format eq 'sql';
11853 0 ▶ return $self->_render_json(\@grid_records, \@export_cols, 'pivot')
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "json" 0 0 0
11854 if $format eq 'json';
11855 0 ▶ if ($format eq 'xlsx') {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "xlsx") 0 0 0
11856 0 $self->stash(buffer => 0);
11857 0 require Excel::Writer::XLSX;
11858 0 my $out = '';
11859 0 ▶ open my $fh, '>', \$out
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", \$out or return $self->render("text", "Cannot open XLSX buffer", "status", 500) 0 0 0
11860 or return $self->render(text => 'Cannot open XLSX buffer', status => 500);
11861 0 my $wb = Excel::Writer::XLSX->new($fh);
11862 0 my $ws = $wb->add_worksheet('pivot');
11863 0 $ws->write_row(0, 0, \@export_cols);
11864 0 my $row_idx = 1;
11865 0 for my $rec (@grid_records) {
11866 0 ▶ $ws->write_row($row_idx++, 0, [ map { $rec->{$_} // '' } @export_cols ]);
Condition0%0/2
$rec->{$_} // ""
l!l
00
MC/DC0%0/1
$rec->{$_} // ""
$rec->{$_}
Truth table0%0/2
A
A= $rec->{$_}
Aresult
11
00
11867 }
11868 0 $wb->close;
11869 0 $self->res->headers->content_type(
11870 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
11871 );
11872 0 $self->res->headers->content_disposition(
11873 'attachment; filename="pivot.xlsx"'
11874 );
11875 0 return $self->render(data => $out);
11876 }
11877 }
11878  
11879 # -----------------------------------------------------------------------
11880 # Pagination: slice @row_key_order using the N+1 trick.
11881 # Must come after the export early-return above (exports use the full set)
11882 # and after subtotals/grand total (computed from $pipeline, not @row_key_order).
11883 # -----------------------------------------------------------------------
11884 31 my ($page, $per_page, $offset) = $self->_pagination;
11885 31 my $total_row_groups = scalar @row_key_order;
11886 31 ▶ my $piv_has_next = ($total_row_groups > $offset + $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$total_row_groups > $offset + $per_page ? : 3 28 31
11887 31 ▶ @row_key_order = $offset < $total_row_groups
Branch: 2 branches
BranchTrueFalseTotal
$offset < $total_row_groups ? : 30 1 31
$piv_has_next ? : 3 27 30
11888 ? @row_key_order[$offset .. ($piv_has_next ? $offset + $per_page - 1 : $#row_key_order)]
11889 : ();
11890  
11891 31 my $piv_page_url = $self->req->url->clone;
11892 31 $piv_page_url->query->remove('page')->remove('per_page');
11893  
11894 # -----------------------------------------------------------------------
11895 # Build the template-ready data structure.
11896 # -----------------------------------------------------------------------
11897 my @col_combo_list = map {
11898 31 my $ck = $_;
11899 {
11900 key => $ck,
11901 dim_vals => $col_combos{$ck},
11902 0 ▶ label => join(' / ', map { $col_combos{$ck}{$_} // '' } @cols),
Condition0%0/2
$col_combos{$ck}{$_} // ""
l!l
00
MC/DC0%0/1
$col_combos{$ck}{$_} // ""
$col_combos{$ck}{$_}
Truth table0%0/2
A
A= $col_combos{$ck}{$_}
Aresult
11
00
11903 }
11904 } @col_key_order;
11905  
11906 31 my @grid_rows;
11907 31 for my $rk (@row_key_order) {
11908 86 my %row_cells;
11909 86 for my $ck (@col_key_order) {
11910 86 ▶ $row_cells{$ck} = $cells{$rk}{$ck} // {};
Condition50%1/2
$cells{$rk}{$ck} // {}
l!l
860
MC/DC0%0/1
$cells{$rk}{$ck} // {}
$cells{$rk}{$ck}
Truth table50%1/2
A
A= $cells{$rk}{$ck}
Aresult
11
00
11911 }
11912 push @grid_rows, {
11913 row_vals => $row_combos{$rk},
11914 cells => \%row_cells,
11915 86 ▶ subtotals => $show_totals ? ($row_subtotals{$rk} // {}) : {},
Branch: 1 branch
BranchTrueFalseTotal
$show_totals ? : 38 48 86
Condition50%1/2
$row_subtotals{$rk} // {}
l!l
380
MC/DC0%0/1
$row_subtotals{$rk} // {}
$row_subtotals{$rk}
Truth table50%1/2
A
A= $row_subtotals{$rk}
Aresult
11
00
11916 };
11917 }
11918  
11919 31 (my $left_label = $left_spec) =~ s/\A(?:table:|path:|url:)//;
11920  
11921 31 my ($platform, $language) = $self->_resolve_template;
11922 31 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 31 31
$back2 ? : 0 31 31
Condition22%2/9
$back2 // $back
l!l&&r!l&&!r
0310
$back2_lbl or "Back"
l!l
00
$self->param("back_label") // "Back to table"
l!l
031
$self->param("back_label") // "Back to table"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
MC/DC0%0/1
$self->param("back_label") // "Back to table"
$self->param("back_label")
MC/DC0%0/1
$self->param("back_label") // "Back to table"
$self->param("back_label")
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
Truth table50%1/2
A
A= $self->param("back_label")
Aresult
11
00
Truth table0%0/2
A
A= $self->param("back_label")
Aresult
11
00
11923 handler => 'tt',
11924 template => "$platform/$language/pivot",
11925 format => 'html',
11926 title => 'Pivot: ' . join(', ', @rows),
11927 rows_dims => \@rows,
11928 cols_dims => \@cols,
11929 measures => \@measures,
11930 col_combos => \@col_combo_list,
11931 grid_rows => \@grid_rows,
11932 show_totals => $show_totals,
11933 col_subtotals => \%col_subtotals,
11934 grand_total => \%grand_total,
11935 scheme => $scheme,
11936 left_spec => $left_spec,
11937 left_label => $left_label,
11938 back_url => ($back2 // $back),
11939 back_label => ($back2 ? ($back2_lbl || 'Back') : ($self->param('back_label') // 'Back to table')),
11940 ($back2 ? (back2_url => $back, back2_label => ($self->param('back_label') // 'Back to table')) : ()),
11941 page => $page,
11942 per_page => $per_page,
11943 has_next => $piv_has_next,
11944 page_count => _page_count($total_row_groups, $per_page),
11945 page_base_url => $piv_page_url->to_string,
11946 total_row_groups => $total_row_groups,
11947 language => $language,
11948 );
11949 }
11950  
11951 =head2 stats_view
11952  
11953 C<GET /stats> -- Column statistics panel.
11954  
11955 Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus C<p=N>
11956 to choose the percentile column (1 to 100, default 95), and C<range=name> with
11957 C<rcol=column> for a relative window of rows. Displays per-column statistics:
11958 row_count, null_count, distinct_count, and for numeric columns min, max, range,
11959 mean, median, the chosen percentile and sample standard deviation; first and
11960 last are shown for every column, being the first and last value the column
11961 holds.
11962  
11963 C<distinct_count> is computed through C<_grouped_totals>, so it agrees with the
11964 pivot view. The numeric statistics are computed in Perl by sorting the column's
11965 values, through the same C<_percentile_of>, C<_median_of>, C<_stdev_of> and
11966 C<_range_of> arithmetic the pivot's C<median>, C<pN>, C<stdev> and C<range>
11967 measures use -- so a median here and a median measure there are the same number.
11968  
11969 =head3 API SPECIFICATION
11970  
11971 =head4 INPUT
11972  
11973 The query parameters above, with C<l=> required.
11974  
11975 =head4 OUTPUT
11976  
11977 200 text/html The statistics.
11978 400 text/plain 'Missing l= parameter', or error_stats_percentile when p= is
11979 not a whole number from 1 to 100.
11980 404 text/plain The source cannot be opened.
11981  
11982 =head3 FORMAL SPECIFICATION
11983  
11984 stats_view
11985 l?, p? : seq Char
11986 response! : HTTP
11987 ──────────
11988 l? = ⟨⟩ ⇒ response!.status = 400
11989 p? ≠ ⟨⟩ ∧ p? ∉ { "1" .. "100" } ⇒ response!.status = 400
11990  
11991 =cut
11992  
11993 59 ▶sub stats_view ($self) {
Subroutine stats_view: called CC=28 SCAR=34.6
Pod documented
11994 59 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
572
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
11995 59 ▶ return $self->render(text => 'Missing l= parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 3 56 59
11996 unless length $left_spec;
11997  
11998 # The percentile column is the reader's to choose; an unreadable one is a
11999 # 400 rather than a silent 95, so the page never claims a level it did not
12000 # apply.
12001 56 my $pct_arg = $self->param('p');
12002 56 my $percentile = 95;
12003 56 ▶ if (defined $pct_arg && length $pct_arg) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pct_arg and length $pct_arg) 9 47 56
Condition66%2/3
defined $pct_arg and length $pct_arg
!ll&&!rl&&r
4709
MC/DC50%1/2
defined $pct_arg and length $pct_arg
defined $pct_arg length $pct_arg
Truth table66%2/3
A and B
A= defined $pct_argB= length $pct_arg
ABresult
0X0
100
111
12004 9 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless $pct_arg =~ /\A\d{1,3}\z/u and $pct_arg >= 1 and $pct_arg <= 100 6 3 9
Condition100%6/6
$pct_arg =~ /\A\d{1,3}\z/u and $pct_arg >= 1 and $pct_arg <= 100
!ll&&!rl&&r
423
$pct_arg =~ /\A\d{1,3}\z/u and $pct_arg >= 1
!ll&&!rl&&r
315
MC/DC100%3/3
$pct_arg =~ /\A\d{1,3}\z/u and $pct_arg >= 1 and $pct_arg <= 100
$pct_arg =~ /\A\d{1,3}\z/u $pct_arg >= 1 $pct_arg <= 100
Truth table100%4/4
A and B and C
A= $pct_arg =~ /\A\d{1,3}\z/uB= $pct_arg >= 1C= $pct_arg <= 100
ABCresult
0XX0
10X0
1100
1111
12005 text => $self->_i18n('error_stats_percentile', $pct_arg),
12006 status => 400,
12007 ) unless $pct_arg =~ /\A\d{1,3}\z/ && $pct_arg >= 1 && $pct_arg <= 100;
12008 3 $percentile = $pct_arg + 0;
12009 }
12010  
12011 50 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
050
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table50%1/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
12012 50 my $back2 = _safe_back_url($self->param('back2'));
12013 50 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
050
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
12014  
12015 50 my ($src, $records, $columns) = $self->_run_pipeline_source;
12016 50 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 3 47 50
12017 unless defined $records;
12018  
12019 47 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
12020 47 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 46 47
12021  
12022 46 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 45 46
12023  
12024 45 my $row_count = scalar @$records;
12025 45 my $pipeline = { source => $src, records => $records };
12026  
12027 45 my @stats;
12028 45 for my $col (@{$columns}) {
12029 # null_count = rows where cell is undef or '' (phase 2 definition).
12030 261 ▶ my @nonnull = grep { defined $_->{$col} && length($_->{$col}) } @$records;
Condition33%1/3
defined $_->{$col} && length $_->{$col}
!ll&&!rl&&r
001593
MC/DC0%0/2
defined $_->{$col} && length $_->{$col}
defined $_->{$col} length $_->{$col}
Truth table33%1/3
A && B
A= defined $_->{$col}B= length $_->{$col}
ABresult
0X0
100
111
12031 261 my $null_count = $row_count - scalar @nonnull;
12032  
12033 # distinct_count via _grouped_totals (count groups by the column).
12034 261 my $dist_rows = $self->_grouped_totals($pipeline, {
12035 by => [$col],
12036 fn => 'count',
12037 as => 'cnt',
12038 });
12039 261 my $distinct_count = scalar @$dist_rows;
12040  
12041 # first/last: the value the column holds in the first and the last row
12042 # that has one. $nonnull is in row order, so no second pass is needed
12043 # and the two agree with the pivot's first() and last() measures.
12044 261 ▶ my $first_val = $nonnull[0] ? $nonnull[0]{$col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$nonnull[0] ? : 261 0 261
12045 261 ▶ my $last_val = $nonnull[-1] ? $nonnull[-1]{$col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$nonnull[-1] ? : 261 0 261
12046  
12047 # Numeric statistics, through the same arithmetic the pivot measures use.
12048 261 my @nums = grep { defined $_ } map { _numeric_cell($_->{$col}) } @nonnull;
12049 261 my ($min_val, $max_val, $avg_val, $median_val, $range_val, $pct_val, $stdev_val);
12050 261 ▶ if (@nums) {
Branch: 1 branch
BranchTrueFalseTotal
if (@nums) 87 174 261
12051 87 my @sorted = sort { $a <=> $b } @nums;
12052 87 $min_val = $sorted[0];
12053 87 $max_val = $sorted[-1];
12054 87 my $sum = 0;
12055 87 $sum += $_ for @nums;
12056 87 $avg_val = $sum / @nums;
12057 # _median_of is _percentile_of at 50; a stdev of one value is undef,
12058 # which the template shows as a dash rather than as a spread of 0.
12059 87 $median_val = _median_of(\@sorted);
12060 87 $range_val = _range_of(\@sorted);
12061 87 $pct_val = _percentile_of(\@sorted, $percentile);
12062 87 $stdev_val = _stdev_of(\@sorted);
12063 }
12064  
12065 261 ▶ push @stats, {
Branch: 2 branches
BranchTrueFalseTotal
defined $min_val ? : 87 174 261
defined $stdev_val ? : 87 0 87
12066 col => $col,
12067 row_count => $row_count,
12068 null_count => $null_count,
12069 distinct_count => $distinct_count,
12070 first => $first_val,
12071 last => $last_val,
12072 (defined $min_val ? (
12073 min => $min_val,
12074 max => $max_val,
12075 range => sprintf('%.4g', $range_val),
12076 avg => sprintf('%.4g', $avg_val),
12077 median => sprintf('%.4g', $median_val),
12078 pct => sprintf('%.4g', $pct_val),
12079 stdev => (defined $stdev_val ? sprintf('%.4g', $stdev_val) : undef),
12080 ) : ()),
12081 };
12082 }
12083  
12084 45 (my $left_label = $left_spec) =~ s/\A(?:table:|path:|url:)//;
12085  
12086 45 my ($platform, $language) = $self->_resolve_template;
12087 45 ▶ $self->render(
Branch: 3 branches
BranchTrueFalseTotal
CORE::index($back, '?') != -1 ? : 0 45 45
$back2 ? : 0 45 45
$back2 ? : 0 45 45
Condition22%2/9
$back2 // $back
l!l&&r!l&&!r
0450
$back2_lbl or "Back"
l!l
00
$self->param("back_label") // "Back to table"
l!l
045
$self->param("back_label") // "Back to table"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
MC/DC0%0/1
$self->param("back_label") // "Back to table"
$self->param("back_label")
MC/DC0%0/1
$self->param("back_label") // "Back to table"
$self->param("back_label")
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
Truth table50%1/2
A
A= $self->param("back_label")
Aresult
11
00
Truth table0%0/2
A
A= $self->param("back_label")
Aresult
11
00
12088 handler => 'tt',
12089 template => "$platform/$language/stats",
12090 format => 'html',
12091 title => 'Column statistics',
12092 stats => \@stats,
12093 stats_percentile => $percentile,
12094 row_count => $row_count,
12095 left_spec => $left_spec,
12096 left_label => $left_label,
12097 drill_back_url => $back,
12098 drill_sep => (CORE::index($back, '?') >= 0 ? '&' : '?'),
12099 stats_url => $self->req->url->path_query,
12100 back_url => ($back2 // $back),
12101 back_label => ($back2 ? ($back2_lbl || 'Back') : ($self->param('back_label') // 'Back to table')),
12102 ($back2 ? (back2_url => $back, back2_label => ($self->param('back_label') // 'Back to table')) : ()),
12103 language => $language,
12104 );
12105 }
12106  
12107 # ---------------------------------------------------------------------------
12108 # Calculated-field CRUD (POST /calc/save, POST /calc/delete, GET /calc/list)
12109 # ---------------------------------------------------------------------------
12110  
12111 36 ▶sub calc_save ($self) {
Subroutine calc_save: called CC=7 SCAR=19.5
Pod documented
12112 36 my $lock = $self->_models_lock; # read, change and write as one step
12113 36 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
333
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12114 36 ▶ my $name = $self->param('name') // '';
Condition100%2/2
$self->param("name") // ""
l!l
351
MC/DC100%1/1
$self->param("name") // ""
$self->param("name")
Truth table100%2/2
A
A= $self->param("name")
Aresult
11
00
12115 36 ▶ my $expr = $self->param('expr') // '';
Condition100%2/2
$self->param("expr") // ""
l!l
324
MC/DC100%1/1
$self->param("expr") // ""
$self->param("expr")
Truth table100%2/2
A
A= $self->param("expr")
Aresult
11
00
12116  
12117 36 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 3 33 36
12118 unless length $spec;
12119 33 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/u 5 28 33
12120 json => { error => $self->_i18n('error_calc_name', $name) },
12121 status => 400,
12122 ) unless $name =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/;
12123 28 ▶ return $self->render(json => { error => 'expr= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $expr 4 24 28
12124 unless length $expr;
12125  
12126 24 my $models = $self->_read_models;
12127 24 $models->{fields}{$spec}{$name} = $expr;
12128 24 $self->_write_models($models);
12129 23 $self->render(json => { ok => 1 });
12130 }
12131  
12132 16 ▶sub calc_delete ($self) {
Subroutine calc_delete: called CC=4 SCAR=13.9
Pod documented
12133 16 my $lock = $self->_models_lock; # read, change and write as one step
12134 16 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
142
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12135 16 ▶ my $name = $self->param('name') // '';
Condition100%2/2
$self->param("name") // ""
l!l
151
MC/DC100%1/1
$self->param("name") // ""
$self->param("name")
Truth table100%2/2
A
A= $self->param("name")
Aresult
11
00
12136  
12137 16 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 14 16
12138 unless length $spec;
12139  
12140 14 my $models = $self->_read_models;
12141 14 delete $models->{fields}{$spec}{$name};
12142 14 $self->_write_models($models);
12143 14 $self->render(json => { ok => 1 });
12144 }
12145  
12146 32 ▶sub calc_list ($self) {
Subroutine calc_list: called CC=4 SCAR=13.9
Pod documented
12147 32 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
293
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12148 32 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 4 28 32
12149 unless length $spec;
12150  
12151 28 my $models = $self->_read_models;
12152 28 ▶ $self->render(json => { fields => $models->{fields}{$spec} // {} });
Condition100%2/2
$models->{"fields"}{$spec} // {}
l!l
217
MC/DC100%1/1
$models->{"fields"}{$spec} // {}
$models->{"fields"}{$spec}
Truth table100%2/2
A
A= $models->{"fields"}{$spec}
Aresult
11
00
12153 }
12154  
12155 # ---------------------------------------------------------------------------
12156 # Named-group CRUD (POST /groups/save, POST /groups/delete, GET /groups/list)
12157 # ---------------------------------------------------------------------------
12158  
12159 12 ▶sub groups_save ($self) {
Subroutine groups_save: called CC=8 SCAR=20.8
Pod documented
12160 12 my $lock = $self->_models_lock; # read, change and write as one step
12161 12 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
102
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12162 12 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
93
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
12163 12 ▶ my $group_name = $self->param('group') // '';
Condition100%2/2
$self->param("group") // ""
l!l
84
MC/DC100%1/1
$self->param("group") // ""
$self->param("group")
Truth table100%2/2
A
A= $self->param("group")
Aresult
11
00
12164  
12165 # The panel sends one values= holding a line for each value; a script may just
12166 # as well repeat the parameter.
12167 12 ▶ my @values = map { split /\r?\n/ } @{ $self->every_param('values') // [] };
Condition50%1/2
$self->every_param("values") // []
l!l
120
MC/DC0%0/1
$self->every_param("values") // []
$self->every_param("values")
Truth table50%1/2
A
A= $self->every_param("values")
Aresult
11
00
12168  
12169 12 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 10 12
12170 unless length $spec;
12171 10 ▶ return $self->render(json => { error => 'col= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 2 8 10
12172 unless length $col;
12173 8 ▶ return $self->render(json => { error => 'group= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $group_name 2 6 8
12174 unless length $group_name;
12175  
12176 6 my $models = $self->_read_models;
12177 6 $models->{groups}{$spec}{$col}{$group_name} = \@values;
12178 6 $self->_write_models($models);
12179 6 $self->render(json => { ok => 1 });
12180 }
12181  
12182 7 ▶sub groups_delete ($self) {
Subroutine groups_delete: called CC=8 SCAR=20.8
Pod documented
12183 7 my $lock = $self->_models_lock; # read, change and write as one step
12184 7 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
61
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12185 7 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
34
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
12186 7 ▶ my $group_name = $self->param('group') // '';
Condition100%2/2
$self->param("group") // ""
l!l
25
MC/DC100%1/1
$self->param("group") // ""
$self->param("group")
Truth table100%2/2
A
A= $self->param("group")
Aresult
11
00
12187  
12188 7 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 6 7
12189 unless length $spec;
12190  
12191 6 my $models = $self->_read_models;
12192 6 ▶ if (length $col && length $group_name) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $col and length $group_name) { } 2 4 6
elsif (length $col) { } 1 3 4
Condition100%3/3
length $col and length $group_name
!ll&&!rl&&r
312
MC/DC100%2/2
length $col and length $group_name
length $col length $group_name
Truth table100%3/3
A and B
A= length $colB= length $group_name
ABresult
0X0
100
111
12193 2 delete $models->{groups}{$spec}{$col}{$group_name};
12194 } elsif (length $col) {
12195 1 delete $models->{groups}{$spec}{$col};
12196 } else {
12197 3 delete $models->{groups}{$spec};
12198 }
12199 6 $self->_write_models($models);
12200 6 $self->render(json => { ok => 1 });
12201 }
12202  
12203 12 ▶sub groups_list ($self) {
Subroutine groups_list: called CC=4 SCAR=13.9
Pod documented
12204 12 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
102
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12205 12 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 3 9 12
12206 unless length $spec;
12207  
12208 9 my $models = $self->_read_models;
12209 9 ▶ $self->render(json => { groups => $models->{groups}{$spec} // {} });
Condition100%2/2
$models->{"groups"}{$spec} // {}
l!l
72
MC/DC100%1/1
$models->{"groups"}{$spec} // {}
$models->{"groups"}{$spec}
Truth table100%2/2
A
A= $models->{"groups"}{$spec}
Aresult
11
00
12210 }
12211  
12212 # ---------------------------------------------------------------------------
12213 # Date-pattern CRUD (POST /dates/save, POST /dates/delete, GET /dates/list)
12214 # ---------------------------------------------------------------------------
12215  
12216 # dates_save: POST /dates/save?l=<spec>&col=<col>&pattern=<fmt>[&time=<fmt>][&as=timestamp]
12217 # Stores a strptime-style date normalisation pattern for $col in models.json.
12218 # Only the three patterns in %ALLOWED_DATE_PATTERNS are accepted, and only the
12219 # two in %ALLOWED_TIME_PATTERNS beside one of them.
12220 #
12221 # A pattern on its own is stored as the string it has always been, so an
12222 # existing entry keeps its meaning. A time, or as=timestamp, stores the hash
12223 # shape { date =>, time =>, as => } that Calc::date_normalise reads, and which
12224 # normalises the column to 'YYYY-MM-DDTHH:MM:SS' -- the shape the date
12225 # comparisons already read to the second, so a last_24_hours window filters on
12226 # a column that has a pattern of this kind.
12227 20 ▶sub dates_save ($self) {
Subroutine dates_save: called CC=17 SCAR=28.4
Pod documented
12228 20 my $lock = $self->_models_lock; # read, change and write as one step
12229 20 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
173
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12230 20 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
173
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
12231 20 ▶ my $pattern = $self->param('pattern') // '';
Condition100%2/2
$self->param("pattern") // ""
l!l
182
MC/DC100%1/1
$self->param("pattern") // ""
$self->param("pattern")
Truth table100%2/2
A
A= $self->param("pattern")
Aresult
11
00
12232 20 ▶ my $time = $self->param('time') // '';
Condition100%2/2
$self->param("time") // ""
l!l
119
MC/DC100%1/1
$self->param("time") // ""
$self->param("time")
Truth table100%2/2
A
A= $self->param("time")
Aresult
11
00
12233 20 ▶ my $as = $self->param('as') // '';
Condition100%2/2
$self->param("as") // ""
l!l
218
MC/DC100%1/1
$self->param("as") // ""
$self->param("as")
Truth table100%2/2
A
A= $self->param("as")
Aresult
11
00
12234  
12235 20 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 3 17 20
12236 unless length $spec;
12237 17 ▶ return $self->render(json => { error => 'col= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 2 15 17
12238 unless length $col;
12239 return $self->render(
12240 json => { error => $self->_i18n('error_date_pattern', $pattern) },
12241 status => 400,
12242 15 ▶ ) unless $ALLOWED_DATE_PATTERNS{$pattern};
Branch: 1 branch
BranchTrueFalseTotal
unless $ALLOWED_DATE_PATTERNS{$pattern} 4 11 15
12243 return $self->render(
12244 json => { error => $self->_i18n('error_date_time_pattern', $time) },
12245 status => 400,
12246 11 ▶ ) if length($time) && !$ALLOWED_TIME_PATTERNS{$time};
Branch: 1 branch
BranchTrueFalseTotal
if length $time and not $ALLOWED_TIME_PATTERNS{$time} 1 10 11
Condition66%2/3
length $time and not $ALLOWED_TIME_PATTERNS{$time}
!ll&&!rl&&r
1001
MC/DC50%1/2
length $time and not $ALLOWED_TIME_PATTERNS{$time}
length $time not $ALLOWED_TIME_PATTERNS{$time}
Truth table66%2/3
A and not(B)
A= length $timeB= not $ALLOWED_TIME_PATTERNS{$time}
ABresult
0X0
100
111
12247 10 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
if length $as and $as ne "timestamp" 1 9 10
Condition100%3/3
length $as and $as ne "timestamp"
!ll&&!rl&&r
811
MC/DC100%2/2
length $as and $as ne "timestamp"
length $as $as ne "timestamp"
Truth table100%3/3
A and B
A= length $asB= $as ne "timestamp"
ABresult
0X0
100
111
12248 json => { error => $self->_i18n('error_date_as', $as) },
12249 status => 400,
12250 ) if length($as) && $as ne 'timestamp';
12251  
12252 9 ▶ my $stored = (length($time) || length($as))
Branch: 3 branches
BranchTrueFalseTotal
length $time || length $as ? : 1 8 9
length $time ? : 0 1 1
length $as ? : 1 0 1
Condition66%2/3
length $time or length $as
l!l&&r!l&&!r
018
MC/DC50%1/2
length $time or length $as
length $time length $as
Truth table66%2/3
A or B
A= length $timeB= length $as
ABresult
1X1
011
000
12253 ? { date => $pattern, (length($time) ? (time => $time) : ()), (length($as) ? (as => $as) : ()) }
12254 : $pattern;
12255  
12256 9 my $models = $self->_read_models;
12257 9 $models->{date_patterns}{$spec}{$col} = $stored;
12258 9 $self->_write_models($models);
12259 9 $self->render(json => { ok => 1 });
12260 }
12261  
12262 # dates_delete: POST /dates/delete?l=<spec>&col=<col>
12263 # Removes the pattern for $col (or all patterns for $spec when col is absent).
12264 9 ▶sub dates_delete ($self) {
Subroutine dates_delete: called CC=5 SCAR=16.1
Pod documented
12265 9 my $lock = $self->_models_lock; # read, change and write as one step
12266 9 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
81
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12267 9 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
54
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
12268  
12269 9 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 8 9
12270 unless length $spec;
12271  
12272 8 my $models = $self->_read_models;
12273 8 ▶ if (length $col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $col) { } 5 3 8
12274 5 delete $models->{date_patterns}{$spec}{$col};
12275 } else {
12276 3 delete $models->{date_patterns}{$spec};
12277 }
12278 8 $self->_write_models($models);
12279 8 $self->render(json => { ok => 1 });
12280 }
12281  
12282 # dates_list: GET /dates/list?l=<spec>
12283 # Returns { patterns: { col: pattern, ... } } for $spec, where a pattern is the
12284 # date-format string it has always been or, for a column that also holds a time,
12285 # { date =>, time =>, as => }.
12286 16 ▶sub dates_list ($self) {
Subroutine dates_list: called CC=4 SCAR=13.9
Pod documented
12287 16 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
133
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12288 16 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 4 12 16
12289 unless length $spec;
12290  
12291 12 my $models = $self->_read_models;
12292 12 ▶ $self->render(json => { patterns => $models->{date_patterns}{$spec} // {} });
Condition100%2/2
$models->{"date_patterns"}{$spec} // {}
l!l
84
MC/DC100%1/1
$models->{"date_patterns"}{$spec} // {}
$models->{"date_patterns"}{$spec}
Truth table100%2/2
A
A= $models->{"date_patterns"}{$spec}
Aresult
11
00
12293 }
12294  
12295 # ---------------------------------------------------------------------------
12296 # Stored-lookup CRUD (POST /lookups/save, POST /lookups/delete, GET /lookups/list)
12297 # ---------------------------------------------------------------------------
12298  
12299 # lookups_save: POST /lookups/save?l=<spec>&name=<ident>&file=<path>&key=<col>
12300 # [&col=<col>][&fields=<col>[,<col>...]][&default=<value>]
12301 # Stores models.json lookups.<spec>.<name>. The file is read now, so a file
12302 # outside data_dir, a missing one, one too large, and a key or field it does not
12303 # have are all 400s here rather than on the next page. fields= may repeat or
12304 # hold a comma-separated list; without it every column but the key is added.
12305 19 ▶sub lookups_save ($self) {
Subroutine lookups_save: called CC=14 SCAR=26.4
Pod documented
12306 19 my $lock = $self->_models_lock; # read, change and write as one step
12307 19 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
172
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12308 19 ▶ my $name = $self->param('name') // '';
Condition100%2/2
$self->param("name") // ""
l!l
172
MC/DC100%1/1
$self->param("name") // ""
$self->param("name")
Truth table100%2/2
A
A= $self->param("name")
Aresult
11
00
12309 19 ▶ my $key = $self->param('key') // '';
Condition100%2/2
$self->param("key") // ""
l!l
154
MC/DC100%1/1
$self->param("key") // ""
$self->param("key")
Truth table100%2/2
A
A= $self->param("key")
Aresult
11
00
12310 19 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
316
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
12311 19 ▶ my @fields = grep { length } map { split /,/ } @{ $self->every_param('fields') // [] };
Condition50%1/2
$self->every_param("fields") // []
l!l
190
MC/DC0%0/1
$self->every_param("fields") // []
$self->every_param("fields")
Truth table50%1/2
A
A= $self->every_param("fields")
Aresult
11
00
12312  
12313 19 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 17 19
12314 unless length $spec;
12315 17 ▶ return $self->render(json => { error => $self->_i18n('error_lookup_name', $name) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$LOOKUP_NAME_RE/u 2 15 17
12316 unless $name =~ $LOOKUP_NAME_RE;
12317 15 ▶ return $self->render(json => { error => 'key= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $key 2 13 15
12318 unless length $key;
12319  
12320 13 ▶ my %def = (
Branch: 3 branches
BranchTrueFalseTotal
length $col ? : 3 10 13
@fields ? : 5 8 13
defined $self->param('default') ? : 0 13 13
Condition50%1/2
$self->param("file") // ""
l!l
130
MC/DC0%0/1
$self->param("file") // ""
$self->param("file")
Truth table50%1/2
A
A= $self->param("file")
Aresult
11
00
12321 file => $self->param('file') // '',
12322 key => $key,
12323 (length $col ? (col => $col) : ()),
12324 (@fields ? (fields => \@fields) : ()),
12325 (defined $self->param('default') ? (default => $self->param('default')) : ()),
12326 );
12327 13 my $ok = eval { $self->_load_lookup({ %def, name => $name }); 1 };
12328 13 ▶ return $self->render(json => { error => _tidy_error($@) }, status => 400) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 9 4 13
12329  
12330 4 my $models = $self->_read_models;
12331 4 $models->{lookups}{$spec}{$name} = \%def;
12332 4 $self->_write_models($models);
12333 4 $self->render(json => { ok => 1 });
12334 }
12335  
12336 # lookups_delete: POST /lookups/delete?l=<spec>[&name=<ident>]
12337 # Removes one lookup, or every lookup of $spec when name= is absent.
12338 6 ▶sub lookups_delete ($self) {
Subroutine lookups_delete: called CC=5 SCAR=16.1
Pod documented
12339 6 my $lock = $self->_models_lock; # read, change and write as one step
12340 6 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
42
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12341 6 ▶ my $name = $self->param('name') // '';
Condition100%2/2
$self->param("name") // ""
l!l
24
MC/DC100%1/1
$self->param("name") // ""
$self->param("name")
Truth table100%2/2
A
A= $self->param("name")
Aresult
11
00
12342  
12343 6 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 4 6
12344 unless length $spec;
12345  
12346 4 my $models = $self->_read_models;
12347 4 ▶ if (length $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $name) { } 2 2 4
12348 2 delete $models->{lookups}{$spec}{$name};
12349 } else {
12350 2 delete $models->{lookups}{$spec};
12351 }
12352 4 $self->_write_models($models);
12353 4 $self->render(json => { ok => 1 });
12354 }
12355  
12356 # lookups_list: GET /lookups/list?l=<spec>
12357 # Returns { lookups: { name: { file, key, col?, fields?, default? }, ... } }.
12358 10 ▶sub lookups_list ($self) {
Subroutine lookups_list: called CC=4 SCAR=13.9
Pod documented
12359 10 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
82
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12360 10 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 3 7 10
12361 unless length $spec;
12362  
12363 7 my $models = $self->_read_models;
12364 7 ▶ $self->render(json => { lookups => $models->{lookups}{$spec} // {} });
Condition100%2/2
$models->{"lookups"}{$spec} // {}
l!l
34
MC/DC100%1/1
$models->{"lookups"}{$spec} // {}
$models->{"lookups"}{$spec}
Truth table100%2/2
A
A= $models->{"lookups"}{$spec}
Aresult
11
00
12365 }
12366  
12367 # ---------------------------------------------------------------------------
12368 # Stored-extraction CRUD (POST /extract/save, POST /extract/delete, GET /extract/list)
12369 # ---------------------------------------------------------------------------
12370  
12371 # extract_save: POST /extract/save?l=<spec>&name=<ident>&col=<col>&pattern=<re>
12372 # [&fields=<group>[,<group>...]]
12373 # Stores models.json extractions.<spec>.<name> = { col, pattern, fields }. The
12374 # pattern is compiled now, so one that is too long, uses a refused construct,
12375 # does not compile or names no group is a 400 here. fields= picks some of the
12376 # named groups; without it every named group becomes a column.
12377 17 ▶sub extract_save ($self) {
Subroutine extract_save: called CC=12 SCAR=24.9
Pod documented
12378 17 my $lock = $self->_models_lock; # read, change and write as one step
12379 17 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
152
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12380 17 ▶ my $name = $self->param('name') // '';
Condition100%2/2
$self->param("name") // ""
l!l
152
MC/DC100%1/1
$self->param("name") // ""
$self->param("name")
Truth table100%2/2
A
A= $self->param("name")
Aresult
11
00
12381 17 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
134
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
12382 17 ▶ my $pattern = $self->param('pattern') // '';
Condition100%2/2
$self->param("pattern") // ""
l!l
134
MC/DC100%1/1
$self->param("pattern") // ""
$self->param("pattern")
Truth table100%2/2
A
A= $self->param("pattern")
Aresult
11
00
12383 17 ▶ my @fields = grep { length } map { split /,/ } @{ $self->every_param('fields') // [] };
Condition50%1/2
$self->every_param("fields") // []
l!l
170
MC/DC0%0/1
$self->every_param("fields") // []
$self->every_param("fields")
Truth table50%1/2
A
A= $self->every_param("fields")
Aresult
11
00
12384  
12385 17 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 15 17
12386 unless length $spec;
12387 15 ▶ return $self->render(json => { error => $self->_i18n('error_extract_name', $name) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$LOOKUP_NAME_RE/u 2 13 15
12388 unless $name =~ $LOOKUP_NAME_RE;
12389 13 ▶ return $self->render(json => { error => 'col= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 2 11 13
12390 unless length $col;
12391 11 ▶ return $self->render(json => { error => 'pattern= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $pattern 2 9 11
12392 unless length $pattern;
12393  
12394 9 ▶ my %def = (col => $col, pattern => $pattern, (@fields ? (fields => \@fields) : ()));
Branch: 1 branch
BranchTrueFalseTotal
@fields ? : 1 8 9
12395 9 my $fields;
12396 9 my $ok = eval { (undef, $fields) = $self->_compile_extraction($name, \%def); 1 };
12397 9 ▶ return $self->render(json => { error => _tidy_error($@) }, status => 400) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 5 4 9
12398 4 $def{fields} = $fields;
12399  
12400 4 my $models = $self->_read_models;
12401 4 $models->{extractions}{$spec}{$name} = \%def;
12402 4 $self->_write_models($models);
12403 4 $self->render(json => { ok => 1, fields => $fields });
12404 }
12405  
12406 # extract_delete: POST /extract/delete?l=<spec>[&name=<ident>]
12407 # Removes one extraction, or every extraction of $spec when name= is absent.
12408 5 ▶sub extract_delete ($self) {
Subroutine extract_delete: called CC=5 SCAR=16.1
Pod documented
12409 5 my $lock = $self->_models_lock; # read, change and write as one step
12410 5 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
32
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12411 5 ▶ my $name = $self->param('name') // '';
Condition100%2/2
$self->param("name") // ""
l!l
23
MC/DC100%1/1
$self->param("name") // ""
$self->param("name")
Truth table100%2/2
A
A= $self->param("name")
Aresult
11
00
12412  
12413 5 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 3 5
12414 unless length $spec;
12415  
12416 3 my $models = $self->_read_models;
12417 3 ▶ if (length $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $name) { } 2 1 3
12418 2 delete $models->{extractions}{$spec}{$name};
12419 } else {
12420 1 delete $models->{extractions}{$spec};
12421 }
12422 3 $self->_write_models($models);
12423 3 $self->render(json => { ok => 1 });
12424 }
12425  
12426 # extract_list: GET /extract/list?l=<spec>
12427 # Returns { extractions: { name: { col, pattern, fields }, ... } }.
12428 8 ▶sub extract_list ($self) {
Subroutine extract_list: called CC=4 SCAR=13.9
Pod documented
12429 8 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
62
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12430 8 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 3 5 8
12431 unless length $spec;
12432  
12433 5 my $models = $self->_read_models;
12434 5 ▶ $self->render(json => { extractions => $models->{extractions}{$spec} // {} });
Condition100%2/2
$models->{"extractions"}{$spec} // {}
l!l
23
MC/DC100%1/1
$models->{"extractions"}{$spec} // {}
$models->{"extractions"}{$spec}
Truth table100%2/2
A
A= $models->{"extractions"}{$spec}
Aresult
11
00
12435 }
12436  
12437 # ---------------------------------------------------------------------------
12438 # Geo column preferences CRUD (POST /geo/save, POST /geo/delete, GET /geo/list)
12439 #
12440 # Stores the user's choice of lat/lon/loc columns for a given l= spec in
12441 # models.json under geo.<spec>.columns. The geocode cache itself lives under
12442 # geo.<spec>.places and is written by _map_data independently.
12443 # ---------------------------------------------------------------------------
12444  
12445 # geo_save: POST /geo/save?l=<spec>&col=<col>&kind=lat|lon|location|location_suffix[&replace=1][&loc_text=<text>]
12446 # location_suffix is the column whose cells follow the place's, after ", "
12447 # (a country after an address). loc_text= is the text the map adds to the end
12448 # of each place ("Virginia, USA"); it is not a column, so it is kept beside
12449 # them, as geo.<spec>.loc_text, and replace=1 forgets it too.
12450 # col= and kind= may repeat, in pairs, so a latitude and a longitude are saved
12451 # in one request. replace=1 forgets the spec's saved columns first: the map
12452 # panel's "Remember" sends it, so a new choice replaces the old one rather than
12453 # leaving, say, a place-name column beside the latitude chosen after it.
12454 14 ▶sub geo_save ($self) {
Subroutine geo_save: called CC=14 SCAR=26.8
Pod documented
12455 14 my $lock = $self->_models_lock; # read, change and write as one step
12456 14 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
122
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12457 14 ▶ my @cols = @{ $self->every_param('col') // [] };
Condition50%1/2
$self->every_param("col") // []
l!l
140
MC/DC0%0/1
$self->every_param("col") // []
$self->every_param("col")
Truth table50%1/2
A
A= $self->every_param("col")
Aresult
11
00
12458 14 ▶ my @kinds = @{ $self->every_param('kind') // [] };
Condition50%1/2
$self->every_param("kind") // []
l!l
140
MC/DC0%0/1
$self->every_param("kind") // []
$self->every_param("kind")
Truth table50%1/2
A
A= $self->every_param("kind")
Aresult
11
00
12459  
12460 14 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 12 14
12461 unless length $spec;
12462 return $self->render(json => { error => 'col= required' }, status => 400)
12463 12 ▶ unless @cols && !grep { !length } @cols;
Branch: 1 branch
BranchTrueFalseTotal
unless @cols and not grep({not length $_;} @cols) 2 10 12
Condition66%2/3
@cols and not grep({not length $_;} @cols)
!ll&&!rl&&r
2010
MC/DC50%1/2
@cols and not grep({not length $_;} @cols)
@cols not grep({not length $_;} @cols)
Truth table66%2/3
A and not(B)
A= @colsB= not grep({not length $_;} @cols)
ABresult
0X0
100
111
12464 return $self->render(json => { error => 'kind must be lat, lon, location or location_suffix' }, status => 400)
12465 10 ▶ unless @kinds == @cols && !grep { !/\A(?:lat|lon|location|location_suffix)\z/ } @kinds;
Branch: 1 branch
BranchTrueFalseTotal
unless @kinds == @cols and not grep({not /\A(?:lat|lon|location|location_suffix)\z/u;} @kinds) 3 7 10
Condition100%3/3
@kinds == @cols and not grep({not /\A(?:lat|lon|location|location_suffix)\z/u;} @kinds)
!ll&&!rl&&r
127
MC/DC100%2/2
@kinds == @cols and not grep({not /\A(?:lat|lon|location|location_suffix)\z/u;} @kinds)
@kinds == @cols not grep({not /\A(?:lat|lon|location|location_suffix)\z/u;} @kinds)
Truth table100%3/3
A and not(B)
A= @kinds == @colsB= not grep({not /\A(?:lat|lon|location|location_suffix)\z/u;} @kinds)
ABresult
0X0
100
111
12466 7 ▶ my $loc_text_raw = $self->param('loc_text') // '';
Condition100%2/2
$self->param("loc_text") // ""
l!l
16
MC/DC100%1/1
$self->param("loc_text") // ""
$self->param("loc_text")
Truth table100%2/2
A
A= $self->param("loc_text")
Aresult
11
00
12467 7 my ($loc_text) = _map_loc_text($loc_text_raw);
12468 7 ▶ return $self->render(json => { error => $self->_i18n('error_map_loc_text', $Database::BI::Model::Geocode::PLACE_TEXT_MAX, $loc_text_raw) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $loc_text 1 6 7
12469 unless defined $loc_text;
12470  
12471 6 my $models = $self->_read_models;
12472 6 ▶ if ($self->param('replace')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->param("replace")) 0 6 6
12473 0 delete $models->{geo}{$spec}{columns};
12474 0 delete $models->{geo}{$spec}{loc_text};
12475 }
12476 6 $models->{geo}{$spec}{columns}{ $cols[$_] } = { kind => $kinds[$_] } for 0 .. $#cols;
12477 6 ▶ $models->{geo}{$spec}{loc_text} = $loc_text if length $loc_text;
Branch: 1 branch
BranchTrueFalseTotal
if length $loc_text 0 6 6
12478 6 $self->_write_models($models);
12479 6 $self->render(json => { ok => 1 });
12480 }
12481  
12482 # geo_delete: POST /geo/delete?l=<spec>&col=<col>
12483 # Omit col= to clear all column preferences for the spec, and its loc_text.
12484 6 ▶sub geo_delete ($self) {
Subroutine geo_delete: called CC=5 SCAR=16.1
Pod documented
12485 6 my $lock = $self->_models_lock; # read, change and write as one step
12486 6 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
42
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12487 6 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
33
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
12488  
12489 6 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 4 6
12490 unless length $spec;
12491  
12492 4 my $models = $self->_read_models;
12493 4 ▶ if (length $col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $col) { } 3 1 4
12494 3 delete $models->{geo}{$spec}{columns}{$col};
12495 } else {
12496 1 delete $models->{geo}{$spec}{columns};
12497 1 delete $models->{geo}{$spec}{loc_text};
12498 }
12499 4 $self->_write_models($models);
12500 4 $self->render(json => { ok => 1 });
12501 }
12502  
12503 # geo_list: GET /geo/list?l=<spec>
12504 # Returns { columns: { col: { kind: "lat"|"lon"|"location"|"location_suffix" }, ... } },
12505 # with loc_text: "<text>" when that is remembered too.
12506 9 ▶sub geo_list ($self) {
Subroutine geo_list: called CC=7 SCAR=20.7
Pod documented
12507 9 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
72
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12508 9 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 3 6 9
12509 unless length $spec;
12510  
12511 6 my $models = $self->_read_models;
12512 6 my $loc_text = $models->{geo}{$spec}{loc_text};
12513 $self->render(json => {
12514 columns => $models->{geo}{$spec}{columns} // {},
12515 6 ▶ (defined($loc_text) && !ref($loc_text) && length($loc_text) ? (loc_text => $loc_text) : ()),
Branch: 1 branch
BranchTrueFalseTotal
defined $loc_text && !ref($loc_text) && length $loc_text ? : 0 6 6
Condition50%4/8
$models->{"geo"}{$spec}{"columns"} // {}
l!l
33
defined $loc_text and not ref $loc_text and length $loc_text
!ll&&!rl&&r
600
defined $loc_text and not ref $loc_text
!ll&&!rl&&r
600
MC/DC100%1/1
$models->{"geo"}{$spec}{"columns"} // {}
$models->{"geo"}{$spec}{"columns"}
MC/DC0%0/3
defined $loc_text and not ref $loc_text and length $loc_text
defined $loc_text not ref $loc_text length $loc_text
Truth table100%2/2
A
A= $models->{"geo"}{$spec}{"columns"}
Aresult
11
00
Truth table25%1/4
A and not(B) and C
A= defined $loc_textB= not ref $loc_textC= length $loc_text
ABCresult
0XX0
10X0
1100
1111
12516 });
12517 }
12518  
12519 # ---------------------------------------------------------------------------
12520 # Scatter chart (GET /scatter)
12521 # ---------------------------------------------------------------------------
12522  
12523 54 ▶sub scatter_view ($self) {
Subroutine scatter_view: called CC=45 SCAR=42.1
Pod documented
12524 54 ▶ my $x_col = $self->param('x') // '';
Condition100%2/2
$self->param("x") // ""
l!l
504
MC/DC100%1/1
$self->param("x") // ""
$self->param("x")
Truth table100%2/2
A
A= $self->param("x")
Aresult
11
00
12525 54 ▶ my $y_col = $self->param('y') // '';
Condition100%2/2
$self->param("y") // ""
l!l
504
MC/DC100%1/1
$self->param("y") // ""
$self->param("y")
Truth table100%2/2
A
A= $self->param("y")
Aresult
11
00
12526 54 ▶ my $series_col = $self->param('series') // '';
Condition100%2/2
$self->param("series") // ""
l!l
153
MC/DC100%1/1
$self->param("series") // ""
$self->param("series")
Truth table100%2/2
A
A= $self->param("series")
Aresult
11
00
12527 54 ▶ my $size_col = $self->param('size') // '';
Condition100%2/2
$self->param("size") // ""
l!l
252
MC/DC100%1/1
$self->param("size") // ""
$self->param("size")
Truth table100%2/2
A
A= $self->param("size")
Aresult
11
00
12528 54 ▶ my $scheme = $self->param('scheme') // 'tableau10';
Condition100%2/2
$self->param("scheme") // "tableau10"
l!l
351
MC/DC100%1/1
$self->param("scheme") // "tableau10"
$self->param("scheme")
Truth table100%2/2
A
A= $self->param("scheme")
Aresult
11
00
12529 54 my ($min_r, $max_r) = _scatter_radii($self->param('min_r'), $self->param('max_r'));
12530 54 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
054
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table50%1/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
12531 54 my $back2 = _safe_back_url($self->param('back2'));
12532 54 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
054
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
12533  
12534 54 ▶ return $self->render(text => 'Missing x= parameter', status => 400) unless length $x_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col 5 49 54
12535 49 ▶ return $self->render(text => 'Missing y= parameter', status => 400) unless length $y_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $y_col 2 47 49
12536  
12537 47 my ($src, $records, $columns) = $self->_run_pipeline_source;
12538 47 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 2 45 47
12539  
12540 45 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
12541 45 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 44 45
12542  
12543 44 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 43 44
12544  
12545 43 my %col_set = map { $_ => 1 } @{$columns};
12546 43 ▶ return $self->render(text => "Column not found: $x_col", status => 400) unless $col_set{$x_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$x_col} 2 41 43
12547 41 ▶ return $self->render(text => "Column not found: $y_col", status => 400) unless $col_set{$y_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$y_col} 1 40 41
12548 return $self->render(text => "Column not found: $series_col", status => 400)
12549 40 ▶ if length $series_col && !$col_set{$series_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $series_col and not $col_set{$series_col} 0 40 40
Condition66%2/3
length $series_col and not $col_set{$series_col}
!ll&&!rl&&r
3910
MC/DC0%0/2
length $series_col and not $col_set{$series_col}
length $series_col not $col_set{$series_col}
Truth table66%2/3
A and not(B)
A= length $series_colB= not $col_set{$series_col}
ABresult
0X0
100
111
12550 return $self->render(text => "Column not found: $size_col", status => 400)
12551 40 ▶ if length $size_col && !$col_set{$size_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $size_col and not $col_set{$size_col} 1 39 40
Condition66%2/3
length $size_col and not $col_set{$size_col}
!ll&&!rl&&r
3901
MC/DC50%1/2
length $size_col and not $col_set{$size_col}
length $size_col not $col_set{$size_col}
Truth table66%2/3
A and not(B)
A= length $size_colB= not $col_set{$size_col}
ABresult
0X0
100
111
12552  
12553 39 ▶ if (length $series_col && !$SCATTER_SCHEMES{$scheme}) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col and not $SCATTER_SCHEMES{$scheme}) 1 38 39
Condition66%2/3
length $series_col and not $SCATTER_SCHEMES{$scheme}
!ll&&!rl&&r
3801
MC/DC50%1/2
length $series_col and not $SCATTER_SCHEMES{$scheme}
length $series_col not $SCATTER_SCHEMES{$scheme}
Truth table66%2/3
A and not(B)
A= length $series_colB= not $SCATTER_SCHEMES{$scheme}
ABresult
0X0
100
111
12554 1 return $self->render(text => "Unknown colour scheme: $scheme", status => 400);
12555 }
12556  
12557 38 my @points;
12558 38 for my $row (@$records) {
12559 227 ▶ my $xv = _numeric_cell($row->{$x_col} // '');
Condition50%1/2
$row->{$x_col} // ""
l!l
2270
MC/DC0%0/1
$row->{$x_col} // ""
$row->{$x_col}
Truth table50%1/2
A
A= $row->{$x_col}
Aresult
11
00
12560 227 ▶ my $yv = _numeric_cell($row->{$y_col} // '');
Condition50%1/2
$row->{$y_col} // ""
l!l
2270
MC/DC0%0/1
$row->{$y_col} // ""
$row->{$y_col}
Truth table50%1/2
A
A= $row->{$y_col}
Aresult
11
00
12561 227 ▶ next unless defined $xv && defined $yv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $xv and defined $yv 210 17 227
Condition66%2/3
defined $xv and defined $yv
!ll&&!rl&&r
210017
MC/DC50%1/2
defined $xv and defined $yv
defined $xv defined $yv
Truth table66%2/3
A and B
A= defined $xvB= defined $yv
ABresult
0X0
100
111
12562 60 ▶ my %extra = map { $_ => _decode_cell($row->{$_} // '') }
Condition50%1/2
$row->{$_} // ""
l!l
600
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table50%1/2
A
A= $row->{$_}
Aresult
11
00
12563 17 ▶ grep { $_ ne $x_col && $_ ne $y_col } @$columns;
Condition100%3/3
$_ ne $x_col && $_ ne $y_col
!ll&&!rl&&r
17560
MC/DC100%2/2
$_ ne $x_col && $_ ne $y_col
$_ ne $x_col $_ ne $y_col
Truth table100%3/3
A && B
A= $_ ne $x_colB= $_ ne $y_col
ABresult
0X0
100
111
12564 17 my %pt_meta;
12565 17 ▶ $pt_meta{series} = _decode_cell($row->{$series_col}) if length $series_col;
Branch: 1 branch
BranchTrueFalseTotal
if length $series_col 0 17 17
12566 17 ▶ if (length $size_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $size_col) 0 17 17
12567 0 ▶ my $sv = _numeric_cell($row->{$size_col} // '');
Condition0%0/2
$row->{$size_col} // ""
l!l
00
MC/DC0%0/1
$row->{$size_col} // ""
$row->{$size_col}
Truth table0%0/2
A
A= $row->{$size_col}
Aresult
11
00
12568 0 ▶ $pt_meta{size} = $sv if defined $sv;
Branch: 1 branch
BranchTrueFalseTotal
if defined $sv 0 0 0
12569 }
12570 17 ▶ push @points, [$xv, $yv, \%extra, (%pt_meta ? \%pt_meta : ())];
Branch: 1 branch
BranchTrueFalseTotal
%pt_meta ? : 0 17 17
12571 }
12572  
12573 38 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @points 35 3 38
12574 text => 'No plottable data: no rows have valid numeric values in both selected columns.',
12575 status => 200,
12576 ) unless @points;
12577  
12578 3 my ($source_url, $source_accessed) = $self->_url_attribution;
12579  
12580 3 require HTML::D3;
12581 3 my $title = "$y_col vs $x_col";
12582 3 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 480)
Branch: 2 branches
BranchTrueFalseTotal
length $series_col ? : 0 3 3
length $size_col ? : 0 3 3
12583 ->render_scatter_chart_snippet(\@points, {
12584 animated => 1,
12585 x_label => $x_col,
12586 y_label => $y_col,
12587 (length $series_col ? (colour_by_series => 1, series_col => $series_col, scheme => $scheme) : ()),
12588 (length $size_col ? (size_col => $size_col, radius_range => [$min_r, $max_r]) : ()),
12589 });
12590  
12591 3 my $chart_html = $snippet->{html};
12592 3 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 3 3
12593  
12594 3 ▶ my %chart_spec = (
Branch: 4 branches
BranchTrueFalseTotal
length $series_col ? : 0 3 3
length $size_col ? : 0 3 3
length $series_col ? : 0 3 3
length $size_col ? : 0 3 3
12595 kind => 'scatter',
12596 title => $title,
12597 encode => { x => $x_col, y => $y_col,
12598 (length $series_col ? (series => $series_col) : ()),
12599 (length $size_col ? (size => $size_col) : ()),
12600 },
12601 # scheme= means nothing without series=, and is unchecked then, so it
12602 # is not saved: a canvas copy would otherwise carry ?scheme=Blues. The
12603 # radii likewise only with size=.
12604 options => {
12605 (length $series_col ? (scheme => $scheme) : ()),
12606 (length $size_col ? (min_r => $min_r, max_r => $max_r) : ()),
12607 },
12608 );
12609 3 my ($platform, $language) = $self->_resolve_template;
12610 3 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 3 3
$back2 ? : 0 3 3
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
030
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
12611 handler => 'tt',
12612 template => "$platform/$language/scatter",
12613 format => 'html',
12614 title => $title,
12615 chart_html => $chart_html,
12616 chart => \%chart_spec,
12617 chart_json => $self->_chart_json(\%chart_spec),
12618 point_count => scalar @points,
12619 x_col => $x_col,
12620 y_col => $y_col,
12621 back_url => ($back2 // $back),
12622 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
12623 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
12624 source_url => $source_url,
12625 source_accessed => $source_accessed,
12626 language => $language,
12627 );
12628 }
12629  
12630 # ---------------------------------------------------------------------------
12631 # Stacked bar chart (GET /stacked)
12632 # ---------------------------------------------------------------------------
12633  
12634 61 ▶sub stacked_view ($self) {
Subroutine stacked_view: called CC=36 SCAR=39.9
Pod documented
12635 61 ▶ my $cat_col = $self->param('cat') // '';
Condition100%2/2
$self->param("cat") // ""
l!l
574
MC/DC100%1/1
$self->param("cat") // ""
$self->param("cat")
Truth table100%2/2
A
A= $self->param("cat")
Aresult
11
00
12636 # ?series= is the canonical spec name; ?seg= is the legacy alias (keep both).
12637 61 ▶ my $seg_col = $self->param('series') // $self->param('seg') // '';
Condition100%5/5
($self->param("series") // $self->param("seg")) // ""
l!l
1645
$self->param("series") // $self->param("seg")
l!l&&r!l&&!r
8845
MC/DC100%2/2
($self->param("series") // $self->param("seg")) // ""
$self->param("series") $self->param("seg")
Truth table100%3/3
A // B
A= $self->param("series")B= $self->param("seg")
ABresult
1X1
011
000
12638 61 ▶ my $val_col = $self->param('val') // '';
Condition100%2/2
$self->param("val") // ""
l!l
853
MC/DC100%1/1
$self->param("val") // ""
$self->param("val")
Truth table100%2/2
A
A= $self->param("val")
Aresult
11
00
12639 61 ▶ my $orient = $self->param('orient') // 'v';
Condition50%1/2
$self->param("orient") // "v"
l!l
061
MC/DC0%0/1
$self->param("orient") // "v"
$self->param("orient")
Truth table50%1/2
A
A= $self->param("orient")
Aresult
11
00
12640 61 my $scheme = _categorical_scheme($self->param('scheme'));
12641 61 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
061
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table50%1/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
12642 61 my $back2 = _safe_back_url($self->param('back2'));
12643 61 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
061
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
12644  
12645 61 ▶ return $self->render(text => 'Missing cat= parameter', status => 400) unless length $cat_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col 5 56 61
12646 56 ▶ return $self->render(text => 'Missing series= parameter', status => 400) unless length $seg_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $seg_col 43 13 56
12647  
12648 13 my ($src, $records, $columns) = $self->_run_pipeline_source;
12649 13 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 12 13
12650  
12651 12 my $span = $self->_span_calc_spec($columns, 'cat');
12652 12 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 0 12 12
Condition33%1/3
$span and $span->{"error"}
!ll&&!rl&&r
1200
MC/DC0%0/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table33%1/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
12653  
12654 12 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
12655 12 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 12 12
12656 0 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 12 12
12657  
12658 12 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 12 12
12659  
12660 12 my %col_set = map { $_ => 1 } @{$columns};
12661 12 ▶ return $self->render(text => "Column not found: $cat_col", status => 400) unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 1 11 12
12662 11 ▶ return $self->render(text => "Column not found: $seg_col", status => 400) unless $col_set{$seg_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$seg_col} 1 10 11
12663  
12664 10 ▶ my $count_mode = (!length $val_col || $val_col eq '__count__');
Condition66%2/3
!length($val_col) || $val_col eq '__count__'
l!l&&r!l&&!r
406
MC/DC50%1/2
!length($val_col) || $val_col eq '__count__'
!length($val_col) $val_col eq '__count__'
Truth table66%2/3
not(A) || B
A= !length($val_col)B= $val_col eq '__count__'
ABresult
1X1
011
000
12665 return $self->render(text => "Column not found: $val_col", status => 400)
12666 10 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 0 10 10
Condition66%2/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
460
MC/DC0%0/2
$count_mode or $col_set{$val_col}
$count_mode $col_set{$val_col}
Truth table66%2/3
A or B
A= $count_modeB= $col_set{$val_col}
ABresult
1X1
011
000
12667  
12668 10 ▶ $cat_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 10 10
12669  
12670 # Aggregate by [cat, seg] via _grouped_totals to respect the governing
12671 # invariant (all numbers from a single path) and to get ascending key order.
12672 10 ▶ my $agg_rows = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 4 6 10
$count_mode ? : 4 6 10
12673 { source => $src, records => $records },
12674 {
12675 by => [$cat_col, $seg_col],
12676 fn => $count_mode ? 'count' : 'sum',
12677 val => $count_mode ? undef : $val_col,
12678 as => 'value',
12679 },
12680 );
12681  
12682 # render_stacked_bar_snippet accepts flat [{cat_col=>,seg_col=>,val_col=>}] rows
12683 # and handles the stacking itself; only include pairs actually returned (no phantom
12684 # zero cells for missing intersections).
12685 my @data = map {
12686 10 ▶ my $cat = _decode_cell($_->{$cat_col} // '');
Condition50%1/2
$_->{$cat_col} // ""
l!l
380
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
Truth table50%1/2
A
A= $_->{$cat_col}
Aresult
11
00
12687 38 ▶ my $seg = _decode_cell($_->{$seg_col} // '');
Condition50%1/2
$_->{$seg_col} // ""
l!l
380
MC/DC0%0/1
$_->{$seg_col} // ""
$_->{$seg_col}
Truth table50%1/2
A
A= $_->{$seg_col}
Aresult
11
00
12688 (length $cat && length $seg)
12689 ? { cat => $cat, seg => $seg, val => $_->{value} }
12690 : ()
12691 38 ▶ } @$agg_rows;
Branch: 1 branch
BranchTrueFalseTotal
length $cat && length $seg ? : 38 0 38
Condition33%1/3
length $cat and length $seg
!ll&&!rl&&r
0038
MC/DC0%0/2
length $cat and length $seg
length $cat length $seg
Truth table33%1/3
A and B
A= length $catB= length $seg
ABresult
0X0
100
111
12692  
12693 10 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @data 0 10 10
12694 text => 'No plottable data: no rows have valid data in the selected columns.',
12695 status => 200,
12696 ) unless @data;
12697  
12698 10 my ($source_url, $source_accessed) = $self->_url_attribution;
12699  
12700 10 require HTML::D3;
12701 10 ▶ my $title = $count_mode ? "Count by $cat_col and $seg_col"
Branch: 1 branch
BranchTrueFalseTotal
$count_mode ? : 4 6 10
12702 : "$val_col by $cat_col and $seg_col";
12703 10 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 900, height => 500)
Branch: 1 branch
BranchTrueFalseTotal
$orient eq 'h' ? : 0 10 10
12704 ->render_stacked_bar_snippet(\@data, {
12705 orient => ($orient eq 'h') ? 'h' : 'v',
12706 x_label => $cat_col,
12707 scheme => $scheme,
12708 });
12709  
12710 10 my $chart_html = $snippet->{html};
12711 10 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 10 10
12712  
12713 10 my %chart_spec = (
12714 kind => 'stacked',
12715 title => $title,
12716 encode => { cat => $cat_col, series => $seg_col, value => $val_col },
12717 options => { orientation => $orient, scheme => $scheme },
12718 );
12719 10 my ($platform, $language) = $self->_resolve_template;
12720 $self->render(
12721 handler => 'tt',
12722 template => "$platform/$language/stacked",
12723 format => 'html',
12724 title => $title,
12725 chart_html => $chart_html,
12726 chart => \%chart_spec,
12727 chart_json => $self->_chart_json(\%chart_spec),
12728 10 ▶ bar_count => scalar(grep { defined $_->{cat} } @data),
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 10 10
$back2 ? : 0 10 10
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0100
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
12729 back_url => ($back2 // $back),
12730 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
12731 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
12732 source_url => $source_url,
12733 source_accessed => $source_accessed,
12734 language => $language,
12735 );
12736 }
12737  
12738 # ---------------------------------------------------------------------------
12739 # Combo bar+line chart (GET /combo)
12740 # ---------------------------------------------------------------------------
12741  
12742 56 ▶sub combo_view ($self) {
Subroutine combo_view: called CC=42 SCAR=42.7
Pod documented
12743 # ?cat= is the canonical spec name; ?x= is the legacy alias (keep both).
12744 56 ▶ my $x_col = $self->param('cat') // $self->param('x') // '';
Condition100%5/5
($self->param("cat") // $self->param("x")) // ""
l!l
524
$self->param("cat") // $self->param("x")
l!l&&r!l&&!r
4934
MC/DC100%2/2
($self->param("cat") // $self->param("x")) // ""
$self->param("cat") $self->param("x")
Truth table100%3/3
A // B
A= $self->param("cat")B= $self->param("x")
ABresult
1X1
011
000
12745 # ?bar_val= is the canonical spec name; ?bar= is the legacy alias (keep both).
12746 56 ▶ my $bar_col = $self->param('bar_val') // $self->param('bar') // '';
Condition100%5/5
($self->param("bar_val") // $self->param("bar")) // ""
l!l
1145
$self->param("bar_val") // $self->param("bar")
l!l&&r!l&&!r
4745
MC/DC100%2/2
($self->param("bar_val") // $self->param("bar")) // ""
$self->param("bar_val") $self->param("bar")
Truth table100%3/3
A // B
A= $self->param("bar_val")B= $self->param("bar")
ABresult
1X1
011
000
12747 # ?line_val= is the canonical spec name; ?line= is the legacy alias (keep both).
12748 56 ▶ my $line_col = $self->param('line_val') // $self->param('line') // '';
Condition100%5/5
($self->param("line_val") // $self->param("line")) // ""
l!l
1145
$self->param("line_val") // $self->param("line")
l!l&&r!l&&!r
4745
MC/DC100%2/2
($self->param("line_val") // $self->param("line")) // ""
$self->param("line_val") $self->param("line")
Truth table100%3/3
A // B
A= $self->param("line_val")B= $self->param("line")
ABresult
1X1
011
000
12749 56 ▶ my $bar_label = $self->param('bar_label') // '';
Condition50%1/2
$self->param("bar_label") // ""
l!l
056
MC/DC0%0/1
$self->param("bar_label") // ""
$self->param("bar_label")
Truth table50%1/2
A
A= $self->param("bar_label")
Aresult
11
00
12750 56 ▶ my $line_label = $self->param('line_label') // '';
Condition50%1/2
$self->param("line_label") // ""
l!l
056
MC/DC0%0/1
$self->param("line_label") // ""
$self->param("line_label")
Truth table50%1/2
A
A= $self->param("line_label")
Aresult
11
00
12751 56 my $scheme = _optional_scheme($self->param('scheme'));
12752 56 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
056
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table50%1/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
12753 56 my $back2 = _safe_back_url($self->param('back2'));
12754 56 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
056
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
12755  
12756 56 ▶ return $self->render(text => 'Missing cat= parameter', status => 400) unless length $x_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col 5 51 56
12757 51 ▶ return $self->render(text => 'Missing bar_val= parameter', status => 400) unless length $bar_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $bar_col 43 8 51
12758 8 ▶ return $self->render(text => 'Missing line_val= parameter', status => 400) unless length $line_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $line_col 3 5 8
12759  
12760 5 my ($src, $records, $columns) = $self->_run_pipeline_source;
12761 5 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 4 5
12762  
12763 4 my $span = $self->_span_calc_spec($columns, 'cat', 'x');
12764 4 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 0 4 4
Condition33%1/3
$span and $span->{"error"}
!ll&&!rl&&r
400
MC/DC0%0/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table33%1/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
12765  
12766 4 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
12767 4 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 4 4
12768 0 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 4 4
12769  
12770 4 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 4 4
12771  
12772 4 my %col_set = map { $_ => 1 } @{$columns};
12773 4 ▶ return $self->render(text => "Column not found: $x_col", status => 400) unless $col_set{$x_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$x_col} 0 4 4
12774 4 ▶ return $self->render(text => "Column not found: $bar_col", status => 400) unless $col_set{$bar_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$bar_col} 0 4 4
12775 4 ▶ return $self->render(text => "Column not found: $line_col", status => 400) unless $col_set{$line_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$line_col} 0 4 4
12776  
12777 4 ▶ $x_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 4 4
12778  
12779 # Aggregate bar and line measures separately via _grouped_totals so both
12780 # use the same path (push or fold) and produce ascending x-axis order.
12781 # A category missing from one result set renders as a gap (undef), not zero.
12782 4 my $bar_rows = $self->_grouped_totals(
12783 { source => $src, records => $records },
12784 { by => [$x_col], fn => 'sum', val => $bar_col, as => 'bar_val' },
12785 );
12786 4 my $line_rows = $self->_grouped_totals(
12787 { source => $src, records => $records },
12788 { by => [$x_col], fn => 'sum', val => $line_col, as => 'line_val' },
12789 );
12790  
12791 # Merge: build a lookup from both result sets and walk the union of categories.
12792 4 my (%bar_map, %line_map, @x_order, %x_seen);
12793 4 for my $r (@$bar_rows) {
12794 13 ▶ my $xv = _decode_cell($r->{$x_col} // '');
Condition50%1/2
$r->{$x_col} // ""
l!l
130
MC/DC0%0/1
$r->{$x_col} // ""
$r->{$x_col}
Truth table50%1/2
A
A= $r->{$x_col}
Aresult
11
00
12795 13 ▶ next unless length $xv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $xv 0 13 13
12796 13 ▶ push @x_order, $xv unless $x_seen{$xv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $x_seen{$xv}++ 13 0 13
12797 13 $bar_map{$xv} = $r->{bar_val};
12798 }
12799 4 for my $r (@$line_rows) {
12800 13 ▶ my $xv = _decode_cell($r->{$x_col} // '');
Condition50%1/2
$r->{$x_col} // ""
l!l
130
MC/DC0%0/1
$r->{$x_col} // ""
$r->{$x_col}
Truth table50%1/2
A
A= $r->{$x_col}
Aresult
11
00
12801 13 ▶ next unless length $xv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $xv 0 13 13
12802 13 ▶ push @x_order, $xv unless $x_seen{$xv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $x_seen{$xv}++ 0 13 13
12803 13 $line_map{$xv} = $r->{line_val};
12804 }
12805  
12806 4 my @data = map { {
12807 x => $_,
12808 bar_val => $bar_map{$_}, # undef = gap in bar series
12809 13 line_val => $line_map{$_}, # undef = gap in line series
12810 } } @x_order;
12811  
12812 4 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @data 0 4 4
12813 text => 'No plottable data: no rows have valid data in the selected columns.',
12814 status => 200,
12815 ) unless @data;
12816  
12817 4 my ($source_url, $source_accessed) = $self->_url_attribution;
12818  
12819 4 require HTML::D3;
12820 4 ▶ my $eff_bar_lbl = $bar_label || $bar_col;
Condition33%1/3
$bar_label || $bar_col
l!l&&r!l&&!r
040
MC/DC0%0/2
$bar_label || $bar_col
$bar_label $bar_col
Truth table33%1/3
A || B
A= $bar_labelB= $bar_col
ABresult
1X1
011
000
12821 4 ▶ my $eff_line_lbl = $line_label || $line_col;
Condition33%1/3
$line_label || $line_col
l!l&&r!l&&!r
040
MC/DC0%0/2
$line_label || $line_col
$line_label $line_col
Truth table33%1/3
A || B
A= $line_labelB= $line_col
ABresult
1X1
011
000
12822 4 my $title = "$eff_bar_lbl and $eff_line_lbl by $x_col";
12823 4 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 900, height => 500)
Branch: 1 branch
BranchTrueFalseTotal
$scheme ? : 0 4 4
12824 ->render_combo_snippet(\@data, {
12825 bar_label => $eff_bar_lbl,
12826 line_label => $eff_line_lbl,
12827 ($scheme ? (scheme => $scheme) : ()),
12828 });
12829  
12830 4 my $chart_html = $snippet->{html};
12831 4 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 4 4
12832  
12833 4 ▶ my %chart_spec = (
Branch: 1 branch
BranchTrueFalseTotal
$scheme ? : 0 4 4
12834 kind => 'combo',
12835 title => $title,
12836 encode => { x => $x_col, bar => $bar_col, line => $line_col },
12837 ($scheme ? (options => { scheme => $scheme }) : ()),
12838 );
12839 4 my ($platform, $language) = $self->_resolve_template;
12840 4 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 4 4
$back2 ? : 0 4 4
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
040
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
12841 handler => 'tt',
12842 template => "$platform/$language/combo",
12843 format => 'html',
12844 title => $title,
12845 chart_html => $chart_html,
12846 chart => \%chart_spec,
12847 chart_json => $self->_chart_json(\%chart_spec),
12848 point_count => scalar @data,
12849 back_url => ($back2 // $back),
12850 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
12851 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
12852 source_url => $source_url,
12853 source_accessed => $source_accessed,
12854 language => $language,
12855 );
12856 }
12857  
12858 # ---------------------------------------------------------------------------
12859 # Treemap (GET /treemap)
12860 # ---------------------------------------------------------------------------
12861  
12862 # _tile_colour_measure($self, $fn, $col) -> \%measure | { error => $text }
12863 #
12864 # The measure a treemap's tiles are coloured by: $fn (color_agg=, or a card's
12865 # options.color_agg) of $col, average when $fn is absent or empty, since a
12866 # margin or a rating is read as an average rather than a total. A name that
12867 # is not an aggregate function comes back as { error }, worded as the
12868 # function check elsewhere words it. /treemap and a canvas treemap card both
12869 # ask here, so they accept and refuse the same names.
12870 7 ▶sub _tile_colour_measure :Protected ($self, $fn, $col) {
Subroutine _tile_colour_measure: called CC=5 SCAR=16.1
12871 7 ▶ $fn = (defined $fn && !ref $fn) ? lc $fn : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $fn && !ref($fn) ? : 4 3 7
Condition100%3/3
defined $fn and not ref $fn
!ll&&!rl&&r
214
MC/DC100%2/2
defined $fn and not ref $fn
defined $fn not ref $fn
Truth table100%3/3
A and not(B)
A= defined $fnB= not ref $fn
ABresult
0X0
100
111
12872 7 ▶ $fn = 'avg' unless length $fn;
Branch: 1 branch
BranchTrueFalseTotal
unless length $fn 3 4 7
12873 7 ▶ return { error => $self->_i18n('error_agg_fn', $fn, join(' ', @MEASURE_FNS)) }
Branch: 1 branch
BranchTrueFalseTotal
unless _measure_fn_ok($fn) 1 6 7
12874 unless _measure_fn_ok($fn);
12875 6 return _visual_measure($fn, $col);
12876 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
12877  
12878 # _tile_colours($self, $source, \@records, $cat_col, \%measure) -> \%colour_of
12879 #
12880 # The number each treemap tile is coloured by: the measure (from
12881 # _visual_measure) folded per value of $cat_col, keyed by the raw value. With
12882 # $cat_col undef it is one total over every row, under the key ''. A group
12883 # whose result is not a finite number has no entry, and its tile is drawn
12884 # grey. /treemap and a canvas treemap card both fold here, so a card saved
12885 # from the page is coloured by the same numbers.
12886 3 ▶sub _tile_colours :Protected ($self, $source, $records, $cat_col, $m) {
Subroutine _tile_colours: called CC=8 SCAR=22.5
12887 my $rows = $self->_grouped_totals(
12888 { source => $source, records => $records },
12889 { by => [ defined $cat_col ? ($cat_col) : () ],
12890 3 ▶ fn => $m->{fn}, val => $m->{val}, as => 'colour' },
Branch: 1 branch
BranchTrueFalseTotal
defined $cat_col ? : 2 1 3
12891 );
12892 3 my %colour_of;
12893 3 for my $r (@$rows) {
12894 3 my $v = $r->{colour};
12895 3 ▶ next unless defined $v && Scalar::Util::looks_like_number($v) && $v !~ /\A\s*[-+]?(?:nan|inf)/i;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and &Scalar::Util::looks_like_number($v) and not $v =~ /\A\s*[-+]?(?:nan|inf)/iu 0 3 3
Condition33%2/6
defined $v and &Scalar::Util::looks_like_number($v) and not $v =~ /\A\s*[-+]?(?:nan|inf)/iu
!ll&&!rl&&r
003
defined $v and &Scalar::Util::looks_like_number($v)
!ll&&!rl&&r
003
MC/DC0%0/3
defined $v and &Scalar::Util::looks_like_number($v) and not $v =~ /\A\s*[-+]?(?:nan|inf)/iu
defined $v &Scalar::Util::looks_like_number($v) not $v =~ /\A\s*[-+]?(?:nan|inf)/iu
Truth table25%1/4
A and B and not(C)
A= defined $vB= &Scalar::Util::looks_like_number($v)C= not $v =~ /\A\s*[-+]?(?:nan|inf)/iu
ABCresult
0XX0
10X0
1100
1111
12896 3 ▶ $colour_of{ defined $cat_col ? ($r->{$cat_col} // '') : '' } = $v + 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $cat_col ? : 2 1 3
Condition50%1/2
$r->{$cat_col} // ""
l!l
20
MC/DC0%0/1
$r->{$cat_col} // ""
$r->{$cat_col}
Truth table50%1/2
A
A= $r->{$cat_col}
Aresult
11
00
12897 }
12898 3 return \%colour_of;
12899 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
12900  
12901 58 ▶sub treemap_view ($self) {
Subroutine treemap_view: called CC=54 SCAR=52.0
Pod documented
12902 # ?group= is the canonical spec name; ?cat= is the legacy alias (keep both).
12903 58 ▶ my $cat_col = $self->param('group') // $self->param('cat') // '';
Condition100%5/5
($self->param("group") // $self->param("cat")) // ""
l!l
544
$self->param("group") // $self->param("cat")
l!l&&r!l&&!r
11434
MC/DC100%2/2
($self->param("group") // $self->param("cat")) // ""
$self->param("group") $self->param("cat")
Truth table100%3/3
A // B
A= $self->param("group")B= $self->param("cat")
ABresult
1X1
011
000
12904 # ?size= is the canonical spec name; ?val= is the legacy alias (keep both).
12905 58 ▶ my $val_col = $self->param('size') // $self->param('val') // '';
Condition100%5/5
($self->param("size") // $self->param("val")) // ""
l!l
949
$self->param("size") // $self->param("val")
l!l&&r!l&&!r
8149
MC/DC100%2/2
($self->param("size") // $self->param("val")) // ""
$self->param("size") $self->param("val")
Truth table100%3/3
A // B
A= $self->param("size")B= $self->param("val")
ABresult
1X1
011
000
12906 58 my $scheme = _categorical_scheme($self->param('scheme'));
12907 58 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
058
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table50%1/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
12908 58 my $back2 = _safe_back_url($self->param('back2'));
12909 58 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
058
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
12910  
12911 # ?color= shades each tile by a second column, folded per tile with
12912 # ?color_agg= (default avg: a margin or a rating is read as an average, not
12913 # a total) on the sequential ?color_scheme=, as the heatmap's cells are.
12914 58 ▶ my $color_col = $self->param('color') // '';
Condition100%2/2
$self->param("color") // ""
l!l
157
MC/DC100%1/1
$self->param("color") // ""
$self->param("color")
Truth table100%2/2
A
A= $self->param("color")
Aresult
11
00
12915 58 ▶ my $color_m = length $color_col
Branch: 1 branch
BranchTrueFalseTotal
length $color_col ? : 1 57 58
12916 ? $self->_tile_colour_measure($self->param('color_agg'), $color_col)
12917 : undef;
12918 58 my $color_scheme = _sequential_scheme($self->param('color_scheme'));
12919  
12920 58 ▶ return $self->render(text => 'Missing group= parameter', status => 400) unless length $cat_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col 5 53 58
12921 53 ▶ return $self->render(text => $color_m->{error}, status => 400) if $color_m && $color_m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $color_m and $color_m->{"error"} 0 53 53
Condition66%2/3
$color_m and $color_m->{"error"}
!ll&&!rl&&r
5210
MC/DC0%0/2
$color_m and $color_m->{"error"}
$color_m $color_m->{"error"}
Truth table66%2/3
A and B
A= $color_mB= $color_m->{"error"}
ABresult
0X0
100
111
12922  
12923 53 my ($src, $records, $columns) = $self->_run_pipeline_source;
12924 53 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 2 51 53
12925  
12926 51 my $span = $self->_span_calc_spec($columns, 'group', 'cat');
12927 51 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 1 50 51
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
5001
MC/DC50%1/2
$span and $span->{"error"}
$span $span->{"error"}
Truth table66%2/3
A and B
A= $spanB= $span->{"error"}
ABresult
0X0
100
111
12928  
12929 50 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
12930 50 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 50 50
12931 50 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 49 50
12932  
12933 49 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 48 49
12934  
12935 48 my %col_set = map { $_ => 1 } @{$columns};
12936 48 ▶ return $self->render(text => "Column not found: $cat_col", status => 400) unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 3 45 48
12937  
12938 45 ▶ my $count_mode = (!length $val_col || $val_col eq '__count__');
Condition66%2/3
!length($val_col) || $val_col eq '__count__'
l!l&&r!l&&!r
3708
MC/DC50%1/2
!length($val_col) || $val_col eq '__count__'
!length($val_col) $val_col eq '__count__'
Truth table66%2/3
not(A) || B
A= !length($val_col)B= $val_col eq '__count__'
ABresult
1X1
011
000
12939 return $self->render(text => "Column not found: $val_col", status => 400)
12940 45 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 2 43 45
Condition100%3/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
3762
MC/DC100%2/2
$count_mode or $col_set{$val_col}
$count_mode $col_set{$val_col}
Truth table100%3/3
A or B
A= $count_modeB= $col_set{$val_col}
ABresult
1X1
011
000
12941 return $self->render(text => "Column not found: $color_col", status => 400)
12942 43 ▶ if length $color_col && !$col_set{$color_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $color_col and not $col_set{$color_col} 1 42 43
Condition66%2/3
length $color_col and not $col_set{$color_col}
!ll&&!rl&&r
4201
MC/DC50%1/2
length $color_col and not $col_set{$color_col}
length $color_col not $col_set{$color_col}
Truth table66%2/3
A and not(B)
A= length $color_colB= not $col_set{$color_col}
ABresult
0X0
100
111
12943  
12944 42 ▶ $cat_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 42 42
12945  
12946 42 ▶ my $agg_rows = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 36 6 42
$count_mode ? : 36 6 42
12947 { source => $src, records => $records },
12948 {
12949 by => [$cat_col],
12950 fn => $count_mode ? 'count' : 'sum',
12951 val => $count_mode ? undef : $val_col,
12952 as => 'value',
12953 },
12954 );
12955  
12956 42 ▶ my $colour_of = $color_m
Branch: 1 branch
BranchTrueFalseTotal
$color_m ? : 0 42 42
12957 ? $self->_tile_colours($src, $records, $cat_col, $color_m)
12958 : {};
12959  
12960 # Top-N: keep the highest-N tiles, aggregate the rest as "Other".
12961 42 ▶ my $topn_n = _whole_number($self->param('topn')) // 0;
Condition50%1/2
_whole_number($self->param("topn")) // 0
l!l
042
MC/DC0%0/1
_whole_number($self->param("topn")) // 0
_whole_number($self->param("topn"))
Truth table50%1/2
A
A= _whole_number($self->param("topn"))
Aresult
11
00
12962 42 ▶ if ($topn_n > 0 && @$agg_rows > $topn_n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($topn_n > 0 and @$agg_rows > $topn_n) 0 42 42
Condition33%1/3
$topn_n > 0 and @$agg_rows > $topn_n
!ll&&!rl&&r
4200
MC/DC0%0/2
$topn_n > 0 and @$agg_rows > $topn_n
$topn_n > 0 @$agg_rows > $topn_n
Truth table33%1/3
A and B
A= $topn_n > 0B= @$agg_rows > $topn_n
ABresult
0X0
100
111
12963 0 ▶ my @sorted = sort { ($b->{value} // 0) <=> ($a->{value} // 0) } @$agg_rows;
Condition0%0/4
$Database::BI::Controller::Dashboard::b->{"value"} // 0
l!l
00
$Database::BI::Controller::Dashboard::a->{"value"} // 0
l!l
00
MC/DC0%0/1
$Database::BI::Controller::Dashboard::b->{"value"} // 0
$Database::BI::Controller::Dashboard::b->{"value"}
MC/DC0%0/1
$Database::BI::Controller::Dashboard::a->{"value"} // 0
$Database::BI::Controller::Dashboard::a->{"value"}
Truth table0%0/2
A
A= $Database::BI::Controller::Dashboard::b->{"value"}
Aresult
11
00
Truth table0%0/2
A
A= $Database::BI::Controller::Dashboard::a->{"value"}
Aresult
11
00
12964 0 my @top_agg = @sorted[0 .. $topn_n - 1];
12965 0 ▶ my %top_cats = map { ($_->{$cat_col} // '') => 1 } @top_agg;
Condition0%0/2
$_->{$cat_col} // ""
l!l
00
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
Truth table0%0/2
A
A= $_->{$cat_col}
Aresult
11
00
12966 my $other_rec = [
12967 0 ▶ grep { !$top_cats{$_->{$cat_col} // ''} } @$records
Condition0%0/2
$_->{$cat_col} // ""
l!l
00
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
Truth table0%0/2
A
A= $_->{$cat_col}
Aresult
11
00
12968 ];
12969 0 ▶ if (@$other_rec) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$other_rec) 0 0 0
12970 0 ▶ my $other = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 0 0 0
$count_mode ? : 0 0 0
12971 { source => undef, records => $other_rec },
12972 { by => [], fn => ($count_mode ? 'count' : 'sum'),
12973 val => ($count_mode ? undef : $val_col), as => 'value' },
12974 );
12975 0 ▶ if (@$other && defined $other->[0]{value}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$other and defined $other->[0]{"value"}) 0 0 0
Condition0%0/3
@$other and defined $other->[0]{"value"}
!ll&&!rl&&r
000
MC/DC0%0/2
@$other and defined $other->[0]{"value"}
@$other defined $other->[0]{"value"}
Truth table0%0/3
A and B
A= @$otherB= defined $other->[0]{"value"}
ABresult
0X0
100
111
12976 0 push @top_agg, { $cat_col => 'Other', value => $other->[0]{value} };
12977 # Other's colour is its own rows', not an average of averages.
12978 # The key is the tile, so a category itself named Other is
12979 # drawn with this one, as its area already is.
12980 0 ▶ $colour_of->{Other} = $self->_tile_colours(undef, $other_rec, undef, $color_m)->{''}
Branch: 1 branch
BranchTrueFalseTotal
if $color_m 0 0 0
12981 if $color_m;
12982 }
12983 }
12984 0 $agg_rows = \@top_agg;
12985 }
12986  
12987 42 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg_rows 0 42 42
12988 text => 'No plottable data: no rows have valid data in the selected column.',
12989 status => 200,
12990 ) unless @$agg_rows;
12991  
12992 my @data = map {
12993 42 ▶ my $cv = $colour_of->{ $_->{$cat_col} // '' };
Condition50%1/2
$_->{$cat_col} // ""
l!l
1610
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
Truth table50%1/2
A
A= $_->{$cat_col}
Aresult
11
00
12994 +{ path => 'Root/' . _decode_cell($_->{$cat_col}), value => $_->{value},
12995 161 ▶ (defined $cv ? (color_value => $cv) : ()) }
Branch: 1 branch
BranchTrueFalseTotal
defined $cv ? : 0 161 161
12996 } @$agg_rows;
12997  
12998 42 my ($source_url, $source_accessed) = $self->_url_attribution;
12999  
13000 42 require HTML::D3;
13001 42 ▶ my $title = $count_mode ? "Treemap of $cat_col by count" : "Treemap of $cat_col by $val_col";
Branch: 1 branch
BranchTrueFalseTotal
$count_mode ? : 36 6 42
13002 42 ▶ $title .= " coloured by $color_m->{label}" if $color_m;
Branch: 1 branch
BranchTrueFalseTotal
if $color_m 0 42 42
13003 my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 500)
13004 ->render_treemap_snippet(\@data, {
13005 scheme => $scheme,
13006 42 ▶ ($color_m ? (color_scheme => $color_scheme, color_label => $color_m->{label}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$color_m ? : 0 42 42
13007 });
13008  
13009 42 my $chart_html = $snippet->{html};
13010 42 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 42 42
13011  
13012 my %chart_spec = (
13013 kind => 'treemap',
13014 title => $title,
13015 encode => { cat => $cat_col, value => $val_col,
13016 ($color_m ? (color => $color_col) : ()) },
13017 options => { scheme => $scheme,
13018 42 ▶ ($color_m ? (color_agg => $color_m->{fn}, color_scheme => $color_scheme) : ()) },
Branch: 2 branches
BranchTrueFalseTotal
$color_m ? : 0 42 42
$color_m ? : 0 42 42
13019 );
13020 42 my ($platform, $language) = $self->_resolve_template;
13021 42 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 42 42
$back2 ? : 0 42 42
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0420
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
13022 handler => 'tt',
13023 template => "$platform/$language/treemap",
13024 format => 'html',
13025 title => $title,
13026 chart_html => $chart_html,
13027 chart => \%chart_spec,
13028 chart_json => $self->_chart_json(\%chart_spec),
13029 tile_count => scalar @data,
13030 cat_col => $cat_col,
13031 drill_back_url => $back,
13032 back_url => ($back2 // $back),
13033 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
13034 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
13035 source_url => $source_url,
13036 source_accessed => $source_accessed,
13037 language => $language,
13038 );
13039 }
13040  
13041 # ---------------------------------------------------------------------------
13042 # Histogram (GET /histogram)
13043 # ---------------------------------------------------------------------------
13044  
13045 57 ▶sub histogram_view ($self) {
Subroutine histogram_view: called CC=35 SCAR=36.5
Pod documented
13046 57 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
534
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
13047 57 my $_bins_raw = $self->param('bins');
13048 57 ▶ my $bins = (defined $_bins_raw && length $_bins_raw) ? $_bins_raw : 10;
Branch: 1 branch
BranchTrueFalseTotal
defined $_bins_raw && length $_bins_raw ? : 5 52 57
Condition100%3/3
defined $_bins_raw and length $_bins_raw
!ll&&!rl&&r
5115
MC/DC100%2/2
defined $_bins_raw and length $_bins_raw
defined $_bins_raw length $_bins_raw
Truth table100%3/3
A and B
A= defined $_bins_rawB= length $_bins_raw
ABresult
0X0
100
111
13049 57 my $scheme = _optional_scheme($self->param('scheme'));
13050 57 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
057
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table50%1/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
13051 57 my $back2 = _safe_back_url($self->param('back2'));
13052 57 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
057
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
13053  
13054 57 ▶ return $self->render(text => 'Missing col= parameter', status => 400) unless length $col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 5 52 57
13055  
13056 52 my ($src, $records, $columns) = $self->_run_pipeline_source;
13057 52 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 2 50 52
13058  
13059 50 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
13060 50 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 49 50
13061  
13062 49 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 48 49
13063  
13064 48 my %col_set = map { $_ => 1 } @{$columns};
13065 48 ▶ return $self->render(text => "Column not found: $col", status => 400) unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 2 46 48
13066  
13067 46 my @values;
13068 46 for my $row (@$records) {
13069 284 ▶ my $v = _numeric_cell($row->{$col} // '');
Condition50%1/2
$row->{$col} // ""
l!l
2840
MC/DC0%0/1
$row->{$col} // ""
$row->{$col}
Truth table50%1/2
A
A= $row->{$col}
Aresult
11
00
13070 284 ▶ push @values, $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 278 6 284
13071 }
13072  
13073 46 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @values 1 45 46
13074 text => 'No plottable data: no rows have valid numeric values in the selected column.',
13075 status => 200,
13076 ) unless @values;
13077  
13078 45 ▶ $bins = _whole_number($bins) // ($bins =~ /\A\d+\z/ ? $MAX_HISTOGRAM_BINS : 1); # more digits than a number holds is a lot of bins
Branch: 1 branch
BranchTrueFalseTotal
$bins =~ /\A\d+\z/u ? : 0 1 1
Condition66%2/3
_whole_number($bins) // ($bins =~ /\A\d+\z/u ? $MAX_HISTOGRAM_BINS : 1)
l!l&&r!l&&!r
4410
MC/DC0%0/2
_whole_number($bins) // ($bins =~ /\A\d+\z/u ? $MAX_HISTOGRAM_BINS : 1)
_whole_number($bins) ($bins =~ /\A\d+\z/u ? $MAX_HISTOGRAM_BINS : 1)
Truth table66%2/3
A // B
A= _whole_number($bins)B= ($bins =~ /\A\d+\z/u ? $MAX_HISTOGRAM_BINS : 1)
ABresult
1X1
011
000
13079 45 ▶ $bins = 1 if $bins < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $bins < 1 1 44 45
13080 45 ▶ $bins = $MAX_HISTOGRAM_BINS if $bins > $MAX_HISTOGRAM_BINS;
Branch: 1 branch
BranchTrueFalseTotal
if $bins > $MAX_HISTOGRAM_BINS 1 44 45
13081  
13082 # Server-side binning: compute equal-width bins over the data range.
13083 # Values equal to $max land in the highest bin (no overflow bar).
13084 # Uses the same bin-boundary logic as Calc.pm bin() to stay consistent with
13085 # ?c=band:bin(col,width) computed columns on the same data.
13086 10 ▶ use POSIX qw(floor);
Subroutine BEGIN: called CC=1 SCAR=0.0
13087 45 my $min_v = min(@values);
13088 45 my $max_v = max(@values);
13089 45 my @bin_data;
13090 45 ▶ if ($min_v == $max_v) {
Branch: 1 branch
BranchTrueFalseTotal
if ($min_v == $max_v) { } 0 45 45
13091 # All values identical: one bin.
13092 0 push @bin_data, { label => "$min_v", count => scalar @values, lo => $min_v, hi => $min_v };
13093 } else {
13094 45 my $raw_w = ($max_v - $min_v) / $bins;
13095 # Round up to a "nice" width using 10 significant digits (same guard as Calc bin()).
13096 45 my $width = sprintf('%.10g', $raw_w) + 0;
13097 45 ▶ $width = $raw_w if $width <= 0; # safety: never produce zero width
Branch: 1 branch
BranchTrueFalseTotal
if $width <= 0 0 45 45
13098 45 ▶ my $fmt = ($width == int($width)) ? '%d' : '%g';
Branch: 1 branch
BranchTrueFalseTotal
$width == int $width ? : 2 43 45
13099  
13100 # Build bin boundaries.
13101 45 my @bin_counts;
13102 my @bin_los;
13103 45 for my $i (0 .. $bins - 1) {
13104 612 push @bin_los, $min_v + $i * $width;
13105 612 push @bin_counts, 0;
13106 }
13107  
13108 # Assign each value to a bin.
13109 45 for my $v (@values) {
13110 278 my $idx = floor(sprintf('%.10g', ($v - $min_v) / $width) + 0);
13111 278 ▶ $idx = $bins - 1 if $idx >= $bins; # max value -> last bin
Branch: 1 branch
BranchTrueFalseTotal
if $idx >= $bins 45 233 278
13112 278 ▶ $idx = 0 if $idx < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $idx < 0 0 278 278
13113 278 $bin_counts[$idx]++;
13114 }
13115  
13116 45 for my $i (0 .. $bins - 1) {
13117 612 ▶ next unless $bin_counts[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless $bin_counts[$i] 392 220 612
13118 220 my $lo = $bin_los[$i];
13119 220 my $hi = $lo + $width;
13120 220 my $lbl = sprintf("[${fmt},${fmt})", $lo, $hi);
13121 220 push @bin_data, { label => $lbl, count => $bin_counts[$i], lo => $lo, hi => $hi };
13122 }
13123 }
13124  
13125 45 my ($source_url, $source_accessed) = $self->_url_attribution;
13126  
13127 45 require HTML::D3;
13128 45 my $title = "Distribution of $col";
13129 45 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 480)
Branch: 1 branch
BranchTrueFalseTotal
$scheme ? : 0 45 45
13130 ->render_histogram_snippet(\@bin_data, {
13131 binned => 1,
13132 x_label => $col,
13133 ($scheme ? (scheme => $scheme) : ()),
13134 });
13135  
13136 45 my $chart_html = $snippet->{html};
13137 45 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 45 45
13138  
13139 45 ▶ my %chart_spec = (
Branch: 1 branch
BranchTrueFalseTotal
$scheme ? : 0 45 45
13140 kind => 'histogram',
13141 title => $title,
13142 encode => { value => $col },
13143 options => { bins => $bins, ($scheme ? (scheme => $scheme) : ()) },
13144 );
13145 45 my ($platform, $language) = $self->_resolve_template;
13146 45 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 45 45
$back2 ? : 0 45 45
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0450
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
13147 handler => 'tt',
13148 template => "$platform/$language/histogram",
13149 format => 'html',
13150 title => $title,
13151 chart_html => $chart_html,
13152 chart => \%chart_spec,
13153 chart_json => $self->_chart_json(\%chart_spec),
13154 value_count => scalar @values,
13155 bins => $bins,
13156 back_url => ($back2 // $back),
13157 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
13158 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
13159 source_url => $source_url,
13160 source_accessed => $source_accessed,
13161 language => $language,
13162 );
13163 }
13164  
13165 # ---------------------------------------------------------------------------
13166 # Word cloud (GET /wordcloud)
13167 # ---------------------------------------------------------------------------
13168  
13169 # The words that say nothing about the data: without them a cloud of a notes
13170 # column is all "the" and "and". English, like the only page language the
13171 # templates have. ?stop= adds to this list for one request rather than
13172 # replacing it, so adding a word never silently brings back the ones this list
13173 # already removes.
13174 10 my %STOP_WORD = map { $_ => 1 } qw(
13175 a about above after again against all also am an and any are as at be
13176 because been before being below between both but by can could did do does
13177 doing down during each few for from further had has have having he her here
13178 hers herself him himself his how i if in into is it its itself just me more
13179 most my myself no nor not now of off on once only or other our ours ourselves
13180 out over own same she should so some such than that the their theirs them
13181 themselves then there these they this those through to too under until up
13182 very was we were what when where which while who whom why will with would
13183 you your yours yourself yourselves
13184 );
13185  
13186 # _percent_encode($text) -> $url_component
13187 #
13188 # Purpose: Percent-encode one value for a query string.
13189 # Notes: url_escape() works on bytes, so a decoded (character) string is
13190 # encoded to UTF-8 first; otherwise "caf\x{e9}" would become "caf%E9" and a
13191 # browser would read that back as Latin-1.
13192 12 ▶sub _percent_encode {
Subroutine _percent_encode: called CC=3 SCAR=11.0
13193 12 my ($text) = @_;
13194 12 ▶ my $bytes = defined $text ? "$text" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $text ? : 11 1 12
13195 12 ▶ utf8::encode($bytes) if utf8::is_utf8($bytes);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($bytes) 1 11 12
13196 12 return url_escape($bytes);
13197 }
13198  
13199 # _word_tokens($text, $minlen) -> @words
13200 #
13201 # Purpose: The words in one cell, lower-cased and split on everything that is
13202 # neither a letter, a digit nor an apostrophe.
13203 # Entry: $text is a cell (may be undef); $minlen is the shortest word kept.
13204 # Exit: The words at least $minlen characters long that contain a letter.
13205 # A run of digits alone is kept -- a year or a model number can be the
13206 # point of a column -- while a run of punctuation is not a word at all.
13207 # Notes: A CSV cell arrives as bytes, so it is decoded first (the same
13208 # _decode_cell() every page uses): without that, \p{L} would see the
13209 # bytes of "caf\x{e9}" and split the word in two. The apostrophe stays
13210 # inside a word, so O'Brien is one word rather than "o" and "brien".
13211 290 ▶sub _word_tokens {
Subroutine _word_tokens: called CC=5 SCAR=16.1
13212 290 my ($text, $minlen) = @_;
13213 290 ▶ return () unless defined $text && length $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text and length $text 8 282 290
Condition100%3/3
defined $text and length $text
!ll&&!rl&&r
71282
MC/DC100%2/2
defined $text and length $text
defined $text length $text
Truth table100%3/3
A and B
A= defined $textB= length $text
ABresult
0X0
100
111
13214  
13215 282 my @words = split /[^\p{L}\p{N}']+/, lc _decode_cell($text);
13216 282 for my $word (@words) {
13217 566 $word =~ s/\A'+//;
13218 566 $word =~ s/'+\z//;
13219 }
13220  
13221 282 ▶ return grep { length($_) >= $minlen && /\p{L}/ } @words;
Condition100%3/3
length $_ >= $minlen && /\p{L}/u
!ll&&!rl&&r
25722881
MC/DC100%2/2
length $_ >= $minlen && /\p{L}/u
length $_ >= $minlen /\p{L}/u
Truth table100%3/3
A && B
A= length $_ >= $minlenB= /\p{L}/u
ABresult
0X0
100
111
13222 }
13223  
13224 # _wordcloud_option($raw, $default, $min, $max) -> $n
13225 #
13226 # Purpose: One of the two counts a cloud takes -- how many words to show, how
13227 # short a word may be.
13228 # Notes: A value that is absent or unreadable is the default, not the minimum:
13229 # ?topn= with nothing after it must not silently show a single word.
13230 119 ▶sub _wordcloud_option {
Subroutine _wordcloud_option: called CC=6 SCAR=17.9
13231 119 my ($raw, $default, $min, $max) = @_;
13232  
13233 119 ▶ my $n = (defined $raw && !ref $raw && $raw =~ /\A\d+\z/) ? int $raw : $default;
Branch: 1 branch
BranchTrueFalseTotal
defined $raw && !ref($raw) && $raw =~ /\A\d+\z/u ? : 5 114 119
Condition100%6/6
defined $raw and not ref $raw and $raw =~ /\A\d+\z/u
!ll&&!rl&&r
102125
defined $raw and not ref $raw
!ll&&!rl&&r
101117
MC/DC100%3/3
defined $raw and not ref $raw and $raw =~ /\A\d+\z/u
defined $raw not ref $raw $raw =~ /\A\d+\z/u
Truth table100%4/4
A and not(B) and C
A= defined $rawB= not ref $rawC= $raw =~ /\A\d+\z/u
ABCresult
0XX0
10X0
1100
1111
13234 119 ▶ $n = $min if $n < $min;
Branch: 1 branch
BranchTrueFalseTotal
if $n < $min 1 118 119
13235 119 ▶ $n = $max if $n > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $n > $max 3 116 119
13236 119 return $n;
13237 }
13238  
13239 # _wordcloud_counts($records, $col, $topn, $minlen, $extra_stop) -> \%cloud
13240 #
13241 # Purpose: The words a text column repeats and how often each appears, ranked,
13242 # which is what both the /wordcloud page and a canvas's word-cloud card
13243 # draw. One function, so the page and the card cannot count differently.
13244 # Entry: $records is a list of rows; $col names the text column; $topn is how
13245 # many words to return; $minlen is the shortest word kept; $extra_stop
13246 # is the reader's own stoplist ("apple,pear"), added to the built-in
13247 # one rather than replacing it.
13248 # Exit: { words => [ { word, count }, ... ] } in cloud order -- count
13249 # descending, then alphabetically -- with distinct (every different word
13250 # seen, before truncation), total (words counted) and rows (rows read).
13251 # Notes: A word counts once per row that contains it, so a long note does not
13252 # outweigh ten short rows that say the same thing.
13253 49 ▶sub _wordcloud_counts {
Subroutine _wordcloud_counts: called CC=10 SCAR=23.1
13254 49 my ($records, $col, $topn, $minlen, $extra_stop) = @_;
13255  
13256 49 my %stop = %STOP_WORD;
13257 49 ▶ for my $extra (split /[\s,]+/, $extra_stop // '') {
Condition100%2/2
$extra_stop // ""
l!l
445
MC/DC100%1/1
$extra_stop // ""
$extra_stop
Truth table100%2/2
A
A= $extra_stop
Aresult
11
00
13258 3 ▶ $stop{ lc $extra } = 1 if length $extra;
Branch: 1 branch
BranchTrueFalseTotal
if length $extra 3 0 3
13259 }
13260  
13261 49 my (%count, $row_count);
13262 49 for my $row (@$records) {
13263 282 $row_count++;
13264 282 my %seen;
13265 282 ▶ $count{$_}++ for grep { !$seen{$_}++ && !$stop{$_} }
Condition100%3/3
$seen{$_}++ || $stop{$_}
l!l&&r!l&&!r
2761
MC/DC100%2/2
$seen{$_}++ || $stop{$_}
$seen{$_}++ $stop{$_}
Truth table100%3/3
A || B
A= $seen{$_}++B= $stop{$_}
ABresult
1X1
011
000
13266 _word_tokens($row->{$col}, $minlen);
13267 }
13268  
13269 49 ▶ my $total = sum(values %count) // 0;
Condition100%2/2
&sum(values %count) // 0
l!l
940
MC/DC100%1/1
&sum(values %count) // 0
&sum(values %count)
Truth table100%2/2
A
A= &sum(values %count)
Aresult
11
00
13270 49 ▶ my @words = sort { $count{$b} <=> $count{$a} || $a cmp $b } keys %count;
Condition66%2/3
$count{$b} <=> $count{$a} || $a cmp $b
l!l&&r!l&&!r
1180
MC/DC0%0/2
$count{$b} <=> $count{$a} || $a cmp $b
$count{$b} <=> $count{$a} $a cmp $b
Truth table66%2/3
A || B
A= $count{$b} <=> $count{$a}B= $a cmp $b
ABresult
1X1
011
000
13271 49 my $distinct = scalar @words;
13272 49 ▶ @words = @words[0 .. $topn - 1] if @words > $topn;
Branch: 1 branch
BranchTrueFalseTotal
if @words > $topn 1 48 49
13273  
13274 return {
13275 49 words => [ map { { word => $_, count => $count{$_} } } @words ],
13276 distinct => $distinct,
13277 total => $total,
13278 rows => $row_count,
13279 };
13280 }
13281  
13282 # _wordcloud_link($back, $col, $word, $cloud_url) -> $url
13283 #
13284 # Purpose: The view URL that shows the rows containing one word, with the cloud
13285 # as that page's breadcrumb, so a click on a word is a drill-down.
13286 # Note: The URL is returned unescaped; the caller escapes it once for the
13287 # href it goes into, because HTML::TagCloud writes its input verbatim.
13288 3 ▶sub _wordcloud_link {
Subroutine _wordcloud_link: called CC=2 SCAR=6.9
13289 3 my ($back, $col, $word, $cloud_url) = @_;
13290 3 ▶ my $sep = $back =~ /\?/ ? '&' : '?';
Branch: 1 branch
BranchTrueFalseTotal
$back =~ /\?/u ? : 1 2 3
13291  
13292 3 return $back . $sep . 'f=' . _percent_encode("$col:contains:$word")
13293 . '&back2=' . _percent_encode($cloud_url)
13294 . '&back2_label=' . _percent_encode('Back to word cloud');
13295 }
13296  
13297 54 ▶sub wordcloud_view ($self) {
Subroutine wordcloud_view: called CC=22 SCAR=31.6
Pod documented
13298 54 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
513
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
13299 54 my $_topn = $self->param('topn');
13300 54 my $_minlen = $self->param('minlen');
13301 54 my $back_raw = $self->param('back');
13302 54 ▶ my $back = _safe_back_url($back_raw) // '/';
Condition50%1/2
_safe_back_url($back_raw) // "/"
l!l
054
MC/DC0%0/1
_safe_back_url($back_raw) // "/"
_safe_back_url($back_raw)
Truth table50%1/2
A
A= _safe_back_url($back_raw)
Aresult
11
00
13303 54 my $back2 = _safe_back_url($self->param('back2'));
13304 54 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
054
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
13305  
13306 # A count that is absent or unreadable is the default, not a clamp of zero:
13307 # ?topn= with nothing after it must not silently show a single word.
13308 54 my $topn = _wordcloud_option($_topn, 50, 1, 500);
13309 54 my $minlen = _wordcloud_option($_minlen, 3, 1, 64);
13310  
13311 54 ▶ return $self->render(text => 'Missing col= parameter', status => 400) unless length $col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 4 50 54
13312  
13313 50 my ($src, $records, $columns) = $self->_run_pipeline_source;
13314 50 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 2 48 50
13315  
13316 48 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
13317 48 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 47 48
13318  
13319 47 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 46 47
13320  
13321 46 my %col_set = map { $_ => 1 } @$columns;
13322 46 ▶ return $self->render(text => "Column not found: $col", status => 400) unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 1 45 46
13323  
13324 # One pass over the rows, shared with a canvas's word-cloud card so the page
13325 # and the card count the same way.
13326 45 my $cloud = _wordcloud_counts(
13327 $records, $col, $topn, $minlen, $self->param('stop'),
13328 );
13329 45 my @words = map { $_->{word} } @{ $cloud->{words} };
13330 45 my %count = map { $_->{word} => $_->{count} } @{ $cloud->{words} };
13331 45 my $distinct = $cloud->{distinct};
13332 45 my $word_total = $cloud->{total};
13333 45 my $row_count = $cloud->{rows};
13334  
13335 # A word links back to the rows that contain it, so the cloud is a way into
13336 # the data rather than a picture of it. Only when the request names the page
13337 # it came from: a bare /wordcloud URL has no table to filter, and sending a
13338 # click to "/?f=..." would be a dead end.
13339 45 ▶ my $drill = (defined $back_raw && length $back_raw) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $back_raw && length $back_raw ? : 1 44 45
Condition66%2/3
defined $back_raw and length $back_raw
!ll&&!rl&&r
4401
MC/DC50%1/2
defined $back_raw and length $back_raw
defined $back_raw length $back_raw
Truth table66%2/3
A and B
A= defined $back_rawB= length $back_raw
ABresult
0X0
100
111
13340  
13341 45 my $cloud_url = $self->req->url->path->to_string;
13342 45 my $qs = $self->req->url->query->to_string;
13343 45 ▶ $cloud_url .= "?$qs" if length $qs;
Branch: 1 branch
BranchTrueFalseTotal
if length $qs 45 0 45
13344  
13345 my @tags = map {
13346 45 {
13347 word => _decode_cell($_),
13348 21 ▶ count => $count{$_},
Branch: 1 branch
BranchTrueFalseTotal
$drill ? : 0 21 21
13349 ($drill ? (href => _wordcloud_link($back, $col, $_, $cloud_url)) : ()),
13350 }
13351 } @words;
13352  
13353 # The font size is the module's own logarithm of the count, so a word that
13354 # appears twice as often is one step bigger rather than twice as wide.
13355 45 require HTML::TagCloud;
13356 45 my $ranked = HTML::TagCloud->new(levels => 18);
13357 45 for my $tag (@tags) {
13358 21 my $name = xml_escape($tag->{word});
13359 21 ▶ if (defined $tag->{href}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tag->{'href'}) { } 0 21 21
13360 0 $ranked->add($name, xml_escape($tag->{href}), $tag->{count});
13361 }
13362 else {
13363 21 $ranked->add_static($name, $tag->{count});
13364 }
13365 }
13366  
13367 45 ▶ my $cloud_html = @tags ? $ranked->html_and_css(scalar @tags) : '';
Branch: 1 branch
BranchTrueFalseTotal
@tags ? : 7 38 45
13368  
13369 45 my ($source_url, $source_accessed) = $self->_url_attribution;
13370 45 my $title = "Words in $col";
13371  
13372 # The spec a canvas word-cloud card reads (_render_visual_html), so the
13373 # layout's New canvas / Add to existing canvas buttons save this cloud as
13374 # it is drawn, as they do for every other chart page.
13375 45 my $stop = $self->param('stop');
13376 45 ▶ my %chart_spec = (
Branch: 1 branch
BranchTrueFalseTotal
defined $stop && length $stop ? : 1 44 45
Condition66%2/3
defined $stop and length $stop
!ll&&!rl&&r
4401
MC/DC50%1/2
defined $stop and length $stop
defined $stop length $stop
Truth table66%2/3
A and B
A= defined $stopB= length $stop
ABresult
0X0
100
111
13377 kind => 'wordcloud',
13378 title => $title,
13379 encode => { col => $col },
13380 options => {
13381 topn => $topn,
13382 minlen => $minlen,
13383 ((defined $stop && length $stop) ? (stop => $stop) : ()),
13384 },
13385 );
13386  
13387 45 my ($platform, $language) = $self->_resolve_template;
13388 45 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 45 45
$back2 ? : 0 45 45
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0450
$back2_lbl or "Back"
l!l
00
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
13389 handler => 'tt',
13390 template => "$platform/$language/wordcloud",
13391 format => 'html',
13392 title => $title,
13393 chart => \%chart_spec,
13394 chart_json => $self->_chart_json(\%chart_spec),
13395 cloud_html => $cloud_html,
13396 words => \@tags,
13397 col => $col,
13398 topn => $topn,
13399 minlen => $minlen,
13400 drill => $drill,
13401 distinct_words => $distinct,
13402 word_total => $word_total,
13403 row_count => $row_count,
13404 back_url => ($back2 // $back),
13405 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
13406 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
13407 source_url => $source_url,
13408 source_accessed => $source_accessed,
13409 language => $language,
13410 );
13411 }
13412  
13413 # ---------------------------------------------------------------------------
13414 # Map (GET /map)
13415 #
13416 # one route, one template, two ways for a row to get a
13417 # position. With lat= and lon= the columns already hold coordinates; with
13418 # loc=<column> every distinct value of that column is geocoded once, by
13419 # Database::BI::Model::Geocode. Answers are remembered in one shared cache in
13420 # the model store, keyed by the place rather than by the file or column that
13421 # named it, so a second visit asks nothing and a second dataset naming the same
13422 # place asks nothing either. Everything before that - the pipeline, calculated
13423 # fields and f= filters - is the same as every other visual, so a map shows the
13424 # filtered, calculated view and not the raw table.
13425 # ---------------------------------------------------------------------------
13426  
13427 # _map_loc_columns($loc) -> @columns
13428 #
13429 # The place-name columns of a map, in order, from loc: one name (a canvas card
13430 # saved before a place could span columns), or a list of them (loc= repeated,
13431 # or a card's encode.loc array). Empty and non-string entries are dropped, and
13432 # a column named twice is used once.
13433 181 ▶sub _map_loc_columns {
Subroutine _map_loc_columns: called CC=5 SCAR=16.1
13434 181 my $loc = shift;
13435 181 ▶ my @names = ref($loc) eq 'ARRAY' ? @{$loc} : ($loc);
Branch: 1 branch
BranchTrueFalseTotal
ref $loc eq 'ARRAY' ? : 140 41 181
13436 181 my %seen;
13437 181 ▶ return grep { defined($_) && !ref($_) && length($_) && !$seen{$_}++ } @names;
Condition100%9/9
defined $_ && !ref($_) && length $_ && !$seen{$_}++
!ll&&!rl&&r
39160
defined $_ and not ref $_ and length $_
!ll&&!rl&&r
36361
defined $_ and not ref $_
!ll&&!rl&&r
33364
MC/DC100%4/4
defined $_ && !ref($_) && length $_ && !$seen{$_}++
defined $_ not ref $_ length $_ !$seen{$_}++
Truth table100%5/5
A and not(B) and C && not(D)
A= defined $_B= not ref $_C= length $_D= !$seen{$_}++
ABCDresult
0XXX0
10XX0
110X0
11100
11111
13438 }
13439  
13440 # _map_loc_text($value) -> ($text) | ()
13441 #
13442 # The text added to the end of each place (loc_text=, a card's
13443 # encode.loc_text): "Virginia, USA" for a column of county names, tidied by
13444 # Geocode->place_text, as bi-geocode's --text is. Nothing is returned for a
13445 # value that is not one short line, which the map page refuses and a card,
13446 # stored unchecked, leaves out.
13447 183 ▶sub _map_loc_text {
Subroutine _map_loc_text: called CC=1 SCAR=0.0
13448 183 my ($value) = @_;
13449 183 require Database::BI::Model::Geocode;
13450 183 return Database::BI::Model::Geocode->place_text($value);
13451 }
13452  
13453 # How many outlines holding several markers the map page lists, the fullest
13454 # first; a map of shops has thousands, and the list is for looking into a few.
13455 10 Readonly my $MAP_OUTLINE_GROUPS_MAX => 50;
13456  
13457 # _map_outline_groups($outlines, \@markers, \@records, \@columns) -> @groups
13458 #
13459 # Purpose: Why a map has fewer outlines than markers, for the reader to look
13460 # into: which outlines hold more than one marker, and which markers
13461 # are in no outline. Geocoded places that land in the wrong county
13462 # show up here, as two places in one outline.
13463 # Entry: $outlines as Boundary's outlines() returns it; each marker has
13464 # lat, lon, row_indexes (or first_row) and, when it was geocoded,
13465 # value (the place); the columns that tell rows apart, for the links.
13466 # Exit: One entry for each outline holding two markers or more, the
13467 # fullest first, at most $MAP_OUTLINE_GROUPS_MAX of them, then one
13468 # with none => 1 for the markers in no outline, when there are any:
13469 # { name, markers, places => [text, ...], rows, filters }. A marker
13470 # still waiting for its outline is in neither. () when every marker
13471 # has an outline to itself.
13472 # Side effects: none.
13473 11 ▶sub _map_outline_groups {
Subroutine _map_outline_groups: called CC=12 SCAR=26.9
13474 11 my ($outlines, $markers, $records, $columns) = @_;
13475  
13476 11 require Database::BI::Model::Boundary;
13477 11 ▶ my $inside = $outlines->{inside} // {};
Condition50%1/2
$outlines->{"inside"} // {}
l!l
110
MC/DC0%0/1
$outlines->{"inside"} // {}
$outlines->{"inside"}
Truth table50%1/2
A
A= $outlines->{"inside"}
Aresult
11
00
13478 11 ▶ my %waiting = map { $_ => 1 } @{ $outlines->{pending} // [] };
Condition50%1/2
$outlines->{"pending"} // []
l!l
110
MC/DC0%0/1
$outlines->{"pending"} // []
$outlines->{"pending"}
Truth table50%1/2
A
A= $outlines->{"pending"}
Aresult
11
00
13479 11 my (%held, @none);
13480 11 for my $marker (@{$markers}) {
13481 56 my $key = Database::BI::Model::Boundary->point_key($marker->{lat}, $marker->{lon});
13482 56 ▶ next if !defined($key) || $waiting{$key};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $key or $waiting{$key} 26 30 56
Condition66%2/3
not defined $key or $waiting{$key}
l!l&&r!l&&!r
02630
MC/DC50%1/2
not defined $key or $waiting{$key}
not defined $key $waiting{$key}
Truth table66%2/3
not(A) or B
A= not defined $keyB= $waiting{$key}
ABresult
1X1
011
000
13483 30 ▶ if (defined(my $osm = $inside->{$key})) { push @{ $held{$osm} }, $marker }
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $osm = $inside->{$key})) { } 29 1 30
13484 1 else { push @none, $marker }
13485 }
13486  
13487 1 ▶ my $group = sub {
Subroutine __ANON__: called CC=5 SCAR=17.6
13488 1 my ($name, $in, %more) = @_;
13489 1 ▶ my @rows = map { @{ $_->{row_indexes} // [ $_->{first_row} ] } } @{$in};
Condition50%1/2
$_->{"row_indexes"} // [$_->{"first_row"}]
l!l
10
MC/DC0%0/1
$_->{"row_indexes"} // [$_->{"first_row"}]
$_->{"row_indexes"}
Truth table50%1/2
A
A= $_->{"row_indexes"}
Aresult
11
00
13490 return {
13491 name => $name,
13492 1 markers => scalar(@{$in}),
13493 # A geocoded marker is known by its place, another by where it is
13494 places => [ map {
13495 (defined($_->{value}) && !ref($_->{value}) && length($_->{value}))
13496 1 ▶ ? $_->{value} : "$_->{lat}, $_->{lon}"
Branch: 1 branch
BranchTrueFalseTotal
defined $_->{'value'} && !ref($_->{'value'}) && length $_->{'value'} ? : 0 1 1
Condition33%2/6
defined $_->{"value"} and not ref $_->{"value"} and length $_->{"value"}
!ll&&!rl&&r
100
defined $_->{"value"} and not ref $_->{"value"}
!ll&&!rl&&r
100
MC/DC0%0/3
defined $_->{"value"} and not ref $_->{"value"} and length $_->{"value"}
defined $_->{"value"} not ref $_->{"value"} length $_->{"value"}
Truth table25%1/4
A and not(B) and C
A= defined $_->{"value"}B= not ref $_->{"value"}C= length $_->{"value"}
ABCresult
0XX0
10X0
1100
1111
13497 1 } @{$in} ],
13498 rows => scalar(@rows),
13499 filters => [ _map_rows_filters($records, \@rows, $columns) ],
13500 %more,
13501 };
13502 11 };
13503  
13504 11 ▶ my @shared = grep { @{ $held{ $_->{properties}{osm} // '' } // [] } > 1 } @{ $outlines->{features} };
Condition50%2/4
$held{$_->{"properties"}{"osm"} // ""} // []
l!l
290
$_->{"properties"}{"osm"} // ""
l!l
290
MC/DC0%0/1
$held{$_->{"properties"}{"osm"} // ""} // []
$held{$_->{"properties"}{"osm"} // ""}
MC/DC0%0/1
$_->{"properties"}{"osm"} // ""
$_->{"properties"}{"osm"}
Truth table50%1/2
A
A= $held{$_->{"properties"}{"osm"} // ""}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"properties"}{"osm"}
Aresult
11
00
13505 @shared = sort {
13506 0 @{ $held{ $b->{properties}{osm} } } <=> @{ $held{ $a->{properties}{osm} } }
13507 } @shared;
13508 11 ▶ splice(@shared, $MAP_OUTLINE_GROUPS_MAX) if @shared > $MAP_OUTLINE_GROUPS_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if @shared > $MAP_OUTLINE_GROUPS_MAX 0 11 11
13509  
13510 return (
13511 0 ▶ (map { $group->($_->{properties}{name} // '', $held{ $_->{properties}{osm} }) } @shared),
Branch: 1 branch
BranchTrueFalseTotal
@none ? : 1 10 11
Condition0%0/2
$_->{"properties"}{"name"} // ""
l!l
00
MC/DC0%0/1
$_->{"properties"}{"name"} // ""
$_->{"properties"}{"name"}
Truth table0%0/2
A
A= $_->{"properties"}{"name"}
Aresult
11
00
13512 (@none ? $group->('', \@none, none => 1) : ()),
13513 );
13514 }
13515  
13516 # _map_rows_filters(\@records, \@row_indexes, \@columns) -> @filters
13517 #
13518 # Purpose: Filters that select exactly the given rows, for a link from the
13519 # map to them in the table.
13520 # Entry: Indexes into @records; the columns that tell the rows apart (the
13521 # place columns, or latitude and longitude).
13522 # Exit: One "col:in:[...]" filter a column, listing the cells those rows
13523 # hold. () when together they would select another row too (two
13524 # columns' lists can pair up into a row that was not asked for), or
13525 # when no row or column is given: a link must not show the wrong rows.
13526 # Side effects: none.
13527 7 ▶sub _map_rows_filters {
Subroutine _map_rows_filters: called CC=7 SCAR=20.2
13528 7 my ($records, $indexes, $columns) = @_;
13529  
13530 7 my @rows = grep { ref($_) eq 'HASH' } map { $records->[$_] } @{$indexes};
13531 7 ▶ return () unless @rows && @{$columns};
Branch: 1 branch
BranchTrueFalseTotal
unless @rows and @{$columns;} 0 7 7
Condition33%1/3
@rows and @{$columns;}
!ll&&!rl&&r
007
MC/DC0%0/2
@rows and @{$columns;}
@rows @{$columns;}
Truth table33%1/3
A and B
A= @rowsB= @{$columns;}
ABresult
0X0
100
111
13532  
13533 my @filters = map {
13534 14 my $col = $_;
13535 14 ▶ my %cells = map { my $cell = $_->{$col}; ((defined($cell) && !ref($cell)) ? $cell : '') => 1 } @rows;
Branch: 1 branch
BranchTrueFalseTotal
defined $cell && !ref($cell) ? : 54 0 54
Condition33%1/3
defined $cell and not ref $cell
!ll&&!rl&&r
0054
MC/DC0%0/2
defined $cell and not ref $cell
defined $cell not ref $cell
Truth table33%1/3
A and not(B)
A= defined $cellB= not ref $cell
ABresult
0X0
100
111
13536 14 "$col:in:" . to_json([ sort keys %cells ]);
13537 7 } @{$columns};
13538  
13539 # Tried on every row: the filters are kept only if they find just these
13540 7 my $hit = [ grep { ref($_) eq 'HASH' } @{$records} ];
13541 7 $hit = _apply_filter_spec($hit, $_) for @filters;
13542 7 ▶ return scalar(@{$hit}) == scalar(@rows) ? @filters : ();
Branch: 1 branch
BranchTrueFalseTotal
scalar @{$hit;} == scalar @rows ? : 7 0 7
13543 }
13544  
13545 # _map_unplotted(\@records, \@places, $loc_col, \@loc_cols, \%resolved)
13546 # -> (\@entries, \@all_filters)
13547 #
13548 # The places a geocoded map could not plot, so that the page can say which
13549 # they are: one entry for each, in the order of the first row that names it,
13550 # as { place, rows, reason, filters }. reason is 'empty' (no place in the
13551 # row), 'refused' (not a place name: a bare number), 'not_found', or 'later'
13552 # (not looked up yet: past a cap, or waiting for OpenStreetMap). filters are
13553 # f= specs that select the place's rows in the table, built from the cells of
13554 # its first row: one for each place column, eq that cell, or empty.
13555 #
13556 # @all_filters select every unplotted row at once: for each place column, in
13557 # the list of its cells in those rows. Columns filtered apart can pair a cell
13558 # of one row with a cell of another, which may name a place that was plotted,
13559 # so the filters are tried on the rows and kept only when they select exactly
13560 # the unplotted ones; otherwise @all_filters is empty.
13561 29 ▶sub _map_unplotted {
Subroutine _map_unplotted: called CC=27 SCAR=33.0
13562 29 my ($records, $places, $loc_col, $loc_cols, $resolved) = @_;
13563  
13564 29 my %reason;
13565 29 ▶ for my $value (@{ $resolved->{skipped} // [] }) {
Condition100%2/2
$resolved->{"skipped"} // []
l!l
263
MC/DC100%1/1
$resolved->{"skipped"} // []
$resolved->{"skipped"}
Truth table100%2/2
A
A= $resolved->{"skipped"}
Aresult
11
00
13566 22 ▶ my $key = (defined($value) && !ref($value)) ? $value : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $value && !ref($value) ? : 13 9 22
Condition66%2/3
defined $value and not ref $value
!ll&&!rl&&r
9013
MC/DC50%1/2
defined $value and not ref $value
defined $value not ref $value
Truth table66%2/3
A and not(B)
A= defined $valueB= not ref $value
ABresult
0X0
100
111
13567 22 ▶ $reason{$key} = length($key) ? 'refused' : 'empty';
Branch: 1 branch
BranchTrueFalseTotal
length $key ? : 9 13 22
13568 }
13569 29 ▶ $reason{$_} = 'not_found' for grep { defined } @{ $resolved->{unresolved} // [] };
Condition100%2/2
$resolved->{"unresolved"} // []
l!l
281
MC/DC100%1/1
$resolved->{"unresolved"} // []
$resolved->{"unresolved"}
Truth table100%2/2
A
A= $resolved->{"unresolved"}
Aresult
11
00
13570 29 ▶ $reason{$_} = 'later' for grep { defined } @{ $resolved->{not_attempted} // [] };
Condition100%2/2
$resolved->{"not_attempted"} // []
l!l
263
MC/DC100%1/1
$resolved->{"not_attempted"} // []
$resolved->{"not_attempted"}
Truth table100%2/2
A
A= $resolved->{"not_attempted"}
Aresult
11
00
13571  
13572 29 my (%rows, %first, %cells);
13573 29 my $total = 0;
13574 29 for my $index (0 .. $#{$places}) {
13575 97 my $place = $places->[$index];
13576 97 ▶ my $value = ref($place) eq 'HASH' ? $place->{$loc_col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $place eq 'HASH' ? : 96 1 97
13577 97 ▶ my $key = (defined($value) && !ref($value)) ? $value : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $value && !ref($value) ? : 87 10 97
Condition66%2/3
defined $value and not ref $value
!ll&&!rl&&r
10087
MC/DC50%1/2
defined $value and not ref $value
defined $value not ref $value
Truth table66%2/3
A and not(B)
A= defined $valueB= not ref $value
ABresult
0X0
100
111
13578 97 ▶ next unless exists $reason{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $reason{$key} 53 44 97
13579 44 $rows{$key}++;
13580 44 $total++;
13581 44 ▶ $first{$key} //= $index;
Condition66%2/3
$first{$key} //= $index
l!l&&r!l&&!r
2420
MC/DC0%0/2
$first{$key} //= $index
$first{$key} $index
Truth table66%2/3
A //= B
A= $first{$key}B= $index
ABresult
1X1
011
000
13582  
13583 44 my $row = $records->[$index];
13584 44 for my $col (@{$loc_cols}) {
13585 51 ▶ my $cell = ref($row) eq 'HASH' ? $row->{$col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $row eq 'HASH' ? : 50 1 51
13586 51 ▶ $cells{$col}{ (defined($cell) && !ref($cell)) ? $cell : '' } = 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $cell && !ref($cell) ? : 41 10 51
Condition66%2/3
defined $cell and not ref $cell
!ll&&!rl&&r
10041
MC/DC50%1/2
defined $cell and not ref $cell
defined $cell not ref $cell
Truth table66%2/3
A and not(B)
A= defined $cellB= not ref $cell
ABresult
0X0
100
111
13587 }
13588 }
13589  
13590 29 my @all_filters;
13591 29 ▶ if ($total) {
Branch: 1 branch
BranchTrueFalseTotal
if ($total) 23 6 29
13592 23 @all_filters = map { "$_:in:" . to_json([ sort keys %{ $cells{$_} } ]) } @{$loc_cols};
13593 # Only rows can be filtered; one that is not is never selected.
13594 23 my $hit = [ grep { ref($_) eq 'HASH' } @{$records} ];
13595 23 $hit = _apply_filter_spec($hit, $_) for @all_filters;
13596 23 ▶ @all_filters = () unless scalar(@{$hit}) == $total;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @{$hit;} == $total 2 21 23
13597 }
13598  
13599 my @entries = map {
13600 42 my $row = $records->[ $first{$_} ];
13601 42 ▶ $row = {} unless ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 1 41 42
13602 +{
13603 place => $_,
13604 rows => $rows{$_},
13605 reason => $reason{$_},
13606 filters => [ map {
13607 48 my $cell = $row->{$_};
13608 48 ▶ (defined($cell) && !ref($cell) && length($cell)) ? "$_:eq:$cell" : "$_:empty";
Branch: 1 branch
BranchTrueFalseTotal
defined $cell && !ref($cell) && length $cell ? : 33 15 48
Condition83%5/6
defined $cell and not ref $cell and length $cell
!ll&&!rl&&r
10533
defined $cell and not ref $cell
!ll&&!rl&&r
10038
MC/DC66%2/3
defined $cell and not ref $cell and length $cell
defined $cell not ref $cell length $cell
Truth table75%3/4
A and not(B) and C
A= defined $cellB= not ref $cellC= length $cell
ABCresult
0XX0
10X0
1100
1111
13609 42 } @{$loc_cols} ],
13610 };
13611 29 } sort { $first{$a} <=> $first{$b} } keys %first;
13612  
13613 29 return (\@entries, \@all_filters);
13614 }
13615  
13616 # _map_region($config) -> $region or undef
13617 #
13618 # The country hint for the local geocoder: config map_region when it is two
13619 # letters, else none.
13620 38 ▶sub _map_region {
Subroutine _map_region: called CC=4 SCAR=13.9
13621 38 my $cfg = shift;
13622 38 my $region = $cfg->{map_region};
13623  
13624 38 ▶ return (defined($region) && !ref($region) && $region =~ /\A[A-Za-z]{2}\z/) ? $region : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $region && !ref($region) && $region =~ /\A[A-Za-z]{2}\z/u ? : 1 37 38
Condition100%6/6
defined $region and not ref $region and $region =~ /\A[A-Za-z]{2}\z/u
!ll&&!rl&&r
3251
defined $region and not ref $region
!ll&&!rl&&r
3116
MC/DC100%3/3
defined $region and not ref $region and $region =~ /\A[A-Za-z]{2}\z/u
defined $region not ref $region $region =~ /\A[A-Za-z]{2}\z/u
Truth table100%4/4
A and not(B) and C
A= defined $regionB= not ref $regionC= $region =~ /\A[A-Za-z]{2}\z/u
ABCresult
0XX0
10X0
1100
1111
13625 }
13626  
13627 # _map_geocoder($self, $online) -> Database::BI::Model::Geocode
13628 #
13629 # The geocoder a map asks, built from the config the same way for the map page,
13630 # a canvas card and /geo/lookup. The geocoder is a config seam first and a
13631 # recommended dependency second: a deployment may hand in an object, and a test
13632 # does exactly that. With neither, the model reports the module as unavailable
13633 # and the map is still the map.
13634 #
13635 # map_geocode_online => 0 keeps every lookup on this machine: a place the local
13636 # data does not know is then not sent to OpenStreetMap. A false $online does
13637 # the same for one request (the progress run, once Nominatim has failed).
13638 # Geo::Coder::List keeps its answers in files, so a place Nominatim found is not
13639 # asked again by another request, worker or restart. Geocode->new chooses the
13640 # directory (Object::Configure, CACHEDIR, CACHE_DIR, cache_dir in this config,
13641 # then <model_dir>/geocode-cache). A model_dir that is refused (inside
13642 # data_dir) gives no default, and with nothing else set the module falls back
13643 # on a cache in this process's memory.
13644 34 ▶sub _map_geocoder :Protected ($self, $online) {
Subroutine _map_geocoder: called CC=10 SCAR=23.1
13645 34 require Database::BI::Model::Geocode;
13646  
13647 34 my $cfg = $self->app->config;
13648 34 my $models_path = $self->_calc_models_path;
13649 34 my $injected = $cfg->{geocoder};
13650  
13651 return Database::BI::Model::Geocode->new(
13652 (defined($models_path)
13653 ? (model_dir => Mojo::File->new($models_path)->dirname->to_string)
13654 : ()),
13655 config => $cfg,
13656 home => $self->app->home->to_string,
13657 (defined($injected) && ref($injected) && $injected->can('geocode_many')
13658 ? (geocoder => $injected) : ()),
13659 (defined($cfg->{openaddr}) && length($cfg->{openaddr})
13660 ? (openaddr => $cfg->{openaddr}) : ()),
13661 online => (($online && ($cfg->{map_geocode_online} // 1)) ? 1 : 0),
13662 34 ▶ online_max => _map_limit($cfg->{map_geocode_online_max}, $DEFAULT_MAP_GEOCODE_ONLINE_MAX),
Branch: 4 branches
BranchTrueFalseTotal
defined $models_path ? : 32 2 34
defined $injected && ref $injected && $injected->can('geocode_many') ? : 31 3 34
defined $cfg->{'openaddr'} && length $cfg->{'openaddr'} ? : 19 15 34
$online && ($cfg->{'map_geocode_online'} // 1) ? : 30 4 34
Condition85%12/14
defined $injected and ref $injected and $injected->can("geocode_many")
!ll&&!rl&&r
3031
defined $injected and ref $injected
!ll&&!rl&&r
1231
defined $cfg->{"openaddr"} and length $cfg->{"openaddr"}
!ll&&!rl&&r
15019
$online and $cfg->{"map_geocode_online"} // 1
!ll&&!rl&&r
1330
$cfg->{"map_geocode_online"} // 1
l!l
330
MC/DC66%2/3
defined $injected and ref $injected and $injected->can("geocode_many")
defined $injected ref $injected $injected->can("geocode_many")
MC/DC50%1/2
defined $cfg->{"openaddr"} and length $cfg->{"openaddr"}
defined $cfg->{"openaddr"} length $cfg->{"openaddr"}
MC/DC100%2/2
$online and $cfg->{"map_geocode_online"} // 1
$online $cfg->{"map_geocode_online"}
Truth table75%3/4
A and B and C
A= defined $injectedB= ref $injectedC= $injected->can("geocode_many")
ABCresult
0XX0
10X0
1100
1111
Truth table66%2/3
A and B
A= defined $cfg->{"openaddr"}B= length $cfg->{"openaddr"}
ABresult
0X0
100
111
Truth table100%3/3
A and B
A= $onlineB= $cfg->{"map_geocode_online"}
ABresult
0X0
100
111
13663 );
13664 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13665  
13666 # _map_boundary($self, $level, $online) -> Database::BI::Model::Boundary
13667 #
13668 # What finds the outline around each marker, for the map and /geo/boundary
13669 # alike. It asks OpenStreetMap only when the operator allows the geocoder to
13670 # (map_geocode_online), and at most map_geocode_online_max times a request.
13671 # Its answers are kept beside the geocode cache, under model_dir, so they
13672 # outlive the process and are shared by every worker; with no model_dir it
13673 # keeps them in memory. Config map_bounds_ranks adds or changes the place rank
13674 # that is a county in a country (checked at startup).
13675 11 ▶sub _map_boundary :Protected ($self, $level, $online) {
Subroutine _map_boundary: called CC=7 SCAR=19.9
13676 11 require Database::BI::Model::Boundary;
13677  
13678 11 my $cfg = $self->app->config;
13679 11 my $models_path = $self->_calc_models_path;
13680 11 my $cache;
13681 11 ▶ if (defined $models_path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $models_path) 11 0 11
13682 11 my $dir = Mojo::File->new($models_path)->dirname->to_string;
13683 11 $cache = eval { Database::BI::Model::Boundary->file_cache($dir) };
13684 }
13685  
13686 return Database::BI::Model::Boundary->new(
13687 level => $level,
13688 online => (($online && ($cfg->{map_geocode_online} // 1)) ? 1 : 0),
13689 online_max => _map_limit($cfg->{map_geocode_online_max}, $DEFAULT_MAP_GEOCODE_ONLINE_MAX),
13690 (defined($cache) ? (cache => $cache) : ()),
13691 11 ▶ (ref($cfg->{map_bounds_ranks}) eq 'HASH' ? (ranks => $cfg->{map_bounds_ranks}) : ()),
Branch: 3 branches
BranchTrueFalseTotal
$online && ($cfg->{'map_geocode_online'} // 1) ? : 9 2 11
defined $cache ? : 11 0 11
ref $cfg->{'map_bounds_ranks'} eq 'HASH' ? : 0 11 11
Condition80%4/5
$online and $cfg->{"map_geocode_online"} // 1
!ll&&!rl&&r
029
$cfg->{"map_geocode_online"} // 1
l!l
29
MC/DC50%1/2
$online and $cfg->{"map_geocode_online"} // 1
$online $cfg->{"map_geocode_online"}
Truth table66%2/3
A and B
A= $onlineB= $cfg->{"map_geocode_online"}
ABresult
0X0
100
111
13692 );
13693 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13694  
13695 # The colours of the outlines on a heat map, low to high: green, amber,
13696 # red, as the top of the heat layer's own gradient (lime, yellow, red). An
13697 # outline's colour is one of $OUTLINE_STEPS steps between them, so outlines of
13698 # about the same total share a layer.
13699 10 Readonly my @OUTLINE_STOPS => ([ 0x1a, 0x98, 0x50 ], [ 0xf5, 0xa6, 0x23 ], [ 0xd7, 0x30, 0x27 ]);
13700 10 Readonly my $OUTLINE_STEPS => 9;
13701 # How an outline is drawn: thin and grey on a plain map, heavier when its
13702 # colour carries a meaning, so the colour can be told apart on a busy map.
13703 10 Readonly my %OUTLINE_PLAIN => (colour => '#555555', weight => 1.5, opacity => 0.8);
13704 10 Readonly my %OUTLINE_HEAT => (weight => 2.5, opacity => 0.9);
13705 # Colour shade (shade=): each outline filled in a shade of one colour, darker
13706 # for a larger total, as a census map is. $SHADE_STEPS shades, the lightest
13707 # $SHADE_LIGHTEST of the way from white to the colour so that it still shows;
13708 # the fill lets the map underneath through.
13709 10 Readonly my $SHADE_STEPS => 5;
13710 10 Readonly my $SHADE_LIGHTEST => 0.15;
13711 10 Readonly my $SHADE_OPACITY => 0.65;
13712 10 Readonly my $DEFAULT_SHADE_COLOR => '#d94801';
13713 # A key's totals are rounded to $KEY_FIGURES significant figures, from
13714 # $KEY_ROUND_FROM up; smaller ones are short enough as they are.
13715 10 Readonly my $KEY_FIGURES => 2;
13716 10 Readonly my $KEY_ROUND_FROM => 100;
13717 # The HTML::OSM whose marker key can leave an entry out while a layer is shown
13718 # (a legend entry's unless_layer).
13719 10 Readonly my $OSM_KEY_WAITS_VERSION => '0.19';
13720  
13721 # _map_outline_layers($self, $outlines, \@markers, $records, $weight_col)
13722 # -> list of { features, colour, weight, opacity }
13723 #
13724 # The county outlines as layers for add_geojson. Without the heat layer
13725 # ($weight_col undef) they are one grey layer. With it, each outline is
13726 # coloured by the total of what is in it: the weight column summed over every
13727 # row of every marker inside it (a cell that is not a number adds nothing), or,
13728 # with no weight column (''), its rows counted. _outline_shares places each
13729 # total between green and red. A lone outline, or totals all alike, stays
13730 # grey with no key, having nothing to be compared with; $noun is what an
13731 # outline is called there, for the key's title. The layers go from low to high, so where two
13732 # outlines share a border the higher is drawn on top; the first carries the
13733 # key to the colours, high to low with the totals each covers. Each popup names the
13734 # outline and its total. Leaflet reads a popup as HTML, and a name from
13735 # OpenStreetMap is text, so it is escaped.
13736 41 ▶sub _map_outline_layers :Protected ($self, $outlines, $markers, $records, $weight_col, $noun) {
Subroutine _map_outline_layers: called CC=13 SCAR=25.8
13737 41 ▶ return () unless $outlines && @{ $outlines->{features} };
Branch: 1 branch
BranchTrueFalseTotal
unless $outlines and @{$outlines->{"features"};} 35 6 41
Condition100%3/3
$outlines and @{$outlines->{"features"};}
!ll&&!rl&&r
3056
MC/DC100%2/2
$outlines and @{$outlines->{"features"};}
$outlines @{$outlines->{"features"};}
Truth table100%3/3
A and B
A= $outlinesB= @{$outlines->{"features"};}
ABresult
0X0
100
111
13738  
13739 6 my @features = @{ $outlines->{features} };
13740 29 ▶ my $named = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
13741 29 my ($feature, $text) = @_;
13742 # osm stays, so the fill (shade=) can find the outline's total
13743 29 return { %{$feature}, properties => { name => xml_escape($text), osm => $feature->{properties}{osm} } };
13744 6 };
13745  
13746 # No heat layer: nothing to total, so one grey layer and no key.
13747 6 ▶ unless (defined $weight_col) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $weight_col) 2 4 6
13748 return {
13749 2 ▶ features => [ map { $named->($_, $_->{properties}{name} // '') } @features ],
Condition50%1/2
$_->{"properties"}{"name"} // ""
l!l
30
MC/DC0%0/1
$_->{"properties"}{"name"} // ""
$_->{"properties"}{"name"}
Truth table50%1/2
A
A= $_->{"properties"}{"name"}
Aresult
11
00
13750 %OUTLINE_PLAIN,
13751 };
13752 }
13753  
13754 4 ▶ my $total = $self->_map_outline_totals($outlines->{inside} // {}, $markers, $records, $weight_col);
Condition50%1/2
$outlines->{"inside"} // {}
l!l
40
MC/DC0%0/1
$outlines->{"inside"} // {}
$outlines->{"inside"}
Truth table50%1/2
A
A= $outlines->{"inside"}
Aresult
11
00
13755 4 ▶ my @totals = map { $total->{ $_->{properties}{osm} } // 0 } @features;
Condition50%1/2
$$total{$_->{"properties"}{"osm"}} // 0
l!l
260
MC/DC0%0/1
$$total{$_->{"properties"}{"osm"}} // 0
$$total{$_->{"properties"}{"osm"}}
Truth table50%1/2
A
A= $$total{$_->{"properties"}{"osm"}}
Aresult
11
00
13756  
13757 4 my %seen;
13758 4 my @distinct = grep { !$seen{$_}++ } sort { $a <=> $b } @totals;
13759  
13760 # One outline, or totals all alike: there is nothing to compare, so a
13761 # colour would mean nothing. Grey, with no key, but the popups still
13762 # give the totals.
13763 4 ▶ if (@distinct < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@distinct < 2) 1 3 4
13764 return {
13765 features => [ map {
13766 1 $named->($features[$_], $self->_map_outline_popup(
13767 2 ▶ $features[$_]{properties}{name} // '', $totals[$_], $weight_col))
Condition50%1/2
$features[$_]{"properties"}{"name"} // ""
l!l
20
MC/DC0%0/1
$features[$_]{"properties"}{"name"} // ""
$features[$_]{"properties"}{"name"}
Truth table50%1/2
A
A= $features[$_]{"properties"}{"name"}
Aresult
11
00
13768 } 0 .. $#features ],
13769 %OUTLINE_PLAIN,
13770 };
13771 }
13772 3 my $share_of = _outline_shares(\@distinct);
13773  
13774 # Lowest first: a layer is made the first time its step is met, so the
13775 # layers come out in the order they must be drawn.
13776 3 my (%layer_of, @layers);
13777 3 for my $i (sort { $totals[$a] <=> $totals[$b] } 0 .. $#features) {
13778 24 my $share = $share_of->{ $totals[$i] };
13779 24 my $step = int($share * ($OUTLINE_STEPS - 1) + 0.5);
13780 24 ▶ my $layer = $layer_of{$step} //= do {
Condition66%2/3
$layer_of{$step} //= do { push @layers, {"features", [], "totals", [], "colour", _outline_colour($step / ($OUTLINE_STEPS - 1)), %OUTLINE_HEAT}; $layers[-1] }
l!l&&r!l&&!r
12120
MC/DC0%0/2
$layer_of{$step} //= do { push @layers, {"features", [], "totals", [], "colour", _outline_colour($step / ($OUTLINE_STEPS - 1)), %OUTLINE_HEAT}; $layers[-1] }
$layer_of{$step} do { push @layers, {"features", [], "totals", [], "colour", _outline_colour($step / ($OUTLINE_STEPS - 1)), %OUTLINE_HEAT}; $layers[-1] }
Truth table66%2/3
A //= B
A= $layer_of{$step}B= do { push @layers, {"features", [], "totals", [], "colour", _outline_colour($step / ($OUTLINE_STEPS - 1)), %OUTLINE_HEAT}; $layers[-1] }
ABresult
1X1
011
000
13781 12 push @layers, { features => [], totals => [],
13782 colour => _outline_colour($step / ($OUTLINE_STEPS - 1)), %OUTLINE_HEAT };
13783 12 $layers[-1];
13784 };
13785 # Sorted already, so each layer's totals are low to high for the key.
13786 24 push @{ $layer->{totals} }, $totals[$i];
13787 24 my $feature = $features[$i];
13788 24 ▶ push @{ $layer->{features} }, $named->($feature,
Condition50%1/2
$feature->{"properties"}{"name"} // ""
l!l
240
MC/DC0%0/1
$feature->{"properties"}{"name"} // ""
$feature->{"properties"}{"name"}
Truth table50%1/2
A
A= $feature->{"properties"}{"name"}
Aresult
11
00
13789 24 $self->_map_outline_popup($feature->{properties}{name} // '', $totals[$i], $weight_col));
13790 # Drawn inside its own edge (HTML::OSM 0.17's bands), so a neighbour of
13791 # another colour is beside it, not over it.
13792 24 $layer->{features}[-1]{properties}{colours} = [ $layer->{colour} ];
13793 24 $layer->{bands} = 1;
13794 }
13795  
13796 # HTML::OSM 0.16 shows one key a layer name and hides it with the layer;
13797 # an older copy ignores it. The totals were only for the key.
13798 3 $layers[0]{key} = $self->_map_outline_key(\@layers, $weight_col, $noun);
13799 3 delete $_->{totals} for @layers;
13800 3 return @layers;
13801 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13802  
13803 # _map_outline_marker_layers($self, $outlines, \@markers)
13804 # -> list of { features, colour, weight, opacity, bands }
13805 #
13806 # Purpose: The outlines coloured as the markers in them, for a map whose
13807 # markers are coloured by a column.
13808 # Entry: $outlines as Boundary's outlines() returns it, or undef; each
13809 # coloured marker has lat, lon and colour (#rgb or #rrggbb).
13810 # Exit: One layer for each distinct list of colours, the outlines of one
13811 # colour first. An outline whose markers differ lists every colour,
13812 # the one most of its markers have first (the earliest on a tie), in
13813 # its feature's "colours" property. A coloured layer has bands set:
13814 # HTML::OSM 0.17 then draws each outline just inside its own edge, a
13815 # line of each colour side by side, the first outermost, so
13816 # neighbours of different colours are beside each other; "colour"
13817 # (the first) is what an older HTML::OSM draws, along the edge. () when there is nothing to draw or no marker has a
13818 # colour, so the caller can fall back.
13819 # Side effects: none.
13820 1 ▶sub _map_outline_marker_layers :Protected ($self, $outlines, $markers) {
Subroutine _map_outline_marker_layers: called CC=19 SCAR=58.2
13821 0 ▶ return () unless $outlines && @{ $outlines->{features} };
Branch: 1 branch
BranchTrueFalseTotal
unless $outlines and @{$outlines->{"features"};} 1 0 1
Condition33%1/3
$outlines and @{$outlines->{"features"};}
!ll&&!rl&&r
100
MC/DC0%0/2
$outlines and @{$outlines->{"features"};}
$outlines @{$outlines->{"features"};}
Truth table33%1/3
A and B
A= $outlinesB= @{$outlines->{"features"};}
ABresult
0X0
100
111
13822  
13823 0 require Database::BI::Model::Boundary;
13824 0 ▶ my $inside = $outlines->{inside} // {};
Condition0%0/2
$outlines->{"inside"} // {}
l!l
00
MC/DC0%0/1
$outlines->{"inside"} // {}
$outlines->{"inside"}
Truth table0%0/2
A
A= $outlines->{"inside"}
Aresult
11
00
13825 # How many markers of each colour are in each outline, in the order the
13826 # colours were first met there.
13827 0 my (%count, %order);
13828 0 for my $marker (@{$markers}) {
13829 0 ▶ my $colour = $marker->{colour} // next;
Condition0%0/2
$marker->{"colour"} // (next)
l!l
00
MC/DC0%0/1
$marker->{"colour"} // (next)
$marker->{"colour"}
Truth table0%0/2
A
A= $marker->{"colour"}
Aresult
11
00
13830 # The script takes #rrggbb only, so #rgb is written out in full
13831 0 $colour =~ s/\A#(.)(.)(.)\z/#$1$1$2$2$3$3/;
13832 0 my $key = Database::BI::Model::Boundary->point_key($marker->{lat}, $marker->{lon});
13833 0 ▶ my $osm = defined($key) ? $inside->{$key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $key ? : 0 0 0
13834 0 ▶ next unless defined $osm;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $osm 0 0 0
13835 0 ▶ push @{ $order{$osm} }, $colour unless $count{$osm}{$colour}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $count{$osm}{$colour}++ 0 0 0
13836 }
13837 0 ▶ return () unless %count;
Branch: 1 branch
BranchTrueFalseTotal
unless %count 0 0 0
13838  
13839 0 my (%layer_of, @layers);
13840 0 for my $feature (@{ $outlines->{features} }) {
13841 0 ▶ my $osm = $feature->{properties}{osm} // '';
Condition0%0/2
$feature->{"properties"}{"osm"} // ""
l!l
00
MC/DC0%0/1
$feature->{"properties"}{"osm"} // ""
$feature->{"properties"}{"osm"}
Truth table0%0/2
A
A= $feature->{"properties"}{"osm"}
Aresult
11
00
13842 0 ▶ my $seen = $order{$osm} // [];
Condition0%0/2
$order{$osm} // []
l!l
00
MC/DC0%0/1
$order{$osm} // []
$order{$osm}
Truth table0%0/2
A
A= $order{$osm}
Aresult
11
00
13843 0 my %place = map { $seen->[$_] => $_ } 0 .. $#{$seen};
13844 0 ▶ my @colours = sort { $count{$osm}{$b} <=> $count{$osm}{$a} || $place{$a} <=> $place{$b} } @{$seen};
Condition0%0/3
$count{$osm}{$b} <=> $count{$osm}{$a} || $place{$a} <=> $place{$b}
l!l&&r!l&&!r
000
MC/DC0%0/2
$count{$osm}{$b} <=> $count{$osm}{$a} || $place{$a} <=> $place{$b}
$count{$osm}{$b} <=> $count{$osm}{$a} $place{$a} <=> $place{$b}
Truth table0%0/3
A || B
A= $count{$osm}{$b} <=> $count{$osm}{$a}B= $place{$a} <=> $place{$b}
ABresult
1X1
011
000
13845 # An outline none of whose markers is coloured stays grey
13846 0 ▶ my $style = @colours ? { colour => $colours[0], %OUTLINE_HEAT } : { %OUTLINE_PLAIN };
Branch: 1 branch
BranchTrueFalseTotal
@colours ? : 0 0 0
13847 0 ▶ my $layer = $layer_of{"@colours"} //= do {
Condition0%0/3
$layer_of{join $", @colours} //= do { push @layers, {"features", [], %{$style;}, "bands", @colours ? 1 : 0, "mixed", @colours > 1 ? 1 : 0}; $layers[-1] }
l!l&&r!l&&!r
000
MC/DC0%0/2
$layer_of{join $", @colours} //= do { push @layers, {"features", [], %{$style;}, "bands", @colours ? 1 : 0, "mixed", @colours > 1 ? 1 : 0}; $layers[-1] }
$layer_of{join $", @colours} do { push @layers, {"features", [], %{$style;}, "bands", @colours ? 1 : 0, "mixed", @colours > 1 ? 1 : 0}; $layers[-1] }
Truth table0%0/3
A //= B
A= $layer_of{join $", @colours}B= do { push @layers, {"features", [], %{$style;}, "bands", @colours ? 1 : 0, "mixed", @colours > 1 ? 1 : 0}; $layers[-1] }
ABresult
1X1
011
000
13848 0 ▶ push @layers, { features => [], %{$style}, bands => (@colours ? 1 : 0), mixed => (@colours > 1 ? 1 : 0) };
Branch: 2 branches
BranchTrueFalseTotal
@colours ? : 0 0 0
@colours > 1 ? : 0 0 0
13849 0 $layers[-1];
13850 };
13851 # Leaflet reads a popup as HTML, and a name from OpenStreetMap is text
13852 0 push @{ $layer->{features} }, {
13853 0 ▶ %{$feature},
Condition0%0/2
$feature->{"properties"}{"name"} // ""
l!l
00
MC/DC0%0/1
$feature->{"properties"}{"name"} // ""
$feature->{"properties"}{"name"}
Truth table0%0/2
A
A= $feature->{"properties"}{"name"}
Aresult
11
00
13854 0 properties => { name => xml_escape($feature->{properties}{name} // ''), colours => \@colours, osm => $osm },
13855 };
13856 }
13857 # Those of several colours last: only an older HTML::OSM, which draws every
13858 # outline along its edge, can draw one over another, and then they show.
13859 0 return sort { $a->{mixed} <=> $b->{mixed} } @layers;
13860 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13861  
13862 # _map_outline_shade($self, \@layers, $outlines, \@markers, $records, $col, $colour, $noun, $lower)
13863 # -> list of layers, each with fill
13864 #
13865 # Purpose: Colour shade: fill each outline in a shade of a colour, by the
13866 # total of $col in it.
13867 # Entry: @layers as _map_outline_layers or _map_outline_marker_layers made
13868 # them (each feature keeps its osm and an escaped name); $col is a
13869 # column of $records. $colour is the one colour to shade, as
13870 # _parse_color takes one, or undef for the default. $lower, when a
13871 # hashref, says the markers are coloured and no colour was asked for:
13872 # each outline is then shaded in its own line colour (its markers'),
13873 # and $lower->{<#rrggbb>} is true for a colour whose rule is "less
13874 # than", where the smaller total is the stronger.
13875 # Exit: Each layer split by shade, so every part has one line style and
13876 # one "fill" (#rrggbb), in the order given. One colour: darker for a
13877 # larger total, across every outline. The markers' colours: each
13878 # colour is a scale of its own over the outlines of that colour,
13879 # stronger the further the total is into what the colour stands for
13880 # (larger, or smaller for a "less than" colour), so a county well
13881 # under a "below 20,000" rule is greener than one just under it; a
13882 # colour with one total is its middle shade. The shade follows
13883 # _outline_shares, as the heat colours do. Each popup names the
13884 # outline and its total; the first layer carries the key, every
13885 # shade in use by size, the largest totals first, drawn as boxes (HTML::OSM 0.18; an older copy
13886 # draws lines). () with one colour when fewer than two totals
13887 # differ: nothing to compare, so the caller leaves the outlines
13888 # unfilled.
13889 # Side effects: none.
13890 0 ▶sub _map_outline_shade :Protected ($self, $layers, $outlines, $markers, $records, $col, $colour, $noun, $lower) {
Subroutine _map_outline_shade: not called CC=21 SCAR=61.4
13891 0 ▶ return () unless $outlines && @{$layers};
Branch: 1 branch
BranchTrueFalseTotal
unless $outlines and @{$layers;} 0 0 0
Condition0%0/3
$outlines and @{$layers;}
!ll&&!rl&&r
000
MC/DC0%0/2
$outlines and @{$layers;}
$outlines @{$layers;}
Truth table0%0/3
A and B
A= $outlinesB= @{$layers;}
ABresult
0X0
100
111
13892  
13893 0 ▶ my $total = $self->_map_outline_totals($outlines->{inside} // {}, $markers, $records, $col);
Condition0%0/2
$outlines->{"inside"} // {}
l!l
00
MC/DC0%0/1
$outlines->{"inside"} // {}
$outlines->{"inside"}
Truth table0%0/2
A
A= $outlines->{"inside"}
Aresult
11
00
13894 0 ▶ my $amount = sub { return $total->{ $_[0]{properties}{osm} // '' } // 0 };
Subroutine __ANON__: not called CC=3 SCAR=24.8
Condition0%0/4
$$total{$_[0]{"properties"}{"osm"} // ""} // 0
l!l
00
$_[0]{"properties"}{"osm"} // ""
l!l
00
MC/DC0%0/1
$$total{$_[0]{"properties"}{"osm"} // ""} // 0
$$total{$_[0]{"properties"}{"osm"} // ""}
MC/DC0%0/1
$_[0]{"properties"}{"osm"} // ""
$_[0]{"properties"}{"osm"}
Truth table0%0/2
A
A= $$total{$_[0]{"properties"}{"osm"} // ""}
Aresult
11
00
Truth table0%0/2
A
A= $_[0]{"properties"}{"osm"}
Aresult
11
00
13895 0 ▶ my $one = _color_hex(_parse_color($colour // '') // $DEFAULT_SHADE_COLOR);
Condition0%0/5
_parse_color($colour // "") // $DEFAULT_SHADE_COLOR
l!l&&r!l&&!r
000
$colour // ""
l!l
00
MC/DC0%0/2
_parse_color($colour // "") // $DEFAULT_SHADE_COLOR
_parse_color($colour // "") $DEFAULT_SHADE_COLOR
MC/DC0%0/1
$colour // ""
$colour
Truth table0%0/3
A // B
A= _parse_color($colour // "")B= $DEFAULT_SHADE_COLOR
ABresult
1X1
011
000
Truth table0%0/2
A
A= $colour
Aresult
11
00
13896  
13897 # The colour each layer is shaded in: the one colour, or its own line's.
13898 # Written out as #rrggbb, which _shade_colour reads.
13899 0 ▶ my $hue_of = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
13900 0 ▶ my $hue = $lower ? $_[0]{colour} : $one;
Branch: 1 branch
BranchTrueFalseTotal
$lower ? : 0 0 0
13901 0 $hue =~ s/\A#(.)(.)(.)\z/#$1$1$2$2$3$3/;
13902 0 return lc $hue;
13903 0 };
13904  
13905 # Each colour's totals, then where each sits on that colour's scale.
13906 0 my (%totals_of, @hues);
13907 0 for my $layer (@{$layers}) {
13908 0 my $hue = $hue_of->($layer);
13909 0 ▶ push @hues, $hue unless $totals_of{$hue};
Branch: 1 branch
BranchTrueFalseTotal
unless $totals_of{$hue} 0 0 0
13910 0 $totals_of{$hue}{ $amount->($_) } = 1 for @{ $layer->{features} };
13911 }
13912 0 ▶ return () if !$lower && keys(%{ $totals_of{ $hues[0] } }) < 2;
Branch: 1 branch
BranchTrueFalseTotal
if not $lower and keys %{$totals_of{$hues[0]};} < 2 0 0 0
Condition0%0/3
not $lower and keys %{$totals_of{$hues[0]};} < 2
!ll&&!rl&&r
000
MC/DC0%0/2
not $lower and keys %{$totals_of{$hues[0]};} < 2
not $lower keys %{$totals_of{$hues[0]};} < 2
Truth table0%0/3
not(A) and B
A= not $lowerB= keys %{$totals_of{$hues[0]};} < 2
ABresult
0X0
100
111
13913 0 my %share_of;
13914 0 for my $hue (@hues) {
13915 0 my @distinct = sort { $a <=> $b } keys %{ $totals_of{$hue} };
13916 0 ▶ my $shares = @distinct > 1 ? _outline_shares(\@distinct) : { $distinct[0] => 0.5 };
Branch: 1 branch
BranchTrueFalseTotal
@distinct > 1 ? : 0 0 0
13917 # A "less than" colour is the stronger the smaller the total
13918 0 ▶ $shares = { map { $_ => 1 - $shares->{$_} } keys %{$shares} } if $lower && $lower->{$hue};
Branch: 1 branch
BranchTrueFalseTotal
if $lower and $lower->{$hue} 0 0 0
Condition0%0/3
$lower and $lower->{$hue}
!ll&&!rl&&r
000
MC/DC0%0/2
$lower and $lower->{$hue}
$lower $lower->{$hue}
Truth table0%0/3
A and B
A= $lowerB= $lower->{$hue}
ABresult
0X0
100
111
13919 0 $share_of{$hue} = $shares;
13920 }
13921  
13922 0 my (@shaded, %amounts);
13923 0 for my $layer (@{$layers}) {
13924 0 my $hue = $hue_of->($layer);
13925 0 my (%part, @steps);
13926 0 for my $feature (@{ $layer->{features} }) {
13927 0 my $sum = $amount->($feature);
13928 0 my $step = int($share_of{$hue}{$sum} * ($SHADE_STEPS - 1) + 0.5);
13929 0 ▶ push @steps, $step unless $part{$step};
Branch: 1 branch
BranchTrueFalseTotal
unless $part{$step} 0 0 0
13930 0 push @{ $amounts{$hue}{$step} }, $sum;
13931 # The name is escaped already; the column is text of the reader's
13932 0 push @{ $part{$step} }, {
13933 0 %{$feature},
13934 properties => {
13935 0 ▶ %{ $feature->{properties} },
Condition0%0/2
$feature->{"properties"}{"name"} // ""
l!l
00
MC/DC0%0/1
$feature->{"properties"}{"name"} // ""
$feature->{"properties"}{"name"}
Truth table0%0/2
A
A= $feature->{"properties"}{"name"}
Aresult
11
00
13936 name => $self->_i18n('map_bounds_total',
13937 0 $feature->{properties}{name} // '', _map_total_text($sum), xml_escape($col)),
13938 },
13939 };
13940 }
13941 push @shaded, map {
13942 0 +{ %{$layer}, features => $part{$_}, fill => _shade_colour($hue, $_ / ($SHADE_STEPS - 1)) }
13943 0 } sort { $a <=> $b } @steps;
13944 }
13945  
13946 # One key for the fills, in place of any the lines had: for each colour
13947 # the shades in use, strongest first as _map_outline_key lists them,
13948 # drawn as boxes.
13949 0 delete $_->{key} for @shaded;
13950 # They are listed by size whatever their colour, the largest totals at the
13951 # top, so a key of red above 100,000 and green below 20,000 runs from the
13952 # strongest red down to the strongest green.
13953 0 ▶ my @in_use = sort { $a->{totals}[-1] <=> $b->{totals}[-1] || $a->{totals}[0] <=> $b->{totals}[0] } map {
Condition0%0/3
$Database::BI::Controller::Dashboard::a->{'totals'}[-1] <=> $Database::BI::Controller::Dashboard::b->{'totals'}[-1] || $Database::BI::Controller::Dashboard::a->{'totals'}[0] <=> $Database::BI::Controller::Dashboard::b->{'totals'}[0]
l!l&&r!l&&!r
000
MC/DC0%0/2
$Database::BI::Controller::Dashboard::a->{'totals'}[-1] <=> $Database::BI::Controller::Dashboard::b->{'totals'}[-1] || $Database::BI::Controller::Dashboard::a->{'totals'}[0] <=> $Database::BI::Controller::Dashboard::b->{'totals'}[0]
$Database::BI::Controller::Dashboard::a->{'totals'}[-1] <=> $Database::BI::Controller::Dashboard::b->{'totals'}[-1] $Database::BI::Controller::Dashboard::a->{'totals'}[0] <=> $Database::BI::Controller::Dashboard::b->{'totals'}[0]
Truth table0%0/3
A || B
A= $Database::BI::Controller::Dashboard::a->{'totals'}[-1] <=> $Database::BI::Controller::Dashboard::b->{'totals'}[-1]B= $Database::BI::Controller::Dashboard::a->{'totals'}[0] <=> $Database::BI::Controller::Dashboard::b->{'totals'}[0]
ABresult
1X1
011
000
13954 0 my $hue = $_;
13955 map {
13956 +{ colour => _shade_colour($hue, $_ / ($SHADE_STEPS - 1)),
13957 0 totals => [ sort { $a <=> $b } @{ $amounts{$hue}{$_} } ] }
13958 0 } keys %{ $amounts{$hue} };
13959 } @hues;
13960 0 $shaded[0]{key} = { %{ $self->_map_outline_key(\@in_use, $col, $noun) }, shape => 'box' };
13961 0 return @shaded;
13962 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13963  
13964 # _shade_colour($hex, $share) -> '#rrggbb': $hex (#rrggbb) at its full
13965 # strength for a share of 1, down to $SHADE_LIGHTEST of the way from white for
13966 # a share of 0.
13967 0 ▶sub _shade_colour {
Subroutine _shade_colour: not called CC=3 SCAR=24.8
13968 0 my ($hex, $share) = @_;
13969 0 ▶ $share = 0 if $share < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $share < 0 0 0 0
13970 0 ▶ $share = 1 if $share > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $share > 1 0 0 0
13971 0 my $strength = $SHADE_LIGHTEST + (1 - $SHADE_LIGHTEST) * $share;
13972 return sprintf('#%02x%02x%02x',
13973 0 map { int(255 + (hex($_) - 255) * $strength + 0.5) } $hex =~ /\A#(..)(..)(..)\z/);
13974 }
13975  
13976 # _map_outline_totals($self, \%inside, \@markers, $records, $weight_col) -> \%total
13977 #
13978 # Purpose: What is in each outline, for its colour.
13979 # Entry: %inside maps a point key to the osm of the outline it is in (from
13980 # Boundary's outlines()); each marker has lat, lon and row_indexes
13981 # (or first_row); $weight_col is a column, or '' to count rows.
13982 # Exit: { osm => total }; an outline no marker is in has no entry.
13983 # Side effects: none. Rows are only read, so locked SQL rows are safe.
13984 4 ▶sub _map_outline_totals :Protected ($self, $inside, $markers, $records, $weight_col) {
Subroutine _map_outline_totals: called CC=10 SCAR=24.1
13985 4 require Database::BI::Model::Boundary;
13986 4 my %total;
13987 4 for my $marker (@{$markers}) {
13988 26 my $key = Database::BI::Model::Boundary->point_key($marker->{lat}, $marker->{lon});
13989 26 ▶ my $osm = defined($key) ? $inside->{$key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $key ? : 26 0 26
13990 26 ▶ next unless defined $osm;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $osm 0 26 26
13991 # A marker stands for every row at its place, not only the first.
13992 26 ▶ for my $index (@{ $marker->{row_indexes} // [ $marker->{first_row} ] }) {
Condition50%1/2
$marker->{"row_indexes"} // [$marker->{"first_row"}]
l!l
260
MC/DC0%0/1
$marker->{"row_indexes"} // [$marker->{"first_row"}]
$marker->{"row_indexes"}
Truth table50%1/2
A
A= $marker->{"row_indexes"}
Aresult
11
00
13993 27 my $row = $records->[$index];
13994 27 ▶ next unless ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 0 27 27
13995 # A cell that is not a number adds nothing, as on the heat layer.
13996 27 ▶ $total{$osm} += length($weight_col) ? (_numeric_cell($row->{$weight_col} // '') // 0) : 1;
Branch: 1 branch
BranchTrueFalseTotal
length $weight_col ? : 22 5 27
Condition50%2/4
_numeric_cell($row->{$weight_col} // "") // 0
l!l
220
$row->{$weight_col} // ""
l!l
220
MC/DC0%0/1
_numeric_cell($row->{$weight_col} // "") // 0
_numeric_cell($row->{$weight_col} // "")
MC/DC0%0/1
$row->{$weight_col} // ""
$row->{$weight_col}
Truth table50%1/2
A
A= _numeric_cell($row->{$weight_col} // "")
Aresult
11
00
Truth table50%1/2
A
A= $row->{$weight_col}
Aresult
11
00
13997 }
13998 }
13999 4 return \%total;
14000 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
14001  
14002 # _map_outline_popup($self, $name, $total, $weight_col) -> $text
14003 #
14004 # Purpose: The text of a coloured outline's popup: its name and its total.
14005 # Entry: $weight_col is the column totalled, or '' when rows were counted.
14006 # Exit: Plain text (the caller escapes it); one row is "1 row", not "1 rows".
14007 # Side effects: none.
14008 26 ▶sub _map_outline_popup :Protected ($self, $name, $total, $weight_col) {
Subroutine _map_outline_popup: called CC=3 SCAR=11.0
14009 26 ▶ return $self->_i18n('map_bounds_total', $name, _map_total_text($total), $weight_col) if length $weight_col;
Branch: 1 branch
BranchTrueFalseTotal
if length $weight_col 22 4 26
14010 4 ▶ return $total == 1
Branch: 1 branch
BranchTrueFalseTotal
$total == 1 ? : 3 1 4
14011 ? $self->_i18n('map_bounds_row', $name)
14012 : $self->_i18n('map_bounds_rows', $name, _map_total_text($total));
14013 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
14014  
14015 # _map_outline_key($self, \@layers, $weight_col) -> { title, entries }
14016 #
14017 # Purpose: The key to the outline colours, for add_geojson's key option.
14018 # Entry: Each layer has its colour and its totals, low to high; the layers
14019 # are low to high too, and there is at least one.
14020 # Exit: The entries are the highest colour first, each labelled with the
14021 # total it covers, or the range when it covers unequal totals.
14022 # Side effects: none.
14023 3 ▶sub _map_outline_key :Protected ($self, $layers, $weight_col, $noun) {
Subroutine _map_outline_key: called CC=3 SCAR=11.0
14024 my @entries = map {
14025 12 my ($low, $high) = @{ $_->{totals} }[0, -1];
14026 +{
14027 colour => $_->{colour},
14028 # Round figures: a key is read at a glance, and the popups
14029 # give each outline's exact total.
14030 12 ▶ label => (_map_key_number($low) eq _map_key_number($high) ? _map_key_number($low)
Branch: 1 branch
BranchTrueFalseTotal
_map_key_number($low) eq _map_key_number($high) ? : 7 5 12
14031 : $self->_i18n('map_bounds_key_range', _map_key_number($low), _map_key_number($high))),
14032 };
14033 3 } reverse @{$layers};
14034 return {
14035 3 ▶ title => (length($weight_col)
Branch: 1 branch
BranchTrueFalseTotal
length $weight_col ? : 2 1 3
14036 ? $self->_i18n('map_bounds_key_total', $weight_col, $noun)
14037 : $self->_i18n('map_bounds_key_rows', $noun)),
14038 entries => \@entries,
14039 };
14040 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
14041  
14042 # _outline_shares(\@distinct) -> { total => share }
14043 #
14044 # Purpose: Where each total sits between the lowest (0) and the highest (1),
14045 # which decides its colour.
14046 # Entry: At least two distinct totals, sorted low to high.
14047 # Exit: When every total is above zero, the share is by size on a log
14048 # scale: each step up the colours is the same multiple, so totals
14049 # close in size share a colour and totals far apart do not. A
14050 # straight scale would leave most outlines green, because such totals
14051 # are skewed (Fairfax County has 500 times the people of Highland).
14052 # A total of zero or less has no logarithm, so then the share is by
14053 # rank: evenly spread in order, whatever the sizes.
14054 # Side effects: none.
14055 3 ▶sub _outline_shares {
Subroutine _outline_shares: called CC=2 SCAR=7.6
14056 3 my ($distinct) = @_;
14057 3 my %share;
14058 3 ▶ if ($distinct->[0] > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distinct->[0] > 0) { } 3 0 3
14059 3 my ($low, $high) = (log $distinct->[0], log $distinct->[-1]);
14060 # The ends are set exactly, so rounding cannot push them off the scale.
14061 3 %share = map { $_ => (log($_) - $low) / ($high - $low) } @{$distinct};
14062 3 @share{ $distinct->[0], $distinct->[-1] } = (0, 1);
14063 } else {
14064 0 %share = map { $distinct->[$_] => $_ / $#{$distinct} } 0 .. $#{$distinct};
14065 }
14066 3 return \%share;
14067 }
14068  
14069 # _map_outline_noun($self, $outlines, $level) -> $word
14070 #
14071 # Purpose: What the outlines drawn are called ("county", "district"), for the
14072 # layer's checkbox, the key, the summary line and the notes about
14073 # outlines not had yet.
14074 # Entry: $outlines as Boundary's outlines() returns it, or undef; $level
14075 # the bounds= level they were asked at, or undef.
14076 # Exit: The word for the one kind drawn; "area" when the map mixes kinds
14077 # (a county and a province); what the level is called by default
14078 # ("state", "town") when nothing is drawn, since no country is known
14079 # then; "county" with no level.
14080 # Side effects: none.
14081 97 ▶sub _map_outline_noun :Protected ($self, $outlines, $level = undef) {
Subroutine _map_outline_noun: called CC=7 SCAR=19.9
14082 97 require Database::BI::Model::Boundary;
14083 97 ▶ my $usual = Database::BI::Model::Boundary->level_name($level) // 'county';
Condition100%2/2
"Database::BI::Model::Boundary"->level_name($level) // "county"
l!l
2869
MC/DC100%1/1
"Database::BI::Model::Boundary"->level_name($level) // "county"
"Database::BI::Model::Boundary"->level_name($level)
Truth table100%2/2
A
A= "Database::BI::Model::Boundary"->level_name($level)
Aresult
11
00
14084 97 ▶ my %called = map { ($_->{properties}{called} // $usual) => 1 } @{ $outlines ? $outlines->{features} : [] };
Branch: 1 branch
BranchTrueFalseTotal
$outlines ? : 28 69 97
Condition33%1/3
$_->{"properties"}{"called"} // $usual
l!l&&r!l&&!r
5900
MC/DC0%0/2
$_->{"properties"}{"called"} // $usual
$_->{"properties"}{"called"} $usual
Truth table33%1/3
A // B
A= $_->{"properties"}{"called"}B= $usual
ABresult
1X1
011
000
14085 97 my @kinds = keys %called;
14086 97 ▶ my $kind = @kinds > 1 ? 'area' : ($kinds[0] // $usual);
Branch: 1 branch
BranchTrueFalseTotal
@kinds > 1 ? : 0 97 97
Condition66%2/3
$kinds[0] // $usual
l!l&&r!l&&!r
13840
MC/DC0%0/2
$kinds[0] // $usual
$kinds[0] $usual
Truth table66%2/3
A // B
A= $kinds[0]B= $usual
ABresult
1X1
011
000
14087 97 return $self->_i18n("map_bounds_noun_$kind");
14088 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
14089  
14090 # _outline_colour($share) -> '#rrggbb' at $share (0..1) along @OUTLINE_STOPS
14091 12 ▶sub _outline_colour {
Subroutine _outline_colour: called CC=4 SCAR=13.9
14092 12 my ($share) = @_;
14093 12 ▶ $share = 0 if $share < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $share < 0 0 12 12
14094 12 ▶ $share = 1 if $share > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $share > 1 0 12 12
14095 12 my $at = $share * $#OUTLINE_STOPS;
14096 12 my $from = int($at);
14097 12 ▶ $from = $#OUTLINE_STOPS - 1 if $from >= $#OUTLINE_STOPS;
Branch: 1 branch
BranchTrueFalseTotal
if $from >= $#OUTLINE_STOPS 3 9 12
14098 12 my $part = $at - $from;
14099 12 my ($lo, $hi) = @OUTLINE_STOPS[ $from, $from + 1 ];
14100 12 return sprintf('#%02x%02x%02x', map { int($lo->[$_] + ($hi->[$_] - $lo->[$_]) * $part + 0.5) } 0 .. 2);
14101 }
14102  
14103 # _map_key_number($n) -> a total as a key shows it: rounded to two figures
14104 # ("330,000" for 330,818, "1,200,000" for 1,150,309), since a key gives ranges
14105 # to be read at a glance. A total under 100 is given as it is.
14106 41 ▶sub _map_key_number {
Subroutine _map_key_number: called CC=2 SCAR=9.2
14107 41 my ($n) = @_;
14108 41 ▶ return _map_total_text($n) if abs($n) < $KEY_ROUND_FROM;
Branch: 1 branch
BranchTrueFalseTotal
if abs $n < $KEY_ROUND_FROM 41 0 41
14109 0 my $unit = 10 ** (POSIX::floor(log(abs($n)) / log(10)) - ($KEY_FIGURES - 1));
14110 0 return _map_total_text(POSIX::floor($n / $unit + 0.5) * $unit);
14111 }
14112  
14113 # _map_total_text($n) -> the total as a popup shows it: thousands separated,
14114 # and at most two decimal places ("1,150,309", "12.5").
14115 64 ▶sub _map_total_text {
Subroutine _map_total_text: called CC=5 SCAR=17.0
14116 64 my ($n) = @_;
14117 64 my $text = sprintf('%.2f', $n);
14118 64 ▶ $text =~ s/\.?0+\z// if $text =~ /\./;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /\./u 64 0 64
14119 # A small negative total rounds to nothing; say 0, not "-0".
14120 64 ▶ $text = '0' if $text eq '-0';
Branch: 1 branch
BranchTrueFalseTotal
if $text eq "-0" 0 64 64
14121 64 my ($whole, $fraction) = split /\./, $text, 2;
14122 64 ▶ 1 while $whole =~ s/^(-?\d+)(\d{3})/$1,$2/;
Branch: 1 branch
BranchTrueFalseTotal
$whole =~ s/^(-?\d+)(\d{3})/$1,$2/u and do { '???' } 0 64 64
14123 64 ▶ return defined($fraction) ? "$whole.$fraction" : $whole;
Branch: 1 branch
BranchTrueFalseTotal
defined $fraction ? : 0 64 64
14124 }
14125  
14126 # _map_bounds_level($value) -> the level, or undef when $value names none
14127 #
14128 # bounds= on the map page, and a map card's options.bounds, which is stored
14129 # unchecked.
14130 64 ▶sub _map_bounds_level {
Subroutine _map_bounds_level: called CC=5 SCAR=16.2
14131 64 my ($value) = @_;
14132 64 ▶ return unless defined($value) && !ref($value) && length($value);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value and length $value 39 25 64
Condition66%4/6
defined $value and not ref $value and length $value
!ll&&!rl&&r
39025
defined $value and not ref $value
!ll&&!rl&&r
39025
MC/DC33%1/3
defined $value and not ref $value and length $value
defined $value not ref $value length $value
Truth table50%2/4
A and not(B) and C
A= defined $valueB= not ref $valueC= length $value
ABCresult
0XX0
10X0
1100
1111
14133 25 require Database::BI::Model::Boundary;
14134 25 ▶ return (grep { $_ eq $value } Database::BI::Model::Boundary->levels) ? $value : undef;
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ eq $value;} 'Database::BI::Model::Boundary'->levels) ? : 24 1 25
14135 }
14136  
14137 # _map_data($self, \@records, \@columns, \%encode, \%options, $spec_key, $id_suffix)
14138 # -> \%result
14139 #
14140 # Resolve a map's markers and draw its HTML. The map page and a map card on a
14141 # canvas both come through here: a map spec names either loc=<column> (places
14142 # to geocode) or lat=/lon= (coordinates already in the data), and everything
14143 # else - the marker cap, popups, the geocode cache and HTML::OSM - is the same
14144 # in both places. %result has { map_body, map_head, title, messages, ... } on success
14145 # or { error, status } when the spec cannot be drawn. $id_suffix makes the
14146 # Leaflet element ids unique when several maps share one page; undef leaves the
14147 # map page's own ids alone.
14148 63 ▶sub _map_data :Protected ($self, $records, $columns, $encode, $options, $spec_key, $id_suffix) {
Subroutine _map_data: called CC=217 SCAR=69.9
14149 63 $spec_key = canonical_spec($spec_key);
14150 63 ▶ $encode //= {};
Condition50%1/2
$encode //= {}
l!l
630
MC/DC0%0/1
$encode //= {}
$encode
Truth table50%1/2
A
A= $encode
Aresult
11
00
14151 63 ▶ $options //= {};
Condition50%1/2
$options //= {}
l!l
630
MC/DC0%0/1
$options //= {}
$options
Truth table50%1/2
A
A= $options
Aresult
11
00
14152  
14153 # loc may name several columns, in order: the place is their cells joined
14154 # with ", " (an address and then its country). $loc_col is that list's
14155 # name, which is what the page and the geocoder are told.
14156 63 my @loc_cols = _map_loc_columns($encode->{loc});
14157 63 my $loc_col = join(', ', @loc_cols);
14158 63 ▶ my $lat_col = $encode->{lat} // '';
Condition100%2/2
$encode->{"lat"} // ""
l!l
3132
MC/DC100%1/1
$encode->{"lat"} // ""
$encode->{"lat"}
Truth table100%2/2
A
A= $encode->{"lat"}
Aresult
11
00
14159 63 ▶ my $lon_col = $encode->{lon} // '';
Condition100%2/2
$encode->{"lon"} // ""
l!l
3132
MC/DC100%1/1
$encode->{"lon"} // ""
$encode->{"lon"}
Truth table100%2/2
A
A= $encode->{"lon"}
Aresult
11
00
14160 63 my $by_location = length $loc_col;
14161 63 my ($loc_text) = _map_loc_text($encode->{loc_text});
14162 63 ▶ $loc_text = '' unless defined($loc_text) && $by_location;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $loc_text and $by_location 32 31 63
Condition66%2/3
defined $loc_text and $by_location
!ll&&!rl&&r
03231
MC/DC50%1/2
defined $loc_text and $by_location
defined $loc_text $by_location
Truth table66%2/3
A and B
A= defined $loc_textB= $by_location
ABresult
0X0
100
111
14163  
14164 63 ▶ return { error => $self->_i18n('error_map_source'), status => 400 }
Branch: 1 branch
BranchTrueFalseTotal
unless $by_location or length $lat_col or length $lon_col 1 62 63
Condition83%5/6
$by_location or length $lat_col or length $lon_col
l!l&&r!l&&!r
6201
$by_location or length $lat_col
l!l&&r!l&&!r
31311
MC/DC66%2/3
$by_location or length $lat_col or length $lon_col
$by_location length $lat_col length $lon_col
Truth table75%3/4
A or B or C
A= $by_locationB= length $lat_colC= length $lon_col
ABCresult
1XX1
01X1
0011
0000
14165 unless $by_location || length($lat_col) || length($lon_col);
14166 62 ▶ return { error => $self->_i18n('error_map_coordinates'), status => 400 }
Branch: 1 branch
BranchTrueFalseTotal
unless $by_location or length $lat_col and length $lon_col 0 62 62
Condition50%3/6
$by_location or length $lat_col and length $lon_col
l!l&&r!l&&!r
31310
length $lat_col and length $lon_col
!ll&&!rl&&r
0031
MC/DC0%0/3
$by_location or length $lat_col and length $lon_col
$by_location length $lat_col length $lon_col
Truth table50%2/4
A or B and C
A= $by_locationB= length $lat_colC= length $lon_col
ABCresult
1XX1
0111
00X0
0100
14167 if !$by_location && (!length($lat_col) || !length($lon_col));
14168  
14169 62 my %col_set = map { $_ => 1 } @$columns;
14170 62 my $cfg = $self->app->config;
14171  
14172 62 my %loc_set = map { $_ => 1 } @loc_cols;
14173 my @popup = grep {
14174 2 ▶ defined($_) && !ref($_) && length($_) && !$loc_set{$_} && $col_set{$_}
Condition33%4/12
defined $_ && !ref($_) && length $_ && !$loc_set{$_} && $col_set{$_}
!ll&&!rl&&r
002
defined $_ and not ref $_ and length $_ and not $loc_set{$_}
!ll&&!rl&&r
002
defined $_ and not ref $_ and length $_
!ll&&!rl&&r
002
defined $_ and not ref $_
!ll&&!rl&&r
002
MC/DC0%0/5
defined $_ && !ref($_) && length $_ && !$loc_set{$_} && $col_set{$_}
defined $_ not ref $_ length $_ not $loc_set{$_} $col_set{$_}
Truth table16%1/6
A and not(B) and C and not(D) && E
A= defined $_B= not ref $_C= length $_D= not $loc_set{$_}E= $col_set{$_}
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
14175 62 ▶ } @{ ref($options->{popup}) eq 'ARRAY' ? $options->{popup} : [] };
Branch: 1 branch
BranchTrueFalseTotal
ref $options->{'popup'} eq 'ARRAY' ? : 2 60 62
14176  
14177 # Default: when no popup columns are requested, show every column that is
14178 # not a coordinate column so the marker tooltip is informative out of the box.
14179 62 ▶ unless (@popup) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@popup) 60 2 62
14180 90 my %coord_set = map { $_ => 1 }
14181 60 ▶ grep { defined($_) && length($_) } (@loc_cols, $lat_col, $lon_col);
Condition66%2/3
defined $_ && length $_
!ll&&!rl&&r
06090
MC/DC50%1/2
defined $_ && length $_
defined $_ length $_
Truth table66%2/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
14182 60 @popup = grep { !$coord_set{$_} } @$columns;
14183 }
14184  
14185 62 my ($backend, $plotted_rows) = (undef, 0);
14186 62 my (@markers, @messages, @unplotted, @unplotted_filters, @pending);
14187  
14188 # How many rows a popup lists, and where the rest are: the map page passes
14189 # rows_url, which makes a table link from filters; a canvas card has none.
14190 62 my $popup_rows = _map_limit($cfg->{map_popup_rows}, $DEFAULT_MAP_POPUP_ROWS);
14191 62 ▶ my $rows_url = ref($options->{rows_url}) eq 'CODE' ? $options->{rows_url} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $options->{'rows_url'} eq 'CODE' ? : 56 6 62
14192  
14193 62 ▶ if ($by_location) {
Branch: 1 branch
BranchTrueFalseTotal
if ($by_location) { } 31 31 62
14194 31 for my $col (@loc_cols) {
14195 return { error => $self->_i18n('error_map_loc_column', $col), status => 400 }
14196 31 ▶ unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 5 26 31
14197 }
14198  
14199 26 require Database::BI::Model::Geocode;
14200  
14201 # What the geocoder is given: one cell a row, under $loc_col, in the
14202 # rows' own order, so a marker's first_row still indexes $records.
14203 26 my ($places) = Database::BI::Model::Geocode->place_rows($records, \@loc_cols, $loc_text);
14204  
14205 26 my $geocode = $self->_map_geocoder(1);
14206  
14207 # A place name means the same place whichever file's column holds it, so
14208 # the answers live in one shared cache: the second dataset that names a
14209 # place plots it without asking the geocoder. A per-dataset entry from an
14210 # older model store is folded in as well; the shared answer wins if both
14211 # have the name, and places only the old entry knows about are moved into
14212 # the shared cache below, so the next dataset benefits from them too.
14213 26 ▶ my $cache_spec = ($spec_key // '') . '|loc=' . $loc_col;
Condition50%1/2
$spec_key // ""
l!l
260
MC/DC0%0/1
$spec_key // ""
$spec_key
Truth table50%1/2
A
A= $spec_key
Aresult
11
00
14214 26 my $models = $self->_read_models;
14215 26 my $legacy = Database::BI::Model::Geocode->cache_from_models($models, $cache_spec);
14216 26 my $shared = Database::BI::Model::Geocode->shared_cache_from_models($models);
14217 26 my %cache = (%$legacy, %$shared);
14218 0 my $to_share = grep { !exists $shared->{$_} } keys %$legacy;
14219 26 my $region = _map_region($cfg);
14220  
14221 # lookup => 0 (the map page in a browser) asks nothing here: the
14222 # places not cached yet come back as pending, and the page looks them
14223 # up one at a time through /geo/lookup, with a progress bar.
14224 my $result = $geocode->resolve_column(
14225 $places, $loc_col,
14226 cache => \%cache,
14227 (defined($region) ? (region => $region) : ()),
14228 max => _map_limit($cfg->{map_geocode_max}, $DEFAULT_MAP_GEOCODE_MAX),
14229 26 ▶ lookup => ((defined($options->{lookup}) && !$options->{lookup}) ? 0 : 1),
Branch: 2 branches
BranchTrueFalseTotal
defined $region ? : 0 26 26
defined $options->{'lookup'} && !$options->{'lookup'} ? : 1 25 26
Condition66%2/3
defined $options->{"lookup"} and not $options->{"lookup"}
!ll&&!rl&&r
2501
MC/DC50%1/2
defined $options->{"lookup"} and not $options->{"lookup"}
defined $options->{"lookup"} not $options->{"lookup"}
Truth table66%2/3
A and not(B)
A= defined $options->{"lookup"}B= not $options->{"lookup"}
ABresult
0X0
100
111
14230 );
14231 25 ▶ @pending = @{ $result->{pending} // [] };
Condition50%1/2
$result->{"pending"} // []
l!l
250
MC/DC0%0/1
$result->{"pending"} // []
$result->{"pending"}
Truth table50%1/2
A
A= $result->{"pending"}
Aresult
11
00
14232  
14233 25 push @messages, @{ $result->{messages} };
14234 25 $backend = $result->{backend};
14235 25 $plotted_rows = $result->{counts}{plotted};
14236 25 my ($entries, $all) = _map_unplotted($records, $places, $loc_col, \@loc_cols, $result);
14237 25 @unplotted = @{$entries};
14238 25 @unplotted_filters = @{$all};
14239  
14240 # Only a request that asked something new, or found old answers to move
14241 # into the shared cache, has something new to remember: rewriting the
14242 # store for a page answered entirely from the shared cache would be a
14243 # write per view. $to_share empties after the migration, so an old store
14244 # is written once per dataset rather than on every view.
14245 25 ▶ if ($result->{counts}{attempted} || $to_share) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{"counts"}{"attempted"} or $to_share) 20 5 25
Condition66%2/3
$result->{"counts"}{"attempted"} or $to_share
l!l&&r!l&&!r
2005
MC/DC50%1/2
$result->{"counts"}{"attempted"} or $to_share
$result->{"counts"}{"attempted"} $to_share
Truth table66%2/3
A or B
A= $result->{"counts"}{"attempted"}B= $to_share
ABresult
1X1
011
000
14246 my $updated = Database::BI::Model::Geocode->models_with_shared_cache(
14247 $models, $result->{cache},
14248 20 ▶ (defined($backend) ? (backend => $backend) : ()),
Branch: 1 branch
BranchTrueFalseTotal
defined $backend ? : 19 1 20
14249 built => _iso8601_utc(),
14250 );
14251 20 my $written = $self->_write_models($updated);
14252  
14253 # A failed migration is not worth a page message: the answers are
14254 # still in the old entry, so this dataset is unaffected. A failed
14255 # new lookup is, because the next visit pays for it again.
14256 20 ▶ if (!$written && $result->{counts}{attempted}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $written and $result->{"counts"}{"attempted"}) 4 16 20
Condition66%2/3
not $written and $result->{"counts"}{"attempted"}
!ll&&!rl&&r
1604
MC/DC50%1/2
not $written and $result->{"counts"}{"attempted"}
not $written $result->{"counts"}{"attempted"}
Truth table66%2/3
not(A) and B
A= not $writtenB= $result->{"counts"}{"attempted"}
ABresult
0X0
100
111
14257 4 push @messages, {
14258 key => 'warn_map_cache_unwritten',
14259 text => $self->_i18n('warn_map_cache_unwritten'),
14260 };
14261 }
14262 }
14263  
14264 # Every row at a place, keyed as the geocoder keyed the place, so its
14265 # popup can list them all and not only the first.
14266 25 my %rows_at;
14267 25 for my $index (0 .. $#{$places}) {
14268 83 my $place = $places->[$index];
14269 83 ▶ my $value = ref($place) eq 'HASH' ? $place->{$loc_col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $place eq 'HASH' ? : 83 0 83
14270 83 ▶ push @{ $rows_at{ (defined($value) && !ref($value)) ? $value : '' } }, $index;
Branch: 1 branch
BranchTrueFalseTotal
defined $value && !ref($value) ? : 74 9 83
Condition66%2/3
defined $value and not ref $value
!ll&&!rl&&r
9074
MC/DC50%1/2
defined $value and not ref $value
defined $value not ref $value
Truth table66%2/3
A and not(B)
A= defined $valueB= not ref $value
ABresult
0X0
100
111
14271 }
14272  
14273 25 for my $marker (@{ $result->{markers} }) {
14274 38 ▶ my @at = @{ $rows_at{ $marker->{value} } // [] };
Condition50%1/2
$rows_at{$marker->{"value"}} // []
l!l
380
MC/DC0%0/1
$rows_at{$marker->{"value"}} // []
$rows_at{$marker->{"value"}}
Truth table50%1/2
A
A= $rows_at{$marker->{"value"}}
Aresult
11
00
14275 38 ▶ my $row = $records->[ $at[0] // $marker->{first_row} ];
Condition33%1/3
$at[0] // $marker->{"first_row"}
l!l&&r!l&&!r
3800
MC/DC0%0/2
$at[0] // $marker->{"first_row"}
$at[0] $marker->{"first_row"}
Truth table33%1/3
A // B
A= $at[0]B= $marker->{"first_row"}
ABresult
1X1
011
000
14276 38 ▶ $row = {} unless ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 0 38 38
14277 my $more_url = $rows_url ? $rows_url->([ map {
14278 38 ▶ my $cell = $row->{$_};
Branch: 1 branch
BranchTrueFalseTotal
$rows_url ? : 35 3 38
14279 35 ▶ (defined($cell) && !ref($cell) && length($cell)) ? "$_:eq:$cell" : "$_:empty";
Branch: 1 branch
BranchTrueFalseTotal
defined $cell && !ref($cell) && length $cell ? : 35 0 35
Condition33%2/6
defined $cell and not ref $cell and length $cell
!ll&&!rl&&r
0035
defined $cell and not ref $cell
!ll&&!rl&&r
0035
MC/DC0%0/3
defined $cell and not ref $cell and length $cell
defined $cell not ref $cell length $cell
Truth table25%1/4
A and not(B) and C
A= defined $cellB= not ref $cellC= length $cell
ABCresult
0XX0
10X0
1100
1111
14280 } @loc_cols ]) : '';
14281 push @markers, {
14282 38 %{ $marker },
14283 'row_indexes' => \@at,
14284 'label' => _map_popup(
14285 38 $marker->{value}, [ @{$records}[@at] ], \@popup, $popup_rows, $more_url,
14286 ),
14287 };
14288 }
14289  
14290 } else {
14291 return { error => "Column not found: $lat_col", status => 400 }
14292 31 ▶ unless $col_set{$lat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$lat_col} 0 31 31
14293 return { error => "Column not found: $lon_col", status => 400 }
14294 31 ▶ unless $col_set{$lon_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$lon_col} 0 31 31
14295  
14296 31 my (%by_key, %rows_at, $out_of_lat, $out_of_lon, $unusable);
14297  
14298 31 for my $index (0 .. $#$records) {
14299 159 my $row = $records->[$index];
14300 159 ▶ my $lat = _numeric_cell($row->{$lat_col} // '');
Condition100%2/2
$row->{$lat_col} // ""
l!l
1572
MC/DC100%1/1
$row->{$lat_col} // ""
$row->{$lat_col}
Truth table100%2/2
A
A= $row->{$lat_col}
Aresult
11
00
14301 159 ▶ my $lon = _numeric_cell($row->{$lon_col} // '');
Condition100%2/2
$row->{$lon_col} // ""
l!l
1572
MC/DC100%1/1
$row->{$lon_col} // ""
$row->{$lon_col}
Truth table100%2/2
A
A= $row->{$lon_col}
Aresult
11
00
14302  
14303 # A row is never plotted at (0,0): a fake point in the Gulf of
14304 # Guinea is worse than a missing one. A whole column outside its
14305 # range is named instead, because a transposed pair is the error a
14306 # user makes here.
14307 159 ▶ if (defined($lat) && ($lat < -90 || $lat > 90)) { $out_of_lat++; next }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lat and $lat < -90 || $lat > 90) 4 155 159
Condition83%5/6
defined $lat and $lat < -90 || $lat > 90
!ll&&!rl&&r
221334
$lat < -90 or $lat > 90
l!l&&r!l&&!r
04133
MC/DC66%2/3
defined $lat and $lat < -90 || $lat > 90
defined $lat $lat < -90 $lat > 90
Truth table75%3/4
A and B or C
A= defined $latB= $lat < -90C= $lat > 90
ABCresult
0XX0
1000
11X1
1011
14308 155 ▶ if (defined($lon) && ($lon < -180 || $lon > 180)) { $out_of_lon++; next }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lon and $lon < -180 || $lon > 180) 8 147 155
Condition83%5/6
defined $lon and $lon < -180 || $lon > 180
!ll&&!rl&&r
221258
$lon < -180 or $lon > 180
l!l&&r!l&&!r
08125
MC/DC66%2/3
defined $lon and $lon < -180 || $lon > 180
defined $lon $lon < -180 $lon > 180
Truth table75%3/4
A and B or C
A= defined $lonB= $lon < -180C= $lon > 180
ABCresult
0XX0
1000
11X1
1011
14309 147 ▶ unless (defined($lat) && defined($lon)) { $unusable++; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $lat and defined $lon) 22 125 147
Condition66%2/3
defined $lat and defined $lon
!ll&&!rl&&r
220125
MC/DC50%1/2
defined $lat and defined $lon
defined $lat defined $lon
Truth table66%2/3
A and B
A= defined $latB= defined $lon
ABresult
0X0
100
111
14310  
14311 # Rows at one coordinate are one marker: that is what makes a large
14312 # file renderable, and "how many are here?" is the question a map
14313 # answers.
14314 125 my $key = sprintf('%.6f,%.6f', $lat, $lon);
14315 125 push @{ $rows_at{$key} }, $index;
14316 125 my $point = $by_key{$key};
14317 125 ▶ if ($point) { $point->{rows}++; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($point) 41 84 125
14318  
14319 84 $point = $by_key{$key} = {
14320 'lat' => $lat, 'lon' => $lon, 'rows' => 1, 'first_row' => $index,
14321 };
14322 84 push @markers, $point;
14323 }
14324  
14325 31 ▶ return { error => $self->_i18n('error_map_coordinate_range', $lat_col, 'latitude'),
Branch: 1 branch
BranchTrueFalseTotal
if not @markers and $out_of_lat 2 29 31
Condition100%3/3
not @markers and $out_of_lat
!ll&&!rl&&r
2542
MC/DC100%2/2
not @markers and $out_of_lat
not @markers $out_of_lat
Truth table100%3/3
not(A) and B
A= not @markersB= $out_of_lat
ABresult
0X0
100
111
14326 status => 400 } if !@markers && $out_of_lat;
14327 29 ▶ return { error => $self->_i18n('error_map_coordinate_range', $lon_col, 'longitude'),
Branch: 1 branch
BranchTrueFalseTotal
if not @markers and $out_of_lon 2 27 29
Condition100%3/3
not @markers and $out_of_lon
!ll&&!rl&&r
2522
MC/DC100%2/2
not @markers and $out_of_lon
not @markers $out_of_lon
Truth table100%3/3
not(A) and B
A= not @markersB= $out_of_lon
ABresult
0X0
100
111
14328 status => 400 } if !@markers && $out_of_lon;
14329 27 ▶ return { error => $self->_i18n('error_map_coordinate_numeric', $lat_col, $lon_col),
Branch: 1 branch
BranchTrueFalseTotal
if not @markers and @$records 2 25 27
Condition66%2/3
not @markers and @$records
!ll&&!rl&&r
2502
MC/DC50%1/2
not @markers and @$records
not @markers @$records
Truth table66%2/3
not(A) and B
A= not @markersB= @$records
ABresult
0X0
100
111
14330 status => 400 } if !@markers && @$records;
14331  
14332 25 $plotted_rows += $_->{rows} for @markers;
14333  
14334 25 ▶ push @messages, {
Branch: 1 branch
BranchTrueFalseTotal
if $plotted_rows < scalar @$records 14 11 25
14335 key => 'warn_map_coordinate_rows',
14336 text => $self->_i18n('warn_map_coordinate_rows', $plotted_rows,
14337 scalar(@$records), scalar(@$records) - $plotted_rows),
14338 } if $plotted_rows < scalar @$records;
14339  
14340 25 for my $marker (@markers) {
14341 84 my $key = sprintf('%.6f,%.6f', $marker->{lat}, $marker->{lon});
14342 84 $marker->{row_indexes} = $rows_at{$key};
14343 84 my $row = $records->[ $marker->{first_row} ];
14344 my $more_url = $rows_url ? $rows_url->([
14345 "$lat_col:eq:" . ($row->{$lat_col} // ''),
14346 84 ▶ "$lon_col:eq:" . ($row->{$lon_col} // ''),
Branch: 1 branch
BranchTrueFalseTotal
$rows_url ? : 84 0 84
Condition50%2/4
$row->{$lat_col} // ""
l!l
840
$row->{$lon_col} // ""
l!l
840
MC/DC0%0/1
$row->{$lat_col} // ""
$row->{$lat_col}
MC/DC0%0/1
$row->{$lon_col} // ""
$row->{$lon_col}
Truth table50%1/2
A
A= $row->{$lat_col}
Aresult
11
00
Truth table50%1/2
A
A= $row->{$lon_col}
Aresult
11
00
14347 ]) : '';
14348 $marker->{label} = _map_popup(
14349 sprintf('%.6f, %.6f', $marker->{lat}, $marker->{lon}),
14350 84 [ @{$records}[ @{ $rows_at{$key} } ] ], \@popup, $popup_rows, $more_url,
14351 );
14352 }
14353 }
14354  
14355 50 ▶ my $title = $by_location ? "Map of $loc_col" : "$lat_col and $lon_col";
Branch: 1 branch
BranchTrueFalseTotal
$by_location ? : 25 25 50
14356 my $cap = _map_limit($options->{max},
14357 50 _map_limit($cfg->{map_max_markers}, $DEFAULT_MAP_MAX_MARKERS));
14358  
14359 50 ▶ if (@markers > $cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (@markers > $cap) 1 49 50
14360 1 push @messages, {
14361 key => 'warn_map_markers_capped',
14362 text => $self->_i18n('warn_map_markers_capped', $cap, scalar @markers),
14363 };
14364 1 @markers = @markers[0 .. $cap - 1];
14365 }
14366  
14367 50 ▶ push @messages, {
Branch: 1 branch
BranchTrueFalseTotal
unless @markers 3 47 50
14368 key => 'error_map_no_markers',
14369 text => $self->_i18n('error_map_no_markers'),
14370 } unless @markers;
14371  
14372 # The outline of the area around each marker (bounds=county, or another
14373 # of Boundary's levels: bounds=state, bounds=city). Those
14374 # not known yet are looked up here, up to the online limit, unless the
14375 # caller said lookup => 0: the map page in a browser lists them for its
14376 # progress bar instead, as it does places.
14377 50 my $bounds_level = _map_bounds_level($options->{bounds});
14378 50 my ($outlines, @bounds_pending);
14379 50 my $bounds_coloured = 0; # set when the outlines are coloured by their totals
14380 50 my $bounds_as_markers = 0; # set when they take their markers' colours
14381 50 my $bounds_shade = ''; # the column they are filled by (shade=), when they are
14382 50 my $bounds_shade_as = ''; # 'one' colour, or the 'markers' colours
14383 50 my (@bounds_left_filters, $bounds_left_rows); # the rows whose marker has no outline
14384 50 my @bounds_groups; # why there are fewer outlines than markers (_map_outline_groups)
14385 50 ▶ if (defined($bounds_level) && @markers) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bounds_level and @markers) 11 39 50
Condition66%2/3
defined $bounds_level and @markers
!ll&&!rl&&r
39011
MC/DC50%1/2
defined $bounds_level and @markers
defined $bounds_level @markers
Truth table66%2/3
A and B
A= defined $bounds_levelB= @markers
ABresult
0X0
100
111
14386 11 ▶ my $lookup = (defined($options->{lookup}) && !$options->{lookup}) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $options->{'lookup'} && !$options->{'lookup'} ? : 0 11 11
Condition33%1/3
defined $options->{"lookup"} and not $options->{"lookup"}
!ll&&!rl&&r
1100
MC/DC0%0/2
defined $options->{"lookup"} and not $options->{"lookup"}
defined $options->{"lookup"} not $options->{"lookup"}
Truth table33%1/3
A and not(B)
A= defined $options->{"lookup"}B= not $options->{"lookup"}
ABresult
0X0
100
111
14387 $outlines = $self->_map_boundary($bounds_level, 1)->outlines(
14388 11 [ map { [ $_->{lat}, $_->{lon} ] } @markers ],
14389 lookup => $lookup,
14390 );
14391 11 @bounds_pending = @{ $outlines->{pending} };
14392 11 ▶ if (@bounds_pending) {
Branch: 1 branch
BranchTrueFalseTotal
if (@bounds_pending) 6 5 11
14393 # The rows behind the markers left without an outline, for a link
14394 # to them in the table, as the rows not plotted have.
14395 6 require Database::BI::Model::Boundary;
14396 6 my %left = map { $_ => 1 } @bounds_pending;
14397 26 ▶ my @rows = map { @{ $_->{row_indexes} // [ $_->{first_row} ] } } grep {
Condition50%1/2
$_->{"row_indexes"} // [$_->{"first_row"}]
l!l
260
MC/DC0%0/1
$_->{"row_indexes"} // [$_->{"first_row"}]
$_->{"row_indexes"}
Truth table50%1/2
A
A= $_->{"row_indexes"}
Aresult
11
00
14398 6 my $key = Database::BI::Model::Boundary->point_key($_->{lat}, $_->{lon});
14399 28 ▶ defined($key) && $left{$key};
Condition66%2/3
defined $key && $left{$key}
!ll&&!rl&&r
0226
MC/DC50%1/2
defined $key && $left{$key}
defined $key $left{$key}
Truth table66%2/3
A && B
A= defined $keyB= $left{$key}
ABresult
0X0
100
111
14400 } @markers;
14401 6 $bounds_left_rows = scalar @rows;
14402 6 ▶ @bounds_left_filters = _map_rows_filters($records, \@rows,
Branch: 1 branch
BranchTrueFalseTotal
$by_location ? : 0 6 6
14403 [ $by_location ? @loc_cols : ($lat_col, $lon_col) ]);
14404 my $key = $outlines->{offline} ? 'warn_map_bounds_offline'
14405 6 ▶ : $outlines->{failed} ? 'warn_map_bounds_failed'
Branch: 2 branches
BranchTrueFalseTotal
$outlines->{'offline'} ? : 2 4 6
$outlines->{'failed'} ? : 2 2 4
14406 : 'warn_map_bounds_pending';
14407 push @messages, {
14408 key => $key,
14409 # One place "has" no outline; the key stays the plural's
14410 text => $self->_i18n($key . (@bounds_pending == 1 ? '_one' : ''),
14411 scalar(@bounds_pending), $outlines->{counts}{points},
14412 6 ▶ $self->_map_outline_noun($outlines, $bounds_level)),
Branch: 1 branch
BranchTrueFalseTotal
@bounds_pending == 1 ? : 3 3 6
14413 };
14414 }
14415 11 ▶ @bounds_groups = _map_outline_groups($outlines, \@markers, $records,
Branch: 1 branch
BranchTrueFalseTotal
$by_location ? : 0 11 11
14416 [ $by_location ? @loc_cols : ($lat_col, $lon_col) ]);
14417 }
14418  
14419 # Leaflet's CSS and JS belong in the head, which the layout owns; the rest of
14420 # the map - the search box, the buttons, the div and its script - goes in the
14421 # body where the map should appear.
14422 50 my ($map_head, $map_body);
14423 50 ▶ if (@markers) {
Branch: 1 branch
BranchTrueFalseTotal
if (@markers) 47 3 50
14424 # HTML::OSM is a recommended dependency, so its absence - or an install
14425 # older than the options below - is a state the page reports and
14426 # survives: the markers are still counted, nothing is drawn, and the
14427 # rest of the application is untouched. The version check is not
14428 # optional: HTML::OSM rejects unknown constructor keys, so passing
14429 # search/max_zoom to an older copy would croak and turn the page into a
14430 # 500 rather than the warning this branch produces.
14431 #
14432 # The installed version comes back with the answer so the warning can
14433 # say which problem it is: "not installed" and "installed but older than
14434 # 0.12" have different fixes, and the old wording called both of them
14435 # "could not be loaded". The probe is a method (see
14436 # _map_renderer_version) so the tests can produce either state without
14437 # installing or removing the module.
14438 47 my ($osm_ok, $osm_version) = $self->_map_renderer_version;
14439 47 ▶ if ($osm_ok) {
Branch: 2 branches
BranchTrueFalseTotal
if ($osm_ok) { } 43 4 47
elsif (defined $osm_version) { } 2 2 4
14440 # Markers go in a cluster group rather than straight onto the map.
14441 # A card may plot up to map_max_markers (2000 by default), and at a
14442 # low zoom that many pins overlap into noise; markercluster draws a
14443 # count instead and splits it as the reader zooms in. A sparse map
14444 # looks the same - the plugin leaves markers that are far apart on
14445 # their own - but the plugin is only fetched once the map itself is.
14446 # The Leaflet assets are a config seam too. A deployment with no
14447 # outbound network access serves them from its own origin; any key
14448 # the operator leaves out keeps HTML::OSM's pinned CDN URL. The tile
14449 # layer has its own key, since a local tile server removes the last
14450 # outbound request the page makes.
14451 43 my %leaflet_assets;
14452 43 for my $asset (
14453 [ 'leaflet_js_url', 'js_url' ],
14454 [ 'leaflet_css_url', 'css_url' ],
14455 [ 'leaflet_cluster_js_url', 'cluster_js_url' ],
14456 [ 'leaflet_cluster_css_url', 'cluster_css_url' ],
14457 [ 'leaflet_cluster_default_css_url', 'cluster_default_css_url' ],
14458 ) {
14459 215 my ($key, $param) = @$asset;
14460 215 my $url = $cfg->{$key};
14461 215 ▶ $leaflet_assets{$param} = $url
Branch: 1 branch
BranchTrueFalseTotal
if defined $url and not ref $url and length $url 0 215 215
Condition33%2/6
defined $url and not ref $url and length $url
!ll&&!rl&&r
21500
defined $url and not ref $url
!ll&&!rl&&r
21500
MC/DC0%0/3
defined $url and not ref $url and length $url
defined $url not ref $url length $url
Truth table25%1/4
A and not(B) and C
A= defined $urlB= not ref $urlC= length $url
ABCresult
0XX0
10X0
1100
1111
14462 if defined $url && !ref $url && length $url;
14463 }
14464  
14465 43 my $tile_url = $cfg->{tile_url};
14466 43 ▶ $tile_url = undef
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tile_url and not ref $tile_url and length $tile_url 43 0 43
Condition33%2/6
defined $tile_url and not ref $tile_url and length $tile_url
!ll&&!rl&&r
4300
defined $tile_url and not ref $tile_url
!ll&&!rl&&r
4300
MC/DC0%0/3
defined $tile_url and not ref $tile_url and length $tile_url
defined $tile_url not ref $tile_url length $tile_url
Truth table25%1/4
A and not(B) and C
A= defined $tile_urlB= not ref $tile_urlC= length $tile_url
ABCresult
0XX0
10X0
1100
1111
14467 unless defined($tile_url) && !ref($tile_url) && length($tile_url);
14468  
14469 # options{tile_url} wins over the global config tile_url when set.
14470 # HTML::OSM >= 0.12 is the minimum, so tile_url is always accepted.
14471 43 ▶ my $eff_tile_url = $options->{tile_url} // $tile_url;
Condition33%1/3
$options->{"tile_url"} // $tile_url
l!l&&r!l&&!r
0043
MC/DC0%0/2
$options->{"tile_url"} // $tile_url
$options->{"tile_url"} $tile_url
Truth table33%1/3
A // B
A= $options->{"tile_url"}B= $tile_url
ABresult
1X1
011
000
14472 43 ▶ $eff_tile_url = undef
Branch: 1 branch
BranchTrueFalseTotal
unless defined $eff_tile_url and not ref $eff_tile_url and length $eff_tile_url 43 0 43
Condition33%2/6
defined $eff_tile_url and not ref $eff_tile_url and length $eff_tile_url
!ll&&!rl&&r
4300
defined $eff_tile_url and not ref $eff_tile_url
!ll&&!rl&&r
4300
MC/DC0%0/3
defined $eff_tile_url and not ref $eff_tile_url and length $eff_tile_url
defined $eff_tile_url not ref $eff_tile_url length $eff_tile_url
Truth table25%1/4
A and not(B) and C
A= defined $eff_tile_urlB= not ref $eff_tile_urlC= length $eff_tile_url
ABCresult
0XX0
10X0
1100
1111
14473 unless defined($eff_tile_url) && !ref($eff_tile_url) && length($eff_tile_url);
14474  
14475 my %osm_args = (
14476 height => '560px',
14477 width => '100%',
14478 cluster => 1,
14479 search => 0,
14480 ($eff_tile_url ? (tile_url => $eff_tile_url) : ()),
14481 (defined($options->{zoom}) ? (zoom => $options->{zoom}) : ()),
14482 43 ▶ (defined($options->{max_zoom}) ? (max_zoom => $options->{max_zoom}) : ()),
Branch: 3 branches
BranchTrueFalseTotal
$eff_tile_url ? : 0 43 43
defined $options->{'zoom'} ? : 0 43 43
defined $options->{'max_zoom'} ? : 0 43 43
14483 %leaflet_assets,
14484 );
14485 # The renderer is a third-party module: whatever it does, the page
14486 # reports it and survives, as it does when the module is absent.
14487 # The map page passes the colour and size columns as options; a
14488 # canvas card has them in its encode, as the page saved them. A
14489 # card's are stored unchecked, so one that names no column is
14490 # left out rather than refused.
14491 43 ▶ my $color_col = $options->{color_col} // $encode->{color} // '';
Condition80%4/5
($options->{"color_col"} // $encode->{"color"}) // ""
l!l
142
$options->{"color_col"} // $encode->{"color"}
l!l&&r!l&&!r
1042
MC/DC50%1/2
($options->{"color_col"} // $encode->{"color"}) // ""
$options->{"color_col"} $encode->{"color"}
Truth table66%2/3
A // B
A= $options->{"color_col"}B= $encode->{"color"}
ABresult
1X1
011
000
14492 43 ▶ $color_col = '' if ref($color_col) || !$col_set{$color_col};
Branch: 1 branch
BranchTrueFalseTotal
if ref $color_col or not $col_set{$color_col} 42 1 43
Condition66%2/3
ref $color_col or not $col_set{$color_col}
l!l&&r!l&&!r
0421
MC/DC50%1/2
ref $color_col or not $col_set{$color_col}
ref $color_col not $col_set{$color_col}
Truth table66%2/3
A or not(B)
A= ref $color_colB= not $col_set{$color_col}
ABresult
1X1
011
000
14493 # A card's rules are stored unchecked: one that is not a rule is
14494 # left out rather than read as one.
14495 5 my $color_rules = [ grep { ref($_) eq 'HASH' }
14496 43 ▶ @{ ref($options->{color_rules}) eq 'ARRAY' ? $options->{color_rules} : [] } ];
Branch: 1 branch
BranchTrueFalseTotal
ref $options->{'color_rules'} eq 'ARRAY' ? : 2 41 43
14497 43 ▶ my $color_default = $options->{color_default} // $DEFAULT_MARKER_COLOR;
Condition66%2/3
$options->{"color_default"} // $DEFAULT_MARKER_COLOR
l!l&&r!l&&!r
4030
MC/DC0%0/2
$options->{"color_default"} // $DEFAULT_MARKER_COLOR
$options->{"color_default"} $DEFAULT_MARKER_COLOR
Truth table66%2/3
A // B
A= $options->{"color_default"}B= $DEFAULT_MARKER_COLOR
ABresult
1X1
011
000
14498 43 ▶ my $size_col = $options->{size} // $encode->{size} // '';
Condition40%2/5
($options->{"size"} // $encode->{"size"}) // ""
l!l
043
$options->{"size"} // $encode->{"size"}
l!l&&r!l&&!r
0043
MC/DC0%0/2
($options->{"size"} // $encode->{"size"}) // ""
$options->{"size"} $encode->{"size"}
Truth table33%1/3
A // B
A= $options->{"size"}B= $encode->{"size"}
ABresult
1X1
011
000
14499 43 ▶ $size_col = '' if ref($size_col) || !$col_set{$size_col};
Branch: 1 branch
BranchTrueFalseTotal
if ref $size_col or not $col_set{$size_col} 43 0 43
Condition33%1/3
ref $size_col or not $col_set{$size_col}
l!l&&r!l&&!r
0430
MC/DC0%0/2
ref $size_col or not $col_set{$size_col}
ref $size_col not $col_set{$size_col}
Truth table33%1/3
A or not(B)
A= ref $size_colB= not $col_set{$size_col}
ABresult
1X1
011
000
14500  
14501 # The scale bar, and the key on the map: colours and bubble sizes.
14502 43 my $size_range = [ _map_size_range($records, \@markers, $size_col) ];
14503 # When the outlines are shaded in the markers' colours by the column
14504 # the colours read, the shade key lists every colour with its totals,
14505 # so a second key of the same colours would only repeat it. Shaded by
14506 # another column, or in one colour, the marker key is still the only
14507 # place the colours are explained. Bubble sizes are listed either way.
14508 0 ▶ my $shade_covers = length($color_col) && $outlines && @{ $outlines->{features} }
Condition0%0/4
$options->{"shade"} // ""
l!l
00
$options->{"shade"} // ""
l!l
00
MC/DC0%0/1
$options->{"shade"} // ""
$options->{"shade"}
MC/DC0%0/1
$options->{"shade"} // ""
$options->{"shade"}
Truth table0%0/2
A
A= $options->{"shade"}
Aresult
11
00
Truth table0%0/2
A
A= $options->{"shade"}
Aresult
11
00
14509 && !ref($options->{shade} // '') && ($options->{shade} // '') eq $color_col
14510 43 ▶ && !defined($options->{shade_color});
Condition40%6/15
length $color_col && $outlines && @{$outlines->{'features'};} && !ref($options->{'shade'} // '') && ($options->{'shade'} // '') eq $color_col && !defined($options->{'shade_color'})
!ll&&!rl&&r
4300
length $color_col and $outlines and @{$outlines->{"features"};} and not ref($options->{"shade"} // "") and ($options->{"shade"} // "") eq $color_col
!ll&&!rl&&r
4300
length $color_col and $outlines and @{$outlines->{"features"};} and not ref($options->{"shade"} // "")
!ll&&!rl&&r
4300
length $color_col and $outlines and @{$outlines->{"features"};}
!ll&&!rl&&r
4300
length $color_col and $outlines
!ll&&!rl&&r
4210
MC/DC0%0/6
length $color_col && $outlines && @{$outlines->{'features'};} && !ref($options->{'shade'} // '') && ($options->{'shade'} // '') eq $color_col && !defined($options->{'shade_color'})
length $color_col $outlines @{$outlines->{"features"};} not ref($options->{"shade"} // "") ($options->{"shade"} // "") eq $color_col !defined($options->{'shade_color'})
Truth table28%2/7
A and B and C and not(D) and E && not(F)
A= length $color_colB= $outlinesC= @{$outlines->{"features"};}D= not ref($options->{"shade"} // "")E= ($options->{"shade"} // "") eq $color_colF= !defined($options->{'shade_color'})
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
14511 # HTML::OSM 0.19 can leave a key entry out while a layer is shown and
14512 # bring it back when the reader hides the layer, so the markers are
14513 # never left without a key; an older copy cannot, and gets no colour
14514 # entries at all.
14515 my $key_waits = $shade_covers
14516 0 ▶ && eval { version->parse($osm_version) >= version->parse($OSM_KEY_WAITS_VERSION) };
Condition33%1/3
$shade_covers && eval { do { 'version'->parse($osm_version) >= 'version'->parse($OSM_KEY_WAITS_VERSION) } }
!ll&&!rl&&r
4300
MC/DC0%0/2
$shade_covers && eval { do { 'version'->parse($osm_version) >= 'version'->parse($OSM_KEY_WAITS_VERSION) } }
$shade_covers eval { do { 'version'->parse($osm_version) >= 'version'->parse($OSM_KEY_WAITS_VERSION) } }
Truth table33%1/3
A && B
A= $shade_coversB= eval { do { 'version'->parse($osm_version) >= 'version'->parse($OSM_KEY_WAITS_VERSION) } }
ABresult
0X0
100
111
14517 my %key = $self->_map_key((($shade_covers && !$key_waits) ? '' : $color_col), $color_rules,
14518 43 ▶ $color_default, defined($options->{scheme}), $size_col, $size_range);
Branch: 1 branch
BranchTrueFalseTotal
$shade_covers && !$key_waits ? : 0 43 43
Condition33%1/3
$shade_covers and not $key_waits
!ll&&!rl&&r
4300
MC/DC0%0/2
$shade_covers and not $key_waits
$shade_covers not $key_waits
Truth table33%1/3
A and not(B)
A= $shade_coversB= not $key_waits
ABresult
0X0
100
111
14519 43 ▶ if ($key_waits) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key_waits) 0 43 43
14520 0 my $layer = $self->_i18n('map_bounds_layer', ucfirst $self->_map_outline_noun($outlines, $bounds_level));
14521 0 ▶ $_->{unless_layer} = $layer for grep { defined $_->{group} } @{ $key{legend} // [] };
Condition0%0/2
$key{"legend"} // []
l!l
00
MC/DC0%0/1
$key{"legend"} // []
$key{"legend"}
Truth table0%0/2
A
A= $key{"legend"}
Aresult
11
00
14522 }
14523 43 $osm_args{scale} = 1;
14524 # Every <script> the map writes carries the page's nonce.
14525 43 $osm_args{nonce} = $self->csp_nonce;
14526 # Without a zoom the map opens on every marker, as the panel promises
14527 43 ▶ $osm_args{fit} = 1 unless defined $options->{zoom};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"zoom"} 43 0 43
14528 43 ▶ %osm_args = (%osm_args, %key) if @{ $key{legend} // [] };
Branch: 1 branch
BranchTrueFalseTotal
if @{$key{"legend"} // [];} 1 42 43
Condition100%2/2
$key{"legend"} // []
l!l
142
MC/DC100%1/1
$key{"legend"} // []
$key{"legend"}
Truth table100%2/2
A
A= $key{"legend"}
Aresult
11
00
14529  
14530 43 my $drawn = eval {
14531 43 my $map = HTML::OSM->new(%osm_args);
14532  
14533 # Bubble maps: one radius per marker, scaled across the plotted
14534 # values. Circle markers keep their pixel size as the reader
14535 # zooms, which is what makes them comparable.
14536 41 my ($size_min, $size_max) = @{$size_range};
14537  
14538 41 for my $marker (@markers) {
14539 110 my $row = $records->[ $marker->{first_row} ];
14540 110 my ($color, $group);
14541 110 ▶ if (length $color_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $color_col) 2 108 110
14542 2 ▶ my $cval = (defined($row) ? $row->{$color_col} : undef) // '';
Branch: 1 branch
BranchTrueFalseTotal
defined $row ? : 2 0 2
Condition50%1/2
(defined $row ? $row->{$color_col} : undef) // ""
l!l
20
MC/DC0%0/1
(defined $row ? $row->{$color_col} : undef) // ""
(defined $row ? $row->{$color_col} : undef)
Truth table50%1/2
A
A= (defined $row ? $row->{$color_col} : undef)
Aresult
11
00
14543 2 $color = _apply_color_rule($cval, $color_rules, $color_default);
14544 # Which key entry the marker belongs to, so the key lists
14545 # only what is in view
14546 2 my $index = _color_rule_index($cval, $color_rules);
14547 2 ▶ $group = defined($index) ? "rule$index" : 'other';
Branch: 1 branch
BranchTrueFalseTotal
defined $index ? : 2 0 2
14548 # Kept for the outline round it, which is drawn to match
14549 2 $marker->{colour} = _color_hex($color);
14550 }
14551 110 ▶ if (length $size_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $size_col) { } 0 110 110
14552 my $sv = defined($row)
14553 0 ▶ ? _numeric_cell($row->{$size_col} // '') : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $row ? : 0 0 0
Condition0%0/2
$row->{$size_col} // ""
l!l
00
MC/DC0%0/1
$row->{$size_col} // ""
$row->{$size_col}
Truth table0%0/2
A
A= $row->{$size_col}
Aresult
11
00
14554 $map->add_circle_marker(
14555 [ $marker->{lat}, $marker->{lon} ],
14556 html => $marker->{label},
14557 0 ▶ radius => _map_radius($sv, $size_min, $size_max),
Branch: 2 branches
BranchTrueFalseTotal
defined $color ? : 0 0 0
defined $group ? : 0 0 0
14558 (defined($color) ? (colour => _color_hex($color)) : ()),
14559 (defined($group) ? (group => $group) : ()),
14560 );
14561 } else {
14562 $map->add_marker(
14563 [ $marker->{lat}, $marker->{lon} ],
14564 html => $marker->{label},
14565 110 ▶ (defined($color) ? (icon => _marker_icon($color)) : ()),
Branch: 2 branches
BranchTrueFalseTotal
defined $color ? : 2 108 110
defined $group ? : 2 108 110
14566 (defined($group) ? (group => $group) : ()),
14567 );
14568 }
14569 }
14570  
14571 # Heat map overlay: when heat=1 is requested, plot a density
14572 # heatmap in addition to the regular markers. The weight column
14573 # (weight=<col>) drives the intensity of each point; absent the
14574 # column every point has equal weight 1.0. Normalisation to [0,1]
14575 # ensures the heatmap library gets values in the expected range.
14576 41 ▶ if ($options->{heat}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"heat"}) 4 37 41
14577 4 ▶ my $weight_col = $options->{weight} // '';
Condition100%2/2
$options->{"weight"} // ""
l!l
22
MC/DC100%1/1
$options->{"weight"} // ""
$options->{"weight"}
Truth table100%2/2
A
A= $options->{"weight"}
Aresult
11
00
14578 4 my @heat_pts;
14579 4 for my $marker (@markers) {
14580 26 my $row = $records->[ $marker->{first_row} ];
14581 26 my $w;
14582 26 ▶ if (length $weight_col && defined $row) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $weight_col and defined $row) 22 4 26
Condition66%2/3
length $weight_col and defined $row
!ll&&!rl&&r
4022
MC/DC50%1/2
length $weight_col and defined $row
length $weight_col defined $row
Truth table66%2/3
A and B
A= length $weight_colB= defined $row
ABresult
0X0
100
111
14583 22 ▶ $w = _numeric_cell($row->{$weight_col} // '');
Condition50%1/2
$row->{$weight_col} // ""
l!l
220
MC/DC0%0/1
$row->{$weight_col} // ""
$row->{$weight_col}
Truth table50%1/2
A
A= $row->{$weight_col}
Aresult
11
00
14584 }
14585 push @heat_pts, [ $marker->{lat}, $marker->{lon},
14586 26 ▶ (defined($w) ? $w : 1) ];
Branch: 1 branch
BranchTrueFalseTotal
defined $w ? : 22 4 26
14587 }
14588 # Normalise weights to [0,1] when a weight column was used.
14589 4 ▶ if (length $weight_col && @heat_pts) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $weight_col and @heat_pts) 2 2 4
Condition66%2/3
length $weight_col and @heat_pts
!ll&&!rl&&r
202
MC/DC50%1/2
length $weight_col and @heat_pts
length $weight_col @heat_pts
Truth table66%2/3
A and B
A= length $weight_colB= @heat_pts
ABresult
0X0
100
111
14590 2 my $max_w = 0;
14591 2 ▶ $max_w = $_->[2] > $max_w ? $_->[2] : $max_w for @heat_pts;
Branch: 1 branch
BranchTrueFalseTotal
$_->[2] > $max_w ? : 22 0 22
14592 2 ▶ if ($max_w > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max_w > 0) 2 0 2
14593 2 $_->[2] = $_->[2] / $max_w for @heat_pts;
14594 }
14595 }
14596 4 eval { $map->add_heatmap(\@heat_pts) };
14597 }
14598  
14599 # The county outlines, under the markers, with a checkbox on
14600 # the map to hide them (HTML::OSM 0.15; an older copy ignores
14601 # name and draws them always). Grey, or with heat=1 coloured
14602 # by what the heat layer weighs in each, one layer a colour
14603 # under one name, so one checkbox still hides them all.
14604 # When the markers are coloured, each outline takes the colours
14605 # of the markers in it, so the two never disagree; the heat
14606 # layer's own scale is for a map whose markers are all alike.
14607 41 my $noun = $self->_map_outline_noun($outlines, $bounds_level);
14608 41 ▶ my @outline_layers = length($color_col)
Branch: 1 branch
BranchTrueFalseTotal
length $color_col ? : 1 40 41
14609 ? $self->_map_outline_marker_layers($outlines, \@markers) : ();
14610 41 ▶ $bounds_as_markers = 1 if @outline_layers;
Branch: 1 branch
BranchTrueFalseTotal
if @outline_layers 0 41 41
14611 # Colour shade fills each outline by a column's total. It says
14612 # what the heat layer's line colours would, so those stay grey.
14613 41 ▶ my $shade_col = $options->{shade} // '';
Condition50%1/2
$options->{"shade"} // ""
l!l
041
MC/DC0%0/1
$options->{"shade"} // ""
$options->{"shade"}
Truth table50%1/2
A
A= $options->{"shade"}
Aresult
11
00
14614 41 ▶ $shade_col = '' if ref($shade_col) || !$col_set{$shade_col};
Branch: 1 branch
BranchTrueFalseTotal
if ref $shade_col or not $col_set{$shade_col} 41 0 41
Condition33%1/3
ref $shade_col or not $col_set{$shade_col}
l!l&&r!l&&!r
0410
MC/DC0%0/2
ref $shade_col or not $col_set{$shade_col}
ref $shade_col not $col_set{$shade_col}
Truth table33%1/3
A or not(B)
A= ref $shade_colB= not $col_set{$shade_col}
ABresult
1X1
011
000
14615 @outline_layers = $self->_map_outline_layers($outlines, \@markers, $records,
14616 41 ▶ (($options->{heat} && !length($shade_col)) ? ($options->{weight} // '') : undef), $noun)
Branch: 2 branches
BranchTrueFalseTotal
unless @outline_layers 41 0 41
$options->{'heat'} && !length($shade_col) ? : 4 37 41
Condition80%4/5
$options->{"heat"} and not length $shade_col
!ll&&!rl&&r
3704
$options->{"weight"} // ""
l!l
22
MC/DC50%1/2
$options->{"heat"} and not length $shade_col
$options->{"heat"} not length $shade_col
MC/DC100%1/1
$options->{"weight"} // ""
$options->{"weight"}
Truth table66%2/3
A and not(B)
A= $options->{"heat"}B= not length $shade_col
ABresult
0X0
100
111
Truth table100%2/2
A
A= $options->{"weight"}
Aresult
11
00
14617 unless @outline_layers;
14618 41 ▶ if (length $shade_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $shade_col) 0 41 41
14619 # Coloured markers and no colour asked for: each outline is
14620 # shaded in its markers' colour. When the shade is of the
14621 # column the rules read, a "less than" rule's colour is the
14622 # stronger the smaller the total.
14623 0 my $lower;
14624 0 ▶ if ($bounds_as_markers && !defined($options->{shade_color})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bounds_as_markers and not defined $options->{"shade_color"}) 0 0 0
Condition0%0/3
$bounds_as_markers and not defined $options->{"shade_color"}
!ll&&!rl&&r
000
MC/DC0%0/2
$bounds_as_markers and not defined $options->{"shade_color"}
$bounds_as_markers not defined $options->{"shade_color"}
Truth table0%0/3
A and not(B)
A= $bounds_as_markersB= not defined $options->{"shade_color"}
ABresult
0X0
100
111
14625 0 $lower = {};
14626 0 ▶ for my $rule ($shade_col eq $color_col ? @{$color_rules} : ()) {
Branch: 1 branch
BranchTrueFalseTotal
$shade_col eq $color_col ? : 0 0 0
14627 0 my $hue = _color_hex($rule->{color});
14628 0 $hue =~ s/\A#(.)(.)(.)\z/#$1$1$2$2$3$3/;
14629 0 ▶ $lower->{ lc $hue } //= (($rule->{op} // '') =~ /\Al[te]\z/) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
($rule->{'op'} // '') =~ /\Al[te]\z/u ? : 0 0 0
Condition0%0/4
$$lower{lc $hue} //= ($rule->{"op"} // "") =~ /\Al[te]\z/u ? 1 : 0
l!l
00
$rule->{"op"} // ""
l!l
00
MC/DC0%0/1
$$lower{lc $hue} //= ($rule->{"op"} // "") =~ /\Al[te]\z/u ? 1 : 0
$$lower{lc $hue}
Truth table0%0/2
A
A= $$lower{lc $hue}
Aresult
11
00
14630 }
14631 }
14632 my @shaded = $self->_map_outline_shade(\@outline_layers, $outlines, \@markers,
14633 0 $records, $shade_col, $options->{shade_color}, $noun, $lower);
14634 0 ▶ if (@shaded) {
Branch: 1 branch
BranchTrueFalseTotal
if (@shaded) 0 0 0
14635 0 @outline_layers = @shaded;
14636 0 $bounds_shade = $shade_col;
14637 0 ▶ $bounds_shade_as = $lower ? 'markers' : 'one';
Branch: 1 branch
BranchTrueFalseTotal
$lower ? : 0 0 0
14638 }
14639 }
14640 41 for my $layer (@outline_layers) {
14641 # Only a layer with a key was coloured to mean something;
14642 # a shaded map's key is for its fills.
14643 15 ▶ $bounds_coloured = 1 if $layer->{key} && !length($bounds_shade);
Branch: 1 branch
BranchTrueFalseTotal
if $layer->{"key"} and not length $bounds_shade 3 12 15
Condition66%2/3
$layer->{"key"} and not length $bounds_shade
!ll&&!rl&&r
1203
MC/DC50%1/2
$layer->{"key"} and not length $bounds_shade
$layer->{"key"} not length $bounds_shade
Truth table66%2/3
A and not(B)
A= $layer->{"key"}B= not length $bounds_shade
ABresult
0X0
100
111
14644 $map->add_geojson(
14645 { type => 'FeatureCollection', features => $layer->{features} },
14646 style => { color => $layer->{colour}, weight => $layer->{weight},
14647 opacity => $layer->{opacity},
14648 ($layer->{fill}
14649 ? (fill => \1, fillColor => $layer->{fill}, fillOpacity => $SHADE_OPACITY)
14650 : (fill => \0)) },
14651 popup => 'name',
14652 name => $self->_i18n('map_bounds_layer', ucfirst $noun),
14653 ($layer->{key} ? (key => $layer->{key}) : ()),
14654 # HTML::OSM 0.17 draws each colour as a line of its own,
14655 # inside the outline's edge; an older copy ignores this
14656 # and draws the first alone, along the edge.
14657 15 ▶ ($layer->{bands} ? (bands => 'colours') : ()),
Branch: 3 branches
BranchTrueFalseTotal
$layer->{'fill'} ? : 0 15 15
$layer->{'key'} ? : 3 12 15
$layer->{'bands'} ? : 12 3 15
14658 );
14659 }
14660  
14661 41 ($map_head, $map_body) = $map->onload_render();
14662 41 ▶ ($map_head, $map_body) = _canvas_map_html($map_head, $map_body, $id_suffix)
Branch: 1 branch
BranchTrueFalseTotal
if defined $id_suffix and length $id_suffix 3 38 41
Condition66%2/3
defined $id_suffix and length $id_suffix
!ll&&!rl&&r
3803
MC/DC50%1/2
defined $id_suffix and length $id_suffix
defined $id_suffix length $id_suffix
Truth table66%2/3
A and B
A= defined $id_suffixB= length $id_suffix
ABresult
0X0
100
111
14663 if defined($id_suffix) && length($id_suffix);
14664 41 1;
14665 };
14666 43 ▶ unless ($drawn) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($drawn) 2 41 43
14667 2 $self->app->log->error('The map could not be drawn: ' . _tidy_error($@));
14668 2 ($map_head, $map_body) = ();
14669 2 push @messages, {
14670 key => 'error_map_renderer_failed',
14671 text => $self->_i18n('error_map_renderer_failed'),
14672 };
14673 }
14674 } elsif (defined $osm_version) {
14675 2 push @messages, {
14676 key => 'error_map_renderer_old',
14677 text => $self->_i18n('error_map_renderer_old', $osm_version),
14678 };
14679 } else {
14680 2 push @messages, {
14681 key => 'error_map_renderer_missing',
14682 text => $self->_i18n('error_map_renderer_missing'),
14683 };
14684 }
14685 }
14686  
14687 50 ▶ my %chart_spec = (
Branch: 3 branches
BranchTrueFalseTotal
$by_location ? : 25 25 50
@loc_cols == 1 ? : 25 0 25
length $loc_text ? : 0 25 25
14688 kind => 'map',
14689 title => $title,
14690 encode => ($by_location
14691 ? { loc => (@loc_cols == 1 ? $loc_cols[0] : [ @loc_cols ]),
14692 (length($loc_text) ? (loc_text => $loc_text) : ()) }
14693 : { lat => $lat_col, lon => $lon_col }),
14694 );
14695 50 ▶ $chart_spec{options}{popup} = \@popup if @popup;
Branch: 1 branch
BranchTrueFalseTotal
if @popup 50 0 50
14696 $chart_spec{options}{max} = $options->{max}
14697 50 ▶ if defined($options->{max}) && $options->{max} =~ /\A\d+\z/ && $options->{max} > 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"max"} and $options->{"max"} =~ /\A\d+\z/u and $options->{"max"} > 0 1 49 50
Condition66%4/6
defined $options->{"max"} and $options->{"max"} =~ /\A\d+\z/u and $options->{"max"} > 0
!ll&&!rl&&r
4901
defined $options->{"max"} and $options->{"max"} =~ /\A\d+\z/u
!ll&&!rl&&r
4901
MC/DC33%1/3
defined $options->{"max"} and $options->{"max"} =~ /\A\d+\z/u and $options->{"max"} > 0
defined $options->{"max"} $options->{"max"} =~ /\A\d+\z/u $options->{"max"} > 0
Truth table50%2/4
A and B and C
A= defined $options->{"max"}B= $options->{"max"} =~ /\A\d+\z/uC= $options->{"max"} > 0
ABCresult
0XX0
10X0
1100
1111
14698 50 ▶ $chart_spec{options}{zoom} = $options->{zoom} if defined $options->{zoom};
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"zoom"} 0 50 50
14699 50 ▶ $chart_spec{options}{heat} = 1 if $options->{heat};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"heat"} 4 46 50
14700 50 ▶ $chart_spec{options}{bounds} = $bounds_level if defined $bounds_level;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bounds_level 11 39 50
14701 $chart_spec{options}{shade} = $options->{shade}
14702 50 ▶ if defined($options->{shade}) && !ref($options->{shade}) && length($options->{shade});
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"shade"} and not ref $options->{"shade"} and length $options->{"shade"} 0 50 50
Condition33%2/6
defined $options->{"shade"} and not ref $options->{"shade"} and length $options->{"shade"}
!ll&&!rl&&r
5000
defined $options->{"shade"} and not ref $options->{"shade"}
!ll&&!rl&&r
5000
MC/DC0%0/3
defined $options->{"shade"} and not ref $options->{"shade"} and length $options->{"shade"}
defined $options->{"shade"} not ref $options->{"shade"} length $options->{"shade"}
Truth table25%1/4
A and not(B) and C
A= defined $options->{"shade"}B= not ref $options->{"shade"}C= length $options->{"shade"}
ABCresult
0XX0
10X0
1100
1111
14703 $chart_spec{options}{shade_color} = $options->{shade_color}
14704 50 ▶ if defined($chart_spec{options}{shade}) && defined($options->{shade_color}) && !ref($options->{shade_color});
Branch: 1 branch
BranchTrueFalseTotal
if defined $chart_spec{"options"}{"shade"} and defined $options->{"shade_color"} and not ref $options->{"shade_color"} 0 50 50
Condition33%2/6
defined $chart_spec{"options"}{"shade"} and defined $options->{"shade_color"} and not ref $options->{"shade_color"}
!ll&&!rl&&r
5000
defined $chart_spec{"options"}{"shade"} and defined $options->{"shade_color"}
!ll&&!rl&&r
5000
MC/DC0%0/3
defined $chart_spec{"options"}{"shade"} and defined $options->{"shade_color"} and not ref $options->{"shade_color"}
defined $chart_spec{"options"}{"shade"} defined $options->{"shade_color"} not ref $options->{"shade_color"}
Truth table25%1/4
A and B and not(C)
A= defined $chart_spec{"options"}{"shade"}B= defined $options->{"shade_color"}C= not ref $options->{"shade_color"}
ABCresult
0XX0
10X0
1100
1111
14705 $chart_spec{options}{weight} = $options->{weight}
14706 50 ▶ if defined($options->{weight}) && length($options->{weight});
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"weight"} and length $options->{"weight"} 2 48 50
Condition66%2/3
defined $options->{"weight"} and length $options->{"weight"}
!ll&&!rl&&r
4802
MC/DC50%1/2
defined $options->{"weight"} and length $options->{"weight"}
defined $options->{"weight"} length $options->{"weight"}
Truth table66%2/3
A and B
A= defined $options->{"weight"}B= length $options->{"weight"}
ABresult
0X0
100
111
14707 50 ▶ if (defined($options->{size}) && length($options->{size})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"size"} and length $options->{"size"}) 0 50 50
Condition33%1/3
defined $options->{"size"} and length $options->{"size"}
!ll&&!rl&&r
5000
MC/DC0%0/2
defined $options->{"size"} and length $options->{"size"}
defined $options->{"size"} length $options->{"size"}
Truth table33%1/3
A and B
A= defined $options->{"size"}B= length $options->{"size"}
ABresult
0X0
100
111
14708 0 $chart_spec{encode}{size} = $options->{size};
14709 }
14710 50 ▶ if (defined($options->{scheme}) && length($options->{scheme})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"scheme"} and length $options->{"scheme"}) 1 49 50
Condition66%2/3
defined $options->{"scheme"} and length $options->{"scheme"}
!ll&&!rl&&r
4901
MC/DC50%1/2
defined $options->{"scheme"} and length $options->{"scheme"}
defined $options->{"scheme"} length $options->{"scheme"}
Truth table66%2/3
A and B
A= defined $options->{"scheme"}B= length $options->{"scheme"}
ABresult
0X0
100
111
14711 1 $chart_spec{options}{scheme} = $options->{scheme};
14712 }
14713 50 ▶ if (defined($options->{color_col}) && length($options->{color_col})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"color_col"} and length $options->{"color_col"}) 1 49 50
Condition66%2/3
defined $options->{"color_col"} and length $options->{"color_col"}
!ll&&!rl&&r
4901
MC/DC50%1/2
defined $options->{"color_col"} and length $options->{"color_col"}
defined $options->{"color_col"} length $options->{"color_col"}
Truth table66%2/3
A and B
A= defined $options->{"color_col"}B= length $options->{"color_col"}
ABresult
0X0
100
111
14714 1 $chart_spec{encode}{color} = $options->{color_col};
14715 $chart_spec{options}{color_rules} = $options->{color_rules}
14716 1 ▶ if defined($options->{color_rules}) && @{ $options->{color_rules} };
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"color_rules"} and @{$options->{"color_rules"};} 1 0 1
Condition33%1/3
defined $options->{"color_rules"} and @{$options->{"color_rules"};}
!ll&&!rl&&r
001
MC/DC0%0/2
defined $options->{"color_rules"} and @{$options->{"color_rules"};}
defined $options->{"color_rules"} @{$options->{"color_rules"};}
Truth table33%1/3
A and B
A= defined $options->{"color_rules"}B= @{$options->{"color_rules"};}
ABresult
0X0
100
111
14717 $chart_spec{options}{color_default} = $options->{color_default}
14718 1 ▶ if defined($options->{color_default});
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"color_default"} 1 0 1
14719 }
14720  
14721 return {
14722 title => $title,
14723 map_head => $map_head,
14724 map_body => $map_body,
14725 messages => \@messages,
14726 marker_count => scalar @markers,
14727 row_count => $plotted_rows,
14728 source_rows => scalar @$records,
14729 loc_col => ($by_location ? $loc_col : undef),
14730 loc_text => $loc_text,
14731 lat_col => ($by_location ? undef : $lat_col),
14732 lon_col => ($by_location ? undef : $lon_col),
14733 backend => $backend,
14734 chart => \%chart_spec,
14735 unplotted => \@unplotted,
14736 unplotted_filters => \@unplotted_filters,
14737 pending => \@pending,
14738 bounds_level => $bounds_level,
14739 bounds_pending => \@bounds_pending,
14740 bounds_drawn => ($outlines ? $outlines->{counts}{drawn} : 0),
14741 bounds_noun => $self->_map_outline_noun($outlines, $bounds_level),
14742 # Coloured by the heat layer's weight column, or its rows when it has
14743 # none; not when the outlines had nothing to compare and stayed grey.
14744 bounds_heat => $bounds_coloured,
14745 50 ▶ bounds_weight => ($bounds_coloured ? ($options->{weight} // '') : ''),
Branch: 5 branches
BranchTrueFalseTotal
$by_location ? : 25 25 50
$by_location ? : 25 25 50
$by_location ? : 25 25 50
$outlines ? : 11 39 50
$bounds_coloured ? : 3 47 50
Condition100%4/4
$options->{"weight"} // ""
l!l
21
$bounds_left_rows // 0
l!l
644
MC/DC100%1/1
$options->{"weight"} // ""
$options->{"weight"}
MC/DC100%1/1
$bounds_left_rows // 0
$bounds_left_rows
Truth table100%2/2
A
A= $options->{"weight"}
Aresult
11
00
Truth table100%2/2
A
A= $bounds_left_rows
Aresult
11
00
14746 bounds_as_markers => $bounds_as_markers,
14747 bounds_shade => $bounds_shade,
14748 bounds_shade_as => $bounds_shade_as,
14749 bounds_left_filters => \@bounds_left_filters,
14750 bounds_groups => \@bounds_groups,
14751 bounds_left_rows => $bounds_left_rows // 0,
14752 };
14753 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
14754  
14755 # _map_renderer_version() -> ($ok, $installed_version)
14756 #
14757 # Loads the optional HTML::OSM and says whether it is new enough for the options
14758 # _map_data passes. $installed_version is undef when the module could not be
14759 # loaded at all; when it is defined but $ok is false the copy is too old.
14760 #
14761 # This is a method rather than an inline require so a test can replace it.
14762 # Test::Without::Module does not produce the missing case here: its @INC hook
14763 # is bypassed during Mojolicious' in-process dispatch, so the installed copy is
14764 # still found, and the branch an operator without the dependency is in cannot
14765 # be reached by hiding the module. Replacing one method exercises the same
14766 # else branch, the same message and the same page.
14767 32 ▶sub _map_renderer_version {
Subroutine _map_renderer_version: called CC=4 SCAR=14.5
14768 32 my $self = shift;
14769  
14770 32 my $version = eval {
14771 32 require HTML::OSM;
14772 32 HTML::OSM->VERSION;
14773 };
14774 32 ▶ return (0, undef) unless defined($version) && length($version);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $version and length $version 0 32 32
Condition33%1/3
defined $version and length $version
!ll&&!rl&&r
0032
MC/DC0%0/2
defined $version and length $version
defined $version length $version
Truth table33%1/3
A and B
A= defined $versionB= length $version
ABresult
0X0
100
111
14775  
14776 32 my $new_enough = eval { HTML::OSM->VERSION($MIN_HTML_OSM_VERSION); 1 };
14777 32 ▶ return ($new_enough ? 1 : 0, $version);
Branch: 1 branch
BranchTrueFalseTotal
$new_enough ? : 32 0 32
14778 }
14779  
14780 # _canvas_map_html($head, $body, $id_suffix) -> ($head, $body)
14781 #
14782 # HTML::OSM names the map element "map" and its reset button "reset-button".
14783 # With search => 0 (always set by _map_data), the search-box and
14784 # clear-search-button elements are absent. Suffixing still happens so a
14785 # canvas with two maps gets distinct element ids and local variable scopes.
14786 # The head is the same Leaflet stylesheet and script for every map, so only
14787 # the first head is passed to the layout.
14788 # _scope_card_scripts($html) -> $html
14789 #
14790 # Purpose: Close every inline script in a rendered card over a function of its
14791 # own, so two cards on one canvas cannot collide.
14792 # Entry: $html -- one card's markup, as _render_visual_markup returns it.
14793 # Exit: The same markup, with each inline script wrapped.
14794 # Notes: Called once, by _render_visual_html, so no caller has to remember
14795 # it and no card is scoped twice. HTML::D3 writes a chart as a
14796 # snippet that declares its SVG with
14797 # C<const>. A top-level C<const> belongs to the page's shared lexical
14798 # environment rather than to the <script> element it was written in,
14799 # so a canvas of two charts failed at the second one -- "Identifier
14800 # 'svg' has already been declared" -- and drew an empty card, while
14801 # either card on a page of its own was fine. A script with a C<src>,
14802 # or with a C<type> of its own (a data block, a module), is left
14803 # alone, and one that is already wrapped is not wrapped twice.
14804 55 ▶sub _scope_card_scripts {
Subroutine _scope_card_scripts: called CC=3 SCAR=11.0
14805 55 my ($html) = @_;
14806 55 ▶ return '' unless defined $html && length $html;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $html and length $html 2 53 55
Condition100%3/3
defined $html and length $html
!ll&&!rl&&r
1153
MC/DC100%2/2
defined $html and length $html
defined $html length $html
Truth table100%3/3
A and B
A= defined $htmlB= length $html
ABresult
0X0
100
111
14807  
14808 # ~ is the delimiter because the lookaheads below need !, and the wrapper
14809 # the replacement builds is a pair of braces, which a brace-delimited
14810 # pattern would take for its own.
14811 53 $html =~ s~(<script\b(?![^>]*\bsrc=)(?![^>]*\btype=)[^>]*>)(.*?)(</script>)~_wrap_card_script($1, $2, $3)~gsex;
14812  
14813 53 return $html;
14814 }
14815  
14816 # _wrap_card_script($open, $body, $close) -> $html
14817 #
14818 # Purpose: One <script> element of a card, closed over a function of its own.
14819 # Entry: The element's opening tag, its body and its closing tag.
14820 # Exit: The same element, wrapped unless it already is.
14821 # Notes: Split out of _scope_card_scripts so that pattern can use a plain
14822 # delimiter: its lookaheads need the ones the wrapper is made of.
14823 48 ▶sub _wrap_card_script {
Subroutine _wrap_card_script: called CC=2 SCAR=6.9
14824 48 my ($open, $body, $close) = @_;
14825  
14826 # A body that already opens with the wrapper is left alone, so scoping a
14827 # card twice is scoping it once.
14828 48 my ($blank) = $body =~ /\A(\s*)/;
14829 48 ▶ return $open . $body . $close
Branch: 1 branch
BranchTrueFalseTotal
if CORE::index(substr($body, length $blank), "(function () {") == 0 2 46 48
14830 if CORE::index(substr($body, length $blank), '(function () {') == 0;
14831  
14832 46 return $open . "\n(function () {\n" . $body . "\n})();\n" . $close;
14833 }
14834  
14835 7 ▶sub _canvas_map_html {
Subroutine _canvas_map_html: called CC=4 SCAR=13.9
14836 7 my ($head, $body, $id_suffix) = @_;
14837  
14838 7 ▶ my $suffix = $id_suffix // 'map';
Condition100%2/2
$id_suffix // "map"
l!l
61
MC/DC100%1/1
$id_suffix // "map"
$id_suffix
Truth table100%2/2
A
A= $id_suffix
Aresult
11
00
14839 7 $suffix =~ s/[^A-Za-z0-9_-]//g;
14840 7 ▶ $suffix = 'map' unless length $suffix;
Branch: 1 branch
BranchTrueFalseTotal
unless length $suffix 1 6 7
14841  
14842 7 my %ids = (
14843 'map' => "map-$suffix",
14844 'search-box' => "search-box-$suffix",
14845 'reset-button' => "reset-button-$suffix",
14846 'clear-search-button' => "clear-search-button-$suffix",
14847 );
14848 7 for my $old (sort keys %ids) {
14849 28 my $new = $ids{$old};
14850 28 $body =~ s/id="\Q$old\E"/id="$new"/g;
14851 28 $body =~ s{getElementById\('\Q$old\E'\)}{getElementById('$new')}g;
14852 28 $body =~ s{L\.map\('\Q$old\E'\)}{L.map('$new')}g;
14853 }
14854 7 $body =~ s{<div id="$ids{map}"></div>}{<div id="$ids{map}" class="canvas-map"></div>};
14855  
14856 # The card owns the map's size, so the page-wide #map rule is noise here.
14857 7 $head =~ s{<style>.*?</style>}{}s;
14858  
14859 # The scope around the map's script is not put on here: every card is
14860 # scoped once, by _render_visual_html, whichever kind it is.
14861 7 return ($head, $body);
14862 }
14863  
14864 114 ▶sub map_view ($self) {
Subroutine map_view: called CC=112 SCAR=59.9
Pod documented
14865 114 my @loc_cols = _map_loc_columns($self->every_param('loc'));
14866 114 my $loc_col = join(', ', @loc_cols);
14867 114 ▶ my $lat_col = $self->param('lat') // '';
Condition100%2/2
$self->param("lat") // ""
l!l
4272
MC/DC100%1/1
$self->param("lat") // ""
$self->param("lat")
Truth table100%2/2
A
A= $self->param("lat")
Aresult
11
00
14868 114 ▶ my $lon_col = $self->param('lon') // '';
Condition100%2/2
$self->param("lon") // ""
l!l
4074
MC/DC100%1/1
$self->param("lon") // ""
$self->param("lon")
Truth table100%2/2
A
A= $self->param("lon")
Aresult
11
00
14869 114 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
0114
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table50%1/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
14870 114 my $back2 = _safe_back_url($self->param('back2'));
14871 114 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
0114
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
14872  
14873 # Optional display params
14874 114 ▶ my $zoom_raw = $self->param('zoom') // '';
Condition50%1/2
$self->param("zoom") // ""
l!l
0114
MC/DC0%0/1
$self->param("zoom") // ""
$self->param("zoom")
Truth table50%1/2
A
A= $self->param("zoom")
Aresult
11
00
14875 114 ▶ my $max_zoom_raw = $self->param('max_zoom') // '';
Condition50%1/2
$self->param("max_zoom") // ""
l!l
0114
MC/DC0%0/1
$self->param("max_zoom") // ""
$self->param("max_zoom")
Truth table50%1/2
A
A= $self->param("max_zoom")
Aresult
11
00
14876 114 ▶ my $tiles_name = $self->param('tiles') // '';
Condition100%2/2
$self->param("tiles") // ""
l!l
1113
MC/DC100%1/1
$self->param("tiles") // ""
$self->param("tiles")
Truth table100%2/2
A
A= $self->param("tiles")
Aresult
11
00
14877 114 ▶ my $heat = $self->param('heat') // 0;
Condition100%2/2
$self->param("heat") // 0
l!l
4110
MC/DC100%1/1
$self->param("heat") // 0
$self->param("heat")
Truth table100%2/2
A
A= $self->param("heat")
Aresult
11
00
14878 114 ▶ my $bounds_raw = $self->param('bounds') // '';
Condition100%2/2
$self->param("bounds") // ""
l!l
12102
MC/DC100%1/1
$self->param("bounds") // ""
$self->param("bounds")
Truth table100%2/2
A
A= $self->param("bounds")
Aresult
11
00
14879 114 ▶ my $loc_text_raw = $self->param('loc_text') // '';
Condition100%2/2
$self->param("loc_text") // ""
l!l
1113
MC/DC100%1/1
$self->param("loc_text") // ""
$self->param("loc_text")
Truth table100%2/2
A
A= $self->param("loc_text")
Aresult
11
00
14880 114 ▶ my $weight_col = $self->param('weight') // '';
Condition100%2/2
$self->param("weight") // ""
l!l
2112
MC/DC100%1/1
$self->param("weight") // ""
$self->param("weight")
Truth table100%2/2
A
A= $self->param("weight")
Aresult
11
00
14881 114 ▶ my $shade_col = $self->param('shade') // '';
Condition50%1/2
$self->param("shade") // ""
l!l
0114
MC/DC0%0/1
$self->param("shade") // ""
$self->param("shade")
Truth table50%1/2
A
A= $self->param("shade")
Aresult
11
00
14882 114 ▶ my $shade_color = _parse_color($self->param('shade_color') // '');
Condition50%1/2
$self->param("shade_color") // ""
l!l
0114
MC/DC0%0/1
$self->param("shade_color") // ""
$self->param("shade_color")
Truth table50%1/2
A
A= $self->param("shade_color")
Aresult
11
00
14883 114 ▶ my $size_col = $self->param('size') // '';
Condition100%2/2
$self->param("size") // ""
l!l
2112
MC/DC100%1/1
$self->param("size") // ""
$self->param("size")
Truth table100%2/2
A
A= $self->param("size")
Aresult
11
00
14884 114 ▶ my $series_col = $self->param('series') // '';
Condition100%2/2
$self->param("series") // ""
l!l
1113
MC/DC100%1/1
$self->param("series") // ""
$self->param("series")
Truth table100%2/2
A
A= $self->param("series")
Aresult
11
00
14885 114 ▶ my $scheme = $self->param('scheme') // 'tableau10';
Condition100%2/2
$self->param("scheme") // "tableau10"
l!l
2112
MC/DC100%1/1
$self->param("scheme") // "tableau10"
$self->param("scheme")
Truth table100%2/2
A
A= $self->param("scheme")
Aresult
11
00
14886  
14887 # tiles= names a source from tile_sources in config; an arbitrary URL is
14888 # never accepted so a crafted share link cannot redirect tiles fetches.
14889 114 my $tile_url_override;
14890 114 ▶ if (length $tiles_name) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $tiles_name) 1 113 114
14891 1 ▶ my $sources = $self->app->config('tile_sources') // {};
Condition50%1/2
$self->app->config("tile_sources") // {}
l!l
01
MC/DC0%0/1
$self->app->config("tile_sources") // {}
$self->app->config("tile_sources")
Truth table50%1/2
A
A= $self->app->config("tile_sources")
Aresult
11
00
14892 1 ▶ unless (exists $sources->{$tiles_name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $sources->{$tiles_name}) 1 0 1
14893 1 return $self->render(
14894 text => $self->_i18n('error_map_tiles_unknown', $tiles_name),
14895 status => 400,
14896 );
14897 }
14898 0 $tile_url_override = $sources->{$tiles_name}{url};
14899 }
14900  
14901 113 my $zoom_val;
14902 113 ▶ if (length $zoom_raw && $zoom_raw =~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $zoom_raw and $zoom_raw =~ /\A\d+\z/u) 0 113 113
Condition33%1/3
length $zoom_raw and $zoom_raw =~ /\A\d+\z/u
!ll&&!rl&&r
11300
MC/DC0%0/2
length $zoom_raw and $zoom_raw =~ /\A\d+\z/u
length $zoom_raw $zoom_raw =~ /\A\d+\z/u
Truth table33%1/3
A and B
A= length $zoom_rawB= $zoom_raw =~ /\A\d+\z/u
ABresult
0X0
100
111
14903 0 $zoom_val = int $zoom_raw;
14904 0 ▶ $zoom_val = 0 if $zoom_val < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $zoom_val < 0 0 0 0
14905 0 ▶ $zoom_val = 19 if $zoom_val > 19;
Branch: 1 branch
BranchTrueFalseTotal
if $zoom_val > 19 0 0 0
14906 }
14907  
14908 113 my $max_zoom_val;
14909 113 ▶ if (length $max_zoom_raw && $max_zoom_raw =~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $max_zoom_raw and $max_zoom_raw =~ /\A\d+\z/u) { } 0 113 113
Condition33%1/3
length $max_zoom_raw and $max_zoom_raw =~ /\A\d+\z/u
!ll&&!rl&&r
11300
MC/DC0%0/2
length $max_zoom_raw and $max_zoom_raw =~ /\A\d+\z/u
length $max_zoom_raw $max_zoom_raw =~ /\A\d+\z/u
Truth table33%1/3
A and B
A= length $max_zoom_rawB= $max_zoom_raw =~ /\A\d+\z/u
ABresult
0X0
100
111
14910 0 $max_zoom_val = int $max_zoom_raw;
14911 0 ▶ $max_zoom_val = 0 if $max_zoom_val < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $max_zoom_val < 0 0 0 0
14912 0 ▶ $max_zoom_val = 28 if $max_zoom_val > 28;
Branch: 1 branch
BranchTrueFalseTotal
if $max_zoom_val > 28 0 0 0
14913 } else {
14914 113 my $cfg_max_zoom = $self->app->config('map_max_zoom');
14915 113 ▶ $max_zoom_val = int($cfg_max_zoom)
Branch: 1 branch
BranchTrueFalseTotal
if defined $cfg_max_zoom and $cfg_max_zoom =~ /\A\d+\z/u 0 113 113
Condition33%1/3
defined $cfg_max_zoom and $cfg_max_zoom =~ /\A\d+\z/u
!ll&&!rl&&r
11300
MC/DC0%0/2
defined $cfg_max_zoom and $cfg_max_zoom =~ /\A\d+\z/u
defined $cfg_max_zoom $cfg_max_zoom =~ /\A\d+\z/u
Truth table33%1/3
A and B
A= defined $cfg_max_zoomB= $cfg_max_zoom =~ /\A\d+\z/u
ABresult
0X0
100
111
14916 if defined($cfg_max_zoom) && $cfg_max_zoom =~ /\A\d+\z/;
14917 }
14918  
14919 113 my $by_location = length $loc_col;
14920  
14921 113 my ($loc_text) = _map_loc_text($loc_text_raw);
14922 113 ▶ return $self->render(text => $self->_i18n('error_map_loc_text', $Database::BI::Model::Geocode::PLACE_TEXT_MAX, $loc_text_raw), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $loc_text 1 112 113
14923 unless defined $loc_text;
14924  
14925 112 my $bounds_level;
14926 112 ▶ if (length $bounds_raw) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $bounds_raw) 12 100 112
14927 12 $bounds_level = _map_bounds_level($bounds_raw);
14928 12 ▶ return $self->render(text => $self->_i18n('error_map_bounds_unknown',
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bounds_level 1 11 12
14929 join(', ', Database::BI::Model::Boundary->levels), $bounds_raw), status => 400)
14930 unless defined $bounds_level;
14931 }
14932  
14933 111 ▶ return $self->render(text => $self->_i18n('error_map_source'), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $by_location or length $lat_col or length $lon_col 45 66 111
Condition100%6/6
$by_location or length $lat_col or length $lon_col
l!l&&r!l&&!r
64245
$by_location or length $lat_col
l!l&&r!l&&!r
253947
MC/DC100%3/3
$by_location or length $lat_col or length $lon_col
$by_location length $lat_col length $lon_col
Truth table100%4/4
A or B or C
A= $by_locationB= length $lat_colC= length $lon_col
ABCresult
1XX1
01X1
0011
0000
14934 unless $by_location || length($lat_col) || length($lon_col);
14935 66 ▶ return $self->render(text => $self->_i18n('error_map_coordinates'), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $by_location or length $lat_col and length $lon_col 6 60 66
Condition100%6/6
$by_location or length $lat_col and length $lon_col
l!l&&r!l&&!r
25356
length $lat_col and length $lon_col
!ll&&!rl&&r
2435
MC/DC100%3/3
$by_location or length $lat_col and length $lon_col
$by_location length $lat_col length $lon_col
Truth table100%4/4
A or B and C
A= $by_locationB= length $lat_colC= length $lon_col
ABCresult
1XX1
0111
00X0
0100
14936 if !$by_location && (!length($lat_col) || !length($lon_col));
14937  
14938 60 my ($src, $records, $columns) = $self->_run_pipeline_source;
14939 60 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 3 57 60
14940 unless defined $records;
14941  
14942 57 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
14943 57 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 57 57
14944 0 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
14945 0 return $self->render(text => $e, status => 400);
14946 }
14947  
14948 # geocode= says when the places not in the cache yet are looked up: 'wait'
14949 # in this request, before the page is sent; 'cached' not at all, so the map
14950 # shows what the cache knows (where Cancel leads). Without it, a page a
14951 # browser navigated to (a GET whose Accept names text/html, which fetch()
14952 # and scripts do not send) asks nothing here: it lists the places for the
14953 # page, which looks them up one at a time with a progress bar. Any other
14954 # client waits, as every client did before.
14955 57 ▶ my $geocode_mode = $self->param('geocode') // '';
Condition100%2/2
$self->param("geocode") // ""
l!l
156
MC/DC100%1/1
$self->param("geocode") // ""
$self->param("geocode")
Truth table100%2/2
A
A= $self->param("geocode")
Aresult
11
00
14956 57 ▶ return $self->render(text => $self->_i18n('error_map_geocode_mode', $geocode_mode), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $geocode_mode =~ /\A(?:wait|cached|)\z/u 1 56 57
14957 unless $geocode_mode =~ /\A(?:wait|cached|)\z/;
14958 56 ▶ my $progress = ($by_location || defined($bounds_level)) && !length($geocode_mode)
Condition71%10/14
($by_location || defined $bounds_level) && !length($geocode_mode) && $self->req->method eq 'GET' && ($self->req->headers->accept // '') =~ m[\btext/html\b]u
!ll&&!rl&&r
20360
$by_location || defined $bounds_level and not length $geocode_mode and $self->req->method eq "GET"
!ll&&!rl&&r
20036
$by_location || defined $bounds_level and not length $geocode_mode
!ll&&!rl&&r
20036
$by_location or defined $bounds_level
l!l&&r!l&&!r
251120
$self->req->headers->accept // ""
l!l
036
MC/DC0%0/5
($by_location || defined $bounds_level) && !length($geocode_mode) && $self->req->method eq 'GET' && ($self->req->headers->accept // '') =~ m[\btext/html\b]u
$by_location defined $bounds_level not length $geocode_mode $self->req->method eq "GET" $self->req->headers->accept
Truth table33%3/9
A or B and not(C) and D && E
A= $by_locationB= defined $bounds_levelC= not length $geocode_modeD= $self->req->method eq "GET"E= $self->req->headers->accept
ABCDEresult
00XXX0
1X0XX0
010XX0
1X10X0
0110X0
1X1100
011100
1X1111
011111
14959 && $self->req->method eq 'GET'
14960 && ($self->req->headers->accept // '') =~ m{\btext/html\b};
14961  
14962 56 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 56 56
14963  
14964 56 my %col_set = map { $_ => 1 } @{ $columns };
14965 56 my %loc_set = map { $_ => 1 } @loc_cols;
14966 3 ▶ my @popup = grep { length($_) && !$loc_set{$_} && $col_set{$_} }
Condition50%3/6
length $_ && !$loc_set{$_} && $col_set{$_}
!ll&&!rl&&r
012
length $_ and not $loc_set{$_}
!ll&&!rl&&r
003
MC/DC33%1/3
length $_ && !$loc_set{$_} && $col_set{$_}
length $_ not $loc_set{$_} $col_set{$_}
Truth table50%2/4
A and not(B) && C
A= length $_B= not $loc_set{$_}C= $col_set{$_}
ABCresult
0XX0
10X0
1100
1111
14967 56 @{ $self->every_param('popup') };
14968  
14969 # Marker colour params. color= applies explicit threshold rules;
14970 # series= colours one value per distinct category from scheme=, which is the
14971 # categorical form the other chart pages already offer.
14972 56 ▶ my $color_col = $self->param('color') // '';
Condition50%1/2
$self->param("color") // ""
l!l
056
MC/DC0%0/1
$self->param("color") // ""
$self->param("color")
Truth table50%1/2
A
A= $self->param("color")
Aresult
11
00
14973 56 ▶ my $color_def_raw = $self->param('color_default') // '';
Condition50%1/2
$self->param("color_default") // ""
l!l
056
MC/DC0%0/1
$self->param("color_default") // ""
$self->param("color_default")
Truth table50%1/2
A
A= $self->param("color_default")
Aresult
11
00
14974 56 my ($color_rules, $color_default) =
14975 _parse_color_rules($self->every_param('color_rule'), $color_def_raw);
14976  
14977 56 ▶ if (length($color_col) && !$col_set{$color_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $color_col and not $col_set{$color_col}) 0 56 56
Condition33%1/3
length $color_col and not $col_set{$color_col}
!ll&&!rl&&r
5600
MC/DC0%0/2
length $color_col and not $col_set{$color_col}
length $color_col not $col_set{$color_col}
Truth table33%1/3
A and not(B)
A= length $color_colB= not $col_set{$color_col}
ABresult
0X0
100
111
14978 0 return $self->render(text => "Column not found: $color_col", status => 400);
14979 }
14980 56 ▶ return $self->render(text => 'Use either color= or series=, not both', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if length $color_col and length $series_col 0 56 56
Condition33%1/3
length $color_col and length $series_col
!ll&&!rl&&r
5600
MC/DC0%0/2
length $color_col and length $series_col
length $color_col length $series_col
Truth table33%1/3
A and B
A= length $color_colB= length $series_col
ABresult
0X0
100
111
14981 if length($color_col) && length($series_col);
14982 return $self->render(text => "Column not found: $size_col", status => 400)
14983 56 ▶ if length($size_col) && !$col_set{$size_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $size_col and not $col_set{$size_col} 0 56 56
Condition33%1/3
length $size_col and not $col_set{$size_col}
!ll&&!rl&&r
5600
MC/DC0%0/2
length $size_col and not $col_set{$size_col}
length $size_col not $col_set{$size_col}
Truth table33%1/3
A and not(B)
A= length $size_colB= not $col_set{$size_col}
ABresult
0X0
100
111
14984  
14985 56 my (@series_cats, $series_palette);
14986 56 ▶ if (length $series_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col) 1 55 56
14987 return $self->render(text => "Column not found: $series_col", status => 400)
14988 1 ▶ unless $col_set{$series_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$series_col} 0 1 1
14989 return $self->render(text => "Unknown colour scheme: $scheme", status => 400)
14990 1 ▶ unless $SCATTER_SCHEMES{$scheme};
Branch: 1 branch
BranchTrueFalseTotal
unless $SCATTER_SCHEMES{$scheme} 0 1 1
14991  
14992 1 ▶ $series_palette = $CATEGORY_PALETTES{$scheme} // $CATEGORY_PALETTES{tableau10};
Condition33%1/3
$CATEGORY_PALETTES{$scheme} // $CATEGORY_PALETTES{"tableau10"}
l!l&&r!l&&!r
100
MC/DC0%0/2
$CATEGORY_PALETTES{$scheme} // $CATEGORY_PALETTES{"tableau10"}
$CATEGORY_PALETTES{$scheme} $CATEGORY_PALETTES{"tableau10"}
Truth table33%1/3
A // B
A= $CATEGORY_PALETTES{$scheme}B= $CATEGORY_PALETTES{"tableau10"}
ABresult
1X1
011
000
14993 1 my %seen;
14994 3 @series_cats = grep { !$seen{$_}++ } map {
14995 1 my $value = $_->{$series_col};
14996 3 ▶ defined($value) ? "$value" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 3 0 3
14997 } @$records;
14998  
14999 # A legend longer than two cycles of the palette helps nobody; the
15000 # remaining values keep a palette colour but are not listed.
15001 1 my $limit = @$series_palette * 2;
15002 1 ▶ @series_cats = @series_cats[0 .. $limit - 1] if @series_cats > $limit;
Branch: 1 branch
BranchTrueFalseTotal
if @series_cats > $limit 0 1 1
15003  
15004 1 $color_col = $series_col;
15005 $color_rules = [
15006 map {
15007 1 {
15008 3 op => 'eq',
15009 val => $series_cats[$_],
15010 color => $series_palette->[ $_ % @$series_palette ],
15011 }
15012 } 0 .. $#series_cats
15013 ];
15014 1 $color_default = $series_palette->[0];
15015 }
15016  
15017 56 my %options;
15018 56 ▶ $options{popup} = \@popup if @popup;
Branch: 1 branch
BranchTrueFalseTotal
if @popup 2 54 56
15019 56 ▶ $options{color_col} = $color_col if length $color_col;
Branch: 1 branch
BranchTrueFalseTotal
if length $color_col 1 55 56
15020 56 ▶ $options{color_rules} = $color_rules if @$color_rules;
Branch: 1 branch
BranchTrueFalseTotal
if @$color_rules 1 55 56
15021 56 $options{color_default} = $color_default;
15022 56 ▶ $options{size} = $size_col if length $size_col;
Branch: 1 branch
BranchTrueFalseTotal
if length $size_col 0 56 56
15023 56 ▶ $options{scheme} = $scheme if length $series_col;
Branch: 1 branch
BranchTrueFalseTotal
if length $series_col 1 55 56
15024 56 my $max = $self->param('max');
15025 56 ▶ $options{max} = $max if defined($max) && $max =~ /\A\d+\z/ && $max > 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $max and $max =~ /\A\d+\z/u and $max > 0 1 55 56
Condition83%5/6
defined $max and $max =~ /\A\d+\z/u and $max > 0
!ll&&!rl&&r
5411
defined $max and $max =~ /\A\d+\z/u
!ll&&!rl&&r
5402
MC/DC66%2/3
defined $max and $max =~ /\A\d+\z/u and $max > 0
defined $max $max =~ /\A\d+\z/u $max > 0
Truth table75%3/4
A and B and C
A= defined $maxB= $max =~ /\A\d+\z/uC= $max > 0
ABCresult
0XX0
10X0
1100
1111
15026 56 ▶ $options{zoom} = $zoom_val if defined $zoom_val;
Branch: 1 branch
BranchTrueFalseTotal
if defined $zoom_val 0 56 56
15027 56 ▶ $options{max_zoom} = $max_zoom_val if defined $max_zoom_val;
Branch: 1 branch
BranchTrueFalseTotal
if defined $max_zoom_val 0 56 56
15028 56 ▶ $options{tile_url} = $tile_url_override if defined $tile_url_override;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tile_url_override 0 56 56
15029 56 ▶ $options{heat} = 1 if $heat;
Branch: 1 branch
BranchTrueFalseTotal
if $heat 4 52 56
15030 56 ▶ $options{bounds} = $bounds_level if defined $bounds_level;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bounds_level 11 45 56
15031 56 ▶ $options{weight} = $weight_col if length($weight_col) && $col_set{$weight_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $weight_col and $col_set{$weight_col} 2 54 56
Condition66%2/3
length $weight_col and $col_set{$weight_col}
!ll&&!rl&&r
5402
MC/DC50%1/2
length $weight_col and $col_set{$weight_col}
length $weight_col $col_set{$weight_col}
Truth table66%2/3
A and B
A= length $weight_colB= $col_set{$weight_col}
ABresult
0X0
100
111
15032 # Colour shade: a column to fill the outlines by, and the colour to shade
15033 56 ▶ $options{shade} = $shade_col if length($shade_col) && $col_set{$shade_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $shade_col and $col_set{$shade_col} 0 56 56
Condition33%1/3
length $shade_col and $col_set{$shade_col}
!ll&&!rl&&r
5600
MC/DC0%0/2
length $shade_col and $col_set{$shade_col}
length $shade_col $col_set{$shade_col}
Truth table33%1/3
A and B
A= length $shade_colB= $col_set{$shade_col}
ABresult
0X0
100
111
15034 56 ▶ $options{shade_color} = $shade_color if defined($shade_color) && defined($options{shade});
Branch: 1 branch
BranchTrueFalseTotal
if defined $shade_color and defined $options{"shade"} 0 56 56
Condition33%1/3
defined $shade_color and defined $options{"shade"}
!ll&&!rl&&r
5600
MC/DC0%0/2
defined $shade_color and defined $options{"shade"}
defined $shade_color defined $options{"shade"}
Truth table33%1/3
A and B
A= defined $shade_colorB= defined $options{"shade"}
ABresult
0X0
100
111
15035 56 ▶ $options{lookup} = 0 if $progress || $geocode_mode eq 'cached';
Branch: 1 branch
BranchTrueFalseTotal
if $progress or $geocode_mode eq "cached" 0 56 56
Condition33%1/3
$progress or $geocode_mode eq "cached"
l!l&&r!l&&!r
0056
MC/DC0%0/2
$progress or $geocode_mode eq "cached"
$progress $geocode_mode eq "cached"
Truth table33%1/3
A or B
A= $progressB= $geocode_mode eq "cached"
ABresult
1X1
011
000
15036  
15037 # Each place that could not be plotted, and each marker with more rows
15038 # than its popup lists, links to its rows in the table, as a bar drills
15039 # into its category: the table this map came from, with
15040 # the place's filters added, and back2= to return here.
15041 56 ▶ my $rows_base = ($back =~ m{\A(?:https?://[^/]+)?/(?:open\?|view/)}) ? $back
Branch: 1 branch
BranchTrueFalseTotal
$back =~ m[\A(?:https?://[^/]+)?/(?:open\?|view/)]u ? : 0 56 56
Condition50%1/2
$self->param("l") // ""
l!l
560
MC/DC0%0/1
$self->param("l") // ""
$self->param("l")
Truth table50%1/2
A
A= $self->param("l")
Aresult
11
00
15042 : $self->_spec_to_url($self->param('l') // '');
15043 56 my $here = $self->req->url->path_query;
15044 237 ▶ my $rows_url = sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
15045 237 my ($filters) = @_;
15046 237 ▶ return '' if $rows_base eq '/' || !@{$filters};
Branch: 1 branch
BranchTrueFalseTotal
if $rows_base eq "/" or not @{$filters;} 68 169 237
Condition66%2/3
$rows_base eq "/" or not @{$filters;}
l!l&&r!l&&!r
068169
MC/DC50%1/2
$rows_base eq "/" or not @{$filters;}
$rows_base eq "/" not @{$filters;}
Truth table66%2/3
A or not(B)
A= $rows_base eq "/"B= not @{$filters;}
ABresult
1X1
011
000
15047 169 ▶ my $sep = ($rows_base =~ /\?/) ? '&' : '?';
Branch: 1 branch
BranchTrueFalseTotal
$rows_base =~ /\?/u ? : 169 0 169
15048 return $rows_base . $sep . join('&',
15049 169 (map { 'f=' . url_escape(encode('UTF-8', $_)) } @{$filters}),
15050 'back2=' . url_escape($here),
15051 'back2_label=' . url_escape('Back to map'),
15052 );
15053 56 };
15054 56 $options{rows_url} = $rows_url;
15055  
15056 56 ▶ my $result = $self->_map_data(
Branch: 1 branch
BranchTrueFalseTotal
$by_location ? : 25 31 56
Condition50%1/2
$self->param("l") // ""
l!l
560
MC/DC0%0/1
$self->param("l") // ""
$self->param("l")
Truth table50%1/2
A
A= $self->param("l")
Aresult
11
00
15057 $records, $columns,
15058 ($by_location ? { loc => [ @loc_cols ], loc_text => $loc_text } : { lat => $lat_col, lon => $lon_col }),
15059 \%options,
15060 $self->param('l') // '',
15061 undef,
15062 );
15063  
15064 return $self->render(text => $result->{error}, status => $result->{status})
15065 55 ▶ if $result->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"error"} 10 45 55
15066  
15067 45 my ($source_url, $source_accessed) = $self->_url_attribution;
15068 45 my ($platform, $language) = $self->_resolve_template;
15069  
15070 my @unplotted = map {
15071 27 my $entry = { %{$_} };
15072 27 $entry->{url} = $rows_url->($entry->{filters});
15073 27 $entry;
15074 45 ▶ } @{ $result->{unplotted} // [] };
Condition50%1/2
$result->{"unplotted"} // []
l!l
450
MC/DC0%0/1
$result->{"unplotted"} // []
$result->{"unplotted"}
Truth table50%1/2
A
A= $result->{"unplotted"}
Aresult
11
00
15075 45 my $unplotted_rows = 0;
15076 45 $unplotted_rows += $_->{rows} for @unplotted;
15077  
15078 # This page with geocode= set to $mode, or without it for undef.
15079 45 ▶ my $here_with = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
15080 45 my ($mode) = @_;
15081 45 my $url = $self->req->url->clone;
15082 45 $url->query->remove('geocode');
15083 45 ▶ $url->query->append(geocode => $mode) if defined $mode;
Branch: 1 branch
BranchTrueFalseTotal
if defined $mode 0 45 45
15084 45 return $url->path_query;
15085 45 };
15086  
15087 # The places to look up, each signed so that /geo/lookup asks only what a
15088 # map page listed: without that, any page on the web could post a string
15089 # for this server to send to OpenStreetMap.
15090 0 ▶ my @pending = $progress ? @{ $result->{pending} // [] } : ();
Branch: 1 branch
BranchTrueFalseTotal
$progress ? : 0 45 45
Condition0%0/2
$result->{"pending"} // []
l!l
00
MC/DC0%0/1
$result->{"pending"} // []
$result->{"pending"}
Truth table0%0/2
A
A= $result->{"pending"}
Aresult
11
00
15091 # The points whose outline is not known yet go on the same list,
15092 # after the places, each signed with its level for /geo/boundary.
15093 0 ▶ my @bounds_pending = $progress ? @{ $result->{bounds_pending} // [] } : ();
Branch: 1 branch
BranchTrueFalseTotal
$progress ? : 0 45 45
Condition0%0/2
$result->{"bounds_pending"} // []
l!l
00
MC/DC0%0/1
$result->{"bounds_pending"} // []
$result->{"bounds_pending"}
Truth table0%0/2
A
A= $result->{"bounds_pending"}
Aresult
11
00
15094 45 my @messages = @{ $result->{messages} };
15095 0 ▶ @messages = grep { $_->{key} ne 'warn_map_bounds_pending' } @messages if @bounds_pending;
Branch: 1 branch
BranchTrueFalseTotal
if @bounds_pending 0 45 45
15096 45 my %progress;
15097 45 ▶ if (@pending || @bounds_pending) {
Branch: 1 branch
BranchTrueFalseTotal
if (@pending or @bounds_pending) 0 45 45
Condition33%1/3
@pending or @bounds_pending
l!l&&r!l&&!r
0045
MC/DC0%0/2
@pending or @bounds_pending
@pending @bounds_pending
Truth table33%1/3
A or B
A= @pendingB= @bounds_pending
ABresult
1X1
011
000
15098 my $json = to_json([
15099 0 (map { { place => $_, sig => $self->_geo_lookup_sig($_) } } @pending),
15100 0 (map { {
15101 point => $_,
15102 level => $result->{bounds_level},
15103 0 sig => $self->_geo_boundary_sig($result->{bounds_level}, $_),
15104 } } @bounds_pending),
15105 ]);
15106 0 $json =~ s{</}{<\\/}g;
15107 0 %progress = (
15108 geocode_pending => scalar(@pending) + scalar(@bounds_pending),
15109 geocode_places => scalar @pending,
15110 geocode_outlines => scalar @bounds_pending,
15111 geocode_pending_json => $json,
15112 geocode_done_url => $here_with->(undef),
15113 geocode_cached_url => $here_with->('cached'),
15114 geocode_wait_url => $here_with->('wait'),
15115 );
15116 }
15117  
15118 # After Cancel, the places left are offered again.
15119 $progress{geocode_retry_url} = $here_with->(undef)
15120 0 ▶ if $geocode_mode eq 'cached' && grep { $_->{reason} eq 'later' } @unplotted;
Branch: 1 branch
BranchTrueFalseTotal
if $geocode_mode eq "cached" and grep {$_->{"reason"} eq "later";} @unplotted 0 45 45
Condition33%1/3
$geocode_mode eq "cached" and grep {$_->{"reason"} eq "later";} @unplotted
!ll&&!rl&&r
4500
MC/DC0%0/2
$geocode_mode eq "cached" and grep {$_->{"reason"} eq "later";} @unplotted
$geocode_mode eq "cached" grep {$_->{"reason"} eq "later";} @unplotted
Truth table33%1/3
A and B
A= $geocode_mode eq "cached"B= grep {$_->{"reason"} eq "later";} @unplotted
ABresult
0X0
100
111
15121  
15122 $self->render(
15123 handler => 'tt',
15124 template => "$platform/$language/map",
15125 %progress,
15126 unplotted => \@unplotted,
15127 unplotted_rows => $unplotted_rows,
15128 unplotted_url => $rows_url->($result->{unplotted_filters} // []),
15129 # Where the outlines and the markers do not pair off, each with a link
15130 # to its rows
15131 1 ▶ bounds_groups => [ map { +{ %{$_}, url => $rows_url->($_->{filters}) } } @{ $result->{bounds_groups} // [] } ],
Condition50%2/4
$result->{"bounds_groups"} // []
l!l
450
$result->{"bounds_left_filters"} // []
l!l
450
MC/DC0%0/1
$result->{"bounds_groups"} // []
$result->{"bounds_groups"}
MC/DC0%0/1
$result->{"bounds_left_filters"} // []
$result->{"bounds_left_filters"}
Truth table50%1/2
A
A= $result->{"bounds_groups"}
Aresult
11
00
Truth table50%1/2
A
A= $result->{"bounds_left_filters"}
Aresult
11
00
15132 # The rows whose place has no outline, and this page again to
15133 # look those outlines up (as it was opened: waiting, or with progress)
15134 bounds_left_url => $rows_url->($result->{bounds_left_filters} // []),
15135 bounds_left_rows => $result->{bounds_left_rows},
15136 45 ▶ bounds_left => scalar(@{ $result->{bounds_pending} // [] }),
Branch: 4 branches
BranchTrueFalseTotal
$geocode_mode eq 'wait' ? : 0 45 45
@loc_cols > 1 ? : 0 45 45
$back2 ? : 0 45 45
$back2 ? : 0 45 45
Condition28%2/7
$result->{"bounds_pending"} // []
l!l
450
$back2 // $back
l!l&&r!l&&!r
0450
$back2_lbl or "Back"
l!l
00
MC/DC0%0/1
$result->{"bounds_pending"} // []
$result->{"bounds_pending"}
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
Truth table50%1/2
A
A= $result->{"bounds_pending"}
Aresult
11
00
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
15137 bounds_retry_url => $here_with->($geocode_mode eq 'wait' ? 'wait' : undef),
15138 format => 'html',
15139 title => $result->{title},
15140 extra_head => $result->{map_head},
15141 map_body => $result->{map_body},
15142 messages => \@messages,
15143 marker_count => $result->{marker_count},
15144 bounds_drawn => $result->{bounds_drawn},
15145 bounds_heat => $result->{bounds_heat},
15146 bounds_noun => $result->{bounds_noun},
15147 bounds_as_markers => $result->{bounds_as_markers},
15148 bounds_shade => $result->{bounds_shade},
15149 bounds_shade_as => $result->{bounds_shade_as},
15150 bounds_weight => $result->{bounds_weight},
15151 row_count => $result->{row_count},
15152 source_rows => $result->{source_rows},
15153 loc_col => $result->{loc_col},
15154 loc_many => (@loc_cols > 1 ? 1 : 0),
15155 loc_text => $result->{loc_text},
15156 lat_col => $result->{lat_col},
15157 lon_col => $result->{lon_col},
15158 backend => $result->{backend},
15159 chart => $result->{chart},
15160 45 ▶ chart_json => $self->_chart_json($result->{chart}),
Condition50%1/2
$result->{"unplotted_filters"} // []
l!l
450
MC/DC0%0/1
$result->{"unplotted_filters"} // []
$result->{"unplotted_filters"}
Truth table50%1/2
A
A= $result->{"unplotted_filters"}
Aresult
11
00
15161 back_url => ($back2 // $back),
15162 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
15163 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
15164 source_url => $source_url,
15165 source_accessed => $source_accessed,
15166 language => $language,
15167 );
15168 }
15169  
15170 # _geo_lookup_sig($self, $place) -> $hex
15171 #
15172 # What the map page signs each place it lists with, and /geo/lookup checks.
15173 # The key is the application's secret, which BI.pm makes at random for each
15174 # start unless the config names one, so a list outlives neither a restart nor
15175 # another installation.
15176 15 ▶sub _geo_lookup_sig :Protected ($self, $place) {
Subroutine _geo_lookup_sig: called CC=1 SCAR=0.0
15177 15 return hmac_sha256_hex(encode('UTF-8', "geo-lookup\0$place"), $self->app->secrets->[0]);
15178 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15179  
15180 # _geo_boundary_sig($self, $level, $point) -> $hex
15181 #
15182 # The same for a point whose outline the map page lists. Its own prefix, so a
15183 # place's signature is never a point's.
15184 1 ▶sub _geo_boundary_sig :Protected ($self, $level, $point) {
Subroutine _geo_boundary_sig: called CC=1 SCAR=0.0
15185 1 return hmac_sha256_hex(encode('UTF-8', "geo-boundary\0$level\0$point"), $self->app->secrets->[0]);
15186 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15187  
15188 # ---------------------------------------------------------------------------
15189 # POST /geo/boundary point=<lat,lon>&level=<level>&sig=<sig>[&online=0]
15190 #
15191 # One point's outline, for the map page's progress bar: found as the map would
15192 # find it, and remembered at once, so a run that is cancelled keeps what it
15193 # found. The point must carry the signature the map page gave it, or any page
15194 # on the web could have this server send coordinates to OpenStreetMap.
15195 # online=0 asks nothing, after OpenStreetMap has failed once.
15196 #
15197 # Replies 200 JSON:
15198 # { point, status => 'found' | 'nowhere' | 'held', stored => 0|1,
15199 # online_failed => 0|1, name }
15200 # 'nowhere' is a point in no area of the level (at sea); 'held' could not be settled now
15201 # and is asked again next time.
15202 # 400 JSON { error } without point= or sig=, or with an unknown level=;
15203 # 403 JSON { error } for a bad sig=.
15204 # ---------------------------------------------------------------------------
15205 2 ▶sub geo_boundary ($self) {
Subroutine geo_boundary: called CC=14 SCAR=39.0
Pod undocumented
15206 2 ▶ my $point = $self->param('point') // '';
Condition100%2/2
$self->param("point") // ""
l!l
11
MC/DC100%1/1
$self->param("point") // ""
$self->param("point")
Truth table100%2/2
A
A= $self->param("point")
Aresult
11
00
15207 2 ▶ my $sig = $self->param('sig') // '';
Condition100%2/2
$self->param("sig") // ""
l!l
11
MC/DC100%1/1
$self->param("sig") // ""
$self->param("sig")
Truth table100%2/2
A
A= $self->param("sig")
Aresult
11
00
15208 2 ▶ my $level = _map_bounds_level($self->param('level') // 'county');
Condition50%1/2
$self->param("level") // "county"
l!l
02
MC/DC0%0/1
$self->param("level") // "county"
$self->param("level")
Truth table50%1/2
A
A= $self->param("level")
Aresult
11
00
15209  
15210 2 ▶ return $self->render(json => { error => $self->_i18n('error_geo_boundary_point') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $point and length $sig and defined $level 1 1 2
Condition66%4/6
length $point and length $sig and defined $level
!ll&&!rl&&r
101
length $point and length $sig
!ll&&!rl&&r
101
MC/DC33%1/3
length $point and length $sig and defined $level
length $point length $sig defined $level
Truth table50%2/4
A and B and C
A= length $pointB= length $sigC= defined $level
ABCresult
0XX0
10X0
1100
1111
15211 unless length($point) && length($sig) && defined($level);
15212 1 ▶ return $self->render(json => { error => $self->_i18n('error_geo_boundary_unsigned') }, status => 403)
Branch: 1 branch
BranchTrueFalseTotal
unless secure_compare($sig, $self->_geo_boundary_sig($level, $point)) 1 0 1
15213 unless secure_compare($sig, $self->_geo_boundary_sig($level, $point));
15214  
15215 0 ▶ my $online = ($self->param('online') // 1) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('online') // 1 ? : 0 0 0
Condition0%0/2
$self->param("online") // 1
l!l
00
MC/DC0%0/1
$self->param("online") // 1
$self->param("online")
Truth table0%0/2
A
A= $self->param("online")
Aresult
11
00
15216 0 my $answer = eval { $self->_map_boundary($level, $online)->lookup_point($point) };
15217 0 ▶ return $self->render(json => { error => $self->_i18n('error_geo_boundary_point') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $answer 0 0 0
15218 unless $answer;
15219  
15220 return $self->render(json => {
15221 point => $point,
15222 status => $answer->{status},
15223 stored => ($answer->{status} eq 'held' ? 0 : 1),
15224 online_failed => (($answer->{status} eq 'held' && $answer->{asked}) ? 1 : 0),
15225 name => $answer->{name},
15226 0 ▶ });
Branch: 2 branches
BranchTrueFalseTotal
$answer->{'status'} eq 'held' ? : 0 0 0
$answer->{'status'} eq 'held' && $answer->{'asked'} ? : 0 0 0
Condition0%0/3
$answer->{"status"} eq "held" and $answer->{"asked"}
!ll&&!rl&&r
000
MC/DC0%0/2
$answer->{"status"} eq "held" and $answer->{"asked"}
$answer->{"status"} eq "held" $answer->{"asked"}
Truth table0%0/3
A and B
A= $answer->{"status"} eq "held"B= $answer->{"asked"}
ABresult
0X0
100
111
15227 }
15228  
15229 # ---------------------------------------------------------------------------
15230 # POST /geo/lookup place=<place>&sig=<sig>[&online=0]
15231 #
15232 # One place, for the map page's progress bar: looked up as the map would, and
15233 # its answer saved in the shared place cache straight away, so a run that is
15234 # cancelled or interrupted keeps every place it found. The place must carry the
15235 # signature the map page gave it. online=0 keeps the lookup on this machine;
15236 # the page sends it once OpenStreetMap has failed, so that each place left does
15237 # not wait for it again.
15238 #
15239 # Replies 200 JSON:
15240 # { place, status => 'found' | 'not_found' | 'held' | 'refused',
15241 # stored => 0|1, online_failed => 0|1, messages => [ text ... ] }
15242 # 'held' is a place that could not be looked up now (OpenStreetMap did not
15243 # answer, or the geocoder is missing); it is not remembered, so the next map
15244 # asks again. stored says that the answer is in the cache: a found or
15245 # not-found place the store refused to keep is 0.
15246 # 400 JSON { error } without place= or sig=; 403 JSON { error } for a bad sig=.
15247 # ---------------------------------------------------------------------------
15248 9 ▶sub geo_lookup ($self) {
Subroutine geo_lookup: called CC=20 SCAR=32.0
Pod documented
15249 9 ▶ my $place = $self->param('place') // '';
Condition100%2/2
$self->param("place") // ""
l!l
72
MC/DC100%1/1
$self->param("place") // ""
$self->param("place")
Truth table100%2/2
A
A= $self->param("place")
Aresult
11
00
15250 9 ▶ my $sig = $self->param('sig') // '';
Condition100%2/2
$self->param("sig") // ""
l!l
63
MC/DC100%1/1
$self->param("sig") // ""
$self->param("sig")
Truth table100%2/2
A
A= $self->param("sig")
Aresult
11
00
15251  
15252 9 ▶ return $self->render(json => { error => $self->_i18n('error_geo_lookup_place') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $place and length $sig 3 6 9
Condition100%3/3
length $place and length $sig
!ll&&!rl&&r
216
MC/DC100%2/2
length $place and length $sig
length $place length $sig
Truth table100%3/3
A and B
A= length $placeB= length $sig
ABresult
0X0
100
111
15253 unless length($place) && length($sig);
15254 6 ▶ return $self->render(json => { error => $self->_i18n('error_geo_lookup_unsigned') }, status => 403)
Branch: 1 branch
BranchTrueFalseTotal
unless secure_compare($sig, $self->_geo_lookup_sig($place)) 3 3 6
15255 unless secure_compare($sig, $self->_geo_lookup_sig($place));
15256  
15257 3 my $cfg = $self->app->config;
15258 3 ▶ my $geocode = $self->_map_geocoder(($self->param('online') // 1) ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$self->param('online') // 1 ? : 3 0 3
Condition50%1/2
$self->param("online") // 1
l!l
03
MC/DC0%0/1
$self->param("online") // 1
$self->param("online")
Truth table50%1/2
A
A= $self->param("online")
Aresult
11
00
15259 3 my $models = $self->_read_models;
15260 3 my $region = _map_region($cfg);
15261  
15262 3 ▶ my $result = $geocode->resolve_values(
Branch: 1 branch
BranchTrueFalseTotal
defined $region ? : 0 3 3
15263 [ $place ],
15264 cache => Database::BI::Model::Geocode->shared_cache_from_models($models),
15265 (defined($region) ? (region => $region) : ()),
15266 max => 1,
15267 );
15268  
15269 my $status = $result->{points}{$place} ? 'found'
15270 1 ▶ : (grep { $_ eq $place } @{ $result->{unresolved} }) ? 'not_found'
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ eq $place;} @{$$result{'skipped'};}) ? : 0 0 0
15271 0 ▶ : (grep { $_ eq $place } @{ $result->{skipped} }) ? 'refused'
Branch: 2 branches
BranchTrueFalseTotal
$result->{'points'}{$place} ? : 2 1 3
grep({$_ eq $place;} @{$$result{'unresolved'};}) ? : 1 0 1
15272 : 'held';
15273  
15274 # A place another tab answered meanwhile is in the cache already.
15275 3 ▶ my $stored = ($status eq 'found' || $status eq 'not_found') && !$result->{counts}{attempted};
Condition66%4/6
($status eq 'found' || $status eq 'not_found') && !$result->{'counts'}{'attempted'}
!ll&&!rl&&r
021
$status eq "found" or $status eq "not_found"
l!l&&r!l&&!r
210
MC/DC33%1/3
($status eq 'found' || $status eq 'not_found') && !$result->{'counts'}{'attempted'}
$status eq "found" $status eq "not_found" !$result->{'counts'}{'attempted'}
Truth table60%3/5
A or B && not(C)
A= $status eq "found"B= $status eq "not_found"C= !$result->{'counts'}{'attempted'}
ABCresult
00X0
1X00
0100
1X11
0111
15276  
15277 3 ▶ if ($result->{counts}{attempted} && $status ne 'held') {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{"counts"}{"attempted"} and $status ne "held") 2 1 3
Condition66%2/3
$result->{"counts"}{"attempted"} and $status ne "held"
!ll&&!rl&&r
102
MC/DC50%1/2
$result->{"counts"}{"attempted"} and $status ne "held"
$result->{"counts"}{"attempted"} $status ne "held"
Truth table66%2/3
A and B
A= $result->{"counts"}{"attempted"}B= $status ne "held"
ABresult
0X0
100
111
15278 2 my $backend = $result->{backend};
15279 $stored = $self->_write_models(Database::BI::Model::Geocode->models_with_shared_cache(
15280 2 ▶ $models, { $place => $result->{cache}{$place} },
Branch: 2 branches
BranchTrueFalseTotal
$self->_write_models('Database::BI::Model::Geocode'->models_with_shared_cache($models, {$place, $result->{'cache'}{$place}}, defined $backend ? ('backend', $backend) : (), 'built', _iso8601_utc())) ? : 2 0 2
defined $backend ? : 1 1 2
15281 (defined($backend) ? (backend => $backend) : ()),
15282 built => _iso8601_utc(),
15283 )) ? 1 : 0;
15284 }
15285  
15286 0 my @messages = map { $_->{text} } grep {
15287 2 $_->{key} ne 'warn_map_geocoder_unavailable_data'
15288 3 } @{ $result->{messages} };
15289  
15290 return $self->render(json => {
15291 place => $place,
15292 status => $status,
15293 stored => $stored ? 1 : 0,
15294 3 ▶ online_failed => (grep { $_->{key} eq 'warn_map_geocoder_online_failed' } @{ $result->{messages} }) ? 1 : 0,
Branch: 2 branches
BranchTrueFalseTotal
$stored ? : 3 0 3
grep({$_->{'key'} eq 'warn_map_geocoder_online_failed';} @{$$result{'messages'};}) ? : 0 3 3
15295 messages => \@messages,
15296 });
15297 }
15298  
15299 # _map_popup($heading, \@rows, \@columns, $limit, $more_url) -> $html
15300 #
15301 # The popup for one marker: what it is, how many rows it stands for, and the
15302 # rows themselves. A value every row shares is said once, as "Column: value";
15303 # the columns that differ are a small table of at most $limit rows, in a box
15304 # that scrolls, so a place with many rows does not cover the map. The rest
15305 # are counted, with a link to them in the table when $more_url is given.
15306 # Leaflet treats a popup string as HTML, and a value out of a user's file is
15307 # not markup, so every value is escaped here.
15308 158 ▶sub _map_popup {
Subroutine _map_popup: called CC=15 SCAR=27.1
15309 158 my ($heading, $rows, $columns, $limit, $more_url) = @_;
15310  
15311 158 ▶ my @rows = grep { ref($_) eq 'HASH' } @{ ref($rows) eq 'ARRAY' ? $rows : [] };
Branch: 1 branch
BranchTrueFalseTotal
ref $rows eq 'ARRAY' ? : 155 3 158
15312 158 ▶ my @cols = grep { defined($_) && !ref($_) && length($_) } @{ ref($columns) eq 'ARRAY' ? $columns : [] };
Branch: 1 branch
BranchTrueFalseTotal
ref $columns eq 'ARRAY' ? : 155 3 158
Condition100%6/6
defined $_ && !ref($_) && length $_
!ll&&!rl&&r
41239
defined $_ and not ref $_
!ll&&!rl&&r
22240
MC/DC100%3/3
defined $_ && !ref($_) && length $_
defined $_ not ref $_ length $_
Truth table100%4/4
A and not(B) && C
A= defined $_B= not ref $_C= length $_
ABCresult
0XX0
10X0
1100
1111
15313 158 $limit = _map_limit($limit, $DEFAULT_MAP_POPUP_ROWS);
15314 158 ▶ my $cell = sub { my $v = $_[0]->{ $_[1] }; (defined($v) && !ref($v)) ? $v : '' };
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
defined $v && !ref($v) ? : 201234 8 201242
Condition100%3/3
defined $v and not ref $v
!ll&&!rl&&r
35201234
MC/DC100%2/2
defined $v and not ref $v
defined $v not ref $v
Truth table100%3/3
A and not(B)
A= defined $vB= not ref $v
ABresult
0X0
100
111
15315  
15316 158 ▶ my @lines = '<strong>' . xml_escape($heading // '') . '</strong>';
Condition100%2/2
$heading // ""
l!l
1562
MC/DC100%1/1
$heading // ""
$heading
Truth table100%2/2
A
A= $heading
Aresult
11
00
15317 158 ▶ push @lines, scalar(@rows) . ' rows' if @rows > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @rows > 1 39 119 158
15318  
15319 # The same in every row, or not.
15320 158 my (@shared, @differ);
15321 158 for my $col (@cols) {
15322 239 my %seen = map { $cell->($_, $col) => 1 } @rows;
15323 239 ▶ if (keys(%seen) > 1) { push @differ, $col }
Branch: 2 branches
BranchTrueFalseTotal
if (keys %seen > 1) { } 47 192 239
elsif (@rows) { } 191 1 192
15324 191 elsif (@rows) { push @shared, [ $col, $cell->($rows[0], $col) ] }
15325 }
15326 186 push @lines, map { xml_escape($_->[0]) . ': ' . xml_escape($_->[1]) }
15327 158 grep { length $_->[1] } @shared;
15328  
15329 158 my $html = join('<br>', @lines);
15330 158 ▶ return $html unless @differ;
Branch: 1 branch
BranchTrueFalseTotal
unless @differ 121 37 158
15331  
15332 # The box keeps its size and scroll inline, one style a marker, so a page
15333 # without the stylesheet still cannot be covered; the cells' spacing is
15334 # .bi-map-popup-rows in the page's stylesheet, not repeated in every cell.
15335 37 ▶ my @shown = @rows > $limit ? @rows[0 .. $limit - 1] : @rows;
Branch: 1 branch
BranchTrueFalseTotal
@rows > $limit ? : 20 17 37
15336 $html .= '<div class="bi-map-popup-rows" style="max-height:14em;overflow:auto">'
15337 47 . '<table><tr>' . join('', map { '<th>' . xml_escape($_) . '</th>' } @differ) . '</tr>'
15338 . join('', map {
15339 37 my $row = $_;
15340 236 '<tr>' . join('', map { '<td>' . xml_escape($cell->($row, $_)) . '</td>' } @differ) . '</tr>';
15341 } @shown)
15342 . '</table></div>';
15343  
15344 37 ▶ if (my $more = @rows - @shown) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $more = @rows - @shown) 20 17 37
15345 20 ▶ $html .= "<div>and $more more"
Branch: 1 branch
BranchTrueFalseTotal
defined $more_url && length $more_url ? : 4 16 20
Condition100%3/3
defined $more_url and length $more_url
!ll&&!rl&&r
1064
MC/DC100%2/2
defined $more_url and length $more_url
defined $more_url length $more_url
Truth table100%3/3
A and B
A= defined $more_urlB= length $more_url
ABresult
0X0
100
111
15346 . ((defined($more_url) && length($more_url))
15347 ? ': <a href="' . xml_escape($more_url) . '">show all ' . scalar(@rows) . ' in the table</a>'
15348 : '')
15349 . '</div>';
15350 }
15351  
15352 37 return $html;
15353 }
15354  
15355 # _map_size_range($records, \@markers, $col) -> ($min, $max)
15356 #
15357 # The numeric range of the bubble-size column across the markers that will be
15358 # drawn, or an empty list when the column is absent or has no numeric values.
15359 47 ▶sub _map_size_range {
Subroutine _map_size_range: called CC=11 SCAR=24.1
15360 47 my ($records, $markers, $col) = @_;
15361 47 ▶ return () unless defined($col) && length($col);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col and length $col 45 2 47
Condition100%3/3
defined $col and length $col
!ll&&!rl&&r
1442
MC/DC100%2/2
defined $col and length $col
defined $col length $col
Truth table100%3/3
A and B
A= defined $colB= length $col
ABresult
0X0
100
111
15362  
15363 2 my ($min, $max);
15364 2 for my $marker (@$markers) {
15365 6 my $row = $records->[ $marker->{first_row} ];
15366 6 ▶ next unless defined $row;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row 1 5 6
15367 5 ▶ my $value = _numeric_cell($row->{$col} // '');
Condition100%2/2
$row->{$col} // ""
l!l
41
MC/DC100%1/1
$row->{$col} // ""
$row->{$col}
Truth table100%2/2
A
A= $row->{$col}
Aresult
11
00
15368 5 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 3 2 5
15369 2 ▶ $min = $value if !defined($min) || $value < $min;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $min or $value < $min 1 1 2
Condition66%2/3
not defined $min or $value < $min
l!l&&r!l&&!r
101
MC/DC50%1/2
not defined $min or $value < $min
not defined $min $value < $min
Truth table66%2/3
not(A) or B
A= not defined $minB= $value < $min
ABresult
1X1
011
000
15370 2 ▶ $max = $value if !defined($max) || $value > $max;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $max or $value > $max 2 0 2
Condition66%2/3
not defined $max or $value > $max
l!l&&r!l&&!r
110
MC/DC0%0/2
not defined $max or $value > $max
not defined $max $value > $max
Truth table66%2/3
not(A) or B
A= not defined $maxB= $value > $max
ABresult
1X1
011
000
15371 }
15372  
15373 2 return ($min, $max);
15374 }
15375  
15376 # _map_radius($value, $min, $max) -> $pixels
15377 #
15378 # A bubble radius for one marker: 6..30 px across the plotted range, and the
15379 # midpoint for a column that is constant or has no numeric value. Pixels, not
15380 # metres: a circle over the same place must not grow as the reader zooms in.
15381 11 ▶sub _map_radius {
Subroutine _map_radius: called CC=7 SCAR=19.5
15382 11 my ($value, $min, $max) = @_;
15383  
15384 11 ▶ return 10 unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 10 11
15385 10 ▶ return 10 unless defined($min) && defined($max) && $max > $min;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $min and defined $max and $max > $min 3 7 10
Condition83%5/6
defined $min and defined $max and $max > $min
!ll&&!rl&&r
127
defined $min and defined $max
!ll&&!rl&&r
109
MC/DC66%2/3
defined $min and defined $max and $max > $min
defined $min defined $max $max > $min
Truth table75%3/4
A and B and C
A= defined $minB= defined $maxC= $max > $min
ABCresult
0XX0
10X0
1100
1111
15386  
15387 7 my $fraction = ($value - $min) / ($max - $min);
15388 7 ▶ $fraction = 0 if $fraction < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $fraction < 0 1 6 7
15389 7 ▶ $fraction = 1 if $fraction > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $fraction > 1 1 6 7
15390  
15391 7 return int(6 + $fraction * 24 + 0.5);
15392 }
15393  
15394 # _map_limit($value, $default) -> $integer
15395 #
15396 # A positive integer from a config value or request parameter, or the default.
15397 # An absent, empty or nonsensical map setting is an operator's typo, not a data
15398 # error, so the page falls back instead of refusing.
15399 400 ▶sub _map_limit {
Subroutine _map_limit: called CC=4 SCAR=13.9
15400 400 my ($value, $default) = @_;
15401  
15402 400 ▶ return $default unless defined($value) && ($value =~ /\A\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/) && ($value > 0);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value =~ /\A\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u and $value > 0 264 136 400
Condition100%6/6
defined $value and $value =~ /\A\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u and $value > 0
!ll&&!rl&&r
2613136
defined $value and $value =~ /\A\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u
!ll&&!rl&&r
24417139
MC/DC100%3/3
defined $value and $value =~ /\A\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u and $value > 0
defined $value $value =~ /\A\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u $value > 0
Truth table100%4/4
A and B and C
A= defined $valueB= $value =~ /\A\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/uC= $value > 0
ABCresult
0XX0
10X0
1100
1111
15403  
15404 136 return $value + 0;
15405 }
15406  
15407 # _parse_color($str) -> $color_or_undef
15408 #
15409 # Accepts a lowercase CSS named color from a fixed whitelist, or a hex color
15410 # string in #rgb or #rrggbb form. Returns the normalised lowercase string or
15411 # undef when the input is invalid.
15412 193 ▶sub _parse_color {
Subroutine _parse_color: called CC=6 SCAR=17.9
15413 193 my ($c) = @_;
15414 193 ▶ return undef unless defined($c) && length($c);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $c and length $c 173 20 193
Condition100%3/3
defined $c and length $c
!ll&&!rl&&r
117220
MC/DC100%2/2
defined $c and length $c
defined $c length $c
Truth table100%3/3
A and B
A= defined $cB= length $c
ABresult
0X0
100
111
15415 20 $c = lc $c;
15416 20 ▶ return $c if $NAMED_COLORS{$c};
Branch: 1 branch
BranchTrueFalseTotal
if $NAMED_COLORS{$c} 3 17 20
15417 17 ▶ return $c if $c =~ /\A#[0-9a-f]{3}\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $c =~ /\A#[0-9a-f]{3}\z/u 2 15 17
15418 15 ▶ return $c if $c =~ /\A#[0-9a-f]{6}\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $c =~ /\A#[0-9a-f]{6}\z/u 1 14 15
15419 14 return undef;
15420 }
15421  
15422 # _parse_color_rules(\@raw_rules, $default_raw) -> (\@rules, $default_color)
15423 #
15424 # Parses the ?color_rule=op:threshold:color repeatable param list and the
15425 # optional ?color_default=color param into a structured rules array and a
15426 # fallback colour. Invalid rule entries are silently dropped.
15427 59 ▶sub _parse_color_rules {
Subroutine _parse_color_rules: called CC=10 SCAR=23.0
15428 59 my ($raw_rules, $default_raw) = @_;
15429 59 ▶ my $default_color = _parse_color($default_raw // '') // $DEFAULT_MARKER_COLOR;
Condition100%5/5
_parse_color($default_raw // "") // $DEFAULT_MARKER_COLOR
l!l&&r!l&&!r
1553
$default_raw // ""
l!l
581
MC/DC100%2/2
_parse_color($default_raw // "") // $DEFAULT_MARKER_COLOR
_parse_color($default_raw // "") $DEFAULT_MARKER_COLOR
MC/DC100%1/1
$default_raw // ""
$default_raw
Truth table100%3/3
A // B
A= _parse_color($default_raw // "")B= $DEFAULT_MARKER_COLOR
ABresult
1X1
011
000
Truth table100%2/2
A
A= $default_raw
Aresult
11
00
15430 59 my @rules;
15431 59 ▶ for my $raw (@{ $raw_rules // [] }) {
Condition100%2/2
$raw_rules // []
l!l
581
MC/DC100%1/1
$raw_rules // []
$raw_rules
Truth table100%2/2
A
A= $raw_rules
Aresult
11
00
15432 7 my ($op, $val, $color_str) = split /:/, $raw, 3;
15433 7 ▶ next unless defined($op) && defined($val) && defined($color_str);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $op and defined $val and defined $color_str 2 5 7
Condition83%5/6
defined $op and defined $val and defined $color_str
!ll&&!rl&&r
115
defined $op and defined $val
!ll&&!rl&&r
106
MC/DC66%2/3
defined $op and defined $val and defined $color_str
defined $op defined $val defined $color_str
Truth table75%3/4
A and B and C
A= defined $opB= defined $valC= defined $color_str
ABCresult
0XX0
10X0
1100
1111
15434 5 $op = lc $op;
15435 5 ▶ next unless $op =~ /\A(?:gt|ge|lt|le|eq|ne)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $op =~ /\A(?:gt|ge|lt|le|eq|ne)\z/u 1 4 5
15436 4 my $color = _parse_color($color_str);
15437 4 ▶ next unless defined $color;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $color 2 2 4
15438 2 push @rules, { op => $op, val => $val, color => $color };
15439 }
15440 59 return (\@rules, $default_color);
15441 }
15442  
15443 # _map_colour_entries($color_col, \@rules, $default, $is_series) -> @entries
15444 #
15445 # The colour key of a map, as { color, label, group }: one entry for each rule,
15446 # and Other for the default colour. A series (series= with a scheme) is
15447 # listed by value, with no Other: its values past the palette's two cycles
15448 # take a palette colour but are not listed. group names the entry for
15449 # _color_rule_index's answer ("rule<N>", or "other"), which is how HTML::OSM
15450 # lists only the entries in view.
15451 7 ▶sub _map_colour_entries {
Subroutine _map_colour_entries: called CC=12 SCAR=25.0
15452 7 my ($color_col, $rules, $default, $is_series) = @_;
15453  
15454 7 my %op_label = (gt => '>', ge => '>=', lt => '<', le => '<=', eq => '=', ne => '!=');
15455 7 my @entries;
15456 7 ▶ $rules = [] unless ref($rules) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rules eq "ARRAY" 1 6 7
15457 7 for my $index (0 .. $#{$rules}) {
15458 10 my $rule = $rules->[$index];
15459 10 ▶ next unless ref($rule) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rule eq "HASH" 2 8 10
15460 8 ▶ my $val = $rule->{val} // '';
Condition50%1/2
$rule->{"val"} // ""
l!l
80
MC/DC0%0/1
$rule->{"val"} // ""
$rule->{"val"}
Truth table50%1/2
A
A= $rule->{"val"}
Aresult
11
00
15461 push @entries, {
15462 color => $rule->{color},
15463 label => $is_series
15464 ? (length($val) ? $val : '(blank)')
15465 8 ▶ : "$color_col " . ($op_label{ $rule->{op} // '' } // $rule->{op} // '') . " $val",
Branch: 2 branches
BranchTrueFalseTotal
$is_series ? : 5 3 8
length $val ? : 4 1 5
Condition57%4/7
($op_label{$rule->{"op"} // ""} // $rule->{"op"}) // ""
l!l
30
$op_label{$rule->{"op"} // ""} // $rule->{"op"}
l!l&&r!l&&!r
210
$rule->{"op"} // ""
l!l
30
MC/DC0%0/2
($op_label{$rule->{"op"} // ""} // $rule->{"op"}) // ""
$op_label{$rule->{"op"} // ""} $rule->{"op"}
MC/DC0%0/1
$rule->{"op"} // ""
$rule->{"op"}
Truth table66%2/3
A // B
A= $op_label{$rule->{"op"} // ""}B= $rule->{"op"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $rule->{"op"}
Aresult
11
00
15466 group => "rule$index",
15467 };
15468 }
15469 7 ▶ push @entries, { color => $default, label => 'Other', group => 'other' }
Branch: 1 branch
BranchTrueFalseTotal
if @entries and not $is_series 2 5 7
Condition100%3/3
@entries and not $is_series
!ll&&!rl&&r
322
MC/DC100%2/2
@entries and not $is_series
@entries not $is_series
Truth table100%3/3
A and not(B)
A= @entriesB= not $is_series
ABresult
0X0
100
111
15470 if @entries && !$is_series;
15471 7 return @entries;
15472 }
15473  
15474 # _map_key($self, $color_col, \@rules, $default, $is_series, $size_col, \@range)
15475 # -> (legend => \@entries, legend_title => $title, legend_empty => $text)
15476 #
15477 # What HTML::OSM is given to draw a map's key: the colour entries, each with
15478 # its group so the key lists only what is in view, then two or three bubble
15479 # sizes when a size column is set (those are always listed: they say what a
15480 # size means, wherever the reader is). The title is the colour column, or
15481 # the size column when there is no colour; with both, each size is labelled
15482 # with its column. The colours go to HTML::OSM as hex, which is all it takes.
15483 49 ▶sub _map_key :Protected ($self, $color_col, $rules, $default, $is_series, $size_col, $range) {
Subroutine _map_key: called CC=12 SCAR=24.9
15484 my @legend = map {
15485 49 { label => $_->{label}, colour => _color_hex($_->{color}), group => $_->{group} }
15486 5 ▶ } (length($color_col) ? _map_colour_entries($color_col, $rules, $default, $is_series) : ());
Branch: 1 branch
BranchTrueFalseTotal
length $color_col ? : 3 46 49
15487  
15488 49 ▶ my ($min, $max) = @{ $range // [] };
Condition100%2/2
$range // []
l!l
481
MC/DC100%1/1
$range // []
$range
Truth table100%2/2
A
A= $range
Aresult
11
00
15489 49 ▶ if (length($size_col) && defined($min)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $size_col and defined $min) 2 47 49
Condition100%3/3
length $size_col and defined $min
!ll&&!rl&&r
4612
MC/DC100%2/2
length $size_col and defined $min
length $size_col defined $min
Truth table100%3/3
A and B
A= length $size_colB= defined $min
ABresult
0X0
100
111
15490 2 ▶ my @values = ($max > $min) ? ($min, ($min + $max) / 2, $max) : ($min);
Branch: 1 branch
BranchTrueFalseTotal
$max > $min ? : 1 1 2
15491 2 for my $value (@values) {
15492 4 my $text = 0 + sprintf('%.4g', $value);
15493 4 ▶ push @legend, {
Branch: 2 branches
BranchTrueFalseTotal
@legend && length $color_col ? : 0 4 4
length $color_col ? : 0 4 4
Condition66%2/3
@legend and length $color_col
!ll&&!rl&&r
220
MC/DC0%0/2
@legend and length $color_col
@legend length $color_col
Truth table66%2/3
A and B
A= @legendB= length $color_col
ABresult
0X0
100
111
15494 label => (@legend && length($color_col) ? "$size_col $text" : "$text"),
15495 colour => (length($color_col) ? $MAP_SIZE_KEY_COLOR : _color_hex($default)),
15496 radius => _map_radius($value, $min, $max),
15497 };
15498 }
15499 }
15500  
15501 49 ▶ return () unless @legend;
Branch: 1 branch
BranchTrueFalseTotal
unless @legend 45 4 49
15502 return (
15503 4 ▶ legend => \@legend,
Branch: 1 branch
BranchTrueFalseTotal
length $color_col ? : 2 2 4
15504 legend_title => (length($color_col) ? $color_col : $size_col),
15505 legend_empty => $self->_i18n('map_legend_empty'),
15506 );
15507 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15508  
15509 # _color_rule_index($value, \@rules) -> $index | undef
15510 #
15511 # The index of the first rule that matches $value, or undef when none does
15512 # (the marker takes the default colour). _apply_color_rule says the colour.
15513 28 ▶sub _color_rule_index {
Subroutine _color_rule_index: called CC=24 SCAR=31.9
15514 28 my ($value, $rules) = @_;
15515 28 ▶ $value //= '';
Condition100%2/2
$value //= ""
l!l
262
MC/DC100%1/1
$value //= ""
$value
Truth table100%2/2
A
A= $value
Aresult
11
00
15516 28 ▶ $rules = [] unless ref($rules) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rules eq "ARRAY" 2 26 28
15517 28 for my $index (0 .. $#{$rules}) {
15518 37 ▶ next unless ref($rules->[$index]) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rules->[$index] eq "HASH" 3 34 37
15519 34 my ($op, $threshold) = @{ $rules->[$index] }{qw(op val)};
15520 34 ▶ $op //= '';
Condition100%2/2
$op //= ""
l!l
331
MC/DC100%1/1
$op //= ""
$op
Truth table100%2/2
A
A= $op
Aresult
11
00
15521 34 ▶ $threshold //= '';
Condition50%1/2
$threshold //= ""
l!l
340
MC/DC0%0/1
$threshold //= ""
$threshold
Truth table50%1/2
A
A= $threshold
Aresult
11
00
15522 34 my $match;
15523 34 ▶ if ( $value =~ /\A-?\d+(?:\.\d+)?\z/ &&
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /\A-?\d+(?:\.\d+)?\z/u and $threshold =~ /\A-?\d+(?:\.\d+)?\z/u) { } 16 18 34
Condition100%3/3
$value =~ /\A-?\d+(?:\.\d+)?\z/u and $threshold =~ /\A-?\d+(?:\.\d+)?\z/u
!ll&&!rl&&r
16216
MC/DC100%2/2
$value =~ /\A-?\d+(?:\.\d+)?\z/u and $threshold =~ /\A-?\d+(?:\.\d+)?\z/u
$value =~ /\A-?\d+(?:\.\d+)?\z/u $threshold =~ /\A-?\d+(?:\.\d+)?\z/u
Truth table100%3/3
A and B
A= $value =~ /\A-?\d+(?:\.\d+)?\z/uB= $threshold =~ /\A-?\d+(?:\.\d+)?\z/u
ABresult
0X0
100
111
15524 $threshold =~ /\A-?\d+(?:\.\d+)?\z/) {
15525 16 my ($num_val, $num_thr) = ($value + 0, $threshold + 0);
15526 16 ▶ $match = ($op eq 'gt' && $num_val > $num_thr)
Condition87%29/33
$op eq 'gt' && $num_val > $num_thr || $op eq 'ge' && $num_val >= $num_thr || $op eq 'lt' && $num_val < $num_thr || $op eq 'le' && $num_val <= $num_thr || $op eq 'eq' && $num_val == $num_thr || $op eq 'ne' && $num_val != $num_thr
l!l&&r!l&&!r
925
$op eq "gt" and $num_val > $num_thr or $op eq "ge" and $num_val >= $num_thr or $op eq "lt" and $num_val < $num_thr or $op eq "le" and $num_val <= $num_thr or $op eq "eq" and $num_val == $num_thr
l!l&&r!l&&!r
817
$op eq "gt" and $num_val > $num_thr or $op eq "ge" and $num_val >= $num_thr or $op eq "lt" and $num_val < $num_thr or $op eq "le" and $num_val <= $num_thr
l!l&&r!l&&!r
718
$op eq "gt" and $num_val > $num_thr or $op eq "ge" and $num_val >= $num_thr or $op eq "lt" and $num_val < $num_thr
l!l&&r!l&&!r
529
$op eq "gt" and $num_val > $num_thr or $op eq "ge" and $num_val >= $num_thr
l!l&&r!l&&!r
4111
$op eq "gt" and $num_val > $num_thr
!ll&&!rl&&r
934
$op eq "ge" and $num_val >= $num_thr
!ll&&!rl&&r
1101
$op eq "lt" and $num_val < $num_thr
!ll&&!rl&&r
902
$op eq "le" and $num_val <= $num_thr
!ll&&!rl&&r
801
$op eq "eq" and $num_val == $num_thr
!ll&&!rl&&r
701
$op eq "ne" and $num_val != $num_thr
!ll&&!rl&&r
412
MC/DC66%8/12
$op eq 'gt' && $num_val > $num_thr || $op eq 'ge' && $num_val >= $num_thr || $op eq 'lt' && $num_val < $num_thr || $op eq 'le' && $num_val <= $num_thr || $op eq 'eq' && $num_val == $num_thr || $op eq 'ne' && $num_val != $num_thr
$op eq "gt" $num_val > $num_thr $op eq "ge" $num_val >= $num_thr $op eq "lt" $num_val < $num_thr $op eq "le" $num_val <= $num_thr $op eq "eq" $num_val == $num_thr $op eq "ne" $num_val != $num_thr
Truth table7%9/127
A and B or C and D or E and F or G and H or I and J || K and L
A= $op eq "gt"B= $num_val > $num_thrC= $op eq "ge"D= $num_val >= $num_thrE= $op eq "lt"F= $num_val < $num_thrG= $op eq "le"H= $num_val <= $num_thrI= $op eq "eq"J= $num_val == $num_thrK= $op eq "ne"L= $num_val != $num_thr
ABCDEFGHIJKLresult
11XXXXXXXXXX1
0X11XXXXXXXX1
1011XXXXXXXX1
0X0X11XXXXXX1
0X1011XXXXXX1
100X11XXXXXX1
101011XXXXXX1
0X0X0X11XXXX1
0X0X1011XXXX1
0X100X11XXXX1
0X101011XXXX1
100X0X11XXXX1
100X1011XXXX1
10100X11XXXX1
10101011XXXX1
0X0X0X0X11XX1
0X0X0X1011XX1
0X0X100X11XX1
0X0X101011XX1
0X100X0X11XX1
0X100X1011XX1
0X10100X11XX1
0X10101011XX1
100X0X0X11XX1
100X0X1011XX1
100X100X11XX1
100X101011XX1
10100X0X11XX1
10100X1011XX1
1010100X11XX1
1010101011XX1
0X0X0X0X0X111
0X0X0X0X10111
0X0X0X100X111
0X0X0X1010111
0X0X100X0X111
0X0X100X10111
0X0X10100X111
0X0X101010111
0X100X0X0X111
0X100X0X10111
0X100X100X111
0X100X1010111
0X10100X0X111
0X10100X10111
0X1010100X111
0X10101010111
100X0X0X0X111
100X0X0X10111
100X0X100X111
100X0X1010111
100X100X0X111
100X100X10111
100X10100X111
100X101010111
10100X0X0X111
10100X0X10111
10100X100X111
10100X1010111
1010100X0X111
1010100X10111
101010100X111
1010101010111
0X0X0X0X0X0X0
0X0X0X0X0X100
0X0X0X0X100X0
0X0X0X0X10100
0X0X0X100X0X0
0X0X0X100X100
0X0X0X10100X0
0X0X0X1010100
0X0X100X0X0X0
0X0X100X0X100
0X0X100X100X0
0X0X100X10100
0X0X10100X0X0
0X0X10100X100
0X0X1010100X0
0X0X101010100
0X100X0X0X0X0
0X100X0X0X100
0X100X0X100X0
0X100X0X10100
0X100X100X0X0
0X100X100X100
0X100X10100X0
0X100X1010100
0X10100X0X0X0
0X10100X0X100
0X10100X100X0
0X10100X10100
0X1010100X0X0
0X1010100X100
0X101010100X0
0X10101010100
100X0X0X0X0X0
100X0X0X0X100
100X0X0X100X0
100X0X0X10100
100X0X100X0X0
100X0X100X100
100X0X10100X0
100X0X1010100
100X100X0X0X0
100X100X0X100
100X100X100X0
100X100X10100
100X10100X0X0
100X10100X100
100X1010100X0
100X101010100
10100X0X0X0X0
10100X0X0X100
10100X0X100X0
10100X0X10100
10100X100X0X0
10100X100X100
10100X10100X0
10100X1010100
1010100X0X0X0
1010100X0X100
1010100X100X0
1010100X10100
101010100X0X0
101010100X100
10101010100X0
1010101010100
15527 || ($op eq 'ge' && $num_val >= $num_thr)
15528 || ($op eq 'lt' && $num_val < $num_thr)
15529 || ($op eq 'le' && $num_val <= $num_thr)
15530 || ($op eq 'eq' && $num_val == $num_thr)
15531 || ($op eq 'ne' && $num_val != $num_thr);
15532 } else {
15533 18 ▶ $match = ($op eq 'eq' && lc($value) eq lc($threshold))
Condition88%8/9
$op eq 'eq' && lc $value eq lc $threshold || $op eq 'ne' && lc $value ne lc $threshold
l!l&&r!l&&!r
7110
$op eq "eq" and lc $value eq lc $threshold
!ll&&!rl&&r
567
$op eq "ne" and lc $value ne lc $threshold
!ll&&!rl&&r
1001
MC/DC75%3/4
$op eq 'eq' && lc $value eq lc $threshold || $op eq 'ne' && lc $value ne lc $threshold
$op eq "eq" lc $value eq lc $threshold $op eq "ne" lc $value ne lc $threshold
Truth table57%4/7
A and B || C and D
A= $op eq "eq"B= lc $value eq lc $thresholdC= $op eq "ne"D= lc $value ne lc $threshold
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
15534 || ($op eq 'ne' && lc($value) ne lc($threshold));
15535 }
15536 34 ▶ return $index if $match;
Branch: 1 branch
BranchTrueFalseTotal
if $match 19 15 34
15537 }
15538 9 return undef;
15539 }
15540  
15541 # _apply_color_rule($value, \@rules, $default_color) -> $color
15542 #
15543 # Returns the first colour whose rule matches $value, or $default_color.
15544 # Numeric comparisons are used when both sides look like plain numbers.
15545 15 ▶sub _apply_color_rule {
Subroutine _apply_color_rule: called CC=2 SCAR=6.9
15546 15 my ($value, $rules, $default) = @_;
15547 15 my $index = _color_rule_index($value, $rules);
15548 15 ▶ return defined($index) ? $rules->[$index]{color} : $default;
Branch: 1 branch
BranchTrueFalseTotal
defined $index ? : 11 4 15
15549 }
15550  
15551 # _marker_icon($color) -> $data_uri
15552 #
15553 # Returns a data:image/svg+xml URI for a 32x32 teardrop pin icon whose fill is
15554 # $color. The icon anchor is [16,32] (HTML::OSM's hardcoded default), so the
15555 # path tip lands at the bottom centre of the bounding box.
15556 4 ▶sub _marker_icon {
Subroutine _marker_icon: called CC=2 SCAR=6.9
15557 4 my ($color) = @_;
15558 4 ▶ $color //= $DEFAULT_MARKER_COLOR;
Condition66%2/3
$color //= $DEFAULT_MARKER_COLOR
l!l&&r!l&&!r
310
MC/DC0%0/2
$color //= $DEFAULT_MARKER_COLOR
$color $DEFAULT_MARKER_COLOR
Truth table66%2/3
A //= B
A= $colorB= $DEFAULT_MARKER_COLOR
ABresult
1X1
011
000
15559  
15560 # Commas in path data avoid spaces that would need percent-encoding.
15561 4 my $svg =
15562 "<svg xmlns='http://www.w3.org/2000/svg' width='32' height='32' viewBox='0 0 32 32'>" .
15563 "<path d='M16,0C10,0,5,5,5,12C5,21,16,32,16,32C16,32,27,21,27,12C27,5,22,0,16,0Z'" .
15564 " fill='$color' stroke='#444' stroke-width='1.5'/>" .
15565 "<circle cx='16' cy='12' r='5' fill='white' opacity='0.65'/>" .
15566 "</svg>";
15567  
15568 # Minimal percent-encoding for a data: URI (RFC 2397).
15569 4 $svg =~ s/#/%23/g;
15570 4 $svg =~ s/</%3C/g;
15571 4 $svg =~ s/>/%3E/g;
15572 4 $svg =~ s/ /%20/g;
15573  
15574 4 return "data:image/svg+xml,$svg";
15575 }
15576  
15577 # _color_hex($color) -> $hex
15578 #
15579 # add_circle_marker() accepts hex colours only, while _parse_color() also
15580 # allows a fixed set of CSS names for the icon path. Translate the names so a
15581 # colour rule means the same thing on a bubble map as on a pin map.
15582 16 ▶sub _color_hex {
Subroutine _color_hex: called CC=5 SCAR=16.1
15583 16 my ($color) = @_;
15584  
15585 16 ▶ return $DEFAULT_MARKER_COLOR unless defined($color) && length($color);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $color and length $color 2 14 16
Condition100%3/3
defined $color and length $color
!ll&&!rl&&r
1114
MC/DC100%2/2
defined $color and length $color
defined $color length $color
Truth table100%3/3
A and B
A= defined $colorB= length $color
ABresult
0X0
100
111
15586 14 ▶ return $color if $color =~ /\A#[0-9a-f]{3}(?:[0-9a-f]{3})?\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $color =~ /\A#[0-9a-f]{3}(?:[0-9a-f]{3})?\z/u 11 3 14
15587  
15588 3 ▶ return $NAMED_COLOR_HEX{$color} // $DEFAULT_MARKER_COLOR;
Condition66%2/3
$NAMED_COLOR_HEX{$color} // $DEFAULT_MARKER_COLOR
l!l&&r!l&&!r
210
MC/DC0%0/2
$NAMED_COLOR_HEX{$color} // $DEFAULT_MARKER_COLOR
$NAMED_COLOR_HEX{$color} $DEFAULT_MARKER_COLOR
Truth table66%2/3
A // B
A= $NAMED_COLOR_HEX{$color}B= $DEFAULT_MARKER_COLOR
ABresult
1X1
011
000
15589 }
15590  
15591 # _iso8601_utc() -> $string
15592 #
15593 # When a geocode cache was built, in the form the model store records.
15594 23 ▶sub _iso8601_utc {
Subroutine _iso8601_utc: called CC=1 SCAR=0.0
15595 23 return Database::BI::Util::iso8601_utc();
15596 }
15597  
15598 # _catalog_entry($self, $mf, $analyses) -> \%entry
15599 #
15600 # Build one catalog entry for a Mojo::File data file.
15601 211 ▶sub _catalog_entry :Protected ($self, $mf, $analyses) {
Subroutine _catalog_entry: called CC=14 SCAR=27.2
15602 211 my $path = $mf->to_string;
15603 211 my $name = $mf->basename;
15604 211 ▶ my $size = -s $path // 0;
Condition50%1/2
-s $path // 0
l!l
2110
MC/DC0%0/1
-s $path // 0
-s $path
Truth table50%1/2
A
A= -s $path
Aresult
11
00
15605 211 ▶ my $mtime = (stat($path))[9] // 0;
Condition50%1/2
(stat $path)[9] // 0
l!l
2110
MC/DC0%0/1
(stat $path)[9] // 0
(stat $path)[9]
Truth table50%1/2
A
A= (stat $path)[9]
Aresult
11
00
15606  
15607 211 require POSIX;
15608 211 ▶ my $mtime_str = $mtime ? Database::BI::Util::minute_stamp(gmtime($mtime)) . ' UTC' : '';
Branch: 1 branch
BranchTrueFalseTotal
$mtime ? : 211 0 211
15609  
15610 # Find which analyses reference this file.
15611 # Normalize path separators so that Windows paths stored with backslashes
15612 # match Mojo::File paths that may use forward slashes, and vice versa.
15613 # Case-fold only the path portion on case-insensitive filesystems.
15614 211 my $use_ci = File::Spec->case_tolerant;
15615 211 (my $norm_path = $path) =~ s{\\}{/}g;
15616 211 ▶ $norm_path = lc $norm_path if $use_ci;
Branch: 1 branch
BranchTrueFalseTotal
if $use_ci 0 211 211
15617  
15618 211 my @refs;
15619 211 for my $aid (sort keys %$analyses) {
15620 145 my $a = $analyses->{$aid};
15621 145 ▶ for my $ds (@{ $a->{datasets} // [] }) {
Condition100%2/2
$a->{"datasets"} // []
l!l
11233
MC/DC100%1/1
$a->{"datasets"} // []
$a->{"datasets"}
Truth table100%2/2
A
A= $a->{"datasets"}
Aresult
11
00
15622 112 ▶ my $spec = $ds->{spec} // '';
Condition50%1/2
$ds->{"spec"} // ""
l!l
1120
MC/DC0%0/1
$ds->{"spec"} // ""
$ds->{"spec"}
Truth table50%1/2
A
A= $ds->{"spec"}
Aresult
11
00
15623 112 my $table_stem = $mf->basename; $table_stem =~ s/\.[^.]+\z//;
15624 112 (my $norm_spec = $spec) =~ s{\\}{/}g;
15625 112 ▶ $norm_spec = lc $norm_spec if $use_ci;
Branch: 1 branch
BranchTrueFalseTotal
if $use_ci 0 112 112
15626 112 ▶ if (CORE::index($norm_spec, $norm_path) >= 0 || CORE::index($spec, "table:$table_stem") == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (CORE::index($norm_spec, $norm_path) != -1 or CORE::index($spec, "table:$table_stem") == 0) 11 101 112
Condition66%2/3
CORE::index($norm_spec, $norm_path) != -1 or CORE::index($spec, "table:$table_stem") == 0
l!l&&r!l&&!r
011101
MC/DC50%1/2
CORE::index($norm_spec, $norm_path) != -1 or CORE::index($spec, "table:$table_stem") == 0
CORE::index($norm_spec, $norm_path) != -1 CORE::index($spec, "table:$table_stem") == 0
Truth table66%2/3
A or B
A= CORE::index($norm_spec, $norm_path) != -1B= CORE::index($spec, "table:$table_stem") == 0
ABresult
1X1
011
000
15627 11 push @refs, { id => $aid, name => $a->{name} };
15628 11 last;
15629 }
15630 }
15631 }
15632  
15633 # Derive a human-readable type from the extension.
15634 211 my ($ext) = ($name =~ /\.([^.]+)\z/);
15635 211 ▶ $ext = lc($ext // '');
Condition50%1/2
$ext // ""
l!l
2110
MC/DC0%0/1
$ext // ""
$ext
Truth table50%1/2
A
A= $ext
Aresult
11
00
15636 211 my %type_map = (
15637 csv => 'CSV file', tsv => 'TSV file', psv => 'PSV file',
15638 xml => 'XML file', xlsx => 'XLSX spreadsheet',
15639 sql => 'SQLite database', sqlite => 'SQLite database',
15640 sqlite3 => 'SQLite database', db => 'Berkeley DB / SQLite',
15641 );
15642 211 ▶ my $type = $type_map{$ext} // 'Data file';
Condition50%1/2
$type_map{$ext} // "Data file"
l!l
2110
MC/DC0%0/1
$type_map{$ext} // "Data file"
$type_map{$ext}
Truth table50%1/2
A
A= $type_map{$ext}
Aresult
11
00
15643  
15644 return {
15645 211 name => $name,
15646 path => $path,
15647 type => $type,
15648 size => $size,
15649 mtime_str => $mtime_str,
15650 analysis_count => scalar @refs,
15651 analyses => \@refs,
15652 };
15653 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15654  
15655 # GET /catalog
15656 19 ▶sub catalog_view ($self) {
Subroutine catalog_view: called CC=5 SCAR=16.4
Pod documented
15657 19 ▶ return if $self->buffer_is_cached;
Branch: 1 branch
BranchTrueFalseTotal
if $self->buffer_is_cached 0 19 19
15658 19 my $dir = _data_dir_for($self->app);
15659 19 my $analyses = $self->_read_analyses;
15660  
15661 19 my @entries;
15662 19 ▶ if (-d $dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $dir) 19 0 19
15663 19 my $ext_re = $EXT_RE;
15664 19 for my $mf ($dir->list->each) {
15665 209 ▶ next unless $mf->to_string =~ $ext_re;
Branch: 1 branch
BranchTrueFalseTotal
unless $mf->to_string =~ /$ext_re/u 0 209 209
15666 209 push @entries, $self->_catalog_entry($mf, $analyses);
15667 }
15668 }
15669  
15670 19 my ($platform, $language) = $self->_resolve_template;
15671 19 $self->render(
15672 handler => 'tt',
15673 template => "$platform/$language/catalog",
15674 format => 'html',
15675 title => 'Dataset catalog',
15676 catalog_entries => \@entries,
15677 language => $language,
15678 );
15679 }
15680  
15681 =head2 canvases_view
15682  
15683 C<GET /canvases> -- The saved canvases, as cards that open, select and delete,
15684 with Import canvas. The main navigation's Canvases link. The list is the one
15685 the home page shows (C<layouts/canvas_list.html.tt>); here it also says when
15686 there are none, and how to make one.
15687  
15688 =head3 API SPECIFICATION
15689  
15690 =head4 INPUT
15691  
15692 None.
15693  
15694 =head4 OUTPUT
15695  
15696 C<200> with the HTML page. The cards are drawn by the page from
15697 C<GET /api/analyses>.
15698  
15699 =cut
15700  
15701 2 ▶sub canvases_view ($self) {
Subroutine canvases_view: called CC=1 SCAR=0.0
Pod documented
15702 2 my ($platform, $language) = $self->_resolve_template;
15703 2 $self->render(
15704 handler => 'tt',
15705 template => "$platform/$language/canvases",
15706 format => 'html',
15707 title => 'Canvases',
15708 canvases_empty => 'There are no saved canvases yet. To make one, open a table and click New canvas..., or import a canvas from a file.',
15709 language => $language,
15710 );
15711 }
15712  
15713 # _share_secret($self) -> $secret_string
15714 #
15715 # The key share and embed tokens are signed with: config share_secret, else
15716 # one derived from the application's first secret. It used to fall back to a
15717 # fixed string, the same on every install, so anyone could sign a token for
15718 # any canvas, with any expiry, and read it without the password. The first
15719 # secret is random for each start unless config secrets sets it, so without
15720 # either a restart ends every link (_share_links_last says which). It is
15721 # derived, not the secret itself, so a token is never a signature that the
15722 # session cookie or a map list would also accept.
15723 73 ▶sub _share_secret :Protected ($self) {
Subroutine _share_secret: called CC=4 SCAR=13.9
15724 73 ▶ my $s = $self->app->config('share_secret') // '';
Condition100%2/2
$self->app->config("share_secret") // ""
l!l
1954
MC/DC100%1/1
$self->app->config("share_secret") // ""
$self->app->config("share_secret")
Truth table100%2/2
A
A= $self->app->config("share_secret")
Aresult
11
00
15725 73 ▶ return $s if !ref($s) && length $s;
Branch: 1 branch
BranchTrueFalseTotal
if not ref $s and length $s 18 55 73
Condition100%3/3
not ref $s and length $s
!ll&&!rl&&r
15418
MC/DC100%2/2
not ref $s and length $s
not ref $s length $s
Truth table100%3/3
not(A) and B
A= not ref $sB= length $s
ABresult
0X0
100
111
15726 55 require Digest::SHA;
15727 55 return Digest::SHA::hmac_sha256_hex('Database::BI share tokens', $self->app->secrets->[0]);
15728 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15729  
15730 # _share_links_last($self) -> 1 | 0
15731 #
15732 # Whether a share link outlives a restart: true when share_secret or secrets
15733 # is configured, so the key is the same next time.
15734 5 ▶sub _share_links_last :Protected ($self) {
Subroutine _share_links_last: called CC=6 SCAR=19.3
15735 5 ▶ my $s = $self->app->config('share_secret') // '';
Condition100%2/2
$self->app->config("share_secret") // ""
l!l
32
MC/DC100%1/1
$self->app->config("share_secret") // ""
$self->app->config("share_secret")
Truth table100%2/2
A
A= $self->app->config("share_secret")
Aresult
11
00
15736 5 my $secrets = $self->app->config('secrets');
15737 0 ▶ return (!ref($s) && length $s) || (ref($secrets) eq 'ARRAY' && @{$secrets}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
!ref($s) && length $s || ref $secrets eq 'ARRAY' && @{$secrets;} ? : 3 2 5
Condition55%5/9
not ref $s and length $s or ref $secrets eq "ARRAY" and @{$secrets;}
l!l&&r!l&&!r
302
not ref $s and length $s
!ll&&!rl&&r
023
ref $secrets eq "ARRAY" and @{$secrets;}
!ll&&!rl&&r
200
MC/DC25%1/4
not ref $s and length $s or ref $secrets eq "ARRAY" and @{$secrets;}
not ref $s length $s ref $secrets eq "ARRAY" @{$secrets;}
Truth table28%2/7
not(A) and B or C and D
A= not ref $sB= length $sC= ref $secrets eq "ARRAY"D= @{$secrets;}
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
15738 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15739  
15740 # _make_share_token($self, $id, $expires) -> $token_string
15741 #
15742 # Signs with HMAC-SHA256 using Digest::SHA (Perl core since 5.10).
15743 22 ▶sub _make_share_token :Protected ($self, $id, $expires) {
Subroutine _make_share_token: called CC=1 SCAR=0.0
15744 22 require Digest::SHA;
15745 22 require MIME::Base64;
15746 22 my $secret = $self->_share_secret;
15747 22 my $payload = "$id|$expires";
15748 22 my $hmac = Digest::SHA::hmac_sha256_hex($payload, $secret);
15749 22 return MIME::Base64::encode_base64url("$payload|$hmac");
15750 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15751  
15752 # _verify_share_token($self, $id, $token) -> 1 | undef
15753 62 ▶sub _verify_share_token :Protected ($self, $id, $token) {
Subroutine _verify_share_token: called CC=13 SCAR=25.7
15754 62 ▶ return undef unless defined $token && length $token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $token and length $token 2 60 62
Condition100%3/3
defined $token and length $token
!ll&&!rl&&r
1160
MC/DC100%2/2
defined $token and length $token
defined $token length $token
Truth table100%3/3
A and B
A= defined $tokenB= length $token
ABresult
0X0
100
111
15755 60 require MIME::Base64;
15756 60 my $decoded = eval { MIME::Base64::decode_base64url($token) };
15757 60 ▶ return undef unless defined $decoded;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $decoded 0 60 60
15758 60 my ($tid, $expires, $hmac) = split /\|/, $decoded, 3;
15759 60 ▶ return undef unless defined $tid && defined $expires && defined $hmac;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tid and defined $expires and defined $hmac 8 52 60
Condition83%5/6
defined $tid and defined $expires and defined $hmac
!ll&&!rl&&r
8052
defined $tid and defined $expires
!ll&&!rl&&r
2652
MC/DC66%2/3
defined $tid and defined $expires and defined $hmac
defined $tid defined $expires defined $hmac
Truth table75%3/4
A and B and C
A= defined $tidB= defined $expiresC= defined $hmac
ABCresult
0XX0
10X0
1100
1111
15760 52 ▶ return undef unless $tid eq $id;
Branch: 1 branch
BranchTrueFalseTotal
unless $tid eq $id 3 49 52
15761 49 ▶ return undef unless $expires =~ /\A\d+\z/ && $expires > time();
Branch: 1 branch
BranchTrueFalseTotal
unless $expires =~ /\A\d+\z/u and $expires > time 2 47 49
Condition100%3/3
$expires =~ /\A\d+\z/u and $expires > time
!ll&&!rl&&r
1147
MC/DC100%2/2
$expires =~ /\A\d+\z/u and $expires > time
$expires =~ /\A\d+\z/u $expires > time
Truth table100%3/3
A and B
A= $expires =~ /\A\d+\z/uB= $expires > time
ABresult
0X0
100
111
15762 47 require Digest::SHA;
15763 47 my $secret = $self->_share_secret;
15764 47 my $expected = Digest::SHA::hmac_sha256_hex("$id|$expires", $secret);
15765 47 ▶ return undef unless length($hmac) == length($expected);
Branch: 1 branch
BranchTrueFalseTotal
unless length $hmac == length $expected 2 45 47
15766 # Every character is compared, so the time taken says nothing about how
15767 # much of a guessed signature was right.
15768 45 my $diff = 0;
15769 45 $diff |= ord(substr($hmac, $_, 1)) ^ ord(substr($expected, $_, 1)) for 0 .. length($expected) - 1;
15770 45 ▶ return undef if $diff;
Branch: 1 branch
BranchTrueFalseTotal
if $diff 4 41 45
15771 41 return 1;
15772 10 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15773  
15774 # POST /api/analyses/:id/share
15775 10 ▶sub analyses_share ($self) {
Subroutine analyses_share: called CC=5 SCAR=16.1
Pod documented
15776 10 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
100
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
15777 10 ▶ return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 3 7 10
15778 unless $id =~ /\A[A-Za-z0-9]+\z/;
15779  
15780 7 my $analyses = $self->_read_analyses;
15781 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
15782 7 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 2 5 7
15783  
15784 5 my $expires = time() + $SHARE_TOKEN_TTL;
15785 5 my $token = $self->_make_share_token($id, $expires);
15786 5 my $url = $self->req->url->base->to_string . "/share/$id?token=" . url_escape($token);
15787  
15788 5 ▶ $self->render(json => {
Branch: 1 branch
BranchTrueFalseTotal
$self->_share_links_last ? : 3 2 5
15789 token => $token, url => $url, expires => $expires,
15790 lasts_restart => $self->_share_links_last ? Mojo::JSON::true() : Mojo::JSON::false(),
15791 });
15792 }
15793  
15794 # GET /share/:id?token=...
15795 30 ▶sub share_view ($self) {
Subroutine share_view: called CC=9 SCAR=22.0
Pod documented
15796 30 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
300
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
15797 30 ▶ my $token = $self->param('token') // '';
Condition100%2/2
$self->param("token") // ""
l!l
273
MC/DC100%1/1
$self->param("token") // ""
$self->param("token")
Truth table100%2/2
A
A= $self->param("token")
Aresult
11
00
15798 30 ▶ return $self->render(text => _message_text('error_analysis_id_invalid'), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 2 28 30
15799 unless $id =~ /\A[A-Za-z0-9]+\z/;
15800 28 ▶ return $self->render(text => _message_text('error_token_missing'), status => 401)
Branch: 1 branch
BranchTrueFalseTotal
unless length $token 3 25 28
15801 unless length $token;
15802 25 ▶ unless ($self->_verify_share_token($id, $token)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_verify_share_token($id, $token)) 5 20 25
15803 5 return $self->render(text => _message_text('error_token_invalid'), status => 403);
15804 }
15805  
15806 20 my $analyses = $self->_read_analyses;
15807 return $self->render(text => sprintf(_message_text('error_analysis_not_found'), $id), status => 404)
15808 20 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 3 17 20
15809 17 my $a = $analyses->{$id};
15810  
15811 17 ▶ my @visuals = @{ $a->{visuals} // [] };
Condition100%2/2
$a->{"visuals"} // []
l!l
107
MC/DC100%1/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
15812 17 ▶ unless (@visuals) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@visuals) 7 10 17
15813 7 return $self->render(text => 'This shared analysis has no visuals', status => 404);
15814 }
15815  
15816 # Reuse canvas_render logic by temporarily setting id in stash and
15817 # forwarding; set sharing_mode so the template hides admin controls.
15818 10 $self->stash(sharing_mode => 1);
15819 # Delegate to canvas_render which reads stash('id').
15820 10 return $self->canvas_render;
15821 }
15822  
15823 # GET /embed/:id?token=...
15824 27 ▶sub embed_view ($self) {
Subroutine embed_view: called CC=20 SCAR=30.6
Pod documented
15825 27 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
270
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
15826 27 ▶ my $token = $self->param('token') // '';
Condition100%2/2
$self->param("token") // ""
l!l
252
MC/DC100%1/1
$self->param("token") // ""
$self->param("token")
Truth table100%2/2
A
A= $self->param("token")
Aresult
11
00
15827 27 ▶ return $self->render(text => _message_text('error_analysis_id_invalid'), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 2 25 27
15828 unless $id =~ /\A[A-Za-z0-9]+\z/;
15829 25 ▶ return $self->render(text => _message_text('error_token_missing'), status => 401)
Branch: 1 branch
BranchTrueFalseTotal
unless length $token 2 23 25
15830 unless length $token;
15831 23 ▶ unless ($self->_verify_share_token($id, $token)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_verify_share_token($id, $token)) 3 20 23
15832 3 return $self->render(text => _message_text('error_token_invalid'), status => 403);
15833 }
15834  
15835 20 my $analyses = $self->_read_analyses;
15836 return $self->render(text => sprintf(_message_text('error_analysis_not_found'), $id), status => 404)
15837 20 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 2 18 20
15838 18 my $a = $analyses->{$id};
15839  
15840 # Every HTML page gets this from the after_dispatch hook in Database::BI;
15841 # the page made to be framed says it itself, so it never depends on that.
15842 # The sites embed_frame_ancestors names are allowed by frame-ancestors,
15843 # which the browsers that know it follow in place of this header; those
15844 # that know only this header refuse them, which is the safe way to fail.
15845 18 $self->res->headers->header('X-Frame-Options' => 'SAMEORIGIN');
15846 18 my @framers = Database::BI::_embed_frame_ancestors($self->app->config);
15847 18 ▶ $self->stash(csp_frame_ancestors => \@framers) if @framers;
Branch: 1 branch
BranchTrueFalseTotal
if @framers 0 18 18
15848  
15849 18 ▶ my @visuals = @{ $a->{visuals} // [] };
Condition100%2/2
$a->{"visuals"} // []
l!l
117
MC/DC100%1/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
15850 18 ▶ unless (@visuals) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@visuals) 7 11 18
15851 7 return $self->render(text => 'This shared analysis has no visuals', status => 404);
15852 }
15853  
15854 # Drawn as on the canvas page, each card through its own failure: one card that
15855 # cannot be drawn says so, and leaves the others.
15856 11 my $ctx = $self->_canvas_render_context($a, $self->req->url->query->to_string);
15857 return $self->render(text => $ctx->{error}, status => $ctx->{status})
15858 11 ▶ if $ctx->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"error"} 0 11 11
15859  
15860 11 my (@rendered, $head);
15861 11 for my $i (0 .. $#visuals) {
15862 12 my $vis = $visuals[$i];
15863 12 ▶ my $card = eval {
Condition50%1/2
eval { do { $self->_render_visual_html($vis, $ctx->{"records"}, $ctx->{"columns"}, $ctx->{"src"}, $i, $ctx->{"spec_key"}, 0, $ctx->{"cross_row"}) } } // {"error", _tidy_error($@)}
l!l
120
MC/DC0%0/1
eval { do { $self->_render_visual_html($vis, $ctx->{"records"}, $ctx->{"columns"}, $ctx->{"src"}, $i, $ctx->{"spec_key"}, 0, $ctx->{"cross_row"}) } } // {"error", _tidy_error($@)}
eval { do { $self->_render_visual_html($vis, $ctx->{"records"}, $ctx->{"columns"}, $ctx->{"src"}, $i, $ctx->{"spec_key"}, 0, $ctx->{"cross_row"}) } }
Truth table50%1/2
A
A= eval { do { $self->_render_visual_html($vis, $ctx->{"records"}, $ctx->{"columns"}, $ctx->{"src"}, $i, $ctx->{"spec_key"}, 0, $ctx->{"cross_row"}) } }
Aresult
11
00
15864 $self->_render_visual_html(
15865 $vis, $ctx->{records}, $ctx->{columns}, $ctx->{src}, $i, $ctx->{spec_key}, 0, $ctx->{cross_row},
15866 12 );
15867 } // { error => _tidy_error($@) };
15868 12 ▶ $head //= $card->{head} if length($card->{head} // '');
Branch: 1 branch
BranchTrueFalseTotal
if length($card->{"head"} // "") 0 12 12
Condition20%1/5
$card->{"head"} // ""
l!l
012
$head //= $card->{"head"}
l!l&&r!l&&!r
000
MC/DC0%0/1
$card->{"head"} // ""
$card->{"head"}
MC/DC0%0/2
$head //= $card->{"head"}
$head $card->{"head"}
Truth table50%1/2
A
A= $card->{"head"}
Aresult
11
00
Truth table0%0/3
A //= B
A= $headB= $card->{"head"}
ABresult
1X1
011
000
15869 push @rendered, {
15870 id => $i,
15871 title => ($vis->{title} // $card->{title} // ''),
15872 html => $card->{html},
15873 error => $card->{error},
15874 12 ▶ kind => ($vis->{kind} // ''),
Condition100%7/7
($vis->{"title"} // $card->{"title"}) // ""
l!l
75
$vis->{"title"} // $card->{"title"}
l!l&&r!l&&!r
435
$vis->{"kind"} // ""
l!l
102
MC/DC100%2/2
($vis->{"title"} // $card->{"title"}) // ""
$vis->{"title"} $card->{"title"}
MC/DC100%1/1
$vis->{"kind"} // ""
$vis->{"kind"}
Truth table100%3/3
A // B
A= $vis->{"title"}B= $card->{"title"}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $vis->{"kind"}
Aresult
11
00
15875 plain => _text_card_plain($vis),
15876 };
15877 }
15878  
15879 11 $self->stash(embed_mode => 1, sharing_mode => 1);
15880 11 my ($platform, $language) = $self->_resolve_template;
15881 $self->render(
15882 handler => 'tt',
15883 template => "$platform/$language/embed",
15884 format => 'html',
15885 title => $a->{name},
15886 canvas_id => $id,
15887 canvas_name => $a->{name},
15888 11 ▶ visuals => \@rendered,
Condition50%1/2
$head // ""
l!l
011
MC/DC0%0/1
$head // ""
$head
Truth table50%1/2
A
A= $head
Aresult
11
00
15889 card_head => ($head // ''),
15890 language => $language,
15891 );
15892 }
15893  
15894 # GET /a/:id/visual/:n/:format
15895 34 ▶sub visual_download ($self) {
Subroutine visual_download: called CC=16 SCAR=27.9
Pod documented
15896 34 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
340
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
15897 34 ▶ my $n = $self->stash('n') // 0;
Condition50%1/2
$self->stash("n") // 0
l!l
340
MC/DC0%0/1
$self->stash("n") // 0
$self->stash("n")
Truth table50%1/2
A
A= $self->stash("n")
Aresult
11
00
15898 34 ▶ my $format = $self->stash('fmt') // '';
Condition50%1/2
$self->stash("fmt") // ""
l!l
340
MC/DC0%0/1
$self->stash("fmt") // ""
$self->stash("fmt")
Truth table50%1/2
A
A= $self->stash("fmt")
Aresult
11
00
15899  
15900 34 ▶ return $self->render(text => _message_text('error_analysis_id_invalid'), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A[A-Za-z0-9]+\z/u 1 33 34
15901 unless $id =~ /\A[A-Za-z0-9]+\z/;
15902 33 ▶ return $self->render(text => 'Format must be csv or png', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $format =~ /\A(?:csv|png)\z/u 2 31 33
15903 unless $format =~ /\A(?:csv|png)\z/;
15904 31 ▶ return $self->render(text => 'Visual index must be a non-negative integer', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $n =~ /\A\d+\z/u 3 28 31
15905 unless $n =~ /\A\d+\z/;
15906  
15907 28 my $analyses = $self->_read_analyses;
15908 return $self->render(text => sprintf(_message_text('error_analysis_not_found'), $id), status => 404)
15909 28 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 4 24 28
15910 24 my $a = $analyses->{$id};
15911  
15912 24 ▶ my @visuals = @{ $a->{visuals} // [] };
Condition100%2/2
$a->{"visuals"} // []
l!l
186
MC/DC100%1/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
15913 24 ▶ return $self->render(text => "Visual $n not found", status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless $n < scalar @visuals 9 15 24
15914 unless $n < scalar @visuals;
15915 return $self->render(text => _message_text('error_text_card_no_data'), status => 404)
15916 15 ▶ if ($visuals[$n]{kind} // '') eq 'text';
Branch: 1 branch
BranchTrueFalseTotal
if ($visuals[$n]{"kind"} // "") eq "text" 1 14 15
Condition100%2/2
$visuals[$n]{"kind"} // ""
l!l
132
MC/DC100%1/1
$visuals[$n]{"kind"} // ""
$visuals[$n]{"kind"}
Truth table100%2/2
A
A= $visuals[$n]{"kind"}
Aresult
11
00
15917  
15918 14 ▶ if ($format eq 'csv') {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "csv") 12 2 14
15919 12 $self->stash(buffer => 0);
15920 # The canvas names its own source: l= on this URL is no way to reach another.
15921 12 my $ctx = $self->_canvas_render_context($a, $self->req->url->query->to_string);
15922 return $self->render(text => $ctx->{error}, status => $ctx->{status})
15923 12 ▶ if $ctx->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"error"} 1 11 12
15924 11 my $records = $ctx->{records};
15925 11 ▶ for my $spec (@{ $visuals[$n]{filters} // [] }) {
Condition50%1/2
$visuals[$n]{"filters"} // []
l!l
011
MC/DC0%0/1
$visuals[$n]{"filters"} // []
$visuals[$n]{"filters"}
Truth table50%1/2
A
A= $visuals[$n]{"filters"}
Aresult
11
00
15926 0 $records = _apply_filter_spec($records, $spec);
15927 }
15928 $self->res->headers->content_disposition(
15929 11 "attachment; filename=\"visual-$n.csv\""
15930 );
15931 11 return $self->render(data => _serialize_csv($records, $ctx->{columns}), format => 'txt');
15932 }
15933  
15934 # PNG: not implemented in the server (canvas/SVG rendering is client-side).
15935 # Return 501 with a descriptive message.
15936 2 return $self->render(
15937 text => 'PNG download requires the browser SVG renderer; use the PNG button on the card',
15938 status => 501,
15939 );
15940 }
15941  
15942 # ask_api($self)
15943 #
15944 # POST /api/ask
15945 #
15946 # Translates a plain-English question into an analysis spec by
15947 # calling the configured AI provider. The model receives only column
15948 # names and types -- never raw row data, file paths, or spec_key.
15949 #
15950 # Body params:
15951 # l=<spec> (required) -- left table spec
15952 # q=<question> (required) -- natural language question
15953 # f=<filter> (repeatable, optional)
15954 #
15955 # Returns JSON: { spec, url, valid => 1 }
15956 # On error: { error } with 400, 503, or 502 status
15957 44 ▶sub ask_api ($self) {
Subroutine ask_api: called CC=20 SCAR=30.6
Pod documented
15958 44 ▶ my $api_key = $self->app->config('ai_api_key') // '';
Condition100%2/2
$self->app->config("ai_api_key") // ""
l!l
395
MC/DC100%1/1
$self->app->config("ai_api_key") // ""
$self->app->config("ai_api_key")
Truth table100%2/2
A
A= $self->app->config("ai_api_key")
Aresult
11
00
15959 44 ▶ return $self->render(json => { error => _message_text('ask_unavailable') }, status => 503)
Branch: 1 branch
BranchTrueFalseTotal
unless length $api_key 5 39 44
15960 unless length $api_key;
15961  
15962 39 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
372
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
15963 39 ▶ return $self->render(json => { error => 'Missing required parameter: l' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 2 37 39
15964 unless length $left_spec;
15965  
15966 37 ▶ my $question = $self->param('q') // '';
Condition100%2/2
$self->param("q") // ""
l!l
352
MC/DC100%1/1
$self->param("q") // ""
$self->param("q")
Truth table100%2/2
A
A= $self->param("q")
Aresult
11
00
15967 37 ▶ return $self->render(json => { error => _message_text('ask_no_question') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $question 2 35 37
15968 unless length $question;
15969 35 ▶ return $self->render(json => { error => sprintf(_message_text('ask_question_too_long'), $ASK_MAX_QUESTION) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if length $question > $ASK_MAX_QUESTION 1 34 35
15970 if length($question) > $ASK_MAX_QUESTION;
15971  
15972 34 my ($src, $records, $columns, $left_label) = $self->_run_pipeline_source;
15973 34 ▶ return $self->render(json => { error => 'Could not open data source' }, status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 0 34 34
15974 unless defined $records;
15975  
15976 34 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
15977  
15978 # Sample up to 200 rows for type inference; avoids slurping huge files.
15979 34 ▶ my @sample = @{$records}[0 .. ($#$records < 199 ? $#$records : 199)];
Branch: 1 branch
BranchTrueFalseTotal
$records->$#* < 199 ? : 34 0 34
15980  
15981 34 require Database::BI::Ask;
15982 34 my $typed_cols = Database::BI::Ask::infer_column_types(\@sample, $columns);
15983  
15984 34 ▶ my $ai_config = {
Condition50%2/4
$self->app->config("ai_provider") // "anthropic"
l!l
034
$self->app->config("ai_model") // "claude-haiku-5-5"
l!l
034
MC/DC0%0/1
$self->app->config("ai_provider") // "anthropic"
$self->app->config("ai_provider")
MC/DC0%0/1
$self->app->config("ai_model") // "claude-haiku-5-5"
$self->app->config("ai_model")
Truth table50%1/2
A
A= $self->app->config("ai_provider")
Aresult
11
00
Truth table50%1/2
A
A= $self->app->config("ai_model")
Aresult
11
00
15985 provider => $self->app->config('ai_provider') // 'anthropic',
15986 api_key => $api_key,
15987 model => $self->app->config('ai_model') // 'claude-haiku-5-5',
15988 };
15989  
15990 34 ▶ return $self->render(json => { error => sprintf(_message_text('ai_limit_reached'), _ai_calls_per_hour($self)) }, status => 429)
Branch: 1 branch
BranchTrueFalseTotal
unless _ai_call_allowed($self) 1 33 34
15991 unless _ai_call_allowed($self);
15992  
15993 33 ▶ my $result = Database::BI::Ask::ask(
Condition33%1/3
$left_label // $left_spec
l!l&&r!l&&!r
3300
MC/DC0%0/2
$left_label // $left_spec
$left_label $left_spec
Truth table33%1/3
A // B
A= $left_labelB= $left_spec
ABresult
1X1
011
000
15994 question => $question,
15995 spec_key => $left_spec,
15996 label => $left_label // $left_spec,
15997 columns => $typed_cols,
15998 ai_config => $ai_config,
15999 );
16000  
16001 33 ▶ if (my $err = $result->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $result->{"error"}) 28 5 33
16002 28 ▶ my ($status, $msg) =
Branch: 5 branches
BranchTrueFalseTotal
$err eq 'ask_unavailable' ? : 0 28 28
$err eq 'ask_no_question' ? : 0 28 28
$err eq 'ask_provider_error' ? : 22 6 28
$err eq 'ask_unparseable' ? : 4 2 6
$err =~ /\Aask_invalid_spec:(.+)\z/u ? : 2 0 2
16003 $err eq 'ask_unavailable' ? (503, _message_text('ask_unavailable'))
16004 : $err eq 'ask_no_question' ? (400, _message_text('ask_no_question'))
16005 : $err eq 'ask_provider_error' ? (502, _message_text('ask_provider_error'))
16006 : $err eq 'ask_unparseable' ? (422, _message_text('ask_unparseable'))
16007 : $err =~ /\Aask_invalid_spec:(.+)\z/ ? (422, sprintf(_message_text('ask_invalid_spec'), $1))
16008 : (500, $err);
16009 28 return $self->render(json => { error => $msg }, status => $status);
16010 }
16011  
16012 5 return $self->render(json => $result);
16013 }
16014  
16015 # summary_api($self)
16016 #
16017 # POST /api/summary
16018 #
16019 # Runs the same pipeline as insights_view, computes insights, then generates
16020 # a narrative summary via Database::BI::Summary::generate().
16021 #
16022 # Body params:
16023 # l=<spec> (required) -- left table spec
16024 # f=<filter> (repeatable, optional)
16025 # ai=1 (optional) -- request LLM polish (honoured only when ai_api_key
16026 # is set in the app config)
16027 #
16028 # Returns JSON: { text, source, cached }
16029 # On error: { error } with 400 or 404 status
16030 26 ▶sub summary_api ($self) {
Subroutine summary_api: called CC=10 SCAR=23.4
Pod documented
16031 26 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
242
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
16032 26 ▶ return $self->render(json => { error => 'Missing required parameter: l' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 2 24 26
16033 unless length $left_spec;
16034  
16035 24 my ($src, $records, $columns) = $self->_run_pipeline_source;
16036 24 ▶ return $self->render(json => { error => 'Could not open data source' }, status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 23 24
16037 unless defined $records;
16038  
16039 23 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
16040 0 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(json => { error => $e }, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 23 23
16041  
16042 23 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 23 23
16043  
16044 23 my $row_count = scalar @$records;
16045 23 (my $label = $left_spec) =~ s/\A(?:table:|path:|url:|mariadb:|redis:[^|]+\|)//;
16046  
16047 23 require Database::BI::Insights;
16048 23 my $insights = Database::BI::Insights::compute(
16049 records => $records,
16050 columns => $columns,
16051 spec_key => $left_spec,
16052 );
16053  
16054 23 ▶ my $use_ai = $self->param('ai') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('ai') ? : 21 2 23
16055 23 ▶ my $ai_config = {
Condition66%4/6
$self->app->config("ai_provider") // "anthropic"
l!l
023
$self->app->config("ai_api_key") // ""
l!l
212
$self->app->config("ai_model") // "claude-haiku-5-5"
l!l
023
MC/DC0%0/1
$self->app->config("ai_provider") // "anthropic"
$self->app->config("ai_provider")
MC/DC100%1/1
$self->app->config("ai_api_key") // ""
$self->app->config("ai_api_key")
MC/DC0%0/1
$self->app->config("ai_model") // "claude-haiku-5-5"
$self->app->config("ai_model")
Truth table50%1/2
A
A= $self->app->config("ai_provider")
Aresult
11
00
Truth table100%2/2
A
A= $self->app->config("ai_api_key")
Aresult
11
00
Truth table50%1/2
A
A= $self->app->config("ai_model")
Aresult
11
00
16056 provider => $self->app->config('ai_provider') // 'anthropic',
16057 api_key => $self->app->config('ai_api_key') // '',
16058 model => $self->app->config('ai_model') // 'claude-haiku-5-5',
16059 };
16060  
16061 23 require Database::BI::Summary;
16062 my $result = Database::BI::Summary::generate(
16063 insights => $insights,
16064 spec_key => $left_spec,
16065 label => $label,
16066 row_count => $row_count,
16067 use_ai => $use_ai,
16068 ai_config => $ai_config,
16069 11 ▶ ai_allowed => sub { _ai_call_allowed($self) },
Subroutine __ANON__: called CC=1 SCAR=0.0
16070 23 );
16071  
16072 23 return $self->render(json => $result);
16073 }
16074  
16075 # _ai_calls_per_hour($c) -> $n
16076 #
16077 # Config ai_calls_per_hour, else $AI_CALLS_PER_HOUR; 0 means no limit.
16078 46 ▶sub _ai_calls_per_hour {
Subroutine _ai_calls_per_hour: called CC=3 SCAR=11.0
16079 46 my ($c) = @_;
16080 46 my $n = $c->app->config('ai_calls_per_hour');
16081 46 ▶ return defined($n) && $n =~ /\A\d+\z/ ? $n : $AI_CALLS_PER_HOUR;
Branch: 1 branch
BranchTrueFalseTotal
defined $n && $n =~ /\A\d+\z/u ? : 2 44 46
Condition66%2/3
defined $n and $n =~ /\A\d+\z/u
!ll&&!rl&&r
4402
MC/DC50%1/2
defined $n and $n =~ /\A\d+\z/u
defined $n $n =~ /\A\d+\z/u
Truth table66%2/3
A and B
A= defined $nB= $n =~ /\A\d+\z/u
ABresult
0X0
100
111
16082 }
16083  
16084 # _ai_call_allowed($c) -> 1 | 0
16085 #
16086 # Takes one provider call from this process's budget: the times of the calls
16087 # in the last hour, kept per application (tests build many in one process).
16088 # Returns 0, taking nothing, when the hour's calls are used up.
16089 10 my %AI_CALLS;
16090 45 ▶sub _ai_call_allowed {
Subroutine _ai_call_allowed: called CC=4 SCAR=13.9
16091 45 my ($c) = @_;
16092 45 my $max = _ai_calls_per_hour($c);
16093 45 ▶ return 1 unless $max;
Branch: 1 branch
BranchTrueFalseTotal
unless $max 0 45 45
16094 45 my $now = time;
16095 45 ▶ my $calls = $AI_CALLS{ Scalar::Util::refaddr($c->app) } //= [];
Condition100%2/2
$AI_CALLS{builtin::refaddr($c->app)} //= []
l!l
378
MC/DC100%1/1
$AI_CALLS{builtin::refaddr($c->app)} //= []
$AI_CALLS{builtin::refaddr($c->app)}
Truth table100%2/2
A
A= $AI_CALLS{builtin::refaddr($c->app)}
Aresult
11
00
16096 45 @{$calls} = grep { $_ > $now - $AI_WINDOW_S } @{$calls};
16097 45 ▶ return 0 if @{$calls} >= $max;
Branch: 1 branch
BranchTrueFalseTotal
if @{$calls;} >= $max 1 44 45
16098 44 push @{$calls}, $now;
16099 44 return 1;
16100 }
16101  
16102 # insights_view($self)
16103 #
16104 # Accepts the same l=, j=, f=, c= pipeline as /stats. Runs the standard
16105 # pipeline (date normalisation, calc fields, filters), then delegates to
16106 # Database::BI::Insights::compute() for pure-arithmetic insight detection.
16107 #
16108 # No LLM or external service is invoked. Every returned insight carries a
16109 # view_url linking to the chart or stats page that shows the underlying data.
16110 #
16111 # Stash keys:
16112 # insights -- arrayref of insight hashrefs (kind/headline/detail/view_url/method)
16113 # left_spec -- the l= value
16114 # left_label -- human-readable data-source label
16115 # row_count -- number of rows analysed
16116 # base_url -- current request URL (passed to Insights for fallback URLs)
16117 49 ▶sub insights_view ($self) {
Subroutine insights_view: called CC=16 SCAR=30.2
Pod documented
16118 49 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
472
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
16119 49 ▶ return $self->render(text => 'Missing l= parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 3 46 49
16120 unless length $left_spec;
16121  
16122 46 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
046
MC/DC0%0/1
_safe_back_url($self->param("back")) // "/"
_safe_back_url($self->param("back"))
Truth table50%1/2
A
A= _safe_back_url($self->param("back"))
Aresult
11
00
16123 46 my $back2 = _safe_back_url($self->param('back2'));
16124 46 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
046
MC/DC0%0/1
$self->param("back2_label") // ""
$self->param("back2_label")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
16125  
16126 46 my ($src, $records, $columns) = $self->_run_pipeline_source;
16127 46 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 3 43 46
16128 unless defined $records;
16129  
16130 43 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
16131 43 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 42 43
16132  
16133 42 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 41 42
16134  
16135 41 my $row_count = scalar @$records;
16136 41 (my $left_label = $left_spec) =~ s/\A(?:table:|path:|url:|mariadb:|redis:[^|]+\|)//;
16137  
16138 41 require Database::BI::Insights;
16139 41 my $insights = Database::BI::Insights::compute(
16140 records => $records,
16141 columns => $columns,
16142 spec_key => $left_spec,
16143 base_url => $self->req->url->path_query,
16144 );
16145  
16146 41 my ($platform, $language) = $self->_resolve_template;
16147 41 ▶ $self->render(
Branch: 3 branches
BranchTrueFalseTotal
length($self->app->config('ai_api_key') // '') ? : 0 41 41
$back2 ? : 0 41 41
$back2 ? : 0 41 41
Condition27%3/11
$self->app->config("ai_api_key") // ""
l!l
041
$back2 // $back
l!l&&r!l&&!r
0410
$back2_lbl or "Back"
l!l
00
$self->param("back_label") // "Back to table"
l!l
041
$self->param("back_label") // "Back to table"
l!l
00
MC/DC0%0/1
$self->app->config("ai_api_key") // ""
$self->app->config("ai_api_key")
MC/DC0%0/2
$back2 // $back
$back2 $back
MC/DC0%0/1
$back2_lbl or "Back"
$back2_lbl
MC/DC0%0/1
$self->param("back_label") // "Back to table"
$self->param("back_label")
MC/DC0%0/1
$self->param("back_label") // "Back to table"
$self->param("back_label")
Truth table50%1/2
A
A= $self->app->config("ai_api_key")
Aresult
11
00
Truth table33%1/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
Truth table50%1/2
A
A= $self->param("back_label")
Aresult
11
00
Truth table0%0/2
A
A= $self->param("back_label")
Aresult
11
00
16148 handler => 'tt',
16149 template => "$platform/$language/insights",
16150 format => 'html',
16151 title => 'Automatic insights',
16152 insights => $insights,
16153 left_spec => $left_spec,
16154 left_label => $left_label,
16155 row_count => $row_count,
16156 ai_available => (length($self->app->config('ai_api_key') // '') ? 1 : 0),
16157 back_url => ($back2 // $back),
16158 back_label => ($back2 ? ($back2_lbl || 'Back') : ($self->param('back_label') // 'Back to table')),
16159 ($back2 ? (back2_url => $back, back2_label => ($self->param('back_label') // 'Back to table')) : ()),
16160 language => $language,
16161 );
16162 }
16163  
16164 10 1;
16165  
16166 __END__
↑ Summary blib/lib/Database/BI/Util.pm »