packages/sql-semantics-mysql/src/Statement/Call/Clock.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Call;
6
7use SqlSemantics\Platform\MySql\Rules\Call\TypeClass;
8
9/**
10 * The functions that read the current date or time of the statement or of the system clock.
11 *
12 * Each case holds the keyword the function is written with. CURRENT_DATE is
13 * the keyword CURDATE, CURRENT_TIME is CURTIME, and CURRENT_TIMESTAMP,
14 * LOCALTIME and LOCALTIMESTAMP are NOW to the lexer. NOW and its synonyms
15 * read the time the statement started; SYSDATE reads the time it executes.
16 * Source: https://dev.mysql.com/doc/refman/8.4/en/date-and-time-functions.html#function_now.
17 *
18 * @visibility public
19 * @example Reading the keyword of a case
20 *     \SqlSemantics\Platform\MySql\Statement\Call\Clock::Now->value // => 'NOW'
21 */
22enum Clock: string
23{
24    case Now = 'NOW';
25    case CurrentTime = 'CURTIME';
26    case SystemDate = 'SYSDATE';
27    case UtcTime = 'UTC_TIME';
28    case UtcTimestamp = 'UTC_TIMESTAMP';
29    case CurrentDate = 'CURDATE';
30    case UtcDate = 'UTC_DATE';
31
32    /**
33     * Tells whether the function takes a fractional seconds precision.
34     */
35    public function precise(): bool
36    {
37        return $this !== self::CurrentDate && $this !== self::UtcDate;
38    }
39
40    /**
41     * Answers the keyword that writes the function without parentheses, or null when it is only written with them.
42     *
43     * NOW, CURTIME, CURDATE and SYSDATE are keywords only before an opening
44     * parenthesis (`SYM_FN` in sql/lex.h); without one the function is
45     * written CURRENT_TIMESTAMP, CURRENT_TIME or CURRENT_DATE, and SYSDATE
46     * cannot be.
47     *
48     * @example Reading the keyword NOW is written with without parentheses
49     *     \SqlSemantics\Platform\MySql\Statement\Call\Clock::Now->bare() // => 'CURRENT_TIMESTAMP'
50     */
51    public function bare(): ?string
52    {
53        return match ($this) {
54            self::Now => 'CURRENT_TIMESTAMP',
55            self::CurrentTime => 'CURRENT_TIME',
56            self::CurrentDate => 'CURRENT_DATE',
57            self::SystemDate => null,
58            self::UtcTime, self::UtcTimestamp, self::UtcDate => $this->value,
59        };
60    }
61
62    /**
63     * Answers the class of the type the function returns.
64     */
65    public function result(): TypeClass
66    {
67        return match ($this) {
68            self::Now, self::SystemDate, self::UtcTimestamp => TypeClass::DateTime,
69            self::CurrentTime, self::UtcTime => TypeClass::Time,
70            self::CurrentDate, self::UtcDate => TypeClass::Date,
71        };
72    }
73}
74