packages/sql-semantics-mysql/src/Statement/Dml/Handler/HandlerIndexRead.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Dml\Handler;
6
7use SqlSemantics\Platform\MySql\Model\Construction\Derivation;
8use SqlSemantics\Platform\MySql\Model\Contract\NameUse;
9use SqlSemantics\Platform\MySql\Model\Rendering\Output;
10use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
11use SqlSemantics\Platform\MySql\Model\Statement\Scalar;
12use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
13use SqlSemantics\Platform\MySql\Model\Statement\Statement;
14use SqlSemantics\Platform\MySql\Rules\Dml\HandlerFacts;
15use SqlSemantics\Platform\MySql\Statement\Query\Limit;
16
17/**
18 * HANDLER ... READ index FIRST|NEXT|PREV|LAST: reads rows of an open handler in the order of an index.
19 *
20 * The facts follow MYSQL-HANDLER-READ-001.
21 * Source: https://dev.mysql.com/doc/refman/8.4/en/handler.html.
22 *
23 * @visibility public
24 * @example Reading an index read of a handler
25 * $read = (new \SqlSemantics\Platform\MySql\Semantics())->analyze('HANDLER h READ idx PREV');
26 * [$read->statement->index->value, $read->statement->direction, $read->toString()] // => ['idx', \SqlSemantics\Platform\MySql\Statement\Dml\Handler\IndexDirection::Previous, 'HANDLER h READ idx PREV']
27 */
28final class HandlerIndexRead implements Statement
29{
30 use Snapshot;
31
32 /**
33 * @param OpenHandler $handler The handler read from
34 * @param Name $index The index whose order is followed; `PRIMARY` names the primary key
35 * @param IndexDirection $direction Which row is read
36 * @param Scalar|null $where The condition rows must meet
37 * @param Limit|null $limit The most rows read
38 */
39 public function __construct(public readonly OpenHandler $handler, public readonly Name $index, public readonly IndexDirection $direction, public readonly ?Scalar $where = null, public readonly ?Limit $limit = null)
40 {
41 }
42
43 /**
44 * Derives the handler, WHERE and LIMIT, and records the rows read.
45 */
46 public function deriveStatement(Derivation $derivation): void
47 {
48 (new HandlerFacts())->read($this->handler, [], $this->where, $this->limit, $derivation);
49 }
50
51 /**
52 * Writes the statement.
53 */
54 public function render(Output $out): void
55 {
56 $out->keyword('HANDLER')->node($this->handler)->keyword('READ')->name($this->index, NameUse::Label)->keyword($this->direction->value);
57 if ($this->where !== null) {
58 $out->keyword('WHERE')->node($this->where);
59 }
60 $out->node($this->limit);
61 }
62}
63