packages/sql-semantics-postgres/src/Statement/Operator/MemberPurpose.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Statement\Operator;
6
7use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
8use SqlSemantics\Platform\PostgreSql\Model\Rendering\Output;
9use SqlSemantics\Platform\PostgreSql\Model\Resolution\Environment;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Snapshot;
11use SqlSemantics\Platform\PostgreSql\Statement\Clause;
12use SqlSemantics\Platform\PostgreSql\Statement\Name\DottedName;
13
14/**
15 * `FOR SEARCH` or `FOR ORDER BY sort_family`: what an operator of an operator class is for.
16 *
17 * Without the clause an operator is for searching, as with FOR SEARCH; the
18 * written clause is kept. An ordering operator names the btree operator
19 * family that sorts its results.
20 * Source: https://www.postgresql.org/docs/17/sql-createopclass.html.
21 *
22 * @visibility public
23 * @example Telling a search operator
24 *     (new \SqlSemantics\Platform\PostgreSql\Statement\Operator\MemberPurpose())->sortFamily // => null
25 */
26final class MemberPurpose implements Clause
27{
28    use Snapshot;
29
30    /**
31     * @param DottedName|null $sortFamily The sort operator family of an ordering operator; null for FOR SEARCH
32     */
33    public function __construct(public readonly ?DottedName $sortFamily = null)
34    {
35    }
36
37    /**
38     * Derives nothing: a name holds no expression.
39     */
40    public function deriveClause(Derivation $derivation, Environment $environment): void
41    {
42    }
43
44    /**
45     * Writes FOR SEARCH or FOR ORDER BY and the family.
46     */
47    public function render(Output $out): void
48    {
49        $out->keyword('FOR');
50        if ($this->sortFamily === null) {
51            $out->keyword('SEARCH');
52
53            return;
54        }
55        $out->keyword('ORDER', 'BY')->node($this->sortFamily);
56    }
57}
58