File Coverage

File:blib/lib/Database/BI/Util.pm
Coverage:92.7%

linestmtbrancondsubtimecode
1package Database::BI::Util;
2
3
146
146
146
834006
83
906
use strict;
4
146
146
146
140
70
2664
use warnings;
5
6our $VERSION = '0.025.0';
7
8
146
146
146
131
89
924
use Exporter qw(import);
9
146
146
146
3920
35567
1684
use Readonly;
10
146
146
146
3646
60668
740
use POSIX ();
11
146
146
146
2926
2524
43541
use Carp qw(croak);
12
13our @EXPORT_OK = qw( urlencode parse_number iso_datetime minute_stamp iso8601_utc
14        parse_zone zone_wall frame_epoch local_epoch local_wall data_windows );
15
16# A list rather than any three capitals, or 'SKU 100' would be read as 100.
17Readonly my $CURRENCY_CODES => join '|', qw(AUD BRL CAD CHF CNY DKK EUR GBP HKD INR JPY MXN NOK NZD SEK SGD USD ZAR);
18# The largest number a chart can use: a C double's, which is what the browser
19# has (parseAccounting refuses what is not isFinite there).  Not perl's own
20# infinity: a perl built with -Duselongdouble or -Dusequadmath holds 1e999 as
21# a finite number, so comparing with infinity let it through on those perls
22# alone (GitHub issue 6).
23Readonly my $LARGEST_NUMBER => POSIX::DBL_MAX();
24
25# A date, or a date and a time with T or a space between them; the time may
26# carry seconds, a fraction of a second, and a zone (Z, or an offset such as
27# +01:00, +0100 or +01).  The last three are what JSON APIs and exports write.
28Readonly my $ISO_DATETIME_RE => qr{
29        \A (\d{4}-\d{2}-\d{2})
30        (?: [T ] (\d{2}) : (\d{2}) (?: : (\d{2}) (?: [.,] \d+ )? )?
31                ( [Zz] | [+-] \d{2} (?: :? \d{2} )? )? )?
32        \z
33}x;
34
35# Premise 1: iso_datetime runs once per cell of a date filter, time range or
36#            formula.
37# Premise 2: reading a Readonly scalar costs several times a plain lexical's,
38#            and a compiled regex is the same object either way.
39# Conclusion: the hot path matches against a lexical copy; the Readonly stays
40#             the one definition, so the pattern is still written once.
41my $ISO_DATETIME_FAST = $ISO_DATETIME_RE;
42
43# urlencode($str) -> $encoded
44#
45# Percent-encodes a string for use as a URI query-parameter value.
46# Preserves only the RFC 3986 unreserved characters (letters, digits,
47# hyphen, dot, underscore, tilde) and encodes everything else as %XX.
48#
49# Why a shared copy rather than Mojo::Util::url_escape:
50#   Ask.pm and Insights.pm are plain Perl modules with no Mojo dependency;
51#   pulling in Mojo::Util for a 3-line function would be an undue coupling.
52#
53# Multi-byte characters: a decoded string is encoded to its UTF-8 bytes first,
54# because ord() returns the codepoint and U+263A would print as "%263A", which
55# decodes to "&3A".  A string of bytes (the usual CSV cell) is left as it is, so
56# text that is already UTF-8 is not encoded twice.
57sub urlencode {
58
1112
46036
        my ($str) = @_;
59
1112
551
        return '' unless defined $str;
60
1108
585
        utf8::encode($str) if utf8::is_utf8($str);
61        # '-' placed at end of character class to avoid ambiguity with a range.
62
1108
2138
666
1492
        $str =~ s/([^A-Za-z0-9._~-])/sprintf('%%%02X', ord($1))/ge;
63
1108
879
        return $str;
64}
65
66# Only what dresses up a number is removed: spaces, brackets, thousands
67# separators, a percent sign, currency symbols and a known currency code.  Any
68# other letter stays and fails the match, so 'SKU123' and 'AB-100' are text
69# rather than 123 and -100.  The bracket is read before it is removed.
70# The browser's parseAccounting (layouts/parse_accounting.html.tt) is a copy,
71# so a table sorts the same on the server as on the page: change one, change
72# the other.
73sub parse_number {
74
14634
35117
        my $value = $_[0];
75
76
14634
10999
        return undef unless defined($value) && length($value);
77
78        # Premise 1: the slow path below only removes spaces, brackets, commas, $, %,
79        #            non-ASCII and currency codes before matching a plain decimal.
80        # Premise 2: an ASCII plain decimal contains none of those.
81        # Premise 3: at most 300 integer digits is below 1e300, under DBL_MAX.
82        # Conclusion: such a cell reaches the same number without the substitutions
83        #             or the range check (a Readonly read costs several times a
84        #             lexical's); longer ones take the full path.
85
14579
15043
        return $value + 0 if $value =~ /\A-?[0-9]{1,300}(?:\.[0-9]+)?\z/;
86
87
2935
1652
        my $is_accounting = ($value =~ /\A\s*\(/);
88
2935
3142
        (my $text = $value) =~ s/(?:\A|(?<=[\s(]))(?:$CURRENCY_CODES)(?=[\s\d.])|(?<=[\s\d])(?:$CURRENCY_CODES)(?=[\s)]|\z)//g;
89
2935
36554
        $text =~ s/[\s(),\$%]|[^\x00-\x7F]//g;
90
2935
2466
        $text = "-$text" if $is_accounting && $text =~ /\A\d/;
91
2935
10138
        return undef unless $text =~ /\A-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?\z/;
92
93
241
251
        my $number = $text + 0;
94
95        # 1e999 spells a number, but one past a double's range is infinity in the
96        # browser, which is no use to a total or an axis -- on every perl.
97
241
195
        return undef unless abs($number) <= $LARGEST_NUMBER;
98
224
528
        return $number;
99}
100
101# The zone the server works in, or undef (the default: a time is as written).
102# A { kind => 'fixed', offset => seconds } or { kind => 'local' } from
103# parse_zone.  The app's around_dispatch hook sets it with `local` from config
104# time_zone, so it is the one setting every reader of a time sees.
105our $ZONE;
106
107# parse_zone($spec) -> \%zone | undef
108#
109# 'UTC' (or 'Z', 'GMT'), 'local' (the server's own zone, daylight saving
110# included), or a fixed offset: +05:30, -0800, +01.  undef and '' are no zone.
111# Anything else croaks, so a typo in the configuration stops the start.
112sub parse_zone {
113
413
8051
        my ($spec) = @_;
114
413
844
        return undef unless defined $spec && length $spec;
115
20
35
        croak "time_zone: '" . (ref $spec || $spec) . "' is not UTC, local, or an offset such as +05:30"
116                if ref $spec;
117
18
46
        return { kind => 'fixed', offset => 0 } if $spec =~ /\A(?:utc|gmt|z)\z/i;
118
15
17
        return { kind => 'local' }             if $spec =~ /\Alocal\z/i;
119
13
31
        if (my ($sign, $hh, $mm) = $spec =~ /\A([+-])([0-9]{2})(?::?([0-9]{2}))?\z/) {
120
9
26
                croak "time_zone: '$spec' is not UTC, local, or an offset such as +05:30"
121                        unless $hh <= 14 && ($mm // 0) <= 59;
122
6
6
                my $secs = $hh * 3_600 + ($mm // 0) * 60;
123
6
12
                return { kind => 'fixed', offset => $sign eq '-' ? -$secs : $secs };
124        }
125
4
32
        croak "time_zone: '$spec' is not UTC, local, or an offset such as +05:30";
126}
127
128# zone_wall($epoch) -> (sec, min, hour, mday, mon, year, wday, yday, isdst)
129#
130# What localtime gives, but in the configured zone: the clock on the wall
131# there at that moment.  With no zone it is localtime.
132sub zone_wall {
133
28
12
        my ($epoch) = @_;
134
28
39
        local $!;       # localtime's tzset may leave errno set; see Calc::_epoch_of
135        return ($ZONE && $ZONE->{kind} eq 'fixed')
136                ? gmtime($epoch + $ZONE->{offset})
137
28
85
                : localtime($epoch);
138}
139
140# The C library cannot be asked about old dates everywhere: Windows has no
141# mktime or localtime before 1970, and on macOS a date in 1887 came back
142# undefined.  So before 1971 the calendar arithmetic is done here, at the fixed
143# offset the server has at the start of 1971.  Both directions use the same
144# offset and the same boundary, so they agree with each other and join the C
145# library's answers with no gap and no overlap.
146
147# 1971-01-01T00:00:00 as seconds, with no zone applied.
148
146
146
146
251
105
75010
use constant _YEAR_1971 => 31_536_000;
149
150# The seconds to add to a UTC reading to get the server's epoch in 1971.
151sub _old_offset {
152
98
111
        my $start = POSIX::mktime(0, 0, 0, 1, 0, 71);
153
98
272
        return defined $start ? $start - _YEAR_1971 : 0;
154}
155
156# local_epoch($sec, $min, $hour, $mday, $mon, $year) -> $epoch | undef
157#
158# POSIX::mktime for any year.  $mon is 0-based and $year is years since 1900,
159# and values out of range carry over (day 0, month -1), as in mktime.
160sub local_epoch {
161
541
79440
        my ($sec, $min, $hour, $mday, $mon, $year) = @_;
162
541
296
        local $!;       # mktime's tzset may leave errno set; see Calc::_epoch_of
163
541
328
        my $carry = int($mon / 12);
164
541
565
        $carry-- if $mon % 12 && $mon < 0;
165
541
401
        my $naive = (_days_from_civil($year + 1900 + $carry, $mon % 12 + 1, 1) + $mday - 1) * 86_400
166                + $hour * 3_600 + $min * 60 + $sec;
167
541
339
        return $naive + _old_offset() if $naive < _YEAR_1971;
168
504
1771
        return POSIX::mktime($sec, $min, $hour, $mday, $mon, $year);
169}
170
171# local_wall($epoch) -> (sec, min, hour, mday, mon, year, wday, yday, isdst)
172#
173# localtime for any year.
174sub local_wall {
175
921
444
        my ($epoch) = @_;
176
921
494
        local $!;
177        # Two days of margin cover every offset without asking for it each time.
178
921
1482
        return localtime($epoch) if $epoch >= _YEAR_1971 + 172_800;
179
61
29
        my $offset = _old_offset();
180
61
41
        return localtime($epoch) if $epoch >= _YEAR_1971 + $offset;
181
182
59
37
        my $t    = POSIX::floor($epoch - $offset);
183
59
35
        my $days = POSIX::floor($t / 86_400);
184
59
27
        my $secs = $t - $days * 86_400;
185
186        # The civil date of a day number: _days_from_civil run backwards.
187
59
19
        my $z   = $days + 719_468;
188
59
44
        my $era = POSIX::floor($z / 146_097);
189
59
22
        my $doe = $z - $era * 146_097;
190
59
41
        my $yoe = int(($doe - int($doe / 1_460) + int($doe / 36_524) - int($doe / 146_096)) / 365);
191
59
28
        my $doy = $doe - (365 * $yoe + int($yoe / 4) - int($yoe / 100));
192
59
32
        my $mp  = int((5 * $doy + 2) / 153);
193
59
29
        my $day = $doy - int((153 * $mp + 2) / 5) + 1;
194
59
23
        my $mon = $mp < 10 ? $mp + 3 : $mp - 9;
195
59
35
        my $y   = $yoe + $era * 400 + ($mon <= 2 ? 1 : 0);
196
197
59
44
        return ($secs % 60, int($secs / 60) % 60, int($secs / 3_600), $day, $mon - 1, $y - 1900,
198                ($days + 4) % 7, $days - _days_from_civil($y, 1, 1), 0);
199}
200
201# frame_epoch($epoch) -> $epoch'
202#
203# The date code (Calc, the time range) reads a clock with localtime and builds
204# one with mktime, so it lives in the server's zone.  For a time read in
205# another zone this gives the epoch whose localtime shows that zone's wall
206# clock; with no zone, or the server's own, it is $epoch.
207sub frame_epoch {
208
60628
25419
        my ($epoch) = @_;
209
60628
42617
        return $epoch unless $ZONE && $ZONE->{kind} eq 'fixed';
210
14
11
        my @wall = zone_wall($epoch);
211
14
10
        local $!;
212
14
8
        return local_epoch(@wall[0 .. 5]) // $epoch;
213}
214
215# _days_from_civil($y, $m, $d) -> days since 1970-01-01 (proleptic Gregorian)
216sub _days_from_civil {
217
768
432
        my ($y, $m, $d) = @_;
218
768
480
        $y -= $m <= 2 ? 1 : 0;
219
768
556
        my $era = int(($y >= 0 ? $y : $y - 399) / 400);
220
768
376
        my $yoe = $y - $era * 400;
221
768
606
        my $doy = int((153 * ($m + ($m > 2 ? -3 : 9)) + 2) / 5) + $d - 1;
222
768
446
        my $doe = $yoe * 365 + int($yoe / 4) - int($yoe / 100) + $doy;
223
768
628
        return $era * 146_097 + $doe - 719_468;
224}
225
226# _in_zone($day, $hour, $minute, $second, $zone_text) -> ($day, $h, $m, $s)
227#
228# Premise 1: a value that names a zone names one moment.
229# Premise 2: a configured zone is the clock the reader works to.
230# Conclusion: the written time is moved to that zone's clock, and the day may
231#             change with it.  A date or time that cannot exist (a 31st of
232#             February, hour 25) is left as written: the callers that need a
233#             real one refuse it, and arithmetic would make it another day.
234sub _in_zone {
235
16
15
        my ($day, $hour, $minute, $second, $zone_text) = @_;
236
16
14
        my ($y, $mon, $dom) = split /-/, $day;
237
16
36
        my @dim = (31, (($y % 4 == 0 && $y % 100 != 0) || $y % 400 == 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
238
16
61
        return ($day, $hour, $minute, $second)
239                unless $mon >= 1 && $mon <= 12 && $dom >= 1 && $dom <= $dim[$mon - 1]
240                        && $hour <= 23 && $minute <= 59 && ($second // 0) <= 59;
241
242
14
5
        my $from = 0;
243
14
20
        if ($zone_text =~ /\A([+-])([0-9]{2}):?([0-9]{2})?\z/) {
244
14
28
                $from = ($2 * 3_600 + ($3 // 0) * 60) * ($1 eq '-' ? -1 : 1);
245        }
246
14
18
        my $epoch = _days_from_civil($y + 0, $mon + 0, $dom + 0) * 86_400
247                + $hour * 3_600 + $minute * 60 + ($second // 0) - $from;
248
14
12
        my @wall = zone_wall($epoch);
249        return (
250
14
58
                sprintf('%04d-%02d-%02d', $wall[5] + 1900, $wall[4] + 1, $wall[3]),
251                sprintf('%02d', $wall[2]),
252                sprintf('%02d', $wall[1]),
253                defined $second ? sprintf('%02d', $wall[0]) : undef,
254        );
255}
256
257# iso_datetime($value) -> ($day, $hour, $minute, $second) | ()
258#
259# The one reading of an ISO date or timestamp, for the filters, the time range
260# and the formulas alike.  A fraction of a second is set aside.  A time that
261# names a zone (Z, +01:00) is moved to the configured zone ($ZONE, config
262# time_zone) when there is one, so 2026-11-06T23:30:00Z is 18:30 on the 6th
263# for -05:00; with no zone configured, or a time with none written, the time
264# is taken as written and the value is the day the table shows.
265sub iso_datetime {
266
6510
120875
        my ($value) = @_;
267
6510
6382
        return () unless defined $value && !ref $value;
268
6502
11372
        my ($day, $hour, $minute, $second, $zone) = $value =~ $ISO_DATETIME_FAST or return ();
269
3185
4598
        return ($day, $hour, $minute, $second) unless defined $zone && $ZONE;
270
16
19
        return _in_zone($day, $hour, $minute, $second, $zone =~ /\A[Zz]\z/ ? '+00:00' : $zone);
271}
272
273# minute_stamp(@tm) -> 'YYYY-MM-DD HH:MM'
274# iso8601_utc($epoch) -> 'YYYY-MM-DDTHH:MM:SSZ'
275#
276# Written with sprintf rather than POSIX::strftime: on Windows, perl 5.38's
277# strftime did not return (CI sat in t/function.t until the job's limit),
278# and these fixed formats need nothing from the C library.
279sub minute_stamp {
280
305
2011
        my @tm = @_;
281
305
227
        return '' unless @tm >= 6;
282
303
615
        return sprintf '%04d-%02d-%02d %02d:%02d', $tm[5] + 1900, $tm[4] + 1, $tm[3], $tm[2], $tm[1];
283}
284
285sub iso8601_utc {
286
27
33
        my ($epoch) = @_;
287
27
70
        my @tm = gmtime(defined $epoch ? $epoch : time);
288
27
140
        return sprintf '%04d-%02d-%02dT%02d:%02d:%02dZ', $tm[5] + 1900, $tm[4] + 1, $tm[3], $tm[2], $tm[1], $tm[0];
289}
290
291# _civil_from_days($days) -> ($y, $m, $d)
292#
293# The inverse of _days_from_civil above (Howard Hinnant's calendar arithmetic),
294# in whole days and no clock: a window anchored to the data is a matter of
295# dates, and mktime would make it depend on the server's zone.
296sub _civil_from_days {
297
128
57
        my ($z) = @_;
298
128
49
        $z += 719_468;
299
128
72
        my $era = int(($z >= 0 ? $z : $z - 146_096) / 146_097);
300
128
50
        my $doe = $z - $era * 146_097;
301
128
83
        my $yoe = int(($doe - int($doe / 1_460) + int($doe / 36_524) - int($doe / 146_096)) / 365);
302
128
66
        my $doy = $doe - (365 * $yoe + int($yoe / 4) - int($yoe / 100));
303
128
61
        my $mp  = int((5 * $doy + 2) / 153);
304
128
64
        my $d   = $doy - int((153 * $mp + 2) / 5) + 1;
305
128
60
        my $m   = $mp + ($mp < 10 ? 3 : -9);
306
128
65
        my $y   = $yoe + $era * 400 + ($m <= 2 ? 1 : 0);
307
128
121
        return ($y, $m, $d);
308}
309
310# _plus_years($y, $m, $d, $n) -> days since 1970-01-01 of the same day $n years on
311# (29 February lands on the 28th in a year that has none).
312sub _plus_years {
313
62
45
        my ($y, $m, $d, $n) = @_;
314
62
23
        $y += $n;
315
62
81
        my $leap = ($y % 4 == 0 && $y % 100 != 0) || $y % 400 == 0;
316
62
57
        $d = 28 if $m == 2 && $d == 29 && !$leap;
317
62
37
        return _days_from_civil($y, $m, $d);
318}
319
320# data_windows($min, $max) -> \@windows
321#
322# Purpose: Windows anchored to the data rather than to today: the first and
323#          the last decade and year of a column's own extent.  Only a window
324#          shorter than the extent is offered, because one as long as the data
325#          would show every row.
326# Entry:   $min and $max are 'YYYY-MM-DD', the column's earliest and latest day.
327# Exit:    A list of { name, label, lo, hi }, 'YYYY-MM-DD' bounds that are
328#          inclusive at both ends; [] when either bound is not a date or min is
329#          after max.
330# Notes:   A window is ten (or one) calendar years counted from the first day
331#          in the data: 1883-04-09 starts the first decade, which ends on
332#          1893-04-08.  The last window is counted back from the last day the
333#          same way.  It does not read the clock.
334sub data_windows {
335
32
77721
        my ($min, $max) = @_;
336
32
20
        my @parts;
337
32
22
        for my $day ($min, $max) {
338
56
133
                return [] unless defined $day && !ref $day && $day =~ /\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/;
339
49
68
                my ($y, $m, $d) = ($1 + 0, $2 + 0, $3 + 0);
340
49
101
                return [] unless $m >= 1 && $m <= 12 && $d >= 1 && $d <= 31;
341
48
44
                my @back = _civil_from_days(_days_from_civil($y, $m, $d));
342
48
72
                return [] unless "@back" eq "$y $m $d";     # 31 February is not a day
343
46
54
                push @parts, [ $y, $m, $d ];
344        }
345
22
22
16
20
        my $first = _days_from_civil(@{ $parts[0] });
346
22
22
16
19
        my $last  = _days_from_civil(@{ $parts[1] });
347
22
22
        return [] if $first > $last;
348
349
21
80
28
45
        my $iso = sub { sprintf '%04d-%02d-%02d', _civil_from_days($_[0]) };
350
21
12
        my @out;
351
21
29
        for my $span ([ decade => 10, 'decade' ], [ year => 1, 'year' ]) {
352
42
28
                my ($name, $years, $word) = @$span;
353
42
42
17
29
                my $end = _plus_years(@{ $parts[0] }, $years) - 1;
354
42
35
                next unless $end < $last;    # the data is longer than the window
355
20
22
                push @out, { name => "data_first_$name", label => "First $word in the data",
356                        lo => $iso->($first), hi => $iso->($end) };
357
20
20
13
12
                my $start = _plus_years(@{ $parts[1] }, -$years) + 1;
358
20
17
                push @out, { name => "data_last_$name", label => "Last $word in the data",
359                        lo => $iso->($start), hi => $iso->($last) };
360        }
361
21
76
        return \@out;
362}
363
3641;
365