| File: | blib/lib/Database/BI/Calc.pm |
| Coverage: | 97.1% |
| line | stmt | bran | cond | sub | time | code |
|---|---|---|---|---|---|---|
| 1 | package Database::BI::Calc; | |||||
| 2 | ||||||
| 3 | 26 26 26 | 729456 47 260 | use strict; | |||
| 4 | 26 26 26 | 35 23 711 | use warnings; | |||
| 5 | ||||||
| 6 | 26 26 26 | 38 20 556 | use Carp qw(croak); | |||
| 7 | 26 26 26 | 37 17 308 | use POSIX qw(floor ceil); | |||
| 8 | 26 26 26 | 1690 28 133 | use Database::BI::I18N (); | |||
| 9 | 26 26 26 | 29 20 328 | use Readonly; | |||
| 10 | 26 26 26 | 573 22 168 | use Database::BI::Util (); | |||
| 11 | 26 26 26 | 41 18 5792 | use Scalar::Util qw(looks_like_number); | |||
| 12 | ||||||
| 13 | our $VERSION = '0.025.0'; | |||||
| 14 | ||||||
| 15 | Readonly my $MAX_EXPR_LEN => 512; | |||||
| 16 | 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 | 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 | Readonly my $MAX_PATTERN_LEN => 200; | |||||
| 27 | 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 | Readonly my $REFUSED_PATTERN_RE => qr/(?:\A|[^\\])(?:\\\\)*\K(\((?:\?\??\{|\?p|\*))/; | |||||
| 34 | ||||||
| 35 | # --- token type constants --- | |||||
| 36 | Readonly my $T_NUM => 'NUM'; | |||||
| 37 | Readonly my $T_STR => 'STR'; | |||||
| 38 | Readonly my $T_IDENT => 'IDENT'; | |||||
| 39 | Readonly my $T_PLUS => 'PLUS'; | |||||
| 40 | Readonly my $T_MINUS => 'MINUS'; | |||||
| 41 | Readonly my $T_STAR => 'STAR'; | |||||
| 42 | Readonly my $T_SLASH => 'SLASH'; | |||||
| 43 | Readonly my $T_LPAREN => 'LPAREN'; | |||||
| 44 | Readonly my $T_RPAREN => 'RPAREN'; | |||||
| 45 | Readonly my $T_COMMA => 'COMMA'; | |||||
| 46 | Readonly my $T_EOF => 'EOF'; | |||||
| 47 | ||||||
| 48 | # Comparison operator tokens (two-char forms checked before single-char forms) | |||||
| 49 | Readonly my $T_EQ => 'EQ'; # = | |||||
| 50 | Readonly my $T_NEQ => 'NEQ'; # != | |||||
| 51 | Readonly my $T_LT => 'LT'; # < | |||||
| 52 | Readonly my $T_LE => 'LE'; # <= | |||||
| 53 | Readonly my $T_GT => 'GT'; # > | |||||
| 54 | Readonly my $T_GE => 'GE'; # >= | |||||
| 55 | ||||||
| 56 | 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, y, dec or c, 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 | sub _fmt { | |||||
| 79 | 255 | 2244 | my ($key, @args) = @_; | |||
| 80 | 255 | 446 | 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 | 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 | 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 | Readonly my %TIME_CONST_FNS => map { $_ => 1 } qw(epoch span); | |||||
| 113 | ||||||
| 114 | my %FUNCTIONS = ( | |||||
| 115 | # --- string functions --- | |||||
| 116 | upper => sub { defined $_[0] ? uc($_[0]) : undef }, | |||||
| 117 | lower => sub { defined $_[0] ? lc($_[0]) : undef }, | |||||
| 118 | trim => sub { | |||||
| 119 | return undef unless defined $_[0]; | |||||
| 120 | 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 | $s =~ s/\A\s+//; | |||||
| 123 | $s =~ s/\s+\z//; | |||||
| 124 | $s; | |||||
| 125 | }, | |||||
| 126 | len => sub { defined $_[0] ? length($_[0]) : undef }, | |||||
| 127 | concat => sub { join '', map { defined $_ ? $_ : '' } @_ }, | |||||
| 128 | substr => sub { | |||||
| 129 | my ($s, $start, $len) = @_; | |||||
| 130 | return undef unless defined $s; | |||||
| 131 | $start //= 0; | |||||
| 132 | # A start past the end is undef, the empty-cell result; it is not worth one | |||||
| 133 | # log line per row. | |||||
| 134 | 26 26 26 | 40 15 54901 | no warnings 'substr'; | |||
| 135 | defined $len ? CORE::substr($s, $start, $len) | |||||
| 136 | : CORE::substr($s, $start); | |||||
| 137 | }, | |||||
| 138 | ||||||
| 139 | # --- numeric functions --- | |||||
| 140 | round => sub { | |||||
| 141 | my ($n, $d) = @_; | |||||
| 142 | return undef unless defined $n && looks_like_number($n); | |||||
| 143 | $d = (defined $d && looks_like_number($d)) ? int($d) : 0; | |||||
| 144 | $d = $MAX_ROUND_PLACES if $d > $MAX_ROUND_PLACES; | |||||
| 145 | $d = -$MAX_ROUND_PLACES if $d < -$MAX_ROUND_PLACES; | |||||
| 146 | return sprintf("%.${d}f", $n) + 0 if $d >= 0; | |||||
| 147 | ||||||
| 148 | # Negative places round to the left of the point: round(1234, -2) is 1200. | |||||
| 149 | my $unit = 10 ** -$d; | |||||
| 150 | sprintf('%.0f', $n / $unit) * $unit; | |||||
| 151 | }, | |||||
| 152 | floor => sub { | |||||
| 153 | defined $_[0] && looks_like_number($_[0]) ? POSIX::floor($_[0]) : undef; | |||||
| 154 | }, | |||||
| 155 | ceil => sub { | |||||
| 156 | defined $_[0] && looks_like_number($_[0]) ? POSIX::ceil($_[0]) : undef; | |||||
| 157 | }, | |||||
| 158 | 'abs' => sub { | |||||
| 159 | defined $_[0] && looks_like_number($_[0]) ? CORE::abs($_[0]) : undef; | |||||
| 160 | }, | |||||
| 161 | ||||||
| 162 | # --- conditional / null-handling --- | |||||
| 163 | isnull => sub { defined $_[0] ? $_[0] : $_[1] }, | |||||
| 164 | coalesce => sub { | |||||
| 165 | for my $v (@_) { return $v if defined $v } | |||||
| 166 | return undef; | |||||
| 167 | }, | |||||
| 168 | ||||||
| 169 | # --- date functions (ISO-8601 YYYY-MM-DD prefix; no external module) --- | |||||
| 170 | year => sub { | |||||
| 171 | return undef unless defined $_[0] && $_[0] =~ /\A(\d{4})-\d\d-\d\d/; | |||||
| 172 | $1 + 0; | |||||
| 173 | }, | |||||
| 174 | month => sub { | |||||
| 175 | return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-\d\d/; | |||||
| 176 | $1 + 0; | |||||
| 177 | }, | |||||
| 178 | day => sub { | |||||
| 179 | return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-\d\d-(0[1-9]|[12]\d|3[01])/; | |||||
| 180 | $1 + 0; | |||||
| 181 | }, | |||||
| 182 | quarter => sub { | |||||
| 183 | return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/; | |||||
| 184 | int(($1 - 1) / 3) + 1; | |||||
| 185 | }, | |||||
| 186 | week => sub { | |||||
| 187 | # Returns ISO 8601 week number (1-53); week containing the first | |||||
| 188 | # Thursday of the year is week 1. | |||||
| 189 | return undef unless defined $_[0] && $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/; | |||||
| 190 | my $t = _epoch_of($1 + 0, $2 + 0, $3 + 0, 12, 0, 0); | |||||
| 191 | return undef unless defined $t; | |||||
| 192 | my @lt = Database::BI::Util::local_wall($t); | |||||
| 193 | # Not strftime('%V'): the Windows C runtime does not have it, and | |||||
| 194 | # gives ''. | |||||
| 195 | _iso_week($lt[5] + 1900, $lt[6], $lt[7]); | |||||
| 196 | }, | |||||
| 197 | month_name => sub { | |||||
| 198 | # Returns full English month name, e.g. 'January'. | |||||
| 199 | my @M = qw(January February March April May June | |||||
| 200 | July August September October November December); | |||||
| 201 | return undef unless defined $_[0] && $_[0] =~ /\A\d{4}-(0[1-9]|1[0-2])-/; | |||||
| 202 | $M[$1 - 1]; | |||||
| 203 | }, | |||||
| 204 | weekday => sub { | |||||
| 205 | # Returns ISO 8601 weekday: 1 = Monday, 7 = Sunday. | |||||
| 206 | return undef unless defined $_[0] && $_[0] =~ /\A(\d{4})-(\d\d)-(\d\d)/; | |||||
| 207 | my $t = _epoch_of($1 + 0, $2 + 0, $3 + 0, 12, 0, 0); | |||||
| 208 | return undef unless defined $t; | |||||
| 209 | my $wd = (Database::BI::Util::local_wall($t))[6]; # 0 = Sunday | |||||
| 210 | $wd == 0 ? 7 : $wd; | |||||
| 211 | }, | |||||
| 212 | now => sub { | |||||
| 213 | # Returns today's date as 'YYYY-MM-DD'. Takes no arguments. | |||||
| 214 | my @t = (localtime(Database::BI::Util::frame_epoch(time)))[3, 4, 5]; # mday, mon (0-based), year (since 1900) | |||||
| 215 | 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 | hour => sub { | |||||
| 220 | my $t = _parse_time($_[0]); | |||||
| 221 | return undef unless $t && $t->{has_time}; | |||||
| 222 | (Database::BI::Util::local_wall($t->{epoch}))[2] + 0; | |||||
| 223 | }, | |||||
| 224 | minute => sub { | |||||
| 225 | my $t = _parse_time($_[0]); | |||||
| 226 | return undef unless $t && $t->{has_time}; | |||||
| 227 | (Database::BI::Util::local_wall($t->{epoch}))[1] + 0; | |||||
| 228 | }, | |||||
| 229 | second => sub { | |||||
| 230 | my $t = _parse_time($_[0]); | |||||
| 231 | return undef unless $t && $t->{has_time}; | |||||
| 232 | (Database::BI::Util::local_wall($t->{epoch}))[0] + 0; | |||||
| 233 | }, | |||||
| 234 | ||||||
| 235 | # --- grouping / binning --- | |||||
| 236 | bin => sub { | |||||
| 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 | my ($v, $w) = @_; | |||||
| 241 | return undef unless defined $v && defined $w; | |||||
| 242 | return undef unless looks_like_number($v) && looks_like_number($w) && $w > 0; | |||||
| 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 | my $n = POSIX::floor(sprintf('%.10g', $v / $w) + 0); | |||||
| 247 | my $lo = $n * $w; | |||||
| 248 | my $hi = $lo + $w; | |||||
| 249 | my $fmt = ($w == int($w)) ? '%d' : '%g'; | |||||
| 250 | sprintf("[${fmt},${fmt})", $lo, $hi); | |||||
| 251 | }, | |||||
| 252 | ); | |||||
| 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 | sub _fmt_body { | |||||
| 272 | 81 | 3689 | my ($fmt) = @_; | |||
| 273 | 81 | 50 | my @tokens; | |||
| 274 | 81 | 34 | my $body = ''; | |||
| 275 | 81 | 40 | my $i = 0; | |||
| 276 | ||||||
| 277 | 81 | 72 | while ($i < length $fmt) { | |||
| 278 | 314 | 128 | my $ch = substr($fmt, $i, 1); | |||
| 279 | 314 | 163 | if ($ch ne '%') { | |||
| 280 | 127 | 69 | $body .= quotemeta($ch); | |||
| 281 | 127 | 49 | $i++; | |||
| 282 | 127 | 69 | next; | |||
| 283 | } | |||||
| 284 | 187 | 77 | my $tok = substr($fmt, $i + 1, 1); | |||
| 285 | croak _fmt('error_time_format', length($tok // '') ? "%$tok" : $fmt) | |||||
| 286 | 187 | 235 | unless length($tok // '') && exists $_FMT_RE{$tok}; | |||
| 287 | 178 | 357 | push @tokens, $tok; | |||
| 288 | 178 | 135 | $body .= '(' . $_FMT_RE{$tok} . ')'; | |||
| 289 | 178 | 326 | $i += 2; | |||
| 290 | } | |||||
| 291 | ||||||
| 292 | 72 | 60 | 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 | sub _fmt_compile { | |||||
| 300 | 20 | 2074 | my ($fmt) = @_; | |||
| 301 | 20 | 23 | my ($body, $tokens) = _fmt_body($fmt); | |||
| 302 | 16 | 15 | croak _fmt('error_time_format_date', $fmt) | |||
| 303 | unless _fmt_has_date($tokens); | |||||
| 304 | 13 | 146 | 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 | sub _fmt_has_date { | |||||
| 312 | 47 | 1375 | my ($tokens) = @_; | |||
| 313 | 47 131 | 35 96 | my %has = map { $_ => 1 } @$tokens; | |||
| 314 | 47 | 135 | return $has{Y} && $has{d} && ($has{m} || $has{b}) ? 1 : 0; | |||
| 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 | sub _fmt_compile_pair { | |||||
| 322 | 27 | 2398 | my ($date_fmt, $time_fmt) = @_; | |||
| 323 | 27 | 33 | my ($dbody, $dtokens) = _fmt_body($date_fmt); | |||
| 324 | 27 | 24 | my ($tbody, $ttokens) = _fmt_body($time_fmt); | |||
| 325 | 25 | 34 | croak _fmt('error_time_format_date', $date_fmt) | |||
| 326 | unless _fmt_has_date($dtokens); | |||||
| 327 | return { | |||||
| 328 | 24 | 201 | re => qr/\A$dbody[ T]?$tbody\z/, | |||
| 329 | tokens => [ @$dtokens, @$ttokens ], | |||||
| 330 | }; | |||||
| 331 | } | |||||
| 332 | ||||||
| 333 | # _fmt_parts($value, $compiled) -> \%parts | undef | |||||
| 334 | sub _fmt_parts { | |||||
| 335 | 40 | 33 | my ($value, $compiled) = @_; | |||
| 336 | 40 | 86 | my @caps = ($value =~ $compiled->{re}); | |||
| 337 | 40 | 40 | return undef unless @caps; | |||
| 338 | ||||||
| 339 | 36 | 17 | my %part; | |||
| 340 | 36 36 | 20 31 | my @tokens = @{ $compiled->{tokens} }; | |||
| 341 | 36 | 42 | for my $i (0 .. $#tokens) { | |||
| 342 | 155 | 94 | $part{ $tokens[$i] } = $caps[$i]; | |||
| 343 | } | |||||
| 344 | 36 | 65 | 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 | sub _iso_week { | |||||
| 363 | 452 | 5677 | my ($year, $wday, $yday) = @_; | |||
| 364 | 452 409 409 | 235 141 517 | my $leap = sub { my $y = shift; ($y % 4 == 0 && $y % 100 != 0) || $y % 400 == 0 }; | |||
| 365 | # Monday is 1 and Sunday 7, as ISO counts. | |||||
| 366 | 452 | 241 | my $iso_wday = $wday || 7; | |||
| 367 | 452 | 197 | my $week = int(($yday + 1 - $iso_wday + 10) / 7); | |||
| 368 | # The weekday of 1 January, 0 = Sunday. | |||||
| 369 | 452 | 179 | my $jan1 = ($wday - $yday) % 7; | |||
| 370 | my $weeks = sub { | |||||
| 371 | 452 | 177 | my ($y, $j1) = @_; | |||
| 372 | 452 | 252 | return ($j1 == 4 || ($leap->($y) && $j1 == 3)) ? 53 : 52; | |||
| 373 | 452 | 231 | }; | |||
| 374 | 452 | 211 | if ($week < 1) { | |||
| 375 | 29 | 13 | my $prev_jan1 = ($jan1 - ($leap->($year - 1) ? 366 : 365)) % 7; | |||
| 376 | 29 | 11 | return $weeks->($year - 1, $prev_jan1); | |||
| 377 | } | |||||
| 378 | 423 | 179 | return 1 if $week > $weeks->($year, $jan1); | |||
| 379 | 396 | 325 | return $week; | |||
| 380 | } | |||||
| 381 | ||||||
| 382 | sub _epoch_of { | |||||
| 383 | 480 | 1294 | 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 | 480 | 392 | local $!; | |||
| 387 | 480 | 443 | my $epoch = Database::BI::Util::local_epoch($s, $mi, $h, $day, $mon - 1, $y - 1900); | |||
| 388 | 480 | 362 | return undef unless defined $epoch; | |||
| 389 | ||||||
| 390 | 480 | 338 | my @lt = Database::BI::Util::local_wall($epoch); | |||
| 391 | return undef | |||||
| 392 | 480 | 821 | unless $lt[5] + 1900 == $y && $lt[4] + 1 == $mon && $lt[3] == $day; | |||
| 393 | ||||||
| 394 | 443 | 240 | my $want = $h * 3_600 + $mi * 60 + $s; | |||
| 395 | 443 | 252 | my $got = $lt[2] * 3_600 + $lt[1] * 60 + $lt[0]; | |||
| 396 | 443 | 267 | return undef if abs($got - $want) > 7_200; | |||
| 397 | 443 | 343 | return $epoch; | |||
| 398 | } | |||||
| 399 | ||||||
| 400 | # _parse_time($value) -> { epoch => E, has_time => 0|1 } | undef | |||||
| 401 | # | |||||
| 402 | # Purpose: Read one cell as a point in time. Three shapes are recognised, in | |||||
| 403 | # this order: an ISO date, or an ISO timestamp with 'T' or a space | |||||
| 404 | # between the date and the time (a fraction of a second and a zone | |||||
| 405 | # are moved to the configured time_zone, and set aside without one: | |||||
| 406 | # Database::BI::Util::iso_datetime); | |||||
| 407 | # ten digits, an epoch in seconds; and | |||||
| 408 | # thirteen digits, an epoch in milliseconds. Only the digit count | |||||
| 409 | # separates the last two, so it is the rule -- and it is documented, | |||||
| 410 | # because nothing in the value itself says which one it is. | |||||
| 411 | sub _parse_time { | |||||
| 412 | 465 | 4076 | my ($value) = @_; | |||
| 413 | 465 | 607 | return undef unless defined $value && !ref $value && length $value; | |||
| 414 | 453 | 330 | (my $s = $value) =~ s/\A\s+//; | |||
| 415 | 453 | 270 | $s =~ s/\s+\z//; | |||
| 416 | 453 | 264 | return undef unless length $s; | |||
| 417 | ||||||
| 418 | 452 | 322 | my ($ymd, $h, $mi, $sec) = Database::BI::Util::iso_datetime($s); | |||
| 419 | 452 | 293 | if (defined $ymd) { | |||
| 420 | 386 | 316 | my ($y, $mon, $day) = split /-/, $ymd; | |||
| 421 | 386 | 767 | my $epoch = _epoch_of($y + 0, $mon + 0, $day + 0, | |||
| 422 | ($h // 0) + 0, ($mi // 0) + 0, ($sec // 0) + 0); | |||||
| 423 | 386 | 222 | return undef unless defined $epoch; | |||
| 424 | 374 | 441 | return { epoch => $epoch, has_time => defined $h ? 1 : 0 }; | |||
| 425 | } | |||||
| 426 | ||||||
| 427 | # An epoch is one moment; the buckets read it on the configured zone's clock. | |||||
| 428 | 66 | 57 | return { epoch => Database::BI::Util::frame_epoch($s + 0), has_time => 1 } if $s =~ /\A\d{10}\z/; | |||
| 429 | 57 | 36 | return { epoch => Database::BI::Util::frame_epoch(int($s / 1_000)), has_time => 1 } if $s =~ /\A\d{13}\z/; | |||
| 430 | 55 | 36 | return undef; | |||
| 431 | } | |||||
| 432 | ||||||
| 433 | # _time_from_format($value, $compiled) -> { epoch => E, has_time => 0|1 } | undef | |||||
| 434 | sub _time_from_format { | |||||
| 435 | 40 | 33 | my ($value, $compiled) = @_; | |||
| 436 | 40 | 67 | return undef unless defined $value && !ref $value; | |||
| 437 | 38 | 31 | my $part = _fmt_parts($value, $compiled) or return undef; | |||
| 438 | ||||||
| 439 | my $mon = defined $part->{m} ? $part->{m} + 0 | |||||
| 440 | : defined $part->{b} ? $_MONTH_NAME_TO_NUM{ lc $part->{b} } | |||||
| 441 | 35 | 51 | : undef; | |||
| 442 | 35 | 95 | return undef unless defined $mon && $mon >= 1 && $mon <= 12; | |||
| 443 | ||||||
| 444 | my $epoch = _epoch_of($part->{Y} + 0, $mon, $part->{d} + 0, | |||||
| 445 | 32 | 104 | ($part->{H} // 0) + 0, ($part->{M} // 0) + 0, ($part->{S} // 0) + 0); | |||
| 446 | 32 | 33 | return undef unless defined $epoch; | |||
| 447 | 30 | 58 | return { epoch => $epoch, has_time => defined $part->{H} ? 1 : 0 }; | |||
| 448 | } | |||||
| 449 | ||||||
| 450 | # _iso_second_label($epoch) -> 'YYYY-MM-DDTHH:MM:SS' in local time | |||||
| 451 | sub _iso_second_label { | |||||
| 452 | 24 | 1039 | my @lt = Database::BI::Util::local_wall($_[0]); | |||
| 453 | 24 | 79 | return sprintf '%04d-%02d-%02dT%02d:%02d:%02d', | |||
| 454 | $lt[5] + 1900, $lt[4] + 1, $lt[3], $lt[2], $lt[1], $lt[0]; | |||||
| 455 | } | |||||
| 456 | ||||||
| 457 | # _civil_day($y, $mon, $day) -> days since 1970-01-01 | |||||
| 458 | # | |||||
| 459 | # Purpose: A day number that does not move with daylight saving, so the n-day | |||||
| 460 | # and n-week buckets can be counted from a fixed origin. Integer | |||||
| 461 | # civil-calendar arithmetic; no part of this reads the clock. | |||||
| 462 | sub _civil_day { | |||||
| 463 | 191 | 956 | my ($y, $mon, $day) = @_; | |||
| 464 | 191 | 133 | $y -= ($mon <= 2) ? 1 : 0; | |||
| 465 | 191 | 119 | my $era = int(($y >= 0 ? $y : $y - 399) / 400); | |||
| 466 | 191 | 114 | my $yoe = $y - $era * 400; # [0, 399] | |||
| 467 | 191 | 143 | my $doy = int((153 * ($mon + ($mon > 2 ? -3 : 9)) + 2) / 5) + $day - 1; | |||
| 468 | 191 | 135 | my $doe = $yoe * 365 + int($yoe / 4) - int($yoe / 100) + $doy; | |||
| 469 | 191 | 104 | return $era * 146_097 + $doe - 719_468; | |||
| 470 | } | |||||
| 471 | ||||||
| 472 | # _shift_days($y, $mon, $day, $delta) -> ($y, $mon, $day) | |||||
| 473 | # | |||||
| 474 | # Purpose: Move a date by whole days without a calendar library. | |||||
| 475 | # Notes: Noon is the anchor. A day is then 86,400 seconds away from its | |||||
| 476 | # neighbours even across a daylight-saving change, so counting days | |||||
| 477 | # cannot land on the wrong date -- counting from midnight does, once a | |||||
| 478 | # year, and only in the autumn. | |||||
| 479 | sub _shift_days { | |||||
| 480 | 187 | 108 | my ($y, $mon, $day, $delta) = @_; | |||
| 481 | 187 | 382 | return ($y, $mon, $day) unless $delta; | |||
| 482 | 21 | 21 | local $!; # mktime and localtime may set errno; see _epoch_of | |||
| 483 | 21 | 23 | my $noon = Database::BI::Util::local_epoch(12, 0, 0, $day, $mon - 1, $y - 1900); | |||
| 484 | 21 | 23 | my @lt = Database::BI::Util::local_wall($noon + $delta * 86_400); | |||
| 485 | 21 | 56 | return ($lt[5] + 1900, $lt[4] + 1, $lt[3]); | |||
| 486 | } | |||||
| 487 | ||||||
| 488 | # span_interval($interval) -> { n => N, unit => U, [secs => S] } | undef | |||||
| 489 | # | |||||
| 490 | # Purpose: The interval vocabulary span() takes, and the only place its rule | |||||
| 491 | # lives: a count and a unit, 'mon' for months (because 'm' is | |||||
| 492 | # minutes) and 'q' for quarters. A count below one and an unknown | |||||
| 493 | # unit are both undef rather than a bucket that quietly means | |||||
| 494 | # something else. 'dec' (ten years) and 'c' (a hundred) come back as | |||||
| 495 | # years, so { n => 10, unit => 'y' } is both '1dec' and '10y'. 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 | sub span_interval { | |||||
| 499 | 417 | 256184 | my ($interval) = @_; | |||
| 500 | 417 | 826 | return undef unless defined $interval && !ref $interval && length $interval; | |||
| 501 | 410 | 898 | my ($n, $unit) = $interval =~ /\A(\d+)(mon|dec|s|m|h|d|w|q|y|c)\z/ or return undef; | |||
| 502 | 358 | 266 | $n += 0; | |||
| 503 | 358 | 249 | return undef if $n < 1; | |||
| 504 | ||||||
| 505 | # A decade and a century are only a count of years, so the label code below | |||||
| 506 | # has one rule for all three. | |||||
| 507 | 351 | 455 | if ($unit eq 'dec' || $unit eq 'c') { | |||
| 508 | 59 | 46 | $n *= $unit eq 'dec' ? 10 : 100; | |||
| 509 | 59 | 20 | $unit = 'y'; | |||
| 510 | } | |||||
| 511 | ||||||
| 512 | 351 | 497 | my $secs = $unit eq 's' ? 1 | |||
| 513 | : $unit eq 'm' ? 60 | |||||
| 514 | : $unit eq 'h' ? 3_600 | |||||
| 515 | : undef; | |||||
| 516 | 351 | 577 | return { n => $n, unit => $unit, (defined $secs ? (secs => $secs) : ()) }; | |||
| 517 | } | |||||
| 518 | ||||||
| 519 | # compile_pattern($pattern) -> \%compiled | |||||
| 520 | # | |||||
| 521 | # Purpose: The one place a reader's regular expression is checked and compiled, | |||||
| 522 | # for rx() and for the stored extractions, so both refuse the same | |||||
| 523 | # things with the same words. | |||||
| 524 | # Entry: $pattern is a string. | |||||
| 525 | # Exit: { re => qr//, groups => N, names => [ named groups, in order ] }. | |||||
| 526 | # Croaks error_pattern_too_long, error_pattern_construct or | |||||
| 527 | # error_pattern_invalid. | |||||
| 528 | # Notes: A pattern is checked, not sandboxed: the engine has no timeout, so a | |||||
| 529 | # pathological one stalls the request that uses it. Patterns are typed | |||||
| 530 | # by the reader who owns the machine, never taken from a remote party. | |||||
| 531 | sub compile_pattern { | |||||
| 532 | 115 | 180980 | my ($pattern) = @_; | |||
| 533 | 115 | 83 | local $@; | |||
| 534 | 115 | 249 | $pattern = '' unless defined $pattern && !ref $pattern; | |||
| 535 | 115 | 174 | croak _fmt('error_pattern_too_long', substr($pattern, 0, 40) . (length($pattern) > 40 ? '...' : ''), $MAX_PATTERN_LEN) | |||
| 536 | if length($pattern) > $MAX_PATTERN_LEN; | |||||
| 537 | 112 | 318 | if ($pattern =~ $REFUSED_PATTERN_RE) { | |||
| 538 | 16 | 81 | croak _fmt('error_pattern_construct', $pattern, $1); | |||
| 539 | } | |||||
| 540 | ||||||
| 541 | 96 96 | 465 734 | my $re = eval { qr/$pattern/ }; | |||
| 542 | 96 | 1214 | unless ($re) { | |||
| 543 | 11 | 39 | (my $why = $@ // '') =~ s/ at \S+ line \d+\.?\n?\z//; | |||
| 544 | 11 | 132 | $why =~ s/\s+\z//; | |||
| 545 | 11 | 19 | croak _fmt('error_pattern_invalid', $pattern, $why); | |||
| 546 | } | |||||
| 547 | ||||||
| 548 | # An optional match of the empty string always succeeds, and leaves behind | |||||
| 549 | # how many groups the pattern has and every name it declares. | |||||
| 550 | 85 | 490 | '' =~ /(?:$re)?/; | |||
| 551 | 85 | 107 | my $groups = $#+; | |||
| 552 | 85 | 131 | require re; | |||
| 553 | 85 79 | 182 97 | my %known = map { $_ => 1 } re::regnames(1); | |||
| 554 | # The names in the order they are written, which is the order a reader | |||||
| 555 | # expects the columns in; regnames() itself has no order. | |||||
| 556 | 85 | 68 | my (@names, %seen); | |||
| 557 | 85 | 192 | while ($pattern =~ /(?<!\\)\(\?(?:P?<([A-Za-z_]\w*)>|'([A-Za-z_]\w*)')/g) { | |||
| 558 | 79 | 110 | my $n = defined $1 ? $1 : $2; | |||
| 559 | 79 | 242 | push @names, $n if $known{$n} && !$seen{$n}++; | |||
| 560 | } | |||||
| 561 | 85 79 | 118 76 | push @names, grep { !$seen{$_}++ } sort keys %known; | |||
| 562 | ||||||
| 563 | 85 | 225 | return { re => $re, groups => $groups, names => \@names }; | |||
| 564 | } | |||||
| 565 | ||||||
| 566 | # capture_of(\%compiled, $value, $group) -> $capture | undef | |||||
| 567 | # | |||||
| 568 | # Purpose: One capture of a compiled pattern against a value: $group is a | |||||
| 569 | # number (1 is the first group) or a group's name. | |||||
| 570 | # Exit: The capture, cut to $MAX_CAPTURE_LEN characters; '' when the pattern | |||||
| 571 | # matched but the group took no part; undef when the value is undefined, | |||||
| 572 | # the pattern does not match, or there is no such group. | |||||
| 573 | sub capture_of { | |||||
| 574 | 136 | 528 | my ($compiled, $value, $group) = @_; | |||
| 575 | 136 | 226 | return undef unless defined $value && !ref $value && defined $group; | |||
| 576 | # Which group is asked for is settled first: a match of its own here would | |||||
| 577 | # replace the captures of the one that matters. | |||||
| 578 | 132 | 113 | my $number = $group =~ /\A[0-9]+\z/ ? $group + 0 : undef; | |||
| 579 | 132 | 100 | if (defined $number) { | |||
| 580 | 26 | 44 | return undef if $number < 1 || $number > $compiled->{groups}; | |||
| 581 | } else { | |||||
| 582 | 106 179 106 | 44 116 62 | return undef unless grep { $_ eq $group } @{ $compiled->{names} }; | |||
| 583 | } | |||||
| 584 | 123 | 184 | return undef unless $value =~ $compiled->{re}; | |||
| 585 | 100 | 190 | my $got = defined $number ? ${^CAPTURE}[$number - 1] : $+{$group}; | |||
| 586 | 100 | 97 | return '' unless defined $got; | |||
| 587 | 97 | 76 | return length($got) > $MAX_CAPTURE_LEN ? substr($got, 0, $MAX_CAPTURE_LEN) : $got; | |||
| 588 | } | |||||
| 589 | ||||||
| 590 | # _span_label($value, \%interval) -> bucket label | undef | |||||
| 591 | # | |||||
| 592 | # Purpose: The ISO label of the bucket a value falls in -- the half-open | |||||
| 593 | # interval from the bucket's start to the next bucket's start. | |||||
| 594 | # Notes: The label is ISO at the bucket's own resolution, never 'Oct 2026': | |||||
| 595 | # group keys are sorted as strings, so an ISO label makes | |||||
| 596 | # lexicographic order chronological order and a bucketed chart comes | |||||
| 597 | # out in the right order with no second sort path. A pretty name is a | |||||
| 598 | # presentation step (month_name() already reads a month number); it is | |||||
| 599 | # never the key. | |||||
| 600 | # The intervals below a day are floored on the local clock, never on | |||||
| 601 | # the epoch: that is the UTC clock, which put 14:05 in India into a | |||||
| 602 | # 13:30 bucket. 'd' and upwards are counted in calendar units, because | |||||
| 603 | # a day is not always 86,400 seconds and a month never is. | |||||
| 604 | sub _span_label { | |||||
| 605 | 391 | 596 | my ($value, $interval) = @_; | |||
| 606 | 391 | 287 | my $t = _parse_time($value); | |||
| 607 | ||||||
| 608 | # A column of years -- 1887, with no month or day -- is not a time, but a | |||||
| 609 | # year bucket (1y, a decade, a century) is exactly what one is for. Only | |||||
| 610 | # a year unit reads it: a month or a day of "1887" would be made up. | |||||
| 611 | 391 | 371 | if (!$t && $interval->{unit} eq 'y' && defined $value && !ref $value | |||
| 612 | && $value =~ /\A\s*([0-9]{3,4})\s*\z/) { | |||||
| 613 | 20 | 12 | my $year = $1 + 0; | |||
| 614 | 20 | 23 | return sprintf('%04d-01-01', $year - ($year % $interval->{n})); | |||
| 615 | } | |||||
| 616 | 371 | 224 | return undef unless $t; | |||
| 617 | ||||||
| 618 | 341 | 193 | my $n = $interval->{n}; | |||
| 619 | 341 | 170 | my $unit = $interval->{unit}; | |||
| 620 | ||||||
| 621 | 341 | 191 | my @lt = Database::BI::Util::local_wall($t->{epoch}); | |||
| 622 | 341 | 250 | my ($y, $mon, $day) = ($lt[5] + 1900, $lt[4] + 1, $lt[3]); | |||
| 623 | ||||||
| 624 | 341 | 221 | if (defined $interval->{secs}) { | |||
| 625 | 163 | 92 | my $step = $n * $interval->{secs}; | |||
| 626 | 163 | 126 | my $day_no = _civil_day($y, $mon, $day); | |||
| 627 | # The clock reading as seconds, counted as if no zone existed. | |||||
| 628 | 163 | 95 | my $wall = $day_no * 86_400 + $lt[2] * 3_600 + $lt[1] * 60 + $lt[0]; | |||
| 629 | 163 | 155 | my $start = floor($wall / $step) * $step; | |||
| 630 | 163 | 80 | my $secs = $start % 86_400; | |||
| 631 | 163 | 286 | return sprintf('%04d-%02d-%02dT%02d:%02d:%02d', | |||
| 632 | _shift_days($y, $mon, $day, floor($start / 86_400) - $day_no), | |||||
| 633 | int($secs / 3_600), int($secs / 60) % 60, $secs % 60); | |||||
| 634 | } | |||||
| 635 | ||||||
| 636 | 178 | 109 | if ($unit eq 'd') { | |||
| 637 | 37 | 63 | return sprintf('%04d-%02d-%02d', $y, $mon, $day) if $n == 1; | |||
| 638 | 7 | 6 | my $day_no = _civil_day($y, $mon, $day); | |||
| 639 | 7 | 7 | return sprintf('%04d-%02d-%02d', _shift_days($y, $mon, $day, -($day_no % $n))); | |||
| 640 | } | |||||
| 641 | ||||||
| 642 | 141 | 85 | if ($unit eq 'w') { | |||
| 643 | # Monday is the first day of the ISO week, and 1970-01-05 is the | |||||
| 644 | # Monday the week count runs from. | |||||
| 645 | 13 | 13 | local $!; # mktime and localtime may set errno; see _epoch_of | |||
| 646 | 13 | 14 | my $dow = (Database::BI::Util::local_wall( | |||
| 647 | Database::BI::Util::local_epoch(12, 0, 0, $day, $mon - 1, $y - 1900)))[6]; | |||||
| 648 | 13 | 14 | my $day_no = _civil_day($y, $mon, $day); | |||
| 649 | 13 | 10 | my $monday = $day_no - ($dow == 0 ? 6 : $dow - 1); | |||
| 650 | 13 | 15 | my $weeks = floor(($monday - 4) / 7); | |||
| 651 | 13 | 13 | my $start = $monday - ($weeks % $n) * 7; | |||
| 652 | 13 | 10 | return sprintf('%04d-%02d-%02d', _shift_days($y, $mon, $day, $start - $day_no)); | |||
| 653 | } | |||||
| 654 | ||||||
| 655 | # A month count runs from January 1970, and a quarter count from its first | |||||
| 656 | # quarter, so the buckets line up with the calendar at every width and not | |||||
| 657 | # only when the count is one. | |||||
| 658 | 128 | 75 | if ($unit eq 'mon') { | |||
| 659 | 59 | 45 | my $idx = ($y - 1970) * 12 + ($mon - 1); | |||
| 660 | 59 | 26 | my $lo = $idx - ($idx % $n); | |||
| 661 | 59 | 121 | return sprintf('%04d-%02d-01', 1970 + floor($lo / 12), $lo % 12 + 1); | |||
| 662 | } | |||||
| 663 | ||||||
| 664 | 69 | 32 | if ($unit eq 'q') { | |||
| 665 | 11 | 7 | my $qi = ($y - 1970) * 4 + int(($mon - 1) / 3); | |||
| 666 | 11 | 8 | my $lo = $qi - ($qi % $n); | |||
| 667 | 11 | 27 | return sprintf('%04d-%02d-01', 1970 + floor($lo / 4), ($lo % 4) * 3 + 1); | |||
| 668 | } | |||||
| 669 | ||||||
| 670 | 58 | 90 | return sprintf('%04d-01-01', $y - ($y % $n)); | |||
| 671 | } | |||||
| 672 | ||||||
| 673 | # --------------------------------------------------------------------------- | |||||
| 674 | # Constructor | |||||
| 675 | # --------------------------------------------------------------------------- | |||||
| 676 | ||||||
| 677 | sub new { | |||||
| 678 | 863 | 108126 | my ($class, %args) = @_; | |||
| 679 | # A bad expression is an answer here, not an exception, so nothing of the | |||||
| 680 | # compile may reach the caller's $@. | |||||
| 681 | 863 | 536 | local $@; | |||
| 682 | # Takes off the where-it-happened tail that croak adds. A path can hold spaces, | |||||
| 683 | # and this text reaches the reader, so the tail is everything from the last | |||||
| 684 | # " at " on rather than one word. | |||||
| 685 | my $tidy = sub { | |||||
| 686 | 185 | 177 | my ($err) = @_; | |||
| 687 | 185 | 459 | $err =~ s/\A(.*) at .+? line \d+\.?\n?\z/$1/s; | |||
| 688 | 185 | 2460 | return $err; | |||
| 689 | 863 | 963 | }; | |||
| 690 | ||||||
| 691 | 863 | 1363 | my $self = bless { | |||
| 692 | _error => undef, | |||||
| 693 | _code => undef, | |||||
| 694 | _columns => {}, | |||||
| 695 | _params => {}, | |||||
| 696 | }, $class; | |||||
| 697 | ||||||
| 698 | 863 | 1044 | my $expr = $args{expr} // ''; | |||
| 699 | 863 863 | 457 1069 | my @cols = @{ $args{columns} // [] }; | |||
| 700 | 863 863 | 500 1202 | my %params = %{ $args{params} // {} }; | |||
| 701 | 863 | 1291 | $self->{_columns}{$_} = 1 for @cols; | |||
| 702 | ||||||
| 703 | # A name that is both a column and a parameter is an error: the ambiguity | |||||
| 704 | # would be resolved silently in whichever direction, making expressions | |||||
| 705 | # non-deterministic when the data changes. | |||||
| 706 | 863 | 687 | for my $p (keys %params) { | |||
| 707 | 9 | 18 | if ($self->{_columns}{$p}) { | |||
| 708 | 4 | 6 | $self->{_error} = _fmt('error_param_col_clash', $p); | |||
| 709 | 4 | 10 | return $self; | |||
| 710 | } | |||||
| 711 | } | |||||
| 712 | # Extend the compile-time column whitelist with param names so _parse_colref | |||||
| 713 | # accepts them as identifiers; at evaluate() time their values come from | |||||
| 714 | # _params rather than the row hashref. | |||||
| 715 | 859 | 687 | $self->{_columns}{$_} = 1 for keys %params; | |||
| 716 | 859 | 706 | $self->{_params} = \%params; | |||
| 717 | ||||||
| 718 | 859 | 1082 | if (length($expr) > $MAX_EXPR_LEN) { | |||
| 719 | 5 | 15 | $self->{_error} = _fmt('error_expr_too_long', $MAX_EXPR_LEN); | |||
| 720 | 5 | 14 | return $self; | |||
| 721 | } | |||||
| 722 | ||||||
| 723 | 854 | 1486 | my $tokens; | |||
| 724 | 854 854 835 | 494 757 439 | my $ok = eval { $tokens = _tokenize($expr); 1 }; | |||
| 725 | 854 | 2284 | unless ($ok) { | |||
| 726 | 19 | 17 | $self->{_error} = $tidy->($@); | |||
| 727 | 19 | 76 | return $self; | |||
| 728 | } | |||||
| 729 | ||||||
| 730 | 835 | 368 | my $pos = 0; | |||
| 731 | 835 | 388 | my $depth = 0; | |||
| 732 | 835 | 446 | my $code; | |||
| 733 | 835 835 669 | 367 933 387 | $ok = eval { $code = _parse_cmp($tokens, \$pos, \$depth, $self->{_columns}); 1 }; | |||
| 734 | 835 | 38437 | unless ($ok) { | |||
| 735 | 166 | 175 | $self->{_error} = $tidy->($@); | |||
| 736 | 166 | 2095 | return $self; | |||
| 737 | } | |||||
| 738 | ||||||
| 739 | 669 | 488 | if ($tokens->[$pos]{type} ne $T_EOF) { | |||
| 740 | $self->{_error} = _fmt('error_trailing', | |||||
| 741 | 3 | 6 | $tokens->[$pos]{val}, $tokens->[$pos]{pos}); | |||
| 742 | 3 | 10 | return $self; | |||
| 743 | } | |||||
| 744 | ||||||
| 745 | 666 | 1053 | $self->{_code} = $code; | |||
| 746 | 666 | 1751 | return $self; | |||
| 747 | } | |||||
| 748 | ||||||
| 749 | # --------------------------------------------------------------------------- | |||||
| 750 | # Public API | |||||
| 751 | # --------------------------------------------------------------------------- | |||||
| 752 | ||||||
| 753 | 224 | 645 | sub error { $_[0]->{_error} } | |||
| 754 | 736 | 1425 | sub has_error { defined $_[0]->{_error} } | |||
| 755 | ||||||
| 756 | sub evaluate { | |||||
| 757 | 1100 | 1888 | my ($self, $row) = @_; | |||
| 758 | 1100 | 747 | return undef unless defined $self->{_code}; | |||
| 759 | 1091 | 650 | $row //= {}; | |||
| 760 | 1091 | 731 | return undef unless ref $row eq 'HASH'; | |||
| 761 | 1089 | 443 | local $@; # a failed row is undef, and the caller's $@ is its own | |||
| 762 | 1089 | 1801 | local $!; # the date functions call mktime and localtime, which may set errno | |||
| 763 | # Merge bound parameters into the evaluation context. Parameters take | |||||
| 764 | # precedence over same-named columns: the clash check in new() ensures this | |||||
| 765 | # never happens legitimately, but a column added to the data after compile | |||||
| 766 | # time should still see the parameter value. | |||||
| 767 | 1089 | 747 | my $ctx = %{ $self->{_params} } | |||
| 768 | 1089 17 | 420 20 | ? { %$row, %{ $self->{_params} } } | |||
| 769 | : $row; | |||||
| 770 | 1089 | 458 | my $result; | |||
| 771 | 1089 1089 1086 | 475 628 772 | my $ok = eval { $result = $self->{_code}->($ctx); 1 }; | |||
| 772 | 1089 | 688 | return undef unless $ok; | |||
| 773 | 1086 | 1696 | return $result; | |||
| 774 | } | |||||
| 775 | ||||||
| 776 | # --------------------------------------------------------------------------- | |||||
| 777 | # Tokenizer | |||||
| 778 | # --------------------------------------------------------------------------- | |||||
| 779 | ||||||
| 780 | sub _tokenize { | |||||
| 781 | 874 | 6597 | my ($expr) = @_; | |||
| 782 | 874 | 449 | my @tokens; | |||
| 783 | 874 | 422 | my $pos = 0; | |||
| 784 | 874 | 485 | my $len = length($expr); | |||
| 785 | 874 | 965 | my %single_ops = ( | |||
| 786 | '+' => $T_PLUS, '-' => $T_MINUS, | |||||
| 787 | '*' => $T_STAR, '/' => $T_SLASH, | |||||
| 788 | '(' => $T_LPAREN, ')' => $T_RPAREN, ',' => $T_COMMA, | |||||
| 789 | ); | |||||
| 790 | ||||||
| 791 | 874 | 7147 | while ($pos < $len) { | |||
| 792 | 6515 | 2793 | my $ch = substr($expr, $pos, 1); | |||
| 793 | ||||||
| 794 | # skip whitespace | |||||
| 795 | 6515 889 889 | 3643 330 431 | if ($ch =~ /\A\s/) { $pos++; next } | |||
| 796 | ||||||
| 797 | # number literal (integer, decimal, scientific) | |||||
| 798 | 5626 | 3842 | if (substr($expr, $pos) =~ /\A(\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/) { | |||
| 799 | 716 | 587 | push @tokens, { type => $T_NUM, val => $1, pos => $pos }; | |||
| 800 | 716 | 1181 | $pos += length($1); | |||
| 801 | 716 | 476 | next; | |||
| 802 | } | |||||
| 803 | ||||||
| 804 | # double-quoted string | |||||
| 805 | 4910 | 2426 | if ($ch eq '"') { | |||
| 806 | 40 | 33 | my $end = index($expr, '"', $pos + 1); | |||
| 807 | 40 | 29 | croak _fmt('error_unterminated', $pos) if $end < 0; | |||
| 808 | 38 | 34 | push @tokens, { | |||
| 809 | type => $T_STR, | |||||
| 810 | val => substr($expr, $pos + 1, $end - $pos - 1), | |||||
| 811 | pos => $pos, | |||||
| 812 | }; | |||||
| 813 | 38 | 56 | $pos = $end + 1; | |||
| 814 | 38 | 19 | next; | |||
| 815 | } | |||||
| 816 | ||||||
| 817 | # single-quoted string | |||||
| 818 | 4870 | 2305 | if ($ch eq "'") { | |||
| 819 | 215 | 167 | my $end = index($expr, "'", $pos + 1); | |||
| 820 | 215 | 183 | croak _fmt('error_unterminated', $pos) if $end < 0; | |||
| 821 | 214 | 224 | push @tokens, { | |||
| 822 | type => $T_STR, | |||||
| 823 | val => substr($expr, $pos + 1, $end - $pos - 1), | |||||
| 824 | pos => $pos, | |||||
| 825 | }; | |||||
| 826 | 214 | 347 | $pos = $end + 1; | |||
| 827 | 214 | 127 | next; | |||
| 828 | } | |||||
| 829 | ||||||
| 830 | # identifier: letters/digits/underscore, leading letter or _ | |||||
| 831 | 4655 | 3132 | if (substr($expr, $pos) =~ /\A([a-zA-Z_][a-zA-Z0-9_]*)/) { | |||
| 832 | 1341 | 1113 | push @tokens, { type => $T_IDENT, val => $1, pos => $pos }; | |||
| 833 | 1341 | 2444 | $pos += length($1); | |||
| 834 | 1341 | 900 | next; | |||
| 835 | } | |||||
| 836 | ||||||
| 837 | # two-character comparison operators (must be tested before single-char) | |||||
| 838 | 3314 | 1803 | if ($pos + 1 < $len) { | |||
| 839 | 2864 | 1308 | my $two = substr($expr, $pos, 2); | |||
| 840 | 2864 | 1498 | if ($two eq '!=') { | |||
| 841 | 12 | 9 | push @tokens, { type => $T_NEQ, val => '!=', pos => $pos }; | |||
| 842 | 12 12 | 17 9 | $pos += 2; next; | |||
| 843 | } | |||||
| 844 | 2852 | 1423 | if ($two eq '<=') { | |||
| 845 | 27 | 19 | push @tokens, { type => $T_LE, val => '<=', pos => $pos }; | |||
| 846 | 27 27 | 36 17 | $pos += 2; next; | |||
| 847 | } | |||||
| 848 | 2825 | 1387 | if ($two eq '>=') { | |||
| 849 | 13 | 14 | push @tokens, { type => $T_GE, val => '>=', pos => $pos }; | |||
| 850 | 13 13 | 18 8 | $pos += 2; next; | |||
| 851 | } | |||||
| 852 | 2812 | 1428 | if ($two eq '==') { | |||
| 853 | 5 | 7 | croak _fmt('error_double_eq', $pos); | |||
| 854 | } | |||||
| 855 | } | |||||
| 856 | ||||||
| 857 | # single-character comparison operators | |||||
| 858 | 3257 | 1581 | if ($ch eq '=') { | |||
| 859 | 17 | 14 | push @tokens, { type => $T_EQ, val => '=', pos => $pos }; | |||
| 860 | 17 17 | 23 11 | $pos++; next; | |||
| 861 | } | |||||
| 862 | 3240 | 1481 | if ($ch eq '<') { | |||
| 863 | 23 | 14 | push @tokens, { type => $T_LT, val => '<', pos => $pos }; | |||
| 864 | 23 23 | 52 12 | $pos++; next; | |||
| 865 | } | |||||
| 866 | 3217 | 1476 | if ($ch eq '>') { | |||
| 867 | 27 | 32 | push @tokens, { type => $T_GT, val => '>', pos => $pos }; | |||
| 868 | 27 27 | 41 18 | $pos++; next; | |||
| 869 | } | |||||
| 870 | ||||||
| 871 | # single-character arithmetic operators and punctuation | |||||
| 872 | 3190 | 1800 | if (exists $single_ops{$ch}) { | |||
| 873 | 3161 | 2397 | push @tokens, { type => $single_ops{$ch}, val => $ch, pos => $pos }; | |||
| 874 | 3161 | 1139 | $pos++; | |||
| 875 | 3161 | 1580 | next; | |||
| 876 | } | |||||
| 877 | ||||||
| 878 | 29 | 20 | croak _fmt('error_bad_char', $ch, $pos); | |||
| 879 | } | |||||
| 880 | ||||||
| 881 | 837 | 686 | push @tokens, { type => $T_EOF, val => '', pos => $pos }; | |||
| 882 | 837 | 1716 | return \@tokens; | |||
| 883 | } | |||||
| 884 | ||||||
| 885 | # --------------------------------------------------------------------------- | |||||
| 886 | # Parser (each _parse_* returns a coderef sub { my ($row) = @_; ... }) | |||||
| 887 | # --------------------------------------------------------------------------- | |||||
| 888 | ||||||
| 889 | sub _check_depth { | |||||
| 890 | 3058 | 2545 | my ($depth_ref) = @_; | |||
| 891 | 3058 | 1685 | croak _fmt('error_expr_too_deep', $MAX_DEPTH) if $$depth_ref >= $MAX_DEPTH; | |||
| 892 | } | |||||
| 893 | ||||||
| 894 | sub _expect { | |||||
| 895 | 430 | 814 | my ($tokens, $pos_ref, $expected) = @_; | |||
| 896 | 430 | 567 | my $tok = $tokens->[$$pos_ref]; | |||
| 897 | croak _fmt('error_expected_tok', $expected, $tok->{pos}, $tok->{val}) | |||||
| 898 | 430 | 326 | unless $tok->{type} eq $expected; | |||
| 899 | 425 | 199 | $$pos_ref++; | |||
| 900 | } | |||||
| 901 | ||||||
| 902 | # cmp_expr ::= add_expr (cmp_op add_expr)? | |||||
| 903 | # Comparison yields 1 (true), 0 (false), or undef (either operand undef). | |||||
| 904 | # When both operands look numeric, numeric comparison is used; otherwise | |||||
| 905 | # case-insensitive string comparison, matching _apply_filter_spec semantics. | |||||
| 906 | sub _parse_cmp { | |||||
| 907 | 1443 | 839 | my ($tokens, $pos_ref, $depth_ref, $cols) = @_; | |||
| 908 | 1443 | 1135 | _check_depth($depth_ref); | |||
| 909 | 1440 | 3795 | $$depth_ref++; | |||
| 910 | ||||||
| 911 | 1440 | 1006 | my $left = _parse_add($tokens, $pos_ref, $depth_ref, $cols); | |||
| 912 | ||||||
| 913 | 1246 | 715 | my $type = $tokens->[$$pos_ref]{type}; | |||
| 914 | 1246 | 721 | if ($type eq $T_EQ || $type eq $T_NEQ | |||
| 915 | || $type eq $T_LT || $type eq $T_LE | |||||
| 916 | || $type eq $T_GT || $type eq $T_GE) { | |||||
| 917 | 112 | 450 | my $op = $type; | |||
| 918 | 112 | 44 | $$pos_ref++; | |||
| 919 | 112 | 65 | my $right = _parse_add($tokens, $pos_ref, $depth_ref, $cols); | |||
| 920 | 112 | 52 | my ($l, $r) = ($left, $right); | |||
| 921 | $left = sub { | |||||
| 922 | 109 | 59 | my $lv = $l->($_[0]); | |||
| 923 | 109 | 60 | my $rv = $r->($_[0]); | |||
| 924 | 109 | 95 | return undef unless defined $lv && defined $rv; | |||
| 925 | 106 | 135 | if (looks_like_number($lv) && looks_like_number($rv)) { | |||
| 926 | 98 | 62 | return $op eq $T_EQ ? ($lv == $rv ? 1 : 0) | |||
| 927 | : $op eq $T_NEQ ? ($lv != $rv ? 1 : 0) | |||||
| 928 | : $op eq $T_LT ? ($lv < $rv ? 1 : 0) | |||||
| 929 | : $op eq $T_LE ? ($lv <= $rv ? 1 : 0) | |||||
| 930 | : $op eq $T_GT ? ($lv > $rv ? 1 : 0) | |||||
| 931 | : ($lv >= $rv ? 1 : 0); | |||||
| 932 | } else { | |||||
| 933 | 8 | 7 | my $cmp = lc($lv) cmp lc($rv); | |||
| 934 | 8 | 4 | return $op eq $T_EQ ? ($cmp == 0 ? 1 : 0) | |||
| 935 | : $op eq $T_NEQ ? ($cmp != 0 ? 1 : 0) | |||||
| 936 | : $op eq $T_LT ? ($cmp < 0 ? 1 : 0) | |||||
| 937 | : $op eq $T_LE ? ($cmp <= 0 ? 1 : 0) | |||||
| 938 | : $op eq $T_GT ? ($cmp > 0 ? 1 : 0) | |||||
| 939 | : ($cmp >= 0 ? 1 : 0); | |||||
| 940 | } | |||||
| 941 | 112 | 104 | }; | |||
| 942 | } | |||||
| 943 | ||||||
| 944 | 1246 | 8464 | $$depth_ref--; | |||
| 945 | 1246 | 671 | return $left; | |||
| 946 | } | |||||
| 947 | ||||||
| 948 | # add_expr ::= term ( ('+' | '-') term )* | |||||
| 949 | sub _parse_add { | |||||
| 950 | 1552 | 839 | my ($tokens, $pos_ref, $depth_ref, $cols) = @_; | |||
| 951 | 1552 | 911 | _check_depth($depth_ref); | |||
| 952 | 1552 | 1765 | $$depth_ref++; | |||
| 953 | ||||||
| 954 | 1552 | 1015 | my $left = _parse_term($tokens, $pos_ref, $depth_ref, $cols); | |||
| 955 | ||||||
| 956 | 1364 | 908 | while ($tokens->[$$pos_ref]{type} eq $T_PLUS | |||
| 957 | || $tokens->[$$pos_ref]{type} eq $T_MINUS) { | |||||
| 958 | 259 | 375 | my $op = $tokens->[$$pos_ref]{type}; | |||
| 959 | 259 | 115 | $$pos_ref++; | |||
| 960 | 259 | 131 | my $right = _parse_term($tokens, $pos_ref, $depth_ref, $cols); | |||
| 961 | 253 | 121 | my ($l, $r) = ($left, $right); | |||
| 962 | 253 | 120 | if ($op eq $T_PLUS) { | |||
| 963 | $left = sub { | |||||
| 964 | 253 252 | 133 131 | my $lv = $l->($_[0]); my $rv = $r->($_[0]); | |||
| 965 | 252 | 185 | return undef unless defined $lv && defined $rv; | |||
| 966 | 246 | 222 | return undef unless looks_like_number($lv) && looks_like_number($rv); | |||
| 967 | 240 | 101 | $lv + $rv; | |||
| 968 | 243 | 495 | }; | |||
| 969 | } else { | |||||
| 970 | $left = sub { | |||||
| 971 | 12 12 | 10 10 | my $lv = $l->($_[0]); my $rv = $r->($_[0]); | |||
| 972 | 12 | 18 | return undef unless defined $lv && defined $rv; | |||
| 973 | 12 | 18 | return undef unless looks_like_number($lv) && looks_like_number($rv); | |||
| 974 | 11 | 9 | $lv - $rv; | |||
| 975 | 10 | 26 | }; | |||
| 976 | } | |||||
| 977 | } | |||||
| 978 | ||||||
| 979 | 1358 | 3337 | $$depth_ref--; | |||
| 980 | 1358 | 665 | return $left; | |||
| 981 | } | |||||
| 982 | ||||||
| 983 | # term ::= factor ( ('*' | '/') factor )* | |||||
| 984 | sub _parse_term { | |||||
| 985 | 1811 | 879 | my ($tokens, $pos_ref, $depth_ref, $cols) = @_; | |||
| 986 | ||||||
| 987 | 1811 | 1178 | my $left = _parse_factor($tokens, $pos_ref, $depth_ref, $cols); | |||
| 988 | ||||||
| 989 | 1619 | 1113 | while ($tokens->[$$pos_ref]{type} eq $T_STAR | |||
| 990 | || $tokens->[$$pos_ref]{type} eq $T_SLASH) { | |||||
| 991 | 153 | 484 | my $op = $tokens->[$$pos_ref]{type}; | |||
| 992 | 153 | 127 | $$pos_ref++; | |||
| 993 | 153 | 151 | my $right = _parse_factor($tokens, $pos_ref, $depth_ref, $cols); | |||
| 994 | 151 | 146 | my ($l, $r) = ($left, $right); | |||
| 995 | 151 | 121 | if ($op eq $T_STAR) { | |||
| 996 | $left = sub { | |||||
| 997 | 263 263 | 162 165 | my $lv = $l->($_[0]); my $rv = $r->($_[0]); | |||
| 998 | 263 | 337 | return undef unless defined $lv && defined $rv; | |||
| 999 | 261 | 396 | return undef unless looks_like_number($lv) && looks_like_number($rv); | |||
| 1000 | 259 | 182 | $lv * $rv; | |||
| 1001 | 93 | 342 | }; | |||
| 1002 | } else { | |||||
| 1003 | $left = sub { | |||||
| 1004 | 114 114 | 83 75 | my $lv = $l->($_[0]); my $rv = $r->($_[0]); | |||
| 1005 | 114 | 125 | return undef unless defined $lv && defined $rv; | |||
| 1006 | 114 | 158 | return undef unless looks_like_number($lv) && looks_like_number($rv); | |||
| 1007 | 113 | 90 | return undef if $rv == 0; | |||
| 1008 | 97 | 64 | $lv / $rv; | |||
| 1009 | 58 | 176 | }; | |||
| 1010 | } | |||||
| 1011 | } | |||||
| 1012 | ||||||
| 1013 | 1617 | 4116 | return $left; | |||
| 1014 | } | |||||
| 1015 | ||||||
| 1016 | # factor ::= unary | '(' cmp_expr ')' | number | string | column | call | |||||
| 1017 | sub _parse_factor { | |||||
| 1018 | 2023 | 1069 | my ($tokens, $pos_ref, $depth_ref, $cols) = @_; | |||
| 1019 | 2023 | 955 | my $tok = $tokens->[$$pos_ref]; | |||
| 1020 | ||||||
| 1021 | # unary minus | |||||
| 1022 | 2023 | 1246 | if ($tok->{type} eq $T_MINUS) { | |||
| 1023 | 40 | 46 | $$pos_ref++; | |||
| 1024 | 40 | 23 | _check_depth($depth_ref); | |||
| 1025 | 39 | 43 | $$depth_ref++; | |||
| 1026 | 39 | 37 | my $inner = _parse_factor($tokens, $pos_ref, $depth_ref, $cols); | |||
| 1027 | 21 | 15 | $$depth_ref--; | |||
| 1028 | return sub { | |||||
| 1029 | 21 | 13 | my $v = $inner->($_[0]); | |||
| 1030 | 21 | 31 | return undef unless defined $v && looks_like_number($v); | |||
| 1031 | 20 | 15 | -$v; | |||
| 1032 | 21 | 22 | }; | |||
| 1033 | } | |||||
| 1034 | ||||||
| 1035 | # unary plus (no-op) | |||||
| 1036 | 1983 | 2800 | if ($tok->{type} eq $T_PLUS) { | |||
| 1037 | 21 | 24 | $$pos_ref++; | |||
| 1038 | 21 | 14 | _check_depth($depth_ref); | |||
| 1039 | 20 | 21 | $$depth_ref++; | |||
| 1040 | 20 | 9 | my $inner = _parse_factor($tokens, $pos_ref, $depth_ref, $cols); | |||
| 1041 | 2 | 1 | $$depth_ref--; | |||
| 1042 | 2 | 2 | return $inner; | |||
| 1043 | } | |||||
| 1044 | ||||||
| 1045 | # parenthesized sub-expression: allow full cmp_expr so (qty > 0) works | |||||
| 1046 | 1962 | 2651 | if ($tok->{type} eq $T_LPAREN) { | |||
| 1047 | 31 | 38 | $$pos_ref++; | |||
| 1048 | 31 | 30 | my $inner = _parse_cmp($tokens, $pos_ref, $depth_ref, $cols); | |||
| 1049 | 10 | 11 | _expect($tokens, $pos_ref, $T_RPAREN); | |||
| 1050 | 7 | 1 | return $inner; | |||
| 1051 | } | |||||
| 1052 | ||||||
| 1053 | # number literal | |||||
| 1054 | 1931 | 2655 | if ($tok->{type} eq $T_NUM) { | |||
| 1055 | 602 | 879 | my $val = $tok->{val} + 0; | |||
| 1056 | 602 | 278 | $$pos_ref++; | |||
| 1057 | 602 785 | 581 441 | return sub { $val }; | |||
| 1058 | } | |||||
| 1059 | ||||||
| 1060 | # string literal | |||||
| 1061 | 1329 | 1958 | if ($tok->{type} eq $T_STR) { | |||
| 1062 | 49 | 56 | my $val = $tok->{val}; | |||
| 1063 | 49 | 25 | $$pos_ref++; | |||
| 1064 | 49 51 | 37 58 | return sub { $val }; | |||
| 1065 | } | |||||
| 1066 | ||||||
| 1067 | # identifier -- function call or column reference | |||||
| 1068 | 1280 | 1866 | if ($tok->{type} eq $T_IDENT) { | |||
| 1069 | 1269 | 1792 | my $name = $tok->{val}; | |||
| 1070 | 1269 | 529 | $$pos_ref++; | |||
| 1071 | return $tokens->[$$pos_ref]{type} eq $T_LPAREN | |||||
| 1072 | ? _parse_call($tokens, $pos_ref, $depth_ref, $cols, $name, $tok->{pos}) | |||||
| 1073 | 1269 | 862 | : _parse_colref($cols, $name, $tok->{pos}); | |||
| 1074 | } | |||||
| 1075 | ||||||
| 1076 | 11 | 27 | croak _fmt('error_unexpected_tok', $tok->{val}, $tok->{pos}); | |||
| 1077 | } | |||||
| 1078 | ||||||
| 1079 | # Parse a function call. 'if' is a special form (short-circuit branches). | |||||
| 1080 | # Arguments may be full cmp_expr (e.g. IF(qty > 0, amount/qty, 0)). | |||||
| 1081 | sub _parse_call { | |||||
| 1082 | 448 | 919 | my ($tokens, $pos_ref, $depth_ref, $cols, $name, $name_pos) = @_; | |||
| 1083 | 448 | 259 | my $lc = lc($name); | |||
| 1084 | ||||||
| 1085 | croak _fmt('error_unknown_fn', $name) | |||||
| 1086 | 448 | 945 | unless exists $FUNCTIONS{$lc} || $lc eq 'if' || $lc eq 'rx' || $TIME_CONST_FNS{$lc}; | |||
| 1087 | ||||||
| 1088 | # rx(v, 'pattern' [, 'group']): the pattern and the group are constants, | |||||
| 1089 | # so the pattern is checked and compiled once, here. A group the pattern | |||||
| 1090 | # does not have is undef on every row rather than an error, as the POD says. | |||||
| 1091 | 432 | 707 | if ($lc eq 'rx') { | |||
| 1092 | 13 | 5 | $$pos_ref++; # consume '(' | |||
| 1093 | 13 | 15 | my $value_fn = _parse_cmp($tokens, $pos_ref, $depth_ref, $cols); | |||
| 1094 | 13 | 3 | my @const; | |||
| 1095 | 13 | 13 | while ($tokens->[$$pos_ref]{type} eq $T_COMMA) { | |||
| 1096 | 16 | 22 | $$pos_ref++; | |||
| 1097 | 16 | 9 | my $tok = $tokens->[$$pos_ref]; | |||
| 1098 | croak _fmt('error_rx_args') | |||||
| 1099 | 16 | 10 | unless $tok->{type} eq $T_STR || $tok->{type} eq $T_NUM; | |||
| 1100 | 15 | 25 | push @const, $tok->{val}; | |||
| 1101 | 15 | 12 | $$pos_ref++; | |||
| 1102 | } | |||||
| 1103 | 12 | 21 | _expect($tokens, $pos_ref, $T_RPAREN); | |||
| 1104 | 12 | 13 | croak _fmt('error_rx_args') unless @const == 1 || @const == 2; | |||
| 1105 | 11 | 11 | my $compiled = compile_pattern($const[0]); | |||
| 1106 | 7 | 6 | my $group = defined $const[1] ? $const[1] : 1; | |||
| 1107 | 7 10 | 11 6 | return sub { capture_of($compiled, $value_fn->($_[0]), $group) }; | |||
| 1108 | } | |||||
| 1109 | ||||||
| 1110 | # epoch(v [, fmt]) and span(v, interval) take a constant second argument: | |||||
| 1111 | # a format or an interval. It is checked here, once per column rather than | |||||
| 1112 | # once per row, so a bad one is a compile error that names it -- and the | |||||
| 1113 | # pattern is compiled once instead of on every value. | |||||
| 1114 | 419 | 377 | if ($TIME_CONST_FNS{$lc}) { | |||
| 1115 | 196 | 396 | $$pos_ref++; # consume '(' | |||
| 1116 | 196 | 152 | my $value_fn = _parse_cmp($tokens, $pos_ref, $depth_ref, $cols); | |||
| 1117 | 196 | 106 | my $const; | |||
| 1118 | 196 | 159 | if ($tokens->[$$pos_ref]{type} eq $T_COMMA) { | |||
| 1119 | 178 | 253 | $$pos_ref++; | |||
| 1120 | 178 | 109 | my $tok = $tokens->[$$pos_ref]; | |||
| 1121 | croak _fmt('error_const_arg', $name) | |||||
| 1122 | 178 | 132 | unless $tok->{type} eq $T_STR; | |||
| 1123 | 175 | 289 | $const = $tok->{val}; | |||
| 1124 | 175 | 116 | $$pos_ref++; | |||
| 1125 | } | |||||
| 1126 | 193 | 204 | _expect($tokens, $pos_ref, $T_RPAREN); | |||
| 1127 | ||||||
| 1128 | 193 | 182 | if ($lc eq 'epoch') { | |||
| 1129 | 23 | 18 | my $compiled = defined $const ? _fmt_compile($const) : undef; | |||
| 1130 | return sub { | |||||
| 1131 | 20 | 15 | my $value = $value_fn->($_[0]); | |||
| 1132 | 20 | 20 | my $t = defined $compiled | |||
| 1133 | ? _time_from_format($value, $compiled) | |||||
| 1134 | : _parse_time($value); | |||||
| 1135 | 20 | 29 | return defined $t ? $t->{epoch} : undef; | |||
| 1136 | 20 | 36 | }; | |||
| 1137 | } | |||||
| 1138 | ||||||
| 1139 | 170 | 194 | my $interval = defined $const ? span_interval($const) : undef; | |||
| 1140 | 170 | 143 | croak _fmt('error_span_interval', defined $const ? $const : '') | |||
| 1141 | unless $interval; | |||||
| 1142 | 160 310 | 247 208 | return sub { _span_label($value_fn->($_[0]), $interval) }; | |||
| 1143 | } | |||||
| 1144 | ||||||
| 1145 | 223 | 418 | $$pos_ref++; # consume '(' | |||
| 1146 | 223 | 92 | my @arg_fns; | |||
| 1147 | 223 | 136 | if ($tokens->[$$pos_ref]{type} ne $T_RPAREN) { | |||
| 1148 | 219 | 343 | push @arg_fns, _parse_cmp($tokens, $pos_ref, $depth_ref, $cols); | |||
| 1149 | 209 | 144 | while ($tokens->[$$pos_ref]{type} eq $T_COMMA) { | |||
| 1150 | 149 | 173 | $$pos_ref++; | |||
| 1151 | 149 | 79 | push @arg_fns, _parse_cmp($tokens, $pos_ref, $depth_ref, $cols); | |||
| 1152 | } | |||||
| 1153 | } | |||||
| 1154 | 213 | 343 | _expect($tokens, $pos_ref, $T_RPAREN); | |||
| 1155 | ||||||
| 1156 | # 'if' special form: short-circuit true/false branches | |||||
| 1157 | 212 | 127 | if ($lc eq 'if') { | |||
| 1158 | 44 | 18 | my ($cond_fn, $true_fn, $false_fn) = @arg_fns; | |||
| 1159 | return sub { | |||||
| 1160 | 42 | 68 | $cond_fn->($_[0]) ? $true_fn->($_[0]) : $false_fn->($_[0]); | |||
| 1161 | 44 | 58 | }; | |||
| 1162 | } | |||||
| 1163 | ||||||
| 1164 | 168 | 100 | my $fn = $FUNCTIONS{$lc}; | |||
| 1165 | return sub { | |||||
| 1166 | 193 | 98 | my $row = $_[0]; | |||
| 1167 | 193 270 | 106 135 | $fn->(map { $_->($row) } @arg_fns); | |||
| 1168 | 168 | 211 | }; | |||
| 1169 | } | |||||
| 1170 | ||||||
| 1171 | # Parse a column reference; validates against the whitelist at compile time. | |||||
| 1172 | # Underscores in the expression may match spaces in the actual column name, | |||||
| 1173 | # and the comparison is case-insensitive, so per_unit_price can address | |||||
| 1174 | # a column named "Per Unit Price". | |||||
| 1175 | sub _parse_colref { | |||||
| 1176 | 821 | 1719 | my ($cols, $name, $name_pos) = @_; | |||
| 1177 | ||||||
| 1178 | # 1. Exact match | |||||
| 1179 | 821 1115 | 1349 789 | return sub { $_[0]->{$name} } if $cols->{$name}; | |||
| 1180 | ||||||
| 1181 | # 2. Underscore-to-space alias, case-insensitive | |||||
| 1182 | 112 | 198 | (my $spaced = $name) =~ s/_/ /g; | |||
| 1183 | 112 | 137 | my $lc_spaced = lc($spaced); | |||
| 1184 | 112 112 | 85 169 | for my $col (keys %{$cols}) { | |||
| 1185 | 207 | 180 | if (lc($col) eq $lc_spaced) { | |||
| 1186 | 4 | 4 | my $lookup = $col; | |||
| 1187 | 4 4 | 4 3 | return sub { $_[0]->{$lookup} }; | |||
| 1188 | } | |||||
| 1189 | } | |||||
| 1190 | ||||||
| 1191 | 108 | 195 | croak _fmt('error_unknown_col', $name); | |||
| 1192 | } | |||||
| 1193 | ||||||
| 1194 | # --------------------------------------------------------------------------- | |||||
| 1195 | # Standalone date-normalisation helper (used by Dashboard::_apply_date_normalization) | |||||
| 1196 | # --------------------------------------------------------------------------- | |||||
| 1197 | ||||||
| 1198 | # _iso_day_label($epoch) -> 'YYYY-MM-DD' in local time | |||||
| 1199 | sub _iso_day_label { | |||||
| 1200 | 2 | 2 | my @lt = Database::BI::Util::local_wall($_[0]); | |||
| 1201 | 2 | 9 | return sprintf '%04d-%02d-%02d', $lt[5] + 1900, $lt[4] + 1, $lt[3]; | |||
| 1202 | } | |||||
| 1203 | ||||||
| 1204 | # _normalise_with_format($value, \%pattern) -> ISO string or undef | |||||
| 1205 | # | |||||
| 1206 | # The hash shape of a stored pattern: { date => '<fmt>', [time => '<fmt'>], | |||||
| 1207 | # [as => 'timestamp'] }. With a time pattern the value is normalised to | |||||
| 1208 | # 'YYYY-MM-DDTHH:MM:SS', which is the shape the date comparisons already read | |||||
| 1209 | # to the second; with as => 'timestamp' and no time pattern it is that same | |||||
| 1210 | # shape at midnight, so a date-only column can be compared against a | |||||
| 1211 | # last_24_hours window. | |||||
| 1212 | sub _normalise_with_format { | |||||
| 1213 | 33 | 27 | my ($val, $pattern) = @_; | |||
| 1214 | 33 | 57 | return undef unless defined $pattern->{date} && length $pattern->{date}; | |||
| 1215 | ||||||
| 1216 | # The pattern is stored JSON and the caller has no eval: one that cannot be | |||||
| 1217 | # compiled is an unknown pattern, which is undef, not a 500 on every page. | |||||
| 1218 | 31 | 23 | my $time_fmt = $pattern->{time}; | |||
| 1219 | 31 | 45 | if (defined $time_fmt && length $time_fmt) { | |||
| 1220 | 23 23 | 15 29 | my $compiled = eval { _fmt_compile_pair($pattern->{date}, $time_fmt) } or return undef; | |||
| 1221 | 22 | 27 | my $t = _time_from_format($val, $compiled); | |||
| 1222 | 22 | 29 | return undef unless $t; | |||
| 1223 | 21 | 23 | return _iso_second_label($t->{epoch}); | |||
| 1224 | } | |||||
| 1225 | ||||||
| 1226 | 8 8 | 4 11 | my $compiled = eval { _fmt_compile($pattern->{date}) } or return undef; | |||
| 1227 | 5 | 5 | my $t = _time_from_format($val, $compiled); | |||
| 1228 | 5 | 10 | return undef unless $t; | |||
| 1229 | return ($pattern->{as} // '') eq 'timestamp' | |||||
| 1230 | ? _iso_second_label($t->{epoch}) | |||||
| 1231 | 3 | 9 | : _iso_day_label($t->{epoch}); | |||
| 1232 | } | |||||
| 1233 | ||||||
| 1234 | # _iso_date_if_real($y, $mon, $day) -> 'YYYY-MM-DD' or undef | |||||
| 1235 | # | |||||
| 1236 | # A UK file read with the US pattern has "months" up to 31. Undef sends it to the | |||||
| 1237 | # '(unparseable)' bucket, where it can be seen; "2026-15-01" looks like a date and | |||||
| 1238 | # sorts among the real ones. | |||||
| 1239 | sub _iso_date_if_real { | |||||
| 1240 | 40 | 1203 | my ($y, $mon, $day) = @_; | |||
| 1241 | 40 | 70 | return undef unless defined _epoch_of($y + 0, $mon + 0, $day + 0, 12, 0, 0); | |||
| 1242 | 27 | 75 | return sprintf('%04d-%02d-%02d', $y, $mon, $day); | |||
| 1243 | } | |||||
| 1244 | ||||||
| 1245 | # date_normalise($value, $pattern) -> ISO string or undef | |||||
| 1246 | # | |||||
| 1247 | # Converts $value from the given strptime-style $pattern to ISO-8601. | |||||
| 1248 | # Returns undef when $value does not match the pattern or the pattern is | |||||
| 1249 | # unknown. No external modules required. | |||||
| 1250 | # | |||||
| 1251 | # $pattern is either one of the three date patterns below, or a hashref | |||||
| 1252 | # { date => ..., time => ..., as => ... } for a column that holds a time as | |||||
| 1253 | # well as a date; see _normalise_with_format. | |||||
| 1254 | # | |||||
| 1255 | # Supported date patterns: | |||||
| 1256 | # %m/%d/%Y -- US slash-date (01/15/2026) | |||||
| 1257 | # %d/%m/%Y -- EU slash-date (15/01/2026) | |||||
| 1258 | # %d-%b-%Y -- DD-Mon-YYYY (15-Jan-2026, case-insensitive month abbrev) | |||||
| 1259 | sub date_normalise { | |||||
| 1260 | 92 | 10893 | my ($val, $pattern) = @_; | |||
| 1261 | 92 | 193 | local $!; # mktime and localtime may set errno; see _epoch_of | |||
| 1262 | 92 | 205 | return undef unless defined $val && defined $pattern && length $val; | |||
| 1263 | 81 | 98 | return _normalise_with_format($val, $pattern) if ref $pattern eq 'HASH'; | |||
| 1264 | 48 | 56 | if ($pattern eq '%m/%d/%Y') { | |||
| 1265 | 22 | 47 | return undef unless $val =~ /\A(\d{1,2})\/(\d{1,2})\/(\d{4})\z/; | |||
| 1266 | 18 | 27 | return _iso_date_if_real($3, $1, $2); | |||
| 1267 | } elsif ($pattern eq '%d/%m/%Y') { | |||||
| 1268 | 13 | 25 | return undef unless $val =~ /\A(\d{1,2})\/(\d{1,2})\/(\d{4})\z/; | |||
| 1269 | 8 | 7 | return _iso_date_if_real($3, $2, $1); | |||
| 1270 | } elsif ($pattern eq '%d-%b-%Y') { | |||||
| 1271 | 10 | 22 | return undef unless $val =~ /\A(\d{1,2})-([A-Za-z]{3})-(\d{4})\z/; | |||
| 1272 | 8 | 22 | my $mon = $_MONTH_NAME_TO_NUM{lc($2)}; | |||
| 1273 | 8 | 27 | return undef unless defined $mon; | |||
| 1274 | 6 | 6 | return _iso_date_if_real($3, $mon, $1); | |||
| 1275 | } | |||||
| 1276 | 3 | 6 | return undef; | |||
| 1277 | } | |||||
| 1278 | ||||||
| 1279 | 1; | |||||
| 1280 | ||||||