packages/sql-semantics-postgres/src/Statement/Table/Alter/Column/ColumnStatistics.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Statement\Table\Alter\Column;
6
7use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
8use SqlSemantics\Platform\PostgreSql\Model\Rendering\Output;
9use SqlSemantics\Platform\PostgreSql\Model\Resolution\Environment;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Snapshot;
12use SqlSemantics\Platform\PostgreSql\Rules\Table\Command\Alterations;
13use SqlSemantics\Platform\PostgreSql\Statement\Literal\IntegerConstant;
14use SqlSemantics\Platform\PostgreSql\Statement\Literal\SignedNumber;
15use SqlSemantics\Platform\PostgreSql\Statement\Table\Alter\AlterCommand;
16
17/**
18 * ALTER [ COLUMN ] ... SET STATISTICS: the statistics target of a column, or DEFAULT.
19 *
20 * Mirrors `AT_SetStatistics`. An index column is named by its number. PostgreSQL 17 accepts DEFAULT, which is
21 * the target -1 of earlier releases.
22 * Source: https://www.postgresql.org/docs/17/sql-altertable.html.
23 *
24 * @visibility public
25 * @example Setting a statistics target
26 *     $statement = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze('ALTER INDEX i ALTER COLUMN 1 SET STATISTICS 100');
27 *     $statement->statement->commands[0]->column->digits // => '1'
28 */
29final class ColumnStatistics implements AlterCommand
30{
31    use Snapshot;
32
33    /**
34     * @param Name|IntegerConstant $column The column, by name or, for an index, by number
35     * @param SignedNumber|null $target The target; null for DEFAULT
36     */
37    public function __construct(public readonly Name|IntegerConstant $column, public readonly ?SignedNumber $target)
38    {
39    }
40
41    /**
42     * Checks that a named column exists.
43     */
44    public function deriveClause(Derivation $derivation, Environment $environment): void
45    {
46        (new Alterations())->column($derivation, $environment, $this->column);
47    }
48
49    /**
50     * Writes the action.
51     */
52    public function render(Output $out): void
53    {
54        $out->keyword('ALTER');
55        if ($this->column instanceof Name) {
56            $out->name($this->column);
57        } else {
58            $out->node($this->column);
59        }
60        $out->keyword('SET', 'STATISTICS');
61        if ($this->target === null) {
62            $out->keyword('DEFAULT');
63        } else {
64            $out->node($this->target);
65        }
66    }
67}
68