packages/sql-semantics-mysql/src/Statement/Routine/Condition/Diagnostics/GetDiagnostics.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Routine\Condition\Diagnostics;
6
7use SqlSemantics\Platform\MySql\Model\Construction\Derivation;
8use SqlSemantics\Platform\MySql\Model\Rendering\Output;
9use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
10use SqlSemantics\Platform\MySql\Model\Statement\Statement;
11use SqlSemantics\Platform\MySql\Rules\Routine\ConditionFacts;
12use SqlSemantics\Platform\MySql\Rules\Routine\ProgramScope;
13use SqlSemantics\Platform\MySql\Statement\Routine\Program\ProgramStatement;
14
15/**
16 * GET DIAGNOSTICS: copies statement or condition information of a diagnostics area into variables.
17 *
18 * The statement is valid on its own and inside a stored program; it returns
19 * no rows. The facts follow MYSQL-PROGRAM-CONDITIONS-001.
20 * Source: https://dev.mysql.com/doc/refman/8.4/en/get-diagnostics.html.
21 *
22 * @visibility public
23 * @example Reading the area and the kind of information
24 *     $get = (new \SqlSemantics\Platform\MySql\Semantics())->analyze('GET STACKED DIAGNOSTICS CONDITION 1 @m = MESSAGE_TEXT');
25 *     [$get->statement->area->value, $get->toString()] // => ['STACKED', 'GET STACKED DIAGNOSTICS CONDITION 1 @m = MESSAGE_TEXT']
26 */
27final class GetDiagnostics implements Statement, ProgramStatement
28{
29    use Snapshot;
30
31    /**
32     * @param ConditionDiagnostics|StatementDiagnostics $information The information read
33     * @param DiagnosticsArea|null $area The area keyword, when written
34     */
35    public function __construct(public readonly ConditionDiagnostics|StatementDiagnostics $information, public readonly ?DiagnosticsArea $area = null)
36    {
37    }
38
39    /**
40     * Derives the statement outside a stored program, where no local variable is in scope.
41     */
42    public function deriveStatement(Derivation $derivation): void
43    {
44        $this->deriveProgram($derivation, new ProgramScope($derivation->environment()));
45    }
46
47    /**
48     * Derives the condition number and the targets in the scope of the statement.
49     */
50    public function deriveProgram(Derivation $derivation, ProgramScope $scope): void
51    {
52        if ($this->information instanceof ConditionDiagnostics) {
53            $derivation->scalar($this->information->number, $scope->environment);
54        }
55        (new ConditionFacts())->targets($this->information->items, $derivation, $scope);
56    }
57
58    /**
59     * Writes the statement.
60     */
61    public function render(Output $out): void
62    {
63        $out->keyword('GET');
64        if ($this->area !== null) {
65            $out->keyword($this->area->value);
66        }
67        $out->keyword('DIAGNOSTICS')->node($this->information);
68    }
69}
70