packages/sql-semantics-mysql/src/Statement/Account/CreateRole.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Account;
6
7use SqlSemantics\Platform\MySql\Model\Construction\Derivation;
8use SqlSemantics\Platform\MySql\Model\Diagnostic\Check;
9use SqlSemantics\Platform\MySql\Model\Rendering\Output;
10use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
11use SqlSemantics\Platform\MySql\Model\Statement\Statement;
12use SqlSemantics\Platform\MySql\Statement\Name\AccountName;
13
14/**
15 * `CREATE ROLE [IF NOT EXISTS] role, …` (8.0+): a request to create roles, which are locked accounts.
16 *
17 * Mirrors PT_create_role. Rule: MYSQL-CREATE-ROLE-001.
18 * Source: https://dev.mysql.com/doc/refman/8.4/en/create-role.html. Status: Implemented.
19 *
20 * @visibility public
21 * @example Creating roles
22 *     (new \SqlSemantics\Platform\MySql\Semantics())->analyze("create role if not exists reader, 'writer'@'%'")->toString() // => 'CREATE ROLE IF NOT EXISTS reader, writer@`%`'
23 */
24final class CreateRole implements Statement
25{
26    use Snapshot;
27
28    /**
29     * @var list<AccountName> The roles in order
30     */
31    public readonly array $roles;
32
33    /**
34     * @param bool $ifNotExists Whether IF NOT EXISTS is written
35     * @param list<AccountName> $roles The roles in order; at least one
36     */
37    public function __construct(public readonly bool $ifNotExists, array $roles)
38    {
39        $this->roles = Check::listOf($roles, AccountName::class, 'CREATE ROLE names at least one role.', 1);
40    }
41
42    /**
43     * Derives nothing: the statement names no relation and no expression.
44     */
45    public function deriveStatement(Derivation $derivation): void
46    {
47    }
48
49    /**
50     * Writes the request.
51     */
52    public function render(Output $out): void
53    {
54        $out->keyword('CREATE', 'ROLE');
55        if ($this->ifNotExists) {
56            $out->keyword('IF', 'NOT', 'EXISTS');
57        }
58        $out->list($this->roles);
59    }
60}
61