packages/sql-semantics-postgres/src/Statement/Relation/TableSample.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\Scalar;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Snapshot;
13use SqlSemantics\Platform\PostgreSql\Statement\Clause;
14use SqlSemantics\Platform\PostgreSql\Statement\Name\DottedName;
15
16/**
17 * TABLESAMPLE method (arguments) [REPEATABLE (seed)]: a sample of the rows of a table.
18 *
19 * Mirrors PostgreSQL's `RangeTableSample`. The arguments and the seed are
20 * evaluated once and see no column of the sampled table.
21 * Source: https://www.postgresql.org/docs/17/sql-select.html#SQL-FROM.
22 *
23 * @visibility public
24 * @example Reading a table sample
25 *     $query = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze('SELECT 1 FROM t TABLESAMPLE bernoulli (10) REPEATABLE (1)');
26 *     [$query->statement->from->sample->method->parts[0]->value, $query->statement->from->sample->seed !== null] // => ['bernoulli', true]
27 */
28final class TableSample implements Clause
29{
30    use Snapshot;
31
32    /**
33     * @var non-empty-list<Scalar> The arguments of the sampling method
34     */
35    public readonly array $arguments;
36
37    /**
38     * @param DottedName $method The sampling method
39     * @param list<Scalar> $arguments The arguments of the method; at least one
40     * @param Scalar|null $seed The seed written after REPEATABLE
41     */
42    public function __construct(public readonly DottedName $method, array $arguments, public readonly ?Scalar $seed = null)
43    {
44        $this->arguments = Check::listOf($arguments, Scalar::class, 'A sampling method takes at least one argument.', 1);
45    }
46
47    /**
48     * Derives the arguments and the seed.
49     */
50    public function deriveClause(Derivation $derivation, Environment $environment): void
51    {
52        foreach ([...$this->arguments, ...($this->seed === null ? [] : [$this->seed])] as $expression) {
53            $derivation->scalar($expression, $environment);
54        }
55    }
56
57    /**
58     * Writes TABLESAMPLE, the method, its arguments and the seed.
59     */
60    public function render(Output $out): void
61    {
62        $out->keyword('TABLESAMPLE')->node($this->method)->symbol('(')->list($this->arguments)->symbol(')');
63        if ($this->seed !== null) {
64            $out->keyword('REPEATABLE')->symbol('(')->node($this->seed)->symbol(')');
65        }
66    }
67}
68