packages/sql-semantics-sqlite/src/Statement/Schema/Reference/Deferrability.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\Sqlite\Statement\Schema\Reference;
6
7use SqlSemantics\Platform\Sqlite\Model\Construction\Derivation;
8use SqlSemantics\Platform\Sqlite\Model\Rendering\Output;
9use SqlSemantics\Platform\Sqlite\Model\Statement\Snapshot;
10use SqlSemantics\Platform\Sqlite\Rules\Definition\ConstraintScope;
11use SqlSemantics\Platform\Sqlite\Statement\Schema\Column\ColumnConstraint;
12
13/**
14 * A DEFERRABLE or NOT DEFERRABLE clause of a foreign key.
15 *
16 * Rule: SQLITE-FK-DEFERRABLE-001. A foreign key is checked at the end of the
17 * transaction only when the clause is `DEFERRABLE INITIALLY DEFERRED`; every
18 * other form, `NOT DEFERRABLE INITIALLY DEFERRED` included, is checked at the
19 * end of each statement. Written as a column constraint, the clause applies
20 * to the foreign key defined last before it in the table definition and has
21 * no effect when there is none.
22 * Source: https://sqlite.org/foreignkeys.html#fk_deferred. Status: Implemented.
23 *
24 * @visibility public
25 * @example Telling a deferred foreign key from an immediate one
26 *     $semantics = new \SqlSemantics\Platform\Sqlite\Semantics();
27 *     $deferred = $semantics->analyze('CREATE TABLE c (p REFERENCES parent DEFERRABLE INITIALLY DEFERRED)')->statement->columns[0]->constraints[1];
28 *     $immediate = $semantics->analyze('CREATE TABLE c (p REFERENCES parent NOT DEFERRABLE INITIALLY DEFERRED)')->statement->columns[0]->constraints[1];
29 *     [$deferred->deferred(), $immediate->deferred()] // => [true, false]
30 */
31final class Deferrability implements ColumnConstraint
32{
33    use Snapshot;
34
35    /**
36     * @param bool $deferrable Whether DEFERRABLE is written without NOT
37     * @param InitialMode|null $initially The word written after INITIALLY
38     */
39    public function __construct(public readonly bool $deferrable, public readonly ?InitialMode $initially = null)
40    {
41    }
42
43    /**
44     * Tells whether the foreign key is checked at the end of the transaction.
45     */
46    public function deferred(): bool
47    {
48        return $this->deferrable && $this->initially === InitialMode::Deferred;
49    }
50
51    /**
52     * Derives nothing: the clause has no operand.
53     */
54    public function deriveConstraint(Derivation $derivation, ConstraintScope $scope): void
55    {
56    }
57
58    /**
59     * Writes the clause.
60     */
61    public function render(Output $out): void
62    {
63        if (!$this->deferrable) {
64            $out->keyword('NOT');
65        }
66        $out->keyword('DEFERRABLE');
67        if ($this->initially !== null) {
68            $out->keyword('INITIALLY', $this->initially->value);
69        }
70    }
71}
72