packages/sql-semantics-postgres/src/Statement/Manipulation/Cursor/FetchMovement.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Statement\Manipulation\Cursor;
6
7use SqlSemantics\Platform\PostgreSql\Model\Rendering\Output;
8
9/**
10 * Where FETCH or MOVE positions the cursor, as written.
11 *
12 * Mirrors the `direction` and `howMany` of PostgreSQL's `FetchStmt`: NEXT
13 * and a missing direction are FORWARD 1, PRIOR is BACKWARD 1, FIRST is
14 * ABSOLUTE 1, LAST is ABSOLUTE -1, a count alone is FORWARD count and ALL is
15 * FORWARD ALL. The spellings are kept because they are different requests
16 * of the grammar. The counted movements take a count.
17 * Source: https://www.postgresql.org/docs/17/sql-fetch.html.
18 *
19 * @visibility public
20 * @example Reading a movement
21 *     $fetch = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze('FETCH BACKWARD 5 FROM c');
22 *     [$fetch->statement->movement, $fetch->statement->count->magnitude->digits] // => [\SqlSemantics\Platform\PostgreSql\Statement\Manipulation\Cursor\FetchMovement::BackwardCount, '5']
23 */
24enum FetchMovement
25{
26    case Implicit;
27    case Next;
28    case Prior;
29    case First;
30    case Last;
31    case Absolute;
32    case Relative;
33    case Count;
34    case All;
35    case Forward;
36    case ForwardCount;
37    case ForwardAll;
38    case Backward;
39    case BackwardCount;
40    case BackwardAll;
41
42    /**
43     * Tells whether the movement takes a count.
44     */
45    public function counted(): bool
46    {
47        return in_array($this, [self::Absolute, self::Relative, self::Count, self::ForwardCount, self::BackwardCount], true);
48    }
49
50    /**
51     * Writes the keywords before the count.
52     */
53    public function write(Output $out): void
54    {
55        $keywords = match ($this) {
56            self::Implicit, self::Count => [],
57            self::Next => ['NEXT'],
58            self::Prior => ['PRIOR'],
59            self::First => ['FIRST'],
60            self::Last => ['LAST'],
61            self::Absolute => ['ABSOLUTE'],
62            self::Relative => ['RELATIVE'],
63            self::All => ['ALL'],
64            self::Forward, self::ForwardCount => ['FORWARD'],
65            self::ForwardAll => ['FORWARD', 'ALL'],
66            self::Backward, self::BackwardCount => ['BACKWARD'],
67            self::BackwardAll => ['BACKWARD', 'ALL'],
68        };
69        if ($keywords !== []) {
70            $out->keyword(...$keywords);
71        }
72    }
73}
74