packages/sql-semantics-postgres/src/Lowering/Catalog/DatabaseRule.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Lowering\Catalog;
6
7use SqlParser\Parser\Node;
8use SqlSemantics\Platform\PostgreSql\Lowering\Lowering;
9use SqlSemantics\Platform\PostgreSql\Model\Diagnostic\ImplementationGap;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Statement;
11use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Database\AlterDatabase;
12use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Database\AlterDatabaseSetting;
13use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Database\CreateDatabase;
14use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Database\DatabaseOption;
15use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Database\DatabaseOptionKeyword;
16use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Database\DefaultSetting;
17use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Database\DropDatabase;
18use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Database\DropDatabaseOption;
19use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Database\MoveDatabase;
20use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Database\RefreshDatabaseCollation;
21use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Tablespace\AlterTablespaceOptions;
22use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Tablespace\CreateTablespace;
23use SqlSemantics\Platform\PostgreSql\Statement\Catalog\Tablespace\DropTablespace;
24
25/**
26 * Lowers the database and tablespace commands.
27 *
28 * Rule: PG-DATABASE-LOWER-001. Scope: `CreatedbStmt`, `createdb_opt_list`,
29 * `createdb_opt_items`, `createdb_opt_item`, `createdb_opt_name`,
30 * `opt_equal`, `AlterDatabaseStmt`, `AlterDatabaseSetStmt`, `DropdbStmt`,
31 * `drop_option_list`, `drop_option`, `CreateTableSpaceStmt`,
32 * `OptTableSpaceOwner`, `DropTableSpaceStmt`, `AlterTblSpcStmt`.
33 * Constructors: `CreateDatabase`, `AlterDatabase`, `MoveDatabase`,
34 * `RefreshDatabaseCollation`, `AlterDatabaseSetting`, `DropDatabase`,
35 * `DatabaseOption`, `CreateTablespace`, `DropTablespace`,
36 * `AlterTablespaceOptions`. The optional `=` of a database option and the
37 * optional WITH before database options are noise (CatalogNoise).
38 * Termination: lists are flattened iteratively.
39 * Source: https://www.postgresql.org/docs/17/sql-createdatabase.html, https://www.postgresql.org/docs/17/sql-alterdatabase.html,
40 * https://www.postgresql.org/docs/17/sql-dropdatabase.html, https://www.postgresql.org/docs/17/sql-createtablespace.html,
41 * https://www.postgresql.org/docs/17/sql-altertablespace.html. Status: Implemented.
42 *
43 * @visibility SqlSemantics\Platform\PostgreSql\Lowering
44 */
45final class DatabaseRule
46{
47    /**
48     * The option each keyword spelling of `createdb_opt_name` names.
49     */
50    private const KEYWORDS = [
51        'createdb_opt_name: CONNECTION LIMIT' => DatabaseOptionKeyword::ConnectionLimit,
52        'createdb_opt_name: ENCODING' => DatabaseOptionKeyword::Encoding,
53        'createdb_opt_name: LOCATION' => DatabaseOptionKeyword::Location,
54        'createdb_opt_name: OWNER' => DatabaseOptionKeyword::Owner,
55        'createdb_opt_name: TABLESPACE' => DatabaseOptionKeyword::Tablespace,
56        'createdb_opt_name: TEMPLATE' => DatabaseOptionKeyword::Template,
57    ];
58
59    /**
60     * @param Lowering $lowering The hub
61     */
62    public function __construct(private readonly Lowering $lowering)
63    {
64    }
65
66    /**
67     * Lowers a database or tablespace command.
68     *
69     * @throws ImplementationGap When the production has no rule
70     */
71    public function statement(Node $statement): Statement
72    {
73        $form = $this->lowering->productions->form($statement);
74        $names = $this->lowering->names;
75
76        return match ($form->signature) {
77            'CreatedbStmt: CREATE DATABASE name opt_with createdb_opt_list' => new CreateDatabase($names->name($form->node(2)), $this->options($form->node(4))),
78            'AlterDatabaseStmt: ALTER DATABASE name WITH createdb_opt_list' => new AlterDatabase($names->name($form->node(2)), $this->options($form->node(4))),
79            'AlterDatabaseStmt: ALTER DATABASE name createdb_opt_list' => new AlterDatabase($names->name($form->node(2)), $this->options($form->node(3))),
80            'AlterDatabaseStmt: ALTER DATABASE name SET TABLESPACE name' => new MoveDatabase($names->name($form->node(2)), $names->name($form->node(5))),
81            'AlterDatabaseStmt: ALTER DATABASE name REFRESH COLLATION VERSION_P' => new RefreshDatabaseCollation($names->name($form->node(2))),
82            'AlterDatabaseSetStmt: ALTER DATABASE name SetResetClause' => new AlterDatabaseSetting($names->name($form->node(2)), $this->lowering->utilities->setReset($form->node(3))),
83            'DropdbStmt: DROP DATABASE name' => new DropDatabase($names->name($form->node(2))),
84            'DropdbStmt: DROP DATABASE IF_P EXISTS name' => new DropDatabase($names->name($form->node(4)), true),
85            'DropdbStmt: DROP DATABASE name opt_with ( drop_option_list )' => new DropDatabase($names->name($form->node(2)), false, $this->dropOptions($form->node(5))),
86            'DropdbStmt: DROP DATABASE IF_P EXISTS name opt_with ( drop_option_list )' => new DropDatabase($names->name($form->node(4)), true, $this->dropOptions($form->node(7))),
87            'CreateTableSpaceStmt: CREATE TABLESPACE name OptTableSpaceOwner LOCATION Sconst opt_reloptions' => new CreateTablespace($names->name($form->node(2)), $this->owner($form->node(3)), $this->lowering->literals->string($form->node(5)), $this->lowering->options->definitions($form->node(6))),
88            'DropTableSpaceStmt: DROP TABLESPACE name' => new DropTablespace($names->name($form->node(2))),
89            'DropTableSpaceStmt: DROP TABLESPACE IF_P EXISTS name' => new DropTablespace($names->name($form->node(4)), true),
90            'AlterTblSpcStmt: ALTER TABLESPACE name SET reloptions' => new AlterTablespaceOptions($names->name($form->node(2)), false, $this->lowering->options->definitions($form->node(4))),
91            'AlterTblSpcStmt: ALTER TABLESPACE name RESET reloptions' => new AlterTablespaceOptions($names->name($form->node(2)), true, $this->lowering->options->definitions($form->node(4))),
92            default => throw ImplementationGap::production($form),
93        };
94    }
95
96    /**
97     * Lowers `createdb_opt_list`; an empty list has no options.
98     *
99     * @return list<DatabaseOption>
100     *
101     * @throws ImplementationGap When the production has no rule
102     */
103    public function options(Node $list): array
104    {
105        $form = $this->lowering->productions->form($list);
106        if ($form->signature === 'createdb_opt_list:') {
107            return [];
108        }
109        if ($form->signature !== 'createdb_opt_list: createdb_opt_items') {
110            throw ImplementationGap::production($form);
111        }
112        $options = [];
113        foreach ($this->lowering->items($form->node(0), 'createdb_opt_items: createdb_opt_item', 'createdb_opt_items: createdb_opt_items createdb_opt_item') as $item) {
114            $options[] = $this->option($item);
115        }
116
117        return $options;
118    }
119
120    /**
121     * Lowers `createdb_opt_item`.
122     *
123     * @throws ImplementationGap When the production has no rule
124     */
125    public function option(Node $item): DatabaseOption
126    {
127        $form = $this->lowering->productions->form($item);
128        $this->equal($form->node(1));
129        $name = $this->lowering->productions->form($form->node(0));
130        $option = match ($name->signature) {
131            'createdb_opt_name: IDENT' => $this->lowering->names->token($name->token(0)),
132            default => self::KEYWORDS[$name->signature] ?? throw ImplementationGap::production($name),
133        };
134
135        return new DatabaseOption($option, match ($form->signature) {
136            'createdb_opt_item: createdb_opt_name opt_equal NumericOnly' => $this->lowering->literals->signed($form->node(2)),
137            'createdb_opt_item: createdb_opt_name opt_equal opt_boolean_or_string' => $this->lowering->options->value($form->node(2)),
138            'createdb_opt_item: createdb_opt_name opt_equal DEFAULT' => DefaultSetting::Default,
139            default => throw ImplementationGap::production($form),
140        });
141    }
142
143    /**
144     * Accepts `opt_equal`, whose `=` is noise.
145     *
146     * @throws ImplementationGap When the production has no rule
147     */
148    public function equal(Node $equal): void
149    {
150        $form = $this->lowering->productions->form($equal);
151        if ($form->signature !== 'opt_equal: =' && $form->signature !== 'opt_equal:') {
152            throw ImplementationGap::production($form);
153        }
154    }
155
156    /**
157     * Lowers `drop_option_list`.
158     *
159     * @return list<DropDatabaseOption>
160     *
161     * @throws ImplementationGap When the production has no rule
162     */
163    public function dropOptions(Node $list): array
164    {
165        $options = [];
166        foreach ($this->lowering->items($list, 'drop_option_list: drop_option', 'drop_option_list: drop_option_list , drop_option') as $item) {
167            $form = $this->lowering->productions->form($item);
168            $options[] = $form->signature === 'drop_option: FORCE' ? DropDatabaseOption::Force : throw ImplementationGap::production($form);
169        }
170
171        return $options;
172    }
173
174    /**
175     * Lowers `OptTableSpaceOwner`; no owner is null.
176     *
177     * @throws ImplementationGap When the production has no rule
178     */
179    public function owner(Node $owner): ?\SqlSemantics\Platform\PostgreSql\Statement\Name\RoleSpec
180    {
181        $form = $this->lowering->productions->form($owner);
182
183        return match ($form->signature) {
184            'OptTableSpaceOwner: OWNER RoleSpec' => $this->lowering->roles->role($form->node(1)),
185            'OptTableSpaceOwner:' => null,
186            default => throw ImplementationGap::production($form),
187        };
188    }
189}
190