packages/sql-semantics-mysql/src/Statement/Type/Decimal.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Type;
6
7use SqlSemantics\Platform\MySql\Model\Diagnostic\Check;
8use SqlSemantics\Platform\MySql\Model\Rendering\Output;
9use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
10use SqlSemantics\Platform\MySql\Statement\Type\Kind\NumericModifier;
11
12/**
13 * The exact fixed-point type DECIMAL with its optional precision and scale.
14 *
15 * `DEC`, `NUMERIC` and `FIXED` are synonyms of `DECIMAL`. A precision without
16 * a scale is written `DECIMAL(M)`.
17 * Source: https://dev.mysql.com/doc/refman/8.4/en/fixed-point-types.html.
18 *
19 * @visibility public
20 * @example Reading a fixed-point type
21 * $type = new \SqlSemantics\Platform\MySql\Statement\Type\Decimal('10', '2');
22 * [$type->name(), $type->precision, $type->scale] // => ['DECIMAL', '10', '2']
23 */
24final class Decimal implements TypeName
25{
26 use Snapshot;
27
28 /**
29 * @var list<NumericModifier> The attributes in the order written; an attribute may repeat
30 */
31 public readonly array $modifiers;
32
33 /**
34 * @param string|null $precision The precision exactly as written
35 * @param string|null $scale The scale exactly as written; requires a precision
36 * @param list<NumericModifier> $modifiers The attributes in the order written
37 */
38 public function __construct(public readonly ?string $precision = null, public readonly ?string $scale = null, array $modifiers = [])
39 {
40 Check::input($precision === null || preg_match('/\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/', $precision) === 1, 'A precision is an unsigned number.');
41 Check::input($scale === null || ($precision !== null && preg_match('/\A[0-9]+\z/', $scale) === 1), 'A scale is an unsigned integer written after a precision.');
42 $this->modifiers = Check::listOf($modifiers, NumericModifier::class, 'Numeric attributes are SIGNED, UNSIGNED and ZEROFILL.');
43 }
44
45 /**
46 * Names the type by its keyword.
47 */
48 public function name(): string
49 {
50 return 'DECIMAL';
51 }
52
53 /**
54 * Writes the keyword, the precision and scale, and the attributes.
55 */
56 public function render(Output $out): void
57 {
58 $out->keyword('DECIMAL');
59 if ($this->precision !== null) {
60 $out->glue()->symbol('(')->spelled($this->precision);
61 if ($this->scale !== null) {
62 $out->symbol(',')->spelled($this->scale);
63 }
64 $out->symbol(')');
65 }
66 foreach ($this->modifiers as $modifier) {
67 $out->keyword($modifier->value);
68 }
69 }
70}
71