packages/sql-semantics-postgres/src/Rules/Table/KeyClauses.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Rules\Table;
6
7use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
8use SqlSemantics\Platform\PostgreSql\Model\Rendering\Output;
9use SqlSemantics\Platform\PostgreSql\Model\Resolution\Environment;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
11use SqlSemantics\Platform\PostgreSql\Statement\Option\Definition;
12use SqlSemantics\Platform\PostgreSql\Statement\Table\Problem\DefinitionRule;
13
14/**
15 * Derives and writes the column lists and index parameters of UNIQUE, PRIMARY KEY, EXCLUDE and FOREIGN KEY table constraints.
16 *
17 * Rule: PG-KEY-CLAUSE-001. Each named column must be a column of the table
18 * the constraint belongs to, which is the visible relation of the
19 * environment; a column the complete row shape lacks is reported (PG-KEY-COLUMNS-001).
20 * The storage parameters are derived in the same environment. Source:
21 * https://www.postgresql.org/docs/17/sql-createtable.html. Termination: one
22 * pass over the names. Status: Implemented.
23 *
24 * @visibility SqlSemantics\Platform\PostgreSql
25 */
26final class KeyClauses
27{
28 /**
29 * Checks the named columns and derives the parameters.
30 *
31 * @param list<Name> $columns
32 * @param list<Definition> $options
33 */
34 public function derive(Derivation $derivation, Environment $environment, array $columns, array $options): void
35 {
36 foreach ($environment->relations as $relation) {
37 (new KeyColumns())->report($derivation, $columns, $relation->shape, DefinitionRule::MissingKeyColumn);
38 }
39 foreach ($options as $option) {
40 $option->deriveClause($derivation, $environment);
41 }
42 }
43
44 /**
45 * Writes the key columns, the included columns and the index parameters, each when given.
46 *
47 * @param list<Name> $columns
48 * @param list<Name> $included
49 * @param list<Definition> $options
50 */
51 public function write(Output $out, array $columns, array $included, array $options, ?Name $tablespace): void
52 {
53 $writing = new Writing();
54 if ($columns !== []) {
55 $writing->parenthesized($out, $columns);
56 }
57 if ($included !== []) {
58 $out->keyword('INCLUDE');
59 $writing->parenthesized($out, $included);
60 }
61 $writing->indexParameters($out, $options, $tablespace);
62 }
63}
64