packages/sql-semantics-postgres/src/Statement/Query/ValuesList.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Statement\Query;
6
7use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
8use SqlSemantics\Platform\PostgreSql\Model\Diagnostic\Check;
9use SqlSemantics\Platform\PostgreSql\Model\Rendering\Output;
10use SqlSemantics\Platform\PostgreSql\Model\Resolution\Environment;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Fact\QueryFact;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
13use SqlSemantics\Platform\PostgreSql\Model\Statement\Query;
14use SqlSemantics\Platform\PostgreSql\Model\Statement\Snapshot;
15use SqlSemantics\Platform\PostgreSql\Model\Statement\Statement;
16use SqlSemantics\Platform\PostgreSql\Rules\Query\Facts\QueryRoots;
17use SqlSemantics\Platform\PostgreSql\Rules\Query\Facts\ValuesFacts;
18use SqlSemantics\Platform\PostgreSql\Statement\OutputNaming;
19use SqlSemantics\Platform\PostgreSql\Statement\Query\Clause\ValuesRow;
20
21/**
22 * VALUES: a constant table of rows written in the query.
23 *
24 * Mirrors the `valuesLists` form of PostgreSQL's `SelectStmt`. The facts
25 * follow PG-VALUES-001.
26 * Source: https://www.postgresql.org/docs/17/sql-values.html.
27 *
28 * @visibility public
29 * @example Reading the columns of a VALUES list
30 *     $query = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze("VALUES (1, 'a'), (2, NULL)");
31 *     [$query->field(1)->name->value, $query->field(1)->type->descriptor->name(), $query->field(1)->nullability->name] // => ['column2', 'text', 'Nullable']
32 */
33final class ValuesList implements Statement, Query, OutputNaming
34{
35    use Snapshot;
36
37    /**
38     * @var non-empty-list<ValuesRow> The rows in written order
39     */
40    public readonly array $rows;
41
42    /**
43     * @param list<ValuesRow> $rows The rows in written order; at least one
44     */
45    public function __construct(array $rows)
46    {
47        $this->rows = Check::listOf($rows, ValuesRow::class, 'A VALUES list holds at least one row.', 1);
48    }
49
50    /**
51     * Answers the name of the first column.
52     */
53    public function outputName(): Name
54    {
55        return new Name('column1');
56    }
57
58    /**
59     * Derives the list as a statement root.
60     */
61    public function deriveStatement(Derivation $derivation): void
62    {
63        (new QueryRoots())->derive($this, $derivation);
64    }
65
66    /**
67     * Derives the rows and the output columns.
68     */
69    public function deriveQuery(Derivation $derivation, Environment $outer): QueryFact
70    {
71        return (new ValuesFacts())->derive($this, $derivation, $outer);
72    }
73
74    /**
75     * Writes VALUES and the rows.
76     */
77    public function render(Output $out): void
78    {
79        $out->keyword('VALUES')->list($this->rows);
80    }
81}
82