packages/sql-semantics-mysql/src/Rules/Routine/ProgramNames.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Rules\Routine;
6
7use SqlSemantics\Platform\MySql\Model\Contract\NameUse;
8use SqlSemantics\Platform\MySql\Model\Rendering\Output;
9use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
10use SqlSemantics\Platform\MySql\Model\Statement\Identifier\QualifiedName;
11use SqlSemantics\Platform\MySql\Statement\Name\CollationName;
12use SqlSemantics\Platform\MySql\Statement\Type\TypeName;
13
14/**
15 * Writes the names of stored programs and the labels of their statements.
16 *
17 * Rule: MYSQL-PROGRAM-NAMES-001. A program name is written with its
18 * database qualifier when it has one; a label before a statement is
19 * followed by a colon; a data type is followed by its COLLATE clause when
20 * it has one. Terminates: constant work.
21 * Source: https://dev.mysql.com/doc/refman/8.4/en/identifier-qualifiers.html,
22 * https://dev.mysql.com/doc/refman/8.4/en/statement-labels.html.
23 * Status: Implemented.
24 *
25 * @visibility SqlSemantics\Platform\MySql
26 */
27final class ProgramNames
28{
29    /**
30     * Writes a name with its optional database qualifier.
31     */
32    public function qualified(Output $out, QualifiedName $name, NameUse $use = NameUse::Routine): void
33    {
34        if ($name->schema !== null) {
35            $out->name($name->schema, NameUse::Qualifier)->symbol('.');
36        }
37        $out->name($name->name, $use);
38    }
39
40    /**
41     * Writes the label that begins a block or loop, when there is one.
42     */
43    public function label(Output $out, ?Name $label): void
44    {
45        if ($label !== null) {
46            $out->name($label, NameUse::Label)->glue()->symbol(':');
47        }
48    }
49
50    /**
51     * Writes the label that ends a block or loop, when there is one.
52     */
53    public function end(Output $out, ?Name $label): void
54    {
55        if ($label !== null) {
56            $out->name($label, NameUse::Label);
57        }
58    }
59
60    /**
61     * Writes a data type and its COLLATE clause, when there is one.
62     */
63    public function type(Output $out, TypeName $type, ?CollationName $collation): void
64    {
65        $out->node($type);
66        if ($collation !== null) {
67            $out->keyword('COLLATE')->node($collation);
68        }
69    }
70}
71