packages/sql-semantics-postgres/src/Statement/Constraint/Column/ColumnCheck.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Statement\Constraint\Column;
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\Model\Statement\Scalar;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Snapshot;
13use SqlSemantics\Platform\PostgreSql\Rules\Table\Conditions;
14use SqlSemantics\Platform\PostgreSql\Rules\Table\Writing;
15use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Constraint;
16use SqlSemantics\Platform\PostgreSql\Statement\Constraint\ConstraintKind;
17
18/**
19 * A CHECK column constraint: a condition every row satisfies.
20 *
21 * Mirrors `CONSTR_CHECK` with `raw_expr` and `is_no_inherit`. The condition
22 * is derived where the columns of the table are visible
23 * (PG-TABLE-CONDITION-001); a column constraint may refer to any column.
24 * Source: https://www.postgresql.org/docs/17/sql-createtable.html, https://www.postgresql.org/docs/17/ddl-constraints.html#DDL-CONSTRAINTS-CHECK-CONSTRAINTS.
25 *
26 * @visibility public
27 * @example A check refers to the columns of its table
28 * $create = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze('CREATE TABLE t (a int CHECK (a > 0) NO INHERIT)');
29 * $check = $create->statement->definition->elements[0]->qualifiers[0];
30 * [$check->noInherit, $create->facts->scalar($check->condition->left)->resolution->slot->column === $create->declarations()[0]->columns[0]] // => [true, true]
31 */
32final class ColumnCheck implements Constraint
33{
34 use Snapshot;
35
36 /**
37 * @param Scalar $condition The condition
38 * @param bool $noInherit Whether NO INHERIT is written: the constraint does not apply to child tables
39 * @param Name|null $name The constraint name
40 */
41 public function __construct(public readonly Scalar $condition, public readonly bool $noInherit = false, public readonly ?Name $name = null)
42 {
43 }
44
45 /**
46 * Answers the kind of the constraint.
47 */
48 public function kind(): ConstraintKind
49 {
50 return ConstraintKind::Check;
51 }
52
53 /**
54 * Derives the condition against the table.
55 */
56 public function deriveClause(Derivation $derivation, Environment $environment): void
57 {
58 (new Conditions())->derive($derivation, $this->condition, $environment, 'CHECK');
59 }
60
61 /**
62 * Writes the constraint.
63 */
64 public function render(Output $out): void
65 {
66 (new Writing())->constraintName($out, $this->name);
67 $out->keyword('CHECK')->symbol('(')->node($this->condition)->symbol(')');
68 if ($this->noInherit) {
69 $out->keyword('NO', 'INHERIT');
70 }
71 }
72}
73