packages/sql-semantics-postgres/src/Statement/Relation/FunctionTable.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Statement\Relation;
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\RelationFact;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
13use SqlSemantics\Platform\PostgreSql\Model\Statement\Relation;
14use SqlSemantics\Platform\PostgreSql\Model\Statement\Snapshot;
15use SqlSemantics\Platform\PostgreSql\Rules\Query\AliasSpelling;
16use SqlSemantics\Platform\PostgreSql\Rules\Resolution\FunctionShapes;
17use SqlSemantics\Platform\PostgreSql\Statement\Type\TypedColumn;
18
19/**
20 * A function call, or ROWS FROM of several, used as a FROM item.
21 *
22 * Mirrors PostgreSQL's `RangeFunction`. The facts follow
23 * PG-FUNCTION-TABLE-001. A function call may refer to the FROM items before
24 * it whether or not LATERAL is written; the word is kept as written.
25 * Column definitions are written after the alias for one function outside
26 * ROWS FROM, and per function inside it.
27 * Source: https://www.postgresql.org/docs/17/queries-table-expressions.html#QUERIES-TABLEFUNCTIONS. Status: Implemented.
28 *
29 * @visibility public
30 * @example Reading a function in FROM
31 *     $query = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze('SELECT * FROM f() WITH ORDINALITY AS x (a integer)');
32 *     [$query->statement->from->ordinality, $query->statement->from->definitions[0]->name->value, $query->toString()] // => [true, 'a', 'SELECT * FROM f() WITH ORDINALITY AS x (a INTEGER)']
33 * @example Refusing several functions outside ROWS FROM
34 *     $call = new \SqlSemantics\Platform\PostgreSql\Statement\Relation\TableFunction(new \SqlSemantics\Platform\PostgreSql\Statement\Literal\NullLiteral());
35 *     $other = new \SqlSemantics\Platform\PostgreSql\Statement\Relation\TableFunction(new \SqlSemantics\Platform\PostgreSql\Statement\Literal\NullLiteral());
36 *     new \SqlSemantics\Platform\PostgreSql\Statement\Relation\FunctionTable([$call, $other]) // throws \SqlSemantics\Platform\PostgreSql\Model\Diagnostic\InvalidConstruction
37 */
38final class FunctionTable implements Relation
39{
40    use Snapshot;
41
42    /**
43     * @var non-empty-list<TableFunction> The function calls in written order
44     */
45    public readonly array $functions;
46
47    /**
48     * @var list<Name> The column names written after the correlation name
49     */
50    public readonly array $columns;
51
52    /**
53     * @var list<TypedColumn> The column definitions written after the correlation name or AS
54     */
55    public readonly array $definitions;
56
57    /**
58     * @param list<TableFunction> $functions The function calls in written order; one unless ROWS FROM is written
59     * @param bool $rowsFrom Whether ROWS FROM is written
60     * @param bool $ordinality Whether WITH ORDINALITY is written
61     * @param Name|null $alias The correlation name
62     * @param list<Name> $columns The column names written after the correlation name
63     * @param list<TypedColumn> $definitions The column definitions written after the correlation name or AS
64     * @param bool $lateral Whether LATERAL is written
65     */
66    public function __construct(
67        array $functions,
68        public readonly bool $rowsFrom = false,
69        public readonly bool $ordinality = false,
70        public readonly ?Name $alias = null,
71        array $columns = [],
72        array $definitions = [],
73        public readonly bool $lateral = false,
74    ) {
75        $this->functions = Check::listOf($functions, TableFunction::class, 'A function FROM item calls at least one function.', 1);
76        $this->columns = Check::listOf($columns, Name::class, 'Column aliases are names.');
77        $this->definitions = Check::listOf($definitions, TypedColumn::class, 'Column definitions are typed columns.');
78        Check::input($rowsFrom || (count($this->functions) === 1 && $this->functions[0]->definitions === []), 'Several functions, and column definitions per function, are written inside ROWS FROM.');
79        Check::input($alias !== null || $this->columns === [], 'Column aliases are written after a correlation name.');
80        Check::input($this->columns === [] || $this->definitions === [], 'A function FROM item has column names or column definitions, not both.');
81    }
82
83    /**
84     * Derives the calls and the columns of the occurrence.
85     */
86    public function deriveRelation(Derivation $derivation, Environment $environment): RelationFact
87    {
88        return (new FunctionShapes())->derive($this, $derivation, $environment);
89    }
90
91    /**
92     * Answers the name the occurrence is known by without an alias: the name of its first function.
93     */
94    public function name(): ?Name
95    {
96        return (new FunctionShapes())->functionName($this->functions[0]);
97    }
98
99    /**
100     * Writes LATERAL, the calls, WITH ORDINALITY and the alias with its columns or column definitions.
101     */
102    public function render(Output $out): void
103    {
104        if ($this->lateral) {
105            $out->keyword('LATERAL');
106        }
107        if ($this->rowsFrom) {
108            $out->keyword('ROWS', 'FROM')->symbol('(')->list($this->functions)->symbol(')');
109        } else {
110            $out->node($this->functions[0]);
111        }
112        if ($this->ordinality) {
113            $out->keyword('WITH', 'ORDINALITY');
114        }
115        (new AliasSpelling())->write($out, $this->alias, $this->columns);
116        if ($this->definitions !== []) {
117            if ($this->alias === null) {
118                $out->keyword('AS');
119            }
120            $out->symbol('(')->list($this->definitions)->symbol(')');
121        }
122    }
123}
124