packages/sql-semantics-postgres/src/Lowering/Table/ColumnRule.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Lowering\Table;
6
7use SqlParser\Parser\Node;
8use SqlSemantics\Platform\PostgreSql\Lowering\Lowering;
9use SqlSemantics\Platform\PostgreSql\Model\Diagnostic\ImplementationGap;
10use SqlSemantics\Platform\PostgreSql\Model\Lowering\Form;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
12use SqlSemantics\Platform\PostgreSql\Statement\Clause;
13use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Column\ColumnCheck;
14use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Column\ColumnPrimaryKey;
15use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Column\ColumnUnique;
16use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Column\DefaultExpression;
17use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Column\Generated;
18use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Column\GeneratedWhen;
19use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Column\Identity;
20use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Column\NotNull;
21use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Column\NullAllowed;
22use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Column\References;
23use SqlSemantics\Platform\PostgreSql\Statement\Constraint\ColumnCollation;
24use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Constraint;
25use SqlSemantics\Platform\PostgreSql\Statement\Constraint\ConstraintAttribute;
26use SqlSemantics\Platform\PostgreSql\Statement\Table\Element\ColumnCompression;
27use SqlSemantics\Platform\PostgreSql\Statement\Table\Element\ColumnDefinition;
28use SqlSemantics\Platform\PostgreSql\Statement\Table\Element\ColumnOptions;
29use SqlSemantics\Platform\PostgreSql\Statement\Table\Element\ColumnStorage;
30use SqlSemantics\Platform\PostgreSql\Statement\Table\Element\LikeClause;
31use SqlSemantics\Platform\PostgreSql\Statement\Table\Element\LikeOption;
32use SqlSemantics\Platform\PostgreSql\Statement\Table\Element\LikeOptionKind;
33
34/**
35 * Lowers the elements of a table definition: column definitions, column options, column constraints and LIKE.
36 *
37 * Rule: PG-COLUMN-LOWER-001. Scope: `columnDef`, `columnOptions`,
38 * `column_compression`, `opt_column_compression`, `column_storage`,
39 * `opt_column_storage`, `ColQualList`, `ColConstraint`,
40 * `ColConstraintElem`, `generated_when`, `ConstraintAttr`, `opt_no_inherit`,
41 * `TableLikeClause`, `TableLikeOptionList`, `TableLikeOption`, and the
42 * element lists of `CreateTableRule`. A constraint name is kept on its
43 * constraint. WITH OPTIONS in `columnOptions` is noise (TableNoise).
44 * Termination: lists are flattened iteratively. Source:
45 * https://www.postgresql.org/docs/17/sql-createtable.html. Status: Implemented.
46 *
47 * @visibility SqlSemantics
48 */
49final class ColumnRule
50{
51    /**
52     * The attribute each `ConstraintAttr` production writes.
53     */
54    private const ATTRIBUTES = [
55        'ConstraintAttr: DEFERRABLE' => ConstraintAttribute::Deferrable,
56        'ConstraintAttr: NOT DEFERRABLE' => ConstraintAttribute::NotDeferrable,
57        'ConstraintAttr: INITIALLY DEFERRED' => ConstraintAttribute::InitiallyDeferred,
58        'ConstraintAttr: INITIALLY IMMEDIATE' => ConstraintAttribute::InitiallyImmediate,
59    ];
60
61    /**
62     * The property each `TableLikeOption` production names.
63     */
64    private const LIKE = [
65        'TableLikeOption: COMMENTS' => LikeOptionKind::Comments, 'TableLikeOption: COMPRESSION' => LikeOptionKind::Compression,
66        'TableLikeOption: CONSTRAINTS' => LikeOptionKind::Constraints, 'TableLikeOption: DEFAULTS' => LikeOptionKind::Defaults,
67        'TableLikeOption: IDENTITY_P' => LikeOptionKind::Identity, 'TableLikeOption: GENERATED' => LikeOptionKind::Generated,
68        'TableLikeOption: INDEXES' => LikeOptionKind::Indexes, 'TableLikeOption: STATISTICS' => LikeOptionKind::Statistics,
69        'TableLikeOption: STORAGE' => LikeOptionKind::Storage, 'TableLikeOption: ALL' => LikeOptionKind::All,
70    ];
71
72    /**
73     * @param Lowering $lowering The hub
74     */
75    public function __construct(private readonly Lowering $lowering)
76    {
77    }
78
79    /**
80     * Lowers `OptTableElementList`.
81     *
82     * @return list<ColumnDefinition|LikeClause|Constraint>
83     *
84     * @throws ImplementationGap When the production has no rule
85     */
86    public function elements(Node $list): array
87    {
88        $form = $this->lowering->productions->form($list);
89        if ($form->signature === 'OptTableElementList:') {
90            return [];
91        }
92        if ($form->signature !== 'OptTableElementList: TableElementList') {
93            throw ImplementationGap::production($form);
94        }
95        $elements = [];
96        foreach ($this->lowering->items($form->node(0), 'TableElementList: TableElement', 'TableElementList: TableElementList , TableElement') as $item) {
97            $element = $this->lowering->productions->form($item);
98            $elements[] = match ($element->signature) {
99                'TableElement: columnDef' => $this->column($element->node(0)),
100                'TableElement: TableLikeClause' => $this->like($element->node(0)),
101                'TableElement: TableConstraint' => $this->lowering->tables->tableConstraint($element->node(0)),
102                default => throw ImplementationGap::production($element),
103            };
104        }
105
106        return $elements;
107    }
108
109    /**
110     * Lowers `OptTypedTableElementList`.
111     *
112     * @return list<Clause>
113     *
114     * @throws ImplementationGap When the production has no rule
115     */
116    public function typedElements(Node $list): array
117    {
118        $form = $this->lowering->productions->form($list);
119        if ($form->signature === 'OptTypedTableElementList:') {
120            return [];
121        }
122        if ($form->signature !== 'OptTypedTableElementList: ( TypedTableElementList )') {
123            throw ImplementationGap::production($form);
124        }
125        $elements = [];
126        foreach ($this->lowering->items($form->node(1), 'TypedTableElementList: TypedTableElement', 'TypedTableElementList: TypedTableElementList , TypedTableElement') as $item) {
127            $element = $this->lowering->productions->form($item);
128            $elements[] = match ($element->signature) {
129                'TypedTableElement: columnOptions' => $this->options($element->node(0)),
130                'TypedTableElement: TableConstraint' => $this->lowering->tables->tableConstraint($element->node(0)),
131                default => throw ImplementationGap::production($element),
132            };
133        }
134
135        return $elements;
136    }
137
138    /**
139     * Lowers `columnDef`.
140     *
141     * @throws ImplementationGap When the production has no rule
142     */
143    public function column(Node $definition): ColumnDefinition
144    {
145        $form = $this->lowering->productions->form($definition);
146        if ($form->signature !== 'columnDef: ColId Typename opt_column_storage opt_column_compression create_generic_options ColQualList') {
147            throw ImplementationGap::production($form);
148        }
149
150        return new ColumnDefinition(
151            $this->lowering->names->name($form->node(0)),
152            $this->lowering->types->typeName($form->node(1)),
153            $this->storage($form->node(2)),
154            $this->compression($form->node(3)),
155            $this->lowering->options->genericOptions($form->node(4)),
156            $this->qualifiers($form->node(5)),
157        );
158    }
159
160    /**
161     * Lowers `columnOptions`.
162     *
163     * @throws ImplementationGap When the production has no rule
164     */
165    public function options(Node $options): ColumnOptions
166    {
167        $form = $this->lowering->productions->form($options);
168
169        return match ($form->signature) {
170            'columnOptions: ColId ColQualList' => new ColumnOptions($this->lowering->names->name($form->node(0)), $this->qualifiers($form->node(1))),
171            'columnOptions: ColId WITH OPTIONS ColQualList' => new ColumnOptions($this->lowering->names->name($form->node(0)), $this->qualifiers($form->node(3))),
172            default => throw ImplementationGap::production($form),
173        };
174    }
175
176    /**
177     * Lowers `opt_column_storage` or `column_storage`; none is null.
178     *
179     * @throws ImplementationGap When the production has no rule
180     */
181    public function storage(Node $clause): ?ColumnStorage
182    {
183        $form = $this->lowering->productions->form($clause);
184
185        return match ($form->signature) {
186            'opt_column_storage: column_storage' => $this->storage($form->node(0)),
187            'opt_column_storage:' => null,
188            'column_storage: STORAGE ColId' => new ColumnStorage($this->lowering->names->name($form->node(1))),
189            'column_storage: STORAGE DEFAULT' => new ColumnStorage(null),
190            default => throw ImplementationGap::production($form),
191        };
192    }
193
194    /**
195     * Lowers `opt_column_compression` or `column_compression`; none is null.
196     *
197     * @throws ImplementationGap When the production has no rule
198     */
199    public function compression(Node $clause): ?ColumnCompression
200    {
201        $form = $this->lowering->productions->form($clause);
202
203        return match ($form->signature) {
204            'opt_column_compression: column_compression' => $this->compression($form->node(0)),
205            'opt_column_compression:' => null,
206            'column_compression: COMPRESSION ColId' => new ColumnCompression($this->lowering->names->name($form->node(1))),
207            'column_compression: COMPRESSION DEFAULT' => new ColumnCompression(null),
208            default => throw ImplementationGap::production($form),
209        };
210    }
211
212    /**
213     * Lowers `ColQualList`.
214     *
215     * @return list<Clause>
216     *
217     * @throws ImplementationGap When the production has no rule
218     */
219    public function qualifiers(Node $list): array
220    {
221        $qualifiers = [];
222        foreach ($this->lowering->items($list, 'ColQualList: ColQualList ColConstraint', 'ColQualList:') as $item) {
223            $form = $this->lowering->productions->form($item);
224            $qualifiers[] = match ($form->signature) {
225                'ColConstraint: CONSTRAINT name ColConstraintElem' => $this->constraint($this->lowering->productions->form($form->node(2)), $this->lowering->names->name($form->node(1))),
226                'ColConstraint: ColConstraintElem' => $this->constraint($this->lowering->productions->form($form->node(0)), null),
227                'ColConstraint: ConstraintAttr' => $this->attribute($form->node(0)),
228                'ColConstraint: COLLATE any_name' => new ColumnCollation($this->lowering->names->dotted($form->node(1))),
229                default => throw ImplementationGap::production($form),
230            };
231        }
232
233        return $qualifiers;
234    }
235
236    /**
237     * Lowers `ColConstraintElem` with its name.
238     *
239     * @throws ImplementationGap When the production has no rule
240     */
241    public function constraint(Form $form, ?Name $name): Constraint
242    {
243        $constraints = new ConstraintRule($this->lowering);
244        $options = $this->lowering->options;
245
246        return match ($form->signature) {
247            'ColConstraintElem: NOT NULL_P' => new NotNull($name),
248            'ColConstraintElem: NULL_P' => new NullAllowed($name),
249            'ColConstraintElem: UNIQUE opt_unique_null_treatment opt_definition OptConsTableSpace' => new ColumnUnique(
250                $this->lowering->tables->uniqueNullTreatment($form->node(1)),
251                $options->definitions($form->node(2)),
252                $constraints->tablespace($form->node(3)),
253                $name,
254            ),
255            'ColConstraintElem: PRIMARY KEY opt_definition OptConsTableSpace' => new ColumnPrimaryKey($options->definitions($form->node(2)), $constraints->tablespace($form->node(3)), $name),
256            'ColConstraintElem: CHECK ( a_expr ) opt_no_inherit' => new ColumnCheck($this->lowering->expressions->expression($form->node(2)), $this->noInherit($form->node(4)), $name),
257            'ColConstraintElem: DEFAULT b_expr' => new DefaultExpression($this->lowering->expressions->expression($form->node(1)), $name),
258            'ColConstraintElem: GENERATED generated_when AS IDENTITY_P OptParenthesizedSeqOptList' => new Identity($this->when($form->node(1)), (new SequenceRule($this->lowering))->parenthesized($form->node(4)), $name),
259            'ColConstraintElem: GENERATED generated_when AS ( a_expr ) STORED' => new Generated($this->when($form->node(1)), $this->lowering->expressions->expression($form->node(4)), $name),
260            'ColConstraintElem: REFERENCES qualified_name opt_column_list key_match key_actions' => new References(
261                $this->lowering->names->qualified($form->node(1)),
262                $this->lowering->names->names($form->node(2)),
263                $constraints->match($form->node(3)),
264                $constraints->actions($form->node(4)),
265                $name,
266            ),
267            default => throw ImplementationGap::production($form),
268        };
269    }
270
271    /**
272     * Lowers `generated_when`.
273     *
274     * @throws ImplementationGap When the production has no rule
275     */
276    public function when(Node $when): GeneratedWhen
277    {
278        $form = $this->lowering->productions->form($when);
279
280        return match ($form->signature) {
281            'generated_when: ALWAYS' => GeneratedWhen::Always,
282            'generated_when: BY DEFAULT' => GeneratedWhen::ByDefault,
283            default => throw ImplementationGap::production($form),
284        };
285    }
286
287    /**
288     * Lowers `ConstraintAttr`.
289     *
290     * @throws ImplementationGap When the production has no rule
291     */
292    public function attribute(Node $attribute): ConstraintAttribute
293    {
294        $form = $this->lowering->productions->form($attribute);
295
296        return self::ATTRIBUTES[$form->signature] ?? throw ImplementationGap::production($form);
297    }
298
299    /**
300     * Lowers `opt_no_inherit`.
301     *
302     * @throws ImplementationGap When the production has no rule
303     */
304    public function noInherit(Node $flag): bool
305    {
306        $form = $this->lowering->productions->form($flag);
307
308        return match ($form->signature) {
309            'opt_no_inherit: NO INHERIT' => true,
310            'opt_no_inherit:' => false,
311            default => throw ImplementationGap::production($form),
312        };
313    }
314
315    /**
316     * Lowers `TableLikeClause` with its `TableLikeOptionList`.
317     *
318     * @throws ImplementationGap When the production has no rule
319     */
320    public function like(Node $clause): LikeClause
321    {
322        $form = $this->lowering->productions->form($clause);
323        if ($form->signature !== 'TableLikeClause: LIKE qualified_name TableLikeOptionList') {
324            throw ImplementationGap::production($form);
325        }
326        $options = [];
327        $list = $this->lowering->productions->form($form->node(2));
328        while ($list->signature !== 'TableLikeOptionList:') {
329            if ($list->signature !== 'TableLikeOptionList: TableLikeOptionList INCLUDING TableLikeOption' && $list->signature !== 'TableLikeOptionList: TableLikeOptionList EXCLUDING TableLikeOption') {
330                throw ImplementationGap::production($list);
331            }
332            $option = $this->lowering->productions->form($list->node(2));
333            $options[] = new LikeOption($list->token(1)->name === 'INCLUDING', self::LIKE[$option->signature] ?? throw ImplementationGap::production($option));
334            $list = $this->lowering->productions->form($list->node(0));
335        }
336
337        return new LikeClause($this->lowering->names->qualified($form->node(1)), array_reverse($options));
338    }
339}
340