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

filter: Statementstmt 78.6% 5274 / 6707 Branchbran 64.3% 2693 / 4188 Conditioncond 54.9% 2191 / 3984 MC/DCmcdc 35.1% 763 / 2172 Subroutinesub 91.9% 421 / 458 Podpod 98.8% 82 / 83 totaltotal 64.9% 11424 / 17592 CC 3982 SCAR 80.9
CC
3982
Cov
68%
_render_visual_markup
38758.0
_map_data
8661.9
pivot_view
4017.3
CRAP 3257.5
↑ Summary blib/lib/Database/BI/Model/DataSource.pm »
1 package Database::BI::Controller::Dashboard;
2  
3 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 5 our $VERSION = '0.023.0';
7  
8 5 ▶use Mojo::Base 'Mojolicious::Controller', -strict, -signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 5 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 5 ▶use Cwd qw(realpath);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 5 ▶use List::Util qw(min max sum);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 5 ▶use CGI::Info;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 5 ▶use CGI::Lingua;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 5 ▶use Database::BI::I18N ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 5 ▶use Unicode::Normalize ();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 5 ▶use Database::BI::Tutorial;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 5 ▶use Database::BI::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 5 ▶use Mojo::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 5 ▶use Mojo::JSON qw(encode_json decode_json from_json to_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 5 ▶use Mojo::Parameters;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 5 ▶use Mojo::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 5 ▶use Mojo::Util qw(url_escape encode xml_escape hmac_sha1_sum secure_compare);
Subroutine BEGIN: called CC=1 SCAR=0.0
24 5 ▶use Digest::SHA ();
Subroutine BEGIN: called CC=1 SCAR=0.0
25 5 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
26 5 ▶use Database::BI::Password ();
Subroutine BEGIN: called CC=1 SCAR=0.0
27 5 ▶use File::Path qw(remove_tree);
Subroutine BEGIN: called CC=1 SCAR=0.0
28 5 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 5 ▶use File::Temp qw(tempfile tempdir);
Subroutine BEGIN: called CC=1 SCAR=0.0
30 5 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 5 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 5 ▶use version ();
Subroutine BEGIN: called CC=1 SCAR=0.0
33  
34 # ---------------------------------------------------------------------------
35 # Constants
36 # ---------------------------------------------------------------------------
37  
38 # File extensions that Database::Abstraction can probe, in probe order.
39 # .sql, .sqlite, and .sqlite3 are all SQLite databases; .db is Berkeley DB.
40 # As many digits as a request parameter may have and still be exact in a Perl
41 # number. More than this is not a page number or a limit, it is someone probing.
42 5 Readonly my $MAX_WHOLE_NUMBER_DIGITS => 15;
43 5 Readonly my %ANALYSIS_KEYS => map { $_ => 1 } qw(id version created updated name datasets joins combines fields measures params visuals layout bookmarks hierarchies);
44 5 Readonly my $MAX_HISTOGRAM_BINS => 200;
45  
46 # What a text card on a canvas may be styled with. The fonts are ones browsers
47 # already have, so a card needs no CDN, and a stored card names a font by its
48 # key: only the CSS written here ever reaches a style attribute.
49 5 Readonly my @TEXT_FONTS => (
50 { value => '', label => 'Same as the page', css => '' },
51 { value => 'arial', label => 'Arial', css => 'Arial, Helvetica, sans-serif' },
52 { value => 'georgia', label => 'Georgia', css => 'Georgia, "Times New Roman", serif' },
53 { value => 'times', label => 'Times New Roman', css => '"Times New Roman", Times, serif' },
54 { value => 'verdana', label => 'Verdana', css => 'Verdana, Geneva, sans-serif' },
55 { value => 'trebuchet', label => 'Trebuchet MS', css => '"Trebuchet MS", Helvetica, sans-serif' },
56 { value => 'courier', label => 'Courier New', css => '"Courier New", Courier, monospace' },
57 );
58 5 Readonly my %TEXT_FONT_CSS => map { $_->{value} => $_->{css} } grep { length $_->{value} } @TEXT_FONTS;
59 5 Readonly my %TEXT_ALIGNS => map { $_ => 1 } qw(left center right);
60 5 Readonly my $MIN_TEXT_POINTS => 8;
61 5 Readonly my $MAX_TEXT_POINTS => 96;
62 5 Readonly my $MAX_TEXT_CHARS => 20_000;
63 5 Readonly my $TEXT_TITLE_CHARS => 60;
64  
65 # What HTML::D3 calls its heatmap colour scales.
66 5 Readonly my %SEQUENTIAL_SCHEMES => map { $_ => 1 } qw(YlOrRd Blues Greens Purples RdPu YlGnBu);
67 5 Readonly my $DEFAULT_SEQUENTIAL_SCHEME => 'YlOrRd';
68 5 Readonly my $DEFAULT_CATEGORICAL_SCHEME => 'tableau10';
69  
70 5 Readonly my @SUPPORTED_EXT => qw( csv db sql sqlite sqlite3 xml tsv psv xlsx json );
71 # Use \z (absolute end-of-string) not $ (which permits a trailing \n before \z).
72 # A query param decoded from "file.csv%0A" has basename "sales.csv\n"; without \z
73 # that passes the extension guard and reaches realpath with an embedded newline.
74 5 Readonly my $EXT_RE => do { my $p = join '|', @SUPPORTED_EXT; qr/\.(?:$p)\z/i };
75  
76 # Table name safe-identifier pattern -- must match DataSource's TABLE_NAME_RE
77 # exactly: first character must be a letter or underscore (not a digit), so
78 # that every table name the controller accepts can also be opened by DataSource
79 # without an unhandled croak.
80 5 Readonly my $TABLE_NAME_RE => qr/\A[A-Za-z_][A-Za-z0-9_]*\z/;
81  
82 # URL spec pattern shared by _open_spec and _spec_to_url.
83 # qr{} delimiter avoids the \/ escaping noise required by the // form.
84 # /s: makes . match \n so a percent-decoded newline inside a URL does not
85 # silently truncate the captured URL before the \z end-of-string anchor.
86 5 Readonly my $URL_SPEC_RE => qr{\Aurl:(https?://.+)\z}si;
87  
88 # Redis spec pattern: redis:tablename|redis://[password@]host[:port][/db_index]
89 # The pipe separates the table name from the connection URL so the URL's own
90 # colons and slashes do not require extra quoting.
91 5 Readonly my $REDIS_SPEC_RE => qr{\Aredis:([^|]+)\|(redis://.+)\z}si;
92  
93 # Bare Redis URL -- no table name -- used to list available keys.
94 # Excludes '|' so it cannot match the redis:table|redis://... full spec.
95 5 Readonly my $REDIS_URL_RE => qr{\Aredis://[^\s|]+\z}si;
96  
97 # MariaDB spec: mariadb:server/table, where server names an entry in the
98 # mariadb_servers configuration. A spec travels in URLs, links and saved
99 # canvases, so it holds no address or password. It has no '|', which also lets
100 # it be the right side of a j= join.
101 5 Readonly my $MARIADB_SPEC_RE => qr{\Amariadb:([A-Za-z_][A-Za-z0-9_]*)/([A-Za-z_][A-Za-z0-9_]*)\z};
102  
103 # A server with no table: lists its tables.
104 5 Readonly my $MARIADB_SERVER_RE => qr{\Amariadb:([A-Za-z_][A-Za-z0-9_]*)\z};
105  
106 # Hostname pattern accepted in /../hostname/... remote paths.
107 # Mirrors Database::Abstraction's own host validation regex.
108 # Accepts 'hostname', 'user@hostname', and IPv4 addresses (IPv6 is excluded
109 # because the [...] notation would be ambiguous in the path syntax).
110 5 Readonly my $REMOTE_HOST_RE => qr/\A(?:[a-zA-Z0-9][a-zA-Z0-9._-]*\@)?[a-zA-Z0-9][a-zA-Z0-9._-]*\z/;
111  
112 # The tile layer HTML::OSM 0.10 hardcodes. HTML::OSM >= 0.14 is required;
113 # 0.12 introduced search => 0, max_zoom, and tile_url (0.11), 0.13 the scale
114 # bar, the key on the map and fit, and 0.14 the nonce on its scripts.
115 5 Readonly my $DEFAULT_TILE_URL => 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
116  
117 # The language the distribution ships templates for. It is what a request falls
118 # back to when the language it resolved has no template directory of its own;
119 # see _resolve_language. Keep it equal to Database::BI's $DEFAULT_LANGUAGE.
120 5 Readonly my $DEFAULT_LANGUAGE => 'en';
121  
122 # The floor this controller passes options for. HTML::OSM validates its
123 # constructor arguments strictly, so an older install does not ignore the new
124 # keys - it croaks on them. _map_data therefore checks the version before
125 # building a map, and reports a missing or old renderer instead of a 500.
126 # 0.13 draws the scale bar and the key on the map, listing only what is in view
127 # (scale, legend, and group on each marker), and opens on every marker (fit).
128 # 0.14 puts the Content-Security-Policy nonce on its scripts (nonce).
129 5 Readonly my $MIN_HTML_OSM_VERSION => '0.14';
130  
131 # ---------------------------------------------------------------------------
132 # I18N message dictionary for all user-visible strings in this controller.
133 # To plug in a Locale::Maketext backend, extend _i18n() below.
134 # ---------------------------------------------------------------------------
135  
136 5 Readonly my %MESSAGES => (
137 error_table_invalid => 'Invalid table name "%s"',
138 error_table_open => 'Could not open table "%s": %s',
139 error_table_missing => 'There is no table called "%s".',
140 error_file_open => 'Could not open "%s": %s',
141 error_no_path => 'No path specified',
142 error_not_found => 'File or directory not found: %s',
143 error_dir_not_found => 'Directory not found: %s',
144 error_login_required => 'Log in first: this server asks for a password.',
145 error_login_failed => 'That is not the password.',
146 error_login_locked => 'Too many wrong passwords from this address. Try again in %d minutes.',
147 error_hidden_target => 'Refused to save into "%s": a hidden file or folder (one whose name starts with a dot) holds settings, not exports.',
148 error_outside_roots => 'Refused: "%s" is outside the folders this server may use (file_roots in database_bi.conf).',
149 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.',
150 error_export_not_file => 'Refused: "%s" is already there and is not a plain file, so an export does not replace it.',
151 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".',
152 error_cross_site => 'Refused: this request came from another site (%s). Only pages of this application can change what it keeps or write files.',
153 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.',
154 error_write_failed => 'Write failed: %s',
155 error_ext_required => 'Use a .csv, .sql, or .json filename extension',
156 error_upload_none => 'No file received',
157 error_upload_ext => 'Unsupported file type. Accepted: CSV, TSV, PSV, XML, JSON, SQLite (.sql, .sqlite, .sqlite3), Berkeley DB (.db), XLSX',
158 error_upload_too_large => 'File too large (maximum %s MiB)',
159 error_upload_save => 'Could not save uploaded file',
160 error_uploads_clear => 'Could not clear the uploaded files',
161 error_export_sqlite => 'Could not build the SQLite export; the server log has the reason',
162 error_path_required => '"path" parameter is required',
163 error_url_required => 'Please enter a URL',
164 error_url_invalid => '"%s" is not a valid http:// or https:// URL',
165 error_url_fetch => 'Could not load HTML table from "%s": %s',
166 error_url_ssrf => '"%s" resolves to a private or reserved address and cannot be fetched',
167 warn_combine_sort => 'Sorting is applied in memory for /combine; result order may differ from a backend sort',
168 error_sort_column => 'Unknown sort column "%s"',
169 warn_measure_fallback => 'Measure "%s" on column "%s" is not uniformly numeric; totalled in Perl',
170 error_measure_column => 'Measure column "%s" is not in the view',
171 error_pivot_rows_required => 'At least one rows= dimension is required',
172 error_pivot_measure_req => 'At least one m= measure (col:fn:as) is required',
173 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',
174 error_stats_percentile => 'The percentile must be a whole number from 1 to 100; "%s" is not',
175 error_pivot_dim_not_found => 'Row/column dimension "%s" is not in the view',
176 error_pivot_dim_comma => 'Dimension name "%s" must not contain a comma',
177 error_calc_compile => 'Calculated field "%s": %s',
178 error_calc_name => 'Calculated field name "%s" is not a valid identifier',
179 error_topn_col => 'Top-N column "%s" is not a measure alias in this view',
180 warn_calc_undef => 'Calculated field "%s" returned undef for %d row(s)',
181 error_date_pattern => 'Unsupported date format pattern "%s"; allowed: %%m/%%d/%%Y, %%d/%%m/%%Y, %%d-%%b-%%Y',
182 error_date_time_pattern => 'Unsupported time format pattern "%s"; allowed: %%H:%%M, %%H:%%M:%%S',
183 error_date_as => 'as= must be "timestamp" or absent; "%s" is neither',
184 error_lookup_name => 'Lookup name "%s" is not a valid identifier',
185 error_lookup_unknown => 'Lookup "%s" is not stored for any dataset',
186 error_lookup_remote => 'Lookup "%s": "%s" is not a file; a lookup reads a file under data_dir (use Import for a URL)',
187 error_lookup_outside => 'Lookup "%s": "%s" is not under data_dir',
188 error_lookup_not_found => 'Lookup "%s": file "%s" not found, or not a supported data file',
189 error_lookup_too_large => 'Lookup "%s": "%s" is %d bytes, more than a lookup may be (%d)',
190 error_lookup_unreadable => 'Lookup "%s": cannot read "%s": %s',
191 error_lookup_key_unknown => 'Lookup "%s": key column "%s" is not in "%s"',
192 error_lookup_field_unknown => 'Lookup "%s": field "%s" is not in "%s"',
193 error_lookup_col_unknown => 'Lookup "%s": column "%s" is not in this dataset (nolk=%s skips the lookup)',
194 error_lookup_name_taken => 'Lookup "%s": field "%s" cannot be added, because "%s" is a column already',
195 warn_lookup_duplicate_key => 'Lookup "%s": %d duplicate key(s) in "%s"; the first row of each is used',
196 error_extract_name => 'Extraction name "%s" is not a valid identifier',
197 error_extract_pattern => 'Extraction "%s": %s',
198 error_extract_no_names => 'Extraction "%s": the pattern names no group; write one as (?<name>...) for each column',
199 error_extract_field => 'Extraction "%s": the pattern has no group named "%s"',
200 error_extract_col_unknown => 'Extraction "%s": column "%s" is not in this dataset',
201 error_extract_name_taken => 'Extraction "%s": group "%s" cannot be added, because "%s" is a column already',
202 error_accel_spec => 'Cannot accelerate "%s": it must be a table: or path: spec naming a local file that exists',
203 error_accel_sqlite => 'Cannot accelerate "%s": it is a SQLite database already',
204 error_accel_open => 'Cannot accelerate "%s": the file cannot be opened: %s',
205 error_accel_store => 'Cannot accelerate "%s": the model store cannot be written (model_dir inside data_dir, or not writable)',
206 error_accel_build => 'Cannot accelerate "%s": %s',
207 error_analysis_not_found => 'Analysis "%s" not found',
208 error_analysis_invalid => 'Invalid analysis spec: %s',
209 error_analysis_version => 'Unsupported analysis version %s; please upgrade the application',
210 error_analysis_storage => 'Analysis storage is not writable; use import/export instead',
211 error_analysis_json => 'Invalid JSON body: %s',
212 error_analysis_id_invalid => 'Invalid analysis id',
213 error_text_card_empty => 'A text card needs some text',
214 error_text_card_long => 'A text card can hold at most %d characters',
215 error_text_card_font => 'That font is not one of the choices',
216 error_text_card_size => 'The size must be a whole number of points from %d to %d',
217 error_text_card_colour => 'A colour must be written #rrggbb',
218 error_text_card_align => 'The alignment must be left, center or right',
219 error_text_card_options => 'options must be given as an object',
220 error_text_card_columns => 'A text card has no columns to change',
221 error_text_card_no_data => 'A text card has no data to download',
222 error_visual_not_text => 'Only a text card can be removed',
223 error_param_range => "Parameter '%s' is out of range (min %s, max %s)",
224 error_param_type => "Parameter '%s' must be a number",
225 error_map_source => 'A map needs loc=<column> to geocode, or both lat= and lon= coordinate columns',
226 error_map_coordinates => 'A map with lat= needs lon= as well, and a map with lon= needs lat=',
227 error_map_loc_column => 'Column "%s" is not in this view, so there is nothing to geocode',
228 error_map_coordinate_range => 'Column "%s" holds only values outside the range of %s; check that lat= and lon= are not swapped',
229 error_map_coordinate_numeric => 'Columns "%s" and "%s" hold no numeric coordinate pairs; a map needs numbers, or loc=<column> to geocode places',
230 error_map_no_markers => 'No row has a location that could be plotted',
231 error_map_renderer_missing => 'Drawing a map needs HTML::OSM 0.14 or later, and it is not installed',
232 error_map_renderer_failed => 'The map could not be drawn; the server log has the reason',
233 error_map_renderer_old => 'Drawing a map needs HTML::OSM 0.14 or later, but the installed HTML::OSM is %s',
234 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',
235 warn_map_coordinate_rows => 'Plotted %d of %d rows; %d hold no usable coordinate',
236 warn_map_markers_capped => 'Showing the first %d of %d markers; add f= filters to see the rest',
237 map_legend_empty => 'Nothing in this view',
238 map_bounds_layer => '%s boundaries',
239 map_bounds_noun_county => 'county',
240 map_bounds_noun_district => 'district',
241 map_bounds_noun_province => 'province',
242 map_bounds_noun_prefecture => 'prefecture',
243 map_bounds_noun_department => 'department',
244 map_bounds_noun_area => 'area',
245 map_bounds_total => '%s: %s %s',
246 map_bounds_row => '%s: 1 row',
247 map_bounds_rows => '%s: %s rows',
248 map_bounds_key_total => '%s in each %s',
249 map_bounds_key_rows => 'Rows in each %s',
250 map_bounds_key_range => '%s to %s',
251 warn_map_cache_unwritten => 'The resolved places could not be remembered in the model store, so the next request will look them up again',
252 error_map_tiles_unknown => 'Unknown tile source "%s"; define it under tile_sources in database_bi.conf',
253 error_map_geocode_mode => 'geocode= must be "wait" (look places up before the page is sent) or "cached" (look nothing up), not "%s"',
254 error_geo_lookup_place => 'A lookup needs place= and the sig= the map page gave it',
255 error_geo_lookup_unsigned => 'This place was not listed by a map page, or the server has restarted since; open the map again',
256 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"',
257 error_map_bounds_unknown => 'bounds= must be "county", the only kind of boundary so far, not "%s"',
258 warn_map_bounds_pending => '%d of %d places have no county outline yet',
259 warn_map_bounds_pending_one => '%d of %d places has no county outline yet',
260 warn_map_bounds_offline => '%d of %d places have no county outline: outlines come from OpenStreetMap, which this server does not ask (map_geocode_online is off, or LWP::UserAgent::Throttled is not installed)',
261 warn_map_bounds_offline_one => '%d of %d places has no county outline: outlines come from OpenStreetMap, which this server does not ask (map_geocode_online is off, or LWP::UserAgent::Throttled is not installed)',
262 warn_map_bounds_failed => 'OpenStreetMap did not answer, so %d of %d places have no county outline; they are tried again next time',
263 warn_map_bounds_failed_one => 'OpenStreetMap did not answer, so %d of %d places has no county outline; it is tried again next time',
264 error_geo_boundary_point => 'A lookup needs point= and the sig= the map page gave it',
265 error_geo_boundary_unsigned => 'This point was not listed by a map page, or the server has restarted since; open the map again',
266 error_insights_no_data => 'No data available to analyse',
267 insights_insufficient_data => 'Insufficient data for this insight type (need more rows or periods)',
268 ask_unavailable => 'Ask a question is not available: no AI provider is configured',
269 ask_no_question => 'Please enter a question',
270 ask_question_too_long => 'The question is longer than %d characters; please shorten it',
271 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',
272 ask_provider_error => 'AI provider error; could not generate an analysis',
273 ask_unparseable => 'Could not parse a valid visualization from the response; please rephrase your question',
274 ask_invalid_spec => 'Generated spec contains an unknown column: %s',
275 summary_consent_required => 'AI consent is required before sending data to an external provider',
276 summary_ai_unavailable => 'AI provider not configured; using template summary',
277 summary_provider_error => 'AI provider error; using template summary',
278 error_token_invalid => 'Share token is invalid or has expired',
279 error_token_missing => 'A share token is required to view this analysis',
280 freshness_stale_msg => 'Source data has changed since this analysis was last saved',
281 error_agg_fn => 'Unknown aggregate function "%s"; expected one of: %s, or p1 to p100 for a percentile',
282 error_range_name => 'Unknown time range "%s"; expected one of: %s',
283 error_range_column => 'A time range is applied to one column: add rcol=<column> to the URL',
284 error_filter_op => 'Unknown filter operator "%s" in f=%s; expected one of: %s',
285 error_filter_column => 'There is no column called "%s" to filter on (f=%s); the columns are: %s',
286 error_range_column_unknown => 'There is no column called "%s" for the time range (rcol=%s); the columns are: %s',
287 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',
288 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',
289 error_span_tcol_orphan => 'tcol=%s names the column to bucket, but span=<interval> is missing',
290 error_span_tcol_unknown => 'Column "%s" is not in this view, so there is nothing to bucket',
291 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',
292 error_span_name => 'Bucket column name "%s" is not a usable column name; add as=<name>',
293 error_cs_spec => 'cs=%s must be <column>:<function>:<alias>, optionally followed by :<parameter>',
294 error_cs_column => 'cs=%s names the column "%s", which is not in this view',
295 error_cs_fn => 'Unknown cross-row function "%s"; use one of: %s',
296 error_cs_alias => 'Cross-row alias "%s" is not a usable column name',
297 error_cs_conflict => 'Cross-row alias "%s" is already a column of this view, or another cs= already writes it; choose another name',
298 error_cs_arg => 'cs=%s: %s takes a whole number greater than zero, as in %s:%s:ma7:7',
299 error_cs_no_arg => 'cs=%s: %s takes no parameter',
300 error_cs_by => 'by=%s names "%s", which is not a column of this view',
301 error_cs_order => 'order=%s must be <column>, <column>:asc or <column>:desc',
302 error_cs_order_col => 'order=%s names "%s", which is not a column of this view',
303 error_cs_order_need => 'cs=%s needs order=: %s reads its rows in order, so the order has to be named',
304 );
305  
306 # Maximum accepted upload body size. Enforced both here (application layer)
307 # and via Mojolicious max_request_size (transport layer) set in startup().
308 # Must match $MAX_REQUEST_SIZE in BI.pm.
309 5 Readonly my $MAX_UPLOAD_MIB => 50;
310 5 Readonly my $MAX_UPLOAD_BYTES => $MAX_UPLOAD_MIB * 1_048_576;
311 5 Readonly my $DEFAULT_JOIN_MAX_ROWS => 10_000;
312 5 Readonly my $LOOKUP_MAX_BYTES => 8 * 1_048_576; # a bigger file is a join, not a lookup
313 5 Readonly my $LOOKUP_NAME_RE => qr/\A[A-Za-z_][A-Za-z0-9_]*\z/;
314 5 Readonly my $DEFAULT_MAP_GEOCODE_MAX => 500; # new lookups per request (map_geocode_max)
315 # Places looked up online (OpenStreetMap's Nominatim) per request. Nominatim
316 # allows one request a second, so this is roughly the seconds a page can wait
317 # for it: twenty keeps a page well inside hypnotoad's 50-second heartbeat, and
318 # script/bi-geocode, which has no page to hold, asks without a limit.
319 5 Readonly my $DEFAULT_MAP_GEOCODE_ONLINE_MAX => 20; # map_geocode_online_max
320 5 Readonly my $DEFAULT_MAP_MAX_MARKERS => 2_000; # markers drawn per request (map_max_markers)
321 5 Readonly my $DEFAULT_MAP_POPUP_ROWS => 10; # rows listed in one marker's popup (map_popup_rows)
322 5 Readonly my $DEFAULT_MARKER_COLOR => '#3388ff'; # Leaflet default blue
323 # A bubble map's size key: the bubbles' own colour when they have one, and
324 # this grey when the colour says something else (a colour column)
325 5 Readonly my $MAP_SIZE_KEY_COLOR => '#888888';
326 5 Readonly my %NAMED_COLORS => map { $_ => 1 } qw(
327 red orange yellow green teal cyan blue navy purple
328 magenta pink brown maroon olive silver gray grey gold lime white black
329 );
330 5 Readonly my $MAX_PREFIX_LEN => 20;
331 5 Readonly my $DEFAULT_PER_PAGE => 200;
332 5 Readonly my $MAX_PER_PAGE => 2_000;
333 # The page sizes offered under a table or pivot and on /preferences; 0 is every
334 # row on one page. The preference is the cookie $PAGE_SIZE_COOKIE (the server
335 # must see it before it reads the page), and only these values are taken from it.
336 5 Readonly my @PAGE_SIZES => (25, 50, 100, 200, 0);
337 5 Readonly my %PAGE_SIZE_OK => map { $_ => 1 } @PAGE_SIZES;
338 5 Readonly my $PAGE_SIZE_COOKIE => 'bi_per_page';
339 # per_page=0 (all rows) as a page size the arithmetic can use: one page that
340 # holds any table this application can read.
341 5 Readonly my $ALL_ROWS => 2_000_000_000;
342 5 Readonly my %SCATTER_SCHEMES => map { $_ => 1 } qw(tableau10 category10 set2 set3 paired);
343  
344 # Categorical palettes for map series colouring, matching the D3 schemes the
345 # chart pages offer. The map draws per-marker icons rather than D3 marks, so
346 # the hexes live here instead of in a template.
347 5 Readonly my %CATEGORY_PALETTES => (
348 tableau10 => [ '#4e79a7', '#f28e2c', '#e15759', '#76b7b2', '#59a14f',
349 '#edc949', '#af7aa1', '#ff9da7', '#9c755f', '#bab0ab' ],
350 category10 => [ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
351 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf' ],
352 set2 => [ '#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854',
353 '#ffd92f', '#e5c494', '#b3b3b3' ],
354 set3 => [ '#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3',
355 '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd',
356 '#ccebc5', '#ffed6f' ],
357 paired => [ '#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99',
358 '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a',
359 '#ffff99', '#b15928' ],
360 );
361  
362 # add_circle_marker() accepts only hex colours, while the icon path also takes
363 # the named colours _parse_color() allows. Map the names once, here.
364 5 Readonly my %NAMED_COLOR_HEX => (
365 red => '#ff0000', orange => '#ffa500', yellow => '#ffff00',
366 green => '#008000', teal => '#008080', cyan => '#00ffff',
367 blue => '#0000ff', navy => '#000080', purple => '#800080',
368 magenta => '#ff00ff', pink => '#ffc0cb', brown => '#a52a2a',
369 maroon => '#800000', olive => '#808000', silver => '#c0c0c0',
370 gray => '#808080', grey => '#808080', gold => '#ffd700',
371 lime => '#00ff00', white => '#ffffff', black => '#000000',
372 );
373  
374 # The aggregate function vocabulary shared by _measure, _grouped_totals, the
375 # /pivot measure-spec parser and the /stats view.
376 #
377 # It has two halves. @PUSHED_MEASURE_FNS are the functions
378 # Database::Abstraction's aggregate() computes in the backend: adding one here
379 # means adding it there as well. @PERL_MEASURE_FNS are computed by the Perl
380 # fold in _grouped_totals from all the values in a group, because a subtotal has
381 # to be recomputed from the rows rather than combined out of the cells (a median
382 # is not the sum of the medians of its parts), and because the app already holds
383 # the rows: the fold is one pass over records that are in memory, with no second
384 # implementation of the same statistic to agree with. Database::Abstraction
385 # does accept a median and a stddev measure, computing them in Perl over rows it
386 # materialises itself -- close enough to be tempting, and exactly the second
387 # implementation to avoid, so _measure_pushable refuses to send them.
388 #
389 # A percentile is spelled p<N>, for N from 1 to 100: p90, p99, p1. The level
390 # rides in the function name because the spec dialect is col:fn:as, with no
391 # room for a parameter in it; p50 is the median, and median is kept as its own
392 # name because that is what a reader looks for.
393 5 Readonly my @PUSHED_MEASURE_FNS => qw(sum avg min max count count_distinct);
394 5 Readonly my @PERL_MEASURE_FNS => qw(median stdev first last range);
395 5 Readonly my @MEASURE_FNS => (@PUSHED_MEASURE_FNS, @PERL_MEASURE_FNS);
396 5 Readonly my %PUSHED_MEASURE_FN_OK => map { $_ => 1 } @PUSHED_MEASURE_FNS;
397 5 Readonly my %MEASURE_FN_OK => map { $_ => 1 } @MEASURE_FNS;
398  
399 # _measure_percentile($fn) -> $level | undef
400 #
401 # The percentile level a measure function names, or undef when it names none:
402 # 'p95' -> 95, 'p50' -> 50, 'percentile' -> undef, 'sum' -> undef. A level
403 # outside 1..100 is not a percentile, so an unknown function still fails as an
404 # unknown function rather than as a percentile of -40.
405 37 ▶sub _measure_percentile {
Subroutine _measure_percentile: called CC=6 SCAR=17.9
406 37 my $fn = shift;
407 37 ▶ return undef unless defined $fn && length $fn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fn and length $fn 2 35 37
Condition100%3/3
defined $fn and length $fn
!ll&&!rl&&r
1135
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
408 35 my ($level) = $fn =~ /\Ap(\d{1,3})\z/;
409 35 ▶ return undef unless defined $level;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $level 18 17 35
410 17 ▶ return ($level >= 1 && $level <= 100) ? $level + 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$level >= 1 && $level <= 100 ? : 12 5 17
Condition100%3/3
$level >= 1 and $level <= 100
!ll&&!rl&&r
2312
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
411 }
412  
413 # _measure_fn_ok($fn) -> bool
414 #
415 # True for every function _grouped_totals can compute: the named ones and any
416 # percentile level. This is the single answer to "is this a measure function?"
417 # for the parser, and the vocabulary the 400 message prints comes from the same
418 # two lists, so a message can never list a function the fold cannot compute.
419 47 ▶sub _measure_fn_ok {
Subroutine _measure_fn_ok: called CC=5 SCAR=16.1
420 47 my $fn = shift;
421 47 ▶ return 0 unless defined $fn && length $fn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fn and length $fn 2 45 47
Condition100%3/3
defined $fn and length $fn
!ll&&!rl&&r
1145
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
422 45 ▶ return 1 if $MEASURE_FN_OK{$fn};
Branch: 1 branch
BranchTrueFalseTotal
if $MEASURE_FN_OK{$fn} 28 17 45
423 17 ▶ return defined _measure_percentile($fn) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined _measure_percentile($fn) ? : 7 10 17
424 }
425  
426 # ---------------------------------------------------------------------------
427 # Relative time ranges
428 #
429 # A relative time range is a named window worked out from the clock when the
430 # request arrives -- "the last 30 days", "this quarter" -- so a link, a
431 # bookmark or a saved canvas that carries one keeps meaning the same thing
432 # every time it is opened instead of freezing the dates it first resolved to.
433 #
434 # The range is named in the URL (?range=<name>&rcol=<column>) and resolved to
435 # two f= filters on that column, which every data route already applies, so the
436 # table view, the charts, the pivot, the stats page, the insights page, the
437 # exports and a saved canvas all see the same rows.
438 #
439 # The vocabulary is day-granular except last_24_hours, which is to the second.
440 # ---------------------------------------------------------------------------
441  
442 5 Readonly my @TIME_RANGES => (
443 { name => 'last_24_hours', label => 'Last 24 hours', hours => 24 },
444 { name => 'today', label => 'Today', day => 0 },
445 { name => 'yesterday', label => 'Yesterday', day => -1 },
446 { name => 'last_7_days', label => 'Last 7 days', days => 7 },
447 { name => 'last_30_days', label => 'Last 30 days', days => 30 },
448 { name => 'last_90_days', label => 'Last 90 days', days => 90 },
449 { name => 'this_month', label => 'This month', month => 0 },
450 { name => 'last_month', label => 'Last month', month => -1 },
451 { name => 'this_quarter', label => 'This quarter', quarter => 0 },
452 { name => 'last_quarter', label => 'Last quarter', quarter => -1 },
453 { name => 'this_year', label => 'This year', year => 0 },
454 { name => 'last_year', label => 'Last year', year => -1 },
455 );
456 5 Readonly my %TIME_RANGE => map { $_->{name} => $_ } @TIME_RANGES;
457  
458 # The operators an f= filter may name (_apply_filter_spec), as written: an
459 # operator in capitals is refused with the rest, not read as another one.
460 5 Readonly my @FILTER_OPS => qw(eq ne contains starts lt le gt ge empty notempty between in);
461 5 Readonly my %FILTER_OP => map { $_ => 1 } @FILTER_OPS;
462  
463 # How many column names a refusal lists before it says how many more there are.
464 5 Readonly my $FILTER_COLUMNS_LISTED => 20;
465  
466 # Allowed strptime-style date format patterns for the /dates/save endpoint, and
467 # the two time patterns that may be given beside one of them for a column that
468 # holds a clock time as well as a date.
469 5 Readonly my %ALLOWED_DATE_PATTERNS => map { $_ => 1 }
470 qw(%m/%d/%Y %d/%m/%Y %d-%b-%Y);
471 5 Readonly my %ALLOWED_TIME_PATTERNS => map { $_ => 1 }
472 qw(%H:%M %H:%M:%S);
473  
474 # Default share token lifetime: 30 days in seconds.
475 5 Readonly my $SHARE_TOKEN_TTL => 30 * 86_400;
476  
477 # The AI routes spend the configured ai_api_key on every call. A question is
478 # at most this long, and each server process makes at most ai_calls_per_hour
479 # provider calls in any hour (0: no limit).
480 5 Readonly my $ASK_MAX_QUESTION => 500;
481 5 Readonly my $AI_CALLS_PER_HOUR => 60;
482 5 Readonly my $AI_WINDOW_S => 3600;
483  
484 # ---------------------------------------------------------------------------
485 # Protected helpers
486 # ---------------------------------------------------------------------------
487  
488 # _whole_number($value) -> $integer | undef
489 #
490 # A request parameter as an integer, or undef if it does not spell one. int()
491 # on the raw text warns on 'abc' and turns it into 0, and reads a long run of
492 # digits or '1e400' as infinity, which no LIMIT or OFFSET can use.
493 727 ▶sub _whole_number {
Subroutine _whole_number: called CC=3 SCAR=11.0
494 727 my $value = $_[0];
495 727 ▶ return undef unless defined($value) && $value =~ /\A-?\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value =~ /\A-?\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u 672 55 727
Condition100%3/3
defined $value and $value =~ /\A-?\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u
!ll&&!rl&&r
6225055
MC/DC100%2/2
defined $value and $value =~ /\A-?\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u
defined $value $value =~ /\A-?\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u
Truth table100%3/3
A and B
A= defined $valueB= $value =~ /\A-?\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u
ABresult
0X0
100
111
496 55 return $value + 0;
497 }
498  
499 # _categorical_scheme($name) -> $name
500 # _sequential_scheme($name) -> $name
501 #
502 # A colour scheme the chart can use, or the default. These must be checked here:
503 # HTML::D3 writes a categorical name into its script as SCHEMES['name'], so an
504 # unchecked value is script on the page, and it dies on a sequential name it does
505 # not know, which is a 500. An unknown name has always drawn the default colours.
506 113 ▶sub _categorical_scheme {
Subroutine _categorical_scheme: called CC=4 SCAR=13.9
507 113 my $name = $_[0];
508 113 ▶ return (defined($name) && !ref($name) && $SCATTER_SCHEMES{$name}) ? $name : $DEFAULT_CATEGORICAL_SCHEME;
Branch: 1 branch
BranchTrueFalseTotal
defined $name && !ref($name) && $SCATTER_SCHEMES{$name} ? : 1 112 113
Condition100%6/6
defined $name and not ref $name and $SCATTER_SCHEMES{$name}
!ll&&!rl&&r
100121
defined $name and not ref $name
!ll&&!rl&&r
99113
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
509 }
510  
511 115 ▶sub _sequential_scheme {
Subroutine _sequential_scheme: called CC=4 SCAR=13.9
512 115 my $name = $_[0];
513 115 ▶ return (defined($name) && !ref($name) && $SEQUENTIAL_SCHEMES{$name}) ? $name : $DEFAULT_SEQUENTIAL_SCHEME;
Branch: 1 branch
BranchTrueFalseTotal
defined $name && !ref($name) && $SEQUENTIAL_SCHEMES{$name} ? : 1 114 115
Condition100%6/6
defined $name and not ref $name and $SEQUENTIAL_SCHEMES{$name}
!ll&&!rl&&r
104101
defined $name and not ref $name
!ll&&!rl&&r
103111
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
514 }
515  
516 # _optional_scheme($name) -> $name | undef
517 #
518 # A categorical scheme for a chart that draws its own colours without one:
519 # a histogram's bars are steelblue, a combo's bars and line steelblue and red,
520 # and a scheme replaces them with its first colours. Unlike
521 # _categorical_scheme there is no scheme by default, so a name that is not one
522 # of the five is undef and the chart keeps the colours it had before scheme=
523 # existed. /histogram, /combo and their canvas cards all read it here.
524 109 ▶sub _optional_scheme {
Subroutine _optional_scheme: called CC=4 SCAR=13.9
525 109 my $name = $_[0];
526 109 ▶ return (defined($name) && !ref($name) && $SCATTER_SCHEMES{$name}) ? $name : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $name && !ref($name) && $SCATTER_SCHEMES{$name} ? : 5 104 109
Condition100%6/6
defined $name and not ref $name and $SCATTER_SCHEMES{$name}
!ll&&!rl&&r
9595
defined $name and not ref $name
!ll&&!rl&&r
94114
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
527 }
528  
529 # _scatter_radii($min, $max) -> ($min, $max)
530 #
531 # A scatter's bubble radius range in pixels: each value a whole number clamped
532 # to 1..40, anything else (absent, empty, 0, text) the default 3 or 15, and the
533 # pair put in order rather than refused. /scatter and a canvas scatter card
534 # both read it here, so a card saved from the page draws the same bubbles.
535 53 ▶sub _scatter_radii {
Subroutine _scatter_radii: called CC=8 SCAR=20.8
536 53 ▶ my ($min, $max) = map { _whole_number(ref $_ ? undef : $_) } @_[0, 1];
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 1 105 106
537 53 ▶ $min = 3 unless $min;
Branch: 1 branch
BranchTrueFalseTotal
unless $min 51 2 53
538 53 ▶ $max = 15 unless $max;
Branch: 1 branch
BranchTrueFalseTotal
unless $max 51 2 53
539 53 for ($min, $max) {
540 106 ▶ $_ = 1 if $_ < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $_ < 1 1 105 106
541 106 ▶ $_ = 40 if $_ > 40;
Branch: 1 branch
BranchTrueFalseTotal
if $_ > 40 1 105 106
542 }
543 53 ▶ return $min > $max ? ($max, $min) : ($min, $max);
Branch: 1 branch
BranchTrueFalseTotal
$min > $max ? : 1 52 53
544 }
545  
546 # _pagination($self) -> ($page, $per_page, $offset)
547 #
548 # Reads ?page= and ?per_page= from the current request, clamps them to sane
549 # ranges, and returns the 1-based page number, the page size, and the
550 # 0-based row offset. Without per_page= the size is the reader's preference
551 # (_page_size_preference), else DEFAULT_PER_PAGE. 0 is every row: one page of
552 # $ALL_ROWS, so it bypasses MAX_PER_PAGE, which bounds only a number typed in
553 # the URL.
554 #
555 # Also stashes, for layouts/page_size.html.tt: page_size (0 for every row),
556 # page_size_asked (the URL named one) and page_size_choices.
557 234 ▶sub _pagination {
Subroutine _pagination: called CC=12 SCAR=25.1
558 234 my $self = $_[0];
559  
560 234 ▶ 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
215316
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
561 234 my $asked = _whole_number($self->param('per_page'));
562 234 ▶ $asked = _page_size_preference($self) unless defined $asked;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $asked 231 3 234
563  
564 234 my ($per_page, $page);
565 234 ▶ if (defined $asked && $asked == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $asked and $asked == 0) { } 0 234 234
Condition66%2/3
defined $asked and $asked == 0
!ll&&!rl&&r
23130
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
566 0 ($per_page, $page) = ($ALL_ROWS, 1);
567 } else {
568 234 ▶ $per_page = $asked || $DEFAULT_PER_PAGE;
Condition66%2/3
$asked || $DEFAULT_PER_PAGE
l!l&&r!l&&!r
32310
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
569 234 ▶ $per_page = 1 if $per_page < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $per_page < 1 1 233 234
570 234 ▶ $per_page = $MAX_PER_PAGE if $per_page > $MAX_PER_PAGE;
Branch: 1 branch
BranchTrueFalseTotal
if $per_page > $MAX_PER_PAGE 1 233 234
571 234 ▶ $page = _whole_number($self->param('page')) || 1;
Condition100%2/2
_whole_number($self->param('page')) || 1
l!l
2232
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
572 234 ▶ $page = 1 if $page < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $page < 1 1 233 234
573 }
574 234 my $offset = ($page - 1) * $per_page;
575  
576 234 ▶ $self->stash(
Branch: 2 branches
BranchTrueFalseTotal
$per_page == $ALL_ROWS ? : 0 234 234
$asked_in_url ? : 16 218 234
577 page_size => ($per_page == $ALL_ROWS ? 0 : $per_page),
578 page_size_asked => ($asked_in_url ? 1 : 0),
579 page_size_choices => [ @PAGE_SIZES ],
580 );
581 234 return ($page, $per_page, $offset);
582 }
583  
584 # _page_size_preference($self) -> $size | undef
585 #
586 # The page size set on /preferences, from the bi_per_page cookie: one of
587 # @PAGE_SIZES (0 = every row), or undef when there is none or it is anything
588 # else.
589 232 ▶sub _page_size_preference {
Subroutine _page_size_preference: called CC=4 SCAR=19.7
590 232 my $self = $_[0];
591 232 my $value = $self->cookie($PAGE_SIZE_COOKIE);
592 232 ▶ return undef unless defined $value && $value =~ /\A\d{1,4}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value =~ /\A\d{1,4}\z/u 232 0 232
Condition33%1/3
defined $value and $value =~ /\A\d{1,4}\z/u
!ll&&!rl&&r
23200
MC/DC0%0/2
defined $value and $value =~ /\A\d{1,4}\z/u
defined $value $value =~ /\A\d{1,4}\z/u
Truth table33%1/3
A and B
A= defined $valueB= $value =~ /\A\d{1,4}\z/u
ABresult
0X0
100
111
593 0 $value += 0;
594 0 ▶ return $PAGE_SIZE_OK{$value} ? $value : undef;
Branch: 1 branch
BranchTrueFalseTotal
$PAGE_SIZE_OK{$value} ? : 0 0 0
595 }
596  
597 # _message_text($key) -> $template | undef
598 #
599 # The %MESSAGES template for $key in the reader's language (Database::BI::I18N,
600 # which CGI::Lingua chose from the request's Accept-Language). A plain function:
601 # the package-level checks (request_refusal, _outside_roots) have no $self.
602 690 ▶sub _message_text ($key) {
Subroutine _message_text: called CC=1 SCAR=0.0
603 690 return Database::BI::I18N::text(__PACKAGE__, \%MESSAGES, $key);
604 }
605  
606 # _i18n($self, $key, @sprintf_args) -> $string
607 #
608 # Purpose: Look up a user-visible string from %MESSAGES and apply sprintf
609 # for positional arguments. The entry point for future i18n
610 # backend integration (e.g. Locale::Maketext).
611 # Entry: $key must be a key in %MESSAGES; @args are sprintf positionals.
612 # Exit: Returns the formatted string, or a fallback containing $key.
613 316 ▶sub _i18n :Protected ($self, $key, @args) {
Subroutine _i18n: called CC=3 SCAR=11.0
614 316 ▶ 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
3151
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
615 315 ▶ return @args ? sprintf($tmpl, @args) : $tmpl;
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 151 164 315
616 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
617  
618 # _file_roots($self) -> @roots
619 #
620 # Purpose: The folders a reader may browse, open files in and export to.
621 # Entry: Config file_roots: unset or [] for the whole filesystem, else a list
622 # of folders (a relative one is under the application home).
623 # Exit: () when unrestricted; otherwise the realpath of each root that
624 # exists, plus data_dir and uploads_dir, which the application itself
625 # uses (the home page lists data_dir; dropped files go to uploads_dir).
626 425 ▶sub _file_roots :Protected ($self) {
Subroutine _file_roots: called CC=3 SCAR=15.1
627 425 my $roots = $self->app->config('file_roots');
628 0 ▶ return () unless ref($roots) eq 'ARRAY' && @{$roots};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $roots eq "ARRAY" and @{$roots;} 425 0 425
Condition33%1/3
ref $roots eq "ARRAY" and @{$roots;}
!ll&&!rl&&r
42500
MC/DC0%0/2
ref $roots eq "ARRAY" and @{$roots;}
ref $roots eq "ARRAY" @{$roots;}
Truth table33%1/3
A and B
A= ref $roots eq "ARRAY"B= @{$roots;}
ABresult
0X0
100
111
629 0 return _real_folders($self, $roots, _data_dir_for($self->app), $self->app->_uploads_dir);
630 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
631  
632 # _export_dirs($self) -> @realpaths
633 #
634 # Config export_dirs, as realpaths: the only folders POST /export may write
635 # in, and the Export panel may list, when set. Empty when unset.
636 34 ▶sub _export_dirs :Protected ($self) {
Subroutine _export_dirs: called CC=3 SCAR=15.1
637 34 my $dirs = $self->app->config('export_dirs');
638 0 ▶ return () unless ref($dirs) eq 'ARRAY' && @{$dirs};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $dirs eq "ARRAY" and @{$dirs;} 34 0 34
Condition33%1/3
ref $dirs eq "ARRAY" and @{$dirs;}
!ll&&!rl&&r
3400
MC/DC0%0/2
ref $dirs eq "ARRAY" and @{$dirs;}
ref $dirs eq "ARRAY" @{$dirs;}
Truth table33%1/3
A and B
A= ref $dirs eq "ARRAY"B= @{$dirs;}
ABresult
0X0
100
111
639 0 return _real_folders($self, $dirs);
640 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
641  
642 # _real_folders($self, \@configured, @always) -> @realpaths
643 #
644 # The configured folders (relative ones under the application home) and
645 # @always, resolved, without repeats. A list none of which resolves gives a
646 # folder that cannot exist, so that it fences everything out rather than
647 # nothing. Resolved as a requested path is (_resolved_path), so a folder
648 # configured through a link is compared as the folder it leads to: on
649 # Windows realpath keeps the link, while _resolved_path follows it, and every
650 # path inside such a folder was refused.
651 0 ▶sub _real_folders {
Subroutine _real_folders: not called CC=9 SCAR=45.0
652 0 my ($self, $list, @always) = @_;
653 0 my $home = $self->app->home;
654 0 ▶ my @dirs = map { File::Spec->file_name_is_absolute($_) ? Mojo::File->new($_) : $home->child($_) }
Branch: 1 branch
BranchTrueFalseTotal
'File::Spec'->file_name_is_absolute($_) ? : 0 0 0
655 0 ▶ grep { defined && !ref && length } @{$list};
Condition0%0/6
defined $_ && !ref($_) && length $_
!ll&&!rl&&r
000
defined $_ and not ref $_
!ll&&!rl&&r
000
MC/DC0%0/3
defined $_ && !ref($_) && length $_
defined $_ not ref $_ length $_
Truth table0%0/4
A and not(B) && C
A= defined $_B= not ref $_C= length $_
ABCresult
0XX0
10X0
1100
1111
656 0 my (%seen, @real);
657 0 for my $dir (@dirs, @always) {
658 0 ▶ next unless -e "$dir";
Branch: 1 branch
BranchTrueFalseTotal
unless -e "$dir" 0 0 0
659 0 ▶ my $real = _resolved_path("$dir") // next;
Condition0%0/2
_resolved_path("$dir") // (next)
l!l
00
MC/DC0%0/1
_resolved_path("$dir") // (next)
_resolved_path("$dir")
Truth table0%0/2
A
A= _resolved_path("$dir")
Aresult
11
00
660 0 ▶ push @real, $real unless $seen{$real}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$real}++ 0 0 0
661 }
662 0 ▶ return @real ? @real : ('/nonexistent-file-root');
Branch: 1 branch
BranchTrueFalseTotal
@real ? : 0 0 0
663 }
664  
665 # _inside_any($path, @folders) -> 1 | 0
666 #
667 # Whether a path, resolved as _resolved_path does, is one of the folders or
668 # inside one.
669 2 ▶sub _inside_any {
Subroutine _inside_any: called CC=9 SCAR=24.6
670 2 my ($path, @folders) = @_;
671 2 ▶ my $abs = defined $path && length $path ? _resolved_path($path) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $path && length $path ? : 2 0 2
Condition33%1/3
defined $path and length $path
!ll&&!rl&&r
002
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
672 2 ▶ return 0 unless defined $abs;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $abs 0 2 2
673 2 $abs = _path_key($abs);
674 2 for my $root (map { _path_key($_) } @folders) {
675 2 ▶ 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 1 2
$root =~ m[/\z]u ? : 0 2 2
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
011
$root eq "/" or $abs eq $root
l!l&&r!l&&!r
002
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
676 || index($abs, $root =~ m{/\z} ? $root : "$root/") == 0;
677 }
678 1 return 0;
679 }
680  
681 # _path_key($path) -> $string
682 #
683 # A path in the form two spellings of one place share, for comparing. On
684 # Windows, Cwd::realpath gives C:/dir while File::Spec gives C:\dir, and names
685 # are not case-sensitive, so separators become / and letters lower case.
686 4 ▶sub _path_key {
Subroutine _path_key: called CC=2 SCAR=7.0
687 4 my ($path) = @_;
688 4 ▶ return $path unless $^O eq 'MSWin32';
Branch: 1 branch
BranchTrueFalseTotal
unless $^O eq "MSWin32" 0 4 4
689 4 (my $key = $path) =~ tr{\\}{/};
690 4 return lc $key;
691 }
692  
693 # _outside_export_dirs($self, $path) -> $message | undef
694 #
695 # Purpose: Refuse an export folder outside config export_dirs.
696 # Exit: undef when export_dirs is unset or the folder is inside one.
697 33 ▶sub _outside_export_dirs :Protected ($self, $path) {
Subroutine _outside_export_dirs: called CC=4 SCAR=24.4
698 33 ▶ my @dirs = _export_dirs($self) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my(@dirs) = _export_dirs($self) or return undef 0 33 33
699 0 ▶ return undef if _inside_any($path, @dirs);
Branch: 1 branch
BranchTrueFalseTotal
if _inside_any($path, @dirs) 0 0 0
700 0 ▶ return sprintf(_message_text('error_outside_export_dirs'), $path // '');
Condition0%0/2
$path // ""
l!l
00
MC/DC0%0/1
$path // ""
$path
Truth table0%0/2
A
A= $path
Aresult
11
00
701 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
702  
703 # _resolved_path($path) -> $absolute | undef
704 #
705 # Purpose: Where a path really leads, whether or not it exists, so that a
706 # path outside the roots is refused the same way whether it names
707 # something or not (else the refusal would say what exists there).
708 # Entry: A path as given.
709 # Exit: The realpath of its longest existing part, with the rest appended;
710 # undef when the rest climbs with '..', which cannot be followed
711 # without the folders it would climb out of, or when, on Windows,
712 # the links it goes through loop.
713 5 ▶sub _resolved_path {
Subroutine _resolved_path: called CC=9 SCAR=22.5
714 5 my ($path) = @_;
715 5 my $abs = File::Spec->rel2abs($path);
716 # Cwd::realpath on Windows leaves a symlink as it is (Strawberry Perl
717 # 5.42 gives the link's own path back), so a link inside file_roots or
718 # export_dirs that points outside would be taken as inside. The links are
719 # followed first, as _canonical_path does; a chain that loops is refused.
720 5 ▶ if ($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq "MSWin32") 5 0 5
721 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
722 }
723 4 my @parts = File::Spec->splitdir($abs);
724 4 my @rest;
725 4 ▶ while (@parts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parts) 6 0 6
726 6 my $try = File::Spec->catdir(@parts);
727 6 ▶ $try = File::Spec->rootdir unless length $try;
Branch: 1 branch
BranchTrueFalseTotal
unless length $try 0 6 6
728 6 ▶ if (-e $try) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $try) 4 2 6
729 4 ▶ 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
40
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
730 4 ▶ return undef if grep { $_ eq '..' } @rest;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_ eq "..";} @rest 0 4 4
731 4 ▶ return @rest ? File::Spec->catdir($real, @rest) : $real;
Branch: 1 branch
BranchTrueFalseTotal
@rest ? : 1 3 4
732 }
733 2 unshift @rest, pop @parts;
734 }
735 0 return undef;
736 }
737  
738 # _outside_roots($self, $path) -> $message | undef
739 #
740 # Purpose: Refuse a local path outside config file_roots.
741 # Entry: A path a request named (a file or a folder).
742 # Exit: undef when there are no roots or the path is inside one; otherwise
743 # error_outside_roots naming the path as it was given.
744 425 ▶sub _outside_roots :Protected ($self, $path) {
Subroutine _outside_roots: called CC=4 SCAR=24.4
745 425 ▶ my @roots = _file_roots($self) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my(@roots) = _file_roots($self) or return undef 0 425 425
746 0 ▶ return undef if _inside_any($path, @roots);
Branch: 1 branch
BranchTrueFalseTotal
if _inside_any($path, @roots) 0 0 0
747 0 ▶ return sprintf(_message_text('error_outside_roots'), $path // '');
Condition0%0/2
$path // ""
l!l
00
MC/DC0%0/1
$path // ""
$path
Truth table0%0/2
A
A= $path
Aresult
11
00
748 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
749  
750 # _first_root($self) -> $folder
751 #
752 # Where /browse and /api/dirs start with no path=: the home folder, unless
753 # that is outside the roots, when the first root is.
754 44 ▶sub _first_root :Protected ($self) {
Subroutine _first_root: called CC=3 SCAR=14.2
755 44 ▶ my $home = $ENV{HOME} // File::Spec->rootdir;
Condition33%1/3
$ENV{"HOME"} // "File::Spec"->rootdir
l!l&&r!l&&!r
4400
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
756 44 ▶ return $home unless _outside_roots($self, $home);
Branch: 1 branch
BranchTrueFalseTotal
unless _outside_roots($self, $home) 44 0 44
757 0 return (_file_roots($self))[0];
758 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
759  
760 # request_refusal($c) -> $message | undef
761 #
762 # Purpose: Refuse a request that a hostile web page made through the reader's
763 # browser. The application has no login, so whatever can reach it
764 # can write files (POST /export) and read any file (/open); listening
765 # on 127.0.0.1 keeps other machines out but not other sites' pages.
766 # Entry: A controller of the application, before dispatch.
767 # Exit: The refusal message, or undef to let the request through.
768 #
769 # Three checks:
770 # * No password, so only this machine: a request from an address that is
771 # not loopback (as a trusted proxy reports it) is refused.
772 # * DNS rebinding. A page on evil.example whose name is made to resolve to
773 # 127.0.0.1 is the same origin as this server to the browser, so it can
774 # read the replies too. It still names its own host, so the Host must be
775 # localhost, *.localhost, an IP address, or a name in config allowed_hosts
776 # (['*'] lets every name in). Behind a trusted reverse proxy, whose Host is
777 # whatever the proxy sends, only allowed_hosts is checked, when it is set.
778 # * Cross-site writes. A form POST from another site needs no preflight.
779 # For any method but GET, HEAD and OPTIONS, Sec-Fetch-Site (set by the
780 # browser, not the page) must be same-origin or none; without it, an
781 # Origin must name this host and port. A request with neither is a
782 # script or an old browser, and is let through: it is not a page of
783 # another site acting with the reader's browser.
784 2184 ▶sub request_refusal {
Subroutine request_refusal: called CC=35 SCAR=59.3
Pod documented
785 2184 my ($c) = @_;
786 2184 my $req = $c->req;
787  
788 # With no password, only this machine. Startup already refuses to listen
789 # anywhere else, but a reverse proxy on this machine can still bring other
790 # machines' requests in; trusted, it names them in X-Forwarded-For, which
791 # is what remote_address then reads. A Unix socket has no address, and is
792 # this machine.
793 2184 my $hash = $c->app->config('password_hash');
794 2184 ▶ unless (defined $hash && length $hash) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $hash and length $hash) 2184 0 2184
Condition33%1/3
defined $hash and length $hash
!ll&&!rl&&r
218400
MC/DC0%0/2
defined $hash and length $hash
defined $hash length $hash
Truth table33%1/3
A and B
A= defined $hashB= length $hash
ABresult
0X0
100
111
795 2184 ▶ my $from = $c->tx->remote_address // '';
Condition50%1/2
$c->tx->remote_address // ""
l!l
21840
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
796 2184 ▶ return _message_text('error_remote_needs_password')
Branch: 1 branch
BranchTrueFalseTotal
unless $from eq "" or $from =~ /\A(?:::ffff:)?127\./iu or $from eq "::1" 0 2184 2184
Condition33%2/6
$from eq "" or $from =~ /\A(?:::ffff:)?127\./iu or $from eq "::1"
l!l&&r!l&&!r
218400
$from eq "" or $from =~ /\A(?:::ffff:)?127\./iu
l!l&&r!l&&!r
021840
MC/DC0%0/3
$from eq "" or $from =~ /\A(?:::ffff:)?127\./iu or $from eq "::1"
$from eq "" $from =~ /\A(?:::ffff:)?127\./iu $from eq "::1"
Truth table25%1/4
A or B or C
A= $from eq ""B= $from =~ /\A(?:::ffff:)?127\./iuC= $from eq "::1"
ABCresult
1XX1
01X1
0011
0000
797 unless $from eq '' || $from =~ /\A(?:::ffff:)?127\./i || $from eq '::1';
798 }
799  
800 2184 ▶ my $host = lc($req->url->to_abs->host // '');
Condition50%1/2
$req->url->to_abs->host // ""
l!l
21840
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
801 2184 ▶ if (length $host) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $host) 2184 0 2184
802 2184 my $allowed = $c->app->config('allowed_hosts');
803 0 ▶ my @allowed = ref($allowed) eq 'ARRAY' ? map { lc } grep { defined && !ref } @{$allowed} : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $allowed eq 'ARRAY' ? : 0 2184 2184
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
804 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
805 2184 ▶ my $local = $host eq 'localhost' || $host =~ /\.localhost\z/
Condition33%3/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
218400
$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
021840
$host eq "localhost" or $host =~ /\.localhost\z/u
l!l&&r!l&&!r
002184
MC/DC0%0/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 table20%1/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
806 || $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/ || $host =~ /[:\[]/;
807 2184 ▶ my $ok = $req->reverse_proxy ? (!@allowed || $listed) : ($local || $listed);
Branch: 1 branch
BranchTrueFalseTotal
$req->reverse_proxy ? : 0 2184 2184
Condition16%1/6
not @allowed or $listed
l!l&&r!l&&!r
000
$local or $listed
l!l&&r!l&&!r
218400
MC/DC0%0/2
not @allowed or $listed
not @allowed $listed
MC/DC0%0/2
$local or $listed
$local $listed
Truth table0%0/3
not(A) or B
A= not @allowedB= $listed
ABresult
1X1
011
000
Truth table33%1/3
A or B
A= $localB= $listed
ABresult
1X1
011
000
808 2184 ▶ return sprintf(_message_text('error_host_refused'), $host) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 2184 2184
809 }
810  
811 2184 ▶ return if $req->method =~ /\A(?:GET|HEAD|OPTIONS)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $req->method =~ /\A(?:GET|HEAD|OPTIONS)\z/u 1946 238 2184
812  
813 238 my $headers = $req->headers;
814 238 ▶ my $site = lc($headers->header('Sec-Fetch-Site') // '');
Condition50%1/2
$headers->header("Sec-Fetch-Site") // ""
l!l
0238
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
815 238 ▶ if (length $site) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $site) 0 238 238
816 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
817 0 return sprintf(_message_text('error_cross_site'), $site);
818 }
819 238 my $origin = $headers->origin;
820 238 ▶ return unless defined $origin;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $origin 238 0 238
821 0 ▶ my $from = lc(Mojo::URL->new($origin)->host_port // '');
Condition0%0/2
"Mojo::URL"->new($origin)->host_port // ""
l!l
00
MC/DC0%0/1
"Mojo::URL"->new($origin)->host_port // ""
"Mojo::URL"->new($origin)->host_port
Truth table0%0/2
A
A= "Mojo::URL"->new($origin)->host_port
Aresult
11
00
822 0 ▶ my $to = lc($req->url->to_abs->host_port // '');
Condition0%0/2
$req->url->to_abs->host_port // ""
l!l
00
MC/DC0%0/1
$req->url->to_abs->host_port // ""
$req->url->to_abs->host_port
Truth table0%0/2
A
A= $req->url->to_abs->host_port
Aresult
11
00
823 0 ▶ my $fwd = $req->reverse_proxy ? lc($headers->header('X-Forwarded-Host') // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
$req->reverse_proxy ? : 0 0 0
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
824 0 ▶ 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 0 0
Condition0%0/9
length $from and $from eq $to || length $fwd && $from eq $fwd
!ll&&!rl&&r
000
$from eq $to or length $fwd and $from eq $fwd
l!l&&r!l&&!r
000
length $fwd and $from eq $fwd
!ll&&!rl&&r
000
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 table0%0/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
825 0 return sprintf(_message_text('error_cross_site'), $origin);
826 }
827  
828 # _is_safe_url($url) -> bool
829 #
830 # Purpose: The quick SSRF check on a URL a request names (/import, url:
831 # specs), before anything is fetched, so the reader is told at once.
832 # Entry: The URL.
833 # Exit: 0 for anything but http(s), no host, localhost or *.localhost, or a
834 # host written as an address that is not public; else 1.
835 #
836 # It reads the URL as LWP will (URI: so http://user@127.0.0.1/ is host
837 # 127.0.0.1), and an address in every spelling the resolver accepts
838 # (2130706433, 0x7f000001, 0177.0.0.1, 127.1, [::ffff:127.0.0.1]). It does not
839 # look names up: a name such as localtest.me, or one whose DNS answers
840 # 127.0.0.1, is refused when it is fetched, by Database::BI::SafeUA, which
841 # resolves each request (and each redirect), checks every address, and
842 # connects to the one it checked, so a second DNS answer cannot differ.
843 32 ▶sub _is_safe_url {
Subroutine _is_safe_url: called CC=13 SCAR=26.8
844 32 my ($url) = @_;
845 32 ▶ return 0 unless defined $url && $url =~ m{\Ahttps?://}i;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and $url =~ m[\Ahttps?://]iu 3 29 32
Condition66%2/3
defined $url and $url =~ m[\Ahttps?://]iu
!ll&&!rl&&r
0329
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
846 29 require URI;
847 29 require Database::BI::SafeUA;
848 29 my $uri = URI->new($url);
849 29 ▶ my $host = eval { lc($uri->host // '') } // '';
Condition50%2/4
eval { do { lc($uri->host // "") } } // ""
l!l
290
$uri->host // ""
l!l
290
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
850 29 $host =~ s/\.\z//;
851 29 ▶ return 0 unless length $host;
Branch: 1 branch
BranchTrueFalseTotal
unless length $host 0 29 29
852 # A host that is neither a name nor an IPv6 address is not a URL LWP
853 # would read the same way (http://::1/ has the host ':').
854 29 ▶ 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) 0 29 29
Condition50%3/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
2810
$host =~ /:/u and defined Database::BI::SafeUA::numeric_host($host)
!ll&&!rl&&r
001
MC/DC0%0/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 table50%2/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
855 || ($host =~ /:/ && defined Database::BI::SafeUA::numeric_host($host));
856 29 ▶ return 0 if $host eq 'localhost' || $host =~ /\.localhost\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $host eq "localhost" or $host =~ /\.localhost\z/u 4 25 29
Condition66%2/3
$host eq "localhost" or $host =~ /\.localhost\z/u
l!l&&r!l&&!r
4025
MC/DC50%1/2
$host eq "localhost" or $host =~ /\.localhost\z/u
$host eq "localhost" $host =~ /\.localhost\z/u
Truth table66%2/3
A or B
A= $host eq "localhost"B= $host =~ /\.localhost\z/u
ABresult
1X1
011
000
857 25 my $ip = Database::BI::SafeUA::numeric_host($host);
858 25 ▶ 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) 15 10 25
Condition100%3/3
defined $ip and Database::BI::SafeUA::blocked_address($ip)
!ll&&!rl&&r
4615
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
859 10 return 1;
860 }
861  
862 # _safe_back_url($url) -> $url | undef
863 #
864 # Purpose: Sanitise a user-supplied back-link URL before it is passed to the
865 # template and rendered inside an href="" attribute. Template Toolkit's
866 # | html filter encodes <>&" but does NOT block the javascript: or
867 # data: URI schemes, so a raw param('back') = "javascript:alert(1)"
868 # would be rendered verbatim inside the href and execute on click.
869 #
870 # Rule: Only absolute http(s) URLs and root-relative paths (starting with /)
871 # are permitted. Anything else (javascript:, data:, vbscript:, empty
872 # strings, undef) returns undef so the template renders no href.
873 #
874 4806 ▶sub _safe_back_url {
Subroutine _safe_back_url: called CC=4 SCAR=13.9
875 4806 my ($url) = @_;
876 4806 ▶ return undef unless defined $url && length($url);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and length $url 3786 1020 4806
Condition100%3/3
defined $url and length $url
!ll&&!rl&&r
3741451020
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
877 1020 ▶ return $url if $url =~ m{\A(?:/(?!/)|https?://)}i;
Branch: 1 branch
BranchTrueFalseTotal
if $url =~ m[\A(?:/(?!/)|https?://)]iu 958 62 1020
878 62 return undef;
879 }
880  
881 # ---------------------------------------------------------------------------
882 # Breadcrumb trail
883 # ---------------------------------------------------------------------------
884 #
885 # Every page shows Home > ... > the page itself. The trail is not passed in:
886 # each page's URL already names the page it was opened from (a chart's back=,
887 # a table's back2= when it was drilled into from a chart), and that URL names
888 # its own, so the whole path is recovered by following the links up. Each
889 # step is named from its own URL by one function, so a crumb always reads the
890 # same whichever page it appears on.
891  
892 # The chart and analysis routes, which name their parent with back=.
893 5 Readonly my %CRUMB_KIND => (
894 graph => 'Line graph', line => 'Line graph',
895 pie => 'Pie chart', heatmap => 'Heatmap',
896 bar => 'Bar chart', stacked => 'Stacked bar chart',
897 scatter => 'Scatter plot', combo => 'Combo chart',
898 treemap => 'Treemap', histogram => 'Histogram',
899 wordcloud => 'Word cloud', map => 'Map',
900 pivot => 'Pivot table', stats => 'Column stats',
901 insights => 'Insights', folder => 'Folder view',
902 );
903  
904 # How a filter reads in a crumb: "region = East".
905 5 Readonly my %CRUMB_OP => (
906 eq => '=', ne => '!=', contains => 'contains', starts => 'starts with',
907 lt => '<', le => '<=', gt => '>', ge => '>=', between => 'between',
908 empty => 'is empty', notempty => 'is not empty', in => 'is one of',
909 );
910  
911 # A trail is never longer than this, whatever the URLs say.
912 5 Readonly my $CRUMB_MAX_DEPTH => 8;
913  
914 # A column name or filter value that a crumb will repeat. The URL is the
915 # user's, so a crafted one could put any text in the trail; markup and
916 # over-long values are left out and the crumb names the page more generally.
917 5 Readonly my $CRUMB_TEXT_RE => qr/\A[^<>"\x00-\x1f]{1,64}\z/;
918  
919 # _breadcrumb_trail($c) -> \@crumbs
920 #
921 # Purpose: The pages between Home and this one, this one last: a list of
922 # { label, url }. Home itself is not in the list; the template
923 # always puts it first.
924 # Entry: $c -- the controller for the request. A plain function, called
925 # from the before_render hook in Database::BI, so every page gets a
926 # trail without per-action code.
927 # Exit: An arrayref, empty for Home and for a controller that is not this
928 # class (a 404 page rendered by Mojolicious itself).
929 # Notes: A parent is followed only when _safe_back_url accepts it and it is
930 # on this host; a loop or the depth cap ends the trail, so a crafted
931 # URL can make it short but never wrong or endless.
932 2195 ▶sub _breadcrumb_trail {
Subroutine _breadcrumb_trail: called CC=8 SCAR=20.8
933 2195 my ($c) = @_;
934 2195 ▶ return [] unless ref $c && $c->isa(__PACKAGE__);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $c and $c->isa(__PACKAGE__) 225 1970 2195
Condition100%3/3
ref $c and $c->isa(__PACKAGE__)
!ll&&!rl&&r
22231970
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
935  
936 1970 my @trail;
937 my %seen;
938 1970 my $url = Mojo::URL->new($c->req->url->path_query);
939 1970 ▶ while ($url && @trail < $CRUMB_MAX_DEPTH) {
Branch: 1 branch
BranchTrueFalseTotal
if ($url and @trail < $CRUMB_MAX_DEPTH) 2980 1210 4190
Condition100%3/3
$url and @trail < $CRUMB_MAX_DEPTH
!ll&&!rl&&r
120912980
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
940 2980 my $key = $url->path_query;
941 2980 ▶ last if $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$key}++ 0 2980 2980
942 2980 my $label = $c->_crumb_label($url);
943 2980 ▶ last unless defined $label && length $label;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $label and length $label 760 2220 2980
Condition100%3/3
defined $label and length $label
!ll&&!rl&&r
75912220
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
944 2220 unshift @trail, { label => $label, url => $key };
945 2220 $url = $c->_crumb_parent($url);
946 }
947 1970 return \@trail;
948 }
949  
950 # _preferences_url($c) -> $href
951 #
952 # Where the nav's Preferences link goes: /preferences?back=<this page>, so
953 # the preferences page's trail ends with a way back here. This page is the
954 # last crumb of its trail; a page with no trail (Home, an error page) gets the
955 # plain link, and so does the preferences page, which keeps its own back=.
956 # A plain function, called from the before_render hook in Database::BI.
957 2186 ▶sub _preferences_url {
Subroutine _preferences_url: called CC=8 SCAR=21.1
958 2186 my ($c) = @_;
959 2186 my $plain = '/preferences';
960 2186 ▶ return $plain unless ref $c && $c->isa(__PACKAGE__);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $c and $c->isa(__PACKAGE__) 223 1963 2186
Condition66%2/3
ref $c and $c->isa(__PACKAGE__)
!ll&&!rl&&r
02231963
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
961 1963 my $trail = $c->stash('trail');
962 1963 ▶ return $plain unless ref $trail eq 'ARRAY' && @$trail;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $trail eq "ARRAY" and @$trail 759 1204 1963
Condition66%2/3
ref $trail eq "ARRAY" and @$trail
!ll&&!rl&&r
07591204
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
963 1204 ▶ my $here = $trail->[-1]{url} // '';
Condition50%1/2
$trail->[-1]{"url"} // ""
l!l
12040
MC/DC0%0/1
$trail->[-1]{"url"} // ""
$trail->[-1]{"url"}
Truth table50%1/2
A
A= $trail->[-1]{"url"}
Aresult
11
00
964 1204 ▶ 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 1203 1204
Condition66%2/3
not length $here or "Mojo::URL"->new($here)->path->to_string eq $plain
l!l&&r!l&&!r
011203
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
965 1203 return "$plain?back=" . url_escape(encode('UTF-8', $here));
966 }
967  
968 # _crumb_local($self, $raw) -> Mojo::URL | undef
969 #
970 # A parent link as a URL on this site, or undef when there is none to follow:
971 # empty, refused by _safe_back_url, on another host, or Home (which the trail
972 # shows anyway). Absolute links -- the panels pass window.location.href --
973 # are reduced to their path and query.
974 2997 ▶sub _crumb_local :Protected ($self, $raw) {
Subroutine _crumb_local: called CC=8 SCAR=21.0
975 2997 ▶ my $safe = _safe_back_url($raw) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $safe = _safe_back_url($raw) or return undef 946 2051 2997
976 946 my $url = Mojo::URL->new($safe);
977 946 ▶ if (defined $url->host) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $url->host) 4 942 946
978 4 my $here = $self->req->url->to_abs;
979 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
980 }
981 943 my $path = $url->path->to_string;
982 943 ▶ return undef if $path eq '' || $path eq '/';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "" or $path eq "/" 53 890 943
Condition66%2/3
$path eq "" or $path eq "/"
l!l&&r!l&&!r
053890
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
983 890 return Mojo::URL->new($url->path_query);
984 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
985  
986 # _crumb_parent($self, $url) -> Mojo::URL | undef
987 #
988 # The page $url was opened from. A chart names it with back=. A table page
989 # names it with back2= when it was drilled into from a chart, and otherwise
990 # has a natural parent: the left table for a merge or a combine, the schema
991 # page or the folder for a file, nothing for a table in data_dir.
992 2233 ▶sub _crumb_parent :Protected ($self, $url) {
Subroutine _crumb_parent: called CC=23 SCAR=31.5
993 2233 my $path = $url->path->to_string;
994 2233 my $q = $url->query;
995  
996 2233 ▶ 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}) 837 1396 2233
Condition100%3/3
$path =~ m[\A/([a-z]+)\z]u and $CRUMB_KIND{$1}
!ll&&!rl&&r
948448837
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
997 837 ▶ 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
1377252
$q->param("l") // ""
l!l
8186
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
998 // $self->_crumb_local($self->_spec_to_url($q->param('l') // ''));
999 }
1000 1396 ▶ if ($path =~ m{\A/view/} || $path eq '/import') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ m[\A/view/]u or $path eq "/import") 912 484 1396
Condition100%3/3
$path =~ m[\A/view/]u or $path eq "/import"
l!l&&r!l&&!r
9075484
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
1001 912 return $self->_crumb_local($q->param('back2'));
1002 }
1003 484 ▶ if ($path eq '/join' || $path eq '/combine') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/join" or $path eq "/combine") 97 387 484
Condition100%3/3
$path eq "/join" or $path eq "/combine"
l!l&&r!l&&!r
5146387
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
1004 97 ▶ return $self->_crumb_local($q->param('back2'))
Condition40%2/5
$self->_crumb_local($q->param("back2")) // $self->_crumb_local($self->_spec_to_url($q->param("l") // ""))
l!l&&r!l&&!r
0970
$q->param("l") // ""
l!l
970
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 table33%1/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
1005 // $self->_crumb_local($self->_spec_to_url($q->param('l') // ''));
1006 }
1007 387 ▶ if ($path eq '/open') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/open") 89 298 387
1008 89 ▶ my $parent = $self->_crumb_local($q->param('back2'))
Condition66%2/3
$self->_crumb_local($q->param("back2")) // $self->_crumb_local($q->param("back"))
l!l&&r!l&&!r
0188
MC/DC50%1/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 table66%2/3
A // B
A= $self->_crumb_local($q->param("back2"))B= $self->_crumb_local($q->param("back"))
ABresult
1X1
011
000
1009 // $self->_crumb_local($q->param('back'));
1010 89 ▶ return $parent if $parent;
Branch: 1 branch
BranchTrueFalseTotal
if $parent 1 88 89
1011 88 ▶ my $file = $q->param('path') // '';
Condition50%1/2
$q->param("path") // ""
l!l
880
MC/DC0%0/1
$q->param("path") // ""
$q->param("path")
Truth table50%1/2
A
A= $q->param("path")
Aresult
11
00
1012 88 ▶ return undef unless length $file && $file !~ m{\A/\.\./};
Branch: 1 branch
BranchTrueFalseTotal
unless length $file and not $file =~ m[\A/\.\./]u 6 82 88
Condition100%3/3
length $file and not $file =~ m[\A/\.\./]u
!ll&&!rl&&r
1582
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
1013 82 return Mojo::URL->new('/browse?path=' . url_escape(Mojo::File->new($file)->dirname->to_string));
1014 }
1015 298 ▶ if ($path eq '/tables') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/tables") 56 242 298
1016 56 ▶ my $spec = $q->param('l') // '';
Condition50%1/2
$q->param("l") // ""
l!l
560
MC/DC0%0/1
$q->param("l") // ""
$q->param("l")
Truth table50%1/2
A
A= $q->param("l")
Aresult
11
00
1017 56 ▶ return undef unless $spec =~ /\Apath:(.+)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $spec =~ /\Apath:(.+)\z/u 49 7 56
1018 7 my ($file) = _split_path($1);
1019 7 return Mojo::URL->new('/browse?path=' . url_escape(Mojo::File->new($file)->dirname->to_string));
1020 }
1021 # Preferences came from the page whose nav link opened it (_preferences_url).
1022 242 ▶ if ($path eq '/preferences') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/preferences") 1 241 242
1023 1 return $self->_crumb_local($q->param('back'));
1024 }
1025 # A canvas came from where its back= says, else from the list of canvases.
1026 241 ▶ if ($path =~ m{\A/a/}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ m[\A/a/]u) 41 200 241
1027 41 ▶ 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
1400
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
1028 }
1029 200 return undef;
1030 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1031  
1032 # _crumb_label($self, $url) -> $text | undef
1033 #
1034 # What a page is called in a trail. undef for a page that has no place in
1035 # one, which ends the trail there.
1036 2998 ▶sub _crumb_label :Protected ($self, $url) {
Subroutine _crumb_label: called CC=34 SCAR=35.3
1037 2998 my $path = $url->path->to_string;
1038 2998 my $q = $url->query;
1039 2998 my $view = _crumb_view_suffix($q);
1040  
1041 2998 ▶ return _crumb_spec_name("table:$1") . $view if $path =~ m{\A/view/([^/]+)\z};
Branch: 1 branch
BranchTrueFalseTotal
if $path =~ m[\A/view/([^/]+)\z]u 906 2092 2998
1042  
1043 2092 ▶ if ($path eq '/open') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/open") 132 1960 2092
1044 132 ▶ my $file = $q->param('path') // '';
Condition100%2/2
$q->param("path") // ""
l!l
8943
MC/DC100%1/1
$q->param("path") // ""
$q->param("path")
Truth table100%2/2
A
A= $q->param("path")
Aresult
11
00
1045 132 ▶ return undef unless length $file;
Branch: 1 branch
BranchTrueFalseTotal
unless length $file 44 88 132
1046 88 my $name = Mojo::File->new($file)->basename;
1047 88 my $it = $q->param('it');
1048 88 ▶ $name .= ": $it" if defined $it && length $it;
Branch: 1 branch
BranchTrueFalseTotal
if defined $it and length $it 2 86 88
Condition66%2/3
defined $it and length $it
!ll&&!rl&&r
8602
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
1049 88 ▶ return length $name ? "$name$view" : undef;
Branch: 1 branch
BranchTrueFalseTotal
length $name ? : 88 0 88
1050 }
1051 # Either route takes both joins and combined files.
1052 1960 ▶ if ($path eq '/join' || $path eq '/combine') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/join" or $path eq "/combine") 107 1853 1960
Condition100%3/3
$path eq "/join" or $path eq "/combine"
l!l&&r!l&&!r
56511853
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
1053 113 ▶ my @names = map { _crumb_spec_name($_) } grep { /\A(?:table|path|url|redis|mariadb):/i }
Condition100%2/2
$q->param("l") // ""
l!l
1043
MC/DC100%1/1
$q->param("l") // ""
$q->param("l")
Truth table100%2/2
A
A= $q->param("l")
Aresult
11
00
1054 ($q->param('l') // ''),
1055 13 ▶ (map { (split /\|/, $_, 2)[0] // '' } @{ $q->every_param('j') }),
Condition100%2/2
(split(/\|/u, $_, 2))[0] // ""
l!l
112
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
1056 107 @{ $q->every_param('c') };
1057 107 ▶ return @names ? join(' + ', @names) . $view : undef;
Branch: 1 branch
BranchTrueFalseTotal
@names ? : 99 8 107
1058 }
1059 1853 ▶ if ($path eq '/import') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/import") 52 1801 1853
1060 52 ▶ my $src = Mojo::URL->new($q->param('url') // '');
Condition100%2/2
$q->param("url") // ""
l!l
646
MC/DC100%1/1
$q->param("url") // ""
$q->param("url")
Truth table100%2/2
A
A= $q->param("url")
Aresult
11
00
1061 52 ▶ return defined $src->host ? $src->host . $view : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $src->host ? : 6 46 52
1062 }
1063 1801 ▶ 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}) 835 966 1801
Condition100%3/3
$path =~ m[\A/([a-z]+)\z]u and $CRUMB_KIND{$1}
!ll&&!rl&&r
585381835
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
1064 835 my $what = _crumb_chart_subject($1, $q);
1065 835 ▶ return $CRUMB_KIND{$1} . (length $what ? ": $what" : '');
Branch: 1 branch
BranchTrueFalseTotal
length $what ? : 682 153 835
1066 }
1067 966 ▶ if ($path eq '/tables') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/tables") 60 906 966
1068 60 ▶ my $spec = $q->param('l') // '';
Condition100%2/2
$q->param("l") // ""
l!l
573
MC/DC100%1/1
$q->param("l") // ""
$q->param("l")
Truth table100%2/2
A
A= $q->param("l")
Aresult
11
00
1069 60 ▶ return length $spec ? _crumb_spec_name($spec) . ' schema' : undef;
Branch: 1 branch
BranchTrueFalseTotal
length $spec ? : 55 5 60
1070 }
1071 906 ▶ if ($path eq '/browse') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/browse") 138 768 906
1072 138 ▶ my $dir = $q->param('path') // '';
Condition100%2/2
$q->param("path") // ""
l!l
9444
MC/DC100%1/1
$q->param("path") // ""
$q->param("path")
Truth table100%2/2
A
A= $q->param("path")
Aresult
11
00
1073 138 ▶ return length $dir ? 'Files: ' . Mojo::File->new($dir)->basename : 'Files';
Branch: 1 branch
BranchTrueFalseTotal
length $dir ? : 92 46 138
1074 }
1075 768 ▶ return 'Catalog' if $path eq '/catalog';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/catalog" 19 749 768
1076 749 ▶ return 'Canvases' if $path eq '/canvases';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/canvases" 42 707 749
1077 707 ▶ return 'Tutorial' if $path eq '/tutorial';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/tutorial" 4 703 707
1078 703 ▶ return 'Preferences' if $path eq '/preferences';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/preferences" 1 702 703
1079 702 ▶ return 'Log in' if $path eq '/login';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/login" 0 702 702
1080 702 ▶ if ($path =~ m{\A/a/([A-Za-z0-9_-]+)}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ m[\A/a/([A-Za-z0-9_-]+)]u) 41 661 702
1081 41 my $a = $self->_read_analyses->{$1};
1082 41 ▶ return (ref $a eq 'HASH' && length($a->{name} // '')) ? $a->{name} : 'Canvas';
Branch: 1 branch
BranchTrueFalseTotal
ref $a eq 'HASH' && length($a->{'name'} // '') ? : 30 11 41
Condition100%5/5
ref $a eq "HASH" and length($a->{"name"} // "")
!ll&&!rl&&r
9230
$a->{"name"} // ""
l!l
302
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
1083 }
1084 661 return undef;
1085 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1086  
1087 # _crumb_spec_name($spec) -> $name
1088 #
1089 # A data source as a person would name it: "sales" for table:sales,
1090 # "store: orders" for an internal table, the file name for path:, the host
1091 # for a web page.
1092 1082 ▶sub _crumb_spec_name {
Subroutine _crumb_spec_name: called CC=4 SCAR=13.9
1093 1082 my ($spec) = @_;
1094 1082 ▶ $spec //= '';
Condition100%2/2
$spec //= ""
l!l
10811
MC/DC100%1/1
$spec //= ""
$spec
Truth table100%2/2
A
A= $spec
Aresult
11
00
1095 1082 ▶ if ($spec =~ m{\Apath:(.+)\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ /\Apath:(.+)\z/u) 18 1064 1082
1096 18 my ($file, $internal) = _split_path($1);
1097 18 my $name = Mojo::File->new($file)->basename;
1098 18 ▶ return defined $internal ? "$name: $internal" : $name;
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 0 18 18
1099 }
1100 1064 return _crumb_spec_name_other($spec);
1101 }
1102  
1103 # _split_path($path) -> ($file, $internal)
1104 #
1105 # Purpose: What follows "path:" in a spec: the file, and the table it names
1106 # after a "#" (Database::BI::Model::DataSource::split_path).
1107 544 ▶sub _split_path {
Subroutine _split_path: called CC=1 SCAR=0.0
1108 544 my ($path) = @_;
1109 544 require Database::BI::Model::DataSource;
1110 544 return Database::BI::Model::DataSource::split_path($path);
1111 }
1112  
1113 1064 ▶sub _crumb_spec_name_other {
Subroutine _crumb_spec_name_other: called CC=9 SCAR=22.5
1114 1064 my ($spec) = @_;
1115 1064 ▶ $spec //= '';
Condition50%1/2
$spec //= ""
l!l
10640
MC/DC0%0/1
$spec //= ""
$spec
Truth table50%1/2
A
A= $spec
Aresult
11
00
1116 1064 ▶ return "$1: $2" if $spec =~ m{\Atable:([^/]+)/(.+)\z};
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ m[\Atable:([^/]+)/(.+)\z]u 1 1063 1064
1117 1063 ▶ return $1 if $spec =~ m{\Atable:(.+)\z};
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /\Atable:(.+)\z/u 1054 9 1063
1118 9 ▶ if ($spec =~ m{\Aurl:(.+)\z}i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ /\Aurl:(.+)\z/iu) 3 6 9
1119 3 my $host = Mojo::URL->new($1)->host;
1120 3 ▶ return $host // $1;
Condition33%1/3
$host // $1
l!l&&r!l&&!r
300
MC/DC0%0/2
$host // $1
$host $1
Truth table33%1/3
A // B
A= $hostB= $1
ABresult
1X1
011
000
1121 }
1122 6 ▶ return 'Redis' if $spec =~ /\Aredis:/i;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /\Aredis:/iu 1 5 6
1123 5 ▶ return "$1: $2" if $spec =~ $MARIADB_SPEC_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /$MARIADB_SPEC_RE/u 0 5 5
1124 5 ▶ return $1 if $spec =~ $MARIADB_SERVER_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /$MARIADB_SERVER_RE/u 0 5 5
1125 5 return $spec;
1126 }
1127  
1128 # _crumb_view_suffix($query) -> " (region = East, last 90 days)" | ''
1129 #
1130 # The part of a table's view that makes it a different page from the whole
1131 # table: its filters and its time range. Two filters are shown; more are
1132 # counted, so a crumb stays short.
1133 3011 ▶sub _crumb_view_suffix {
Subroutine _crumb_view_suffix: called CC=22 SCAR=31.0
1134 3011 my ($q) = @_;
1135 3011 my @bits;
1136 3011 for my $spec (@{ $q->every_param('f') }) {
1137 97 my ($col, $op, $val) = split /:/, $spec, 3;
1138 97 ▶ next unless length($col // '') && length($op // '');
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and length($op // "") 63 34 97
Condition100%7/7
length($col // "") and length($op // "")
!ll&&!rl&&r
422134
$col // ""
l!l
5740
$op // ""
l!l
3421
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
1139 34 ▶ next unless $col =~ $CRUMB_TEXT_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $col =~ /$CRUMB_TEXT_RE/u 2 32 34
1140 # A list is JSON, which the crumb text pattern refuses: say how long it is.
1141 32 ▶ if ($op eq 'in') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "in") 2 30 32
1142 2 my $n = () = _filter_in_values($val);
1143 2 ▶ push @bits, "$col $CRUMB_OP{in} $n value" . ($n == 1 ? '' : 's');
Branch: 1 branch
BranchTrueFalseTotal
$n == 1 ? : 0 2 2
1144 2 next;
1145 }
1146 30 ▶ next if length($val // '') && $val !~ $CRUMB_TEXT_RE;
Branch: 1 branch
BranchTrueFalseTotal
if length($val // "") and not $val =~ /$CRUMB_TEXT_RE/u 1 29 30
Condition100%5/5
length($val // "") and not $val =~ /$CRUMB_TEXT_RE/u
!ll&&!rl&&r
2271
$val // ""
l!l
282
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
1147 29 ▶ my $word = $CRUMB_OP{$op} // $op;
Condition33%1/3
$CRUMB_OP{$op} // $op
l!l&&r!l&&!r
2900
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
1148 29 ▶ push @bits, ($op eq 'empty' || $op eq 'notempty')
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'empty' || $op eq 'notempty' ? : 2 27 29
Condition60%3/5
$op eq "empty" or $op eq "notempty"
l!l&&r!l&&!r
2027
$val // ""
l!l
270
MC/DC50%1/2
$op eq "empty" or $op eq "notempty"
$op eq "empty" $op eq "notempty"
MC/DC0%0/1
$val // ""
$val
Truth table66%2/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
1149 ? "$col $word" : "$col $word " . (($val // '') =~ s/:/ and /r);
1150 }
1151 3011 ▶ my $extra = @bits > 2 ? @bits - 2 : 0;
Branch: 1 branch
BranchTrueFalseTotal
@bits > 2 ? : 1 3010 3011
1152 3011 ▶ splice @bits, 2 if $extra;
Branch: 1 branch
BranchTrueFalseTotal
if $extra 1 3010 3011
1153 3011 ▶ push @bits, "+$extra more" if $extra;
Branch: 1 branch
BranchTrueFalseTotal
if $extra 1 3010 3011
1154 3011 ▶ if (my $range = $TIME_RANGE{ $q->param('range') // '' }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $range = $TIME_RANGE{$q->param("range") // ""}) 1 3010 3011
Condition100%2/2
$q->param("range") // ""
l!l
422969
MC/DC100%1/1
$q->param("range") // ""
$q->param("range")
Truth table100%2/2
A
A= $q->param("range")
Aresult
11
00
1155 1 push @bits, lc $range->{label};
1156 }
1157 3011 ▶ return @bits ? ' (' . join(', ', @bits) . ')' : '';
Branch: 1 branch
BranchTrueFalseTotal
@bits ? : 26 2985 3011
1158 }
1159  
1160 # _crumb_chart_subject($kind, $query) -> $text
1161 #
1162 # What a chart shows, from its own parameters: "amount by region",
1163 # "Count by region", "amount". Empty for the pages that are about the
1164 # whole table (stats, insights).
1165 849 ▶sub _crumb_chart_subject {
Subroutine _crumb_chart_subject: called CC=28 SCAR=33.3
1166 849 my ($kind, $q) = @_;
1167 my %p = map {
1168 # loc= may repeat, for a place spread over columns (address, country).
1169 849 ▶ my $v = ($_ eq 'loc') ? join(', ', grep { length } @{ $q->every_param('loc') }) : ($q->param($_) // '');
Branch: 1 branch
BranchTrueFalseTotal
$_ eq 'loc' ? : 849 9339 10188
Condition100%2/2
$q->param($_) // ""
l!l
30746265
MC/DC100%1/1
$q->param($_) // ""
$q->param($_)
Truth table100%2/2
A
A= $q->param($_)
Aresult
11
00
1170 10188 ▶ ($_ => ($v =~ $CRUMB_TEXT_RE ? $v : ''));
Branch: 1 branch
BranchTrueFalseTotal
$v =~ /$CRUMB_TEXT_RE/u ? : 2904 7284 10188
1171 } qw(x y cat val seg col rows bar_val line_val loc lat lon);
1172  
1173 849 ▶ 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"} 139 710 849
Condition100%12/12
$kind eq "graph" || $kind eq "line" || $kind eq "scatter" and length $p{"x"} and length $p{"y"}
!ll&&!rl&&r
7082139
$kind eq "graph" || $kind eq "line" || $kind eq "scatter" and length $p{"x"}
!ll&&!rl&&r
6999141
$kind eq "graph" or $kind eq "line" or $kind eq "scatter"
l!l&&r!l&&!r
10149699
$kind eq "graph" or $kind eq "line"
l!l&&r!l&&!r
5744748
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
1174 710 ▶ 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"} 53 657 710
Condition100%6/6
$kind eq "heatmap" and length $p{"x"} and length $p{"y"}
!ll&&!rl&&r
656153
$kind eq "heatmap" and length $p{"x"}
!ll&&!rl&&r
652454
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
1175 657 ▶ 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"} 2 655 657
Condition100%6/6
$kind eq "stacked" and length $p{"cat"} and length $p{"seg"}
!ll&&!rl&&r
611442
$kind eq "stacked" and length $p{"cat"}
!ll&&!rl&&r
608346
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
1176 655 ▶ return $p{rows} =~ s/,/, /gr if $kind eq 'pivot';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "pivot" 50 605 655
1177 605 ▶ 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" 50 555 605
length $p{'loc'} ? : 2 48 50
length $p{'lat'} ? : 3 45 48
1178  
1179 555 ▶ my $dim = (grep { length } @p{qw(cat x col)})[0] // '';
Condition100%2/2
(grep {length $_;} @p{"cat", "x", "col"})[0] // ""
l!l
48768
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
1180 555 ▶ my $measure = (grep { length } @p{qw(val bar_val y)})[0] // '';
Condition100%2/2
(grep {length $_;} @p{"val", "bar_val", "y"})[0] // ""
l!l
444111
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
1181 555 ▶ $measure = 'Count' if $measure eq '__count__';
Branch: 1 branch
BranchTrueFalseTotal
if $measure eq "__count__" 3 552 555
1182 555 ▶ $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" 36 519 555
Condition100%9/9
not length $measure and $kind eq "pie" || $kind eq "bar" || $kind eq "treemap"
!ll&&!rl&&r
4447536
$kind eq "pie" or $kind eq "bar" or $kind eq "treemap"
l!l&&r!l&&!r
29775
$kind eq "pie" or $kind eq "bar"
l!l&&r!l&&!r
42582
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
1183 555 ▶ return length $measure && length $dim ? "$measure by $dim" : $dim;
Branch: 1 branch
BranchTrueFalseTotal
length $measure && length $dim ? : 451 104 555
Condition100%3/3
length $measure and length $dim
!ll&&!rl&&r
7529451
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
1184 }
1185  
1186 # _resolve_template($self) -> ($platform, $language)
1187 #
1188 # Purpose: Read platform and language from config, then resolve the Accept-Language
1189 # header to a language code -- falling back to the config language, and
1190 # then to the default language, when no template directory exists for
1191 # the code that was resolved.
1192 # Exit: Returns ($platform, $language) -- both guaranteed non-empty strings.
1193 962 ▶sub _resolve_template :Protected ($self) {
Subroutine _resolve_template: called CC=5 SCAR=16.1
1194 962 my $conf = $self->app->config();
1195 962 ▶ my $cfg_platform = $conf->{platform} // 'web';
Condition100%2/2
$conf->{"platform"} // "web"
l!l
9611
MC/DC100%1/1
$conf->{"platform"} // "web"
$conf->{"platform"}
Truth table100%2/2
A
A= $conf->{"platform"}
Aresult
11
00
1196 962 ▶ my $cfg_language = $conf->{language} // 'en';
Condition100%2/2
$conf->{"language"} // "en"
l!l
9611
MC/DC100%1/1
$conf->{"language"} // "en"
$conf->{"language"}
Truth table100%2/2
A
A= $conf->{"language"}
Aresult
11
00
1197  
1198 # Detect platform from the request User-Agent via CGI::Info.
1199 # Falls back to the configured platform when:
1200 # (a) CGI::Info is unavailable or throws, or
1201 # (b) no templates/<detected>/ directory exists.
1202 962 ▶ my $platform = _detect_platform(
Condition100%2/2
$self->req->headers->user_agent // ""
l!l
9602
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
1203 $self->req->headers->user_agent // '',
1204 $cfg_platform,
1205 );
1206 962 ▶ unless (-d $self->app->home->child("templates/$platform")) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $self->app->home->child("templates/$platform")) 2 960 962
1207 2 $platform = $cfg_platform;
1208 }
1209  
1210 962 my $language = $self->_resolve_language($platform, $cfg_language);
1211 962 return ($platform, $language);
1212 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1213  
1214 # _detect_platform($user_agent, $fallback) -> $platform_string
1215 #
1216 # Purpose: Map a raw User-Agent string to a VWF platform dimension
1217 # ('mobile', 'tablet', or 'web') via CGI::Info.
1218 # Entry: $user_agent -- the raw HTTP User-Agent header value (may be empty).
1219 # $fallback -- value to return if detection fails.
1220 # Exit: Returns 'mobile', 'tablet', 'web', or $fallback.
1221 # Side Effects: temporarily sets $ENV{HTTP_USER_AGENT} with local().
1222 966 ▶sub _detect_platform ($user_agent, $fallback) {
Subroutine _detect_platform: called CC=4 SCAR=14.5
1223 966 my $platform = eval {
1224 966 local $ENV{HTTP_USER_AGENT} = $user_agent;
1225 966 my $info = CGI::Info->new();
1226 966 ▶ $info->is_mobile() ? 'mobile'
Branch: 2 branches
BranchTrueFalseTotal
$info->is_mobile ? : 4 962 966
$info->is_tablet ? : 0 962 962
1227 : $info->is_tablet() ? 'tablet'
1228 : 'web';
1229 };
1230 966 ▶ return $platform // $fallback;
Condition33%1/3
$platform // $fallback
l!l&&r!l&&!r
96600
MC/DC0%0/2
$platform // $fallback
$platform $fallback
Truth table33%1/3
A // B
A= $platformB= $fallback
ABresult
1X1
011
000
1231 }
1232  
1233 # _resolve_language($self, $platform, $default) -> $language_code
1234 #
1235 # Purpose: Determine the best ISO 639-1 language code for this request.
1236 # When Accept-Language is present, CGI::Lingua selects the best
1237 # match from the languages that have a template directory under
1238 # templates/<platform>/. $default answers when the header is absent,
1239 # no templates exist for the matched language, or CGI::Lingua is
1240 # unavailable. The result has a template directory whenever one
1241 # exists: a code without one - the configured language included -
1242 # becomes the default language, and only when that has no directory
1243 # either is the resolved code returned, so the missing template names
1244 # what was asked for.
1245 # Entry: $platform is the resolved VWF platform string.
1246 # $default is a non-empty fallback language code (e.g. 'en').
1247 # Exit: Returns a two-letter ISO 639-1 language code string, or a code
1248 # and region (en-us) when the browser names that region and
1249 # templates/<platform>/<code>-<region>/ exists.
1250 # Side Effects: filesystem stats for template directories;
1251 # temporarily sets $ENV{HTTP_ACCEPT_LANGUAGE} with local().
1252 967 ▶sub _resolve_language :Protected ($self, $platform, $default) {
Subroutine _resolve_language: called CC=7 SCAR=19.6
1253 967 ▶ my $accept = $self->req->headers->accept_language() // '';
Condition100%2/2
$self->req->headers->accept_language // ""
l!l
25942
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
1254  
1255 967 my $language = $default;
1256 967 ▶ if ($accept) {
Branch: 1 branch
BranchTrueFalseTotal
if ($accept) 24 943 967
1257 # Discover supported languages from template directories so CGI::Lingua
1258 # only returns a code we can actually serve. The configured language is
1259 # offered as well, so a request that asks for it gets it, whether or not
1260 # it can be served - the check below decides that.
1261 24 my @supported = _template_languages($self->app->home, $platform);
1262 24 ▶ push @supported, $default unless grep { $_ eq $default } @supported;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $default;} @supported 0 24 24
1263  
1264 # A regional variant (templates/web/en-us/ for a browser asking for
1265 # en-US) is chosen when it has a directory, otherwise the language
1266 # itself: en-GB, en-CA and plain en get en. Database::BI::I18N makes
1267 # the same CGI::Lingua call for the messages, so the two agree.
1268 24 my $chosen = Database::BI::I18N::lingua_choice($accept, \@supported);
1269 24 ▶ $language = $chosen if defined $chosen;
Branch: 1 branch
BranchTrueFalseTotal
if defined $chosen 18 6 24
1270 }
1271  
1272 # Confirm a template directory exists for the language we are about to
1273 # render from. Naming a language does not give it templates, and rendering
1274 # a directory that is not there is a 500 rather than a translation. This
1275 # covers the configured language itself and not just the one Accept-Language
1276 # produced: the documented fallback used to happen only when the two
1277 # differed, so the ordinary case - an operator setting language => 'de'
1278 # before adding templates/web/de/ - reached the renderer unchecked.
1279 967 my $home = $self->app->home;
1280 967 ▶ return $language if _has_templates($home, $platform, $language);
Branch: 1 branch
BranchTrueFalseTotal
if _has_templates($home, $platform, $language) 966 1 967
1281 1 ▶ return $DEFAULT_LANGUAGE
Branch: 1 branch
BranchTrueFalseTotal
if _has_templates($home, $platform, $DEFAULT_LANGUAGE) 1 0 1
1282 if _has_templates($home, $platform, $DEFAULT_LANGUAGE);
1283  
1284 # Neither exists. Keep what was resolved, so the missing template names the
1285 # language the request asked for rather than one nobody configured.
1286 0 return $language;
1287 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1288  
1289 # _template_languages($home, $platform) -> @codes
1290 #
1291 # The languages that have a template directory for the platform, sorted so that
1292 # the answer does not depend on the order the filesystem returns entries in.
1293 # Plain functions taking the application home rather than methods: the tests
1294 # call _resolve_language with a mock controller, and a method call on it would
1295 # look for the helper in the mock's package rather than this one.
1296 26 ▶sub _template_languages ($home, $platform) {
Subroutine _template_languages: called CC=2 SCAR=6.9
1297 26 my $base = $home->child("templates/$platform");
1298 26 ▶ return () unless -d $base;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $base 1 25 26
1299  
1300 50 return sort map { Mojo::File->new($_)->basename }
1301 25 grep { -d $_ } @{ $base->list({ dir => 1 }) };
1302 }
1303  
1304 # _has_templates($home, $platform, $language) -> 1 | 0
1305 #
1306 # Whether the application can render a language: the controller builds template
1307 # names as "<platform>/<language>/<page>", so a language without a directory
1308 # under templates/<platform>/ cannot be served at all.
1309 973 ▶sub _has_templates ($home, $platform, $language) {
Subroutine _has_templates: called CC=4 SCAR=13.9
1310 973 ▶ return 0 unless defined $language && length $language;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $language and length $language 2 971 973
Condition100%3/3
defined $language and length $language
!ll&&!rl&&r
11971
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
1311  
1312 971 ▶ return -d $home->child("templates/$platform/$language") ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
-d $home->child("templates/$platform/$language") ? : 968 3 971
1313 }
1314  
1315 # _data_dir_for($app) -> Mojo::File
1316 #
1317 # The configured data directory. A relative value is resolved against the
1318 # application home, which is the historical behaviour; an absolute one is used
1319 # as given, because Mojo::File->child() appends an absolute path rather than
1320 # replacing the base. It takes the app rather than $self because the unit
1321 # tests call the scanning helpers with a bare controller.
1322 7541 ▶sub _data_dir_for ($app) {
Subroutine _data_dir_for: called CC=3 SCAR=11.0
1323 7541 ▶ my $dir = $app->config->{data_dir} // 'data';
Condition100%2/2
$app->config->{"data_dir"} // "data"
l!l
75401
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
1324 7541 my $file = Mojo::File->new($dir);
1325 7541 ▶ return $file if $file->is_abs;
Branch: 1 branch
BranchTrueFalseTotal
if $file->is_abs 320 7221 7541
1326 7221 return $app->home->child($dir);
1327 }
1328  
1329 # _scan_data_dir($self) -> \@table_list
1330 #
1331 # Purpose: Return an arrayref of { name, file } hashrefs for every supported
1332 # data file in the configured data_dir. Used by the index action; the
1333 # join panel uses _scan_join_tables, which also lists internal tables.
1334 # Entry: None.
1335 # Exit: Returns [] when data_dir does not exist or contains no supported files.
1336 # Side Effects: Filesystem directory read.
1337 #
1338 # Optimisation: single-pass map replaces a two-pass grep+map chain, and calls
1339 # basename() only once per entry (the original chain called it twice: once in
1340 # grep to check the extension and again in map to extract the stem).
1341 # ->to_array avoids the extra flat-list expansion that ->each produced.
1342 312 ▶sub _scan_data_dir :Protected ($self) {
Subroutine _scan_data_dir: called CC=3 SCAR=11.3
1343 312 my $dir = _data_dir_for($self->app);
1344 312 ▶ return [] unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 2 310 312
1345  
1346 # A directory that exists but may not be read holds nothing this application
1347 # can show, and must not take the home page with it.
1348 310 my $files = eval { $dir->list };
1349 310 ▶ unless ($files) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($files) 0 310 310
1350 0 $self->app->log->error("Cannot read data_dir $dir: " . _tidy_error($@));
1351 0 return [];
1352 }
1353 3400 ▶ return $files->map(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1354 3400 my $base = $_->basename;
1355 3400 ▶ return unless $base =~ $EXT_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $base =~ /$EXT_RE/u 0 3400 3400
1356 3400 (my $name = $base) =~ s/\.[^.]+\z//;
1357 3400 { name => $name, file => $base, path => $_->to_string }
1358 310 })->to_array;
1359 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1360  
1361 # _scan_join_tables($self) -> \@table_list
1362 #
1363 # Purpose: Like _scan_data_dir, but each multi-table SQLite file contributes
1364 # one entry per internal table as well as the file entry. The join
1365 # and combine panels need this: "table:store/customer" names a table
1366 # inside store.db, which a plain file name cannot do.
1367 # Entry: None.
1368 # Exit: Returns [] when data_dir does not exist or has no supported files.
1369 # Every entry has a spec suitable for the panel's option value.
1370 # Side Effects: Reads data_dir and opens each SQLite file to list its tables.
1371 204 ▶sub _scan_join_tables :Protected ($self) {
Subroutine _scan_join_tables: called CC=8 SCAR=21.2
1372 204 my $dir = _data_dir_for($self->app);
1373 204 my $tables = $self->_scan_data_dir;
1374 204 my @all;
1375  
1376 204 for my $table (@$tables) {
1377 2223 push @all, { %$table, spec => "table:$table->{name}" };
1378 2223 ▶ next unless $table->{file} =~ /\.(?:db|sql|sqlite|sqlite3)\z/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $table->{"file"} =~ /\.(?:db|sql|sqlite|sqlite3)\z/iu 2021 202 2223
1379  
1380 202 my $source = eval { $self->open_table($table->{name}, directory => $dir->to_string) };
1381 202 ▶ next unless $source;
Branch: 1 branch
BranchTrueFalseTotal
unless $source 0 202 202
1382  
1383 202 my $internal_tables = eval { $source->sqlite_tables };
1384 202 ▶ next unless $internal_tables && @$internal_tables > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $internal_tables and @$internal_tables > 1 0 202 202
Condition33%1/3
$internal_tables and @$internal_tables > 1
!ll&&!rl&&r
00202
MC/DC0%0/2
$internal_tables and @$internal_tables > 1
$internal_tables @$internal_tables > 1
Truth table33%1/3
A and B
A= $internal_tablesB= @$internal_tables > 1
ABresult
0X0
100
111
1385  
1386 202 my @internal = @$internal_tables;
1387  
1388 202 for my $name (@internal) {
1389 606 ▶ next unless $name =~ $TABLE_NAME_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$TABLE_NAME_RE/u 0 606 606
1390 606 push @all, {
1391 %$table,
1392 name => "$table->{name} / $name",
1393 internal => $name,
1394 spec => "table:$table->{name}/$name",
1395 };
1396 }
1397 }
1398  
1399 204 return \@all;
1400 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1401  
1402 # _tidy_error($error) -> $string
1403 #
1404 # Purpose: A backend error as a reader should see it: without the "at FILE line N"
1405 # that croak adds each time the error is passed up, or the list of
1406 # library directories perl adds when a module is missing.
1407 49 ▶sub _tidy_error {
Subroutine _tidy_error: called CC=2 SCAR=6.9
1408 49 ▶ my $error = $_[0] // '';
Condition100%2/2
$_[0] // ""
l!l
472
MC/DC100%1/1
$_[0] // ""
$_[0]
Truth table100%2/2
A
A= $_[0]
Aresult
11
00
1409 49 $error =~ s/\s*\(\@INC (?:contains|entries checked):.*?\)(?=\s+at\s|\s*\z)//sg;
1410 49 $error =~ s/(?:\s+at \S.*? line \d+\.?)+\s*\z//;
1411 49 return $error;
1412 }
1413  
1414 # _analysis_json_error($error) -> $string
1415 #
1416 # Purpose: The message for a canvas request whose body is not a JSON object.
1417 # Entry: the error from decode_json, which is empty when the body parsed
1418 # but was an array or a scalar, and otherwise ends in a library's path.
1419 31 ▶sub _analysis_json_error {
Subroutine _analysis_json_error: called CC=2 SCAR=6.9
1420 31 my $reason = _tidy_error($_[0]);
1421 31 ▶ return sprintf(_message_text('error_analysis_json'), length($reason) ? $reason : 'expected a JSON object');
Branch: 1 branch
BranchTrueFalseTotal
length $reason ? : 13 18 31
1422 }
1423  
1424 # ---------------------------------------------------------------------------
1425 # Accelerated views (Phase 7 item 7.5)
1426 #
1427 # A dataset marked in models.json accelerated.<spec> is read from a SQLite copy
1428 # of itself, built by script/bi-extract through Database::BI::Extract, as long
1429 # as the copy's fingerprint (the spec, and the file's mtime and size) still
1430 # matches the file. When it does not, the file itself is read and the table
1431 # page says the extract is stale: stale numbers are never served. An extract is
1432 # a cache. Deleting <model_dir>/extracts/ only makes every accelerated dataset
1433 # read its file again, and nothing is ever written under data_dir.
1434 # ---------------------------------------------------------------------------
1435  
1436 # _model_dir_of($app) -> Mojo::File
1437 #
1438 # Purpose: model_dir as a path: absolute as configured, or under the app home.
1439 # Nothing is created and nothing is checked; the writers check.
1440 7 ▶sub _model_dir_of {
Subroutine _model_dir_of: called CC=3 SCAR=11.0
1441 7 my ($app) = @_;
1442 7 ▶ my $cfg = Mojo::File->new($app->config('model_dir') // '.bi');
Condition100%2/2
$app->config("model_dir") // ".bi"
l!l
61
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
1443 7 ▶ return $cfg->is_abs ? $cfg : $app->home->child($cfg->to_string);
Branch: 1 branch
BranchTrueFalseTotal
$cfg->is_abs ? : 5 2 7
1444 }
1445  
1446 # _table_stem($data_dir, $name, @exts) -> $stem | undef
1447 #
1448 # Purpose: The file stem table:<name> means in data_dir: the name as written
1449 # when a file has it, else in lower case, which is what every reader
1450 # once looked for (so table:Orders still opens orders.csv); undef
1451 # when neither has a file with one of @exts (default @SUPPORTED_EXT).
1452 # Reading only the lower case made a file named with a capital,
1453 # BandMusic.csv, open on its own page (/view/BandMusic) and nowhere
1454 # else: a pivot, chart or merge of table:BandMusic was a 404.
1455 896 ▶sub _table_stem ($data_dir, $name, @exts) {
Subroutine _table_stem: called CC=4 SCAR=13.9
1456 896 ▶ @exts = @SUPPORTED_EXT unless @exts;
Branch: 1 branch
BranchTrueFalseTotal
unless @exts 852 44 896
1457 896 for my $stem ($name, lc $name) {
1458 961 ▶ return $stem if grep { -f $data_dir->child("$stem.$_") } @exts;
Branch: 1 branch
BranchTrueFalseTotal
if grep {-f $data_dir->child("$stem.$_");} @exts 831 130 961
1459 }
1460 65 return undef; ## no critic (ProhibitExplicitReturnUndef)
1461 }
1462  
1463 # _accel_file($self, $spec) -> $path | undef
1464 #
1465 # Purpose: The local file a spec can be accelerated from: table:<name> in
1466 # data_dir, or path:<file>. An internal table, a remote path and
1467 # every other kind of spec have none.
1468 16 ▶sub _accel_file :Protected ($self, $spec) {
Subroutine _accel_file: called CC=9 SCAR=22.0
1469 16 ▶ $spec //= '';
Condition100%2/2
$spec //= ""
l!l
151
MC/DC100%1/1
$spec //= ""
$spec
Truth table100%2/2
A
A= $spec
Aresult
11
00
1470 16 ▶ if ($spec =~ m{\Atable:([A-Za-z0-9_]+)\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ /\Atable:([A-Za-z0-9_]+)\z/u) 4 12 16
1471 4 my $data_dir = _data_dir_for($self->app);
1472 4 ▶ my $stem = _table_stem($data_dir, $1) // return undef;
Condition100%2/2
_table_stem($data_dir, $1) // (return undef)
l!l
22
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
1473 2 my ($file) = grep { -f } map { $data_dir->child("$stem.$_")->to_string } @SUPPORTED_EXT;
1474 2 return $file;
1475 }
1476 12 ▶ if ($spec =~ m{\Apath:(?!/\.\./)(.+)\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ m[\Apath:(?!/\.\./)(.+)\z]u) 7 5 12
1477 7 my ($path) = _split_path($1);
1478 7 ▶ return undef if _outside_roots($self, $path);
Branch: 1 branch
BranchTrueFalseTotal
if _outside_roots($self, $path) 0 7 7
1479 7 my $file = eval { Mojo::File->new($path)->realpath };
1480 7 ▶ 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 ? : 5 2 7
Condition66%4/6
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
!ll&&!rl&&r
205
defined $file and -f $file
!ll&&!rl&&r
025
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
1481 }
1482 5 return undef;
1483 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1484  
1485 # _accelerated_source($self, $spec) -> $DataSource | undef
1486 #
1487 # Purpose: The extract of an accelerated dataset, when it still matches the file.
1488 # Exit: The extract opened as a source, or undef: the spec is not accelerated,
1489 # or its extract is missing or stale, and the caller reads the file.
1490 # The first call in a request stashes acceleration => { state =>
1491 # 'fresh' | 'stale', built => epoch, spec => $spec } for the table page.
1492 1084 ▶sub _accelerated_source :Protected ($self, $spec) {
Subroutine _accelerated_source: called CC=14 SCAR=26.8
1493 1084 ▶ return undef if $self->stash('_no_acceleration');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_no_acceleration") 2 1082 1084
1494 1082 ▶ return undef unless defined $spec && length $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec and length $spec 7 1075 1082
Condition66%2/3
defined $spec and length $spec
!ll&&!rl&&r
071075
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
1495 # Only this application's controller has a model store; a bare controller
1496 # (a test's, calling _open_spec as a function) has nothing accelerated.
1497 1075 ▶ return undef unless $self->isa(__PACKAGE__);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->isa(__PACKAGE__) 7 1068 1075
1498 1068 $spec = canonical_spec($spec);
1499 1068 my $entry = $self->_read_models->{accelerated}{$spec};
1500 1068 ▶ return undef unless ref $entry eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 1066 2 1068
1501 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
1502  
1503 2 my @st = stat $file;
1504 2 my $cache = _extract_store($self->app);
1505 2 my $path = $cache->get($spec, $st[9], $st[7]);
1506 2 my $src;
1507 2 ▶ if (defined $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $path) 1 1 2
1508 1 my $x = Mojo::File->new($path);
1509 1 $src = eval { $self->open_table($x->basename =~ s/\.db\z//r, directory => $x->dirname->to_string,
1510 1 ▶ (ref $entry->{columns} eq 'ARRAY' ? (column_order => $entry->{columns}) : ())) };
Branch: 1 branch
BranchTrueFalseTotal
ref $entry->{'columns'} eq 'ARRAY' ? : 1 0 1
1511 }
1512 2 require POSIX;
1513 2 ▶ my $built = $src ? (stat $path)[9] : $entry->{built};
Branch: 1 branch
BranchTrueFalseTotal
$src ? : 1 1 2
1514 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
1515 spec => $spec,
1516 state => ($src ? 'fresh' : 'stale'),
1517 built => $built,
1518 built_text => (defined $built && $built =~ /\A\d+\z/ ? Database::BI::Util::minute_stamp(localtime $built) : ''),
1519 }) unless $self->stash('acceleration');
1520 2 return $src;
1521 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1522  
1523 # _extract_store($app) -> Database::BI::Extract
1524 #
1525 # Purpose: The extract store, in the cache directory Database::BI::CacheDir
1526 # chooses (Object::Configure, CACHEDIR, CACHE_DIR, cache_dir in the
1527 # config), else in <model_dir>/extracts as before. A cache directory
1528 # inside data_dir is not used for them: each extract is a .db file,
1529 # which the home page would list as a table of the user's own, and
1530 # nothing is written under data_dir. They then go in model_dir, whose
1531 # own check (_calc_models_path) stops a store inside data_dir.
1532 4 ▶sub _extract_store {
Subroutine _extract_store: called CC=2 SCAR=7.5
1533 4 my ($app) = @_;
1534 4 require Database::BI::Extract;
1535 4 my $model_dir = _model_dir_of($app);
1536 4 my $store = Database::BI::Extract->new(
1537 model_dir => $model_dir->to_string,
1538 config => $app->config,
1539 home => $app->home->to_string,
1540 );
1541 4 ▶ 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 4 4
1542 0 carp 'The cache directory is inside data_dir; extracts are kept in model_dir instead';
1543 0 $store = Database::BI::Extract->new(dir => $model_dir->child('extracts')->to_string);
1544 }
1545 4 return $store;
1546 }
1547  
1548 # _is_sqlite_file($path) -> $bool
1549 #
1550 # Purpose: True for a SQLite database, whatever its extension (a .db may be one).
1551 9 ▶sub _is_sqlite_file {
Subroutine _is_sqlite_file: called CC=4 SCAR=13.9
1552 9 my ($path) = @_;
1553 9 ▶ open my $fh, '<:raw', $path or return 0;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or return 0 7 2 9
1554 7 my $n = read $fh, my $head, 16;
1555 7 close $fh;
1556 7 ▶ return ($n && $head eq "SQLite format 3\0") ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$n && $head eq "SQLite format 3\000" ? : 2 5 7
Condition100%3/3
$n and $head eq "SQLite format 3\0"
!ll&&!rl&&r
142
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
1557 }
1558  
1559 # accelerate($c, $spec) -> \%built
1560 #
1561 # Purpose: Mark a dataset accelerated and build its extract: the rows its file
1562 # gives, in a SQLite file in the extract store (_extract_store). Called by
1563 # script/bi-extract; not a route.
1564 # Entry: $c is a controller of the application (Mojolicious build_controller);
1565 # $spec is a table: or path: spec naming a local, non-SQLite file.
1566 # Exit: { spec, path, rows, columns, built } -- the extract written and when.
1567 # The model store records accelerated.<spec> = { built, file, rows }.
1568 # Croaks error_accel_spec, error_accel_sqlite, error_accel_open,
1569 # error_accel_store or error_accel_build.
1570 # Side Effects: Writes the extract, removes the one it replaces, and writes
1571 # models.json.
1572 5 ▶sub accelerate {
Subroutine accelerate: called CC=17 SCAR=30.6
Pod documented
1573 5 my ($c, $spec) = @_;
1574 5 ▶ croak 'accelerate() 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
104
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
1575 # Filed under the resolved spec, which is what the file's page asks for;
1576 # messages name the spec as the caller wrote it.
1577 4 my $key = canonical_spec($spec);
1578 4 ▶ my $file = $c->_accel_file($spec)
Condition100%2/2
$c->_accel_file($spec) // croak($c->_i18n("error_accel_spec", $spec))
l!l
31
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
1579 // croak $c->_i18n('error_accel_spec', $spec);
1580 3 ▶ 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) 1 2 3
Condition66%2/3
$file =~ /\.(?:sql|sqlite3?)\z/iu or _is_sqlite_file($file)
l!l&&r!l&&!r
012
MC/DC50%1/2
$file =~ /\.(?:sql|sqlite3?)\z/iu or _is_sqlite_file($file)
$file =~ /\.(?:sql|sqlite3?)\z/iu _is_sqlite_file($file)
Truth table66%2/3
A or B
A= $file =~ /\.(?:sql|sqlite3?)\z/iuB= _is_sqlite_file($file)
ABresult
1X1
011
000
1581 2 ▶ 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)) 1 1 2
1582  
1583 # Read the file itself, not the extract being replaced.
1584 1 local $c->stash->{_no_acceleration} = 1;
1585 1 my @st = stat $file;
1586 1 my ($src) = $c->_open_spec($spec);
1587 1 ▶ croak $c->_i18n('error_accel_open', $spec, _tidy_error($c->stash('open_spec_error') // 'unreadable')) unless $src;
Branch: 1 branch
BranchTrueFalseTotal
unless $src 0 1 1
Condition0%0/2
$c->stash("open_spec_error") // "unreadable"
l!l
00
MC/DC0%0/1
$c->stash("open_spec_error") // "unreadable"
$c->stash("open_spec_error")
Truth table0%0/2
A
A= $c->stash("open_spec_error")
Aresult
11
00
1588 1 my ($records, @columns);
1589 1 my $ok = eval {
1590 1 $records = $src->fetch_all;
1591 1 @columns = _get_columns($src, $records);
1592 1 1;
1593 };
1594 1 ▶ croak $c->_i18n('error_accel_open', $spec, _tidy_error($@)) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 1 1
1595 1 my $bytes = eval { $c->_write_sqlite_db($records, \@columns, 'extract') };
1596 1 ▶ croak $c->_i18n('error_accel_build', $spec, _tidy_error($@)) unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 1 1
1597  
1598 1 my $cache = _extract_store($c->app);
1599 1 my $path = eval { $cache->put($key, $st[9], $st[7], $bytes) };
1600 1 ▶ croak $c->_i18n('error_accel_build', $spec, _tidy_error($@)) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 1 1
1601  
1602 1 my $models = $c->_read_models;
1603 1 my $old = $models->{accelerated}{$key};
1604 1 my $name = Mojo::File->new($path)->basename;
1605 1 ▶ 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 1 1
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
100
ref $old eq "HASH" and defined $old->{"file"} and $old->{"file"} ne $name
!ll&&!rl&&r
100
ref $old eq "HASH" and defined $old->{"file"}
!ll&&!rl&&r
100
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
1606 0 unlink Mojo::File->new($path)->dirname->child($old->{file})->to_string;
1607 }
1608 1 my $built = time;
1609 # The file's own column order: the extract would list its columns alphabetically.
1610 1 $models->{accelerated}{$key} = { built => $built, file => $name, rows => scalar(@$records), columns => \@columns };
1611 1 ▶ $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)) 1 0 1
1612 1 return { spec => $key, path => $path, rows => scalar(@$records), columns => scalar(@columns), built => $built };
1613 }
1614  
1615 # unaccelerate($c, $spec) -> $bool
1616 #
1617 # Purpose: Stop reading a dataset from an extract, and remove its extract.
1618 # Exit: True when the spec was accelerated.
1619 3 ▶sub unaccelerate {
Subroutine unaccelerate: called CC=6 SCAR=18.3
Pod documented
1620 3 my ($c, $spec) = @_;
1621 3 ▶ croak 'unaccelerate() needs a controller and a spec' unless ref $c && defined $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $c and defined $spec 1 2 3
Condition66%2/3
ref $c and defined $spec
!ll&&!rl&&r
012
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
1622 2 $spec = canonical_spec($spec); # unaccelerate names no spec in a message
1623 2 my $models = $c->_read_models;
1624 2 my $entry = delete $models->{accelerated}{$spec};
1625 2 ▶ return 0 unless ref $entry eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 1 1 2
1626 1 ▶ 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) 1 0 1
Condition33%1/3
defined $entry->{"file"} and $entry->{"file"} =~ /\A[0-9a-f]{32}\.db\z/u
!ll&&!rl&&r
001
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
1627 1 unlink Mojo::File->new(_extract_store($c->app)->dir)->child($entry->{file})->to_string;
1628 }
1629 1 $c->_write_models($models);
1630 1 return 1;
1631 }
1632  
1633 # accelerated_specs($c) -> @specs
1634 #
1635 # Purpose: Every spec marked accelerated, sorted, for script/bi-extract --all.
1636 3 ▶sub accelerated_specs {
Subroutine accelerated_specs: called CC=2 SCAR=6.9
Pod documented
1637 3 my ($c) = @_;
1638 3 ▶ croak 'accelerated_specs() needs a controller' unless ref $c;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $c 1 2 3
1639 2 return sort keys %{ $c->_read_models->{accelerated} };
1640 }
1641  
1642 # _open_spec($self, $spec) -> ($DataSource, $label) or ()
1643 #
1644 # Purpose: Parse a "table:name", "table:file/table" or "path:/abs/path" spec,
1645 # verify the underlying file exists (Database::Abstraction creates empty objects silently for
1646 # missing files, so we must check ourselves), and return a live
1647 # DataSource object and a display label.
1648 # Entry: $spec is a non-empty string.
1649 # Exit: Returns ($datasource, $label) on success; an empty list on any failure
1650 # (invalid spec format, file missing, DataSource init error).
1651 # Side Effects: Filesystem stat; DataSource construction (reads file header).
1652 968 ▶sub _open_spec :Protected ($self, $spec) {
Subroutine _open_spec: called CC=38 SCAR=51.6
1653 # An accelerated dataset whose extract still matches its file is read from
1654 # the extract, under the file's own label.
1655 968 ▶ if (my $fast = _accelerated_source($self, $spec)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fast = _accelerated_source($self, $spec)) 0 968 968
1656 my $label = $spec =~ m{\Atable:(.+)\z} ? (_table_stem(_data_dir_for($self->app), $1) // $1)
1657 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
1658 0 return ($fast, $label);
1659 }
1660 968 ▶ 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) { } 842 126 968
elsif ($spec =~ /\Apath:(.+)\z/u) { } 85 41 126
elsif ($spec =~ /$URL_SPEC_RE/u) { } 1 40 41
elsif ($spec =~ /$REDIS_SPEC_RE/u) { } 0 40 40
elsif ($spec =~ /$MARIADB_SPEC_RE/u) { } 0 40 40
1661 842 my ($name, $internal) = ($1, $2);
1662 842 my $data_dir = _data_dir_for($self->app);
1663 842 ▶ my $table = _table_stem($data_dir, $name) // return ();
Condition100%2/2
_table_stem($data_dir, $name) // (return ())
l!l
82220
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
1664 822 my $src = eval {
1665 822 ▶ $self->open_table($table, directory => $data_dir->to_string,
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 0 822 822
1666 defined $internal ? (internal_table => $internal) : ())
1667 };
1668 822 ▶ return ($src, defined $internal ? $internal : $table) if $src && !$@;
Branch: 2 branches
BranchTrueFalseTotal
if $src and not $@ 822 0 822
defined $internal ? : 0 822 822
Condition33%1/3
$src and not $@
!ll&&!rl&&r
00822
MC/DC0%0/2
$src and not $@
$src not $@
Truth table33%1/3
A and not(B)
A= $srcB= not $@
ABresult
0X0
100
111
1669 } elsif ($spec =~ /\Apath:(.+)\z/) {
1670 # path:<file>#<table> names one table of the file, as table:<file>/<table>
1671 # does in data_dir.
1672 85 my ($path_arg, $internal) = _split_path($1);
1673 85 ▶ my @it = defined $internal ? (internal_table => $internal) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 0 85 85
1674 # Remote path: /../hostname/dir/file -- delegate to DataSource with host param.
1675 # No EXT_RE check: security comes from REMOTE_HOST_RE. The original
1676 # extension (if any) is passed as file_ext so _init_backend tries it first.
1677 85 ▶ if ($path_arg =~ m{\A/\.\./([^/]+)((?:/.+)?)/([^/]+)\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path_arg =~ m[\A/\.\./([^/]+)((?:/.+)?)/([^/]+)\z]u) 5 80 85
1678 5 ▶ my ($host, $dir_part, $file) = ($1, $2 // '', $3);
Condition50%1/2
$2 // ""
l!l
50
MC/DC0%0/1
$2 // ""
$2
Truth table50%1/2
A
A= $2
Aresult
11
00
1679 5 ▶ $dir_part = '/' unless length $dir_part;
Branch: 1 branch
BranchTrueFalseTotal
unless length $dir_part 0 5 5
1680 5 ▶ return () unless $host =~ $REMOTE_HOST_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $host =~ /$REMOTE_HOST_RE/u 1 4 5
1681 4 ▶ my ($table, $ext) = $file =~ /\A(.+)\.([^.]+)\z/ ? ($1, $2) : ($file, undef);
Branch: 1 branch
BranchTrueFalseTotal
$file =~ /\A(.+)\.([^.]+)\z/u ? : 4 0 4
1682 4 ▶ my $src = eval { $self->open_table($table, directory => $dir_part, host => $host,
Branch: 1 branch
BranchTrueFalseTotal
defined $ext ? : 4 0 4
1683 defined $ext ? (file_ext => $ext) : (), @it) };
1684 4 ▶ return ($src, $internal // $file) if $src && !$@;
Branch: 1 branch
BranchTrueFalseTotal
if $src and not $@ 3 1 4
Condition50%3/6
$src and not $@
!ll&&!rl&&r
103
$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
1685 1 return ();
1686 }
1687 80 ▶ return () if _outside_roots($self, $path_arg);
Branch: 1 branch
BranchTrueFalseTotal
if _outside_roots($self, $path_arg) 0 80 80
1688 80 my $file = eval { Mojo::File->new($path_arg)->realpath };
1689 80 ▶ 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) 75 5 80
Condition83%5/6
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
!ll&&!rl&&r
1475
defined $file and -f $file
!ll&&!rl&&r
1079
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
1690 75 my $dir = $file->dirname->to_string;
1691 75 (my $table = $file->basename) =~ s/\.[^.]+\z//;
1692 75 my $src = eval { $self->open_table($table, directory => $dir, @it) };
1693 75 ▶ return ($src, $internal // $file->basename) if $src && !$@;
Branch: 1 branch
BranchTrueFalseTotal
if $src and not $@ 75 0 75
Condition33%2/6
$src and not $@
!ll&&!rl&&r
0075
$internal // $file->basename
l!l&&r!l&&!r
0750
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
1694 }
1695 } elsif($spec =~ $URL_SPEC_RE) {
1696 1 my $url = $1;
1697 1 ▶ return () unless _is_safe_url($url);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_safe_url($url) 1 0 1
1698 0 my $src = eval { $self->open_table('', url => $url) };
1699 0 ▶ return ($src, $src->table_name) 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
1700 } elsif($spec =~ $REDIS_SPEC_RE) {
1701 0 my ($table, $redis_url) = ($1, $2);
1702 0 my $src = eval { $self->open_table($table, redis => $redis_url) };
1703 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
1704 } elsif($spec =~ $MARIADB_SPEC_RE) {
1705 0 my ($server, $table) = ($1, $2);
1706 0 my $src = eval { $self->open_table($table, mariadb => $server) };
1707 0 ▶ return ($src, $table) if $src;
Branch: 1 branch
BranchTrueFalseTotal
if $src 0 0 0
1708 # A server has more ways to fail than a file has; /open says which.
1709 0 $self->stash(open_spec_error => _tidy_error($@));
1710 }
1711 45 return ();
1712 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1713  
1714 # _schema_type_name($entry) -> $type
1715 #
1716 # Purpose: Normalise one schema() entry to an upper-case type name.
1717 # Entry: A hashref such as { type => 'INTEGER' }, a plain string, or undef.
1718 # Exit: The type name, or '' when the backend did not declare one.
1719 24 ▶sub _schema_type_name {
Subroutine _schema_type_name: called CC=6 SCAR=17.9
1720 24 my ($entry) = @_;
1721 24 ▶ return '' unless defined $entry;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry 1 23 24
1722  
1723 23 ▶ my $type = ref($entry) eq 'HASH' ? $entry->{type} : $entry;
Branch: 1 branch
BranchTrueFalseTotal
ref $entry eq 'HASH' ? : 15 8 23
1724 23 ▶ return '' unless defined($type) && !ref($type) && length($type);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type and not ref $type and length $type 6 17 23
Condition100%6/6
defined $type and not ref $type and length $type
!ll&&!rl&&r
3317
defined $type and not ref $type
!ll&&!rl&&r
2120
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
1725  
1726 17 return uc $type;
1727 }
1728  
1729 # _schema_type_warnings($self, $left, $right, $left_label, $right_label,
1730 # $left_key, $right_key) -> @warning_text
1731 #
1732 # Purpose: Describe columns whose declared types disagree across one join step.
1733 # Entry: $left and $right are open sources; the labels name them in the message.
1734 # The two join keys are excluded: Database::Join itself treats their
1735 # types as free to differ, because the key is not a data column.
1736 # Exit: Zero or more formatted warning strings for the schema_warnings banner.
1737 #
1738 # Database::Join's warn_schema_type_mismatch cannot fire here: every join this
1739 # controller builds passes a collision_prefix for the right table, so the
1740 # mismatched columns are published under distinct names and the check correctly
1741 # stays quiet. The difference still matters to a reader - a sum over a text
1742 # column yields nothing - so the comparison is made here, on the two sides as
1743 # the user sees them in the join panel.
1744 17 ▶sub _schema_type_warnings :Protected ($self, $left, $right, $left_label, $right_label,
Subroutine _schema_type_warnings: called CC=15 SCAR=27.4
1745 $left_key, $right_key) {
1746 17 ▶ my $left_schema = eval { $left->schema } // {};
Condition100%2/2
eval { do { $left->schema } } // {}
l!l
161
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
1747 17 ▶ my $right_schema = eval { $right->schema } // {};
Condition50%1/2
eval { do { $right->schema } } // {}
l!l
170
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
1748 17 ▶ return () unless %{ $left_schema // {} } && %{ $right_schema // {} };
Branch: 1 branch
BranchTrueFalseTotal
unless %{$left_schema // {};} and %{$right_schema // {};} 2 15 17
Condition57%4/7
%{$left_schema // {};} and %{$right_schema // {};}
!ll&&!rl&&r
2015
$left_schema // {}
l!l
170
$right_schema // {}
l!l
150
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
1749  
1750 15 ▶ my %is_key = map { (defined($_) && length($_)) ? ($_ => 1) : () }
Branch: 1 branch
BranchTrueFalseTotal
defined $_ && length $_ ? : 24 6 30
Condition66%2/3
defined $_ and length $_
!ll&&!rl&&r
0624
MC/DC50%1/2
defined $_ and length $_
defined $_ length $_
Truth table66%2/3
A and B
A= defined $_B= length $_
ABresult
0X0
100
111
1751 ($left_key, $right_key);
1752  
1753 15 my @warnings;
1754 15 for my $col (sort keys %$right_schema) {
1755 35 ▶ next if $is_key{$col};
Branch: 1 branch
BranchTrueFalseTotal
if $is_key{$col} 12 23 35
1756 23 ▶ next unless exists $left_schema->{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $left_schema->{$col} 15 8 23
1757  
1758 8 my $left_type = _schema_type_name($left_schema->{$col});
1759 8 my $right_type = _schema_type_name($right_schema->{$col});
1760 8 ▶ next unless length($left_type) && length($right_type);
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_type and length $right_type 1 7 8
Condition66%2/3
length $left_type and length $right_type
!ll&&!rl&&r
107
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
1761 7 ▶ next if $left_type eq $right_type;
Branch: 1 branch
BranchTrueFalseTotal
if $left_type eq $right_type 6 1 7
1762  
1763 1 push @warnings, $self->_i18n('warn_join_schema_mismatch',
1764 $col, $left_type, $left_label, $right_type, $right_label);
1765 }
1766  
1767 15 return @warnings;
1768 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1769  
1770 # _spec_to_url($self, $spec) -> $url_string
1771 #
1772 # Purpose: Convert a table/path spec back to a browseable URL (used for the
1773 # back-link on join and export views).
1774 # Entry: $spec is a "table:name", "table:file/table" or "path:/abs" string.
1775 # Exit: Returns a URL string beginning with '/'.
1776 1070 ▶sub _spec_to_url :Protected ($self, $spec) {
Subroutine _spec_to_url: called CC=10 SCAR=27.3
1777 1070 ▶ 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) 959 111 1070
1778 959 my ($table, $internal) = ($1, $2);
1779 959 ▶ return "/view/$table" unless defined $internal;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $internal 959 0 959
1780  
1781 0 my $data_dir = _data_dir_for($self->app);
1782 0 for my $ext (@SUPPORTED_EXT) {
1783 0 my $file = $data_dir->child("$table.$ext");
1784 0 ▶ next unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 0 0 0
1785 0 return '/open?path=' . url_escape($file->to_string) . '&it=' . url_escape($internal);
1786 }
1787 0 return "/view/$table";
1788 }
1789 111 ▶ if ($spec =~ /\Apath:(.+)\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ /\Apath:(.+)\z/u) 55 56 111
1790 55 my ($file, $internal) = _split_path($1);
1791 55 ▶ return '/open?path=' . url_escape($file) . (defined $internal ? '&it=' . url_escape($internal) : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 0 55 55
1792 }
1793 56 ▶ return '/import?url=' . url_escape($1) if $spec =~ $URL_SPEC_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /$URL_SPEC_RE/u 2 54 56
1794 54 ▶ return '/' if $spec =~ $REDIS_SPEC_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /$REDIS_SPEC_RE/u 0 54 54
1795 54 ▶ return '/open?path=' . url_escape($spec) if $spec =~ $MARIADB_SPEC_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /$MARIADB_SPEC_RE/u 0 54 54
1796 54 return '/';
1797 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1798  
1799 # _url_attribution($self) -> ($url_string, $date_string) or (undef, undef)
1800 #
1801 # Purpose: Return source URL and access date for chart attribution when the
1802 # left table was imported from a web URL. The date is the time of
1803 # the current request (which is when the data is being accessed),
1804 # formatted as "D Month YYYY".
1805 # Entry: Reads the 'l' query param.
1806 # Exit: ($url, $date) when the spec matches $URL_SPEC_RE; (undef, undef)
1807 # for table: and path: specs.
1808 300 ▶sub _url_attribution :Protected ($self) {
Subroutine _url_attribution: called CC=3 SCAR=11.0
1809 300 ▶ my $spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
2991
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
1810 300 ▶ return (undef, undef) unless $spec =~ $URL_SPEC_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $spec =~ /$URL_SPEC_RE/u 299 1 300
1811 1 my $url = $1;
1812 1 my @MON = qw(January February March April May June July August
1813 September October November December);
1814 1 my (undef, undef, undef, $mday, $mon, $year) = localtime;
1815 1 return ($url, sprintf('%d %s %d', $mday, $MON[$mon], $year + 1900));
1816 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1817  
1818 # _get_columns($source, $records) -> @column_names
1819 #
1820 # Purpose: Return an ordered column list from a DataSource object.
1821 # For CSV/TSV/PSV the DataSource stores the original file-header order.
1822 # For SQLite/XML where no file-header order is available, the fallback
1823 # is: id_column first (only if it actually appears in the data), then
1824 # the remaining columns sorted alphabetically.
1825 # Entry: $source is a DataSource; $records is an arrayref of hashrefs (may be empty).
1826 # Exit: Returns a flat list of column-name strings (may be empty).
1827 #
1828 # Reduction: columns() is a pure accessor -- cache once to avoid a redundant
1829 # method dispatch on the second reference.
1830 985 ▶sub _get_columns {
Subroutine _get_columns: called CC=5 SCAR=16.1
1831 985 my ($source, $records) = @_;
1832 985 my $cols = $source->columns;
1833 985 ▶ return @$cols if $cols;
Branch: 1 branch
BranchTrueFalseTotal
if $cols 980 5 985
1834 5 ▶ return () unless $records->[0];
Branch: 1 branch
BranchTrueFalseTotal
unless $records->[0] 2 3 5
1835 3 my %all = map { $_ => 1 } keys %{ $records->[0] };
1836 3 my $c = $source->id_column;
1837 3 ▶ my $id = ($c && $all{$c}) ? $c : (sort keys %all)[0];
Branch: 1 branch
BranchTrueFalseTotal
$c && $all{$c} ? : 1 2 3
Condition66%2/3
$c and $all{$c}
!ll&&!rl&&r
201
MC/DC50%1/2
$c and $all{$c}
$c $all{$c}
Truth table66%2/3
A and B
A= $cB= $all{$c}
ABresult
0X0
100
111
1838 3 delete $all{$id};
1839 3 return ($id, sort keys %all);
1840 }
1841  
1842 # _apply_filter_spec($records, $spec) -> \@filtered_records
1843 #
1844 # Purpose: Apply one "col:op:val" filter to an arrayref of record hashrefs and
1845 # return a new (possibly shorter) arrayref. The original is not mutated.
1846 # Value may contain colons: "col:op:val:with:colons" -- split limit 3
1847 # puts everything after the second colon into $val.
1848 # Unknown operators fall through to 1 (all rows pass) so new operators
1849 # added in future do not break existing callers.
1850 # Entry: $records is an arrayref of hashrefs; $spec is a colon-delimited string.
1851 # Exit: Returns filtered arrayref (same reference if spec is invalid/unparseable).
1852 #
1853 # Domain Constraints (operator names):
1854 # Operator names are CASE-SENSITIVE. Only the exact lowercase forms below are
1855 # recognised; an uppercase or mixed-case name (e.g. "EQ", "Lt") falls through
1856 # to the default `1` branch and all rows pass unfiltered.
1857 # Valid operators:
1858 # String (value comparison is case-insensitive via lc()):
1859 # eq, ne, contains, starts
1860 # Numeric (Perl <, <=, >, >= coercion):
1861 # lt (strict), le (inclusive), gt (strict), ge (inclusive)
1862 # Unary (val is ignored):
1863 # empty (cell eq ''), notempty (cell ne '')
1864 # List (val = a JSON array of strings; compared as eq is):
1865 # in -- lc(cell) is one of them; a val that is not such an array matches nothing
1866 # Range (val = lo:hi, both ends included, whichever is written first;
1867 # see _between_bounds for where a timestamp's colons leave it):
1868 # between -- two numbers compare as numbers, two dates or timestamps
1869 # as times (at the precision of the bounds), anything else as text,
1870 # case-insensitively
1871 # Boundary rules for numeric operators:
1872 # le/ge include the boundary value; lt/gt exclude it.
1873 # contains/starts with empty val ('') match every record (index always 0).
1874 #
1875 # Reduction: split(/:/, $spec, 3) always produces at least one defined element,
1876 # so "defined $col" is structurally guaranteed true and is removed.
1877 # "$_->{$col} // ''" replaces the equivalent ternary form.
1878 #
1879 # Optimisation: $lval = lc($val) is computed once before the grep. Without this
1880 # precompute, every case-insensitive operator (eq, ne, contains, starts) would
1881 # call lc($val) O(N) times for N records -- a pure O(N) waste since $val is
1882 # constant within a single filter application.
1883 # _is_iso_date($value) -> bool
1884 #
1885 # Purpose: Report whether a filter value names a point in time rather than a
1886 # plain string, so the date comparisons can be used instead of the
1887 # string ones. A bare date (YYYY-MM-DD) qualifies, and so does an ISO
1888 # timestamp (YYYY-MM-DDTHH:MM:SS) or the same with a space separator,
1889 # which is what CSV exports and SQLite text columns usually hold, and
1890 # one with a fraction of a second or a zone (Z, +01:00), which is what
1891 # JSON APIs write. The time is taken as written (Util::iso_datetime).
1892 2104 ▶sub _is_iso_date {
Subroutine _is_iso_date: called CC=2 SCAR=6.9
1893 2104 ▶ return scalar(() = Database::BI::Util::iso_datetime($_[0])) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
scalar(() = Database::BI::Util::iso_datetime($_[0])) ? : 1055 1049 2104
1894 }
1895  
1896 # Convert M/D/YYYY or YYYY-MM-DD to YYYY-MM-DD; returns undef for other formats.
1897 # A value that is already ISO is returned unchanged, including its time part: a
1898 # timestamp cell is the caller's to compare, not this sub's to truncate.
1899 1947 ▶sub _to_iso_date {
Subroutine _to_iso_date: called CC=4 SCAR=13.9
1900 1947 my ($v) = @_;
1901 1947 ▶ return unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 1 1946 1947
1902 1946 ▶ return $v if _is_iso_date($v);
Branch: 1 branch
BranchTrueFalseTotal
if _is_iso_date($v) 1009 937 1946
1903 937 ▶ 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) 4 933 937
1904 4 return sprintf '%04d-%02d-%02d', $y, $m, $d;
1905 }
1906 933 return;
1907 }
1908  
1909 # _time_columns(\@columns, \@records) -> \@names
1910 #
1911 # Purpose: The columns a time range can be applied to: those whose every
1912 # non-empty cell on the page is a date or a date and time that the
1913 # range filter reads (_to_iso_date: YYYY-MM-DD, with an optional
1914 # "THH:MM[:SS]" or " HH:MM[:SS]", or M/D/YYYY), with a month and day
1915 # that can exist, and at least one such cell. The dashboard offers
1916 # Time range only when this is not empty, and lists only these.
1917 # Entry: $columns is the page's column order; $records its rows (hashes).
1918 # Exit: Returns the qualifying names, in column order; [] when there are
1919 # none, no rows, or either argument is not an array.
1920 # Notes: It reads the rows drawn on the page, as the table's own date
1921 # detection does: reading every row of the view for this would cost a
1922 # second pass over the data on every page.
1923 202 ▶sub _time_columns {
Subroutine _time_columns: called CC=15 SCAR=29.1
1924 202 my ($columns, $records) = @_;
1925 202 ▶ 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 202 202
Condition33%1/3
ref $columns eq "ARRAY" and ref $records eq "ARRAY"
!ll&&!rl&&r
00202
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
1926 202 my @found;
1927 202 COLUMN: for my $col (@{$columns}) {
1928 1105 ▶ next unless defined $col;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col 0 1105 1105
1929 1105 my $seen = 0;
1930 1105 for my $row (@{$records}) {
1931 1974 ▶ next unless ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 0 1974 1974
1932 1974 my $v = $row->{$col};
1933 1974 ▶ next unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 3 1971 1974
1934 1971 $v =~ s/\A\s+|\s+\z//g;
1935 1971 ▶ next unless length $v;
Branch: 1 branch
BranchTrueFalseTotal
unless length $v 72 1899 1971
1936 1899 my $iso = _to_iso_date($v);
1937 1899 ▶ next COLUMN unless defined $iso;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $iso 932 967 1899
1938 967 my ($m, $d) = $iso =~ /\A\d{4}-(\d{2})-(\d{2})/;
1939 967 ▶ 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 967 967
Condition33%3/9
$m >= 1 and $m <= 12 and $d >= 1 and $d <= 31
!ll&&!rl&&r
00967
$m >= 1 and $m <= 12 and $d >= 1
!ll&&!rl&&r
00967
$m >= 1 and $m <= 12
!ll&&!rl&&r
00967
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
1940 967 $seen = 1;
1941 }
1942 173 ▶ push @found, $col if $seen;
Branch: 1 branch
BranchTrueFalseTotal
if $seen 170 3 173
1943 }
1944 202 return \@found;
1945 }
1946  
1947 # _date_key($value, $precision) -> comparable key | undef
1948 #
1949 # Purpose: Put a cell and a filter bound on the same footing so that a
1950 # lexicographic comparison answers the question the filter asked.
1951 # $precision is 10 for a day and 19 for a second: a cell holding a
1952 # timestamp is compared at the day it falls in when the bound is a
1953 # day, and to the second when the bound carries a time. A value that
1954 # is not date-shaped at all returns undef, and the caller keeps the
1955 # raw cell instead.
1956 68 ▶sub _date_key {
Subroutine _date_key: called CC=7 SCAR=19.5
1957 68 my ($value, $precision) = @_;
1958 68 ▶ return undef unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 67 68
1959 67 my ($day, $hour, $min, $sec) = Database::BI::Util::iso_datetime($value);
1960 67 ▶ return undef unless defined $day;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $day 1 66 67
1961 66 ▶ return $day if $precision < 19;
Branch: 1 branch
BranchTrueFalseTotal
if $precision < 19 43 23 66
1962 23 ▶ return sprintf '%sT%s:%s:%s', $day, $hour // '00', $min // '00', $sec // '00';
Condition100%6/6
$hour // "00"
l!l
212
$min // "00"
l!l
212
$sec // "00"
l!l
194
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
1963 }
1964  
1965 # ---------------------------------------------------------------------------
1966 # Relative time ranges
1967 # ---------------------------------------------------------------------------
1968  
1969 # _iso_day($epoch) -> 'YYYY-MM-DD' in local time
1970 48098 ▶sub _iso_day {
Subroutine _iso_day: called CC=1 SCAR=0.0
1971 48098 my @lt = localtime($_[0]);
1972 48098 return sprintf '%04d-%02d-%02d', $lt[5] + 1900, $lt[4] + 1, $lt[3];
1973 }
1974  
1975 # _iso_second($epoch) -> 'YYYY-MM-DDTHH:MM:SS' in local time
1976 4373 ▶sub _iso_second {
Subroutine _iso_second: called CC=1 SCAR=0.0
1977 4373 my @lt = localtime($_[0]);
1978 4373 return sprintf '%04d-%02d-%02dT%02d:%02d:%02d',
1979 $lt[5] + 1900, $lt[4] + 1, $lt[3], $lt[2], $lt[1], $lt[0];
1980 }
1981  
1982 # _midday($mday, $mon, $year) -> epoch
1983 #
1984 # Noon, so a boundary never lands in a daylight-saving gap, and mktime's own
1985 # normalisation (day 0 is the last day of the previous month, month -1 is
1986 # December, and so on) is what makes the month, quarter and year arithmetic
1987 # below one line each. $mon is 0-based, $year is years since 1900, matching
1988 # localtime's own convention.
1989 54657 ▶sub _midday {
Subroutine _midday: called CC=1 SCAR=0.0
1990 54657 require POSIX;
1991 54657 return POSIX::mktime(12, 0, 0, $_[0], $_[1], $_[2]);
1992 }
1993  
1994 # _time_range_bounds($preset, $now) -> ($lo, $hi)
1995 #
1996 # Purpose: Resolve one preset to the window it names, as two strings that the
1997 # filter engine can compare against: 'YYYY-MM-DD' for a day-granular
1998 # window, 'YYYY-MM-DDTHH:MM:SS' for last_24_hours.
1999 # Entry: $preset -- one entry of @TIME_RANGES.
2000 # $now -- epoch second; defaults to the clock, and a caller may
2001 # pass one so a test can name the day it is asking about.
2002 # Exit: Two-element list, or an empty list for a preset with no window.
2003 # Notes: "This month" and "this quarter" end today rather than at the end of
2004 # the period, which is what the same names mean in a search bar; the
2005 # completed period is last_month / last_quarter.
2006 26234 ▶sub _time_range_bounds {
Subroutine _time_range_bounds: called CC=11 SCAR=24.0
2007 26234 my ($preset, $now) = @_;
2008 26234 ▶ $now = time() unless defined $now;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $now 26209 25 26234
2009  
2010 26234 my @lt = localtime($now);
2011 26234 my ($mday, $mon, $year) = @lt[3, 4, 5]; # mon is 0-based
2012  
2013 26234 ▶ if ($preset->{hours}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($preset->{"hours"}) 2186 24048 26234
2014 2186 return (_iso_second($now - $preset->{hours} * 3600), _iso_second($now));
2015 }
2016  
2017 24048 my $today = _midday($mday, $mon, $year);
2018  
2019 24048 ▶ if (defined $preset->{day}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $preset->{"day"}) 4372 19676 24048
2020 4372 my $day = _midday($mday + $preset->{day}, $mon, $year);
2021 4372 return (_iso_day($day), _iso_day($day));
2022 }
2023  
2024 19676 ▶ if (defined $preset->{days}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $preset->{"days"}) 6557 13119 19676
2025 6557 return (_iso_day(_midday($mday - $preset->{days} + 1, $mon, $year)),
2026 _iso_day($today));
2027 }
2028  
2029 13119 ▶ if (defined $preset->{month}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $preset->{"month"}) 4373 8746 13119
2030 4373 my $m = $mon + $preset->{month};
2031 4373 ▶ return $preset->{month} == 0
Branch: 1 branch
BranchTrueFalseTotal
$preset->{'month'} == 0 ? : 2186 2187 4373
2032 ? (_iso_day(_midday(1, $mon, $year)), _iso_day($today))
2033 : (_iso_day(_midday(1, $m, $year)), _iso_day(_midday(0, $m + 1, $year)));
2034 }
2035  
2036 8746 ▶ if (defined $preset->{quarter}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $preset->{"quarter"}) 4373 4373 8746
2037 4373 my $q = int($mon / 3) * 3 + 3 * $preset->{quarter};
2038 4373 ▶ return $preset->{quarter} == 0
Branch: 1 branch
BranchTrueFalseTotal
$preset->{'quarter'} == 0 ? : 2186 2187 4373
2039 ? (_iso_day(_midday(1, $q, $year)), _iso_day($today))
2040 : (_iso_day(_midday(1, $q, $year)), _iso_day(_midday(0, $q + 3, $year)));
2041 }
2042  
2043 4373 ▶ if (defined $preset->{year}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $preset->{"year"}) 4372 1 4373
2044 4372 my $y = $preset->{year}; # 0 = this year, -1 = last year
2045 4372 my $start = _midday(1, 0, $year + $y);
2046 4372 ▶ return $preset->{year} == 0
Branch: 1 branch
BranchTrueFalseTotal
$preset->{'year'} == 0 ? : 2186 2186 4372
2047 ? (_iso_day($start), _iso_day($today))
2048 : (_iso_day($start), _iso_day(_midday(31, 11, $year + $y)));
2049 }
2050  
2051 1 return ();
2052 }
2053  
2054 # _time_range_specs($col, $lo, $hi) -> \@specs
2055 #
2056 # Purpose: Express a window as the f= filters the pipeline applies.
2057 # Notes: Two bounds -- col:ge:lo and col:le:hi -- rather than one between
2058 # spec. A between value is "lo:hi", and its colon has to be found
2059 # among a timestamp's own (_between_bounds; last_24_hours ends in
2060 # HH:MM:SS); one bound per spec needs no such search. Two specs are
2061 # inclusive at both ends exactly once, whatever precision the bounds
2062 # carry.
2063 6 ▶sub _time_range_specs {
Subroutine _time_range_specs: called CC=7 SCAR=19.6
2064 6 my ($col, $lo, $hi) = @_;
2065 6 ▶ return [] unless length($col // '') && length($lo // '') && length($hi // '');
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and length($lo // "") and length($hi // "") 4 2 6
Condition83%10/12
length($col // "") and length($lo // "") and length($hi // "")
!ll&&!rl&&r
312
length($col // "") and length($lo // "")
!ll&&!rl&&r
213
$col // ""
l!l
51
$lo // ""
l!l
40
$hi // ""
l!l
30
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
2066 2 return [ "$col:ge:$lo", "$col:le:$hi" ];
2067 }
2068  
2069 # _time_range_preset($name) -> \%preset | undef
2070 #
2071 # The named entry of the vocabulary above, or undef for a name that is not in
2072 # it. A URL value reaches this, so it answers undef rather than croaking.
2073 17 ▶sub _time_range_preset {
Subroutine _time_range_preset: called CC=2 SCAR=6.9
2074 17 my ($name) = @_;
2075 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
2076 }
2077  
2078 # _time_range_presets($now) -> \@presets
2079 #
2080 # Purpose: The menu a filter bar offers, with the dates each entry currently
2081 # resolves to, so the page can show a range and, where it has asked
2082 # for the dataset's own extent, disable an entry the data cannot
2083 # answer.
2084 2185 ▶sub _time_range_presets {
Subroutine _time_range_presets: called CC=1 SCAR=0.0
2085 2185 my ($now) = @_;
2086 return [ map {
2087 2185 my ($lo, $hi) = _time_range_bounds($_, $now);
2088 26220 { name => $_->{name}, label => $_->{label}, lo => $lo, hi => $hi }
2089 } @TIME_RANGES ];
2090 }
2091  
2092 # _apply_time_range($records, $name, $col) -> \@records
2093 #
2094 # Purpose: Apply a named relative range to a record set. Used by the canvas,
2095 # which renders its cards from its own pipeline rather than through a
2096 # route's f= params.
2097 # Entry: $name and $col are the URL values; neither is trusted. An unknown
2098 # name or an unusable column leaves the records alone, so a stale
2099 # bookmark shows unfiltered data rather than an error page.
2100 31 ▶sub _apply_time_range {
Subroutine _apply_time_range: called CC=7 SCAR=19.5
2101 31 my ($records, $name, $col) = @_;
2102 31 ▶ my $preset = $TIME_RANGE{$name // ''} or return $records;
Branch: 1 branch
BranchTrueFalseTotal
my $preset = $TIME_RANGE{$name // ""} or return $records 4 27 31
Condition100%2/2
$name // ""
l!l
625
MC/DC100%1/1
$name // ""
$name
Truth table100%2/2
A
A= $name
Aresult
11
00
2103 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
2104 1 my ($lo, $hi) = _time_range_bounds($preset);
2105 1 for my $spec (@{ _time_range_specs($col, $lo, $hi) }) {
2106 2 $records = _apply_filter_spec($records, $spec);
2107 }
2108 1 return $records;
2109 }
2110  
2111 # _time_range_request($c) -> bool
2112 #
2113 # Purpose: Turn the relative time range a request names -- ?range=<name> and
2114 # ?rcol=<column> -- into the f= filters every data route already
2115 # applies, and describe the range on the stash so a template can show
2116 # a chip and the preset menu. Registered as a before_dispatch hook in
2117 # Database::BI::startup, so one implementation covers the table view,
2118 # every chart, the pivot, stats, insights, the exports and the canvas,
2119 # and a request that carries a range needs no per-route code.
2120 # Entry: $c -- the controller for the request.
2121 # Exit: Records the resolved bounds on the stash, where _filter_specs picks
2122 # them up for whichever pipeline the route runs, and returns true --
2123 # or renders 400 for a range that cannot be honoured and returns
2124 # false, which stops the route from running against the wrong rows.
2125 # The bounds are not written back into the request's f= params, so the
2126 # reader's own filter list -- the chips, the panel forms and the
2127 # filter UI -- never shows a range as dates it did not choose.
2128 2184 ▶sub _time_range_request ($c) {
Subroutine _time_range_request: called CC=7 SCAR=25.7
2129 2184 my $name = $c->param('range');
2130 2184 my $col = $c->param('rcol');
2131  
2132 2184 $c->stash(time_range_presets => _time_range_presets());
2133 2184 $c->stash(range_specs => []);
2134  
2135 2184 ▶ return 1 unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 1967 217 2184
Condition100%3/3
defined $name and length $name
!ll&&!rl&&r
192740217
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
2136  
2137 217 my $preset = $TIME_RANGE{$name};
2138 217 ▶ unless ($preset) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($preset) 217 0 217
2139 $c->render(
2140 text => sprintf(_message_text('error_range_name'), $name,
2141 217 join(', ', map { $_->{name} } @TIME_RANGES)),
2142 status => 400,
2143 );
2144 217 return 0;
2145 }
2146 0 ▶ unless (defined $col && length $col && $col !~ /:/) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $col and length $col and not $col =~ /:/u) 0 0 0
Condition0%0/6
defined $col and length $col and not $col =~ /:/u
!ll&&!rl&&r
000
defined $col and length $col
!ll&&!rl&&r
000
MC/DC0%0/3
defined $col and length $col and not $col =~ /:/u
defined $col length $col not $col =~ /:/u
Truth table0%0/4
A and B and not(C)
A= defined $colB= length $colC= not $col =~ /:/u
ABCresult
0XX0
10X0
1100
1111
2147 0 $c->render(text => _message_text('error_range_column'), status => 400);
2148 0 return 0;
2149 }
2150  
2151 0 my ($lo, $hi) = _time_range_bounds($preset);
2152 0 my $specs = _time_range_specs($col, $lo, $hi);
2153  
2154 $c->stash(
2155 time_range => {
2156 name => $preset->{name},
2157 label => $preset->{label},
2158 0 col => $col,
2159 lo => $lo,
2160 hi => $hi,
2161 },
2162 range_specs => $specs,
2163 );
2164 0 return 1;
2165 }
2166  
2167 # _filter_request($c) -> bool
2168 #
2169 # Purpose: Refuse an f= filter whose operator is not one _apply_filter_spec
2170 # knows. Until 0.021.0 such a filter kept every row, with nothing to
2171 # say it had done nothing (f=amount:GT:5, f=amount:gtx:5). Registered
2172 # as a before_dispatch hook in Database::BI::startup beside the time
2173 # range's, so every route that reads f= refuses it the same way.
2174 # Entry: $c -- the controller for the request.
2175 # Exit: True when every filter names a known operator, or has no column or
2176 # operator at all (such a spec has always been skipped); otherwise
2177 # renders 400 (error_filter_op, which lists the operators) and
2178 # returns false.
2179 # Notes: A filter on a column the view does not have is refused later, once
2180 # the columns are known (_unknown_filter_column). A canvas card's own
2181 # stored filters never come through here: they are ignored when stale,
2182 # by design.
2183 1967 ▶sub _filter_request ($c) {
Subroutine _filter_request: called CC=8 SCAR=20.9
2184 1967 ▶ for my $spec (@{ $c->every_param('f') // [] }) {
Condition50%1/2
$c->every_param("f") // []
l!l
19670
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
2185 87 my ($col, $op) = split /:/, $spec, 3;
2186 87 ▶ next unless length($col // '') && defined $op && length $op;
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and defined $op and length $op 61 26 87
Condition87%7/8
length($col // "") and defined $op and length $op
!ll&&!rl&&r
61026
length($col // "") and defined $op
!ll&&!rl&&r
412026
$col // ""
l!l
4740
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
2187 26 ▶ next if $FILTER_OP{$op};
Branch: 1 branch
BranchTrueFalseTotal
if $FILTER_OP{$op} 22 4 26
2188 4 $c->render(
2189 text => sprintf(_message_text('error_filter_op'), $op, $spec, join(', ', @FILTER_OPS)),
2190 status => 400,
2191 );
2192 4 return 0;
2193 }
2194 1963 return 1;
2195 }
2196  
2197 # _unknown_filter_column($self, \@columns, \%later) -> $message | undef
2198 #
2199 # Purpose: The refusal for a filter, or the time range, on a column the view
2200 # does not have. Such a filter used to read every cell as empty and
2201 # keep no rows (or every row, for ne and empty), so a mistyped name
2202 # looked like an empty file.
2203 # Entry: \@columns -- the view's columns at the filter stage; \%later -- the
2204 # columns stages 6 and 7 will add (a filter on one waits for them).
2205 # Exit: undef when every filter names a column there, or when the columns
2206 # are not known (no list, or an empty one: a URL source's cache, or
2207 # a view with no rows); else the error_filter_column message (or
2208 # error_range_column_unknown for rcol=), naming the columns there.
2209 # Notes: A plain function, like _reduce_records, which calls it; _fetch_page
2210 # calls it too, for the table pages.
2211 654 ▶sub _unknown_filter_column {
Subroutine _unknown_filter_column: called CC=14 SCAR=32.2
2212 654 my ($self, $columns, $later) = @_;
2213 654 ▶ return undef unless ref $columns eq 'ARRAY' && @{$columns};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $columns eq "ARRAY" and @{$columns;} 9 645 654
Condition66%2/3
ref $columns eq "ARRAY" and @{$columns;}
!ll&&!rl&&r
90645
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
2214 645 ▶ my %known = ((map { $_ => 1 } @{$columns}), %{ $later // {} });
Condition50%1/2
$later // {}
l!l
6450
MC/DC0%0/1
$later // {}
$later
Truth table50%1/2
A
A= $later
Aresult
11
00
2215 0 ▶ my $listed = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2216 0 my @names = @{$columns};
2217 0 ▶ return join(', ', @names) if @names <= $FILTER_COLUMNS_LISTED;
Branch: 1 branch
BranchTrueFalseTotal
if @names <= $FILTER_COLUMNS_LISTED 0 0 0
2218 0 return join(', ', @names[0 .. $FILTER_COLUMNS_LISTED - 1])
2219 . sprintf(' and %d more', @names - $FILTER_COLUMNS_LISTED);
2220 645 };
2221 645 ▶ for my $spec (@{ $self->every_param('f') // [] }) {
Condition50%1/2
$self->every_param("f") // []
l!l
6450
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
2222 36 my ($col, $op) = split /:/, $spec, 3;
2223 36 ▶ next unless length($col // '') && defined $op && length $op;
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and defined $op and length $op 11 25 36
Condition62%5/8
length($col // "") and defined $op and length $op
!ll&&!rl&&r
11025
length($col // "") and defined $op
!ll&&!rl&&r
01125
$col // ""
l!l
360
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
2224 25 ▶ next if $known{$col};
Branch: 1 branch
BranchTrueFalseTotal
if $known{$col} 25 0 25
2225 0 return sprintf(_message_text('error_filter_column'), $col, $spec, $listed->());
2226 }
2227 645 my $range = $self->stash('time_range');
2228 645 ▶ if (ref $range eq 'HASH' && !$known{ $range->{col} // '' }) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $range eq "HASH" and not $known{$range->{"col"} // ""}) 0 645 645
Condition20%1/5
ref $range eq "HASH" and not $known{$range->{"col"} // ""}
!ll&&!rl&&r
64500
$range->{"col"} // ""
l!l
00
MC/DC0%0/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 table33%1/3
A and not(B)
A= ref $range eq "HASH"B= not $known{$range->{"col"} // ""}
ABresult
0X0
100
111
Truth table0%0/2
A
A= $range->{"col"}
Aresult
11
00
2229 0 return sprintf(_message_text('error_range_column_unknown'), $range->{col}, $range->{col}, $listed->());
2230 }
2231 645 return undef;
2232 }
2233  
2234 # _filter_in_values($val) -> @strings
2235 #
2236 # The values an f=col:in:<val> filter lists: $val is a JSON array, and only its
2237 # plain scalars count (a null is the empty cell). Anything else lists nothing,
2238 # so a damaged link matches no row rather than every row.
2239 32 ▶sub _filter_in_values {
Subroutine _filter_in_values: called CC=5 SCAR=16.1
2240 32 my ($val) = @_;
2241 32 local $@;
2242 32 my $list;
2243 32 ▶ return () unless eval { $list = from_json($val // q{}); 1 };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $list = from_json($val // ""); 1 } } 7 25 32
Condition100%2/2
$val // ""
l!l
311
MC/DC100%1/1
$val // ""
$val
Truth table100%2/2
A
A= $val
Aresult
11
00
2244 25 ▶ return () unless ref($list) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" 4 21 25
2245 21 ▶ return map { $_ // '' } grep { !ref } @{$list};
Condition100%2/2
$_ // ""
l!l
332
MC/DC100%1/1
$_ // ""
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
2246 }
2247  
2248 # _between_bounds($val) -> ($lo, $hi) | ()
2249 #
2250 # Purpose: Split a between value, "lo:hi", into its two bounds. The
2251 # separator is a colon, and a timestamp holds colons of its own, so
2252 # the split is made where both sides read as dates or timestamps if
2253 # there is such a place, and at the first colon otherwise.
2254 # Input: $val - the filter value.
2255 # Output: The two bounds, both non-empty, in the order written; the empty
2256 # list when there is no colon or either side is empty.
2257 26 ▶sub _between_bounds {
Subroutine _between_bounds: called CC=9 SCAR=22.0
2258 26 my ($val) = @_;
2259 26 ▶ return () unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 1 25 26
2260 25 my @at;
2261 25 my $pos = -1;
2262 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
2263 25 ▶ return () unless @at;
Branch: 1 branch
BranchTrueFalseTotal
unless @at 3 22 25
2264 22 for my $i (@at) {
2265 30 my ($lo, $hi) = (substr($val, 0, $i), substr($val, $i + 1));
2266 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
2267 }
2268 12 my ($lo, $hi) = (substr($val, 0, $at[0]), substr($val, $at[0] + 1));
2269 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
2270 9 return ($lo, $hi);
2271 }
2272  
2273 111 ▶sub _apply_filter_spec {
Subroutine _apply_filter_spec: called CC=63 SCAR=42.6
2274 111 my ($records, $spec) = @_;
2275 111 my ($col, $op, $val) = split /:/, $spec, 3;
2276 111 ▶ return $records unless length($col // '') && defined $op && length $op;
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and defined $op and length $op 13 98 111
Condition62%5/8
length($col // "") and defined $op and length $op
!ll&&!rl&&r
13098
length($col // "") and defined $op
!ll&&!rl&&r
01398
$col // ""
l!l
1110
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
2277 98 ▶ $val //= '';
Condition50%1/2
$val //= ""
l!l
980
MC/DC0%0/1
$val //= ""
$val
Truth table50%1/2
A
A= $val
Aresult
11
00
2278 98 my $lval = lc $val; # precompute once; avoids O(N) redundant lc() inside grep
2279 98 my $between = $op eq 'between';
2280 98 ▶ my ($lo, $hi) = $between ? _between_bounds($val) : ();
Branch: 1 branch
BranchTrueFalseTotal
$between ? : 21 77 98
2281 # A between is about times only when both its bounds are.
2282 98 ▶ my $is_date = $between
Branch: 1 branch
BranchTrueFalseTotal
$between ? : 21 77 98
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
2283 ? (defined $lo && _is_iso_date($lo) && _is_iso_date($hi))
2284 : _is_iso_date($val);
2285 # Compare at the precision the bound names: a bound with a time in it asks
2286 # about the second, a bare date asks about the day. Without this, a date
2287 # bound compared against a column of timestamps drops every row on the
2288 # boundary day, because the cell string carries more characters than the
2289 # bound and "2026-10-27T09:15:00" sorts after "2026-10-27".
2290 98 ▶ 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 95 98
$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
8783
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
2291 $between ? ($lo, $hi) : ($val))) ? 19 : 10;
2292 98 ▶ my $nval = $is_date && !$between ? (_date_key($val, $prec) // $val) : $val;
Branch: 1 branch
BranchTrueFalseTotal
$is_date && !$between ? : 2 96 98
Condition66%4/6
$is_date and not $between
!ll&&!rl&&r
8792
_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
2293 # An order is a statement about numbers. A blank or a word has no place in
2294 # one, so it matches none of the four, rather than counting as zero.
2295 98 ▶ 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
117413
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
2296 98 ▶ my $num_val = $by_number ? _numeric_cell($val) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$by_number ? : 13 85 98
2297 # A between of two numbers (a range of years, of prices) compares as
2298 # numbers, inclusive at both ends and whichever bound is written first;
2299 # "9" sorts after "10" as text. Anything else keeps the text comparison.
2300 # Dates and text likewise: the bounds are put in order before they are
2301 # used, so "2026-12-31:2026-01-01" is the year, not nothing.
2302 98 my ($num_lo, $num_hi);
2303 98 ▶ if ($between && defined $lo) {
Branch: 1 branch
BranchTrueFalseTotal
if ($between and defined $lo) 17 81 98
Condition100%3/3
$between and defined $lo
!ll&&!rl&&r
77417
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
2304 17 ▶ if ($is_date) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_date) { } 9 8 17
2305 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
2306 } else {
2307 8 ($num_lo, $num_hi) = (_numeric_cell($lo), _numeric_cell($hi));
2308 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
2309 8 ($lo, $hi) = (lc $lo, lc $hi);
2310 }
2311 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
2312 17 ▶ ($lo, $hi) = ($hi, $lo) if $lo gt $hi;
Branch: 1 branch
BranchTrueFalseTotal
if $lo gt $hi 8 9 17
2313 }
2314 98 ▶ my %in_set = $op eq 'in' ? (map { lc($_) => 1 } _filter_in_values($val)) : ();
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'in' ? : 20 78 98
2315 return [grep {
2316 98 ▶ my $cell = $_->{$col} // '';
Condition100%2/2
$_->{$col} // ""
l!l
39812
MC/DC100%1/1
$_->{$col} // ""
$_->{$col}
Truth table100%2/2
A
A= $_->{$col}
Aresult
11
00
2317 410 ▶ my $num = $by_number ? _numeric_cell($cell) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$by_number ? : 36 374 410
2318 410 ▶ my $both = defined $num && defined $num_val;
Condition66%2/3
defined $num && defined $num_val
!ll&&!rl&&r
374036
MC/DC50%1/2
defined $num && defined $num_val
defined $num defined $num_val
Truth table66%2/3
A && B
A= defined $numB= defined $num_val
ABresult
0X0
100
111
2319 # Normalise M/D/YYYY cells to ISO for date comparisons so that the
2320 # ISO values produced by <input type="date"> match against either format.
2321 410 ▶ my $ncell = $is_date
Branch: 1 branch
BranchTrueFalseTotal
$is_date ? : 43 367 410
Condition33%2/6
_date_key(_to_iso_date($cell) // $cell, $prec) // $cell
l!l&&r!l&&!r
4300
_to_iso_date($cell) // $cell
l!l&&r!l&&!r
4300
MC/DC0%0/2
_date_key(_to_iso_date($cell) // $cell, $prec) // $cell
_date_key(_to_iso_date($cell) // $cell, $prec) $cell
MC/DC0%0/2
_to_iso_date($cell) // $cell
_to_iso_date($cell) $cell
Truth table33%1/3
A // B
A= _date_key(_to_iso_date($cell) // $cell, $prec)B= $cell
ABresult
1X1
011
000
Truth table33%1/3
A // B
A= _to_iso_date($cell)B= $cell
ABresult
1X1
011
000
2322 ? (_date_key(_to_iso_date($cell) // $cell, $prec) // $cell)
2323 : $cell;
2324 $op eq 'eq' ? ($is_date ? $ncell eq $nval : lc($cell) eq $lval) :
2325 $op eq 'ne' ? ($is_date ? $ncell ne $nval : lc($cell) ne $lval) :
2326 $op eq 'contains' ? index(lc($cell), $lval) != -1 :
2327 $op eq 'starts' ? index(lc($cell), $lval) == 0 :
2328 $op eq 'lt' ? ($is_date ? $ncell lt $nval : $both && $num < $num_val) :
2329 $op eq 'le' ? ($is_date ? $ncell le $nval : $both && $num <= $num_val) :
2330 $op eq 'gt' ? ($is_date ? $ncell gt $nval : $both && $num > $num_val) :
2331 $op eq 'ge' ? ($is_date ? $ncell ge $nval : $both && $num >= $num_val) :
2332 $op eq 'empty' ? $cell eq '' :
2333 $op eq 'notempty' ? $cell ne '' :
2334 $op eq 'in' ? $in_set{ lc($cell) } :
2335 $op eq 'between' && defined $num_lo ? do {
2336 40 my $n = _numeric_cell($cell);
2337 40 ▶ defined $n && $n >= $num_lo && $n <= $num_hi
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'between' ? : 82 5 87
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
2338 } :
2339 410 ▶ $op eq 'between' ? do {
Branch: 18 branches
BranchTrueFalseTotal
$op eq 'eq' ? : 139 271 410
$is_date ? : 0 139 139
$op eq 'ne' ? : 2 269 271
$is_date ? : 0 2 2
$op eq 'contains' ? : 4 265 269
$op eq 'starts' ? : 4 261 265
$op eq 'lt' ? : 3 258 261
$is_date ? : 0 3 3
$op eq 'le' ? : 6 252 258
$is_date ? : 1 5 6
$op eq 'gt' ? : 18 234 252
$is_date ? : 0 18 18
$op eq 'ge' ? : 12 222 234
$is_date ? : 2 10 12
$op eq 'empty' ? : 3 219 222
$op eq 'notempty' ? : 3 216 219
$op eq 'in' ? : 89 127 216
$op eq 'between' && defined $num_lo ? : 40 87 127
Condition73%11/15
$both and $num < $num_val
!ll&&!rl&&r
021
$both and $num <= $num_val
!ll&&!rl&&r
023
$both and $num > $num_val
!ll&&!rl&&r
0810
$both and $num >= $num_val
!ll&&!rl&&r
055
$op eq "between" and defined $num_lo
!ll&&!rl&&r
58240
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/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
$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 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= $op eq "between"B= defined $num_lo
ABresult
0X0
100
111
2340 82 ▶ my $key = $is_date ? $ncell : lc $cell;
Branch: 1 branch
BranchTrueFalseTotal
$is_date ? : 40 42 82
2341 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
2342 } :
2343 1
2344 } @$records];
2345 }
2346  
2347 # ---------------------------------------------------------------------------
2348 # The cross-row pass (BI-Phase-7.md item 7.2)
2349 # ---------------------------------------------------------------------------
2350 #
2351 # A measure folds a group into one number and a calculated field computes one
2352 # row from that row. This is the third shape: one row from many rows, written
2353 # back onto every row -- a running total, a moving average, a rank, a share of
2354 # the whole. None of them can be a measure (the answer is per row, not per
2355 # group) and none can be a calc field (it needs its neighbours), which is why
2356 # they are a pass of their own.
2357 #
2358 # The functions follow Splunk's split, because it is also the natural one:
2359 # the eventstats family is order-free (pct_of_total, rank, zscore), the
2360 # streamstats family is incremental and therefore needs an order (running_*,
2361 # window_*, lag, delta, pct_change).
2362  
2363 # The same vocabulary as a menu, for the panel that adds a cross-row column.
2364 # It is data rather than a list written into the template so the function
2365 # names, their labels and the two facts the form needs -- whether a function
2366 # takes a window, and whether it needs an order -- cannot drift from the
2367 # validator above.
2368 5 Readonly my @CROSS_ROW_MENU => (
2369 { name => 'running_total', label => 'Running total', arg => 0, order => 1 },
2370 { name => 'running_count', label => 'Running count', arg => 0, order => 1 },
2371 { name => 'running_pct', label => 'Running percent', arg => 0, order => 1 },
2372 { name => 'window_sum', label => 'Moving sum', arg => 1, order => 1 },
2373 { name => 'window_avg', label => 'Moving average', arg => 1, order => 1 },
2374 { name => 'lag', label => 'Previous row', arg => 0, order => 1 },
2375 { name => 'delta', label => 'Change from previous', arg => 0, order => 1 },
2376 { name => 'pct_change', label => 'Percent change', arg => 0, order => 1 },
2377 { name => 'pct_of_total', label => 'Percent of total', arg => 0, order => 0 },
2378 { name => 'rank', label => 'Rank, largest first', arg => 0, order => 0 },
2379 { name => 'zscore', label => 'Z-score', arg => 0, order => 0 },
2380 );
2381  
2382 5 Readonly my %CROSS_ROW_FNS => (
2383 running_total => { family => 'stream' },
2384 running_count => { family => 'stream' },
2385 running_pct => { family => 'stream' },
2386 window_sum => { family => 'stream', arg => 'count' },
2387 window_avg => { family => 'stream', arg => 'count' },
2388 lag => { family => 'stream' },
2389 delta => { family => 'stream' },
2390 pct_change => { family => 'stream' },
2391 pct_of_total => { family => 'event' },
2392 rank => { family => 'event' },
2393 zscore => { family => 'event' },
2394 );
2395  
2396 # _cross_row_specs($self, \@columns, $params) -> \%plan | { error => $message } | undef
2397 #
2398 # Purpose: Read cs=/by=/order= and turn them into a plan the pass can run:
2399 # which function writes which column, partitioned by what, ordered by
2400 # what. Nothing is evaluated here, so a request that names a column
2401 # or a function that does not exist is refused before a single row is
2402 # touched, and the refusal is a 400 rather than a chart of something
2403 # else.
2404 # Entry: \@columns -- the columns of this view, so a cs=/by=/order= column is
2405 # checked against what the reader can actually see.
2406 # $params -- where the three parameters are read from, or undef for
2407 # this request. Anything with param()/every_param() will
2408 # do: the canvas reads them from the canvas page's own query
2409 # string, because its cards are drawn against the canvas's
2410 # state rather than against whatever URL fetched them.
2411 # Exit: undef when the request names no cross-row column. Otherwise
2412 # { specs => [ { col, fn, as, arg } ], by => [col ...],
2413 # order => [ { col, dir } ] }, or { error => $message } for a
2414 # request that cannot be honoured.
2415 # Notes: The streamstats family reads its rows in order, so order= is
2416 # required for it and refused as missing by name. The eventstats
2417 # family does not care and does not require it.
2418 60 ▶sub _cross_row_specs :Protected ($self, $columns, $params = undef) {
Subroutine _cross_row_specs: called CC=6 SCAR=18.5
2419 60 ▶ my $p = $params // $self;
Condition66%2/3
$params // $self
l!l&&r!l&&!r
24360
MC/DC0%0/2
$params // $self
$params $self
Truth table66%2/3
A // B
A= $paramsB= $self
ABresult
1X1
011
000
2420  
2421 # The three values are the URL's spelling of a plan, read once here so the
2422 # parser below serves a canvas card too - a card stores its own plan as
2423 # { cs, by, order } rather than as a query string.
2424 return $self->_cross_row_specs_from($columns, {
2425 60 ▶ cs => [ @{ $p->every_param('cs') // [] } ],
Condition75%3/4
$p->every_param("cs") // []
l!l
600
$p->param("by") // ""
l!l
159
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
2426 by => ($p->param('by') // ''),
2427 60 ▶ order => [ @{ $p->every_param('order') // [] } ],
Condition50%1/2
$p->every_param("order") // []
l!l
600
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
2428 });
2429 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2430  
2431 # _cross_row_specs_from($self, \@columns, \%raw) -> \%plan | { error } | undef
2432 #
2433 # Purpose: The same validation, from a plan as a saved canvas card stores it.
2434 # Entry: \%raw -- { cs => [spec ...], by => 'a,b', order => ['col:dir' ...] },
2435 # in the spelling cs=/by=/order= use.
2436 # Exit: As _cross_row_specs.
2437 77 ▶sub _cross_row_specs_from :Protected ($self, $columns, $raw) {
Subroutine _cross_row_specs_from: called CC=44 SCAR=38.8
2438 77 ▶ my @texts = grep { defined $_ && !ref $_ && length } @{ $raw->{cs} // [] };
Condition100%8/8
defined $_ && !ref($_) && length $_
!ll&&!rl&&r
2134
defined $_ and not ref $_
!ll&&!rl&&r
1135
$raw->{"cs"} // []
l!l
761
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
2439 77 ▶ return undef unless @texts;
Branch: 1 branch
BranchTrueFalseTotal
unless @texts 44 33 77
2440  
2441 33 ▶ my %col_set = map { $_ => 1 } @{ $columns // [] };
Condition50%1/2
$columns // []
l!l
330
MC/DC0%0/1
$columns // []
$columns
Truth table50%1/2
A
A= $columns
Aresult
11
00
2442 33 my %taken;
2443 my @specs;
2444  
2445 33 for my $text (@texts) {
2446 34 my ($col, $fn, $as, $arg) = split /:/, $text, 4;
2447 34 ▶ 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 15 19 34
Condition80%12/15
defined $col and length $col and defined $fn and length $fn and defined $as and length $as
!ll&&!rl&&r
15019
defined $col and length $col and defined $fn and length $fn and defined $as
!ll&&!rl&&r
12319
defined $col and length $col and defined $fn and length $fn
!ll&&!rl&&r
12022
defined $col and length $col and defined $fn
!ll&&!rl&&r
11122
defined $col and length $col
!ll&&!rl&&r
0133
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
2448 unless defined $col && length $col
2449 && defined $fn && length $fn
2450 && defined $as && length $as;
2451  
2452 return { error => $self->_i18n('error_cs_column', $text, $col) }
2453 19 ▶ unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 2 17 19
2454  
2455 return { error => $self->_i18n('error_cs_fn', $fn, join(' ', sort keys %CROSS_ROW_FNS)) }
2456 17 ▶ unless $CROSS_ROW_FNS{$fn};
Branch: 1 branch
BranchTrueFalseTotal
unless $CROSS_ROW_FNS{$fn} 1 16 17
2457  
2458 16 ▶ return { error => $self->_i18n('error_cs_alias', $as) }
Branch: 1 branch
BranchTrueFalseTotal
unless $as =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/u 1 15 16
2459 unless $as =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/;
2460  
2461 return { error => $self->_i18n(q{error_cs_conflict}, $as) }
2462 15 ▶ if $col_set{$as} || $taken{$as};
Branch: 1 branch
BranchTrueFalseTotal
if $col_set{$as} or $taken{$as} 2 13 15
Condition100%3/3
$col_set{$as} or $taken{$as}
l!l&&r!l&&!r
1113
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
2463 13 $taken{$as} = 1;
2464  
2465 13 my $decl = $CROSS_ROW_FNS{$fn};
2466 13 ▶ if ($decl->{arg}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($decl->{'arg'}) { } 3 10 13
elsif (defined $arg and length $arg) { } 1 18 19
2467 3 ▶ 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 3 0 3
Condition83%5/6
defined $arg and $arg =~ /\A\d+\z/u and $arg > 0
!ll&&!rl&&r
210
defined $arg and $arg =~ /\A\d+\z/u
!ll&&!rl&&r
111
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
2468 unless defined $arg && $arg =~ /\A\d+\z/ && $arg > 0;
2469 }
2470 ▶ elsif (defined $arg && length $arg) {
Condition66%2/3
defined $arg and length $arg
!ll&&!rl&&r
901
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
2471 1 return { error => $self->_i18n('error_cs_no_arg', $text, $fn) };
2472 }
2473  
2474 9 ▶ push @specs, {
Branch: 1 branch
BranchTrueFalseTotal
defined $arg && length $arg ? : 0 9 9
Condition33%1/3
defined $arg and length $arg
!ll&&!rl&&r
900
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
2475 col => $col,
2476 fn => $fn,
2477 as => $as,
2478 arg => (defined $arg && length $arg) ? $arg + 0 : undef,
2479 };
2480 }
2481  
2482 # by= is the partition. An empty value is its own partition rather than a
2483 # dropped row: a windowed column has to cover every displayed row, which is
2484 # not the rule the pivot uses for a cell -- see the POD.
2485 8 ▶ my $by_text = (!ref $raw->{by} && defined $raw->{by}) ? "$raw->{by}" : '';
Branch: 1 branch
BranchTrueFalseTotal
!ref($raw->{'by'}) && defined $raw->{'by'} ? : 5 3 8
Condition66%2/3
not ref $raw->{"by"} and defined $raw->{"by"}
!ll&&!rl&&r
035
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
2486 8 my @by = grep { length } map { _trim($_) } split /,/, $by_text, -1;
2487 8 for my $c (@by) {
2488 3 ▶ return { error => $self->_i18n('error_cs_by', $by_text, $c) } unless $col_set{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$c} 1 2 3
2489 }
2490  
2491 7 my @order;
2492 7 ▶ for my $text (@{ $raw->{order} // [] }) {
Condition100%2/2
$raw->{"order"} // []
l!l
61
MC/DC100%1/1
$raw->{"order"} // []
$raw->{"order"}
Truth table100%2/2
A
A= $raw->{"order"}
Aresult
11
00
2493 5 ▶ my $spec = _trim((!ref $text && defined $text) ? $text : '');
Branch: 1 branch
BranchTrueFalseTotal
!ref($text) && defined $text ? : 5 0 5
Condition33%1/3
not ref $text and defined $text
!ll&&!rl&&r
005
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
2494 5 ▶ next unless length $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 0 5 5
2495 5 my ($c, $dir) = split /:/, $spec, 2;
2496 5 ▶ $c = _trim($c // '');
Condition50%1/2
$c // ""
l!l
50
MC/DC0%0/1
$c // ""
$c
Truth table50%1/2
A
A= $c
Aresult
11
00
2497 5 ▶ $dir = defined $dir && length $dir ? lc _trim($dir) : 'asc';
Branch: 1 branch
BranchTrueFalseTotal
defined $dir && length $dir ? : 2 3 5
Condition66%2/3
defined $dir and length $dir
!ll&&!rl&&r
302
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
2498 5 ▶ return { error => $self->_i18n('error_cs_order', $spec) }
Branch: 1 branch
BranchTrueFalseTotal
unless length $c and $dir =~ /\A(?:asc|desc)\z/u 1 4 5
Condition66%2/3
length $c and $dir =~ /\A(?:asc|desc)\z/u
!ll&&!rl&&r
014
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
2499 unless length $c && $dir =~ /\A(?:asc|desc)\z/;
2500 return { error => $self->_i18n('error_cs_order_col', $spec, $c) }
2501 4 ▶ unless $col_set{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$c} 1 3 4
2502 3 push @order, { col => $c, dir => $dir };
2503 }
2504  
2505 5 for my $spec (@specs) {
2506 5 ▶ next unless $CROSS_ROW_FNS{ $spec->{fn} }{family} eq 'stream';
Branch: 1 branch
BranchTrueFalseTotal
unless $CROSS_ROW_FNS{$spec->{"fn"}}{"family"} eq "stream" 2 3 5
2507 return {
2508 error => $self->_i18n('error_cs_order_need',
2509 join(':', $spec->{col}, $spec->{fn}, $spec->{as}), $spec->{fn})
2510 3 ▶ } unless @order;
Branch: 1 branch
BranchTrueFalseTotal
unless @order 1 2 3
2511 }
2512  
2513 4 return { specs => \@specs, by => \@by, order => \@order };
2514 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2515  
2516 # _card_plan($raw) -> \%plan | { error }
2517 #
2518 # Purpose: The cross-row plan a saved canvas card carries, in the spelling
2519 # cs=/by=/order= use, so a card added and a card repaired store the
2520 # same shape and the one parser above reads them both.
2521 # Entry: $raw -- the request's cross_row value. A hash that names no cs is
2522 # the card saying it runs no plan of its own; _cross_row_specs_from
2523 # reads that as no pass at all, and so does the renderer.
2524 # Exit: { cs => [...], by => '', order => [...] } -- only the shape is
2525 # checked here. Which columns exist is a fact about the data file and
2526 # is checked again on every render, so a plan written today is read
2527 # against the columns the canvas has today.
2528 # Notes: A part of the plan that is the wrong kind is an error rather than a
2529 # silently empty list: a repair that stores nothing still answers 200,
2530 # and the caller would have no way to know the card had not changed.
2531 7 ▶sub _card_plan {
Subroutine _card_plan: called CC=11 SCAR=24.0
2532 7 my ($raw) = @_;
2533  
2534 7 for my $key (qw(cs order)) {
2535 11 ▶ next unless defined $raw->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw->{$key} 5 6 11
2536 return { error => "cross_row.$key must be a list" }
2537 6 ▶ if ref $raw->{$key} ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $raw->{$key} ne "ARRAY" 3 3 6
2538 return { error => "cross_row.$key must be a list of strings" }
2539 3 ▶ if grep { ref } @{ $raw->{$key} };
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_;} @{$$raw{$key};} 1 2 3
2540 }
2541 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
2542  
2543 return {
2544 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
2545 by => (defined $raw->{by} ? "$raw->{by}" : ''),
2546 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
2547 };
2548 }
2549  
2550 # _cross_row_ui_state($c) -> %stash_pairs
2551 #
2552 # Purpose: The cross-row state the table page shows: the specs it puts in
2553 # chips, the partition and order its chart panels carry, and the
2554 # panel's own menu. Also the rest of the query string, because the
2555 # panel edits three parameters and must submit the others unchanged.
2556 # Entry: $c -- the controller, for its query string only.
2557 # Exit: A list suitable for stash(): cross_row_specs, cross_row_by,
2558 # cross_row_order, cross_row_menu, cross_row_hidden.
2559 # Notes: cs=/by=/order= are deliberately absent from cross_row_hidden. The
2560 # panel writes them from its own controls, and a hidden by= as well
2561 # would send two values; param('by') reads the first, so the reader's
2562 # choice would be silently ignored in favour of the old one.
2563 # Only the query string is read -- never the body -- because this runs
2564 # before dispatch on every request, including JSON posts.
2565 2186 ▶sub _cross_row_ui_state {
Subroutine _cross_row_ui_state: called CC=9 SCAR=22.0
2566 2186 my ($c) = @_;
2567  
2568 2186 my $query = $c->req->query_params;
2569 2186 ▶ my @specs = grep { length } @{ $query->every_param('cs') // [] };
Condition50%1/2
$query->every_param("cs") // []
l!l
21860
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
2570 2186 ▶ my @orders = grep { length } @{ $query->every_param('order') // [] };
Condition50%1/2
$query->every_param("order") // []
l!l
21860
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
2571  
2572 2186 my @hidden;
2573 # names() is a list in some Mojo releases and an arrayref in others; taking
2574 # the arrayref is what both accept.
2575 2186 for my $name (@{ $query->names }) {
2576 17410 ▶ 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" 769 16641 17410
Condition100%6/6
$name eq "cs" or $name eq "by" or $name eq "order"
l!l&&r!l&&!r
51325616641
$name eq "cs" or $name eq "by"
l!l&&r!l&&!r
25725616897
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
2577 16780 push @hidden, map { { name => $name, value => $_ } }
2578 16641 ▶ @{ $query->every_param($name) // [] };
Condition50%1/2
$query->every_param($name) // []
l!l
166410
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
2579 }
2580  
2581 return (
2582 2186 ▶ cross_row_specs => \@specs,
Condition100%2/2
$query->param("by") // ""
l!l
2561930
MC/DC100%1/1
$query->param("by") // ""
$query->param("by")
Truth table100%2/2
A
A= $query->param("by")
Aresult
11
00
2583 cross_row_by => ($query->param('by') // ''),
2584 cross_row_order => \@orders,
2585 cross_row_menu => \@CROSS_ROW_MENU,
2586 cross_row_hidden => \@hidden,
2587 );
2588 }
2589  
2590 # _apply_cross_row($self, $records, \@columns, $plan) -> ($records, \@columns)
2591 #
2592 # Purpose: Stage 6 of the pipeline: run every cs= spec over the rows and write
2593 # the answer onto each row as a column of its own. Called from
2594 # _reduce_records (the routes that reduce there) and from _fetch_page
2595 # after its own filtering (the routes that paginate), always before
2596 # anything slices a page, so page 2 continues page 1's running total.
2597 # Entry: $records -- arrayref of hashrefs, already filtered.
2598 # \@columns -- the columns list, or undef where the caller has none in
2599 # scope; then it is derived from the first row.
2600 # $plan -- an already validated plan from _cross_row_specs($columns,
2601 # $params), or undef to read this request's cs=. A canvas
2602 # validates once and runs the plan once per card, on each
2603 # card's own rows; re-reading cs= there would work today only
2604 # because the canvas page carries it, and would silently stop
2605 # working for a card redrawn by an API call.
2606 # Exit: ($records, \@columns) with the produced columns appended, or the
2607 # arguments untouched when the request names no cs=. Croaks with an
2608 # i18n message when a spec cannot be honoured; the caller renders 400.
2609 # Notes: Rows are grouped into partitions by by=, each partition is sorted
2610 # once (stable, ties in arrival order, so two runs over the same file
2611 # agree), and each spec is then one pass over each partition. A
2612 # partition total is accumulated in that pass, never per row.
2613 #
2614 # The rows keep the order they arrived in: order= says which order the
2615 # window is read along, not which order the table is shown in. The
2616 # table has its own sort controls, and a reader may well want them to
2617 # disagree (a ledger sorted by amount, running totals following the
2618 # date), so the pass writes values in place rather than reordering.
2619 #
2620 # A cell that is not numeric yields undef in the produced column rather
2621 # than a placeholder: there is no previous row for the first row of a
2622 # partition, and a chart skips undef while the measure fold does too,
2623 # so an undef window cannot silently become a zero.
2624 19 ▶sub _apply_cross_row :Protected ($self, $records, $columns, $plan = undef) {
Subroutine _apply_cross_row: called CC=23 SCAR=31.7
2625 19 my $cols = $columns;
2626 19 ▶ unless (defined $cols) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cols) 1 18 19
2627 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
2628 }
2629  
2630 19 ▶ $plan //= $self->_cross_row_specs($cols);
Condition66%2/3
$plan //= $self->_cross_row_specs($cols)
l!l&&r!l&&!r
0181
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
2631 19 ▶ return ($records, $columns) unless $plan;
Branch: 1 branch
BranchTrueFalseTotal
unless $plan 1 18 19
2632 18 ▶ croak $plan->{error} if $plan->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $plan->{"error"} 15 3 18
2633  
2634 # Partitions, in first-appearance order so a report reads in file order.
2635 3 my (@part_keys, %parts);
2636 3 for my $i (0 .. $#$records) {
2637 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
2638 5 ▶ my $key = join("\x00", map { defined $row->{$_} ? "$row->{$_}" : '' } @{ $plan->{by} });
Branch: 1 branch
BranchTrueFalseTotal
defined $row->{$_} ? : 3 0 3
2639 5 ▶ push @part_keys, $key unless exists $parts{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $parts{$key} 4 1 5
2640 5 push @{ $parts{$key} }, $i;
2641 }
2642  
2643 # One sort per partition, whatever the number of specs. The index is the
2644 # tie-break, so the sort is stable even where the keys are equal.
2645 3 ▶ if (my @order = @{ $plan->{order} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@order) = @{$plan->{"order"};}) 1 2 3
2646 1 for my $key (@part_keys) {
2647 2 my $idx = $parts{$key};
2648 2 ▶ next unless @$idx > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @$idx > 1 1 1 2
2649 $parts{$key} = [ sort {
2650 1 my $cmp = 0;
2651 1 for my $o (@order) {
2652 1 $cmp = _cross_row_cmp($records->[$a]{ $o->{col} }, $records->[$b]{ $o->{col} });
2653 1 ▶ $cmp = -$cmp if $o->{dir} eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"dir"} eq "desc" 0 1 1
2654 1 ▶ last if $cmp;
Branch: 1 branch
BranchTrueFalseTotal
if $cmp 1 0 1
2655 }
2656 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
2657 } @$idx ];
2658 }
2659 }
2660  
2661 3 my @names;
2662 3 for my $spec (@{ $plan->{specs} }) {
2663 3 my ($fn, $as, $col) = @{$spec}{qw(fn as col)};
2664 3 for my $key (@part_keys) {
2665 4 my $idx = $parts{$key};
2666 4 my @vals = map { _numeric_cell($records->[$_]{$col}) } @$idx;
2667 4 my @out = _cross_row_values($fn, \@vals, $spec->{arg});
2668 4 for my $j (0 .. $#$idx) {
2669 5 my $i = $idx->[$j];
2670 5 $records->[$i] = _extend_row($records->[$i], $as, $out[$j]);
2671 }
2672 }
2673 3 push @names, $as;
2674 }
2675  
2676 3 my @extended = (@$cols, @names);
2677 3 ▶ $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->stash("_virtual_columns") 3 0 3
2678 3 $self->stash('_virtual_columns')->{$_} = 1 for @names;
2679 # The routes that paginate ask for their columns separately, after the page
2680 # is sliced, so the names are left where they can be picked up.
2681 3 $self->stash('_cross_row_columns' => \@names);
2682  
2683 3 return ($records, \@extended);
2684 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2685  
2686 # _cross_row_values($fn, \@values, $arg) -> @values
2687 #
2688 # The arithmetic of one spec over one partition: @values is the source column
2689 # of each row in order, numeric or undef, and the answer is aligned with it.
2690 # A plain function, so the pass has one place where the functions are defined
2691 # and the tests can drive them without a controller.
2692 24 ▶sub _cross_row_values {
Subroutine _cross_row_values: called CC=44 SCAR=37.8
2693 24 my ($fn, $vals, $arg) = @_;
2694 24 my @out;
2695 24 my $n = scalar @$vals;
2696 24 ▶ return @out unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 1 23 24
2697  
2698 23 ▶ if ($fn eq 'running_count') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "running_count") 1 22 23
2699 1 return map { $_ + 1 } 0 .. $n - 1;
2700 }
2701  
2702 22 ▶ if ($fn eq 'running_total') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "running_total") 4 18 22
2703 4 my $run = 0;
2704 4 for my $v (@$vals) {
2705 9 ▶ $run += $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 8 1 9
2706 9 ▶ push @out, defined $v ? $run : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 8 1 9
2707 }
2708 4 return @out;
2709 }
2710  
2711 18 ▶ if ($fn eq 'running_pct') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "running_pct") 2 16 18
2712 2 my $total = 0;
2713 2 $total += $_ for grep { defined } @$vals;
2714 2 my $run = 0;
2715 2 for my $v (@$vals) {
2716 4 ▶ $run += $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 4 0 4
2717 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
2718 }
2719 2 return @out;
2720 }
2721  
2722 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
2723 4 for my $i (0 .. $n - 1) {
2724 10 my $lo = $i - $arg + 1;
2725 10 ▶ $lo = 0 if $lo < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $lo < 0 5 5 10
2726 10 my @win = grep { defined } @{$vals}[$lo .. $i];
2727 10 ▶ unless (@win) { push @out, undef; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (@win) 2 8 10
2728 8 my $sum = 0;
2729 8 $sum += $_ for @win;
2730 8 ▶ push @out, $fn eq 'window_sum' ? $sum : $sum / scalar @win;
Branch: 1 branch
BranchTrueFalseTotal
$fn eq 'window_sum' ? : 5 3 8
2731 }
2732 4 return @out;
2733 }
2734  
2735 12 ▶ if ($fn eq 'lag') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "lag") 1 11 12
2736 1 my $prev;
2737 1 for my $v (@$vals) {
2738 3 push @out, $prev;
2739 3 $prev = $v;
2740 }
2741 1 return @out;
2742 }
2743  
2744 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
2745 2 my $prev;
2746 2 for my $v (@$vals) {
2747 8 my $d;
2748 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
2749 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
2750 }
2751 8 push @out, $d;
2752 8 $prev = $v;
2753 }
2754 2 return @out;
2755 }
2756  
2757 9 my @nums = grep { defined } @$vals;
2758  
2759 9 ▶ if ($fn eq 'pct_of_total') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "pct_of_total") 2 7 9
2760 2 my $total = 0;
2761 2 $total += $_ for @nums;
2762 2 for my $v (@$vals) {
2763 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
2764 }
2765 2 return @out;
2766 }
2767  
2768 7 ▶ if ($fn eq 'rank') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "rank") 3 4 7
2769 # SQL RANK(): ties share a rank and the next rank skips, which counting
2770 # the values strictly greater gives for free.
2771 3 for my $v (@$vals) {
2772 7 ▶ push @out, defined $v ? 1 + scalar(grep { $_ > $v } @nums) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 6 1 7
2773 }
2774 3 return @out;
2775 }
2776  
2777 4 ▶ if ($fn eq 'zscore') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "zscore") 3 1 4
2778 3 my ($mean, $sd);
2779 3 ▶ if (@nums >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@nums >= 2) 2 1 3
2780 2 $mean = 0;
2781 2 $mean += $_ for @nums;
2782 2 $mean /= scalar @nums;
2783 2 $sd = _stdev_of(\@nums);
2784 }
2785 3 for my $v (@$vals) {
2786 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
2787 }
2788 3 return @out;
2789 }
2790  
2791 1 croak "Unknown cross-row function '$fn'"; # unreachable: validated above
2792 }
2793  
2794 # _cross_row_cmp($x, $y) -> -1 | 0 | 1
2795 #
2796 # The order= comparator: numeric when both cells are numbers, case-sensitive
2797 # string otherwise. Numbers sort as numbers because an order= on an amount is
2798 # meant to put 100 after 20, and a mixed column still has to be total.
2799 8 ▶sub _cross_row_cmp {
Subroutine _cross_row_cmp: called CC=5 SCAR=16.1
2800 8 my ($x, $y) = @_;
2801 8 my ($nx, $ny) = (_numeric_cell($x), _numeric_cell($y));
2802 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
2803 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
2804 }
2805  
2806 # _trim($text) -> $text
2807 20 ▶sub _trim {
Subroutine _trim: called CC=2 SCAR=6.9
2808 20 ▶ my $s = defined $_[0] ? $_[0] : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 19 1 20
2809 20 $s =~ s/\A\s+//;
2810 20 $s =~ s/\s+\z//;
2811 20 return $s;
2812 }
2813  
2814 # _reduce_records($self, $records, $columns, $opts) -> ($records, $columns)
2815 #
2816 # Purpose: The reduce half of every data pipeline, in one place: the request's
2817 # filters -- the reader's own f= params, then the two bounds of the
2818 # relative time range -- run over $records in order, with the columns
2819 # list threaded through so a later stage can add columns and hand back
2820 # the extended list. Every route that reads rows and then filters
2821 # them calls this rather than writing the loop out again, so a stage
2822 # added here reaches all of them at once.
2823 # Entry: $records -- arrayref of hashrefs, after the calculated-field pass.
2824 # $columns -- arrayref of column names, or undef where the caller has
2825 # no list in scope; a stage that adds columns needs one,
2826 # so undef is only for the filters-only callers.
2827 # $opts -- optional hashref. chips_only => 1 says the caller's rows
2828 # have already been reduced and it is here only for the
2829 # chip list _apply_filters returns: the stage is skipped
2830 # and both arguments come back as they arrived.
2831 # no_cross_row => 1 runs the filters only, for a caller
2832 # that wants the rows without stage 6 (_apply_filters,
2833 # whose callers are after the chip list).
2834 # Exit: ($records, $columns), reduced -- or untouched, when chips_only is
2835 # set. A malformed f= spec leaves the records alone rather than
2836 # croaking, as _apply_filter_spec always has.
2837 # Notes: This is stage 5 of the stage order in BI-Phase-7.md section 3, and
2838 # it is where that document's stages 6 and 7 are meant to land: the
2839 # cross-row pass and the second calculated-field pass. Both belong
2840 # here rather than at a call site, because they have to see *filtered*
2841 # rows and have to run before pagination (an exported or second page
2842 # then carries the same numbers as the first).
2843 #
2844 # Three kinds of row-reading route deliberately do not reduce here,
2845 # and each is a different case: the canvas builds its own per-card
2846 # pipeline and runs stage 6 per card, after that card's filters
2847 # (_canvas_render_context, _render_visual_html), /view's table action
2848 # filters inside _fetch_page before it paginates, and /api/ask samples
2849 # rows without filtering them at all.
2850 #
2851 # chips_only exists for the routes that filter somewhere else and then
2852 # call _apply_filters for its chip list: /view, the three /open
2853 # branches and /join reduce inside _fetch_page, before they paginate,
2854 # and /combine reduces through this function before slicing its page.
2855 # Re-running the stage on that page would still give the right answer
2856 # today, because every stage in it is idempotent -- filtering a
2857 # filtered set changes nothing. It stops being harmless as soon as a
2858 # stage is not: a cross-row pass (running totals, differences) or a
2859 # time-fill that adds rows would double-apply to a page that has
2860 # already been through it, and would do so only on non-first pages.
2861 # So the option is not a micro-optimisation; it is what keeps those
2862 # six call sites correct once such a stage lands here.
2863 #
2864 # A plain function rather than a method, like _filter_specs and
2865 # _apply_filter_spec beside it: the tests drive the reduce stage with a
2866 # controller-shaped mock (build_controller), and only every_param and
2867 # stash are ever wanted of $self.
2868 843 ▶sub _reduce_records {
Subroutine _reduce_records: called CC=15 SCAR=28.0
2869 843 my ($self, $records, $columns, $opts) = @_;
2870  
2871 # Already reduced: hand the rows and the columns back exactly as they came,
2872 # ahead of the first stage, so a stage that is not idempotent cannot see
2873 # these rows a second time.
2874 843 ▶ return ($records, $columns) if $opts && $opts->{chips_only};
Branch: 1 branch
BranchTrueFalseTotal
if $opts and $opts->{"chips_only"} 204 639 843
Condition100%3/3
$opts and $opts->{"chips_only"}
!ll&&!rl&&r
6318204
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
2875  
2876 # A filter on a column stage 6 or 7 will write has to wait for it: f=ytd:gt:50
2877 # selects rows by their running total, and must not change those totals. So
2878 # every filter that can run first does, and the rest run last.
2879 639 ▶ 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
861912
$opts && $opts->{'no_cross_row'}
!ll&&!rl&&r
63108
$self->param("cs") // ""
l!l
13618
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
2880 639 ▶ my %written = $crossing ? map { $_ => 1 } _cross_row_written($self) : ();
Branch: 1 branch
BranchTrueFalseTotal
$crossing ? : 12 627 639
2881 639 ▶ if (defined(my $why = _unknown_filter_column($self, $columns, \%written))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $why = _unknown_filter_column($self, $columns, \%written))) 0 639 639
2882 0 croak $why;
2883 }
2884 639 my @late;
2885 639 for my $s (@{ _filter_specs($self) }) {
2886 36 ▶ if ($written{ (split /:/, $s, 2)[0] // '' }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($written{(split(/:/u, $s, 2))[0] // ""}) 0 36 36
Condition50%1/2
(split(/:/u, $s, 2))[0] // ""
l!l
360
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
2887 0 push @late, $s;
2888 0 next;
2889 }
2890 36 $records = _apply_filter_spec($records, $s);
2891 }
2892  
2893 # d=1 removes duplicate rows after the filters and before the cross-row
2894 # pass, the order _fetch_page uses for the table view, so a chart of a
2895 # de-duplicated view counts the rows the table shows. Only callers with a
2896 # columns list run the whole stage; the filters-only entry point does not.
2897 639 ▶ $records = _dedup_records($records, $columns)
Branch: 1 branch
BranchTrueFalseTotal
if $columns and _dedup_requested($self) 3 636 639
Condition100%3/3
$columns and _dedup_requested($self)
!ll&&!rl&&r
96273
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
2898 if $columns && _dedup_requested($self);
2899  
2900 # Stage 6: the cross-row pass, and only when the request asks for one. It
2901 # has to see filtered rows -- a window is over what the filters left -- and it
2902 # has to run before anything paginates, which is why the routes that slice
2903 # their own page call it again (once) inside _fetch_page.
2904 639 ▶ if ($crossing) {
Branch: 1 branch
BranchTrueFalseTotal
if ($crossing) 12 627 639
2905 12 ($records, $columns) = $self->_apply_cross_row($records, $columns);
2906 # Stage 7: the calculated fields stage 4 held back for these columns.
2907 0 ($records, $columns) = $self->_apply_held_calc_fields($records, $columns);
2908 0 $records = _apply_filter_spec($records, $_) for @late;
2909 }
2910  
2911 627 return ($records, $columns);
2912 }
2913  
2914 # _reduce_or_render($self, \$records, \$columns) -> $ok
2915 #
2916 # Purpose: Run _reduce_records and turn a cross-row spec that cannot be
2917 # honoured into the 400 it deserves, in the one shape every route
2918 # already uses for a calculated field that will not compile.
2919 # Entry: References to the route's own lexicals: on success they are updated
2920 # in place, so a call site is one line.
2921 # Exit: True when the records are ready. False after rendering a 400 -- the
2922 # caller returns straight away, because nothing has been produced.
2923 # Notes: A method, unlike _reduce_records itself, because the failure needs
2924 # a controller to render through. The error text is the i18n message
2925 # the pass croaked with, with the "at File line N" tail removed so a
2926 # reader sees the fault rather than the interpreter's location.
2927 626 ▶sub _reduce_or_render :Protected ($self, $recs_ref, $cols_ref) {
Subroutine _reduce_or_render: called CC=2 SCAR=6.9
2928 626 my @reduced = eval { _reduce_records($self, $$recs_ref, $$cols_ref) };
2929 626 ▶ if (@reduced) {
Branch: 1 branch
BranchTrueFalseTotal
if (@reduced) 614 12 626
2930 614 ($$recs_ref, $$cols_ref) = @reduced;
2931 614 return 1;
2932 }
2933  
2934 12 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
2935 12 $self->render(text => $e, status => 400);
2936 # Recorded because the callers that answer a missing table with a 404 get
2937 # their rows back empty here, and the 400 has already been rendered.
2938 12 $self->stash('_reduce_error' => 1);
2939 12 return 0;
2940 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2941  
2942 # _apply_filters($self, $records, $opts) -> ($filtered_records, \@raw_specs, $json_string)
2943 #
2944 # Purpose: Read all "f=" query params, apply them in order via _apply_filter_spec,
2945 # and return: the filtered arrayref, the raw spec strings (for building
2946 # export URLs), and a script-safe JSON string for pre-populating the UI.
2947 # Entry: $records is an arrayref of hashrefs. $opts is passed straight to
2948 # _reduce_records: chips_only => 1 for the routes whose rows are
2949 # already reduced and which are here only for the chips.
2950 # Exit: Three-element list; never croaks. $json_string has '</' escaped to
2951 # '<\/' so it is safe to embed directly in a <script> block.
2952 #
2953 # Reduction: the original code had two sequential loops over @specs -- one to
2954 # apply filters, one to parse them for JSON. By Modus Ponens, _apply_filter_spec
2955 # returns $records unchanged for a malformed spec (same guard condition), so
2956 # skipping the call for malformed specs is equivalent. Merging into one loop
2957 # eliminates a full O(n) pass and the redundant split() on every spec.
2958 211 ▶sub _apply_filters :Protected ($self, $records, $opts = undef) {
Subroutine _apply_filters: called CC=10 SCAR=23.1
2959 211 ▶ my @specs = @{ $self->every_param('f') // [] };
Condition50%1/2
$self->every_param("f") // []
l!l
2110
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
2960 211 my @parsed;
2961 211 for my $s (@specs) {
2962 22 my ($col, $op, $val) = split /:/, $s, 3;
2963 22 ▶ next unless length($col // '') && defined $op && length $op;
Branch: 1 branch
BranchTrueFalseTotal
unless length($col // "") and defined $op and length $op 4 18 22
Condition87%7/8
length($col // "") and defined $op and length $op
!ll&&!rl&&r
4018
length($col // "") and defined $op
!ll&&!rl&&r
1318
$col // ""
l!l
211
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
2964 18 ▶ push @parsed, { col => $col, op => $op, val => $val // '' };
Condition50%1/2
$val // ""
l!l
180
MC/DC0%0/1
$val // ""
$val
Truth table50%1/2
A
A= $val
Aresult
11
00
2965 }
2966  
2967 # The range joins the request's own filters here, but it is not one of them:
2968 # @specs -- which the page shows as chips, keeps in its panel forms and
2969 # offers to its filter UI -- stays the reader's own list, so a relative range
2970 # cannot be submitted as a frozen pair of dates and a reopened link cannot
2971 # narrow twice. The application itself is _reduce_records, so this entry
2972 # point and the routes that call it directly cannot drift apart; the columns
2973 # list is not in scope here and every caller holds its own, so none is
2974 # threaded through. $opts travels with the records for the same reason:
2975 # a caller that has already reduced asks for the chips alone here, and the
2976 # seam, not this wrapper, is where that is decided.
2977 # no_cross_row: this entry point is the chip list, and its callers either
2978 # skip the stage entirely (chips_only) or want the rows without stage 6.
2979 211 ▶ ($records) = _reduce_records($self, $records, undef, { %{ $opts // {} }, no_cross_row => 1 });
Condition100%2/2
$opts // {}
l!l
2038
MC/DC100%1/1
$opts // {}
$opts
Truth table100%2/2
A
A= $opts
Aresult
11
00
2980  
2981 211 my $json = encode_json(\@parsed);
2982 211 $json =~ s{</}{<\\/}g;
2983 211 return ($records, \@specs, $json);
2984 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2985  
2986 # _filter_specs($self) -> \@specs
2987 #
2988 # Purpose: Every filter that applies to this request: the f= params the reader
2989 # wrote, followed by the two bounds of the relative time range the
2990 # request names, if any. This is the list the data pipelines fold over
2991 # -- charts, pivots, stats, insights and the exports as well as the
2992 # table view -- so a range narrows all of them through one call site
2993 # each, and a route that never heard of ranges still honours one.
2994 # Entry: $self -- the controller; it needs only every_param() and stash().
2995 # Exit: Returns an arrayref of "col:op:val" strings; possibly empty.
2996 1276 ▶sub _filter_specs {
Subroutine _filter_specs: called CC=3 SCAR=11.0
2997 1276 my ($self) = @_;
2998 return [
2999 1276 ▶ @{ $self->every_param('f') // [] },
Condition50%1/2
$self->every_param("f") // []
l!l
12760
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
3000 1276 ▶ @{ $self->stash('range_specs') // [] },
Condition100%2/2
$self->stash("range_specs") // []
l!l
126214
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
3001 ];
3002 }
3003  
3004 # _dedup_requested($self) -> $bool
3005 #
3006 # Purpose: True when the request asks for duplicate rows to be removed (d=1).
3007 # The SQL aggregate push paths check it too, because the backend
3008 # would count the duplicates the Perl fold has already dropped.
3009 1100 ▶sub _dedup_requested {
Subroutine _dedup_requested: called CC=2 SCAR=6.9
3010 1100 my ($self) = @_;
3011 1100 ▶ return $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 4 1096 1100
3012 }
3013  
3014 # _dedup_records(\@records, \@columns) -> \@unique_records
3015 #
3016 # Purpose: Remove duplicate rows from $records. Two rows are duplicates when
3017 # every column value is identical (string comparison, undef treated as '').
3018 # Preserves the order of first occurrence.
3019 # Entry: $records is an arrayref of hashrefs; $columns is an arrayref of names.
3020 # Exit: Returns a new arrayref; the input is not modified.
3021 10 ▶sub _dedup_records {
Subroutine _dedup_records: called CC=4 SCAR=13.9
3022 10 my ($records, $columns) = @_;
3023 10 my (%seen, @out);
3024 10 for my $row (@$records) {
3025 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
3026 34 ▶ push @out, $row unless $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$key}++ 20 14 34
3027 }
3028 10 return \@out;
3029 }
3030  
3031 # _filter_specs_to_criteria( \@specs, $source ) -> ( \%criteria, \@residual_specs )
3032 #
3033 # Purpose: Map the f= filter vocabulary onto Database::Abstraction / Database::Join
3034 # criteria hashrefs so the backend can apply pushable filters before
3035 # paginating. Specs that cannot be safely pushed are returned as
3036 # @residual_specs for subsequent in-memory application.
3037 #
3038 # Pushdown is only performed when $source->dbi_source() confirms a SQL (SQLite)
3039 # backend. For CSV (slurp path), in-memory, XLSX, BerkeleyDB and URL sources
3040 # everything is placed in @residual_specs so the existing _apply_filter_spec
3041 # Perl path handles them.
3042 #
3043 # Pushable mapping (SQLite only):
3044 # eq / ne -- LIKE / NOT LIKE without wildcards. SQLite LIKE is
3045 # case-insensitive for ASCII, matching the existing Perl
3046 # lc() semantics. Values containing % or _ are pushed to
3047 # residual to avoid LIKE metacharacter conflicts.
3048 # contains -- LIKE '%val%'. Residual when value contains % or _.
3049 # starts -- LIKE 'val%'. Residual when value contains % or _.
3050 # lt / le / gt / ge -- SQL numeric comparison. Residual when the value is
3051 # not a plain number (avoids column-affinity surprises
3052 # with currency or comma-formatted values).
3053 # in -- Always residual (a list of values, matched as eq is).
3054 # empty / notempty -- Always residual. Must match both SQL NULL and the
3055 # literal empty string; cannot be expressed as a single
3056 # D::A criterion without an -or grouping.
3057 #
3058 # Column collision: if a column already has a pushable criterion, the second
3059 # spec for that column is placed in @residual_specs. This keeps the AND logic
3060 # simple and safe; callers with multiple conditions on one column (e.g. a range)
3061 # still get correct results via the in-memory fallback.
3062 35 ▶sub _filter_specs_to_criteria {
Subroutine _filter_specs_to_criteria: called CC=28 SCAR=33.3
3063 35 my ($specs, $source) = @_;
3064  
3065 # Only push when the source has a live SQL (SQLite) backend.
3066 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
3067 && $source->can('dbi_source')
3068 && $source->dbi_source();
3069 35 ▶ return ({}, [@$specs]) unless $is_sql;
Branch: 1 branch
BranchTrueFalseTotal
unless $is_sql 12 23 35
3070  
3071 23 require Scalar::Util;
3072 23 my (%criteria, @residual);
3073  
3074 23 for my $spec (@$specs) {
3075 27 my ($col, $op, $val) = split /:/, $spec, 3;
3076 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
3077 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
3078  
3079 # A second spec on the same column goes to residual.
3080 23 ▶ if (exists $criteria{$col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $criteria{$col}) 1 22 23
3081 1 push @residual, $spec;
3082 1 next;
3083 }
3084  
3085 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
3086 # A date compares by the day in Perl (a timestamp cell is on the
3087 # day it names); LIKE would want the cell to be the date exactly.
3088 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
3089 3 push @residual, $spec;
3090 } else {
3091 2 ▶ $criteria{$col} = ($op eq 'eq')
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'eq' ? : 1 1 2
3092 ? { -like => $val }
3093 : { -not_like => $val };
3094 }
3095 } elsif ($op eq 'contains') {
3096 2 ▶ if ($val =~ /[%_]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val =~ /[%_]/u) { } 1 1 2
3097 1 push @residual, $spec;
3098 } else {
3099 1 $criteria{$col} = { -like => "%${val}%" };
3100 }
3101 } elsif ($op eq 'starts') {
3102 2 ▶ if ($val =~ /[%_]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val =~ /[%_]/u) { } 1 1 2
3103 1 push @residual, $spec;
3104 } else {
3105 1 $criteria{$col} = { -like => "${val}%" };
3106 }
3107 } elsif ($op eq 'lt') {
3108 Scalar::Util::looks_like_number($val)
3109 2 ▶ ? ($criteria{$col} = { '<' => $val })
Branch: 1 branch
BranchTrueFalseTotal
&Scalar::Util::looks_like_number($val) ? : 1 1 2
3110 : push @residual, $spec;
3111 } elsif ($op eq 'le') {
3112 Scalar::Util::looks_like_number($val)
3113 2 ▶ ? ($criteria{$col} = { '<=' => $val })
Branch: 1 branch
BranchTrueFalseTotal
&Scalar::Util::looks_like_number($val) ? : 1 1 2
3114 : push @residual, $spec;
3115 } elsif ($op eq 'gt') {
3116 Scalar::Util::looks_like_number($val)
3117 3 ▶ ? ($criteria{$col} = { '>' => $val })
Branch: 1 branch
BranchTrueFalseTotal
&Scalar::Util::looks_like_number($val) ? : 2 1 3
3118 : push @residual, $spec;
3119 } elsif ($op eq 'ge') {
3120 Scalar::Util::looks_like_number($val)
3121 2 ▶ ? ($criteria{$col} = { '>=' => $val })
Branch: 1 branch
BranchTrueFalseTotal
&Scalar::Util::looks_like_number($val) ? : 1 1 2
3122 : push @residual, $spec;
3123 } else {
3124 # empty, notempty, between, unknown operator: always residual.
3125 4 push @residual, $spec;
3126 }
3127 }
3128  
3129 23 return (\%criteria, \@residual);
3130 }
3131  
3132 # _measure($fn, $col, $as) -> \%measure
3133 #
3134 # Build one measure descriptor in the vocabulary shared by Database::Abstraction
3135 # and Database::Join (sum|avg|min|max|count|count_distinct). $col is the
3136 # source column name, or undef for COUNT(*). $as is the result-row key.
3137 # The returned hashref is consumed directly by aggregate(measures => [...]).
3138 588 ▶sub _measure {
Subroutine _measure: called CC=2 SCAR=6.9
3139 588 my ($fn, $col, $as) = @_;
3140 588 ▶ return { fn => $fn, (defined $col ? (col => $col) : ()), as => $as };
Branch: 1 branch
BranchTrueFalseTotal
defined $col ? : 240 348 588
3141 }
3142  
3143 # _numeric_cell($v) -> $number | undef
3144 #
3145 # Extract a numeric value from a raw cell, handling currency prefixes
3146 # (e.g. $1,234.56) and accounting-notation negatives ((1,234.56) -> -1234.56).
3147 # Returns undef for empty, undef, or non-numeric input.
3148 # Used by the Perl fold path of _grouped_totals so all four chart routes
3149 # share one extraction function.
3150 3070 ▶sub _numeric_cell {
Subroutine _numeric_cell: called CC=1 SCAR=0.0
3151 3070 return Database::BI::Util::parse_number($_[0]);
3152 }
3153  
3154 # _percentile_of(\@sorted, $level) -> $number | undef
3155 #
3156 # The value at the given percentile of an already sorted list of numbers, by
3157 # linear interpolation between closest ranks (R's type 7, Excel's
3158 # PERCENTILE.INC). $level is 1..100. The empty list has no percentile, so it
3159 # returns undef rather than a made-up 0.
3160 #
3161 # At level 50 this is the median the column-stats view has always shown: the
3162 # middle value when the count is odd, the mean of the two middle values when it
3163 # is even. That is the point of it, and the reason median is defined in terms
3164 # of it below -- one arithmetic, so a p50 measure, a median measure and the
3165 # median column of the stats page cannot disagree.
3166 191 ▶sub _percentile_of {
Subroutine _percentile_of: called CC=4 SCAR=13.9
3167 191 my ($sorted, $level) = @_;
3168 191 my $n = scalar @$sorted;
3169 191 ▶ return undef unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 1 190 191
3170 190 my $h = ($n - 1) * $level / 100;
3171 190 my $lo = int $h;
3172 190 ▶ return $sorted->[$lo] if $h == $lo || $lo >= $n - 1;
Branch: 1 branch
BranchTrueFalseTotal
if $h == $lo or $lo >= $n - 1 11 179 190
Condition66%2/3
$h == $lo or $lo >= $n - 1
l!l&&r!l&&!r
110179
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
3173 179 return $sorted->[$lo] + ($h - $lo) * ($sorted->[ $lo + 1 ] - $sorted->[$lo]);
3174 }
3175  
3176 # _median_of(\@sorted) -> $number | undef
3177 89 ▶sub _median_of {
Subroutine _median_of: called CC=1 SCAR=0.0
3178 89 return _percentile_of($_[0], 50);
3179 }
3180  
3181 # _stdev_of(\@nums) -> $number | undef
3182 #
3183 # Sample standard deviation, the n-1 denominator: what Splunk's stdev() and
3184 # Excel's STDEV.S report. One value has no spread to measure, so fewer than
3185 # two values give undef rather than a reassuring 0.
3186 88 ▶sub _stdev_of {
Subroutine _stdev_of: called CC=4 SCAR=13.9
3187 88 my $nums = shift;
3188 88 my $n = scalar @$nums;
3189 88 ▶ return undef unless $n >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless $n >= 2 2 86 88
3190 86 my $mean = 0;
3191 86 $mean += $_ for @$nums;
3192 86 $mean /= $n;
3193 86 my $sum_sq = 0;
3194 86 $sum_sq += ($_ - $mean) ** 2 for @$nums;
3195 86 return sqrt($sum_sq / ($n - 1));
3196 }
3197  
3198 # _range_of(\@sorted) -> $number | undef
3199 #
3200 # Largest minus smallest, on the already sorted list: the spread a reader means
3201 # by "range", which is not min/max in the sense the SQL backend could push.
3202 85 ▶sub _range_of {
Subroutine _range_of: called CC=2 SCAR=6.9
3203 85 my $sorted = shift;
3204 85 ▶ return undef unless @$sorted;
Branch: 1 branch
BranchTrueFalseTotal
unless @$sorted 1 84 85
3205 84 return $sorted->[-1] - $sorted->[0];
3206 }
3207  
3208 # _measure_value($fn, \@sorted_values) -> $number | undef
3209 #
3210 # The function from @PERL_MEASURE_FNS (or a percentile) applied to the sorted
3211 # values of one group. It takes the values rather than a group key so that the
3212 # caller decides what a group is: the pivot's fold has one list per group, and
3213 # the stats page measures a whole column with the same four functions.
3214 6 ▶sub _measure_value {
Subroutine _measure_value: called CC=5 SCAR=16.1
3215 6 my ($fn, $sorted) = @_;
3216 6 my $level = _measure_percentile($fn);
3217 6 ▶ return _percentile_of($sorted, $level) if defined $level;
Branch: 1 branch
BranchTrueFalseTotal
if defined $level 1 5 6
3218 5 ▶ return _median_of($sorted) if $fn eq 'median';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "median" 1 4 5
3219 4 ▶ return _stdev_of($sorted) if $fn eq 'stdev';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "stdev" 1 3 4
3220 3 ▶ return _range_of($sorted) if $fn eq 'range';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "range" 1 2 3
3221 2 return undef;
3222 }
3223  
3224 # _column_is_numeric($records, $col) -> bool
3225 #
3226 # Says whether a column can be used as a chart measure. It samples the first
3227 # non-empty cells rather than the whole table: the canvas needs a quick answer
3228 # for the column picker, and a column with a non-numeric value in its first 20
3229 # rows is not a safe measure anyway.
3230 108 ▶sub _column_is_numeric {
Subroutine _column_is_numeric: called CC=8 SCAR=20.8
3231 108 my ($records, $col) = @_;
3232 108 my $seen = 0;
3233 108 ▶ for my $row (@{ $records // [] }) {
Condition100%2/2
$records // []
l!l
1071
MC/DC100%1/1
$records // []
$records
Truth table100%2/2
A
A= $records
Aresult
11
00
3234 296 my $v = $row->{$col};
3235 296 ▶ next unless defined $v && length $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and length $v 5 291 296
Condition100%3/3
defined $v and length $v
!ll&&!rl&&r
32291
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
3236 291 ▶ return 0 unless defined _numeric_cell($v);
Branch: 1 branch
BranchTrueFalseTotal
unless defined _numeric_cell($v) 68 223 291
3237 223 ▶ last if ++$seen >= 20;
Branch: 1 branch
BranchTrueFalseTotal
if ++$seen >= 20 1 222 223
3238 }
3239 40 ▶ return $seen ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$seen ? : 37 3 40
3240 }
3241  
3242 # _measure_pushable($source, $fn, $col, \@records) -> bool
3243 #
3244 # Returns true when the measure can be computed by aggregate() on $source and
3245 # the result will be identical to the Perl fold. False means use the Perl fold.
3246 #
3247 # Decision table:
3248 # Not in the pushed vocabulary -- never pushable. None of median, a
3249 # percentile, stdev, first, last or range is a sum
3250 # of its parts, and the backend would either refuse
3251 # the spec or quietly answer with its own idea of
3252 # the statistic (it has one for median and stddev).
3253 # count / count_distinct -- always pushable (no numeric coercion).
3254 # sum / avg / min / max -- only when every sampled value in $col is either
3255 # a plain number (looks_like_number) or empty/undef.
3256 # Currency symbols or accounting parentheses in any
3257 # value force the Perl fold, which strips them
3258 # correctly; SQLite CAST would coerce them to 0.
3259 # Missing $source -- never pushable.
3260 # Missing $col -- sum/avg/min/max are not pushable without a column.
3261 464 ▶sub _measure_pushable {
Subroutine _measure_pushable: called CC=13 SCAR=25.9
3262 464 my ($source, $fn, $col, $records) = @_;
3263 464 ▶ return 0 unless $source && $source->can('aggregate');
Branch: 1 branch
BranchTrueFalseTotal
unless $source and $source->can("aggregate") 1 463 464
Condition66%2/3
$source and $source->can("aggregate")
!ll&&!rl&&r
01463
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
3264 463 ▶ return 0 unless defined $fn && $PUSHED_MEASURE_FN_OK{$fn};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fn and $PUSHED_MEASURE_FN_OK{$fn} 6 457 463
Condition66%2/3
defined $fn and $PUSHED_MEASURE_FN_OK{$fn}
!ll&&!rl&&r
06457
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
3265 457 ▶ return 1 if $fn eq 'count' || $fn eq 'count_distinct';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "count" or $fn eq "count_distinct" 348 109 457
Condition100%3/3
$fn eq "count" or $fn eq "count_distinct"
l!l&&r!l&&!r
3471109
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
3266 109 ▶ return 0 unless defined $col;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col 0 109 109
3267 # For sum/avg/min/max, only push when at least one value is a plain number
3268 # and every non-null/non-blank value passes looks_like_number.
3269 #
3270 # Two cases where both paths must agree:
3271 # - All values undef/blank: Perl fold produces no rows; SQL SUM(NULL)
3272 # produces NULL, normalised to 0 by D::A -> discrepancy. Return 0 so
3273 # the Perl fold runs and yields the expected "No plottable data" result.
3274 # - Currency/accounting notation (e.g. ($1,234)): _numeric_cell strips
3275 # these correctly; SQL sees non-numeric text -> SUM = NULL -> 0. Return 0
3276 # so _numeric_cell is used on every value.
3277 109 require Scalar::Util;
3278 109 my $found = 0;
3279 109 ▶ for my $row (@{ $records // [] }) {
Condition50%1/2
$records // []
l!l
1090
MC/DC0%0/1
$records // []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
3280 587 my $v = $row->{$col};
3281 587 ▶ next unless defined $v && length($v); # undef/blank: same effect as NULL
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and length $v 2 585 587
Condition66%2/3
defined $v and length $v
!ll&&!rl&&r
20585
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
3282 585 ▶ return 0 unless Scalar::Util::looks_like_number($v);
Branch: 1 branch
BranchTrueFalseTotal
unless &Scalar::Util::looks_like_number($v) 7 578 585
3283 578 $found = 1;
3284 }
3285 102 return $found; # 0 (false) when every sampled value was undef or blank
3286 }
3287  
3288 # _parse_measure_param($spec_str) -> \%measure | undef
3289 #
3290 # Parse 'col:fn:as' into { col => ..., fn => ..., as => ... }.
3291 # Shared dialect for /pivot so it does not invent a second format.
3292 # $fn is lower-cased first, so SUM and P90 are the same measures as sum and
3293 # p90. Returns undef for an invalid or unrecognised spec.
3294 22 ▶sub _parse_measure_param {
Subroutine _parse_measure_param: called CC=8 SCAR=21.4
3295 22 my $str = shift;
3296 22 ▶ return undef unless defined $str && length($str);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str and length $str 0 22 22
Condition33%1/3
defined $str and length $str
!ll&&!rl&&r
0022
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
3297 22 my ($col, $fn, $as) = split /:/, $str, 3;
3298 22 ▶ 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 2 20 22
Condition77%7/9
defined $fn and defined $as and length $fn and length $as
!ll&&!rl&&r
2020
defined $fn and defined $as and length $fn
!ll&&!rl&&r
1120
defined $fn and defined $as
!ll&&!rl&&r
0121
MC/DC50%2/4
defined $fn and defined $as and length $fn and length $as
defined $fn defined $as length $fn length $as
Truth table60%3/5
A and B and C and D
A= defined $fnB= defined $asC= length $fnD= length $as
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3299 20 $fn = lc $fn;
3300 20 ▶ return undef unless _measure_fn_ok($fn);
Branch: 1 branch
BranchTrueFalseTotal
unless _measure_fn_ok($fn) 5 15 20
3301 15 return { col => $col, fn => $fn, as => $as };
3302 }
3303  
3304 # _grouped_totals($self, \%pipeline, \%spec) -> \@rows
3305 #
3306 # Single GROUP BY entry point for all four chart routes. Returns an arrayref
3307 # of hashrefs, each containing the 'by' column values and the aggregate result
3308 # under $spec->{as}.
3309 #
3310 # $pipeline = { source => $src_or_undef, records => \@rows }
3311 # source -- a DataSource or Database::Join for the push path; undef when
3312 # the pipeline is a /combine union (must fold in Perl).
3313 # records -- the already-fetched rows (pre-filtered by the caller).
3314 #
3315 # $spec = { by => [...], fn => ..., val => ..., as => ..., [sort_by, having, limit, offset] }
3316 #
3317 # Dispatch:
3318 # Push path -- $source is defined, measure is pushable (checked by
3319 # _measure_pushable), and either no active f= filters or all
3320 # active filters are SQL-pushable (via _filter_specs_to_criteria).
3321 # Calls $source->aggregate() with pushable criteria when present.
3322 # Perl fold -- Iterates $pipeline->{records} (pre-filtered by the caller)
3323 # when the push path is unavailable (combine union, non-SQL
3324 # source, non-pushable measure, or residual filters that cannot
3325 # be expressed as SQL criteria).
3326 #
3327 # $ENV{BI_FORCE_PERL_AGG}: set to a true value in tests to force the Perl fold
3328 # regardless of source type, enabling cross-backend equivalence assertions.
3329 394 ▶sub _grouped_totals :Protected ($self, $pipeline, $spec) {
Subroutine _grouped_totals: called CC=79 SCAR=62.9
3330 394 my $source = $pipeline->{source};
3331 394 ▶ my $records = $pipeline->{records} // [];
Condition50%1/2
$pipeline->{"records"} // []
l!l
3940
MC/DC0%0/1
$pipeline->{"records"} // []
$pipeline->{"records"}
Truth table50%1/2
A
A= $pipeline->{"records"}
Aresult
11
00
3332 394 ▶ my $by = $spec->{by} // [];
Condition50%1/2
$spec->{"by"} // []
l!l
3940
MC/DC0%0/1
$spec->{"by"} // []
$spec->{"by"}
Truth table50%1/2
A
A= $spec->{"by"}
Aresult
11
00
3333 394 ▶ my $fn = lc($spec->{fn} // 'count');
Condition50%1/2
$spec->{"fn"} // "count"
l!l
3940
MC/DC0%0/1
$spec->{"fn"} // "count"
$spec->{"fn"}
Truth table50%1/2
A
A= $spec->{"fn"}
Aresult
11
00
3334 394 my $val_col = $spec->{val};
3335 394 ▶ my $as = $spec->{as} // 'value';
Condition50%1/2
$spec->{"as"} // "value"
l!l
3940
MC/DC0%0/1
$spec->{"as"} // "value"
$spec->{"as"}
Truth table50%1/2
A
A= $spec->{"as"}
Aresult
11
00
3336  
3337 # Push path: use backend aggregate() when safe.
3338 # When f= filters are active, _filter_specs_to_criteria translates as many
3339 # specs as possible to SQL criteria. The push path is used only when ALL
3340 # specs are SQL-pushable (no residual); otherwise the Perl fold handles the
3341 # pre-filtered records the caller already passed in.
3342 394 my @f_specs = grep { /\S/ } @{ _filter_specs($self) };
3343 394 my $has_filter = !!@f_specs;
3344  
3345 # SQL::Statement 1.414 (the SQL engine under DBD::CSV) uses
3346 # "use warnings FATAL => 'all'" and calls join("\0", @row[@keycols])
3347 # inside getAffectedResult without guarding against undef. When a GROUP BY
3348 # column contains blank CSV cells (empty_is_undef => 1 converts them to
3349 # undef), the join triggers a fatal "uninitialized value" exception and the
3350 # execute() call dies. The correct fix is to use
3351 # map { $_ // '' } @row[@keycols]
3352 # in SQL::Statement::getAffectedResult, but the module has been unmaintained
3353 # since 2020 (21 open RT tickets as of 2026-10).
3354 # See: https://rt.cpan.org/Ticket/Display.html?id=181946
3355 # Skip the push path whenever any 'by' column has a blank or undef value so
3356 # DBD::CSV/SQL::Statement is never asked to GROUP BY a null key.
3357 # TODO: remove this guard once SQL-Statement RT#181946 is fixed (last checked: 1.414, still the latest release, 2026-11-06).
3358 394 ▶ my $has_null_by_key = @$by && do {
Condition66%2/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
13930
MC/DC0%0/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 table66%2/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
3359 393 my $found;
3360 393 KEY_SCAN: for my $row (@$records) {
3361 2295 for my $col (@$by) {
3362 2541 my $v = $row->{$col};
3363 0 ▶ if (!defined($v) || !length($v)) { $found = 1; last KEY_SCAN; }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $v and length $v) 0 2541 2541
Condition33%1/3
defined $v and length $v
!ll&&!rl&&r
002541
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
3364 }
3365 }
3366 393 $found;
3367 };
3368  
3369 # When filters are active, translate them to SQL criteria for the push path.
3370 # If any spec has no SQL equivalent (@residual is non-empty), the push path
3371 # is skipped and the Perl fold uses the already-filtered $records.
3372 394 ▶ my ($push_crit, $push_residual) = ($has_filter && $source)
Branch: 1 branch
BranchTrueFalseTotal
$has_filter && $source ? : 9 385 394
Condition66%2/3
$has_filter and $source
!ll&&!rl&&r
38509
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
3373 ? _filter_specs_to_criteria(\@f_specs, $source)
3374 : ({}, []);
3375 394 ▶ my $can_push_filters = !$has_filter || (!@$push_residual && %$push_crit);
Condition50%3/6
!$has_filter || !@$push_residual && %$push_crit
l!l&&r!l&&!r
38509
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
3376  
3377 # Skip the push path when any 'by' or 'val' column is virtual (added by
3378 # _apply_calc_fields or named-group loader). Virtual columns do not exist in
3379 # the backend and would cause a "No such column" SQL error before the fold fallback.
3380 394 ▶ my $virt = $self->stash('_virtual_columns') // {};
Condition50%1/2
$self->stash("_virtual_columns") // {}
l!l
0394
MC/DC0%0/1
$self->stash("_virtual_columns") // {}
$self->stash("_virtual_columns")
Truth table50%1/2
A
A= $self->stash("_virtual_columns")
Aresult
11
00
3381 482 ▶ my $has_virtual = grep { $virt->{$_} }
Branch: 1 branch
BranchTrueFalseTotal
defined $val_col ? : 38 356 394
3382 394 ▶ (@$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
3383  
3384 394 ▶ 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)) 376 18 394
Condition83%15/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
144376
$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
104380
$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
100384
$ENV{"BI_FORCE_PERL_AGG"} or _dedup_requested($self) or $has_virtual or not $can_push_filters
l!l&&r!l&&!r
19384
$ENV{"BI_FORCE_PERL_AGG"} or _dedup_requested($self) or $has_virtual
l!l&&r!l&&!r
10393
$ENV{"BI_FORCE_PERL_AGG"} or _dedup_requested($self)
l!l&&r!l&&!r
10393
MC/DC57%4/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 table62%5/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
3385 || !_measure_pushable($source, $fn, $val_col, $records)) {
3386 376 my $m = _measure($fn, $val_col, $as);
3387 376 my $agg_rows = eval {
3388 $source->aggregate(
3389 by => $by,
3390 measures => [$m],
3391 ($has_filter && %$push_crit ? (%$push_crit) : ()),
3392 ($spec->{sort_by} ? (sort_by => $spec->{sort_by}) : ()),
3393 ($spec->{having} ? (having => $spec->{having}) : ()),
3394 ($spec->{limit} ? (limit => $spec->{limit}) : ()),
3395 376 ▶ ($spec->{offset} ? (offset => $spec->{offset}) : ()),
Branch: 5 branches
BranchTrueFalseTotal
$has_filter && %$push_crit ? : 0 376 376
$spec->{'sort_by'} ? : 0 376 376
$spec->{'having'} ? : 0 376 376
$spec->{'limit'} ? : 0 376 376
$spec->{'offset'} ? : 0 376 376
Condition33%1/3
$has_filter and %$push_crit
!ll&&!rl&&r
37600
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
3396 )
3397 };
3398 376 ▶ unless ($@) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($@) 376 0 376
3399 376 ▶ return $agg_rows // [];
Condition50%1/2
$agg_rows // []
l!l
3760
MC/DC0%0/1
$agg_rows // []
$agg_rows
Truth table50%1/2
A
A= $agg_rows
Aresult
11
00
3400 }
3401 0 $self->app->log->debug("aggregate() push failed: $@; falling back to Perl fold");
3402 }
3403  
3404 # Perl fold over pre-filtered records.
3405 #
3406 # The fold keeps a running total for the functions that are sums of their
3407 # parts (sum, avg, min, max) and the values themselves for the ones that are
3408 # not (median, a percentile, stdev, range), which are resolved once the group
3409 # is complete. first and last are order-dependent, so they are taken as the
3410 # rows arrive and need no list at all.
3411 18 my (%seen_warned, %seen_key, @key_order);
3412 18 my (%totals, %count_map, %distinct_vals, %values);
3413  
3414 18 for my $row (@$records) {
3415 # Skip rows where any 'by' column is empty/undef (mirrors SQL GROUP BY NULL exclusion).
3416 # Note: calc field columns store '(unparseable)' (not undef) for failed expressions,
3417 # so those rows pass this guard and appear in the (unparseable) group instead.
3418 75 ▶ my @key_parts = map { $row->{$_} // '' } @$by;
Condition50%1/2
$row->{$_} // ""
l!l
780
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table50%1/2
A
A= $row->{$_}
Aresult
11
00
3419 75 ▶ next if @$by && grep { !length($_) } @key_parts;
Branch: 1 branch
BranchTrueFalseTotal
if @$by and grep {not length $_;} @key_parts 0 75 75
Condition66%2/3
@$by and grep {not length $_;} @key_parts
!ll&&!rl&&r
3720
MC/DC0%0/2
@$by and grep {not length $_;} @key_parts
@$by grep {not length $_;} @key_parts
Truth table66%2/3
A and B
A= @$byB= grep {not length $_;} @key_parts
ABresult
0X0
100
111
3420 75 my $key = join("\x00", @key_parts);
3421  
3422 75 ▶ if ($fn eq 'count') {
Branch: 3 branches
BranchTrueFalseTotal
if ($fn eq 'count') { } 54 21 75
elsif ($fn eq 'count_distinct') { } 0 21 21
elsif ($fn eq 'first' or $fn eq 'last') { } 0 21 21
3423 54 ▶ push @key_order, $key unless $seen_key{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_key{$key}++ 43 11 54
3424 54 $totals{$key}++;
3425 } elsif ($fn eq 'count_distinct') {
3426 0 ▶ push @key_order, $key unless $seen_key{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_key{$key}++ 0 0 0
3427 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
3428 0 $distinct_vals{$key}{$dv}++;
3429 ▶ } elsif ($fn eq 'first' || $fn eq 'last') {
Condition33%1/3
$fn eq "first" or $fn eq "last"
l!l&&r!l&&!r
0021
MC/DC0%0/2
$fn eq "first" or $fn eq "last"
$fn eq "first" $fn eq "last"
Truth table33%1/3
A or B
A= $fn eq "first"B= $fn eq "last"
ABresult
1X1
011
000
3430 # first/last read any column, not only a numeric one, and they
3431 # report the value as it appears: the number a cell holds when it
3432 # holds a number, the text it holds otherwise. A blank cell is
3433 # not a value, so it is passed over -- the first row that has
3434 # something in the column is the first value.
3435 0 ▶ my $v = defined $val_col ? $row->{$val_col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $val_col ? : 0 0 0
3436 0 ▶ next unless defined $v && length $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and length $v 0 0 0
Condition0%0/3
defined $v and length $v
!ll&&!rl&&r
000
MC/DC0%0/2
defined $v and length $v
defined $v length $v
Truth table0%0/3
A and B
A= defined $vB= length $v
ABresult
0X0
100
111
3437 0 ▶ push @key_order, $key unless $seen_key{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_key{$key}++ 0 0 0
3438 0 ▶ $totals{$key} = $v if $fn eq 'last' || !exists $totals{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "last" or not exists $totals{$key} 0 0 0
Condition0%0/3
$fn eq "last" or not exists $totals{$key}
l!l&&r!l&&!r
000
MC/DC0%0/2
$fn eq "last" or not exists $totals{$key}
$fn eq "last" not exists $totals{$key}
Truth table0%0/3
A or not(B)
A= $fn eq "last"B= not exists $totals{$key}
ABresult
1X1
011
000
3439 } else {
3440 21 ▶ my $v = defined $val_col ? ($row->{$val_col} // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $val_col ? : 21 0 21
Condition100%2/2
$row->{$val_col} // ""
l!l
192
MC/DC100%1/1
$row->{$val_col} // ""
$row->{$val_col}
Truth table100%2/2
A
A= $row->{$val_col}
Aresult
11
00
3441 21 my $n = _numeric_cell($v);
3442 21 ▶ unless (defined $n) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $n) 3 18 21
3443 3 ▶ unless ($seen_warned{"$fn\x01" . ($val_col // '')}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($seen_warned{"$fn\cA" . ($val_col // "")}++) 2 1 3
Condition50%1/2
$val_col // ""
l!l
30
MC/DC0%0/1
$val_col // ""
$val_col
Truth table50%1/2
A
A= $val_col
Aresult
11
00
3444 2 ▶ carp $self->_i18n('warn_measure_fallback', $fn, $val_col // '(none)');
Condition50%1/2
$val_col // "(none)"
l!l
20
MC/DC0%0/1
$val_col // "(none)"
$val_col
Truth table50%1/2
A
A= $val_col
Aresult
11
00
3445 }
3446 3 next; # skip: do NOT add key to order for non-numeric rows
3447 }
3448 18 ▶ push @key_order, $key unless $seen_key{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_key{$key}++ 13 5 18
3449 18 ▶ if ($fn eq 'sum') { $totals{$key} += $n }
Branch: 4 branches
BranchTrueFalseTotal
if ($fn eq 'sum') { } 15 3 18
elsif ($fn eq 'avg') { } 3 0 3
elsif ($fn eq 'min') { } 0 0 0
elsif ($fn eq 'max') { } 0 0 0
3450 3 elsif ($fn eq 'avg') { $totals{$key} += $n; $count_map{$key}++ }
3451 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
3452 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
3453 0 else { push @{ $values{$key} }, $n }
3454 }
3455 }
3456  
3457 18 ▶ if ($fn eq 'avg') {
Branch: 3 branches
BranchTrueFalseTotal
if ($fn eq 'avg') { } 2 16 18
elsif ($fn eq 'count_distinct') { } 0 16 16
elsif (%values) { } 0 16 16
3458 2 for my $k (keys %totals) {
3459 2 ▶ $totals{$k} = $count_map{$k} ? $totals{$k} / $count_map{$k} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$count_map{$k} ? : 2 0 2
3460 }
3461 } elsif ($fn eq 'count_distinct') {
3462 0 for my $k (@key_order) {
3463 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
3464 }
3465 } elsif (%values) {
3466 # median / p<N> / stdev / range: resolved from the group's values, and
3467 # through the same arithmetic the stats view uses for a whole column.
3468 0 for my $k (keys %values) {
3469 0 my @sorted = sort { $a <=> $b } @{ $values{$k} };
3470 0 $totals{$k} = _measure_value($fn, \@sorted);
3471 }
3472 }
3473  
3474 # Assemble result rows in ascending key order (matching the SQL push path)
3475 # unless the caller requested an explicit sort.
3476 18 ▶ unless ($spec->{sort_by}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($spec->{"sort_by"}) 18 0 18
3477 18 @key_order = sort @key_order;
3478 }
3479 18 my @result;
3480 18 for my $key (@key_order) {
3481 56 ▶ my @parts = @$by ? (split /\x00/, $key, scalar @$by) : ();
Branch: 1 branch
BranchTrueFalseTotal
@$by ? : 55 1 56
3482 56 my %row;
3483 56 for my $i (0 .. $#$by) {
3484 61 $row{$by->[$i]} = $parts[$i];
3485 }
3486 56 ▶ $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
560
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
3487 56 push @result, \%row;
3488 }
3489  
3490 18 return \@result;
3491 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3492  
3493 # _rows_of_page(\@rows, $offset, $per_page) -> \@page
3494 #
3495 # One page of rows, in an array of its own. The rows may be a backend's own
3496 # read-only array, as they are from a DBI handle that is not SQLite, so they are
3497 # copied and never spliced.
3498 198 ▶sub _rows_of_page {
Subroutine _rows_of_page: called CC=3 SCAR=11.0
3499 198 my ($rows, $offset, $per_page) = @_;
3500 # A negative offset would count from the end of the rows.
3501 198 ▶ $offset = 0 if $offset < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $offset < 0 1 197 198
3502 198 my $last = $offset + $per_page - 1;
3503 198 ▶ $last = $#$rows if $last > $#$rows;
Branch: 1 branch
BranchTrueFalseTotal
if $last > $rows->$#* 195 3 198
3504 198 return [ @{$rows}[$offset .. $last] ];
3505 }
3506  
3507 # _page_count($total, $per_page) -> $pages
3508 #
3509 # How many pages $total rows make, for the table's "Page N of M". No rows is
3510 # still one page, the empty one the table shows.
3511 189 ▶sub _page_count {
Subroutine _page_count: called CC=4 SCAR=17.1
3512 189 my ($total, $per_page) = @_;
3513 189 ▶ return 1 unless $total && $per_page && $per_page > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $total and $per_page and $per_page > 0 0 189 189
Condition33%2/6
$total and $per_page and $per_page > 0
!ll&&!rl&&r
00189
$total and $per_page
!ll&&!rl&&r
00189
MC/DC0%0/3
$total and $per_page and $per_page > 0
$total $per_page $per_page > 0
Truth table25%1/4
A and B and C
A= $totalB= $per_pageC= $per_page > 0
ABCresult
0XX0
10X0
1100
1111
3514 189 return int(($total + $per_page - 1) / $per_page);
3515 }
3516  
3517 # Where a cell with no date or number sorts: first, ascending, as -Infinity
3518 # does in the browser.
3519 5 Readonly my $NO_NUMBER => -9**9**9;
3520  
3521 # _sort_records(\@rows, $column, $dir) -> \@sorted
3522 #
3523 # Every row, in the order the table's own header sort gives a page of them
3524 # (biValueComparator in dashboard.html.tt), so the first page of a table too
3525 # long for one page is the first page of the sorted rows rather than the first
3526 # rows sorted. The column sorts as dates when every non-empty cell is one
3527 # (YYYY-MM-DD, or M/D/YYYY unless a cell shows the day comes first), else as
3528 # numbers when every non-empty cell holds one (Util::parse_number, which the
3529 # browser's parseAccounting copies: "$1,000" and "(5)" are numbers, "T27" is
3530 # text), else as text the way localeCompare(..., { numeric: true, sensitivity:
3531 # 'base' }) does: case and accents ignored, a run of digits compared as a
3532 # number. An empty cell sorts first, ascending. Rows that compare equal keep
3533 # their order, in either direction. A new array: the rows may be read-only.
3534 1 ▶sub _sort_records ($rows, $column, $dir) {
Subroutine _sort_records: called CC=14 SCAR=39.8
3535 my @text = map {
3536 1 ▶ my $v = $_->{$column} // '';
Condition50%1/2
$_->{$column} // ""
l!l
20
MC/DC0%0/1
$_->{$column} // ""
$_->{$column}
Truth table50%1/2
A
A= $_->{$column}
Aresult
11
00
3537 2 $v =~ s/\A\s+|\s+\z//g;
3538 2 $v;
3539 } @$rows;
3540 1 my @filled = grep { length } @text;
3541  
3542 1 my $key_of; # cell text -> number; text sorts when there is none
3543 1 ▶ 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)) { } 1 0 1
elsif (@filled and not grep({not defined Database::BI::Util::parse_number($_);} @filled)) { } 0 0 0
Condition33%1/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
001
MC/DC0%0/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 table33%1/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
3544 1 my $month_first = 1;
3545 1 for (@filled) {
3546 2 ▶ 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 2 2
3547 0 ▶ if ($p1 > 12) { $month_first = 0; last }
Branch: 1 branch
BranchTrueFalseTotal
if ($p1 > 12) 0 0 0
3548 0 ▶ if ($p2 > 12) { last }
Branch: 1 branch
BranchTrueFalseTotal
if ($p2 > 12) 0 0 0
3549 }
3550 2 ▶ $key_of = sub ($v) {
Subroutine __ANON__: called CC=4 SCAR=25.0
3551 2 ▶ 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 2 0 2
3552 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
3553 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
3554 }
3555 0 return $NO_NUMBER;
3556 1 };
3557 0 ▶ } elsif (@filled && !(grep { !defined Database::BI::Util::parse_number($_) } @filled)) {
Condition0%0/3
@filled and not grep({not defined Database::BI::Util::parse_number($_);} @filled)
!ll&&!rl&&r
000
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 table0%0/3
A and not(B)
A= @filledB= not grep({not defined Database::BI::Util::parse_number($_);} @filled)
ABresult
0X0
100
111
3558 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
3559 }
3560  
3561 # Equal rows keep their order in either direction, as the browser's stable
3562 # sort of -cmp does: the direction turns the comparison, not the result.
3563 1 ▶ my $sign = $dir eq 'desc' ? -1 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$dir eq 'desc' ? : 1 0 1
3564 1 my @order;
3565 1 ▶ if ($key_of) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key_of) { } 1 0 1
3566 1 my @key = map { $key_of->($_) } @text;
3567 1 ▶ @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
100
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
3568 } else {
3569 0 my @key = map { _collation_key($_) } @text;
3570 0 ▶ @order = sort { $sign * _collate($key[$a], $key[$b]) || $a <=> $b } 0 .. $#$rows;
Condition0%0/3
$sign * _collate($key[$a], $key[$b]) || $a <=> $b
l!l&&r!l&&!r
000
MC/DC0%0/2
$sign * _collate($key[$a], $key[$b]) || $a <=> $b
$sign * _collate($key[$a], $key[$b]) $a <=> $b
Truth table0%0/3
A || B
A= $sign * _collate($key[$a], $key[$b])B= $a <=> $b
ABresult
1X1
011
000
3571 }
3572 1 return [ @{$rows}[@order] ];
3573 }
3574  
3575 # _collation_key($text) -> \@tokens
3576 #
3577 # The text as localeCompare with sensitivity 'base' and numeric sees it: case
3578 # and accents folded away, each run of digits one number, every other
3579 # character ranked as ICU's root collation does -- spaces, then punctuation and
3580 # symbols, then digits, then letters.
3581 0 ▶sub _collation_key ($text) {
Subroutine _collation_key: not called CC=5 SCAR=34.0
3582 0 my $folded = CORE::fc(Unicode::Normalize::NFD($text));
3583 0 $folded =~ s/\p{Mn}+//g;
3584 0 my @tokens;
3585 0 ▶ while ($folded =~ /(\d+)|(.)/gs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($folded =~ /(\d+)|(.)/gsu) 0 0 0
3586 0 ▶ if (defined $1) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $1) { } 0 0 0
3587 0 push @tokens, [2, $1 + 0];
3588 } else {
3589 0 my $c = $2;
3590 0 ▶ push @tokens, [ $c =~ /\s/ ? 0 : $c =~ /\p{L}/ ? 3 : 1, $c ];
Branch: 2 branches
BranchTrueFalseTotal
$c =~ /\s/u ? : 0 0 0
$c =~ /\p{L}/u ? : 0 0 0
3591 }
3592 }
3593 0 return \@tokens;
3594 }
3595  
3596 # _collate(\@a, \@b) -> -1 | 0 | 1
3597 0 ▶sub _collate ($x, $y) {
Subroutine _collate: not called CC=6 SCAR=37.4
3598 0 ▶ my $n = @$x < @$y ? @$x : @$y;
Branch: 1 branch
BranchTrueFalseTotal
@$x < @$y ? : 0 0 0
3599 0 for my $i (0 .. $n - 1) {
3600 0 my ($p, $q) = ($x->[$i], $y->[$i]);
3601 0 ▶ my $c = $p->[0] <=> $q->[0]
Branch: 1 branch
BranchTrueFalseTotal
$p->[0] == 2 ? : 0 0 0
Condition0%0/3
$p->[0] <=> $q->[0] || ($p->[0] == 2 ? $p->[1] <=> $q->[1] : $p->[1] cmp $q->[1])
l!l&&r!l&&!r
000
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 table0%0/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
3602 || ($p->[0] == 2 ? $p->[1] <=> $q->[1] : $p->[1] cmp $q->[1]);
3603 0 ▶ return $c if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 0 0 0
3604 }
3605 0 return @$x <=> @$y;
3606 }
3607  
3608 # _fetch_page( $self, $source, \%params ) -> ( $records, $has_next )
3609 # (also stashes page_count, the number of pages: from the rows read, or on
3610 # the SQL fast path, which reads one page and a row, from the source's count)
3611 # params: per_page -- page size (required)
3612 # offset -- 0-based row offset (required)
3613 # dedup -- truthy when ?d=1 dedup is requested
3614 # sort_col -- column name to sort by (optional; default the request's
3615 # sort= parameter)
3616 # sort_dir -- 'asc' or 'desc' (default the request's dir=, else 'asc')
3617 #
3618 # Purpose: Fetch and reduce one page of records from $source, honouring the
3619 # reduce-before-paginate ordering contract. Two modes:
3620 #
3621 # Fast path (no f= filters, no dedup): uses the N+1 trick
3622 # selectall_arrayref(limit => per_page+1, offset => offset). has_next is
3623 # determined by the extra row before it is popped.
3624 #
3625 # Reduction path (f= filters or dedup present): materialises the full result
3626 # in memory, applies all f= filters with _apply_filter_spec (case-insensitive),
3627 # applies dedup if requested, then paginates in Perl. This guarantees that
3628 # the Nth page contains the Nth page of the *reduced* set, not the Nth page
3629 # of the raw set reduced to fewer rows. Memory cost: the full reduced set.
3630 #
3631 # Sort: a sort column takes the reduction path, and every row is sorted by
3632 # _sort_records -- after the fields, filters and cross-row columns, so any
3633 # column the table shows can be sorted on -- before the page is cut. The
3634 # table's header sort works on the rows it was given, so on a table longer
3635 # than a page it sorted only those, and the page was not the first of the
3636 # sorted table; the page asks for sort= instead whenever there is more than
3637 # one page. The backend's sort_by is not used: it compares as text, and
3638 # ignores a column whose name is not a safe identifier. When the sort is
3639 # applied, stash sorted_by => { col, dir } tells the page what it shows.
3640 #
3641 # Returns (undef, 0) when the underlying fetch throws; the caller must handle
3642 # $records being undef.
3643 164 ▶sub _fetch_page :Protected ($self, $source, $params) {
Subroutine _fetch_page: called CC=57 SCAR=49.8
3644 164 my $per_page = $params->{per_page};
3645 164 my $offset = $params->{offset};
3646 164 my $dedup = $params->{dedup};
3647 164 ▶ my $sort_col = $params->{sort_col} // $self->param('sort');
Condition100%3/3
$params->{"sort_col"} // $self->param("sort")
l!l&&r!l&&!r
22160
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
3648 164 ▶ $sort_col = undef unless defined $sort_col && length $sort_col;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sort_col and length $sort_col 161 3 164
Condition100%3/3
defined $sort_col and length $sort_col
!ll&&!rl&&r
16013
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
3649 164 ▶ 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 ? : 1 163 164
Condition80%4/5
($params->{"sort_dir"} // $self->param("dir")) // "asc"
l!l
50114
$params->{"sort_dir"} // $self->param("dir")
l!l&&r!l&&!r
500114
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
3650  
3651 # Collect and validate the filters, the range's bounds included.
3652 my @f_specs = grep {
3653 12 my ($c, $o) = split /:/, $_, 3;
3654 12 ▶ length($c // '') && defined $o && length $o;
Condition87%7/8
length($c // '') && defined $o && length $o
!ll&&!rl&&r
2010
length($c // "") and defined $o
!ll&&!rl&&r
1110
$c // ""
l!l
111
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
3655 164 } @{ _filter_specs($self) };
3656  
3657 # Determine whether the source has a SQL backend that supports LIMIT/OFFSET.
3658 # DBD::CSV / SQL::Statement do not implement LIMIT/OFFSET; passing them emits
3659 # a "Bad limit clause" error at the D::A layer before falling back to a Perl
3660 # approach. Avoid the noise by only using the N+1 fast path for SQL-backed
3661 # sources. For non-SQL sources (CSV, XLSX, in-memory) the reduction path
3662 # below materialises the full set and paginates in Perl.
3663 164 ▶ 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
190145
$source->can("dbi_source") and $source->dbi_source
!ll&&!rl&&r
014519
$source->can("pages_on_server") and $source->pages_on_server
!ll&&!rl&&r
01450
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
3664 || ($source->can('pages_on_server') && $source->pages_on_server);
3665  
3666 # A cross-row column is a column of the whole filtered set, so a request that
3667 # names one cannot take the N+1 fast path: it would see one page of rows and
3668 # restart every running total on page 2.
3669 164 ▶ my $cross = length($self->param('cs') // '') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length($self->param('cs') // '') ? : 2 162 164
Condition100%2/2
$self->param("cs") // ""
l!l
3161
MC/DC100%1/1
$self->param("cs") // ""
$self->param("cs")
Truth table100%2/2
A
A= $self->param("cs")
Aresult
11
00
3670  
3671 164 ▶ unless (@f_specs || $dedup || $cross || defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@f_specs or $dedup or $cross or defined $sort_col) 149 15 164
Condition100%9/9
@f_specs or $dedup or $cross or defined $sort_col
l!l&&r!l&&!r
123149
@f_specs or $dedup or $cross
l!l&&r!l&&!r
102152
@f_specs or $dedup
l!l&&r!l&&!r
91154
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
3672 149 ▶ if ($is_sql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_sql) 16 133 149
3673 # Fast path (SQL-backed): delegate LIMIT/OFFSET to the backend N+1 trick.
3674 # Copy before pop: D::A may return a read-only ref to its internal cache.
3675 16 ▶ my @records = @{ $source->selectall_arrayref(
Condition50%1/2
$source->selectall_arrayref("limit", $per_page + 1, "offset", $offset) // []
l!l
160
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
3676 limit => $per_page + 1, offset => $offset,
3677 ) // [] };
3678 16 ▶ my $has_next = (@records > $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
@records > $per_page ? : 0 16 16
3679 16 ▶ pop @records if $has_next;
Branch: 1 branch
BranchTrueFalseTotal
if $has_next 0 16 16
3680 # The number of pages needs the number of rows. count() remembers a
3681 # file's until it changes, so only the first page of a big SQLite
3682 # file pays for the COUNT(*). Only when there is more than one page:
3683 # a short table shows no pagination. A count that fails costs the
3684 # page its "of M", never the page.
3685 16 ▶ if ($has_next || $offset > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_next or $offset > 0) 0 16 16
Condition33%1/3
$has_next or $offset > 0
l!l&&r!l&&!r
0016
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
3686 0 my $total;
3687 0 my $ok = eval { $total = $source->count; 1 };
3688 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
3689 if $ok && defined $total && $total =~ /\A\d+\z/;
3690 }
3691 16 return (\@records, $has_next);
3692 }
3693 # Non-SQL fast path: fetch all, then paginate. Every row is in hand, so
3694 # the number of pages costs nothing.
3695 133 ▶ my $all = $source->selectall_arrayref() // [];
Condition50%1/2
$source->selectall_arrayref // []
l!l
1330
MC/DC0%0/1
$source->selectall_arrayref // []
$source->selectall_arrayref
Truth table50%1/2
A
A= $source->selectall_arrayref
Aresult
11
00
3696 133 ▶ my $has_next = (@$all > $offset + $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
@$all > $offset + $per_page ? : 0 133 133
3697 133 $self->stash(page_count => _page_count(scalar(@$all), $per_page));
3698 133 return (_rows_of_page($all, $offset, $per_page), $has_next);
3699 }
3700  
3701 # Always fetch all rows in Perl and filter with _apply_filter_spec.
3702 # SQL criteria pushdown (passing %criteria to selectall_arrayref) is
3703 # intentionally avoided: on some Perl/D::A version combinations the WHERE
3704 # clause is silently dropped, returning the full unfiltered set. The Perl
3705 # path is correct on every supported version. Memory cost: bounded by the
3706 # source file size (the same as the dedup path already accepted).
3707 15 ▶ my $all = $source->selectall_arrayref() // [];
Condition50%1/2
$source->selectall_arrayref // []
l!l
150
MC/DC0%0/1
$source->selectall_arrayref // []
$source->selectall_arrayref
Truth table50%1/2
A
A= $source->selectall_arrayref
Aresult
11
00
3708  
3709 # A stored date or time pattern is what makes a patterned column comparable
3710 # with the ISO bounds a relative time range carries, and it belongs to stage 2
3711 # of the pipeline -- before the filters of stage 5. The rest of the
3712 # application reaches the filters through that order already; this path, which
3713 # filters before it paginates, is the one call site that would otherwise
3714 # compare the reader's format, so it normalises first, on exactly the rows the
3715 # specs are about to be applied to.
3716 15 $self->_apply_date_normalization($all, [_get_columns($source, $all)],
3717 $self->_calc_spec_key);
3718  
3719 # A failure below is a 400 about the request. It is rendered here, and the
3720 # caller sees the stash and returns rather than drawing a page over it.
3721 2 ▶ my $refuse = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3722 2 my ($why) = @_;
3723 2 $why =~ s/ at \S+ line \d+\.?\n?$//;
3724 2 $self->render(text => $why, status => 400);
3725 2 $self->stash('_cross_row_error' => $why);
3726 2 return;
3727 15 };
3728  
3729 # Stage 4. The page's own fields run on the sliced page (_page_columns), which
3730 # is enough to show them, but a filter or a window that reads one needs it on
3731 # every row, and before them. That pass then only repeats these, on one page.
3732 15 $all = [ @$all ]; # the backend's own array can be read-only
3733 15 my @cols_so_far;
3734 15 ▶ if (defined $params->{calc_spec_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"calc_spec_key"}) 15 0 15
3735 15 my @before = _get_columns($source, $all);
3736 15 ▶ my $span = @before ? $self->_span_calc_spec(\@before, ()) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@before ? : 15 0 15
3737 15 ▶ if ($span && $span->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($span and $span->{"error"}) 0 15 15
Condition33%1/3
$span and $span->{"error"}
!ll&&!rl&&r
1500
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
3738 0 $refuse->($span->{error});
3739 0 return ();
3740 }
3741 15 my ($r, $c) = eval {
3742 $self->_calc_for_page($all, \@before, {
3743 spec_key => $params->{calc_spec_key},
3744 15 ▶ ($span ? (calc => $span->{calc}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 15 15
3745 })
3746 };
3747 15 ▶ unless ($r) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($r) 0 15 15
3748 0 $refuse->($@);
3749 0 return ();
3750 }
3751 15 ($all, @cols_so_far) = ($r, @$c);
3752 }
3753  
3754 # A filter on a column stages 6 and 7 write waits for them. See _reduce_records.
3755 0 ▶ my %written = $cross ? map { $_ => 1 } _cross_row_written($self) : ();
Branch: 1 branch
BranchTrueFalseTotal
$cross ? : 2 13 15
3756 15 ▶ my @filter_cols = @cols_so_far ? @cols_so_far : _get_columns($source, $all);
Branch: 1 branch
BranchTrueFalseTotal
@cols_so_far ? : 15 0 15
3757 15 ▶ 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))) 0 15 15
3758 0 $refuse->($why);
3759 0 return ();
3760 }
3761 15 my @late = grep { $written{ (split /:/, $_, 2)[0] } } @f_specs;
3762 15 $all = _apply_filter_spec($all, $_) for grep { !$written{ (split /:/, $_, 2)[0] } } @f_specs;
3763  
3764 15 ▶ if ($dedup) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dedup) 1 14 15
3765 1 my $cols = $source->columns;
3766 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
3767 1 $all = _dedup_records($all, \@dcols);
3768 }
3769  
3770 # Stages 6 and 7, before the slice: a running total has to see every filtered
3771 # row, or page 2 would start again from zero.
3772 15 ▶ if ($cross) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cross) 2 13 15
3773 2 my $cols = $source->columns;
3774 my @xcols = @cols_so_far ? @cols_so_far
3775 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
3776 2 my $done = eval {
3777 2 my ($r, $c) = $self->_apply_cross_row($all, \@xcols);
3778 0 ($all) = $self->_apply_held_calc_fields($r, $c);
3779 0 1;
3780 };
3781 2 ▶ unless ($done) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($done) 2 0 2
3782 2 $refuse->($@);
3783 2 return ();
3784 }
3785 0 $all = _apply_filter_spec($all, $_) for @late;
3786 }
3787  
3788 # The whole reduced set, sorted, before the page is cut. A column the view
3789 # does not have is left alone (the order is the file's), as the header sort
3790 # ignores one it cannot find.
3791 13 ▶ if (defined $sort_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort_col) 3 10 13
3792 3 ▶ my %known = map { $_ => 1 } (@cols_so_far ? @cols_so_far : _get_columns($source, $all)), keys %written;
Branch: 1 branch
BranchTrueFalseTotal
@cols_so_far ? : 3 0 3
3793 3 ▶ $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 3 3
Condition33%2/6
$cross and @$all and exists $all->[0]{$sort_col}
!ll&&!rl&&r
300
$cross and @$all
!ll&&!rl&&r
300
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
3794 3 ▶ if ($known{$sort_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($known{$sort_col}) 1 2 3
3795 1 $all = _sort_records($all, $sort_col, $sort_dir);
3796 1 $self->stash(sorted_by => { col => $sort_col, dir => $sort_dir });
3797 }
3798 }
3799  
3800 13 my $total = scalar @$all;
3801 13 ▶ my $has_next = ($total > $offset + $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$total > $offset + $per_page ? : 0 13 13
3802 13 my @page = @{ _rows_of_page($all, $offset, $per_page) };
3803 13 $self->stash(page_count => _page_count($total, $per_page));
3804  
3805 13 return (\@page, $has_next);
3806 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3807  
3808 # _combine_tables(\@sources) -> (\@merged_records, \@merged_columns)
3809 #
3810 # Purpose: Perform a vertical stack (UNION ALL equivalent) of two or more
3811 # record sets. The merged column list is the union of all source
3812 # column lists: the first source's columns appear first (in their
3813 # original order), then each subsequent source contributes any new
3814 # column names it introduces, in order. Where a source does not
3815 # have a particular column, its rows receive an empty string for
3816 # that column.
3817 # Entry: $sources is an arrayref of [$records_aref, $columns_aref] pairs.
3818 # At least one element is required; a single-element call returns
3819 # that element's data unchanged (no allocation beyond the column copy).
3820 # Exit: Returns (\@merged_records, \@merged_columns).
3821 # Side Effects: None; allocates new record hashrefs (original rows are not mutated).
3822 12 ▶sub _combine_tables {
Subroutine _combine_tables: called CC=9 SCAR=22.0
3823 12 my ($sources) = @_;
3824  
3825 # Build the unified column order: first source's columns first, then any
3826 # new columns introduced by each subsequent source in their file order.
3827 12 my (@all_cols, %seen);
3828 12 for my $src (@$sources) {
3829 23 for my $col (@{ $src->[1] }) {
3830 95 ▶ push @all_cols, $col unless $seen{$col}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$col}++ 57 38 95
3831 }
3832 }
3833  
3834 12 my @merged;
3835 12 for my $src (@$sources) {
3836 23 my ($recs, $cols) = @$src;
3837 23 my %has_col = map { $_ => 1 } @$cols;
3838 23 for my $row (@$recs) {
3839 133 my %new_row;
3840 $new_row{$_} = $has_col{$_} ? ($row->{$_} // '') : ''
3841 133 ▶ for @all_cols;
Branch: 1 branch
BranchTrueFalseTotal
$has_col{$_} ? : 790 150 940
Condition50%1/2
$row->{$_} // ""
l!l
7900
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table50%1/2
A
A= $row->{$_}
Aresult
11
00
3842 133 push @merged, \%new_row;
3843 }
3844 }
3845  
3846 12 return (\@merged, \@all_cols);
3847 }
3848  
3849 # _csv_row(@fields) -> $csv_line_with_crlf
3850 #
3851 # Purpose: Format one row as an RFC 4180 CSV line. Fields containing commas,
3852 # double-quotes, or newlines are enclosed in double-quotes; embedded
3853 # double-quotes are doubled. The line ends with CRLF.
3854 # Entry: @fields may contain undef (treated as empty string).
3855 # Exit: Returns a string ending with "\r\n".
3856 521 ▶sub _csv_row {
Subroutine _csv_row: called CC=3 SCAR=11.0
3857 return join(',', map {
3858 521 ▶ my $f = $_ // '';
Condition100%2/2
$_ // ""
l!l
30462
MC/DC100%1/1
$_ // ""
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
3859 3048 ▶ $f =~ /[,"\r\n]/ ? do { (my $q = $f) =~ s/"/""/g; qq{"$q"} } : $f;
Branch: 1 branch
BranchTrueFalseTotal
$f =~ /[,"\r\n]/u ? : 6 3042 3048
3860 } @_) . "\r\n";
3861 }
3862  
3863 # _build_export_url($self, $left_spec, \@join_specs, \@filter_specs) -> $url_string
3864 #
3865 # Purpose: Assemble a /export?l=...&j=...&f=... URL string for the current
3866 # logical view. The caller must apply | html in TT to escape & as &amp;.
3867 # Entry: All args non-undef; spec arrays may be empty.
3868 # Exit: Returns a relative URL string beginning with '/export'.
3869 207 ▶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
3870 207 my $u = '/export?l=' . url_escape($left_spec);
3871 207 $u .= '&j=' . url_escape($_) for @$join_specs;
3872 207 ▶ $u .= '&c=' . url_escape($_) for @{ $combine_specs // [] };
Condition100%2/2
$combine_specs // []
l!l
43164
MC/DC100%1/1
$combine_specs // []
$combine_specs
Truth table100%2/2
A
A= $combine_specs
Aresult
11
00
3873 207 $u .= '&f=' . url_escape($_) for @$filter_specs;
3874 207 ▶ $u .= '&d=1' if $dedup;
Branch: 1 branch
BranchTrueFalseTotal
if $dedup 2 205 207
3875 # Parameters that shape the columns rather than the rows travel with the
3876 # export, so the file holds the column the page shows -- a time bucket, for
3877 # one -- and not the raw values behind it.
3878 207 ▶ for my $key (sort keys %{ $extra // {} }) {
Condition100%2/2
$extra // {}
l!l
76131
MC/DC100%1/1
$extra // {}
$extra
Truth table100%2/2
A
A= $extra
Aresult
11
00
3879 228 my $val = $extra->{$key};
3880 228 ▶ next unless defined $val && length $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val and length $val 227 1 228
Condition100%3/3
defined $val and length $val
!ll&&!rl&&r
22431
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
3881 1 $u .= "&$key=" . url_escape($val);
3882 }
3883 207 return $u;
3884 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3885  
3886 # _list_dir($self, $dir, $want_files) -> { dirs => [...], files => [...] }
3887 #
3888 # Purpose: Shared directory-listing kernel used by browse (which needs files)
3889 # and dirs_api (which needs only subdirectories). Hidden entries
3890 # (names starting with ".") are excluded. Entries are sorted
3891 # case-insensitively.
3892 # Entry: $dir is a Mojo::File pointing to an existing readable directory.
3893 # $want_files: if true, populate 'files' with entries matching $EXT_RE.
3894 # Exit: Returns a hashref with 'dirs' and 'files' arrayrefs (files is always
3895 # present but empty when $want_files is false).
3896 # Side Effects: Filesystem directory read.
3897 57 ▶sub _list_dir :Protected ($self, $dir, $want_files) {
Subroutine _list_dir: called CC=9 SCAR=22.0
3898 57 my (@dirs, @files);
3899 57 ▶ if (opendir my $dh, $dir->to_string) {
Branch: 1 branch
BranchTrueFalseTotal
if (opendir my $dh, $dir->to_string) 57 0 57
3900 57 ▶ while (my $entry = readdir $dh) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $entry = readdir $dh)) 429 57 486
3901 429 ▶ next if $entry eq '.' || $entry eq '..' || $entry =~ /\A\./;
Branch: 1 branch
BranchTrueFalseTotal
if $entry eq "." or $entry eq ".." or $entry =~ /\A\./u 295 134 429
Condition100%6/6
$entry eq "." or $entry eq ".." or $entry =~ /\A\./u
l!l&&r!l&&!r
114181134
$entry eq "." or $entry eq ".."
l!l&&r!l&&!r
5757315
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
3902 134 my $f = $dir->child($entry);
3903 134 ▶ if (-d $f) {
Branch: 2 branches
BranchTrueFalseTotal
if (-d $f) { } 75 59 134
elsif ($want_files and $entry =~ /$EXT_RE/u) { } 21 52 73
3904 75 push @dirs, { name => $entry, path => $f->to_string };
3905 }
3906 ▶ elsif ($want_files && $entry =~ $EXT_RE) {
Condition100%3/3
$want_files and $entry =~ /$EXT_RE/u
!ll&&!rl&&r
142421
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
3907 21 push @files, { name => $entry, path => $f->to_string };
3908 }
3909 }
3910 57 closedir $dh;
3911 }
3912 return {
3913 48 dirs => [ sort { lc($a->{name}) cmp lc($b->{name}) } @dirs ],
3914 57 files => [ sort { lc($a->{name}) cmp lc($b->{name}) } @files ],
3915 };
3916 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3917  
3918 # _write_sqlite_db($self, $records, $columns, $table) -> $raw_bytes
3919 #
3920 # Purpose: $records as a SQLite database of one table, every column TEXT, as
3921 # the file's bytes. Used by both _render_sqlite (HTTP download) and
3922 # export_write (filesystem write); Database::Join::Catalog writes it.
3923 # Entry: $records is an arrayref of hashrefs; $columns is an arrayref of names;
3924 # $table names the table, "data" unless given. An extract passes
3925 # "extract", which Database::Abstraction before 0.54 needed (it could
3926 # not read a table called "data"); extracts already built use it.
3927 # Exit: Returns scalar binary string. Croaks when it cannot be written.
3928 # Side Effects: Catalog makes and removes one temporary file under tmpdir.
3929 8 ▶sub _write_sqlite_db :Protected ($self, $records, $columns, $table = 'data') {
Subroutine _write_sqlite_db: called CC=3 SCAR=11.0
3930 # D~ fix: an empty column list would be "CREATE TABLE data ()", which is
3931 # invalid SQLite syntax; this message is the one readers have seen.
3932 8 ▶ croak 'Cannot export SQLite: result set has no columns'
Branch: 1 branch
BranchTrueFalseTotal
unless @$columns 1 7 8
3933 unless @$columns;
3934  
3935 7 require Database::Join::Catalog;
3936 7 return Database::Join::Catalog->sqlite_bytes(table => $table, columns => $columns, rows => $records);
3937 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3938  
3939 # _run_pipeline_source($self) -> ($src, $records, \@columns, $left_label) or ()
3940 #
3941 # Purpose: Inner pipeline: opens the left spec, builds the join chain, fetches
3942 # all rows, and runs any c= combine step. Does NOT apply f= filters,
3943 # dedup, or pagination -- that is the caller's responsibility.
3944 # Chart routes call this directly so they can access $src for the
3945 # aggregate() push path. Row-viewing routes and export routes
3946 # call the thin _run_export_pipeline wrapper instead.
3947 # Exit: On success: ($src_or_undef, $records_aref, $columns_aref, $label).
3948 # $src is undef when a c= combine makes the result non-aggregatable.
3949 # On failure: empty list (left table not found / fetch error).
3950 749 ▶sub _run_pipeline_source :Protected ($self) {
Subroutine _run_pipeline_source: called CC=27 SCAR=33.9
3951 749 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
7472
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
3952 749 my ($left_src, $left_label) = $self->_open_spec($left_spec);
3953 749 ▶ return () unless $left_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $left_src 34 715 749
3954  
3955 # Build the join chain lazily.
3956 715 ▶ 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
07132
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
3957 715 ▶ my $join_type = $self->param('jtype') // 'left';
Condition100%2/2
$self->param("jtype") // "left"
l!l
15700
MC/DC100%1/1
$self->param("jtype") // "left"
$self->param("jtype")
Truth table100%2/2
A
A= $self->param("jtype")
Aresult
11
00
3958 715 ▶ $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 701 715
3959 715 my $src = $left_src;
3960 715 my (@schema_warnings, @joined, @combined);
3961 715 for my $jspec (@{ $self->every_param('j') }) {
3962 20 my ($right_spec, $left_key, $right_key) = split /\|/, $jspec, 3;
3963 20 ▶ 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 6 20
Condition66%4/6
defined $right_spec and defined $left_key and defined $right_key
!ll&&!rl&&r
1406
defined $right_spec and defined $left_key
!ll&&!rl&&r
0146
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
3964  
3965 6 my $cur_cols = $src->columns;
3966 6 ▶ next unless $cur_cols;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_cols 0 6 6
3967 6 ▶ next unless +{ map { $_ => 1 } @$cur_cols }->{$left_key};
Branch: 1 branch
BranchTrueFalseTotal
unless {map({$_, 1;} @$cur_cols)}->{$left_key} 0 6 6
3968  
3969 6 my ($right_src, $right_label) = $self->_open_spec($right_spec);
3970 6 ▶ next unless $right_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_src 1 5 6
3971  
3972 5 my $right_cols = $right_src->columns;
3973 5 ▶ next unless $right_cols;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_cols 0 5 5
3974 5 ▶ next unless +{ map { $_ => 1 } @$right_cols }->{$right_key};
Branch: 1 branch
BranchTrueFalseTotal
unless {map({$_, 1;} @$right_cols)}->{$right_key} 0 5 5
3975  
3976 # Types are compared while the two sides are still separate sources;
3977 # after the join is built the mismatched columns are already published
3978 # under different names. See _schema_type_warnings.
3979 5 push @schema_warnings, $self->_schema_type_warnings(
3980 $src, $right_src, $left_label, $right_label, $left_key, $right_key);
3981  
3982 5 require Database::Join;
3983 0 ▶ local $SIG{__WARN__} = sub { push @schema_warnings, $_[0] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
3984 5 ▶ $src = Database::Join->new(
Branch: 2 branches
BranchTrueFalseTotal
$left_key ne $right_key ? : 0 5 5
$right_label ? : 5 0 5
3985 databases => [$src, $right_src],
3986 join_column => $left_key,
3987 backend => 'auto',
3988 max_array_rows => $max_rows,
3989 join_type => $join_type,
3990 ($left_key ne $right_key ? (join_map => {1 => $right_key}) : ()),
3991 ($right_label ? (collision_prefix => {1 => $right_label}) : ()),
3992 );
3993 5 push @joined, { label => $right_label, left_key => $left_key, right_key => $right_key };
3994 }
3995  
3996 715 ▶ $self->stash(schema_warnings => \@schema_warnings) if @schema_warnings;
Branch: 1 branch
BranchTrueFalseTotal
if @schema_warnings 0 715 715
3997  
3998 715 my $records = eval { $src->selectall_arrayref };
3999 715 ▶ return () if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 715 715
4000 715 ▶ $records //= [];
Condition50%1/2
$records //= []
l!l
7150
MC/DC0%0/1
$records //= []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
4001 715 my @columns = _get_columns($src, $records);
4002  
4003 # Combine (vertical stack): sets $src = undef since the result is a union
4004 # with no single aggregatable object.
4005 715 ▶ my @cspecs = @{ $self->every_param('c') // [] };
Condition50%1/2
$self->every_param("c") // []
l!l
7150
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
4006 715 ▶ if (@cspecs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cspecs) 24 691 715
4007 24 my @sources = ([$records, \@columns]);
4008 24 for my $cspec (@cspecs) {
4009 24 my ($csrc, $clabel) = $self->_open_spec($cspec);
4010 24 ▶ next unless $csrc;
Branch: 1 branch
BranchTrueFalseTotal
unless $csrc 17 7 24
4011 7 ▶ my $crecs = eval { $csrc->fetch_all } // [];
Condition50%1/2
eval { do { $csrc->fetch_all } } // []
l!l
70
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
4012 7 ▶ next if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 7 7
4013 7 my @ccols = _get_columns($csrc, $crecs);
4014 7 push @sources, [$crecs, \@ccols];
4015 7 push @combined, { label => $clabel };
4016 }
4017 24 ▶ if (@sources > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sources > 1) 7 17 24
4018 7 ($records, my $new_cols) = _combine_tables(\@sources);
4019 7 @columns = @$new_cols;
4020 7 $src = undef; # union: no single aggregatable source
4021 }
4022 }
4023  
4024 # What was actually joined and stacked, for the page that shows the rows.
4025 715 $self->stash(pipeline_joined => \@joined, pipeline_combined => \@combined);
4026  
4027 715 return ($src, $records, \@columns, $left_label);
4028 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4029  
4030 # _calc_spec_key($self) -> $spec
4031 #
4032 # Purpose: The key the stored calc fields, groups and date patterns are filed
4033 # under for this request: the l= spec, or the table a /view route is
4034 # addressed by, which names its spec explicitly because it has no l=.
4035 23 ▶sub _calc_spec_key :Protected ($self) {
Subroutine _calc_spec_key: called CC=5 SCAR=16.1
4036 23 ▶ my $l = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
716
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
4037 23 ▶ return canonical_spec($l) if length $l;
Branch: 1 branch
BranchTrueFalseTotal
if length $l 7 16 23
4038 16 my $table = $self->stash('table');
4039 16 ▶ return (defined $table && $table =~ /$TABLE_NAME_RE/) ? "table:$table" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $table && $table =~ /$TABLE_NAME_RE/u ? : 6 10 16
Condition100%3/3
defined $table and $table =~ /$TABLE_NAME_RE/u
!ll&&!rl&&r
916
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
4040 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4041  
4042 # _span_calc_spec($self, \@columns, @dimension_params) -> \%span | undef
4043 #
4044 # Purpose: Turn span=/tcol=/as= into the c= calculated field a reader could have
4045 # typed, so bucketing a dimension is one code path with one set of
4046 # semantics (Calc.pm's span()) rather than a second pipeline of its
4047 # own, and so a bucket works on every route at once.
4048 # Entry: \@columns -- the source's columns, so the column to bucket and the
4049 # name of the bucket are both checked before anything is
4050 # evaluated.
4051 # @dimension_params -- the params that name this route's dimension
4052 # (cat, x, rows, ...), in the order they should be tried.
4053 # Exit: undef when the request says nothing about bucketing. Otherwise
4054 # { calc => [ '<col>_span:span(<col>,<interval>)' ],
4055 # src => <column to bucket>, col => '<bucket column>' },
4056 # or { error => <message> } for a request that cannot be honoured,
4057 # which the caller renders as a 400 rather than drawing a chart of
4058 # something the reader did not ask for.
4059 # Notes: An ambiguous dimension is refused, not guessed: with rows=at,region
4060 # only tcol= knows which column the reader meant, and bucketing the
4061 # wrong one silently is worse than an error that says so. A name that
4062 # is already a column, or already a calculated field, is refused too,
4063 # because two definitions of one name is the bug that rule prevents.
4064 634 ▶sub _span_calc_spec :Protected ($self, $columns, @dimension_params) {
Subroutine _span_calc_spec: called CC=25 SCAR=32.5
4065 634 ▶ my $interval = $self->param('span') // '';
Condition100%2/2
$self->param("span") // ""
l!l
30604
MC/DC100%1/1
$self->param("span") // ""
$self->param("span")
Truth table100%2/2
A
A= $self->param("span")
Aresult
11
00
4066 634 ▶ my $tcol = $self->param('tcol') // '';
Condition100%2/2
$self->param("tcol") // ""
l!l
23611
MC/DC100%1/1
$self->param("tcol") // ""
$self->param("tcol")
Truth table100%2/2
A
A= $self->param("tcol")
Aresult
11
00
4067 634 ▶ my $as = $self->param('as') // '';
Condition100%2/2
$self->param("as") // ""
l!l
19615
MC/DC100%1/1
$self->param("as") // ""
$self->param("as")
Truth table100%2/2
A
A= $self->param("as")
Aresult
11
00
4068 634 ▶ return undef unless length($interval) || length($tcol);
Branch: 1 branch
BranchTrueFalseTotal
unless length $interval or length $tcol 595 39 634
Condition100%3/3
length $interval or length $tcol
l!l&&r!l&&!r
2811595
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
4069  
4070 39 ▶ return { error => $self->_i18n('error_span_tcol_orphan', $tcol) }
Branch: 1 branch
BranchTrueFalseTotal
if length $tcol and not length $interval 11 28 39
Condition100%3/3
length $tcol and not length $interval
!ll&&!rl&&r
171111
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
4071 if length($tcol) && !length($interval);
4072  
4073 28 require Database::BI::Calc;
4074 28 ▶ return { error => $self->_i18n('error_span_interval', $interval) }
Branch: 1 branch
BranchTrueFalseTotal
unless Database::BI::Calc::span_interval($interval) 15 13 28
4075 unless Database::BI::Calc::span_interval($interval);
4076  
4077 13 my %col_set = map { $_ => 1 } @$columns;
4078  
4079 13 my $col;
4080 13 ▶ if (length $tcol) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $tcol) { } 10 3 13
4081 return { error => $self->_i18n('error_span_tcol_unknown', $tcol) }
4082 10 ▶ unless $col_set{$tcol};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$tcol} 1 9 10
4083 9 $col = $tcol;
4084 } else {
4085 3 my @named = grep { length }
4086 3 ▶ map { split /,/, ($self->param($_) // ''), -1 } @dimension_params;
Condition100%2/2
$self->param($_) // ""
l!l
21
MC/DC100%1/1
$self->param($_) // ""
$self->param($_)
Truth table100%2/2
A
A= $self->param($_)
Aresult
11
00
4087 3 ▶ return { error => $self->_i18n('error_span_no_column') } unless @named == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @named == 1 2 1 3
4088 1 $col = $named[0];
4089 }
4090  
4091 # A bucket column is written in the calc grammar, so spaces in the column's
4092 # name arrive as underscores, exactly as a reader typing the expression
4093 # would have to write them.
4094 10 (my $expr_col = $col) =~ s/ /_/g;
4095 10 ▶ my $name = length($as) ? $as : "${expr_col}_span";
Branch: 1 branch
BranchTrueFalseTotal
length $as ? : 8 2 10
4096 10 ▶ return { error => $self->_i18n('error_span_name', $name) }
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/u 5 5 10
4097 unless $name =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/;
4098  
4099 5 ▶ 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
113
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
4100 4 my $found = 0;
4101 4 my $sk = $self->_calc_spec_key;
4102 4 ▶ my $stored = length($sk) ? (($self->_read_models)->{fields}{$sk} // {}) : {};
Branch: 1 branch
BranchTrueFalseTotal
length $sk ? : 0 4 4
Condition0%0/2
$self->_read_models->{"fields"}{$sk} // {}
l!l
00
MC/DC0%0/1
$self->_read_models->{"fields"}{$sk} // {}
$self->_read_models->{"fields"}{$sk}
Truth table0%0/2
A
A= $self->_read_models->{"fields"}{$sk}
Aresult
11
00
4103 4 ▶ $found = 1 if $stored->{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $stored->{$name} 0 4 4
4104 4 ▶ for my $spec (@{ $self->every_param('c') // [] }) {
Condition50%1/2
$self->every_param("c") // []
l!l
40
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
4105 1 ▶ next if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/i;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/iu 0 1 1
4106 1 my ($n) = $spec =~ /\A([A-Za-z_][A-Za-z0-9_]*):/;
4107 1 ▶ $found = 1 if defined $n && $n eq $name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $n and $n eq $name 1 0 1
Condition33%1/3
defined $n and $n eq $name
!ll&&!rl&&r
001
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
4108 }
4109 4 $found;
4110 };
4111 5 ▶ return { error => $self->_i18n('error_span_conflict', $name) } if $taken;
Branch: 1 branch
BranchTrueFalseTotal
if $taken 2 3 5
4112  
4113 return {
4114 3 src => $col,
4115 col => $name,
4116 calc => [ "$name:span($expr_col,'$interval')" ],
4117 };
4118 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4119  
4120 # _apply_date_normalization($self, $records, \@columns, $spec_key) -> void
4121 #
4122 # Reads date_patterns from .bi/models.json for $spec_key and normalises each
4123 # configured column's values to ISO-8601 in-place. A value that does not match
4124 # the stored pattern is left unchanged so YEAR/MONTH/etc. return undef (and the
4125 # row falls into the '(unparseable)' bucket in _grouped_totals).
4126 # Called at the top of _apply_calc_fields so registered patterns are applied
4127 # before any calc expression is evaluated.
4128 896 ▶sub _apply_date_normalization :Protected ($self, $records, $columns, $spec_key) {
Subroutine _apply_date_normalization: called CC=11 SCAR=24.0
4129 896 ▶ return unless defined $spec_key && length $spec_key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec_key and length $spec_key 13 883 896
Condition100%3/3
defined $spec_key and length $spec_key
!ll&&!rl&&r
112883
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
4130 883 my $models = $self->_read_models;
4131 883 my $patterns = $models->{date_patterns}{$spec_key};
4132 883 ▶ return unless $patterns && %{$patterns};
Branch: 1 branch
BranchTrueFalseTotal
unless $patterns and %{$patterns;} 880 3 883
Condition66%2/3
$patterns and %{$patterns;}
!ll&&!rl&&r
88003
MC/DC50%1/2
$patterns and %{$patterns;}
$patterns %{$patterns;}
Truth table66%2/3
A and B
A= $patternsB= %{$patterns;}
ABresult
0X0
100
111
4133 3 my %col_set = map { $_ => 1 } @{$columns};
4134 3 require Database::BI::Calc;
4135 3 for my $col (keys %{$patterns}) {
4136 3 ▶ next unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 1 2 3
4137 2 my $pat = $patterns->{$col};
4138 2 for my $row (@{$records}) {
4139 6 my $v = $row->{$col};
4140 6 ▶ next unless defined $v && length $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and length $v 2 4 6
Condition100%3/3
defined $v and length $v
!ll&&!rl&&r
114
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
4141 # Only overwrite when normalisation succeeds; leave unchanged on
4142 # mismatch so the row lands in the '(unparseable)' group.
4143 4 my $iso = Database::BI::Calc::date_normalise($v, $pat);
4144 4 ▶ $row->{$col} = $iso if defined $iso;
Branch: 1 branch
BranchTrueFalseTotal
if defined $iso 1 3 4
4145 }
4146 }
4147 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4148  
4149 # _lookups_of_request($self, $spec_key) -> @lookups
4150 #
4151 # Purpose: The lookups this request applies, in order: those stored for
4152 # $spec_key, by name, then each lk=<name> stored for another dataset,
4153 # less every nolk=<name>.
4154 # Entry: $spec_key files the stored lookups (the l= spec, or a canvas's).
4155 # Exit: A list of { name => $name, %definition }. Croaks error_lookup_unknown
4156 # for an lk= that names no stored lookup, and error_lookup_name for one
4157 # that is not an identifier.
4158 881 ▶sub _lookups_of_request :Protected ($self, $spec_key) {
Subroutine _lookups_of_request: called CC=14 SCAR=26.4
4159 881 my $all = $self->_read_models->{lookups};
4160 881 ▶ my %skip = map { $_ => 1 } @{ $self->every_param('nolk') // [] };
Condition50%1/2
$self->every_param("nolk") // []
l!l
8810
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
4161 881 ▶ 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' ? : 8 873 881
Condition100%5/5
length($spec_key // "") and ref $all->{$spec_key} eq "HASH"
!ll&&!rl&&r
88658
$spec_key // ""
l!l
8801
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
4162  
4163 881 my (@lookups, %seen);
4164 881 for my $name (sort keys %$own) {
4165 12 ▶ next if $skip{$name} || ref $own->{$name} ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if $skip{$name} or ref $own->{$name} ne "HASH" 5 7 12
Condition100%3/3
$skip{$name} or ref $own->{$name} ne "HASH"
l!l&&r!l&&!r
147
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
4166 7 push @lookups, { %{ $own->{$name} }, name => $name };
4167 7 $seen{$name} = 1;
4168 }
4169 881 ▶ for my $name (@{ $self->every_param('lk') // [] }) {
Condition50%1/2
$self->every_param("lk") // []
l!l
8810
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
4170 21 ▶ next if $seen{$name}++ || $skip{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$name}++ or $skip{$name} 2 19 21
Condition66%2/3
$seen{$name}++ or $skip{$name}
l!l&&r!l&&!r
0219
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
4171 19 ▶ croak $self->_i18n('error_lookup_name', $name) unless $name =~ $LOOKUP_NAME_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$LOOKUP_NAME_RE/u 15 4 19
4172 # Another dataset's lookup, the first by the order of the specs, so the
4173 # choice does not depend on how the store happens to be read.
4174 6 my ($def) = grep { ref $_ eq 'HASH' }
4175 4 map { $all->{$_}{$name} } sort keys %$all;
4176 4 ▶ croak $self->_i18n('error_lookup_unknown', $name) unless $def;
Branch: 1 branch
BranchTrueFalseTotal
unless $def 2 2 4
4177 2 push @lookups, { %$def, name => $name };
4178 }
4179 864 return @lookups;
4180 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4181  
4182 # _lookup_file($self, $name, $file) -> $path
4183 #
4184 # Purpose: Resolve a lookup's file= to the file it reads. A relative path is
4185 # under data_dir; an absolute one must be, after symlinks are resolved,
4186 # so a link inside data_dir cannot reach outside it.
4187 # Entry: $name names the lookup in the messages.
4188 # Exit: The resolved path as a string. Croaks error_lookup_remote (a URL or
4189 # another source spec, or a remote /../host/ path), error_lookup_outside,
4190 # error_lookup_not_found (missing, or not a supported extension) or
4191 # error_lookup_too_large (over $LOOKUP_MAX_BYTES).
4192 26 ▶sub _lookup_file :Protected ($self, $name, $file) {
Subroutine _lookup_file: called CC=10 SCAR=23.0
4193 26 ▶ $file //= '';
Condition100%2/2
$file //= ""
l!l
251
MC/DC100%1/1
$file //= ""
$file
Truth table100%2/2
A
A= $file
Aresult
11
00
4194 # Two letters at least before the colon, so C:\data is still a path.
4195 26 ▶ croak $self->_i18n('error_lookup_remote', $name, $file)
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ m[\A(?:[A-Za-z][A-Za-z0-9+.-]+:|/\.\./)]u 5 21 26
4196 if $file =~ m{\A(?:[A-Za-z][A-Za-z0-9+.-]+:|/\.\./)};
4197 21 ▶ croak $self->_i18n('error_lookup_not_found', $name, $file) unless length $file;
Branch: 1 branch
BranchTrueFalseTotal
unless length $file 2 19 21
4198  
4199 19 my $data_dir = _data_dir_for($self->app);
4200 19 my $given = Mojo::File->new($file);
4201 19 ▶ my $path = $given->is_abs ? $given : $data_dir->child($file);
Branch: 1 branch
BranchTrueFalseTotal
$given->is_abs ? : 2 17 19
4202 19 ▶ croak $self->_i18n('error_lookup_outside', $name, $file)
Branch: 1 branch
BranchTrueFalseTotal
unless _inside_dir(_canonical_path($path), _canonical_path($data_dir)) 4 15 19
4203 unless _inside_dir(_canonical_path($path), _canonical_path($data_dir));
4204 15 ▶ croak $self->_i18n('error_lookup_not_found', $name, $file)
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path and $path->basename =~ /$EXT_RE/u 3 12 15
Condition100%3/3
-f $path and $path->basename =~ /$EXT_RE/u
!ll&&!rl&&r
2112
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
4205 unless -f $path && $path->basename =~ $EXT_RE;
4206 12 ▶ my $size = -s $path // 0;
Condition50%1/2
-s $path // 0
l!l
120
MC/DC0%0/1
-s $path // 0
-s $path
Truth table50%1/2
A
A= -s $path
Aresult
11
00
4207 12 ▶ croak $self->_i18n('error_lookup_too_large', $name, $file, $size, $LOOKUP_MAX_BYTES)
Branch: 1 branch
BranchTrueFalseTotal
if $size > $LOOKUP_MAX_BYTES 1 11 12
4208 if $size > $LOOKUP_MAX_BYTES;
4209 11 return _canonical_path($path);
4210 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4211  
4212 # _load_lookup($self, $lookup) -> \%entry
4213 #
4214 # Purpose: Read a lookup's file into a map from key to row, once per request.
4215 # Entry: $lookup is one entry of _lookups_of_request.
4216 # Exit: { map => { key => \%row }, fields => \@names, file => $basename }.
4217 # Keys are compared as strings after trimming, case-sensitively; a
4218 # duplicate key keeps its first row and is logged once. Croaks one of
4219 # _lookup_file's errors, error_lookup_unreadable, error_lookup_key_unknown
4220 # or error_lookup_field_unknown.
4221 # Side Effects: Caches the entry in the stash, keyed by name, path and mtime.
4222 11 ▶sub _load_lookup :Protected ($self, $lookup) {
Subroutine _load_lookup: called CC=18 SCAR=29.2
4223 11 my $name = $lookup->{name};
4224 11 my $path = $self->_lookup_file($name, $lookup->{file});
4225 9 my $file = Mojo::File->new($path)->basename;
4226 9 ▶ my $memo = $self->stash('_lookup_maps') // {};
Condition100%2/2
$self->stash("_lookup_maps") // {}
l!l
36
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
4227 my $tag = join "\0", $name, $path, (stat $path)[9] // 0,
4228 9 ▶ $lookup->{key} // '', @{ ref $lookup->{fields} eq 'ARRAY' ? $lookup->{fields} : [] };
Branch: 1 branch
BranchTrueFalseTotal
ref $lookup->{'fields'} eq 'ARRAY' ? : 5 4 9
Condition50%2/4
(stat $path)[9] // 0
l!l
90
$lookup->{"key"} // ""
l!l
90
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
4229 9 ▶ return $memo->{$tag} if $memo->{$tag};
Branch: 1 branch
BranchTrueFalseTotal
if $memo->{$tag} 1 8 9
4230  
4231 8 (my $table = $file) =~ s/\.[^.]+\z//;
4232 8 my ($src, $rows);
4233 8 my $ok = eval {
4234 8 $src = $self->open_table($table, directory => Mojo::File->new($path)->dirname->to_string);
4235 8 $rows = $src->fetch_all;
4236 8 1;
4237 };
4238 8 ▶ croak $self->_i18n('error_lookup_unreadable', $name, $file, _tidy_error($@)) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 8 8
4239  
4240 8 my @columns = _get_columns($src, $rows);
4241 8 my %has = map { $_ => 1 } @columns;
4242 8 ▶ my $key = $lookup->{key} // '';
Condition50%1/2
$lookup->{"key"} // ""
l!l
80
MC/DC0%0/1
$lookup->{"key"} // ""
$lookup->{"key"}
Truth table50%1/2
A
A= $lookup->{"key"}
Aresult
11
00
4243 8 ▶ croak $self->_i18n('error_lookup_key_unknown', $name, $key, $file) unless $has{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $has{$key} 1 7 8
4244  
4245 5 my @fields = ref $lookup->{fields} eq 'ARRAY' && @{ $lookup->{fields} }
4246 5 ? @{ $lookup->{fields} }
4247 7 ▶ : grep { $_ ne $key } @columns;
Branch: 1 branch
BranchTrueFalseTotal
ref $lookup->{'fields'} eq 'ARRAY' && @{$lookup->{'fields'};} ? : 5 2 7
Condition66%2/3
ref $lookup->{"fields"} eq "ARRAY" and @{$lookup->{"fields"};}
!ll&&!rl&&r
205
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
4248 7 for my $f (@fields) {
4249 9 ▶ croak $self->_i18n('error_lookup_field_unknown', $name, $f, $file) unless $has{$f};
Branch: 1 branch
BranchTrueFalseTotal
unless $has{$f} 1 8 9
4250 }
4251  
4252 6 my (%map, $duplicates);
4253 6 for my $row (@$rows) {
4254 17 my $k = _lookup_key($row->{$key});
4255 17 ▶ next unless defined $k && length $k;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $k and length $k 0 17 17
Condition33%1/3
defined $k and length $k
!ll&&!rl&&r
0017
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
4256 17 ▶ if (exists $map{$k}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $map{$k}) 5 12 17
4257 5 $duplicates++;
4258 5 next;
4259 }
4260 12 $map{$k} = { map { $_ => $row->{$_} } @fields };
4261 }
4262 6 ▶ $self->app->log->warn($self->_i18n('warn_lookup_duplicate_key', $name, $duplicates, $file))
Branch: 1 branch
BranchTrueFalseTotal
if $duplicates 5 1 6
4263 if $duplicates;
4264  
4265 6 $memo->{$tag} = { map => \%map, fields => \@fields, file => $file };
4266 6 $self->stash('_lookup_maps' => $memo);
4267 6 return $memo->{$tag};
4268 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4269  
4270 # _lookup_key($value) -> $key | undef
4271 #
4272 # Purpose: The form in which a lookup compares a key: the string, trimmed. Case
4273 # and everything else are left as they are, so "ab" and "AB" are two keys.
4274 30 ▶sub _lookup_key {
Subroutine _lookup_key: called CC=3 SCAR=11.0
4275 30 my ($v) = @_;
4276 30 ▶ return undef unless defined $v && !ref $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and not ref $v 2 28 30
Condition100%3/3
defined $v and not ref $v
!ll&&!rl&&r
1128
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
4277 28 (my $k = $v) =~ s/\A\s+|\s+\z//g;
4278 28 return $k;
4279 }
4280  
4281 # _apply_lookups($self, $records, \@cols, $spec_key) -> void
4282 #
4283 # Purpose: Stage 3 of the pipeline: each lookup the request applies adds its
4284 # fields to every row, read from the lookup file's row whose key equals
4285 # the row's own (col=, which defaults to the key's name). A row whose
4286 # key is missing gets the lookup's default, or undef.
4287 # Entry: \@cols is the column list so far; it gains the new columns.
4288 # Exit: Rows are replaced through _extend_row where they must be. The new
4289 # columns are virtual, so an aggregate that groups by one is folded in
4290 # Perl. Croaks with a message for a bad lookup or a missing column.
4291 # Notes: A field lands under its own name unless a column has it, and then
4292 # under <lookup>_<field>; a source column is never overwritten. The
4293 # columns this pass wrote do not count as taken when it runs again in
4294 # the same request, so the names a page gets do not depend on how
4295 # many times the stage has run over it.
4296 876 ▶sub _apply_lookups :Protected ($self, $records, $cols, $spec_key) {
Subroutine _apply_lookups: called CC=17 SCAR=28.4
4297 876 my @lookups = $self->_lookups_of_request($spec_key);
4298 861 ▶ return unless @lookups;
Branch: 1 branch
BranchTrueFalseTotal
unless @lookups 857 4 861
4299  
4300 4 ▶ my $written = $self->stash('_lookup_written') // {};
Condition50%1/2
$self->stash("_lookup_written") // {}
l!l
04
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
4301 4 my %taken = map { $_ => 1 } grep { !$written->{$_} } @$cols;
4302 4 for my $lookup (@lookups) {
4303 4 my $name = $lookup->{name};
4304 4 my $entry = $self->_load_lookup($lookup);
4305 4 ▶ my $col = length($lookup->{col} // '') ? $lookup->{col} : $lookup->{key};
Branch: 1 branch
BranchTrueFalseTotal
length($lookup->{'col'} // '') ? : 1 3 4
Condition100%2/2
$lookup->{"col"} // ""
l!l
13
MC/DC100%1/1
$lookup->{"col"} // ""
$lookup->{"col"}
Truth table100%2/2
A
A= $lookup->{"col"}
Aresult
11
00
4306 croak $self->_i18n('error_lookup_col_unknown', $name, $col, $name)
4307 4 ▶ unless $taken{$col} || $written->{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $taken{$col} or $written->{$col} 1 3 4
Condition66%2/3
$taken{$col} or $written->{$col}
l!l&&r!l&&!r
301
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
4308  
4309 3 my @out;
4310 3 for my $f (@{ $entry->{fields} }) {
4311 3 ▶ my $as = $taken{$f} ? "${name}_$f" : $f;
Branch: 1 branch
BranchTrueFalseTotal
$taken{$f} ? : 2 1 3
4312 3 ▶ croak $self->_i18n('error_lookup_name_taken', $name, $f, $as) if $taken{$as};
Branch: 1 branch
BranchTrueFalseTotal
if $taken{$as} 1 2 3
4313 2 $taken{$as} = 1;
4314 2 push @out, [ $f, $as ];
4315 }
4316  
4317 2 my $default = $lookup->{default};
4318 2 my $map = $entry->{map};
4319 2 for my $i (0 .. $#$records) {
4320 6 my $k = _lookup_key($records->[$i]{$col});
4321 6 ▶ my $hit = defined $k ? $map->{$k} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $k ? : 6 0 6
4322 6 for my $pair (@out) {
4323 $records->[$i] = _extend_row($records->[$i], $pair->[1],
4324 6 ▶ $hit ? $hit->{ $pair->[0] } : $default);
Branch: 1 branch
BranchTrueFalseTotal
$hit ? : 4 2 6
4325 }
4326 }
4327  
4328 2 my %have = map { $_ => 1 } @$cols;
4329 2 push @$cols, grep { !$have{$_} } map { $_->[1] } @out;
4330 2 ▶ $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->stash("_virtual_columns") 2 0 2
4331 2 for my $pair (@out) {
4332 2 $self->stash('_virtual_columns')->{ $pair->[1] } = 1;
4333 2 $written->{ $pair->[1] } = 1;
4334 }
4335 }
4336 2 $self->stash('_lookup_written' => $written);
4337 2 return;
4338 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4339  
4340 # _compile_extraction($self, $name, \%definition) -> (\%compiled, \@fields)
4341 #
4342 # Purpose: Check a stored extraction and compile its pattern, the same way on
4343 # save and on every request.
4344 # Exit: The compiled pattern (Calc::compile_pattern) and the named groups it
4345 # writes: fields= when it was given, else every named group, in order.
4346 # Croaks error_extract_pattern (wrapping Calc's reason),
4347 # error_extract_no_names or error_extract_field.
4348 13 ▶sub _compile_extraction :Protected ($self, $name, $def) {
Subroutine _compile_extraction: called CC=7 SCAR=19.5
4349 13 require Database::BI::Calc;
4350 13 my $compiled = eval { Database::BI::Calc::compile_pattern($def->{pattern}) };
4351 13 ▶ croak $self->_i18n('error_extract_pattern', $name, _tidy_error($@)) unless $compiled;
Branch: 1 branch
BranchTrueFalseTotal
unless $compiled 4 9 13
4352 9 my @names = @{ $compiled->{names} };
4353 9 ▶ croak $self->_i18n('error_extract_no_names', $name) unless @names;
Branch: 1 branch
BranchTrueFalseTotal
unless @names 2 7 9
4354 7 my %named = map { $_ => 1 } @names;
4355 7 ▶ my @fields = ref $def->{fields} eq 'ARRAY' && @{ $def->{fields} } ? @{ $def->{fields} } : @names;
Branch: 1 branch
BranchTrueFalseTotal
ref $def->{'fields'} eq 'ARRAY' && @{$def->{'fields'};} ? : 2 5 7
Condition66%2/3
ref $def->{"fields"} eq "ARRAY" and @{$def->{"fields"};}
!ll&&!rl&&r
502
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
4356 7 for my $f (@fields) {
4357 8 ▶ croak $self->_i18n('error_extract_field', $name, $f) unless $named{$f};
Branch: 1 branch
BranchTrueFalseTotal
unless $named{$f} 1 7 8
4358 }
4359 6 return ($compiled, \@fields);
4360 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4361  
4362 # _apply_extractions($self, $records, \@cols, $spec_key) -> void
4363 #
4364 # Purpose: The stored extractions of $spec_key, after the lookups in stage 3:
4365 # each named group of a pattern becomes a column, read from the column
4366 # the extraction names. A row the pattern does not match, or whose
4367 # cell is empty, gets '(unparseable)', so it groups visibly rather than
4368 # vanishing; a group that took no part in a match is ''.
4369 # Entry: \@cols is the column list so far; it gains the new columns.
4370 # Exit: Croaks with a message for a bad pattern or a missing column.
4371 # Notes: Columns are named as a lookup's are: the group's own name unless a
4372 # column has it, then <extraction>_<group>. A capture is cut to 200
4373 # characters (Calc::capture_of).
4374 861 ▶sub _apply_extractions :Protected ($self, $records, $cols, $spec_key) {
Subroutine _apply_extractions: called CC=19 SCAR=29.5
4375 861 ▶ return unless length($spec_key // '');
Branch: 1 branch
BranchTrueFalseTotal
unless length($spec_key // "") 8 853 861
Condition100%2/2
$spec_key // ""
l!l
8601
MC/DC100%1/1
$spec_key // ""
$spec_key
Truth table100%2/2
A
A= $spec_key
Aresult
11
00
4376 853 my $stored = $self->_read_models->{extractions}{$spec_key};
4377 853 ▶ return unless ref $stored eq 'HASH' && %$stored;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $stored eq "HASH" and %$stored 849 4 853
Condition66%2/3
ref $stored eq "HASH" and %$stored
!ll&&!rl&&r
84904
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
4378  
4379 4 ▶ my $written = $self->stash('_extract_written') // {};
Condition50%1/2
$self->stash("_extract_written") // {}
l!l
04
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
4380 4 my %taken = map { $_ => 1 } grep { !$written->{$_} } @$cols;
4381 4 for my $name (sort keys %$stored) {
4382 4 my $def = $stored->{$name};
4383 4 ▶ next unless ref $def eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $def eq "HASH" 1 3 4
4384 3 my ($compiled, $fields) = $self->_compile_extraction($name, $def);
4385 3 ▶ my $col = $def->{col} // '';
Condition50%1/2
$def->{"col"} // ""
l!l
30
MC/DC0%0/1
$def->{"col"} // ""
$def->{"col"}
Truth table50%1/2
A
A= $def->{"col"}
Aresult
11
00
4386 croak $self->_i18n('error_extract_col_unknown', $name, $col)
4387 3 ▶ unless $taken{$col} || $written->{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $taken{$col} or $written->{$col} 1 2 3
Condition66%2/3
$taken{$col} or $written->{$col}
l!l&&r!l&&!r
201
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
4388  
4389 2 my @out;
4390 2 for my $f (@$fields) {
4391 2 ▶ my $as = $taken{$f} ? "${name}_$f" : $f;
Branch: 1 branch
BranchTrueFalseTotal
$taken{$f} ? : 1 1 2
4392 2 ▶ croak $self->_i18n('error_extract_name_taken', $name, $f, $as) if $taken{$as};
Branch: 1 branch
BranchTrueFalseTotal
if $taken{$as} 1 1 2
4393 1 $taken{$as} = 1;
4394 1 push @out, [ $f, $as ];
4395 }
4396  
4397 # The groups were checked against the pattern, so undef is a row it
4398 # does not match, and a group that took no part is ''.
4399 1 for my $i (0 .. $#$records) {
4400 3 my $v = $records->[$i]{$col};
4401 3 for my $pair (@out) {
4402 3 my $got = Database::BI::Calc::capture_of($compiled, $v, $pair->[0]);
4403 3 ▶ $records->[$i] = _extend_row($records->[$i], $pair->[1], $got // '(unparseable)');
Condition100%2/2
$got // "(unparseable)"
l!l
21
MC/DC100%1/1
$got // "(unparseable)"
$got
Truth table100%2/2
A
A= $got
Aresult
11
00
4404 }
4405 }
4406  
4407 1 my %have = map { $_ => 1 } @$cols;
4408 1 push @$cols, grep { !$have{$_} } map { $_->[1] } @out;
4409 1 ▶ $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->stash("_virtual_columns") 1 0 1
4410 1 for my $pair (@out) {
4411 1 $self->stash('_virtual_columns')->{ $pair->[1] } = 1;
4412 1 $written->{ $pair->[1] } = 1;
4413 }
4414 }
4415 2 $self->stash('_extract_written' => $written);
4416 2 return;
4417 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4418  
4419 # _extend_row($row, $name, $value) -> $row | \%copy
4420 #
4421 # Purpose: Write a virtual column into a row that came out of a source. A row
4422 # from a SQL-backed source arrives with its key set locked (the backend
4423 # locks it so that reading a column that is not there fails loudly),
4424 # and a locked row cannot take a new key in place: the assignment raises
4425 # "Attempt to access disallowed key". Such a row is replaced by an
4426 # unlocked copy of itself carrying the new cell, which the rest of the
4427 # pipeline reads exactly as it reads any other row.
4428 # Entry: $row -- the row hashref; $name -- the column to add; $value -- its value.
4429 # Exit: $row itself when it can take the key (already present, or writable),
4430 # otherwise a new hashref.
4431 # Notes: Only a *new* key is a problem -- writing a key a locked row already
4432 # has is allowed -- so the common case (a CSV-backed source, and any
4433 # repeated evaluation) copies nothing.
4434 46 ▶sub _extend_row {
Subroutine _extend_row: called CC=3 SCAR=11.0
4435 46 my ($row, $name, $value) = @_;
4436 46 ▶ return $row if ref $row ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $row ne "HASH" 2 44 46
4437 44 require Hash::Util;
4438 44 ▶ unless (Hash::Util::hashref_locked($row)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (Hash::Util::hashref_locked($row)) 41 3 44
4439 41 $row->{$name} = $value;
4440 41 return $row;
4441 }
4442 3 return { %$row, $name => $value };
4443 }
4444  
4445 # _write_calc_column($self, $records, \@cols, $name, $calc)
4446 #
4447 # Purpose: Evaluate one compiled calculated field over the rows and write it as
4448 # a column, recording it as virtual so _grouped_totals skips the SQL
4449 # push path. \@cols gains the name if it is new.
4450 13 ▶sub _write_calc_column :Protected ($self, $records, $cols, $name, $calc) {
Subroutine _write_calc_column: called CC=7 SCAR=19.5
4451 13 my $undef_count = 0;
4452 13 for my $i (0 .. $#$records) {
4453 26 my $row = $records->[$i];
4454 26 my $val = $calc->evaluate($row);
4455 26 ▶ $undef_count++ unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 4 22 26
4456 # Store '(unparseable)' rather than undef so that pivot/bar
4457 # grouping (which skips empty-string keys) keeps these rows in a
4458 # visible '(unparseable)' bucket rather than silently dropping them.
4459 # See _extend_row for why the row may have to be replaced.
4460 26 ▶ $records->[$i] = _extend_row($row, $name,
Branch: 1 branch
BranchTrueFalseTotal
defined $val ? : 22 4 26
4461 defined $val ? $val : '(unparseable)');
4462 }
4463 13 ▶ if ($undef_count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($undef_count) 2 11 13
4464 2 $self->app->log->warn($self->_i18n('warn_calc_undef', $name, $undef_count));
4465 }
4466 13 ▶ push @$cols, $name unless grep { $_ eq $name } @$cols;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $name;} @$cols 12 1 13
4467 13 ▶ $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->stash("_virtual_columns") 9 4 13
4468 13 $self->stash('_virtual_columns')->{$name} = 1;
4469 13 return;
4470 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4471  
4472 # _apply_held_calc_fields($self, $records, \@columns, $card) -> ($records, \@columns)
4473 #
4474 # Purpose: Stage 7 of the pipeline: the calculated fields stage 4 held back,
4475 # now that the cross-row columns they name exist. Each was checked
4476 # against those names when it was held, so a failure here is reported
4477 # as any other compile failure is.
4478 # Entry: $card is true for a canvas card. A canvas holds a field for any
4479 # card's plan, so a field that does not compile against this card's
4480 # columns belongs to another card, and this card goes without it.
4481 # Exit: The rows and columns, extended. The list is a new array, and both
4482 # come back as they arrived when nothing is held.
4483 3 ▶sub _apply_held_calc_fields :Protected ($self, $records, $columns, $card = 0) {
Subroutine _apply_held_calc_fields: called CC=9 SCAR=22.5
4484 3 my $held = $self->stash('_held_calc_fields');
4485 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
4486  
4487 2 require Database::BI::Calc;
4488 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
4489 2 for my $cs (@$held) {
4490 my $calc = Database::BI::Calc->new(
4491 expr => $cs->{expr},
4492 columns => \@cols,
4493 params => $cs->{params},
4494 4 );
4495 4 ▶ if ($calc->has_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($calc->has_error) 2 2 4
4496 2 ▶ next if $card;
Branch: 1 branch
BranchTrueFalseTotal
if $card 1 1 2
4497 1 croak $self->_i18n('error_calc_compile', $cs->{name}, $calc->error);
4498 }
4499 2 $self->_write_calc_column($records, \@cols, $cs->{name}, $calc);
4500 }
4501 1 return ($records, \@cols);
4502 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4503  
4504 # _cross_row_aliases(@specs) -> @names
4505 #
4506 # Purpose: The columns a list of cs= specs will add: the third field of each.
4507 # Only names are wanted, so a malformed spec simply has none; refusing
4508 # it is the work of _cross_row_specs_from.
4509 878 ▶sub _cross_row_aliases {
Subroutine _cross_row_aliases: called CC=4 SCAR=13.9
4510 878 ▶ return map { (split /:/, $_, 4)[2] // () } grep { defined && !ref && length } @_;
Condition88%8/9
(split(/:/u, $_, 4))[2] // ()
l!l&&r!l&&!r
8300
defined $_ && !ref($_) && length $_
!ll&&!rl&&r
2338
defined $_ and not ref $_
!ll&&!rl&&r
1141
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
4511 }
4512  
4513 # _cross_row_written($self) -> @names
4514 #
4515 # Purpose: The columns this request writes at stages 6 and 7: the cs= aliases and
4516 # the calculated fields held back for them. A filter on one of these
4517 # has to run after them.
4518 16 ▶sub _cross_row_written {
Subroutine _cross_row_written: called CC=3 SCAR=11.0
4519 16 my ($self) = @_;
4520 return (
4521 16 ▶ _cross_row_aliases(@{ $self->every_param('cs') // [] }),
Condition50%1/2
$self->every_param("cs") // []
l!l
160
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
4522 16 ▶ map { $_->{name} } @{ $self->stash('_held_calc_fields') // [] },
Condition100%2/2
$self->stash("_held_calc_fields") // []
l!l
151
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
4523 );
4524 }
4525  
4526 # _canvas_window_columns($analysis, $params, \@more) -> \@names
4527 #
4528 # Purpose: Every column a cross-row plan may add on this canvas: the page's cs=,
4529 # read from $params, and each card's own plan. \@more holds cards that
4530 # are not on the canvas yet: one being added, or being given a new plan.
4531 44 ▶sub _canvas_window_columns {
Subroutine _canvas_window_columns: called CC=8 SCAR=20.8
4532 44 my ($analysis, $params, $more) = @_;
4533 44 ▶ my @specs = @{ $params->every_param('cs') // [] };
Condition50%1/2
$params->every_param("cs") // []
l!l
440
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
4534 44 ▶ for my $vis (@{ $analysis->{visuals} // [] }, @{ $more // [] }) {
Condition100%4/4
$analysis->{"visuals"} // []
l!l
422
$more // []
l!l
539
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
4535 next unless ref $vis eq 'HASH' && ref $vis->{cross_row} eq 'HASH'
4536 50 ▶ && 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" 48 2 50
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
4712
ref $vis eq "HASH" and ref $vis->{"cross_row"} eq "HASH"
!ll&&!rl&&r
1463
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
4537 2 push @specs, @{ $vis->{cross_row}{cs} };
4538 }
4539 44 return [ _cross_row_aliases(@specs) ];
4540 }
4541  
4542 # _canvas_cross_filter($self, $records, \@columns, \@specs) -> ($records, \@late)
4543 #
4544 # Purpose: Apply a canvas's cross-filter to a card's rows, except any spec on a
4545 # column a cross-row plan writes. That column does not exist yet, so
4546 # the spec comes back for _render_visual_html to apply after the pass.
4547 7 ▶sub _canvas_cross_filter :Protected ($self, $records, $columns, $specs) {
Subroutine _canvas_cross_filter: called CC=6 SCAR=17.9
4548 3 my %written = map { $_ => 1 }
4549 7 ▶ @{ $self->stash('_canvas_window_names') // [] },
Condition100%2/2
$self->stash("_canvas_window_names") // []
l!l
61
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
4550 7 ▶ map { $_->{name} } @{ $self->stash('_held_calc_fields') // [] };
Condition100%2/2
$self->stash("_held_calc_fields") // []
l!l
61
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
4551 7 delete @written{ @$columns };
4552 7 my @late;
4553 7 for my $spec (@$specs) {
4554 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
4555 2 push @late, $spec;
4556 2 next;
4557 }
4558 4 $records = _apply_filter_spec($records, $spec);
4559 }
4560 7 return ($records, \@late);
4561 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4562  
4563 # _calc_specs_of_request($self) -> @specs
4564 #
4565 # Purpose: The calculated fields among the request's c= params, leaving out the
4566 # files it stacks, which share that parameter.
4567 213 ▶sub _calc_specs_of_request :Protected ($self) {
Subroutine _calc_specs_of_request: called CC=2 SCAR=7.1
4568 213 ▶ return grep { !/\A(?:path|table|url|redis|mariadb):/i } @{ $self->every_param('c') // [] };
Condition50%1/2
$self->every_param("c") // []
l!l
2130
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
4569 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4570  
4571 # _page_columns($self, $source, $records, $spec_key) -> ($records, \@columns) | ()
4572 #
4573 # Purpose: The columns of a table page from _fetch_page, with the calculated
4574 # fields and any span= bucket drawn on its rows. A page is one slice,
4575 # so _fetch_page has already run them over the whole set if a filter or
4576 # a window needed them; this pass is what puts them on the page.
4577 # Entry: $spec_key files the stored fields: the page's left_spec.
4578 # Exit: The rows and columns; or the empty list after rendering a 400, and the
4579 # caller returns.
4580 166 ▶sub _page_columns :Protected ($self, $source, $records, $spec_key) {
Subroutine _page_columns: called CC=7 SCAR=19.6
4581 166 my @columns = _get_columns($source, $records);
4582 166 my %seen_col = map { $_ => 1 } @columns;
4583 # Stage 6 wrote its columns onto the rows before the page was sliced, so the
4584 # list is what makes the table show them, and lets a field below read one.
4585 0 ▶ push @columns, grep { !$seen_col{$_}++ } @{ $self->stash('_cross_row_columns') // [] };
Condition50%1/2
$self->stash("_cross_row_columns") // []
l!l
0166
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
4586 # Nothing to draw a field from: a source with no declared columns and no rows.
4587 166 ▶ return ($records, \@columns) unless @columns;
Branch: 1 branch
BranchTrueFalseTotal
unless @columns 1 165 166
4588  
4589 # span= adds a bucket column to the table rather than grouping it: a table has
4590 # no dimension to bucket *into*, so the reader gets the column and the raw
4591 # value beside it. See _span_calc_spec.
4592 165 my $span = $self->_span_calc_spec(\@columns, ());
4593 165 ▶ if ($span && $span->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($span and $span->{"error"}) 5 160 165
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
16005
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
4594 5 $self->render(text => $span->{error}, status => 400);
4595 5 return ();
4596 }
4597  
4598 160 my ($calc_records, $calc_columns) = eval {
4599 $self->_calc_for_page($records, \@columns, {
4600 spec_key => $spec_key,
4601 160 ▶ ($span ? (calc => $span->{calc}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 160 160
4602 })
4603 };
4604 160 ▶ unless ($calc_records) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($calc_records) 1 159 160
4605 # Every location croak added on the way up, not only the last.
4606 1 $self->render(text => _tidy_error($@), status => 400);
4607 1 return ();
4608 }
4609 159 return ($calc_records, $calc_columns);
4610 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4611  
4612 # _calc_for_page($self, $records, \@columns, \%extra) -> ($records, \@columns)
4613 #
4614 # Purpose: _apply_calc_fields for a table page, which must still be drawn when a
4615 # definition saved for its data cannot be applied -- a lookup file that
4616 # is gone, a column an extraction or a field reads that the file no
4617 # longer has. Every chart and export of that data refuses with the
4618 # reason, and the panels that mend a definition are on the table page,
4619 # so a page that refused too would leave the reader no way back.
4620 # Entry: As _apply_calc_fields; $extra->{spec_key} files the definitions.
4621 # Exit: As _apply_calc_fields. When the first pass croaks and a second one
4622 # without the saved fields, lookups and extractions succeeds, returns
4623 # that, with stash stored_error holding the first pass's reason and
4624 # _skip_stored set for the rest of the request. Otherwise croaks with
4625 # the first pass's error, so a mistake in the request's own c= is the
4626 # 400 it always was.
4627 # Side Effects: The first pass runs on a copy of the rows when anything is
4628 # saved, so a pass that failed half way leaves nothing on them.
4629 177 ▶sub _calc_for_page :Protected ($self, $records, $columns, $extra) {
Subroutine _calc_for_page: called CC=9 SCAR=23.0
4630 177 ▶ 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
01734
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
4631 177 ▶ my $rows = $stored ? [ map { ref $_ eq 'HASH' ? { %$_ } : $_ } @$records ] : $records;
Branch: 2 branches
BranchTrueFalseTotal
$stored ? : 4 173 177
ref $_ eq 'HASH' ? : 21 0 21
4632 177 my @got = eval { $self->_apply_calc_fields($rows, $columns, $extra) };
4633 177 ▶ return @got if @got && $got[0];
Branch: 1 branch
BranchTrueFalseTotal
if @got and $got[0] 172 5 177
Condition66%2/3
@got and $got[0]
!ll&&!rl&&r
50172
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
4634 5 my $error = $@;
4635 5 ▶ croak $error unless $stored;
Branch: 1 branch
BranchTrueFalseTotal
unless $stored 2 3 5
4636  
4637 3 $self->stash('_skip_stored' => 1);
4638 3 @got = eval { $self->_apply_calc_fields($records, $columns, $extra) };
4639 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
4640 0 $self->stash('_skip_stored' => 0);
4641 0 croak $error;
4642 }
4643 3 $self->stash(stored_error => _tidy_error($error));
4644 3 return @got;
4645 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4646  
4647 # _has_stored_columns($self, $spec_key) -> $bool
4648 #
4649 # Purpose: Whether anything saved for $spec_key adds columns that can fail: a
4650 # calculated field, a lookup (its own, or another's through lk=) or an
4651 # extraction.
4652 # Entry: $spec_key may be undef, when the request's l= is the key.
4653 # Exit: True or false.
4654 182 ▶sub _has_stored_columns :Protected ($self, $spec_key) {
Subroutine _has_stored_columns: called CC=9 SCAR=22.3
4655 182 ▶ $spec_key = canonical_spec($spec_key // $self->param('l') // '');
Condition60%3/5
($spec_key // $self->param("l")) // ""
l!l
1820
$spec_key // $self->param("l")
l!l&&r!l&&!r
18110
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
4656 182 ▶ return 1 if @{ $self->every_param('lk') // [] };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->every_param("lk") // [];} 4 178 182
Condition50%1/2
$self->every_param("lk") // []
l!l
1820
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
4657 178 ▶ return 0 unless length $spec_key;
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec_key 1 177 178
4658 177 my $models = $self->_read_models;
4659 177 for my $kind (qw(fields lookups extractions)) {
4660 525 my $set = $models->{$kind}{$spec_key};
4661 525 ▶ return 1 if ref $set eq 'HASH' && %$set;
Branch: 1 branch
BranchTrueFalseTotal
if ref $set eq "HASH" and %$set 3 522 525
Condition66%2/3
ref $set eq "HASH" and %$set
!ll&&!rl&&r
52203
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
4662 }
4663 174 return 0;
4664 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4665  
4666 # _apply_calc_fields($self, $records, \@columns, \%extra) -> ($records, \@columns)
4667 #
4668 # Reads ?c=<name>:<expression> params (those NOT matching a path:/table:/url:/redis:/mariadb:
4669 # source spec) and compiles each via Database::BI::Calc. Evaluates per row,
4670 # appending the virtual column to each row hashref. Croaks on compile error
4671 # (caller renders 400); runtime undef values are logged at warn level.
4672 # Later ?c= specs may reference names defined by earlier ones (evaluated in order).
4673 #
4674 # Optional \%extra keys:
4675 # params => \%hash -- named parameter values bound from the URL (?p.name=val)
4676 # passed to Calc->new so expressions may reference them.
4677 # spec_key => $str -- override the l= spec key used to look up stored calc
4678 # fields (canvas context where ?l= is absent).
4679 # calc => \@specs -- additional ?c=-style specs, for a canvas whose query
4680 # string arrived with the request rather than as the
4681 # request's own parameters.
4682 # window_columns => \@names -- the columns the cross-row pass will add, for a
4683 # canvas, whose plans are not the request's own cs=.
4684 #
4685 # A field that needs a cross-row column cannot run yet: stage 6 comes after the
4686 # filters this stage feeds. So a field that fails to compile, and would compile
4687 # once those columns exist, is held back for _apply_held_calc_fields. Any other
4688 # failure is still the error it always was, a mistyped name included, so holding
4689 # cannot hide a mistake, and with no cs= nothing is ever held.
4690 874 ▶sub _apply_calc_fields :Protected ($self, $records, $columns, $extra = undef) {
Subroutine _apply_calc_fields: called CC=41 SCAR=37.7
4691 874 ▶ my $bound_params = ($extra // {})->{params} // {};
Condition100%4/4
+($extra // {})->{"params"} // {}
l!l
43831
$extra // {}
l!l
223651
MC/DC100%1/1
+($extra // {})->{"params"} // {}
$extra
Truth table100%2/2
A
A= $extra
Aresult
11
00
4692 874 ▶ my $spec_key_override = ($extra // {})->{spec_key};
Condition100%2/2
$extra // {}
l!l
223651
MC/DC100%1/1
$extra // {}
$extra
Truth table100%2/2
A
A= $extra
Aresult
11
00
4693 874 ▶ my $extra_calc = ($extra // {})->{calc} // [];
Condition100%4/4
+($extra // {})->{"calc"} // []
l!l
26848
$extra // {}
l!l
223651
MC/DC100%1/1
+($extra // {})->{"calc"} // []
$extra
Truth table100%2/2
A
A= $extra
Aresult
11
00
4694  
4695 # Normalise date columns before evaluating expressions so that date
4696 # functions (YEAR, MONTH, etc.) see ISO-8601 values even when the source
4697 # file uses a non-ISO format (e.g. M/D/YYYY).
4698 874 ▶ my $date_spec = defined $spec_key_override
Branch: 1 branch
BranchTrueFalseTotal
defined $spec_key_override ? : 222 652 874
Condition100%2/2
$self->param("l") // ""
l!l
6457
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
4699 ? $spec_key_override : ($self->param('l') // '');
4700 # A canvas dataset's spec comes from the stored canvas, not the request,
4701 # so the hook that spells the request's specs one way has not seen it.
4702 874 $date_spec = canonical_spec($date_spec);
4703 874 $self->_apply_date_normalization($records, $columns, $date_spec);
4704  
4705 # Stage 3: the stored lookups, so that a field, a filter, a bucket or a window
4706 # can read a looked-up column. They join the column list from here on.
4707 # _skip_stored is set by _calc_for_page when one of them cannot be applied:
4708 # the table page is drawn without them, so its panels can mend them.
4709 874 my $skip_stored = $self->stash('_skip_stored');
4710 874 my @cols = @{$columns};
4711 874 ▶ unless ($skip_stored) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($skip_stored) 871 3 874
4712 871 $self->_apply_lookups($records, \@cols, $date_spec);
4713 856 $self->_apply_extractions($records, \@cols, $date_spec);
4714 }
4715  
4716 # Build calc spec list: stored fields from models.json first (lower priority),
4717 # then URL ?c= params (higher priority -- they override stored fields of the
4718 # same name so the user can test a new expression without permanently saving).
4719 859 my (@calc_specs, %seen_calc);
4720 {
4721 859 my $sk = $date_spec;
4722 859 ▶ if (length $sk && !$skip_stored) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $sk and not $skip_stored) 849 10 859
Condition100%3/3
length $sk and not $skip_stored
!ll&&!rl&&r
73849
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
4723 849 ▶ my $stored = ($self->_read_models)->{fields}{$sk} // {};
Condition100%2/2
$self->_read_models->{"fields"}{$sk} // {}
l!l
2847
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
4724 849 for my $n (sort keys %{$stored}) {
4725 3 push @calc_specs, { name => $n, expr => $stored->{$n} };
4726 3 $seen_calc{$n} = $#calc_specs;
4727 }
4728 }
4729 }
4730 859 ▶ for my $spec (@{ $self->every_param('c') // [] }, @$extra_calc) {
Condition50%1/2
$self->every_param("c") // []
l!l
8590
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
4731 # Skip source specs handled by _run_pipeline_source.
4732 40 ▶ next if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/i;
Branch: 1 branch
BranchTrueFalseTotal
if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/iu 11 29 40
4733 29 my ($name, $expr) = ($spec =~ /\A([A-Za-z_][A-Za-z0-9_]*):(.+)\z/s);
4734 29 ▶ next unless defined $name && defined $expr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and defined $expr 15 14 29
Condition66%2/3
defined $name and defined $expr
!ll&&!rl&&r
15014
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
4735 14 ▶ if (exists $seen_calc{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $seen_calc{$name}) { } 1 13 14
4736 1 $calc_specs[$seen_calc{$name}]{expr} = $expr; # URL overrides stored
4737 } else {
4738 13 push @calc_specs, { name => $name, expr => $expr };
4739 13 $seen_calc{$name} = $#calc_specs;
4740 }
4741 }
4742  
4743 my @window = $extra && $extra->{window_columns}
4744 42 ? @{ $extra->{window_columns} }
4745 859 ▶ : _cross_row_aliases(@{ $self->every_param('cs') // [] });
Branch: 1 branch
BranchTrueFalseTotal
$extra && $extra->{'window_columns'} ? : 42 817 859
Condition80%4/5
$extra and $extra->{"window_columns"}
!ll&&!rl&&r
63817942
$self->every_param("cs") // []
l!l
8170
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
4746 859 my @held;
4747  
4748 859 ▶ if (@calc_specs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@calc_specs) 14 845 859
4749 14 require Database::BI::Calc;
4750 14 for my $cs (@calc_specs) {
4751 16 my $name = $cs->{name};
4752 my $calc = Database::BI::Calc->new(
4753 expr => $cs->{expr},
4754 16 columns => \@cols,
4755 params => $bound_params,
4756 );
4757 16 ▶ if ($calc->has_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($calc->has_error) 8 8 16
4758 # The names of fields already held count too, so that a field
4759 # can build on one that is waiting.
4760 my $later = @window && Database::BI::Calc->new(
4761 expr => $cs->{expr},
4762 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
800
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
4763 params => $bound_params,
4764 );
4765 8 ▶ if ($later && !$later->has_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($later and not $later->has_error) 0 8 8
Condition33%1/3
$later and not $later->has_error
!ll&&!rl&&r
800
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
4766 0 push @held, { %$cs, params => $bound_params };
4767 0 next;
4768 }
4769 8 croak $self->_i18n('error_calc_compile', $name, $calc->error);
4770 }
4771  
4772 8 $self->_write_calc_column($records, \@cols, $name, $calc);
4773 }
4774 }
4775 851 $self->stash('_held_calc_fields' => \@held);
4776  
4777 # Apply named value groups from models.json.
4778 # For each source column that has groups registered under the current l=
4779 # spec, add a virtual "${col}_group" column to every row. Each row's value
4780 # is mapped to its group label; values not in any group become '(other)'.
4781 # The spec is the one the stored fields use, so a table page, which names
4782 # its spec rather than taking l=, shows the column its charts can draw.
4783 {
4784 851 my $spec_key = $date_spec;
4785 851 ▶ if (length $spec_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $spec_key) 845 6 851
4786 845 my $models = $self->_read_models;
4787 845 my $grps = $models->{groups}{$spec_key};
4788 845 ▶ if ($grps && %{$grps}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($grps and %{$grps;}) 1 844 845
Condition66%2/3
$grps and %{$grps;}
!ll&&!rl&&r
84401
MC/DC50%1/2
$grps and %{$grps;}
$grps %{$grps;}
Truth table66%2/3
A and B
A= $grpsB= %{$grps;}
ABresult
0X0
100
111
4789 1 my %col_set = map { $_ => 1 } @cols;
4790 1 for my $col (sort keys %{$grps}) {
4791 1 ▶ next unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 0 1 1
4792 # Build reverse map: value -> group label.
4793 1 my %val2group;
4794 1 for my $gname (keys %{$grps->{$col}}) {
4795 2 for my $v (@{$grps->{$col}{$gname}}) {
4796 2 $val2group{$v} = $gname;
4797 }
4798 }
4799 1 my $vcol = "${col}_group";
4800 1 for my $i (0 .. $#$records) {
4801 2 my $row = $records->[$i];
4802 2 ▶ my $v = $row->{$col} // '';
Condition50%1/2
$row->{$col} // ""
l!l
20
MC/DC0%0/1
$row->{$col} // ""
$row->{$col}
Truth table50%1/2
A
A= $row->{$col}
Aresult
11
00
4803 $records->[$i] = _extend_row(
4804 2 ▶ $row, $vcol, $val2group{$v} // '(other)');
Condition100%2/2
$val2group{$v} // "(other)"
l!l
11
MC/DC100%1/1
$val2group{$v} // "(other)"
$val2group{$v}
Truth table100%2/2
A
A= $val2group{$v}
Aresult
11
00
4805 }
4806 1 ▶ push @cols, $vcol unless grep { $_ eq $vcol } @cols;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $vcol;} @cols 1 0 1
4807 # Record group column as virtual.
4808 1 ▶ $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->stash("_virtual_columns") 1 0 1
4809 1 $self->stash('_virtual_columns')->{$vcol} = 1;
4810 }
4811 }
4812 }
4813 }
4814  
4815 851 return ($records, \@cols);
4816 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4817  
4818 # ---------------------------------------------------------------------------
4819 # Calculated-field model storage (.bi/models.json)
4820 # ---------------------------------------------------------------------------
4821  
4822 # _canonical_path($path) -> $string
4823 #
4824 # The absolute, symlink-resolved form of a path, for the data_dir guard. Two
4825 # spellings of one directory have to compare equal, or the guard can be walked
4826 # around: a model_dir reached through a symlink is still inside the directory it
4827 # points at, and a data_dir that is itself a symlink is still where the user
4828 # keeps their data. Cwd::realpath resolves the whole path when it exists; a
4829 # store directory usually does not exist yet -- deciding whether to create it is
4830 # what the guard is for -- so the deepest ancestor that does exist is resolved
4831 # and the names below it are re-attached.
4832 12232 ▶sub _canonical_path {
Subroutine _canonical_path: called CC=9 SCAR=22.4
4833 12232 my ($path) = @_;
4834  
4835 12232 ▶ my $abs = eval { $path->to_abs } // $path;
Condition33%1/3
eval { do { $path->to_abs } } // $path
l!l&&r!l&&!r
1223200
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
4836 # Cwd::realpath on Windows does not follow symlinks: it gives undef for a
4837 # path through one, which would send the loop below to the link's parent
4838 # and keep the link's own name. So the links are followed first.
4839 12232 ▶ if ($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq "MSWin32") 3 12229 12232
4840 3 my $followed = _follow_links($abs->to_string);
4841 3 ▶ $abs = Mojo::File->new($followed) if defined $followed;
Branch: 1 branch
BranchTrueFalseTotal
if defined $followed 3 0 3
4842 }
4843 12232 my @tail;
4844 12232 my $probe = $abs;
4845 12232 while (1) {
4846 12245 my $string = $probe->to_string;
4847 12245 ▶ my $real = -e $string ? realpath($string) : undef;
Branch: 1 branch
BranchTrueFalseTotal
-e $string ? : 12232 13 12245
4848 12245 ▶ if (defined $real && length $real) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $real and length $real) 12232 13 12245
Condition66%2/3
defined $real and length $real
!ll&&!rl&&r
13012232
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
4849 12232 ▶ return File::Spec->canonpath(
Branch: 1 branch
BranchTrueFalseTotal
@tail ? : 10 12222 12232
4850 @tail ? Mojo::File->new($real, @tail)->to_string : $real
4851 );
4852 }
4853 13 my $parent = $probe->dirname;
4854 13 ▶ last if $parent->to_string eq $string; # the root: nothing left to resolve
Branch: 1 branch
BranchTrueFalseTotal
if $parent->to_string eq $string 0 13 13
4855 13 unshift @tail, $probe->basename;
4856 13 $probe = $parent;
4857 }
4858  
4859 # Nothing on the path exists at all, so the lexical absolute form is all
4860 # there is to compare.
4861 0 return File::Spec->canonpath($abs->to_string);
4862 }
4863  
4864 # _follow_links($path) -> $path | undef
4865 #
4866 # Purpose: $path with every symlink in it replaced by what it points at, one
4867 # component at a time, as realpath does where it can. For Windows,
4868 # whose realpath leaves links alone; it works the same anywhere, which
4869 # is how it is tested.
4870 # Entry: An absolute path.
4871 # Exit: The resolved absolute path; undef after 40 links, which is a loop.
4872 21 ▶sub _follow_links {
Subroutine _follow_links: called CC=10 SCAR=23.2
4873 21 my ($path) = @_;
4874 21 my ($vol, $dirs, $file) = File::Spec->splitpath($path);
4875 21 my @todo = grep { length } File::Spec->splitdir($dirs), $file;
4876 21 my @done;
4877 21 my $hops = 0;
4878 21 ▶ while (@todo) {
Branch: 1 branch
BranchTrueFalseTotal
if (@todo) 219 19 238
4879 219 my $part = shift @todo;
4880 219 ▶ next if $part eq '.';
Branch: 1 branch
BranchTrueFalseTotal
if $part eq "." 0 219 219
4881 219 ▶ if ($part eq '..') { pop @done; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($part eq "..") 3 216 219
4882 216 my $here = File::Spec->catpath($vol, File::Spec->catdir(File::Spec->rootdir, @done, $part), '');
4883 216 ▶ if (-l $here) {
Branch: 1 branch
BranchTrueFalseTotal
if (-l $here) 102 114 216
4884 102 ▶ return undef if ++$hops > 40;
Branch: 1 branch
BranchTrueFalseTotal
if ++$hops > 40 2 100 102
4885 100 my $target = readlink $here;
4886 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
4887 # Windows perls can give the NT form of an absolute target,
4888 # \??\C:\dir, or the long-path form \\?\C:\dir.
4889 100 $target =~ s{\A(?:\\\?\?\\|\\\\\?\\)}{};
4890 100 my ($tvol, $tdirs, $tfile) = File::Spec->splitpath($target);
4891 100 ▶ if (File::Spec->file_name_is_absolute($target)) {
Branch: 1 branch
BranchTrueFalseTotal
if ("File::Spec"->file_name_is_absolute($target)) 12 88 100
4892 12 ▶ $vol = $tvol if length $tvol;
Branch: 1 branch
BranchTrueFalseTotal
if length $tvol 0 12 12
4893 12 @done = ();
4894 }
4895 100 unshift @todo, grep { length } File::Spec->splitdir($tdirs), $tfile;
4896 100 next;
4897 }
4898 114 push @done, $part;
4899 }
4900 19 return File::Spec->catpath($vol, File::Spec->catdir(File::Spec->rootdir, @done), '');
4901 }
4902  
4903 # canonical_spec($spec) -> $spec
4904 #
4905 # Purpose: The one spelling of a path: spec that the model store files things
4906 # under. /open names its file by its realpath, so a definition saved,
4907 # or an extract built, under a path reached through a symlink (macOS's
4908 # /var is /private/var) would never be found by the page it is for.
4909 # Entry: Any spec, or undef.
4910 # Exit: path:<realpath> when the spec is path:<file> and the file exists
4911 # locally; anything else -- another kind of spec, a remote /../host
4912 # path, a file that is not there, a name with a newline -- unchanged.
4913 2287 ▶sub canonical_spec {
Subroutine canonical_spec: called CC=9 SCAR=22.2
Pod documented
4914 2287 my ($spec) = @_;
4915 2287 ▶ return $spec unless defined $spec && $spec =~ m{\Apath:(?!/\.\./)([^\n]+)\z};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec and $spec =~ m[\Apath:(?!/\.\./)([^\n]+)\z]u 1963 324 2287
Condition100%3/3
defined $spec and $spec =~ m[\Apath:(?!/\.\./)([^\n]+)\z]u
!ll&&!rl&&r
11962324
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
4916 324 my ($path, $internal) = _split_path($1);
4917 324 ▶ my $tail = defined $internal ? "#$internal" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 2 322 324
4918 # Windows' realpath leaves a symlink as it is, so a file reached through
4919 # one would be filed under a second key; follow the links first, as
4920 # _canonical_path does.
4921 324 ▶ if ($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq "MSWin32") 1 323 324
4922 1 my $followed = eval { _follow_links(Mojo::File->new($path)->to_abs->to_string) };
4923 1 ▶ $path = $followed if defined $followed;
Branch: 1 branch
BranchTrueFalseTotal
if defined $followed 1 0 1
4924 }
4925 324 ▶ return $spec unless -e $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $path 4 320 324
4926 320 my $real = eval { Mojo::File->new($path)->realpath->to_string };
4927 320 ▶ return (defined $real && length $real) ? "path:$real$tail" : $spec;
Branch: 1 branch
BranchTrueFalseTotal
defined $real && length $real ? : 320 0 320
Condition33%1/3
defined $real and length $real
!ll&&!rl&&r
00320
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
4928 }
4929  
4930 # _inside_dir($path, $dir) -> $bool
4931 #
4932 # True when $path names $dir itself or something below it. abs2rel asks the
4933 # file system what the relationship between the two is, so a textual prefix
4934 # cannot make ".../data-archive" look like it is inside ".../data", and the
4935 # comparison is made with the platform's separator rather than a hard-coded
4936 # slash.
4937 6116 ▶sub _inside_dir {
Subroutine _inside_dir: called CC=9 SCAR=22.3
4938 6116 my ($path, $dir) = @_;
4939 6116 ▶ return 0 unless length $path && length $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless length $path and length $dir 2 6114 6116
Condition100%3/3
length $path and length $dir
!ll&&!rl&&r
116114
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
4940 6114 ▶ return 1 if $path eq $dir;
Branch: 1 branch
BranchTrueFalseTotal
if $path eq $dir 2 6112 6114
4941  
4942 6112 my $rel = eval { File::Spec->abs2rel($path, $dir) };
4943 6112 ▶ return 0 unless defined $rel && length $rel;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rel and length $rel 0 6112 6112
Condition33%1/3
defined $rel and length $rel
!ll&&!rl&&r
006112
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
4944 6112 ▶ return 0 if File::Spec->file_name_is_absolute($rel);
Branch: 1 branch
BranchTrueFalseTotal
if "File::Spec"->file_name_is_absolute($rel) 0 6112 6112
4945 6112 ▶ return $rel eq '..' || $rel =~ m{\A\.\.[\\/]} ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$rel eq '..' || $rel =~ m[\A\.\.[\\/]]u ? : 6093 19 6112
Condition100%3/3
$rel eq ".." or $rel =~ m[\A\.\.[\\/]]u
l!l&&r!l&&!r
1609219
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
4946 }
4947  
4948 # _calc_models_path($self) -> $path_string_or_undef
4949 #
4950 # Returns the path to .bi/models.json (creating .bi/ on first call), or undef
4951 # when the write must be skipped (data_dir safety guard, mkdir failure).
4952 5692 ▶sub _calc_models_path :Protected ($self) {
Subroutine _calc_models_path: called CC=6 SCAR=18.0
4953 5692 my $app = $self->app;
4954 5692 my $home = $app->home;
4955 5692 ▶ my $cfg_dir = $app->config('model_dir') // '.bi';
Condition50%1/2
$app->config("model_dir") // ".bi"
l!l
56920
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
4956 # Support absolute paths in model_dir (e.g. when tests redirect to a temp dir).
4957 5692 ▶ my $bi_dir = Mojo::File->new($cfg_dir)->is_abs
Branch: 1 branch
BranchTrueFalseTotal
'Mojo::File'->new($cfg_dir)->is_abs ? : 5692 0 5692
4958 ? Mojo::File->new($cfg_dir)
4959 : $home->child($cfg_dir);
4960 5692 my $data_dir = _data_dir_for($app);
4961  
4962 # A store inside data_dir is refused, not created: the file would sit beside
4963 # the user's data, in a directory they chose for something else. The test is
4964 # on canonical paths, so it holds however the two are spelled -- an absolute
4965 # path, a relative one, or either of them reached through a symlink.
4966 5692 ▶ 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))) 2 5690 5692
4967 2 carp 'model_dir is inside data_dir; skipping model file write';
4968 2 return undef;
4969 }
4970 5690 ▶ unless (-d $bi_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $bi_dir) 2 5688 5690
4971 mkdir $bi_dir->to_string
4972 2 ▶ 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 1 2
4973 }
4974 5689 return $bi_dir->child('models.json')->to_string;
4975 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4976  
4977 # _read_models($self) -> \%models
4978 #
4979 # Returns the parsed models hashref from .bi/models.json, or an empty scaffold.
4980 5627 ▶sub _read_models :Protected ($self) {
Subroutine _read_models: called CC=9 SCAR=22.0
4981 5627 my $path = $self->_calc_models_path;
4982 5627 my $scaffold = { version => 1, fields => {}, groups => {}, date_patterns => {}, lookups => {}, extractions => {}, accelerated => {} };
4983 5627 ▶ return $scaffold unless defined $path && -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and -f $path 5526 101 5627
Condition66%2/3
defined $path and -f $path
!ll&&!rl&&r
05526101
MC/DC50%1/2
defined $path and -f $path
defined $path -f $path
Truth table66%2/3
A and B
A= defined $pathB= -f $path
ABresult
0X0
100
111
4984 101 my $json = eval { Mojo::File->new($path)->slurp };
4985 101 ▶ return $scaffold unless $json && !$@;
Branch: 1 branch
BranchTrueFalseTotal
unless $json and not $@ 1 100 101
Condition66%2/3
$json and not $@
!ll&&!rl&&r
10100
MC/DC50%1/2
$json and not $@
$json not $@
Truth table66%2/3
A and not(B)
A= $jsonB= not $@
ABresult
0X0
100
111
4986 100 my $data = eval { decode_json($json) };
4987 100 ▶ return $scaffold unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 4 96 100
4988 # Callers go straight to ->{fields}{$spec}{$name}, so a hand-edited section of
4989 # the wrong shape would otherwise be a strict-refs crash on every page.
4990 96 for my $section (qw(fields groups date_patterns lookups extractions accelerated)) {
4991 576 ▶ $data->{$section} = {} unless ref $data->{$section} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data->{$section} eq "HASH" 246 330 576
4992 576 my $by_spec = $data->{$section};
4993 576 delete @{$by_spec}{ grep { ref $by_spec->{$_} ne 'HASH' } keys %$by_spec };
4994 }
4995 96 _canonical_store_keys($data->{$_}) for grep { ref $data->{$_} eq 'HASH' }
4996 qw(fields groups date_patterns lookups extractions accelerated geo);
4997 96 return $data;
4998 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
4999  
5000 # _canonical_store_keys(\%by_spec) -> void
5001 #
5002 # Purpose: File every path: entry of one section of the model store under
5003 # canonical_spec of its key, so that a reader asking with the resolved
5004 # spec finds an entry written under a symlinked spelling, by a version
5005 # before specs were resolved or by hand. The next write persists it.
5006 # Notes: A geo key is <spec>|loc=<column>; only the spec part is resolved.
5007 # When both spellings are present the resolved one's names win.
5008 587 ▶sub _canonical_store_keys {
Subroutine _canonical_store_keys: called CC=7 SCAR=19.6
5009 587 my ($by_spec) = @_;
5010 587 for my $key (grep { /\Apath:/ } keys %$by_spec) {
5011 43 my ($spec, $rest) = split /\|/, $key, 2;
5012 43 ▶ my $new = canonical_spec($spec) . (defined $rest ? "|$rest" : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $rest ? : 1 42 43
5013 43 ▶ next if $new eq $key;
Branch: 1 branch
BranchTrueFalseTotal
if $new eq $key 41 2 43
5014 2 my $old = delete $by_spec->{$key};
5015 2 my $cur = $by_spec->{$new};
5016 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
5017 }
5018 587 return;
5019 }
5020  
5021 # _write_models($self, \%models) -> $bool
5022 #
5023 # Persists models to .bi/models.json. Returns false when the store could not be
5024 # written - because the data_dir guard refused it, or because the write failed -
5025 # so a caller whose result is only an optimisation (the geocode cache: it
5026 # degrades to a per-request cache) can say so rather than pretend.
5027 46 ▶sub _write_models :Protected ($self, $models) {
Subroutine _write_models: called CC=5 SCAR=16.2
5028 46 my $path = $self->_calc_models_path;
5029 46 ▶ return 0 unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 46 46
5030 46 $self->_set_aside_corrupt_store($path);
5031 46 my $ok = eval { Mojo::File->new($path)->spurt(encode_json($models)); 1 };
5032 46 ▶ $self->app->log->warn("Cannot write $path: $@") if !$ok && $@;
Branch: 1 branch
BranchTrueFalseTotal
if not $ok and $@ 3 43 46
Condition66%2/3
not $ok and $@
!ll&&!rl&&r
4303
MC/DC50%1/2
not $ok and $@
not $ok $@
Truth table66%2/3
not(A) and B
A= not $okB= $@
ABresult
0X0
100
111
5033 46 ▶ return $ok ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 43 3 46
5034 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5035  
5036 # _set_aside_corrupt_store($self, $path) -> void
5037 #
5038 # Purpose: Keep a store that cannot be parsed from being overwritten. A reader
5039 # treats such a file as empty, so without this the next save would
5040 # replace every saved canvas or model with the one change it carries.
5041 # Entry: $path is the store about to be written; it need not exist.
5042 # Exit: A file holding anything but a JSON object is renamed to
5043 # <path>.corrupt.<time>, for its owner to repair.
5044 # Only a plain file: a folder (or anything else) of that name is left
5045 # where it is, and the write then fails as it should. Linux will not
5046 # read a folder, but the BSDs read its raw entries, which never parse,
5047 # so a folder was moved aside there and the write went ahead.
5048 # Side Effects: Renames the file and logs where it went.
5049 107 ▶sub _set_aside_corrupt_store :Protected ($self, $path) {
Subroutine _set_aside_corrupt_store: called CC=6 SCAR=18.1
5050 107 ▶ return unless -f $path && -s _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path and -s _ 47 60 107
Condition100%3/3
-f $path and -s _
!ll&&!rl&&r
46160
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
5051  
5052 60 my $json = eval { Mojo::File->new($path)->slurp };
5053 60 ▶ return unless defined $json;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $json 0 60 60
5054 60 ▶ return if ref(eval { decode_json($json) }) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref eval { do { decode_json($json) } } eq "HASH" 58 2 60
5055  
5056 2 my $aside = "$path.corrupt." . time();
5057 2 ▶ if (rename $path, $aside) {
Branch: 1 branch
BranchTrueFalseTotal
if (rename $path, $aside) { } 2 0 2
5058 2 $self->app->log->error("$path could not be parsed; kept it as $aside");
5059 } else {
5060 0 $self->app->log->error("$path could not be parsed, and could not be kept as $aside: $!");
5061 }
5062 2 return;
5063 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5064  
5065 # _analyses_path($self) -> $path_string_or_undef
5066 #
5067 # Returns the path to model_dir/analyses.json (creating model_dir on first call),
5068 # or undef when the write must be skipped (data_dir safety guard, mkdir failure).
5069 392 ▶sub _analyses_path :Protected ($self) {
Subroutine _analyses_path: called CC=7 SCAR=23.0
5070 392 my $app = $self->app;
5071 392 my $home = $app->home;
5072 392 ▶ my $cfg_dir = $app->config('model_dir') // '.bi';
Condition50%1/2
$app->config("model_dir") // ".bi"
l!l
3920
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
5073 392 ▶ my $bi_dir = Mojo::File->new($cfg_dir)->is_abs
Branch: 1 branch
BranchTrueFalseTotal
'Mojo::File'->new($cfg_dir)->is_abs ? : 392 0 392
5074 ? Mojo::File->new($cfg_dir)
5075 : $home->child($cfg_dir);
5076 392 my $data_dir = _data_dir_for($app);
5077  
5078 # The same refusal as the model store, with its own message: see
5079 # _canonical_path for why the comparison is on resolved paths.
5080 392 ▶ 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 391 392
5081 1 carp 'model_dir is inside data_dir; skipping analyses file write';
5082 1 return undef;
5083 }
5084 391 ▶ unless (-d $bi_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $bi_dir) 0 391 391
5085 mkdir $bi_dir->to_string
5086 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
5087 }
5088 391 ▶ unless (-w $bi_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-w $bi_dir) 0 391 391
5089 0 carp 'model_dir is not writable; analysis storage disabled';
5090 0 return undef;
5091 }
5092 391 return $bi_dir->child('analyses.json')->to_string;
5093 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5094  
5095 # _read_analyses($self) -> \%analyses (keyed by id)
5096 306 ▶sub _read_analyses :Protected ($self) {
Subroutine _read_analyses: called CC=6 SCAR=18.0
5097 306 my $path = $self->_analyses_path;
5098 306 ▶ return {} unless defined $path && -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and -f $path 32 274 306
Condition66%2/3
defined $path and -f $path
!ll&&!rl&&r
032274
MC/DC50%1/2
defined $path and -f $path
defined $path -f $path
Truth table66%2/3
A and B
A= defined $pathB= -f $path
ABresult
0X0
100
111
5099 274 my $json = eval { Mojo::File->new($path)->slurp };
5100 274 ▶ return {} unless $json && !$@;
Branch: 1 branch
BranchTrueFalseTotal
unless $json and not $@ 1 273 274
Condition66%2/3
$json and not $@
!ll&&!rl&&r
10273
MC/DC50%1/2
$json and not $@
$json not $@
Truth table66%2/3
A and not(B)
A= $jsonB= not $@
ABresult
0X0
100
111
5101 273 my $data = eval { decode_json($json) };
5102 273 ▶ return {} unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 2 271 273
5103 271 return { map { $_ => _tidy_analysis($data->{$_}) } grep { ref $data->{$_} eq 'HASH' } keys %$data };
5104 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5105  
5106 # _tidy_analysis(\%doc) -> \%doc
5107 #
5108 # A stored canvas can hold anything: it may be hand-edited or older than a rule.
5109 # Every page that reads one goes straight to ->{visuals}[0]{encode}{cat}, so the
5110 # shape is put right here, once, and a part of the wrong shape is treated as
5111 # absent: a canvas with one bad part still shows the rest, not a 500. A visual
5112 # of the wrong shape becomes an empty one rather than going away, because a
5113 # visual's index is its identity in the layout and in /a/:id/visual/:n.
5114 262 ▶sub _tidy_analysis {
Subroutine _tidy_analysis: called CC=16 SCAR=27.7
5115 262 my $doc = $_[0];
5116  
5117 262 delete $doc->{$_} for grep { ref $doc->{$_} ne 'ARRAY' } qw(datasets visuals joins measures combines bookmarks layout hierarchies);
5118 262 delete $doc->{$_} for grep { ref $doc->{$_} ne 'HASH' } qw(fields params);
5119 262 delete $doc->{$_} for grep { ref $doc->{$_} } qw(name updated);
5120  
5121 262 ▶ if ($doc->{datasets}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($doc->{"datasets"}) 224 38 262
5122 224 ▶ $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
21224
ref $_ eq "HASH" and defined $_->{"spec"}
!ll&&!rl&&r
11225
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
5123 224 for my $ds (@{ $doc->{datasets} }) {
5124 224 ▶ delete $ds->{filters} if ref $ds->{filters} ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $ds->{"filters"} ne "ARRAY" 223 1 224
5125 }
5126 }
5127 262 for my $key (grep { $doc->{$_} } qw(joins layout)) {
5128 20 $doc->{$key} = [ grep { ref $_ eq 'HASH' } @{ $doc->{$key} } ];
5129 }
5130 262 ▶ if ($doc->{visuals}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($doc->{"visuals"}) 167 95 262
5131 167 ▶ $doc->{visuals} = [ map { ref $_ eq 'HASH' ? $_ : {} } @{ $doc->{visuals} } ];
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 207 13 220
5132 167 _tidy_visual($_) for @{ $doc->{visuals} };
5133 }
5134 262 ▶ if ($doc->{params}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($doc->{"params"}) 13 249 262
5135 13 for my $def (values %{ $doc->{params} }) {
5136 14 ▶ $def = {} unless ref $def eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $def eq "HASH" 12 2 14
5137 }
5138 }
5139 262 return $doc;
5140 }
5141  
5142 # _tidy_visual(\%visual) -> \%visual
5143 #
5144 # The same for one card, whose parts are read as blindly as the document's.
5145 220 ▶sub _tidy_visual {
Subroutine _tidy_visual: called CC=4 SCAR=13.9
5146 220 my $vis = $_[0];
5147  
5148 220 delete $vis->{$_} for grep { ref $vis->{$_} ne 'HASH' } qw(encode options);
5149 220 ▶ delete $vis->{filters} if ref $vis->{filters} ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $vis->{"filters"} ne "ARRAY" 219 1 220
5150 220 delete $vis->{$_} for grep { ref $vis->{$_} } qw(kind title);
5151 220 return $vis;
5152 }
5153  
5154 # _write_analyses($self, \%analyses) -> 1 | 0 | nothing -- atomic write (temp + rename)
5155 # Nothing means the store is switched off (see _analyses_path).
5156 56 ▶sub _write_analyses :Protected ($self, $analyses) {
Subroutine _write_analyses: called CC=9 SCAR=23.9
5157 56 my $path = $self->_analyses_path;
5158 56 ▶ return unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 56 56
5159 56 $self->_set_aside_corrupt_store($path);
5160 56 my $dir = Mojo::File->new($path)->dirname->to_string;
5161 56 my ($fh, $tmpfile) = eval { tempfile(DIR => $dir, UNLINK => 0) };
5162 56 ▶ if ($@ || !$fh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $fh) 0 56 56
Condition33%1/3
$@ or not $fh
l!l&&r!l&&!r
0056
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
5163 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
5164 0 return;
5165 }
5166 56 my $ok = eval {
5167 56 ▶ print {$fh} encode_json($analyses) or croak "print: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} encode_json($analyses) or croak("print: $!") 56 0 56
5168 56 ▶ close $fh or croak "close: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("close: $!") 56 0 56
5169 56 ▶ rename($tmpfile, $path) or croak "rename: $!";
Branch: 1 branch
BranchTrueFalseTotal
rename $tmpfile, $path or croak("rename: $!") 54 2 56
5170 54 1;
5171 };
5172 56 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 2 54 56
5173 2 $self->app->log->warn("Cannot write $path: $@");
5174 2 unlink $tmpfile;
5175 2 return 0;
5176 }
5177 54 return 1;
5178 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5179  
5180 # _gen_analysis_id($self) -> $id_string
5181 #
5182 # Returns a 10-character URL-safe alphanumeric random ID.
5183 5 Readonly my $_ID_CHARS => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
5184  
5185 228 ▶sub _gen_analysis_id :Protected ($self) {
Subroutine _gen_analysis_id: called CC=2 SCAR=6.9
5186 228 my $id = '';
5187 228 $id .= substr($_ID_CHARS, int(rand(62)), 1) for 1..10;
5188 228 return $id;
5189 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5190  
5191 # The canvas is a 12-column CSS grid; a layout entry addresses cells in it.
5192 # Shared by _validate_layout and by the layout precompute in canvas_render.
5193 5 Readonly my $GRID_COLUMNS => 12;
5194  
5195 # How many grid rows one visual may span. A row is at least 15rem tall (see
5196 # grid-auto-rows in templates/web/en/canvas.html.tt), so this is also a cap on
5197 # how tall a single visual can be made from the canvas.
5198 5 Readonly my $MAX_ROW_SPAN => 6;
5199  
5200 # _save_analyses_or_503($self, \%analyses) -> $bool
5201 #
5202 # Writes the store, or answers 503 and returns false, so that no route tells a
5203 # client something was saved when it was not.
5204 42 ▶sub _save_analyses_or_503 :Protected ($self, $analyses) {
Subroutine _save_analyses_or_503: called CC=2 SCAR=6.9
5205 42 ▶ return 1 if $self->_write_analyses($analyses);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_write_analyses($analyses) 39 3 42
5206  
5207 3 $self->render(json => { error => _message_text('error_analysis_storage') }, status => 503);
5208 3 return 0;
5209 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5210  
5211 # _validate_layout($self, $layout_or_undef) -> $error_string_or_undef
5212 #
5213 # A layout entry is { visual, x, y, w, h } -- the grid position of one visual
5214 # on the canvas. The canvas PATCHes these straight out of a drag, so they are
5215 # untrusted input like every other field: reject anything that is not a whole
5216 # number of columns or rows inside the grid, rather than store a position that
5217 # renders as "span 0" or runs off the right-hand edge.
5218 60 ▶sub _validate_layout :Protected ($self, $layout) {
Subroutine _validate_layout: called CC=22 SCAR=31.0
5219 60 ▶ return undef unless defined $layout;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $layout 39 21 60
5220 21 ▶ return 'layout must be an array' unless ref $layout eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $layout eq "ARRAY" 1 20 21
5221  
5222 20 my $n = 0;
5223 20 my @placed; # the cells already spoken for, to reject an overlap
5224 20 for my $lp (@$layout) {
5225 23 $n++;
5226 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
5227 21 for my $f (qw( visual x y w h )) {
5228 94 ▶ return "layout entry $n is missing $f" unless defined $lp->{$f};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lp->{$f} 2 92 94
5229 return "layout entry $n: $f must be a whole number"
5230 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
5231 }
5232 return "layout entry $n: x must be between 1 and $GRID_COLUMNS"
5233 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
5234 return "layout entry $n: y must be at least 1"
5235 13 ▶ unless $lp->{y} >= 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $lp->{"y"} >= 1 1 12 13
5236 return "layout entry $n: w must be between 1 and $GRID_COLUMNS"
5237 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
5238 return "layout entry $n: h must be between 1 and $MAX_ROW_SPAN"
5239 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
5240 return "layout entry $n: x + w - 1 must not exceed $GRID_COLUMNS"
5241 9 ▶ if $lp->{x} + $lp->{w} - 1 > $GRID_COLUMNS;
Branch: 1 branch
BranchTrueFalseTotal
if $lp->{"x"} + $lp->{"w"} - 1 > $GRID_COLUMNS 1 8 9
5242  
5243 # Two visuals cannot hold the same cell: the canvas is a grid of positions,
5244 # and an overlapping layout renders one visual on top of another. The
5245 # canvas pushes the cards a drop lands on out of the way before it PATCHes,
5246 # so this rejects a hand-written or stale layout rather than a drag.
5247 8 for my $p (@placed) {
5248 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
5249 return "layout entry $n overlaps an earlier entry"
5250 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
5251 }
5252 6 push @placed, { x => $lp->{x}, y => $lp->{y}, w => $lp->{w}, h => $lp->{h} };
5253 }
5254  
5255 3 return undef;
5256 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5257  
5258 # _validate_analysis($self, \%doc) -> $error_string_or_undef
5259 #
5260 # Structural validation of a saved-analysis document. Called on create, on
5261 # replace and on import; analyses_patch validates the keys it is given instead,
5262 # so that a PATCH of one field cannot fail because of another field it never
5263 # read.
5264 72 ▶sub _validate_analysis :Protected ($self, $doc) {
Subroutine _validate_analysis: called CC=3 SCAR=11.0
5265 72 for my $required (qw(name datasets)) {
5266 143 ▶ return "Missing required field: $required" unless defined $doc->{$required};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $doc->{$required} 3 140 143
5267 }
5268 69 return $self->_validate_analysis_parts($doc);
5269 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5270  
5271 # _drop_unknown_keys(\%doc) -> void
5272 #
5273 # Only these keys are ever read back, so anything else a client sends is not kept
5274 # on any write: the POD promises this, and a store should not grow what nothing uses.
5275 39 ▶sub _drop_unknown_keys {
Subroutine _drop_unknown_keys: called CC=1 SCAR=0.0
5276 39 my $doc = $_[0];
5277  
5278 39 delete @{$doc}{ grep { !$ANALYSIS_KEYS{$_} } keys %$doc };
5279 }
5280  
5281 # _validate_analysis_parts($self, \%doc) -> $error_string_or_undef
5282 #
5283 # Checks only the keys present, which is all a PATCH may be judged on. This body
5284 # is whatever a client sent, so nothing about the shape of a value is assumed.
5285 84 ▶sub _validate_analysis_parts :Protected ($self, $doc) {
Subroutine _validate_analysis_parts: called CC=30 SCAR=34.1
5286 84 ▶ if (exists $doc->{name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $doc->{"name"}) 72 12 84
5287 return 'Missing required field: name'
5288 72 ▶ 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 65 72
Condition83%5/6
defined $doc->{"name"} and not ref $doc->{"name"} and length $doc->{"name"}
!ll&&!rl&&r
5265
defined $doc->{"name"} and not ref $doc->{"name"}
!ll&&!rl&&r
0567
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
5289 }
5290 77 ▶ if (exists $doc->{datasets}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $doc->{"datasets"}) 64 13 77
5291 return 'Missing required field: datasets'
5292 64 ▶ unless ref $doc->{datasets} eq 'ARRAY' && @{ $doc->{datasets} };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc->{"datasets"} eq "ARRAY" and @{$doc->{"datasets"};} 3 61 64
Condition100%3/3
ref $doc->{"datasets"} eq "ARRAY" and @{$doc->{"datasets"};}
!ll&&!rl&&r
1261
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
5293 61 for my $ds (@{ $doc->{datasets} }) {
5294 return 'Each dataset entry must have a spec field'
5295 61 ▶ 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 46 61
Condition88%8/9
ref $ds eq "HASH" and defined $ds->{"spec"} and not ref $ds->{"spec"} and length $ds->{"spec"}
!ll&&!rl&&r
15046
ref $ds eq "HASH" and defined $ds->{"spec"} and not ref $ds->{"spec"}
!ll&&!rl&&r
11446
ref $ds eq "HASH" and defined $ds->{"spec"}
!ll&&!rl&&r
10150
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
5296 return qq{"$ds->{spec}" is not a valid spec (must start with table:, path:, url:, or redis:, or be mariadb:server/table)}
5297 46 ▶ 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 45 46
Condition66%2/3
$ds->{"spec"} =~ /\A(?:table:|path:|url:|redis:)/u or $ds->{"spec"} =~ /$MARIADB_SPEC_RE/u
l!l&&r!l&&!r
4501
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
5298 }
5299 }
5300 58 ▶ if (defined $doc->{version}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $doc->{"version"}) 5 53 58
5301 return sprintf(_message_text('error_analysis_version'), $doc->{version})
5302 5 ▶ 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 3 2 5
Condition100%6/6
not ref $doc->{"version"} and $doc->{"version"} =~ /\A\d+\z/u and $doc->{"version"} <= 1
!ll&&!rl&&r
212
not ref $doc->{"version"} and $doc->{"version"} =~ /\A\d+\z/u
!ll&&!rl&&r
113
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
5303 }
5304 55 for my $key (qw( visuals joins measures combines bookmarks layout hierarchies )) {
5305 345 ▶ if (defined $doc->{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $doc->{$key}) 46 299 345
5306 return "$key must be an array"
5307 46 ▶ unless ref $doc->{$key} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc->{$key} eq "ARRAY" 11 35 46
5308 }
5309 }
5310 44 for my $key (qw( visuals joins )) {
5311 86 ▶ next unless defined $doc->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $doc->{$key} 56 30 86
5312 return "Each entry in $key must be an object"
5313 30 ▶ if grep { ref $_ ne 'HASH' } @{ $doc->{$key} };
Branch: 1 branch
BranchTrueFalseTotal
if grep {ref $_ ne "HASH";} @{$$doc{$key};} 3 27 30
5314 }
5315 41 my $lerr = $self->_validate_layout($doc->{layout});
5316 41 ▶ return $lerr if $lerr;
Branch: 1 branch
BranchTrueFalseTotal
if $lerr 2 39 41
5317 39 ▶ if (defined $doc->{fields}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $doc->{"fields"}) 1 38 39
5318 return 'fields must be a hash'
5319 1 ▶ unless ref $doc->{fields} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc->{"fields"} eq "HASH" 1 0 1
5320 }
5321 38 ▶ if (defined $doc->{params}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $doc->{"params"}) 2 36 38
5322 return 'params must be a hash'
5323 2 ▶ unless ref $doc->{params} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc->{"params"} eq "HASH" 2 0 2
5324 }
5325 36 return undef;
5326 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5327  
5328 # _analysis_to_url($self, \%analysis) -> $url_string_or_undef
5329 #
5330 # Reconstructs a /join?l=...&j=...&f=... URL from a saved analysis.
5331 # Used by canvas_render to redirect when no visuals exist yet.
5332 30 ▶sub _analysis_to_url :Protected ($self, $a) {
Subroutine _analysis_to_url: called CC=18 SCAR=29.0
5333 30 ▶ my @datasets = @{ $a->{datasets} // [] };
Condition100%2/2
$a->{"datasets"} // []
l!l
264
MC/DC100%1/1
$a->{"datasets"} // []
$a->{"datasets"}
Truth table100%2/2
A
A= $a->{"datasets"}
Aresult
11
00
5334 30 ▶ return undef unless @datasets;
Branch: 1 branch
BranchTrueFalseTotal
unless @datasets 4 26 30
5335  
5336 26 ▶ my $left_spec = $datasets[0]{spec} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $left_spec = $datasets[0]{"spec"} or return undef 25 1 26
5337 25 my @params = ('l=' . url_escape($left_spec));
5338  
5339 # Build an alias->spec lookup for join resolution
5340 25 my %spec_by_alias;
5341 25 for my $ds (@datasets) {
5342 26 ▶ $spec_by_alias{ $ds->{alias} // '' } = $ds->{spec} // '';
Condition75%3/4
$ds->{"spec"} // ""
l!l
260
$ds->{"alias"} // ""
l!l
323
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
5343 }
5344  
5345 25 ▶ for my $j (@{ $a->{joins} // [] }) {
Condition100%2/2
$a->{"joins"} // []
l!l
322
MC/DC100%1/1
$a->{"joins"} // []
$a->{"joins"}
Truth table100%2/2
A
A= $a->{"joins"}
Aresult
11
00
5346 3 ▶ next unless ref $j eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $j eq "HASH" 1 2 3
5347 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
5348 2 ▶ next unless $right_spec;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_spec 1 1 2
5349 push @params, 'j=' . url_escape(
5350 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
5351 );
5352 }
5353  
5354 # Filters from all datasets
5355 25 for my $ds (@datasets) {
5356 26 ▶ next unless ref $ds->{filters} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ds->{"filters"} eq "ARRAY" 25 1 26
5357 1 for my $f (@{ $ds->{filters} }) {
5358 1 push @params, 'f=' . url_escape(encode('UTF-8', $f));
5359 }
5360 }
5361  
5362 25 return '/join?' . join('&', @params);
5363 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
5364  
5365 # GET /api/analyses
5366 21 ▶sub analyses_list ($self) {
Subroutine analyses_list: called CC=1 SCAR=0.0
Pod documented
5367 21 my $analyses = $self->_read_analyses;
5368 my @list = map {
5369 21 my $a = $analyses->{$_};
5370 { id => $_, name => $a->{name}, datasets => $a->{datasets},
5371 updated => $a->{updated} }
5372 16 } sort keys %$analyses;
5373 21 $self->render(json => { analyses => \@list });
5374 }
5375  
5376 # POST /api/analyses
5377 40 ▶sub analyses_create ($self) {
Subroutine analyses_create: called CC=8 SCAR=21.1
Pod documented
5378 40 my $body = eval { decode_json($self->req->body) };
5379 40 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 8 32 40
5380 unless ref $body eq 'HASH';
5381  
5382 32 my $err = $self->_validate_analysis($body);
5383 32 ▶ return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $err) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if $err 6 26 32
5384 if $err;
5385  
5386 26 my $analyses = $self->_read_analyses;
5387 26 ▶ unless ($self->_analyses_path) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_analyses_path) 0 26 26
5388 0 return $self->render(json => { error => _message_text('error_analysis_storage') }, status => 503);
5389 }
5390  
5391 26 my $id;
5392 26 my $tries = 0;
5393 26 do { $id = $self->_gen_analysis_id; $tries++ }
5394 26 ▶ 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 26 26
Condition33%1/3
exists $analyses->{$id} and $tries < 100
!ll&&!rl&&r
2600
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
5395  
5396 26 $body->{id} = $id;
5397 26 ▶ $body->{version} //= 1;
Condition50%1/2
$body->{"version"} //= 1
l!l
026
MC/DC0%0/1
$body->{"version"} //= 1
$body->{"version"}
Truth table50%1/2
A
A= $body->{"version"}
Aresult
11
00
5398 26 $body->{created} = time();
5399 26 $body->{updated} = time();
5400  
5401 # Strip caller-supplied immutable fields except id/version/created/updated
5402 26 _drop_unknown_keys($body);
5403  
5404 26 $analyses->{$id} = $body;
5405 26 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 25 1 26
5406  
5407 25 $self->res->headers->location("/api/analyses/$id");
5408 25 $self->render(json => { id => $id, created => 1 }, status => 201);
5409 }
5410  
5411 # GET /api/analyses/:id
5412 40 ▶sub analyses_get ($self) {
Subroutine analyses_get: called CC=4 SCAR=13.9
Pod documented
5413 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
5414 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
5415 unless $id =~ /\A[A-Za-z0-9]+\z/;
5416  
5417 37 my $analyses = $self->_read_analyses;
5418 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5419 37 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 5 32 37
5420  
5421 32 $self->render(json => $analyses->{$id});
5422 }
5423  
5424 # PUT /api/analyses/:id (full replace)
5425 17 ▶sub analyses_update ($self) {
Subroutine analyses_update: called CC=9 SCAR=22.1
Pod documented
5426 17 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
170
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5427 17 ▶ 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 2 15 17
5428 unless $id =~ /\A[A-Za-z0-9]+\z/;
5429  
5430 15 my $analyses = $self->_read_analyses;
5431 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5432 15 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 2 13 15
5433  
5434 13 my $body = eval { decode_json($self->req->body) };
5435 13 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 7 6 13
5436 unless ref $body eq 'HASH';
5437  
5438 6 my $err = $self->_validate_analysis($body);
5439 6 ▶ return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $err) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if $err 4 2 6
5440 if $err;
5441  
5442 2 _drop_unknown_keys($body);
5443 2 $body->{id} = $id;
5444 2 ▶ $body->{version} //= 1;
Condition50%1/2
$body->{"version"} //= 1
l!l
02
MC/DC0%0/1
$body->{"version"} //= 1
$body->{"version"}
Truth table50%1/2
A
A= $body->{"version"}
Aresult
11
00
5445 2 ▶ $body->{created} = $analyses->{$id}{created} // time();
Condition50%1/2
$analyses->{$id}{"created"} // time
l!l
20
MC/DC0%0/1
$analyses->{$id}{"created"} // time
$analyses->{$id}{"created"}
Truth table50%1/2
A
A= $analyses->{$id}{"created"}
Aresult
11
00
5446 2 $body->{updated} = time();
5447  
5448 2 $analyses->{$id} = $body;
5449 2 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 2 0 2
5450  
5451 2 $self->render(json => { id => $id, updated => 1 });
5452 }
5453  
5454 # PATCH /api/analyses/:id (partial update -- merges supplied keys)
5455 13 ▶sub analyses_patch ($self) {
Subroutine analyses_patch: called CC=10 SCAR=23.0
Pod documented
5456 13 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
130
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5457 13 ▶ 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 2 11 13
5458 unless $id =~ /\A[A-Za-z0-9]+\z/;
5459  
5460 11 my $analyses = $self->_read_analyses;
5461 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5462 11 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 2 9 11
5463  
5464 9 my $body = eval { decode_json($self->req->body) };
5465 9 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 2 7 9
5466 unless ref $body eq 'HASH';
5467  
5468 # Only the keys actually supplied are validated here: the canvas PATCHes
5469 # nothing but the layout (a drag) or the bookmarks, and a document that
5470 # fails on some other field it never mentioned is not this request's fault.
5471 7 my $perr = $self->_validate_analysis_parts($body);
5472 7 ▶ return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $perr) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if $perr 4 3 7
5473 if $perr;
5474  
5475 3 _drop_unknown_keys($body);
5476 3 my $existing = { %{ $analyses->{$id} } };
5477 3 for my $key (keys %$body) {
5478 6 ▶ next if $key eq 'id' || $key eq 'created'; # immutable
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "id" or $key eq "created" 2 4 6
Condition100%3/3
$key eq "id" or $key eq "created"
l!l&&r!l&&!r
114
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
5479 4 $existing->{$key} = $body->{$key};
5480 }
5481 3 $existing->{updated} = time();
5482  
5483 3 $analyses->{$id} = $existing;
5484 3 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 3 0 3
5485  
5486 3 $self->render(json => { id => $id, updated => 1 });
5487 }
5488  
5489 # DELETE /api/analyses/:id
5490 9 ▶sub analyses_delete ($self) {
Subroutine analyses_delete: called CC=5 SCAR=16.1
Pod documented
5491 9 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
90
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5492 9 ▶ 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 6 9
5493 unless $id =~ /\A[A-Za-z0-9]+\z/;
5494  
5495 6 my $analyses = $self->_read_analyses;
5496 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5497 6 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 3 3 6
5498  
5499 3 delete $analyses->{$id};
5500 3 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 2 1 3
5501  
5502 2 $self->render(json => { deleted => 1 });
5503 }
5504  
5505 # POST /api/analyses/:id/visuals (append one table or chart)
5506 #
5507 # Adds a visual to a saved canvas without sending the reader back to the table
5508 # or chart page it came from. The request is { kind, encode, options, title }
5509 # and the visual is rendered here, with the same pipeline and renderer the
5510 # canvas itself uses, before it is stored: a column that does not exist is a
5511 # 400 rather than a broken card the reader only discovers after a reload.
5512 #
5513 # The new card is deliberately left out of the saved layout. An auto-placed
5514 # card is ordered after the saved ones and stays there without pinning a
5515 # position that the next drag would have to fight; the canvas writes a layout
5516 # entry once the reader moves or resizes it.
5517 17 ▶sub analyses_add_visual ($self) {
Subroutine analyses_add_visual: called CC=35 SCAR=43.9
Pod documented
5518 17 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
170
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5519 17 ▶ 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 2 15 17
5520 unless $id =~ /\A[A-Za-z0-9]+\z/;
5521  
5522 15 my $analyses = $self->_read_analyses;
5523 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5524 15 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 2 13 15
5525 13 my $a = $analyses->{$id};
5526  
5527 13 my $body = eval { decode_json($self->req->body) };
5528 13 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 2 11 13
5529 unless ref $body eq 'HASH';
5530  
5531 11 ▶ my $kind = $body->{kind} // '';
Condition50%1/2
$body->{"kind"} // ""
l!l
110
MC/DC0%0/1
$body->{"kind"} // ""
$body->{"kind"}
Truth table50%1/2
A
A= $body->{"kind"}
Aresult
11
00
5532 11 my %supported = map { $_ => 1 }
5533 qw( table bar pie line graph scatter heatmap stacked combo treemap histogram map wordcloud text );
5534 return $self->render(json => { error => 'Unsupported visual kind' }, status => 400)
5535 11 ▶ unless $supported{$kind};
Branch: 1 branch
BranchTrueFalseTotal
unless $supported{$kind} 1 10 11
5536  
5537 10 for my $key (qw( encode options cross_row )) {
5538 return $self->render(json => { error => "$key must be an object" }, status => 400)
5539 30 ▶ if defined $body->{$key} && ref $body->{$key} ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if defined $body->{$key} and ref $body->{$key} ne "HASH" 1 29 30
Condition100%3/3
defined $body->{$key} and ref $body->{$key} ne "HASH"
!ll&&!rl&&r
2091
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
5540 }
5541  
5542 # A text card reads no data, so it can be added whatever state the canvas's
5543 # source is in.
5544 9 ▶ if ($kind eq 'text') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "text") 5 4 9
5545 5 my ($options, $errors) = _text_card_options($body->{options});
5546 5 ▶ return $self->render(json => { error => $errors->[0] }, status => 400) if @$errors;
Branch: 1 branch
BranchTrueFalseTotal
if @$errors 5 0 5
5547  
5548 0 my $vis = { kind => 'text', encode => {}, options => $options };
5549 $vis->{title} = $body->{title}
5550 0 ▶ 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 0 0
Condition0%0/6
defined $body->{"title"} and not ref $body->{"title"} and length $body->{"title"}
!ll&&!rl&&r
000
defined $body->{"title"} and not ref $body->{"title"}
!ll&&!rl&&r
000
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 table0%0/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
5551  
5552 0 ▶ my $index = scalar @{ $a->{visuals} // [] };
Condition0%0/2
$a->{"visuals"} // []
l!l
00
MC/DC0%0/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table0%0/2
A
A= $a->{"visuals"}
Aresult
11
00
5553 0 ▶ push @{ $a->{visuals} //= [] }, $vis;
Condition0%0/2
$a->{"visuals"} //= []
l!l
00
MC/DC0%0/1
$a->{"visuals"} //= []
$a->{"visuals"}
Truth table0%0/2
A
A= $a->{"visuals"}
Aresult
11
00
5554 0 $a->{updated} = time();
5555 0 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 0 0 0
5556  
5557 0 return $self->render(json => _text_card_reply($id, $index, $vis), status => 201);
5558 }
5559  
5560 my $vis = {
5561 kind => $kind,
5562 encode => ($body->{encode} // {}),
5563 4 ▶ options => ($body->{options} // {}),
Condition75%3/4
$body->{"encode"} // {}
l!l
31
$body->{"options"} // {}
l!l
04
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
5564 };
5565  
5566 # A card may bring a cross-row plan of its own; it is stored in the same
5567 # spelling cs=/by=/order= use -- { cs => [...], by => '...', order => [...] }
5568 # -- so the pass reads it through the one parser, with the page's plan left
5569 # out of it. Only the shape is checked here: which columns exist is a fact
5570 # about the data file, and it is checked again on every render for the same
5571 # reason a saved canvas is.
5572 4 ▶ if (my $raw = $body->{cross_row}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $raw = $body->{"cross_row"}) 1 3 4
5573 1 my $plan = _card_plan($raw);
5574 return $self->render(json => { error => $plan->{error} }, status => 400)
5575 1 ▶ if $plan->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $plan->{"error"} 1 0 1
5576 0 $vis->{cross_row} = $plan;
5577 }
5578  
5579 $vis->{title} = $body->{title}
5580 3 ▶ 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"} 2 1 3
Condition66%4/6
defined $body->{"title"} and not ref $body->{"title"} and length $body->{"title"}
!ll&&!rl&&r
102
defined $body->{"title"} and not ref $body->{"title"}
!ll&&!rl&&r
102
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
5581  
5582 # The card is added without a page reload, so the canvas's own URL state has
5583 # to come with the request: a reader who adds a card while a chart is
5584 # cross-filtering the canvas, with calculated columns on the URL, or with a
5585 # what-if parameter set, gets a card drawn like the ones beside it rather
5586 # than against the unfiltered table.
5587 3 my $ctx = $self->_canvas_render_context($a, $body->{query}, [$vis]);
5588 return $self->render(json => { error => $ctx->{error} }, status => $ctx->{status})
5589 3 ▶ if $ctx->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"error"} 0 3 3
5590  
5591 # The new card is never the cross-filter source: it did not exist when the
5592 # filter was made, so every cf applies to it, as it does to every card but
5593 # the source.
5594 3 my ($records, $late_cf) = $self->_canvas_cross_filter($ctx->{records}, $ctx->{columns}, $ctx->{cf_specs});
5595  
5596 # The index is known before the render, so the card's SVG and Leaflet ids
5597 # match the ones a later page load will give it.
5598 3 ▶ my $index = scalar @{ $a->{visuals} // [] };
Condition100%2/2
$a->{"visuals"} // []
l!l
21
MC/DC100%1/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
5599  
5600 my $rendered = $self->_render_visual_html(
5601 $vis, $records, $ctx->{columns}, $ctx->{src}, $index, $ctx->{spec_key},
5602 3 (@{ $ctx->{cf_specs} } ? 1 : 0),
5603 $ctx->{cross_row},
5604 3 ▶ $late_cf,
Branch: 1 branch
BranchTrueFalseTotal
@{$ctx->{'cf_specs'};} ? : 0 3 3
5605 );
5606 return $self->render(json => { error => $rendered->{error} }, status => 400)
5607 3 ▶ if $rendered->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $rendered->{"error"} 1 2 3
5608  
5609 2 ▶ push @{ $a->{visuals} //= [] }, $vis;
Condition100%2/2
$a->{"visuals"} //= []
l!l
11
MC/DC100%1/1
$a->{"visuals"} //= []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
5610 2 $a->{updated} = time();
5611 2 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 2 0 2
5612  
5613 return $self->render(
5614 json => {
5615 id => $id,
5616 visual => $index,
5617 kind => $kind,
5618 title => ($vis->{title} // $rendered->{title} // 'Visual ' . ($index + 1)),
5619 html => $rendered->{html},
5620 2 ▶ head => ($rendered->{head} // ''),
Condition44%4/9
($vis->{"title"} // $rendered->{"title"}) // 'Visual ' . ($index + 1)
l!l
20
$vis->{"title"} // $rendered->{"title"}
l!l&&r!l&&!r
200
$rendered->{"head"} // ""
l!l
02
_vis_cf_col($vis) // ""
l!l
20
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 table33%1/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
5621 # The nonce the card's scripts were written with: the page runs
5622 # only those that carry it (runCardScripts in canvas.html.tt).
5623 nonce => $self->csp_nonce,
5624 # The column a chart's marks filter by, so the card appended in
5625 # place is a cross-filter control like the cards around it.
5626 cf_col => (_vis_cf_col($vis) // ''),
5627 },
5628 status => 201,
5629 );
5630 }
5631  
5632 # PATCH /api/analyses/:id/visuals/:visual (change a saved visual's columns)
5633 #
5634 # A map card that plotted the wrong column should not have to be deleted and
5635 # added again: the visual keeps its index - and with it its place in the
5636 # layout, its size, its title and the Leaflet ids a re-render reuses - while
5637 # its C<encode> is replaced. Like the append above, the replacement is drawn
5638 # before it is stored, so an unknown column is a 400 and the saved visual is
5639 # left alone. The optional C<query> is the canvas page's URL state, so a card
5640 # edited while the canvas is cross-filtered is redrawn with the others.
5641 #
5642 # C<cross_row> is repaired the same way, and on the same request: a card's plan
5643 # is stored data like its columns, so a card that was saved with a plan this
5644 # canvas cannot honour - or with none where one is now wanted - is fixed in
5645 # place, keeping its layout slot, its size and its title. The two keys are
5646 # independent, so a repair that renames the column the pass produces writes
5647 # both in one request rather than leaving the card drawn against a column that
5648 # no longer exists. A JSON C<null> is the card giving up its plan and taking
5649 # the page's again, which is the state a card added without one is in; an
5650 # empty plan (C<{ cs => [] }>) is the card running no pass even where the page
5651 # runs one, and leaving the key out is no request to change it at all.
5652 4 ▶sub analyses_update_visual ($self) {
Subroutine analyses_update_visual: called CC=34 SCAR=50.9
Pod documented
5653 4 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
40
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5654 4 ▶ 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 4 4
5655 unless $id =~ /\A[A-Za-z0-9]+\z/;
5656  
5657 4 my $analyses = $self->_read_analyses;
5658 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5659 4 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 0 4 4
5660 4 my $a = $analyses->{$id};
5661  
5662 4 ▶ my $index = $self->stash('visual') // '';
Condition50%1/2
$self->stash("visual") // ""
l!l
40
MC/DC0%0/1
$self->stash("visual") // ""
$self->stash("visual")
Truth table50%1/2
A
A= $self->stash("visual")
Aresult
11
00
5663 4 ▶ return $self->render(json => { error => 'Visual index must be a number' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $index =~ /\A\d+\z/u 1 3 4
5664 unless $index =~ /\A\d+\z/;
5665 3 $index += 0;
5666 return $self->render(json => { error => "No visual at index $index" }, status => 404)
5667 3 ▶ unless $index < scalar @{ $a->{visuals} // [] };
Branch: 1 branch
BranchTrueFalseTotal
unless $index < scalar @{$a->{"visuals"} // [];} 1 2 3
Condition50%1/2
$a->{"visuals"} // []
l!l
30
MC/DC0%0/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table50%1/2
A
A= $a->{"visuals"}
Aresult
11
00
5668  
5669 2 my $body = eval { decode_json($self->req->body) };
5670 2 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 1 1 2
5671 unless ref $body eq 'HASH';
5672  
5673 # A text card's only settings are its options, and it reads no data.
5674 1 ▶ if (($a->{visuals}[$index]{kind} // '') eq 'text') {
Branch: 1 branch
BranchTrueFalseTotal
if (($a->{"visuals"}[$index]{"kind"} // "") eq "text") 0 1 1
Condition50%1/2
$a->{"visuals"}[$index]{"kind"} // ""
l!l
10
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
5675 return $self->render(json => { error => _message_text('error_text_card_columns') }, status => 400)
5676 0 ▶ if exists $body->{encode} || exists $body->{cross_row};
Branch: 1 branch
BranchTrueFalseTotal
if exists $body->{"encode"} or exists $body->{"cross_row"} 0 0 0
Condition0%0/3
exists $body->{"encode"} or exists $body->{"cross_row"}
l!l&&r!l&&!r
000
MC/DC0%0/2
exists $body->{"encode"} or exists $body->{"cross_row"}
exists $body->{"encode"} exists $body->{"cross_row"}
Truth table0%0/3
A or B
A= exists $body->{"encode"}B= exists $body->{"cross_row"}
ABresult
1X1
011
000
5677 return $self->render(json => { error => _message_text('error_text_card_options') }, status => 400)
5678 0 ▶ unless ref $body->{options} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body->{"options"} eq "HASH" 0 0 0
5679  
5680 0 my ($options, $errors) = _text_card_options($body->{options});
5681 0 ▶ return $self->render(json => { error => $errors->[0] }, status => 400) if @$errors;
Branch: 1 branch
BranchTrueFalseTotal
if @$errors 0 0 0
5682  
5683 0 my $vis = { %{ $a->{visuals}[$index] }, options => $options };
5684 0 $a->{visuals}[$index] = $vis;
5685 0 $a->{updated} = time();
5686 0 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 0 0 0
5687  
5688 0 return $self->render(json => _text_card_reply($id, $index, $vis));
5689 }
5690  
5691 1 my $has_encode = exists $body->{encode};
5692 1 my $has_plan = exists $body->{cross_row};
5693 1 ▶ return $self->render(json => { error => 'encode or cross_row must be given' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $has_encode or $has_plan 0 1 1
Condition33%1/3
$has_encode or $has_plan
l!l&&r!l&&!r
100
MC/DC0%0/2
$has_encode or $has_plan
$has_encode $has_plan
Truth table33%1/3
A or B
A= $has_encodeB= $has_plan
ABresult
1X1
011
000
5694 unless $has_encode || $has_plan;
5695  
5696 1 my $vis = { %{ $a->{visuals}[$index] } };
5697  
5698 1 ▶ if ($has_encode) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_encode) 1 0 1
5699 return $self->render(json => { error => 'encode must be an object' }, status => 400)
5700 1 ▶ unless ref $body->{encode} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body->{"encode"} eq "HASH" 0 1 1
5701 1 $vis->{encode} = { %{ $body->{encode} } };
5702 }
5703  
5704 1 ▶ if ($has_plan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_plan) 0 1 1
5705 0 ▶ if (defined $body->{cross_row}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $body->{'cross_row'}) { } 0 0 0
5706 return $self->render(json => { error => 'cross_row must be an object or null' }, status => 400)
5707 0 ▶ unless ref $body->{cross_row} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body->{"cross_row"} eq "HASH" 0 0 0
5708 0 my $plan = _card_plan($body->{cross_row});
5709 return $self->render(json => { error => $plan->{error} }, status => 400)
5710 0 ▶ if $plan->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $plan->{"error"} 0 0 0
5711 0 $vis->{cross_row} = $plan;
5712 }
5713 else {
5714 0 delete $vis->{cross_row};
5715 }
5716 }
5717  
5718 1 my $ctx = $self->_canvas_render_context($a, $body->{query}, [$vis]);
5719 return $self->render(json => { error => $ctx->{error} }, status => $ctx->{status})
5720 1 ▶ if $ctx->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"error"} 0 1 1
5721  
5722 # The card is drawn as it is on this page: a cross-filter applies to every
5723 # card but the one that made it, and this card may be that one.
5724 1 my $records = $ctx->{records};
5725 1 my $prefiltered = 0;
5726 1 my $late_cf = [];
5727 1 ▶ if (@{ $ctx->{cf_specs} } && $ctx->{cf_source} != $index) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ctx->{"cf_specs"};} and $ctx->{"cf_source"} != $index) 0 1 1
Condition33%1/3
@{$ctx->{"cf_specs"};} and $ctx->{"cf_source"} != $index
!ll&&!rl&&r
100
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
5728 0 ($records, $late_cf) = $self->_canvas_cross_filter($records, $ctx->{columns}, $ctx->{cf_specs});
5729 0 $prefiltered = 1;
5730 }
5731  
5732 my $rendered = $self->_render_visual_html(
5733 $vis, $records, $ctx->{columns}, $ctx->{src}, $index, $ctx->{spec_key},
5734 $prefiltered,
5735 $ctx->{cross_row},
5736 1 $late_cf,
5737 );
5738 return $self->render(json => { error => $rendered->{error} }, status => 400)
5739 1 ▶ if $rendered->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $rendered->{"error"} 0 1 1
5740  
5741 1 $a->{visuals}[$index] = $vis;
5742 1 $a->{updated} = time();
5743 1 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 1 0 1
5744  
5745 return $self->render(
5746 json => {
5747 id => $id,
5748 visual => $index,
5749 kind => ($vis->{kind} // ''),
5750 title => ($vis->{title} // $rendered->{title} // 'Visual ' . ($index + 1)),
5751 html => $rendered->{html},
5752 1 ▶ head => ($rendered->{head} // ''),
Condition45%5/11
$vis->{"kind"} // ""
l!l
10
($vis->{"title"} // $rendered->{"title"}) // 'Visual ' . ($index + 1)
l!l
10
$vis->{"title"} // $rendered->{"title"}
l!l&&r!l&&!r
100
$rendered->{"head"} // ""
l!l
01
_vis_cf_col($vis) // ""
l!l
10
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 table33%1/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
5753 # The nonce the card's scripts were written with: the page runs
5754 # only those that carry it (runCardScripts in canvas.html.tt).
5755 nonce => $self->csp_nonce,
5756 cf_col => (_vis_cf_col($vis) // ''),
5757 },
5758 );
5759 }
5760  
5761 # DELETE /api/analyses/:id/visuals/:visual (remove a text card)
5762 #
5763 # A visual's index is its identity in the layout and in a cross-filter's cv=, so
5764 # everything that names a later card moves down by one with it. The page reloads
5765 # afterwards, because the cards on screen carry the old numbers.
5766 5 ▶sub analyses_delete_visual ($self) {
Subroutine analyses_delete_visual: called CC=22 SCAR=33.2
Pod documented
5767 5 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
50
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
5768 5 ▶ 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 5 5
5769 unless $id =~ /\A[A-Za-z0-9]+\z/;
5770  
5771 5 my $analyses = $self->_read_analyses;
5772 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5773 5 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 1 4 5
5774 4 my $a = $analyses->{$id};
5775  
5776 4 ▶ my $index = $self->stash('visual') // '';
Condition50%1/2
$self->stash("visual") // ""
l!l
40
MC/DC0%0/1
$self->stash("visual") // ""
$self->stash("visual")
Truth table50%1/2
A
A= $self->stash("visual")
Aresult
11
00
5777 4 ▶ return $self->render(json => { error => 'Visual index must be a number' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $index =~ /\A\d+\z/u 1 3 4
5778 unless $index =~ /\A\d+\z/;
5779 3 $index += 0;
5780 return $self->render(json => { error => "No visual at index $index" }, status => 404)
5781 3 ▶ unless $index < scalar @{ $a->{visuals} // [] };
Branch: 1 branch
BranchTrueFalseTotal
unless $index < scalar @{$a->{"visuals"} // [];} 1 2 3
Condition50%1/2
$a->{"visuals"} // []
l!l
30
MC/DC0%0/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table50%1/2
A
A= $a->{"visuals"}
Aresult
11
00
5782 return $self->render(json => { error => _message_text('error_visual_not_text') }, status => 400)
5783 2 ▶ unless ($a->{visuals}[$index]{kind} // '') eq 'text';
Branch: 1 branch
BranchTrueFalseTotal
unless ($a->{"visuals"}[$index]{"kind"} // "") eq "text" 1 1 2
Condition50%1/2
$a->{"visuals"}[$index]{"kind"} // ""
l!l
20
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
5784  
5785 1 $a->{visuals} = [ @{ $a->{visuals} }[ grep { $_ != $index } 0 .. $#{ $a->{visuals} } ] ];
5786  
5787 1 my @layout;
5788 1 ▶ for my $entry (@{ $a->{layout} // [] }) {
Condition50%1/2
$a->{"layout"} // []
l!l
10
MC/DC0%0/1
$a->{"layout"} // []
$a->{"layout"}
Truth table50%1/2
A
A= $a->{"layout"}
Aresult
11
00
5789 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
5790 2 ▶ if ($n =~ /\A\d+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n =~ /\A\d+\z/u) 2 0 2
5791 2 ▶ next if $n == $index;
Branch: 1 branch
BranchTrueFalseTotal
if $n == $index 1 1 2
5792 1 ▶ $entry = { %$entry, visual => $n - 1 } if $n > $index;
Branch: 1 branch
BranchTrueFalseTotal
if $n > $index 0 1 1
5793 }
5794 1 push @layout, $entry;
5795 }
5796 1 ▶ $a->{layout} = \@layout if $a->{layout};
Branch: 1 branch
BranchTrueFalseTotal
if $a->{"layout"} 1 0 1
5797  
5798 1 ▶ for my $bm (grep { ref $_ eq 'HASH' && defined $_->{state} && !ref $_->{state} } @{ $a->{bookmarks} // [] }) {
Condition37%3/8
ref $_ eq 'HASH' && defined $_->{'state'} && !ref($_->{'state'})
!ll&&!rl&&r
001
ref $_ eq "HASH" and defined $_->{"state"}
!ll&&!rl&&r
001
$a->{"bookmarks"} // []
l!l
10
MC/DC0%0/3
ref $_ eq 'HASH' && defined $_->{'state'} && !ref($_->{'state'})
ref $_ eq "HASH" defined $_->{"state"} !ref($_->{'state'})
MC/DC0%0/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 table50%1/2
A
A= $a->{"bookmarks"}
Aresult
11
00
5799 1 $bm->{state} = _shift_card_param($bm->{state}, $index);
5800 }
5801  
5802 1 $a->{updated} = time();
5803 1 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 1 0 1
5804  
5805 1 return $self->render(json => { deleted => 1 });
5806 }
5807  
5808 # _shift_card_param($search, $removed) -> $search
5809 #
5810 # A saved query string with its cv= moved down if the card it names came after
5811 # the one removed. The canvas never makes a text card a cross-filter's source,
5812 # but a bookmark is stored as PATCHed, so a cv= naming the removed card is
5813 # dropped: kept, it would name the card that moved into its place. A cv= of
5814 # more than nine digits names no card (_cross_filter_source), so it is left
5815 # as it is: arithmetic on it came back as cv=1e+20. A search or index that is
5816 # not one is returned unchanged.
5817 10 ▶sub _shift_card_param {
Subroutine _shift_card_param: called CC=9 SCAR=26.1
5818 10 my ($search, $removed) = @_;
5819 10 ▶ 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 0 10 10
Condition33%4/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
0010
defined $search and not ref $search and defined $removed and not ref $removed
!ll&&!rl&&r
0010
defined $search and not ref $search and defined $removed
!ll&&!rl&&r
0010
defined $search and not ref $search
!ll&&!rl&&r
0010
MC/DC0%0/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 table16%1/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
5820 && defined($removed) && !ref($removed) && $removed =~ /\A[0-9]{1,9}\z/;
5821 10 $search =~ s{(?<![^?&])cv=(\d+)(&?)}{
5822 10 ▶ length($1) > 9 ? "cv=$1$2"
Branch: 3 branches
BranchTrueFalseTotal
length $1 > 9 ? : 0 10 10
$1 == $removed ? : 5 5 10
$1 > $removed ? : 3 2 5
5823 : $1 == $removed ? ''
5824 : ('cv=' . ($1 > $removed ? $1 - 1 : $1) . $2)
5825 }ge;
5826 10 $search =~ s{&\z}{};
5827 10 return $search;
5828 }
5829  
5830 # _text_card_options($raw) -> (\%options, \@errors)
5831 #
5832 # Purpose: The one reader of a text card's settings.
5833 # Entry: Whatever is stored or was sent; it may be any shape.
5834 # Exit: The settings that are allowed, each in its one spelling, and a message
5835 # for each that was not. Settings not asked for are absent.
5836 # Notes: A write refuses a card with errors. A render ignores them and draws
5837 # what is left, because PUT, PATCH and import can store a card that
5838 # never came through here, and nothing else stands between a stored
5839 # value and a style attribute.
5840 37 ▶sub _text_card_options {
Subroutine _text_card_options: called CC=27 SCAR=33.0
5841 37 my ($raw) = @_;
5842 37 ▶ $raw = {} unless ref $raw eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw eq "HASH" 5 32 37
5843  
5844 37 my (%clean, @errors);
5845  
5846 37 ▶ my $text = (defined $raw->{text} && !ref $raw->{text}) ? $raw->{text} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $raw->{'text'} && !ref($raw->{'text'}) ? : 31 6 37
Condition100%3/3
defined $raw->{"text"} and not ref $raw->{"text"}
!ll&&!rl&&r
5131
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
5847 37 $text =~ s/\r\n?/\n/g;
5848 37 ▶ if ($text !~ /\S/) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $text =~ /\S/u) { } 8 29 37
elsif (length $text > $MAX_TEXT_CHARS) { } 1 28 29
5849 8 push @errors, _message_text('error_text_card_empty');
5850 }
5851 elsif (length($text) > $MAX_TEXT_CHARS) {
5852 1 push @errors, sprintf(_message_text('error_text_card_long'), $MAX_TEXT_CHARS);
5853 }
5854 37 $clean{text} = $text;
5855  
5856 37 ▶ if (length(my $font = $raw->{font} // '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (length(my $font = $raw->{"font"} // "")) 5 32 37
Condition100%2/2
$raw->{"font"} // ""
l!l
532
MC/DC100%1/1
$raw->{"font"} // ""
$raw->{"font"}
Truth table100%2/2
A
A= $raw->{"font"}
Aresult
11
00
5857 5 ▶ 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 3 5
Condition100%3/3
not ref $font and exists $TEXT_FONT_CSS{$font}
!ll&&!rl&&r
122
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
5858 3 else { push @errors, _message_text('error_text_card_font') }
5859 }
5860  
5861 37 ▶ if (length(my $size = $raw->{size} // '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (length(my $size = $raw->{"size"} // "")) 8 29 37
Condition100%2/2
$raw->{"size"} // ""
l!l
829
MC/DC100%1/1
$raw->{"size"} // ""
$raw->{"size"}
Truth table100%2/2
A
A= $raw->{"size"}
Aresult
11
00
5862 8 ▶ 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 7 8
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
611
not ref $size and $size =~ /\A\d{1,3}\z/u and $size >= $MIN_TEXT_POINTS
!ll&&!rl&&r
512
not ref $size and $size =~ /\A\d{1,3}\z/u
!ll&&!rl&&r
143
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
5863 1 $clean{size} = $size + 0;
5864 }
5865 else {
5866 7 push @errors, sprintf(_message_text('error_text_card_size'), $MIN_TEXT_POINTS, $MAX_TEXT_POINTS);
5867 }
5868 }
5869  
5870 37 for my $key (qw(colour background)) {
5871 74 ▶ my $value = $raw->{$key} // '';
Condition100%2/2
$raw->{$key} // ""
l!l
1163
MC/DC100%1/1
$raw->{$key} // ""
$raw->{$key}
Truth table100%2/2
A
A= $raw->{$key}
Aresult
11
00
5872 74 ▶ next unless length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless length $value 63 11 74
5873 11 ▶ 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 9 11
Condition100%3/3
not ref $value and $value =~ /\A#[0-9a-fA-F]{6}\z/u
!ll&&!rl&&r
182
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
5874 9 else { push @errors, _message_text('error_text_card_colour') }
5875 }
5876  
5877 37 ▶ if (length(my $align = $raw->{align} // '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (length(my $align = $raw->{"align"} // "")) 2 35 37
Condition100%2/2
$raw->{"align"} // ""
l!l
235
MC/DC100%1/1
$raw->{"align"} // ""
$raw->{"align"}
Truth table100%2/2
A
A= $raw->{"align"}
Aresult
11
00
5878 2 ▶ if (!ref $align && $TEXT_ALIGNS{$align}) { $clean{align} = $align }
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $align and $TEXT_ALIGNS{$align}) { } 1 1 2
Condition66%2/3
not ref $align and $TEXT_ALIGNS{$align}
!ll&&!rl&&r
011
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
5879 1 else { push @errors, _message_text('error_text_card_align') }
5880 }
5881  
5882 37 for my $key (qw(bold italic plain)) {
5883 111 ▶ $clean{$key} = 1 if $raw->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $raw->{$key} 4 107 111
5884 }
5885  
5886 37 return (\%clean, \@errors);
5887 }
5888  
5889 # _text_card_markup(\%visual) -> $html
5890 #
5891 # The body of a text card. The text is escaped and the style holds only values
5892 # _text_card_options has checked. Spaces and line ends are written as entities
5893 # and <br>, not left to CSS, because the response minifier collapses whitespace
5894 # and the embed page has none of this page's styles.
5895 7 ▶sub _text_card_markup {
Subroutine _text_card_markup: called CC=9 SCAR=22.3
5896 7 my ($vis) = @_;
5897 7 my ($o) = _text_card_options($vis->{options});
5898  
5899 7 my @style;
5900 7 ▶ push @style, "font-family:$TEXT_FONT_CSS{$o->{font}}" if $o->{font};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"font"} 1 6 7
5901 7 ▶ push @style, "font-size:$o->{size}pt" if $o->{size};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"size"} 0 7 7
5902 7 ▶ push @style, "color:$o->{colour}" if $o->{colour};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"colour"} 0 7 7
5903 7 ▶ push @style, "background-color:$o->{background}" if $o->{background};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"background"} 0 7 7
5904 7 ▶ push @style, 'font-weight:bold' if $o->{bold};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"bold"} 1 6 7
5905 7 ▶ push @style, 'font-style:italic' if $o->{italic};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"italic"} 0 7 7
5906 7 ▶ push @style, "text-align:$o->{align}" if $o->{align};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"align"} 0 7 7
5907 7 ▶ my $style = @style ? ' style="' . xml_escape(join ';', @style) . '"' : '';
Branch: 1 branch
BranchTrueFalseTotal
@style ? : 1 6 7
5908  
5909 7 my $text = xml_escape($o->{text});
5910 7 $text =~ s/\t/ /g;
5911 7 $text =~ s/^ /&#160;/mg;
5912 7 $text =~ s/ (?= )/&#160;/g;
5913 7 $text =~ s/\n/<br>/g;
5914  
5915 7 return qq{<div class="text-card-text"$style>$text</div>};
5916 }
5917  
5918 # _text_card_title(\%visual) -> $title
5919 #
5920 # What names a text card to the controls on it and to a screen reader: the start
5921 # of its first line that has anything on it.
5922 7 ▶sub _text_card_title {
Subroutine _text_card_title: called CC=3 SCAR=11.0
5923 7 my ($vis) = @_;
5924 7 my ($o) = _text_card_options($vis->{options});
5925 7 my ($line) = $o->{text} =~ /^[ \t]*(\S[^\n]*)/m;
5926 7 ▶ return 'Text' unless defined $line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 2 5 7
5927 5 $line =~ s/\s+\z//;
5928 5 ▶ return length($line) > $TEXT_TITLE_CHARS ? substr($line, 0, $TEXT_TITLE_CHARS) . '...' : $line;
Branch: 1 branch
BranchTrueFalseTotal
length $line > $TEXT_TITLE_CHARS ? : 1 4 5
5929 }
5930  
5931 # _text_card_plain(\%visual) -> $bool
5932 #
5933 # Whether the card hides its frame and header until it is pointed at.
5934 32 ▶sub _text_card_plain {
Subroutine _text_card_plain: called CC=4 SCAR=13.9
5935 32 my ($vis) = @_;
5936 32 ▶ return 0 unless ($vis->{kind} // '') eq 'text';
Branch: 1 branch
BranchTrueFalseTotal
unless ($vis->{"kind"} // "") eq "text" 29 3 32
Condition100%2/2
$vis->{"kind"} // ""
l!l
248
MC/DC100%1/1
$vis->{"kind"} // ""
$vis->{"kind"}
Truth table100%2/2
A
A= $vis->{"kind"}
Aresult
11
00
5937 3 my ($o) = _text_card_options($vis->{options});
5938 3 ▶ return $o->{plain} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$o->{'plain'} ? : 1 2 3
5939 }
5940  
5941 # _text_card_reply($id, $index, \%visual) -> \%json
5942 2 ▶sub _text_card_reply {
Subroutine _text_card_reply: called CC=2 SCAR=7.1
5943 2 my ($id, $index, $vis) = @_;
5944 return {
5945 id => $id,
5946 visual => $index,
5947 kind => 'text',
5948 2 ▶ title => ($vis->{title} // _text_card_title($vis)),
Condition66%2/3
$vis->{"title"} // _text_card_title($vis)
l!l&&r!l&&!r
110
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
5949 html => _text_card_markup($vis),
5950 head => '',
5951 cf_col => '',
5952 plain => _text_card_plain($vis),
5953 };
5954 }
5955  
5956 # GET /api/analyses/:id/export
5957 21 ▶sub analyses_export ($self) {
Subroutine analyses_export: called CC=4 SCAR=13.9
Pod documented
5958 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
5959 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 2 19 21
5960 unless $id =~ /\A[A-Za-z0-9]+\z/;
5961  
5962 19 my $analyses = $self->_read_analyses;
5963 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5964 19 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 4 15 19
5965  
5966 15 my $json = encode_json($analyses->{$id});
5967 15 $self->res->headers->content_disposition("attachment; filename=\"analysis-$id.json\"");
5968 15 $self->render(data => $json, format => 'json');
5969 }
5970  
5971 # POST /api/analyses/import (create from uploaded JSON or raw body)
5972 13 ▶sub analyses_import ($self) {
Subroutine analyses_import: called CC=9 SCAR=22.5
Pod documented
5973 13 my $upload = $self->req->upload('file');
5974 13 ▶ my $body_json = $upload ? $upload->slurp : $self->req->body;
Branch: 1 branch
BranchTrueFalseTotal
$upload ? : 0 13 13
5975  
5976 13 my $body = eval { decode_json($body_json) };
5977 13 ▶ return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 7 6 13
5978 unless ref $body eq 'HASH';
5979  
5980 # Strip any id/timestamps from imported document; assign fresh ones below
5981 6 delete @{$body}{qw( id created updated )};
5982 6 _drop_unknown_keys($body);
5983  
5984 6 my $err = $self->_validate_analysis($body);
5985 6 ▶ return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $err) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if $err 4 2 6
5986 if $err;
5987  
5988 2 ▶ unless ($self->_analyses_path) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_analyses_path) 0 2 2
5989 0 return $self->render(json => { error => _message_text('error_analysis_storage') }, status => 503);
5990 }
5991  
5992 2 my $analyses = $self->_read_analyses;
5993  
5994 2 my $id;
5995 2 my $tries = 0;
5996 2 do { $id = $self->_gen_analysis_id; $tries++ }
5997 2 ▶ 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 2 2
Condition33%1/3
exists $analyses->{$id} and $tries < 100
!ll&&!rl&&r
200
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
5998  
5999 2 $body->{id} = $id;
6000 2 ▶ $body->{version} //= 1;
Condition50%1/2
$body->{"version"} //= 1
l!l
20
MC/DC0%0/1
$body->{"version"} //= 1
$body->{"version"}
Truth table50%1/2
A
A= $body->{"version"}
Aresult
11
00
6001 2 $body->{created} = time();
6002 2 $body->{updated} = time();
6003  
6004 2 $analyses->{$id} = $body;
6005 2 ▶ $self->_save_analyses_or_503($analyses) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_save_analyses_or_503($analyses) or return 2 0 2
6006  
6007 2 $self->res->headers->location("/api/analyses/$id");
6008 2 $self->render(json => { id => $id, imported => 1 }, status => 201);
6009 }
6010  
6011 # _cross_filter_source($cv) -> Int
6012 #
6013 # The index of the card a cross-filter came from (cv=), or -1 for none. Only
6014 # a whole number names a card: int('abc') is 0, which would draw the first
6015 # card unfiltered as if it were the source.
6016 52 ▶sub _cross_filter_source {
Subroutine _cross_filter_source: called CC=3 SCAR=11.0
6017 52 my $cv = shift;
6018 52 ▶ 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 ? : 3 49 52
Condition100%3/3
defined $cv and $cv =~ /\A[0-9]{1,9}\z/u
!ll&&!rl&&r
39103
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
6019 }
6020  
6021 # _build_canvas_pipeline($self, \%analysis) -> ($src, $records, \@cols) or ()
6022 #
6023 # Opens the first dataset from a saved analysis and chains any declared joins.
6024 # Returns the base pipeline triple for _render_visual_html.
6025 # Returns an empty list on any error so canvas_render can respond 422.
6026 # _canvas_render_context($self, \%analysis, $query) -> \%ctx | { error, status }
6027 #
6028 # The state a card is drawn through when it is rendered outside canvas_render:
6029 # the base pipeline, calculated columns, bound parameters and the cross-filters
6030 # named by a canvas page's query string. C<cf_specs> are returned unapplied so
6031 # the caller can decide which card, if any, is their source; C<cf_source> is
6032 # the C<cv> index, or -1 when the page names none. C<cross_row> is the
6033 # validated cs= plan, undef when the page names none, which the caller passes to
6034 # _render_visual_html so each card runs it over its own rows. Only C<cf>,
6035 # C<cv>, C<c>, C<cs>, C<by>, C<order>, C<range>, C<rcol> and C<p.<name>> are read
6036 # from C<$query> - the same keys canvas_render reads from its own URL - so a
6037 # page's state is not a way to reach anything else.
6038 28 ▶sub _canvas_render_context :Protected ($self, $a, $query, $more_cards = undef) {
Subroutine _canvas_render_context: called CC=21 SCAR=31.2
6039 28 my $params;
6040 28 ▶ if (defined $query) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query) 23 5 28
6041 23 ▶ return { error => 'query must be a string', status => 400 }
Branch: 1 branch
BranchTrueFalseTotal
if ref $query or length $query > 4096 2 21 23
Condition100%3/3
ref $query or length $query > 4096
l!l&&r!l&&!r
1121
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
6042 if ref $query || length($query) > 4096;
6043 21 (my $qs = $query) =~ s/\A\?//;
6044 21 $params = Mojo::Parameters->new($qs);
6045 }
6046  
6047 26 my ($src, $records, $columns) = $self->_build_canvas_pipeline($a);
6048 26 ▶ return { error => 'Cannot open data source for this canvas', status => 422 }
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 25 26
6049 unless defined $records;
6050  
6051 my ($bound_ref, $p_errors) = $self->_bound_canvas_params(
6052 2 ▶ $a, sub { $params ? $params->param($_[0]) : undef },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$params ? : 2 0 2
6053 25 );
6054 25 ▶ return { error => join('; ', @$p_errors), status => 400 }
Branch: 1 branch
BranchTrueFalseTotal
if @$p_errors 0 25 25
6055 if @$p_errors;
6056 25 my %param_values = %$bound_ref;
6057  
6058 25 ▶ 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
2050
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
6059 25 $self->stash('_canvas_window_names' => $window_names);
6060  
6061 25 eval {
6062 ($records, $columns) = $self->_apply_calc_fields(
6063 $records, $columns,
6064 {
6065 params => \%param_values,
6066 spec_key => ($a->{datasets}[0]{spec} // ''),
6067 25 ▶ calc => [ $params ? @{ $params->every_param('c') // [] } : () ],
Branch: 1 branch
BranchTrueFalseTotal
$params ? : 20 5 25
Condition50%2/4
$a->{"datasets"}[0]{"spec"} // ""
l!l
250
$params->every_param("c") // []
l!l
200
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
6068 window_columns => $window_names,
6069 }
6070 );
6071 };
6072 25 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 24 25
6073 1 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
6074 1 return { error => $e, status => 400 };
6075 }
6076  
6077 # The canvas names cs= once and every card runs the same plan over its own
6078 # rows (see _render_visual_html). Validated here, against the columns the
6079 # cards will be drawn from, so a card added or edited in place fails with
6080 # the same 400 the page itself would give.
6081 24 ▶ my $cross_row = $self->_cross_row_specs($columns, $params || Mojo::Parameters->new);
Condition66%2/3
$params || 'Mojo::Parameters'->new
l!l&&r!l&&!r
1950
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
6082 return { error => $cross_row->{error}, status => 400 }
6083 24 ▶ if $cross_row && $cross_row->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $cross_row and $cross_row->{"error"} 0 24 24
Condition33%1/3
$cross_row and $cross_row->{"error"}
!ll&&!rl&&r
2400
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
6084  
6085 24 ▶ my @cf_specs = $params ? grep { /\S/ } @{ $params->every_param('cf') // [] } : ();
Branch: 1 branch
BranchTrueFalseTotal
$params ? : 19 5 24
Condition50%1/2
$params->every_param("cf") // []
l!l
190
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
6086 24 ▶ my $cf_source = _cross_filter_source($params ? $params->param('cv') : undef);
Branch: 1 branch
BranchTrueFalseTotal
$params ? : 19 5 24
6087  
6088 # The relative time range the canvas page names in its query string is part
6089 # of the state a card is drawn through, like cf= and the bound parameters,
6090 # so a visual added while a range is active shows the same rows as the
6091 # cards already on screen.
6092 24 ▶ $records = _apply_time_range(
Branch: 2 branches
BranchTrueFalseTotal
$params ? : 19 5 24
$params ? : 19 5 24
6093 $records,
6094 $params ? $params->param('range') : undef,
6095 $params ? $params->param('rcol') : undef,
6096 );
6097  
6098 return {
6099 src => $src,
6100 records => $records,
6101 columns => $columns,
6102 24 ▶ spec_key => ($a->{datasets}[0]{spec} // ''),
Condition50%1/2
$a->{"datasets"}[0]{"spec"} // ""
l!l
240
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
6103 cf_specs => \@cf_specs,
6104 cf_source => $cf_source,
6105 cross_row => $cross_row,
6106 };
6107 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
6108  
6109 49 ▶sub _build_canvas_pipeline :Protected ($self, $analysis) {
Subroutine _build_canvas_pipeline: called CC=21 SCAR=33.5
6110 49 ▶ my @datasets = @{ $analysis->{datasets} // [] };
Condition100%2/2
$analysis->{"datasets"} // []
l!l
481
MC/DC100%1/1
$analysis->{"datasets"} // []
$analysis->{"datasets"}
Truth table100%2/2
A
A= $analysis->{"datasets"}
Aresult
11
00
6111 49 ▶ return () unless @datasets;
Branch: 1 branch
BranchTrueFalseTotal
unless @datasets 2 47 49
6112  
6113 47 ▶ my $left_spec = $datasets[0]{spec} or return ();
Branch: 1 branch
BranchTrueFalseTotal
my $left_spec = $datasets[0]{"spec"} or return () 46 1 47
6114 46 my ($left_src) = $self->_open_spec($left_spec);
6115 46 ▶ return () unless $left_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $left_src 1 45 46
6116  
6117 45 ▶ 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
0450
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
6118 45 my $src = $left_src;
6119  
6120 # Build alias -> spec lookup for join resolution.
6121 45 my %spec_by_alias;
6122 45 for my $ds (@datasets) {
6123 46 ▶ $spec_by_alias{ $ds->{alias} // '' } = $ds->{spec} // '';
Condition75%3/4
$ds->{"spec"} // ""
l!l
460
$ds->{"alias"} // ""
l!l
640
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
6124 }
6125  
6126 45 ▶ for my $j (@{ $analysis->{joins} // [] }) {
Condition100%2/2
$analysis->{"joins"} // []
l!l
144
MC/DC100%1/1
$analysis->{"joins"} // []
$analysis->{"joins"}
Truth table100%2/2
A
A= $analysis->{"joins"}
Aresult
11
00
6127 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
6128 2 ▶ next unless length $right_spec;
Branch: 1 branch
BranchTrueFalseTotal
unless length $right_spec 1 1 2
6129 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
6130 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
6131 1 ▶ next unless length $left_key;
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_key 1 0 1
6132  
6133 0 my ($right_src) = $self->_open_spec($right_spec);
6134 0 ▶ next unless $right_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_src 0 0 0
6135  
6136 0 require Database::Join;
6137 0 ▶ $src = Database::Join->new(
Branch: 1 branch
BranchTrueFalseTotal
$left_key ne $right_key ? : 0 0 0
6138 databases => [$src, $right_src],
6139 join_column => $left_key,
6140 backend => 'auto',
6141 max_array_rows => $max_rows,
6142 ($left_key ne $right_key ? (join_map => {1 => $right_key}) : ()),
6143 );
6144 }
6145  
6146 45 my $records = eval { $src->selectall_arrayref };
6147 45 ▶ return () if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 45 45
6148 45 ▶ $records //= [];
Condition50%1/2
$records //= []
l!l
450
MC/DC0%0/1
$records //= []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
6149 45 my @columns = _get_columns($src, $records);
6150  
6151 45 return ($src, $records, \@columns);
6152 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
6153  
6154 # _chart_json($self, \%chart_spec) -> $json_for_a_data_attribute
6155 #
6156 # The chart templates put this in the New canvas panel's data-chart attribute
6157 # so the canvas buttons can save the chart exactly as it is drawn, including
6158 # options the URL does not carry. Escape '<' as well, so the value is inert
6159 # even if a title or column name contains markup.
6160 298 ▶sub _chart_json :Protected ($self, $chart) {
Subroutine _chart_json: called CC=1 SCAR=0.0
6161 298 my $json = encode_json($chart);
6162 298 $json =~ s{<}{\\u003c}g;
6163 298 return $json;
6164 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
6165  
6166 # _chart_orientation(\%options) -> 'horizontal' | 'vertical'
6167 #
6168 # The chart pages store a bar's direction as options.orientation, the spelling
6169 # their URL uses, while the canvas used to read options.orient; both are read
6170 # here. The values the pages emit are v/h and vertical/horizontal.
6171 21 ▶sub _chart_orientation {
Subroutine _chart_orientation: called CC=4 SCAR=13.9
6172 21 my ($options) = @_;
6173  
6174 21 ▶ my $orient = $options->{orientation} // $options->{orient} // '';
Condition100%5/5
($options->{"orientation"} // $options->{"orient"}) // ""
l!l
714
$options->{"orientation"} // $options->{"orient"}
l!l&&r!l&&!r
6114
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
6175 21 ▶ return ($orient =~ /\A(?:h|horizontal)\z/i) ? 'horizontal' : 'vertical';
Branch: 1 branch
BranchTrueFalseTotal
$orient =~ /\A(?:h|horizontal)\z/iu ? : 4 17 21
6176 }
6177  
6178 # _visual_measure($agg_fn, $val_col) -> \%measure
6179 #
6180 # The measure a canvas card aggregates a value column with: C<{ fn, val,
6181 # label }> when the card can be drawn, or C<{ error }> when it cannot, which
6182 # the card reports in place of its chart.
6183 #
6184 # A card that names no function keeps the default it has always had: count the
6185 # rows when it names no value column, sum it when it does. A named function is
6186 # the measure vocabulary the pivot and the stats page share, with a percentile
6187 # riding in the name as p<N> -- p90, p50 -- exactly as a pivot's measure spells
6188 # it, so a card needs no second key to keep in step. 'count' counts rows, so it
6189 # ignores the value column and needs none.
6190 #
6191 # label is what the card's title calls the result: 'Count', the column's own
6192 # name for a plain sum, and "fn(col)" for anything else, so two cards over one
6193 # column do not read alike when one of them is a median. An explicit sum keeps
6194 # the plain name, because naming the default should not change a card.
6195 #
6196 # The name itself is not checked here: _render_visual_html validates it once,
6197 # before the dispatch, so that a card of any kind reports a function it cannot
6198 # compute -- including the kinds that never call this.
6199 47 ▶sub _visual_measure {
Subroutine _visual_measure: called CC=14 SCAR=26.4
6200 47 my ($agg_fn, $val_col) = @_;
6201 47 ▶ 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
10235
defined $val_col && length $val_col
!ll&&!rl&&r
4637
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
6202 # An absent name and an empty one are the same non-choice, so the default is
6203 # one branch rather than two.
6204 47 ▶ 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 20 47
Condition83%5/6
defined $agg_fn and not ref $agg_fn and length $agg_fn
!ll&&!rl&&r
19127
defined $agg_fn and not ref $agg_fn
!ll&&!rl&&r
19028
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
6205  
6206 47 ▶ return { fn => 'count', val => undef, label => 'Count' }
Branch: 1 branch
BranchTrueFalseTotal
if defined $named and $named eq "count" 2 45 47
Condition100%3/3
defined $named and $named eq "count"
!ll&&!rl&&r
20252
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
6207 if defined $named && $named eq 'count';
6208 45 ▶ return { fn => 'count', val => undef, label => 'Count' }
Branch: 1 branch
BranchTrueFalseTotal
if not defined $named and $count_col 6 39 45
Condition100%3/3
not defined $named and $count_col
!ll&&!rl&&r
25146
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
6209 if !defined $named && $count_col;
6210 39 ▶ return { error => "Aggregate '$named' needs a value column" }
Branch: 1 branch
BranchTrueFalseTotal
if defined $named and $count_col 5 34 39
Condition100%3/3
defined $named and $count_col
!ll&&!rl&&r
14205
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
6211 if defined $named && $count_col;
6212  
6213 34 ▶ my $fn = defined $named ? $named : 'sum';
Branch: 1 branch
BranchTrueFalseTotal
defined $named ? : 20 14 34
6214 return {
6215 34 ▶ fn => $fn,
Branch: 1 branch
BranchTrueFalseTotal
$fn eq 'sum' ? : 17 17 34
6216 val => $val_col,
6217 label => ($fn eq 'sum' ? $val_col : "$fn($val_col)"),
6218 };
6219 }
6220  
6221 # _render_visual_html($self, \%vis, $records, \@columns, $src, $vis_id, $spec_key,
6222 # $prefiltered, $cross_row)
6223 # -> { html => Str, title => Str, head => Str } | { error => Str }
6224 #
6225 # Renders one canvas visual spec to an HTML snippet without touching
6226 # $self->render(), with each of the card's inline scripts closed over a
6227 # function of its own (see _scope_card_scripts). The scoping is done here
6228 # rather than by the callers because every card passes through here and every
6229 # caller wants the same thing: a card's script and the page's are separate
6230 # programs, whether the card is drawn on a canvas of its own kind or returned
6231 # to a page that is about to insert it.
6232 37 ▶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
6233 37 my $rendered = $self->_render_visual_markup(
6234 $vis, $records, $columns, $src, $vis_id, $spec_key, $prefiltered, $cross_row, $late_cf,
6235 );
6236 37 ▶ return $rendered unless defined $rendered->{html};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rendered->{"html"} 19 18 37
6237  
6238 18 $rendered->{html} = _scope_card_scripts($rendered->{html});
6239 18 return $rendered;
6240 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
6241  
6242 # _render_visual_markup($self, \%vis, $records, \@columns, $src, $vis_id,
6243 # $spec_key, $prefiltered, $cross_row)
6244 # -> { html => Str, title => Str, head => Str } | { error => Str }
6245 #
6246 # The card itself, without the scope _render_visual_html puts around its
6247 # scripts. Applies any per-visual filters, then dispatches by
6248 # kind to the appropriate renderer. $vis_id gives a map's Leaflet element
6249 # ids a page-unique suffix; $spec_key is the dataset whose older per-dataset
6250 # geocode entry may still be read while the shared cache is migrated.
6251 # $cross_row is the canvas's validated cs= plan, run here so that each card's
6252 # window is over that card's own rows: see the note at the pass below. A card
6253 # that saved a plan of its own uses that one instead. $late_cf holds the
6254 # cross-filter specs on columns a plan writes (_canvas_cross_filter); a card
6255 # whose plan does not write the column has nothing to filter by, and ignores it.
6256 37 ▶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=105.7
6257 37 ▶ my $kind = $vis->{kind} // '';
Condition100%2/2
$vis->{"kind"} // ""
l!l
316
MC/DC100%1/1
$vis->{"kind"} // ""
$vis->{"kind"}
Truth table100%2/2
A
A= $vis->{"kind"}
Aresult
11
00
6258 37 ▶ return { html => _text_card_markup($vis), title => _text_card_title($vis) }
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "text" 2 35 37
6259 if $kind eq 'text';
6260  
6261 # A stored card is not checked part by part (PUT and import keep a visual
6262 # as sent), so a part of the wrong shape is read as absent here rather than
6263 # dereferenced.
6264 35 ▶ my $encode = ref($vis->{encode}) eq 'HASH' ? $vis->{encode} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $vis->{'encode'} eq 'HASH' ? : 21 14 35
6265 35 ▶ my $options = ref($vis->{options}) eq 'HASH' ? $vis->{options} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $vis->{'options'} eq 'HASH' ? : 7 28 35
6266 0 ▶ my $filters = ref($vis->{filters}) eq 'ARRAY' ? [ grep { defined && !ref } @{ $vis->{filters} } ] : [];
Branch: 1 branch
BranchTrueFalseTotal
ref $vis->{'filters'} eq 'ARRAY' ? : 0 35 35
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
6267 35 ▶ my $title = $vis->{title} // '';
Condition100%2/2
$vis->{"title"} // ""
l!l
431
MC/DC100%1/1
$vis->{"title"} // ""
$vis->{"title"}
Truth table100%2/2
A
A= $vis->{"title"}
Aresult
11
00
6268  
6269 # Every chart on a canvas needs an element id of its own: HTML::D3 names the
6270 # SVG after the chart kind by default, so two bar cards both write #bar_chart
6271 # and the second card's script draws into the first. The id carries the
6272 # visual's index, which is stable across renders, so a saved canvas and a
6273 # card appended in place agree; the chart pages render one chart and keep
6274 # HTML::D3's default.
6275 35 ▶ my $svg_id = 'vis-' . (defined($vis_id) ? $vis_id : 'chart');
Branch: 1 branch
BranchTrueFalseTotal
defined $vis_id ? : 35 0 35
6276  
6277 # A card that carries a cross-row plan of its own (visual.cross_row) runs that
6278 # plan instead of the page's: putting a running total on one card is not a
6279 # request to put one on every card, and a card whose plan is empty has none
6280 # at all rather than the page's. Its plan is validated here rather than
6281 # when it was saved, because the columns a saved canvas has are the columns
6282 # its data file has today. A card's own plan is its own fault, so a bad one
6283 # is that card's error while the page's bad plan is the page's 400.
6284 35 my $plan = $cross_row;
6285 35 ▶ if (ref $vis->{cross_row} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $vis->{"cross_row"} eq "HASH") 0 35 35
6286 0 $plan = $self->_cross_row_specs_from($columns, $vis->{cross_row});
6287 return { error => $plan->{error} }
6288 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
6289 }
6290  
6291 # Apply per-visual filters on top of the base pipeline records. One on a column
6292 # this card's plan writes waits for the pass, as it does on a table page.
6293 my %written = $plan
6294 0 ? (map({ $_->{as} => 1 } @{ $plan->{specs} }),
6295 0 ▶ map({ $_->{name} => 1 } @{ $self->stash('_held_calc_fields') // [] }))
Branch: 1 branch
BranchTrueFalseTotal
$plan ? : 0 35 35
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
6296 : ();
6297 35 my $vis_recs = $records;
6298 35 my @late_filters;
6299 35 for my $f (@$filters) {
6300 0 ▶ if ($written{ (split /:/, $f, 2)[0] // '' }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($written{(split(/:/u, $f, 2))[0] // ""}) 0 0 0
Condition0%0/2
(split(/:/u, $f, 2))[0] // ""
l!l
00
MC/DC0%0/1
(split(/:/u, $f, 2))[0] // ""
(split(/:/u, $f, 2))[0]
Truth table0%0/2
A
A= (split(/:/u, $f, 2))[0]
Aresult
11
00
6301 0 push @late_filters, $f;
6302 0 next;
6303 }
6304 0 $vis_recs = _apply_filter_spec($vis_recs, $f);
6305 }
6306  
6307 # Stage 6, per card. A canvas names cs= once, but by the time the pass runs
6308 # the card has already been narrowed by its own filters and by the page's
6309 # cross-filter, so a running total is over the rows that card is drawn from:
6310 # two cards showing different regions show different running totals. The
6311 # pass therefore cannot be hoisted above the card loop -- one shared pass
6312 # would give every card the same numbers, and those are the numbers of
6313 # neither card. A fault is this card's error, not the page's: the plan was
6314 # validated once, and only the arithmetic can still fail here.
6315 35 ▶ if ($plan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plan) 0 35 35
6316 # The pass writes its column onto the rows it is handed, and a card is
6317 # handed the canvas's rows -- the same hashrefs every card draws from. The
6318 # numbers a pass produces are that card's, so it runs on copies: without
6319 # them one card's running total is written into its neighbour's rows, and a
6320 # card that asked for no plan at all reads a column it never asked for.
6321 0 ▶ my $own = [ map { ref $_ eq 'HASH' ? { %$_ } : $_ } @$vis_recs ];
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 0 0 0
6322 0 my ($crossed, $crossed_cols) = eval {
6323 0 my ($r, $c) = $self->_apply_cross_row($own, $columns, $plan);
6324 0 $self->_apply_held_calc_fields($r, $c, 1);
6325 };
6326 0 ▶ if (my $e = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $e = $@) 0 0 0
6327 0 $e =~ s/ at \S+ line \d+\.?\n?$//;
6328 0 return { error => $e };
6329 }
6330 0 ($vis_recs, $columns) = ($crossed, $crossed_cols);
6331 }
6332  
6333 35 my %col_set = map { $_ => 1 } @$columns;
6334  
6335 $vis_recs = _apply_filter_spec($vis_recs, $_)
6336 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
2213
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
6337  
6338 # The aggregate function this card picked for itself, if any (encode.agg).
6339 # It is read and checked here, before the dispatch, so a misspelt function
6340 # is this card's error whatever kind it is, rather than a chart quietly
6341 # drawn some other way; the kinds that aggregate then honour it below. A
6342 # percentile rides in the name (p90, p50), as it does in a pivot measure, so
6343 # there is no second key to keep in step.
6344 35 my $agg_fn = $encode->{agg};
6345 35 ▶ 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 35 35
Condition33%2/6
defined $agg_fn and not ref $agg_fn and length $agg_fn
!ll&&!rl&&r
3500
defined $agg_fn and not ref $agg_fn
!ll&&!rl&&r
3500
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
6346 0 ▶ return { error => "Unknown aggregate function '$agg_fn'; expected one of: "
Branch: 1 branch
BranchTrueFalseTotal
unless _measure_fn_ok($agg_fn) 0 0 0
6347 . join(' ', @MEASURE_FNS) . ', or p1 to p100 for a percentile' }
6348 unless _measure_fn_ok($agg_fn);
6349 } else {
6350 35 $agg_fn = undef;
6351 }
6352  
6353 # A chart aggregates the rows it is given. The SQL push path in
6354 # _grouped_totals re-reads the source, which has none of the filters the
6355 # caller already applied (a cross-filter, or this visual's own filters), so
6356 # those rows have to be folded in Perl. Passing no source is how the
6357 # pipeline says so.
6358 35 ▶ my $agg_src = (@$filters || $prefiltered) ? undef : $src;
Branch: 1 branch
BranchTrueFalseTotal
@$filters || $prefiltered ? : 1 34 35
Condition66%2/3
@$filters or $prefiltered
l!l&&r!l&&!r
0134
MC/DC50%1/2
@$filters or $prefiltered
@$filters $prefiltered
Truth table66%2/3
A or B
A= @$filtersB= $prefiltered
ABresult
1X1
011
000
6359  
6360 35 require HTML::D3;
6361  
6362 # ------------------------------------------------------------------ bar --
6363 35 ▶ if ($kind eq 'bar') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "bar") 22 13 35
6364 22 ▶ my $cat_col = $encode->{cat} // '';
Condition100%2/2
$encode->{"cat"} // ""
l!l
184
MC/DC100%1/1
$encode->{"cat"} // ""
$encode->{"cat"}
Truth table100%2/2
A
A= $encode->{"cat"}
Aresult
11
00
6365 22 ▶ my $val_col = $encode->{value} // '';
Condition100%2/2
$encode->{"value"} // ""
l!l
1210
MC/DC100%1/1
$encode->{"value"} // ""
$encode->{"value"}
Truth table100%2/2
A
A= $encode->{"value"}
Aresult
11
00
6366 22 ▶ return { error => 'Missing cat column for bar visual' } unless length $cat_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col 4 18 22
6367 18 ▶ return { error => "Column not found: $cat_col" } unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 5 13 18
6368 13 ▶ 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
0310
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
6369 return { error => "Column not found: $val_col" }
6370 13 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 0 13 13
Condition66%2/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
3100
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
6371  
6372 13 my $m = _visual_measure($agg_fn, $val_col);
6373 13 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 13 13
6374  
6375 my $agg = $self->_grouped_totals(
6376 { source => $agg_src, records => $vis_recs },
6377 { by => [$cat_col], fn => $m->{fn},
6378 13 val => $m->{val}, as => 'value' },
6379 );
6380 13 ▶ return { error => 'No plottable data' } unless @$agg;
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg 0 13 13
6381  
6382 13 ▶ $title ||= "$m->{label} by $cat_col";
Condition100%2/2
$title ||= qq[$m->{"label"} by $cat_col]
l!l
49
MC/DC100%1/1
$title ||= qq[$m->{"label"} by $cat_col]
$title
Truth table100%2/2
A
A= $title
Aresult
11
00
6383 13 my @bars = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg;
6384 13 my $orient = _chart_orientation($options);
6385 # The bar page caps its bars as max_bars and stores the cap as
6386 # max_items; the seed has to carry it or a seeded canvas draws every
6387 # category where the page drew the top few and Other.
6388 13 ▶ my $max_bars = int($options->{max_items} // $options->{max_bars} // 0);
Condition40%2/5
($options->{"max_items"} // $options->{"max_bars"}) // 0
l!l
013
$options->{"max_items"} // $options->{"max_bars"}
l!l&&r!l&&!r
0013
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
6389 13 ▶ 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 13 13
6390 ->render_bar_chart_snippet(\@bars, {
6391 orientation => $orient,
6392 x_label => $cat_col,
6393 id => $svg_id,
6394 ($max_bars > 0 ? (max_bars => $max_bars) : ()),
6395 });
6396 13 my $html = $sn->{html};
6397 13 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 13 13
6398 13 return { html => $html, title => $title };
6399 }
6400  
6401 # ------------------------------------------------------------------ pie --
6402 13 ▶ if ($kind eq 'pie') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "pie") 1 12 13
6403 1 ▶ my $cat_col = $encode->{cat} // '';
Condition50%1/2
$encode->{"cat"} // ""
l!l
10
MC/DC0%0/1
$encode->{"cat"} // ""
$encode->{"cat"}
Truth table50%1/2
A
A= $encode->{"cat"}
Aresult
11
00
6404 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
6405 1 ▶ return { error => 'Missing cat or val column for pie visual' }
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col and length $val_col 0 1 1
Condition33%1/3
length $cat_col and length $val_col
!ll&&!rl&&r
001
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
6406 unless length($cat_col) && length($val_col);
6407 1 ▶ return { error => "Column not found: $cat_col" } unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 0 1 1
6408 1 my $count_mode = ($val_col eq '__count__');
6409 return { error => "Column not found: $val_col" }
6410 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
6411  
6412 1 my $m = _visual_measure($agg_fn, $val_col);
6413 1 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 1 1
6414  
6415 my $agg = $self->_grouped_totals(
6416 { source => $agg_src, records => $vis_recs },
6417 { by => [$cat_col], fn => $m->{fn},
6418 1 val => $m->{val}, as => 'value' },
6419 );
6420 1 ▶ return { error => 'No plottable data' } unless @$agg;
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg 0 1 1
6421  
6422 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
6423 1 my @slices = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg;
6424 1 my $scheme = _categorical_scheme($options->{scheme});
6425 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6426 ->render_pie_chart_snippet(\@slices, {
6427 1 ▶ donut => $options->{donut} ? 1 : 0,
Branch: 1 branch
BranchTrueFalseTotal
$options->{'donut'} ? : 0 1 1
6428 legend => 1,
6429 color_scheme => $scheme,
6430 id => $svg_id,
6431 });
6432 1 my $html = $sn->{html};
6433 1 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 1 1
6434 1 return { html => $html, title => $title };
6435 }
6436  
6437 # -------------------------------------------------------------- line/graph --
6438 12 ▶ if ($kind eq 'line' || $kind eq 'graph') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "line" or $kind eq "graph") 0 12 12
Condition33%1/3
$kind eq "line" or $kind eq "graph"
l!l&&r!l&&!r
0012
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
6439 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
6440 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
6441 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
6442 unless length($x_col) && length($y_col);
6443 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
6444 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
6445  
6446 # encode.series is what /graph's "Add to canvas" saves from series=: one
6447 # line per value of that column, as on the page. Without it every row
6448 # is one line, which runs through all the groups' points in turn.
6449 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
6450 0 ▶ $series_col = '' if ref $series_col;
Branch: 1 branch
BranchTrueFalseTotal
if ref $series_col 0 0 0
6451 return { error => "Column not found: $series_col" }
6452 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
6453  
6454 # A card whose spec names a measure plots one point per x value rather
6455 # than one per row: the shape /graph?agg= draws, and the only shape that
6456 # makes sense when the x axis is a bucket. The fold writes its result
6457 # back under the y column's own name, so the loop below is the same one
6458 # an unaggregated card runs, and the groups arrive in label order, which
6459 # for an ISO bucket is chronological order. With a series the fold is
6460 # per x value and series value, so each line has its own totals.
6461 0 my $rows = $vis_recs;
6462 0 my $m;
6463 0 ▶ if (defined $agg_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $agg_fn) 0 0 0
6464 0 $m = _visual_measure($agg_fn, $y_col);
6465 0 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 0 0
6466 my $agg = $self->_grouped_totals(
6467 { source => undef, records => $vis_recs },
6468 { by => [ $x_col, (length $series_col ? $series_col : ()) ],
6469 0 ▶ fn => $m->{fn}, val => $m->{val}, as => 'value' },
Branch: 1 branch
BranchTrueFalseTotal
length $series_col ? : 0 0 0
6470 );
6471 0 $rows = [ map { { %$_, $y_col => $_->{value} } } @$agg ];
6472 }
6473  
6474 0 my $sn;
6475 0 ▶ if (length $series_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col) { } 0 0 0
6476 # The order /graph draws, so each line has the page's colour:
6477 # aggregated, lines by name and points by label; unaggregated, lines
6478 # as first met and each keeping its rows' order.
6479 0 my (%points_of, @names);
6480 0 for my $row (@$rows) {
6481 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
6482 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
6483 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
6484 0 $name = _decode_cell($name);
6485 0 ▶ push @names, $name unless $points_of{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless $points_of{$name} 0 0 0
6486 0 push @{ $points_of{$name} }, { label => _decode_cell($xv), value => $yn };
6487 }
6488 0 ▶ return { error => 'No plottable data' } unless @names;
Branch: 1 branch
BranchTrueFalseTotal
unless @names 0 0 0
6489 my @series_data = map {
6490 0 my $points = $points_of{$_};
6491 0 ▶ $points = [ sort { $a->{label} cmp $b->{label} } @$points ] if $m;
Branch: 1 branch
BranchTrueFalseTotal
if $m 0 0 0
6492 0 ▶ { name => $_, data => $points };
Branch: 1 branch
BranchTrueFalseTotal
$m ? : 0 0 0
6493 } ($m ? sort @names : @names);
6494  
6495 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
6496 0 $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6497 ->render_multi_series_line_chart_snippet(\@series_data, { id => $svg_id });
6498 } else {
6499 0 my @pairs;
6500 0 for my $row (@$rows) {
6501 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
6502 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
6503 0 push @pairs, [_decode_cell($xv), $yn];
6504 }
6505 0 ▶ return { error => 'No plottable data' } unless @pairs;
Branch: 1 branch
BranchTrueFalseTotal
unless @pairs 0 0 0
6506  
6507 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
6508 0 $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6509 ->render_zoomable_line_chart_snippet(\@pairs, { id => $svg_id });
6510 }
6511 0 my $html = $sn->{html};
6512 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
6513 0 return { html => $html, title => $title };
6514 }
6515  
6516 # --------------------------------------------------------------- scatter --
6517 12 ▶ if ($kind eq 'scatter') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "scatter") 0 12 12
6518 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
6519 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
6520 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
6521 unless length($x_col) && length($y_col);
6522 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
6523 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
6524  
6525 # series and size are what /scatter's "Add to canvas" saves from series=
6526 # and size=; scheme, min_r and max_r come with them in options. A
6527 # canvas stores a visual unchecked (PUT, PATCH, import), so the scheme
6528 # goes through _categorical_scheme -- HTML::D3 writes it into the script
6529 # -- and an unknown one draws the default colours, as on a pie card.
6530 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
6531 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
6532 0 ▶ $series_col = '' if ref $series_col;
Branch: 1 branch
BranchTrueFalseTotal
if ref $series_col 0 0 0
6533 0 ▶ $size_col = '' if ref $size_col;
Branch: 1 branch
BranchTrueFalseTotal
if ref $size_col 0 0 0
6534 return { error => "Column not found: $series_col" }
6535 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
6536 return { error => "Column not found: $size_col" }
6537 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
6538  
6539 0 my @points;
6540 0 for my $row (@$vis_recs) {
6541 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
6542 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
6543 0 my %meta;
6544 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
6545 0 ▶ if (length $size_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $size_col) 0 0 0
6546 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
6547 0 ▶ $meta{size} = $sv if defined $sv;
Branch: 1 branch
BranchTrueFalseTotal
if defined $sv 0 0 0
6548 }
6549 0 ▶ push @points, [$xv, $yv, {}, (%meta ? \%meta : ())];
Branch: 1 branch
BranchTrueFalseTotal
%meta ? : 0 0 0
6550 }
6551 0 ▶ return { error => 'No plottable data' } unless @points;
Branch: 1 branch
BranchTrueFalseTotal
unless @points 0 0 0
6552  
6553 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
6554 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6555 ->render_scatter_chart_snippet(\@points, {
6556 x_label => $x_col,
6557 y_label => $y_col,
6558 id => $svg_id,
6559 (length $series_col
6560 ? (colour_by_series => 1, series_col => $series_col,
6561 scheme => _categorical_scheme($options->{scheme}))
6562 : ()),
6563 (length $size_col
6564 ? (size_col => $size_col,
6565 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
6566 : ()),
6567 });
6568 0 my $html = $sn->{html};
6569 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
6570 0 return { html => $html, title => $title };
6571 }
6572  
6573 # -------------------------------------------------------------- heatmap --
6574 12 ▶ if ($kind eq 'heatmap') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "heatmap") 1 11 12
6575 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
6576 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
6577 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
6578 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
6579 unless length($x_col) && length($y_col);
6580 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
6581 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
6582 return { error => "Column not found: $val_col" }
6583 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
6584  
6585 1 my (@x_order, @y_order, %seen_x, %seen_y);
6586 1 for my $row (@$vis_recs) {
6587 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
6588 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
6589 6 ▶ push @x_order, $xv unless $seen_x{$xv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_x{$xv}++ 4 2 6
6590 6 ▶ push @y_order, $yv unless $seen_y{$yv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_y{$yv}++ 3 3 6
6591 }
6592 1 my $m = _visual_measure($agg_fn, $val_col);
6593 1 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 1 1
6594  
6595 my $agg = $self->_grouped_totals(
6596 { source => $agg_src, records => $vis_recs },
6597 { by => [$x_col, $y_col],
6598 fn => $m->{fn},
6599 val => $m->{val},
6600 1 as => 'value' },
6601 );
6602 1 my %grid;
6603 1 for my $r (@$agg) {
6604 6 $grid{$r->{$x_col}}{$r->{$y_col}} = $r->{value};
6605 }
6606 my @triples = map {
6607 1 my ($raw_x, $xv) = ($_, _decode_cell($_));
6608 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
6609 } @x_order;
6610 1 ▶ return { error => 'No plottable data' } unless @triples;
Branch: 1 branch
BranchTrueFalseTotal
unless @triples 0 1 1
6611  
6612 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
6613 1 my $scheme = _sequential_scheme($options->{scheme});
6614 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6615 ->render_heatmap_snippet(\@triples, {
6616 x_label => $x_col,
6617 y_label => $y_col,
6618 val_label => $m->{label},
6619 color_scheme => $scheme,
6620 1 ▶ show_values => ($options->{show_values} ? 1 : 0),
Branch: 1 branch
BranchTrueFalseTotal
$options->{'show_values'} ? : 0 1 1
6621 id => $svg_id,
6622 });
6623 1 my $html = $sn->{html};
6624 1 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 1 1
6625 1 return { html => $html, title => $title };
6626 }
6627  
6628 # --------------------------------------------------------------- stacked --
6629 11 ▶ if ($kind eq 'stacked') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "stacked") 0 11 11
6630 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
6631 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
6632 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
6633 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
6634 unless length($cat_col) && length($seg_col);
6635 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
6636 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
6637 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
6638 return { error => "Column not found: $val_col" }
6639 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
6640  
6641 0 my $m = _visual_measure($agg_fn, $val_col);
6642 0 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 0 0
6643  
6644 my $agg = $self->_grouped_totals(
6645 { source => $agg_src, records => $vis_recs },
6646 { by => [$cat_col, $seg_col],
6647 fn => $m->{fn},
6648 val => $m->{val},
6649 0 as => 'value' },
6650 );
6651 my @data = map {
6652 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
6653 (length $c && length $s)
6654 ? { cat => $c, seg => $s, val => $_->{value} }
6655 : ()
6656 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
6657 0 ▶ return { error => 'No plottable data' } unless @data;
Branch: 1 branch
BranchTrueFalseTotal
unless @data 0 0 0
6658  
6659 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
6660 0 my $scheme = _categorical_scheme($options->{scheme});
6661 0 ▶ my $orient = (_chart_orientation($options) eq 'horizontal') ? 'h' : 'v';
Branch: 1 branch
BranchTrueFalseTotal
_chart_orientation($options) eq 'horizontal' ? : 0 0 0
6662 0 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6663 ->render_stacked_bar_snippet(\@data, {
6664 scheme => $scheme,
6665 x_label => $cat_col,
6666 orient => $orient,
6667 id => $svg_id,
6668 });
6669 0 my $html = $sn->{html};
6670 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
6671 0 return { html => $html, title => $title };
6672 }
6673  
6674 # ---------------------------------------------------------------- combo --
6675 11 ▶ if ($kind eq 'combo') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "combo") 0 11 11
6676 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
6677 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
6678 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
6679 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
6680 unless length($x_col) && length($bar_col) && length($line_col);
6681 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
6682 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
6683 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
6684  
6685 # One card, one function: a combo aggregates both its series the same
6686 # way, so the two cannot be read against different arithmetic by
6687 # accident.
6688 0 my $bar_m = _visual_measure($agg_fn, $bar_col);
6689 0 my $line_m = _visual_measure($agg_fn, $line_col);
6690 0 ▶ return { error => $bar_m->{error} } if $bar_m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $bar_m->{"error"} 0 0 0
6691 0 ▶ return { error => $line_m->{error} } if $line_m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $line_m->{"error"} 0 0 0
6692  
6693 my $bar_rows = $self->_grouped_totals(
6694 { source => $agg_src, records => $vis_recs },
6695 0 { by => [$x_col], fn => $bar_m->{fn}, val => $bar_m->{val}, as => 'bar_val' },
6696 );
6697 my $line_rows = $self->_grouped_totals(
6698 { source => $agg_src, records => $vis_recs },
6699 0 { by => [$x_col], fn => $line_m->{fn}, val => $line_m->{val}, as => 'line_val' },
6700 );
6701 0 my (%bar_map, %line_map, @x_order, %x_seen);
6702 0 for my $r (@$bar_rows) {
6703 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
6704 0 ▶ push @x_order, $xv unless $x_seen{$xv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $x_seen{$xv}++ 0 0 0
6705 0 $bar_map{$xv} = $r->{bar_val};
6706 }
6707 0 for my $r (@$line_rows) {
6708 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
6709 0 ▶ push @x_order, $xv unless $x_seen{$xv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $x_seen{$xv}++ 0 0 0
6710 0 $line_map{$xv} = $r->{line_val};
6711 }
6712 0 ▶ return { error => 'No plottable data' } unless @x_order;
Branch: 1 branch
BranchTrueFalseTotal
unless @x_order 0 0 0
6713  
6714 0 my @data = map { { x => $_, bar_val => $bar_map{$_}, line_val => $line_map{$_} } }
6715 @x_order;
6716 # Sum keeps the columns in the title because that is what the card has
6717 # always said; count needs no column, so it reads as the tally it is.
6718 $title ||= ($bar_m->{fn} eq 'sum')
6719 ? "$bar_col and $line_col by $x_col"
6720 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
6721 ? "Count by $x_col"
6722 : "$bar_m->{fn} of $bar_col and $line_col by $x_col";
6723 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6724 ->render_combo_snippet(\@data, {
6725 bar_label => $bar_col,
6726 line_label => $line_col,
6727 id => $svg_id,
6728 # What /combo saves from scheme=, checked again: a canvas stores it
6729 # unchecked.
6730 0 ▶ (_optional_scheme($options->{scheme}) ? (scheme => $options->{scheme}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
_optional_scheme($options->{'scheme'}) ? : 0 0 0
6731 });
6732 0 my $html = $sn->{html};
6733 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
6734 0 return { html => $html, title => $title };
6735 }
6736  
6737 # --------------------------------------------------------------- treemap --
6738 11 ▶ if ($kind eq 'treemap') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "treemap") 0 11 11
6739 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
6740 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
6741 0 ▶ return { error => 'Missing group column for treemap visual' } unless length $cat_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col 0 0 0
6742 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
6743 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
6744 return { error => "Column not found: $val_col" }
6745 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
6746  
6747 0 my $m = _visual_measure($agg_fn, $val_col);
6748 0 ▶ return { error => $m->{error} } if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 0 0
6749  
6750 # encode.color and options.color_agg / color_scheme are what /treemap
6751 # saves from color=, color_agg= and color_scheme=. The function is
6752 # checked by _tile_colour_measure, as the page's is; the scheme falls back as the
6753 # heatmap's does, since HTML::D3 refuses a name it does not know.
6754 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
6755 0 ▶ $color_col = '' if ref $color_col;
Branch: 1 branch
BranchTrueFalseTotal
if ref $color_col 0 0 0
6756 0 my $color_m;
6757 0 ▶ if (length $color_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $color_col) 0 0 0
6758 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
6759 0 $color_m = $self->_tile_colour_measure($options->{color_agg}, $color_col);
6760 0 ▶ return { error => $color_m->{error} } if $color_m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $color_m->{"error"} 0 0 0
6761 }
6762  
6763 my $agg = $self->_grouped_totals(
6764 { source => $agg_src, records => $vis_recs },
6765 { by => [$cat_col],
6766 fn => $m->{fn},
6767 val => $m->{val},
6768 0 as => 'value' },
6769 );
6770 0 ▶ return { error => 'No plottable data' } unless @$agg;
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg 0 0 0
6771 0 ▶ my $colour_of = $color_m
Branch: 1 branch
BranchTrueFalseTotal
$color_m ? : 0 0 0
6772 ? $self->_tile_colours($agg_src, $vis_recs, $cat_col, $color_m)
6773 : {};
6774  
6775 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
6776 0 my $scheme = _categorical_scheme($options->{scheme});
6777 # The snippet takes one row per tile as { path, value }, the shape the
6778 # treemap page builds; a [label, value] pair is not a path and croaks.
6779 my @tiles = map {
6780 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
6781 +{ path => 'Root/' . _decode_cell($_->{$cat_col}), value => $_->{value},
6782 0 ▶ (defined $cv ? (color_value => $cv) : ()) }
Branch: 1 branch
BranchTrueFalseTotal
defined $cv ? : 0 0 0
6783 } @$agg;
6784 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6785 ->render_treemap_snippet(\@tiles, {
6786 scheme => $scheme,
6787 id => $svg_id,
6788 ($color_m
6789 ? (color_scheme => _sequential_scheme($options->{color_scheme}),
6790 color_label => $color_m->{label})
6791 0 ▶ : ()),
Branch: 1 branch
BranchTrueFalseTotal
$color_m ? : 0 0 0
6792 });
6793 0 my $html = $sn->{html};
6794 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
6795 0 return { html => $html, title => $title };
6796 }
6797  
6798 # ------------------------------------------------------------ histogram --
6799 11 ▶ if ($kind eq 'histogram') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "histogram") 0 11 11
6800 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
6801 0 ▶ return { error => 'Missing col for histogram visual' } unless length $col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 0 0 0
6802 0 ▶ return { error => "Column not found: $col" } unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 0 0 0
6803  
6804 0 my @values;
6805 0 for my $row (@$vis_recs) {
6806 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
6807 0 ▶ push @values, $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 0 0 0
6808 }
6809 0 ▶ return { error => 'No plottable data' } unless @values;
Branch: 1 branch
BranchTrueFalseTotal
unless @values 0 0 0
6810  
6811 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
6812 0 ▶ $bins = 1 if $bins < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $bins < 1 0 0 0
6813 0 ▶ $bins = $MAX_HISTOGRAM_BINS if $bins > $MAX_HISTOGRAM_BINS;
Branch: 1 branch
BranchTrueFalseTotal
if $bins > $MAX_HISTOGRAM_BINS 0 0 0
6814 0 my $min_v = min(@values);
6815 0 my $max_v = max(@values);
6816 0 my @bin_data;
6817 0 ▶ if ($min_v == $max_v) {
Branch: 1 branch
BranchTrueFalseTotal
if ($min_v == $max_v) { } 0 0 0
6818 0 push @bin_data, { label => "$min_v", count => scalar @values,
6819 lo => $min_v, hi => $min_v };
6820 } else {
6821 0 my $raw_w = ($max_v - $min_v) / $bins;
6822 0 my $width = sprintf('%.10g', $raw_w) + 0;
6823 0 ▶ $width = $raw_w if $width <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $width <= 0 0 0 0
6824 0 ▶ my $fmt = ($width == int($width)) ? '%d' : '%g';
Branch: 1 branch
BranchTrueFalseTotal
$width == int $width ? : 0 0 0
6825 0 my (@bin_counts, @bin_los);
6826 0 for my $i (0 .. $bins - 1) {
6827 0 push @bin_los, $min_v + $i * $width;
6828 0 push @bin_counts, 0;
6829 }
6830 0 for my $v (@values) {
6831 0 my $idx = POSIX::floor(sprintf('%.10g', ($v - $min_v) / $width) + 0);
6832 0 ▶ $idx = $bins - 1 if $idx >= $bins;
Branch: 1 branch
BranchTrueFalseTotal
if $idx >= $bins 0 0 0
6833 0 ▶ $idx = 0 if $idx < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $idx < 0 0 0 0
6834 0 $bin_counts[$idx]++;
6835 }
6836 0 for my $i (0 .. $bins - 1) {
6837 0 ▶ next unless $bin_counts[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless $bin_counts[$i] 0 0 0
6838 0 my $lo = $bin_los[$i];
6839 0 my $hi = $lo + $width;
6840 0 push @bin_data, {
6841 label => sprintf("[${fmt},${fmt})", $lo, $hi),
6842 count => $bin_counts[$i],
6843 lo => $lo,
6844 hi => $hi,
6845 };
6846 }
6847 }
6848  
6849 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
6850 my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6851 ->render_histogram_snippet(\@bin_data, {
6852 binned => 1,
6853 x_label => $col,
6854 id => $svg_id,
6855 # What /histogram saves from scheme=. Stored unchecked, so it
6856 # goes through the same check as the page's.
6857 0 ▶ (_optional_scheme($options->{scheme}) ? (scheme => $options->{scheme}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
_optional_scheme($options->{'scheme'}) ? : 0 0 0
6858 });
6859 0 my $html = $sn->{html};
6860 0 ▶ utf8::decode($html) unless utf8::is_utf8($html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($html) 0 0 0
6861 0 return { html => $html, title => $title };
6862 }
6863  
6864 # ------------------------------------------------------------------- map --
6865 11 ▶ if ($kind eq 'map') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "map") 1 10 11
6866 1 my $map = $self->_map_data(
6867 $vis_recs, $columns, $encode, $options, $spec_key, $vis_id,
6868 );
6869 1 ▶ return { error => $map->{error} } if $map->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $map->{"error"} 0 1 1
6870  
6871 1 my $html = '';
6872 1 ▶ if ($map->{map_body}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($map->{"map_body"}) 0 1 1
6873 0 $html .= '<div class="canvas-map-wrap">' . $map->{map_body} . '</div>';
6874 }
6875 1 ▶ if ($map->{marker_count}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($map->{"marker_count"}) 0 1 1
6876 $html .= '<p class="map-summary">Plotting '
6877 . $map->{marker_count} . ' marker' . ($map->{marker_count} == 1 ? '' : 's')
6878 . ' for ' . $map->{row_count} . ' of ' . $map->{source_rows}
6879 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
6880 }
6881 1 ▶ if (@{ $map->{messages} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$map->{"messages"};}) 1 0 1
6882 $html .= '<div class="map-notes" role="status"><ul>'
6883 . join('', map {
6884 '<li class="map-note" data-key="' . xml_escape($_->{key} // '') . '">'
6885 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
6886 1 } @{ $map->{messages} })
6887 . '</ul></div>';
6888 }
6889  
6890 return {
6891 html => $html,
6892 title => $title || $map->{title},
6893 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
6894 };
6895 }
6896  
6897 # ------------------------------------------------------------ word cloud --
6898 # A card that draws the words of a text column, the way GET /wordcloud does,
6899 # from the same counted and ranked words (see _wordcloud_counts). It is the
6900 # one kind with no value column and no measure: the size of a word is how
6901 # many of the card's own rows contain it, so a card the reader has filtered
6902 # shows the words of those rows.
6903 10 ▶ if ($kind eq 'wordcloud') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "wordcloud") 0 10 10
6904 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
6905 0 ▶ return { error => 'Missing col for word cloud visual' } unless length $col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 0 0 0
6906 0 ▶ return { error => "Column not found: $col" } unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 0 0 0
6907  
6908 0 my $topn = _wordcloud_option($options->{topn}, 50, 1, 500);
6909 0 my $minlen = _wordcloud_option($options->{minlen}, 3, 1, 64);
6910  
6911 my $cloud = _wordcloud_counts(
6912 $vis_recs, $col, $topn, $minlen, $options->{stop},
6913 0 );
6914 0 my @tags = @{ $cloud->{words} };
6915  
6916 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
6917 my $summary = $cloud->{distinct}
6918 ? scalar(@tags) . ' of ' . $cloud->{distinct} . ' different word'
6919 . ($cloud->{distinct} == 1 ? '' : 's')
6920 . ' &middot; ' . $cloud->{total} . ' word'
6921 . ($cloud->{total} == 1 ? '' : 's')
6922 . ' in ' . $cloud->{rows} . ' row'
6923 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
6924 : '';
6925  
6926 0 ▶ if (!@tags) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@tags) 0 0 0
6927 return {
6928 0 html => '<div class="wordcloud-card"><p class="wordcloud-empty">'
6929 . 'No words: no row in this view has text in '
6930 . xml_escape($col) . ' at least ' . $minlen
6931 . ' characters long.</p></div>',
6932 title => $title,
6933 };
6934 }
6935  
6936 # HTML::TagCloud ranks the words and works out each one's level; the size
6937 # it would give that level is 12px plus the level. The size is written on
6938 # the word here instead of using the module's style sheet, because that
6939 # sheet scopes itself through #htmltagcloud -- an id only one element on a
6940 # page may carry, and a canvas may hold two word-cloud cards. The level,
6941 # the part that is actually arithmetic, stays the module's. The module is
6942 # handed the word as it is and the escaping happens on the way out, because
6943 # the same word is both what the reader reads and, unescaped, the filter a
6944 # click on it asks for.
6945 0 require HTML::TagCloud;
6946 0 my $ranked = HTML::TagCloud->new(levels => 18);
6947 0 $ranked->add_static($_->{word}, $_->{count}) for @tags;
6948  
6949 # A word is a control, not a label. Clicking one cross-filters the canvas
6950 # the way a chart mark does -- ?cf=...&cv=<card>, so every other card is
6951 # narrowed and this one stays drawn in full -- but with C<contains> rather
6952 # than C<eq>: a word is a token inside a cell, not the cell's whole value,
6953 # so no row equals it. The href carries the whole URL the click asks for,
6954 # so a word filters even before the page's script runs; the script takes
6955 # the click over only to keep the rest of the query string (a bound
6956 # parameter, a drill path) and to record the undo step, as it does for a
6957 # mark. A card drawn with no index -- by anything that is not a canvas
6958 # render -- names no source, so the filter applies to every card.
6959 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
6960 my $spans = join(' ', map {
6961 0 my $word = $_->{name};
6962 0 my $label = xml_escape("Filter by $col: $word");
6963 # aria-describedby names the canvas's cross-filter help, which covers
6964 # a word as well as a chart mark: the label says which word this is,
6965 # the help says what pressing Enter on it does.
6966 '<a class="wordcloud-word" href="?cf='
6967 . _percent_encode("$col:contains:$word") . $cv . '"'
6968 . ' data-cf-value="' . xml_escape($word) . '"'
6969 0 . ' style="font-size:' . (12 + $_->{level}) . 'px"'
6970 . ' aria-label="' . $label . '" title="' . $label . '"'
6971 . ' aria-describedby="cf-help">'
6972 . xml_escape($word) . '</a>'
6973 } $ranked->tags(scalar @tags));
6974  
6975 return {
6976 0 html => '<div class="wordcloud-card" data-col="' . xml_escape($col) . '">'
6977 . '<p class="wordcloud-cloud">' . $spans . '</p>'
6978 . '<p class="wordcloud-summary">' . $summary . '</p></div>',
6979 title => $title,
6980 };
6981 }
6982  
6983 # ----------------------------------------------------------------- table --
6984 10 ▶ if ($kind eq 'table') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "table") 0 10 10
6985 0 ▶ return { error => 'No data to display' } unless @$vis_recs;
Branch: 1 branch
BranchTrueFalseTotal
unless @$vis_recs 0 0 0
6986 0 my @cols = @$columns;
6987 0 ▶ if (ref $encode->{columns} eq 'ARRAY' && @{ $encode->{columns} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $encode->{"columns"} eq "ARRAY" and @{$encode->{"columns"};}) 0 0 0
Condition0%0/3
ref $encode->{"columns"} eq "ARRAY" and @{$encode->{"columns"};}
!ll&&!rl&&r
000
MC/DC0%0/2
ref $encode->{"columns"} eq "ARRAY" and @{$encode->{"columns"};}
ref $encode->{"columns"} eq "ARRAY" @{$encode->{"columns"};}
Truth table0%0/3
A and B
A= ref $encode->{"columns"} eq "ARRAY"B= @{$encode->{"columns"};}
ABresult
0X0
100
111
6988 # A table names the columns it shows, and it is the one kind that
6989 # could name a column nothing produces: the heading printed and
6990 # every cell under it was empty, which reads as missing data rather
6991 # than as a card drawn against a column that is not there. Whether
6992 # a plan produces a name is not something a reader can see from the
6993 # card, so the name is refused here as the charts below refuse it.
6994 0 for my $c (@{ $encode->{columns} }) {
6995 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
6996 0 ▶ return { error => "Column not found: $c" } unless $col_set{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$c} 0 0 0
6997 }
6998 0 @cols = @{ $encode->{columns} };
6999 }
7000  
7001 0 ▶ $title ||= 'Table';
Condition0%0/2
$title ||= "Table"
l!l
00
MC/DC0%0/1
$title ||= "Table"
$title
Truth table0%0/2
A
A= $title
Aresult
11
00
7002 0 ▶ my $max_rows_t = int($options->{rows} // 50);
Condition0%0/2
$options->{"rows"} // 50
l!l
00
MC/DC0%0/1
$options->{"rows"} // 50
$options->{"rows"}
Truth table0%0/2
A
A= $options->{"rows"}
Aresult
11
00
7003 0 ▶ $max_rows_t = 200 if $max_rows_t > 200;
Branch: 1 branch
BranchTrueFalseTotal
if $max_rows_t > 200 0 0 0
7004 0 ▶ $max_rows_t = 1 if $max_rows_t < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $max_rows_t < 1 0 0 0
7005  
7006 0 my $html = '<div class="visual-table-wrap"><table class="data-table">'
7007 . '<thead><tr>';
7008 0 for my $c (@cols) {
7009 0 (my $ch = $c) =~ s/&/&amp;/g; $ch =~ s/</&lt;/g; $ch =~ s/>/&gt;/g;
7010 0 $html .= "<th>$ch</th>";
7011 }
7012 0 $html .= '</tr></thead><tbody>';
7013 0 my $count = 0;
7014 0 for my $row (@$vis_recs) {
7015 0 ▶ last if $count++ >= $max_rows_t;
Branch: 1 branch
BranchTrueFalseTotal
if $count++ >= $max_rows_t 0 0 0
7016 0 $html .= '<tr>';
7017 0 for my $c (@cols) {
7018 0 ▶ my $v = $row->{$c} // '';
Condition0%0/2
$row->{$c} // ""
l!l
00
MC/DC0%0/1
$row->{$c} // ""
$row->{$c}
Truth table0%0/2
A
A= $row->{$c}
Aresult
11
00
7019 0 $v =~ s/&/&amp;/g; $v =~ s/</&lt;/g; $v =~ s/>/&gt;/g;
7020 0 $html .= "<td>$v</td>";
7021 }
7022 0 $html .= '</tr>';
7023 }
7024 0 $html .= '</tbody></table></div>';
7025 0 return { html => $html, title => $title };
7026 }
7027  
7028 10 return { error => "Unknown visual kind: $kind" };
7029 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7030  
7031 # _vis_cf_col(\%vis) -> $col_name | undef
7032 #
7033 # Returns the primary categorical dimension of a visual -- the column that
7034 # makes sense to cross-filter on when the user clicks a mark.
7035 # Priority: cat > group > x > col (histogram). Series/size/val are measures,
7036 # not dimensions, so they are intentionally excluded.
7037 27 ▶sub _vis_cf_col {
Subroutine _vis_cf_col: called CC=5 SCAR=16.1
7038 27 my ($vis) = @_;
7039 27 ▶ my $enc = $vis->{encode} // {};
Condition100%2/2
$vis->{"encode"} // {}
l!l
1710
MC/DC100%1/1
$vis->{"encode"} // {}
$vis->{"encode"}
Truth table100%2/2
A
A= $vis->{"encode"}
Aresult
11
00
7040 27 for my $key (qw(cat group x col)) {
7041 66 ▶ return $enc->{$key} if length($enc->{$key} // '');
Branch: 1 branch
BranchTrueFalseTotal
if length($enc->{$key} // "") 16 50 66
Condition100%2/2
$enc->{$key} // ""
l!l
1749
MC/DC100%1/1
$enc->{$key} // ""
$enc->{$key}
Truth table100%2/2
A
A= $enc->{$key}
Aresult
11
00
7042 }
7043 11 return undef;
7044 }
7045  
7046 # GET /a/:id -- render a saved canvas
7047 #
7048 # redirects to the reconstructed data-view URL when the
7049 # canvas has no visuals array.
7050 # renders N visuals in a CSS grid when visuals are present.
7051 # _bound_canvas_params($self, $a, $lookup) -> (\%bound, \@errors)
7052 #
7053 # Resolve the canvas's declared parameters against URL values. $lookup takes a
7054 # parameter name ("p.<name>") and returns the raw string from the request or
7055 # undef; the default is used when it returns undef. Numbers are coerced and
7056 # range-checked, and an error is reported rather than a value bound, so the
7057 # canvas page and a card appended to it draw the same parameter values.
7058 58 ▶sub _bound_canvas_params :Protected ($self, $a, $lookup) {
Subroutine _bound_canvas_params: called CC=16 SCAR=27.7
7059 58 ▶ my %param_defs = %{ $a->{params} // {} };
Condition100%2/2
$a->{"params"} // {}
l!l
1939
MC/DC100%1/1
$a->{"params"} // {}
$a->{"params"}
Truth table100%2/2
A
A= $a->{"params"}
Aresult
11
00
7060 58 my (%bound_params, @errors);
7061  
7062 58 for my $pname (sort keys %param_defs) {
7063 20 ▶ my $def = ref $param_defs{$pname} eq 'HASH' ? $param_defs{$pname} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $param_defs{$pname} eq 'HASH' ? : 17 3 20
7064 20 ▶ my $type = $def->{type} // 'string';
Condition100%2/2
$def->{"type"} // "string"
l!l
119
MC/DC100%1/1
$def->{"type"} // "string"
$def->{"type"}
Truth table100%2/2
A
A= $def->{"type"}
Aresult
11
00
7065 20 ▶ my $default = $def->{default} // '';
Condition100%2/2
$def->{"default"} // ""
l!l
218
MC/DC100%1/1
$def->{"default"} // ""
$def->{"default"}
Truth table100%2/2
A
A= $def->{"default"}
Aresult
11
00
7066 20 my $raw = $lookup->("p.$pname");
7067 20 ▶ my $val = defined $raw ? $raw : $default;
Branch: 1 branch
BranchTrueFalseTotal
defined $raw ? : 11 9 20
7068  
7069 20 ▶ if ($type eq 'number') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "number") 11 9 20
7070 11 require Scalar::Util;
7071 # looks_like_number accepts these, and every comparison with NaN is
7072 # false, so it would walk straight past min and max below.
7073 11 ▶ 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) 6 5 11
Condition100%3/3
&Scalar::Util::looks_like_number($val) and not $val =~ /\A\s*[-+]?(?:nan|inf)/iu
!ll&&!rl&&r
155
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
7074 6 push @errors, sprintf(_message_text('error_param_type'), $pname);
7075 6 next;
7076 }
7077 5 $val = $val + 0;
7078 5 my ($lo, $hi) = ($def->{min}, $def->{max});
7079 5 ▶ if (defined $lo && $val < $lo) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lo and $val < $lo) 1 4 5
Condition100%3/3
defined $lo and $val < $lo
!ll&&!rl&&r
311
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
7080 1 ▶ push @errors, sprintf(_message_text('error_param_range'),
Branch: 1 branch
BranchTrueFalseTotal
defined $hi ? : 0 1 1
7081 $pname, $lo, defined $hi ? $hi : '+inf');
7082 1 next;
7083 }
7084 4 ▶ if (defined $hi && $val > $hi) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hi and $val > $hi) 2 2 4
Condition66%2/3
defined $hi and $val > $hi
!ll&&!rl&&r
202
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
7085 2 ▶ push @errors, sprintf(_message_text('error_param_range'),
Branch: 1 branch
BranchTrueFalseTotal
defined $lo ? : 1 1 2
7086 $pname, defined $lo ? $lo : '-inf', $hi);
7087 2 next;
7088 }
7089 }
7090 11 $bound_params{$pname} = $val;
7091 }
7092  
7093 58 return (\%bound_params, \@errors);
7094 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7095  
7096 27 ▶sub canvas_render ($self) {
Subroutine canvas_render: called CC=125 SCAR=74.1
Pod documented
7097 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
7098 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 0 27 27
7099 unless $id =~ /\A[A-Za-z0-9]+\z/;
7100  
7101 27 my $analyses = $self->_read_analyses;
7102 27 ▶ unless (exists $analyses->{$id}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $analyses->{$id}) 4 23 27
7103 # An HTML page, not plain text, so the user keeps the breadcrumb and
7104 # the site navigation. No canvas_id: there is nothing to delete.
7105 4 my ($platform, $language) = $self->_resolve_template;
7106 4 return $self->render(
7107 handler => 'tt',
7108 template => "$platform/$language/canvas_error",
7109 format => 'html',
7110 status => 404,
7111 title => 'Canvas not found',
7112 canvas_name => $id,
7113 error_msg => sprintf(_message_text('error_analysis_not_found'), $id),
7114 error_specs => [],
7115 language => $language,
7116 );
7117 }
7118 23 my $a = $analyses->{$id};
7119  
7120 # freshness: compare each dataset's current mtime against
7121 # the analysis's saved updated timestamp. Flag stale when any source
7122 # is newer. Non-fatal: the canvas renders with a stale banner.
7123 23 my ($freshness_stale, $freshness_msg, $freshness_source_mtime) = (0, '', '');
7124 {
7125 23 ▶ my $analysis_updated = $a->{updated} // 0;
Condition100%2/2
$a->{"updated"} // 0
l!l
320
MC/DC100%1/1
$a->{"updated"} // 0
$a->{"updated"}
Truth table100%2/2
A
A= $a->{"updated"}
Aresult
11
00
7126 # Parse ISO-8601 to epoch for comparison if needed.
7127 23 ▶ 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 23 23
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
2030
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
7128 \A
7129 (\d{4}) - (\d{2}) - (\d{2}) # $1 yr $2 mon $3 day
7130 T
7131 (\d{2}) : (\d{2}) : (\d{2}) # $4 hr $5 min $6 sec
7132 Z? \z
7133 /x) {
7134 0 require POSIX;
7135 0 $analysis_updated = POSIX::mktime($6, $5, $4, $3, $2 - 1, $1 - 1900);
7136 }
7137 23 my $newest_src_mtime = 0;
7138 23 ▶ for my $ds (@{ $a->{datasets} // [] }) {
Condition100%2/2
$a->{"datasets"} // []
l!l
203
MC/DC100%1/1
$a->{"datasets"} // []
$a->{"datasets"}
Truth table100%2/2
A
A= $a->{"datasets"}
Aresult
11
00
7139 20 ▶ my $spec = $ds->{spec} // '';
Condition50%1/2
$ds->{"spec"} // ""
l!l
200
MC/DC0%0/1
$ds->{"spec"} // ""
$ds->{"spec"}
Truth table50%1/2
A
A= $ds->{"spec"}
Aresult
11
00
7140 20 ▶ next unless $spec =~ /\A(?:table|path):/;
Branch: 1 branch
BranchTrueFalseTotal
unless $spec =~ /\A(?:table|path):/u 0 20 20
7141 20 my ($src) = eval { $self->_open_spec($spec) };
7142 20 ▶ next unless $src && $src->can('updated');
Branch: 1 branch
BranchTrueFalseTotal
unless $src and $src->can("updated") 0 20 20
Condition33%1/3
$src and $src->can("updated")
!ll&&!rl&&r
0020
MC/DC0%0/2
$src and $src->can("updated")
$src $src->can("updated")
Truth table33%1/3
A and B
A= $srcB= $src->can("updated")
ABresult
0X0
100
111
7143 20 ▶ my $mt = eval { $src->updated } // 0;
Condition50%1/2
eval { do { $src->updated } } // 0
l!l
200
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
7144 20 ▶ $newest_src_mtime = $mt if $mt > $newest_src_mtime;
Branch: 1 branch
BranchTrueFalseTotal
if $mt > $newest_src_mtime 20 0 20
7145 }
7146 23 ▶ 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) 0 23 23
Condition83%5/6
$newest_src_mtime and $analysis_updated and $newest_src_mtime > $analysis_updated
!ll&&!rl&&r
2030
$newest_src_mtime and $analysis_updated
!ll&&!rl&&r
3173
MC/DC0%0/3
$newest_src_mtime and $analysis_updated and $newest_src_mtime > $analysis_updated
$newest_src_mtime $analysis_updated $newest_src_mtime > $analysis_updated
Truth table75%3/4
A and B and C
A= $newest_src_mtimeB= $analysis_updatedC= $newest_src_mtime > $analysis_updated
ABCresult
0XX0
10X0
1100
1111
7147 0 $freshness_stale = 1;
7148 0 $freshness_msg = _message_text('freshness_stale_msg');
7149 0 require POSIX;
7150 0 $freshness_source_mtime = Database::BI::Util::minute_stamp(gmtime($newest_src_mtime)) . ' UTC';
7151 }
7152 }
7153  
7154 # if visuals array is non-empty, render the canvas.
7155 23 ▶ my @visuals = @{ $a->{visuals} // [] };
Condition100%2/2
$a->{"visuals"} // []
l!l
176
MC/DC100%1/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
7156 23 ▶ if (@visuals) {
Branch: 1 branch
BranchTrueFalseTotal
if (@visuals) 17 6 23
7157  
7158 # bound parameters from URL ?p.<name>=<value>.
7159 # Parameter definitions live in the analysis: params => { name => { type, default, min, max } }.
7160 # URL values are type-coerced and range-checked; out-of-range returns 400.
7161 my ($bound_ref, $p_errors) = $self->_bound_canvas_params(
7162 2 ▶ $a, sub { $self->param($_[0]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
7163 17 );
7164 17 my %bound_params = %$bound_ref;
7165 17 ▶ if (@$p_errors) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$p_errors) 0 17 17
7166 0 return $self->render(
7167 text => join('; ', @$p_errors),
7168 status => 400,
7169 );
7170 }
7171  
7172 # Build stash list for parameter bar: sorted by name.
7173 17 ▶ my %param_defs = %{ $a->{params} // {} };
Condition100%2/2
$a->{"params"} // {}
l!l
215
MC/DC100%1/1
$a->{"params"} // {}
$a->{"params"}
Truth table100%2/2
A
A= $a->{"params"}
Aresult
11
00
7174 my @canvas_params = map {
7175 17 my $def = $param_defs{$_};
7176 {
7177 name => $_,
7178 type => ($def->{type} // 'string'),
7179 value => $bound_params{$_},
7180 default => ($def->{default} // ''),
7181 min => (defined $def->{min} ? $def->{min} : ''),
7182 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
7183 }
7184 } sort keys %param_defs;
7185  
7186 # Everything else the canvas is showing has to survive a change of time
7187 # range, so the control carries the rest of this page's query string: the
7188 # cross-filter (cf/vc), the drill path (dd/dl), the calculated columns
7189 # (c) and the what-if parameter values (p.<name>).
7190 17 my @canvas_range_hidden;
7191 {
7192 17 my $q = $self->req->query_params;
7193 17 for my $name ($q->names) {
7194 17 ▶ next if $name eq 'range' || $name eq 'rcol';
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "range" or $name eq "rcol" 0 17 17
Condition33%1/3
$name eq "range" or $name eq "rcol"
l!l&&r!l&&!r
0017
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
7195 push @canvas_range_hidden,
7196 0 ▶ map { { name => $name, value => $_ } } @{ $q->every_param($name) // [] };
Condition50%1/2
$q->every_param($name) // []
l!l
170
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
7197 }
7198 }
7199  
7200 17 my ($src, $records, $columns) = $self->_build_canvas_pipeline($a);
7201 17 ▶ unless (defined $records) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $records) 0 17 17
7202 0 my ($platform, $language) = $self->_resolve_template;
7203 0 ▶ my @specs = map { $_->{spec} // '' } @{ $a->{datasets} // [] };
Condition0%0/4
$_->{"spec"} // ""
l!l
00
$a->{"datasets"} // []
l!l
00
MC/DC0%0/1
$_->{"spec"} // ""
$_->{"spec"}
MC/DC0%0/1
$a->{"datasets"} // []
$a->{"datasets"}
Truth table0%0/2
A
A= $_->{"spec"}
Aresult
11
00
Truth table0%0/2
A
A= $a->{"datasets"}
Aresult
11
00
7204 return $self->render(
7205 handler => 'tt',
7206 template => "$platform/$language/canvas_error",
7207 format => 'html',
7208 status => 422,
7209 title => 'Canvas unavailable',
7210 canvas_id => $id,
7211 0 ▶ canvas_name => ($a->{name} // $id),
Condition0%0/3
$a->{"name"} // $id
l!l&&r!l&&!r
000
MC/DC0%0/2
$a->{"name"} // $id
$a->{"name"} $id
Truth table0%0/3
A // B
A= $a->{"name"}B= $id
ABresult
1X1
011
000
7212 error_msg => 'The data source for this canvas could not be opened.',
7213 error_specs => \@specs,
7214 language => $language,
7215 );
7216 }
7217  
7218 # Apply calc fields with bound params so expressions may reference them.
7219 17 ▶ my $canvas_spec_key = ($a->{datasets}[0]{spec} // '');
Condition50%1/2
$a->{"datasets"}[0]{"spec"} // ""
l!l
170
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
7220 17 my $window_names = _canvas_window_columns($a, $self);
7221 17 $self->stash('_canvas_window_names' => $window_names);
7222 17 eval {
7223 17 ($records, $columns) = $self->_apply_calc_fields(
7224 $records, $columns,
7225 {
7226 params => \%bound_params,
7227 spec_key => $canvas_spec_key,
7228 window_columns => $window_names,
7229 }
7230 );
7231 };
7232 17 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 17 17
7233 0 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
7234 0 return $self->render(text => $e, status => 400);
7235 }
7236  
7237 # cs= belongs to the page, not to a card: one plan, run per card on that
7238 # card's own rows (see _render_visual_html). A fault is the page's 400 --
7239 # the same message repeated on every card would be noise, not a report.
7240 17 my $cross_row = $self->_cross_row_specs($columns);
7241 17 ▶ if ($cross_row && $cross_row->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cross_row and $cross_row->{"error"}) 0 17 17
Condition33%1/3
$cross_row and $cross_row->{"error"}
!ll&&!rl&&r
1700
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
7242 0 return $self->render(text => $cross_row->{error}, status => 400);
7243 }
7244  
7245 # The relative time range the page names (?range=/?rcol=) narrows every
7246 # card, before the per-card cross-filter. The before_dispatch hook has
7247 # already resolved it into the f= params the routes apply, but the canvas
7248 # builds its own pipeline, so it applies the range itself from the same
7249 # two specs.
7250 17 ▶ if (my $range = $self->stash('time_range')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $range = $self->stash("time_range")) 0 17 17
7251 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
7252 0 $records = _apply_filter_spec($records, $spec);
7253 }
7254 }
7255  
7256 # cross-filter state from URL params.
7257 # ?cf=col:op:val (repeatable) filters all visuals except the source.
7258 # ?cv=N identifies the source visual (shown unfiltered but highlighted).
7259 # Semantics: self-highlighting (source shown in full; others filtered).
7260 # Multiple simultaneous selections are not supported in this version.
7261 17 ▶ my @cf_specs = grep { /\S/ } @{ $self->every_param('cf') // [] };
Condition50%1/2
$self->every_param("cf") // []
l!l
170
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
7262 17 my $cf_source = _cross_filter_source($self->param('cv'));
7263 17 my $cf_active = !!@cf_specs;
7264  
7265 # Build the "clear cross-filter" URL for the chip close button.
7266 17 my $cf_clear_url = $self->req->url->clone;
7267 17 $cf_clear_url->query->remove('cf')->remove('cv');
7268 17 $cf_clear_url = $cf_clear_url->to_string;
7269  
7270 # Human-readable summary for the cross-filter chip, e.g. "region = North".
7271 17 my $cf_display = '';
7272 17 ▶ if ($cf_active) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cf_active) 1 16 17
7273 1 my @parts;
7274 1 for my $spec (@cf_specs) {
7275 1 my ($col, $op, $val) = split /:/, $spec, 3;
7276 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
7277 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
7278 : ($op eq 'lt') ? '<' : ($op eq 'le') ? '<='
7279 : ($op eq 'gt') ? '>' : ($op eq 'ge') ? '>='
7280 : ($op eq 'contains') ? 'contains'
7281 : ($op eq 'starts') ? 'starts with'
7282 : $op;
7283 1 push @parts, "$col $sym $val";
7284 }
7285 1 $cf_display = join(' AND ', @parts);
7286 }
7287  
7288 # drill-through and drill-down.
7289 #
7290 # Drill-through: when cross-filters are active, build a URL to the
7291 # primary data source with those filters applied as ?f= params so the
7292 # user can inspect the raw rows behind the selection.
7293 17 my $drillthrough_url = '';
7294 17 ▶ if (@cf_specs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cf_specs) 1 16 17
7295 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
7296 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
7297 1 my $base = $self->_spec_to_url($spec0);
7298 1 ▶ if ($base ne '/') {
Branch: 1 branch
BranchTrueFalseTotal
if ($base ne "/") 1 0 1
7299 1 ▶ my $sep = ($base =~ /\?/) ? '&' : '?';
Branch: 1 branch
BranchTrueFalseTotal
$base =~ /\?/u ? : 1 0 1
7300 1 for my $cf (@cf_specs) {
7301 1 $base .= $sep . 'f=' . url_escape(encode('UTF-8', $cf));
7302 1 $sep = '&';
7303 }
7304 1 $drillthrough_url = $base;
7305 }
7306 }
7307  
7308 # Drill-down: navigate a named hierarchy one level at a time.
7309 # ?dd=<name> names the active hierarchy; ?dl=<N> is the current level
7310 # (0-based); accumulated ?cf= params carry the drill path.
7311 17 ▶ my $dd_name = $self->param('dd') // '';
Condition50%1/2
$self->param("dd") // ""
l!l
017
MC/DC0%0/1
$self->param("dd") // ""
$self->param("dd")
Truth table50%1/2
A
A= $self->param("dd")
Aresult
11
00
7312 17 my $dl_raw = $self->param('dl');
7313 17 ▶ my $dd_level = (defined $dl_raw && length $dl_raw) ? int($dl_raw) : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $dl_raw && length $dl_raw ? : 0 17 17
Condition33%1/3
defined $dl_raw and length $dl_raw
!ll&&!rl&&r
1700
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
7314 17 ▶ $dd_level = 0 if $dd_level < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $dd_level < 0 0 17 17
7315  
7316 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
7317 17 ▶ @{ $a->{hierarchies} // [] };
Condition50%1/2
$a->{"hierarchies"} // []
l!l
017
MC/DC0%0/1
$a->{"hierarchies"} // []
$a->{"hierarchies"}
Truth table50%1/2
A
A= $a->{"hierarchies"}
Aresult
11
00
7318  
7319 # A drill needs a first level to name: a hierarchy with none answers no
7320 # press, and #cf-help has no column it could call the one that drills.
7321 my $drill_active = ($dd_hier && length $dd_name
7322 0 ▶ && @{ $dd_hier->{levels} // [] }) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$dd_hier && length $dd_name && @{$dd_hier->{'levels'} // [];} ? : 0 17 17
Condition25%2/8
$dd_hier and length $dd_name and @{$dd_hier->{"levels"} // [];}
!ll&&!rl&&r
1700
$dd_hier and length $dd_name
!ll&&!rl&&r
1700
$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
7323 17 my $drill_col = '';
7324 17 my @drill_crumb = ();
7325 17 my $drill_max = 0;
7326  
7327 17 ▶ if ($drill_active) {
Branch: 1 branch
BranchTrueFalseTotal
if ($drill_active) 0 17 17
7328 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
7329 0 $drill_max = $#levels;
7330 # Allow dl up to scalar(@levels) -- one past the last valid level
7331 # means "all levels drilled through" (drill-through mode).
7332 0 my $dl_cap = scalar @levels;
7333 0 ▶ $dd_level = $dl_cap if $dd_level > $dl_cap;
Branch: 1 branch
BranchTrueFalseTotal
if $dd_level > $dl_cap 0 0 0
7334 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
7335  
7336 # Extract drilled values: each crossed level contributes a
7337 # cf=<col>:eq:<val> param in the URL.
7338 0 my %cf_by_col;
7339 0 for my $cf (@cf_specs) {
7340 0 my ($col, $op, $val) = split /:/, $cf, 3;
7341 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
7342 if length($col // '') && ($op // '') eq 'eq';
7343 }
7344  
7345 # "All" crumb -- keep ?dd=, remove dl/cf/cv.
7346 0 my $all_url = $self->req->url->clone;
7347 0 $all_url->query->remove('dl')->remove('cf')->remove('cv');
7348 0 ▶ push @drill_crumb, {
Branch: 2 branches
BranchTrueFalseTotal
$dd_level > 0 ? : 0 0 0
$dd_level == 0 ? : 0 0 0
7349 label => 'All',
7350 url => ($dd_level > 0 ? $all_url->to_string : ''),
7351 cur => ($dd_level == 0 ? 1 : 0),
7352 };
7353  
7354 # One crumb per drilled value (levels 0 .. dd_level-1).
7355 0 for my $i (0 .. $dd_level - 1) {
7356 0 my $col_i = $levels[$i];
7357 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
7358 0 my $is_last = ($i == $dd_level - 1);
7359  
7360 # Back-link: keep ?dd=, cf for levels 0..i, dl=i+1.
7361 0 my $back_url = '';
7362 0 ▶ unless ($is_last) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_last) 0 0 0
7363 0 my $u = $self->req->url->clone;
7364 0 $u->query->remove('dl')->remove('cf')->remove('cv');
7365 0 $u->query->append('dl' => $i + 1);
7366 0 for my $j (0 .. $i) {
7367 0 my $val_j = $cf_by_col{ $levels[$j] };
7368 0 ▶ $u->query->append('cf' => "$levels[$j]:eq:$val_j")
Branch: 1 branch
BranchTrueFalseTotal
if defined $val_j 0 0 0
7369 if defined $val_j;
7370 }
7371 0 $back_url = $u->to_string;
7372 }
7373  
7374 0 ▶ push @drill_crumb, {
Branch: 1 branch
BranchTrueFalseTotal
$is_last ? : 0 0 0
7375 label => $val_i,
7376 url => $back_url,
7377 cur => $is_last ? 1 : 0,
7378 };
7379 }
7380 }
7381  
7382 # Pre-build CSS grid position strings to avoid TT hash-key lookups, and
7383 # keep the two spans of a saved card so the page can print the card's size
7384 # on the card before the script has measured anything.
7385 17 my %layout_pos;
7386 my %layout_size;
7387 17 ▶ for my $lp (@{ $a->{layout} // [] }) {
Condition50%1/2
$a->{"layout"} // []
l!l
017
MC/DC0%0/1
$a->{"layout"} // []
$a->{"layout"}
Truth table50%1/2
A
A= $a->{"layout"}
Aresult
11
00
7388 0 my ($x, $y, $w, $h) = @{$lp}{qw(x y w h)};
7389 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
7390 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
7391 "grid-column:${x}/span ${w};grid-row:${y}/span ${h}";
7392 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
7393 }
7394  
7395 17 my @rendered;
7396 17 my $canvas_map_head = '';
7397 17 for my $i (0 .. $#visuals) {
7398 19 my $vis = $visuals[$i];
7399  
7400 # Apply cross-filter to every visual except the source (self-highlighting).
7401 19 my $vis_recs = $records;
7402 19 my $late_cf = [];
7403 19 ▶ if ($cf_active && $i != $cf_source) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cf_active and $i != $cf_source) 2 17 19
Condition66%2/3
$cf_active and $i != $cf_source
!ll&&!rl&&r
1702
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
7404 2 ($vis_recs, $late_cf) = $self->_canvas_cross_filter($records, $columns, \@cf_specs);
7405 }
7406  
7407 19 ▶ my $result = $self->_render_visual_html(
Branch: 1 branch
BranchTrueFalseTotal
$cf_active && $i != $cf_source ? : 2 17 19
Condition66%2/3
$cf_active and $i != $cf_source
!ll&&!rl&&r
1702
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
7408 $vis, $vis_recs, $columns, $src, $i, $canvas_spec_key,
7409 ($cf_active && $i != $cf_source ? 1 : 0),
7410 $cross_row,
7411 $late_cf,
7412 );
7413 19 ▶ $canvas_map_head ||= $result->{head} // '';
Condition40%2/5
$canvas_map_head ||= $result->{"head"} // ""
l!l&&r!l&&!r
0019
$result->{"head"} // ""
l!l
019
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
7414 push @rendered, {
7415 id => $i,
7416 title => ($vis->{title} // $result->{title} // ('Visual ' . ($i + 1))),
7417 html => $result->{html} // '',
7418 error => $result->{error} // '',
7419 kind => $vis->{kind} // '',
7420 plain => _text_card_plain($vis),
7421 style => $layout_pos{$i} // '',
7422 # The saved spans, or nothing: a card with no saved position is
7423 # placed by the browser, and only the script can measure that.
7424 w => (defined $layout_size{$i} ? $layout_size{$i}[0] : undef),
7425 19 ▶ h => (defined $layout_size{$i} ? $layout_size{$i}[1] : undef),
Branch: 3 branches
BranchTrueFalseTotal
defined $layout_size{$i} ? : 0 19 19
defined $layout_size{$i} ? : 0 19 19
$i == $cf_source ? : 0 19 19
Condition93%14/15
($vis->{"title"} // $result->{"title"}) // 'Visual ' . ($i + 1)
l!l
910
$vis->{"title"} // $result->{"title"}
l!l&&r!l&&!r
1810
$result->{"html"} // ""
l!l
910
$result->{"error"} // ""
l!l
109
$vis->{"kind"} // ""
l!l
154
$layout_pos{$i} // ""
l!l
019
_vis_cf_col($vis) // ""
l!l
109
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
7426 cf_col => (_vis_cf_col($vis) // ''),
7427 cf_source => ($i == $cf_source ? 1 : 0),
7428 };
7429 }
7430  
7431 # bookmarks list for the toolbar panel.
7432 17 ▶ my @canvas_bookmarks = @{ $a->{bookmarks} // [] };
Condition50%1/2
$a->{"bookmarks"} // []
l!l
017
MC/DC0%0/1
$a->{"bookmarks"} // []
$a->{"bookmarks"}
Truth table50%1/2
A
A= $a->{"bookmarks"}
Aresult
11
00
7433 # Pre-encode as JSON for the JS canvasBookmarks variable.
7434 # Escape </ so the array literal cannot prematurely close a <script> tag.
7435 17 (my $bm_json = encode_json(\@canvas_bookmarks)) =~ s{</}{<\\/}g;
7436  
7437 my $canvas_columns_json = encode_json([
7438 17 ▶ map { { name => $_, numeric => _column_is_numeric($records, $_) ? 1 : 0 } }
Branch: 1 branch
BranchTrueFalseTotal
_column_is_numeric($records, $_) ? : 34 65 99
7439 @$columns
7440 ]);
7441 # The JSON is written into a <script> block. Escape '<' so a column
7442 # name containing markup cannot close the tag, as the chart spec is.
7443 17 $canvas_columns_json =~ s{<}{\\u003c}g;
7444  
7445 # The columns the page's own plan produces, for the panel that repairs a
7446 # card's: a card that takes the page's plan plots whatever that plan makes,
7447 # so the panel can only tell a reader what a change would cost it if it
7448 # knows the page's columns too.
7449 my $page_aliases = ($cross_row && ref $cross_row eq 'HASH')
7450 0 ▶ ? [ map { $_->{as} } @{ $cross_row->{specs} // [] } ] : [];
Branch: 1 branch
BranchTrueFalseTotal
$cross_row && ref $cross_row eq 'HASH' ? : 0 17 17
Condition20%1/5
$cross_row and ref $cross_row eq "HASH"
!ll&&!rl&&r
1700
$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
7451 17 my $canvas_page_aliases_json = encode_json($page_aliases);
7452 17 $canvas_page_aliases_json =~ s{<}{\\u003c}g;
7453  
7454 17 my ($platform, $language) = $self->_resolve_template;
7455 return $self->render(
7456 handler => 'tt',
7457 template => "$platform/$language/canvas",
7458 format => 'html',
7459 title => $a->{name},
7460 canvas_id => $id,
7461 canvas_name => $a->{name},
7462 # The other sites the Share panel's embed code works on.
7463 embed_origins => [ Database::BI::_embed_frame_ancestors($self->app->config) ],
7464 canvas_data_url => ($self->_analysis_to_url($a) // ''),
7465 canvas_columns_json => $canvas_columns_json,
7466 canvas_page_aliases_json => $canvas_page_aliases_json,
7467 # The same menu the table page's cross-row panel renders, so a card
7468 # can offer the functions the pass actually knows.
7469 cross_row_menu => \@CROSS_ROW_MENU,
7470 text_font_menu => \@TEXT_FONTS,
7471 text_min_points => $MIN_TEXT_POINTS,
7472 text_max_points => $MAX_TEXT_POINTS,
7473 text_max_chars => $MAX_TEXT_CHARS,
7474 visuals => \@rendered,
7475 canvas_params => \@canvas_params,
7476 canvas_bookmarks => \@canvas_bookmarks,
7477 canvas_bookmarks_json => $bm_json,
7478 canvas_time_range => $self->stash('time_range'),
7479 canvas_time_range_col => ($self->stash('time_range') ? $self->stash('time_range')->{col} : ''),
7480 17 ▶ canvas_time_range_clear_url => (do {
Branch: 1 branch
BranchTrueFalseTotal
$self->stash('time_range') ? : 0 17 17
Condition50%1/2
$self->_analysis_to_url($a) // ""
l!l
170
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
7481 17 my $u = $self->req->url->clone;
7482 17 $u->query->remove('range')->remove('rcol');
7483 17 ▶ $self->stash('time_range') ? $u->to_string : '';
Branch: 4 branches
BranchTrueFalseTotal
$self->stash('time_range') ? : 0 17 17
$cf_active ? : 1 16 17
$drill_active ? : 0 17 17
$drill_active ? : 0 17 17
7484 }),
7485 canvas_range_cols => [ @$columns ],
7486 canvas_range_hidden => \@canvas_range_hidden,
7487 cf_active => $cf_active ? 1 : 0,
7488 cf_display => $cf_display,
7489 cf_clear_url => $cf_clear_url,
7490 drillthrough_url => $drillthrough_url,
7491 drill_active => $drill_active ? 1 : 0,
7492 # A drill is a hierarchy that exists, not a name in the query string:
7493 # a bookmark can outlive the hierarchy it was saved on, and a page
7494 # that said it was drilled when nothing answered would stop making
7495 # its marks controls and have no column to name in #cf-help.
7496 drill_name => ($drill_active ? $dd_name : ''),
7497 drill_level => $dd_level,
7498 drill_col => $drill_col,
7499 drill_crumb => \@drill_crumb,
7500 drill_max => $drill_max,
7501 extra_head => $canvas_map_head,
7502 back_url => '/',
7503 back_label => 'Home',
7504 freshness_stale => $freshness_stale,
7505 freshness_msg => $freshness_msg,
7506 freshness_source_mtime => $freshness_source_mtime,
7507 language => $language,
7508 );
7509 }
7510  
7511 # no visuals yet -- reconstruct the data-view URL and redirect.
7512 6 my $url = $self->_analysis_to_url($a);
7513 6 ▶ return $self->render(text => 'Cannot reconstruct URL from this analysis', status => 422)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url 3 3 6
7514 unless defined $url;
7515  
7516 3 $self->redirect_to($url);
7517 }
7518  
7519 # _run_export_pipeline($self) -> ($records, \@columns, $left_label) or ()
7520 #
7521 # Purpose: Thin wrapper over _run_pipeline_source that additionally applies
7522 # f= filters, d=1 dedup, and page/per_page pagination. Used by
7523 # export_data, export_write, folder_view, and import_url (row-viewing
7524 # routes that do not need the source object for aggregation).
7525 # Entry: Reads "l=", "j=" (repeatable), "c=" (repeatable), "f=" (repeatable),
7526 # "d=", "page=", "per_page=" query/body params.
7527 # Exit: On success: ($filtered_arrayref, \@column_names, $left_label_string).
7528 # On failure: empty list (left table not found / fetch error).
7529 145 ▶sub _run_export_pipeline :Protected ($self) {
Subroutine _run_export_pipeline: called CC=16 SCAR=28.1
7530 145 my (undef, $records, $columns, $left_label) = $self->_run_pipeline_source;
7531 145 ▶ return () unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 10 135 145
7532  
7533 # The export honours span= like the page it was linked from, and accepts the
7534 # dimension params of the aggregating routes so a chart's own URL can be
7535 # pasted into /export and mean the same thing.
7536 135 my $span = $self->_span_calc_spec($columns, 'cat', 'x', 'rows', 'group');
7537 # The stash says the reply has gone. Without it the caller takes the empty list
7538 # for "no such table" and renders a second time, and the client is left hanging
7539 # on a reply that never finishes.
7540 135 ▶ if ($span && $span->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($span and $span->{"error"}) 10 125 135
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
125010
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
7541 10 $self->stash('_reduce_error' => 1);
7542 10 $self->render(text => $span->{error}, status => 400);
7543 10 return ();
7544 }
7545  
7546 125 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
7547 125 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 125 125
7548 125 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 5 120 125
7549 5 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
7550 5 $self->stash('_reduce_error' => 1);
7551 5 $self->render(text => $e, status => 400);
7552 5 return ();
7553 }
7554  
7555 120 ▶ return () unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 119 120
7556  
7557 119 ▶ my @columns = @{ $columns // [] };
Condition50%1/2
$columns // []
l!l
1190
MC/DC0%0/1
$columns // []
$columns
Truth table50%1/2
A
A= $columns
Aresult
11
00
7558  
7559 # d=1 has been applied by _reduce_or_render, before the cross-row pass.
7560  
7561 # Sort support for /export: applied in memory after filtering/dedup.
7562 119 my $sort = $self->param('sort');
7563 119 ▶ my $dir = ($self->param('dir') // 'asc') =~ /\Adesc\z/i ? 'desc' : 'asc';
Branch: 1 branch
BranchTrueFalseTotal
($self->param('dir') // 'asc') =~ /\Adesc\z/iu ? : 0 119 119
Condition100%2/2
$self->param("dir") // "asc"
l!l
12107
MC/DC100%1/1
$self->param("dir") // "asc"
$self->param("dir")
Truth table100%2/2
A
A= $self->param("dir")
Aresult
11
00
7564 119 ▶ if (defined $sort && grep { $_ eq $sort } @columns) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort and grep {$_ eq $sort;} @columns) { } 0 119 119
elsif (defined $sort) { } 2 117 119
Condition66%2/3
defined $sort and grep {$_ eq $sort;} @columns
!ll&&!rl&&r
11720
MC/DC0%0/2
defined $sort and grep {$_ eq $sort;} @columns
defined $sort grep {$_ eq $sort;} @columns
Truth table66%2/3
A and B
A= defined $sortB= grep {$_ eq $sort;} @columns
ABresult
0X0
100
111
7565 # By the same rule as the table pages (_sort_records returns a new
7566 # array: the backend's own can be read-only, as a SQLite one is).
7567 0 $records = _sort_records($records, $sort, $dir);
7568 0 $self->stash(sorted_by => { col => $sort, dir => $dir });
7569 } elsif (defined $sort) {
7570 2 carp $self->_i18n('error_sort_column', $sort);
7571 }
7572  
7573 # Server-side pagination for /export.
7574 119 ▶ 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")) 4 115 119
Condition100%3/3
defined $self->param("page") or defined $self->param("per_page")
l!l&&r!l&&!r
22115
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
7575 4 my ($page, $per_page, $offset) = $self->_pagination;
7576 4 my $total = scalar @$records;
7577 4 ▶ my $has_next = ($total > $offset + $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$total > $offset + $per_page ? : 0 4 4
7578 4 my @page_recs = @{ _rows_of_page($records, $offset, $per_page) };
7579 4 $records = \@page_recs;
7580 4 $self->stash(export_has_next => $has_next, export_page => $page, export_per_page => $per_page);
7581 }
7582  
7583 119 return ($records, \@columns, $left_label);
7584 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7585  
7586 # _decode_cell($s) -> $character_string
7587 #
7588 # Purpose: Ensure $s is a Perl character string, not raw UTF-8 bytes.
7589 # URL-fetched data (via LWP::UserAgent::Cached + D::A HTML parsing)
7590 # arrives as byte strings without the UTF-8 flag set. encode_json
7591 # then treats each byte as a Latin-1 code point and re-encodes it,
7592 # producing mojibake (e.g. an o-umlaut character displayed as two garbage bytes). This helper
7593 # upgrades the flag in-place on a copy so the original hash key is
7594 # unchanged but the value passed to HTML::D3 is a proper character.
7595 # Entry: $s -- any defined scalar (undef returned as-is).
7596 # Exit: The same string value, but with the UTF-8 flag set if it was absent.
7597 4011 ▶sub _decode_cell {
Subroutine _decode_cell: called CC=3 SCAR=11.0
7598 4011 my $s = shift;
7599 4011 ▶ return $s unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 1 4010 4011
7600 4010 ▶ utf8::decode($s) unless utf8::is_utf8($s);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($s) 4009 1 4010
7601 4010 $s;
7602 }
7603  
7604 # _serialize_csv($records, \@columns) -> $utf8_string
7605 #
7606 # Purpose: Build a complete RFC 4180 CSV document (header + data rows) from
7607 # $records. Shared by _render_csv (HTTP download) and the csv branch
7608 # of export_write (filesystem write) to eliminate duplicated logic.
7609 # Entry: $records is an arrayref of hashrefs; $columns is an arrayref of names.
7610 # Exit: Returns a UTF-8 Perl string ending with CRLF.
7611 #
7612 # Optimisation: rows are collected in @lines and joined in one operation.
7613 # The previous pattern ($out .= _csv_row(...) per row) triggers O(N) string
7614 # reallocations; joining a pre-built array is a single O(total_bytes) allocation.
7615 # For exports of thousands of rows the difference is measurable.
7616 #
7617 # XS note: for very large exports, replacing _csv_row with Text::CSV_XS
7618 # (available from CPAN) would further reduce serialisation time -- its C-level
7619 # implementation is roughly 5-10x faster than the pure-Perl version here.
7620 80 ▶sub _serialize_csv {
Subroutine _serialize_csv: called CC=2 SCAR=6.9
7621 80 my ($records, $columns) = @_;
7622 80 my @lines = _csv_row(@$columns);
7623 80 for my $row (@$records) {
7624 436 push @lines, _csv_row(map { $row->{$_} } @$columns);
7625 }
7626 80 return encode('UTF-8', join('', @lines));
7627 }
7628  
7629 # _render_csv($self, $records, \@columns, $name) -> void (renders response)
7630 #
7631 # Purpose: Serialise $records to RFC 4180 CSV and emit as a UTF-8 download.
7632 # Entry: $name is a safe filename stem (alphanumeric/underscore).
7633 # Exit: Renders the Mojolicious response; does not return a meaningful value.
7634 # Side Effects: Writes HTTP response headers and body.
7635 58 ▶sub _render_csv :Protected ($self, $records, $columns, $name) {
Subroutine _render_csv: called CC=1 SCAR=0.0
7636 58 $self->stash(buffer => 0);
7637 58 $self->res->headers->content_type('text/csv; charset=UTF-8');
7638 58 $self->res->headers->content_disposition(qq{attachment; filename="${name}.csv"});
7639 58 $self->render(data => _serialize_csv($records, $columns));
7640 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7641  
7642 # _render_sqlite($self, $records, \@columns, $name) -> void (renders response)
7643 #
7644 # Purpose: Write $records to a SQLite database and emit it as a binary download.
7645 # Entry: $name is a safe filename stem.
7646 # Exit: Renders the Mojolicious response.
7647 # Side Effects: Creates and unlinks a temporary file; writes HTTP response.
7648 5 ▶sub _render_sqlite :Protected ($self, $records, $columns, $name) {
Subroutine _render_sqlite: called CC=2 SCAR=6.9
7649 5 $self->stash(buffer => 0);
7650 5 my $data = eval { $self->_write_sqlite_db($records, $columns) };
7651 5 ▶ unless (defined $data) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 1 4 5
7652 1 $self->app->log->error('SQLite export failed: ' . _tidy_error($@));
7653 1 return $self->render(text => $self->_i18n('error_export_sqlite'), status => 500);
7654 }
7655 4 $self->res->headers->content_type('application/vnd.sqlite3');
7656 4 $self->res->headers->content_disposition(qq{attachment; filename="${name}.db"});
7657 4 $self->render(data => $data);
7658 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7659  
7660 # _render_json($self, $records, \@columns, $name) -> void (renders response)
7661 #
7662 # Purpose: Emit $records as a JSON array download.
7663 # Entry: $records is an arrayref of hashrefs; $name is a safe filename stem.
7664 # Exit: Renders the Mojolicious response.
7665 # Side Effects: Writes HTTP response headers and body.
7666 4 ▶sub _render_json :Protected ($self, $records, $columns, $name) {
Subroutine _render_json: called CC=1 SCAR=0.0
7667 4 $self->stash(buffer => 0);
7668 4 $self->res->headers->content_disposition(qq{attachment; filename="${name}.json"});
7669 4 $self->render(json => $records);
7670 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
7671  
7672 # ---------------------------------------------------------------------------
7673 # Public actions
7674 # ---------------------------------------------------------------------------
7675  
7676 =encoding utf8
7677  
7678 =head1 ACTIONS
7679  
7680 =head2 index
7681  
7682 C<GET /> -- Scan C<data_dir> and present a card grid of available tables.
7683  
7684 =head3 API SPECIFICATION
7685  
7686 =head4 INPUT
7687  
7688 None (reads C<data_dir> from application config, and C<BI_OPEN> and the
7689 C<Referer> header).
7690  
7691 =head4 OUTPUT
7692  
7693 When C<BI_OPEN> is set and the request has no C<Referer> from this server,
7694 redirects to C</open> for that path. Otherwise renders C<home.html.tt> with:
7695  
7696 tables ARRAYREF of { name => $stem, file => $basename }
7697 title 'Choose a Database'
7698  
7699 =head3 MESSAGES
7700  
7701 None produced by this action; any file-scan errors are silently ignored
7702 (empty directory yields an empty card grid).
7703  
7704 =head3 FORMAL SPECIFICATION
7705  
7706 index == lambda self .
7707 let dir = resolve self.app.config.data_dir in
7708 let tbls = { b | b in dir /\ basename(b) =~ EXT_RE } in
7709 post render(home, tables: map(stem, tbls))
7710  
7711 =head3 EXAMPLE
7712  
7713 GET / -> 200 text/html containing a card for each file in data/
7714  
7715 With BI_OPEN=/data/store.db and no Referer from this server:
7716 GET / -> 302 /open?path=%2Fdata%2Fstore.db
7717  
7718 =cut
7719  
7720 58 ▶sub index ($self) {
Subroutine index: called CC=6 SCAR=29.7
Pod documented
7721 # A database named when the server was started is what a reader arriving
7722 # from outside sees first. A Home link within the application carries this
7723 # server as its Referer and gets the list, so that stays reachable. The
7724 # check needs no state, so it survives morbo restarting the application.
7725 58 ▶ if (defined $ENV{BI_OPEN} && length $ENV{BI_OPEN}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{"BI_OPEN"} and length $ENV{"BI_OPEN"}) 0 58 58
Condition33%1/3
defined $ENV{"BI_OPEN"} and length $ENV{"BI_OPEN"}
!ll&&!rl&&r
5800
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
7726 0 my $from = $self->req->headers->referrer;
7727 0 my $here = $self->req->url->to_abs->host_port;
7728 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
7729 unless defined $from && (Mojo::URL->new($from)->host_port // '') eq $here;
7730 }
7731  
7732 58 my ($platform, $language) = $self->_resolve_template;
7733  
7734 # The layout writes the resolved language into <html lang>, so every action
7735 # that renders a template from $platform/$language hands it over; t/html-lang.t
7736 # holds the controller to that. A screen reader, a translation tool and
7737 # anything that indexes the page read the attribute.
7738 58 $self->render(
7739 template => "$platform/$language/home",
7740 handler => 'tt',
7741 format => 'html',
7742 tables => $self->_scan_data_dir,
7743 title => 'Choose a Database',
7744 language => $language,
7745 );
7746 }
7747  
7748 =head2 is_supported_file
7749  
7750 Say whether a file's name has an extension C</open> will read. C<script/database-bi>
7751 asks this to refuse a file before the server starts, rather than show a 404.
7752  
7753 =head3 API SPECIFICATION
7754  
7755 =head4 INPUT
7756  
7757 $path string, a file name or path; undef is allowed
7758  
7759 =head4 OUTPUT
7760  
7761 1 when the name ends in a supported extension (any case), otherwise 0
7762  
7763 =head3 MESSAGES
7764  
7765 None.
7766  
7767 =head3 FORMAL SPECIFICATION
7768  
7769 is_supported_file == lambda path . path =~ EXT_RE
7770  
7771 =head3 EXAMPLE
7772  
7773 is_supported_file('data/store.db') # 1
7774 is_supported_file('LICENSE') # 0
7775  
7776 =cut
7777  
7778 19 ▶sub is_supported_file ($path) {
Subroutine is_supported_file: called CC=3 SCAR=11.0
Pod documented
7779 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
7780 }
7781  
7782 =head2 require_login / login_form / login / logout
7783  
7784 The login, on only when config C<password_hash> is set (see
7785 L<Database::BI/Logging in>). C<require_login> is the C<under> every route but
7786 C</login>, C</logout>, C</share/:id> and C</embed/:id> passes through; the
7787 others are C<GET /login>, C<POST /login> and C<POST /logout>.
7788  
7789 A session is logged in when its C<login> value is this password's mark (an
7790 HMAC of the hash, keyed by the first secret), so a new password logs every
7791 session out. Wrong passwords are counted per remote address, in each server
7792 process: the tenth within 15 minutes locks that address out for the rest of
7793 the 15 minutes (C<429>), whether or not the next one is right.
7794  
7795 =head3 API SPECIFICATION
7796  
7797 =head4 INPUT
7798  
7799 require_login: any request
7800 GET /login: return= string, optional; a path on this site (default /)
7801 POST /login: password= string; return= as above
7802 POST /logout: none
7803  
7804 =head4 OUTPUT
7805  
7806 require_login: true when login is off or the session is logged in. Otherwise
7807 a browser's GET for a page is redirected (302) to
7808 /login?return=<the page>, and anything else gets
7809 401 application/json { "error": error_login_required }.
7810 GET /login: 200 text/html, the form; 302 to return= when logged in; with
7811 login off, 200 and a page that says no password is set.
7812 POST /login: 302 to return= when the password is right; 401 text/html, the
7813 form with error_login_failed, when not; 429 with
7814 error_login_locked after too many.
7815 POST /logout: 302 to /login (to / when login is off), the session ended.
7816  
7817 return= is followed only when it is a path on this site (one /, not // or /\);
7818 anything else goes to /.
7819  
7820 =cut
7821  
7822 # Wrong passwords per application (a test runs several) and remote address:
7823 # epoch seconds of each, newest last.
7824 5 my %LOGIN_FAILURES;
7825 5 Readonly my $LOGIN_WINDOW => 15 * 60;
7826 5 Readonly my $LOGIN_ATTEMPTS => 10;
7827  
7828 # _login_mark($self, $hash) -> $mark
7829 #
7830 # What a logged-in session holds: not the hash, which the readable cookie
7831 # would hand to anyone who saw it, but an HMAC of it keyed by the secret.
7832 0 ▶sub _login_mark ($self, $hash) {
Subroutine _login_mark: not called CC=1 SCAR=6.9
7833 0 return Digest::SHA::hmac_sha256_hex($hash, $self->app->secrets->[0]);
7834 }
7835  
7836 # _login_return($value) -> $path
7837 #
7838 # Where to go after logging in: a path on this site, never another site
7839 # (//evil.example and /\evil.example are other sites to a browser).
7840 0 ▶sub _login_return {
Subroutine _login_return: not called CC=5 SCAR=34.0
7841 0 my ($value) = @_;
7842 0 ▶ 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 0 0 0
Condition0%0/6
defined $value and $value =~ m(\A/(?![/\\]))u and not $value =~ /[\x00-\x20\x7f\\]/u
!ll&&!rl&&r
000
defined $value and $value =~ m(\A/(?![/\\]))u
!ll&&!rl&&r
000
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 table0%0/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
7843 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
7844 0 return $value;
7845 }
7846  
7847 # _login_hash($self) -> $hash | undef
7848 1921 ▶sub _login_hash ($self) {
Subroutine _login_hash: called CC=3 SCAR=13.1
7849 1921 my $hash = $self->app->config('password_hash');
7850 1921 ▶ return (defined $hash && length $hash) ? $hash : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $hash && length $hash ? : 0 1921 1921
Condition33%1/3
defined $hash and length $hash
!ll&&!rl&&r
192100
MC/DC0%0/2
defined $hash and length $hash
defined $hash length $hash
Truth table33%1/3
A and B
A= defined $hashB= length $hash
ABresult
0X0
100
111
7851 }
7852  
7853 0 ▶sub _logged_in ($self) {
Subroutine _logged_in: not called CC=4 SCAR=30.0
7854 0 ▶ my $hash = $self->_login_hash // return 1;
Condition0%0/2
$self->_login_hash // (return 1)
l!l
00
MC/DC0%0/1
$self->_login_hash // (return 1)
$self->_login_hash
Truth table0%0/2
A
A= $self->_login_hash
Aresult
11
00
7855 0 ▶ 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 0 0
Condition0%0/2
$self->session("login") // ""
l!l
00
MC/DC0%0/1
$self->session("login") // ""
$self->session("login")
Truth table0%0/2
A
A= $self->session("login")
Aresult
11
00
7856 }
7857  
7858 1921 ▶sub require_login ($self) {
Subroutine require_login: called CC=7 SCAR=38.2
Pod documented
7859 1921 ▶ return 1 unless defined $self->_login_hash;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->_login_hash 1921 0 1921
7860 0 ▶ if ($self->_logged_in) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_logged_in) 0 0 0
7861 0 $self->stash(logged_in => 1);
7862 0 return 1;
7863 }
7864  
7865 0 my $req = $self->req;
7866 0 $self->stash(buffer => 0);
7867 0 ▶ 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 0 0
Condition0%0/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
000
$req->method =~ /\A(?:GET|HEAD)\z/u and ($req->headers->accept // "") =~ m[text/html]u
!ll&&!rl&&r
000
$req->headers->accept // ""
l!l
00
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 table0%0/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
7868 && $req->url->path->to_string !~ m{\A/api/}) {
7869 0 my $url = Mojo::URL->new('/login')->query(return => $req->url->path_query);
7870 0 $self->redirect_to($url);
7871 0 return undef;
7872 }
7873 0 $self->render(json => { error => _message_text('error_login_required') }, status => 401);
7874 0 return undef;
7875 }
7876  
7877 0 ▶sub _render_login ($self, %args) {
Subroutine _render_login: not called CC=4 SCAR=30.0
7878 0 my ($platform, $language) = $self->_resolve_template;
7879 0 $self->stash(buffer => 0);
7880 return $self->render(
7881 template => "$platform/$language/login",
7882 handler => 'tt',
7883 format => 'html',
7884 title => 'Log in',
7885 language => $language,
7886 return_to => _login_return(scalar $self->param('return')),
7887 login_error => $args{error} // '',
7888 login_off => $args{login_off} ? 1 : 0,
7889 0 ▶ status => $args{status} // 200,
Branch: 1 branch
BranchTrueFalseTotal
$args{'login_off'} ? : 0 0 0
Condition0%0/4
$args{"error"} // ""
l!l
00
$args{"status"} // 200
l!l
00
MC/DC0%0/1
$args{"error"} // ""
$args{"error"}
MC/DC0%0/1
$args{"status"} // 200
$args{"status"}
Truth table0%0/2
A
A= $args{"error"}
Aresult
11
00
Truth table0%0/2
A
A= $args{"status"}
Aresult
11
00
7890 );
7891 }
7892  
7893 0 ▶sub login_form ($self) {
Subroutine login_form: not called CC=3 SCAR=24.8
Pod documented
7894 # With no password set the page says so, rather than offering a form that
7895 # could never succeed.
7896 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
7897 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
7898 0 return $self->_render_login;
7899 }
7900  
7901 0 ▶sub login ($self) {
Subroutine login: not called CC=12 SCAR=50.5
Pod documented
7902 0 my $hash = $self->_login_hash;
7903 0 ▶ return $self->redirect_to('/') unless defined $hash;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hash 0 0 0
7904  
7905 0 ▶ my $who = $self->tx->remote_address // '';
Condition0%0/2
$self->tx->remote_address // ""
l!l
00
MC/DC0%0/1
$self->tx->remote_address // ""
$self->tx->remote_address
Truth table0%0/2
A
A= $self->tx->remote_address
Aresult
11
00
7906 0 my $now = time;
7907 0 ▶ my $failures = $LOGIN_FAILURES{ Scalar::Util::refaddr($self->app) } //= {};
Condition0%0/2
$LOGIN_FAILURES{builtin::refaddr($self->app)} //= {}
l!l
00
MC/DC0%0/1
$LOGIN_FAILURES{builtin::refaddr($self->app)} //= {}
$LOGIN_FAILURES{builtin::refaddr($self->app)}
Truth table0%0/2
A
A= $LOGIN_FAILURES{builtin::refaddr($self->app)}
Aresult
11
00
7908 0 for my $addr (keys %{$failures}) {
7909 0 $failures->{$addr} = [ grep { $_ > $now - $LOGIN_WINDOW } @{ $failures->{$addr} } ];
7910 0 ▶ delete $failures->{$addr} unless @{ $failures->{$addr} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$failures->{$addr};} 0 0 0
7911 }
7912 0 ▶ my $seen = $failures->{$who} // [];
Condition0%0/2
$failures->{$who} // []
l!l
00
MC/DC0%0/1
$failures->{$who} // []
$failures->{$who}
Truth table0%0/2
A
A= $failures->{$who}
Aresult
11
00
7913 0 ▶ if (@{$seen} >= $LOGIN_ATTEMPTS) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$seen;} >= $LOGIN_ATTEMPTS) 0 0 0
7914 0 ▶ my $minutes = int(($seen->[0] + $LOGIN_WINDOW - $now + 59) / 60) || 1;
Condition0%0/2
int(($seen->[0] + $LOGIN_WINDOW - $now + 59) / 60) || 1
l!l
00
MC/DC0%0/1
int(($seen->[0] + $LOGIN_WINDOW - $now + 59) / 60) || 1
int(($seen->[0] + $LOGIN_WINDOW - $now + 59) / 60)
Truth table0%0/2
A
A= int(($seen->[0] + $LOGIN_WINDOW - $now + 59) / 60)
Aresult
11
00
7915 0 return $self->_render_login(error => sprintf(_message_text('error_login_locked'), $minutes), status => 429);
7916 }
7917  
7918 0 ▶ 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)) 0 0 0
Condition0%0/2
scalar $self->param("password") // ""
l!l
00
MC/DC0%0/1
scalar $self->param("password") // ""
scalar $self->param("password")
Truth table0%0/2
A
A= scalar $self->param("password")
Aresult
11
00
7919 0 ▶ push @{ $failures->{$who} //= [] }, $now;
Condition0%0/2
$failures->{$who} //= []
l!l
00
MC/DC0%0/1
$failures->{$who} //= []
$failures->{$who}
Truth table0%0/2
A
A= $failures->{$who}
Aresult
11
00
7920 0 $self->app->log->warn("Wrong password from $who");
7921 0 return $self->_render_login(error => _message_text('error_login_failed'), status => 401);
7922 }
7923  
7924 0 delete $failures->{$who};
7925 0 $self->session(login => $self->_login_mark($hash));
7926 0 return $self->redirect_to(_login_return(scalar $self->param('return')));
7927 }
7928  
7929 0 ▶sub logout ($self) {
Subroutine logout: not called CC=2 SCAR=17.9
Pod documented
7930 0 $self->session(expires => 1);
7931 0 ▶ return $self->redirect_to(defined $self->_login_hash ? '/login' : '/');
Branch: 1 branch
BranchTrueFalseTotal
defined $self->_login_hash ? : 0 0 0
7932 }
7933  
7934 =head2 preferences
7935  
7936 C<GET /preferences> -- Render the page where a reader sets their preferences:
7937 the light or dark theme, and how many rows a table shows on a page.
7938  
7939 Preferences belong to the browser, not to the server, so this action only
7940 renders the form. The theme is kept in C<localStorage>; the script that
7941 stores and applies it is in C<layouts/theme.html.tt>, which every page loads.
7942 The page size is kept in the cookie C<bi_per_page> (25, 50, 100, 200, or 0 for
7943 every row), because the server needs it before it reads the page; this action
7944 reads it to show the current choice.
7945  
7946 =head3 API SPECIFICATION
7947  
7948 =head4 INPUT
7949  
7950 cookie bi_per_page optional; the saved page size, shown as chosen
7951  
7952 =head4 OUTPUT
7953  
7954 200 text/html The preferences page.
7955  
7956 =head3 FORMAL SPECIFICATION
7957  
7958 preferences
7959 response! : HTTP
7960 ──────────
7961 response!.status = 200
7962  
7963 =cut
7964  
7965 1 ▶sub preferences ($self) {
Subroutine preferences: called CC=2 SCAR=8.1
Pod documented
7966 1 my ($platform, $language) = $self->_resolve_template;
7967  
7968 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
7969 template => "$platform/$language/preferences",
7970 handler => 'tt',
7971 format => 'html',
7972 title => 'Preferences',
7973 language => $language,
7974 page_size => _page_size_preference($self) // $DEFAULT_PER_PAGE,
7975 page_size_choices => [ @PAGE_SIZES ],
7976 page_size_cookie => $PAGE_SIZE_COOKIE,
7977 );
7978 }
7979  
7980 =head2 tutorial
7981  
7982 C<GET /tutorial> -- Render the tutorial that is part of the application.
7983  
7984 The chapters, questions and glossary are data in L<Database::BI::Tutorial>.
7985 They are not in this module's POD, so adding a feature means adding a chapter
7986 there and no change to this action or to the template.
7987  
7988 =head3 API SPECIFICATION
7989  
7990 =head4 INPUT
7991  
7992 None.
7993  
7994 =head4 OUTPUT
7995  
7996 200 text/html The tutorial page. It is cached when page_cache_dir is set.
7997  
7998 =head3 FORMAL SPECIFICATION
7999  
8000 tutorial
8001 response! : HTTP
8002 ──────────
8003 response!.status = 200
8004  
8005 =cut
8006  
8007 3 ▶sub tutorial ($self) {
Subroutine tutorial: called CC=2 SCAR=7.1
Pod documented
8008 3 ▶ return if $self->buffer_is_cached;
Branch: 1 branch
BranchTrueFalseTotal
if $self->buffer_is_cached 0 3 3
8009 3 my ($platform, $language) = $self->_resolve_template;
8010  
8011 3 $self->render(
8012 template => "$platform/$language/tutorial",
8013 handler => 'tt',
8014 format => 'html',
8015 title => 'Tutorial',
8016 language => $language,
8017 intro => Database::BI::Tutorial->intro,
8018 parts => Database::BI::Tutorial->parts,
8019 faq => Database::BI::Tutorial->faq,
8020 glossary => Database::BI::Tutorial->glossary,
8021 version => $self->app->VERSION,
8022 );
8023 }
8024  
8025 =head2 view
8026  
8027 C<GET /view/:table> -- Open and display the chosen table from C<data_dir>.
8028  
8029 =head3 API SPECIFICATION
8030  
8031 =head4 INPUT
8032  
8033 :table string Table name (alphanumeric + underscore). Returns 404 on
8034 other characters.
8035 ?f= string (repeatable) Filter spec: "col:op:val".
8036  
8037 =head4 DOMAIN CONSTRAINTS: :table
8038  
8039 C<:table> is validated against C<\A[A-Za-z_][A-Za-z0-9_]*\z> before C<open_table>
8040 is ever called. The first character must be a letter (A-Z, a-z) or an
8041 underscore; subsequent characters may also include digits (0-9).
8042  
8043 =over 4
8044  
8045 =item Valid partition
8046  
8047 C<sales> (letters only), C<_temp> (underscore-start), C<report_2024>
8048 (mixed). A name that is valid but has no backing file returns 200 with
8049 an error message -- NOT 404.
8050  
8051 =item Invalid partition
8052  
8053 C<1sales> (digit-start, 404), C<my.data> (dot, 404), C<my-data>
8054 (hyphen, 404), non-ASCII characters (404).
8055  
8056 =item Boundary values
8057  
8058 C<a> (single letter, valid), C<_> (single underscore, valid), C<1>
8059 (single digit, 404), C<a1> (letter then digit, valid), C<1a> (digit
8060 then letter, 404).
8061  
8062 =back
8063  
8064 =head4 OUTPUT
8065  
8066 On success renders C<dashboard.html.tt> with table data.
8067 On error re-renders C<home.html.tt> with an C<error> stash variable.
8068  
8069 =head3 MESSAGES
8070  
8071 error_table_open -- DataSource initialisation or fetch_all threw.
8072  
8073 =head3 FORMAL SPECIFICATION
8074  
8075 view == lambda self .
8076 pre self.stash('table') =~ TABLE_NAME_RE
8077 let src = open_table(table) in
8078 let records = src.fetch_all() in
8079 let cols = get_columns(src, records) in
8080 post render(dashboard, records: filter(records, f_params))
8081  
8082 =head3 EXAMPLE
8083  
8084 GET /view/sales -> 200 HTML table of all sales rows
8085 GET /view/sales?f=region:eq:North -> shows only North region rows
8086 GET /view/../etc -> 404
8087  
8088 =cut
8089  
8090 80 ▶sub view ($self) {
Subroutine view: called CC=16 SCAR=33.3
Pod documented
8091 80 my ($platform, $language) = $self->_resolve_template;
8092 80 my $table = $self->stash('table');
8093  
8094 80 ▶ unless (defined $table && $table =~ $TABLE_NAME_RE) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $table and $table =~ /$TABLE_NAME_RE/u) 0 80 80
Condition33%1/3
defined $table and $table =~ /$TABLE_NAME_RE/u
!ll&&!rl&&r
0080
MC/DC0%0/2
defined $table and $table =~ /$TABLE_NAME_RE/u
defined $table $table =~ /$TABLE_NAME_RE/u
Truth table33%1/3
A and B
A= defined $tableB= $table =~ /$TABLE_NAME_RE/u
ABresult
0X0
100
111
8095 0 return $self->reply->not_found;
8096 }
8097  
8098 80 my ($page, $per_page, $offset) = $self->_pagination;
8099  
8100 80 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 80 80
8101 80 my ($source, $records, $has_next, $is_multi);
8102 80 eval {
8103 80 ▶ $source = $self->_accelerated_source("table:$table") // $self->open_table($table);
Condition33%1/3
$self->_accelerated_source("table:$table") // $self->open_table($table)
l!l&&r!l&&!r
0800
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
8104 # Multi-table SQLite: flag redirect without fetching data.
8105 80 ▶ 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 79 80
Condition66%4/6
$source and $source->sqlite_tables and @{$source->sqlite_tables;} > 1
!ll&&!rl&&r
7901
$source and $source->sqlite_tables
!ll&&!rl&&r
0791
MC/DC33%1/3
$source and $source->sqlite_tables and @{$source->sqlite_tables;} > 1
$source $source->sqlite_tables @{$source->sqlite_tables;} > 1
Truth table50%2/4
A and B and C
A= $sourceB= $source->sqlite_tablesC= @{$source->sqlite_tables;} > 1
ABCresult
0XX0
10X0
1100
1111
8106 1 $is_multi = 1;
8107 } else {
8108 # _fetch_page applies reduce-before-paginate: full-fetch + filter + dedup
8109 # + Perl paginate when f= or d=1 are set; N+1 trick otherwise.
8110 79 ($records, $has_next) = $self->_fetch_page($source,
8111 { per_page => $per_page, offset => $offset, dedup => $dedup,
8112 calc_spec_key => "table:$table" });
8113 }
8114 };
8115 80 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 80 80
8116 # No file by that name: a 404 that names the table, with the trail
8117 # and the navigation, rather than the home page and the backend's
8118 # message (which gives away the data directory).
8119 # A directory that may not be read has no file by that name to offer either.
8120 0 my $error = $@;
8121 0 ▶ my $stem_of = sub { lc($_[0]->basename =~ s/\.[^.]+\z//r) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
8122 0 my $listing = eval { _data_dir_for($self->app)->list };
8123 0 $@ = $error;
8124 0 ▶ 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) 0 0 0
Condition0%0/3
$listing and grep {&$stem_of($_) eq lc $table;} $listing->each
!ll&&!rl&&r
000
MC/DC0%0/2
$listing and grep {&$stem_of($_) eq lc $table;} $listing->each
$listing grep {&$stem_of($_) eq lc $table;} $listing->each
Truth table0%0/3
A and B
A= $listingB= grep {&$stem_of($_) eq lc $table;} $listing->each
ABresult
0X0
100
111
8125 0 return $self->render(
8126 template => "$platform/$language/not_found",
8127 handler => 'tt',
8128 format => 'html',
8129 status => 404,
8130 title => 'Table not found',
8131 error_msg => $self->_i18n('error_table_missing', $table),
8132 language => $language,
8133 );
8134 }
8135 0 return $self->render(
8136 template => "$platform/$language/home",
8137 handler => 'tt',
8138 format => 'html',
8139 tables => [],
8140 title => 'Choose a Database',
8141 error => $self->_i18n('error_table_open', $table, _tidy_error($@)),
8142 language => $language,
8143 );
8144 }
8145  
8146 80 ▶ if ($is_multi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_multi) 1 79 80
8147 1 return $self->redirect_to('/tables?l=' . url_escape("table:$table"));
8148 }
8149  
8150 # A cross-row spec that could not be honoured has already rendered its 400
8151 # inside _fetch_page; drawing the page over it would hide the reason.
8152 79 ▶ return if $self->stash('_cross_row_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_cross_row_error") 1 78 79
8153  
8154 78 ▶ $records //= [];
Condition50%1/2
$records //= []
l!l
780
MC/DC0%0/1
$records //= []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
8155 # The page from _fetch_page is already reduced; this call is here for the chip
8156 # list only -- filter_specs (for export URLs) and filters_json (for the UI).
8157 78 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
8158  
8159 # Calculated fields belong to the table, not only to its charts. The table
8160 # action is addressed by :table rather than l=, so name the spec explicitly
8161 # when looking up the fields saved for it; otherwise a saved column would
8162 # appear in every chart and not in the table it was made from.
8163 78 my $page_columns;
8164 78 ($records, $page_columns) = $self->_page_columns($source, $records, "table:$table");
8165 78 ▶ return unless $page_columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $page_columns 2 76 78
8166 76 my @columns = @$page_columns;
8167  
8168 76 my $page_url = $self->req->url->clone;
8169 76 $page_url->query->remove('page')->remove('per_page');
8170 76 my $page_base_url = $page_url->to_string;
8171  
8172 76 ▶ $self->render(
Condition100%2/2
$self->param("back2_label") // "Back"
l!l
373
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
8173 template => "$platform/$language/dashboard",
8174 handler => 'tt',
8175 format => 'html',
8176 records => $records,
8177 columns => \@columns,
8178 table => $table,
8179 title => ucfirst($table),
8180 left_spec => "table:$table",
8181 combine_specs => [ $self->_calc_specs_of_request ],
8182 current_joins => [],
8183 available_tables => $self->_scan_join_tables,
8184 join_summaries => [],
8185 filter_specs => $filter_specs,
8186 filters_json => $filters_json,
8187 dedup => $dedup,
8188 back_url => _safe_back_url($self->param('back2')),
8189 back_label => $self->param('back2_label') // 'Back',
8190 export_url => $self->_build_export_url("table:$table", [], $filter_specs, undef, $dedup, {
8191 span => $self->param('span'), tcol => $self->param('tcol'), as => $self->param('as'),
8192 }),
8193 page => $page,
8194 per_page => $per_page,
8195 has_next => $has_next,
8196 page_base_url => $page_base_url,
8197 language => $language,
8198 );
8199 }
8200  
8201 =head2 browse
8202  
8203 C<GET /browse> -- Navigate the filesystem and pick a data file.
8204  
8205 =head3 API SPECIFICATION
8206  
8207 =head4 INPUT
8208  
8209 ?path= string Absolute filesystem path to browse (default: $HOME).
8210 Returns 404 when the path does not exist or is not a
8211 directory.
8212  
8213 =head4 OUTPUT
8214  
8215 Renders C<browse.html.tt> with:
8216  
8217 current_path string
8218 parent_href string or undef (undef at filesystem root)
8219 crumbs ARRAYREF of { name, href }
8220 dirs ARRAYREF of { name, href } -- subdirectories, sorted
8221 files ARRAYREF of { name, href } -- supported data files, sorted
8222  
8223 =head3 MESSAGES
8224  
8225 None; errors render as 404.
8226  
8227 =head3 FORMAL SPECIFICATION
8228  
8229 browse == lambda self .
8230 let dir = realpath(param('path') // first_root) in
8231 pre inside(dir, file_roots) /\ is_dir(dir)
8232 post render(browse, dirs: subdirs(dir), files: supported_files(dir))
8233  
8234 =head3 EXAMPLE
8235  
8236 GET /browse -> 200, lists $HOME
8237 GET /browse?path=/tmp -> 200, lists /tmp
8238 GET /browse?path=/nonexistent/xyz -> 404
8239  
8240 =cut
8241  
8242 49 ▶sub browse ($self) {
Subroutine browse: called CC=10 SCAR=24.1
Pod documented
8243 49 my ($platform, $language) = $self->_resolve_template;
8244  
8245 49 ▶ my $raw_path = $self->param('path') // _first_root($self);
Condition66%2/3
$self->param("path") // _first_root($self)
l!l&&r!l&&!r
6430
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
8246 49 ▶ if (my $refusal = _outside_roots($self, $raw_path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $refusal = _outside_roots($self, $raw_path)) 0 49 49
8247 0 return $self->render(text => $refusal, status => 403);
8248 }
8249 49 my $dir = eval { Mojo::File->new($raw_path)->realpath };
8250 49 ▶ return $self->reply->not_found unless defined $dir && -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir and -d $dir 0 49 49
Condition33%1/3
defined $dir and -d $dir
!ll&&!rl&&r
0049
MC/DC0%0/2
defined $dir and -d $dir
defined $dir -d $dir
Truth table33%1/3
A and B
A= defined $dirB= -d $dir
ABresult
0X0
100
111
8251  
8252 49 my $listing = $self->_list_dir($dir, 1);
8253  
8254 # Add browse hrefs to file entries (dirs already have path; browse needs href).
8255 my @dirs = map {
8256 59 +{ name => $_->{name}, href => '/browse?path=' . url_escape($_->{path}) }
8257 49 } @{ $listing->{dirs} };
8258  
8259 my @files = map {
8260 18 +{ name => $_->{name}, href => '/open?path=' . url_escape($_->{path}) }
8261 49 } @{ $listing->{files} };
8262  
8263 # Build breadcrumb trail from filesystem root down to $dir.
8264 49 my @crumbs;
8265 {
8266 49 my $f = $dir;
8267 49 while (1) {
8268 158 my $name = $f->basename;
8269 158 ▶ $name = '/' unless length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless length $name 0 158 158
8270 158 unshift @crumbs, { name => $name, href => '/browse?path=' . url_escape($f->to_string) };
8271 158 my $parent = $f->dirname;
8272 158 ▶ last if $parent->to_string eq $f->to_string;
Branch: 1 branch
BranchTrueFalseTotal
if $parent->to_string eq $f->to_string 49 109 158
8273 109 ▶ last if _outside_roots($self, $parent->to_string);
Branch: 1 branch
BranchTrueFalseTotal
if _outside_roots($self, $parent->to_string) 0 109 109
8274 109 $f = $parent;
8275 }
8276 }
8277  
8278 49 my $parent = $dir->dirname;
8279 49 ▶ 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) ? : 49 0 49
Condition33%1/3
$parent->to_string ne $dir->to_string and not _outside_roots($self, $parent->to_string)
!ll&&!rl&&r
0049
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
8280 ? '/browse?path=' . url_escape($parent->to_string)
8281 : undef;
8282  
8283 49 $self->render(
8284 template => "$platform/$language/browse",
8285 handler => 'tt',
8286 format => 'html',
8287 title => 'Browse Files',
8288 current_path => $dir->to_string,
8289 parent_href => $parent_href,
8290 crumbs => \@crumbs,
8291 dirs => \@dirs,
8292 files => \@files,
8293 language => $language,
8294 );
8295 }
8296  
8297 =head2 open_file
8298  
8299 C<GET /open> -- Open a supported data file from any absolute filesystem path.
8300  
8301 =head3 API SPECIFICATION
8302  
8303 =head4 INPUT
8304  
8305 ?path= string Absolute path to the data file. Returns 404 when missing,
8306 not a regular file, or the extension is not in SUPPORTED_EXT.
8307 ?f= string (repeatable) Filter spec: "col:op:val".
8308  
8309 =head4 DOMAIN CONSTRAINTS: ?path=
8310  
8311 =over 4
8312  
8313 =item Extension filter (C<EXT_RE>)
8314  
8315 The basename must match C<\.(?:csv|db|sql|xml|tsv|psv)\z> (case-insensitive).
8316 The C<\z> anchor (absolute end-of-string) means a URL-encoded trailing
8317 newline (e.g. C<file.csv%0A> decoded to C<file.csv\n>) does NOT pass --
8318 the C<\n> falls after the C<\z> boundary and the extension check fails.
8319  
8320 =item Valid partition
8321  
8322 C</data/sales.csv> (lowercase extension), C</tmp/REPORT.CSV> (uppercase
8323 extension, /i matches), any C<.db>, C<.sql>, C<.xml>, C<.tsv>, C<.psv> regular
8324 file.
8325  
8326 =item Invalid partition
8327  
8328 Absent C<?path=> (404), non-existent file (404), directory instead of
8329 file (404), unsupported extension such as C<.txt> (404), empty string
8330 (404), path containing a C<%0A> (newline) suffix (404).
8331  
8332 =item Double-extension filenames
8333  
8334 A file like C<file.php.csv> passes C<EXT_RE> (last segment is C<.csv>)
8335 but produces table stem C<file.php> which fails C<DataSource>'s
8336 C<TABLE_NAME_RE>. The C<open_table> call is inside C<eval>, so the
8337 croak is caught and the action returns 200 with a friendly error, not
8338 a 500.
8339  
8340 =back
8341  
8342 =head4 OUTPUT
8343  
8344 On success renders C<dashboard.html.tt> with C<back_url> pointing to the
8345 directory's C</browse> page, and C<file_path> set to the resolved absolute
8346 path (used by the template to record the file in C<localStorage>).
8347 On error re-renders C<home.html.tt> with C<error>, C<back_url>, C<back_label>.
8348  
8349 =head3 MESSAGES
8350  
8351 error_file_open -- DataSource threw during initialisation or fetch_all.
8352  
8353 =head3 FORMAL SPECIFICATION
8354  
8355 open_file == lambda self .
8356 let file = realpath(param('path')) in
8357 pre is_file(file) /\ basename(file) =~ EXT_RE
8358 let src = open_table(stem(file), dir=dirname(file)) in
8359 post render(dashboard, file_path: file.to_string)
8360  
8361 =head3 EXAMPLE
8362  
8363 GET /open?path=/data/archive/sales.csv -> 200, table view
8364 GET /open -> 404
8365 GET /open?path=/etc/passwd -> 404
8366  
8367 =cut
8368  
8369 86 ▶sub open_file ($self) {
Subroutine open_file: called CC=61 SCAR=55.6
Pod documented
8370 86 my ($platform, $language) = $self->_resolve_template;
8371 86 my $file_path = $self->param('path');
8372  
8373 86 ▶ return $self->reply->not_found unless defined $file_path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_path 42 44 86
8374  
8375 44 my ($page, $per_page, $offset) = $self->_pagination;
8376  
8377 # Bare redis:// URL (no table name) -- redirect to key-listing page.
8378 44 ▶ if ($file_path =~ $REDIS_URL_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file_path =~ /$REDIS_URL_RE/u) 0 44 44
8379 0 return $self->redirect_to('/tables?l=' . url_escape($file_path));
8380 }
8381  
8382 # A MariaDB server with no table named: list its tables.
8383 44 ▶ if ($file_path =~ $MARIADB_SERVER_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file_path =~ /$MARIADB_SERVER_RE/u) 0 44 44
8384 0 return $self->redirect_to('/tables?l=' . url_escape($file_path));
8385 }
8386  
8387 # Redis spec: redis:tablename|redis://host:port -- delegate to _open_spec.
8388 # MariaDB spec: mariadb:server/table -- likewise.
8389 44 ▶ 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 44 44
Condition33%1/3
$file_path =~ /$REDIS_SPEC_RE/u or $file_path =~ /$MARIADB_SPEC_RE/u
l!l&&r!l&&!r
0044
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
8390 0 my $lspec = $file_path;
8391 0 my ($source, $label) = $self->_open_spec($lspec);
8392 0 ▶ unless ($source) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($source) 0 0 0
8393 0 my $why = $self->stash('open_spec_error');
8394 0 ▶ return $self->reply->not_found unless defined $why;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $why 0 0 0
8395 0 return $self->render(
8396 template => "$platform/$language/home",
8397 handler => 'tt',
8398 format => 'html',
8399 tables => [],
8400 title => 'Error',
8401 error => $self->_i18n('error_file_open', $lspec, $why),
8402 back_url => '/',
8403 back_label => 'Home',
8404 language => $language,
8405 );
8406 }
8407 0 my $table = $label;
8408 0 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 0 0
8409 0 my ($records, $has_next);
8410 0 eval {
8411 0 ($records, $has_next) = $self->_fetch_page($source,
8412 { per_page => $per_page, offset => $offset, dedup => $dedup, calc_spec_key => $lspec });
8413 };
8414 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
8415 0 return $self->render(
8416 template => "$platform/$language/home",
8417 handler => 'tt',
8418 format => 'html',
8419 tables => [],
8420 title => 'Error',
8421 error => $self->_i18n('error_file_open', $label, _tidy_error($@)),
8422 back_url => '/',
8423 back_label => 'Home',
8424 language => $language,
8425 );
8426 }
8427 # A cross-row spec that could not be honoured has already rendered its 400
8428 # inside _fetch_page; the page must not be drawn over it.
8429 0 ▶ return if $self->stash('_cross_row_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_cross_row_error") 0 0 0
8430  
8431 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
8432 0 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
8433 0 my $page_columns;
8434 0 ($records, $page_columns) = $self->_page_columns($source, $records, $lspec);
8435 0 ▶ return unless $page_columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $page_columns 0 0 0
8436 0 my @columns = @$page_columns;
8437 0 my $rpage_url = $self->req->url->clone;
8438 0 $rpage_url->query->remove('page')->remove('per_page');
8439 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
8440 template => "$platform/$language/dashboard",
8441 handler => 'tt',
8442 format => 'html',
8443 records => $records,
8444 columns => \@columns,
8445 table => $table,
8446 title => $label,
8447 back_url => _safe_back_url($self->param('back')) // '/',
8448 back_label => $self->param('back_label') // 'Home',
8449 back2_url => _safe_back_url($self->param('back2')),
8450 back2_label => $self->param('back2_label') // 'Back',
8451 file_path => $file_path,
8452 left_spec => $lspec,
8453 combine_specs => [ $self->_calc_specs_of_request ],
8454 current_joins => [],
8455 available_tables => $self->_scan_join_tables,
8456 join_summaries => [],
8457 filter_specs => $filter_specs,
8458 filters_json => $filters_json,
8459 dedup => $dedup,
8460 export_url => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
8461 page => $page,
8462 per_page => $per_page,
8463 has_next => $has_next,
8464 page_base_url => $rpage_url->to_string,
8465 language => $language,
8466 );
8467 }
8468  
8469 # Remote path /../hostname/dir/file.ext: delegate opening to _open_spec
8470 # and render the dashboard directly, bypassing the realpath/local-file path.
8471 44 ▶ if ($file_path =~ m{\A/\.\./}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file_path =~ m[\A/\.\./]u) 4 40 44
8472 4 my $lspec = 'path:' . $file_path;
8473 4 my ($source, $label) = $self->_open_spec($lspec);
8474 4 ▶ return $self->reply->not_found unless $source;
Branch: 1 branch
BranchTrueFalseTotal
unless $source 1 3 4
8475 3 my $filename = $label;
8476 3 (my $table = $filename) =~ s/\.[^.]+\z//;
8477 3 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 3 3
8478 3 my ($records, $has_next);
8479 3 eval {
8480 3 ($records, $has_next) = $self->_fetch_page($source,
8481 { per_page => $per_page, offset => $offset, dedup => $dedup, calc_spec_key => $lspec });
8482 };
8483 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3 3
8484 0 return $self->render(
8485 template => "$platform/$language/home",
8486 handler => 'tt',
8487 format => 'html',
8488 tables => [],
8489 title => 'Error',
8490 error => $self->_i18n('error_file_open', $filename, _tidy_error($@)),
8491 back_url => '/',
8492 back_label => 'Home',
8493 language => $language,
8494 );
8495 }
8496 # A cross-row spec that could not be honoured has already rendered its 400
8497 # inside _fetch_page; the page must not be drawn over it.
8498 3 ▶ return if $self->stash('_cross_row_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_cross_row_error") 0 3 3
8499  
8500 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
8501 3 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
8502 3 my $page_columns;
8503 3 ($records, $page_columns) = $self->_page_columns($source, $records, $lspec);
8504 3 ▶ return unless $page_columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $page_columns 0 3 3
8505 3 my @columns = @$page_columns;
8506 3 my $rpage_url = $self->req->url->clone;
8507 3 $rpage_url->query->remove('page')->remove('per_page');
8508 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
8509 template => "$platform/$language/dashboard",
8510 handler => 'tt',
8511 format => 'html',
8512 records => $records,
8513 columns => \@columns,
8514 table => $table,
8515 title => $filename,
8516 back_url => '/',
8517 back_label => 'Home',
8518 back2_url => _safe_back_url($self->param('back2')),
8519 back2_label => $self->param('back2_label') // 'Back',
8520 file_path => $file_path,
8521 left_spec => $lspec,
8522 combine_specs => [ $self->_calc_specs_of_request ],
8523 current_joins => [],
8524 available_tables => $self->_scan_join_tables,
8525 join_summaries => [],
8526 filter_specs => $filter_specs,
8527 filters_json => $filters_json,
8528 dedup => $dedup,
8529 export_url => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
8530 page => $page,
8531 per_page => $per_page,
8532 has_next => $has_next,
8533 page_base_url => $rpage_url->to_string,
8534 language => $language,
8535 );
8536 }
8537  
8538 # A path that names a table after a "#", as a spec does, is that table.
8539 40 my ($named_file, $named_it) = _split_path($file_path);
8540 40 ▶ $file_path = $named_file if defined $named_it;
Branch: 1 branch
BranchTrueFalseTotal
if defined $named_it 0 40 40
8541 40 ▶ if (my $refusal = _outside_roots($self, $file_path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $refusal = _outside_roots($self, $file_path)) 0 40 40
8542 0 return $self->render(text => $refusal, status => 403);
8543 }
8544  
8545 40 my $file = eval { Mojo::File->new($file_path)->realpath };
8546 40 ▶ return $self->reply->not_found
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file and -f $file and $file->basename =~ /$EXT_RE/u 7 33 40
Condition100%6/6
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
!ll&&!rl&&r
4333
defined $file and -f $file
!ll&&!rl&&r
1336
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
8547 unless defined $file && -f $file && $file->basename =~ $EXT_RE;
8548  
8549 33 my $dir = $file->dirname;
8550 33 (my $table = $file->basename) =~ s/\.[^.]+\z//;
8551 33 my $back = '/browse?path=' . url_escape($dir->to_string);
8552 33 my $filename = $file->basename;
8553 33 my $lspec = 'path:' . $file->to_string;
8554  
8555 33 ▶ 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
1032
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
8556  
8557 # A table opened from the schema browser belongs to a file in data_dir. Name
8558 # it as table:store/sales so the join, filter and export panels keep the
8559 # chosen internal table instead of dropping back to the file's first table.
8560 33 ▶ if (defined $it && $it =~ $TABLE_NAME_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $it and $it =~ /$TABLE_NAME_RE/u) 1 32 33
Condition66%2/3
defined $it and $it =~ /$TABLE_NAME_RE/u
!ll&&!rl&&r
3201
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
8561 1 my $data_dir = eval { _data_dir_for($self->app)->realpath };
8562 1 my $file_dir = eval { $file->dirname->realpath };
8563 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
8564 }
8565 # Elsewhere the spec names the table after a "#", so the panels and charts
8566 # keep it too.
8567 33 ▶ $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 32 33
Condition66%6/9
defined $it and length $it and not $it =~ /[#\n]/u and $lspec =~ /\Apath:/u
!ll&&!rl&&r
3201
defined $it and length $it and not $it =~ /[#\n]/u
!ll&&!rl&&r
3201
defined $it and length $it
!ll&&!rl&&r
3201
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
8568  
8569 # Allow the tables view to override the default "Back to browser" link.
8570 33 my $back_override = _safe_back_url($self->param('back'));
8571 33 ▶ if ($back_override) {
Branch: 1 branch
BranchTrueFalseTotal
if ($back_override) 1 32 33
8572 1 $back = $back_override;
8573 }
8574 33 ▶ my $back_label_default = $back_override ? ($self->param('back_label') // 'Back') : 'Back to browser';
Branch: 1 branch
BranchTrueFalseTotal
$back_override ? : 1 32 33
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
8575  
8576 33 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 1 32 33
8577 33 my ($source, $records, $has_next, $is_multi_local);
8578 33 eval {
8579 33 ▶ $source = (defined $it ? undef : $self->_accelerated_source($lspec))
Branch: 2 branches
BranchTrueFalseTotal
defined $it ? : 1 32 33
defined $it ? : 1 32 33
Condition33%1/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
0330
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
8580 // $self->open_table($table, directory => $dir->to_string,
8581 defined $it ? (internal_table => $it) : ());
8582 # Multi-table SQLite without it=: flag redirect without fetching data.
8583 33 ▶ 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 32 33
Condition88%8/9
not defined $it and $source and $source->sqlite_tables and @{$source->sqlite_tables;} > 1
!ll&&!rl&&r
20121
not defined $it and $source and $source->sqlite_tables
!ll&&!rl&&r
11913
not defined $it and $source
!ll&&!rl&&r
1032
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
8584 13 && @{ $source->sqlite_tables } > 1) {
8585 1 $is_multi_local = 1;
8586 } else {
8587 32 ($records, $has_next) = $self->_fetch_page($source,
8588 { per_page => $per_page, offset => $offset, dedup => $dedup, calc_spec_key => $lspec });
8589 }
8590 };
8591 33 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 33 33
8592 # Provide a SQLite-specific hint when the error looks like a table-name
8593 # mismatch or a missing-tables failure so the user knows what to do. A
8594 # table whose name cannot be used has its own advice in the message.
8595 0 my $hint;
8596 0 ▶ 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) 0 0 0
Condition0%0/3
$filename =~ /\.(?:sql|sqlite|sqlite3|db)\z/iu and not $@ =~ /cannot be opened|can be opened/u
!ll&&!rl&&r
000
MC/DC0%0/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 table0%0/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
8597 0 $hint = 'SQLite files must contain at least one user-defined table. '
8598 . 'The table name inside the database does not need to match the '
8599 . 'filename -- the application auto-detects and uses the first table it can open.';
8600 }
8601 0 ▶ return $self->render(
Condition0%0/2
$self->param("back2_label") // "Back"
l!l
00
MC/DC0%0/1
$self->param("back2_label") // "Back"
$self->param("back2_label")
Truth table0%0/2
A
A= $self->param("back2_label")
Aresult
11
00
8602 template => "$platform/$language/home",
8603 handler => 'tt',
8604 format => 'html',
8605 tables => [],
8606 title => 'Error',
8607 error => $self->_i18n('error_file_open', $filename, _tidy_error($@)),
8608 hint => $hint,
8609 back_url => $back,
8610 back_label => $back_label_default,
8611 back2_url => _safe_back_url($self->param('back2')),
8612 back2_label => $self->param('back2_label') // 'Back',
8613 language => $language,
8614 );
8615 }
8616  
8617 33 ▶ if ($is_multi_local) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_multi_local) 1 32 33
8618 1 return $self->redirect_to('/tables?l=' . url_escape("path:${\$file->to_string}"));
8619 }
8620  
8621 # A cross-row spec that could not be honoured has already rendered its 400
8622 # inside _fetch_page; the page must not be drawn over it.
8623 32 ▶ return if $self->stash('_cross_row_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_cross_row_error") 0 32 32
8624  
8625 32 ▶ $records //= [];
Condition50%1/2
$records //= []
l!l
320
MC/DC0%0/1
$records //= []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
8626 32 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
8627 32 my $page_columns;
8628 32 ($records, $page_columns) = $self->_page_columns($source, $records, $lspec);
8629 32 ▶ return unless $page_columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $page_columns 0 32 32
8630 32 my @columns = @$page_columns;
8631  
8632 32 my $lpage_url = $self->req->url->clone;
8633 32 $lpage_url->query->remove('page')->remove('per_page');
8634  
8635 32 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
defined $it ? : 1 31 32
defined $it ? : 1 31 32
Condition50%1/2
$self->param("back2_label") // "Back"
l!l
032
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
8636 template => "$platform/$language/dashboard",
8637 handler => 'tt',
8638 format => 'html',
8639 records => $records,
8640 columns => \@columns,
8641 table => defined $it ? $it : $table,
8642 title => defined $it ? "$filename ($it)" : $filename,
8643 back_url => $back,
8644 back_label => $back_label_default,
8645 back2_url => _safe_back_url($self->param('back2')),
8646 back2_label => $self->param('back2_label') // 'Back',
8647 file_path => $file->to_string,
8648 left_spec => $lspec,
8649 combine_specs => [ $self->_calc_specs_of_request ],
8650 current_joins => [],
8651 available_tables => $self->_scan_join_tables,
8652 join_summaries => [],
8653 filter_specs => $filter_specs,
8654 filters_json => $filters_json,
8655 dedup => $dedup,
8656 export_url => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
8657 page => $page,
8658 per_page => $per_page,
8659 has_next => $has_next,
8660 page_base_url => $lpage_url->to_string,
8661 language => $language,
8662 );
8663 }
8664  
8665 =head2 import_url
8666  
8667 C<GET /import> -- Fetch a remote HTML page, extract the first (or selected)
8668 table, and render it as a sortable data grid.
8669  
8670 =head3 API SPECIFICATION
8671  
8672 =head4 INPUT
8673  
8674 ?url= string Required. Full http:// or https:// URL of the page
8675 that contains the HTML table. Returns home with an
8676 error message if the scheme is wrong, the fetch fails,
8677 or no table is found at the specified index.
8678 ?table_index= integer Zero-based index of the C<< <table> >> to use when
8679 the page contains more than one table (default: 0).
8680 ?f= string (repeatable) Filter spec: "col:op:val".
8681  
8682 =head4 OUTPUT
8683  
8684 On success renders C<dashboard.html.tt> with the same stash shape as C<open_file>,
8685 plus C<source_url> (the original URL) for C<localStorage> tracking.
8686  
8687 On error re-renders C<home.html.tt> with an C<error> stash variable.
8688  
8689 =head3 MESSAGES
8690  
8691 error_url_required -- empty or missing C<url> param
8692 error_url_invalid -- URL does not begin with http:// or https://
8693 error_url_fetch -- LWP fetch failure or no table found at the index
8694  
8695 =head3 EXAMPLE
8696  
8697 GET /import?url=https://matrix.perl-magpie.org/dist/Database-Abstraction/
8698 GET /import?url=https://example.com/data.html&table_index=2
8699  
8700 =cut
8701  
8702 49 ▶sub import_url ($self) {
Subroutine import_url: called CC=12 SCAR=25.1
Pod documented
8703 49 my ($platform, $language) = $self->_resolve_template;
8704  
8705 49 ▶ my $url = $self->param('url') // '';
Condition100%2/2
$self->param("url") // ""
l!l
445
MC/DC100%1/1
$self->param("url") // ""
$self->param("url")
Truth table100%2/2
A
A= $self->param("url")
Aresult
11
00
8706 49 ▶ my $idx = $self->param('table_index') // 0;
Condition50%1/2
$self->param("table_index") // 0
l!l
049
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
8707 49 ▶ $idx = 0 unless $idx =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $idx =~ /\A[0-9]+\z/u 0 49 49
8708  
8709 47 ▶ my $err_home = sub ($key, @args) {
Subroutine __ANON__: called CC=1 SCAR=0.0
8710 47 $self->render(
8711 template => "$platform/$language/home",
8712 handler => 'tt',
8713 format => 'html',
8714 tables => $self->_scan_data_dir,
8715 title => 'Choose a Database',
8716 error => $self->_i18n($key, @args),
8717 language => $language,
8718 );
8719 49 };
8720  
8721 49 ▶ return $err_home->('error_url_required') unless length $url;
Branch: 1 branch
BranchTrueFalseTotal
unless length $url 45 4 49
8722 4 ▶ return $err_home->('error_url_invalid', $url)
Branch: 1 branch
BranchTrueFalseTotal
unless $url =~ m[\Ahttps?://]iu 1 3 4
8723 unless $url =~ m{\Ahttps?://}i;
8724 3 ▶ return $err_home->('error_url_ssrf', $url)
Branch: 1 branch
BranchTrueFalseTotal
unless _is_safe_url($url) 1 2 3
8725 unless _is_safe_url($url);
8726  
8727 2 my ($source, $records);
8728 2 my $ok = eval {
8729 2 $source = $self->open_table('', url => $url, html_table_index => $idx);
8730 2 $records = $source->fetch_all;
8731 2 1;
8732 };
8733 2 ▶ return $err_home->('error_url_fetch', $url, _tidy_error($@)) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 2 2
8734  
8735 2 my $label = $source->table_name;
8736 2 my $lspec = "url:$url";
8737 2 my @columns = _get_columns($source, $records);
8738 2 my ($filtered, $filter_specs, $filters_json) = $self->_apply_filters($records);
8739 2 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 2 2
8740 2 ▶ $filtered = _dedup_records($filtered, \@columns) if $dedup;
Branch: 1 branch
BranchTrueFalseTotal
if $dedup 0 2 2
8741  
8742 2 my $self_url = '/import?url=' . url_escape($url);
8743 2 ▶ $self_url .= '&table_index=' . $idx if $idx;
Branch: 1 branch
BranchTrueFalseTotal
if $idx 0 2 2
8744  
8745 2 ▶ $self->render(
Condition100%2/2
$self->param("back2_label") // "Back"
l!l
11
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
8746 template => "$platform/$language/dashboard",
8747 handler => 'tt',
8748 format => 'html',
8749 records => $filtered,
8750 columns => \@columns,
8751 table => $label,
8752 title => $label,
8753 source_url => $url,
8754 back_url => $self_url,
8755 back_label => $label,
8756 back2_url => _safe_back_url($self->param('back2')),
8757 back2_label => $self->param('back2_label') // 'Back',
8758 left_spec => $lspec,
8759 combine_specs => [],
8760 current_joins => [],
8761 available_tables => $self->_scan_join_tables,
8762 join_summaries => [],
8763 filter_specs => $filter_specs,
8764 filters_json => $filters_json,
8765 dedup => $dedup,
8766 export_url => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
8767 language => $language,
8768 );
8769 }
8770  
8771 =head2 columns_api
8772  
8773 C<GET /api/columns> -- Return column names for a table or file as JSON.
8774  
8775 Used by the join UI to populate the right-key dropdown without a page reload.
8776  
8777 =head3 API SPECIFICATION
8778  
8779 =head4 INPUT
8780  
8781 ?table= string Table name from C<data_dir>, or C<file/table> for a table
8782 inside a multi-table SQLite file.
8783 ?path= string Absolute path to a data file.
8784 ?spec= string Unified spec: C<"table:name">, C<"table:file/table"> or
8785 C<"path:/abs/path">.
8786 Parsed only when C<table> and C<path> are both absent.
8787  
8788 One of C<table>, C<path>, or C<spec> must be present; C<table> takes
8789 precedence over C<path>, and both take precedence over C<spec>.
8790  
8791 =head4 OUTPUT
8792  
8793 200 application/json { "columns": ["col1", "col2", ...] }
8794 404 application/json { "error": "not found" }
8795  
8796 =head3 MESSAGES
8797  
8798 None produced by this action directly; internal errors yield a 404.
8799  
8800 =head3 FORMAL SPECIFICATION
8801  
8802 columns_api == lambda self .
8803 let src = open_spec(table_param or path_param or parse_spec(spec_param)) in
8804 pre src /= undef
8805 post render_json({ columns: get_columns(src) })
8806  
8807 =head3 EXAMPLE
8808  
8809 GET /api/columns?table=sales -> {"columns":["product","region","amount"]}
8810 GET /api/columns?table=store/customer -> {"columns":["id","name","email"]}
8811 GET /api/columns?spec=table:sales -> {"columns":["product","region","amount"]}
8812 GET /api/columns?spec=path:/data/f.csv -> {"columns":[...]}
8813 GET /api/columns?table=noexist -> 404
8814  
8815 =cut
8816  
8817 55 ▶sub columns_api ($self) {
Subroutine columns_api: called CC=28 SCAR=34.8
Pod documented
8818 55 my $table_name = $self->param('table');
8819 55 my $path = $self->param('path');
8820 55 my $path_internal;
8821  
8822 # Accept the unified spec format used by /join and /graph:
8823 # "table:name" or "path:/abs/path" -- mirrors _open_spec's parsing.
8824 55 ▶ if (!defined($table_name) && !defined($path)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $table_name or defined $path) 46 9 55
Condition100%3/3
defined $table_name or defined $path
l!l&&r!l&&!r
7246
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
8825 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
8826 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
8827 1 $table_name = $1;
8828 } elsif ($spec =~ /\Apath:(.+)\z/s) {
8829 3 ($path, $path_internal) = _split_path($1);
8830 }
8831 }
8832  
8833 55 my $source;
8834 55 ▶ if (($self->param('spec') // '') =~ $MARIADB_SPEC_RE) {
Branch: 3 branches
BranchTrueFalseTotal
if (($self->param('spec') // '') =~ /$MARIADB_SPEC_RE/u) { } 0 55 55
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) { } 6 49 55
elsif (defined $path) { } 6 43 49
Condition100%2/2
$self->param("spec") // ""
l!l
451
MC/DC100%1/1
$self->param("spec") // ""
$self->param("spec")
Truth table100%2/2
A
A= $self->param("spec")
Aresult
11
00
8835 0 ($source) = $self->_open_spec($self->param('spec'));
8836 }
8837 ▶ 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
4726
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
8838 6 my ($table, $internal) = ($1, $2);
8839 6 my $data_dir = _data_dir_for($self->app);
8840 6 my $stem = _table_stem($data_dir, $table);
8841 6 ▶ return $self->render(json => { error => 'not found' }, status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $stem 1 5 6
8842 unless defined $stem;
8843 5 $source = eval {
8844 5 ▶ $self->open_table($stem, directory => $data_dir->to_string,
Branch: 1 branch
BranchTrueFalseTotal
defined $internal ? : 0 5 5
8845 defined $internal ? (internal_table => $internal) : ())
8846 };
8847 }
8848 elsif (defined $path) {
8849 6 ▶ if ($path =~ m{\A/\.\./([^/]+)((?:/.+)?)/([^/]+)\z}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($path =~ m[\A/\.\./([^/]+)((?:/.+)?)/([^/]+)\z]u) { } 2 4 6
elsif (my $refusal = _outside_roots($self, $path)) { } 0 4 4
8850 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
8851 2 ▶ $dir_part = '/' unless length $dir_part;
Branch: 1 branch
BranchTrueFalseTotal
unless length $dir_part 0 2 2
8852 2 ▶ if ($host =~ $REMOTE_HOST_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($host =~ /$REMOTE_HOST_RE/u) 2 0 2
8853 2 ▶ my ($tbl, $ext) = $file =~ /\A(.+)\.([^.]+)\z/ ? ($1, $2) : ($file, undef);
Branch: 1 branch
BranchTrueFalseTotal
$file =~ /\A(.+)\.([^.]+)\z/u ? : 2 0 2
8854 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
8855 defined $ext ? (file_ext => $ext) : (),
8856 defined $path_internal ? (internal_table => $path_internal) : ()) };
8857 }
8858 } elsif (my $refusal = _outside_roots($self, $path)) {
8859 0 return $self->render(json => { error => $refusal }, status => 403);
8860 } else {
8861 4 my $file = eval { Mojo::File->new($path)->realpath };
8862 4 ▶ 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) 1 3 4
Condition83%5/6
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
!ll&&!rl&&r
301
defined $file and -f $file
!ll&&!rl&&r
211
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
8863 1 my $dir = $file->dirname->to_string;
8864 1 (my $tbl = $file->basename) =~ s/\.[^.]+\z//;
8865 1 ▶ $source = eval { $self->open_table($tbl, directory => $dir,
Branch: 1 branch
BranchTrueFalseTotal
defined $path_internal ? : 0 1 1
8866 defined $path_internal ? (internal_table => $path_internal) : ()) };
8867 }
8868 }
8869 }
8870  
8871 54 ▶ return $self->render(json => { error => 'not found' }, status => 404) unless $source;
Branch: 1 branch
BranchTrueFalseTotal
unless $source 46 8 54
8872  
8873 # Use _get_columns to ensure consistent ordering with the view action.
8874 0 ▶ my $recs = ($source->columns ? [] : eval { $source->fetch_all } // []);
Branch: 1 branch
BranchTrueFalseTotal
$source->columns ? : 8 0 8
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
8875 8 my @cols = _get_columns($source, $recs);
8876  
8877 8 $self->render(json => { columns => \@cols });
8878 }
8879  
8880 =head2 range_api
8881  
8882 C<GET /api/range> -- Return the min and max ISO date values for one column of
8883 a view. The view is the left source with any joins and combines applied, so
8884 the column may come from a joined table, and an inner join's dropped rows do not
8885 count. Filters are not applied.
8886  
8887 =head3 API SPECIFICATION
8888  
8889 =head4 INPUT
8890  
8891 ?l= string Required. Data source spec ("table:name", "path:/abs/path", etc.).
8892 ?col= string Required. Column name to compute the range for.
8893 ?j= string Optional, repeatable. Join spec "<spec>|<lkey>|<rkey>".
8894 ?jtype= string Optional. left (default), inner or outer.
8895 ?c= string Optional, repeatable. Source spec to stack under the view.
8896  
8897 =head4 OUTPUT
8898  
8899 200 application/json { "min": "YYYY-MM-DD", "max": "YYYY-MM-DD" }
8900 200 application/json { "min": null, "max": null } (no parseable dates)
8901 400 application/json { "error": "..." }
8902  
8903 =head3 FORMAL SPECIFICATION
8904  
8905 range_api == lambda self .
8906 let recs = _run_pipeline_source().records in
8907 pre param('l') /= '' /\ col /= ''
8908 post render_json({ min: min_date(recs, col), max: max_date(recs, col) })
8909  
8910 =cut
8911  
8912 54 ▶sub range_api ($self) {
Subroutine range_api: called CC=13 SCAR=25.7
Pod documented
8913 54 ▶ my $spec_str = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
531
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
8914 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
8915 54 ▶ return $self->render(json => { error => 'l required' }, status => 400) unless length $spec_str;
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec_str 2 52 54
8916 52 ▶ return $self->render(json => { error => 'col required' }, status => 400) unless length $col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 2 50 52
8917  
8918 # The pipeline, so that the range is of the rows the page shows. A join
8919 # that cannot be built croaks; this route answers "no range" instead.
8920 50 my (undef, $records, $columns) = eval { $self->_run_pipeline_source };
8921 return $self->render(json => { min => undef, max => undef })
8922 50 ▶ unless $records && grep { $_ eq $col } @$columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $records and grep {$_ eq $col;} @$columns 5 45 50
Condition100%3/3
$records and grep {$_ eq $col;} @$columns
!ll&&!rl&&r
2345
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
8923  
8924 45 my $mdy_re = qr|\A(\d{1,2})/(\d{1,2})/(\d{4})\z|;
8925 45 my @dates;
8926 45 for my $rec (@$records) {
8927 254 ▶ my $v = $rec->{$col} // '';
Condition100%2/2
$rec->{$col} // ""
l!l
2531
MC/DC100%1/1
$rec->{$col} // ""
$rec->{$col}
Truth table100%2/2
A
A= $rec->{$col}
Aresult
11
00
8928 254 ▶ next unless length $v;
Branch: 1 branch
BranchTrueFalseTotal
unless length $v 1 253 254
8929 # A timestamp counts as the day it names, as the filters read it.
8930 253 ▶ 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])) { } 13 240 253
elsif (my(@m) = $v =~ /$mdy_re/u) { } 0 240 240
8931 13 push @dates, $day;
8932 } elsif (my @m = ($v =~ $mdy_re)) {
8933 0 push @dates, sprintf '%04d-%02d-%02d', $m[2], $m[0], $m[1];
8934 }
8935 }
8936  
8937 45 ▶ return $self->render(json => { min => undef, max => undef }) unless @dates;
Branch: 1 branch
BranchTrueFalseTotal
unless @dates 40 5 45
8938 5 @dates = sort @dates;
8939 5 $self->render(json => { min => $dates[0], max => $dates[-1] });
8940 }
8941  
8942 =head2 join_tables
8943  
8944 C<GET /join> -- Perform one or more left joins and render the merged table.
8945  
8946 =head3 API SPECIFICATION
8947  
8948 =head4 INPUT
8949  
8950 ?l= string Required. Left table spec: "table:name", "table:file/table"
8951 or "path:/abs/path". Returns 404 if unresolvable.
8952 ?j= string (repeatable) Join step: "<right-spec>|<left-key>|<right-key>".
8953 Invalid or non-existent steps are silently skipped.
8954 ?f= string (repeatable) Result filter: "col:op:val".
8955  
8956 =head4 OUTPUT
8957  
8958 Renders C<dashboard.html.tt> with the merged/filtered result set.
8959  
8960 =head3 MESSAGES
8961  
8962 error_table_open -- Left table fetch threw (re-renders home with error).
8963  
8964 =head3 FORMAL SPECIFICATION
8965  
8966 join_tables == lambda self .
8967 let left = open_spec(param('l')) in
8968 pre left /= undef
8969 let joined = fold(_left_join, left, param_list('j')) in
8970 let filtered = fold(_apply_filter_spec, joined, param_list('f')) in
8971 post render(dashboard, records: filtered)
8972  
8973 =head3 PSEUDOCODE
8974  
8975 1. Parse and open left table spec; 404 on failure.
8976 2. For each j= param (in order):
8977 a. Parse right-spec, left-key, right-key from "|"-split.
8978 b. Verify left-key exists in current column list.
8979 c. Open right table; skip step on any error.
8980 d. Verify right-key exists in right column list.
8981 e. Call _left_join; update records and columns.
8982 3. Apply all f= filters via _apply_filter_spec.
8983 4. Build stable table key for localStorage ("join:left:right1:...").
8984 5. Render dashboard.
8985  
8986 =head3 EXAMPLE
8987  
8988 GET /join?l=table:sales&j=table:products|product|name
8989 -> merged left join of sales and products on product/name columns
8990  
8991 =cut
8992  
8993 54 ▶sub join_tables ($self) {
Subroutine join_tables: called CC=30 SCAR=34.9
Pod documented
8994 # Rows stacked from other files cannot be paged from one backend; the
8995 # combine route runs joins and combines together. c= also carries calculated
8996 # fields, which do not stack anything and stay on this page.
8997 return $self->combine_tables
8998 54 ▶ 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 54 54
8999  
9000 54 my ($platform, $language) = $self->_resolve_template;
9001  
9002 54 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
531
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
9003 54 my ($left_src, $left_label) = $self->_open_spec($left_spec);
9004 54 ▶ return $self->reply->not_found unless $left_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $left_src 4 50 54
9005  
9006 50 my @join_specs = @{ $self->every_param('j') };
9007 50 my @summaries;
9008  
9009 # Build the join chain: each step wraps the previous source in a
9010 # Database::Join. Data is not fetched until after the loop.
9011 50 ▶ 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
0500
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
9012 50 ▶ my $join_type = $self->param('jtype') // 'left';
Condition100%2/2
$self->param("jtype") // "left"
l!l
248
MC/DC100%1/1
$self->param("jtype") // "left"
$self->param("jtype")
Truth table100%2/2
A
A= $self->param("jtype")
Aresult
11
00
9013 50 ▶ $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 49 50
9014 50 my $src = $left_src;
9015 50 my @schema_warnings;
9016 50 for my $jspec (@join_specs) {
9017 9 my ($right_spec, $left_key, $right_key) = split /\|/, $jspec, 3;
9018 9 ▶ 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 7 9
Condition66%4/6
defined $right_spec and defined $left_key and defined $right_key
!ll&&!rl&&r
207
defined $right_spec and defined $left_key
!ll&&!rl&&r
027
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
9019  
9020 7 my $cur_cols = $src->columns;
9021 7 ▶ next unless $cur_cols;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_cols 0 7 7
9022 7 ▶ next unless +{ map { $_ => 1 } @$cur_cols }->{$left_key};
Branch: 1 branch
BranchTrueFalseTotal
unless {map({$_, 1;} @$cur_cols)}->{$left_key} 0 7 7
9023  
9024 7 my ($right_src, $right_label) = $self->_open_spec($right_spec);
9025 7 ▶ next unless $right_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_src 1 6 7
9026  
9027 6 my $right_cols = $right_src->columns;
9028 6 ▶ next unless $right_cols;
Branch: 1 branch
BranchTrueFalseTotal
unless $right_cols 0 6 6
9029 6 ▶ next unless +{ map { $_ => 1 } @$right_cols }->{$right_key};
Branch: 1 branch
BranchTrueFalseTotal
unless {map({$_, 1;} @$right_cols)}->{$right_key} 0 6 6
9030  
9031 # Types are compared while the two sides are still separate sources;
9032 # after the join is built the mismatched columns are already published
9033 # under different names. See _schema_type_warnings.
9034 6 push @schema_warnings, $self->_schema_type_warnings(
9035 $src, $right_src, $left_label, $right_label, $left_key, $right_key);
9036  
9037 6 require Database::Join;
9038 0 ▶ local $SIG{__WARN__} = sub { push @schema_warnings, $_[0] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
9039 6 ▶ $src = Database::Join->new(
Branch: 2 branches
BranchTrueFalseTotal
$left_key ne $right_key ? : 0 6 6
$right_label ? : 6 0 6
9040 databases => [$src, $right_src],
9041 join_column => $left_key,
9042 backend => 'auto',
9043 max_array_rows => $max_rows,
9044 join_type => $join_type,
9045 ($left_key ne $right_key ? (join_map => {1 => $right_key}) : ()),
9046 ($right_label ? (collision_prefix => {1 => $right_label}) : ()),
9047 );
9048 6 push @summaries, { label => $right_label, left_key => $left_key, right_key => $right_key };
9049 }
9050  
9051 50 my ($page, $per_page, $offset) = $self->_pagination;
9052 50 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 50 50
9053 50 my $sort = $self->param('sort');
9054 50 ▶ my $dir = ($self->param('dir') // 'asc') =~ /\Adesc\z/i ? 'desc' : 'asc';
Branch: 1 branch
BranchTrueFalseTotal
($self->param('dir') // 'asc') =~ /\Adesc\z/iu ? : 1 49 50
Condition100%2/2
$self->param("dir") // "asc"
l!l
149
MC/DC100%1/1
$self->param("dir") // "asc"
$self->param("dir")
Truth table100%2/2
A
A= $self->param("dir")
Aresult
11
00
9055  
9056 50 my ($records, $has_next);
9057 50 eval {
9058 50 ($records, $has_next) = $self->_fetch_page($src,
9059 { per_page => $per_page, offset => $offset,
9060 dedup => $dedup, sort_col => $sort,
9061 sort_dir => $dir, calc_spec_key => $left_spec });
9062 };
9063 50 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 50 50
9064 0 return $self->render(
9065 template => "$platform/$language/home",
9066 handler => 'tt',
9067 format => 'html',
9068 tables => [],
9069 title => 'Error',
9070 error => $self->_i18n('error_table_open', $left_label, _tidy_error($@)),
9071 language => $language,
9072 );
9073 }
9074 # A cross-row spec that could not be honoured has already rendered its 400
9075 # inside _fetch_page; the page must not be drawn over it.
9076 50 ▶ return if $self->stash('_cross_row_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_cross_row_error") 1 49 50
9077  
9078 49 ▶ $records //= [];
Condition50%1/2
$records //= []
l!l
490
MC/DC0%0/1
$records //= []
$records
Truth table50%1/2
A
A= $records
Aresult
11
00
9079 49 my $page_columns;
9080 49 ($records, $page_columns) = $self->_page_columns($src, $records, $left_spec);
9081 49 ▶ return unless $page_columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $page_columns 2 47 49
9082 47 my @columns = @$page_columns;
9083  
9084 47 ▶ if (defined $sort && !grep { $_ eq $sort } @columns) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sort and not grep({$_ eq $sort;} @columns)) 1 46 47
Condition100%3/3
defined $sort and not grep({$_ eq $sort;} @columns)
!ll&&!rl&&r
4511
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
9085 1 carp $self->_i18n('error_sort_column', $sort);
9086 }
9087  
9088 47 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
9089  
9090 47 my $title = $left_label;
9091 47 ▶ $title .= ' + ' . join(' + ', map { $_->{label} } @summaries) if @summaries;
Branch: 1 branch
BranchTrueFalseTotal
if @summaries 6 41 47
9092 47 my $table_key = 'join:' . lc($left_label);
9093 47 $table_key .= ':' . lc($_->{label}) for @summaries;
9094  
9095 47 my $page_url = $self->req->url->clone;
9096 47 $page_url->query->remove('page')->remove('per_page');
9097  
9098 47 ▶ $self->render(
Condition50%1/2
$self->param("back2_label") // "Back"
l!l
047
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
9099 template => "$platform/$language/dashboard",
9100 handler => 'tt',
9101 format => 'html',
9102 records => $records,
9103 columns => \@columns,
9104 table => $table_key,
9105 title => $title,
9106 back_url => $self->_spec_to_url($left_spec),
9107 back_label => "Back to $left_label",
9108 back2_url => _safe_back_url($self->param('back2')),
9109 back2_label => $self->param('back2_label') // 'Back',
9110 left_spec => $left_spec,
9111 combine_specs => [ $self->_calc_specs_of_request ],
9112 current_joins => \@join_specs,
9113 available_tables => $self->_scan_join_tables,
9114 join_summaries => \@summaries,
9115 filter_specs => $filter_specs,
9116 filters_json => $filters_json,
9117 dedup => $dedup,
9118 export_url => $self->_build_export_url($left_spec, \@join_specs, $filter_specs, undef, $dedup),
9119 schema_warnings => \@schema_warnings,
9120 page => $page,
9121 per_page => $per_page,
9122 has_next => $has_next,
9123 page_base_url => $page_url->to_string,
9124 language => $language,
9125 );
9126 }
9127  
9128 =head2 combine_tables
9129  
9130 C<GET /combine> -- Stack rows from two or more tables vertically into a single
9131 unified view.
9132  
9133 Unlike C</join> (which appends columns from a matching row in a second table),
9134 C</combine> appends the I<rows> from a second table beneath the rows of the
9135 first. All columns from all sources appear as headers; where a row has no
9136 value for a particular column (because that column did not exist in its source
9137 file) the cell is left blank.
9138  
9139 This is equivalent to a SQL C<UNION ALL> across heterogeneous schemas.
9140  
9141 =head3 API SPECIFICATION
9142  
9143 =head4 INPUT
9144  
9145 ?l= string (required) Left table spec: "table:name" or "path:/abs/path".
9146 Returns 404 if unresolvable.
9147 ?c= string (repeatable) Additional table spec to stack beneath the
9148 current result. Invalid or non-existent specs are silently
9149 skipped.
9150 ?f= string (repeatable) Result filter: "col:op:val".
9151  
9152 =head4 OUTPUT
9153  
9154 Renders C<dashboard.html.tt> with the combined result set.
9155  
9156 =head3 MESSAGES
9157  
9158 error_table_open -- Left table fetch threw (re-renders home with error).
9159  
9160 =head3 FORMAL SPECIFICATION
9161  
9162 combine_tables == lambda self .
9163 let left = open_spec(param('l')) in
9164 pre left /= undef
9165 let sources = [left] ++ map(open_spec, param_list('c')) in
9166 let combined = _combine_tables(sources) in
9167 let filtered = fold(_apply_filter_spec, combined, param_list('f')) in
9168 post render(dashboard, records: filtered)
9169  
9170 =head3 EXAMPLE
9171  
9172 GET /combine?l=table:cats&c=table:dogs
9173 -> unified view: all cat and dog rows; Species/Name/Color/Breed/Eye Color
9174 appear for both; Environment (cats-only) and Sex/Fixed (dogs-only)
9175 are blank where the source file lacks that column.
9176  
9177 =cut
9178  
9179 50 ▶sub combine_tables ($self) {
Subroutine combine_tables: called CC=26 SCAR=35.6
Pod documented
9180 50 my ($platform, $language) = $self->_resolve_template;
9181  
9182 50 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
491
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
9183 50 my ($left_src, $left_label) = $self->_open_spec($left_spec);
9184 50 ▶ return $self->reply->not_found unless $left_src;
Branch: 1 branch
BranchTrueFalseTotal
unless $left_src 4 46 50
9185  
9186 # The same join-then-stack pipeline the charts of this view use, so the
9187 # table shows the rows they draw.
9188 46 my (undef, $records, $cols_ref) = $self->_run_pipeline_source;
9189 46 ▶ unless (defined $records) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $records) 0 46 46
9190 0 return $self->render(
9191 template => "$platform/$language/home",
9192 handler => 'tt',
9193 format => 'html',
9194 tables => [],
9195 title => 'Error',
9196 error => $self->_i18n('error_table_open', $left_label, ''),
9197 language => $language,
9198 );
9199 }
9200 46 my @join_specs = @{ $self->every_param('j') };
9201 46 my @combine_specs = @{ $self->every_param('c') };
9202 46 ▶ my @summaries = (@{ $self->stash('pipeline_joined') // [] },
Condition50%1/2
$self->stash("pipeline_joined") // []
l!l
460
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
9203 46 ▶ @{ $self->stash('pipeline_combined') // [] });
Condition50%1/2
$self->stash("pipeline_combined") // []
l!l
460
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
9204  
9205 # Stage 4, for a table of stacked rows as for any other.
9206 46 my $span = $self->_span_calc_spec($cols_ref, ());
9207 46 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 2 44 46
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
4402
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
9208 44 my ($calc_records, $calc_columns) = eval {
9209 44 ▶ $self->_apply_calc_fields($records, $cols_ref, ($span ? { calc => $span->{calc} } : undef))
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 44 44
9210 };
9211 44 ▶ unless ($calc_records) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($calc_records) 1 43 44
9212 1 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
9213 1 return $self->render(text => $e, status => 400);
9214 }
9215 43 ($records, $cols_ref) = ($calc_records, $calc_columns);
9216  
9217 # Apply the filters in memory before paginating (reduce-before-paginate).
9218 43 my @columns;
9219 43 ▶ return unless $self->_reduce_or_render(\$records, \$cols_ref);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$cols_ref) 1 42 43
9220 42 @columns = @$cols_ref;
9221 # _reduce_or_render has removed duplicates for d=1; $dedup is for the page.
9222 42 ▶ my $dedup = $self->param('d') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('d') ? : 0 42 42
9223  
9224 # In-memory sort for /combine (no single backend to delegate to).
9225 42 my $sort = $self->param('sort');
9226 42 ▶ my $dir = ($self->param('dir') // 'asc') =~ /\Adesc\z/i ? 'desc' : 'asc';
Branch: 1 branch
BranchTrueFalseTotal
($self->param('dir') // 'asc') =~ /\Adesc\z/iu ? : 0 42 42
Condition50%1/2
$self->param("dir") // "asc"
l!l
042
MC/DC0%0/1
$self->param("dir") // "asc"
$self->param("dir")
Truth table50%1/2
A
A= $self->param("dir")
Aresult
11
00
9227 42 ▶ if (defined $sort && grep { $_ eq $sort } @columns) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort and grep {$_ eq $sort;} @columns) { } 0 42 42
elsif (defined $sort) { } 1 41 42
Condition66%2/3
defined $sort and grep {$_ eq $sort;} @columns
!ll&&!rl&&r
4110
MC/DC0%0/2
defined $sort and grep {$_ eq $sort;} @columns
defined $sort grep {$_ eq $sort;} @columns
Truth table66%2/3
A and B
A= defined $sortB= grep {$_ eq $sort;} @columns
ABresult
0X0
100
111
9228 0 carp $self->_i18n('warn_combine_sort');
9229 # A new array: the backend's own can be read-only, as a SQLite one is.
9230 0 ▶ $records = [ sort { ($a->{$sort} // '') cmp ($b->{$sort} // '') } @$records ];
Condition0%0/4
$Database::BI::Controller::Dashboard::a->{$sort} // ""
l!l
00
$Database::BI::Controller::Dashboard::b->{$sort} // ""
l!l
00
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 table0%0/2
A
A= $Database::BI::Controller::Dashboard::a->{$sort}
Aresult
11
00
Truth table0%0/2
A
A= $Database::BI::Controller::Dashboard::b->{$sort}
Aresult
11
00
9231 0 ▶ $records = [ reverse @$records ] if $dir eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if $dir eq "desc" 0 0 0
9232 } elsif (defined $sort) {
9233 1 carp $self->_i18n('error_sort_column', $sort);
9234 }
9235  
9236 # Server-side pagination: slice the fully-reduced combined set. The page
9237 # below is therefore reduced too, and asks for chips only.
9238 42 my ($page, $per_page, $offset) = $self->_pagination;
9239 42 my $total = scalar @$records;
9240 42 ▶ my $has_next = ($total > $offset + $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$total > $offset + $per_page ? : 0 42 42
9241 42 my @page_recs = @{ _rows_of_page($records, $offset, $per_page) };
9242 42 $records = \@page_recs;
9243 42 $self->stash(page_count => _page_count($total, $per_page));
9244  
9245 42 my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
9246  
9247 42 my $title = $left_label;
9248 42 ▶ $title .= ' + ' . join(' + ', map { $_->{label} } @summaries) if @summaries;
Branch: 1 branch
BranchTrueFalseTotal
if @summaries 4 38 42
9249 42 ▶ my $table_key = (@join_specs ? 'join+combine:' : 'combine:') . lc($left_label);
Branch: 1 branch
BranchTrueFalseTotal
@join_specs ? : 1 41 42
9250 42 $table_key .= ':' . lc($_->{label}) for @summaries;
9251  
9252 42 my $page_url = $self->req->url->clone;
9253 42 $page_url->query->remove('page')->remove('per_page');
9254  
9255 42 ▶ $self->render(
Condition50%2/4
$self->param("back2_label") // "Back"
l!l
042
$self->stash("schema_warnings") // []
l!l
042
MC/DC0%0/1
$self->param("back2_label") // "Back"
$self->param("back2_label")
MC/DC0%0/1
$self->stash("schema_warnings") // []
$self->stash("schema_warnings")
Truth table50%1/2
A
A= $self->param("back2_label")
Aresult
11
00
Truth table50%1/2
A
A= $self->stash("schema_warnings")
Aresult
11
00
9256 template => "$platform/$language/dashboard",
9257 handler => 'tt',
9258 format => 'html',
9259 records => $records,
9260 columns => \@columns,
9261 table => $table_key,
9262 title => $title,
9263 back_url => $self->_spec_to_url($left_spec),
9264 back_label => "Back to $left_label",
9265 back2_url => _safe_back_url($self->param('back2')),
9266 back2_label => $self->param('back2_label') // 'Back',
9267 left_spec => $left_spec,
9268 combine_specs => \@combine_specs,
9269 current_joins => \@join_specs,
9270 available_tables => $self->_scan_join_tables,
9271 join_summaries => \@summaries,
9272 filter_specs => $filter_specs,
9273 filters_json => $filters_json,
9274 dedup => $dedup,
9275 export_url => $self->_build_export_url($left_spec, \@join_specs, $filter_specs, \@combine_specs, $dedup),
9276 schema_warnings => $self->stash('schema_warnings') // [],
9277 page => $page,
9278 per_page => $per_page,
9279 has_next => $has_next,
9280 page_base_url => $page_url->to_string,
9281 language => $language,
9282 );
9283 }
9284  
9285 =head2 export_data
9286  
9287 C<GET /export> -- Stream the current logical view as a browser file download.
9288  
9289 =head3 API SPECIFICATION
9290  
9291 =head4 INPUT
9292  
9293 ?l= string (required) Left table spec.
9294 ?j= string (repeatable) Join steps.
9295 ?f= string (repeatable) Filter specs.
9296 ?format= string "csv" (default), "sqlite", or "json".
9297  
9298 =head4 DOMAIN CONSTRAINTS: ?format=
9299  
9300 Exact lowercase string match.
9301  
9302 =over 4
9303  
9304 =item Valid partitions
9305  
9306 C<csv> (explicit CSV), C<sqlite> (SQLite binary), C<json> (JSON array),
9307 absent/undef (defaults to CSV).
9308  
9309 =item Invalid partitions (all fall back to CSV)
9310  
9311 Any value not in the valid set (e.g. C<SQLITE>, C<Json>).
9312  
9313 =back
9314  
9315 =head4 OUTPUT
9316  
9317 200 text/csv Content-Disposition: attachment; filename=<name>.csv
9318 200 application/vnd.sqlite3 Content-Disposition: attachment; filename=<name>.db
9319 200 application/json Content-Disposition: attachment; filename=<name>.json
9320 404 application/json { "error": "Table not found" }
9321 500 text/plain The SQLite file could not be built (no driver, no
9322 temporary space); the reason goes to the log.
9323  
9324 =head3 MESSAGES
9325  
9326 error_export_sqlite -- the SQLite file could not be built.
9327  
9328 =head3 FORMAL SPECIFICATION
9329  
9330 export_data == lambda self .
9331 let (recs, cols, label) = _run_export_pipeline() in
9332 pre recs /= undef
9333 post if format = 'sqlite' then render_sqlite(recs, cols)
9334 else if format = 'json' then render_json(recs, cols)
9335 else render_csv(recs, cols)
9336  
9337 =head3 EXAMPLE
9338  
9339 GET /export?l=table:sales&format=csv -> downloads sales.csv
9340 GET /export?l=table:sales&format=sqlite -> downloads sales.db
9341 GET /export?l=table:sales&format=json -> downloads sales.json
9342  
9343 =cut
9344  
9345 75 ▶sub export_data ($self) {
Subroutine export_data: called CC=8 SCAR=21.4
Pod documented
9346 75 my ($records, $columns, $left_label) = $self->_run_export_pipeline;
9347 75 ▶ return if $self->stash('_reduce_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_reduce_error") 7 68 75
9348 68 ▶ return $self->reply->not_found unless $records;
Branch: 1 branch
BranchTrueFalseTotal
unless $records 6 62 68
9349  
9350 # Surface schema-type-mismatch warnings in a response header so API
9351 # consumers (and the user via browser dev tools) can see them even
9352 # though exports render no HTML template.
9353 62 ▶ my $warnings = $self->stash('schema_warnings') // [];
Condition50%1/2
$self->stash("schema_warnings") // []
l!l
062
MC/DC0%0/1
$self->stash("schema_warnings") // []
$self->stash("schema_warnings")
Truth table50%1/2
A
A= $self->stash("schema_warnings")
Aresult
11
00
9354 62 ▶ if (@$warnings) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$warnings) 0 62 62
9355 0 my $hdr = join('; ', map { s/\s+/ /gr =~ s/^\s+|\s+$//gr } @$warnings);
9356 0 $self->res->headers->header('X-BI-Warnings' => $hdr);
9357 }
9358  
9359 62 ▶ my $format = $self->param('format') // 'csv';
Condition100%2/2
$self->param("format") // "csv"
l!l
2636
MC/DC100%1/1
$self->param("format") // "csv"
$self->param("format")
Truth table100%2/2
A
A= $self->param("format")
Aresult
11
00
9360 62 (my $safe_name = lc $left_label) =~ s/[^a-z0-9_]+/_/g;
9361  
9362 62 ▶ return $format eq 'sqlite' ? $self->_render_sqlite($records, $columns, $safe_name)
Branch: 2 branches
BranchTrueFalseTotal
$format eq 'sqlite' ? : 3 59 62
$format eq 'json' ? : 3 56 59
9363 : $format eq 'json' ? $self->_render_json($records, $columns, $safe_name)
9364 : $self->_render_csv($records, $columns, $safe_name);
9365 }
9366  
9367 =head2 export_write
9368  
9369 C<POST /export> -- Write the current logical view to a chosen filesystem path.
9370  
9371 =head3 API SPECIFICATION
9372  
9373 =head4 INPUT
9374  
9375 l= string (required) Left table spec.
9376 j= string (repeatable) Join steps.
9377 f= string (repeatable) Filter specs.
9378 dir= string Target directory (must exist; resolved via realpath). Inside
9379 config file_roots and export_dirs when they are set.
9380 filename= string Output filename including extension. Extension determines
9381 format: C<.csv> -> RFC 4180 CSV; C<.sql> -> SQLite;
9382 C<.json> -> JSON array of row objects.
9383  
9384 =head4 DOMAIN CONSTRAINTS: filename=
9385  
9386 The extension check uses C</\.csv\z/i> (CSV), C</\.sql\z/i> (SQLite), or
9387 C</\.json\z/i> (JSON): the C</i> flag makes matching case-insensitive, so
9388 C<.CSV>, C<.SQL>, and C<.JSON> are accepted alongside lowercase forms.
9389 Everything else returns 415.
9390  
9391 Path separator characters (C</> and C<\>) in C<filename> are stripped
9392 first via C<m{([^/\\]+)\z}> -- only the basename is kept, preventing
9393 directory traversal.
9394  
9395 =over 4
9396  
9397 =item Valid partitions
9398  
9399 C<report.csv>, C<report.sql>, C<report.json>, C<REPORT.CSV>, C<report.SQL>.
9400 A single-character stem (C<a.csv>) is also valid.
9401  
9402 =item Invalid partitions (415)
9403  
9404 C<report.txt>, C<report> (no extension), empty string.
9405  
9406 =back
9407  
9408 =head4 OUTPUT
9409  
9410 200 application/json { "saved": "/abs/path/to/file" }
9411 403 application/json { "error": "..." } -- a hidden target; dir outside
9412 file_roots or export_dirs; a name
9413 that is a link, folder or anything
9414 but a plain file; or a request
9415 another site's page made
9416 401 application/json { "error": "..." } -- password_hash set, not logged in
9417 404 application/json { "error": "..." } -- bad dir or table not found
9418 415 application/json { "error": "..." } -- unsupported extension
9419 500 application/json { "error": "..." } -- write failure
9420  
9421 =head3 MESSAGES
9422  
9423 error_dir_not_found -- realpath of dir failed or result is not a directory.
9424 error_ext_required -- filename extension is not .csv, .sql or .json.
9425 error_hidden_target -- the directory, after realpath, or the filename has a
9426 part starting with a dot (~/.config, .vscode/,
9427 .profile.json): those hold settings, and
9428 GET /api/dirs never offers them.
9429 error_outside_roots -- dir is outside config file_roots.
9430 error_outside_export_dirs
9431 -- dir is outside config export_dirs.
9432 error_export_not_file -- the name is already a link, a folder or another
9433 non-file: a link could lead the export anywhere.
9434 error_cross_site, error_host_refused
9435 -- from request_refusal, before this action runs.
9436 error_write_failed -- DBI or filesystem write threw.
9437  
9438 A refusal names the folder as C<dir> spelled it, though the checks are made
9439 on its realpath. The C<saved> path of a success is the realpath: where the
9440 file is.
9441  
9442 The file is written to a temporary file (C<.bi-export-XXXXXXXX>) in C<dir> and
9443 renamed over the name, so a reader never sees half a file and a link made
9444 after the check is replaced, not followed. It gets the replaced file's mode,
9445 or C<0666 & ~umask> for a new one; on failure the temporary file is removed.
9446  
9447 =head3 FORMAL SPECIFICATION
9448  
9449 export_write == lambda self .
9450 let dir = realpath(param('dir')) in
9451 let file = dir / strip_path(param('filename')) in
9452 pre is_dir(dir) /\ ext(file) in {csv, sql}
9453 let (recs, cols, _) = _run_export_pipeline() in
9454 pre recs /= undef
9455 post spurt(file, serialise(recs, cols))
9456 /\ render_json({ saved: file.to_string })
9457  
9458 =head3 EXAMPLE
9459  
9460 POST /export l=table:sales dir=/home/user/exports filename=report.csv
9461 -> { "saved": "/home/user/exports/report.csv" }
9462  
9463 =cut
9464  
9465 26 ▶sub export_write ($self) {
Subroutine export_write: called CC=32 SCAR=37.5
Pod documented
9466 26 ▶ my $dir = $self->param('dir') // '';
Condition50%1/2
$self->param("dir") // ""
l!l
260
MC/DC0%0/1
$self->param("dir") // ""
$self->param("dir")
Truth table50%1/2
A
A= $self->param("dir")
Aresult
11
00
9467 26 ▶ my $filename = $self->param('filename') // '';
Condition50%1/2
$self->param("filename") // ""
l!l
260
MC/DC0%0/1
$self->param("filename") // ""
$self->param("filename")
Truth table50%1/2
A
A= $self->param("filename")
Aresult
11
00
9468  
9469 26 ▶ 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)) 0 26 26
Condition33%1/3
_outside_roots($self, $dir) // _outside_export_dirs($self, $dir)
l!l&&r!l&&!r
0026
MC/DC0%0/2
_outside_roots($self, $dir) // _outside_export_dirs($self, $dir)
_outside_roots($self, $dir) _outside_export_dirs($self, $dir)
Truth table33%1/3
A // B
A= _outside_roots($self, $dir)B= _outside_export_dirs($self, $dir)
ABresult
1X1
011
000
9470 0 return $self->render(json => { error => $refusal }, status => 403);
9471 }
9472 26 my $dest_dir = eval { Mojo::File->new($dir)->realpath };
9473 26 ▶ unless (defined $dest_dir && -d $dest_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $dest_dir and -d $dest_dir) 2 24 26
Condition100%3/3
defined $dest_dir and -d $dest_dir
!ll&&!rl&&r
1124
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
9474 2 return $self->render(
9475 json => { error => $self->_i18n('error_dir_not_found', $dir) },
9476 status => 404,
9477 );
9478 }
9479  
9480 # A NUL is not part of any file name, only a way of hiding the real extension.
9481 24 ▶ $filename = '' if $filename =~ /\0/;
Branch: 1 branch
BranchTrueFalseTotal
if $filename =~ /\0/u 2 22 24
9482  
9483 # Strip any path separators the browser might include.
9484 24 ($filename) = $filename =~ m{([^/\\]+)\z};
9485  
9486 # A dot-folder or dot-file holds some program's settings (~/.config, a
9487 # .vscode/settings.json), which a .json export could replace. The folder
9488 # list the panel offers (GET /api/dirs) leaves them out too.
9489 # The checks read the resolved folder; a refusal names the one the reader
9490 # asked for, as every other message does (macOS's tempdir is under /var,
9491 # a link to /private/var, so the two differ there).
9492 24 my $asked = Mojo::File->new($dir);
9493 24 ▶ my @names = (File::Spec->splitdir($dest_dir->to_string), $filename // '');
Condition100%2/2
$filename // ""
l!l
213
MC/DC100%1/1
$filename // ""
$filename
Truth table100%2/2
A
A= $filename
Aresult
11
00
9494 24 ▶ if (grep { /\A\./ && $_ ne '.' && $_ ne '..' } @names) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {/\A\./u and $_ ne "." and $_ ne "..";} @names) 0 24 24
Condition83%5/6
/\A\./u && $_ ne '.' && $_ ne '..'
!ll&&!rl&&r
9510
/\A\./u and $_ ne "."
!ll&&!rl&&r
9411
MC/DC0%0/3
/\A\./u && $_ ne '.' && $_ ne '..'
/\A\./u $_ ne "." $_ ne '..'
Truth table75%3/4
A and B && C
A= /\A\./uB= $_ ne "."C= $_ ne '..'
ABCresult
0XX0
10X0
1100
1111
9495 0 ▶ return $self->render(
Condition0%0/2
$filename // ""
l!l
00
MC/DC0%0/1
$filename // ""
$filename
Truth table0%0/2
A
A= $filename
Aresult
11
00
9496 json => { error => $self->_i18n('error_hidden_target', $asked->child($filename // '')->to_string) },
9497 status => 403,
9498 );
9499 }
9500 24 my $format;
9501 24 ▶ if ($filename && $filename =~ /\.csv\z/i) { $format = 'csv'; }
Branch: 3 branches
BranchTrueFalseTotal
if ($filename and $filename =~ /\.csv\z/iu) { } 16 8 24
elsif ($filename and $filename =~ /\.sql\z/iu) { } 1 7 8
elsif ($filename and $filename =~ /\.json\z/iu) { } 0 7 7
Condition100%3/3
$filename and $filename =~ /\.csv\z/iu
!ll&&!rl&&r
3516
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
9502 1 ▶ elsif ($filename && $filename =~ /\.sql\z/i) { $format = 'sqlite'; }
Condition100%3/3
$filename and $filename =~ /\.sql\z/iu
!ll&&!rl&&r
341
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
9503 0 ▶ elsif ($filename && $filename =~ /\.json\z/i) { $format = 'json'; }
Condition66%2/3
$filename and $filename =~ /\.json\z/iu
!ll&&!rl&&r
340
MC/DC0%0/2
$filename and $filename =~ /\.json\z/iu
$filename $filename =~ /\.json\z/iu
Truth table66%2/3
A and B
A= $filenameB= $filename =~ /\.json\z/iu
ABresult
0X0
100
111
9504 else {
9505 7 return $self->render(
9506 json => { error => $self->_i18n('error_ext_required') },
9507 status => 415,
9508 );
9509 }
9510  
9511 17 my ($records, $columns, $left_label) = $self->_run_export_pipeline;
9512 17 ▶ return if $self->stash('_reduce_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_reduce_error") 3 14 17
9513 14 ▶ return $self->render(json => { error => 'Table not found' }, status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless $records 2 12 14
9514 unless $records;
9515  
9516 12 my $dest = $dest_dir->child($filename);
9517 # A link (or a folder, a pipe) already at the name is not replaced: written
9518 # through, a link inside the folders would put the export wherever it
9519 # points, outside file_roots or export_dirs, or into a dot-file.
9520 12 ▶ if (-l $dest || (-e $dest && !-f $dest)) {
Branch: 1 branch
BranchTrueFalseTotal
if (-l $dest or -e $dest and not -f $dest) 0 12 12
Condition50%3/6
-l $dest or -e $dest and not -f $dest
l!l&&r!l&&!r
0012
-e $dest and not -f $dest
!ll&&!rl&&r
930
MC/DC0%0/3
-l $dest or -e $dest and not -f $dest
-l $dest -e $dest not -f $dest
Truth table50%2/4
A or B and not(C)
A= -l $destB= -e $destC= not -f $dest
ABCresult
1XX1
0111
00X0
0100
9521 0 return $self->render(json => { error => sprintf(_message_text('error_export_not_file'), $asked->child($filename)->to_string) }, status => 403);
9522 }
9523 12 my $tmp;
9524 12 my $ok = eval {
9525 12 ▶ my $bytes = $format eq 'csv' ? _serialize_csv($records, $columns)
Branch: 2 branches
BranchTrueFalseTotal
$format eq 'csv' ? : 11 1 12
$format eq 'json' ? : 0 1 1
9526 : $format eq 'json' ? encode_json($records)
9527 : $self->_write_sqlite_db($records, $columns);
9528 # Written beside it and renamed over it: a rename replaces whatever
9529 # is at the name, a link made since the check included, and never
9530 # follows it, and a reader never sees half a file.
9531 12 (my $fh, $tmp) = tempfile('.bi-export-XXXXXXXX', DIR => $dest_dir->to_string, UNLINK => 0);
9532 12 binmode $fh;
9533 12 ▶ print {$fh} $bytes or croak "$tmp: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $bytes or croak("${tmp}: $!") 12 0 12
9534 12 ▶ close $fh or croak "$tmp: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${tmp}: $!") 12 0 12
9535 # tempfile makes it 0600: give it the mode of the file it replaces, as
9536 # writing over that one did, or the mode a new file gets.
9537 12 my @old = stat $dest->to_string;
9538 12 ▶ chmod(@old ? $old[2] & oct('7777') : 0666 & ~umask(), $tmp);
Branch: 1 branch
BranchTrueFalseTotal
@old ? : 3 9 12
9539 12 ▶ rename $tmp, $dest->to_string or croak "$dest: $!";
Branch: 1 branch
BranchTrueFalseTotal
rename $tmp, $dest->to_string or croak("${dest}: $!") 12 0 12
9540 12 undef $tmp;
9541 12 1;
9542 };
9543 12 my $err = $@;
9544 12 ▶ unlink $tmp if defined $tmp;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tmp 0 12 12
9545 12 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 12 12
9546 json => { error => $self->_i18n('error_write_failed', _tidy_error($err)) },
9547 status => 500,
9548 ) unless $ok;
9549  
9550 12 $self->render(json => { saved => $dest->to_string });
9551 }
9552  
9553 =head2 dirs_api
9554  
9555 C<GET /api/dirs> -- Return a JSON directory listing for the export panel.
9556  
9557 =head3 API SPECIFICATION
9558  
9559 =head4 INPUT
9560  
9561 ?path= string Directory to list. Default: the first config export_dirs
9562 entry, else $HOME if it is inside file_roots, else the first
9563 root. Returns 404 when not a directory. Hidden entries
9564 (names starting with ".") are excluded.
9565  
9566 =head4 OUTPUT
9567  
9568 200 application/json
9569 {
9570 "path": "/abs/path",
9571 "parent": "/abs/parent" or null (at the filesystem root, or when the
9572 parent is outside file_roots or export_dirs),
9573 "dirs": [ { "name": "alpha", "path": "/abs/path/alpha" }, ... ]
9574 }
9575  
9576 403 application/json { "error": "..." } -- path outside file_roots or
9577 export_dirs, whether or not it
9578 exists
9579 404 application/json { "error": "Not a directory" }
9580  
9581 =head3 MESSAGES
9582  
9583 error_outside_roots, error_outside_export_dirs -- the 403 above.
9584  
9585 =head3 FORMAL SPECIFICATION
9586  
9587 dirs_api == lambda self .
9588 let dir = realpath(param('path') // first(export_dirs) // first_root) in
9589 pre inside(dir, file_roots) /\ inside(dir, export_dirs) /\ is_dir(dir)
9590 post render_json({ path: dir, parent: parent(dir), dirs: subdirs(dir) })
9591  
9592 =head3 EXAMPLE
9593  
9594 GET /api/dirs?path=/home/user -> {"path":"/home/user","parent":"/home","dirs":[...]}
9595  
9596 =cut
9597  
9598 4 ▶sub dirs_api ($self) {
Subroutine dirs_api: called CC=10 SCAR=26.7
Pod documented
9599 4 ▶ 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
310
$self->param("path") // (_export_dirs($self))[0]
l!l&&r!l&&!r
301
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
9600 4 ▶ 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)) 0 4 4
Condition33%1/3
_outside_roots($self, $raw) // _outside_export_dirs($self, $raw)
l!l&&r!l&&!r
004
MC/DC0%0/2
_outside_roots($self, $raw) // _outside_export_dirs($self, $raw)
_outside_roots($self, $raw) _outside_export_dirs($self, $raw)
Truth table33%1/3
A // B
A= _outside_roots($self, $raw)B= _outside_export_dirs($self, $raw)
ABresult
1X1
011
000
9601 0 return $self->render(json => { error => $refusal }, status => 403);
9602 }
9603 4 my $dir = eval { Mojo::File->new($raw)->realpath };
9604 4 ▶ return $self->render(json => { error => 'Not a directory' }, status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir and -d $dir 1 3 4
Condition66%2/3
defined $dir and -d $dir
!ll&&!rl&&r
103
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
9605 unless defined $dir && -d $dir;
9606  
9607 3 my $listing = $self->_list_dir($dir, 0);
9608 3 my $parent = $dir->dirname;
9609 3 ▶ my $up = $parent->to_string ne $dir->to_string && !_outside_roots($self, $parent->to_string)
Condition33%2/6
$parent->to_string ne $dir->to_string && !_outside_roots($self, $parent->to_string) && !_outside_export_dirs($self, $parent->to_string)
!ll&&!rl&&r
003
$parent->to_string ne $dir->to_string and not _outside_roots($self, $parent->to_string)
!ll&&!rl&&r
003
MC/DC0%0/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 table25%1/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
9610 && !_outside_export_dirs($self, $parent->to_string);
9611  
9612 $self->render(json => {
9613 path => $dir->to_string,
9614 parent => ($up ? $parent->to_string : undef),
9615 dirs => $listing->{dirs},
9616 3 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
$up ? : 3 0 3
9617 }
9618  
9619 =head2 stat_api
9620  
9621 C<GET /api/stat> -- Return filesystem metadata for a file path.
9622  
9623 Used by the home page tooltip to show modification time and size for recently
9624 opened files without a page reload.
9625  
9626 =head3 API SPECIFICATION
9627  
9628 =head4 INPUT
9629  
9630 ?path= string Absolute path to query. Returns HTTP 400 when absent.
9631  
9632 =head4 OUTPUT
9633  
9634 200 application/json (file exists)
9635 { "exists": true, "path": "/resolved/path", "mtime": 1700000000, "size": 4096 }
9636  
9637 200 application/json (file does not exist)
9638 { "exists": false, "path": "/original/path" }
9639  
9640 400 application/json { "error": "\"path\" parameter is required" }
9641  
9642 C<mtime> is Unix epoch seconds. C<size> is bytes. A missing/unresolvable
9643 path returns HTTP 200 with C<exists: false> (not 404) so the UI can
9644 distinguish "file was deleted" from a request error.
9645  
9646 =head3 MESSAGES
9647  
9648 error_path_required -- the "path" query parameter was not supplied.
9649  
9650 =head3 FORMAL SPECIFICATION
9651  
9652 stat_api == lambda self .
9653 let path = param('path') in
9654 pre path /= undef
9655 let file = realpath(path) in
9656 post if is_file(file) then
9657 render_json({ exists: true, mtime: mtime(file), size: size(file) })
9658 else render_json({ exists: false })
9659  
9660 =head3 EXAMPLE
9661  
9662 GET /api/stat?path=/data/sales.csv
9663 -> { "exists": true, "path": "/data/sales.csv", "mtime": 1700000000, "size": 1234 }
9664  
9665 GET /api/stat?path=/deleted.csv
9666 -> { "exists": false, "path": "/deleted.csv" }
9667  
9668 =cut
9669  
9670 12 ▶sub stat_api ($self) {
Subroutine stat_api: called CC=9 SCAR=22.0
Pod documented
9671 12 my $path = $self->param('path');
9672 12 ▶ unless (defined $path && length $path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $path and length $path) 3 9 12
Condition100%3/3
defined $path and length $path
!ll&&!rl&&r
219
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
9673 3 return $self->render(
9674 json => { error => $self->_i18n('error_path_required') },
9675 status => 400,
9676 );
9677 }
9678  
9679 9 my $file = eval { Mojo::File->new($path)->realpath };
9680 # Restrict to files with a supported data extension so stat_api cannot be
9681 # used as a filesystem oracle to probe /etc/shadow, /root/.ssh/, etc.; and,
9682 # with file_roots, to files inside them, said the same way.
9683 9 ▶ 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) 4 5 9
Condition88%8/9
defined $file and -f $file and $file->basename =~ /$EXT_RE/u and not _outside_roots($self, $path)
!ll&&!rl&&r
405
defined $file and -f $file and $file->basename =~ /$EXT_RE/u
!ll&&!rl&&r
315
defined $file and -f $file
!ll&&!rl&&r
126
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
9684 unless defined $file && -f $file && $file->basename =~ $EXT_RE && !_outside_roots($self, $path);
9685  
9686 5 my @s = stat $file->to_string;
9687  
9688 # For SQLite files, count user tables so the home-page tooltip can show
9689 # "SQLite database - N tables". Silently omit the count if the file is
9690 # not actually a SQLite file (e.g. a Berkeley DB .db file).
9691 5 my $table_count;
9692 5 ▶ if ($file->basename =~ /\.(?:sql|sqlite|sqlite3|db)\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file->basename =~ /\.(?:sql|sqlite|sqlite3|db)\z/iu) 1 4 5
9693 1 eval {
9694 1 require Database::Join::Catalog;
9695 1 $table_count = scalar @{ Database::Join::Catalog->tables(file => $file->to_string) };
9696 };
9697 }
9698  
9699 5 ▶ $self->render(json => {
Branch: 1 branch
BranchTrueFalseTotal
defined $table_count ? : 1 4 5
9700 exists => \1,
9701 path => $file->to_string,
9702 mtime => $s[9],
9703 size => $s[7],
9704 (defined $table_count ? (table_count => $table_count) : ()),
9705 });
9706 }
9707  
9708 =head2 upload_file
9709  
9710 C<POST /upload> -- Accept a drag-and-dropped data file and return a redirect URL.
9711  
9712 The file is saved under its original filename in a managed subdirectory of
9713 C<< <uploads_dir>/ >>. The subdirectory name is randomised so that
9714 concurrent uploads of files with the same name do not collide.
9715  
9716 =head3 API SPECIFICATION
9717  
9718 =head4 INPUT
9719  
9720 Multipart form upload, field name: C<file>.
9721  
9722 file upload Supported extensions: csv, db, sql, xml, tsv, psv.
9723  
9724 =head4 OUTPUT
9725  
9726 200 application/json { "url": "/open?path=/abs/path/file.csv", "path": "/abs/path/file.csv" }
9727 400 application/json { "error": "No file received" }
9728 413 application/json { "error": "File too large to upload (limit: 50 MB)" }
9729 415 application/json { "error": "Unsupported file type. Accepted: ..." }
9730 500 application/json { "error": "Could not save uploaded file" }
9731  
9732 =head3 MESSAGES
9733  
9734 error_upload_none -- no file was received in the multipart upload.
9735 error_upload_ext -- the file's extension is not in the supported list.
9736 error_upload_too_large -- the upload body exceeded MAX_UPLOAD_MIB (50 MiB).
9737 error_upload_save -- move_to failed or the destination file was not
9738 created (I/O error, full disk, permission error).
9739  
9740 =head3 IMPLEMENTATION NOTES
9741  
9742 The C<move_to> call is wrapped with the C<eval { ...; 1 }> idiom (not
9743 C<eval {}> + C<if ($@)>). Mojolicious dispatch and DESTROY-phase evals can
9744 leave C<$@> set before the action runs; checking C<if ($@)> after a new eval
9745 may fire falsely on that stale value. C<eval { move_to(); 1 }> returns 1 on
9746 success and C<undef> on exception, so the result is independent of any prior
9747 C<$@> value.
9748  
9749 =head3 FORMAL SPECIFICATION
9750  
9751 upload_file == lambda self .
9752 let upload = req.upload('file') in
9753 pre upload /= undef /\ basename(upload.filename) =~ EXT_RE
9754 /\ NOT req->is_limit_exceeded
9755 /\ upload.size <= MAX_UPLOAD_BYTES
9756 let dest = uploads_dir/<random>/<filename> in
9757 let ok = eval { upload.move_to(dest); 1 } in
9758 pre ok /\ -f dest
9759 post render_json({ url: '/open?path=' ++ url_escape(dest), path: dest })
9760  
9761 =head3 EXAMPLE
9762  
9763 POST /upload (multipart: file=@sales.csv)
9764 -> { "url": "/open?path=%2F...%2Fsales.csv", "path": "/.../.uploads/abc123/sales.csv" }
9765  
9766 =cut
9767  
9768 15 ▶sub upload_file ($self) {
Subroutine upload_file: called CC=11 SCAR=27.0
Pod documented
9769 15 my $upload = $self->req->upload('file');
9770 15 ▶ unless ($upload && $upload->filename) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($upload and $upload->filename) 1 14 15
Condition66%2/3
$upload and $upload->filename
!ll&&!rl&&r
1014
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
9771 1 return $self->render(
9772 json => { error => $self->_i18n('error_upload_none') },
9773 status => 400,
9774 );
9775 }
9776  
9777 # Enforce upload size limit. max_request_size in startup() sets the
9778 # transport-layer cap, but Mojolicious still calls the controller when the
9779 # limit fires (with req->is_limit_exceeded true and partial content in the
9780 # upload asset). Check is_limit_exceeded first; fall through to an asset
9781 # size check as a belt-and-braces guard for any bytes that slipped through.
9782 14 ▶ 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) 0 14 14
Condition33%1/3
$self->req->is_limit_exceeded or $upload->size > $MAX_UPLOAD_BYTES
l!l&&r!l&&!r
0014
MC/DC0%0/2
$self->req->is_limit_exceeded or $upload->size > $MAX_UPLOAD_BYTES
$self->req->is_limit_exceeded $upload->size > $MAX_UPLOAD_BYTES
Truth table33%1/3
A or B
A= $self->req->is_limit_exceededB= $upload->size > $MAX_UPLOAD_BYTES
ABresult
1X1
011
000
9783 0 return $self->render(
9784 json => { error => $self->_i18n('error_upload_too_large', $MAX_UPLOAD_MIB) },
9785 status => 413,
9786 );
9787 }
9788  
9789 # /s so .* matches \n; a percent-decoded newline inside a browser filename
9790 # must not silently truncate the directory-strip, leaving "dir\ncomponent" in.
9791 14 (my $filename = $upload->filename) =~ s{.*[/\\]}{}s;
9792 14 ▶ unless ($filename && $filename =~ $EXT_RE) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($filename and $filename =~ /$EXT_RE/u) 1 13 14
Condition66%2/3
$filename and $filename =~ /$EXT_RE/u
!ll&&!rl&&r
0113
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
9793 1 return $self->render(
9794 json => { error => $self->_i18n('error_upload_ext') },
9795 status => 415,
9796 );
9797 }
9798  
9799 # Store uploads in <uploads_dir>/<random_subdir>/<original_filename>. The
9800 # staging directory comes from the app (config uploads_dir, default
9801 # <app_home>/.uploads) so a deployment can point it at a writable disc and
9802 # a test can keep its uploads out of the directory another process clears.
9803 # Using the original filename is essential: Database::Abstraction derives
9804 # the table name from the file stem, so "sales.csv" must stay "sales.csv".
9805 # The random subdirectory prevents collisions from concurrent same-name uploads.
9806 13 my $uploads_base = $self->app->_uploads_dir;
9807 13 my $sub_dir = eval {
9808 13 ▶ $uploads_base->make_path unless -d $uploads_base;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $uploads_base 0 13 13
9809 13 tempdir(DIR => $uploads_base->to_string, CLEANUP => 0);
9810 };
9811 13 ▶ unless (defined $sub_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $sub_dir) 0 13 13
9812 0 $self->app->log->error("Cannot stage an upload in $uploads_base: " . _tidy_error($@));
9813 0 return $self->render(
9814 json => { error => $self->_i18n('error_upload_save') },
9815 status => 500,
9816 );
9817 }
9818 13 my $dest = Mojo::File->new($sub_dir)->child($filename)->to_string;
9819  
9820 # move_to returns the destination Mojo::File on success; croaks on I/O
9821 # failure. Wrap in eval so a disk error becomes a 500 JSON response
9822 # rather than a bare Mojolicious exception page.
9823 # Use the "eval { ...; 1 }" idiom: $ok is undef only when THIS eval
9824 # threw, avoiding false positives from a stale $@ left by Mojo's
9825 # internal dispatch code that runs before the controller action.
9826 13 my $ok = eval { $upload->move_to($dest); 1 };
9827 13 ▶ if (!$ok || !-f $dest) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok and -f $dest) 0 13 13
Condition33%1/3
$ok and -f $dest
!ll&&!rl&&r
0013
MC/DC0%0/2
$ok and -f $dest
$ok -f $dest
Truth table33%1/3
A and B
A= $okB= -f $dest
ABresult
0X0
100
111
9828 0 remove_tree($sub_dir);
9829 0 return $self->render(
9830 json => { error => $self->_i18n('error_upload_save') },
9831 status => 500,
9832 );
9833 }
9834  
9835 13 $self->render(json => {
9836 url => '/open?path=' . url_escape($dest),
9837 path => $dest,
9838 });
9839 }
9840  
9841 5 ▶sub clear_uploads ($self) {
Subroutine clear_uploads: called CC=3 SCAR=12.7
Pod documented
9842 5 my $uploads_dir = $self->app->_uploads_dir;
9843  
9844 5 ▶ return $self->render(json => { freed => 0, count => 0 })
Branch: 1 branch
BranchTrueFalseTotal
unless -d $uploads_dir 0 5 5
9845 unless -d $uploads_dir;
9846  
9847 5 my ($freed, $count) = (0, 0);
9848  
9849 # Each upload lands in <uploads_dir>/<random_subdir>/<filename>.
9850 # Iterate the subdirs, tally file sizes, then remove each subdir tree.
9851 5 my $ok = eval {
9852 6 ▶ $uploads_dir->list({ dir => 1 })->each(sub {
Subroutine __ANON__: called CC=4 SCAR=17.5
9853 6 my ($entry) = @_;
9854 6 ▶ if (-d $entry) {
Branch: 2 branches
BranchTrueFalseTotal
if (-d $entry) { } 6 0 6
elsif (-f $entry) { } 0 0 0
9855 6 ▶ $entry->list->each(sub {
Subroutine __ANON__: called CC=3 SCAR=11.4
9856 6 my ($file) = @_;
9857 6 ▶ return unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 0 6 6
9858 6 ▶ $freed += (-s $file) // 0;
Condition50%1/2
-s $file // 0
l!l
60
MC/DC0%0/1
-s $file // 0
-s $file
Truth table50%1/2
A
A= -s $file
Aresult
11
00
9859 6 $count++;
9860 6 });
9861 6 $entry->remove_tree;
9862 } elsif (-f $entry) {
9863 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
9864 0 $count++;
9865 0 unlink $entry->to_string;
9866 }
9867 5 });
9868 5 1;
9869 };
9870 5 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 5 5
9871 0 $self->app->log->error("Cannot clear $uploads_dir: " . _tidy_error($@));
9872 0 return $self->render(json => { error => $self->_i18n('error_uploads_clear') }, status => 500);
9873 }
9874  
9875 5 $self->render(json => { freed => $freed, count => $count });
9876 }
9877  
9878 # graph_view
9879 #
9880 # Purpose: Render a D3.js line chart from the current data pipeline.
9881 # Entry: Query params identical to /join (l=, j=, c=, f=, d=) plus:
9882 # x=<column> -- X-axis column name
9883 # y=<column> -- Y-axis column name (values must be numeric)
9884 # back=<url> -- URL for the "Back to table" link (set by JS)
9885 # Exit: Emits a TT-rendered HTML page with a brush-to-zoom HTML::D3 snippet.
9886 # Each data point carries an "extra" hash of every column not used
9887 # as the X or Y axis; HTML::D3 displays these in the hover tooltip.
9888 # A "Reset zoom" button appears after the user brushes to zoom in.
9889 # Returns HTTP 400 for missing/invalid column names, 404 if the
9890 # data source cannot be opened, 200 with an error message when
9891 # no plottable rows exist.
9892 100 ▶sub graph_view ($self) {
Subroutine graph_view: called CC=86 SCAR=72.7
Pod documented
9893 100 ▶ my $x_col = $self->param('x') // '';
Condition100%2/2
$self->param("x") // ""
l!l
973
MC/DC100%1/1
$self->param("x") // ""
$self->param("x")
Truth table100%2/2
A
A= $self->param("x")
Aresult
11
00
9894 100 ▶ my $y_col = $self->param('y') // '';
Condition100%2/2
$self->param("y") // ""
l!l
973
MC/DC100%1/1
$self->param("y") // ""
$self->param("y")
Truth table100%2/2
A
A= $self->param("y")
Aresult
11
00
9895 100 ▶ my $series_col = $self->param('series') // '';
Condition50%1/2
$self->param("series") // ""
l!l
0100
MC/DC0%0/1
$self->param("series") // ""
$self->param("series")
Truth table50%1/2
A
A= $self->param("series")
Aresult
11
00
9896 100 ▶ my $agg_fn = lc($self->param('agg') // '');
Condition50%1/2
$self->param("agg") // ""
l!l
0100
MC/DC0%0/1
$self->param("agg") // ""
$self->param("agg")
Truth table50%1/2
A
A= $self->param("agg")
Aresult
11
00
9897 100 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
0100
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
9898 100 my $back2 = _safe_back_url($self->param('back2'));
9899 100 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
0100
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
9900  
9901 100 ▶ return $self->render(text => 'Missing x or y column parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col and length $y_col 5 95 100
Condition66%2/3
length $x_col and length $y_col
!ll&&!rl&&r
5095
MC/DC50%1/2
length $x_col and length $y_col
length $x_col length $y_col
Truth table66%2/3
A and B
A= length $x_colB= length $y_col
ABresult
0X0
100
111
9902 unless length($x_col) && length($y_col);
9903  
9904 # ?agg= is the measure vocabulary the pivot and the stats page already use,
9905 # with no new names: a misspelt one is refused here rather than drawn as
9906 # nothing. Absent, this route behaves exactly as it always has.
9907 95 ▶ if (length $agg_fn && !_measure_fn_ok($agg_fn)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $agg_fn and not _measure_fn_ok($agg_fn)) 0 95 95
Condition33%1/3
length $agg_fn and not _measure_fn_ok($agg_fn)
!ll&&!rl&&r
9500
MC/DC0%0/2
length $agg_fn and not _measure_fn_ok($agg_fn)
length $agg_fn not _measure_fn_ok($agg_fn)
Truth table33%1/3
A and not(B)
A= length $agg_fnB= not _measure_fn_ok($agg_fn)
ABresult
0X0
100
111
9908 0 return $self->render(
9909 text => $self->_i18n('error_agg_fn', $agg_fn, join(' ', @MEASURE_FNS)),
9910 status => 400,
9911 );
9912 }
9913  
9914 95 my ($src, $records, $columns) = $self->_run_pipeline_source;
9915 95 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 3 92 95
9916 unless defined $records;
9917  
9918 92 my $span = $self->_span_calc_spec($columns, 'x');
9919 92 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 4 88 92
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
8804
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
9920  
9921 88 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
9922 88 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 88 88
9923 88 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 86 88
9924  
9925 # Pre-filter before building pairs, same as _run_export_pipeline.
9926 86 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 2 84 86
9927  
9928 84 my %col_set = map { $_ => 1 } @{$columns};
9929 return $self->render(text => "Column not found: $x_col", status => 400)
9930 84 ▶ unless $col_set{$x_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$x_col} 2 82 84
9931 return $self->render(text => "Column not found: $y_col", status => 400)
9932 82 ▶ unless $col_set{$y_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$y_col} 3 79 82
9933 79 ▶ if (length $series_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col) 0 79 79
9934 return $self->render(text => "Column not found: $series_col", status => 400)
9935 0 ▶ unless $col_set{$series_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$series_col} 0 0 0
9936 }
9937  
9938 # The x axis is the dimension span= buckets.
9939 79 ▶ $x_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 79 79
9940  
9941 # --- Aggregated path: ?agg= plots one point per group of the x axis rather
9942 # than one per row, which is what turns a bucketed x into a timechart. ---
9943 79 ▶ if (length $agg_fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $agg_fn) 0 79 79
9944 0 my $m = _visual_measure($agg_fn, $y_col);
9945 0 ▶ return $self->render(text => $m->{error}, status => 400) if $m->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $m->{"error"} 0 0 0
9946  
9947 my $agg_rows = $self->_grouped_totals(
9948 { source => $src, records => $records },
9949 {
9950 by => [ length($series_col) ? ($x_col, $series_col) : ($x_col) ],
9951 fn => $m->{fn},
9952 val => $m->{val},
9953 0 ▶ as => 'value',
Branch: 1 branch
BranchTrueFalseTotal
length $series_col ? : 0 0 0
9954 },
9955 );
9956  
9957 0 my (%value_of, %series_seen, @series_order, %bucket_seen, @bucket_order);
9958 0 for my $row (@$agg_rows) {
9959 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
9960 0 ▶ next unless length $bucket;
Branch: 1 branch
BranchTrueFalseTotal
unless length $bucket 0 0 0
9961 0 ▶ push @bucket_order, $bucket unless $bucket_seen{$bucket}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $bucket_seen{$bucket}++ 0 0 0
9962 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
9963 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
9964 0 ▶ push @series_order, $name unless $series_seen{$name}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $series_seen{$name}++ 0 0 0
9965 0 $value_of{$bucket}{$name} = $row->{value};
9966 }
9967  
9968 # Buckets in label order: the ISO labels a time bucket produces sort
9969 # chronologically as strings, which is why they are ISO.
9970 0 my @buckets = sort @bucket_order;
9971 0 my @series = sort @series_order;
9972 0 ▶ my $title = "$m->{label} by $x_col" . (length($series_col) ? " and $series_col" : '');
Branch: 1 branch
BranchTrueFalseTotal
length $series_col ? : 0 0 0
9973  
9974 0 require HTML::D3;
9975 0 my ($chart_html, $point_count, @series_data);
9976 0 ▶ if (length $series_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col) { } 0 0 0
9977 @series_data = map {
9978 0 my $name = $_;
9979 my @points = map {
9980 0 defined $value_of{$_}{$name}
9981 0 ▶ ? { label => $_, value => $value_of{$_}{$name} } : ()
Branch: 1 branch
BranchTrueFalseTotal
defined $value_of{$_}{$name} ? : 0 0 0
9982 } @buckets;
9983 0 ▶ @points ? { name => $name, data => \@points } : ();
Branch: 1 branch
BranchTrueFalseTotal
@points ? : 0 0 0
9984 } @series;
9985 0 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @series_data 0 0 0
9986 text => 'No plottable data: no rows have valid numeric values in the Y column.',
9987 status => 200,
9988 ) unless @series_data;
9989 0 $point_count = scalar @series_data;
9990 $chart_html = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
9991 0 ->render_multi_series_line_chart_snippet(\@series_data, { animated => 1 })->{html};
9992 } else {
9993 my @pairs = map {
9994 0 ▶ defined $value_of{$_}{''} ? [ $_, $value_of{$_}{''} ] : ()
Branch: 1 branch
BranchTrueFalseTotal
defined $value_of{$_}{''} ? : 0 0 0
9995 } @buckets;
9996 0 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @pairs 0 0 0
9997 text => 'No plottable data: no rows have valid numeric values in the Y column.',
9998 status => 200,
9999 ) unless @pairs;
10000 0 $point_count = scalar @pairs;
10001 $chart_html = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
10002 0 ->render_zoomable_line_chart_snippet(\@pairs, { animated => 1 })->{html};
10003 }
10004 0 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 0 0
10005  
10006 my %chart_spec = (
10007 kind => 'graph',
10008 title => $title,
10009 encode => {
10010 x => $x_col, y => $y_col,
10011 (length($series_col) ? (series => $series_col) : ()),
10012 agg => $m->{fn},
10013 },
10014 0 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
length $series_col ? : 0 0 0
10015 0 my ($platform, $language) = $self->_resolve_template;
10016 0 my ($source_url, $source_accessed) = $self->_url_attribution;
10017 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
10018 handler => 'tt',
10019 template => "$platform/$language/graph",
10020 format => 'html',
10021 title => $title,
10022 chart_html => $chart_html,
10023 chart => \%chart_spec,
10024 chart_json => $self->_chart_json(\%chart_spec),
10025 back_url => ($back2 // $back),
10026 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10027 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10028 point_count => $point_count,
10029 source_url => $source_url,
10030 source_accessed => $source_accessed,
10031 language => $language,
10032 );
10033 }
10034  
10035 # --- Multi-series path: ?series=<col> groups records into one line per value ---
10036 79 ▶ if (length $series_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col) 0 79 79
10037 0 my %by_series;
10038 my @series_order;
10039 0 for my $row (@{$records}) {
10040 0 ▶ my $x = $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
10041 0 ▶ my $y = $row->{$y_col} // '';
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
10042 0 ▶ my $grp = $row->{$series_col} // '';
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
10043 0 ▶ next unless length($x) && length($y) && length($grp);
Branch: 1 branch
BranchTrueFalseTotal
unless length $x and length $y and length $grp 0 0 0
Condition0%0/6
length $x and length $y and length $grp
!ll&&!rl&&r
000
length $x and length $y
!ll&&!rl&&r
000
MC/DC0%0/3
length $x and length $y and length $grp
length $x length $y length $grp
Truth table0%0/4
A and B and C
A= length $xB= length $yC= length $grp
ABCresult
0XX0
10X0
1100
1111
10044 0 my $yn = _numeric_cell($y);
10045 0 ▶ next unless defined $yn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $yn 0 0 0
10046 0 ▶ unless (exists $by_series{$grp}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $by_series{$grp}) 0 0 0
10047 0 push @series_order, $grp;
10048 0 $by_series{$grp} = [];
10049 }
10050 0 push @{$by_series{$grp}}, { label => _decode_cell($x), value => $yn };
10051 }
10052  
10053 0 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @series_order 0 0 0
10054 text => 'No plottable data: no rows have valid numeric values in the Y column.',
10055 status => 200,
10056 ) unless @series_order;
10057  
10058 0 my @series_data = map { { name => $_, data => $by_series{$_} } } @series_order;
10059  
10060 0 my ($source_url, $source_accessed) = $self->_url_attribution;
10061  
10062 0 require HTML::D3;
10063 0 my $title = "$y_col vs $x_col by $series_col";
10064 0 my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
10065 ->render_multi_series_line_chart_snippet(\@series_data, { animated => 1 });
10066  
10067 0 my $chart_html = $snippet->{html};
10068 0 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 0 0
10069  
10070 0 my %chart_spec = (
10071 kind => 'graph',
10072 title => $title,
10073 encode => { x => $x_col, y => $y_col, series => $series_col },
10074 );
10075 0 my ($platform, $language) = $self->_resolve_template;
10076 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
10077 handler => 'tt',
10078 template => "$platform/$language/graph",
10079 format => 'html',
10080 title => $title,
10081 chart_html => $chart_html,
10082 chart => \%chart_spec,
10083 chart_json => $self->_chart_json(\%chart_spec),
10084 back_url => ($back2 // $back),
10085 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10086 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10087 point_count => scalar @series_order,
10088 source_url => $source_url,
10089 source_accessed => $source_accessed,
10090 language => $language,
10091 );
10092 }
10093  
10094 # --- Single-series path (original behaviour when ?series= is absent) ---
10095  
10096 # Extract [label, value] pairs; skip rows where Y is missing or non-numeric.
10097 79 my @pairs;
10098 79 for my $row (@{$records}) {
10099 464 ▶ my $x = $row->{$x_col} // '';
Condition50%1/2
$row->{$x_col} // ""
l!l
4640
MC/DC0%0/1
$row->{$x_col} // ""
$row->{$x_col}
Truth table50%1/2
A
A= $row->{$x_col}
Aresult
11
00
10100 464 ▶ my $y = $row->{$y_col} // '';
Condition50%1/2
$row->{$y_col} // ""
l!l
4640
MC/DC0%0/1
$row->{$y_col} // ""
$row->{$y_col}
Truth table50%1/2
A
A= $row->{$y_col}
Aresult
11
00
10101 464 ▶ next unless length($x) && length($y);
Branch: 1 branch
BranchTrueFalseTotal
unless length $x and length $y 0 464 464
Condition33%1/3
length $x and length $y
!ll&&!rl&&r
00464
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
10102 464 my $yn = _numeric_cell($y);
10103 464 ▶ next unless defined $yn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $yn 6 458 464
10104 458 ▶ 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
4584581784
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
10105 458 push @pairs, [_decode_cell($x), $yn, \%extra];
10106 }
10107  
10108 79 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @pairs 1 78 79
10109 text => 'No plottable data: no rows have valid numeric values in the Y column.',
10110 status => 200,
10111 ) unless @pairs;
10112  
10113 78 my @y_vals = map { $_->[1] } @pairs;
10114 78 my ($min_y, $max_y, $avg_y);
10115  
10116 # Try aggregate() push path for the global min/max/avg reference lines.
10117 # Falls back to List::Util on the already-extracted @y_vals when push is
10118 # not available (no source, filters active, or non-pushable column).
10119 78 my @f_specs = grep { /\S/ } @{ _filter_specs($self) };
10120 78 my $has_filter = !!@f_specs;
10121 78 ▶ 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)) 70 8 78
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
4470
not $ENV{"BI_FORCE_PERL_AGG"} and $src and not $has_filter and not _dedup_requested($self)
!ll&&!rl&&r
4074
not $ENV{"BI_FORCE_PERL_AGG"} and $src and not $has_filter
!ll&&!rl&&r
1374
not $ENV{"BI_FORCE_PERL_AGG"} and $src
!ll&&!rl&&r
0177
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
10122 && _measure_pushable($src, 'avg', $y_col, $records)) {
10123 70 my $ref = eval {
10124 70 $src->aggregate(
10125 by => [],
10126 measures => [
10127 _measure('min', $y_col, 'lo'),
10128 _measure('max', $y_col, 'hi'),
10129 _measure('avg', $y_col, 'mean'),
10130 ],
10131 )
10132 };
10133 70 ▶ if (!$@ && $ref && @$ref) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $@ and $ref and @$ref) 70 0 70
Condition33%2/6
not $@ and $ref and @$ref
!ll&&!rl&&r
0070
not $@ and $ref
!ll&&!rl&&r
0070
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
10134 70 $min_y = $ref->[0]{lo};
10135 70 $max_y = $ref->[0]{hi};
10136 70 $avg_y = $ref->[0]{mean};
10137 }
10138 }
10139 # Perl fallback: compute from the already-stripped @y_vals.
10140 78 ▶ unless (defined $min_y) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $min_y) 8 70 78
10141 8 require Statistics::Lite;
10142 8 $min_y = Statistics::Lite::min(@y_vals);
10143 8 $max_y = Statistics::Lite::max(@y_vals);
10144 8 $avg_y = Statistics::Lite::mean(@y_vals);
10145 }
10146  
10147 # The trend line: a least-squares fit of Y against the point's place on the
10148 # axis. The axis is a d3.scalePoint, which spaces the points evenly whatever
10149 # their labels say, so the place (0, 1, 2, ...) is what makes the fit a
10150 # straight line on this chart. The page refits the points in view after a
10151 # zoom, the same way; this is the whole chart's.
10152 78 my $trend = _trend_line(\@y_vals);
10153  
10154 78 my ($source_url, $source_accessed) = $self->_url_attribution;
10155  
10156 78 require HTML::D3;
10157 78 my $title = "$y_col vs $x_col";
10158 78 my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
10159 ->render_zoomable_line_chart_snippet(\@pairs, { animated => 1 });
10160  
10161 78 my $chart_html = $snippet->{html};
10162 78 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 78 78
10163  
10164 78 my %chart_spec = (
10165 kind => 'graph',
10166 title => $title,
10167 encode => { x => $x_col, y => $y_col },
10168 );
10169 78 my ($platform, $language) = $self->_resolve_template;
10170 $self->render(
10171 handler => 'tt',
10172 template => "$platform/$language/graph",
10173 format => 'html',
10174 title => $title,
10175 chart_html => $chart_html,
10176 chart => \%chart_spec,
10177 chart_json => $self->_chart_json(\%chart_spec),
10178 back_url => ($back2 // $back),
10179 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10180 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10181 point_count => scalar @pairs,
10182 ref_min_y => $min_y,
10183 ref_max_y => $max_y,
10184 ref_avg_y => sprintf('%.4g', $avg_y),
10185 ($trend ? (
10186 trend_slope => sprintf('%.4g', $trend->{slope}),
10187 trend_intercept => sprintf('%.6g', $trend->{intercept}),
10188 78 ▶ trend_r2 => sprintf('%.2f', $trend->{r_squared}),
Branch: 3 branches
BranchTrueFalseTotal
$back2 ? : 0 78 78
$back2 ? : 0 78 78
$trend ? : 78 0 78
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0780
$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
10189 ) : ()),
10190 source_url => $source_url,
10191 source_accessed => $source_accessed,
10192 language => $language,
10193 );
10194 }
10195  
10196 # _trend_line(\@y) -> { slope, intercept, r_squared } | undef
10197 #
10198 # The least-squares line through the values, each at its place 0, 1, 2, ...
10199 # (Statistics::LineFit). undef for fewer than two values, or when the fit
10200 # fails. A flat series has slope 0 and an R squared of 1 (LineFit's answer:
10201 # the line passes through every point).
10202 78 ▶sub _trend_line {
Subroutine _trend_line: called CC=7 SCAR=22.0
10203 78 my ($ys) = @_;
10204 78 ▶ return undef unless ref $ys eq 'ARRAY' && @$ys >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ys eq "ARRAY" and @$ys >= 2 0 78 78
Condition33%1/3
ref $ys eq "ARRAY" and @$ys >= 2
!ll&&!rl&&r
0078
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
10205 78 require Statistics::LineFit;
10206 78 my $fit = Statistics::LineFit->new;
10207 78 ▶ return undef unless $fit->setData([ 0 .. $#$ys ], $ys);
Branch: 1 branch
BranchTrueFalseTotal
unless $fit->setData([0 .. $ys->$#*], $ys) 0 78 78
10208 78 my ($intercept, $slope) = $fit->coefficients;
10209 78 ▶ return undef unless defined $slope && defined $intercept;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $slope and defined $intercept 0 78 78
Condition33%1/3
defined $slope and defined $intercept
!ll&&!rl&&r
0078
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
10210 78 my $r2 = $fit->rSquared;
10211 78 ▶ return { slope => $slope, intercept => $intercept, r_squared => $r2 // 0 };
Condition50%1/2
$r2 // 0
l!l
780
MC/DC0%0/1
$r2 // 0
$r2
Truth table50%1/2
A
A= $r2
Aresult
11
00
10212 }
10213  
10214 54 ▶sub pie_view ($self) {
Subroutine pie_view: called CC=44 SCAR=49.9
Pod documented
10215 54 ▶ my $cat_col = $self->param('cat') // '';
Condition100%2/2
$self->param("cat") // ""
l!l
522
MC/DC100%1/1
$self->param("cat") // ""
$self->param("cat")
Truth table100%2/2
A
A= $self->param("cat")
Aresult
11
00
10216 54 ▶ my $val_col = $self->param('val') // '';
Condition100%2/2
$self->param("val") // ""
l!l
1143
MC/DC100%1/1
$self->param("val") // ""
$self->param("val")
Truth table100%2/2
A
A= $self->param("val")
Aresult
11
00
10217 54 ▶ my $donut = $self->param('donut') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('donut') ? : 0 54 54
10218 54 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition100%2/2
_safe_back_url($self->param("back")) // "/"
l!l
153
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
10219 54 my $back2 = _safe_back_url($self->param('back2'));
10220 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
10221  
10222 54 ▶ return $self->render(text => 'Missing cat or val column parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col and length $val_col 45 9 54
Condition100%3/3
length $cat_col and length $val_col
!ll&&!rl&&r
3429
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
10223 unless length($cat_col) && length($val_col);
10224  
10225 9 my ($src, $records, $columns) = $self->_run_pipeline_source;
10226 9 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 0 9 9
10227 unless defined $records;
10228  
10229 9 my $span = $self->_span_calc_spec($columns, 'cat');
10230 return $self->render(text => $span->{error}, status => 400)
10231 9 ▶ if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 0 9 9
Condition33%1/3
$span and $span->{"error"}
!ll&&!rl&&r
900
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
10232  
10233 9 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
10234 9 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 9 9
10235 0 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 9 9
10236  
10237 9 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 9 9
10238  
10239 9 my %col_set = map { $_ => 1 } @{$columns};
10240 return $self->render(text => "Column not found: $cat_col", status => 400)
10241 9 ▶ unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 1 8 9
10242  
10243 # '__count__' is the sentinel value sent when the user picks "Count (rows)".
10244 8 my $count_mode = ($val_col eq '__count__');
10245 return $self->render(text => "Column not found: $val_col", status => 400)
10246 8 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 1 7 8
Condition100%3/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
161
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
10247  
10248 7 ▶ $cat_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 7 7
10249  
10250 # Detect the currency symbol from the first non-empty source value.
10251 # This is a display concern; derive from the pre-filtered source rows so the
10252 # $/$GBP/EUR prefix on the legend is unchanged regardless of the push path.
10253 7 my $currency_symbol = '';
10254 7 ▶ if (!$count_mode) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($count_mode) 6 1 7
10255 6 for my $row (@$records) {
10256 22 ▶ my $v = $row->{$val_col} // '';
Condition50%1/2
$row->{$val_col} // ""
l!l
220
MC/DC0%0/1
$row->{$val_col} // ""
$row->{$val_col}
Truth table50%1/2
A
A= $row->{$val_col}
Aresult
11
00
10257 22 ▶ next unless length($v);
Branch: 1 branch
BranchTrueFalseTotal
unless length $v 0 22 22
10258 22 ▶ if ($v =~ /\A\s*\(?\s*([^\d\s.,\-\(])/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v =~ /\A\s*\(?\s*([^\d\s.,\-\(])/u) 2 20 22
10259 2 $currency_symbol = $1;
10260 2 last;
10261 }
10262 }
10263 }
10264  
10265 # Aggregate via _grouped_totals (push path or Perl fold).
10266 7 ▶ my $agg_rows = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 1 6 7
$count_mode ? : 1 6 7
10267 { source => $src, records => $records },
10268 {
10269 by => [$cat_col],
10270 fn => $count_mode ? 'count' : 'sum',
10271 val => $count_mode ? undef : $val_col,
10272 as => 'value',
10273 },
10274 );
10275  
10276 # Top-N: keep the highest-N slices, aggregate the rest as "Other".
10277 7 ▶ my $topn_n = _whole_number($self->param('topn')) // 0;
Condition50%1/2
_whole_number($self->param("topn")) // 0
l!l
07
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
10278 7 ▶ if ($topn_n > 0 && @$agg_rows > $topn_n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($topn_n > 0 and @$agg_rows > $topn_n) 0 7 7
Condition33%1/3
$topn_n > 0 and @$agg_rows > $topn_n
!ll&&!rl&&r
700
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
10279 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
10280 0 my @top_agg = @sorted[0 .. $topn_n - 1];
10281 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
10282 my $other_rec = [
10283 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
10284 ];
10285 0 ▶ if (@$other_rec) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$other_rec) 0 0 0
10286 0 ▶ my $other = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 0 0 0
$count_mode ? : 0 0 0
10287 { source => undef, records => $other_rec },
10288 { by => [], fn => ($count_mode ? 'count' : 'sum'),
10289 val => ($count_mode ? undef : $val_col), as => 'value' },
10290 );
10291 push @top_agg, { $cat_col => 'Other', value => $other->[0]{value} }
10292 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
10293 }
10294 0 $agg_rows = \@top_agg;
10295 }
10296  
10297 7 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg_rows 0 7 7
10298 text => 'No plottable data: no rows have valid data in the selected columns.',
10299 status => 200,
10300 ) unless @$agg_rows;
10301  
10302 7 my @slices = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg_rows;
10303  
10304 7 my ($source_url, $source_accessed) = $self->_url_attribution;
10305  
10306 7 require HTML::D3;
10307 7 my $scheme = _categorical_scheme($self->param('scheme'));
10308 7 ▶ my $title = $count_mode ? "Count by $cat_col" : "$val_col by $cat_col";
Branch: 1 branch
BranchTrueFalseTotal
$count_mode ? : 1 6 7
10309 7 my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 600, height => 500)
10310 ->render_pie_chart_snippet(\@slices, {
10311 animated => 1,
10312 donut => $donut,
10313 sort_slices => 'value',
10314 max_slices => 12,
10315 legend => 1,
10316 color_scheme => $scheme,
10317 });
10318  
10319 7 my $chart_html = $snippet->{html};
10320 7 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 7 7
10321  
10322 7 my %chart_spec = (
10323 kind => 'pie',
10324 title => $title,
10325 encode => { cat => $cat_col, value => $val_col },
10326 options => { scheme => $scheme, donut => $donut },
10327 );
10328 7 my ($platform, $language) = $self->_resolve_template;
10329 7 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 7 7
$back2 ? : 0 7 7
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
070
$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
10330 handler => 'tt',
10331 template => "$platform/$language/pie",
10332 format => 'html',
10333 title => $title,
10334 chart_html => $chart_html,
10335 chart => \%chart_spec,
10336 chart_json => $self->_chart_json(\%chart_spec),
10337 back_url => ($back2 // $back),
10338 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10339 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10340 drill_back_url => $back,
10341 slice_count => scalar @slices,
10342 cat_col => $cat_col,
10343 val_col => $val_col,
10344 currency_symbol => $currency_symbol,
10345 source_url => $source_url,
10346 source_accessed => $source_accessed,
10347 language => $language,
10348 );
10349 }
10350  
10351 =head2 heatmap_view
10352  
10353 C<GET /heatmap> -- Render a D3.js grid heatmap for two categorical axes.
10354  
10355 Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:
10356  
10357 x=<col> X-axis (horizontal) categorical column (required)
10358 y=<col> Y-axis (vertical) categorical column (required)
10359 val=<col> Cell value column (optional; when absent, cells show row count)
10360 scheme=<name> D3 sequential colour scheme name (default: YlOrRd)
10361 show_val=1 Overlay the numeric value inside each cell
10362 back=<url> URL for the "Back to table" breadcrumb link
10363  
10364 =head3 API SPECIFICATION
10365  
10366 =head4 INPUT
10367  
10368 l spec Required. Left table spec (table:name or path:/abs/path).
10369 x string Required. Name of the X-axis categorical column.
10370 y string Required. Name of the Y-axis categorical column.
10371 val string Optional. Name of the value column; omit for count mode.
10372 scheme string Optional. D3 sequential colour scheme name.
10373 show_val flag Optional. Set to 1 to render values inside cells.
10374 back url Optional. Safe back-link URL (sanitised by _safe_back_url).
10375  
10376 =head4 OUTPUT
10377  
10378 200 text/html Rendered heatmap page.
10379 200 text/plain "No plottable data: ..." when grid is empty.
10380 400 text/plain Missing x= or y= parameter.
10381 400 text/plain Column not found: <col>.
10382 404 text/plain "Could not open data source" when l= is absent/invalid.
10383  
10384 =head3 MESSAGES
10385  
10386 error_heatmap_no_data -- no (x,y) pair has a non-empty value.
10387  
10388 =head3 FORMAL SPECIFICATION
10389  
10390 heatmap_view == lambda self .
10391 pre length(x_col) > 0 /\ length(y_col) > 0
10392 /\ x_col in columns /\ y_col in columns
10393 let triples = { (row[x_col], row[y_col], row[val_col]) | row in records,
10394 all three fields non-empty } in
10395 post render(heatmap, triples)
10396  
10397 =head3 EXAMPLE
10398  
10399 GET /heatmap?l=table:sales&x=region&y=product&val=amount
10400 -> 200 HTML page containing D3 heatmap SVG
10401  
10402 =cut
10403  
10404 57 ▶sub heatmap_view ($self) {
Subroutine heatmap_view: called CC=39 SCAR=37.8
Pod documented
10405 57 ▶ my $x_col = $self->param('x') // '';
Condition100%2/2
$self->param("x") // ""
l!l
543
MC/DC100%1/1
$self->param("x") // ""
$self->param("x")
Truth table100%2/2
A
A= $self->param("x")
Aresult
11
00
10406 57 ▶ my $y_col = $self->param('y') // '';
Condition100%2/2
$self->param("y") // ""
l!l
543
MC/DC100%1/1
$self->param("y") // ""
$self->param("y")
Truth table100%2/2
A
A= $self->param("y")
Aresult
11
00
10407 57 ▶ my $val_col = $self->param('val') // '';
Condition100%2/2
$self->param("val") // ""
l!l
750
MC/DC100%1/1
$self->param("val") // ""
$self->param("val")
Truth table100%2/2
A
A= $self->param("val")
Aresult
11
00
10408 57 my $scheme = _sequential_scheme($self->param('scheme'));
10409 57 ▶ my $show_v = $self->param('show_val') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('show_val') ? : 0 57 57
10410 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
10411 57 my $back2 = _safe_back_url($self->param('back2'));
10412 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
10413  
10414 57 ▶ return $self->render(text => 'Missing x or y column parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col and length $y_col 5 52 57
Condition100%3/3
length $x_col and length $y_col
!ll&&!rl&&r
4152
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
10415 unless length($x_col) && length($y_col);
10416  
10417 52 my ($src, $records, $columns) = $self->_run_pipeline_source;
10418 52 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 2 50 52
10419 unless defined $records;
10420  
10421 50 my $span = $self->_span_calc_spec($columns, 'x');
10422 return $self->render(text => $span->{error}, status => 400)
10423 50 ▶ if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 2 48 50
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
4802
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
10424  
10425 48 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
10426 48 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 48 48
10427 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
10428  
10429 47 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 46 47
10430  
10431 46 my %col_set = map { $_ => 1 } @{$columns};
10432 return $self->render(text => "Column not found: $x_col", status => 400)
10433 46 ▶ unless $col_set{$x_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$x_col} 3 43 46
10434 return $self->render(text => "Column not found: $y_col", status => 400)
10435 43 ▶ unless $col_set{$y_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$y_col} 2 41 43
10436 return $self->render(text => "Column not found: $val_col", status => 400)
10437 41 ▶ if length($val_col) && !$col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $val_col and not $col_set{$val_col} 1 40 41
Condition100%3/3
length $val_col and not $col_set{$val_col}
!ll&&!rl&&r
3551
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
10438  
10439 # A heatmap's time dimension is its x axis, which is the one span= buckets.
10440 40 ▶ $x_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 40 40
10441  
10442 # Collect first-seen axis order from the filtered source rows.
10443 # The aggregate path returns groups ordered by (x,y) ascending, which
10444 # differs from first-seen. We re-derive the layout order from the source
10445 # so the grid renders in natural data order regardless of backend.
10446 40 my (@x_order, @y_order, %seen_x, %seen_y);
10447 40 for my $row (@$records) {
10448 234 ▶ my $x = $row->{$x_col} // next;
Condition50%1/2
$row->{$x_col} // (next)
l!l
2340
MC/DC0%0/1
$row->{$x_col} // (next)
$row->{$x_col}
Truth table50%1/2
A
A= $row->{$x_col}
Aresult
11
00
10449 234 ▶ my $y = $row->{$y_col} // next;
Condition50%1/2
$row->{$y_col} // (next)
l!l
2340
MC/DC0%0/1
$row->{$y_col} // (next)
$row->{$y_col}
Truth table50%1/2
A
A= $row->{$y_col}
Aresult
11
00
10450 234 ▶ next unless length($x) && length($y);
Branch: 1 branch
BranchTrueFalseTotal
unless length $x and length $y 0 234 234
Condition33%1/3
length $x and length $y
!ll&&!rl&&r
00234
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
10451 234 ▶ push @x_order, $x unless $seen_x{$x}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_x{$x}++ 154 80 234
10452 234 ▶ push @y_order, $y unless $seen_y{$y}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_y{$y}++ 219 15 234
10453 }
10454  
10455 # Aggregate with _grouped_totals (push or Perl fold).
10456 40 ▶ my $agg_rows = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
length $val_col ? : 5 35 40
length $val_col ? : 5 35 40
10457 { source => $src, records => $records },
10458 {
10459 by => [$x_col, $y_col],
10460 fn => length($val_col) ? 'sum' : 'count',
10461 val => length($val_col) ? $val_col : undef,
10462 as => 'value',
10463 },
10464 );
10465  
10466 # Index aggregate rows by [x][y] for O(1) lookup.
10467 40 my %grid;
10468 40 for my $row (@$agg_rows) {
10469 234 $grid{$row->{$x_col}}{$row->{$y_col}} = $row->{value};
10470 }
10471  
10472 my @triples = map {
10473 40 my ($raw_x, $xv) = ($_, _decode_cell($_));
10474 154 ▶ map { [$xv, _decode_cell($_), $grid{$raw_x}{$_} // 0] } @y_order
Condition100%2/2
$grid{$raw_x}{$_} // 0
l!l
234630
MC/DC100%1/1
$grid{$raw_x}{$_} // 0
$grid{$raw_x}{$_}
Truth table100%2/2
A
A= $grid{$raw_x}{$_}
Aresult
11
00
10475 } @x_order;
10476  
10477 40 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @triples 0 40 40
10478 text => 'No plottable data: check that x and y columns contain values.',
10479 status => 200,
10480 ) unless @triples;
10481  
10482 40 my ($source_url, $source_accessed) = $self->_url_attribution;
10483  
10484 40 require HTML::D3;
10485 40 ▶ my $title = length($val_col) ? "$val_col by $x_col and $y_col"
Branch: 1 branch
BranchTrueFalseTotal
length $val_col ? : 5 35 40
10486 : "Count by $x_col and $y_col";
10487 40 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 900, height => 500)
Branch: 1 branch
BranchTrueFalseTotal
length $val_col ? : 5 35 40
10488 ->render_heatmap_snippet(\@triples, {
10489 x_label => $x_col,
10490 y_label => $y_col,
10491 val_label => (length($val_col) ? $val_col : 'Count'),
10492 color_scheme => $scheme,
10493 show_values => $show_v,
10494 animated => 1,
10495 });
10496  
10497 40 my $chart_html = $snippet->{html};
10498 40 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 40 40
10499  
10500 40 my %chart_spec = (
10501 kind => 'heatmap',
10502 title => $title,
10503 encode => { x => $x_col, y => $y_col, value => $val_col },
10504 options => { scheme => $scheme, show_values => $show_v },
10505 );
10506 40 my ($platform, $language) = $self->_resolve_template;
10507 40 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 40 40
$back2 ? : 0 40 40
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0400
$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
10508 handler => 'tt',
10509 template => "$platform/$language/heatmap",
10510 format => 'html',
10511 title => $title,
10512 chart_html => $chart_html,
10513 chart => \%chart_spec,
10514 chart_json => $self->_chart_json(\%chart_spec),
10515 cell_count => scalar @triples,
10516 back_url => ($back2 // $back),
10517 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10518 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10519 source_url => $source_url,
10520 source_accessed => $source_accessed,
10521 language => $language,
10522 );
10523 }
10524  
10525 =head2 bar_view
10526  
10527 C<GET /bar> -- Render a D3.js bar chart grouped by a categorical column.
10528  
10529 Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:
10530  
10531 cat=<col> Category (X-axis) column (required)
10532 val=<col> Value column to sum per category; omit or use C<__count__>
10533 to count rows instead of summing (optional)
10534 orient=h Horizontal bars (default: vertical)
10535 sort=value|label Sort bars by descending value or ascending label
10536 max=N Collapse bars beyond the top-N into an "Other" bar
10537 back=<url> URL for the "Back to table" breadcrumb link
10538  
10539 =head3 API SPECIFICATION
10540  
10541 =head4 INPUT
10542  
10543 l spec Required. Left table spec (table:name or path:/abs/path).
10544 cat string Required. Name of the category column.
10545 val string Optional. Name of the value column; use __count__ or
10546 omit entirely to count rows per category.
10547 orient string Optional. "h" for horizontal bars; default vertical.
10548 sort string Optional. "value" or "label"; default file order.
10549 max integer Optional. Collapse beyond top-N categories into "Other".
10550 back url Optional. Safe back-link URL (sanitised by _safe_back_url).
10551  
10552 =head4 OUTPUT
10553  
10554 200 text/html Rendered bar chart page (SVG element id="bar_chart").
10555 200 text/plain "No plottable data: ..." when no categories exist.
10556 400 text/plain Missing cat= parameter.
10557 400 text/plain Column not found: <col>.
10558 404 text/plain "Could not open data source" when l= is absent/invalid.
10559  
10560 =head3 MESSAGES
10561  
10562 error_bar_no_data -- no row has a non-empty category value.
10563  
10564 =head3 FORMAL SPECIFICATION
10565  
10566 bar_view == lambda self .
10567 pre length(cat_col) > 0 /\ cat_col in columns
10568 let bars = { (cat, sum(val)) | row in records, row[cat_col] = cat,
10569 val /= undef } in
10570 post render(bar, bars, orientation, sort, max_bars)
10571  
10572 =head3 EXAMPLE
10573  
10574 GET /bar?l=table:sales&cat=region&val=amount&sort=value
10575 -> 200 HTML page with id="bar_chart" SVG element
10576  
10577 =cut
10578  
10579 63 ▶sub bar_view ($self) {
Subroutine bar_view: called CC=47 SCAR=48.2
Pod documented
10580 63 ▶ my $cat_col = $self->param('cat') // '';
Condition100%2/2
$self->param("cat") // ""
l!l
594
MC/DC100%1/1
$self->param("cat") // ""
$self->param("cat")
Truth table100%2/2
A
A= $self->param("cat")
Aresult
11
00
10581 63 ▶ my $val_col = $self->param('val') // '';
Condition100%2/2
$self->param("val") // ""
l!l
1152
MC/DC100%1/1
$self->param("val") // ""
$self->param("val")
Truth table100%2/2
A
A= $self->param("val")
Aresult
11
00
10582 63 ▶ my $orient = $self->param('orient') // 'vertical';
Condition100%2/2
$self->param("orient") // "vertical"
l!l
261
MC/DC100%1/1
$self->param("orient") // "vertical"
$self->param("orient")
Truth table100%2/2
A
A= $self->param("orient")
Aresult
11
00
10583 63 ▶ my $sort = $self->param('sort') // 'none';
Condition100%2/2
$self->param("sort") // "none"
l!l
459
MC/DC100%1/1
$self->param("sort") // "none"
$self->param("sort")
Truth table100%2/2
A
A= $self->param("sort")
Aresult
11
00
10584 63 ▶ my $max_bars = int($self->param('max') || 0);
Condition50%1/2
$self->param('max') || 0
l!l
063
MC/DC0%0/1
$self->param('max') || 0
$self->param('max')
Truth table50%1/2
A
A= $self->param('max')
Aresult
11
00
10585 63 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
063
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
10586 63 my $back2 = _safe_back_url($self->param('back2'));
10587 63 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
063
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
10588  
10589 63 ▶ return $self->render(text => 'Missing cat column parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col 5 58 63
10590 unless length($cat_col);
10591  
10592 58 my ($src, $records, $columns) = $self->_run_pipeline_source;
10593 58 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 57 58
10594 unless defined $records;
10595  
10596 # span= buckets the category column by expanding into the calculated field a
10597 # reader could have typed, so the buckets come from the same arithmetic a
10598 # ?c= definition would use. See _span_calc_spec.
10599 57 my $span = $self->_span_calc_spec($columns, 'cat');
10600 return $self->render(text => $span->{error}, status => 400)
10601 57 ▶ if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 3 54 57
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
5403
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
10602  
10603 54 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
10604 54 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 54 54
10605 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
10606  
10607 53 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 52 53
10608  
10609 52 my %col_set = map { $_ => 1 } @{$columns};
10610 return $self->render(text => "Column not found: $cat_col", status => 400)
10611 52 ▶ unless $col_set{$cat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$cat_col} 2 50 52
10612  
10613 # '__count__' sentinel: count rows per category instead of summing a column.
10614 50 ▶ 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
1418
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
10615 return $self->render(text => "Column not found: $val_col", status => 400)
10616 50 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 2 48 50
Condition100%3/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
4262
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
10617  
10618 # The chart groups by the bucket column the request asked for, if it did.
10619 48 ▶ $cat_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 48 48
10620  
10621 # Aggregate via _grouped_totals (push path or Perl fold).
10622 48 ▶ my $agg_rows = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 42 6 48
$count_mode ? : 42 6 48
10623 { source => $src, records => $records },
10624 {
10625 by => [$cat_col],
10626 fn => $count_mode ? 'count' : 'sum',
10627 val => $count_mode ? undef : $val_col,
10628 as => 'value',
10629 },
10630 );
10631  
10632 # Top-N: keep the highest-N categories, aggregate the rest as "Other".
10633 48 ▶ my $topn_n = _whole_number($self->param('topn')) // 0;
Condition50%1/2
_whole_number($self->param("topn")) // 0
l!l
048
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
10634 48 ▶ if ($topn_n > 0 && @$agg_rows > $topn_n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($topn_n > 0 and @$agg_rows > $topn_n) 0 48 48
Condition33%1/3
$topn_n > 0 and @$agg_rows > $topn_n
!ll&&!rl&&r
4800
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
10635 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
10636 0 my @top_agg = @sorted[0 .. $topn_n - 1];
10637 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
10638 my $other_rec = [
10639 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
10640 ];
10641 0 ▶ if (@$other_rec) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$other_rec) 0 0 0
10642 0 ▶ my $other = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 0 0 0
$count_mode ? : 0 0 0
10643 { source => undef, records => $other_rec },
10644 { by => [], fn => ($count_mode ? 'count' : 'sum'),
10645 val => ($count_mode ? undef : $val_col), as => 'value' },
10646 );
10647 push @top_agg, { $cat_col => 'Other', value => $other->[0]{value} }
10648 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
10649 }
10650 0 $agg_rows = \@top_agg;
10651 }
10652  
10653 48 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg_rows 1 47 48
10654 text => 'No plottable data: no rows have valid data in the selected columns.',
10655 status => 200,
10656 ) unless @$agg_rows;
10657  
10658 47 my @bars = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg_rows;
10659  
10660 47 ▶ my $orientation = ($orient eq 'h') ? 'horizontal' : 'vertical';
Branch: 1 branch
BranchTrueFalseTotal
$orient eq 'h' ? : 2 45 47
10661 47 ▶ my $sort_bars = ($sort eq 'value' || $sort eq 'label') ? $sort : 'none';
Branch: 1 branch
BranchTrueFalseTotal
$sort eq 'value' || $sort eq 'label' ? : 2 45 47
Condition66%2/3
$sort eq "value" or $sort eq "label"
l!l&&r!l&&!r
2045
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
10662  
10663 47 my ($source_url, $source_accessed) = $self->_url_attribution;
10664  
10665 47 require HTML::D3;
10666 47 ▶ my $title = $count_mode ? "Count by $cat_col"
Branch: 1 branch
BranchTrueFalseTotal
$count_mode ? : 42 5 47
10667 : "$val_col by $cat_col";
10668 47 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 480)
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 42 5 47
$max_bars > 0 ? : 0 47 47
10669 ->render_bar_chart_snippet(\@bars, {
10670 animated => 1,
10671 orientation => $orientation,
10672 sort_bars => $sort_bars,
10673 color => 'categorical',
10674 show_values => 0,
10675 value_label => ($count_mode ? 'Count' : $val_col),
10676 x_label => $cat_col,
10677 ($max_bars > 0 ? (max_bars => $max_bars) : ()),
10678 });
10679  
10680 47 my $chart_html = $snippet->{html};
10681 47 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 47 47
10682  
10683 47 ▶ my %chart_spec = (
Condition50%1/2
$orient // "v"
l!l
470
MC/DC0%0/1
$orient // "v"
$orient
Truth table50%1/2
A
A= $orient
Aresult
11
00
10684 kind => 'bar',
10685 title => $title,
10686 encode => { cat => $cat_col, value => $val_col },
10687 options => { orientation => ($orient // 'v'), max_items => $max_bars },
10688 );
10689 47 my ($platform, $language) = $self->_resolve_template;
10690 47 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 47 47
$back2 ? : 0 47 47
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0470
$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
10691 handler => 'tt',
10692 template => "$platform/$language/bar",
10693 format => 'html',
10694 title => $title,
10695 chart_html => $chart_html,
10696 chart => \%chart_spec,
10697 chart_json => $self->_chart_json(\%chart_spec),
10698 bar_count => scalar @bars,
10699 cat_col => $cat_col,
10700 back_url => ($back2 // $back),
10701 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10702 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10703 source_url => $source_url,
10704 source_accessed => $source_accessed,
10705 language => $language,
10706 );
10707 }
10708  
10709 =head2 folder_view
10710  
10711 C<GET /folder> -- Browse a data table grouped by the letter-prefix hierarchy
10712 of an order-number column (e.g. A10, CT4, B3).
10713  
10714 The top level displays one folder icon per initial letter group (A, B, C ...).
10715 Clicking a folder with sub-prefixes (e.g. C contains CA and CB items) shows
10716 the sub-folders; clicking a leaf prefix shows the actual data rows sorted
10717 numerically by the embedded digit sequence.
10718  
10719 Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:
10720  
10721 col=<col> Column whose values contain order codes (optional; auto-
10722 detected when absent by scanning the first 10 rows for
10723 values matching C<[A-Z]{1,4}\d+[A-Z]?>)
10724 prefix=<str> Current drill-down prefix, e.g. "CA" (optional; top-level
10725 when absent)
10726 back=<url> URL for the "Back to table" breadcrumb link (optional;
10727 derived from C<l=> when absent)
10728  
10729 =head3 API SPECIFICATION
10730  
10731 =head4 INPUT
10732  
10733 l spec Required. Left table spec (table:name or path:/abs/path).
10734 col string Optional. Order-code column name.
10735 prefix string Optional. Current letter prefix; max length MAX_PREFIX_LEN.
10736 back url Optional. Safe back-link URL (sanitised by _safe_back_url).
10737  
10738 =head4 OUTPUT
10739  
10740 200 text/html Rendered folder page with folder grid and/or item table.
10741 400 text/plain "Missing l= parameter" when l= is absent.
10742 400 text/plain "Prefix too long" when prefix exceeds MAX_PREFIX_LEN (20).
10743 404 text/plain "Could not open data source" when the data source is unavailable.
10744  
10745 =head3 MESSAGES
10746  
10747 None -- all failure paths render plain text with an HTTP status code.
10748  
10749 =head3 FORMAL SPECIFICATION
10750  
10751 folder_view == lambda self .
10752 pre length(left_spec) > 0 /\ length(prefix) <= MAX_PREFIX_LEN
10753 let records = pipeline(left_spec, joins, filters)
10754 prefix_map = { p -> [row] | row in records, row[col] =~ /[A-Z]+/ -> p } in
10755 IF prefix = "" THEN
10756 post render(folder, folders = first_letters(prefix_map))
10757 ELSE
10758 post render(folder, folders = sub_prefixes(prefix, prefix_map),
10759 items = sort_numeric(prefix_map[prefix]))
10760  
10761 =head3 EXAMPLE
10762  
10763 GET /folder?l=table:orders&col=order_no
10764 -> 200 HTML folder grid showing A (12 items), B (7 items), C (4 items)
10765  
10766 GET /folder?l=table:orders&col=order_no&prefix=A
10767 -> 200 HTML folder grid for sub-prefixes and items directly under "A"
10768  
10769 =cut
10770  
10771 58 ▶sub folder_view ($self) {
Subroutine folder_view: called CC=38 SCAR=37.7
Pod documented
10772 58 ▶ my $key_col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
508
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
10773 58 ▶ my $prefix = $self->param('prefix') // '';
Condition100%2/2
$self->param("prefix") // ""
l!l
553
MC/DC100%1/1
$self->param("prefix") // ""
$self->param("prefix")
Truth table100%2/2
A
A= $self->param("prefix")
Aresult
11
00
10774 58 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
562
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
10775  
10776 58 ▶ return $self->render(text => 'Missing l= parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 3 55 58
10777 unless length($left_spec);
10778  
10779 # Guard against DoS: a crafted prefix longer than any real order-code would
10780 # generate O(N) breadcrumb entries and a proportionally large HTML response.
10781 55 ▶ return $self->render(text => 'Prefix too long', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
if length $prefix > $MAX_PREFIX_LEN 2 53 55
10782 if length($prefix) > $MAX_PREFIX_LEN;
10783  
10784 # Fall back to the table's own URL when no explicit back= is supplied,
10785 # so the breadcrumb always has a "Back to table" link.
10786 53 ▶ 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
0530
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
10787 || $self->_spec_to_url($left_spec);
10788  
10789 53 my ($records, $columns) = $self->_run_export_pipeline;
10790 53 ▶ return if $self->stash('_reduce_error');
Branch: 1 branch
BranchTrueFalseTotal
if $self->stash("_reduce_error") 6 47 53
10791 47 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless $records 2 45 47
10792 unless $records;
10793  
10794 # Auto-detect key column: find the first column whose sampled values look
10795 # like order-number codes (1-4 uppercase letters followed by digits).
10796 45 ▶ if (!length($key_col)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $key_col) 2 43 45
10797 2 ▶ my $sample_end = $#{$records} < 9 ? $#{$records} : 9;
Branch: 1 branch
BranchTrueFalseTotal
$#{$records;} < 9 ? : 2 0 2
10798 2 OUTER: for my $col (@{$columns}) {
10799 12 for my $row (@{$records}[0 .. $sample_end]) {
10800 72 ▶ 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) 0 72 72
Condition50%1/2
$row->{$col} // ""
l!l
720
MC/DC0%0/1
$row->{$col} // ""
$row->{$col}
Truth table50%1/2
A
A= $row->{$col}
Aresult
11
00
10801 0 $key_col = $col;
10802 0 last OUTER;
10803 }
10804 }
10805 }
10806 2 ▶ $key_col ||= ($columns->[0] // '');
Condition40%2/5
$key_col ||= $columns->[0] // ""
l!l&&r!l&&!r
020
$columns->[0] // ""
l!l
20
MC/DC0%0/2
$key_col ||= $columns->[0] // ""
$key_col $columns->[0]
Truth table33%1/3
A ||= B
A= $key_colB= $columns->[0]
ABresult
1X1
011
000
10807 }
10808  
10809 # Build prefix -> [rows] map. Prefix is the leading letter-run of each
10810 # key value: "A10" -> "A", "CT4" -> "CT", "CC30A" -> "CC".
10811 45 my %prefix_to_rows;
10812 45 for my $row (@{$records}) {
10813 270 ▶ my $val = $row->{$key_col} // '';
Condition50%1/2
$row->{$key_col} // ""
l!l
2700
MC/DC0%0/1
$row->{$key_col} // ""
$row->{$key_col}
Truth table50%1/2
A
A= $row->{$key_col}
Aresult
11
00
10814 270 my ($p) = $val =~ /\A([A-Z]+)/;
10815 270 ▶ next unless defined $p;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $p 234 36 270
10816 36 push @{ $prefix_to_rows{$p} }, $row;
10817 }
10818  
10819 # Return the sorted list of "one-step" child prefixes of $par: all known
10820 # prefixes that share the parent as a strict prefix and extend it by
10821 # exactly one letter.
10822 3 ▶ my $sub_prefixes = sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
10823 3 my ($par) = @_;
10824 3 my $len = length($par);
10825 3 my %seen;
10826 3 for my $p (keys %prefix_to_rows) {
10827 12 ▶ next if length($p) <= $len;
Branch: 1 branch
BranchTrueFalseTotal
if length $p <= $len 10 2 12
10828 2 ▶ next if substr($p, 0, $len) ne $par;
Branch: 1 branch
BranchTrueFalseTotal
if substr($p, 0, $len) ne $par 2 0 2
10829 0 $seen{ substr($p, 0, $len + 1) } = 1;
10830 }
10831 3 return sort keys %seen;
10832 45 };
10833  
10834 # Count total items underneath a prefix (including all deeper sub-prefixes).
10835 10 ▶ my $deep_count = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
10836 10 my ($par) = @_;
10837 10 my $n = 0;
10838 10 for my $p (keys %prefix_to_rows) {
10839 40 ▶ $n += scalar @{ $prefix_to_rows{$p} }
Branch: 1 branch
BranchTrueFalseTotal
if substr($p, 0, length $par) eq $par 12 28 40
10840 if substr($p, 0, length($par)) eq $par;
10841 }
10842 10 return $n;
10843 45 };
10844  
10845 45 my ($platform, $language) = $self->_resolve_template;
10846  
10847 # Base URL carries the table spec (and optional col=) so every sub-link
10848 # re-uses the same data source without repeating params.
10849 45 my $base_url = '/folder?l=' . url_escape($left_spec);
10850 45 ▶ $base_url .= '&col=' . url_escape($key_col) if length($key_col);
Branch: 1 branch
BranchTrueFalseTotal
if length $key_col 45 0 45
10851 # The table it came from travels too, so a folder level keeps the trail.
10852 45 $base_url .= '&back=' . url_escape($back);
10853  
10854 45 my (@folders, @items, @breadcrumb);
10855  
10856 45 ▶ if (!length($prefix)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not length $prefix) { } 42 3 45
10857 # Top level: group all prefixes by their first letter.
10858 42 my %first_letter;
10859 42 for my $p (keys %prefix_to_rows) {
10860 12 $first_letter{ substr($p, 0, 1) } = 1;
10861 }
10862 42 for my $fl (sort keys %first_letter) {
10863 10 push @folders, {
10864 name => $fl,
10865 count => $deep_count->($fl),
10866 href => $base_url . '&prefix=' . url_escape($fl),
10867 };
10868 }
10869 } else {
10870 # Build breadcrumb: one entry per letter-prefix layer up to current.
10871 # e.g. prefix="CD" -> [ {name="C", href=...}, {name="CD", href=undef} ]
10872 3 for my $i (1 .. length($prefix)) {
10873 4 my $p = substr($prefix, 0, $i);
10874 4 ▶ push @breadcrumb, {
Branch: 1 branch
BranchTrueFalseTotal
$i < length $prefix ? : 1 3 4
10875 name => $p,
10876 href => ($i < length($prefix))
10877 ? ($base_url . '&prefix=' . url_escape($p))
10878 : undef,
10879 };
10880 }
10881  
10882 # One-step child prefixes of the current prefix (sub-folders).
10883 3 for my $sp ($sub_prefixes->($prefix)) {
10884 0 push @folders, {
10885 name => $sp,
10886 count => $deep_count->($sp),
10887 href => $base_url . '&prefix=' . url_escape($sp),
10888 };
10889 }
10890  
10891 # Items whose prefix matches exactly (e.g. prefix="C" shows C1, C3, ...).
10892 3 ▶ @items = @{ $prefix_to_rows{$prefix} // [] };
Condition50%1/2
$prefix_to_rows{$prefix} // []
l!l
30
MC/DC0%0/1
$prefix_to_rows{$prefix} // []
$prefix_to_rows{$prefix}
Truth table50%1/2
A
A= $prefix_to_rows{$prefix}
Aresult
11
00
10893  
10894 # Sort by the numeric part of the key value so A9 < A10.
10895 @items = sort {
10896 3 ▶ my ($an) = ($a->{$key_col} // '') =~ /(\d+)/;
Condition50%1/2
$Database::BI::Controller::Dashboard::a->{$key_col} // ""
l!l
40
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
10897 4 ▶ my ($bn) = ($b->{$key_col} // '') =~ /(\d+)/;
Condition50%1/2
$Database::BI::Controller::Dashboard::b->{$key_col} // ""
l!l
40
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
10898 ($an // 0) <=> ($bn // 0)
10899 4 ▶ || ($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
301
$an // 0
l!l
31
$bn // 0
l!l
31
$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
10900 } @items;
10901 }
10902  
10903 45 ▶ my $title = length($prefix) ? "Folder: $prefix" : 'Folder view';
Branch: 1 branch
BranchTrueFalseTotal
length $prefix ? : 3 42 45
10904  
10905 $self->render(
10906 handler => 'tt',
10907 template => "$platform/$language/folder",
10908 format => 'html',
10909 title => $title,
10910 folders => \@folders,
10911 items => \@items,
10912 columns => $columns,
10913 key_col => $key_col,
10914 prefix => $prefix,
10915 breadcrumb => \@breadcrumb,
10916 # Inside a folder the trail goes on past this page, so its own crumb
10917 # links to the top of the folder view.
10918 45 ▶ (@breadcrumb ? (trail => do {
Branch: 1 branch
BranchTrueFalseTotal
@breadcrumb ? : 3 42 45
10919 3 my $trail = _breadcrumb_trail($self);
10920 3 ▶ $trail->[-1]{url} = $base_url if @$trail;
Branch: 1 branch
BranchTrueFalseTotal
if @$trail 3 0 3
10921 3 $trail;
10922 }) : ()),
10923 base_url => $base_url,
10924 back_url => $back,
10925 back_label => 'Back to table',
10926 left_spec => $left_spec,
10927 language => $language,
10928 );
10929 }
10930  
10931 =head2 tables_view
10932  
10933 C<GET /tables> -- Schema browser for multi-table databases (SQLite, etc.).
10934 Lists all internal tables with their columns; clicking a table opens it. A
10935 JSON file that is an object holding lists of objects has one table per list
10936 (see L<Database::BI::Model::DataSource/json_lists>).
10937  
10938 =head3 API SPECIFICATION
10939  
10940 =head4 INPUT
10941  
10942 ?l= string Required. Table spec: "table:name" (data_dir) or
10943 "path:/abs/path" (filesystem path). The file must be a
10944 SQLite database or a .json file.
10945  
10946 =head4 OUTPUT
10947  
10948 Renders C<tables.html.tt> with:
10949  
10950 db_label string Short name / stem of the database file
10951 tables ARRAYREF of { name, columns => [...], href }
10952 spec string The raw l= spec (for building back links)
10953 back_url string URL to navigate back one level
10954 back_label string Label for the back link
10955  
10956 =cut
10957  
10958 57 ▶sub tables_view ($self) {
Subroutine tables_view: called CC=41 SCAR=59.6
Pod documented
10959 57 my ($platform, $language) = $self->_resolve_template;
10960 57 my $spec = $self->param('l');
10961 57 ▶ return $self->reply->not_found unless defined $spec && length $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec and length $spec 4 53 57
Condition100%3/3
defined $spec and length $spec
!ll&&!rl&&r
2253
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
10962  
10963 53 my ($file_path, $db_label, $back_url, $back_label);
10964 53 my @tables;
10965  
10966 53 ▶ if ($spec =~ /\Atable:([A-Za-z0-9_]+)\z/) {
Branch: 4 branches
BranchTrueFalseTotal
if ($spec =~ /\Atable:([A-Za-z0-9_]+)\z/u) { } 44 9 53
elsif ($spec =~ /\Apath:(.+)\z/u) { } 5 4 9
elsif ($spec =~ /$REDIS_URL_RE/u) { } 0 4 4
elsif ($spec =~ /$MARIADB_SERVER_RE/u) { } 0 4 4
10967 44 my $data_dir = _data_dir_for($self->app);
10968 44 my @exts = qw(sql sqlite sqlite3 db json);
10969 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
10970 44 for my $ext (@exts) {
10971 218 my $p = $data_dir->child("$table_name.$ext");
10972 218 ▶ if (-f $p) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $p) 2 216 218
10973 2 $file_path = $p->to_string;
10974 2 last;
10975 }
10976 }
10977 44 ▶ return $self->reply->not_found unless defined $file_path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_path 42 2 44
10978 2 $db_label = $table_name;
10979 2 $back_url = '/';
10980 2 $back_label = 'Home';
10981 } elsif ($spec =~ /\Apath:(.+)\z/) {
10982 5 my ($path_arg) = _split_path($1);
10983 5 ▶ if (my $refusal = _outside_roots($self, $path_arg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $refusal = _outside_roots($self, $path_arg)) 0 5 5
10984 0 return $self->render(text => $refusal, status => 403);
10985 }
10986 5 my $file = eval { Mojo::File->new($path_arg)->realpath };
10987 5 ▶ 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 3 5
Condition83%5/6
defined $file and -f $file and $file->basename =~ /\.(?:sql|sqlite|sqlite3|db|json)\z/iu
!ll&&!rl&&r
113
defined $file and -f $file
!ll&&!rl&&r
104
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
10988 unless defined $file && -f $file && $file->basename =~ /\.(?:sql|sqlite|sqlite3|db|json)\z/i;
10989 3 $file_path = $file->to_string;
10990 3 ($db_label = $file->basename) =~ s/\.[^.]+\z//;
10991 3 $back_url = '/browse?path=' . url_escape($file->dirname->to_string);
10992 3 $back_label = 'Back to browser';
10993 } elsif ($spec =~ $REDIS_URL_RE) {
10994 # Bare redis:// URL -- scan keys and present a picker.
10995 # Parse redis://[:password@]host[:port][/db]
10996 0 my ($password, $hostport, $db_idx);
10997 0 ▶ if ($spec =~ m{\Aredis://(?::([^@]*)@)?([^/]+)(?:/(\d+))?\z}i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec =~ m[\Aredis://(?::([^\@]*)@)?([^/]+)(?:/(\d+))?\z]iu) 0 0 0
10998 0 ($password, $hostport, $db_idx) = ($1, $2, $3);
10999 }
11000 0 ▶ $hostport //= 'localhost:6379';
Condition0%0/2
$hostport //= "localhost:6379"
l!l
00
MC/DC0%0/1
$hostport //= "localhost:6379"
$hostport
Truth table0%0/2
A
A= $hostport
Aresult
11
00
11001 0 $db_label = "redis://$hostport";
11002 0 $back_url = '/';
11003 0 $back_label = 'Home';
11004  
11005 0 eval {
11006 # Load Redis::Fast if available, fall back to Redis.
11007 # Use the file-path form ("Redis/Fast.pm") because require with a
11008 # plain string treats it as a filename, not a module name.
11009 0 my $pkg;
11010 0 for my $mod ('Redis::Fast', 'Redis') {
11011 0 (my $file = $mod) =~ s{::}{/}g;
11012 0 ▶ if (eval { require "$file.pm"; 1 }) { $pkg = $mod; last }
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require "$file.pm"; 1 } }) 0 0 0
11013 }
11014 0 ▶ croak 'Redis or Redis::Fast must be installed to browse a Redis server'
Branch: 1 branch
BranchTrueFalseTotal
unless $pkg 0 0 0
11015 unless $pkg;
11016  
11017 0 my $redis = $pkg->new(
11018 server => $hostport,
11019 cnx_timeout => 5,
11020 read_timeout => 10,
11021 );
11022 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
11023 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
11024  
11025 # SCAN in a loop; stop at 200 keys -- enough for a picker.
11026 0 my $cursor = 0;
11027 0 my @all_keys;
11028 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
11029 0 my ($new_cursor, $batch) = $redis->scan($cursor, 'COUNT', 100);
11030 0 $cursor = $new_cursor;
11031 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
11032 } while ($cursor ne '0' && @all_keys < 200);
11033  
11034 0 my $tables_url = '/tables?l=' . url_escape($spec);
11035 0 for my $key (sort @all_keys) {
11036 0 my $open_url = '/open?path=' . url_escape("redis:$key|$spec")
11037 . '&back=' . url_escape($tables_url)
11038 . '&back_label=Redis+keys';
11039 0 push @tables, { name => $key, columns => [], href => $open_url };
11040 }
11041 };
11042 0 ▶ return $self->reply->not_found if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
11043 } elsif ($spec =~ $MARIADB_SERVER_RE) {
11044 0 my $server = $1;
11045 0 $db_label = $server;
11046 0 $back_url = '/';
11047 0 $back_label = 'Home';
11048 0 my $found = eval {
11049 Database::BI::Model::DataSource->mariadb_tables($server,
11050 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
11051 };
11052 0 ▶ unless ($found) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($found) 0 0 0
11053 0 return $self->render(
11054 template => "$platform/$language/home",
11055 handler => 'tt',
11056 format => 'html',
11057 tables => [],
11058 title => 'Error',
11059 error => $self->_i18n('error_file_open', $spec, _tidy_error($@)),
11060 back_url => '/',
11061 back_label => 'Home',
11062 language => $language,
11063 );
11064 }
11065 0 for my $found_table (@{$found}) {
11066 0 my ($name, $cols) = @{$found_table}{qw(name columns)};
11067 # Database::Abstraction refuses this name, so the card says so.
11068 0 ▶ if ($name !~ $TABLE_NAME_RE) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($name =~ /$TABLE_NAME_RE/u) 0 0 0
11069 0 (my $safe = $name) =~ s/[^A-Za-z0-9_]/_/g;
11070 0 ▶ $safe = "_$safe" unless $safe =~ /\A[A-Za-z_]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $safe =~ /\A[A-Za-z_]/u 0 0 0
11071 0 push @tables, { name => $name, columns => $cols, unusable => 1, safe_name => $safe, on_server => 1 };
11072 0 next;
11073 }
11074 0 my $open_url = '/open?path=' . url_escape("mariadb:$server/$name")
11075 . '&back=' . url_escape('/tables?l=' . $spec)
11076 . '&back_label=' . url_escape(ucfirst($db_label) . ' schema');
11077 0 push @tables, { name => $name, columns => $cols, href => $open_url };
11078 }
11079 } else {
11080 4 return $self->reply->not_found;
11081 }
11082  
11083 5 ▶ if (defined $file_path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file_path) 5 0 5
11084 # A JSON file's tables are its lists of objects; a SQLite file's are
11085 # listed by Database::Join.
11086 my $schema = $file_path =~ /\.json\z/i
11087 0 ? eval { Database::BI::Model::DataSource->json_lists($file_path) }
11088 5 ▶ : eval { require Database::Join::Catalog; Database::Join::Catalog->schema(file => $file_path) };
Branch: 1 branch
BranchTrueFalseTotal
$file_path =~ /\.json\z/iu ? : 0 5 5
11089 5 ▶ return $self->reply->not_found unless $schema;
Branch: 1 branch
BranchTrueFalseTotal
unless $schema 0 5 5
11090 5 for my $table_info (@{$schema}) {
11091 12 my $tname = $table_info->{name};
11092 12 my @cols = @{ $table_info->{columns} };
11093 # Database::Abstraction refuses this name, so the card says so
11094 # rather than linking to an error. A JSON list's name never
11095 # reaches SQL, so any name opens.
11096 12 ▶ 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 12 12
Condition33%1/3
$tname =~ /$TABLE_NAME_RE/u or $file_path =~ /\.json\z/iu
l!l&&r!l&&!r
1200
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
11097 0 (my $safe = $tname) =~ s/[^A-Za-z0-9_]/_/g;
11098 0 ▶ $safe = "_$safe" unless $safe =~ /\A[A-Za-z_]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $safe =~ /\A[A-Za-z_]/u 0 0 0
11099 0 push @tables, { name => $tname, columns => \@cols, unusable => 1, safe_name => $safe };
11100 0 next;
11101 }
11102 12 my $open_url = '/open?path=' . url_escape($file_path)
11103 . '&it=' . url_escape($tname)
11104 . '&back=' . url_escape('/tables?l=' . $spec)
11105 . '&back_label=' . url_escape(ucfirst($db_label) . ' schema');
11106 12 push @tables, { name => $tname, columns => \@cols, href => $open_url };
11107 }
11108 }
11109  
11110 $self->render(
11111 5 template => "$platform/$language/tables",
11112 handler => 'tt',
11113 format => 'html',
11114 title => ucfirst($db_label) . ' -- Tables',
11115 db_label => $db_label,
11116 tables => \@tables,
11117 spec => $spec,
11118 back_url => $back_url,
11119 back_label => $back_label,
11120 language => $language,
11121 );
11122 }
11123  
11124 =head2 pivot_view
11125  
11126 C<GET /pivot> -- Crosstab / pivot table view.
11127  
11128 Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:
11129  
11130 rows=<col>[,<col>...] Row dimensions (required, comma-separated column names)
11131 cols=<col>[,<col>...] Column dimensions (optional)
11132 m=<col>:<fn>:<as> Measure spec, repeatable (required); col may be empty for count
11133 h=<as>:<op>:<val> Post-aggregation HAVING filter (repeatable, optional)
11134 totals=1 Include row subtotals, column subtotals, and grand total
11135 scheme=<name> Colour scheme for cell shading (optional)
11136 max_cols=<n> Collapse column headers beyond top-N into "Other"
11137 page= / per_page= Pagination over row groups
11138 format=csv|sqlite|json Export the pivot grid
11139  
11140 =head3 API SPECIFICATION
11141  
11142 =head4 INPUT
11143  
11144 The query parameters above, with C<l=> required as well.
11145  
11146 =head4 OUTPUT
11147  
11148 200 text/html (or the export format) The grid.
11149 400 text/plain 'Missing l= parameter', error_pivot_rows_required,
11150 error_pivot_measure_req, error_pivot_measure_invalid,
11151 error_measure_column, error_pivot_dim_not_found or error_topn_col.
11152 404 text/plain The source cannot be opened.
11153  
11154 =head3 FORMAL SPECIFICATION
11155  
11156 pivot_view
11157 l?, rows?, m? : seq Char
11158 response! : HTTP
11159 ──────────
11160 l? = ⟨⟩ ∨ rows? = ⟨⟩ ∨ m? = ⟨⟩ ⇒ response!.status = 400
11161 l? ≠ ⟨⟩ ∧ ¬ opens(l?) ⇒ response!.status = 404
11162  
11163 =cut
11164  
11165 49 ▶sub pivot_view ($self) {
Subroutine pivot_view: called CC=129 SCAR=83.0
Pod documented
11166 49 ▶ my $left_spec = $self->param('l') // '';
Condition50%1/2
$self->param("l") // ""
l!l
490
MC/DC0%0/1
$self->param("l") // ""
$self->param("l")
Truth table50%1/2
A
A= $self->param("l")
Aresult
11
00
11167 49 ▶ return $self->render(text => 'Missing l= parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 1 48 49
11168 unless length $left_spec;
11169  
11170 48 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
048
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
11171 48 my $back2 = _safe_back_url($self->param('back2'));
11172 48 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
048
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
11173  
11174 48 ▶ my $rows_str = $self->param('rows') // '';
Condition100%2/2
$self->param("rows") // ""
l!l
642
MC/DC100%1/1
$self->param("rows") // ""
$self->param("rows")
Truth table100%2/2
A
A= $self->param("rows")
Aresult
11
00
11175 48 ▶ return $self->render(text => $self->_i18n('error_pivot_rows_required'), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $rows_str 42 6 48
11176 unless length $rows_str;
11177  
11178 6 ▶ my @measure_strs = @{ $self->every_param('m') // [] };
Condition50%1/2
$self->every_param("m") // []
l!l
60
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
11179 6 ▶ return $self->render(text => $self->_i18n('error_pivot_measure_req'), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless @measure_strs 1 5 6
11180 unless @measure_strs;
11181  
11182 # Split dimensions on comma. A dimension name containing a comma
11183 # would produce an ambiguous split; that must be rejected.
11184 5 my @rows = split /,/, $rows_str, -1;
11185 5 ▶ my @cols = split /,/, ($self->param('cols') // ''), -1;
Condition50%1/2
$self->param("cols") // ""
l!l
05
MC/DC0%0/1
$self->param("cols") // ""
$self->param("cols")
Truth table50%1/2
A
A= $self->param("cols")
Aresult
11
00
11186 0 @cols = grep { length $_ } @cols;
11187  
11188 5 my @measures;
11189 5 for my $ms (@measure_strs) {
11190 5 my $m = _parse_measure_param($ms);
11191 5 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless $m 1 4 5
11192 text => $self->_i18n('error_pivot_measure_invalid', $ms, join(' ', @MEASURE_FNS)),
11193 status => 400,
11194 ) unless $m;
11195 4 push @measures, $m;
11196 }
11197  
11198 4 ▶ my $show_totals = ($self->param('totals') // '') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('totals') // '' ? : 0 4 4
Condition50%1/2
$self->param("totals") // ""
l!l
04
MC/DC0%0/1
$self->param("totals") // ""
$self->param("totals")
Truth table50%1/2
A
A= $self->param("totals")
Aresult
11
00
11199 4 ▶ my $scheme = $self->param('scheme') // '';
Condition50%1/2
$self->param("scheme") // ""
l!l
04
MC/DC0%0/1
$self->param("scheme") // ""
$self->param("scheme")
Truth table50%1/2
A
A= $self->param("scheme")
Aresult
11
00
11200 4 ▶ my $max_cols_n = int($self->param('max_cols') || 0);
Condition50%1/2
$self->param('max_cols') || 0
l!l
04
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
11201 4 ▶ my $format = lc($self->param('format') // '');
Condition100%2/2
$self->param("format") // ""
l!l
13
MC/DC100%1/1
$self->param("format") // ""
$self->param("format")
Truth table100%2/2
A
A= $self->param("format")
Aresult
11
00
11202  
11203 # Build the data pipeline.
11204 4 my ($src, $records, $columns) = $self->_run_pipeline_source;
11205 4 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 3 4
11206 unless defined $records;
11207  
11208 # span= buckets one dimension, which for a pivot is one of the rows= columns;
11209 # the dimension itself may be any of them, so with more than one it is tcol=
11210 # that says which. See _span_calc_spec.
11211 3 my $span = $self->_span_calc_spec($columns, 'rows');
11212 3 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 0 3 3
Condition33%1/3
$span and $span->{"error"}
!ll&&!rl&&r
300
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
11213  
11214 # Calculated fields (?c=name:expr) -- evaluated before aggregation so calc
11215 # columns are available as row/col dimensions and measure columns.
11216 3 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
11217 3 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 3 3
11218 0 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3 3
11219  
11220 3 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 3 3
11221  
11222 3 my %col_set = map { $_ => 1 } @{$columns};
11223  
11224 3 for my $dim (@rows, @cols) {
11225 return $self->render(
11226 text => $self->_i18n('error_pivot_dim_not_found', $dim),
11227 status => 400,
11228 3 ▶ ) unless $col_set{$dim};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$dim} 1 2 3
11229 }
11230  
11231 2 ▶ if ($span) {
Branch: 1 branch
BranchTrueFalseTotal
if ($span) 0 2 2
11232 0 ▶ @rows = map { $_ eq $span->{src} ? $span->{col} : $_ } @rows;
Branch: 1 branch
BranchTrueFalseTotal
$_ eq $span->{'src'} ? : 0 0 0
11233 0 ▶ @cols = map { $_ eq $span->{src} ? $span->{col} : $_ } @cols;
Branch: 1 branch
BranchTrueFalseTotal
$_ eq $span->{'src'} ? : 0 0 0
11234 }
11235  
11236 2 for my $m (@measures) {
11237 2 ▶ next unless defined $m->{col} && length $m->{col};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $m->{"col"} and length $m->{"col"} 0 2 2
Condition33%1/3
defined $m->{"col"} and length $m->{"col"}
!ll&&!rl&&r
002
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
11238 return $self->render(
11239 text => $self->_i18n('error_measure_column', $m->{col}),
11240 status => 400,
11241 2 ▶ ) unless $col_set{$m->{col}};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$m->{"col"}} 0 2 2
11242 }
11243  
11244 2 my $pipeline = { source => $src, records => $records };
11245  
11246 # -----------------------------------------------------------------------
11247 # Aggregate: one _grouped_totals call per measure, grouped by all
11248 # row AND column dimensions together.
11249 # -----------------------------------------------------------------------
11250 2 my (%cells, %row_combos, %col_combos);
11251 2 my (@row_key_order, @col_key_order);
11252 2 my (%row_seen, %col_seen);
11253  
11254 2 for my $m (@measures) {
11255 2 ▶ my $cv = (defined $m->{col} && length $m->{col}) ? $m->{col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $m->{'col'} && length $m->{'col'} ? : 2 0 2
Condition33%1/3
defined $m->{"col"} and length $m->{"col"}
!ll&&!rl&&r
002
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
11256 my $agg = $self->_grouped_totals($pipeline, {
11257 by => [@rows, @cols],
11258 fn => $m->{fn},
11259 val => $cv,
11260 as => $m->{as},
11261 2 });
11262 2 for my $row (@$agg) {
11263 8 ▶ my $rkey = join("\x00", map { $row->{$_} // '' } @rows);
Condition50%1/2
$row->{$_} // ""
l!l
80
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table50%1/2
A
A= $row->{$_}
Aresult
11
00
11264 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
11265 8 ▶ unless ($row_seen{$rkey}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($row_seen{$rkey}++) 8 0 8
11266 8 push @row_key_order, $rkey;
11267 8 ▶ $row_combos{$rkey} = { map { $_ => ($row->{$_} // '') } @rows };
Condition50%1/2
$row->{$_} // ""
l!l
80
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table50%1/2
A
A= $row->{$_}
Aresult
11
00
11268 }
11269 8 ▶ unless ($col_seen{$ckey}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($col_seen{$ckey}++) 2 6 8
11270 2 push @col_key_order, $ckey;
11271 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
11272 }
11273 8 $cells{$rkey}{$ckey}{$m->{as}} = $row->{$m->{as}};
11274 }
11275 }
11276  
11277 # -----------------------------------------------------------------------
11278 # Post-aggregation HAVING filters (h=<as>:<op>:<val>) applied row-by-row.
11279 # Each filter operates on a virtual row whose keys are the measure aliases.
11280 # -----------------------------------------------------------------------
11281 2 ▶ my @h_specs = @{ $self->every_param('h') // [] };
Condition50%1/2
$self->every_param("h") // []
l!l
20
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
11282 2 ▶ if (@h_specs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@h_specs) 0 2 2
11283 0 my @keep;
11284 0 for my $rkey (@row_key_order) {
11285 # Build a virtual row containing each measure's cell value
11286 # (using first col-combo as representative, or grand-total style).
11287 # For HAVING, we filter on the *row subtotal* value, not a single cell.
11288 # We'll compute a temp subtotal row for each row key.
11289 0 my %vrow;
11290 0 for my $m (@measures) {
11291 # Sum across cols for this row as representative value.
11292 0 my $v = 0;
11293 0 for my $ck (@col_key_order) {
11294 0 my $cv = $cells{$rkey}{$ck}{$m->{as}};
11295 0 ▶ $v += $cv if defined $cv;
Branch: 1 branch
BranchTrueFalseTotal
if defined $cv 0 0 0
11296 }
11297 0 $vrow{$m->{as}} = $v;
11298 }
11299 0 my $ok = 1;
11300 0 for my $hs (@h_specs) {
11301 0 my $passed = _apply_filter_spec([\%vrow], $hs);
11302 0 ▶ $ok = 0 unless @$passed;
Branch: 1 branch
BranchTrueFalseTotal
unless @$passed 0 0 0
11303 }
11304 0 ▶ push @keep, $rkey if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
11305 }
11306 0 @row_key_order = @keep;
11307 }
11308  
11309 # -----------------------------------------------------------------------
11310 # Top-N rows: keep only the top-N row groups (ranked by measure sum
11311 # across all col combos); aggregate the remaining rows as an "Other" row.
11312 # -----------------------------------------------------------------------
11313 {
11314 2 ▶ my $topn_n = _whole_number($self->param('topn')) // 0;
Condition50%1/2
_whole_number($self->param("topn")) // 0
l!l
02
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
11315 2 ▶ my $topn_col = $self->param('topn_col') // '';
Condition50%1/2
$self->param("topn_col") // ""
l!l
02
MC/DC0%0/1
$self->param("topn_col") // ""
$self->param("topn_col")
Truth table50%1/2
A
A= $self->param("topn_col")
Aresult
11
00
11316  
11317 2 ▶ if ($topn_n > 0 && @row_key_order > $topn_n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($topn_n > 0 and @row_key_order > $topn_n) 0 2 2
Condition33%1/3
$topn_n > 0 and @row_key_order > $topn_n
!ll&&!rl&&r
200
MC/DC0%0/2
$topn_n > 0 and @row_key_order > $topn_n
$topn_n > 0 @row_key_order > $topn_n
Truth table33%1/3
A and B
A= $topn_n > 0B= @row_key_order > $topn_n
ABresult
0X0
100
111
11318 0 my %m_aliases = map { $_->{as} => 1 } @measures;
11319 0 ▶ if (length $topn_col && !$m_aliases{$topn_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $topn_col and not $m_aliases{$topn_col}) 0 0 0
Condition0%0/3
length $topn_col and not $m_aliases{$topn_col}
!ll&&!rl&&r
000
MC/DC0%0/2
length $topn_col and not $m_aliases{$topn_col}
length $topn_col not $m_aliases{$topn_col}
Truth table0%0/3
A and not(B)
A= length $topn_colB= not $m_aliases{$topn_col}
ABresult
0X0
100
111
11320 0 return $self->render(
11321 text => $self->_i18n('error_topn_col', $topn_col),
11322 status => 400,
11323 );
11324 }
11325 0 ▶ my $sort_as = length($topn_col) ? $topn_col : $measures[0]{as};
Branch: 1 branch
BranchTrueFalseTotal
length $topn_col ? : 0 0 0
11326  
11327 # Sort rows by descending sum of sort_as across all column combos.
11328 my @sorted_rkeys = sort {
11329 0 ▶ (do { my $s = 0; $s += ($cells{$b}{$_}{$sort_as} // 0) for @col_key_order; $s })
Condition0%0/2
$cells{$b}{$_}{$sort_as} // 0
l!l
00
MC/DC0%0/1
$cells{$b}{$_}{$sort_as} // 0
$cells{$b}{$_}{$sort_as}
Truth table0%0/2
A
A= $cells{$b}{$_}{$sort_as}
Aresult
11
00
11330 <=>
11331 0 ▶ (do { my $s = 0; $s += ($cells{$a}{$_}{$sort_as} // 0) for @col_key_order; $s })
Condition0%0/2
$cells{$a}{$_}{$sort_as} // 0
l!l
00
MC/DC0%0/1
$cells{$a}{$_}{$sort_as} // 0
$cells{$a}{$_}{$sort_as}
Truth table0%0/2
A
A= $cells{$a}{$_}{$sort_as}
Aresult
11
00
11332 } @row_key_order;
11333  
11334 0 my @top_rkeys = @sorted_rkeys[0 .. $topn_n - 1];
11335 0 my @rest_rkeys = @sorted_rkeys[$topn_n .. $#sorted_rkeys];
11336  
11337 0 ▶ if (@rest_rkeys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rest_rkeys) { } 0 0 0
11338 0 my %top_rkey_set = map { $_ => 1 } @top_rkeys;
11339 my $other_rec = [
11340 grep {
11341 0 my $r = $_;
11342 0 ▶ !$top_rkey_set{ join("\x00", map { $r->{$_} // '' } @rows) }
Condition0%0/2
$r->{$_} // ""
l!l
00
MC/DC0%0/1
$r->{$_} // ""
$r->{$_}
Truth table0%0/2
A
A= $r->{$_}
Aresult
11
00
11343 } @$records
11344 ];
11345 0 ▶ if (@$other_rec) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$other_rec) { } 0 0 0
11346 0 my $ork = '__topn_other__';
11347 0 $row_combos{$ork} = { map { $_ => 'Other' } @rows };
11348 0 for my $m (@measures) {
11349 0 ▶ my $cv = (defined $m->{col} && length $m->{col}) ? $m->{col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $m->{'col'} && length $m->{'col'} ? : 0 0 0
Condition0%0/3
defined $m->{"col"} and length $m->{"col"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $m->{"col"} and length $m->{"col"}
defined $m->{"col"} length $m->{"col"}
Truth table0%0/3
A and B
A= defined $m->{"col"}B= length $m->{"col"}
ABresult
0X0
100
111
11350 my $oa = $self->_grouped_totals(
11351 { source => undef, records => $other_rec },
11352 { by => [@cols], fn => $m->{fn}, val => $cv, as => $m->{as} },
11353 0 );
11354 0 for my $row (@$oa) {
11355 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
11356 0 $cells{$ork}{$ck}{$m->{as}} = $row->{$m->{as}};
11357 }
11358 }
11359 0 @row_key_order = (@top_rkeys, $ork);
11360 } else {
11361 0 @row_key_order = @top_rkeys;
11362 }
11363 } else {
11364 0 @row_key_order = @top_rkeys;
11365 }
11366 }
11367 }
11368  
11369 # -----------------------------------------------------------------------
11370 # Subtotals and grand total (three additional _grouped_totals calls
11371 # per measure when totals=1).
11372 # -----------------------------------------------------------------------
11373 2 my (%row_subtotals, %col_subtotals, %grand_total);
11374  
11375 2 ▶ if ($show_totals) {
Branch: 1 branch
BranchTrueFalseTotal
if ($show_totals) 0 2 2
11376 0 for my $m (@measures) {
11377 0 ▶ my $cv = (defined $m->{col} && length $m->{col}) ? $m->{col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $m->{'col'} && length $m->{'col'} ? : 0 0 0
Condition0%0/3
defined $m->{"col"} and length $m->{"col"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $m->{"col"} and length $m->{"col"}
defined $m->{"col"} length $m->{"col"}
Truth table0%0/3
A and B
A= defined $m->{"col"}B= length $m->{"col"}
ABresult
0X0
100
111
11378  
11379 # Row subtotals: group by @rows only.
11380 my $rsub = $self->_grouped_totals($pipeline, {
11381 by => [@rows],
11382 fn => $m->{fn},
11383 val => $cv,
11384 as => $m->{as},
11385 0 });
11386 0 for my $r (@$rsub) {
11387 0 ▶ my $rk = join("\x00", map { $r->{$_} // '' } @rows);
Condition0%0/2
$r->{$_} // ""
l!l
00
MC/DC0%0/1
$r->{$_} // ""
$r->{$_}
Truth table0%0/2
A
A= $r->{$_}
Aresult
11
00
11388 0 $row_subtotals{$rk}{$m->{as}} = $r->{$m->{as}};
11389 }
11390  
11391 # Column subtotals: group by @cols only.
11392 0 ▶ if (@cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cols) 0 0 0
11393 my $csub = $self->_grouped_totals($pipeline, {
11394 by => [@cols],
11395 fn => $m->{fn},
11396 val => $cv,
11397 as => $m->{as},
11398 0 });
11399 0 for my $c (@$csub) {
11400 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
11401 0 $col_subtotals{$ck}{$m->{as}} = $c->{$m->{as}};
11402 }
11403 }
11404  
11405 # Grand total: group by nothing (all rows -> one result row).
11406 my $gtot = $self->_grouped_totals($pipeline, {
11407 by => [],
11408 fn => $m->{fn},
11409 val => $cv,
11410 as => $m->{as},
11411 0 });
11412 0 ▶ $grand_total{$m->{as}} = $gtot->[0]{$m->{as}} if @$gtot;
Branch: 1 branch
BranchTrueFalseTotal
if @$gtot 0 0 0
11413 }
11414 }
11415  
11416 # -----------------------------------------------------------------------
11417 # max_cols: collapse the tail of column combos beyond top-N into "Other".
11418 # The top-N are ranked by the first measure's column subtotal (or cell sum).
11419 # -----------------------------------------------------------------------
11420 2 ▶ 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 2 2
Condition33%1/3
$max_cols_n > 0 and @col_key_order > $max_cols_n
!ll&&!rl&&r
200
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
11421 0 my $first_as = $measures[0]{as};
11422 my @sorted_ckeys = sort {
11423 0 ( $show_totals
11424 ? ($col_subtotals{$b}{$first_as} // 0)
11425 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
11426 )
11427 <=>
11428 ( $show_totals
11429 ? ($col_subtotals{$a}{$first_as} // 0)
11430 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
11431 )
11432 } @col_key_order;
11433 0 my @top_ckeys = @sorted_ckeys[0 .. $max_cols_n - 1];
11434 0 my @rest_ckeys = @sorted_ckeys[$max_cols_n .. $#sorted_ckeys];
11435 0 ▶ if (@rest_ckeys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rest_ckeys) { } 0 0 0
11436 0 my $other_key = '__other__';
11437 0 $col_combos{$other_key} = { map { $_ => 'Other' } @cols };
11438 0 for my $rk (@row_key_order) {
11439 0 for my $m (@measures) {
11440 0 my ($v, $have) = (0, 0);
11441 0 for my $ck (@rest_ckeys) {
11442 0 my $cv = $cells{$rk}{$ck}{$m->{as}};
11443 0 ▶ if (defined $cv) { $v += $cv; $have = 1 }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cv) 0 0 0
11444 }
11445 0 ▶ $cells{$rk}{$other_key}{$m->{as}} = $have ? $v : undef;
Branch: 1 branch
BranchTrueFalseTotal
$have ? : 0 0 0
11446 }
11447 }
11448 0 @col_key_order = (@top_ckeys, $other_key);
11449 } else {
11450 0 @col_key_order = @top_ckeys;
11451 }
11452 }
11453  
11454 # -----------------------------------------------------------------------
11455 # Export path: build flat records from the grid.
11456 # -----------------------------------------------------------------------
11457 2 ▶ 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) 1 1 2
Condition66%2/3
$format and $format =~ /\A(?:csv|sqlite|sql|json|xlsx)\z/u
!ll&&!rl&&r
101
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
11458 1 my @grid_records;
11459 1 for my $rk (@row_key_order) {
11460 4 for my $ck (@col_key_order) {
11461 4 my %rec;
11462 4 ▶ $rec{$_} = $row_combos{$rk}{$_} // '' for @rows;
Condition50%1/2
$row_combos{$rk}{$_} // ""
l!l
40
MC/DC0%0/1
$row_combos{$rk}{$_} // ""
$row_combos{$rk}{$_}
Truth table50%1/2
A
A= $row_combos{$rk}{$_}
Aresult
11
00
11463 4 ▶ $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
11464 4 ▶ $rec{$_->{as}} = $cells{$rk}{$ck}{$_->{as}} // '' for @measures;
Condition50%1/2
$cells{$rk}{$ck}{$_->{"as"}} // ""
l!l
40
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
11465 4 push @grid_records, \%rec;
11466 }
11467 }
11468 1 my @export_cols = (@rows, @cols, map { $_->{as} } @measures);
11469 1 ▶ return $self->_render_csv(\@grid_records, \@export_cols, 'pivot')
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "csv" 1 0 1
11470 if $format eq 'csv';
11471 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
11472 if $format eq 'sqlite' || $format eq 'sql';
11473 0 ▶ return $self->_render_json(\@grid_records, \@export_cols, 'pivot')
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "json" 0 0 0
11474 if $format eq 'json';
11475 0 ▶ if ($format eq 'xlsx') {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "xlsx") 0 0 0
11476 0 $self->stash(buffer => 0);
11477 0 require Excel::Writer::XLSX;
11478 0 my $out = '';
11479 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
11480 or return $self->render(text => 'Cannot open XLSX buffer', status => 500);
11481 0 my $wb = Excel::Writer::XLSX->new($fh);
11482 0 my $ws = $wb->add_worksheet('pivot');
11483 0 $ws->write_row(0, 0, \@export_cols);
11484 0 my $row_idx = 1;
11485 0 for my $rec (@grid_records) {
11486 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
11487 }
11488 0 $wb->close;
11489 0 $self->res->headers->content_type(
11490 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
11491 );
11492 0 $self->res->headers->content_disposition(
11493 'attachment; filename="pivot.xlsx"'
11494 );
11495 0 return $self->render(data => $out);
11496 }
11497 }
11498  
11499 # -----------------------------------------------------------------------
11500 # Pagination: slice @row_key_order using the N+1 trick.
11501 # Must come after the export early-return above (exports use the full set)
11502 # and after subtotals/grand total (computed from $pipeline, not @row_key_order).
11503 # -----------------------------------------------------------------------
11504 1 my ($page, $per_page, $offset) = $self->_pagination;
11505 1 my $total_row_groups = scalar @row_key_order;
11506 1 ▶ my $piv_has_next = ($total_row_groups > $offset + $per_page) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$total_row_groups > $offset + $per_page ? : 0 1 1
11507 1 ▶ @row_key_order = $offset < $total_row_groups
Branch: 2 branches
BranchTrueFalseTotal
$offset < $total_row_groups ? : 1 0 1
$piv_has_next ? : 0 1 1
11508 ? @row_key_order[$offset .. ($piv_has_next ? $offset + $per_page - 1 : $#row_key_order)]
11509 : ();
11510  
11511 1 my $piv_page_url = $self->req->url->clone;
11512 1 $piv_page_url->query->remove('page')->remove('per_page');
11513  
11514 # -----------------------------------------------------------------------
11515 # Build the template-ready data structure.
11516 # -----------------------------------------------------------------------
11517 my @col_combo_list = map {
11518 1 my $ck = $_;
11519 {
11520 key => $ck,
11521 dim_vals => $col_combos{$ck},
11522 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
11523 }
11524 } @col_key_order;
11525  
11526 1 my @grid_rows;
11527 1 for my $rk (@row_key_order) {
11528 4 my %row_cells;
11529 4 for my $ck (@col_key_order) {
11530 4 ▶ $row_cells{$ck} = $cells{$rk}{$ck} // {};
Condition50%1/2
$cells{$rk}{$ck} // {}
l!l
40
MC/DC0%0/1
$cells{$rk}{$ck} // {}
$cells{$rk}{$ck}
Truth table50%1/2
A
A= $cells{$rk}{$ck}
Aresult
11
00
11531 }
11532 push @grid_rows, {
11533 row_vals => $row_combos{$rk},
11534 cells => \%row_cells,
11535 4 ▶ subtotals => $show_totals ? ($row_subtotals{$rk} // {}) : {},
Branch: 1 branch
BranchTrueFalseTotal
$show_totals ? : 0 4 4
Condition0%0/2
$row_subtotals{$rk} // {}
l!l
00
MC/DC0%0/1
$row_subtotals{$rk} // {}
$row_subtotals{$rk}
Truth table0%0/2
A
A= $row_subtotals{$rk}
Aresult
11
00
11536 };
11537 }
11538  
11539 1 (my $left_label = $left_spec) =~ s/\A(?:table:|path:|url:)//;
11540  
11541 1 my ($platform, $language) = $self->_resolve_template;
11542 1 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 1 1
$back2 ? : 0 1 1
Condition22%2/9
$back2 // $back
l!l&&r!l&&!r
010
$back2_lbl or "Back"
l!l
00
$self->param("back_label") // "Back to table"
l!l
01
$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
11543 handler => 'tt',
11544 template => "$platform/$language/pivot",
11545 format => 'html',
11546 title => 'Pivot: ' . join(', ', @rows),
11547 rows_dims => \@rows,
11548 cols_dims => \@cols,
11549 measures => \@measures,
11550 col_combos => \@col_combo_list,
11551 grid_rows => \@grid_rows,
11552 show_totals => $show_totals,
11553 col_subtotals => \%col_subtotals,
11554 grand_total => \%grand_total,
11555 scheme => $scheme,
11556 left_spec => $left_spec,
11557 left_label => $left_label,
11558 back_url => ($back2 // $back),
11559 back_label => ($back2 ? ($back2_lbl || 'Back') : ($self->param('back_label') // 'Back to table')),
11560 ($back2 ? (back2_url => $back, back2_label => ($self->param('back_label') // 'Back to table')) : ()),
11561 page => $page,
11562 per_page => $per_page,
11563 has_next => $piv_has_next,
11564 page_count => _page_count($total_row_groups, $per_page),
11565 page_base_url => $piv_page_url->to_string,
11566 total_row_groups => $total_row_groups,
11567 language => $language,
11568 );
11569 }
11570  
11571 =head2 stats_view
11572  
11573 C<GET /stats> -- Column statistics panel.
11574  
11575 Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus C<p=N>
11576 to choose the percentile column (1 to 100, default 95), and C<range=name> with
11577 C<rcol=column> for a relative window of rows. Displays per-column statistics:
11578 row_count, null_count, distinct_count, and for numeric columns min, max, range,
11579 mean, median, the chosen percentile and sample standard deviation; first and
11580 last are shown for every column, being the first and last value the column
11581 holds.
11582  
11583 C<distinct_count> is computed through C<_grouped_totals>, so it agrees with the
11584 pivot view. The numeric statistics are computed in Perl by sorting the column's
11585 values, through the same C<_percentile_of>, C<_median_of>, C<_stdev_of> and
11586 C<_range_of> arithmetic the pivot's C<median>, C<pN>, C<stdev> and C<range>
11587 measures use -- so a median here and a median measure there are the same number.
11588  
11589 =head3 API SPECIFICATION
11590  
11591 =head4 INPUT
11592  
11593 The query parameters above, with C<l=> required.
11594  
11595 =head4 OUTPUT
11596  
11597 200 text/html The statistics.
11598 400 text/plain 'Missing l= parameter', or error_stats_percentile when p= is
11599 not a whole number from 1 to 100.
11600 404 text/plain The source cannot be opened.
11601  
11602 =head3 FORMAL SPECIFICATION
11603  
11604 stats_view
11605 l?, p? : seq Char
11606 response! : HTTP
11607 ──────────
11608 l? = ⟨⟩ ⇒ response!.status = 400
11609 p? ≠ ⟨⟩ ∧ p? ∉ { "1" .. "100" } ⇒ response!.status = 400
11610  
11611 =cut
11612  
11613 47 ▶sub stats_view ($self) {
Subroutine stats_view: called CC=28 SCAR=38.3
Pod documented
11614 47 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
461
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
11615 47 ▶ return $self->render(text => 'Missing l= parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 2 45 47
11616 unless length $left_spec;
11617  
11618 # The percentile column is the reader's to choose; an unreadable one is a
11619 # 400 rather than a silent 95, so the page never claims a level it did not
11620 # apply.
11621 45 my $pct_arg = $self->param('p');
11622 45 my $percentile = 95;
11623 45 ▶ if (defined $pct_arg && length $pct_arg) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pct_arg and length $pct_arg) 0 45 45
Condition33%1/3
defined $pct_arg and length $pct_arg
!ll&&!rl&&r
4500
MC/DC0%0/2
defined $pct_arg and length $pct_arg
defined $pct_arg length $pct_arg
Truth table33%1/3
A and B
A= defined $pct_argB= length $pct_arg
ABresult
0X0
100
111
11624 0 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless $pct_arg =~ /\A\d{1,3}\z/u and $pct_arg >= 1 and $pct_arg <= 100 0 0 0
Condition0%0/6
$pct_arg =~ /\A\d{1,3}\z/u and $pct_arg >= 1 and $pct_arg <= 100
!ll&&!rl&&r
000
$pct_arg =~ /\A\d{1,3}\z/u and $pct_arg >= 1
!ll&&!rl&&r
000
MC/DC0%0/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 table0%0/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
11625 text => $self->_i18n('error_stats_percentile', $pct_arg),
11626 status => 400,
11627 ) unless $pct_arg =~ /\A\d{1,3}\z/ && $pct_arg >= 1 && $pct_arg <= 100;
11628 0 $percentile = $pct_arg + 0;
11629 }
11630  
11631 45 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
045
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
11632 45 my $back2 = _safe_back_url($self->param('back2'));
11633 45 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
045
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
11634  
11635 45 my ($src, $records, $columns) = $self->_run_pipeline_source;
11636 45 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 3 42 45
11637 unless defined $records;
11638  
11639 42 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
11640 42 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 41 42
11641  
11642 41 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 40 41
11643  
11644 40 my $row_count = scalar @$records;
11645 40 my $pipeline = { source => $src, records => $records };
11646  
11647 40 my @stats;
11648 40 for my $col (@{$columns}) {
11649 # null_count = rows where cell is undef or '' (phase 2 definition).
11650 240 ▶ my @nonnull = grep { defined $_->{$col} && length($_->{$col}) } @$records;
Condition33%1/3
defined $_->{$col} && length $_->{$col}
!ll&&!rl&&r
001440
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
11651 240 my $null_count = $row_count - scalar @nonnull;
11652  
11653 # distinct_count via _grouped_totals (count groups by the column).
11654 240 my $dist_rows = $self->_grouped_totals($pipeline, {
11655 by => [$col],
11656 fn => 'count',
11657 as => 'cnt',
11658 });
11659 240 my $distinct_count = scalar @$dist_rows;
11660  
11661 # first/last: the value the column holds in the first and the last row
11662 # that has one. $nonnull is in row order, so no second pass is needed
11663 # and the two agree with the pivot's first() and last() measures.
11664 240 ▶ my $first_val = $nonnull[0] ? $nonnull[0]{$col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$nonnull[0] ? : 240 0 240
11665 240 ▶ my $last_val = $nonnull[-1] ? $nonnull[-1]{$col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$nonnull[-1] ? : 240 0 240
11666  
11667 # Numeric statistics, through the same arithmetic the pivot measures use.
11668 240 my @nums = grep { defined $_ } map { _numeric_cell($_->{$col}) } @nonnull;
11669 240 my ($min_val, $max_val, $avg_val, $median_val, $range_val, $pct_val, $stdev_val);
11670 240 ▶ if (@nums) {
Branch: 1 branch
BranchTrueFalseTotal
if (@nums) 80 160 240
11671 80 my @sorted = sort { $a <=> $b } @nums;
11672 80 $min_val = $sorted[0];
11673 80 $max_val = $sorted[-1];
11674 80 my $sum = 0;
11675 80 $sum += $_ for @nums;
11676 80 $avg_val = $sum / @nums;
11677 # _median_of is _percentile_of at 50; a stdev of one value is undef,
11678 # which the template shows as a dash rather than as a spread of 0.
11679 80 $median_val = _median_of(\@sorted);
11680 80 $range_val = _range_of(\@sorted);
11681 80 $pct_val = _percentile_of(\@sorted, $percentile);
11682 80 $stdev_val = _stdev_of(\@sorted);
11683 }
11684  
11685 240 ▶ push @stats, {
Branch: 2 branches
BranchTrueFalseTotal
defined $min_val ? : 80 160 240
defined $stdev_val ? : 80 0 80
11686 col => $col,
11687 row_count => $row_count,
11688 null_count => $null_count,
11689 distinct_count => $distinct_count,
11690 first => $first_val,
11691 last => $last_val,
11692 (defined $min_val ? (
11693 min => $min_val,
11694 max => $max_val,
11695 range => sprintf('%.4g', $range_val),
11696 avg => sprintf('%.4g', $avg_val),
11697 median => sprintf('%.4g', $median_val),
11698 pct => sprintf('%.4g', $pct_val),
11699 stdev => (defined $stdev_val ? sprintf('%.4g', $stdev_val) : undef),
11700 ) : ()),
11701 };
11702 }
11703  
11704 40 (my $left_label = $left_spec) =~ s/\A(?:table:|path:|url:)//;
11705  
11706 40 my ($platform, $language) = $self->_resolve_template;
11707 40 ▶ $self->render(
Branch: 3 branches
BranchTrueFalseTotal
CORE::index($back, '?') != -1 ? : 0 40 40
$back2 ? : 0 40 40
$back2 ? : 0 40 40
Condition22%2/9
$back2 // $back
l!l&&r!l&&!r
0400
$back2_lbl or "Back"
l!l
00
$self->param("back_label") // "Back to table"
l!l
040
$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
11708 handler => 'tt',
11709 template => "$platform/$language/stats",
11710 format => 'html',
11711 title => 'Column statistics',
11712 stats => \@stats,
11713 stats_percentile => $percentile,
11714 row_count => $row_count,
11715 left_spec => $left_spec,
11716 left_label => $left_label,
11717 drill_back_url => $back,
11718 drill_sep => (CORE::index($back, '?') >= 0 ? '&' : '?'),
11719 stats_url => $self->req->url->path_query,
11720 back_url => ($back2 // $back),
11721 back_label => ($back2 ? ($back2_lbl || 'Back') : ($self->param('back_label') // 'Back to table')),
11722 ($back2 ? (back2_url => $back, back2_label => ($self->param('back_label') // 'Back to table')) : ()),
11723 language => $language,
11724 );
11725 }
11726  
11727 # ---------------------------------------------------------------------------
11728 # Calculated-field CRUD (POST /calc/save, POST /calc/delete, GET /calc/list)
11729 # ---------------------------------------------------------------------------
11730  
11731 6 ▶sub calc_save ($self) {
Subroutine calc_save: called CC=7 SCAR=19.5
Pod documented
11732 6 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
51
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
11733 6 ▶ my $name = $self->param('name') // '';
Condition50%1/2
$self->param("name") // ""
l!l
60
MC/DC0%0/1
$self->param("name") // ""
$self->param("name")
Truth table50%1/2
A
A= $self->param("name")
Aresult
11
00
11734 6 ▶ my $expr = $self->param('expr') // '';
Condition100%2/2
$self->param("expr") // ""
l!l
51
MC/DC100%1/1
$self->param("expr") // ""
$self->param("expr")
Truth table100%2/2
A
A= $self->param("expr")
Aresult
11
00
11735  
11736 6 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 5 6
11737 unless length $spec;
11738 5 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/u 2 3 5
11739 json => { error => $self->_i18n('error_calc_name', $name) },
11740 status => 400,
11741 ) unless $name =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/;
11742 3 ▶ return $self->render(json => { error => 'expr= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $expr 1 2 3
11743 unless length $expr;
11744  
11745 2 my $models = $self->_read_models;
11746 2 $models->{fields}{$spec}{$name} = $expr;
11747 2 $self->_write_models($models);
11748 2 $self->render(json => { ok => 1 });
11749 }
11750  
11751 2 ▶sub calc_delete ($self) {
Subroutine calc_delete: called CC=4 SCAR=13.9
Pod documented
11752 2 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
11
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
11753 2 ▶ my $name = $self->param('name') // '';
Condition50%1/2
$self->param("name") // ""
l!l
20
MC/DC0%0/1
$self->param("name") // ""
$self->param("name")
Truth table50%1/2
A
A= $self->param("name")
Aresult
11
00
11754  
11755 2 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 1 2
11756 unless length $spec;
11757  
11758 1 my $models = $self->_read_models;
11759 1 delete $models->{fields}{$spec}{$name};
11760 1 $self->_write_models($models);
11761 1 $self->render(json => { ok => 1 });
11762 }
11763  
11764 5 ▶sub calc_list ($self) {
Subroutine calc_list: called CC=4 SCAR=13.9
Pod documented
11765 5 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
41
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
11766 5 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 3 5
11767 unless length $spec;
11768  
11769 3 my $models = $self->_read_models;
11770 3 ▶ $self->render(json => { fields => $models->{fields}{$spec} // {} });
Condition100%2/2
$models->{"fields"}{$spec} // {}
l!l
21
MC/DC100%1/1
$models->{"fields"}{$spec} // {}
$models->{"fields"}{$spec}
Truth table100%2/2
A
A= $models->{"fields"}{$spec}
Aresult
11
00
11771 }
11772  
11773 # ---------------------------------------------------------------------------
11774 # Named-group CRUD (POST /groups/save, POST /groups/delete, GET /groups/list)
11775 # ---------------------------------------------------------------------------
11776  
11777 5 ▶sub groups_save ($self) {
Subroutine groups_save: called CC=8 SCAR=20.8
Pod documented
11778 5 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
41
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
11779 5 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
41
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
11780 5 ▶ my $group_name = $self->param('group') // '';
Condition100%2/2
$self->param("group") // ""
l!l
41
MC/DC100%1/1
$self->param("group") // ""
$self->param("group")
Truth table100%2/2
A
A= $self->param("group")
Aresult
11
00
11781  
11782 # The panel sends one values= holding a line for each value; a script may just
11783 # as well repeat the parameter.
11784 5 ▶ my @values = map { split /\r?\n/ } @{ $self->every_param('values') // [] };
Condition50%1/2
$self->every_param("values") // []
l!l
50
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
11785  
11786 5 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 4 5
11787 unless length $spec;
11788 4 ▶ return $self->render(json => { error => 'col= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 1 3 4
11789 unless length $col;
11790 3 ▶ return $self->render(json => { error => 'group= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $group_name 1 2 3
11791 unless length $group_name;
11792  
11793 2 my $models = $self->_read_models;
11794 2 $models->{groups}{$spec}{$col}{$group_name} = \@values;
11795 2 $self->_write_models($models);
11796 2 $self->render(json => { ok => 1 });
11797 }
11798  
11799 2 ▶sub groups_delete ($self) {
Subroutine groups_delete: called CC=8 SCAR=21.3
Pod documented
11800 2 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition50%1/2
$self->param("l") // ""
l!l
20
MC/DC0%0/1
$self->param("l") // ""
$self->param("l")
Truth table50%1/2
A
A= $self->param("l")
Aresult
11
00
11801 2 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
11
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
11802 2 ▶ my $group_name = $self->param('group') // '';
Condition100%2/2
$self->param("group") // ""
l!l
11
MC/DC100%1/1
$self->param("group") // ""
$self->param("group")
Truth table100%2/2
A
A= $self->param("group")
Aresult
11
00
11803  
11804 2 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 0 2 2
11805 unless length $spec;
11806  
11807 2 my $models = $self->_read_models;
11808 2 ▶ if (length $col && length $group_name) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $col and length $group_name) { } 1 1 2
elsif (length $col) { } 0 1 1
Condition66%2/3
length $col and length $group_name
!ll&&!rl&&r
101
MC/DC50%1/2
length $col and length $group_name
length $col length $group_name
Truth table66%2/3
A and B
A= length $colB= length $group_name
ABresult
0X0
100
111
11809 1 delete $models->{groups}{$spec}{$col}{$group_name};
11810 } elsif (length $col) {
11811 0 delete $models->{groups}{$spec}{$col};
11812 } else {
11813 1 delete $models->{groups}{$spec};
11814 }
11815 2 $self->_write_models($models);
11816 2 $self->render(json => { ok => 1 });
11817 }
11818  
11819 6 ▶sub groups_list ($self) {
Subroutine groups_list: called CC=4 SCAR=13.9
Pod documented
11820 6 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
51
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
11821 6 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 4 6
11822 unless length $spec;
11823  
11824 4 my $models = $self->_read_models;
11825 4 ▶ $self->render(json => { groups => $models->{groups}{$spec} // {} });
Condition100%2/2
$models->{"groups"}{$spec} // {}
l!l
22
MC/DC100%1/1
$models->{"groups"}{$spec} // {}
$models->{"groups"}{$spec}
Truth table100%2/2
A
A= $models->{"groups"}{$spec}
Aresult
11
00
11826 }
11827  
11828 # ---------------------------------------------------------------------------
11829 # Date-pattern CRUD (POST /dates/save, POST /dates/delete, GET /dates/list)
11830 # ---------------------------------------------------------------------------
11831  
11832 # dates_save: POST /dates/save?l=<spec>&col=<col>&pattern=<fmt>[&time=<fmt>][&as=timestamp]
11833 # Stores a strptime-style date normalisation pattern for $col in models.json.
11834 # Only the three patterns in %ALLOWED_DATE_PATTERNS are accepted, and only the
11835 # two in %ALLOWED_TIME_PATTERNS beside one of them.
11836 #
11837 # A pattern on its own is stored as the string it has always been, so an
11838 # existing entry keeps its meaning. A time, or as=timestamp, stores the hash
11839 # shape { date =>, time =>, as => } that Calc::date_normalise reads, and which
11840 # normalises the column to 'YYYY-MM-DDTHH:MM:SS' -- the shape the date
11841 # comparisons already read to the second, so a last_24_hours window filters on
11842 # a column that has a pattern of this kind.
11843 9 ▶sub dates_save ($self) {
Subroutine dates_save: called CC=17 SCAR=32.8
Pod documented
11844 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
11845 9 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
81
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
11846 9 ▶ my $pattern = $self->param('pattern') // '';
Condition50%1/2
$self->param("pattern") // ""
l!l
90
MC/DC0%0/1
$self->param("pattern") // ""
$self->param("pattern")
Truth table50%1/2
A
A= $self->param("pattern")
Aresult
11
00
11847 9 ▶ my $time = $self->param('time') // '';
Condition50%1/2
$self->param("time") // ""
l!l
09
MC/DC0%0/1
$self->param("time") // ""
$self->param("time")
Truth table50%1/2
A
A= $self->param("time")
Aresult
11
00
11848 9 ▶ my $as = $self->param('as') // '';
Condition50%1/2
$self->param("as") // ""
l!l
09
MC/DC0%0/1
$self->param("as") // ""
$self->param("as")
Truth table50%1/2
A
A= $self->param("as")
Aresult
11
00
11849  
11850 9 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 8 9
11851 unless length $spec;
11852 8 ▶ return $self->render(json => { error => 'col= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 1 7 8
11853 unless length $col;
11854 return $self->render(
11855 json => { error => $self->_i18n('error_date_pattern', $pattern) },
11856 status => 400,
11857 7 ▶ ) unless $ALLOWED_DATE_PATTERNS{$pattern};
Branch: 1 branch
BranchTrueFalseTotal
unless $ALLOWED_DATE_PATTERNS{$pattern} 2 5 7
11858 return $self->render(
11859 json => { error => $self->_i18n('error_date_time_pattern', $time) },
11860 status => 400,
11861 5 ▶ ) if length($time) && !$ALLOWED_TIME_PATTERNS{$time};
Branch: 1 branch
BranchTrueFalseTotal
if length $time and not $ALLOWED_TIME_PATTERNS{$time} 0 5 5
Condition33%1/3
length $time and not $ALLOWED_TIME_PATTERNS{$time}
!ll&&!rl&&r
500
MC/DC0%0/2
length $time and not $ALLOWED_TIME_PATTERNS{$time}
length $time not $ALLOWED_TIME_PATTERNS{$time}
Truth table33%1/3
A and not(B)
A= length $timeB= not $ALLOWED_TIME_PATTERNS{$time}
ABresult
0X0
100
111
11862 5 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
if length $as and $as ne "timestamp" 0 5 5
Condition33%1/3
length $as and $as ne "timestamp"
!ll&&!rl&&r
500
MC/DC0%0/2
length $as and $as ne "timestamp"
length $as $as ne "timestamp"
Truth table33%1/3
A and B
A= length $asB= $as ne "timestamp"
ABresult
0X0
100
111
11863 json => { error => $self->_i18n('error_date_as', $as) },
11864 status => 400,
11865 ) if length($as) && $as ne 'timestamp';
11866  
11867 5 ▶ my $stored = (length($time) || length($as))
Branch: 3 branches
BranchTrueFalseTotal
length $time || length $as ? : 0 5 5
length $time ? : 0 0 0
length $as ? : 0 0 0
Condition33%1/3
length $time or length $as
l!l&&r!l&&!r
005
MC/DC0%0/2
length $time or length $as
length $time length $as
Truth table33%1/3
A or B
A= length $timeB= length $as
ABresult
1X1
011
000
11868 ? { date => $pattern, (length($time) ? (time => $time) : ()), (length($as) ? (as => $as) : ()) }
11869 : $pattern;
11870  
11871 5 my $models = $self->_read_models;
11872 5 $models->{date_patterns}{$spec}{$col} = $stored;
11873 5 $self->_write_models($models);
11874 5 $self->render(json => { ok => 1 });
11875 }
11876  
11877 # dates_delete: POST /dates/delete?l=<spec>&col=<col>
11878 # Removes the pattern for $col (or all patterns for $spec when col is absent).
11879 4 ▶sub dates_delete ($self) {
Subroutine dates_delete: called CC=5 SCAR=16.2
Pod documented
11880 4 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition50%1/2
$self->param("l") // ""
l!l
40
MC/DC0%0/1
$self->param("l") // ""
$self->param("l")
Truth table50%1/2
A
A= $self->param("l")
Aresult
11
00
11881 4 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
31
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
11882  
11883 4 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 0 4 4
11884 unless length $spec;
11885  
11886 4 my $models = $self->_read_models;
11887 4 ▶ if (length $col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $col) { } 3 1 4
11888 3 delete $models->{date_patterns}{$spec}{$col};
11889 } else {
11890 1 delete $models->{date_patterns}{$spec};
11891 }
11892 4 $self->_write_models($models);
11893 4 $self->render(json => { ok => 1 });
11894 }
11895  
11896 # dates_list: GET /dates/list?l=<spec>
11897 # Returns { patterns: { col: pattern, ... } } for $spec, where a pattern is the
11898 # date-format string it has always been or, for a column that also holds a time,
11899 # { date =>, time =>, as => }.
11900 7 ▶sub dates_list ($self) {
Subroutine dates_list: called CC=4 SCAR=13.9
Pod documented
11901 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
11902 7 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 5 7
11903 unless length $spec;
11904  
11905 5 my $models = $self->_read_models;
11906 5 ▶ $self->render(json => { patterns => $models->{date_patterns}{$spec} // {} });
Condition100%2/2
$models->{"date_patterns"}{$spec} // {}
l!l
32
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
11907 }
11908  
11909 # ---------------------------------------------------------------------------
11910 # Stored-lookup CRUD (POST /lookups/save, POST /lookups/delete, GET /lookups/list)
11911 # ---------------------------------------------------------------------------
11912  
11913 # lookups_save: POST /lookups/save?l=<spec>&name=<ident>&file=<path>&key=<col>
11914 # [&col=<col>][&fields=<col>[,<col>...]][&default=<value>]
11915 # Stores models.json lookups.<spec>.<name>. The file is read now, so a file
11916 # outside data_dir, a missing one, one too large, and a key or field it does not
11917 # have are all 400s here rather than on the next page. fields= may repeat or
11918 # hold a comma-separated list; without it every column but the key is added.
11919 6 ▶sub lookups_save ($self) {
Subroutine lookups_save: called CC=14 SCAR=26.4
Pod documented
11920 6 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
51
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
11921 6 ▶ my $name = $self->param('name') // '';
Condition100%2/2
$self->param("name") // ""
l!l
51
MC/DC100%1/1
$self->param("name") // ""
$self->param("name")
Truth table100%2/2
A
A= $self->param("name")
Aresult
11
00
11922 6 ▶ my $key = $self->param('key') // '';
Condition100%2/2
$self->param("key") // ""
l!l
42
MC/DC100%1/1
$self->param("key") // ""
$self->param("key")
Truth table100%2/2
A
A= $self->param("key")
Aresult
11
00
11923 6 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
15
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
11924 6 ▶ my @fields = grep { length } map { split /,/ } @{ $self->every_param('fields') // [] };
Condition50%1/2
$self->every_param("fields") // []
l!l
60
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
11925  
11926 6 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 5 6
11927 unless length $spec;
11928 5 ▶ return $self->render(json => { error => $self->_i18n('error_lookup_name', $name) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$LOOKUP_NAME_RE/u 1 4 5
11929 unless $name =~ $LOOKUP_NAME_RE;
11930 4 ▶ return $self->render(json => { error => 'key= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $key 1 3 4
11931 unless length $key;
11932  
11933 3 ▶ my %def = (
Branch: 3 branches
BranchTrueFalseTotal
length $col ? : 1 2 3
@fields ? : 1 2 3
defined $self->param('default') ? : 0 3 3
Condition50%1/2
$self->param("file") // ""
l!l
30
MC/DC0%0/1
$self->param("file") // ""
$self->param("file")
Truth table50%1/2
A
A= $self->param("file")
Aresult
11
00
11934 file => $self->param('file') // '',
11935 key => $key,
11936 (length $col ? (col => $col) : ()),
11937 (@fields ? (fields => \@fields) : ()),
11938 (defined $self->param('default') ? (default => $self->param('default')) : ()),
11939 );
11940 3 my $ok = eval { $self->_load_lookup({ %def, name => $name }); 1 };
11941 3 ▶ return $self->render(json => { error => _tidy_error($@) }, status => 400) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 2 1 3
11942  
11943 1 my $models = $self->_read_models;
11944 1 $models->{lookups}{$spec}{$name} = \%def;
11945 1 $self->_write_models($models);
11946 1 $self->render(json => { ok => 1 });
11947 }
11948  
11949 # lookups_delete: POST /lookups/delete?l=<spec>[&name=<ident>]
11950 # Removes one lookup, or every lookup of $spec when name= is absent.
11951 3 ▶sub lookups_delete ($self) {
Subroutine lookups_delete: called CC=5 SCAR=16.1
Pod documented
11952 3 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
21
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
11953 3 ▶ my $name = $self->param('name') // '';
Condition100%2/2
$self->param("name") // ""
l!l
12
MC/DC100%1/1
$self->param("name") // ""
$self->param("name")
Truth table100%2/2
A
A= $self->param("name")
Aresult
11
00
11954  
11955 3 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 2 3
11956 unless length $spec;
11957  
11958 2 my $models = $self->_read_models;
11959 2 ▶ if (length $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $name) { } 1 1 2
11960 1 delete $models->{lookups}{$spec}{$name};
11961 } else {
11962 1 delete $models->{lookups}{$spec};
11963 }
11964 2 $self->_write_models($models);
11965 2 $self->render(json => { ok => 1 });
11966 }
11967  
11968 # lookups_list: GET /lookups/list?l=<spec>
11969 # Returns { lookups: { name: { file, key, col?, fields?, default? }, ... } }.
11970 7 ▶sub lookups_list ($self) {
Subroutine lookups_list: called CC=4 SCAR=13.9
Pod documented
11971 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
11972 7 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 5 7
11973 unless length $spec;
11974  
11975 5 my $models = $self->_read_models;
11976 5 ▶ $self->render(json => { lookups => $models->{lookups}{$spec} // {} });
Condition100%2/2
$models->{"lookups"}{$spec} // {}
l!l
23
MC/DC100%1/1
$models->{"lookups"}{$spec} // {}
$models->{"lookups"}{$spec}
Truth table100%2/2
A
A= $models->{"lookups"}{$spec}
Aresult
11
00
11977 }
11978  
11979 # ---------------------------------------------------------------------------
11980 # Stored-extraction CRUD (POST /extract/save, POST /extract/delete, GET /extract/list)
11981 # ---------------------------------------------------------------------------
11982  
11983 # extract_save: POST /extract/save?l=<spec>&name=<ident>&col=<col>&pattern=<re>
11984 # [&fields=<group>[,<group>...]]
11985 # Stores models.json extractions.<spec>.<name> = { col, pattern, fields }. The
11986 # pattern is compiled now, so one that is too long, uses a refused construct,
11987 # does not compile or names no group is a 400 here. fields= picks some of the
11988 # named groups; without it every named group becomes a column.
11989 7 ▶sub extract_save ($self) {
Subroutine extract_save: called CC=12 SCAR=24.9
Pod documented
11990 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
11991 7 ▶ my $name = $self->param('name') // '';
Condition100%2/2
$self->param("name") // ""
l!l
61
MC/DC100%1/1
$self->param("name") // ""
$self->param("name")
Truth table100%2/2
A
A= $self->param("name")
Aresult
11
00
11992 7 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
52
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
11993 7 ▶ my $pattern = $self->param('pattern') // '';
Condition100%2/2
$self->param("pattern") // ""
l!l
52
MC/DC100%1/1
$self->param("pattern") // ""
$self->param("pattern")
Truth table100%2/2
A
A= $self->param("pattern")
Aresult
11
00
11994 0 ▶ my @fields = grep { length } map { split /,/ } @{ $self->every_param('fields') // [] };
Condition50%1/2
$self->every_param("fields") // []
l!l
70
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
11995  
11996 7 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 6 7
11997 unless length $spec;
11998 6 ▶ return $self->render(json => { error => $self->_i18n('error_extract_name', $name) }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$LOOKUP_NAME_RE/u 1 5 6
11999 unless $name =~ $LOOKUP_NAME_RE;
12000 5 ▶ return $self->render(json => { error => 'col= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 1 4 5
12001 unless length $col;
12002 4 ▶ return $self->render(json => { error => 'pattern= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $pattern 1 3 4
12003 unless length $pattern;
12004  
12005 3 ▶ my %def = (col => $col, pattern => $pattern, (@fields ? (fields => \@fields) : ()));
Branch: 1 branch
BranchTrueFalseTotal
@fields ? : 0 3 3
12006 3 my $fields;
12007 3 my $ok = eval { (undef, $fields) = $self->_compile_extraction($name, \%def); 1 };
12008 3 ▶ return $self->render(json => { error => _tidy_error($@) }, status => 400) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 2 1 3
12009 1 $def{fields} = $fields;
12010  
12011 1 my $models = $self->_read_models;
12012 1 $models->{extractions}{$spec}{$name} = \%def;
12013 1 $self->_write_models($models);
12014 1 $self->render(json => { ok => 1, fields => $fields });
12015 }
12016  
12017 # extract_delete: POST /extract/delete?l=<spec>[&name=<ident>]
12018 # Removes one extraction, or every extraction of $spec when name= is absent.
12019 2 ▶sub extract_delete ($self) {
Subroutine extract_delete: called CC=5 SCAR=16.2
Pod documented
12020 2 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
11
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12021 2 ▶ my $name = $self->param('name') // '';
Condition100%2/2
$self->param("name") // ""
l!l
11
MC/DC100%1/1
$self->param("name") // ""
$self->param("name")
Truth table100%2/2
A
A= $self->param("name")
Aresult
11
00
12022  
12023 2 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 1 2
12024 unless length $spec;
12025  
12026 1 my $models = $self->_read_models;
12027 1 ▶ if (length $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $name) { } 1 0 1
12028 1 delete $models->{extractions}{$spec}{$name};
12029 } else {
12030 0 delete $models->{extractions}{$spec};
12031 }
12032 1 $self->_write_models($models);
12033 1 $self->render(json => { ok => 1 });
12034 }
12035  
12036 # extract_list: GET /extract/list?l=<spec>
12037 # Returns { extractions: { name: { col, pattern, fields }, ... } }.
12038 5 ▶sub extract_list ($self) {
Subroutine extract_list: called CC=4 SCAR=13.9
Pod documented
12039 5 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
41
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12040 5 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 3 5
12041 unless length $spec;
12042  
12043 3 my $models = $self->_read_models;
12044 3 ▶ $self->render(json => { extractions => $models->{extractions}{$spec} // {} });
Condition100%2/2
$models->{"extractions"}{$spec} // {}
l!l
12
MC/DC100%1/1
$models->{"extractions"}{$spec} // {}
$models->{"extractions"}{$spec}
Truth table100%2/2
A
A= $models->{"extractions"}{$spec}
Aresult
11
00
12045 }
12046  
12047 # ---------------------------------------------------------------------------
12048 # Geo column preferences CRUD (POST /geo/save, POST /geo/delete, GET /geo/list)
12049 #
12050 # Stores the user's choice of lat/lon/loc columns for a given l= spec in
12051 # models.json under geo.<spec>.columns. The geocode cache itself lives under
12052 # geo.<spec>.places and is written by _map_data independently.
12053 # ---------------------------------------------------------------------------
12054  
12055 # geo_save: POST /geo/save?l=<spec>&col=<col>&kind=lat|lon|location|location_suffix[&replace=1][&loc_text=<text>]
12056 # location_suffix is the column whose cells follow the place's, after ", "
12057 # (a country after an address). loc_text= is the text the map adds to the end
12058 # of each place ("Virginia, USA"); it is not a column, so it is kept beside
12059 # them, as geo.<spec>.loc_text, and replace=1 forgets it too.
12060 # col= and kind= may repeat, in pairs, so a latitude and a longitude are saved
12061 # in one request. replace=1 forgets the spec's saved columns first: the map
12062 # panel's "Remember" sends it, so a new choice replaces the old one rather than
12063 # leaving, say, a place-name column beside the latitude chosen after it.
12064 5 ▶sub geo_save ($self) {
Subroutine geo_save: called CC=14 SCAR=27.3
Pod documented
12065 5 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
41
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12066 5 ▶ my @cols = @{ $self->every_param('col') // [] };
Condition50%1/2
$self->every_param("col") // []
l!l
50
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
12067 5 ▶ my @kinds = @{ $self->every_param('kind') // [] };
Condition50%1/2
$self->every_param("kind") // []
l!l
50
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
12068  
12069 5 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 4 5
12070 unless length $spec;
12071 return $self->render(json => { error => 'col= required' }, status => 400)
12072 4 ▶ unless @cols && !grep { !length } @cols;
Branch: 1 branch
BranchTrueFalseTotal
unless @cols and not grep({not length $_;} @cols) 1 3 4
Condition66%2/3
@cols and not grep({not length $_;} @cols)
!ll&&!rl&&r
103
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
12073 return $self->render(json => { error => 'kind must be lat, lon, location or location_suffix' }, status => 400)
12074 3 ▶ 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) 2 1 3
Condition100%3/3
@kinds == @cols and not grep({not /\A(?:lat|lon|location|location_suffix)\z/u;} @kinds)
!ll&&!rl&&r
111
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
12075 1 ▶ my $loc_text_raw = $self->param('loc_text') // '';
Condition50%1/2
$self->param("loc_text") // ""
l!l
01
MC/DC0%0/1
$self->param("loc_text") // ""
$self->param("loc_text")
Truth table50%1/2
A
A= $self->param("loc_text")
Aresult
11
00
12076 1 my ($loc_text) = _map_loc_text($loc_text_raw);
12077 1 ▶ 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 0 1 1
12078 unless defined $loc_text;
12079  
12080 1 my $models = $self->_read_models;
12081 1 ▶ if ($self->param('replace')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->param("replace")) 0 1 1
12082 0 delete $models->{geo}{$spec}{columns};
12083 0 delete $models->{geo}{$spec}{loc_text};
12084 }
12085 1 $models->{geo}{$spec}{columns}{ $cols[$_] } = { kind => $kinds[$_] } for 0 .. $#cols;
12086 1 ▶ $models->{geo}{$spec}{loc_text} = $loc_text if length $loc_text;
Branch: 1 branch
BranchTrueFalseTotal
if length $loc_text 0 1 1
12087 1 $self->_write_models($models);
12088 1 $self->render(json => { ok => 1 });
12089 }
12090  
12091 # geo_delete: POST /geo/delete?l=<spec>&col=<col>
12092 # Omit col= to clear all column preferences for the spec, and its loc_text.
12093 3 ▶sub geo_delete ($self) {
Subroutine geo_delete: called CC=5 SCAR=16.3
Pod documented
12094 3 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
21
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12095 3 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
21
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
12096  
12097 3 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 1 2 3
12098 unless length $spec;
12099  
12100 2 my $models = $self->_read_models;
12101 2 ▶ if (length $col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $col) { } 2 0 2
12102 2 delete $models->{geo}{$spec}{columns}{$col};
12103 } else {
12104 0 delete $models->{geo}{$spec}{columns};
12105 0 delete $models->{geo}{$spec}{loc_text};
12106 }
12107 2 $self->_write_models($models);
12108 2 $self->render(json => { ok => 1 });
12109 }
12110  
12111 # geo_list: GET /geo/list?l=<spec>
12112 # Returns { columns: { col: { kind: "lat"|"lon"|"location"|"location_suffix" }, ... } },
12113 # with loc_text: "<text>" when that is remembered too.
12114 5 ▶sub geo_list ($self) {
Subroutine geo_list: called CC=7 SCAR=20.7
Pod documented
12115 5 ▶ my $spec = canonical_spec($self->param('l') // '');
Condition100%2/2
$self->param("l") // ""
l!l
41
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
12116 5 ▶ return $self->render(json => { error => 'l= required' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $spec 2 3 5
12117 unless length $spec;
12118  
12119 3 my $models = $self->_read_models;
12120 3 my $loc_text = $models->{geo}{$spec}{loc_text};
12121 $self->render(json => {
12122 columns => $models->{geo}{$spec}{columns} // {},
12123 3 ▶ (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 3 3
Condition50%4/8
$models->{"geo"}{$spec}{"columns"} // {}
l!l
21
defined $loc_text and not ref $loc_text and length $loc_text
!ll&&!rl&&r
300
defined $loc_text and not ref $loc_text
!ll&&!rl&&r
300
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
12124 });
12125 }
12126  
12127 # ---------------------------------------------------------------------------
12128 # Scatter chart (GET /scatter)
12129 # ---------------------------------------------------------------------------
12130  
12131 48 ▶sub scatter_view ($self) {
Subroutine scatter_view: called CC=45 SCAR=42.4
Pod documented
12132 48 ▶ my $x_col = $self->param('x') // '';
Condition100%2/2
$self->param("x") // ""
l!l
462
MC/DC100%1/1
$self->param("x") // ""
$self->param("x")
Truth table100%2/2
A
A= $self->param("x")
Aresult
11
00
12133 48 ▶ my $y_col = $self->param('y') // '';
Condition100%2/2
$self->param("y") // ""
l!l
462
MC/DC100%1/1
$self->param("y") // ""
$self->param("y")
Truth table100%2/2
A
A= $self->param("y")
Aresult
11
00
12134 48 ▶ my $series_col = $self->param('series') // '';
Condition100%2/2
$self->param("series") // ""
l!l
147
MC/DC100%1/1
$self->param("series") // ""
$self->param("series")
Truth table100%2/2
A
A= $self->param("series")
Aresult
11
00
12135 48 ▶ my $size_col = $self->param('size') // '';
Condition100%2/2
$self->param("size") // ""
l!l
246
MC/DC100%1/1
$self->param("size") // ""
$self->param("size")
Truth table100%2/2
A
A= $self->param("size")
Aresult
11
00
12136 48 ▶ my $scheme = $self->param('scheme') // 'tableau10';
Condition100%2/2
$self->param("scheme") // "tableau10"
l!l
345
MC/DC100%1/1
$self->param("scheme") // "tableau10"
$self->param("scheme")
Truth table100%2/2
A
A= $self->param("scheme")
Aresult
11
00
12137 48 my ($min_r, $max_r) = _scatter_radii($self->param('min_r'), $self->param('max_r'));
12138 48 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
048
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
12139 48 my $back2 = _safe_back_url($self->param('back2'));
12140 48 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
048
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
12141  
12142 48 ▶ return $self->render(text => 'Missing x= parameter', status => 400) unless length $x_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col 3 45 48
12143 45 ▶ return $self->render(text => 'Missing y= parameter', status => 400) unless length $y_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $y_col 1 44 45
12144  
12145 44 my ($src, $records, $columns) = $self->_run_pipeline_source;
12146 44 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 43 44
12147  
12148 43 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
12149 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
12150  
12151 42 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 41 42
12152  
12153 41 my %col_set = map { $_ => 1 } @{$columns};
12154 41 ▶ 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 39 41
12155 39 ▶ 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 38 39
12156 return $self->render(text => "Column not found: $series_col", status => 400)
12157 38 ▶ if length $series_col && !$col_set{$series_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $series_col and not $col_set{$series_col} 0 38 38
Condition66%2/3
length $series_col and not $col_set{$series_col}
!ll&&!rl&&r
3710
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
12158 return $self->render(text => "Column not found: $size_col", status => 400)
12159 38 ▶ if length $size_col && !$col_set{$size_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $size_col and not $col_set{$size_col} 1 37 38
Condition66%2/3
length $size_col and not $col_set{$size_col}
!ll&&!rl&&r
3701
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
12160  
12161 37 ▶ if (length $series_col && !$SCATTER_SCHEMES{$scheme}) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col and not $SCATTER_SCHEMES{$scheme}) 1 36 37
Condition66%2/3
length $series_col and not $SCATTER_SCHEMES{$scheme}
!ll&&!rl&&r
3601
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
12162 1 return $self->render(text => "Unknown colour scheme: $scheme", status => 400);
12163 }
12164  
12165 36 my @points;
12166 36 for my $row (@$records) {
12167 216 ▶ my $xv = _numeric_cell($row->{$x_col} // '');
Condition50%1/2
$row->{$x_col} // ""
l!l
2160
MC/DC0%0/1
$row->{$x_col} // ""
$row->{$x_col}
Truth table50%1/2
A
A= $row->{$x_col}
Aresult
11
00
12168 216 ▶ my $yv = _numeric_cell($row->{$y_col} // '');
Condition50%1/2
$row->{$y_col} // ""
l!l
2160
MC/DC0%0/1
$row->{$y_col} // ""
$row->{$y_col}
Truth table50%1/2
A
A= $row->{$y_col}
Aresult
11
00
12169 216 ▶ next unless defined $xv && defined $yv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $xv and defined $yv 210 6 216
Condition66%2/3
defined $xv and defined $yv
!ll&&!rl&&r
21006
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
12170 30 ▶ my %extra = map { $_ => _decode_cell($row->{$_} // '') }
Condition50%1/2
$row->{$_} // ""
l!l
300
MC/DC0%0/1
$row->{$_} // ""
$row->{$_}
Truth table50%1/2
A
A= $row->{$_}
Aresult
11
00
12171 6 ▶ grep { $_ ne $x_col && $_ ne $y_col } @$columns;
Condition66%2/3
$_ ne $x_col && $_ ne $y_col
!ll&&!rl&&r
6030
MC/DC50%1/2
$_ ne $x_col && $_ ne $y_col
$_ ne $x_col $_ ne $y_col
Truth table66%2/3
A && B
A= $_ ne $x_colB= $_ ne $y_col
ABresult
0X0
100
111
12172 6 my %pt_meta;
12173 6 ▶ $pt_meta{series} = _decode_cell($row->{$series_col}) if length $series_col;
Branch: 1 branch
BranchTrueFalseTotal
if length $series_col 0 6 6
12174 6 ▶ if (length $size_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $size_col) 0 6 6
12175 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
12176 0 ▶ $pt_meta{size} = $sv if defined $sv;
Branch: 1 branch
BranchTrueFalseTotal
if defined $sv 0 0 0
12177 }
12178 6 ▶ push @points, [$xv, $yv, \%extra, (%pt_meta ? \%pt_meta : ())];
Branch: 1 branch
BranchTrueFalseTotal
%pt_meta ? : 0 6 6
12179 }
12180  
12181 36 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @points 35 1 36
12182 text => 'No plottable data: no rows have valid numeric values in both selected columns.',
12183 status => 200,
12184 ) unless @points;
12185  
12186 1 my ($source_url, $source_accessed) = $self->_url_attribution;
12187  
12188 1 require HTML::D3;
12189 1 my $title = "$y_col vs $x_col";
12190 1 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 480)
Branch: 2 branches
BranchTrueFalseTotal
length $series_col ? : 0 1 1
length $size_col ? : 0 1 1
12191 ->render_scatter_chart_snippet(\@points, {
12192 animated => 1,
12193 x_label => $x_col,
12194 y_label => $y_col,
12195 (length $series_col ? (colour_by_series => 1, series_col => $series_col, scheme => $scheme) : ()),
12196 (length $size_col ? (size_col => $size_col, radius_range => [$min_r, $max_r]) : ()),
12197 });
12198  
12199 1 my $chart_html = $snippet->{html};
12200 1 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 1 1
12201  
12202 1 ▶ my %chart_spec = (
Branch: 4 branches
BranchTrueFalseTotal
length $series_col ? : 0 1 1
length $size_col ? : 0 1 1
length $series_col ? : 0 1 1
length $size_col ? : 0 1 1
12203 kind => 'scatter',
12204 title => $title,
12205 encode => { x => $x_col, y => $y_col,
12206 (length $series_col ? (series => $series_col) : ()),
12207 (length $size_col ? (size => $size_col) : ()),
12208 },
12209 # scheme= means nothing without series=, and is unchecked then, so it
12210 # is not saved: a canvas copy would otherwise carry ?scheme=Blues. The
12211 # radii likewise only with size=.
12212 options => {
12213 (length $series_col ? (scheme => $scheme) : ()),
12214 (length $size_col ? (min_r => $min_r, max_r => $max_r) : ()),
12215 },
12216 );
12217 1 my ($platform, $language) = $self->_resolve_template;
12218 1 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 1 1
$back2 ? : 0 1 1
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
010
$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
12219 handler => 'tt',
12220 template => "$platform/$language/scatter",
12221 format => 'html',
12222 title => $title,
12223 chart_html => $chart_html,
12224 chart => \%chart_spec,
12225 chart_json => $self->_chart_json(\%chart_spec),
12226 point_count => scalar @points,
12227 x_col => $x_col,
12228 y_col => $y_col,
12229 back_url => ($back2 // $back),
12230 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
12231 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
12232 source_url => $source_url,
12233 source_accessed => $source_accessed,
12234 language => $language,
12235 );
12236 }
12237  
12238 # ---------------------------------------------------------------------------
12239 # Stacked bar chart (GET /stacked)
12240 # ---------------------------------------------------------------------------
12241  
12242 48 ▶sub stacked_view ($self) {
Subroutine stacked_view: called CC=36 SCAR=42.2
Pod documented
12243 48 ▶ my $cat_col = $self->param('cat') // '';
Condition100%2/2
$self->param("cat") // ""
l!l
462
MC/DC100%1/1
$self->param("cat") // ""
$self->param("cat")
Truth table100%2/2
A
A= $self->param("cat")
Aresult
11
00
12244 # ?series= is the canonical spec name; ?seg= is the legacy alias (keep both).
12245 48 ▶ my $seg_col = $self->param('series') // $self->param('seg') // '';
Condition100%5/5
($self->param("series") // $self->param("seg")) // ""
l!l
543
$self->param("series") // $self->param("seg")
l!l&&r!l&&!r
3243
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
12246 48 ▶ my $val_col = $self->param('val') // '';
Condition100%2/2
$self->param("val") // ""
l!l
246
MC/DC100%1/1
$self->param("val") // ""
$self->param("val")
Truth table100%2/2
A
A= $self->param("val")
Aresult
11
00
12247 48 ▶ my $orient = $self->param('orient') // 'v';
Condition50%1/2
$self->param("orient") // "v"
l!l
048
MC/DC0%0/1
$self->param("orient") // "v"
$self->param("orient")
Truth table50%1/2
A
A= $self->param("orient")
Aresult
11
00
12248 48 my $scheme = _categorical_scheme($self->param('scheme'));
12249 48 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
048
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
12250 48 my $back2 = _safe_back_url($self->param('back2'));
12251 48 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
048
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
12252  
12253 48 ▶ return $self->render(text => 'Missing cat= parameter', status => 400) unless length $cat_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col 3 45 48
12254 45 ▶ return $self->render(text => 'Missing series= parameter', status => 400) unless length $seg_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $seg_col 42 3 45
12255  
12256 3 my ($src, $records, $columns) = $self->_run_pipeline_source;
12257 3 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 0 3 3
12258  
12259 3 my $span = $self->_span_calc_spec($columns, 'cat');
12260 3 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 0 3 3
Condition33%1/3
$span and $span->{"error"}
!ll&&!rl&&r
300
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
12261  
12262 3 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
12263 3 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 3 3
12264 0 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3 3
12265  
12266 3 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 3 3
12267  
12268 3 my %col_set = map { $_ => 1 } @{$columns};
12269 3 ▶ 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 2 3
12270 2 ▶ 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 1 2
12271  
12272 1 ▶ my $count_mode = (!length $val_col || $val_col eq '__count__');
Condition33%1/3
!length($val_col) || $val_col eq '__count__'
l!l&&r!l&&!r
100
MC/DC0%0/2
!length($val_col) || $val_col eq '__count__'
!length($val_col) $val_col eq '__count__'
Truth table33%1/3
not(A) || B
A= !length($val_col)B= $val_col eq '__count__'
ABresult
1X1
011
000
12273 return $self->render(text => "Column not found: $val_col", status => 400)
12274 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
100
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
12275  
12276 1 ▶ $cat_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 1 1
12277  
12278 # Aggregate by [cat, seg] via _grouped_totals to respect the governing
12279 # invariant (all numbers from a single path) and to get ascending key order.
12280 1 ▶ my $agg_rows = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 1 0 1
$count_mode ? : 1 0 1
12281 { source => $src, records => $records },
12282 {
12283 by => [$cat_col, $seg_col],
12284 fn => $count_mode ? 'count' : 'sum',
12285 val => $count_mode ? undef : $val_col,
12286 as => 'value',
12287 },
12288 );
12289  
12290 # render_stacked_bar_snippet accepts flat [{cat_col=>,seg_col=>,val_col=>}] rows
12291 # and handles the stacking itself; only include pairs actually returned (no phantom
12292 # zero cells for missing intersections).
12293 my @data = map {
12294 1 ▶ my $cat = _decode_cell($_->{$cat_col} // '');
Condition50%1/2
$_->{$cat_col} // ""
l!l
60
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
Truth table50%1/2
A
A= $_->{$cat_col}
Aresult
11
00
12295 6 ▶ my $seg = _decode_cell($_->{$seg_col} // '');
Condition50%1/2
$_->{$seg_col} // ""
l!l
60
MC/DC0%0/1
$_->{$seg_col} // ""
$_->{$seg_col}
Truth table50%1/2
A
A= $_->{$seg_col}
Aresult
11
00
12296 (length $cat && length $seg)
12297 ? { cat => $cat, seg => $seg, val => $_->{value} }
12298 : ()
12299 6 ▶ } @$agg_rows;
Branch: 1 branch
BranchTrueFalseTotal
length $cat && length $seg ? : 6 0 6
Condition33%1/3
length $cat and length $seg
!ll&&!rl&&r
006
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
12300  
12301 1 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @data 0 1 1
12302 text => 'No plottable data: no rows have valid data in the selected columns.',
12303 status => 200,
12304 ) unless @data;
12305  
12306 1 my ($source_url, $source_accessed) = $self->_url_attribution;
12307  
12308 1 require HTML::D3;
12309 1 ▶ my $title = $count_mode ? "Count by $cat_col and $seg_col"
Branch: 1 branch
BranchTrueFalseTotal
$count_mode ? : 1 0 1
12310 : "$val_col by $cat_col and $seg_col";
12311 1 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 900, height => 500)
Branch: 1 branch
BranchTrueFalseTotal
$orient eq 'h' ? : 0 1 1
12312 ->render_stacked_bar_snippet(\@data, {
12313 orient => ($orient eq 'h') ? 'h' : 'v',
12314 x_label => $cat_col,
12315 scheme => $scheme,
12316 });
12317  
12318 1 my $chart_html = $snippet->{html};
12319 1 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 1 1
12320  
12321 1 my %chart_spec = (
12322 kind => 'stacked',
12323 title => $title,
12324 encode => { cat => $cat_col, series => $seg_col, value => $val_col },
12325 options => { orientation => $orient, scheme => $scheme },
12326 );
12327 1 my ($platform, $language) = $self->_resolve_template;
12328 $self->render(
12329 handler => 'tt',
12330 template => "$platform/$language/stacked",
12331 format => 'html',
12332 title => $title,
12333 chart_html => $chart_html,
12334 chart => \%chart_spec,
12335 chart_json => $self->_chart_json(\%chart_spec),
12336 1 ▶ bar_count => scalar(grep { defined $_->{cat} } @data),
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 1 1
$back2 ? : 0 1 1
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
010
$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
12337 back_url => ($back2 // $back),
12338 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
12339 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
12340 source_url => $source_url,
12341 source_accessed => $source_accessed,
12342 language => $language,
12343 );
12344 }
12345  
12346 # ---------------------------------------------------------------------------
12347 # Combo bar+line chart (GET /combo)
12348 # ---------------------------------------------------------------------------
12349  
12350 48 ▶sub combo_view ($self) {
Subroutine combo_view: called CC=42 SCAR=43.4
Pod documented
12351 # ?cat= is the canonical spec name; ?x= is the legacy alias (keep both).
12352 48 ▶ my $x_col = $self->param('cat') // $self->param('x') // '';
Condition80%4/5
($self->param("cat") // $self->param("x")) // ""
l!l
462
$self->param("cat") // $self->param("x")
l!l&&r!l&&!r
4602
MC/DC50%1/2
($self->param("cat") // $self->param("x")) // ""
$self->param("cat") $self->param("x")
Truth table66%2/3
A // B
A= $self->param("cat")B= $self->param("x")
ABresult
1X1
011
000
12353 # ?bar_val= is the canonical spec name; ?bar= is the legacy alias (keep both).
12354 48 ▶ my $bar_col = $self->param('bar_val') // $self->param('bar') // '';
Condition100%5/5
($self->param("bar_val") // $self->param("bar")) // ""
l!l
543
$self->param("bar_val") // $self->param("bar")
l!l&&r!l&&!r
1443
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
12355 # ?line_val= is the canonical spec name; ?line= is the legacy alias (keep both).
12356 48 ▶ my $line_col = $self->param('line_val') // $self->param('line') // '';
Condition100%5/5
($self->param("line_val") // $self->param("line")) // ""
l!l
543
$self->param("line_val") // $self->param("line")
l!l&&r!l&&!r
1443
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
12357 48 ▶ my $bar_label = $self->param('bar_label') // '';
Condition50%1/2
$self->param("bar_label") // ""
l!l
048
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
12358 48 ▶ my $line_label = $self->param('line_label') // '';
Condition50%1/2
$self->param("line_label") // ""
l!l
048
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
12359 48 my $scheme = _optional_scheme($self->param('scheme'));
12360 48 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
048
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
12361 48 my $back2 = _safe_back_url($self->param('back2'));
12362 48 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
048
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
12363  
12364 48 ▶ return $self->render(text => 'Missing cat= parameter', status => 400) unless length $x_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $x_col 3 45 48
12365 45 ▶ return $self->render(text => 'Missing bar_val= parameter', status => 400) unless length $bar_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $bar_col 42 3 45
12366 3 ▶ return $self->render(text => 'Missing line_val= parameter', status => 400) unless length $line_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $line_col 2 1 3
12367  
12368 1 my ($src, $records, $columns) = $self->_run_pipeline_source;
12369 1 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 0 1 1
12370  
12371 1 my $span = $self->_span_calc_spec($columns, 'cat', 'x');
12372 1 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 0 1 1
Condition33%1/3
$span and $span->{"error"}
!ll&&!rl&&r
100
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
12373  
12374 1 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
12375 1 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 1 1
12376 0 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 1 1
12377  
12378 1 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 1 1
12379  
12380 1 my %col_set = map { $_ => 1 } @{$columns};
12381 1 ▶ 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 1 1
12382 1 ▶ 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 1 1
12383 1 ▶ 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 1 1
12384  
12385 1 ▶ $x_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 1 1
12386  
12387 # Aggregate bar and line measures separately via _grouped_totals so both
12388 # use the same path (push or fold) and produce ascending x-axis order.
12389 # A category missing from one result set renders as a gap (undef), not zero.
12390 1 my $bar_rows = $self->_grouped_totals(
12391 { source => $src, records => $records },
12392 { by => [$x_col], fn => 'sum', val => $bar_col, as => 'bar_val' },
12393 );
12394 1 my $line_rows = $self->_grouped_totals(
12395 { source => $src, records => $records },
12396 { by => [$x_col], fn => 'sum', val => $line_col, as => 'line_val' },
12397 );
12398  
12399 # Merge: build a lookup from both result sets and walk the union of categories.
12400 1 my (%bar_map, %line_map, @x_order, %x_seen);
12401 1 for my $r (@$bar_rows) {
12402 4 ▶ my $xv = _decode_cell($r->{$x_col} // '');
Condition50%1/2
$r->{$x_col} // ""
l!l
40
MC/DC0%0/1
$r->{$x_col} // ""
$r->{$x_col}
Truth table50%1/2
A
A= $r->{$x_col}
Aresult
11
00
12403 4 ▶ next unless length $xv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $xv 0 4 4
12404 4 ▶ push @x_order, $xv unless $x_seen{$xv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $x_seen{$xv}++ 4 0 4
12405 4 $bar_map{$xv} = $r->{bar_val};
12406 }
12407 1 for my $r (@$line_rows) {
12408 4 ▶ my $xv = _decode_cell($r->{$x_col} // '');
Condition50%1/2
$r->{$x_col} // ""
l!l
40
MC/DC0%0/1
$r->{$x_col} // ""
$r->{$x_col}
Truth table50%1/2
A
A= $r->{$x_col}
Aresult
11
00
12409 4 ▶ next unless length $xv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $xv 0 4 4
12410 4 ▶ push @x_order, $xv unless $x_seen{$xv}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $x_seen{$xv}++ 0 4 4
12411 4 $line_map{$xv} = $r->{line_val};
12412 }
12413  
12414 1 my @data = map { {
12415 x => $_,
12416 bar_val => $bar_map{$_}, # undef = gap in bar series
12417 4 line_val => $line_map{$_}, # undef = gap in line series
12418 } } @x_order;
12419  
12420 1 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @data 0 1 1
12421 text => 'No plottable data: no rows have valid data in the selected columns.',
12422 status => 200,
12423 ) unless @data;
12424  
12425 1 my ($source_url, $source_accessed) = $self->_url_attribution;
12426  
12427 1 require HTML::D3;
12428 1 ▶ my $eff_bar_lbl = $bar_label || $bar_col;
Condition33%1/3
$bar_label || $bar_col
l!l&&r!l&&!r
010
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
12429 1 ▶ my $eff_line_lbl = $line_label || $line_col;
Condition33%1/3
$line_label || $line_col
l!l&&r!l&&!r
010
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
12430 1 my $title = "$eff_bar_lbl and $eff_line_lbl by $x_col";
12431 1 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 900, height => 500)
Branch: 1 branch
BranchTrueFalseTotal
$scheme ? : 0 1 1
12432 ->render_combo_snippet(\@data, {
12433 bar_label => $eff_bar_lbl,
12434 line_label => $eff_line_lbl,
12435 ($scheme ? (scheme => $scheme) : ()),
12436 });
12437  
12438 1 my $chart_html = $snippet->{html};
12439 1 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 1 1
12440  
12441 1 ▶ my %chart_spec = (
Branch: 1 branch
BranchTrueFalseTotal
$scheme ? : 0 1 1
12442 kind => 'combo',
12443 title => $title,
12444 encode => { x => $x_col, bar => $bar_col, line => $line_col },
12445 ($scheme ? (options => { scheme => $scheme }) : ()),
12446 );
12447 1 my ($platform, $language) = $self->_resolve_template;
12448 1 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 1 1
$back2 ? : 0 1 1
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
010
$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
12449 handler => 'tt',
12450 template => "$platform/$language/combo",
12451 format => 'html',
12452 title => $title,
12453 chart_html => $chart_html,
12454 chart => \%chart_spec,
12455 chart_json => $self->_chart_json(\%chart_spec),
12456 point_count => scalar @data,
12457 back_url => ($back2 // $back),
12458 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
12459 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
12460 source_url => $source_url,
12461 source_accessed => $source_accessed,
12462 language => $language,
12463 );
12464 }
12465  
12466 # ---------------------------------------------------------------------------
12467 # Treemap (GET /treemap)
12468 # ---------------------------------------------------------------------------
12469  
12470 # _tile_colour_measure($self, $fn, $col) -> \%measure | { error => $text }
12471 #
12472 # The measure a treemap's tiles are coloured by: $fn (color_agg=, or a card's
12473 # options.color_agg) of $col, average when $fn is absent or empty, since a
12474 # margin or a rating is read as an average rather than a total. A name that
12475 # is not an aggregate function comes back as { error }, worded as the
12476 # function check elsewhere words it. /treemap and a canvas treemap card both
12477 # ask here, so they accept and refuse the same names.
12478 7 ▶sub _tile_colour_measure :Protected ($self, $fn, $col) {
Subroutine _tile_colour_measure: called CC=5 SCAR=16.1
12479 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
12480 7 ▶ $fn = 'avg' unless length $fn;
Branch: 1 branch
BranchTrueFalseTotal
unless length $fn 3 4 7
12481 7 ▶ return { error => $self->_i18n('error_agg_fn', $fn, join(' ', @MEASURE_FNS)) }
Branch: 1 branch
BranchTrueFalseTotal
unless _measure_fn_ok($fn) 1 6 7
12482 unless _measure_fn_ok($fn);
12483 6 return _visual_measure($fn, $col);
12484 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
12485  
12486 # _tile_colours($self, $source, \@records, $cat_col, \%measure) -> \%colour_of
12487 #
12488 # The number each treemap tile is coloured by: the measure (from
12489 # _visual_measure) folded per value of $cat_col, keyed by the raw value. With
12490 # $cat_col undef it is one total over every row, under the key ''. A group
12491 # whose result is not a finite number has no entry, and its tile is drawn
12492 # grey. /treemap and a canvas treemap card both fold here, so a card saved
12493 # from the page is coloured by the same numbers.
12494 3 ▶sub _tile_colours :Protected ($self, $source, $records, $cat_col, $m) {
Subroutine _tile_colours: called CC=8 SCAR=22.5
12495 my $rows = $self->_grouped_totals(
12496 { source => $source, records => $records },
12497 { by => [ defined $cat_col ? ($cat_col) : () ],
12498 3 ▶ fn => $m->{fn}, val => $m->{val}, as => 'colour' },
Branch: 1 branch
BranchTrueFalseTotal
defined $cat_col ? : 2 1 3
12499 );
12500 3 my %colour_of;
12501 3 for my $r (@$rows) {
12502 3 my $v = $r->{colour};
12503 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
12504 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
12505 }
12506 3 return \%colour_of;
12507 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
12508  
12509 49 ▶sub treemap_view ($self) {
Subroutine treemap_view: called CC=54 SCAR=52.0
Pod documented
12510 # ?group= is the canonical spec name; ?cat= is the legacy alias (keep both).
12511 49 ▶ my $cat_col = $self->param('group') // $self->param('cat') // '';
Condition100%5/5
($self->param("group") // $self->param("cat")) // ""
l!l
472
$self->param("group") // $self->param("cat")
l!l&&r!l&&!r
6412
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
12512 # ?size= is the canonical spec name; ?val= is the legacy alias (keep both).
12513 49 ▶ my $val_col = $self->param('size') // $self->param('val') // '';
Condition100%5/5
($self->param("size") // $self->param("val")) // ""
l!l
544
$self->param("size") // $self->param("val")
l!l&&r!l&&!r
4144
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
12514 49 my $scheme = _categorical_scheme($self->param('scheme'));
12515 49 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
049
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
12516 49 my $back2 = _safe_back_url($self->param('back2'));
12517 49 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
049
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
12518  
12519 # ?color= shades each tile by a second column, folded per tile with
12520 # ?color_agg= (default avg: a margin or a rating is read as an average, not
12521 # a total) on the sequential ?color_scheme=, as the heatmap's cells are.
12522 49 ▶ my $color_col = $self->param('color') // '';
Condition100%2/2
$self->param("color") // ""
l!l
148
MC/DC100%1/1
$self->param("color") // ""
$self->param("color")
Truth table100%2/2
A
A= $self->param("color")
Aresult
11
00
12523 49 ▶ my $color_m = length $color_col
Branch: 1 branch
BranchTrueFalseTotal
length $color_col ? : 1 48 49
12524 ? $self->_tile_colour_measure($self->param('color_agg'), $color_col)
12525 : undef;
12526 49 my $color_scheme = _sequential_scheme($self->param('color_scheme'));
12527  
12528 49 ▶ return $self->render(text => 'Missing group= parameter', status => 400) unless length $cat_col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $cat_col 3 46 49
12529 46 ▶ 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 46 46
Condition66%2/3
$color_m and $color_m->{"error"}
!ll&&!rl&&r
4510
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
12530  
12531 46 my ($src, $records, $columns) = $self->_run_pipeline_source;
12532 46 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 45 46
12533  
12534 45 my $span = $self->_span_calc_spec($columns, 'group', 'cat');
12535 45 ▶ return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $span and $span->{"error"} 1 44 45
Condition66%2/3
$span and $span->{"error"}
!ll&&!rl&&r
4401
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
12536  
12537 44 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
12538 44 ▶ ($span ? { calc => $span->{calc} } : undef)) };
Branch: 1 branch
BranchTrueFalseTotal
$span ? : 0 44 44
12539 44 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 43 44
12540  
12541 43 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 42 43
12542  
12543 42 my %col_set = map { $_ => 1 } @{$columns};
12544 42 ▶ 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 39 42
12545  
12546 39 ▶ 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
3504
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
12547 return $self->render(text => "Column not found: $val_col", status => 400)
12548 39 ▶ unless $count_mode || $col_set{$val_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $count_mode or $col_set{$val_col} 2 37 39
Condition100%3/3
$count_mode or $col_set{$val_col}
l!l&&r!l&&!r
3522
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
12549 return $self->render(text => "Column not found: $color_col", status => 400)
12550 37 ▶ if length $color_col && !$col_set{$color_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $color_col and not $col_set{$color_col} 1 36 37
Condition66%2/3
length $color_col and not $col_set{$color_col}
!ll&&!rl&&r
3601
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
12551  
12552 36 ▶ $cat_col = $span->{col} if $span;
Branch: 1 branch
BranchTrueFalseTotal
if $span 0 36 36
12553  
12554 36 ▶ my $agg_rows = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 34 2 36
$count_mode ? : 34 2 36
12555 { source => $src, records => $records },
12556 {
12557 by => [$cat_col],
12558 fn => $count_mode ? 'count' : 'sum',
12559 val => $count_mode ? undef : $val_col,
12560 as => 'value',
12561 },
12562 );
12563  
12564 36 ▶ my $colour_of = $color_m
Branch: 1 branch
BranchTrueFalseTotal
$color_m ? : 0 36 36
12565 ? $self->_tile_colours($src, $records, $cat_col, $color_m)
12566 : {};
12567  
12568 # Top-N: keep the highest-N tiles, aggregate the rest as "Other".
12569 36 ▶ my $topn_n = _whole_number($self->param('topn')) // 0;
Condition50%1/2
_whole_number($self->param("topn")) // 0
l!l
036
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
12570 36 ▶ if ($topn_n > 0 && @$agg_rows > $topn_n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($topn_n > 0 and @$agg_rows > $topn_n) 0 36 36
Condition33%1/3
$topn_n > 0 and @$agg_rows > $topn_n
!ll&&!rl&&r
3600
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
12571 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
12572 0 my @top_agg = @sorted[0 .. $topn_n - 1];
12573 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
12574 my $other_rec = [
12575 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
12576 ];
12577 0 ▶ if (@$other_rec) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$other_rec) 0 0 0
12578 0 ▶ my $other = $self->_grouped_totals(
Branch: 2 branches
BranchTrueFalseTotal
$count_mode ? : 0 0 0
$count_mode ? : 0 0 0
12579 { source => undef, records => $other_rec },
12580 { by => [], fn => ($count_mode ? 'count' : 'sum'),
12581 val => ($count_mode ? undef : $val_col), as => 'value' },
12582 );
12583 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
12584 0 push @top_agg, { $cat_col => 'Other', value => $other->[0]{value} };
12585 # Other's colour is its own rows', not an average of averages.
12586 # The key is the tile, so a category itself named Other is
12587 # drawn with this one, as its area already is.
12588 0 ▶ $colour_of->{Other} = $self->_tile_colours(undef, $other_rec, undef, $color_m)->{''}
Branch: 1 branch
BranchTrueFalseTotal
if $color_m 0 0 0
12589 if $color_m;
12590 }
12591 }
12592 0 $agg_rows = \@top_agg;
12593 }
12594  
12595 36 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @$agg_rows 0 36 36
12596 text => 'No plottable data: no rows have valid data in the selected column.',
12597 status => 200,
12598 ) unless @$agg_rows;
12599  
12600 my @data = map {
12601 36 ▶ my $cv = $colour_of->{ $_->{$cat_col} // '' };
Condition50%1/2
$_->{$cat_col} // ""
l!l
1440
MC/DC0%0/1
$_->{$cat_col} // ""
$_->{$cat_col}
Truth table50%1/2
A
A= $_->{$cat_col}
Aresult
11
00
12602 +{ path => 'Root/' . _decode_cell($_->{$cat_col}), value => $_->{value},
12603 144 ▶ (defined $cv ? (color_value => $cv) : ()) }
Branch: 1 branch
BranchTrueFalseTotal
defined $cv ? : 0 144 144
12604 } @$agg_rows;
12605  
12606 36 my ($source_url, $source_accessed) = $self->_url_attribution;
12607  
12608 36 require HTML::D3;
12609 36 ▶ my $title = $count_mode ? "Treemap of $cat_col by count" : "Treemap of $cat_col by $val_col";
Branch: 1 branch
BranchTrueFalseTotal
$count_mode ? : 34 2 36
12610 36 ▶ $title .= " coloured by $color_m->{label}" if $color_m;
Branch: 1 branch
BranchTrueFalseTotal
if $color_m 0 36 36
12611 my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 500)
12612 ->render_treemap_snippet(\@data, {
12613 scheme => $scheme,
12614 36 ▶ ($color_m ? (color_scheme => $color_scheme, color_label => $color_m->{label}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$color_m ? : 0 36 36
12615 });
12616  
12617 36 my $chart_html = $snippet->{html};
12618 36 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 36 36
12619  
12620 my %chart_spec = (
12621 kind => 'treemap',
12622 title => $title,
12623 encode => { cat => $cat_col, value => $val_col,
12624 ($color_m ? (color => $color_col) : ()) },
12625 options => { scheme => $scheme,
12626 36 ▶ ($color_m ? (color_agg => $color_m->{fn}, color_scheme => $color_scheme) : ()) },
Branch: 2 branches
BranchTrueFalseTotal
$color_m ? : 0 36 36
$color_m ? : 0 36 36
12627 );
12628 36 my ($platform, $language) = $self->_resolve_template;
12629 36 ▶ $self->render(
Branch: 2 branches
BranchTrueFalseTotal
$back2 ? : 0 36 36
$back2 ? : 0 36 36
Condition20%1/5
$back2 // $back
l!l&&r!l&&!r
0360
$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
12630 handler => 'tt',
12631 template => "$platform/$language/treemap",
12632 format => 'html',
12633 title => $title,
12634 chart_html => $chart_html,
12635 chart => \%chart_spec,
12636 chart_json => $self->_chart_json(\%chart_spec),
12637 tile_count => scalar @data,
12638 cat_col => $cat_col,
12639 drill_back_url => $back,
12640 back_url => ($back2 // $back),
12641 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
12642 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
12643 source_url => $source_url,
12644 source_accessed => $source_accessed,
12645 language => $language,
12646 );
12647 }
12648  
12649 # ---------------------------------------------------------------------------
12650 # Histogram (GET /histogram)
12651 # ---------------------------------------------------------------------------
12652  
12653 50 ▶sub histogram_view ($self) {
Subroutine histogram_view: called CC=35 SCAR=37.0
Pod documented
12654 50 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
482
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
12655 50 my $_bins_raw = $self->param('bins');
12656 50 ▶ my $bins = (defined $_bins_raw && length $_bins_raw) ? $_bins_raw : 10;
Branch: 1 branch
BranchTrueFalseTotal
defined $_bins_raw && length $_bins_raw ? : 4 46 50
Condition100%3/3
defined $_bins_raw and length $_bins_raw
!ll&&!rl&&r
4514
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
12657 50 my $scheme = _optional_scheme($self->param('scheme'));
12658 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
12659 50 my $back2 = _safe_back_url($self->param('back2'));
12660 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
12661  
12662 50 ▶ return $self->render(text => 'Missing col= parameter', status => 400) unless length $col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 3 47 50
12663  
12664 47 my ($src, $records, $columns) = $self->_run_pipeline_source;
12665 47 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 46 47
12666  
12667 46 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
12668 46 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 45 46
12669  
12670 45 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 44 45
12671  
12672 44 my %col_set = map { $_ => 1 } @{$columns};
12673 44 ▶ return $self->render(text => "Column not found: $col", status => 400) unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 2 42 44
12674  
12675 42 my @values;
12676 42 for my $row (@$records) {
12677 252 ▶ my $v = _numeric_cell($row->{$col} // '');
Condition50%1/2
$row->{$col} // ""
l!l
2520
MC/DC0%0/1
$row->{$col} // ""
$row->{$col}
Truth table50%1/2
A
A= $row->{$col}
Aresult
11
00
12678 252 ▶ push @values, $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 252 0 252
12679 }
12680  
12681 42 ▶ return $self->render(
Branch: 1 branch
BranchTrueFalseTotal
unless @values 0 42 42
12682 text => 'No plottable data: no rows have valid numeric values in the selected column.',
12683 status => 200,
12684 ) unless @values;
12685  
12686 42 ▶ $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
4110
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
12687 42 ▶ $bins = 1 if $bins < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $bins < 1 1 41 42
12688 42 ▶ $bins = $MAX_HISTOGRAM_BINS if $bins > $MAX_HISTOGRAM_BINS;
Branch: 1 branch
BranchTrueFalseTotal
if $bins > $MAX_HISTOGRAM_BINS 1 41 42
12689  
12690 # Server-side binning: compute equal-width bins over the data range.
12691 # Values equal to $max land in the highest bin (no overflow bar).
12692 # Uses the same bin-boundary logic as Calc.pm bin() to stay consistent with
12693 # ?c=band:bin(col,width) computed columns on the same data.
12694 5 ▶ use POSIX qw(floor);
Subroutine BEGIN: called CC=1 SCAR=0.0
12695 42 my $min_v = min(@values);
12696 42 my $max_v = max(@values);
12697 42 my @bin_data;
12698 42 ▶ if ($min_v == $max_v) {
Branch: 1 branch
BranchTrueFalseTotal
if ($min_v == $max_v) { } 0 42 42
12699 # All values identical: one bin.
12700 0 push @bin_data, { label => "$min_v", count => scalar @values, lo => $min_v, hi => $min_v };
12701 } else {
12702 42 my $raw_w = ($max_v - $min_v) / $bins;
12703 # Round up to a "nice" width using 10 significant digits (same guard as Calc bin()).
12704 42 my $width = sprintf('%.10g', $raw_w) + 0;
12705 42 ▶ $width = $raw_w if $width <= 0; # safety: never produce zero width
Branch: 1 branch
BranchTrueFalseTotal
if $width <= 0 0 42 42
12706 42 ▶ my $fmt = ($width == int($width)) ? '%d' : '%g';
Branch: 1 branch
BranchTrueFalseTotal
$width == int $width ? : 0 42 42
12707  
12708 # Build bin boundaries.
12709 42 my @bin_counts;
12710 my @bin_los;
12711 42 for my $i (0 .. $bins - 1) {
12712 587 push @bin_los, $min_v + $i * $width;
12713 587 push @bin_counts, 0;
12714 }
12715  
12716 # Assign each value to a bin.
12717 42 for my $v (@values) {
12718 252 my $idx = floor(sprintf('%.10g', ($v - $min_v) / $width) + 0);
12719 252 ▶ $idx = $bins - 1 if $idx >= $bins; # max value -> last bin
Branch: 1 branch
BranchTrueFalseTotal
if $idx >= $bins 42 210 252
12720 252 ▶ $idx = 0 if $idx < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $idx < 0 0 252 252
12721 252 $bin_counts[$idx]++;
12722 }
12723  
12724 42 for my $i (0 .. $bins - 1) {
12725 587 ▶ next unless $bin_counts[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless $bin_counts[$i] 386 201 587
12726 201 my $lo = $bin_los[$i];
12727 201 my $hi = $lo + $width;
12728 201 my $lbl = sprintf("[${fmt},${fmt})", $lo, $hi);
12729 201 push @bin_data, { label => $lbl, count => $bin_counts[$i], lo => $lo, hi => $hi };
12730 }
12731 }
12732  
12733 42 my ($source_url, $source_accessed) = $self->_url_attribution;
12734  
12735 42 require HTML::D3;
12736 42 my $title = "Distribution of $col";
12737 42 ▶ my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 480)
Branch: 1 branch
BranchTrueFalseTotal
$scheme ? : 0 42 42
12738 ->render_histogram_snippet(\@bin_data, {
12739 binned => 1,
12740 x_label => $col,
12741 ($scheme ? (scheme => $scheme) : ()),
12742 });
12743  
12744 42 my $chart_html = $snippet->{html};
12745 42 ▶ utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($chart_html) 0 42 42
12746  
12747 42 ▶ my %chart_spec = (
Branch: 1 branch
BranchTrueFalseTotal
$scheme ? : 0 42 42
12748 kind => 'histogram',
12749 title => $title,
12750 encode => { value => $col },
12751 options => { bins => $bins, ($scheme ? (scheme => $scheme) : ()) },
12752 );
12753 42 my ($platform, $language) = $self->_resolve_template;
12754 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
12755 handler => 'tt',
12756 template => "$platform/$language/histogram",
12757 format => 'html',
12758 title => $title,
12759 chart_html => $chart_html,
12760 chart => \%chart_spec,
12761 chart_json => $self->_chart_json(\%chart_spec),
12762 value_count => scalar @values,
12763 bins => $bins,
12764 back_url => ($back2 // $back),
12765 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
12766 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
12767 source_url => $source_url,
12768 source_accessed => $source_accessed,
12769 language => $language,
12770 );
12771 }
12772  
12773 # ---------------------------------------------------------------------------
12774 # Word cloud (GET /wordcloud)
12775 # ---------------------------------------------------------------------------
12776  
12777 # The words that say nothing about the data: without them a cloud of a notes
12778 # column is all "the" and "and". English, like the only page language the
12779 # templates have. ?stop= adds to this list for one request rather than
12780 # replacing it, so adding a word never silently brings back the ones this list
12781 # already removes.
12782 5 my %STOP_WORD = map { $_ => 1 } qw(
12783 a about above after again against all also am an and any are as at be
12784 because been before being below between both but by can could did do does
12785 doing down during each few for from further had has have having he her here
12786 hers herself him himself his how i if in into is it its itself just me more
12787 most my myself no nor not now of off on once only or other our ours ourselves
12788 out over own same she should so some such than that the their theirs them
12789 themselves then there these they this those through to too under until up
12790 very was we were what when where which while who whom why will with would
12791 you your yours yourself yourselves
12792 );
12793  
12794 # _percent_encode($text) -> $url_component
12795 #
12796 # Purpose: Percent-encode one value for a query string.
12797 # Notes: url_escape() works on bytes, so a decoded (character) string is
12798 # encoded to UTF-8 first; otherwise "caf\x{e9}" would become "caf%E9" and a
12799 # browser would read that back as Latin-1.
12800 12 ▶sub _percent_encode {
Subroutine _percent_encode: called CC=3 SCAR=11.0
12801 12 my ($text) = @_;
12802 12 ▶ my $bytes = defined $text ? "$text" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $text ? : 11 1 12
12803 12 ▶ utf8::encode($bytes) if utf8::is_utf8($bytes);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($bytes) 1 11 12
12804 12 return url_escape($bytes);
12805 }
12806  
12807 # _word_tokens($text, $minlen) -> @words
12808 #
12809 # Purpose: The words in one cell, lower-cased and split on everything that is
12810 # neither a letter, a digit nor an apostrophe.
12811 # Entry: $text is a cell (may be undef); $minlen is the shortest word kept.
12812 # Exit: The words at least $minlen characters long that contain a letter.
12813 # A run of digits alone is kept -- a year or a model number can be the
12814 # point of a column -- while a run of punctuation is not a word at all.
12815 # Notes: A CSV cell arrives as bytes, so it is decoded first (the same
12816 # _decode_cell() every page uses): without that, \p{L} would see the
12817 # bytes of "caf\x{e9}" and split the word in two. The apostrophe stays
12818 # inside a word, so O'Brien is one word rather than "o" and "brien".
12819 284 ▶sub _word_tokens {
Subroutine _word_tokens: called CC=5 SCAR=16.1
12820 284 my ($text, $minlen) = @_;
12821 284 ▶ return () unless defined $text && length $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text and length $text 8 276 284
Condition100%3/3
defined $text and length $text
!ll&&!rl&&r
71276
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
12822  
12823 276 my @words = split /[^\p{L}\p{N}']+/, lc _decode_cell($text);
12824 276 for my $word (@words) {
12825 554 $word =~ s/\A'+//;
12826 554 $word =~ s/'+\z//;
12827 }
12828  
12829 276 ▶ return grep { length($_) >= $minlen && /\p{L}/ } @words;
Condition100%3/3
length $_ >= $minlen && /\p{L}/u
!ll&&!rl&&r
25322873
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
12830 }
12831  
12832 # _wordcloud_option($raw, $default, $min, $max) -> $n
12833 #
12834 # Purpose: One of the two counts a cloud takes -- how many words to show, how
12835 # short a word may be.
12836 # Notes: A value that is absent or unreadable is the default, not the minimum:
12837 # ?topn= with nothing after it must not silently show a single word.
12838 115 ▶sub _wordcloud_option {
Subroutine _wordcloud_option: called CC=6 SCAR=17.9
12839 115 my ($raw, $default, $min, $max) = @_;
12840  
12841 115 ▶ 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 110 115
Condition100%6/6
defined $raw and not ref $raw and $raw =~ /\A\d+\z/u
!ll&&!rl&&r
98125
defined $raw and not ref $raw
!ll&&!rl&&r
97117
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
12842 115 ▶ $n = $min if $n < $min;
Branch: 1 branch
BranchTrueFalseTotal
if $n < $min 1 114 115
12843 115 ▶ $n = $max if $n > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $n > $max 3 112 115
12844 115 return $n;
12845 }
12846  
12847 # _wordcloud_counts($records, $col, $topn, $minlen, $extra_stop) -> \%cloud
12848 #
12849 # Purpose: The words a text column repeats and how often each appears, ranked,
12850 # which is what both the /wordcloud page and a canvas's word-cloud card
12851 # draw. One function, so the page and the card cannot count differently.
12852 # Entry: $records is a list of rows; $col names the text column; $topn is how
12853 # many words to return; $minlen is the shortest word kept; $extra_stop
12854 # is the reader's own stoplist ("apple,pear"), added to the built-in
12855 # one rather than replacing it.
12856 # Exit: { words => [ { word, count }, ... ] } in cloud order -- count
12857 # descending, then alphabetically -- with distinct (every different word
12858 # seen, before truncation), total (words counted) and rows (rows read).
12859 # Notes: A word counts once per row that contains it, so a long note does not
12860 # outweigh ten short rows that say the same thing.
12861 48 ▶sub _wordcloud_counts {
Subroutine _wordcloud_counts: called CC=10 SCAR=23.1
12862 48 my ($records, $col, $topn, $minlen, $extra_stop) = @_;
12863  
12864 48 my %stop = %STOP_WORD;
12865 48 ▶ for my $extra (split /[\s,]+/, $extra_stop // '') {
Condition100%2/2
$extra_stop // ""
l!l
444
MC/DC100%1/1
$extra_stop // ""
$extra_stop
Truth table100%2/2
A
A= $extra_stop
Aresult
11
00
12866 3 ▶ $stop{ lc $extra } = 1 if length $extra;
Branch: 1 branch
BranchTrueFalseTotal
if length $extra 3 0 3
12867 }
12868  
12869 48 my (%count, $row_count);
12870 48 for my $row (@$records) {
12871 276 $row_count++;
12872 276 my %seen;
12873 276 ▶ $count{$_}++ for grep { !$seen{$_}++ && !$stop{$_} }
Condition100%3/3
$seen{$_}++ || $stop{$_}
l!l&&r!l&&!r
2753
MC/DC100%2/2
$seen{$_}++ || $stop{$_}
$seen{$_}++ $stop{$_}
Truth table100%3/3
A || B
A= $seen{$_}++B= $stop{$_}
ABresult
1X1
011
000
12874 _word_tokens($row->{$col}, $minlen);
12875 }
12876  
12877 48 ▶ my $total = sum(values %count) // 0;
Condition100%2/2
&sum(values %count) // 0
l!l
840
MC/DC100%1/1
&sum(values %count) // 0
&sum(values %count)
Truth table100%2/2
A
A= &sum(values %count)
Aresult
11
00
12878 48 ▶ 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
1170
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
12879 48 my $distinct = scalar @words;
12880 48 ▶ @words = @words[0 .. $topn - 1] if @words > $topn;
Branch: 1 branch
BranchTrueFalseTotal
if @words > $topn 1 47 48
12881  
12882 return {
12883 48 words => [ map { { word => $_, count => $count{$_} } } @words ],
12884 distinct => $distinct,
12885 total => $total,
12886 rows => $row_count,
12887 };
12888 }
12889  
12890 # _wordcloud_link($back, $col, $word, $cloud_url) -> $url
12891 #
12892 # Purpose: The view URL that shows the rows containing one word, with the cloud
12893 # as that page's breadcrumb, so a click on a word is a drill-down.
12894 # Note: The URL is returned unescaped; the caller escapes it once for the
12895 # href it goes into, because HTML::TagCloud writes its input verbatim.
12896 3 ▶sub _wordcloud_link {
Subroutine _wordcloud_link: called CC=2 SCAR=6.9
12897 3 my ($back, $col, $word, $cloud_url) = @_;
12898 3 ▶ my $sep = $back =~ /\?/ ? '&' : '?';
Branch: 1 branch
BranchTrueFalseTotal
$back =~ /\?/u ? : 1 2 3
12899  
12900 3 return $back . $sep . 'f=' . _percent_encode("$col:contains:$word")
12901 . '&back2=' . _percent_encode($cloud_url)
12902 . '&back2_label=' . _percent_encode('Back to word cloud');
12903 }
12904  
12905 52 ▶sub wordcloud_view ($self) {
Subroutine wordcloud_view: called CC=22 SCAR=31.6
Pod documented
12906 52 ▶ my $col = $self->param('col') // '';
Condition100%2/2
$self->param("col") // ""
l!l
502
MC/DC100%1/1
$self->param("col") // ""
$self->param("col")
Truth table100%2/2
A
A= $self->param("col")
Aresult
11
00
12907 52 my $_topn = $self->param('topn');
12908 52 my $_minlen = $self->param('minlen');
12909 52 my $back_raw = $self->param('back');
12910 52 ▶ my $back = _safe_back_url($back_raw) // '/';
Condition50%1/2
_safe_back_url($back_raw) // "/"
l!l
052
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
12911 52 my $back2 = _safe_back_url($self->param('back2'));
12912 52 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
052
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
12913  
12914 # A count that is absent or unreadable is the default, not a clamp of zero:
12915 # ?topn= with nothing after it must not silently show a single word.
12916 52 my $topn = _wordcloud_option($_topn, 50, 1, 500);
12917 52 my $minlen = _wordcloud_option($_minlen, 3, 1, 64);
12918  
12919 52 ▶ return $self->render(text => 'Missing col= parameter', status => 400) unless length $col;
Branch: 1 branch
BranchTrueFalseTotal
unless length $col 3 49 52
12920  
12921 49 my ($src, $records, $columns) = $self->_run_pipeline_source;
12922 49 ▶ return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 2 47 49
12923  
12924 47 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
12925 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
12926  
12927 46 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 45 46
12928  
12929 45 my %col_set = map { $_ => 1 } @$columns;
12930 45 ▶ return $self->render(text => "Column not found: $col", status => 400) unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 1 44 45
12931  
12932 # One pass over the rows, shared with a canvas's word-cloud card so the page
12933 # and the card count the same way.
12934 44 my $cloud = _wordcloud_counts(
12935 $records, $col, $topn, $minlen, $self->param('stop'),
12936 );
12937 44 my @words = map { $_->{word} } @{ $cloud->{words} };
12938 44 my %count = map { $_->{word} => $_->{count} } @{ $cloud->{words} };
12939 44 my $distinct = $cloud->{distinct};
12940 44 my $word_total = $cloud->{total};
12941 44 my $row_count = $cloud->{rows};
12942  
12943 # A word links back to the rows that contain it, so the cloud is a way into
12944 # the data rather than a picture of it. Only when the request names the page
12945 # it came from: a bare /wordcloud URL has no table to filter, and sending a
12946 # click to "/?f=..." would be a dead end.
12947 44 ▶ my $drill = (defined $back_raw && length $back_raw) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $back_raw && length $back_raw ? : 1 43 44
Condition66%2/3
defined $back_raw and length $back_raw
!ll&&!rl&&r
4301
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
12948  
12949 44 my $cloud_url = $self->req->url->path->to_string;
12950 44 my $qs = $self->req->url->query->to_string;
12951 44 ▶ $cloud_url .= "?$qs" if length $qs;
Branch: 1 branch
BranchTrueFalseTotal
if length $qs 44 0 44
12952  
12953 my @tags = map {
12954 44 {
12955 word => _decode_cell($_),
12956 18 ▶ count => $count{$_},
Branch: 1 branch
BranchTrueFalseTotal
$drill ? : 0 18 18
12957 ($drill ? (href => _wordcloud_link($back, $col, $_, $cloud_url)) : ()),
12958 }
12959 } @words;
12960  
12961 # The font size is the module's own logarithm of the count, so a word that
12962 # appears twice as often is one step bigger rather than twice as wide.
12963 44 require HTML::TagCloud;
12964 44 my $ranked = HTML::TagCloud->new(levels => 18);
12965 44 for my $tag (@tags) {
12966 18 my $name = xml_escape($tag->{word});
12967 18 ▶ if (defined $tag->{href}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tag->{'href'}) { } 0 18 18
12968 0 $ranked->add($name, xml_escape($tag->{href}), $tag->{count});
12969 }
12970 else {
12971 18 $ranked->add_static($name, $tag->{count});
12972 }
12973 }
12974  
12975 44 ▶ my $cloud_html = @tags ? $ranked->html_and_css(scalar @tags) : '';
Branch: 1 branch
BranchTrueFalseTotal
@tags ? : 6 38 44
12976  
12977 44 my ($source_url, $source_accessed) = $self->_url_attribution;
12978 44 my $title = "Words in $col";
12979  
12980 # The spec a canvas word-cloud card reads (_render_visual_html), so the
12981 # layout's New canvas / Add to existing canvas buttons save this cloud as
12982 # it is drawn, as they do for every other chart page.
12983 44 my $stop = $self->param('stop');
12984 44 ▶ my %chart_spec = (
Branch: 1 branch
BranchTrueFalseTotal
defined $stop && length $stop ? : 1 43 44
Condition66%2/3
defined $stop and length $stop
!ll&&!rl&&r
4301
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
12985 kind => 'wordcloud',
12986 title => $title,
12987 encode => { col => $col },
12988 options => {
12989 topn => $topn,
12990 minlen => $minlen,
12991 ((defined $stop && length $stop) ? (stop => $stop) : ()),
12992 },
12993 );
12994  
12995 44 my ($platform, $language) = $self->_resolve_template;
12996 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
12997 handler => 'tt',
12998 template => "$platform/$language/wordcloud",
12999 format => 'html',
13000 title => $title,
13001 chart => \%chart_spec,
13002 chart_json => $self->_chart_json(\%chart_spec),
13003 cloud_html => $cloud_html,
13004 words => \@tags,
13005 col => $col,
13006 topn => $topn,
13007 minlen => $minlen,
13008 drill => $drill,
13009 distinct_words => $distinct,
13010 word_total => $word_total,
13011 row_count => $row_count,
13012 back_url => ($back2 // $back),
13013 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
13014 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
13015 source_url => $source_url,
13016 source_accessed => $source_accessed,
13017 language => $language,
13018 );
13019 }
13020  
13021 # ---------------------------------------------------------------------------
13022 # Map (GET /map)
13023 #
13024 # one route, one template, two ways for a row to get a
13025 # position. With lat= and lon= the columns already hold coordinates; with
13026 # loc=<column> every distinct value of that column is geocoded once, by
13027 # Database::BI::Model::Geocode. Answers are remembered in one shared cache in
13028 # the model store, keyed by the place rather than by the file or column that
13029 # named it, so a second visit asks nothing and a second dataset naming the same
13030 # place asks nothing either. Everything before that - the pipeline, calculated
13031 # fields and f= filters - is the same as every other visual, so a map shows the
13032 # filtered, calculated view and not the raw table.
13033 # ---------------------------------------------------------------------------
13034  
13035 # _map_loc_columns($loc) -> @columns
13036 #
13037 # The place-name columns of a map, in order, from loc: one name (a canvas card
13038 # saved before a place could span columns), or a list of them (loc= repeated,
13039 # or a card's encode.loc array). Empty and non-string entries are dropped, and
13040 # a column named twice is used once.
13041 59 ▶sub _map_loc_columns {
Subroutine _map_loc_columns: called CC=5 SCAR=16.1
13042 59 my $loc = shift;
13043 59 ▶ my @names = ref($loc) eq 'ARRAY' ? @{$loc} : ($loc);
Branch: 1 branch
BranchTrueFalseTotal
ref $loc eq 'ARRAY' ? : 49 10 59
13044 59 my %seen;
13045 59 ▶ return grep { defined($_) && !ref($_) && length($_) && !$seen{$_}++ } @names;
Condition100%9/9
defined $_ && !ref($_) && length $_ && !$seen{$_}++
!ll&&!rl&&r
7111
defined $_ and not ref $_ and length $_
!ll&&!rl&&r
5212
defined $_ and not ref $_
!ll&&!rl&&r
3214
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
13046 }
13047  
13048 # _map_loc_text($value) -> ($text) | ()
13049 #
13050 # The text added to the end of each place (loc_text=, a card's
13051 # encode.loc_text): "Virginia, USA" for a column of county names, tidied by
13052 # Geocode->place_text, as bi-geocode's --text is. Nothing is returned for a
13053 # value that is not one short line, which the map page refuses and a card,
13054 # stored unchecked, leaves out.
13055 56 ▶sub _map_loc_text {
Subroutine _map_loc_text: called CC=1 SCAR=0.0
13056 56 my ($value) = @_;
13057 56 require Database::BI::Model::Geocode;
13058 56 return Database::BI::Model::Geocode->place_text($value);
13059 }
13060  
13061 # How many outlines holding several markers the map page lists, the fullest
13062 # first; a map of shops has thousands, and the list is for looking into a few.
13063 5 Readonly my $MAP_OUTLINE_GROUPS_MAX => 50;
13064  
13065 # _map_outline_groups($outlines, \@markers, \@records, \@columns) -> @groups
13066 #
13067 # Purpose: Why a map has fewer outlines than markers, for the reader to look
13068 # into: which outlines hold more than one marker, and which markers
13069 # are in no outline. Geocoded places that land in the wrong county
13070 # show up here, as two places in one outline.
13071 # Entry: $outlines as Boundary's outlines() returns it; each marker has
13072 # lat, lon, row_indexes (or first_row) and, when it was geocoded,
13073 # value (the place); the columns that tell rows apart, for the links.
13074 # Exit: One entry for each outline holding two markers or more, the
13075 # fullest first, at most $MAP_OUTLINE_GROUPS_MAX of them, then one
13076 # with none => 1 for the markers in no outline, when there are any:
13077 # { name, markers, places => [text, ...], rows, filters }. A marker
13078 # still waiting for its outline is in neither. () when every marker
13079 # has an outline to itself.
13080 # Side effects: none.
13081 0 ▶sub _map_outline_groups {
Subroutine _map_outline_groups: not called CC=12 SCAR=50.5
13082 0 my ($outlines, $markers, $records, $columns) = @_;
13083  
13084 0 require Database::BI::Model::Boundary;
13085 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
13086 0 ▶ my %waiting = map { $_ => 1 } @{ $outlines->{pending} // [] };
Condition0%0/2
$outlines->{"pending"} // []
l!l
00
MC/DC0%0/1
$outlines->{"pending"} // []
$outlines->{"pending"}
Truth table0%0/2
A
A= $outlines->{"pending"}
Aresult
11
00
13087 0 my (%held, @none);
13088 0 for my $marker (@{$markers}) {
13089 0 my $key = Database::BI::Model::Boundary->point_key($marker->{lat}, $marker->{lon});
13090 0 ▶ next if !defined($key) || $waiting{$key};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $key or $waiting{$key} 0 0 0
Condition0%0/3
not defined $key or $waiting{$key}
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $key or $waiting{$key}
not defined $key $waiting{$key}
Truth table0%0/3
not(A) or B
A= not defined $keyB= $waiting{$key}
ABresult
1X1
011
000
13091 0 ▶ if (defined(my $osm = $inside->{$key})) { push @{ $held{$osm} }, $marker }
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $osm = $inside->{$key})) { } 0 0 0
13092 0 else { push @none, $marker }
13093 }
13094  
13095 0 ▶ my $group = sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
13096 0 my ($name, $in, %more) = @_;
13097 0 ▶ my @rows = map { @{ $_->{row_indexes} // [ $_->{first_row} ] } } @{$in};
Condition0%0/2
$_->{"row_indexes"} // [$_->{"first_row"}]
l!l
00
MC/DC0%0/1
$_->{"row_indexes"} // [$_->{"first_row"}]
$_->{"row_indexes"}
Truth table0%0/2
A
A= $_->{"row_indexes"}
Aresult
11
00
13098 return {
13099 name => $name,
13100 0 markers => scalar(@{$in}),
13101 # A geocoded marker is known by its place, another by where it is
13102 places => [ map {
13103 (defined($_->{value}) && !ref($_->{value}) && length($_->{value}))
13104 0 ▶ ? $_->{value} : "$_->{lat}, $_->{lon}"
Branch: 1 branch
BranchTrueFalseTotal
defined $_->{'value'} && !ref($_->{'value'}) && length $_->{'value'} ? : 0 0 0
Condition0%0/6
defined $_->{"value"} and not ref $_->{"value"} and length $_->{"value"}
!ll&&!rl&&r
000
defined $_->{"value"} and not ref $_->{"value"}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $_->{"value"} and not ref $_->{"value"} and length $_->{"value"}
defined $_->{"value"} not ref $_->{"value"} length $_->{"value"}
Truth table0%0/4
A and not(B) and C
A= defined $_->{"value"}B= not ref $_->{"value"}C= length $_->{"value"}
ABCresult
0XX0
10X0
1100
1111
13105 0 } @{$in} ],
13106 rows => scalar(@rows),
13107 filters => [ _map_rows_filters($records, \@rows, $columns) ],
13108 %more,
13109 };
13110 0 };
13111  
13112 0 ▶ my @shared = grep { @{ $held{ $_->{properties}{osm} // '' } // [] } > 1 } @{ $outlines->{features} };
Condition0%0/4
$held{$_->{"properties"}{"osm"} // ""} // []
l!l
00
$_->{"properties"}{"osm"} // ""
l!l
00
MC/DC0%0/1
$held{$_->{"properties"}{"osm"} // ""} // []
$held{$_->{"properties"}{"osm"} // ""}
MC/DC0%0/1
$_->{"properties"}{"osm"} // ""
$_->{"properties"}{"osm"}
Truth table0%0/2
A
A= $held{$_->{"properties"}{"osm"} // ""}
Aresult
11
00
Truth table0%0/2
A
A= $_->{"properties"}{"osm"}
Aresult
11
00
13113 @shared = sort {
13114 0 @{ $held{ $b->{properties}{osm} } } <=> @{ $held{ $a->{properties}{osm} } }
13115 } @shared;
13116 0 ▶ splice(@shared, $MAP_OUTLINE_GROUPS_MAX) if @shared > $MAP_OUTLINE_GROUPS_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if @shared > $MAP_OUTLINE_GROUPS_MAX 0 0 0
13117  
13118 return (
13119 0 ▶ (map { $group->($_->{properties}{name} // '', $held{ $_->{properties}{osm} }) } @shared),
Branch: 1 branch
BranchTrueFalseTotal
@none ? : 0 0 0
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
13120 (@none ? $group->('', \@none, none => 1) : ()),
13121 );
13122 }
13123  
13124 # _map_rows_filters(\@records, \@row_indexes, \@columns) -> @filters
13125 #
13126 # Purpose: Filters that select exactly the given rows, for a link from the
13127 # map to them in the table.
13128 # Entry: Indexes into @records; the columns that tell the rows apart (the
13129 # place columns, or latitude and longitude).
13130 # Exit: One "col:in:[...]" filter a column, listing the cells those rows
13131 # hold. () when together they would select another row too (two
13132 # columns' lists can pair up into a row that was not asked for), or
13133 # when no row or column is given: a link must not show the wrong rows.
13134 # Side effects: none.
13135 0 ▶sub _map_rows_filters {
Subroutine _map_rows_filters: not called CC=7 SCAR=40.3
13136 0 my ($records, $indexes, $columns) = @_;
13137  
13138 0 my @rows = grep { ref($_) eq 'HASH' } map { $records->[$_] } @{$indexes};
13139 0 ▶ return () unless @rows && @{$columns};
Branch: 1 branch
BranchTrueFalseTotal
unless @rows and @{$columns;} 0 0 0
Condition0%0/3
@rows and @{$columns;}
!ll&&!rl&&r
000
MC/DC0%0/2
@rows and @{$columns;}
@rows @{$columns;}
Truth table0%0/3
A and B
A= @rowsB= @{$columns;}
ABresult
0X0
100
111
13140  
13141 my @filters = map {
13142 0 my $col = $_;
13143 0 ▶ my %cells = map { my $cell = $_->{$col}; ((defined($cell) && !ref($cell)) ? $cell : '') => 1 } @rows;
Branch: 1 branch
BranchTrueFalseTotal
defined $cell && !ref($cell) ? : 0 0 0
Condition0%0/3
defined $cell and not ref $cell
!ll&&!rl&&r
000
MC/DC0%0/2
defined $cell and not ref $cell
defined $cell not ref $cell
Truth table0%0/3
A and not(B)
A= defined $cellB= not ref $cell
ABresult
0X0
100
111
13144 0 "$col:in:" . to_json([ sort keys %cells ]);
13145 0 } @{$columns};
13146  
13147 # Tried on every row: the filters are kept only if they find just these
13148 0 my $hit = [ grep { ref($_) eq 'HASH' } @{$records} ];
13149 0 $hit = _apply_filter_spec($hit, $_) for @filters;
13150 0 ▶ return scalar(@{$hit}) == scalar(@rows) ? @filters : ();
Branch: 1 branch
BranchTrueFalseTotal
scalar @{$hit;} == scalar @rows ? : 0 0 0
13151 }
13152  
13153 # _map_unplotted(\@records, \@places, $loc_col, \@loc_cols, \%resolved)
13154 # -> (\@entries, \@all_filters)
13155 #
13156 # The places a geocoded map could not plot, so that the page can say which
13157 # they are: one entry for each, in the order of the first row that names it,
13158 # as { place, rows, reason, filters }. reason is 'empty' (no place in the
13159 # row), 'refused' (not a place name: a bare number), 'not_found', or 'later'
13160 # (not looked up yet: past a cap, or waiting for OpenStreetMap). filters are
13161 # f= specs that select the place's rows in the table, built from the cells of
13162 # its first row: one for each place column, eq that cell, or empty.
13163 #
13164 # @all_filters select every unplotted row at once: for each place column, in
13165 # the list of its cells in those rows. Columns filtered apart can pair a cell
13166 # of one row with a cell of another, which may name a place that was plotted,
13167 # so the filters are tried on the rows and kept only when they select exactly
13168 # the unplotted ones; otherwise @all_filters is empty.
13169 9 ▶sub _map_unplotted {
Subroutine _map_unplotted: called CC=27 SCAR=33.1
13170 9 my ($records, $places, $loc_col, $loc_cols, $resolved) = @_;
13171  
13172 9 my %reason;
13173 9 ▶ for my $value (@{ $resolved->{skipped} // [] }) {
Condition100%2/2
$resolved->{"skipped"} // []
l!l
63
MC/DC100%1/1
$resolved->{"skipped"} // []
$resolved->{"skipped"}
Truth table100%2/2
A
A= $resolved->{"skipped"}
Aresult
11
00
13174 5 ▶ my $key = (defined($value) && !ref($value)) ? $value : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $value && !ref($value) ? : 5 0 5
Condition33%1/3
defined $value and not ref $value
!ll&&!rl&&r
005
MC/DC0%0/2
defined $value and not ref $value
defined $value not ref $value
Truth table33%1/3
A and not(B)
A= defined $valueB= not ref $value
ABresult
0X0
100
111
13175 5 ▶ $reason{$key} = length($key) ? 'refused' : 'empty';
Branch: 1 branch
BranchTrueFalseTotal
length $key ? : 1 4 5
13176 }
13177 9 ▶ $reason{$_} = 'not_found' for grep { defined } @{ $resolved->{unresolved} // [] };
Condition100%2/2
$resolved->{"unresolved"} // []
l!l
81
MC/DC100%1/1
$resolved->{"unresolved"} // []
$resolved->{"unresolved"}
Truth table100%2/2
A
A= $resolved->{"unresolved"}
Aresult
11
00
13178 9 ▶ $reason{$_} = 'later' for grep { defined } @{ $resolved->{not_attempted} // [] };
Condition100%2/2
$resolved->{"not_attempted"} // []
l!l
63
MC/DC100%1/1
$resolved->{"not_attempted"} // []
$resolved->{"not_attempted"}
Truth table100%2/2
A
A= $resolved->{"not_attempted"}
Aresult
11
00
13179  
13180 9 my (%rows, %first, %cells);
13181 9 my $total = 0;
13182 9 for my $index (0 .. $#{$places}) {
13183 26 my $place = $places->[$index];
13184 26 ▶ my $value = ref($place) eq 'HASH' ? $place->{$loc_col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $place eq 'HASH' ? : 25 1 26
13185 26 ▶ my $key = (defined($value) && !ref($value)) ? $value : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $value && !ref($value) ? : 25 1 26
Condition66%2/3
defined $value and not ref $value
!ll&&!rl&&r
1025
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
13186 26 ▶ next unless exists $reason{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $reason{$key} 9 17 26
13187 17 $rows{$key}++;
13188 17 $total++;
13189 17 ▶ $first{$key} //= $index;
Condition66%2/3
$first{$key} //= $index
l!l&&r!l&&!r
2150
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
13190  
13191 17 my $row = $records->[$index];
13192 17 for my $col (@{$loc_cols}) {
13193 24 ▶ my $cell = ref($row) eq 'HASH' ? $row->{$col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $row eq 'HASH' ? : 23 1 24
13194 24 ▶ $cells{$col}{ (defined($cell) && !ref($cell)) ? $cell : '' } = 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $cell && !ref($cell) ? : 23 1 24
Condition66%2/3
defined $cell and not ref $cell
!ll&&!rl&&r
1023
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
13195 }
13196 }
13197  
13198 9 my @all_filters;
13199 9 ▶ if ($total) {
Branch: 1 branch
BranchTrueFalseTotal
if ($total) 7 2 9
13200 7 @all_filters = map { "$_:in:" . to_json([ sort keys %{ $cells{$_} } ]) } @{$loc_cols};
13201 # Only rows can be filtered; one that is not is never selected.
13202 7 my $hit = [ grep { ref($_) eq 'HASH' } @{$records} ];
13203 7 $hit = _apply_filter_spec($hit, $_) for @all_filters;
13204 7 ▶ @all_filters = () unless scalar(@{$hit}) == $total;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @{$hit;} == $total 2 5 7
13205 }
13206  
13207 my @entries = map {
13208 15 my $row = $records->[ $first{$_} ];
13209 15 ▶ $row = {} unless ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 1 14 15
13210 +{
13211 place => $_,
13212 rows => $rows{$_},
13213 reason => $reason{$_},
13214 filters => [ map {
13215 21 my $cell = $row->{$_};
13216 21 ▶ (defined($cell) && !ref($cell) && length($cell)) ? "$_:eq:$cell" : "$_:empty";
Branch: 1 branch
BranchTrueFalseTotal
defined $cell && !ref($cell) && length $cell ? : 15 6 21
Condition83%5/6
defined $cell and not ref $cell and length $cell
!ll&&!rl&&r
1515
defined $cell and not ref $cell
!ll&&!rl&&r
1020
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
13217 15 } @{$loc_cols} ],
13218 };
13219 9 } sort { $first{$a} <=> $first{$b} } keys %first;
13220  
13221 9 return (\@entries, \@all_filters);
13222 }
13223  
13224 # _map_region($config) -> $region or undef
13225 #
13226 # The country hint for the local geocoder: config map_region when it is two
13227 # letters, else none.
13228 17 ▶sub _map_region {
Subroutine _map_region: called CC=4 SCAR=13.9
13229 17 my $cfg = shift;
13230 17 my $region = $cfg->{map_region};
13231  
13232 17 ▶ 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 16 17
Condition100%6/6
defined $region and not ref $region and $region =~ /\A[A-Za-z]{2}\z/u
!ll&&!rl&&r
1151
defined $region and not ref $region
!ll&&!rl&&r
1016
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
13233 }
13234  
13235 # _map_geocoder($self, $online) -> Database::BI::Model::Geocode
13236 #
13237 # The geocoder a map asks, built from the config the same way for the map page,
13238 # a canvas card and /geo/lookup. The geocoder is a config seam first and a
13239 # recommended dependency second: a deployment may hand in an object, and a test
13240 # does exactly that. With neither, the model reports the module as unavailable
13241 # and the map is still the map.
13242 #
13243 # map_geocode_online => 0 keeps every lookup on this machine: a place the local
13244 # data does not know is then not sent to OpenStreetMap. A false $online does
13245 # the same for one request (the progress run, once Nominatim has failed).
13246 # Geo::Coder::List keeps its answers in files, so a place Nominatim found is not
13247 # asked again by another request, worker or restart. Geocode->new chooses the
13248 # directory (Object::Configure, CACHEDIR, CACHE_DIR, cache_dir in this config,
13249 # then <model_dir>/geocode-cache). A model_dir that is refused (inside
13250 # data_dir) gives no default, and with nothing else set the module falls back
13251 # on a cache in this process's memory.
13252 13 ▶sub _map_geocoder :Protected ($self, $online) {
Subroutine _map_geocoder: called CC=10 SCAR=23.6
13253 13 require Database::BI::Model::Geocode;
13254  
13255 13 my $cfg = $self->app->config;
13256 13 my $models_path = $self->_calc_models_path;
13257 13 my $injected = $cfg->{geocoder};
13258  
13259 return Database::BI::Model::Geocode->new(
13260 (defined($models_path)
13261 ? (model_dir => Mojo::File->new($models_path)->dirname->to_string)
13262 : ()),
13263 config => $cfg,
13264 home => $self->app->home->to_string,
13265 (defined($injected) && ref($injected) && $injected->can('geocode_many')
13266 ? (geocoder => $injected) : ()),
13267 (defined($cfg->{openaddr}) && length($cfg->{openaddr})
13268 ? (openaddr => $cfg->{openaddr}) : ()),
13269 online => (($online && ($cfg->{map_geocode_online} // 1)) ? 1 : 0),
13270 13 ▶ online_max => _map_limit($cfg->{map_geocode_online_max}, $DEFAULT_MAP_GEOCODE_ONLINE_MAX),
Branch: 4 branches
BranchTrueFalseTotal
defined $models_path ? : 13 0 13
defined $injected && ref $injected && $injected->can('geocode_many') ? : 10 3 13
defined $cfg->{'openaddr'} && length $cfg->{'openaddr'} ? : 0 13 13
$online && ($cfg->{'map_geocode_online'} // 1) ? : 9 4 13
Condition78%11/14
defined $injected and ref $injected and $injected->can("geocode_many")
!ll&&!rl&&r
3010
defined $injected and ref $injected
!ll&&!rl&&r
1210
defined $cfg->{"openaddr"} and length $cfg->{"openaddr"}
!ll&&!rl&&r
1300
$online and $cfg->{"map_geocode_online"} // 1
!ll&&!rl&&r
139
$cfg->{"map_geocode_online"} // 1
l!l
39
MC/DC66%2/3
defined $injected and ref $injected and $injected->can("geocode_many")
defined $injected ref $injected $injected->can("geocode_many")
MC/DC0%0/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 table33%1/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
13271 );
13272 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13273  
13274 # _map_boundary($self, $level, $online) -> Database::BI::Model::Boundary
13275 #
13276 # What finds the outline around each marker, for the map and /geo/boundary
13277 # alike. It asks OpenStreetMap only when the operator allows the geocoder to
13278 # (map_geocode_online), and at most map_geocode_online_max times a request.
13279 # Its answers are kept beside the geocode cache, under model_dir, so they
13280 # outlive the process and are shared by every worker; with no model_dir it
13281 # keeps them in memory. Config map_bounds_ranks adds or changes the place rank
13282 # that is a county in a country (checked at startup).
13283 0 ▶sub _map_boundary :Protected ($self, $level, $online) {
Subroutine _map_boundary: not called CC=7 SCAR=40.3
13284 0 require Database::BI::Model::Boundary;
13285  
13286 0 my $cfg = $self->app->config;
13287 0 my $models_path = $self->_calc_models_path;
13288 0 my $cache;
13289 0 ▶ if (defined $models_path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $models_path) 0 0 0
13290 0 my $dir = Mojo::File->new($models_path)->dirname->to_string;
13291 0 $cache = eval { Database::BI::Model::Boundary->file_cache($dir) };
13292 }
13293  
13294 return Database::BI::Model::Boundary->new(
13295 level => $level,
13296 online => (($online && ($cfg->{map_geocode_online} // 1)) ? 1 : 0),
13297 online_max => _map_limit($cfg->{map_geocode_online_max}, $DEFAULT_MAP_GEOCODE_ONLINE_MAX),
13298 (defined($cache) ? (cache => $cache) : ()),
13299 0 ▶ (ref($cfg->{map_bounds_ranks}) eq 'HASH' ? (ranks => $cfg->{map_bounds_ranks}) : ()),
Branch: 3 branches
BranchTrueFalseTotal
$online && ($cfg->{'map_geocode_online'} // 1) ? : 0 0 0
defined $cache ? : 0 0 0
ref $cfg->{'map_bounds_ranks'} eq 'HASH' ? : 0 0 0
Condition0%0/5
$online and $cfg->{"map_geocode_online"} // 1
!ll&&!rl&&r
000
$cfg->{"map_geocode_online"} // 1
l!l
00
MC/DC0%0/2
$online and $cfg->{"map_geocode_online"} // 1
$online $cfg->{"map_geocode_online"}
Truth table0%0/3
A and B
A= $onlineB= $cfg->{"map_geocode_online"}
ABresult
0X0
100
111
13300 );
13301 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13302  
13303 # The colours of county outlines on a heat map, low to high: green, amber,
13304 # red, as the top of the heat layer's own gradient (lime, yellow, red). An
13305 # outline's colour is one of $OUTLINE_STEPS steps between them, so outlines of
13306 # about the same total share a layer.
13307 5 Readonly my @OUTLINE_STOPS => ([ 0x1a, 0x98, 0x50 ], [ 0xf5, 0xa6, 0x23 ], [ 0xd7, 0x30, 0x27 ]);
13308 5 Readonly my $OUTLINE_STEPS => 9;
13309 # How an outline is drawn: thin and grey on a plain map, heavier when its
13310 # colour carries a meaning, so the colour can be told apart on a busy map.
13311 5 Readonly my %OUTLINE_PLAIN => (colour => '#555555', weight => 1.5, opacity => 0.8);
13312 5 Readonly my %OUTLINE_HEAT => (weight => 2.5, opacity => 0.9);
13313 # Colour shade (shade=): each outline filled in a shade of one colour, darker
13314 # for a larger total, as a census map is. $SHADE_STEPS shades, the lightest
13315 # $SHADE_LIGHTEST of the way from white to the colour so that it still shows;
13316 # the fill lets the map underneath through.
13317 5 Readonly my $SHADE_STEPS => 5;
13318 5 Readonly my $SHADE_LIGHTEST => 0.15;
13319 5 Readonly my $SHADE_OPACITY => 0.65;
13320 5 Readonly my $DEFAULT_SHADE_COLOR => '#d94801';
13321 # A key's totals are rounded to $KEY_FIGURES significant figures, from
13322 # $KEY_ROUND_FROM up; smaller ones are short enough as they are.
13323 5 Readonly my $KEY_FIGURES => 2;
13324 5 Readonly my $KEY_ROUND_FROM => 100;
13325 # The HTML::OSM whose marker key can leave an entry out while a layer is shown
13326 # (a legend entry's unless_layer).
13327 5 Readonly my $OSM_KEY_WAITS_VERSION => '0.19';
13328  
13329 # _map_outline_layers($self, $outlines, \@markers, $records, $weight_col)
13330 # -> list of { features, colour, weight, opacity }
13331 #
13332 # The county outlines as layers for add_geojson. Without the heat layer
13333 # ($weight_col undef) they are one grey layer. With it, each outline is
13334 # coloured by the total of what is in it: the weight column summed over every
13335 # row of every marker inside it (a cell that is not a number adds nothing), or,
13336 # with no weight column (''), its rows counted. _outline_shares places each
13337 # total between green and red. A lone outline, or totals all alike, stays
13338 # grey with no key, having nothing to be compared with; $noun is what an
13339 # outline is called there, for the key's title. The layers go from low to high, so where two
13340 # outlines share a border the higher is drawn on top; the first carries the
13341 # key to the colours, high to low with the totals each covers. Each popup names the
13342 # outline and its total. Leaflet reads a popup as HTML, and a name from
13343 # OpenStreetMap is text, so it is escaped.
13344 3 ▶sub _map_outline_layers :Protected ($self, $outlines, $markers, $records, $weight_col, $noun) {
Subroutine _map_outline_layers: called CC=13 SCAR=50.7
13345 0 ▶ return () unless $outlines && @{ $outlines->{features} };
Branch: 1 branch
BranchTrueFalseTotal
unless $outlines and @{$outlines->{"features"};} 3 0 3
Condition33%1/3
$outlines and @{$outlines->{"features"};}
!ll&&!rl&&r
300
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
13346  
13347 0 my @features = @{ $outlines->{features} };
13348 0 ▶ my $named = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
13349 0 my ($feature, $text) = @_;
13350 # osm stays, so the fill (shade=) can find the outline's total
13351 0 return { %{$feature}, properties => { name => xml_escape($text), osm => $feature->{properties}{osm} } };
13352 0 };
13353  
13354 # No heat layer: nothing to total, so one grey layer and no key.
13355 0 ▶ unless (defined $weight_col) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $weight_col) 0 0 0
13356 return {
13357 0 ▶ features => [ map { $named->($_, $_->{properties}{name} // '') } @features ],
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
13358 %OUTLINE_PLAIN,
13359 };
13360 }
13361  
13362 0 ▶ my $total = $self->_map_outline_totals($outlines->{inside} // {}, $markers, $records, $weight_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
13363 0 ▶ my @totals = map { $total->{ $_->{properties}{osm} } // 0 } @features;
Condition0%0/2
$$total{$_->{"properties"}{"osm"}} // 0
l!l
00
MC/DC0%0/1
$$total{$_->{"properties"}{"osm"}} // 0
$$total{$_->{"properties"}{"osm"}}
Truth table0%0/2
A
A= $$total{$_->{"properties"}{"osm"}}
Aresult
11
00
13364  
13365 0 my %seen;
13366 0 my @distinct = grep { !$seen{$_}++ } sort { $a <=> $b } @totals;
13367  
13368 # One outline, or totals all alike: there is nothing to compare, so a
13369 # colour would mean nothing. Grey, with no key, but the popups still
13370 # give the totals.
13371 0 ▶ if (@distinct < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@distinct < 2) 0 0 0
13372 return {
13373 features => [ map {
13374 0 $named->($features[$_], $self->_map_outline_popup(
13375 0 ▶ $features[$_]{properties}{name} // '', $totals[$_], $weight_col))
Condition0%0/2
$features[$_]{"properties"}{"name"} // ""
l!l
00
MC/DC0%0/1
$features[$_]{"properties"}{"name"} // ""
$features[$_]{"properties"}{"name"}
Truth table0%0/2
A
A= $features[$_]{"properties"}{"name"}
Aresult
11
00
13376 } 0 .. $#features ],
13377 %OUTLINE_PLAIN,
13378 };
13379 }
13380 0 my $share_of = _outline_shares(\@distinct);
13381  
13382 # Lowest first: a layer is made the first time its step is met, so the
13383 # layers come out in the order they must be drawn.
13384 0 my (%layer_of, @layers);
13385 0 for my $i (sort { $totals[$a] <=> $totals[$b] } 0 .. $#features) {
13386 0 my $share = $share_of->{ $totals[$i] };
13387 0 my $step = int($share * ($OUTLINE_STEPS - 1) + 0.5);
13388 0 ▶ my $layer = $layer_of{$step} //= do {
Condition0%0/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
000
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 table0%0/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
13389 0 push @layers, { features => [], totals => [],
13390 colour => _outline_colour($step / ($OUTLINE_STEPS - 1)), %OUTLINE_HEAT };
13391 0 $layers[-1];
13392 };
13393 # Sorted already, so each layer's totals are low to high for the key.
13394 0 push @{ $layer->{totals} }, $totals[$i];
13395 0 my $feature = $features[$i];
13396 0 ▶ push @{ $layer->{features} }, $named->($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
13397 0 $self->_map_outline_popup($feature->{properties}{name} // '', $totals[$i], $weight_col));
13398 # Drawn inside its own edge (HTML::OSM 0.17's bands), so a neighbour of
13399 # another colour is beside it, not over it.
13400 0 $layer->{features}[-1]{properties}{colours} = [ $layer->{colour} ];
13401 0 $layer->{bands} = 1;
13402 }
13403  
13404 # HTML::OSM 0.16 shows one key a layer name and hides it with the layer;
13405 # an older copy ignores it. The totals were only for the key.
13406 0 $layers[0]{key} = $self->_map_outline_key(\@layers, $weight_col, $noun);
13407 0 delete $_->{totals} for @layers;
13408 0 return @layers;
13409 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13410  
13411 # _map_outline_marker_layers($self, $outlines, \@markers)
13412 # -> list of { features, colour, weight, opacity, bands }
13413 #
13414 # Purpose: The outlines coloured as the markers in them, for a map whose
13415 # markers are coloured by a column.
13416 # Entry: $outlines as Boundary's outlines() returns it, or undef; each
13417 # coloured marker has lat, lon and colour (#rgb or #rrggbb).
13418 # Exit: One layer for each distinct list of colours, the outlines of one
13419 # colour first. An outline whose markers differ lists every colour,
13420 # the one most of its markers have first (the earliest on a tie), in
13421 # its feature's "colours" property. A coloured layer has bands set:
13422 # HTML::OSM 0.17 then draws each outline just inside its own edge, a
13423 # line of each colour side by side, the first outermost, so
13424 # neighbours of different colours are beside each other; "colour"
13425 # (the first) is what an older HTML::OSM draws, along the edge. () when there is nothing to draw or no marker has a
13426 # colour, so the caller can fall back.
13427 # Side effects: none.
13428 0 ▶sub _map_outline_marker_layers :Protected ($self, $outlines, $markers) {
Subroutine _map_outline_marker_layers: not called CC=19 SCAR=59.4
13429 0 ▶ return () unless $outlines && @{ $outlines->{features} };
Branch: 1 branch
BranchTrueFalseTotal
unless $outlines and @{$outlines->{"features"};} 0 0 0
Condition0%0/3
$outlines and @{$outlines->{"features"};}
!ll&&!rl&&r
000
MC/DC0%0/2
$outlines and @{$outlines->{"features"};}
$outlines @{$outlines->{"features"};}
Truth table0%0/3
A and B
A= $outlinesB= @{$outlines->{"features"};}
ABresult
0X0
100
111
13430  
13431 0 require Database::BI::Model::Boundary;
13432 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
13433 # How many markers of each colour are in each outline, in the order the
13434 # colours were first met there.
13435 0 my (%count, %order);
13436 0 for my $marker (@{$markers}) {
13437 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
13438 # The script takes #rrggbb only, so #rgb is written out in full
13439 0 $colour =~ s/\A#(.)(.)(.)\z/#$1$1$2$2$3$3/;
13440 0 my $key = Database::BI::Model::Boundary->point_key($marker->{lat}, $marker->{lon});
13441 0 ▶ my $osm = defined($key) ? $inside->{$key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $key ? : 0 0 0
13442 0 ▶ next unless defined $osm;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $osm 0 0 0
13443 0 ▶ push @{ $order{$osm} }, $colour unless $count{$osm}{$colour}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $count{$osm}{$colour}++ 0 0 0
13444 }
13445 0 ▶ return () unless %count;
Branch: 1 branch
BranchTrueFalseTotal
unless %count 0 0 0
13446  
13447 0 my (%layer_of, @layers);
13448 0 for my $feature (@{ $outlines->{features} }) {
13449 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
13450 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
13451 0 my %place = map { $seen->[$_] => $_ } 0 .. $#{$seen};
13452 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
13453 # An outline none of whose markers is coloured stays grey
13454 0 ▶ my $style = @colours ? { colour => $colours[0], %OUTLINE_HEAT } : { %OUTLINE_PLAIN };
Branch: 1 branch
BranchTrueFalseTotal
@colours ? : 0 0 0
13455 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
13456 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
13457 0 $layers[-1];
13458 };
13459 # Leaflet reads a popup as HTML, and a name from OpenStreetMap is text
13460 0 push @{ $layer->{features} }, {
13461 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
13462 0 properties => { name => xml_escape($feature->{properties}{name} // ''), colours => \@colours, osm => $osm },
13463 };
13464 }
13465 # Those of several colours last: only an older HTML::OSM, which draws every
13466 # outline along its edge, can draw one over another, and then they show.
13467 0 return sort { $a->{mixed} <=> $b->{mixed} } @layers;
13468 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13469  
13470 # _map_outline_shade($self, \@layers, $outlines, \@markers, $records, $col, $colour, $noun, $lower)
13471 # -> list of layers, each with fill
13472 #
13473 # Purpose: Colour shade: fill each outline in a shade of a colour, by the
13474 # total of $col in it.
13475 # Entry: @layers as _map_outline_layers or _map_outline_marker_layers made
13476 # them (each feature keeps its osm and an escaped name); $col is a
13477 # column of $records. $colour is the one colour to shade, as
13478 # _parse_color takes one, or undef for the default. $lower, when a
13479 # hashref, says the markers are coloured and no colour was asked for:
13480 # each outline is then shaded in its own line colour (its markers'),
13481 # and $lower->{<#rrggbb>} is true for a colour whose rule is "less
13482 # than", where the smaller total is the stronger.
13483 # Exit: Each layer split by shade, so every part has one line style and
13484 # one "fill" (#rrggbb), in the order given. One colour: darker for a
13485 # larger total, across every outline. The markers' colours: each
13486 # colour is a scale of its own over the outlines of that colour,
13487 # stronger the further the total is into what the colour stands for
13488 # (larger, or smaller for a "less than" colour), so a county well
13489 # under a "below 20,000" rule is greener than one just under it; a
13490 # colour with one total is its middle shade. The shade follows
13491 # _outline_shares, as the heat colours do. Each popup names the
13492 # outline and its total; the first layer carries the key, every
13493 # shade in use by size, the largest totals first, drawn as boxes (HTML::OSM 0.18; an older copy
13494 # draws lines). () with one colour when fewer than two totals
13495 # differ: nothing to compare, so the caller leaves the outlines
13496 # unfilled.
13497 # Side effects: none.
13498 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
13499 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
13500  
13501 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
13502 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
13503 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
13504  
13505 # The colour each layer is shaded in: the one colour, or its own line's.
13506 # Written out as #rrggbb, which _shade_colour reads.
13507 0 ▶ my $hue_of = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
13508 0 ▶ my $hue = $lower ? $_[0]{colour} : $one;
Branch: 1 branch
BranchTrueFalseTotal
$lower ? : 0 0 0
13509 0 $hue =~ s/\A#(.)(.)(.)\z/#$1$1$2$2$3$3/;
13510 0 return lc $hue;
13511 0 };
13512  
13513 # Each colour's totals, then where each sits on that colour's scale.
13514 0 my (%totals_of, @hues);
13515 0 for my $layer (@{$layers}) {
13516 0 my $hue = $hue_of->($layer);
13517 0 ▶ push @hues, $hue unless $totals_of{$hue};
Branch: 1 branch
BranchTrueFalseTotal
unless $totals_of{$hue} 0 0 0
13518 0 $totals_of{$hue}{ $amount->($_) } = 1 for @{ $layer->{features} };
13519 }
13520 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
13521 0 my %share_of;
13522 0 for my $hue (@hues) {
13523 0 my @distinct = sort { $a <=> $b } keys %{ $totals_of{$hue} };
13524 0 ▶ my $shares = @distinct > 1 ? _outline_shares(\@distinct) : { $distinct[0] => 0.5 };
Branch: 1 branch
BranchTrueFalseTotal
@distinct > 1 ? : 0 0 0
13525 # A "less than" colour is the stronger the smaller the total
13526 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
13527 0 $share_of{$hue} = $shares;
13528 }
13529  
13530 0 my (@shaded, %amounts);
13531 0 for my $layer (@{$layers}) {
13532 0 my $hue = $hue_of->($layer);
13533 0 my (%part, @steps);
13534 0 for my $feature (@{ $layer->{features} }) {
13535 0 my $sum = $amount->($feature);
13536 0 my $step = int($share_of{$hue}{$sum} * ($SHADE_STEPS - 1) + 0.5);
13537 0 ▶ push @steps, $step unless $part{$step};
Branch: 1 branch
BranchTrueFalseTotal
unless $part{$step} 0 0 0
13538 0 push @{ $amounts{$hue}{$step} }, $sum;
13539 # The name is escaped already; the column is text of the reader's
13540 0 push @{ $part{$step} }, {
13541 0 %{$feature},
13542 properties => {
13543 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
13544 name => $self->_i18n('map_bounds_total',
13545 0 $feature->{properties}{name} // '', _map_total_text($sum), xml_escape($col)),
13546 },
13547 };
13548 }
13549 push @shaded, map {
13550 0 +{ %{$layer}, features => $part{$_}, fill => _shade_colour($hue, $_ / ($SHADE_STEPS - 1)) }
13551 0 } sort { $a <=> $b } @steps;
13552 }
13553  
13554 # One key for the fills, in place of any the lines had: for each colour
13555 # the shades in use, strongest first as _map_outline_key lists them,
13556 # drawn as boxes.
13557 0 delete $_->{key} for @shaded;
13558 # They are listed by size whatever their colour, the largest totals at the
13559 # top, so a key of red above 100,000 and green below 20,000 runs from the
13560 # strongest red down to the strongest green.
13561 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
13562 0 my $hue = $_;
13563 map {
13564 +{ colour => _shade_colour($hue, $_ / ($SHADE_STEPS - 1)),
13565 0 totals => [ sort { $a <=> $b } @{ $amounts{$hue}{$_} } ] }
13566 0 } keys %{ $amounts{$hue} };
13567 } @hues;
13568 0 $shaded[0]{key} = { %{ $self->_map_outline_key(\@in_use, $col, $noun) }, shape => 'box' };
13569 0 return @shaded;
13570 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13571  
13572 # _shade_colour($hex, $share) -> '#rrggbb': $hex (#rrggbb) at its full
13573 # strength for a share of 1, down to $SHADE_LIGHTEST of the way from white for
13574 # a share of 0.
13575 0 ▶sub _shade_colour {
Subroutine _shade_colour: not called CC=3 SCAR=24.8
13576 0 my ($hex, $share) = @_;
13577 0 ▶ $share = 0 if $share < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $share < 0 0 0 0
13578 0 ▶ $share = 1 if $share > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $share > 1 0 0 0
13579 0 my $strength = $SHADE_LIGHTEST + (1 - $SHADE_LIGHTEST) * $share;
13580 return sprintf('#%02x%02x%02x',
13581 0 map { int(255 + (hex($_) - 255) * $strength + 0.5) } $hex =~ /\A#(..)(..)(..)\z/);
13582 }
13583  
13584 # _map_outline_totals($self, \%inside, \@markers, $records, $weight_col) -> \%total
13585 #
13586 # Purpose: What is in each outline, for its colour.
13587 # Entry: %inside maps a point key to the osm of the outline it is in (from
13588 # Boundary's outlines()); each marker has lat, lon and row_indexes
13589 # (or first_row); $weight_col is a column, or '' to count rows.
13590 # Exit: { osm => total }; an outline no marker is in has no entry.
13591 # Side effects: none. Rows are only read, so locked SQL rows are safe.
13592 0 ▶sub _map_outline_totals :Protected ($self, $inside, $markers, $records, $weight_col) {
Subroutine _map_outline_totals: not called CC=10 SCAR=47.0
13593 0 require Database::BI::Model::Boundary;
13594 0 my %total;
13595 0 for my $marker (@{$markers}) {
13596 0 my $key = Database::BI::Model::Boundary->point_key($marker->{lat}, $marker->{lon});
13597 0 ▶ my $osm = defined($key) ? $inside->{$key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $key ? : 0 0 0
13598 0 ▶ next unless defined $osm;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $osm 0 0 0
13599 # A marker stands for every row at its place, not only the first.
13600 0 ▶ for my $index (@{ $marker->{row_indexes} // [ $marker->{first_row} ] }) {
Condition0%0/2
$marker->{"row_indexes"} // [$marker->{"first_row"}]
l!l
00
MC/DC0%0/1
$marker->{"row_indexes"} // [$marker->{"first_row"}]
$marker->{"row_indexes"}
Truth table0%0/2
A
A= $marker->{"row_indexes"}
Aresult
11
00
13601 0 my $row = $records->[$index];
13602 0 ▶ next unless ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 0 0 0
13603 # A cell that is not a number adds nothing, as on the heat layer.
13604 0 ▶ $total{$osm} += length($weight_col) ? (_numeric_cell($row->{$weight_col} // '') // 0) : 1;
Branch: 1 branch
BranchTrueFalseTotal
length $weight_col ? : 0 0 0
Condition0%0/4
_numeric_cell($row->{$weight_col} // "") // 0
l!l
00
$row->{$weight_col} // ""
l!l
00
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 table0%0/2
A
A= _numeric_cell($row->{$weight_col} // "")
Aresult
11
00
Truth table0%0/2
A
A= $row->{$weight_col}
Aresult
11
00
13605 }
13606 }
13607 0 return \%total;
13608 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13609  
13610 # _map_outline_popup($self, $name, $total, $weight_col) -> $text
13611 #
13612 # Purpose: The text of a coloured outline's popup: its name and its total.
13613 # Entry: $weight_col is the column totalled, or '' when rows were counted.
13614 # Exit: Plain text (the caller escapes it); one row is "1 row", not "1 rows".
13615 # Side effects: none.
13616 0 ▶sub _map_outline_popup :Protected ($self, $name, $total, $weight_col) {
Subroutine _map_outline_popup: not called CC=3 SCAR=24.8
13617 0 ▶ 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 0 0 0
13618 0 ▶ return $total == 1
Branch: 1 branch
BranchTrueFalseTotal
$total == 1 ? : 0 0 0
13619 ? $self->_i18n('map_bounds_row', $name)
13620 : $self->_i18n('map_bounds_rows', $name, _map_total_text($total));
13621 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13622  
13623 # _map_outline_key($self, \@layers, $weight_col) -> { title, entries }
13624 #
13625 # Purpose: The key to the outline colours, for add_geojson's key option.
13626 # Entry: Each layer has its colour and its totals, low to high; the layers
13627 # are low to high too, and there is at least one.
13628 # Exit: The entries are the highest colour first, each labelled with the
13629 # total it covers, or the range when it covers unequal totals.
13630 # Side effects: none.
13631 0 ▶sub _map_outline_key :Protected ($self, $layers, $weight_col, $noun) {
Subroutine _map_outline_key: not called CC=3 SCAR=24.8
13632 my @entries = map {
13633 0 my ($low, $high) = @{ $_->{totals} }[0, -1];
13634 +{
13635 colour => $_->{colour},
13636 # Round figures: a key is read at a glance, and the popups
13637 # give each outline's exact total.
13638 0 ▶ 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) ? : 0 0 0
13639 : $self->_i18n('map_bounds_key_range', _map_key_number($low), _map_key_number($high))),
13640 };
13641 0 } reverse @{$layers};
13642 return {
13643 0 ▶ title => (length($weight_col)
Branch: 1 branch
BranchTrueFalseTotal
length $weight_col ? : 0 0 0
13644 ? $self->_i18n('map_bounds_key_total', $weight_col, $noun)
13645 : $self->_i18n('map_bounds_key_rows', $noun)),
13646 entries => \@entries,
13647 };
13648 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13649  
13650 # _outline_shares(\@distinct) -> { total => share }
13651 #
13652 # Purpose: Where each total sits between the lowest (0) and the highest (1),
13653 # which decides its colour.
13654 # Entry: At least two distinct totals, sorted low to high.
13655 # Exit: When every total is above zero, the share is by size on a log
13656 # scale: each step up the colours is the same multiple, so totals
13657 # close in size share a colour and totals far apart do not. A
13658 # straight scale would leave most outlines green, because such totals
13659 # are skewed (Fairfax County has 500 times the people of Highland).
13660 # A total of zero or less has no logarithm, so then the share is by
13661 # rank: evenly spread in order, whatever the sizes.
13662 # Side effects: none.
13663 0 ▶sub _outline_shares {
Subroutine _outline_shares: not called CC=2 SCAR=17.9
13664 0 my ($distinct) = @_;
13665 0 my %share;
13666 0 ▶ if ($distinct->[0] > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distinct->[0] > 0) { } 0 0 0
13667 0 my ($low, $high) = (log $distinct->[0], log $distinct->[-1]);
13668 # The ends are set exactly, so rounding cannot push them off the scale.
13669 0 %share = map { $_ => (log($_) - $low) / ($high - $low) } @{$distinct};
13670 0 @share{ $distinct->[0], $distinct->[-1] } = (0, 1);
13671 } else {
13672 0 %share = map { $distinct->[$_] => $_ / $#{$distinct} } 0 .. $#{$distinct};
13673 }
13674 0 return \%share;
13675 }
13676  
13677 # _map_outline_noun($self, $outlines) -> $word
13678 #
13679 # Purpose: What the outlines drawn are called ("county", "district"), for the
13680 # layer's checkbox, the key and the summary line.
13681 # Entry: $outlines as Boundary's outlines() returns it, or undef.
13682 # Exit: The word for the one kind drawn; "area" when the map mixes kinds
13683 # (a county and a province); "county" when nothing is drawn.
13684 # Side effects: none.
13685 8 ▶sub _map_outline_noun :Protected ($self, $outlines) {
Subroutine _map_outline_noun: called CC=5 SCAR=19.4
13686 0 ▶ my %called = map { ($_->{properties}{called} // 'county') => 1 } @{ $outlines ? $outlines->{features} : [] };
Branch: 1 branch
BranchTrueFalseTotal
$outlines ? : 0 8 8
Condition0%0/2
$_->{"properties"}{"called"} // "county"
l!l
00
MC/DC0%0/1
$_->{"properties"}{"called"} // "county"
$_->{"properties"}{"called"}
Truth table0%0/2
A
A= $_->{"properties"}{"called"}
Aresult
11
00
13687 8 my @kinds = keys %called;
13688 8 ▶ my $kind = @kinds > 1 ? 'area' : ($kinds[0] // 'county');
Branch: 1 branch
BranchTrueFalseTotal
@kinds > 1 ? : 0 8 8
Condition50%1/2
$kinds[0] // "county"
l!l
08
MC/DC0%0/1
$kinds[0] // "county"
$kinds[0]
Truth table50%1/2
A
A= $kinds[0]
Aresult
11
00
13689 8 return $self->_i18n("map_bounds_noun_$kind");
13690 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
13691  
13692 # _outline_colour($share) -> '#rrggbb' at $share (0..1) along @OUTLINE_STOPS
13693 0 ▶sub _outline_colour {
Subroutine _outline_colour: not called CC=4 SCAR=30.0
13694 0 my ($share) = @_;
13695 0 ▶ $share = 0 if $share < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $share < 0 0 0 0
13696 0 ▶ $share = 1 if $share > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $share > 1 0 0 0
13697 0 my $at = $share * $#OUTLINE_STOPS;
13698 0 my $from = int($at);
13699 0 ▶ $from = $#OUTLINE_STOPS - 1 if $from >= $#OUTLINE_STOPS;
Branch: 1 branch
BranchTrueFalseTotal
if $from >= $#OUTLINE_STOPS 0 0 0
13700 0 my $part = $at - $from;
13701 0 my ($lo, $hi) = @OUTLINE_STOPS[ $from, $from + 1 ];
13702 0 return sprintf('#%02x%02x%02x', map { int($lo->[$_] + ($hi->[$_] - $lo->[$_]) * $part + 0.5) } 0 .. 2);
13703 }
13704  
13705 # _map_key_number($n) -> a total as a key shows it: rounded to two figures
13706 # ("330,000" for 330,818, "1,200,000" for 1,150,309), since a key gives ranges
13707 # to be read at a glance. A total under 100 is given as it is.
13708 0 ▶sub _map_key_number {
Subroutine _map_key_number: not called CC=2 SCAR=17.9
13709 0 my ($n) = @_;
13710 0 ▶ return _map_total_text($n) if abs($n) < $KEY_ROUND_FROM;
Branch: 1 branch
BranchTrueFalseTotal
if abs $n < $KEY_ROUND_FROM 0 0 0
13711 0 my $unit = 10 ** (POSIX::floor(log(abs($n)) / log(10)) - ($KEY_FIGURES - 1));
13712 0 return _map_total_text(POSIX::floor($n / $unit + 0.5) * $unit);
13713 }
13714  
13715 # _map_total_text($n) -> the total as a popup shows it: thousands separated,
13716 # and at most two decimal places ("1,150,309", "12.5").
13717 0 ▶sub _map_total_text {
Subroutine _map_total_text: not called CC=5 SCAR=34.0
13718 0 my ($n) = @_;
13719 0 my $text = sprintf('%.2f', $n);
13720 0 ▶ $text =~ s/\.?0+\z// if $text =~ /\./;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /\./u 0 0 0
13721 # A small negative total rounds to nothing; say 0, not "-0".
13722 0 ▶ $text = '0' if $text eq '-0';
Branch: 1 branch
BranchTrueFalseTotal
if $text eq "-0" 0 0 0
13723 0 my ($whole, $fraction) = split /\./, $text, 2;
13724 0 ▶ 1 while $whole =~ s/^(-?\d+)(\d{3})/$1,$2/;
Branch: 1 branch
BranchTrueFalseTotal
$whole =~ s/^(-?\d+)(\d{3})/$1,$2/u and do { '???' } 0 0 0
13725 0 ▶ return defined($fraction) ? "$whole.$fraction" : $whole;
Branch: 1 branch
BranchTrueFalseTotal
defined $fraction ? : 0 0 0
13726 }
13727  
13728 # _map_bounds_level($value) -> the level, or undef when $value names none
13729 #
13730 # bounds= on the map page, and a map card's options.bounds, which is stored
13731 # unchecked.
13732 5 ▶sub _map_bounds_level {
Subroutine _map_bounds_level: called CC=5 SCAR=25.2
13733 5 my ($value) = @_;
13734 5 ▶ return unless defined($value) && !ref($value) && length($value);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value and length $value 5 0 5
Condition33%2/6
defined $value and not ref $value and length $value
!ll&&!rl&&r
500
defined $value and not ref $value
!ll&&!rl&&r
500
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 $valueB= not ref $valueC= length $value
ABCresult
0XX0
10X0
1100
1111
13735 0 require Database::BI::Model::Boundary;
13736 0 ▶ return (grep { $_ eq $value } Database::BI::Model::Boundary->levels) ? $value : undef;
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ eq $value;} 'Database::BI::Model::Boundary'->levels) ? : 0 0 0
13737 }
13738  
13739 # _map_data($self, \@records, \@columns, \%encode, \%options, $spec_key, $id_suffix)
13740 # -> \%result
13741 #
13742 # Resolve a map's markers and draw its HTML. The map page and a map card on a
13743 # canvas both come through here: a map spec names either loc=<column> (places
13744 # to geocode) or lat=/lon= (coordinates already in the data), and everything
13745 # else - the marker cap, popups, the geocode cache and HTML::OSM - is the same
13746 # in both places. %result has { map_body, map_head, title, messages, ... } on success
13747 # or { error, status } when the spec cannot be drawn. $id_suffix makes the
13748 # Leaflet element ids unique when several maps share one page; undef leaves the
13749 # map page's own ids alone.
13750 8 ▶sub _map_data :Protected ($self, $records, $columns, $encode, $options, $spec_key, $id_suffix) {
Subroutine _map_data: called CC=217 SCAR=90.7
13751 8 $spec_key = canonical_spec($spec_key);
13752 8 ▶ $encode //= {};
Condition50%1/2
$encode //= {}
l!l
80
MC/DC0%0/1
$encode //= {}
$encode
Truth table50%1/2
A
A= $encode
Aresult
11
00
13753 8 ▶ $options //= {};
Condition50%1/2
$options //= {}
l!l
80
MC/DC0%0/1
$options //= {}
$options
Truth table50%1/2
A
A= $options
Aresult
11
00
13754  
13755 # loc may name several columns, in order: the place is their cells joined
13756 # with ", " (an address and then its country). $loc_col is that list's
13757 # name, which is what the page and the geocoder are told.
13758 8 my @loc_cols = _map_loc_columns($encode->{loc});
13759 8 my $loc_col = join(', ', @loc_cols);
13760 8 ▶ my $lat_col = $encode->{lat} // '';
Condition100%2/2
$encode->{"lat"} // ""
l!l
17
MC/DC100%1/1
$encode->{"lat"} // ""
$encode->{"lat"}
Truth table100%2/2
A
A= $encode->{"lat"}
Aresult
11
00
13761 8 ▶ my $lon_col = $encode->{lon} // '';
Condition100%2/2
$encode->{"lon"} // ""
l!l
17
MC/DC100%1/1
$encode->{"lon"} // ""
$encode->{"lon"}
Truth table100%2/2
A
A= $encode->{"lon"}
Aresult
11
00
13762 8 my $by_location = length $loc_col;
13763 8 my ($loc_text) = _map_loc_text($encode->{loc_text});
13764 8 ▶ $loc_text = '' unless defined($loc_text) && $by_location;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $loc_text and $by_location 1 7 8
Condition66%2/3
defined $loc_text and $by_location
!ll&&!rl&&r
017
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
13765  
13766 8 ▶ return { error => $self->_i18n('error_map_source'), status => 400 }
Branch: 1 branch
BranchTrueFalseTotal
unless $by_location or length $lat_col or length $lon_col 0 8 8
Condition50%3/6
$by_location or length $lat_col or length $lon_col
l!l&&r!l&&!r
800
$by_location or length $lat_col
l!l&&r!l&&!r
710
MC/DC0%0/3
$by_location or length $lat_col or length $lon_col
$by_location length $lat_col length $lon_col
Truth table50%2/4
A or B or C
A= $by_locationB= length $lat_colC= length $lon_col
ABCresult
1XX1
01X1
0011
0000
13767 unless $by_location || length($lat_col) || length($lon_col);
13768 8 ▶ 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 8 8
Condition50%3/6
$by_location or length $lat_col and length $lon_col
l!l&&r!l&&!r
710
length $lat_col and length $lon_col
!ll&&!rl&&r
001
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
13769 if !$by_location && (!length($lat_col) || !length($lon_col));
13770  
13771 8 my %col_set = map { $_ => 1 } @$columns;
13772 8 my $cfg = $self->app->config;
13773  
13774 8 my %loc_set = map { $_ => 1 } @loc_cols;
13775 my @popup = grep {
13776 0 ▶ defined($_) && !ref($_) && length($_) && !$loc_set{$_} && $col_set{$_}
Condition0%0/12
defined $_ && !ref($_) && length $_ && !$loc_set{$_} && $col_set{$_}
!ll&&!rl&&r
000
defined $_ and not ref $_ and length $_ and not $loc_set{$_}
!ll&&!rl&&r
000
defined $_ and not ref $_ and length $_
!ll&&!rl&&r
000
defined $_ and not ref $_
!ll&&!rl&&r
000
MC/DC0%0/5
defined $_ && !ref($_) && length $_ && !$loc_set{$_} && $col_set{$_}
defined $_ not ref $_ length $_ not $loc_set{$_} $col_set{$_}
Truth table0%0/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
13777 8 ▶ } @{ ref($options->{popup}) eq 'ARRAY' ? $options->{popup} : [] };
Branch: 1 branch
BranchTrueFalseTotal
ref $options->{'popup'} eq 'ARRAY' ? : 0 8 8
13778  
13779 # Default: when no popup columns are requested, show every column that is
13780 # not a coordinate column so the marker tooltip is informative out of the box.
13781 8 ▶ unless (@popup) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@popup) 8 0 8
13782 9 my %coord_set = map { $_ => 1 }
13783 8 ▶ grep { defined($_) && length($_) } (@loc_cols, $lat_col, $lon_col);
Condition66%2/3
defined $_ && length $_
!ll&&!rl&&r
0149
MC/DC50%1/2
defined $_ && length $_
defined $_ length $_
Truth table66%2/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
13784 8 @popup = grep { !$coord_set{$_} } @$columns;
13785 }
13786  
13787 8 my ($backend, $plotted_rows) = (undef, 0);
13788 8 my (@markers, @messages, @unplotted, @unplotted_filters, @pending);
13789  
13790 # How many rows a popup lists, and where the rest are: the map page passes
13791 # rows_url, which makes a table link from filters; a canvas card has none.
13792 8 my $popup_rows = _map_limit($cfg->{map_popup_rows}, $DEFAULT_MAP_POPUP_ROWS);
13793 8 ▶ my $rows_url = ref($options->{rows_url}) eq 'CODE' ? $options->{rows_url} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $options->{'rows_url'} eq 'CODE' ? : 2 6 8
13794  
13795 8 ▶ if ($by_location) {
Branch: 1 branch
BranchTrueFalseTotal
if ($by_location) { } 7 1 8
13796 7 for my $col (@loc_cols) {
13797 return { error => $self->_i18n('error_map_loc_column', $col), status => 400 }
13798 7 ▶ unless $col_set{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$col} 2 5 7
13799 }
13800  
13801 5 require Database::BI::Model::Geocode;
13802  
13803 # What the geocoder is given: one cell a row, under $loc_col, in the
13804 # rows' own order, so a marker's first_row still indexes $records.
13805 5 my ($places) = Database::BI::Model::Geocode->place_rows($records, \@loc_cols, $loc_text);
13806  
13807 5 my $geocode = $self->_map_geocoder(1);
13808  
13809 # A place name means the same place whichever file's column holds it, so
13810 # the answers live in one shared cache: the second dataset that names a
13811 # place plots it without asking the geocoder. A per-dataset entry from an
13812 # older model store is folded in as well; the shared answer wins if both
13813 # have the name, and places only the old entry knows about are moved into
13814 # the shared cache below, so the next dataset benefits from them too.
13815 5 ▶ my $cache_spec = ($spec_key // '') . '|loc=' . $loc_col;
Condition50%1/2
$spec_key // ""
l!l
50
MC/DC0%0/1
$spec_key // ""
$spec_key
Truth table50%1/2
A
A= $spec_key
Aresult
11
00
13816 5 my $models = $self->_read_models;
13817 5 my $legacy = Database::BI::Model::Geocode->cache_from_models($models, $cache_spec);
13818 5 my $shared = Database::BI::Model::Geocode->shared_cache_from_models($models);
13819 5 my %cache = (%$legacy, %$shared);
13820 0 my $to_share = grep { !exists $shared->{$_} } keys %$legacy;
13821 5 my $region = _map_region($cfg);
13822  
13823 # lookup => 0 (the map page in a browser) asks nothing here: the
13824 # places not cached yet come back as pending, and the page looks them
13825 # up one at a time through /geo/lookup, with a progress bar.
13826 my $result = $geocode->resolve_column(
13827 $places, $loc_col,
13828 cache => \%cache,
13829 (defined($region) ? (region => $region) : ()),
13830 max => _map_limit($cfg->{map_geocode_max}, $DEFAULT_MAP_GEOCODE_MAX),
13831 5 ▶ lookup => ((defined($options->{lookup}) && !$options->{lookup}) ? 0 : 1),
Branch: 2 branches
BranchTrueFalseTotal
defined $region ? : 0 5 5
defined $options->{'lookup'} && !$options->{'lookup'} ? : 1 4 5
Condition66%2/3
defined $options->{"lookup"} and not $options->{"lookup"}
!ll&&!rl&&r
401
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
13832 );
13833 5 ▶ @pending = @{ $result->{pending} // [] };
Condition50%1/2
$result->{"pending"} // []
l!l
50
MC/DC0%0/1
$result->{"pending"} // []
$result->{"pending"}
Truth table50%1/2
A
A= $result->{"pending"}
Aresult
11
00
13834  
13835 5 push @messages, @{ $result->{messages} };
13836 5 $backend = $result->{backend};
13837 5 $plotted_rows = $result->{counts}{plotted};
13838 5 my ($entries, $all) = _map_unplotted($records, $places, $loc_col, \@loc_cols, $result);
13839 5 @unplotted = @{$entries};
13840 5 @unplotted_filters = @{$all};
13841  
13842 # Only a request that asked something new, or found old answers to move
13843 # into the shared cache, has something new to remember: rewriting the
13844 # store for a page answered entirely from the shared cache would be a
13845 # write per view. $to_share empties after the migration, so an old store
13846 # is written once per dataset rather than on every view.
13847 5 ▶ if ($result->{counts}{attempted} || $to_share) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{"counts"}{"attempted"} or $to_share) 1 4 5
Condition66%2/3
$result->{"counts"}{"attempted"} or $to_share
l!l&&r!l&&!r
104
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
13848 my $updated = Database::BI::Model::Geocode->models_with_shared_cache(
13849 $models, $result->{cache},
13850 1 ▶ (defined($backend) ? (backend => $backend) : ()),
Branch: 1 branch
BranchTrueFalseTotal
defined $backend ? : 1 0 1
13851 built => _iso8601_utc(),
13852 );
13853 1 my $written = $self->_write_models($updated);
13854  
13855 # A failed migration is not worth a page message: the answers are
13856 # still in the old entry, so this dataset is unaffected. A failed
13857 # new lookup is, because the next visit pays for it again.
13858 1 ▶ if (!$written && $result->{counts}{attempted}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $written and $result->{"counts"}{"attempted"}) 0 1 1
Condition33%1/3
not $written and $result->{"counts"}{"attempted"}
!ll&&!rl&&r
100
MC/DC0%0/2
not $written and $result->{"counts"}{"attempted"}
not $written $result->{"counts"}{"attempted"}
Truth table33%1/3
not(A) and B
A= not $writtenB= $result->{"counts"}{"attempted"}
ABresult
0X0
100
111
13859 0 push @messages, {
13860 key => 'warn_map_cache_unwritten',
13861 text => $self->_i18n('warn_map_cache_unwritten'),
13862 };
13863 }
13864 }
13865  
13866 # Every row at a place, keyed as the geocoder keyed the place, so its
13867 # popup can list them all and not only the first.
13868 5 my %rows_at;
13869 5 for my $index (0 .. $#{$places}) {
13870 12 my $place = $places->[$index];
13871 12 ▶ my $value = ref($place) eq 'HASH' ? $place->{$loc_col} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $place eq 'HASH' ? : 12 0 12
13872 12 ▶ push @{ $rows_at{ (defined($value) && !ref($value)) ? $value : '' } }, $index;
Branch: 1 branch
BranchTrueFalseTotal
defined $value && !ref($value) ? : 12 0 12
Condition33%1/3
defined $value and not ref $value
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $value and not ref $value
defined $value not ref $value
Truth table33%1/3
A and not(B)
A= defined $valueB= not ref $value
ABresult
0X0
100
111
13873 }
13874  
13875 5 for my $marker (@{ $result->{markers} }) {
13876 3 ▶ my @at = @{ $rows_at{ $marker->{value} } // [] };
Condition50%1/2
$rows_at{$marker->{"value"}} // []
l!l
30
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
13877 3 ▶ my $row = $records->[ $at[0] // $marker->{first_row} ];
Condition33%1/3
$at[0] // $marker->{"first_row"}
l!l&&r!l&&!r
300
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
13878 3 ▶ $row = {} unless ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 0 3 3
13879 my $more_url = $rows_url ? $rows_url->([ map {
13880 0 ▶ my $cell = $row->{$_};
Branch: 1 branch
BranchTrueFalseTotal
$rows_url ? : 0 3 3
13881 0 ▶ (defined($cell) && !ref($cell) && length($cell)) ? "$_:eq:$cell" : "$_:empty";
Branch: 1 branch
BranchTrueFalseTotal
defined $cell && !ref($cell) && length $cell ? : 0 0 0
Condition0%0/6
defined $cell and not ref $cell and length $cell
!ll&&!rl&&r
000
defined $cell and not ref $cell
!ll&&!rl&&r
000
MC/DC0%0/3
defined $cell and not ref $cell and length $cell
defined $cell not ref $cell length $cell
Truth table0%0/4
A and not(B) and C
A= defined $cellB= not ref $cellC= length $cell
ABCresult
0XX0
10X0
1100
1111
13882 } @loc_cols ]) : '';
13883 push @markers, {
13884 3 %{ $marker },
13885 'row_indexes' => \@at,
13886 'label' => _map_popup(
13887 3 $marker->{value}, [ @{$records}[@at] ], \@popup, $popup_rows, $more_url,
13888 ),
13889 };
13890 }
13891  
13892 } else {
13893 return { error => "Column not found: $lat_col", status => 400 }
13894 1 ▶ unless $col_set{$lat_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$lat_col} 0 1 1
13895 return { error => "Column not found: $lon_col", status => 400 }
13896 1 ▶ unless $col_set{$lon_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$lon_col} 0 1 1
13897  
13898 1 my (%by_key, %rows_at, $out_of_lat, $out_of_lon, $unusable);
13899  
13900 1 for my $index (0 .. $#$records) {
13901 6 my $row = $records->[$index];
13902 6 ▶ my $lat = _numeric_cell($row->{$lat_col} // '');
Condition50%1/2
$row->{$lat_col} // ""
l!l
60
MC/DC0%0/1
$row->{$lat_col} // ""
$row->{$lat_col}
Truth table50%1/2
A
A= $row->{$lat_col}
Aresult
11
00
13903 6 ▶ my $lon = _numeric_cell($row->{$lon_col} // '');
Condition50%1/2
$row->{$lon_col} // ""
l!l
60
MC/DC0%0/1
$row->{$lon_col} // ""
$row->{$lon_col}
Truth table50%1/2
A
A= $row->{$lon_col}
Aresult
11
00
13904  
13905 # A row is never plotted at (0,0): a fake point in the Gulf of
13906 # Guinea is worse than a missing one. A whole column outside its
13907 # range is named instead, because a transposed pair is the error a
13908 # user makes here.
13909 0 ▶ if (defined($lat) && ($lat < -90 || $lat > 90)) { $out_of_lat++; next }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lat and $lat < -90 || $lat > 90) 0 6 6
Condition33%2/6
defined $lat and $lat < -90 || $lat > 90
!ll&&!rl&&r
060
$lat < -90 or $lat > 90
l!l&&r!l&&!r
006
MC/DC0%0/3
defined $lat and $lat < -90 || $lat > 90
defined $lat $lat < -90 $lat > 90
Truth table25%1/4
A and B or C
A= defined $latB= $lat < -90C= $lat > 90
ABCresult
0XX0
1000
11X1
1011
13910 6 ▶ if (defined($lon) && ($lon < -180 || $lon > 180)) { $out_of_lon++; next }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lon and $lon < -180 || $lon > 180) 6 0 6
Condition33%2/6
defined $lon and $lon < -180 || $lon > 180
!ll&&!rl&&r
006
$lon < -180 or $lon > 180
l!l&&r!l&&!r
060
MC/DC0%0/3
defined $lon and $lon < -180 || $lon > 180
defined $lon $lon < -180 $lon > 180
Truth table25%1/4
A and B or C
A= defined $lonB= $lon < -180C= $lon > 180
ABCresult
0XX0
1000
11X1
1011
13911 0 ▶ unless (defined($lat) && defined($lon)) { $unusable++; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $lat and defined $lon) 0 0 0
Condition0%0/3
defined $lat and defined $lon
!ll&&!rl&&r
000
MC/DC0%0/2
defined $lat and defined $lon
defined $lat defined $lon
Truth table0%0/3
A and B
A= defined $latB= defined $lon
ABresult
0X0
100
111
13912  
13913 # Rows at one coordinate are one marker: that is what makes a large
13914 # file renderable, and "how many are here?" is the question a map
13915 # answers.
13916 0 my $key = sprintf('%.6f,%.6f', $lat, $lon);
13917 0 push @{ $rows_at{$key} }, $index;
13918 0 my $point = $by_key{$key};
13919 0 ▶ if ($point) { $point->{rows}++; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($point) 0 0 0
13920  
13921 0 $point = $by_key{$key} = {
13922 'lat' => $lat, 'lon' => $lon, 'rows' => 1, 'first_row' => $index,
13923 };
13924 0 push @markers, $point;
13925 }
13926  
13927 1 ▶ return { error => $self->_i18n('error_map_coordinate_range', $lat_col, 'latitude'),
Branch: 1 branch
BranchTrueFalseTotal
if not @markers and $out_of_lat 0 1 1
Condition33%1/3
not @markers and $out_of_lat
!ll&&!rl&&r
010
MC/DC0%0/2
not @markers and $out_of_lat
not @markers $out_of_lat
Truth table33%1/3
not(A) and B
A= not @markersB= $out_of_lat
ABresult
0X0
100
111
13928 status => 400 } if !@markers && $out_of_lat;
13929 1 ▶ return { error => $self->_i18n('error_map_coordinate_range', $lon_col, 'longitude'),
Branch: 1 branch
BranchTrueFalseTotal
if not @markers and $out_of_lon 1 0 1
Condition33%1/3
not @markers and $out_of_lon
!ll&&!rl&&r
001
MC/DC0%0/2
not @markers and $out_of_lon
not @markers $out_of_lon
Truth table33%1/3
not(A) and B
A= not @markersB= $out_of_lon
ABresult
0X0
100
111
13930 status => 400 } if !@markers && $out_of_lon;
13931 0 ▶ return { error => $self->_i18n('error_map_coordinate_numeric', $lat_col, $lon_col),
Branch: 1 branch
BranchTrueFalseTotal
if not @markers and @$records 0 0 0
Condition0%0/3
not @markers and @$records
!ll&&!rl&&r
000
MC/DC0%0/2
not @markers and @$records
not @markers @$records
Truth table0%0/3
not(A) and B
A= not @markersB= @$records
ABresult
0X0
100
111
13932 status => 400 } if !@markers && @$records;
13933  
13934 0 $plotted_rows += $_->{rows} for @markers;
13935  
13936 0 ▶ push @messages, {
Branch: 1 branch
BranchTrueFalseTotal
if $plotted_rows < scalar @$records 0 0 0
13937 key => 'warn_map_coordinate_rows',
13938 text => $self->_i18n('warn_map_coordinate_rows', $plotted_rows,
13939 scalar(@$records), scalar(@$records) - $plotted_rows),
13940 } if $plotted_rows < scalar @$records;
13941  
13942 0 for my $marker (@markers) {
13943 0 my $key = sprintf('%.6f,%.6f', $marker->{lat}, $marker->{lon});
13944 0 $marker->{row_indexes} = $rows_at{$key};
13945 0 my $row = $records->[ $marker->{first_row} ];
13946 my $more_url = $rows_url ? $rows_url->([
13947 "$lat_col:eq:" . ($row->{$lat_col} // ''),
13948 0 ▶ "$lon_col:eq:" . ($row->{$lon_col} // ''),
Branch: 1 branch
BranchTrueFalseTotal
$rows_url ? : 0 0 0
Condition0%0/4
$row->{$lat_col} // ""
l!l
00
$row->{$lon_col} // ""
l!l
00
MC/DC0%0/1
$row->{$lat_col} // ""
$row->{$lat_col}
MC/DC0%0/1
$row->{$lon_col} // ""
$row->{$lon_col}
Truth table0%0/2
A
A= $row->{$lat_col}
Aresult
11
00
Truth table0%0/2
A
A= $row->{$lon_col}
Aresult
11
00
13949 ]) : '';
13950 $marker->{label} = _map_popup(
13951 sprintf('%.6f, %.6f', $marker->{lat}, $marker->{lon}),
13952 0 [ @{$records}[ @{ $rows_at{$key} } ] ], \@popup, $popup_rows, $more_url,
13953 );
13954 }
13955 }
13956  
13957 5 ▶ my $title = $by_location ? "Map of $loc_col" : "$lat_col and $lon_col";
Branch: 1 branch
BranchTrueFalseTotal
$by_location ? : 5 0 5
13958 my $cap = _map_limit($options->{max},
13959 5 _map_limit($cfg->{map_max_markers}, $DEFAULT_MAP_MAX_MARKERS));
13960  
13961 5 ▶ if (@markers > $cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (@markers > $cap) 0 5 5
13962 0 push @messages, {
13963 key => 'warn_map_markers_capped',
13964 text => $self->_i18n('warn_map_markers_capped', $cap, scalar @markers),
13965 };
13966 0 @markers = @markers[0 .. $cap - 1];
13967 }
13968  
13969 5 ▶ push @messages, {
Branch: 1 branch
BranchTrueFalseTotal
unless @markers 2 3 5
13970 key => 'error_map_no_markers',
13971 text => $self->_i18n('error_map_no_markers'),
13972 } unless @markers;
13973  
13974 # The outline of the county around each marker (bounds=county). Those
13975 # not known yet are looked up here, up to the online limit, unless the
13976 # caller said lookup => 0: the map page in a browser lists them for its
13977 # progress bar instead, as it does places.
13978 5 my $bounds_level = _map_bounds_level($options->{bounds});
13979 5 my ($outlines, @bounds_pending);
13980 5 my $bounds_coloured = 0; # set when the outlines are coloured by their totals
13981 5 my $bounds_as_markers = 0; # set when they take their markers' colours
13982 5 my $bounds_shade = ''; # the column they are filled by (shade=), when they are
13983 5 my $bounds_shade_as = ''; # 'one' colour, or the 'markers' colours
13984 5 my (@bounds_left_filters, $bounds_left_rows); # the rows whose marker has no outline
13985 5 my @bounds_groups; # why there are fewer outlines than markers (_map_outline_groups)
13986 5 ▶ if (defined($bounds_level) && @markers) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bounds_level and @markers) 0 5 5
Condition33%1/3
defined $bounds_level and @markers
!ll&&!rl&&r
500
MC/DC0%0/2
defined $bounds_level and @markers
defined $bounds_level @markers
Truth table33%1/3
A and B
A= defined $bounds_levelB= @markers
ABresult
0X0
100
111
13987 0 ▶ my $lookup = (defined($options->{lookup}) && !$options->{lookup}) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $options->{'lookup'} && !$options->{'lookup'} ? : 0 0 0
Condition0%0/3
defined $options->{"lookup"} and not $options->{"lookup"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $options->{"lookup"} and not $options->{"lookup"}
defined $options->{"lookup"} not $options->{"lookup"}
Truth table0%0/3
A and not(B)
A= defined $options->{"lookup"}B= not $options->{"lookup"}
ABresult
0X0
100
111
13988 $outlines = $self->_map_boundary($bounds_level, 1)->outlines(
13989 0 [ map { [ $_->{lat}, $_->{lon} ] } @markers ],
13990 lookup => $lookup,
13991 );
13992 0 @bounds_pending = @{ $outlines->{pending} };
13993 0 ▶ if (@bounds_pending) {
Branch: 1 branch
BranchTrueFalseTotal
if (@bounds_pending) 0 0 0
13994 # The rows behind the markers left without an outline, for a link
13995 # to them in the table, as the rows not plotted have.
13996 0 require Database::BI::Model::Boundary;
13997 0 my %left = map { $_ => 1 } @bounds_pending;
13998 0 ▶ my @rows = map { @{ $_->{row_indexes} // [ $_->{first_row} ] } } grep {
Condition0%0/2
$_->{"row_indexes"} // [$_->{"first_row"}]
l!l
00
MC/DC0%0/1
$_->{"row_indexes"} // [$_->{"first_row"}]
$_->{"row_indexes"}
Truth table0%0/2
A
A= $_->{"row_indexes"}
Aresult
11
00
13999 0 my $key = Database::BI::Model::Boundary->point_key($_->{lat}, $_->{lon});
14000 0 ▶ defined($key) && $left{$key};
Condition0%0/3
defined $key && $left{$key}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $key && $left{$key}
defined $key $left{$key}
Truth table0%0/3
A && B
A= defined $keyB= $left{$key}
ABresult
0X0
100
111
14001 } @markers;
14002 0 $bounds_left_rows = scalar @rows;
14003 0 ▶ @bounds_left_filters = _map_rows_filters($records, \@rows,
Branch: 1 branch
BranchTrueFalseTotal
$by_location ? : 0 0 0
14004 [ $by_location ? @loc_cols : ($lat_col, $lon_col) ]);
14005 my $key = $outlines->{offline} ? 'warn_map_bounds_offline'
14006 0 ▶ : $outlines->{failed} ? 'warn_map_bounds_failed'
Branch: 2 branches
BranchTrueFalseTotal
$outlines->{'offline'} ? : 0 0 0
$outlines->{'failed'} ? : 0 0 0
14007 : 'warn_map_bounds_pending';
14008 push @messages, {
14009 key => $key,
14010 # One place "has" no outline; the key stays the plural's
14011 text => $self->_i18n($key . (@bounds_pending == 1 ? '_one' : ''),
14012 0 ▶ scalar(@bounds_pending), $outlines->{counts}{points}),
Branch: 1 branch
BranchTrueFalseTotal
@bounds_pending == 1 ? : 0 0 0
14013 };
14014 }
14015 0 ▶ @bounds_groups = _map_outline_groups($outlines, \@markers, $records,
Branch: 1 branch
BranchTrueFalseTotal
$by_location ? : 0 0 0
14016 [ $by_location ? @loc_cols : ($lat_col, $lon_col) ]);
14017 }
14018  
14019 # Leaflet's CSS and JS belong in the head, which the layout owns; the rest of
14020 # the map - the search box, the buttons, the div and its script - goes in the
14021 # body where the map should appear.
14022 5 my ($map_head, $map_body);
14023 5 ▶ if (@markers) {
Branch: 1 branch
BranchTrueFalseTotal
if (@markers) 3 2 5
14024 # HTML::OSM is a recommended dependency, so its absence - or an install
14025 # older than the options below - is a state the page reports and
14026 # survives: the markers are still counted, nothing is drawn, and the
14027 # rest of the application is untouched. The version check is not
14028 # optional: HTML::OSM rejects unknown constructor keys, so passing
14029 # search/max_zoom to an older copy would croak and turn the page into a
14030 # 500 rather than the warning this branch produces.
14031 #
14032 # The installed version comes back with the answer so the warning can
14033 # say which problem it is: "not installed" and "installed but older than
14034 # 0.12" have different fixes, and the old wording called both of them
14035 # "could not be loaded". The probe is a method (see
14036 # _map_renderer_version) so the tests can produce either state without
14037 # installing or removing the module.
14038 3 my ($osm_ok, $osm_version) = $self->_map_renderer_version;
14039 3 ▶ if ($osm_ok) {
Branch: 2 branches
BranchTrueFalseTotal
if ($osm_ok) { } 3 0 3
elsif (defined $osm_version) { } 0 0 0
14040 # Markers go in a cluster group rather than straight onto the map.
14041 # A card may plot up to map_max_markers (2000 by default), and at a
14042 # low zoom that many pins overlap into noise; markercluster draws a
14043 # count instead and splits it as the reader zooms in. A sparse map
14044 # looks the same - the plugin leaves markers that are far apart on
14045 # their own - but the plugin is only fetched once the map itself is.
14046 # The Leaflet assets are a config seam too. A deployment with no
14047 # outbound network access serves them from its own origin; any key
14048 # the operator leaves out keeps HTML::OSM's pinned CDN URL. The tile
14049 # layer has its own key, since a local tile server removes the last
14050 # outbound request the page makes.
14051 3 my %leaflet_assets;
14052 3 for my $asset (
14053 [ 'leaflet_js_url', 'js_url' ],
14054 [ 'leaflet_css_url', 'css_url' ],
14055 [ 'leaflet_cluster_js_url', 'cluster_js_url' ],
14056 [ 'leaflet_cluster_css_url', 'cluster_css_url' ],
14057 [ 'leaflet_cluster_default_css_url', 'cluster_default_css_url' ],
14058 ) {
14059 15 my ($key, $param) = @$asset;
14060 15 my $url = $cfg->{$key};
14061 15 ▶ $leaflet_assets{$param} = $url
Branch: 1 branch
BranchTrueFalseTotal
if defined $url and not ref $url and length $url 0 15 15
Condition33%2/6
defined $url and not ref $url and length $url
!ll&&!rl&&r
1500
defined $url and not ref $url
!ll&&!rl&&r
1500
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
14062 if defined $url && !ref $url && length $url;
14063 }
14064  
14065 3 my $tile_url = $cfg->{tile_url};
14066 3 ▶ $tile_url = undef
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tile_url and not ref $tile_url and length $tile_url 3 0 3
Condition33%2/6
defined $tile_url and not ref $tile_url and length $tile_url
!ll&&!rl&&r
300
defined $tile_url and not ref $tile_url
!ll&&!rl&&r
300
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
14067 unless defined($tile_url) && !ref($tile_url) && length($tile_url);
14068  
14069 # options{tile_url} wins over the global config tile_url when set.
14070 # HTML::OSM >= 0.12 is the minimum, so tile_url is always accepted.
14071 3 ▶ my $eff_tile_url = $options->{tile_url} // $tile_url;
Condition33%1/3
$options->{"tile_url"} // $tile_url
l!l&&r!l&&!r
003
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
14072 3 ▶ $eff_tile_url = undef
Branch: 1 branch
BranchTrueFalseTotal
unless defined $eff_tile_url and not ref $eff_tile_url and length $eff_tile_url 3 0 3
Condition33%2/6
defined $eff_tile_url and not ref $eff_tile_url and length $eff_tile_url
!ll&&!rl&&r
300
defined $eff_tile_url and not ref $eff_tile_url
!ll&&!rl&&r
300
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
14073 unless defined($eff_tile_url) && !ref($eff_tile_url) && length($eff_tile_url);
14074  
14075 my %osm_args = (
14076 height => '560px',
14077 width => '100%',
14078 cluster => 1,
14079 search => 0,
14080 ($eff_tile_url ? (tile_url => $eff_tile_url) : ()),
14081 (defined($options->{zoom}) ? (zoom => $options->{zoom}) : ()),
14082 3 ▶ (defined($options->{max_zoom}) ? (max_zoom => $options->{max_zoom}) : ()),
Branch: 3 branches
BranchTrueFalseTotal
$eff_tile_url ? : 0 3 3
defined $options->{'zoom'} ? : 0 3 3
defined $options->{'max_zoom'} ? : 0 3 3
14083 %leaflet_assets,
14084 );
14085 # The renderer is a third-party module: whatever it does, the page
14086 # reports it and survives, as it does when the module is absent.
14087 # The map page passes the colour and size columns as options; a
14088 # canvas card has them in its encode, as the page saved them. A
14089 # card's are stored unchecked, so one that names no column is
14090 # left out rather than refused.
14091 3 ▶ my $color_col = $options->{color_col} // $encode->{color} // '';
Condition40%2/5
($options->{"color_col"} // $encode->{"color"}) // ""
l!l
03
$options->{"color_col"} // $encode->{"color"}
l!l&&r!l&&!r
003
MC/DC0%0/2
($options->{"color_col"} // $encode->{"color"}) // ""
$options->{"color_col"} $encode->{"color"}
Truth table33%1/3
A // B
A= $options->{"color_col"}B= $encode->{"color"}
ABresult
1X1
011
000
14092 3 ▶ $color_col = '' if ref($color_col) || !$col_set{$color_col};
Branch: 1 branch
BranchTrueFalseTotal
if ref $color_col or not $col_set{$color_col} 3 0 3
Condition33%1/3
ref $color_col or not $col_set{$color_col}
l!l&&r!l&&!r
030
MC/DC0%0/2
ref $color_col or not $col_set{$color_col}
ref $color_col not $col_set{$color_col}
Truth table33%1/3
A or not(B)
A= ref $color_colB= not $col_set{$color_col}
ABresult
1X1
011
000
14093 # A card's rules are stored unchecked: one that is not a rule is
14094 # left out rather than read as one.
14095 2 my $color_rules = [ grep { ref($_) eq 'HASH' }
14096 3 ▶ @{ ref($options->{color_rules}) eq 'ARRAY' ? $options->{color_rules} : [] } ];
Branch: 1 branch
BranchTrueFalseTotal
ref $options->{'color_rules'} eq 'ARRAY' ? : 1 2 3
14097 3 ▶ my $color_default = $options->{color_default} // $DEFAULT_MARKER_COLOR;
Condition33%1/3
$options->{"color_default"} // $DEFAULT_MARKER_COLOR
l!l&&r!l&&!r
030
MC/DC0%0/2
$options->{"color_default"} // $DEFAULT_MARKER_COLOR
$options->{"color_default"} $DEFAULT_MARKER_COLOR
Truth table33%1/3
A // B
A= $options->{"color_default"}B= $DEFAULT_MARKER_COLOR
ABresult
1X1
011
000
14098 3 ▶ my $size_col = $options->{size} // $encode->{size} // '';
Condition40%2/5
($options->{"size"} // $encode->{"size"}) // ""
l!l
03
$options->{"size"} // $encode->{"size"}
l!l&&r!l&&!r
003
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
14099 3 ▶ $size_col = '' if ref($size_col) || !$col_set{$size_col};
Branch: 1 branch
BranchTrueFalseTotal
if ref $size_col or not $col_set{$size_col} 3 0 3
Condition33%1/3
ref $size_col or not $col_set{$size_col}
l!l&&r!l&&!r
030
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
14100  
14101 # The scale bar, and the key on the map: colours and bubble sizes.
14102 3 my $size_range = [ _map_size_range($records, \@markers, $size_col) ];
14103 # When the outlines are shaded in the markers' colours by the column
14104 # the colours read, the shade key lists every colour with its totals,
14105 # so a second key of the same colours would only repeat it. Shaded by
14106 # another column, or in one colour, the marker key is still the only
14107 # place the colours are explained. Bubble sizes are listed either way.
14108 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
14109 && !ref($options->{shade} // '') && ($options->{shade} // '') eq $color_col
14110 3 ▶ && !defined($options->{shade_color});
Condition33%5/15
length $color_col && $outlines && @{$outlines->{'features'};} && !ref($options->{'shade'} // '') && ($options->{'shade'} // '') eq $color_col && !defined($options->{'shade_color'})
!ll&&!rl&&r
300
length $color_col and $outlines and @{$outlines->{"features"};} and not ref($options->{"shade"} // "") and ($options->{"shade"} // "") eq $color_col
!ll&&!rl&&r
300
length $color_col and $outlines and @{$outlines->{"features"};} and not ref($options->{"shade"} // "")
!ll&&!rl&&r
300
length $color_col and $outlines and @{$outlines->{"features"};}
!ll&&!rl&&r
300
length $color_col and $outlines
!ll&&!rl&&r
300
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 table14%1/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
14111 # HTML::OSM 0.19 can leave a key entry out while a layer is shown and
14112 # bring it back when the reader hides the layer, so the markers are
14113 # never left without a key; an older copy cannot, and gets no colour
14114 # entries at all.
14115 my $key_waits = $shade_covers
14116 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
300
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
14117 my %key = $self->_map_key((($shade_covers && !$key_waits) ? '' : $color_col), $color_rules,
14118 3 ▶ $color_default, defined($options->{scheme}), $size_col, $size_range);
Branch: 1 branch
BranchTrueFalseTotal
$shade_covers && !$key_waits ? : 0 3 3
Condition33%1/3
$shade_covers and not $key_waits
!ll&&!rl&&r
300
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
14119 3 ▶ if ($key_waits) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key_waits) 0 3 3
14120 0 my $layer = $self->_i18n('map_bounds_layer', ucfirst $self->_map_outline_noun($outlines));
14121 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
14122 }
14123 3 $osm_args{scale} = 1;
14124 # Every <script> the map writes carries the page's nonce.
14125 3 $osm_args{nonce} = $self->csp_nonce;
14126 # Without a zoom the map opens on every marker, as the panel promises
14127 3 ▶ $osm_args{fit} = 1 unless defined $options->{zoom};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"zoom"} 3 0 3
14128 3 ▶ %osm_args = (%osm_args, %key) if @{ $key{legend} // [] };
Branch: 1 branch
BranchTrueFalseTotal
if @{$key{"legend"} // [];} 0 3 3
Condition50%1/2
$key{"legend"} // []
l!l
03
MC/DC0%0/1
$key{"legend"} // []
$key{"legend"}
Truth table50%1/2
A
A= $key{"legend"}
Aresult
11
00
14129  
14130 3 my $drawn = eval {
14131 3 my $map = HTML::OSM->new(%osm_args);
14132  
14133 # Bubble maps: one radius per marker, scaled across the plotted
14134 # values. Circle markers keep their pixel size as the reader
14135 # zooms, which is what makes them comparable.
14136 3 my ($size_min, $size_max) = @{$size_range};
14137  
14138 3 for my $marker (@markers) {
14139 3 my $row = $records->[ $marker->{first_row} ];
14140 3 my ($color, $group);
14141 3 ▶ if (length $color_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $color_col) 0 3 3
14142 0 ▶ my $cval = (defined($row) ? $row->{$color_col} : undef) // '';
Branch: 1 branch
BranchTrueFalseTotal
defined $row ? : 0 0 0
Condition0%0/2
(defined $row ? $row->{$color_col} : undef) // ""
l!l
00
MC/DC0%0/1
(defined $row ? $row->{$color_col} : undef) // ""
(defined $row ? $row->{$color_col} : undef)
Truth table0%0/2
A
A= (defined $row ? $row->{$color_col} : undef)
Aresult
11
00
14143 0 $color = _apply_color_rule($cval, $color_rules, $color_default);
14144 # Which key entry the marker belongs to, so the key lists
14145 # only what is in view
14146 0 my $index = _color_rule_index($cval, $color_rules);
14147 0 ▶ $group = defined($index) ? "rule$index" : 'other';
Branch: 1 branch
BranchTrueFalseTotal
defined $index ? : 0 0 0
14148 # Kept for the outline round it, which is drawn to match
14149 0 $marker->{colour} = _color_hex($color);
14150 }
14151 3 ▶ if (length $size_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $size_col) { } 0 3 3
14152 my $sv = defined($row)
14153 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
14154 $map->add_circle_marker(
14155 [ $marker->{lat}, $marker->{lon} ],
14156 html => $marker->{label},
14157 0 ▶ radius => _map_radius($sv, $size_min, $size_max),
Branch: 2 branches
BranchTrueFalseTotal
defined $color ? : 0 0 0
defined $group ? : 0 0 0
14158 (defined($color) ? (colour => _color_hex($color)) : ()),
14159 (defined($group) ? (group => $group) : ()),
14160 );
14161 } else {
14162 $map->add_marker(
14163 [ $marker->{lat}, $marker->{lon} ],
14164 html => $marker->{label},
14165 3 ▶ (defined($color) ? (icon => _marker_icon($color)) : ()),
Branch: 2 branches
BranchTrueFalseTotal
defined $color ? : 0 3 3
defined $group ? : 0 3 3
14166 (defined($group) ? (group => $group) : ()),
14167 );
14168 }
14169 }
14170  
14171 # Heat map overlay: when heat=1 is requested, plot a density
14172 # heatmap in addition to the regular markers. The weight column
14173 # (weight=<col>) drives the intensity of each point; absent the
14174 # column every point has equal weight 1.0. Normalisation to [0,1]
14175 # ensures the heatmap library gets values in the expected range.
14176 3 ▶ if ($options->{heat}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"heat"}) 0 3 3
14177 0 ▶ my $weight_col = $options->{weight} // '';
Condition0%0/2
$options->{"weight"} // ""
l!l
00
MC/DC0%0/1
$options->{"weight"} // ""
$options->{"weight"}
Truth table0%0/2
A
A= $options->{"weight"}
Aresult
11
00
14178 0 my @heat_pts;
14179 0 for my $marker (@markers) {
14180 0 my $row = $records->[ $marker->{first_row} ];
14181 0 my $w;
14182 0 ▶ if (length $weight_col && defined $row) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $weight_col and defined $row) 0 0 0
Condition0%0/3
length $weight_col and defined $row
!ll&&!rl&&r
000
MC/DC0%0/2
length $weight_col and defined $row
length $weight_col defined $row
Truth table0%0/3
A and B
A= length $weight_colB= defined $row
ABresult
0X0
100
111
14183 0 ▶ $w = _numeric_cell($row->{$weight_col} // '');
Condition0%0/2
$row->{$weight_col} // ""
l!l
00
MC/DC0%0/1
$row->{$weight_col} // ""
$row->{$weight_col}
Truth table0%0/2
A
A= $row->{$weight_col}
Aresult
11
00
14184 }
14185 push @heat_pts, [ $marker->{lat}, $marker->{lon},
14186 0 ▶ (defined($w) ? $w : 1) ];
Branch: 1 branch
BranchTrueFalseTotal
defined $w ? : 0 0 0
14187 }
14188 # Normalise weights to [0,1] when a weight column was used.
14189 0 ▶ if (length $weight_col && @heat_pts) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $weight_col and @heat_pts) 0 0 0
Condition0%0/3
length $weight_col and @heat_pts
!ll&&!rl&&r
000
MC/DC0%0/2
length $weight_col and @heat_pts
length $weight_col @heat_pts
Truth table0%0/3
A and B
A= length $weight_colB= @heat_pts
ABresult
0X0
100
111
14190 0 my $max_w = 0;
14191 0 ▶ $max_w = $_->[2] > $max_w ? $_->[2] : $max_w for @heat_pts;
Branch: 1 branch
BranchTrueFalseTotal
$_->[2] > $max_w ? : 0 0 0
14192 0 ▶ if ($max_w > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max_w > 0) 0 0 0
14193 0 $_->[2] = $_->[2] / $max_w for @heat_pts;
14194 }
14195 }
14196 0 eval { $map->add_heatmap(\@heat_pts) };
14197 }
14198  
14199 # The county outlines, under the markers, with a checkbox on
14200 # the map to hide them (HTML::OSM 0.15; an older copy ignores
14201 # name and draws them always). Grey, or with heat=1 coloured
14202 # by what the heat layer weighs in each, one layer a colour
14203 # under one name, so one checkbox still hides them all.
14204 # When the markers are coloured, each outline takes the colours
14205 # of the markers in it, so the two never disagree; the heat
14206 # layer's own scale is for a map whose markers are all alike.
14207 3 my $noun = $self->_map_outline_noun($outlines);
14208 3 ▶ my @outline_layers = length($color_col)
Branch: 1 branch
BranchTrueFalseTotal
length $color_col ? : 0 3 3
14209 ? $self->_map_outline_marker_layers($outlines, \@markers) : ();
14210 3 ▶ $bounds_as_markers = 1 if @outline_layers;
Branch: 1 branch
BranchTrueFalseTotal
if @outline_layers 0 3 3
14211 # Colour shade fills each outline by a column's total. It says
14212 # what the heat layer's line colours would, so those stay grey.
14213 3 ▶ my $shade_col = $options->{shade} // '';
Condition50%1/2
$options->{"shade"} // ""
l!l
03
MC/DC0%0/1
$options->{"shade"} // ""
$options->{"shade"}
Truth table50%1/2
A
A= $options->{"shade"}
Aresult
11
00
14214 3 ▶ $shade_col = '' if ref($shade_col) || !$col_set{$shade_col};
Branch: 1 branch
BranchTrueFalseTotal
if ref $shade_col or not $col_set{$shade_col} 3 0 3
Condition33%1/3
ref $shade_col or not $col_set{$shade_col}
l!l&&r!l&&!r
030
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
14215 @outline_layers = $self->_map_outline_layers($outlines, \@markers, $records,
14216 3 ▶ (($options->{heat} && !length($shade_col)) ? ($options->{weight} // '') : undef), $noun)
Branch: 2 branches
BranchTrueFalseTotal
unless @outline_layers 3 0 3
$options->{'heat'} && !length($shade_col) ? : 0 3 3
Condition20%1/5
$options->{"heat"} and not length $shade_col
!ll&&!rl&&r
300
$options->{"weight"} // ""
l!l
00
MC/DC0%0/2
$options->{"heat"} and not length $shade_col
$options->{"heat"} not length $shade_col
MC/DC0%0/1
$options->{"weight"} // ""
$options->{"weight"}
Truth table33%1/3
A and not(B)
A= $options->{"heat"}B= not length $shade_col
ABresult
0X0
100
111
Truth table0%0/2
A
A= $options->{"weight"}
Aresult
11
00
14217 unless @outline_layers;
14218 3 ▶ if (length $shade_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $shade_col) 0 3 3
14219 # Coloured markers and no colour asked for: each outline is
14220 # shaded in its markers' colour. When the shade is of the
14221 # column the rules read, a "less than" rule's colour is the
14222 # stronger the smaller the total.
14223 0 my $lower;
14224 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
14225 0 $lower = {};
14226 0 ▶ for my $rule ($shade_col eq $color_col ? @{$color_rules} : ()) {
Branch: 1 branch
BranchTrueFalseTotal
$shade_col eq $color_col ? : 0 0 0
14227 0 my $hue = _color_hex($rule->{color});
14228 0 $hue =~ s/\A#(.)(.)(.)\z/#$1$1$2$2$3$3/;
14229 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
14230 }
14231 }
14232 my @shaded = $self->_map_outline_shade(\@outline_layers, $outlines, \@markers,
14233 0 $records, $shade_col, $options->{shade_color}, $noun, $lower);
14234 0 ▶ if (@shaded) {
Branch: 1 branch
BranchTrueFalseTotal
if (@shaded) 0 0 0
14235 0 @outline_layers = @shaded;
14236 0 $bounds_shade = $shade_col;
14237 0 ▶ $bounds_shade_as = $lower ? 'markers' : 'one';
Branch: 1 branch
BranchTrueFalseTotal
$lower ? : 0 0 0
14238 }
14239 }
14240 3 for my $layer (@outline_layers) {
14241 # Only a layer with a key was coloured to mean something;
14242 # a shaded map's key is for its fills.
14243 0 ▶ $bounds_coloured = 1 if $layer->{key} && !length($bounds_shade);
Branch: 1 branch
BranchTrueFalseTotal
if $layer->{"key"} and not length $bounds_shade 0 0 0
Condition0%0/3
$layer->{"key"} and not length $bounds_shade
!ll&&!rl&&r
000
MC/DC0%0/2
$layer->{"key"} and not length $bounds_shade
$layer->{"key"} not length $bounds_shade
Truth table0%0/3
A and not(B)
A= $layer->{"key"}B= not length $bounds_shade
ABresult
0X0
100
111
14244 $map->add_geojson(
14245 { type => 'FeatureCollection', features => $layer->{features} },
14246 style => { color => $layer->{colour}, weight => $layer->{weight},
14247 opacity => $layer->{opacity},
14248 ($layer->{fill}
14249 ? (fill => \1, fillColor => $layer->{fill}, fillOpacity => $SHADE_OPACITY)
14250 : (fill => \0)) },
14251 popup => 'name',
14252 name => $self->_i18n('map_bounds_layer', ucfirst $noun),
14253 ($layer->{key} ? (key => $layer->{key}) : ()),
14254 # HTML::OSM 0.17 draws each colour as a line of its own,
14255 # inside the outline's edge; an older copy ignores this
14256 # and draws the first alone, along the edge.
14257 0 ▶ ($layer->{bands} ? (bands => 'colours') : ()),
Branch: 3 branches
BranchTrueFalseTotal
$layer->{'fill'} ? : 0 0 0
$layer->{'key'} ? : 0 0 0
$layer->{'bands'} ? : 0 0 0
14258 );
14259 }
14260  
14261 3 ($map_head, $map_body) = $map->onload_render();
14262 3 ▶ ($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 0 3
Condition33%1/3
defined $id_suffix and length $id_suffix
!ll&&!rl&&r
003
MC/DC0%0/2
defined $id_suffix and length $id_suffix
defined $id_suffix length $id_suffix
Truth table33%1/3
A and B
A= defined $id_suffixB= length $id_suffix
ABresult
0X0
100
111
14263 if defined($id_suffix) && length($id_suffix);
14264 3 1;
14265 };
14266 3 ▶ unless ($drawn) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($drawn) 0 3 3
14267 0 $self->app->log->error('The map could not be drawn: ' . _tidy_error($@));
14268 0 ($map_head, $map_body) = ();
14269 0 push @messages, {
14270 key => 'error_map_renderer_failed',
14271 text => $self->_i18n('error_map_renderer_failed'),
14272 };
14273 }
14274 } elsif (defined $osm_version) {
14275 0 push @messages, {
14276 key => 'error_map_renderer_old',
14277 text => $self->_i18n('error_map_renderer_old', $osm_version),
14278 };
14279 } else {
14280 0 push @messages, {
14281 key => 'error_map_renderer_missing',
14282 text => $self->_i18n('error_map_renderer_missing'),
14283 };
14284 }
14285 }
14286  
14287 5 ▶ my %chart_spec = (
Branch: 3 branches
BranchTrueFalseTotal
$by_location ? : 5 0 5
@loc_cols == 1 ? : 5 0 5
length $loc_text ? : 0 5 5
14288 kind => 'map',
14289 title => $title,
14290 encode => ($by_location
14291 ? { loc => (@loc_cols == 1 ? $loc_cols[0] : [ @loc_cols ]),
14292 (length($loc_text) ? (loc_text => $loc_text) : ()) }
14293 : { lat => $lat_col, lon => $lon_col }),
14294 );
14295 5 ▶ $chart_spec{options}{popup} = \@popup if @popup;
Branch: 1 branch
BranchTrueFalseTotal
if @popup 5 0 5
14296 $chart_spec{options}{max} = $options->{max}
14297 5 ▶ 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 0 5 5
Condition33%2/6
defined $options->{"max"} and $options->{"max"} =~ /\A\d+\z/u and $options->{"max"} > 0
!ll&&!rl&&r
500
defined $options->{"max"} and $options->{"max"} =~ /\A\d+\z/u
!ll&&!rl&&r
500
MC/DC0%0/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 table25%1/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
14298 5 ▶ $chart_spec{options}{zoom} = $options->{zoom} if defined $options->{zoom};
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"zoom"} 0 5 5
14299 5 ▶ $chart_spec{options}{heat} = 1 if $options->{heat};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"heat"} 0 5 5
14300 5 ▶ $chart_spec{options}{bounds} = $bounds_level if defined $bounds_level;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bounds_level 0 5 5
14301 $chart_spec{options}{shade} = $options->{shade}
14302 5 ▶ 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 5 5
Condition33%2/6
defined $options->{"shade"} and not ref $options->{"shade"} and length $options->{"shade"}
!ll&&!rl&&r
500
defined $options->{"shade"} and not ref $options->{"shade"}
!ll&&!rl&&r
500
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
14303 $chart_spec{options}{shade_color} = $options->{shade_color}
14304 5 ▶ 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 5 5
Condition33%2/6
defined $chart_spec{"options"}{"shade"} and defined $options->{"shade_color"} and not ref $options->{"shade_color"}
!ll&&!rl&&r
500
defined $chart_spec{"options"}{"shade"} and defined $options->{"shade_color"}
!ll&&!rl&&r
500
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
14305 $chart_spec{options}{weight} = $options->{weight}
14306 5 ▶ if defined($options->{weight}) && length($options->{weight});
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"weight"} and length $options->{"weight"} 0 5 5
Condition33%1/3
defined $options->{"weight"} and length $options->{"weight"}
!ll&&!rl&&r
500
MC/DC0%0/2
defined $options->{"weight"} and length $options->{"weight"}
defined $options->{"weight"} length $options->{"weight"}
Truth table33%1/3
A and B
A= defined $options->{"weight"}B= length $options->{"weight"}
ABresult
0X0
100
111
14307 5 ▶ if (defined($options->{size}) && length($options->{size})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"size"} and length $options->{"size"}) 0 5 5
Condition33%1/3
defined $options->{"size"} and length $options->{"size"}
!ll&&!rl&&r
500
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
14308 0 $chart_spec{encode}{size} = $options->{size};
14309 }
14310 5 ▶ if (defined($options->{scheme}) && length($options->{scheme})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"scheme"} and length $options->{"scheme"}) 0 5 5
Condition33%1/3
defined $options->{"scheme"} and length $options->{"scheme"}
!ll&&!rl&&r
500
MC/DC0%0/2
defined $options->{"scheme"} and length $options->{"scheme"}
defined $options->{"scheme"} length $options->{"scheme"}
Truth table33%1/3
A and B
A= defined $options->{"scheme"}B= length $options->{"scheme"}
ABresult
0X0
100
111
14311 0 $chart_spec{options}{scheme} = $options->{scheme};
14312 }
14313 5 ▶ if (defined($options->{color_col}) && length($options->{color_col})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"color_col"} and length $options->{"color_col"}) 0 5 5
Condition33%1/3
defined $options->{"color_col"} and length $options->{"color_col"}
!ll&&!rl&&r
500
MC/DC0%0/2
defined $options->{"color_col"} and length $options->{"color_col"}
defined $options->{"color_col"} length $options->{"color_col"}
Truth table33%1/3
A and B
A= defined $options->{"color_col"}B= length $options->{"color_col"}
ABresult
0X0
100
111
14314 0 $chart_spec{encode}{color} = $options->{color_col};
14315 $chart_spec{options}{color_rules} = $options->{color_rules}
14316 0 ▶ if defined($options->{color_rules}) && @{ $options->{color_rules} };
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"color_rules"} and @{$options->{"color_rules"};} 0 0 0
Condition0%0/3
defined $options->{"color_rules"} and @{$options->{"color_rules"};}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $options->{"color_rules"} and @{$options->{"color_rules"};}
defined $options->{"color_rules"} @{$options->{"color_rules"};}
Truth table0%0/3
A and B
A= defined $options->{"color_rules"}B= @{$options->{"color_rules"};}
ABresult
0X0
100
111
14317 $chart_spec{options}{color_default} = $options->{color_default}
14318 0 ▶ if defined($options->{color_default});
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"color_default"} 0 0 0
14319 }
14320  
14321 return {
14322 title => $title,
14323 map_head => $map_head,
14324 map_body => $map_body,
14325 messages => \@messages,
14326 marker_count => scalar @markers,
14327 row_count => $plotted_rows,
14328 source_rows => scalar @$records,
14329 loc_col => ($by_location ? $loc_col : undef),
14330 loc_text => $loc_text,
14331 lat_col => ($by_location ? undef : $lat_col),
14332 lon_col => ($by_location ? undef : $lon_col),
14333 backend => $backend,
14334 chart => \%chart_spec,
14335 unplotted => \@unplotted,
14336 unplotted_filters => \@unplotted_filters,
14337 pending => \@pending,
14338 bounds_level => $bounds_level,
14339 bounds_pending => \@bounds_pending,
14340 bounds_drawn => ($outlines ? $outlines->{counts}{drawn} : 0),
14341 bounds_noun => $self->_map_outline_noun($outlines),
14342 # Coloured by the heat layer's weight column, or its rows when it has
14343 # none; not when the outlines had nothing to compare and stayed grey.
14344 bounds_heat => $bounds_coloured,
14345 5 ▶ bounds_weight => ($bounds_coloured ? ($options->{weight} // '') : ''),
Branch: 5 branches
BranchTrueFalseTotal
$by_location ? : 5 0 5
$by_location ? : 5 0 5
$by_location ? : 5 0 5
$outlines ? : 0 5 5
$bounds_coloured ? : 0 5 5
Condition25%1/4
$options->{"weight"} // ""
l!l
00
$bounds_left_rows // 0
l!l
05
MC/DC0%0/1
$options->{"weight"} // ""
$options->{"weight"}
MC/DC0%0/1
$bounds_left_rows // 0
$bounds_left_rows
Truth table0%0/2
A
A= $options->{"weight"}
Aresult
11
00
Truth table50%1/2
A
A= $bounds_left_rows
Aresult
11
00
14346 bounds_as_markers => $bounds_as_markers,
14347 bounds_shade => $bounds_shade,
14348 bounds_shade_as => $bounds_shade_as,
14349 bounds_left_filters => \@bounds_left_filters,
14350 bounds_groups => \@bounds_groups,
14351 bounds_left_rows => $bounds_left_rows // 0,
14352 };
14353 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
14354  
14355 # _map_renderer_version() -> ($ok, $installed_version)
14356 #
14357 # Loads the optional HTML::OSM and says whether it is new enough for the options
14358 # _map_data passes. $installed_version is undef when the module could not be
14359 # loaded at all; when it is defined but $ok is false the copy is too old.
14360 #
14361 # This is a method rather than an inline require so a test can replace it.
14362 # Test::Without::Module does not produce the missing case here: its @INC hook
14363 # is bypassed during Mojolicious' in-process dispatch, so the installed copy is
14364 # still found, and the branch an operator without the dependency is in cannot
14365 # be reached by hiding the module. Replacing one method exercises the same
14366 # else branch, the same message and the same page.
14367 4 ▶sub _map_renderer_version {
Subroutine _map_renderer_version: called CC=4 SCAR=14.5
14368 4 my $self = shift;
14369  
14370 4 my $version = eval {
14371 4 require HTML::OSM;
14372 4 HTML::OSM->VERSION;
14373 };
14374 4 ▶ return (0, undef) unless defined($version) && length($version);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $version and length $version 0 4 4
Condition33%1/3
defined $version and length $version
!ll&&!rl&&r
004
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
14375  
14376 4 my $new_enough = eval { HTML::OSM->VERSION($MIN_HTML_OSM_VERSION); 1 };
14377 4 ▶ return ($new_enough ? 1 : 0, $version);
Branch: 1 branch
BranchTrueFalseTotal
$new_enough ? : 4 0 4
14378 }
14379  
14380 # _canvas_map_html($head, $body, $id_suffix) -> ($head, $body)
14381 #
14382 # HTML::OSM names the map element "map" and its reset button "reset-button".
14383 # With search => 0 (always set by _map_data), the search-box and
14384 # clear-search-button elements are absent. Suffixing still happens so a
14385 # canvas with two maps gets distinct element ids and local variable scopes.
14386 # The head is the same Leaflet stylesheet and script for every map, so only
14387 # the first head is passed to the layout.
14388 # _scope_card_scripts($html) -> $html
14389 #
14390 # Purpose: Close every inline script in a rendered card over a function of its
14391 # own, so two cards on one canvas cannot collide.
14392 # Entry: $html -- one card's markup, as _render_visual_markup returns it.
14393 # Exit: The same markup, with each inline script wrapped.
14394 # Notes: Called once, by _render_visual_html, so no caller has to remember
14395 # it and no card is scoped twice. HTML::D3 writes a chart as a
14396 # snippet that declares its SVG with
14397 # C<const>. A top-level C<const> belongs to the page's shared lexical
14398 # environment rather than to the <script> element it was written in,
14399 # so a canvas of two charts failed at the second one -- "Identifier
14400 # 'svg' has already been declared" -- and drew an empty card, while
14401 # either card on a page of its own was fine. A script with a C<src>,
14402 # or with a C<type> of its own (a data block, a module), is left
14403 # alone, and one that is already wrapped is not wrapped twice.
14404 27 ▶sub _scope_card_scripts {
Subroutine _scope_card_scripts: called CC=3 SCAR=11.0
14405 27 my ($html) = @_;
14406 27 ▶ return '' unless defined $html && length $html;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $html and length $html 2 25 27
Condition100%3/3
defined $html and length $html
!ll&&!rl&&r
1125
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
14407  
14408 # ~ is the delimiter because the lookaheads below need !, and the wrapper
14409 # the replacement builds is a pair of braces, which a brace-delimited
14410 # pattern would take for its own.
14411 25 $html =~ s~(<script\b(?![^>]*\bsrc=)(?![^>]*\btype=)[^>]*>)(.*?)(</script>)~_wrap_card_script($1, $2, $3)~gsex;
14412  
14413 25 return $html;
14414 }
14415  
14416 # _wrap_card_script($open, $body, $close) -> $html
14417 #
14418 # Purpose: One <script> element of a card, closed over a function of its own.
14419 # Entry: The element's opening tag, its body and its closing tag.
14420 # Exit: The same element, wrapped unless it already is.
14421 # Notes: Split out of _scope_card_scripts so that pattern can use a plain
14422 # delimiter: its lookaheads need the ones the wrapper is made of.
14423 21 ▶sub _wrap_card_script {
Subroutine _wrap_card_script: called CC=2 SCAR=6.9
14424 21 my ($open, $body, $close) = @_;
14425  
14426 # A body that already opens with the wrapper is left alone, so scoping a
14427 # card twice is scoping it once.
14428 21 my ($blank) = $body =~ /\A(\s*)/;
14429 21 ▶ return $open . $body . $close
Branch: 1 branch
BranchTrueFalseTotal
if CORE::index(substr($body, length $blank), "(function () {") == 0 2 19 21
14430 if CORE::index(substr($body, length $blank), '(function () {') == 0;
14431  
14432 19 return $open . "\n(function () {\n" . $body . "\n})();\n" . $close;
14433 }
14434  
14435 7 ▶sub _canvas_map_html {
Subroutine _canvas_map_html: called CC=4 SCAR=13.9
14436 7 my ($head, $body, $id_suffix) = @_;
14437  
14438 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
14439 7 $suffix =~ s/[^A-Za-z0-9_-]//g;
14440 7 ▶ $suffix = 'map' unless length $suffix;
Branch: 1 branch
BranchTrueFalseTotal
unless length $suffix 1 6 7
14441  
14442 7 my %ids = (
14443 'map' => "map-$suffix",
14444 'search-box' => "search-box-$suffix",
14445 'reset-button' => "reset-button-$suffix",
14446 'clear-search-button' => "clear-search-button-$suffix",
14447 );
14448 7 for my $old (sort keys %ids) {
14449 28 my $new = $ids{$old};
14450 28 $body =~ s/id="\Q$old\E"/id="$new"/g;
14451 28 $body =~ s{getElementById\('\Q$old\E'\)}{getElementById('$new')}g;
14452 28 $body =~ s{L\.map\('\Q$old\E'\)}{L.map('$new')}g;
14453 }
14454 7 $body =~ s{<div id="$ids{map}"></div>}{<div id="$ids{map}" class="canvas-map"></div>};
14455  
14456 # The card owns the map's size, so the page-wide #map rule is noise here.
14457 7 $head =~ s{<style>.*?</style>}{}s;
14458  
14459 # The scope around the map's script is not put on here: every card is
14460 # scoped once, by _render_visual_html, whichever kind it is.
14461 7 return ($head, $body);
14462 }
14463  
14464 47 ▶sub map_view ($self) {
Subroutine map_view: called CC=112 SCAR=77.9
Pod documented
14465 47 my @loc_cols = _map_loc_columns($self->every_param('loc'));
14466 47 my $loc_col = join(', ', @loc_cols);
14467 47 ▶ my $lat_col = $self->param('lat') // '';
Condition100%2/2
$self->param("lat") // ""
l!l
443
MC/DC100%1/1
$self->param("lat") // ""
$self->param("lat")
Truth table100%2/2
A
A= $self->param("lat")
Aresult
11
00
14468 47 ▶ my $lon_col = $self->param('lon') // '';
Condition100%2/2
$self->param("lon") // ""
l!l
443
MC/DC100%1/1
$self->param("lon") // ""
$self->param("lon")
Truth table100%2/2
A
A= $self->param("lon")
Aresult
11
00
14469 47 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
047
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
14470 47 my $back2 = _safe_back_url($self->param('back2'));
14471 47 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
047
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
14472  
14473 # Optional display params
14474 47 ▶ my $zoom_raw = $self->param('zoom') // '';
Condition50%1/2
$self->param("zoom") // ""
l!l
047
MC/DC0%0/1
$self->param("zoom") // ""
$self->param("zoom")
Truth table50%1/2
A
A= $self->param("zoom")
Aresult
11
00
14475 47 ▶ my $max_zoom_raw = $self->param('max_zoom') // '';
Condition50%1/2
$self->param("max_zoom") // ""
l!l
047
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
14476 47 ▶ my $tiles_name = $self->param('tiles') // '';
Condition50%1/2
$self->param("tiles") // ""
l!l
047
MC/DC0%0/1
$self->param("tiles") // ""
$self->param("tiles")
Truth table50%1/2
A
A= $self->param("tiles")
Aresult
11
00
14477 47 ▶ my $heat = $self->param('heat') // 0;
Condition50%1/2
$self->param("heat") // 0
l!l
047
MC/DC0%0/1
$self->param("heat") // 0
$self->param("heat")
Truth table50%1/2
A
A= $self->param("heat")
Aresult
11
00
14478 47 ▶ my $bounds_raw = $self->param('bounds') // '';
Condition50%1/2
$self->param("bounds") // ""
l!l
047
MC/DC0%0/1
$self->param("bounds") // ""
$self->param("bounds")
Truth table50%1/2
A
A= $self->param("bounds")
Aresult
11
00
14479 47 ▶ my $loc_text_raw = $self->param('loc_text') // '';
Condition50%1/2
$self->param("loc_text") // ""
l!l
047
MC/DC0%0/1
$self->param("loc_text") // ""
$self->param("loc_text")
Truth table50%1/2
A
A= $self->param("loc_text")
Aresult
11
00
14480 47 ▶ my $weight_col = $self->param('weight') // '';
Condition50%1/2
$self->param("weight") // ""
l!l
047
MC/DC0%0/1
$self->param("weight") // ""
$self->param("weight")
Truth table50%1/2
A
A= $self->param("weight")
Aresult
11
00
14481 47 ▶ my $shade_col = $self->param('shade') // '';
Condition50%1/2
$self->param("shade") // ""
l!l
047
MC/DC0%0/1
$self->param("shade") // ""
$self->param("shade")
Truth table50%1/2
A
A= $self->param("shade")
Aresult
11
00
14482 47 ▶ my $shade_color = _parse_color($self->param('shade_color') // '');
Condition50%1/2
$self->param("shade_color") // ""
l!l
047
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
14483 47 ▶ my $size_col = $self->param('size') // '';
Condition100%2/2
$self->param("size") // ""
l!l
245
MC/DC100%1/1
$self->param("size") // ""
$self->param("size")
Truth table100%2/2
A
A= $self->param("size")
Aresult
11
00
14484 47 ▶ my $series_col = $self->param('series') // '';
Condition50%1/2
$self->param("series") // ""
l!l
047
MC/DC0%0/1
$self->param("series") // ""
$self->param("series")
Truth table50%1/2
A
A= $self->param("series")
Aresult
11
00
14485 47 ▶ my $scheme = $self->param('scheme') // 'tableau10';
Condition100%2/2
$self->param("scheme") // "tableau10"
l!l
245
MC/DC100%1/1
$self->param("scheme") // "tableau10"
$self->param("scheme")
Truth table100%2/2
A
A= $self->param("scheme")
Aresult
11
00
14486  
14487 # tiles= names a source from tile_sources in config; an arbitrary URL is
14488 # never accepted so a crafted share link cannot redirect tiles fetches.
14489 47 my $tile_url_override;
14490 47 ▶ if (length $tiles_name) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $tiles_name) 0 47 47
14491 0 ▶ my $sources = $self->app->config('tile_sources') // {};
Condition0%0/2
$self->app->config("tile_sources") // {}
l!l
00
MC/DC0%0/1
$self->app->config("tile_sources") // {}
$self->app->config("tile_sources")
Truth table0%0/2
A
A= $self->app->config("tile_sources")
Aresult
11
00
14492 0 ▶ unless (exists $sources->{$tiles_name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $sources->{$tiles_name}) 0 0 0
14493 0 return $self->render(
14494 text => $self->_i18n('error_map_tiles_unknown', $tiles_name),
14495 status => 400,
14496 );
14497 }
14498 0 $tile_url_override = $sources->{$tiles_name}{url};
14499 }
14500  
14501 47 my $zoom_val;
14502 47 ▶ 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 47 47
Condition33%1/3
length $zoom_raw and $zoom_raw =~ /\A\d+\z/u
!ll&&!rl&&r
4700
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
14503 0 $zoom_val = int $zoom_raw;
14504 0 ▶ $zoom_val = 0 if $zoom_val < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $zoom_val < 0 0 0 0
14505 0 ▶ $zoom_val = 19 if $zoom_val > 19;
Branch: 1 branch
BranchTrueFalseTotal
if $zoom_val > 19 0 0 0
14506 }
14507  
14508 47 my $max_zoom_val;
14509 47 ▶ 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 47 47
Condition33%1/3
length $max_zoom_raw and $max_zoom_raw =~ /\A\d+\z/u
!ll&&!rl&&r
4700
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
14510 0 $max_zoom_val = int $max_zoom_raw;
14511 0 ▶ $max_zoom_val = 0 if $max_zoom_val < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $max_zoom_val < 0 0 0 0
14512 0 ▶ $max_zoom_val = 28 if $max_zoom_val > 28;
Branch: 1 branch
BranchTrueFalseTotal
if $max_zoom_val > 28 0 0 0
14513 } else {
14514 47 my $cfg_max_zoom = $self->app->config('map_max_zoom');
14515 47 ▶ $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 47 47
Condition33%1/3
defined $cfg_max_zoom and $cfg_max_zoom =~ /\A\d+\z/u
!ll&&!rl&&r
4700
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
14516 if defined($cfg_max_zoom) && $cfg_max_zoom =~ /\A\d+\z/;
14517 }
14518  
14519 47 my $by_location = length $loc_col;
14520  
14521 47 my ($loc_text) = _map_loc_text($loc_text_raw);
14522 47 ▶ 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 0 47 47
14523 unless defined $loc_text;
14524  
14525 47 my $bounds_level;
14526 47 ▶ if (length $bounds_raw) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $bounds_raw) 0 47 47
14527 0 $bounds_level = _map_bounds_level($bounds_raw);
14528 0 ▶ return $self->render(text => $self->_i18n('error_map_bounds_unknown', $bounds_raw), status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bounds_level 0 0 0
14529 unless defined $bounds_level;
14530 }
14531  
14532 47 ▶ 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 42 5 47
Condition100%6/6
$by_location or length $lat_col or length $lon_col
l!l&&r!l&&!r
4142
$by_location or length $lat_col
l!l&&r!l&&!r
1343
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
14533 unless $by_location || length($lat_col) || length($lon_col);
14534 5 ▶ 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 2 3 5
Condition100%6/6
$by_location or length $lat_col and length $lon_col
l!l&&r!l&&!r
122
length $lat_col and length $lon_col
!ll&&!rl&&r
112
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
14535 if !$by_location && (!length($lat_col) || !length($lon_col));
14536  
14537 3 my ($src, $records, $columns) = $self->_run_pipeline_source;
14538 3 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 2 3
14539 unless defined $records;
14540  
14541 2 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
14542 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2 2
14543 0 (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
14544 0 return $self->render(text => $e, status => 400);
14545 }
14546  
14547 # geocode= says when the places not in the cache yet are looked up: 'wait'
14548 # in this request, before the page is sent; 'cached' not at all, so the map
14549 # shows what the cache knows (where Cancel leads). Without it, a page a
14550 # browser navigated to (a GET whose Accept names text/html, which fetch()
14551 # and scripts do not send) asks nothing here: it lists the places for the
14552 # page, which looks them up one at a time with a progress bar. Any other
14553 # client waits, as every client did before.
14554 2 ▶ my $geocode_mode = $self->param('geocode') // '';
Condition50%1/2
$self->param("geocode") // ""
l!l
02
MC/DC0%0/1
$self->param("geocode") // ""
$self->param("geocode")
Truth table50%1/2
A
A= $self->param("geocode")
Aresult
11
00
14555 2 ▶ 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 0 2 2
14556 unless $geocode_mode =~ /\A(?:wait|cached|)\z/;
14557 2 ▶ my $progress = ($by_location || defined($bounds_level)) && !length($geocode_mode)
Condition64%9/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
110
$by_location || defined $bounds_level and not length $geocode_mode and $self->req->method eq "GET"
!ll&&!rl&&r
101
$by_location || defined $bounds_level and not length $geocode_mode
!ll&&!rl&&r
101
$by_location or defined $bounds_level
l!l&&r!l&&!r
101
$self->req->headers->accept // ""
l!l
01
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 table22%2/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
14558 && $self->req->method eq 'GET'
14559 && ($self->req->headers->accept // '') =~ m{\btext/html\b};
14560  
14561 2 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 2 2
14562  
14563 2 my %col_set = map { $_ => 1 } @{ $columns };
14564 2 my %loc_set = map { $_ => 1 } @loc_cols;
14565 0 ▶ my @popup = grep { length($_) && !$loc_set{$_} && $col_set{$_} }
Condition0%0/6
length $_ && !$loc_set{$_} && $col_set{$_}
!ll&&!rl&&r
000
length $_ and not $loc_set{$_}
!ll&&!rl&&r
000
MC/DC0%0/3
length $_ && !$loc_set{$_} && $col_set{$_}
length $_ not $loc_set{$_} $col_set{$_}
Truth table0%0/4
A and not(B) && C
A= length $_B= not $loc_set{$_}C= $col_set{$_}
ABCresult
0XX0
10X0
1100
1111
14566 2 @{ $self->every_param('popup') };
14567  
14568 # Marker colour params. color= applies explicit threshold rules;
14569 # series= colours one value per distinct category from scheme=, which is the
14570 # categorical form the other chart pages already offer.
14571 2 ▶ my $color_col = $self->param('color') // '';
Condition50%1/2
$self->param("color") // ""
l!l
02
MC/DC0%0/1
$self->param("color") // ""
$self->param("color")
Truth table50%1/2
A
A= $self->param("color")
Aresult
11
00
14572 2 ▶ my $color_def_raw = $self->param('color_default') // '';
Condition50%1/2
$self->param("color_default") // ""
l!l
02
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
14573 2 my ($color_rules, $color_default) =
14574 _parse_color_rules($self->every_param('color_rule'), $color_def_raw);
14575  
14576 2 ▶ if (length($color_col) && !$col_set{$color_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $color_col and not $col_set{$color_col}) 0 2 2
Condition33%1/3
length $color_col and not $col_set{$color_col}
!ll&&!rl&&r
200
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
14577 0 return $self->render(text => "Column not found: $color_col", status => 400);
14578 }
14579 2 ▶ 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 2 2
Condition33%1/3
length $color_col and length $series_col
!ll&&!rl&&r
200
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
14580 if length($color_col) && length($series_col);
14581 return $self->render(text => "Column not found: $size_col", status => 400)
14582 2 ▶ if length($size_col) && !$col_set{$size_col};
Branch: 1 branch
BranchTrueFalseTotal
if length $size_col and not $col_set{$size_col} 0 2 2
Condition33%1/3
length $size_col and not $col_set{$size_col}
!ll&&!rl&&r
200
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
14583  
14584 2 my (@series_cats, $series_palette);
14585 2 ▶ if (length $series_col) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $series_col) 0 2 2
14586 return $self->render(text => "Column not found: $series_col", status => 400)
14587 0 ▶ unless $col_set{$series_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col_set{$series_col} 0 0 0
14588 return $self->render(text => "Unknown colour scheme: $scheme", status => 400)
14589 0 ▶ unless $SCATTER_SCHEMES{$scheme};
Branch: 1 branch
BranchTrueFalseTotal
unless $SCATTER_SCHEMES{$scheme} 0 0 0
14590  
14591 0 ▶ $series_palette = $CATEGORY_PALETTES{$scheme} // $CATEGORY_PALETTES{tableau10};
Condition0%0/3
$CATEGORY_PALETTES{$scheme} // $CATEGORY_PALETTES{"tableau10"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$CATEGORY_PALETTES{$scheme} // $CATEGORY_PALETTES{"tableau10"}
$CATEGORY_PALETTES{$scheme} $CATEGORY_PALETTES{"tableau10"}
Truth table0%0/3
A // B
A= $CATEGORY_PALETTES{$scheme}B= $CATEGORY_PALETTES{"tableau10"}
ABresult
1X1
011
000
14592 0 my %seen;
14593 0 @series_cats = grep { !$seen{$_}++ } map {
14594 0 my $value = $_->{$series_col};
14595 0 ▶ defined($value) ? "$value" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 0 0 0
14596 } @$records;
14597  
14598 # A legend longer than two cycles of the palette helps nobody; the
14599 # remaining values keep a palette colour but are not listed.
14600 0 my $limit = @$series_palette * 2;
14601 0 ▶ @series_cats = @series_cats[0 .. $limit - 1] if @series_cats > $limit;
Branch: 1 branch
BranchTrueFalseTotal
if @series_cats > $limit 0 0 0
14602  
14603 0 $color_col = $series_col;
14604 $color_rules = [
14605 map {
14606 0 {
14607 0 op => 'eq',
14608 val => $series_cats[$_],
14609 color => $series_palette->[ $_ % @$series_palette ],
14610 }
14611 } 0 .. $#series_cats
14612 ];
14613 0 $color_default = $series_palette->[0];
14614 }
14615  
14616 2 my %options;
14617 2 ▶ $options{popup} = \@popup if @popup;
Branch: 1 branch
BranchTrueFalseTotal
if @popup 0 2 2
14618 2 ▶ $options{color_col} = $color_col if length $color_col;
Branch: 1 branch
BranchTrueFalseTotal
if length $color_col 0 2 2
14619 2 ▶ $options{color_rules} = $color_rules if @$color_rules;
Branch: 1 branch
BranchTrueFalseTotal
if @$color_rules 0 2 2
14620 2 $options{color_default} = $color_default;
14621 2 ▶ $options{size} = $size_col if length $size_col;
Branch: 1 branch
BranchTrueFalseTotal
if length $size_col 0 2 2
14622 2 ▶ $options{scheme} = $scheme if length $series_col;
Branch: 1 branch
BranchTrueFalseTotal
if length $series_col 0 2 2
14623 2 my $max = $self->param('max');
14624 2 ▶ $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 0 2 2
Condition33%2/6
defined $max and $max =~ /\A\d+\z/u and $max > 0
!ll&&!rl&&r
200
defined $max and $max =~ /\A\d+\z/u
!ll&&!rl&&r
200
MC/DC0%0/3
defined $max and $max =~ /\A\d+\z/u and $max > 0
defined $max $max =~ /\A\d+\z/u $max > 0
Truth table25%1/4
A and B and C
A= defined $maxB= $max =~ /\A\d+\z/uC= $max > 0
ABCresult
0XX0
10X0
1100
1111
14625 2 ▶ $options{zoom} = $zoom_val if defined $zoom_val;
Branch: 1 branch
BranchTrueFalseTotal
if defined $zoom_val 0 2 2
14626 2 ▶ $options{max_zoom} = $max_zoom_val if defined $max_zoom_val;
Branch: 1 branch
BranchTrueFalseTotal
if defined $max_zoom_val 0 2 2
14627 2 ▶ $options{tile_url} = $tile_url_override if defined $tile_url_override;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tile_url_override 0 2 2
14628 2 ▶ $options{heat} = 1 if $heat;
Branch: 1 branch
BranchTrueFalseTotal
if $heat 0 2 2
14629 2 ▶ $options{bounds} = $bounds_level if defined $bounds_level;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bounds_level 0 2 2
14630 2 ▶ $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} 0 2 2
Condition33%1/3
length $weight_col and $col_set{$weight_col}
!ll&&!rl&&r
200
MC/DC0%0/2
length $weight_col and $col_set{$weight_col}
length $weight_col $col_set{$weight_col}
Truth table33%1/3
A and B
A= length $weight_colB= $col_set{$weight_col}
ABresult
0X0
100
111
14631 # Colour shade: a column to fill the outlines by, and the colour to shade
14632 2 ▶ $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 2 2
Condition33%1/3
length $shade_col and $col_set{$shade_col}
!ll&&!rl&&r
200
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
14633 2 ▶ $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 2 2
Condition33%1/3
defined $shade_color and defined $options{"shade"}
!ll&&!rl&&r
200
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
14634 2 ▶ $options{lookup} = 0 if $progress || $geocode_mode eq 'cached';
Branch: 1 branch
BranchTrueFalseTotal
if $progress or $geocode_mode eq "cached" 0 2 2
Condition33%1/3
$progress or $geocode_mode eq "cached"
l!l&&r!l&&!r
002
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
14635  
14636 # Each place that could not be plotted, and each marker with more rows
14637 # than its popup lists, links to its rows in the table, as a bar drills
14638 # into its category: the table this map came from, with
14639 # the place's filters added, and back2= to return here.
14640 2 ▶ my $rows_base = ($back =~ m{\A(?:https?://[^/]+)?/(?:open\?|view/)}) ? $back
Branch: 1 branch
BranchTrueFalseTotal
$back =~ m[\A(?:https?://[^/]+)?/(?:open\?|view/)]u ? : 0 2 2
Condition50%1/2
$self->param("l") // ""
l!l
20
MC/DC0%0/1
$self->param("l") // ""
$self->param("l")
Truth table50%1/2
A
A= $self->param("l")
Aresult
11
00
14641 : $self->_spec_to_url($self->param('l') // '');
14642 2 my $here = $self->req->url->path_query;
14643 0 ▶ my $rows_url = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
14644 0 my ($filters) = @_;
14645 0 ▶ return '' if $rows_base eq '/' || !@{$filters};
Branch: 1 branch
BranchTrueFalseTotal
if $rows_base eq "/" or not @{$filters;} 0 0 0
Condition0%0/3
$rows_base eq "/" or not @{$filters;}
l!l&&r!l&&!r
000
MC/DC0%0/2
$rows_base eq "/" or not @{$filters;}
$rows_base eq "/" not @{$filters;}
Truth table0%0/3
A or not(B)
A= $rows_base eq "/"B= not @{$filters;}
ABresult
1X1
011
000
14646 0 ▶ my $sep = ($rows_base =~ /\?/) ? '&' : '?';
Branch: 1 branch
BranchTrueFalseTotal
$rows_base =~ /\?/u ? : 0 0 0
14647 return $rows_base . $sep . join('&',
14648 0 (map { 'f=' . url_escape(encode('UTF-8', $_)) } @{$filters}),
14649 'back2=' . url_escape($here),
14650 'back2_label=' . url_escape('Back to map'),
14651 );
14652 2 };
14653 2 $options{rows_url} = $rows_url;
14654  
14655 2 ▶ my $result = $self->_map_data(
Branch: 1 branch
BranchTrueFalseTotal
$by_location ? : 1 1 2
Condition50%1/2
$self->param("l") // ""
l!l
20
MC/DC0%0/1
$self->param("l") // ""
$self->param("l")
Truth table50%1/2
A
A= $self->param("l")
Aresult
11
00
14656 $records, $columns,
14657 ($by_location ? { loc => [ @loc_cols ], loc_text => $loc_text } : { lat => $lat_col, lon => $lon_col }),
14658 \%options,
14659 $self->param('l') // '',
14660 undef,
14661 );
14662  
14663 return $self->render(text => $result->{error}, status => $result->{status})
14664 2 ▶ if $result->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"error"} 2 0 2
14665  
14666 0 my ($source_url, $source_accessed) = $self->_url_attribution;
14667 0 my ($platform, $language) = $self->_resolve_template;
14668  
14669 my @unplotted = map {
14670 0 my $entry = { %{$_} };
14671 0 $entry->{url} = $rows_url->($entry->{filters});
14672 0 $entry;
14673 0 ▶ } @{ $result->{unplotted} // [] };
Condition0%0/2
$result->{"unplotted"} // []
l!l
00
MC/DC0%0/1
$result->{"unplotted"} // []
$result->{"unplotted"}
Truth table0%0/2
A
A= $result->{"unplotted"}
Aresult
11
00
14674 0 my $unplotted_rows = 0;
14675 0 $unplotted_rows += $_->{rows} for @unplotted;
14676  
14677 # This page with geocode= set to $mode, or without it for undef.
14678 0 ▶ my $here_with = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
14679 0 my ($mode) = @_;
14680 0 my $url = $self->req->url->clone;
14681 0 $url->query->remove('geocode');
14682 0 ▶ $url->query->append(geocode => $mode) if defined $mode;
Branch: 1 branch
BranchTrueFalseTotal
if defined $mode 0 0 0
14683 0 return $url->path_query;
14684 0 };
14685  
14686 # The places to look up, each signed so that /geo/lookup asks only what a
14687 # map page listed: without that, any page on the web could post a string
14688 # for this server to send to OpenStreetMap.
14689 0 ▶ my @pending = $progress ? @{ $result->{pending} // [] } : ();
Branch: 1 branch
BranchTrueFalseTotal
$progress ? : 0 0 0
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
14690 # The points whose county outline is not known yet go on the same list,
14691 # after the places, each signed with its level for /geo/boundary.
14692 0 ▶ my @bounds_pending = $progress ? @{ $result->{bounds_pending} // [] } : ();
Branch: 1 branch
BranchTrueFalseTotal
$progress ? : 0 0 0
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
14693 0 my @messages = @{ $result->{messages} };
14694 0 ▶ @messages = grep { $_->{key} ne 'warn_map_bounds_pending' } @messages if @bounds_pending;
Branch: 1 branch
BranchTrueFalseTotal
if @bounds_pending 0 0 0
14695 0 my %progress;
14696 0 ▶ if (@pending || @bounds_pending) {
Branch: 1 branch
BranchTrueFalseTotal
if (@pending or @bounds_pending) 0 0 0
Condition0%0/3
@pending or @bounds_pending
l!l&&r!l&&!r
000
MC/DC0%0/2
@pending or @bounds_pending
@pending @bounds_pending
Truth table0%0/3
A or B
A= @pendingB= @bounds_pending
ABresult
1X1
011
000
14697 my $json = to_json([
14698 0 (map { { place => $_, sig => $self->_geo_lookup_sig($_) } } @pending),
14699 0 (map { {
14700 point => $_,
14701 level => $result->{bounds_level},
14702 0 sig => $self->_geo_boundary_sig($result->{bounds_level}, $_),
14703 } } @bounds_pending),
14704 ]);
14705 0 $json =~ s{</}{<\\/}g;
14706 0 %progress = (
14707 geocode_pending => scalar(@pending) + scalar(@bounds_pending),
14708 geocode_places => scalar @pending,
14709 geocode_outlines => scalar @bounds_pending,
14710 geocode_pending_json => $json,
14711 geocode_done_url => $here_with->(undef),
14712 geocode_cached_url => $here_with->('cached'),
14713 geocode_wait_url => $here_with->('wait'),
14714 );
14715 }
14716  
14717 # After Cancel, the places left are offered again.
14718 $progress{geocode_retry_url} = $here_with->(undef)
14719 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 0 0
Condition0%0/3
$geocode_mode eq "cached" and grep {$_->{"reason"} eq "later";} @unplotted
!ll&&!rl&&r
000
MC/DC0%0/2
$geocode_mode eq "cached" and grep {$_->{"reason"} eq "later";} @unplotted
$geocode_mode eq "cached" grep {$_->{"reason"} eq "later";} @unplotted
Truth table0%0/3
A and B
A= $geocode_mode eq "cached"B= grep {$_->{"reason"} eq "later";} @unplotted
ABresult
0X0
100
111
14720  
14721 $self->render(
14722 handler => 'tt',
14723 template => "$platform/$language/map",
14724 %progress,
14725 unplotted => \@unplotted,
14726 unplotted_rows => $unplotted_rows,
14727 unplotted_url => $rows_url->($result->{unplotted_filters} // []),
14728 # Where the outlines and the markers do not pair off, each with a link
14729 # to its rows
14730 0 ▶ bounds_groups => [ map { +{ %{$_}, url => $rows_url->($_->{filters}) } } @{ $result->{bounds_groups} // [] } ],
Condition0%0/4
$result->{"bounds_groups"} // []
l!l
00
$result->{"bounds_left_filters"} // []
l!l
00
MC/DC0%0/1
$result->{"bounds_groups"} // []
$result->{"bounds_groups"}
MC/DC0%0/1
$result->{"bounds_left_filters"} // []
$result->{"bounds_left_filters"}
Truth table0%0/2
A
A= $result->{"bounds_groups"}
Aresult
11
00
Truth table0%0/2
A
A= $result->{"bounds_left_filters"}
Aresult
11
00
14731 # The rows whose place has no county outline, and this page again to
14732 # look those outlines up (as it was opened: waiting, or with progress)
14733 bounds_left_url => $rows_url->($result->{bounds_left_filters} // []),
14734 bounds_left_rows => $result->{bounds_left_rows},
14735 0 ▶ bounds_left => scalar(@{ $result->{bounds_pending} // [] }),
Branch: 4 branches
BranchTrueFalseTotal
$geocode_mode eq 'wait' ? : 0 0 0
@loc_cols > 1 ? : 0 0 0
$back2 ? : 0 0 0
$back2 ? : 0 0 0
Condition0%0/7
$result->{"bounds_pending"} // []
l!l
00
$back2 // $back
l!l&&r!l&&!r
000
$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 table0%0/2
A
A= $result->{"bounds_pending"}
Aresult
11
00
Truth table0%0/3
A // B
A= $back2B= $back
ABresult
1X1
011
000
Truth table0%0/2
A
A= $back2_lbl
Aresult
11
00
14736 bounds_retry_url => $here_with->($geocode_mode eq 'wait' ? 'wait' : undef),
14737 format => 'html',
14738 title => $result->{title},
14739 extra_head => $result->{map_head},
14740 map_body => $result->{map_body},
14741 messages => \@messages,
14742 marker_count => $result->{marker_count},
14743 bounds_drawn => $result->{bounds_drawn},
14744 bounds_heat => $result->{bounds_heat},
14745 bounds_noun => $result->{bounds_noun},
14746 bounds_as_markers => $result->{bounds_as_markers},
14747 bounds_shade => $result->{bounds_shade},
14748 bounds_shade_as => $result->{bounds_shade_as},
14749 bounds_weight => $result->{bounds_weight},
14750 row_count => $result->{row_count},
14751 source_rows => $result->{source_rows},
14752 loc_col => $result->{loc_col},
14753 loc_many => (@loc_cols > 1 ? 1 : 0),
14754 loc_text => $result->{loc_text},
14755 lat_col => $result->{lat_col},
14756 lon_col => $result->{lon_col},
14757 backend => $result->{backend},
14758 chart => $result->{chart},
14759 0 ▶ chart_json => $self->_chart_json($result->{chart}),
Condition0%0/2
$result->{"unplotted_filters"} // []
l!l
00
MC/DC0%0/1
$result->{"unplotted_filters"} // []
$result->{"unplotted_filters"}
Truth table0%0/2
A
A= $result->{"unplotted_filters"}
Aresult
11
00
14760 back_url => ($back2 // $back),
14761 back_label => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
14762 ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
14763 source_url => $source_url,
14764 source_accessed => $source_accessed,
14765 language => $language,
14766 );
14767 }
14768  
14769 # _geo_lookup_sig($self, $place) -> $hex
14770 #
14771 # What the map page signs each place it lists with, and /geo/lookup checks.
14772 # The key is the application's secret, which BI.pm makes at random for each
14773 # start unless the config names one, so a list outlives neither a restart nor
14774 # another installation.
14775 14 ▶sub _geo_lookup_sig :Protected ($self, $place) {
Subroutine _geo_lookup_sig: called CC=1 SCAR=0.0
14776 14 return hmac_sha1_sum(encode('UTF-8', "geo-lookup\0$place"), $self->app->secrets->[0]);
14777 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
14778  
14779 # _geo_boundary_sig($self, $level, $point) -> $hex
14780 #
14781 # The same for a point whose outline the map page lists. Its own prefix, so a
14782 # place's signature is never a point's.
14783 0 ▶sub _geo_boundary_sig :Protected ($self, $level, $point) {
Subroutine _geo_boundary_sig: not called CC=1 SCAR=6.9
14784 0 return hmac_sha1_sum(encode('UTF-8', "geo-boundary\0$level\0$point"), $self->app->secrets->[0]);
14785 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
14786  
14787 # ---------------------------------------------------------------------------
14788 # POST /geo/boundary point=<lat,lon>&level=county&sig=<sig>[&online=0]
14789 #
14790 # One point's outline, for the map page's progress bar: found as the map would
14791 # find it, and remembered at once, so a run that is cancelled keeps what it
14792 # found. The point must carry the signature the map page gave it, or any page
14793 # on the web could have this server send coordinates to OpenStreetMap.
14794 # online=0 asks nothing, after OpenStreetMap has failed once.
14795 #
14796 # Replies 200 JSON:
14797 # { point, status => 'found' | 'nowhere' | 'held', stored => 0|1,
14798 # online_failed => 0|1, name }
14799 # 'nowhere' is a point in no county (at sea); 'held' could not be settled now
14800 # and is asked again next time.
14801 # 400 JSON { error } without point= or sig=, or with an unknown level=;
14802 # 403 JSON { error } for a bad sig=.
14803 # ---------------------------------------------------------------------------
14804 0 ▶sub geo_boundary ($self) {
Subroutine geo_boundary: not called CC=14 SCAR=53.5
Pod undocumented
14805 0 ▶ my $point = $self->param('point') // '';
Condition0%0/2
$self->param("point") // ""
l!l
00
MC/DC0%0/1
$self->param("point") // ""
$self->param("point")
Truth table0%0/2
A
A= $self->param("point")
Aresult
11
00
14806 0 ▶ my $sig = $self->param('sig') // '';
Condition0%0/2
$self->param("sig") // ""
l!l
00
MC/DC0%0/1
$self->param("sig") // ""
$self->param("sig")
Truth table0%0/2
A
A= $self->param("sig")
Aresult
11
00
14807 0 ▶ my $level = _map_bounds_level($self->param('level') // 'county');
Condition0%0/2
$self->param("level") // "county"
l!l
00
MC/DC0%0/1
$self->param("level") // "county"
$self->param("level")
Truth table0%0/2
A
A= $self->param("level")
Aresult
11
00
14808  
14809 0 ▶ 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 0 0 0
Condition0%0/6
length $point and length $sig and defined $level
!ll&&!rl&&r
000
length $point and length $sig
!ll&&!rl&&r
000
MC/DC0%0/3
length $point and length $sig and defined $level
length $point length $sig defined $level
Truth table0%0/4
A and B and C
A= length $pointB= length $sigC= defined $level
ABCresult
0XX0
10X0
1100
1111
14810 unless length($point) && length($sig) && defined($level);
14811 0 ▶ 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)) 0 0 0
14812 unless secure_compare($sig, $self->_geo_boundary_sig($level, $point));
14813  
14814 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
14815 0 my $answer = eval { $self->_map_boundary($level, $online)->lookup_point($point) };
14816 0 ▶ return $self->render(json => { error => $self->_i18n('error_geo_boundary_point') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $answer 0 0 0
14817 unless $answer;
14818  
14819 return $self->render(json => {
14820 point => $point,
14821 status => $answer->{status},
14822 stored => ($answer->{status} eq 'held' ? 0 : 1),
14823 online_failed => (($answer->{status} eq 'held' && $answer->{asked}) ? 1 : 0),
14824 name => $answer->{name},
14825 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
14826 }
14827  
14828 # ---------------------------------------------------------------------------
14829 # POST /geo/lookup place=<place>&sig=<sig>[&online=0]
14830 #
14831 # One place, for the map page's progress bar: looked up as the map would, and
14832 # its answer saved in the shared place cache straight away, so a run that is
14833 # cancelled or interrupted keeps every place it found. The place must carry the
14834 # signature the map page gave it. online=0 keeps the lookup on this machine;
14835 # the page sends it once OpenStreetMap has failed, so that each place left does
14836 # not wait for it again.
14837 #
14838 # Replies 200 JSON:
14839 # { place, status => 'found' | 'not_found' | 'held' | 'refused',
14840 # stored => 0|1, online_failed => 0|1, messages => [ text ... ] }
14841 # 'held' is a place that could not be looked up now (OpenStreetMap did not
14842 # answer, or the geocoder is missing); it is not remembered, so the next map
14843 # asks again. stored says that the answer is in the cache: a found or
14844 # not-found place the store refused to keep is 0.
14845 # 400 JSON { error } without place= or sig=; 403 JSON { error } for a bad sig=.
14846 # ---------------------------------------------------------------------------
14847 7 ▶sub geo_lookup ($self) {
Subroutine geo_lookup: called CC=20 SCAR=32.0
Pod documented
14848 7 ▶ my $place = $self->param('place') // '';
Condition100%2/2
$self->param("place") // ""
l!l
61
MC/DC100%1/1
$self->param("place") // ""
$self->param("place")
Truth table100%2/2
A
A= $self->param("place")
Aresult
11
00
14849 7 ▶ my $sig = $self->param('sig') // '';
Condition100%2/2
$self->param("sig") // ""
l!l
52
MC/DC100%1/1
$self->param("sig") // ""
$self->param("sig")
Truth table100%2/2
A
A= $self->param("sig")
Aresult
11
00
14850  
14851 7 ▶ return $self->render(json => { error => $self->_i18n('error_geo_lookup_place') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $place and length $sig 2 5 7
Condition100%3/3
length $place and length $sig
!ll&&!rl&&r
115
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
14852 unless length($place) && length($sig);
14853 5 ▶ 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)) 2 3 5
14854 unless secure_compare($sig, $self->_geo_lookup_sig($place));
14855  
14856 3 my $cfg = $self->app->config;
14857 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
14858 3 my $models = $self->_read_models;
14859 3 my $region = _map_region($cfg);
14860  
14861 3 ▶ my $result = $geocode->resolve_values(
Branch: 1 branch
BranchTrueFalseTotal
defined $region ? : 0 3 3
14862 [ $place ],
14863 cache => Database::BI::Model::Geocode->shared_cache_from_models($models),
14864 (defined($region) ? (region => $region) : ()),
14865 max => 1,
14866 );
14867  
14868 my $status = $result->{points}{$place} ? 'found'
14869 1 ▶ : (grep { $_ eq $place } @{ $result->{unresolved} }) ? 'not_found'
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ eq $place;} @{$$result{'skipped'};}) ? : 0 0 0
14870 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
14871 : 'held';
14872  
14873 # A place another tab answered meanwhile is in the cache already.
14874 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
14875  
14876 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
14877 2 my $backend = $result->{backend};
14878 $stored = $self->_write_models(Database::BI::Model::Geocode->models_with_shared_cache(
14879 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
14880 (defined($backend) ? (backend => $backend) : ()),
14881 built => _iso8601_utc(),
14882 )) ? 1 : 0;
14883 }
14884  
14885 0 my @messages = map { $_->{text} } grep {
14886 2 $_->{key} ne 'warn_map_geocoder_unavailable_data'
14887 3 } @{ $result->{messages} };
14888  
14889 return $self->render(json => {
14890 place => $place,
14891 status => $status,
14892 stored => $stored ? 1 : 0,
14893 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
14894 messages => \@messages,
14895 });
14896 }
14897  
14898 # _map_popup($heading, \@rows, \@columns, $limit, $more_url) -> $html
14899 #
14900 # The popup for one marker: what it is, how many rows it stands for, and the
14901 # rows themselves. A value every row shares is said once, as "Column: value";
14902 # the columns that differ are a small table of at most $limit rows, in a box
14903 # that scrolls, so a place with many rows does not cover the map. The rest
14904 # are counted, with a link to them in the table when $more_url is given.
14905 # Leaflet treats a popup string as HTML, and a value out of a user's file is
14906 # not markup, so every value is escaped here.
14907 19 ▶sub _map_popup {
Subroutine _map_popup: called CC=15 SCAR=27.1
14908 19 my ($heading, $rows, $columns, $limit, $more_url) = @_;
14909  
14910 19 ▶ my @rows = grep { ref($_) eq 'HASH' } @{ ref($rows) eq 'ARRAY' ? $rows : [] };
Branch: 1 branch
BranchTrueFalseTotal
ref $rows eq 'ARRAY' ? : 18 1 19
14911 19 ▶ my @cols = grep { defined($_) && !ref($_) && length($_) } @{ ref($columns) eq 'ARRAY' ? $columns : [] };
Branch: 1 branch
BranchTrueFalseTotal
ref $columns eq 'ARRAY' ? : 18 1 19
Condition83%5/6
defined $_ && !ref($_) && length $_
!ll&&!rl&&r
2022
defined $_ and not ref $_
!ll&&!rl&&r
1122
MC/DC66%2/3
defined $_ && !ref($_) && length $_
defined $_ not ref $_ length $_
Truth table75%3/4
A and not(B) && C
A= defined $_B= not ref $_C= length $_
ABCresult
0XX0
10X0
1100
1111
14912 19 $limit = _map_limit($limit, $DEFAULT_MAP_POPUP_ROWS);
14913 19 ▶ 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) ? : 301 5 306
Condition100%3/3
defined $v and not ref $v
!ll&&!rl&&r
32301
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
14914  
14915 19 ▶ my @lines = '<strong>' . xml_escape($heading // '') . '</strong>';
Condition100%2/2
$heading // ""
l!l
181
MC/DC100%1/1
$heading // ""
$heading
Truth table100%2/2
A
A= $heading
Aresult
11
00
14916 19 ▶ push @lines, scalar(@rows) . ' rows' if @rows > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @rows > 1 12 7 19
14917  
14918 # The same in every row, or not.
14919 19 my (@shared, @differ);
14920 19 for my $col (@cols) {
14921 22 my %seen = map { $cell->($_, $col) => 1 } @rows;
14922 22 ▶ if (keys(%seen) > 1) { push @differ, $col }
Branch: 2 branches
BranchTrueFalseTotal
if (keys %seen > 1) { } 11 11 22
elsif (@rows) { } 11 0 11
14923 11 elsif (@rows) { push @shared, [ $col, $cell->($rows[0], $col) ] }
14924 }
14925 7 push @lines, map { xml_escape($_->[0]) . ': ' . xml_escape($_->[1]) }
14926 19 grep { length $_->[1] } @shared;
14927  
14928 19 my $html = join('<br>', @lines);
14929 19 ▶ return $html unless @differ;
Branch: 1 branch
BranchTrueFalseTotal
unless @differ 9 10 19
14930  
14931 # The box keeps its size and scroll inline, one style a marker, so a page
14932 # without the stylesheet still cannot be covered; the cells' spacing is
14933 # .bi-map-popup-rows in the page's stylesheet, not repeated in every cell.
14934 10 ▶ my @shown = @rows > $limit ? @rows[0 .. $limit - 1] : @rows;
Branch: 1 branch
BranchTrueFalseTotal
@rows > $limit ? : 8 2 10
14935 $html .= '<div class="bi-map-popup-rows" style="max-height:14em;overflow:auto">'
14936 11 . '<table><tr>' . join('', map { '<th>' . xml_escape($_) . '</th>' } @differ) . '</tr>'
14937 . join('', map {
14938 10 my $row = $_;
14939 67 '<tr>' . join('', map { '<td>' . xml_escape($cell->($row, $_)) . '</td>' } @differ) . '</tr>';
14940 } @shown)
14941 . '</table></div>';
14942  
14943 10 ▶ if (my $more = @rows - @shown) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $more = @rows - @shown) 8 2 10
14944 8 ▶ $html .= "<div>and $more more"
Branch: 1 branch
BranchTrueFalseTotal
defined $more_url && length $more_url ? : 1 7 8
Condition100%3/3
defined $more_url and length $more_url
!ll&&!rl&&r
161
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
14945 . ((defined($more_url) && length($more_url))
14946 ? ': <a href="' . xml_escape($more_url) . '">show all ' . scalar(@rows) . ' in the table</a>'
14947 : '')
14948 . '</div>';
14949 }
14950  
14951 10 return $html;
14952 }
14953  
14954 # _map_size_range($records, \@markers, $col) -> ($min, $max)
14955 #
14956 # The numeric range of the bubble-size column across the markers that will be
14957 # drawn, or an empty list when the column is absent or has no numeric values.
14958 7 ▶sub _map_size_range {
Subroutine _map_size_range: called CC=11 SCAR=24.1
14959 7 my ($records, $markers, $col) = @_;
14960 7 ▶ return () unless defined($col) && length($col);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col and length $col 5 2 7
Condition100%3/3
defined $col and length $col
!ll&&!rl&&r
142
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
14961  
14962 2 my ($min, $max);
14963 2 for my $marker (@$markers) {
14964 6 my $row = $records->[ $marker->{first_row} ];
14965 6 ▶ next unless defined $row;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row 1 5 6
14966 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
14967 5 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 3 2 5
14968 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
14969 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
14970 }
14971  
14972 2 return ($min, $max);
14973 }
14974  
14975 # _map_radius($value, $min, $max) -> $pixels
14976 #
14977 # A bubble radius for one marker: 6..30 px across the plotted range, and the
14978 # midpoint for a column that is constant or has no numeric value. Pixels, not
14979 # metres: a circle over the same place must not grow as the reader zooms in.
14980 11 ▶sub _map_radius {
Subroutine _map_radius: called CC=7 SCAR=19.5
14981 11 my ($value, $min, $max) = @_;
14982  
14983 11 ▶ return 10 unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 10 11
14984 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
14985  
14986 7 my $fraction = ($value - $min) / ($max - $min);
14987 7 ▶ $fraction = 0 if $fraction < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $fraction < 0 1 6 7
14988 7 ▶ $fraction = 1 if $fraction > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $fraction > 1 1 6 7
14989  
14990 7 return int(6 + $fraction * 24 + 0.5);
14991 }
14992  
14993 # _map_limit($value, $default) -> $integer
14994 #
14995 # A positive integer from a config value or request parameter, or the default.
14996 # An absent, empty or nonsensical map setting is an operator's typo, not a data
14997 # error, so the page falls back instead of refusing.
14998 64 ▶sub _map_limit {
Subroutine _map_limit: called CC=4 SCAR=13.9
14999 64 my ($value, $default) = @_;
15000  
15001 64 ▶ 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 54 10 64
Condition100%6/6
defined $value and $value =~ /\A\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u and $value > 0
!ll&&!rl&&r
52210
defined $value and $value =~ /\A\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/u
!ll&&!rl&&r
421012
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
15002  
15003 10 return $value + 0;
15004 }
15005  
15006 # _parse_color($str) -> $color_or_undef
15007 #
15008 # Accepts a lowercase CSS named color from a fixed whitelist, or a hex color
15009 # string in #rgb or #rrggbb form. Returns the normalised lowercase string or
15010 # undef when the input is invalid.
15011 72 ▶sub _parse_color {
Subroutine _parse_color: called CC=6 SCAR=17.9
15012 72 my ($c) = @_;
15013 72 ▶ return undef unless defined($c) && length($c);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $c and length $c 52 20 72
Condition100%3/3
defined $c and length $c
!ll&&!rl&&r
15120
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
15014 20 $c = lc $c;
15015 20 ▶ return $c if $NAMED_COLORS{$c};
Branch: 1 branch
BranchTrueFalseTotal
if $NAMED_COLORS{$c} 3 17 20
15016 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
15017 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
15018 14 return undef;
15019 }
15020  
15021 # _parse_color_rules(\@raw_rules, $default_raw) -> (\@rules, $default_color)
15022 #
15023 # Parses the ?color_rule=op:threshold:color repeatable param list and the
15024 # optional ?color_default=color param into a structured rules array and a
15025 # fallback colour. Invalid rule entries are silently dropped.
15026 5 ▶sub _parse_color_rules {
Subroutine _parse_color_rules: called CC=10 SCAR=23.1
15027 5 my ($raw_rules, $default_raw) = @_;
15028 5 ▶ my $default_color = _parse_color($default_raw // '') // $DEFAULT_MARKER_COLOR;
Condition80%4/5
_parse_color($default_raw // "") // $DEFAULT_MARKER_COLOR
l!l&&r!l&&!r
140
$default_raw // ""
l!l
41
MC/DC0%0/2
_parse_color($default_raw // "") // $DEFAULT_MARKER_COLOR
_parse_color($default_raw // "") $DEFAULT_MARKER_COLOR
MC/DC100%1/1
$default_raw // ""
$default_raw
Truth table66%2/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
15029 5 my @rules;
15030 5 ▶ for my $raw (@{ $raw_rules // [] }) {
Condition100%2/2
$raw_rules // []
l!l
41
MC/DC100%1/1
$raw_rules // []
$raw_rules
Truth table100%2/2
A
A= $raw_rules
Aresult
11
00
15031 7 my ($op, $val, $color_str) = split /:/, $raw, 3;
15032 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
15033 5 $op = lc $op;
15034 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
15035 4 my $color = _parse_color($color_str);
15036 4 ▶ next unless defined $color;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $color 2 2 4
15037 2 push @rules, { op => $op, val => $val, color => $color };
15038 }
15039 5 return (\@rules, $default_color);
15040 }
15041  
15042 # _map_colour_entries($color_col, \@rules, $default, $is_series) -> @entries
15043 #
15044 # The colour key of a map, as { color, label, group }: one entry for each rule,
15045 # and Other for the default colour. A series (series= with a scheme) is
15046 # listed by value, with no Other: its values past the palette's two cycles
15047 # take a palette colour but are not listed. group names the entry for
15048 # _color_rule_index's answer ("rule<N>", or "other"), which is how HTML::OSM
15049 # lists only the entries in view.
15050 6 ▶sub _map_colour_entries {
Subroutine _map_colour_entries: called CC=12 SCAR=25.0
15051 6 my ($color_col, $rules, $default, $is_series) = @_;
15052  
15053 6 my %op_label = (gt => '>', ge => '>=', lt => '<', le => '<=', eq => '=', ne => '!=');
15054 6 my @entries;
15055 6 ▶ $rules = [] unless ref($rules) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rules eq "ARRAY" 1 5 6
15056 6 for my $index (0 .. $#{$rules}) {
15057 7 my $rule = $rules->[$index];
15058 7 ▶ next unless ref($rule) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rule eq "HASH" 2 5 7
15059 5 ▶ my $val = $rule->{val} // '';
Condition50%1/2
$rule->{"val"} // ""
l!l
50
MC/DC0%0/1
$rule->{"val"} // ""
$rule->{"val"}
Truth table50%1/2
A
A= $rule->{"val"}
Aresult
11
00
15060 push @entries, {
15061 color => $rule->{color},
15062 label => $is_series
15063 ? (length($val) ? $val : '(blank)')
15064 5 ▶ : "$color_col " . ($op_label{ $rule->{op} // '' } // $rule->{op} // '') . " $val",
Branch: 2 branches
BranchTrueFalseTotal
$is_series ? : 2 3 5
length $val ? : 1 1 2
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
15065 group => "rule$index",
15066 };
15067 }
15068 6 ▶ push @entries, { color => $default, label => 'Other', group => 'other' }
Branch: 1 branch
BranchTrueFalseTotal
if @entries and not $is_series 2 4 6
Condition100%3/3
@entries and not $is_series
!ll&&!rl&&r
312
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
15069 if @entries && !$is_series;
15070 6 return @entries;
15071 }
15072  
15073 # _map_key($self, $color_col, \@rules, $default, $is_series, $size_col, \@range)
15074 # -> (legend => \@entries, legend_title => $title, legend_empty => $text)
15075 #
15076 # What HTML::OSM is given to draw a map's key: the colour entries, each with
15077 # its group so the key lists only what is in view, then two or three bubble
15078 # sizes when a size column is set (those are always listed: they say what a
15079 # size means, wherever the reader is). The title is the colour column, or
15080 # the size column when there is no colour; with both, each size is labelled
15081 # with its column. The colours go to HTML::OSM as hex, which is all it takes.
15082 9 ▶sub _map_key :Protected ($self, $color_col, $rules, $default, $is_series, $size_col, $range) {
Subroutine _map_key: called CC=12 SCAR=24.9
15083 my @legend = map {
15084 9 { label => $_->{label}, colour => _color_hex($_->{color}), group => $_->{group} }
15085 2 ▶ } (length($color_col) ? _map_colour_entries($color_col, $rules, $default, $is_series) : ());
Branch: 1 branch
BranchTrueFalseTotal
length $color_col ? : 2 7 9
15086  
15087 9 ▶ my ($min, $max) = @{ $range // [] };
Condition100%2/2
$range // []
l!l
81
MC/DC100%1/1
$range // []
$range
Truth table100%2/2
A
A= $range
Aresult
11
00
15088 9 ▶ if (length($size_col) && defined($min)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $size_col and defined $min) 2 7 9
Condition100%3/3
length $size_col and defined $min
!ll&&!rl&&r
612
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
15089 2 ▶ my @values = ($max > $min) ? ($min, ($min + $max) / 2, $max) : ($min);
Branch: 1 branch
BranchTrueFalseTotal
$max > $min ? : 1 1 2
15090 2 for my $value (@values) {
15091 4 my $text = 0 + sprintf('%.4g', $value);
15092 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
15093 label => (@legend && length($color_col) ? "$size_col $text" : "$text"),
15094 colour => (length($color_col) ? $MAP_SIZE_KEY_COLOR : _color_hex($default)),
15095 radius => _map_radius($value, $min, $max),
15096 };
15097 }
15098 }
15099  
15100 9 ▶ return () unless @legend;
Branch: 1 branch
BranchTrueFalseTotal
unless @legend 6 3 9
15101 return (
15102 3 ▶ legend => \@legend,
Branch: 1 branch
BranchTrueFalseTotal
length $color_col ? : 1 2 3
15103 legend_title => (length($color_col) ? $color_col : $size_col),
15104 legend_empty => $self->_i18n('map_legend_empty'),
15105 );
15106 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15107  
15108 # _color_rule_index($value, \@rules) -> $index | undef
15109 #
15110 # The index of the first rule that matches $value, or undef when none does
15111 # (the marker takes the default colour). _apply_color_rule says the colour.
15112 24 ▶sub _color_rule_index {
Subroutine _color_rule_index: called CC=24 SCAR=31.9
15113 24 my ($value, $rules) = @_;
15114 24 ▶ $value //= '';
Condition100%2/2
$value //= ""
l!l
222
MC/DC100%1/1
$value //= ""
$value
Truth table100%2/2
A
A= $value
Aresult
11
00
15115 24 ▶ $rules = [] unless ref($rules) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rules eq "ARRAY" 2 22 24
15116 24 for my $index (0 .. $#{$rules}) {
15117 29 ▶ next unless ref($rules->[$index]) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rules->[$index] eq "HASH" 3 26 29
15118 26 my ($op, $threshold) = @{ $rules->[$index] }{qw(op val)};
15119 26 ▶ $op //= '';
Condition100%2/2
$op //= ""
l!l
251
MC/DC100%1/1
$op //= ""
$op
Truth table100%2/2
A
A= $op
Aresult
11
00
15120 26 ▶ $threshold //= '';
Condition50%1/2
$threshold //= ""
l!l
260
MC/DC0%0/1
$threshold //= ""
$threshold
Truth table50%1/2
A
A= $threshold
Aresult
11
00
15121 26 my $match;
15122 26 ▶ 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 10 26
Condition100%3/3
$value =~ /\A-?\d+(?:\.\d+)?\z/u and $threshold =~ /\A-?\d+(?:\.\d+)?\z/u
!ll&&!rl&&r
8216
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
15123 $threshold =~ /\A-?\d+(?:\.\d+)?\z/) {
15124 16 my ($num_val, $num_thr) = ($value + 0, $threshold + 0);
15125 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
15126 || ($op eq 'ge' && $num_val >= $num_thr)
15127 || ($op eq 'lt' && $num_val < $num_thr)
15128 || ($op eq 'le' && $num_val <= $num_thr)
15129 || ($op eq 'eq' && $num_val == $num_thr)
15130 || ($op eq 'ne' && $num_val != $num_thr);
15131 } else {
15132 10 ▶ $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
316
$op eq "eq" and lc $value eq lc $threshold
!ll&&!rl&&r
523
$op eq "ne" and lc $value ne lc $threshold
!ll&&!rl&&r
601
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
15133 || ($op eq 'ne' && lc($value) ne lc($threshold));
15134 }
15135 26 ▶ return $index if $match;
Branch: 1 branch
BranchTrueFalseTotal
if $match 15 11 26
15136 }
15137 9 return undef;
15138 }
15139  
15140 # _apply_color_rule($value, \@rules, $default_color) -> $color
15141 #
15142 # Returns the first colour whose rule matches $value, or $default_color.
15143 # Numeric comparisons are used when both sides look like plain numbers.
15144 13 ▶sub _apply_color_rule {
Subroutine _apply_color_rule: called CC=2 SCAR=6.9
15145 13 my ($value, $rules, $default) = @_;
15146 13 my $index = _color_rule_index($value, $rules);
15147 13 ▶ return defined($index) ? $rules->[$index]{color} : $default;
Branch: 1 branch
BranchTrueFalseTotal
defined $index ? : 9 4 13
15148 }
15149  
15150 # _marker_icon($color) -> $data_uri
15151 #
15152 # Returns a data:image/svg+xml URI for a 32x32 teardrop pin icon whose fill is
15153 # $color. The icon anchor is [16,32] (HTML::OSM's hardcoded default), so the
15154 # path tip lands at the bottom centre of the bounding box.
15155 2 ▶sub _marker_icon {
Subroutine _marker_icon: called CC=2 SCAR=6.9
15156 2 my ($color) = @_;
15157 2 ▶ $color //= $DEFAULT_MARKER_COLOR;
Condition66%2/3
$color //= $DEFAULT_MARKER_COLOR
l!l&&r!l&&!r
110
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
15158  
15159 # Commas in path data avoid spaces that would need percent-encoding.
15160 2 my $svg =
15161 "<svg xmlns='http://www.w3.org/2000/svg' width='32' height='32' viewBox='0 0 32 32'>" .
15162 "<path d='M16,0C10,0,5,5,5,12C5,21,16,32,16,32C16,32,27,21,27,12C27,5,22,0,16,0Z'" .
15163 " fill='$color' stroke='#444' stroke-width='1.5'/>" .
15164 "<circle cx='16' cy='12' r='5' fill='white' opacity='0.65'/>" .
15165 "</svg>";
15166  
15167 # Minimal percent-encoding for a data: URI (RFC 2397).
15168 2 $svg =~ s/#/%23/g;
15169 2 $svg =~ s/</%3C/g;
15170 2 $svg =~ s/>/%3E/g;
15171 2 $svg =~ s/ /%20/g;
15172  
15173 2 return "data:image/svg+xml,$svg";
15174 }
15175  
15176 # _color_hex($color) -> $hex
15177 #
15178 # add_circle_marker() accepts hex colours only, while _parse_color() also
15179 # allows a fixed set of CSS names for the icon path. Translate the names so a
15180 # colour rule means the same thing on a bubble map as on a pin map.
15181 11 ▶sub _color_hex {
Subroutine _color_hex: called CC=5 SCAR=16.1
15182 11 my ($color) = @_;
15183  
15184 11 ▶ return $DEFAULT_MARKER_COLOR unless defined($color) && length($color);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $color and length $color 2 9 11
Condition100%3/3
defined $color and length $color
!ll&&!rl&&r
119
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
15185 9 ▶ 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 6 3 9
15186  
15187 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
15188 }
15189  
15190 # _iso8601_utc() -> $string
15191 #
15192 # When a geocode cache was built, in the form the model store records.
15193 4 ▶sub _iso8601_utc {
Subroutine _iso8601_utc: called CC=1 SCAR=0.0
15194 4 return Database::BI::Util::iso8601_utc();
15195 }
15196  
15197 # _catalog_entry($self, $mf, $analyses) -> \%entry
15198 #
15199 # Build one catalog entry for a Mojo::File data file.
15200 200 ▶sub _catalog_entry :Protected ($self, $mf, $analyses) {
Subroutine _catalog_entry: called CC=14 SCAR=27.2
15201 200 my $path = $mf->to_string;
15202 200 my $name = $mf->basename;
15203 200 ▶ my $size = -s $path // 0;
Condition50%1/2
-s $path // 0
l!l
2000
MC/DC0%0/1
-s $path // 0
-s $path
Truth table50%1/2
A
A= -s $path
Aresult
11
00
15204 200 ▶ my $mtime = (stat($path))[9] // 0;
Condition50%1/2
(stat $path)[9] // 0
l!l
2000
MC/DC0%0/1
(stat $path)[9] // 0
(stat $path)[9]
Truth table50%1/2
A
A= (stat $path)[9]
Aresult
11
00
15205  
15206 200 require POSIX;
15207 200 ▶ my $mtime_str = $mtime ? Database::BI::Util::minute_stamp(gmtime($mtime)) . ' UTC' : '';
Branch: 1 branch
BranchTrueFalseTotal
$mtime ? : 200 0 200
15208  
15209 # Find which analyses reference this file.
15210 # Normalize path separators so that Windows paths stored with backslashes
15211 # match Mojo::File paths that may use forward slashes, and vice versa.
15212 # Case-fold only the path portion on case-insensitive filesystems.
15213 200 my $use_ci = File::Spec->case_tolerant;
15214 200 (my $norm_path = $path) =~ s{\\}{/}g;
15215 200 ▶ $norm_path = lc $norm_path if $use_ci;
Branch: 1 branch
BranchTrueFalseTotal
if $use_ci 0 200 200
15216  
15217 200 my @refs;
15218 200 for my $aid (sort keys %$analyses) {
15219 145 my $a = $analyses->{$aid};
15220 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
15221 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
15222 112 my $table_stem = $mf->basename; $table_stem =~ s/\.[^.]+\z//;
15223 112 (my $norm_spec = $spec) =~ s{\\}{/}g;
15224 112 ▶ $norm_spec = lc $norm_spec if $use_ci;
Branch: 1 branch
BranchTrueFalseTotal
if $use_ci 0 112 112
15225 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
15226 11 push @refs, { id => $aid, name => $a->{name} };
15227 11 last;
15228 }
15229 }
15230 }
15231  
15232 # Derive a human-readable type from the extension.
15233 200 my ($ext) = ($name =~ /\.([^.]+)\z/);
15234 200 ▶ $ext = lc($ext // '');
Condition50%1/2
$ext // ""
l!l
2000
MC/DC0%0/1
$ext // ""
$ext
Truth table50%1/2
A
A= $ext
Aresult
11
00
15235 200 my %type_map = (
15236 csv => 'CSV file', tsv => 'TSV file', psv => 'PSV file',
15237 xml => 'XML file', xlsx => 'XLSX spreadsheet',
15238 sql => 'SQLite database', sqlite => 'SQLite database',
15239 sqlite3 => 'SQLite database', db => 'Berkeley DB / SQLite',
15240 );
15241 200 ▶ my $type = $type_map{$ext} // 'Data file';
Condition50%1/2
$type_map{$ext} // "Data file"
l!l
2000
MC/DC0%0/1
$type_map{$ext} // "Data file"
$type_map{$ext}
Truth table50%1/2
A
A= $type_map{$ext}
Aresult
11
00
15242  
15243 return {
15244 200 name => $name,
15245 path => $path,
15246 type => $type,
15247 size => $size,
15248 mtime_str => $mtime_str,
15249 analysis_count => scalar @refs,
15250 analyses => \@refs,
15251 };
15252 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15253  
15254 # GET /catalog
15255 18 ▶sub catalog_view ($self) {
Subroutine catalog_view: called CC=5 SCAR=16.4
Pod documented
15256 18 ▶ return if $self->buffer_is_cached;
Branch: 1 branch
BranchTrueFalseTotal
if $self->buffer_is_cached 0 18 18
15257 18 my $dir = _data_dir_for($self->app);
15258 18 my $analyses = $self->_read_analyses;
15259  
15260 18 my @entries;
15261 18 ▶ if (-d $dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $dir) 18 0 18
15262 18 my $ext_re = $EXT_RE;
15263 18 for my $mf ($dir->list->each) {
15264 198 ▶ next unless $mf->to_string =~ $ext_re;
Branch: 1 branch
BranchTrueFalseTotal
unless $mf->to_string =~ /$ext_re/u 0 198 198
15265 198 push @entries, $self->_catalog_entry($mf, $analyses);
15266 }
15267 }
15268  
15269 18 my ($platform, $language) = $self->_resolve_template;
15270 18 $self->render(
15271 handler => 'tt',
15272 template => "$platform/$language/catalog",
15273 format => 'html',
15274 title => 'Dataset catalog',
15275 catalog_entries => \@entries,
15276 language => $language,
15277 );
15278 }
15279  
15280 =head2 canvases_view
15281  
15282 C<GET /canvases> -- The saved canvases, as cards that open, select and delete,
15283 with Import canvas. The main navigation's Canvases link. The list is the one
15284 the home page shows (C<layouts/canvas_list.html.tt>); here it also says when
15285 there are none, and how to make one.
15286  
15287 =head3 API SPECIFICATION
15288  
15289 =head4 INPUT
15290  
15291 None.
15292  
15293 =head4 OUTPUT
15294  
15295 C<200> with the HTML page. The cards are drawn by the page from
15296 C<GET /api/analyses>.
15297  
15298 =cut
15299  
15300 2 ▶sub canvases_view ($self) {
Subroutine canvases_view: called CC=1 SCAR=0.0
Pod documented
15301 2 my ($platform, $language) = $self->_resolve_template;
15302 2 $self->render(
15303 handler => 'tt',
15304 template => "$platform/$language/canvases",
15305 format => 'html',
15306 title => 'Canvases',
15307 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.',
15308 language => $language,
15309 );
15310 }
15311  
15312 # _share_secret($self) -> $secret_string
15313 #
15314 # The key share and embed tokens are signed with: config share_secret, else
15315 # one derived from the application's first secret. It used to fall back to a
15316 # fixed string, the same on every install, so anyone could sign a token for
15317 # any canvas, with any expiry, and read it without the password. The first
15318 # secret is random for each start unless config secrets sets it, so without
15319 # either a restart ends every link (_share_links_last says which). It is
15320 # derived, not the secret itself, so a token is never a signature that the
15321 # session cookie or a map list would also accept.
15322 59 ▶sub _share_secret :Protected ($self) {
Subroutine _share_secret: called CC=4 SCAR=13.9
15323 59 ▶ my $s = $self->app->config('share_secret') // '';
Condition100%2/2
$self->app->config("share_secret") // ""
l!l
1247
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
15324 59 ▶ return $s if !ref($s) && length $s;
Branch: 1 branch
BranchTrueFalseTotal
if not ref $s and length $s 11 48 59
Condition100%3/3
not ref $s and length $s
!ll&&!rl&&r
14711
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
15325 48 require Digest::SHA;
15326 48 return Digest::SHA::hmac_sha256_hex('Database::BI share tokens', $self->app->secrets->[0]);
15327 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15328  
15329 # _share_links_last($self) -> 1 | 0
15330 #
15331 # Whether a share link outlives a restart: true when share_secret or secrets
15332 # is configured, so the key is the same next time.
15333 1 ▶sub _share_links_last :Protected ($self) {
Subroutine _share_links_last: called CC=6 SCAR=25.9
15334 1 ▶ my $s = $self->app->config('share_secret') // '';
Condition50%1/2
$self->app->config("share_secret") // ""
l!l
10
MC/DC0%0/1
$self->app->config("share_secret") // ""
$self->app->config("share_secret")
Truth table50%1/2
A
A= $self->app->config("share_secret")
Aresult
11
00
15335 1 my $secrets = $self->app->config('secrets');
15336 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;} ? : 1 0 1
Condition22%2/9
not ref $s and length $s or ref $secrets eq "ARRAY" and @{$secrets;}
l!l&&r!l&&!r
100
not ref $s and length $s
!ll&&!rl&&r
001
ref $secrets eq "ARRAY" and @{$secrets;}
!ll&&!rl&&r
000
MC/DC0%0/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 table14%1/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
15337 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15338  
15339 # _make_share_token($self, $id, $expires) -> $token_string
15340 #
15341 # Signs with HMAC-SHA256 using Digest::SHA (Perl core since 5.10).
15342 18 ▶sub _make_share_token :Protected ($self, $id, $expires) {
Subroutine _make_share_token: called CC=1 SCAR=0.0
15343 18 require Digest::SHA;
15344 18 require MIME::Base64;
15345 18 my $secret = $self->_share_secret;
15346 18 my $payload = "$id|$expires";
15347 18 my $hmac = Digest::SHA::hmac_sha256_hex($payload, $secret);
15348 18 return MIME::Base64::encode_base64url("$payload|$hmac");
15349 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15350  
15351 # _verify_share_token($self, $id, $token) -> 1 | undef
15352 50 ▶sub _verify_share_token :Protected ($self, $id, $token) {
Subroutine _verify_share_token: called CC=13 SCAR=25.7
15353 50 ▶ return undef unless defined $token && length $token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $token and length $token 2 48 50
Condition100%3/3
defined $token and length $token
!ll&&!rl&&r
1148
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
15354 48 require MIME::Base64;
15355 48 my $decoded = eval { MIME::Base64::decode_base64url($token) };
15356 48 ▶ return undef unless defined $decoded;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $decoded 0 48 48
15357 48 my ($tid, $expires, $hmac) = split /\|/, $decoded, 3;
15358 48 ▶ return undef unless defined $tid && defined $expires && defined $hmac;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tid and defined $expires and defined $hmac 6 42 48
Condition83%5/6
defined $tid and defined $expires and defined $hmac
!ll&&!rl&&r
6042
defined $tid and defined $expires
!ll&&!rl&&r
2442
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
15359 42 ▶ return undef unless $tid eq $id;
Branch: 1 branch
BranchTrueFalseTotal
unless $tid eq $id 3 39 42
15360 39 ▶ return undef unless $expires =~ /\A\d+\z/ && $expires > time();
Branch: 1 branch
BranchTrueFalseTotal
unless $expires =~ /\A\d+\z/u and $expires > time 2 37 39
Condition100%3/3
$expires =~ /\A\d+\z/u and $expires > time
!ll&&!rl&&r
1137
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
15361 37 require Digest::SHA;
15362 37 my $secret = $self->_share_secret;
15363 37 my $expected = Digest::SHA::hmac_sha256_hex("$id|$expires", $secret);
15364 37 ▶ return undef unless length($hmac) == length($expected);
Branch: 1 branch
BranchTrueFalseTotal
unless length $hmac == length $expected 1 36 37
15365 # Every character is compared, so the time taken says nothing about how
15366 # much of a guessed signature was right.
15367 36 my $diff = 0;
15368 36 $diff |= ord(substr($hmac, $_, 1)) ^ ord(substr($expected, $_, 1)) for 0 .. length($expected) - 1;
15369 36 ▶ return undef if $diff;
Branch: 1 branch
BranchTrueFalseTotal
if $diff 3 33 36
15370 33 return 1;
15371 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
15372  
15373 # POST /api/analyses/:id/share
15374 4 ▶sub analyses_share ($self) {
Subroutine analyses_share: called CC=5 SCAR=16.2
Pod documented
15375 4 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
40
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
15376 4 ▶ 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 2 2 4
15377 unless $id =~ /\A[A-Za-z0-9]+\z/;
15378  
15379 2 my $analyses = $self->_read_analyses;
15380 return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
15381 2 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 1 1 2
15382  
15383 1 my $expires = time() + $SHARE_TOKEN_TTL;
15384 1 my $token = $self->_make_share_token($id, $expires);
15385 1 my $url = $self->req->url->base->to_string . "/share/$id?token=" . url_escape($token);
15386  
15387 1 ▶ $self->render(json => {
Branch: 1 branch
BranchTrueFalseTotal
$self->_share_links_last ? : 1 0 1
15388 token => $token, url => $url, expires => $expires,
15389 lasts_restart => $self->_share_links_last ? Mojo::JSON::true() : Mojo::JSON::false(),
15390 });
15391 }
15392  
15393 # GET /share/:id?token=...
15394 20 ▶sub share_view ($self) {
Subroutine share_view: called CC=9 SCAR=22.0
Pod documented
15395 20 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
200
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
15396 20 ▶ my $token = $self->param('token') // '';
Condition100%2/2
$self->param("token") // ""
l!l
191
MC/DC100%1/1
$self->param("token") // ""
$self->param("token")
Truth table100%2/2
A
A= $self->param("token")
Aresult
11
00
15397 20 ▶ 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 19 20
15398 unless $id =~ /\A[A-Za-z0-9]+\z/;
15399 19 ▶ return $self->render(text => _message_text('error_token_missing'), status => 401)
Branch: 1 branch
BranchTrueFalseTotal
unless length $token 1 18 19
15400 unless length $token;
15401 18 ▶ unless ($self->_verify_share_token($id, $token)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_verify_share_token($id, $token)) 2 16 18
15402 2 return $self->render(text => _message_text('error_token_invalid'), status => 403);
15403 }
15404  
15405 16 my $analyses = $self->_read_analyses;
15406 return $self->render(text => sprintf(_message_text('error_analysis_not_found'), $id), status => 404)
15407 16 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 2 14 16
15408 14 my $a = $analyses->{$id};
15409  
15410 14 ▶ my @visuals = @{ $a->{visuals} // [] };
Condition100%2/2
$a->{"visuals"} // []
l!l
86
MC/DC100%1/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
15411 14 ▶ unless (@visuals) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@visuals) 6 8 14
15412 6 return $self->render(text => 'This shared analysis has no visuals', status => 404);
15413 }
15414  
15415 # Reuse canvas_render logic by temporarily setting id in stash and
15416 # forwarding; set sharing_mode so the template hides admin controls.
15417 8 $self->stash(sharing_mode => 1);
15418 # Delegate to canvas_render which reads stash('id').
15419 8 return $self->canvas_render;
15420 }
15421  
15422 # GET /embed/:id?token=...
15423 20 ▶sub embed_view ($self) {
Subroutine embed_view: called CC=20 SCAR=30.8
Pod documented
15424 20 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
200
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
15425 20 ▶ my $token = $self->param('token') // '';
Condition100%2/2
$self->param("token") // ""
l!l
191
MC/DC100%1/1
$self->param("token") // ""
$self->param("token")
Truth table100%2/2
A
A= $self->param("token")
Aresult
11
00
15426 20 ▶ 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 19 20
15427 unless $id =~ /\A[A-Za-z0-9]+\z/;
15428 19 ▶ return $self->render(text => _message_text('error_token_missing'), status => 401)
Branch: 1 branch
BranchTrueFalseTotal
unless length $token 1 18 19
15429 unless length $token;
15430 18 ▶ unless ($self->_verify_share_token($id, $token)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_verify_share_token($id, $token)) 2 16 18
15431 2 return $self->render(text => _message_text('error_token_invalid'), status => 403);
15432 }
15433  
15434 16 my $analyses = $self->_read_analyses;
15435 return $self->render(text => sprintf(_message_text('error_analysis_not_found'), $id), status => 404)
15436 16 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 2 14 16
15437 14 my $a = $analyses->{$id};
15438  
15439 # Every HTML page gets this from the after_dispatch hook in Database::BI;
15440 # the page made to be framed says it itself, so it never depends on that.
15441 # The sites embed_frame_ancestors names are allowed by frame-ancestors,
15442 # which the browsers that know it follow in place of this header; those
15443 # that know only this header refuse them, which is the safe way to fail.
15444 14 $self->res->headers->header('X-Frame-Options' => 'SAMEORIGIN');
15445 14 my @framers = Database::BI::_embed_frame_ancestors($self->app->config);
15446 14 ▶ $self->stash(csp_frame_ancestors => \@framers) if @framers;
Branch: 1 branch
BranchTrueFalseTotal
if @framers 0 14 14
15447  
15448 14 ▶ my @visuals = @{ $a->{visuals} // [] };
Condition100%2/2
$a->{"visuals"} // []
l!l
86
MC/DC100%1/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
15449 14 ▶ unless (@visuals) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@visuals) 6 8 14
15450 6 return $self->render(text => 'This shared analysis has no visuals', status => 404);
15451 }
15452  
15453 # Drawn as on the canvas page, each card through its own failure: one card that
15454 # cannot be drawn says so, and leaves the others.
15455 8 my $ctx = $self->_canvas_render_context($a, $self->req->url->query->to_string);
15456 return $self->render(text => $ctx->{error}, status => $ctx->{status})
15457 8 ▶ if $ctx->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"error"} 0 8 8
15458  
15459 8 my (@rendered, $head);
15460 8 for my $i (0 .. $#visuals) {
15461 8 my $vis = $visuals[$i];
15462 8 ▶ 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
80
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
15463 $self->_render_visual_html(
15464 $vis, $ctx->{records}, $ctx->{columns}, $ctx->{src}, $i, $ctx->{spec_key}, 0, $ctx->{cross_row},
15465 8 );
15466 } // { error => _tidy_error($@) };
15467 8 ▶ $head //= $card->{head} if length($card->{head} // '');
Branch: 1 branch
BranchTrueFalseTotal
if length($card->{"head"} // "") 0 8 8
Condition20%1/5
$card->{"head"} // ""
l!l
08
$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
15468 push @rendered, {
15469 id => $i,
15470 title => ($vis->{title} // $card->{title} // ''),
15471 html => $card->{html},
15472 error => $card->{error},
15473 8 ▶ kind => ($vis->{kind} // ''),
Condition85%6/7
($vis->{"title"} // $card->{"title"}) // ""
l!l
35
$vis->{"title"} // $card->{"title"}
l!l&&r!l&&!r
035
$vis->{"kind"} // ""
l!l
62
MC/DC50%1/2
($vis->{"title"} // $card->{"title"}) // ""
$vis->{"title"} $card->{"title"}
MC/DC100%1/1
$vis->{"kind"} // ""
$vis->{"kind"}
Truth table66%2/3
A // B
A= $vis->{"title"}B= $card->{"title"}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $vis->{"kind"}
Aresult
11
00
15474 plain => _text_card_plain($vis),
15475 };
15476 }
15477  
15478 8 $self->stash(embed_mode => 1, sharing_mode => 1);
15479 8 my ($platform, $language) = $self->_resolve_template;
15480 $self->render(
15481 handler => 'tt',
15482 template => "$platform/$language/embed",
15483 format => 'html',
15484 title => $a->{name},
15485 canvas_id => $id,
15486 canvas_name => $a->{name},
15487 8 ▶ visuals => \@rendered,
Condition50%1/2
$head // ""
l!l
08
MC/DC0%0/1
$head // ""
$head
Truth table50%1/2
A
A= $head
Aresult
11
00
15488 card_head => ($head // ''),
15489 language => $language,
15490 );
15491 }
15492  
15493 # GET /a/:id/visual/:n/:format
15494 24 ▶sub visual_download ($self) {
Subroutine visual_download: called CC=16 SCAR=28.1
Pod documented
15495 24 ▶ my $id = $self->stash('id') // '';
Condition50%1/2
$self->stash("id") // ""
l!l
240
MC/DC0%0/1
$self->stash("id") // ""
$self->stash("id")
Truth table50%1/2
A
A= $self->stash("id")
Aresult
11
00
15496 24 ▶ my $n = $self->stash('n') // 0;
Condition50%1/2
$self->stash("n") // 0
l!l
240
MC/DC0%0/1
$self->stash("n") // 0
$self->stash("n")
Truth table50%1/2
A
A= $self->stash("n")
Aresult
11
00
15497 24 ▶ my $format = $self->stash('fmt') // '';
Condition50%1/2
$self->stash("fmt") // ""
l!l
240
MC/DC0%0/1
$self->stash("fmt") // ""
$self->stash("fmt")
Truth table50%1/2
A
A= $self->stash("fmt")
Aresult
11
00
15498  
15499 24 ▶ 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 23 24
15500 unless $id =~ /\A[A-Za-z0-9]+\z/;
15501 23 ▶ return $self->render(text => 'Format must be csv or png', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $format =~ /\A(?:csv|png)\z/u 1 22 23
15502 unless $format =~ /\A(?:csv|png)\z/;
15503 22 ▶ return $self->render(text => 'Visual index must be a non-negative integer', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless $n =~ /\A\d+\z/u 2 20 22
15504 unless $n =~ /\A\d+\z/;
15505  
15506 20 my $analyses = $self->_read_analyses;
15507 return $self->render(text => sprintf(_message_text('error_analysis_not_found'), $id), status => 404)
15508 20 ▶ unless exists $analyses->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $analyses->{$id} 3 17 20
15509 17 my $a = $analyses->{$id};
15510  
15511 17 ▶ my @visuals = @{ $a->{visuals} // [] };
Condition100%2/2
$a->{"visuals"} // []
l!l
116
MC/DC100%1/1
$a->{"visuals"} // []
$a->{"visuals"}
Truth table100%2/2
A
A= $a->{"visuals"}
Aresult
11
00
15512 17 ▶ return $self->render(text => "Visual $n not found", status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless $n < scalar @visuals 7 10 17
15513 unless $n < scalar @visuals;
15514 return $self->render(text => _message_text('error_text_card_no_data'), status => 404)
15515 10 ▶ if ($visuals[$n]{kind} // '') eq 'text';
Branch: 1 branch
BranchTrueFalseTotal
if ($visuals[$n]{"kind"} // "") eq "text" 0 10 10
Condition100%2/2
$visuals[$n]{"kind"} // ""
l!l
82
MC/DC100%1/1
$visuals[$n]{"kind"} // ""
$visuals[$n]{"kind"}
Truth table100%2/2
A
A= $visuals[$n]{"kind"}
Aresult
11
00
15516  
15517 10 ▶ if ($format eq 'csv') {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "csv") 9 1 10
15518 9 $self->stash(buffer => 0);
15519 # The canvas names its own source: l= on this URL is no way to reach another.
15520 9 my $ctx = $self->_canvas_render_context($a, $self->req->url->query->to_string);
15521 return $self->render(text => $ctx->{error}, status => $ctx->{status})
15522 9 ▶ if $ctx->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"error"} 0 9 9
15523 9 my $records = $ctx->{records};
15524 9 ▶ for my $spec (@{ $visuals[$n]{filters} // [] }) {
Condition50%1/2
$visuals[$n]{"filters"} // []
l!l
09
MC/DC0%0/1
$visuals[$n]{"filters"} // []
$visuals[$n]{"filters"}
Truth table50%1/2
A
A= $visuals[$n]{"filters"}
Aresult
11
00
15525 0 $records = _apply_filter_spec($records, $spec);
15526 }
15527 $self->res->headers->content_disposition(
15528 9 "attachment; filename=\"visual-$n.csv\""
15529 );
15530 9 return $self->render(data => _serialize_csv($records, $ctx->{columns}), format => 'txt');
15531 }
15532  
15533 # PNG: not implemented in the server (canvas/SVG rendering is client-side).
15534 # Return 501 with a descriptive message.
15535 1 return $self->render(
15536 text => 'PNG download requires the browser SVG renderer; use the PNG button on the card',
15537 status => 501,
15538 );
15539 }
15540  
15541 # ask_api($self)
15542 #
15543 # POST /api/ask
15544 #
15545 # Translates a plain-English question into an analysis spec by
15546 # calling the configured AI provider. The model receives only column
15547 # names and types -- never raw row data, file paths, or spec_key.
15548 #
15549 # Body params:
15550 # l=<spec> (required) -- left table spec
15551 # q=<question> (required) -- natural language question
15552 # f=<filter> (repeatable, optional)
15553 #
15554 # Returns JSON: { spec, url, valid => 1 }
15555 # On error: { error } with 400, 503, or 502 status
15556 5 ▶sub ask_api ($self) {
Subroutine ask_api: called CC=20 SCAR=37.2
Pod documented
15557 5 ▶ my $api_key = $self->app->config('ai_api_key') // '';
Condition100%2/2
$self->app->config("ai_api_key") // ""
l!l
23
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
15558 5 ▶ return $self->render(json => { error => _message_text('ask_unavailable') }, status => 503)
Branch: 1 branch
BranchTrueFalseTotal
unless length $api_key 3 2 5
15559 unless length $api_key;
15560  
15561 2 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
11
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
15562 2 ▶ return $self->render(json => { error => 'Missing required parameter: l' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 1 1 2
15563 unless length $left_spec;
15564  
15565 1 ▶ my $question = $self->param('q') // '';
Condition50%1/2
$self->param("q") // ""
l!l
10
MC/DC0%0/1
$self->param("q") // ""
$self->param("q")
Truth table50%1/2
A
A= $self->param("q")
Aresult
11
00
15566 1 ▶ return $self->render(json => { error => _message_text('ask_no_question') }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $question 0 1 1
15567 unless length $question;
15568 1 ▶ 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 0 1 1
15569 if length($question) > $ASK_MAX_QUESTION;
15570  
15571 1 my ($src, $records, $columns, $left_label) = $self->_run_pipeline_source;
15572 1 ▶ return $self->render(json => { error => 'Could not open data source' }, status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 0 1 1
15573 unless defined $records;
15574  
15575 1 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
15576  
15577 # Sample up to 200 rows for type inference; avoids slurping huge files.
15578 1 ▶ my @sample = @{$records}[0 .. ($#$records < 199 ? $#$records : 199)];
Branch: 1 branch
BranchTrueFalseTotal
$records->$#* < 199 ? : 1 0 1
15579  
15580 1 require Database::BI::Ask;
15581 1 my $typed_cols = Database::BI::Ask::infer_column_types(\@sample, $columns);
15582  
15583 1 ▶ my $ai_config = {
Condition50%2/4
$self->app->config("ai_provider") // "anthropic"
l!l
01
$self->app->config("ai_model") // "claude-haiku-5-5"
l!l
01
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
15584 provider => $self->app->config('ai_provider') // 'anthropic',
15585 api_key => $api_key,
15586 model => $self->app->config('ai_model') // 'claude-haiku-5-5',
15587 };
15588  
15589 1 ▶ 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) 0 1 1
15590 unless _ai_call_allowed($self);
15591  
15592 1 ▶ my $result = Database::BI::Ask::ask(
Condition33%1/3
$left_label // $left_spec
l!l&&r!l&&!r
100
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
15593 question => $question,
15594 spec_key => $left_spec,
15595 label => $left_label // $left_spec,
15596 columns => $typed_cols,
15597 ai_config => $ai_config,
15598 );
15599  
15600 1 ▶ if (my $err = $result->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $result->{"error"}) 0 1 1
15601 0 ▶ my ($status, $msg) =
Branch: 5 branches
BranchTrueFalseTotal
$err eq 'ask_unavailable' ? : 0 0 0
$err eq 'ask_no_question' ? : 0 0 0
$err eq 'ask_provider_error' ? : 0 0 0
$err eq 'ask_unparseable' ? : 0 0 0
$err =~ /\Aask_invalid_spec:(.+)\z/u ? : 0 0 0
15602 $err eq 'ask_unavailable' ? (503, _message_text('ask_unavailable'))
15603 : $err eq 'ask_no_question' ? (400, _message_text('ask_no_question'))
15604 : $err eq 'ask_provider_error' ? (502, _message_text('ask_provider_error'))
15605 : $err eq 'ask_unparseable' ? (422, _message_text('ask_unparseable'))
15606 : $err =~ /\Aask_invalid_spec:(.+)\z/ ? (422, sprintf(_message_text('ask_invalid_spec'), $1))
15607 : (500, $err);
15608 0 return $self->render(json => { error => $msg }, status => $status);
15609 }
15610  
15611 1 return $self->render(json => $result);
15612 }
15613  
15614 # summary_api($self)
15615 #
15616 # POST /api/summary
15617 #
15618 # Runs the same pipeline as insights_view, computes insights, then generates
15619 # a narrative summary via Database::BI::Summary::generate().
15620 #
15621 # Body params:
15622 # l=<spec> (required) -- left table spec
15623 # f=<filter> (repeatable, optional)
15624 # ai=1 (optional) -- request LLM polish (honoured only when ai_api_key
15625 # is set in the app config)
15626 #
15627 # Returns JSON: { text, source, cached }
15628 # On error: { error } with 400 or 404 status
15629 3 ▶sub summary_api ($self) {
Subroutine summary_api: called CC=10 SCAR=24.3
Pod documented
15630 3 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
21
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
15631 3 ▶ return $self->render(json => { error => 'Missing required parameter: l' }, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 1 2 3
15632 unless length $left_spec;
15633  
15634 2 my ($src, $records, $columns) = $self->_run_pipeline_source;
15635 2 ▶ return $self->render(json => { error => 'Could not open data source' }, status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 1 1 2
15636 unless defined $records;
15637  
15638 1 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
15639 0 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(json => { error => $e }, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 1 1
15640  
15641 1 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 0 1 1
15642  
15643 1 my $row_count = scalar @$records;
15644 1 (my $label = $left_spec) =~ s/\A(?:table:|path:|url:|mariadb:|redis:[^|]+\|)//;
15645  
15646 1 require Database::BI::Insights;
15647 1 my $insights = Database::BI::Insights::compute(
15648 records => $records,
15649 columns => $columns,
15650 spec_key => $left_spec,
15651 );
15652  
15653 1 ▶ my $use_ai = $self->param('ai') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->param('ai') ? : 0 1 1
15654 1 ▶ my $ai_config = {
Condition50%3/6
$self->app->config("ai_provider") // "anthropic"
l!l
01
$self->app->config("ai_api_key") // ""
l!l
01
$self->app->config("ai_model") // "claude-haiku-5-5"
l!l
01
MC/DC0%0/1
$self->app->config("ai_provider") // "anthropic"
$self->app->config("ai_provider")
MC/DC0%0/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 table50%1/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
15655 provider => $self->app->config('ai_provider') // 'anthropic',
15656 api_key => $self->app->config('ai_api_key') // '',
15657 model => $self->app->config('ai_model') // 'claude-haiku-5-5',
15658 };
15659  
15660 1 require Database::BI::Summary;
15661 my $result = Database::BI::Summary::generate(
15662 insights => $insights,
15663 spec_key => $left_spec,
15664 label => $label,
15665 row_count => $row_count,
15666 use_ai => $use_ai,
15667 ai_config => $ai_config,
15668 0 ▶ ai_allowed => sub { _ai_call_allowed($self) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
15669 1 );
15670  
15671 1 return $self->render(json => $result);
15672 }
15673  
15674 # _ai_calls_per_hour($c) -> $n
15675 #
15676 # Config ai_calls_per_hour, else $AI_CALLS_PER_HOUR; 0 means no limit.
15677 1 ▶sub _ai_calls_per_hour {
Subroutine _ai_calls_per_hour: called CC=3 SCAR=12.5
15678 1 my ($c) = @_;
15679 1 my $n = $c->app->config('ai_calls_per_hour');
15680 1 ▶ return defined($n) && $n =~ /\A\d+\z/ ? $n : $AI_CALLS_PER_HOUR;
Branch: 1 branch
BranchTrueFalseTotal
defined $n && $n =~ /\A\d+\z/u ? : 0 1 1
Condition33%1/3
defined $n and $n =~ /\A\d+\z/u
!ll&&!rl&&r
100
MC/DC0%0/2
defined $n and $n =~ /\A\d+\z/u
defined $n $n =~ /\A\d+\z/u
Truth table33%1/3
A and B
A= defined $nB= $n =~ /\A\d+\z/u
ABresult
0X0
100
111
15681 }
15682  
15683 # _ai_call_allowed($c) -> 1 | 0
15684 #
15685 # Takes one provider call from this process's budget: the times of the calls
15686 # in the last hour, kept per application (tests build many in one process).
15687 # Returns 0, taking nothing, when the hour's calls are used up.
15688 5 my %AI_CALLS;
15689 1 ▶sub _ai_call_allowed {
Subroutine _ai_call_allowed: called CC=4 SCAR=14.2
15690 1 my ($c) = @_;
15691 1 my $max = _ai_calls_per_hour($c);
15692 1 ▶ return 1 unless $max;
Branch: 1 branch
BranchTrueFalseTotal
unless $max 0 1 1
15693 1 my $now = time;
15694 1 ▶ my $calls = $AI_CALLS{ Scalar::Util::refaddr($c->app) } //= [];
Condition50%1/2
$AI_CALLS{builtin::refaddr($c->app)} //= []
l!l
01
MC/DC0%0/1
$AI_CALLS{builtin::refaddr($c->app)} //= []
$AI_CALLS{builtin::refaddr($c->app)}
Truth table50%1/2
A
A= $AI_CALLS{builtin::refaddr($c->app)}
Aresult
11
00
15695 0 @{$calls} = grep { $_ > $now - $AI_WINDOW_S } @{$calls};
15696 1 ▶ return 0 if @{$calls} >= $max;
Branch: 1 branch
BranchTrueFalseTotal
if @{$calls;} >= $max 0 1 1
15697 1 push @{$calls}, $now;
15698 1 return 1;
15699 }
15700  
15701 # insights_view($self)
15702 #
15703 # Accepts the same l=, j=, f=, c= pipeline as /stats. Runs the standard
15704 # pipeline (date normalisation, calc fields, filters), then delegates to
15705 # Database::BI::Insights::compute() for pure-arithmetic insight detection.
15706 #
15707 # No LLM or external service is invoked. Every returned insight carries a
15708 # view_url linking to the chart or stats page that shows the underlying data.
15709 #
15710 # Stash keys:
15711 # insights -- arrayref of insight hashrefs (kind/headline/detail/view_url/method)
15712 # left_spec -- the l= value
15713 # left_label -- human-readable data-source label
15714 # row_count -- number of rows analysed
15715 # base_url -- current request URL (passed to Insights for fallback URLs)
15716 47 ▶sub insights_view ($self) {
Subroutine insights_view: called CC=16 SCAR=30.2
Pod documented
15717 47 ▶ my $left_spec = $self->param('l') // '';
Condition100%2/2
$self->param("l") // ""
l!l
461
MC/DC100%1/1
$self->param("l") // ""
$self->param("l")
Truth table100%2/2
A
A= $self->param("l")
Aresult
11
00
15718 47 ▶ return $self->render(text => 'Missing l= parameter', status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless length $left_spec 2 45 47
15719 unless length $left_spec;
15720  
15721 45 ▶ my $back = _safe_back_url($self->param('back')) // '/';
Condition50%1/2
_safe_back_url($self->param("back")) // "/"
l!l
045
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
15722 45 my $back2 = _safe_back_url($self->param('back2'));
15723 45 ▶ my $back2_lbl = $self->param('back2_label') // '';
Condition50%1/2
$self->param("back2_label") // ""
l!l
045
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
15724  
15725 45 my ($src, $records, $columns) = $self->_run_pipeline_source;
15726 45 ▶ return $self->render(text => 'Could not open data source', status => 404)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $records 3 42 45
15727 unless defined $records;
15728  
15729 42 eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
15730 42 ▶ if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 41 42
15731  
15732 41 ▶ return unless $self->_reduce_or_render(\$records, \$columns);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_reduce_or_render(\$records, \$columns) 1 40 41
15733  
15734 40 my $row_count = scalar @$records;
15735 40 (my $left_label = $left_spec) =~ s/\A(?:table:|path:|url:|mariadb:|redis:[^|]+\|)//;
15736  
15737 40 require Database::BI::Insights;
15738 40 my $insights = Database::BI::Insights::compute(
15739 records => $records,
15740 columns => $columns,
15741 spec_key => $left_spec,
15742 base_url => $self->req->url->path_query,
15743 );
15744  
15745 40 my ($platform, $language) = $self->_resolve_template;
15746 40 ▶ $self->render(
Branch: 3 branches
BranchTrueFalseTotal
length($self->app->config('ai_api_key') // '') ? : 0 40 40
$back2 ? : 0 40 40
$back2 ? : 0 40 40
Condition27%3/11
$self->app->config("ai_api_key") // ""
l!l
040
$back2 // $back
l!l&&r!l&&!r
0400
$back2_lbl or "Back"
l!l
00
$self->param("back_label") // "Back to table"
l!l
040
$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
15747 handler => 'tt',
15748 template => "$platform/$language/insights",
15749 format => 'html',
15750 title => 'Automatic insights',
15751 insights => $insights,
15752 left_spec => $left_spec,
15753 left_label => $left_label,
15754 row_count => $row_count,
15755 ai_available => (length($self->app->config('ai_api_key') // '') ? 1 : 0),
15756 back_url => ($back2 // $back),
15757 back_label => ($back2 ? ($back2_lbl || 'Back') : ($self->param('back_label') // 'Back to table')),
15758 ($back2 ? (back2_url => $back, back2_label => ($self->param('back_label') // 'Back to table')) : ()),
15759 language => $language,
15760 );
15761 }
15762  
15763 5 1;
15764  
15765 __END__
↑ Summary blib/lib/Database/BI/Model/DataSource.pm »