packages/sql-semantics-sqlite/src/Statement/Query/ValuesClause.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\Sqlite\Statement\Query;
6
7use SqlSemantics\Platform\Sqlite\Model\Construction\Derivation;
8use SqlSemantics\Platform\Sqlite\Model\Diagnostic\Check;
9use SqlSemantics\Platform\Sqlite\Model\Rendering\Output;
10use SqlSemantics\Platform\Sqlite\Model\Resolution\Environment;
11use SqlSemantics\Platform\Sqlite\Model\Statement\Fact\QueryFact;
12use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\Name;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Query;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\Field;
15use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\OutputSlot;
16use SqlSemantics\Platform\Sqlite\Model\Statement\Snapshot;
17use SqlSemantics\Platform\Sqlite\Model\Statement\Statement;
18use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Nullability;
19use SqlSemantics\Platform\Sqlite\Rules\Expression\ProgramOnly;
20use SqlSemantics\Platform\Sqlite\Rules\Typing\Storages;
21use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityMismatch;
22use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityRule;
23
24/**
25 * A VALUES clause: a query whose rows are written out.
26 *
27 * Rule: SQLITE-VALUES-001. The values see the enclosing queries and no
28 * relation of their own. The result has the width of the first row; a row of
29 * another width is reported. SQLite names the result columns `column1`,
30 * `column2`, and so on. The type of a column is the choice over its values
31 * and it can be NULL when one of its values can.
32 * Source: https://sqlite.org/lang_select.html#the_values_clause. Status: Implemented.
33 *
34 * @visibility public
35 * @example Reading the output of a VALUES clause
36 *     $query = (new \SqlSemantics\Platform\Sqlite\Semantics())->analyze("VALUES (1, 'a'), (2, NULL)");
37 *     [count($query->statement->rows), $query->field(1)->name->value, $query->field(1)->nullability] // => [2, 'column2', \SqlSemantics\Platform\Sqlite\Model\Statement\Type\Nullability::Nullable]
38 */
39final class ValuesClause implements Statement, Query
40{
41    use Snapshot;
42
43    /**
44     * @var non-empty-list<ValueRow> The rows in written order
45     */
46    public readonly array $rows;
47
48    /**
49     * @param list<ValueRow> $rows The rows in written order; at least one
50     */
51    public function __construct(array $rows)
52    {
53        $this->rows = Check::listOf($rows, ValueRow::class, 'A VALUES clause has at least one row.', 1);
54    }
55
56    /**
57     * Derives the clause as a statement root and records its rows as the output.
58     */
59    public function deriveStatement(Derivation $derivation): void
60    {
61        (new ProgramOnly())->outsideProgram($this, $derivation);
62        $derivation->output($derivation->query($this, $derivation->environment()));
63    }
64
65    /**
66     * Derives every value and the output fields.
67     */
68    public function deriveQuery(Derivation $derivation, Environment $outer): QueryFact
69    {
70        $environment = new Environment($derivation->context, $outer);
71        $width = count($this->rows[0]->values);
72        $types = array_fill(0, $width, []);
73        $nullability = array_fill(0, $width, Nullability::NotNull);
74        $reported = false;
75        foreach ($this->rows as $row) {
76            foreach ($row->values as $position => $value) {
77                $fact = $derivation->scalar($value, $environment);
78                if ($position < $width) {
79                    $types[$position][] = $fact->type;
80                    $nullability[$position] = $nullability[$position]->propagate($fact->nullability);
81                }
82            }
83            if (count($row->values) !== $width && !$reported) {
84                $derivation->report(new ArityMismatch(ArityRule::ValueRows, $width, count($row->values)));
85                $reported = true;
86            }
87        }
88        $fields = [];
89        foreach ($this->rows[0]->values as $position => $value) {
90            $fields[] = new Field($position, new OutputSlot(new Name('column' . ($position + 1)), (new Storages())->either($types[$position]), $nullability[$position]), count($this->rows) === 1 ? $value : null);
91        }
92
93        return new QueryFact($fields, $derivation->context->columnNames);
94    }
95
96    /**
97     * Writes the rows.
98     */
99    public function render(Output $out): void
100    {
101        $out->keyword('VALUES')->list($this->rows);
102    }
103}
104