blib/lib/Database/BI/Calc.pm

filter: Statementstmt 97.2% 610 / 627 Branchbran 92.9% 383 / 412 Conditioncond 87.9% 189 / 215 MC/DCmcdc 80.0% 96 / 120 Subroutinesub 100% 80 / 80 Podpod 50.0% 4 / 8 totaltotal 93.1% 1362 / 1462 CC 301 SCAR 23.9
CC
301
Cov
94%
_parse_call
40.6
__ANON__
28.1
_tokenize
18.0
CRAP 10.9
« blib/lib/Database/BI/SafeUA.pm ↑ Summary blib/lib/Database/BI/Command/password.pm »
1 package Database::BI::Calc;
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 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 5 ▶use POSIX qw(floor ceil);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use Database::BI::I18N ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use Database::BI::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 5 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 5 our $VERSION = '0.024.0';
14  
15 5 Readonly my $MAX_EXPR_LEN => 512;
16 5 Readonly my $MAX_DEPTH => 20;
17  
18 # A double holds about 15 significant digits, so round() has nothing to say past
19 # that, and the count reaches sprintf from a URL: it must not be able to ask for
20 # two thousand million of them.
21 5 Readonly my $MAX_ROUND_PLACES => 15;
22  
23 # A pattern, and what one capture may hold. A capture becomes a group key, so an
24 # unbounded one is a performance and a layout problem; Perl's regex engine has no
25 # timeout, so the length cap is the only bound a pattern itself can be given.
26 5 Readonly my $MAX_PATTERN_LEN => 200;
27 5 Readonly my $MAX_CAPTURE_LEN => 200;
28  
29 # The constructs that run code or steer the engine: (?{ }) and (??{ }) run Perl,
30 # (?p is the old preserve flag, and (* opens a backtracking verb.
31 # A paren after an even number of backslashes is a real one, after an odd number
32 # a literal.
33 5 Readonly my $REFUSED_PATTERN_RE => qr/(?:\A|[^\\])(?:\\\\)*\K(\((?:\?\??\{|\?p|\*))/;
34  
35 # --- token type constants ---
36 5 Readonly my $T_NUM => 'NUM';
37 5 Readonly my $T_STR => 'STR';
38 5 Readonly my $T_IDENT => 'IDENT';
39 5 Readonly my $T_PLUS => 'PLUS';
40 5 Readonly my $T_MINUS => 'MINUS';
41 5 Readonly my $T_STAR => 'STAR';
42 5 Readonly my $T_SLASH => 'SLASH';
43 5 Readonly my $T_LPAREN => 'LPAREN';
44 5 Readonly my $T_RPAREN => 'RPAREN';
45 5 Readonly my $T_COMMA => 'COMMA';
46 5 Readonly my $T_EOF => 'EOF';
47  
48 # Comparison operator tokens (two-char forms checked before single-char forms)
49 5 Readonly my $T_EQ => 'EQ'; # =
50 5 Readonly my $T_NEQ => 'NEQ'; # !=
51 5 Readonly my $T_LT => 'LT'; # <
52 5 Readonly my $T_LE => 'LE'; # <=
53 5 Readonly my $T_GT => 'GT'; # >
54 5 Readonly my $T_GE => 'GE'; # >=
55  
56 5 our %MESSAGES = (
57 error_expr_too_long => 'Expression too long (max %d characters)',
58 error_expr_too_deep => 'Expression nesting too deep (max %d levels)',
59 error_unknown_fn => "Unknown function '%s'",
60 error_unknown_col => "Unknown column '%s'",
61 error_unexpected_tok => "Unexpected token '%s' at position %d",
62 error_expected_tok => "Expected '%s' at position %d, got '%s'",
63 error_unterminated => 'Unterminated string at position %d',
64 error_bad_char => "Unexpected character '%s' at position %d",
65 error_trailing => "Unexpected token '%s' at position %d",
66 error_double_eq => "Use = not == for equality comparison at position %d",
67 error_param_col_clash => "Parameter '%s' conflicts with a column of the same name",
68 error_time_format => "Unsupported time format token %s",
69 error_time_format_date => "Time format '%s' must name a date, with a year, a month and a day token",
70 error_const_arg => "The second argument of %s() must be a quoted literal",
71 error_span_interval => "Unknown time bucket '%s'; use a count and one of s, m, h, d, w, mon, q or y, for example 1h or 15m",
72 error_pattern_too_long => "Pattern '%s' is longer than %d characters",
73 error_pattern_construct => "Pattern '%s' uses %s, which is not allowed",
74 error_pattern_invalid => "Pattern '%s' does not compile: %s",
75 error_rx_args => 'rx() takes a column, a quoted pattern and an optional quoted group',
76 );
77  
78 121 ▶sub _fmt {
Subroutine _fmt: called CC=1 SCAR=0.0
79 121 my ($key, @args) = @_;
80 121 return sprintf Database::BI::I18N::text(__PACKAGE__, \%MESSAGES, $key), @args;
81 }
82  
83 # --- built-in function dispatch table ---
84 # 'if' is handled as a special form in _parse_call (short-circuit branches),
85 # and so are epoch() and span(), whose second argument is a constant that is
86 # checked once, at compile time, rather than on every row.
87 #
88 # The date functions accept an ISO-8601 'YYYY-MM-DD' prefix only, and the time
89 # functions an ISO date, an ISO timestamp, or an epoch in seconds or
90 # milliseconds; non-matching values return undef and appear in the empty-cell
91 # bucket rather than being dropped.
92  
93 5 Readonly my %_MONTH_NAME_TO_NUM => (
94 jan => 1, feb => 2, mar => 3, apr => 4, may => 5, jun => 6,
95 jul => 7, aug => 8, sep => 9, oct => 10, nov => 11, dec => 12,
96 );
97  
98 # The tokens a strptime-style pattern may hold. Plain characters in a pattern
99 # are literals; anything else is a compile error, so a pattern is either fully
100 # understood or refused.
101 5 Readonly my %_FMT_RE => (
102 Y => '\d{4}', # four-digit year
103 m => '\d{1,2}', # month number
104 d => '\d{1,2}', # day of month
105 H => '\d{1,2}', # hour, 24-hour clock
106 M => '\d{1,2}', # minute
107 S => '\d{1,2}', # second
108 b => '[A-Za-z]{3}', # month abbreviation, as in %d-%b-%Y
109 );
110  
111 # The functions whose second argument is a constant, not an expression.
112 5 Readonly my %TIME_CONST_FNS => map { $_ => 1 } qw(epoch span);
113  
114 my %FUNCTIONS = (
115 # --- string functions ---
116 3 ▶ upper => sub { defined $_[0] ? uc($_[0]) : undef },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 2 1 3
117 3 ▶ lower => sub { defined $_[0] ? lc($_[0]) : undef },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 2 1 3
118 3 ▶ trim => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
119 3 ▶ return undef unless defined $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 1 2 3
120 2 my $s = $_[0];
121 # s/\A\s+|\s+\z//g is quadratic on a long run of inner spaces; two anchored substitutions are not.
122 2 $s =~ s/\A\s+//;
123 2 $s =~ s/\s+\z//;
124 2 $s;
125 },
126 3 ▶ len => sub { defined $_[0] ? length($_[0]) : undef },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 2 1 3
127 4 ▶ concat => sub { join '', map { defined $_ ? $_ : '' } @_ },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 8 1 9
128 8 ▶ substr => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
129 8 my ($s, $start, $len) = @_;
130 8 ▶ return undef unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 1 7 8
131 7 ▶ $start //= 0;
Condition50%1/2
$start //= 0
l!l
70
MC/DC0%0/1
$start //= 0
$start
Truth table50%1/2
A
A= $start
Aresult
11
00
132 # A start past the end is undef, the empty-cell result; it is not worth one
133 # log line per row.
134 5 ▶ no warnings 'substr';
Subroutine BEGIN: called CC=1 SCAR=0.0
135 7 ▶ defined $len ? CORE::substr($s, $start, $len)
Branch: 1 branch
BranchTrueFalseTotal
defined $len ? : 4 3 7
136 : CORE::substr($s, $start);
137 },
138  
139 # --- numeric functions ---
140 11 ▶ round => sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
141 11 my ($n, $d) = @_;
142 11 ▶ return undef unless defined $n && looks_like_number($n);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and &looks_like_number($n) 2 9 11
Condition100%3/3
defined $n and &looks_like_number($n)
!ll&&!rl&&r
119
MC/DC100%2/2
defined $n and &looks_like_number($n)
defined $n &looks_like_number($n)
Truth table100%3/3
A and B
A= defined $nB= &looks_like_number($n)
ABresult
0X0
100
111
143 9 ▶ $d = (defined $d && looks_like_number($d)) ? int($d) : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $d && &looks_like_number($d) ? : 6 3 9
Condition100%3/3
defined $d and &looks_like_number($d)
!ll&&!rl&&r
216
MC/DC100%2/2
defined $d and &looks_like_number($d)
defined $d &looks_like_number($d)
Truth table100%3/3
A and B
A= defined $dB= &looks_like_number($d)
ABresult
0X0
100
111
144 9 ▶ $d = $MAX_ROUND_PLACES if $d > $MAX_ROUND_PLACES;
Branch: 1 branch
BranchTrueFalseTotal
if $d > $MAX_ROUND_PLACES 1 8 9
145 9 ▶ $d = -$MAX_ROUND_PLACES if $d < -$MAX_ROUND_PLACES;
Branch: 1 branch
BranchTrueFalseTotal
if $d < -$MAX_ROUND_PLACES 1 8 9
146 9 ▶ return sprintf("%.${d}f", $n) + 0 if $d >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $d >= 0 6 3 9
147  
148 # Negative places round to the left of the point: round(1234, -2) is 1200.
149 3 my $unit = 10 ** -$d;
150 3 sprintf('%.0f', $n / $unit) * $unit;
151 },
152 5 ▶ floor => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
153 5 ▶ defined $_[0] && looks_like_number($_[0]) ? POSIX::floor($_[0]) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] && &looks_like_number($_[0]) ? : 3 2 5
Condition100%3/3
defined $_[0] and &looks_like_number($_[0])
!ll&&!rl&&r
113
MC/DC100%2/2
defined $_[0] and &looks_like_number($_[0])
defined $_[0] &looks_like_number($_[0])
Truth table100%3/3
A and B
A= defined $_[0]B= &looks_like_number($_[0])
ABresult
0X0
100
111
154 },
155 3 ▶ ceil => sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
156 3 ▶ defined $_[0] && looks_like_number($_[0]) ? POSIX::ceil($_[0]) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] && &looks_like_number($_[0]) ? : 2 1 3
Condition66%2/3
defined $_[0] and &looks_like_number($_[0])
!ll&&!rl&&r
012
MC/DC50%1/2
defined $_[0] and &looks_like_number($_[0])
defined $_[0] &looks_like_number($_[0])
Truth table66%2/3
A and B
A= defined $_[0]B= &looks_like_number($_[0])
ABresult
0X0
100
111
157 },
158 4 ▶ 'abs' => sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
159 4 ▶ defined $_[0] && looks_like_number($_[0]) ? CORE::abs($_[0]) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] && &looks_like_number($_[0]) ? : 3 1 4
Condition66%2/3
defined $_[0] and &looks_like_number($_[0])
!ll&&!rl&&r
013
MC/DC50%1/2
defined $_[0] and &looks_like_number($_[0])
defined $_[0] &looks_like_number($_[0])
Truth table66%2/3
A and B
A= defined $_[0]B= &looks_like_number($_[0])
ABresult
0X0
100
111
160 },
161  
162 # --- conditional / null-handling ---
163 8 ▶ isnull => sub { defined $_[0] ? $_[0] : $_[1] },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 5 3 8
164 8 ▶ coalesce => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
165 8 ▶ for my $v (@_) { return $v if defined $v }
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 6 9 15
166 2 return undef;
167 },
168  
169 # --- date functions (ISO-8601 YYYY-MM-DD prefix; no external module) ---
170 14 ▶ year => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
171 14 ▶ return undef unless defined $_[0] && $_[0] =~ /\A(\d{4})-\d\d-\d\d/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A(\d{4})-\d\d-\d\d/ 4 10 14
Condition100%3/3
defined $_[0] and $_[0] =~ /\A(\d{4})-\d\d-\d\d/
!ll&&!rl&&r
1310
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A(\d{4})-\d\d-\d\d/
defined $_[0] $_[0] =~ /\A(\d{4})-\d\d-\d\d/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A(\d{4})-\d\d-\d\d/
ABresult
0X0
100
111
172 10 $1 + 0;
173 },
174 7 ▶ month => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
175 7 ▶ return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/ 5 2 7
Condition100%3/3
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/
!ll&&!rl&&r
142
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/
defined $_[0] $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/
ABresult
0X0
100
111
176 2 $1 + 0;
177 },
178 6 ▶ day => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
179 6 ▶ return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/ 4 2 6
Condition100%3/3
defined $_[0] and $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/
!ll&&!rl&&r
132
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/
defined $_[0] $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/
ABresult
0X0
100
111
180 2 $1 + 0;
181 },
182 8 ▶ quarter => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
183 8 ▶ return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/ 4 4 8
Condition100%3/3
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
!ll&&!rl&&r
134
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
defined $_[0] $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
ABresult
0X0
100
111
184 4 int(($1 - 1) / 3) + 1;
185 },
186 7 ▶ week => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
187 # Returns ISO 8601 week number (1-53); week containing the first
188 # Thursday of the year is week 1.
189 7 ▶ return undef unless defined $_[0] && $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/ 2 5 7
Condition100%3/3
defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
!ll&&!rl&&r
115
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
defined $_[0] $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
ABresult
0X0
100
111
190 5 my $t = _epoch_of($1 + 0, $2 + 0, $3 + 0, 12, 0, 0);
191 5 ▶ return undef unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 2 3 5
192 3 my @lt = localtime($t);
193 # Not strftime('%V'): the Windows C runtime does not have it, and
194 # gives ''.
195 3 _iso_week($lt[5] + 1900, $lt[6], $lt[7]);
196 },
197 6 ▶ month_name => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
198 # Returns full English month name, e.g. 'January'.
199 6 my @M = qw(January February March April May June
200 July August September October November December);
201 6 ▶ return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/ 4 2 6
Condition100%3/3
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
!ll&&!rl&&r
132
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
defined $_[0] $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/
ABresult
0X0
100
111
202 2 $M[$1 - 1];
203 },
204 9 ▶ weekday => sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
205 # Returns ISO 8601 weekday: 1 = Monday, 7 = Sunday.
206 9 ▶ return undef unless defined $_[0] && $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/ 2 7 9
Condition100%3/3
defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
!ll&&!rl&&r
117
MC/DC100%2/2
defined $_[0] and $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
defined $_[0] $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
Truth table100%3/3
A and B
A= defined $_[0]B= $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/
ABresult
0X0
100
111
207 7 my $t = _epoch_of($1 + 0, $2 + 0, $3 + 0, 12, 0, 0);
208 7 ▶ return undef unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 2 5 7
209 5 my $wd = (localtime($t))[6]; # 0 = Sunday
210 5 ▶ $wd == 0 ? 7 : $wd;
Branch: 1 branch
BranchTrueFalseTotal
$wd == 0 ? : 2 3 5
211 },
212 2 ▶ now => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
213 # Returns today's date as 'YYYY-MM-DD'. Takes no arguments.
214 2 my @t = (localtime(Database::BI::Util::frame_epoch(time)))[3, 4, 5]; # mday, mon (0-based), year (since 1900)
215 2 sprintf '%04d-%02d-%02d', $t[2] + 1900, $t[1] + 1, $t[0];
216 },
217  
218 # --- time of day (see "Time values and time buckets" below) --
219 4 ▶ hour => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
220 4 my $t = _parse_time($_[0]);
221 4 ▶ return undef unless $t && $t->{has_time};
Branch: 1 branch
BranchTrueFalseTotal
unless $t and $t->{"has_time"} 3 1 4
Condition100%3/3
$t and $t->{"has_time"}
!ll&&!rl&&r
211
MC/DC100%2/2
$t and $t->{"has_time"}
$t $t->{"has_time"}
Truth table100%3/3
A and B
A= $tB= $t->{"has_time"}
ABresult
0X0
100
111
222 1 (localtime($t->{epoch}))[2] + 0;
223 },
224 3 ▶ minute => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
225 3 my $t = _parse_time($_[0]);
226 3 ▶ return undef unless $t && $t->{has_time};
Branch: 1 branch
BranchTrueFalseTotal
unless $t and $t->{"has_time"} 2 1 3
Condition66%2/3
$t and $t->{"has_time"}
!ll&&!rl&&r
201
MC/DC50%1/2
$t and $t->{"has_time"}
$t $t->{"has_time"}
Truth table66%2/3
A and B
A= $tB= $t->{"has_time"}
ABresult
0X0
100
111
227 1 (localtime($t->{epoch}))[1] + 0;
228 },
229 3 ▶ second => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
230 3 my $t = _parse_time($_[0]);
231 3 ▶ return undef unless $t && $t->{has_time};
Branch: 1 branch
BranchTrueFalseTotal
unless $t and $t->{"has_time"} 2 1 3
Condition66%2/3
$t and $t->{"has_time"}
!ll&&!rl&&r
201
MC/DC50%1/2
$t and $t->{"has_time"}
$t $t->{"has_time"}
Truth table66%2/3
A and B
A= $tB= $t->{"has_time"}
ABresult
0X0
100
111
232 1 (localtime($t->{epoch}))[0] + 0;
233 },
234  
235 # --- grouping / binning ---
236 24 ▶ bin => sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
237 # bin(value, width) -> '[lo,hi)' label for the interval containing value.
238 # Width must be a positive number. Both endpoints use %d when width is
239 # an integer, %g otherwise, to avoid spurious ".0" suffixes.
240 24 my ($v, $w) = @_;
241 24 ▶ return undef unless defined $v && defined $w;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and defined $w 2 22 24
Condition100%3/3
defined $v and defined $w
!ll&&!rl&&r
1122
MC/DC100%2/2
defined $v and defined $w
defined $v defined $w
Truth table100%3/3
A and B
A= defined $vB= defined $w
ABresult
0X0
100
111
242 22 ▶ return undef unless looks_like_number($v) && looks_like_number($w) && $w > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($v) and &looks_like_number($w) and $w > 0 6 16 22
Condition100%6/6
&looks_like_number($v) and &looks_like_number($w) and $w > 0
!ll&&!rl&&r
2416
&looks_like_number($v) and &looks_like_number($w)
!ll&&!rl&&r
1120
MC/DC100%3/3
&looks_like_number($v) and &looks_like_number($w) and $w > 0
&looks_like_number($v) &looks_like_number($w) $w > 0
Truth table100%4/4
A and B and C
A= &looks_like_number($v)B= &looks_like_number($w)C= $w > 0
ABCresult
0XX0
10X0
1100
1111
243 # Normalise the quotient to 10 significant digits before flooring: binary
244 # representation error (0.3 / 0.1 == 2.9999999999999996) must not move a
245 # value one bin to the left. %.10g is magnitude-independent.
246 16 my $n = POSIX::floor(sprintf('%.10g', $v / $w) + 0);
247 16 my $lo = $n * $w;
248 16 my $hi = $lo + $w;
249 16 ▶ my $fmt = ($w == int($w)) ? '%d' : '%g';
Branch: 1 branch
BranchTrueFalseTotal
$w == int $w ? : 8 8 16
250 16 sprintf("[${fmt},${fmt})", $lo, $hi);
251 },
252 5 );
253  
254 # ---------------------------------------------------------------------------
255 # Time values and time buckets
256 #
257 # One parser and one interval vocabulary, with the time-of-day functions and
258 # span() on top of them. Every value is read as *local* time, by
259 # POSIX::mktime, exactly as the date functions and the relative time ranges
260 # already are: no zone is parsed, none is stored, and nothing here reads the
261 # clock -- a bucket for a value is the same bucket tomorrow.
262 # ---------------------------------------------------------------------------
263  
264 # _fmt_body($fmt) -> ($regex_body, \@tokens)
265 #
266 # Purpose: Turn a strptime-style pattern into a regex body with one capture per
267 # token, plus the token each capture belongs to. A token outside
268 # %_FMT_RE is a compile error rather than a silent skip: a pattern
269 # that quietly ignored half of itself is how a value ends up in the
270 # wrong bucket without anybody being told.
271 41 ▶sub _fmt_body {
Subroutine _fmt_body: called CC=8 SCAR=20.8
272 41 my ($fmt) = @_;
273 41 my @tokens;
274 41 my $body = '';
275 41 my $i = 0;
276  
277 41 ▶ while ($i < length $fmt) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < length $fmt) 152 33 185
278 152 my $ch = substr($fmt, $i, 1);
279 152 ▶ if ($ch ne '%') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch ne "%") 66 86 152
280 66 $body .= quotemeta($ch);
281 66 $i++;
282 66 next;
283 }
284 86 my $tok = substr($fmt, $i + 1, 1);
285 croak _fmt('error_time_format', length($tok // '') ? "%$tok" : $fmt)
286 86 ▶ unless length($tok // '') && exists $_FMT_RE{$tok};
Branch: 2 branches
BranchTrueFalseTotal
unless length($tok // "") and exists $_FMT_RE{$tok} 8 78 86
length($tok // '') ? : 7 1 8
Condition71%5/7
length($tok // "") and exists $_FMT_RE{$tok}
!ll&&!rl&&r
1778
$tok // ""
l!l
860
$tok // ""
l!l
80
MC/DC50%1/2
length($tok // "") and exists $_FMT_RE{$tok}
$tok exists $_FMT_RE{$tok}
Truth table66%2/3
A and B
A= $tokB= exists $_FMT_RE{$tok}
ABresult
0X0
100
111
287 78 push @tokens, $tok;
288 78 $body .= '(' . $_FMT_RE{$tok} . ')';
289 78 $i += 2;
290 }
291  
292 33 return ($body, \@tokens);
293 }
294  
295 # _fmt_compile($fmt) -> { re => qr, tokens => \@tokens }
296 #
297 # A pattern on its own has to name a date; a time with no day has no place on a
298 # calendar to be resolved against.
299 16 ▶sub _fmt_compile {
Subroutine _fmt_compile: called CC=2 SCAR=6.9
300 16 my ($fmt) = @_;
301 16 my ($body, $tokens) = _fmt_body($fmt);
302 13 ▶ croak _fmt('error_time_format_date', $fmt)
Branch: 1 branch
BranchTrueFalseTotal
unless _fmt_has_date($tokens) 2 11 13
303 unless _fmt_has_date($tokens);
304 11 return { re => qr/\A$body\z/, tokens => $tokens };
305 }
306  
307 # _fmt_has_date(\@tokens) -> bool
308 #
309 # A pattern has to name a date: a year, a day, and a month -- as a number
310 # (C<%m>) or as an abbreviation (C<%b>), which is what %d-%b-%Y uses.
311 26 ▶sub _fmt_has_date {
Subroutine _fmt_has_date: called CC=5 SCAR=16.1
312 26 my ($tokens) = @_;
313 26 my %has = map { $_ => 1 } @$tokens;
314 26 ▶ return $has{Y} && $has{d} && ($has{m} || $has{b}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$has{'Y'} && $has{'d'} && ($has{'m'} || $has{'b'}) ? : 19 7 26
Condition100%9/9
$has{"Y"} and $has{"d"} and $has{"m"} || $has{"b"}
!ll&&!rl&&r
6119
$has{"Y"} and $has{"d"}
!ll&&!rl&&r
5120
$has{"m"} or $has{"b"}
l!l&&r!l&&!r
1721
MC/DC100%4/4
$has{"Y"} and $has{"d"} and $has{"m"} || $has{"b"}
$has{"Y"} $has{"d"} $has{"m"} $has{"b"}
Truth table100%5/5
A and B and C or D
A= $has{"Y"}B= $has{"d"}C= $has{"m"}D= $has{"b"}
ABCDresult
0XXX0
10XX0
11000
111X1
11011
315 }
316  
317 # _fmt_compile_pair($date_fmt, $time_fmt) -> { re => qr, tokens => \@tokens }
318 #
319 # A stored time pattern is two patterns holding one value between them, so they
320 # are compiled into one regex: the date, an optional 'T' or space, the time.
321 9 ▶sub _fmt_compile_pair {
Subroutine _fmt_compile_pair: called CC=2 SCAR=6.9
322 9 my ($date_fmt, $time_fmt) = @_;
323 9 my ($dbody, $dtokens) = _fmt_body($date_fmt);
324 9 my ($tbody, $ttokens) = _fmt_body($time_fmt);
325 7 ▶ croak _fmt('error_time_format_date', $date_fmt)
Branch: 1 branch
BranchTrueFalseTotal
unless _fmt_has_date($dtokens) 1 6 7
326 unless _fmt_has_date($dtokens);
327 return {
328 6 re => qr/\A$dbody[ T]?$tbody\z/,
329 tokens => [ @$dtokens, @$ttokens ],
330 };
331 }
332  
333 # _fmt_parts($value, $compiled) -> \%parts | undef
334 20 ▶sub _fmt_parts {
Subroutine _fmt_parts: called CC=3 SCAR=11.0
335 20 my ($value, $compiled) = @_;
336 20 my @caps = ($value =~ $compiled->{re});
337 20 ▶ return undef unless @caps;
Branch: 1 branch
BranchTrueFalseTotal
unless @caps 4 16 20
338  
339 16 my %part;
340 16 my @tokens = @{ $compiled->{tokens} };
341 16 for my $i (0 .. $#tokens) {
342 57 $part{ $tokens[$i] } = $caps[$i];
343 }
344 16 return \%part;
345 }
346  
347 # _epoch_of($y, $mon, $day, $h, $mi, $s) -> epoch | undef
348 #
349 # Purpose: Local epoch seconds for a calendar date and clock time.
350 # Notes: POSIX::mktime normalises what it is given -- '2026-02-31' becomes
351 # 3 March, month 13 becomes January -- so the parts are read back and
352 # compared before the value is accepted, and a date that does not
353 # exist is unparseable rather than quietly a different date. The
354 # clock time is allowed two hours of slack, because the hour a
355 # daylight-saving change skips does not exist and mktime moves it.
356 # _iso_week($year, $wday, $yday) -> 1..53
357 #
358 # The ISO 8601 week of a day, from localtime's weekday (0 = Sunday) and day of
359 # the year (0 = 1 January). Week 1 holds the year's first Thursday, so the
360 # first days of January can be in the last week of the year before, and the
361 # last days of December in week 1 of the next.
362 451 ▶sub _iso_week {
Subroutine _iso_week: called CC=5 SCAR=16.1
363 451 my ($year, $wday, $yday) = @_;
364 451 ▶ my $leap = sub { my $y = shift; ($y % 4 == 0 && $y % 100 != 0) || $y % 400 == 0 };
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
$y % 4 == 0 and $y % 100 != 0 or $y % 400 == 0 89 319 408
Condition100%3/3
$y % 4 == 0 and $y % 100 != 0
!ll&&!rl&&r
3071289
MC/DC100%2/2
$y % 4 == 0 and $y % 100 != 0
$y % 4 == 0 $y % 100 != 0
Truth table100%3/3
A and B
A= $y % 4 == 0B= $y % 100 != 0
ABresult
0X0
100
111
365 # Monday is 1 and Sunday 7, as ISO counts.
366 451 ▶ my $iso_wday = $wday || 7;
Condition100%2/2
$wday || 7
l!l
38764
MC/DC100%1/1
$wday || 7
$wday
Truth table100%2/2
A
A= $wday
Aresult
11
00
367 451 my $week = int(($yday + 1 - $iso_wday + 10) / 7);
368 # The weekday of 1 January, 0 = Sunday.
369 451 my $jan1 = ($wday - $yday) % 7;
370 451 ▶ my $weeks = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
371 451 my ($y, $j1) = @_;
372 451 ▶ return ($j1 == 4 || ($leap->($y) && $j1 == 3)) ? 53 : 52;
Branch: 1 branch
BranchTrueFalseTotal
$j1 == 4 || &$leap($y) && $j1 == 3 ? : 90 361 451
Condition100%6/6
$j1 == 4 or &$leap($y) and $j1 == 3
l!l&&r!l&&!r
7218361
&$leap($y) and $j1 == 3
!ll&&!rl&&r
2847718
MC/DC100%3/3
$j1 == 4 or &$leap($y) and $j1 == 3
$j1 == 4 &$leap($y) $j1 == 3
Truth table100%4/4
A or B and C
A= $j1 == 4B= &$leap($y)C= $j1 == 3
ABCresult
1XX1
0111
00X0
0100
373 451 };
374 451 ▶ if ($week < 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($week < 1) 29 422 451
375 29 ▶ my $prev_jan1 = ($jan1 - ($leap->($year - 1) ? 366 : 365)) % 7;
Branch: 1 branch
BranchTrueFalseTotal
&$leap($year - 1) ? : 6 23 29
376 29 return $weeks->($year - 1, $prev_jan1);
377 }
378 422 ▶ return 1 if $week > $weeks->($year, $jan1);
Branch: 1 branch
BranchTrueFalseTotal
if $week > &$weeks($year, $jan1) 27 395 422
379 395 return $week;
380 }
381  
382 111 ▶sub _epoch_of {
Subroutine _epoch_of: called CC=6 SCAR=18.0
383 111 my ($y, $mon, $day, $h, $mi, $s) = @_;
384 # mktime and localtime run the C library's tzset, which on FreeBSD can
385 # leave errno set (EILSEQ) when it succeeds: the caller's $! is kept.
386 111 local $!;
387 111 require POSIX;
388 111 my $epoch = POSIX::mktime($s, $mi, $h, $day, $mon - 1, $y - 1900);
389 111 ▶ return undef unless defined $epoch;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $epoch 0 111 111
390  
391 111 my @lt = localtime($epoch);
392 return undef
393 111 ▶ unless $lt[5] + 1900 == $y && $lt[4] + 1 == $mon && $lt[3] == $day;
Branch: 1 branch
BranchTrueFalseTotal
unless $lt[5] + 1900 == $y and $lt[4] + 1 == $mon and $lt[3] == $day 28 83 111
Condition100%6/6
$lt[5] + 1900 == $y and $lt[4] + 1 == $mon and $lt[3] == $day
!ll&&!rl&&r
26283
$lt[5] + 1900 == $y and $lt[4] + 1 == $mon
!ll&&!rl&&r
131385
MC/DC100%3/3
$lt[5] + 1900 == $y and $lt[4] + 1 == $mon and $lt[3] == $day
$lt[5] + 1900 == $y $lt[4] + 1 == $mon $lt[3] == $day
Truth table100%4/4
A and B and C
A= $lt[5] + 1900 == $yB= $lt[4] + 1 == $monC= $lt[3] == $day
ABCresult
0XX0
10X0
1100
1111
394  
395 83 my $want = $h * 3_600 + $mi * 60 + $s;
396 83 my $got = $lt[2] * 3_600 + $lt[1] * 60 + $lt[0];
397 83 ▶ return undef if abs($got - $want) > 7_200;
Branch: 1 branch
BranchTrueFalseTotal
if abs $got - $want > 7200 0 83 83
398 83 return $epoch;
399 }
400  
401 # _parse_time($value) -> { epoch => E, has_time => 0|1 } | undef
402 #
403 # Purpose: Read one cell as a point in time. Three shapes are recognised, in
404 # this order: an ISO date, or an ISO timestamp with 'T' or a space
405 # between the date and the time (a fraction of a second and a zone
406 # are moved to the configured time_zone, and set aside without one:
407 # Database::BI::Util::iso_datetime);
408 # ten digits, an epoch in seconds; and
409 # thirteen digits, an epoch in milliseconds. Only the digit count
410 # separates the last two, so it is the rule -- and it is documented,
411 # because nothing in the value itself says which one it is.
412 65 ▶sub _parse_time {
Subroutine _parse_time: called CC=13 SCAR=25.6
413 65 my ($value) = @_;
414 65 ▶ return undef unless defined $value && !ref $value && length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value and length $value 8 57 65
Condition100%6/6
defined $value and not ref $value and length $value
!ll&&!rl&&r
6257
defined $value and not ref $value
!ll&&!rl&&r
5159
MC/DC100%3/3
defined $value and not ref $value and length $value
defined $value not ref $value length $value
Truth table100%4/4
A and not(B) and C
A= defined $valueB= not ref $valueC= length $value
ABCresult
0XX0
10X0
1100
1111
415 57 (my $s = $value) =~ s/\A\s+//;
416 57 $s =~ s/\s+\z//;
417 57 ▶ return undef unless length $s;
Branch: 1 branch
BranchTrueFalseTotal
unless length $s 1 56 57
418  
419 56 my ($ymd, $h, $mi, $sec) = Database::BI::Util::iso_datetime($s);
420 56 ▶ if (defined $ymd) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ymd) 41 15 56
421 41 my ($y, $mon, $day) = split /-/, $ymd;
422 41 ▶ my $epoch = _epoch_of($y + 0, $mon + 0, $day + 0,
Condition100%6/6
$h // 0
l!l
1031
$mi // 0
l!l
1031
$sec // 0
l!l
833
MC/DC100%1/1
$h // 0
$h
MC/DC100%1/1
$mi // 0
$mi
MC/DC100%1/1
$sec // 0
$sec
Truth table100%2/2
A
A= $h
Aresult
11
00
Truth table100%2/2
A
A= $mi
Aresult
11
00
Truth table100%2/2
A
A= $sec
Aresult
11
00
423 ($h // 0) + 0, ($mi // 0) + 0, ($sec // 0) + 0);
424 41 ▶ return undef unless defined $epoch;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $epoch 4 37 41
425 37 ▶ return { epoch => $epoch, has_time => defined $h ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
defined $h ? : 9 28 37
426 }
427  
428 # An epoch is one moment; the buckets read it on the configured zone's clock.
429 15 ▶ return { epoch => Database::BI::Util::frame_epoch($s + 0), has_time => 1 } if $s =~ /\A\d{10}\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /\A\d{10}\z/ 1 14 15
430 14 ▶ return { epoch => Database::BI::Util::frame_epoch(int($s / 1_000)), has_time => 1 } if $s =~ /\A\d{13}\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /\A\d{13}\z/ 1 13 14
431 13 return undef;
432 }
433  
434 # _time_from_format($value, $compiled) -> { epoch => E, has_time => 0|1 } | undef
435 20 ▶sub _time_from_format {
Subroutine _time_from_format: called CC=14 SCAR=26.4
436 20 my ($value, $compiled) = @_;
437 20 ▶ return undef unless defined $value && !ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value 2 18 20
Condition100%3/3
defined $value and not ref $value
!ll&&!rl&&r
1118
MC/DC100%2/2
defined $value and not ref $value
defined $value not ref $value
Truth table100%3/3
A and not(B)
A= defined $valueB= not ref $value
ABresult
0X0
100
111
438 18 ▶ my $part = _fmt_parts($value, $compiled) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $part = _fmt_parts($value, $compiled) or return undef 15 3 18
439  
440 my $mon = defined $part->{m} ? $part->{m} + 0
441 : defined $part->{b} ? $_MONTH_NAME_TO_NUM{ lc $part->{b} }
442 15 ▶ : undef;
Branch: 2 branches
BranchTrueFalseTotal
defined $part->{'m'} ? : 11 4 15
defined $part->{'b'} ? : 4 0 4
443 15 ▶ return undef unless defined $mon && $mon >= 1 && $mon <= 12;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mon and $mon >= 1 and $mon <= 12 3 12 15
Condition100%6/6
defined $mon and $mon >= 1 and $mon <= 12
!ll&&!rl&&r
2112
defined $mon and $mon >= 1
!ll&&!rl&&r
1113
MC/DC100%3/3
defined $mon and $mon >= 1 and $mon <= 12
defined $mon $mon >= 1 $mon <= 12
Truth table100%4/4
A and B and C
A= defined $monB= $mon >= 1C= $mon <= 12
ABCresult
0XX0
10X0
1100
1111
444  
445 my $epoch = _epoch_of($part->{Y} + 0, $mon, $part->{d} + 0,
446 12 ▶ ($part->{H} // 0) + 0, ($part->{M} // 0) + 0, ($part->{S} // 0) + 0);
Condition100%6/6
$part->{"H"} // 0
l!l
48
$part->{"M"} // 0
l!l
48
$part->{"S"} // 0
l!l
111
MC/DC100%1/1
$part->{"H"} // 0
$part->{"H"}
MC/DC100%1/1
$part->{"M"} // 0
$part->{"M"}
MC/DC100%1/1
$part->{"S"} // 0
$part->{"S"}
Truth table100%2/2
A
A= $part->{"H"}
Aresult
11
00
Truth table100%2/2
A
A= $part->{"M"}
Aresult
11
00
Truth table100%2/2
A
A= $part->{"S"}
Aresult
11
00
447 12 ▶ return undef unless defined $epoch;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $epoch 2 10 12
448 10 ▶ return { epoch => $epoch, has_time => defined $part->{H} ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
defined $part->{'H'} ? : 4 6 10
449 }
450  
451 # _iso_second_label($epoch) -> 'YYYY-MM-DDTHH:MM:SS' in local time
452 9 ▶sub _iso_second_label {
Subroutine _iso_second_label: called CC=1 SCAR=0.0
453 9 my @lt = localtime($_[0]);
454 9 return sprintf '%04d-%02d-%02dT%02d:%02d:%02d',
455 $lt[5] + 1900, $lt[4] + 1, $lt[3], $lt[2], $lt[1], $lt[0];
456 }
457  
458 # _civil_day($y, $mon, $day) -> days since 1970-01-01
459 #
460 # Purpose: A day number that does not move with daylight saving, so the n-day
461 # and n-week buckets can be counted from a fixed origin. Integer
462 # civil-calendar arithmetic; no part of this reads the clock.
463 18 ▶sub _civil_day {
Subroutine _civil_day: called CC=4 SCAR=13.9
464 18 my ($y, $mon, $day) = @_;
465 18 ▶ $y -= ($mon <= 2) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$mon <= 2 ? : 5 13 18
466 18 ▶ my $era = int(($y >= 0 ? $y : $y - 399) / 400);
Branch: 1 branch
BranchTrueFalseTotal
$y >= 0 ? : 18 0 18
467 18 my $yoe = $y - $era * 400; # [0, 399]
468 18 ▶ my $doy = int((153 * ($mon + ($mon > 2 ? -3 : 9)) + 2) / 5) + $day - 1;
Branch: 1 branch
BranchTrueFalseTotal
$mon > 2 ? : 13 5 18
469 18 my $doe = $yoe * 365 + int($yoe / 4) - int($yoe / 100) + $doy;
470 18 return $era * 146_097 + $doe - 719_468;
471 }
472  
473 # _shift_days($y, $mon, $day, $delta) -> ($y, $mon, $day)
474 #
475 # Purpose: Move a date by whole days without a calendar library.
476 # Notes: Noon is the anchor. A day is then 86,400 seconds away from its
477 # neighbours even across a daylight-saving change, so counting days
478 # cannot land on the wrong date -- counting from midnight does, once a
479 # year, and only in the autumn.
480 14 ▶sub _shift_days {
Subroutine _shift_days: called CC=2 SCAR=6.9
481 14 my ($y, $mon, $day, $delta) = @_;
482 14 ▶ return ($y, $mon, $day) unless $delta;
Branch: 1 branch
BranchTrueFalseTotal
unless $delta 5 9 14
483 9 local $!; # mktime and localtime may set errno; see _epoch_of
484 9 require POSIX;
485 9 my @lt = localtime(POSIX::mktime(12, 0, 0, $day, $mon - 1, $y - 1900) + $delta * 86_400);
486 9 return ($lt[5] + 1900, $lt[4] + 1, $lt[3]);
487 }
488  
489 # span_interval($interval) -> { n => N, unit => U, [secs => S] } | undef
490 #
491 # Purpose: The interval vocabulary span() takes, and the only place its rule
492 # lives: a count and a unit, 'mon' for months (because 'm' is
493 # minutes) and 'q' for quarters. A count below one and an unknown
494 # unit are both undef rather than a bucket that quietly means
495 # something else. Public because the span= sugar validates an
496 # interval before it builds the expression, and one rule with two
497 # callers beats two rules that drift apart.
498 106 ▶sub span_interval {
Subroutine span_interval: called CC=10 SCAR=23.0
Pod undocumented
499 106 my ($interval) = @_;
500 106 ▶ return undef unless defined $interval && !ref $interval && length $interval;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $interval and not ref $interval and length $interval 6 100 106
Condition100%6/6
defined $interval and not ref $interval and length $interval
!ll&&!rl&&r
42100
defined $interval and not ref $interval
!ll&&!rl&&r
22102
MC/DC100%3/3
defined $interval and not ref $interval and length $interval
defined $interval not ref $interval length $interval
Truth table100%4/4
A and not(B) and C
A= defined $intervalB= not ref $intervalC= length $interval
ABCresult
0XX0
10X0
1100
1111
501 100 ▶ my ($n, $unit) = $interval =~ /\A(\d+)(mon|s|m|h|d|w|q|y)\z/ or return undef;
Branch: 1 branch
BranchTrueFalseTotal
() = $interval =~ /\A(\d+)(mon|s|m|h|d|w|q|y)\z/ or return undef 67 33 100
502 67 $n += 0;
503 67 ▶ return undef if $n < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $n < 1 3 64 67
504  
505 64 ▶ my $secs = $unit eq 's' ? 1
Branch: 3 branches
BranchTrueFalseTotal
$unit eq 's' ? : 3 61 64
$unit eq 'm' ? : 3 58 61
$unit eq 'h' ? : 4 54 58
506 : $unit eq 'm' ? 60
507 : $unit eq 'h' ? 3_600
508 : undef;
509 64 ▶ return { n => $n, unit => $unit, (defined $secs ? (secs => $secs) : ()) };
Branch: 1 branch
BranchTrueFalseTotal
defined $secs ? : 10 54 64
510 }
511  
512 # compile_pattern($pattern) -> \%compiled
513 #
514 # Purpose: The one place a reader's regular expression is checked and compiled,
515 # for rx() and for the stored extractions, so both refuse the same
516 # things with the same words.
517 # Entry: $pattern is a string.
518 # Exit: { re => qr//, groups => N, names => [ named groups, in order ] }.
519 # Croaks error_pattern_too_long, error_pattern_construct or
520 # error_pattern_invalid.
521 # Notes: A pattern is checked, not sandboxed: the engine has no timeout, so a
522 # pathological one stalls the request that uses it. Patterns are typed
523 # by the reader who owns the machine, never taken from a remote party.
524 47 ▶sub compile_pattern {
Subroutine compile_pattern: called CC=12 SCAR=25.0
Pod undocumented
525 47 my ($pattern) = @_;
526 47 local $@;
527 47 ▶ $pattern = '' unless defined $pattern && !ref $pattern;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pattern and not ref $pattern 4 43 47
Condition100%3/3
defined $pattern and not ref $pattern
!ll&&!rl&&r
2243
MC/DC100%2/2
defined $pattern and not ref $pattern
defined $pattern not ref $pattern
Truth table100%3/3
A and not(B)
A= defined $patternB= not ref $pattern
ABresult
0X0
100
111
528 47 ▶ croak _fmt('error_pattern_too_long', substr($pattern, 0, 40) . (length($pattern) > 40 ? '...' : ''), $MAX_PATTERN_LEN)
Branch: 2 branches
BranchTrueFalseTotal
if length $pattern > $MAX_PATTERN_LEN 1 46 47
length $pattern > 40 ? : 1 0 1
529 if length($pattern) > $MAX_PATTERN_LEN;
530 46 ▶ if ($pattern =~ $REFUSED_PATTERN_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pattern =~ /$REFUSED_PATTERN_RE/) 8 38 46
531 8 croak _fmt('error_pattern_construct', $pattern, $1);
532 }
533  
534 38 my $re = eval { qr/$pattern/ };
535 38 ▶ unless ($re) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($re) 6 32 38
536 6 ▶ (my $why = $@ // '') =~ s/ at \S+ line \d+\.?\n?\z//;
Condition50%1/2
$@ // ""
l!l
60
MC/DC0%0/1
$@ // ""
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
537 6 $why =~ s/\s+\z//;
538 6 croak _fmt('error_pattern_invalid', $pattern, $why);
539 }
540  
541 # An optional match of the empty string always succeeds, and leaves behind
542 # how many groups the pattern has and every name it declares.
543 32 '' =~ /(?:$re)?/;
544 32 my $groups = $#+;
545 32 require re;
546 32 my %known = map { $_ => 1 } re::regnames(1);
547 # The names in the order they are written, which is the order a reader
548 # expects the columns in; regnames() itself has no order.
549 32 my (@names, %seen);
550 32 ▶ while ($pattern =~ /(?<!\\)\(\?(?:P?<([A-Za-z_]\w*)>|'([A-Za-z_]\w*)')/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pattern =~ /(?<!\\)\(\?(?:P?<([A-Za-z_]\w*)>|'([A-Za-z_]\w*)')/g) 24 32 56
551 24 ▶ my $n = defined $1 ? $1 : $2;
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 23 1 24
552 24 ▶ push @names, $n if $known{$n} && !$seen{$n}++;
Branch: 1 branch
BranchTrueFalseTotal
if $known{$n} and not $seen{$n}++ 24 0 24
Condition33%1/3
$known{$n} and not $seen{$n}++
!ll&&!rl&&r
0024
MC/DC0%0/2
$known{$n} and not $seen{$n}++
$known{$n} not $seen{$n}++
Truth table33%1/3
A and not(B)
A= $known{$n}B= not $seen{$n}++
ABresult
0X0
100
111
553 }
554 32 push @names, grep { !$seen{$_}++ } sort keys %known;
555  
556 32 return { re => $re, groups => $groups, names => \@names };
557 }
558  
559 # capture_of(\%compiled, $value, $group) -> $capture | undef
560 #
561 # Purpose: One capture of a compiled pattern against a value: $group is a
562 # number (1 is the first group) or a group's name.
563 # Exit: The capture, cut to $MAX_CAPTURE_LEN characters; '' when the pattern
564 # matched but the group took no part; undef when the value is undefined,
565 # the pattern does not match, or there is no such group.
566 23 ▶sub capture_of {
Subroutine capture_of: called CC=13 SCAR=25.6
Pod undocumented
567 23 my ($compiled, $value, $group) = @_;
568 23 ▶ return undef unless defined $value && !ref $value && defined $group;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value and defined $group 3 20 23
Condition100%6/6
defined $value and not ref $value and defined $group
!ll&&!rl&&r
2120
defined $value and not ref $value
!ll&&!rl&&r
1121
MC/DC100%3/3
defined $value and not ref $value and defined $group
defined $value not ref $value defined $group
Truth table100%4/4
A and not(B) and C
A= defined $valueB= not ref $valueC= defined $group
ABCresult
0XX0
10X0
1100
1111
569 # Which group is asked for is settled first: a match of its own here would
570 # replace the captures of the one that matters.
571 20 ▶ my $number = $group =~ /\A[0-9]+\z/ ? $group + 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$group =~ /\A[0-9]+\z/ ? : 10 10 20
572 20 ▶ if (defined $number) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $number) { } 10 10 20
573 10 ▶ return undef if $number < 1 || $number > $compiled->{groups};
Branch: 1 branch
BranchTrueFalseTotal
if $number < 1 or $number > $compiled->{"groups"} 2 8 10
Condition100%3/3
$number < 1 or $number > $compiled->{"groups"}
l!l&&r!l&&!r
118
MC/DC100%2/2
$number < 1 or $number > $compiled->{"groups"}
$number < 1 $number > $compiled->{"groups"}
Truth table100%3/3
A or B
A= $number < 1B= $number > $compiled->{"groups"}
ABresult
1X1
011
000
574 } else {
575 10 ▶ return undef unless grep { $_ eq $group } @{ $compiled->{names} };
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $group;} @{$$compiled{"names"};} 2 8 10
576 }
577 16 ▶ return undef unless $value =~ $compiled->{re};
Branch: 1 branch
BranchTrueFalseTotal
unless $value =~ /$compiled->{"re"}/ 3 13 16
578 13 ▶ my $got = defined $number ? ${^CAPTURE}[$number - 1] : $+{$group};
Branch: 1 branch
BranchTrueFalseTotal
defined $number ? : 6 7 13
579 13 ▶ return '' unless defined $got;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $got 2 11 13
580 11 ▶ return length($got) > $MAX_CAPTURE_LEN ? substr($got, 0, $MAX_CAPTURE_LEN) : $got;
Branch: 1 branch
BranchTrueFalseTotal
length $got > $MAX_CAPTURE_LEN ? : 1 10 11
581 }
582  
583 # _span_label($value, \%interval) -> bucket label | undef
584 #
585 # Purpose: The ISO label of the bucket a value falls in -- the half-open
586 # interval from the bucket's start to the next bucket's start.
587 # Notes: The label is ISO at the bucket's own resolution, never 'Oct 2026':
588 # group keys are sorted as strings, so an ISO label makes
589 # lexicographic order chronological order and a bucketed chart comes
590 # out in the right order with no second sort path. A pretty name is a
591 # presentation step (month_name() already reads a month number); it is
592 # never the key.
593 # The intervals below a day are floored out of the epoch, and 'd'
594 # downwards are counted in calendar units, because a day is not always
595 # 86,400 seconds and a month never is.
596 32 ▶sub _span_label {
Subroutine _span_label: called CC=9 SCAR=22.0
597 32 my ($value, $interval) = @_;
598 32 my $t = _parse_time($value);
599 32 ▶ return undef unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 5 27 32
600  
601 27 my $n = $interval->{n};
602 27 my $unit = $interval->{unit};
603  
604 27 ▶ if (defined $interval->{secs}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $interval->{"secs"}) 3 24 27
605 3 my $step = $n * $interval->{secs};
606 3 return _iso_second_label(floor($t->{epoch} / $step) * $step);
607 }
608  
609 24 my @lt = localtime($t->{epoch});
610 24 my ($y, $mon, $day) = ($lt[5] + 1900, $lt[4] + 1, $lt[3]);
611  
612 24 ▶ if ($unit eq 'd') {
Branch: 1 branch
BranchTrueFalseTotal
if ($unit eq "d") 5 19 24
613 5 ▶ return sprintf('%04d-%02d-%02d', $y, $mon, $day) if $n == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $n == 1 1 4 5
614 4 my $day_no = _civil_day($y, $mon, $day);
615 4 return sprintf('%04d-%02d-%02d', _shift_days($y, $mon, $day, -($day_no % $n)));
616 }
617  
618 19 ▶ if ($unit eq 'w') {
Branch: 1 branch
BranchTrueFalseTotal
if ($unit eq "w") 6 13 19
619 # Monday is the first day of the ISO week, and 1970-01-05 is the
620 # Monday the week count runs from.
621 6 require POSIX;
622 6 local $!; # mktime and localtime may set errno; see _epoch_of
623 6 my $dow = (localtime(POSIX::mktime(12, 0, 0, $day, $mon - 1, $y - 1900)))[6];
624 6 my $day_no = _civil_day($y, $mon, $day);
625 6 ▶ my $monday = $day_no - ($dow == 0 ? 6 : $dow - 1);
Branch: 1 branch
BranchTrueFalseTotal
$dow == 0 ? : 1 5 6
626 6 my $weeks = floor(($monday - 4) / 7);
627 6 my $start = $monday - ($weeks % $n) * 7;
628 6 return sprintf('%04d-%02d-%02d', _shift_days($y, $mon, $day, $start - $day_no));
629 }
630  
631 # A month count runs from January 1970, and a quarter count from its first
632 # quarter, so the buckets line up with the calendar at every width and not
633 # only when the count is one.
634 13 ▶ if ($unit eq 'mon') {
Branch: 1 branch
BranchTrueFalseTotal
if ($unit eq "mon") 6 7 13
635 6 my $idx = ($y - 1970) * 12 + ($mon - 1);
636 6 my $lo = $idx - ($idx % $n);
637 6 return sprintf('%04d-%02d-01', 1970 + floor($lo / 12), $lo % 12 + 1);
638 }
639  
640 7 ▶ if ($unit eq 'q') {
Branch: 1 branch
BranchTrueFalseTotal
if ($unit eq "q") 5 2 7
641 5 my $qi = ($y - 1970) * 4 + int(($mon - 1) / 3);
642 5 my $lo = $qi - ($qi % $n);
643 5 return sprintf('%04d-%02d-01', 1970 + floor($lo / 4), ($lo % 4) * 3 + 1);
644 }
645  
646 2 return sprintf('%04d-01-01', $y - ($y % $n));
647 }
648  
649 # ---------------------------------------------------------------------------
650 # Constructor
651 # ---------------------------------------------------------------------------
652  
653 406 ▶sub new {
Subroutine new: called CC=12 SCAR=24.8
Pod documented
654 406 my ($class, %args) = @_;
655 # A bad expression is an answer here, not an exception, so nothing of the
656 # compile may reach the caller's $@.
657 406 local $@;
658 # Takes off the where-it-happened tail that croak adds. A path can hold spaces,
659 # and this text reaches the reader, so the tail is everything from the last
660 # " at " on rather than one word.
661 65 ▶ my $tidy = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
662 65 my ($err) = @_;
663 65 $err =~ s/\A(.*) at .+? line \d+\.?\n?\z/$1/s;
664 65 return $err;
665 406 };
666  
667 406 my $self = bless {
668 _error => undef,
669 _code => undef,
670 _columns => {},
671 _params => {},
672 }, $class;
673  
674 406 ▶ my $expr = $args{expr} // '';
Condition100%2/2
$args{"expr"} // ""
l!l
4051
MC/DC100%1/1
$args{"expr"} // ""
$args{"expr"}
Truth table100%2/2
A
A= $args{"expr"}
Aresult
11
00
675 406 ▶ my @cols = @{ $args{columns} // [] };
Condition100%2/2
$args{"columns"} // []
l!l
3979
MC/DC100%1/1
$args{"columns"} // []
$args{"columns"}
Truth table100%2/2
A
A= $args{"columns"}
Aresult
11
00
676 406 ▶ my %params = %{ $args{params} // {} };
Condition100%2/2
$args{"params"} // {}
l!l
35371
MC/DC100%1/1
$args{"params"} // {}
$args{"params"}
Truth table100%2/2
A
A= $args{"params"}
Aresult
11
00
677 406 $self->{_columns}{$_} = 1 for @cols;
678  
679 # A name that is both a column and a parameter is an error: the ambiguity
680 # would be resolved silently in whichever direction, making expressions
681 # non-deterministic when the data changes.
682 406 for my $p (keys %params) {
683 5 ▶ if ($self->{_columns}{$p}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_columns"}{$p}) 2 3 5
684 2 $self->{_error} = _fmt('error_param_col_clash', $p);
685 2 return $self;
686 }
687 }
688 # Extend the compile-time column whitelist with param names so _parse_colref
689 # accepts them as identifiers; at evaluate() time their values come from
690 # _params rather than the row hashref.
691 404 $self->{_columns}{$_} = 1 for keys %params;
692 404 $self->{_params} = \%params;
693  
694 404 ▶ if (length($expr) > $MAX_EXPR_LEN) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $expr > $MAX_EXPR_LEN) 4 400 404
695 4 $self->{_error} = _fmt('error_expr_too_long', $MAX_EXPR_LEN);
696 4 return $self;
697 }
698  
699 400 my $tokens;
700 400 my $ok = eval { $tokens = _tokenize($expr); 1 };
701 400 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 13 387 400
702 13 $self->{_error} = $tidy->($@);
703 13 return $self;
704 }
705  
706 387 my $pos = 0;
707 387 my $depth = 0;
708 387 my $code;
709 387 $ok = eval { $code = _parse_cmp($tokens, \$pos, \$depth, $self->{_columns}); 1 };
710 387 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 52 335 387
711 52 $self->{_error} = $tidy->($@);
712 52 return $self;
713 }
714  
715 335 ▶ if ($tokens->[$pos]{type} ne $T_EOF) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tokens->[$pos]{"type"} ne $T_EOF) 3 332 335
716 $self->{_error} = _fmt('error_trailing',
717 3 $tokens->[$pos]{val}, $tokens->[$pos]{pos});
718 3 return $self;
719 }
720  
721 332 $self->{_code} = $code;
722 332 return $self;
723 }
724  
725 # ---------------------------------------------------------------------------
726 # Public API
727 # ---------------------------------------------------------------------------
728  
729 129 ▶sub error { $_[0]->{_error} }
Subroutine error: called CC=1 SCAR=0.0
Pod documented
730 296 ▶sub has_error { defined $_[0]->{_error} }
Subroutine has_error: called CC=1 SCAR=0.0
Pod documented
731  
732 400 ▶sub evaluate {
Subroutine evaluate: called CC=6 SCAR=17.9
Pod documented
733 400 my ($self, $row) = @_;
734 400 ▶ return undef unless defined $self->{_code};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"_code"} 7 393 400
735 393 ▶ $row //= {};
Condition100%2/2
$row //= {}
l!l
3912
MC/DC100%1/1
$row //= {}
$row
Truth table100%2/2
A
A= $row
Aresult
11
00
736 393 ▶ return undef unless ref $row eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 1 392 393
737 392 local $@; # a failed row is undef, and the caller's $@ is its own
738 392 local $!; # the date functions call mktime and localtime, which may set errno
739 # Merge bound parameters into the evaluation context. Parameters take
740 # precedence over same-named columns: the clash check in new() ensures this
741 # never happens legitimately, but a column added to the data after compile
742 # time should still see the parameter value.
743 392 my $ctx = %{ $self->{_params} }
744 392 ▶ ? { %$row, %{ $self->{_params} } }
Branch: 1 branch
BranchTrueFalseTotal
%{$self->{'_params'};} ? : 5 387 392
745 : $row;
746 392 my $result;
747 392 my $ok = eval { $result = $self->{_code}->($ctx); 1 };
748 392 ▶ return undef unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 3 389 392
749 389 return $result;
750 }
751  
752 # ---------------------------------------------------------------------------
753 # Tokenizer
754 # ---------------------------------------------------------------------------
755  
756 420 ▶sub _tokenize {
Subroutine _tokenize: called CC=18 SCAR=28.9
757 420 my ($expr) = @_;
758 420 my @tokens;
759 420 my $pos = 0;
760 420 my $len = length($expr);
761 420 my %single_ops = (
762 '+' => $T_PLUS, '-' => $T_MINUS,
763 '*' => $T_STAR, '/' => $T_SLASH,
764 '(' => $T_LPAREN, ')' => $T_RPAREN, ',' => $T_COMMA,
765 );
766  
767 420 ▶ while ($pos < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $len) 4237 389 4626
768 4237 my $ch = substr($expr, $pos, 1);
769  
770 # skip whitespace
771 4237 ▶ if ($ch =~ /\A\s/) { $pos++; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($ch =~ /\A\s/) 542 3695 4237
772  
773 # number literal (integer, decimal, scientific)
774 3695 ▶ if (substr($expr, $pos) =~ /\A(\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($expr, $pos) =~ /\A(\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/) 502 3193 3695
775 502 push @tokens, { type => $T_NUM, val => $1, pos => $pos };
776 502 $pos += length($1);
777 502 next;
778 }
779  
780 # double-quoted string
781 3193 ▶ if ($ch eq '"') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq "\"") 10 3183 3193
782 10 my $end = index($expr, '"', $pos + 1);
783 10 ▶ croak _fmt('error_unterminated', $pos) if $end < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 2 8 10
784 8 push @tokens, {
785 type => $T_STR,
786 val => substr($expr, $pos + 1, $end - $pos - 1),
787 pos => $pos,
788 };
789 8 $pos = $end + 1;
790 8 next;
791 }
792  
793 # single-quoted string
794 3183 ▶ if ($ch eq "'") {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq "'") 62 3121 3183
795 62 my $end = index($expr, "'", $pos + 1);
796 62 ▶ croak _fmt('error_unterminated', $pos) if $end < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 1 61 62
797 61 push @tokens, {
798 type => $T_STR,
799 val => substr($expr, $pos + 1, $end - $pos - 1),
800 pos => $pos,
801 };
802 61 $pos = $end + 1;
803 61 next;
804 }
805  
806 # identifier: letters/digits/underscore, leading letter or _
807 3121 ▶ if (substr($expr, $pos) =~ /\A([a-zA-Z_][a-zA-Z0-9_]*)/) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($expr, $pos) =~ /\A([a-zA-Z_][a-zA-Z0-9_]*)/) 667 2454 3121
808 667 push @tokens, { type => $T_IDENT, val => $1, pos => $pos };
809 667 $pos += length($1);
810 667 next;
811 }
812  
813 # two-character comparison operators (must be tested before single-char)
814 2454 ▶ if ($pos + 1 < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos + 1 < $len) 2231 223 2454
815 2231 my $two = substr($expr, $pos, 2);
816 2231 ▶ if ($two eq '!=') {
Branch: 1 branch
BranchTrueFalseTotal
if ($two eq "!=") 12 2219 2231
817 12 push @tokens, { type => $T_NEQ, val => '!=', pos => $pos };
818 12 $pos += 2; next;
819 }
820 2219 ▶ if ($two eq '<=') {
Branch: 1 branch
BranchTrueFalseTotal
if ($two eq "<=") 27 2192 2219
821 27 push @tokens, { type => $T_LE, val => '<=', pos => $pos };
822 27 $pos += 2; next;
823 }
824 2192 ▶ if ($two eq '>=') {
Branch: 1 branch
BranchTrueFalseTotal
if ($two eq ">=") 13 2179 2192
825 13 push @tokens, { type => $T_GE, val => '>=', pos => $pos };
826 13 $pos += 2; next;
827 }
828 2179 ▶ if ($two eq '==') {
Branch: 1 branch
BranchTrueFalseTotal
if ($two eq "==") 5 2174 2179
829 5 croak _fmt('error_double_eq', $pos);
830 }
831 }
832  
833 # single-character comparison operators
834 2397 ▶ if ($ch eq '=') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq "=") 17 2380 2397
835 17 push @tokens, { type => $T_EQ, val => '=', pos => $pos };
836 17 $pos++; next;
837 }
838 2380 ▶ if ($ch eq '<') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq "<") 23 2357 2380
839 23 push @tokens, { type => $T_LT, val => '<', pos => $pos };
840 23 $pos++; next;
841 }
842 2357 ▶ if ($ch eq '>') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq ">") 27 2330 2357
843 27 push @tokens, { type => $T_GT, val => '>', pos => $pos };
844 27 $pos++; next;
845 }
846  
847 # single-character arithmetic operators and punctuation
848 2330 ▶ if (exists $single_ops{$ch}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $single_ops{$ch}) 2307 23 2330
849 2307 push @tokens, { type => $single_ops{$ch}, val => $ch, pos => $pos };
850 2307 $pos++;
851 2307 next;
852 }
853  
854 23 croak _fmt('error_bad_char', $ch, $pos);
855 }
856  
857 389 push @tokens, { type => $T_EOF, val => '', pos => $pos };
858 389 return \@tokens;
859 }
860  
861 # ---------------------------------------------------------------------------
862 # Parser (each _parse_* returns a coderef sub { my ($row) = @_; ... })
863 # ---------------------------------------------------------------------------
864  
865 1720 ▶sub _check_depth {
Subroutine _check_depth: called CC=2 SCAR=6.9
866 1720 my ($depth_ref) = @_;
867 1720 ▶ croak _fmt('error_expr_too_deep', $MAX_DEPTH) if $$depth_ref >= $MAX_DEPTH;
Branch: 1 branch
BranchTrueFalseTotal
if $$depth_ref >= $MAX_DEPTH 6 1714 1720
868 }
869  
870 213 ▶sub _expect {
Subroutine _expect: called CC=2 SCAR=6.9
871 213 my ($tokens, $pos_ref, $expected) = @_;
872 213 my $tok = $tokens->[$$pos_ref];
873 croak _fmt('error_expected_tok', $expected, $tok->{pos}, $tok->{val})
874 213 ▶ unless $tok->{type} eq $expected;
Branch: 1 branch
BranchTrueFalseTotal
unless $tok->{"type"} eq $expected 3 210 213
875 210 $$pos_ref++;
876 }
877  
878 # cmp_expr ::= add_expr (cmp_op add_expr)?
879 # Comparison yields 1 (true), 0 (false), or undef (either operand undef).
880 # When both operands look numeric, numeric comparison is used; otherwise
881 # case-insensitive string comparison, matching _apply_filter_spec semantics.
882 774 ▶sub _parse_cmp {
Subroutine _parse_cmp: called CC=7 SCAR=19.5
883 774 my ($tokens, $pos_ref, $depth_ref, $cols) = @_;
884 774 _check_depth($depth_ref);
885 771 $$depth_ref++;
886  
887 771 my $left = _parse_add($tokens, $pos_ref, $depth_ref, $cols);
888  
889 692 my $type = $tokens->[$$pos_ref]{type};
890 692 ▶ if ($type eq $T_EQ || $type eq $T_NEQ
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT or $type eq $T_LE or $type eq $T_GT or $type eq $T_GE) 112 580 692
Condition100%15/15
$type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT or $type eq $T_LE or $type eq $T_GT or $type eq $T_GE
l!l&&r!l&&!r
10012580
$type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT or $type eq $T_LE or $type eq $T_GT
l!l&&r!l&&!r
7426592
$type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT or $type eq $T_LE
l!l&&r!l&&!r
4826618
$type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT
l!l&&r!l&&!r
2721644
$type eq $T_EQ or $type eq $T_NEQ
l!l&&r!l&&!r
1611665
MC/DC100%6/6
$type eq $T_EQ or $type eq $T_NEQ or $type eq $T_LT or $type eq $T_LE or $type eq $T_GT or $type eq $T_GE
$type eq $T_EQ $type eq $T_NEQ $type eq $T_LT $type eq $T_LE $type eq $T_GT $type eq $T_GE
Truth table100%7/7
A or B or C or D or E or F
A= $type eq $T_EQB= $type eq $T_NEQC= $type eq $T_LTD= $type eq $T_LEE= $type eq $T_GTF= $type eq $T_GE
ABCDEFresult
1XXXXX1
01XXXX1
001XXX1
0001XX1
00001X1
0000011
0000000
891 || $type eq $T_LT || $type eq $T_LE
892 || $type eq $T_GT || $type eq $T_GE) {
893 112 my $op = $type;
894 112 $$pos_ref++;
895 112 my $right = _parse_add($tokens, $pos_ref, $depth_ref, $cols);
896 112 my ($l, $r) = ($left, $right);
897 109 ▶ $left = sub {
Subroutine __ANON__: called CC=27 SCAR=33.4
898 109 my $lv = $l->($_[0]);
899 109 my $rv = $r->($_[0]);
900 109 ▶ return undef unless defined $lv && defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv and defined $rv 3 106 109
Condition100%3/3
defined $lv and defined $rv
!ll&&!rl&&r
21106
MC/DC100%2/2
defined $lv and defined $rv
defined $lv defined $rv
Truth table100%3/3
A and B
A= defined $lvB= defined $rv
ABresult
0X0
100
111
901 106 ▶ if (looks_like_number($lv) && looks_like_number($rv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&looks_like_number($lv) and &looks_like_number($rv)) { } 98 8 106
Condition66%2/3
&looks_like_number($lv) and &looks_like_number($rv)
!ll&&!rl&&r
8098
MC/DC50%1/2
&looks_like_number($lv) and &looks_like_number($rv)
&looks_like_number($lv) &looks_like_number($rv)
Truth table66%2/3
A and B
A= &looks_like_number($lv)B= &looks_like_number($rv)
ABresult
0X0
100
111
902 98 ▶ return $op eq $T_EQ ? ($lv == $rv ? 1 : 0)
Branch: 11 branches
BranchTrueFalseTotal
$op eq $T_EQ ? : 11 87 98
$lv == $rv ? : 6 5 11
$op eq $T_NEQ ? : 10 77 87
$lv != $rv ? : 5 5 10
$op eq $T_LT ? : 18 59 77
$lv < $rv ? : 5 13 18
$op eq $T_LE ? : 23 36 59
$lv <= $rv ? : 16 7 23
$op eq $T_GT ? : 25 11 36
$lv > $rv ? : 12 13 25
$lv >= $rv ? : 7 4 11
903 : $op eq $T_NEQ ? ($lv != $rv ? 1 : 0)
904 : $op eq $T_LT ? ($lv < $rv ? 1 : 0)
905 : $op eq $T_LE ? ($lv <= $rv ? 1 : 0)
906 : $op eq $T_GT ? ($lv > $rv ? 1 : 0)
907 : ($lv >= $rv ? 1 : 0);
908 } else {
909 8 my $cmp = lc($lv) cmp lc($rv);
910 8 ▶ return $op eq $T_EQ ? ($cmp == 0 ? 1 : 0)
Branch: 11 branches
BranchTrueFalseTotal
$op eq $T_EQ ? : 2 6 8
$cmp == 0 ? : 2 0 2
$op eq $T_NEQ ? : 1 5 6
$cmp != 0 ? : 0 1 1
$op eq $T_LT ? : 2 3 5
$cmp < 0 ? : 2 0 2
$op eq $T_LE ? : 1 2 3
$cmp <= 0 ? : 1 0 1
$op eq $T_GT ? : 1 1 2
$cmp > 0 ? : 0 1 1
$cmp >= 0 ? : 1 0 1
911 : $op eq $T_NEQ ? ($cmp != 0 ? 1 : 0)
912 : $op eq $T_LT ? ($cmp < 0 ? 1 : 0)
913 : $op eq $T_LE ? ($cmp <= 0 ? 1 : 0)
914 : $op eq $T_GT ? ($cmp > 0 ? 1 : 0)
915 : ($cmp >= 0 ? 1 : 0);
916 }
917 112 };
918 }
919  
920 692 $$depth_ref--;
921 692 return $left;
922 }
923  
924 # add_expr ::= term ( ('+' | '-') term )*
925 883 ▶sub _parse_add {
Subroutine _parse_add: called CC=4 SCAR=14.4
926 883 my ($tokens, $pos_ref, $depth_ref, $cols) = @_;
927 883 _check_depth($depth_ref);
928 883 $$depth_ref++;
929  
930 883 my $left = _parse_term($tokens, $pos_ref, $depth_ref, $cols);
931  
932 806 ▶ while ($tokens->[$$pos_ref]{type} eq $T_PLUS
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} eq $T_PLUS or $$tokens[$$pos_ref]{"type"} eq $T_MINUS) 235 804 1039
Condition100%3/3
$$tokens[$$pos_ref]{"type"} eq $T_PLUS or $$tokens[$$pos_ref]{"type"} eq $T_MINUS
l!l&&r!l&&!r
2278804
MC/DC100%2/2
$$tokens[$$pos_ref]{"type"} eq $T_PLUS or $$tokens[$$pos_ref]{"type"} eq $T_MINUS
$$tokens[$$pos_ref]{"type"} eq $T_PLUS $$tokens[$$pos_ref]{"type"} eq $T_MINUS
Truth table100%3/3
A or B
A= $$tokens[$$pos_ref]{"type"} eq $T_PLUSB= $$tokens[$$pos_ref]{"type"} eq $T_MINUS
ABresult
1X1
011
000
933 || $tokens->[$$pos_ref]{type} eq $T_MINUS) {
934 235 my $op = $tokens->[$$pos_ref]{type};
935 235 $$pos_ref++;
936 235 my $right = _parse_term($tokens, $pos_ref, $depth_ref, $cols);
937 233 my ($l, $r) = ($left, $right);
938 233 ▶ if ($op eq $T_PLUS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq $T_PLUS) { } 225 8 233
939 3 ▶ $left = sub {
Subroutine __ANON__: called CC=5 SCAR=18.9
940 3 my $lv = $l->($_[0]); my $rv = $r->($_[0]);
941 3 ▶ return undef unless defined $lv && defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv and defined $rv 0 3 3
Condition33%1/3
defined $lv and defined $rv
!ll&&!rl&&r
003
MC/DC0%0/2
defined $lv and defined $rv
defined $lv defined $rv
Truth table33%1/3
A and B
A= defined $lvB= defined $rv
ABresult
0X0
100
111
942 3 ▶ return undef unless looks_like_number($lv) && looks_like_number($rv);
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($lv) and &looks_like_number($rv) 0 3 3
Condition33%1/3
&looks_like_number($lv) and &looks_like_number($rv)
!ll&&!rl&&r
003
MC/DC0%0/2
&looks_like_number($lv) and &looks_like_number($rv)
&looks_like_number($lv) &looks_like_number($rv)
Truth table33%1/3
A and B
A= &looks_like_number($lv)B= &looks_like_number($rv)
ABresult
0X0
100
111
943 3 $lv + $rv;
944 225 };
945 } else {
946 6 ▶ $left = sub {
Subroutine __ANON__: called CC=5 SCAR=18.9
947 6 my $lv = $l->($_[0]); my $rv = $r->($_[0]);
948 6 ▶ return undef unless defined $lv && defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv and defined $rv 0 6 6
Condition33%1/3
defined $lv and defined $rv
!ll&&!rl&&r
006
MC/DC0%0/2
defined $lv and defined $rv
defined $lv defined $rv
Truth table33%1/3
A and B
A= defined $lvB= defined $rv
ABresult
0X0
100
111
949 6 ▶ return undef unless looks_like_number($lv) && looks_like_number($rv);
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($lv) and &looks_like_number($rv) 0 6 6
Condition33%1/3
&looks_like_number($lv) and &looks_like_number($rv)
!ll&&!rl&&r
006
MC/DC0%0/2
&looks_like_number($lv) and &looks_like_number($rv)
&looks_like_number($lv) &looks_like_number($rv)
Truth table33%1/3
A and B
A= &looks_like_number($lv)B= &looks_like_number($rv)
ABresult
0X0
100
111
950 6 $lv - $rv;
951 8 };
952 }
953 }
954  
955 804 $$depth_ref--;
956 804 return $left;
957 }
958  
959 # term ::= factor ( ('*' | '/') factor )*
960 1118 ▶sub _parse_term {
Subroutine _parse_term: called CC=4 SCAR=13.9
961 1118 my ($tokens, $pos_ref, $depth_ref, $cols) = @_;
962  
963 1118 my $left = _parse_factor($tokens, $pos_ref, $depth_ref, $cols);
964  
965 1039 ▶ while ($tokens->[$$pos_ref]{type} eq $T_STAR
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} eq $T_STAR or $$tokens[$$pos_ref]{"type"} eq $T_SLASH) 37 1039 1076
Condition100%3/3
$$tokens[$$pos_ref]{"type"} eq $T_STAR or $$tokens[$$pos_ref]{"type"} eq $T_SLASH
l!l&&r!l&&!r
21161039
MC/DC100%2/2
$$tokens[$$pos_ref]{"type"} eq $T_STAR or $$tokens[$$pos_ref]{"type"} eq $T_SLASH
$$tokens[$$pos_ref]{"type"} eq $T_STAR $$tokens[$$pos_ref]{"type"} eq $T_SLASH
Truth table100%3/3
A or B
A= $$tokens[$$pos_ref]{"type"} eq $T_STARB= $$tokens[$$pos_ref]{"type"} eq $T_SLASH
ABresult
1X1
011
000
966 || $tokens->[$$pos_ref]{type} eq $T_SLASH) {
967 37 my $op = $tokens->[$$pos_ref]{type};
968 37 $$pos_ref++;
969 37 my $right = _parse_factor($tokens, $pos_ref, $depth_ref, $cols);
970 37 my ($l, $r) = ($left, $right);
971 37 ▶ if ($op eq $T_STAR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq $T_STAR) { } 21 16 37
972 $left = sub {
973 my $lv = $l->($_[0]); my $rv = $r->($_[0]);
974 return undef unless defined $lv && defined $rv;
975 return undef unless looks_like_number($lv) && looks_like_number($rv);
976 $lv * $rv;
977 21 };
978 } else {
979 $left = sub {
980 my $lv = $l->($_[0]); my $rv = $r->($_[0]);
981 return undef unless defined $lv && defined $rv;
982 return undef unless looks_like_number($lv) && looks_like_number($rv);
983 return undef if $rv == 0;
984 $lv / $rv;
985 16 };
986 }
987 }
988  
989 1039 return $left;
990 }
991  
992 # factor ::= unary | '(' cmp_expr ')' | number | string | column | call
993 1241 ▶sub _parse_factor {
Subroutine _parse_factor: called CC=8 SCAR=20.8
994 1241 my ($tokens, $pos_ref, $depth_ref, $cols) = @_;
995 1241 my $tok = $tokens->[$$pos_ref];
996  
997 # unary minus
998 1241 ▶ if ($tok->{type} eq $T_MINUS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_MINUS) 41 1200 1241
999 66 $$pos_ref++;
1000 66 _check_depth($depth_ref);
1001 48 $$depth_ref++;
1002 48 my $inner = _parse_factor($tokens, $pos_ref, $depth_ref, $cols);
1003 30 $$depth_ref--;
1004 return sub {
1005 my $v = $inner->($_[0]);
1006 return undef unless defined $v && looks_like_number($v);
1007 -$v;
1008 30 };
1009 }
1010  
1011 # unary plus (no-op)
1012 1183 ▶ if ($tok->{type} eq $T_PLUS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_PLUS) 21 1179 1200
1013 21 $$pos_ref++;
1014 21 _check_depth($depth_ref);
1015 20 $$depth_ref++;
1016 20 my $inner = _parse_factor($tokens, $pos_ref, $depth_ref, $cols);
1017 2 $$depth_ref--;
1018 2 return $inner;
1019 }
1020  
1021 # parenthesized sub-expression: allow full cmp_expr so (qty > 0) works
1022 1153 ▶ if ($tok->{type} eq $T_LPAREN) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_LPAREN) 28 1134 1162
1023 28 $$pos_ref++;
1024 28 my $inner = _parse_cmp($tokens, $pos_ref, $depth_ref, $cols);
1025 8 _expect($tokens, $pos_ref, $T_RPAREN);
1026 7 return $inner;
1027 }
1028  
1029 # number literal
1030 1125 ▶ if ($tok->{type} eq $T_NUM) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_NUM) 468 666 1134
1031 468 my $val = $tok->{val} + 0;
1032 468 $$pos_ref++;
1033 468 return sub { $val };
1034 }
1035  
1036 # string literal
1037 657 ▶ if ($tok->{type} eq $T_STR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_STR) 58 608 666
1038 49 my $val = $tok->{val};
1039 49 $$pos_ref++;
1040 49 return sub { $val };
1041 }
1042  
1043 # identifier -- function call or column reference
1044 608 ▶ if ($tok->{type} eq $T_IDENT) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok->{"type"} eq $T_IDENT) 604 4 608
1045 604 my $name = $tok->{val};
1046 604 $$pos_ref++;
1047 return $tokens->[$$pos_ref]{type} eq $T_LPAREN
1048 ? _parse_call($tokens, $pos_ref, $depth_ref, $cols, $name, $tok->{pos})
1049 604 ▶ : _parse_colref($cols, $name, $tok->{pos});
Branch: 1 branch
BranchTrueFalseTotal
$$tokens[$$pos_ref]{'type'} eq $T_LPAREN ? : 226 378 604
1050 }
1051  
1052 4 croak _fmt('error_unexpected_tok', $tok->{val}, $tok->{pos});
1053 }
1054  
1055 # Parse a function call. 'if' is a special form (short-circuit branches).
1056 # Arguments may be full cmp_expr (e.g. IF(qty > 0, amount/qty, 0)).
1057 235 ▶sub _parse_call {
Subroutine _parse_call: called CC=23 SCAR=37.0
1058 226 my ($tokens, $pos_ref, $depth_ref, $cols, $name, $name_pos) = @_;
1059 226 my $lc = lc($name);
1060  
1061 croak _fmt('error_unknown_fn', $name)
1062 226 ▶ unless exists $FUNCTIONS{$lc} || $lc eq 'if' || $lc eq 'rx' || $TIME_CONST_FNS{$lc};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $FUNCTIONS{$lc} or $lc eq "if" or $lc eq "rx" or $TIME_CONST_FNS{$lc} 11 215 226
Condition88%8/9
exists $FUNCTIONS{$lc} or $lc eq "if" or $lc eq "rx" or $TIME_CONST_FNS{$lc}
l!l&&r!l&&!r
2031337
exists $FUNCTIONS{$lc} or $lc eq "if" or $lc eq "rx"
l!l&&r!l&&!r
202050
exists $FUNCTIONS{$lc} or $lc eq "if"
l!l&&r!l&&!r
1584433
MC/DC75%3/4
exists $FUNCTIONS{$lc} or $lc eq "if" or $lc eq "rx" or $TIME_CONST_FNS{$lc}
exists $FUNCTIONS{$lc} $lc eq "if" $lc eq "rx" $TIME_CONST_FNS{$lc}
Truth table80%4/5
A or B or C or D
A= exists $FUNCTIONS{$lc}B= $lc eq "if"C= $lc eq "rx"D= $TIME_CONST_FNS{$lc}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1063  
1064 # rx(v, 'pattern' [, 'group']): the pattern and the group are constants,
1065 # so the pattern is checked and compiled once, here. A group the pattern
1066 # does not have is undef on every row rather than an error, as the POD says.
1067 274 ▶ if ($lc eq 'rx') {
Branch: 1 branch
BranchTrueFalseTotal
if ($lc eq "rx") 0 215 215
1068 4 $$pos_ref++; # consume '('
1069 0 my $value_fn = _parse_cmp($tokens, $pos_ref, $depth_ref, $cols);
1070 0 my @const;
1071 0 ▶ while ($tokens->[$$pos_ref]{type} eq $T_COMMA) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} eq $T_COMMA) 0 0 0
1072 0 $$pos_ref++;
1073 0 my $tok = $tokens->[$$pos_ref];
1074 croak _fmt('error_rx_args')
1075 0 ▶ unless $tok->{type} eq $T_STR || $tok->{type} eq $T_NUM;
Branch: 1 branch
BranchTrueFalseTotal
unless $tok->{"type"} eq $T_STR or $tok->{"type"} eq $T_NUM 0 0 0
Condition33%1/3
$tok->{"type"} eq $T_STR or $tok->{"type"} eq $T_NUM
l!l&&r!l&&!r
009
MC/DC0%0/2
$tok->{"type"} eq $T_STR or $tok->{"type"} eq $T_NUM
$tok->{"type"} eq $T_STR $tok->{"type"} eq $T_NUM
Truth table0%0/3
A or B
A= $tok->{"type"} eq $T_STRB= $tok->{"type"} eq $T_NUM
ABresult
1X1
011
000
1076 0 push @const, $tok->{val};
1077 0 $$pos_ref++;
1078 }
1079 0 _expect($tokens, $pos_ref, $T_RPAREN);
1080 0 ▶ croak _fmt('error_rx_args') unless @const == 1 || @const == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @const == 1 or @const == 2 0 0 0
Condition0%0/3
@const == 1 or @const == 2
l!l&&r!l&&!r
000
MC/DC0%0/2
@const == 1 or @const == 2
@const == 1 @const == 2
Truth table0%0/3
A or B
A= @const == 1B= @const == 2
ABresult
1X1
011
000
1081 0 my $compiled = compile_pattern($const[0]);
1082 0 ▶ my $group = defined $const[1] ? $const[1] : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $const[1] ? : 0 0 0
1083 0 ▶ return sub { capture_of($compiled, $value_fn->($_[0]), $group) };
Subroutine __ANON__: called CC=1 SCAR=6.9
1084 }
1085  
1086 # epoch(v [, fmt]) and span(v, interval) take a constant second argument:
1087 # a format or an interval. It is checked here, once per column rather than
1088 # once per row, so a bad one is a compile error that names it -- and the
1089 # pattern is compiled once instead of on every value.
1090 215 ▶ if ($TIME_CONST_FNS{$lc}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($TIME_CONST_FNS{$lc}) 13 202 215
1091 13 $$pos_ref++; # consume '('
1092 13 my $value_fn = _parse_cmp($tokens, $pos_ref, $depth_ref, $cols);
1093 13 my $const;
1094 13 ▶ if ($tokens->[$$pos_ref]{type} eq $T_COMMA) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} eq $T_COMMA) 10 3 13
1095 10 $$pos_ref++;
1096 10 my $tok = $tokens->[$$pos_ref];
1097 croak _fmt('error_const_arg', $name)
1098 10 ▶ unless $tok->{type} eq $T_STR;
Branch: 1 branch
BranchTrueFalseTotal
unless $tok->{"type"} eq $T_STR 2 8 10
1099 8 $const = $tok->{val};
1100 8 $$pos_ref++;
1101 }
1102 11 _expect($tokens, $pos_ref, $T_RPAREN);
1103  
1104 11 ▶ if ($lc eq 'epoch') {
Branch: 1 branch
BranchTrueFalseTotal
if ($lc eq "epoch") 5 6 11
1105 5 ▶ my $compiled = defined $const ? _fmt_compile($const) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $const ? : 3 2 5
1106 4 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=24.8
1107 0 my $value = $value_fn->($_[0]);
1108 0 ▶ my $t = defined $compiled
Branch: 1 branch
BranchTrueFalseTotal
defined $compiled ? : 0 0 0
1109 ? _time_from_format($value, $compiled)
1110 : _parse_time($value);
1111 0 ▶ return defined $t ? $t->{epoch} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $t ? : 0 0 0
1112 4 };
1113 }
1114  
1115 6 ▶ my $interval = defined $const ? span_interval($const) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $const ? : 5 1 6
1116 6 ▶ croak _fmt('error_span_interval', defined $const ? $const : '')
Branch: 2 branches
BranchTrueFalseTotal
unless $interval 3 3 6
defined $const ? : 2 1 3
1117 unless $interval;
1118 3 ▶ return sub { _span_label($value_fn->($_[0]), $interval) };
Subroutine __ANON__: called CC=1 SCAR=0.0
1119 }
1120  
1121 202 $$pos_ref++; # consume '('
1122 202 my @arg_fns;
1123 202 ▶ if ($tokens->[$$pos_ref]{type} ne $T_RPAREN) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} ne $T_RPAREN) 198 4 202
1124 198 push @arg_fns, _parse_cmp($tokens, $pos_ref, $depth_ref, $cols);
1125 188 ▶ while ($tokens->[$$pos_ref]{type} eq $T_COMMA) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$tokens[$$pos_ref]{"type"} eq $T_COMMA) 148 188 336
1126 148 $$pos_ref++;
1127 148 push @arg_fns, _parse_cmp($tokens, $pos_ref, $depth_ref, $cols);
1128 }
1129 }
1130 192 _expect($tokens, $pos_ref, $T_RPAREN);
1131  
1132 # 'if' special form: short-circuit true/false branches
1133 191 ▶ if ($lc eq 'if') {
Branch: 1 branch
BranchTrueFalseTotal
if ($lc eq "if") 44 147 191
1134 44 my ($cond_fn, $true_fn, $false_fn) = @arg_fns;
1135 36 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1136 36 ▶ $cond_fn->($_[0]) ? $true_fn->($_[0]) : $false_fn->($_[0]);
Branch: 1 branch
BranchTrueFalseTotal
&$cond_fn($_[0]) ? : 18 18 36
1137 44 };
1138 }
1139  
1140 147 my $fn = $FUNCTIONS{$lc};
1141 59 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1142 59 my $row = $_[0];
1143 59 $fn->(map { $_->($row) } @arg_fns);
1144 147 };
1145 }
1146  
1147 # Parse a column reference; validates against the whitelist at compile time.
1148 # Underscores in the expression may match spaces in the actual column name,
1149 # and the comparison is case-insensitive, so per_unit_price can address
1150 # a column named "Per Unit Price".
1151 378 ▶sub _parse_colref {
Subroutine _parse_colref: called CC=4 SCAR=13.9
1152 378 my ($cols, $name, $name_pos) = @_;
1153  
1154 # 1. Exact match
1155 378 ▶ return sub { $_[0]->{$name} } if $cols->{$name};
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if $cols->{$name} 350 28 378
1156  
1157 # 2. Underscore-to-space alias, case-insensitive
1158 28 (my $spaced = $name) =~ s/_/ /g;
1159 28 my $lc_spaced = lc($spaced);
1160 28 for my $col (keys %{$cols}) {
1161 64 ▶ if (lc($col) eq $lc_spaced) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $col eq $lc_spaced) 4 60 64
1162 4 my $lookup = $col;
1163 4 ▶ return sub { $_[0]->{$lookup} };
Subroutine __ANON__: called CC=1 SCAR=0.0
1164 }
1165 }
1166  
1167 24 croak _fmt('error_unknown_col', $name);
1168 }
1169  
1170 # ---------------------------------------------------------------------------
1171 # Standalone date-normalisation helper (used by Dashboard::_apply_date_normalization)
1172 # ---------------------------------------------------------------------------
1173  
1174 # _iso_day_label($epoch) -> 'YYYY-MM-DD' in local time
1175 2 ▶sub _iso_day_label {
Subroutine _iso_day_label: called CC=1 SCAR=0.0
1176 2 my @lt = localtime($_[0]);
1177 2 return sprintf '%04d-%02d-%02d', $lt[5] + 1900, $lt[4] + 1, $lt[3];
1178 }
1179  
1180 # _normalise_with_format($value, \%pattern) -> ISO string or undef
1181 #
1182 # The hash shape of a stored pattern: { date => '<fmt>', [time => '<fmt'>],
1183 # [as => 'timestamp'] }. With a time pattern the value is normalised to
1184 # 'YYYY-MM-DDTHH:MM:SS', which is the shape the date comparisons already read
1185 # to the second; with as => 'timestamp' and no time pattern it is that same
1186 # shape at midnight, so a date-only column can be compared against a
1187 # last_24_hours window.
1188 15 ▶sub _normalise_with_format {
Subroutine _normalise_with_format: called CC=11 SCAR=24.0
1189 15 my ($val, $pattern) = @_;
1190 15 ▶ return undef unless defined $pattern->{date} && length $pattern->{date};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pattern->{"date"} and length $pattern->{"date"} 2 13 15
Condition100%3/3
defined $pattern->{"date"} and length $pattern->{"date"}
!ll&&!rl&&r
1113
MC/DC100%2/2
defined $pattern->{"date"} and length $pattern->{"date"}
defined $pattern->{"date"} length $pattern->{"date"}
Truth table100%3/3
A and B
A= defined $pattern->{"date"}B= length $pattern->{"date"}
ABresult
0X0
100
111
1191  
1192 # The pattern is stored JSON and the caller has no eval: one that cannot be
1193 # compiled is an unknown pattern, which is undef, not a 500 on every page.
1194 13 my $time_fmt = $pattern->{time};
1195 13 ▶ if (defined $time_fmt && length $time_fmt) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $time_fmt and length $time_fmt) 5 8 13
Condition66%2/3
defined $time_fmt and length $time_fmt
!ll&&!rl&&r
805
MC/DC50%1/2
defined $time_fmt and length $time_fmt
defined $time_fmt length $time_fmt
Truth table66%2/3
A and B
A= defined $time_fmtB= length $time_fmt
ABresult
0X0
100
111
1196 5 ▶ my $compiled = eval { _fmt_compile_pair($pattern->{date}, $time_fmt) } or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $compiled = eval { do { _fmt_compile_pair($pattern->{"date"}, $time_fmt) } } or return undef 4 1 5
1197 4 my $t = _time_from_format($val, $compiled);
1198 4 ▶ return undef unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 1 3 4
1199 3 return _iso_second_label($t->{epoch});
1200 }
1201  
1202 8 ▶ my $compiled = eval { _fmt_compile($pattern->{date}) } or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $compiled = eval { do { _fmt_compile($pattern->{"date"}) } } or return undef 5 3 8
1203 5 my $t = _time_from_format($val, $compiled);
1204 5 ▶ return undef unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 2 3 5
1205 return ($pattern->{as} // '') eq 'timestamp'
1206 ? _iso_second_label($t->{epoch})
1207 3 ▶ : _iso_day_label($t->{epoch});
Branch: 1 branch
BranchTrueFalseTotal
($pattern->{'as'} // '') eq 'timestamp' ? : 2 1 3
Condition100%2/2
$pattern->{"as"} // ""
l!l
21
MC/DC100%1/1
$pattern->{"as"} // ""
$pattern->{"as"}
Truth table100%2/2
A
A= $pattern->{"as"}
Aresult
11
00
1208 }
1209  
1210 # _iso_date_if_real($y, $mon, $day) -> 'YYYY-MM-DD' or undef
1211 #
1212 # A UK file read with the US pattern has "months" up to 31. Undef sends it to the
1213 # '(unparseable)' bucket, where it can be seen; "2026-15-01" looks like a date and
1214 # sorts among the real ones.
1215 38 ▶sub _iso_date_if_real {
Subroutine _iso_date_if_real: called CC=2 SCAR=6.9
1216 38 my ($y, $mon, $day) = @_;
1217 38 ▶ return undef unless defined _epoch_of($y + 0, $mon + 0, $day + 0, 12, 0, 0);
Branch: 1 branch
BranchTrueFalseTotal
unless defined _epoch_of($y + 0, $mon + 0, $day + 0, 12, 0, 0) 12 26 38
1218 26 return sprintf('%04d-%02d-%02d', $y, $mon, $day);
1219 }
1220  
1221 # date_normalise($value, $pattern) -> ISO string or undef
1222 #
1223 # Converts $value from the given strptime-style $pattern to ISO-8601.
1224 # Returns undef when $value does not match the pattern or the pattern is
1225 # unknown. No external modules required.
1226 #
1227 # $pattern is either one of the three date patterns below, or a hashref
1228 # { date => ..., time => ..., as => ... } for a column that holds a time as
1229 # well as a date; see _normalise_with_format.
1230 #
1231 # Supported date patterns:
1232 # %m/%d/%Y -- US slash-date (01/15/2026)
1233 # %d/%m/%Y -- EU slash-date (15/01/2026)
1234 # %d-%b-%Y -- DD-Mon-YYYY (15-Jan-2026, case-insensitive month abbrev)
1235 66 ▶sub date_normalise {
Subroutine date_normalise: called CC=12 SCAR=24.8
Pod undocumented
1236 66 my ($val, $pattern) = @_;
1237 66 local $!; # mktime and localtime may set errno; see _epoch_of
1238 66 ▶ return undef unless defined $val && defined $pattern && length $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val and defined $pattern and length $val 8 58 66
Condition100%6/6
defined $val and defined $pattern and length $val
!ll&&!rl&&r
5358
defined $val and defined $pattern
!ll&&!rl&&r
3261
MC/DC100%3/3
defined $val and defined $pattern and length $val
defined $val defined $pattern length $val
Truth table100%4/4
A and B and C
A= defined $valB= defined $patternC= length $val
ABCresult
0XX0
10X0
1100
1111
1239 58 ▶ return _normalise_with_format($val, $pattern) if ref $pattern eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $pattern eq "HASH" 15 43 58
1240 43 ▶ if ($pattern eq '%m/%d/%Y') {
Branch: 3 branches
BranchTrueFalseTotal
if ($pattern eq '%m/%d/%Y') { } 20 23 43
elsif ($pattern eq '%d/%m/%Y') { } 10 13 23
elsif ($pattern eq '%d-%b-%Y') { } 10 3 13
1241 20 ▶ return undef unless $val =~ /\A(\d{1,2})\/(\d{1,2})\/(\d{4})\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $val =~ m[\A(\d{1,2})/(\d{1,2})/(\d{4})\z] 4 16 20
1242 16 return _iso_date_if_real($3, $1, $2);
1243 } elsif ($pattern eq '%d/%m/%Y') {
1244 10 ▶ return undef unless $val =~ /\A(\d{1,2})\/(\d{1,2})\/(\d{4})\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $val =~ m[\A(\d{1,2})/(\d{1,2})/(\d{4})\z] 2 8 10
1245 8 return _iso_date_if_real($3, $2, $1);
1246 } elsif ($pattern eq '%d-%b-%Y') {
1247 10 ▶ return undef unless $val =~ /\A(\d{1,2})-([A-Za-z]{3})-(\d{4})\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $val =~ /\A(\d{1,2})-([A-Za-z]{3})-(\d{4})\z/ 2 8 10
1248 8 my $mon = $_MONTH_NAME_TO_NUM{lc($2)};
1249 8 ▶ return undef unless defined $mon;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mon 2 6 8
1250 6 return _iso_date_if_real($3, $mon, $1);
1251 }
1252 3 return undef;
1253 }
1254  
1255 5 1;
1256  
1257 __END__
« blib/lib/Database/BI/SafeUA.pm ↑ Summary blib/lib/Database/BI/Command/password.pm »