packages/sql-semantics-mysql/src/Statement/Routine/Program/Cursor/FetchCursor.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Routine\Program\Cursor;
6
7use SqlSemantics\Platform\MySql\Model\Construction\Derivation;
8use SqlSemantics\Platform\MySql\Model\Contract\NameUse;
9use SqlSemantics\Platform\MySql\Model\Diagnostic\Check;
10use SqlSemantics\Platform\MySql\Model\Rendering\Output;
11use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
12use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
13use SqlSemantics\Platform\MySql\Rules\Routine\CursorFacts;
14use SqlSemantics\Platform\MySql\Rules\Routine\ProgramScope;
15use SqlSemantics\Platform\MySql\Statement\Routine\Program\ProgramStatement;
16
17/**
18 * FETCH: reads the next row of an open cursor into local variables.
19 *
20 * The optional words NEXT FROM and FROM carry no meaning and are not kept.
21 * The facts follow MYSQL-PROGRAM-CURSORS-001.
22 * Source: https://dev.mysql.com/doc/refman/8.4/en/fetch.html.
23 *
24 * @visibility public
25 * @example Reading the targets of a FETCH
26 *     $create = (new \SqlSemantics\Platform\MySql\Semantics())->analyze('CREATE PROCEDURE p(OUT a INT) BEGIN DECLARE c CURSOR FOR SELECT 1; FETCH NEXT FROM c INTO a; END');
27 *     [$create->statement->body->statements[0]->targets[0]->value, $create->toString()] // => ['a', 'CREATE PROCEDURE p(OUT a INT) BEGIN DECLARE c CURSOR FOR SELECT 1; FETCH c INTO a; END']
28 */
29final class FetchCursor implements ProgramStatement
30{
31    use Snapshot;
32
33    /**
34     * @var non-empty-list<Name> The variables that receive the row, in written order
35     */
36    public readonly array $targets;
37
38    /**
39     * @param Name $cursor The cursor name
40     * @param list<Name> $targets The variables that receive the row; at least one
41     */
42    public function __construct(public readonly Name $cursor, array $targets)
43    {
44        $this->targets = Check::listOf($targets, Name::class, 'FETCH names at least one variable.', 1);
45    }
46
47    /**
48     * Checks that the cursor and the variables are declared.
49     */
50    public function deriveProgram(Derivation $derivation, ProgramScope $scope): void
51    {
52        (new CursorFacts())->cursor($this->cursor, $derivation, $scope);
53        (new CursorFacts())->variables($this->targets, $derivation, $scope);
54    }
55
56    /**
57     * Writes the statement.
58     */
59    public function render(Output $out): void
60    {
61        $out->keyword('FETCH')->name($this->cursor, NameUse::Identifier)->keyword('INTO');
62        foreach ($this->targets as $position => $target) {
63            if ($position > 0) {
64                $out->symbol(',');
65            }
66            $out->name($target, NameUse::Identifier);
67        }
68    }
69}
70