packages/sql-semantics-postgres/src/Statement/Invocation/Json/JsonPair.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Statement\Invocation\Json;
6
7use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
8use SqlSemantics\Platform\PostgreSql\Model\Diagnostic\Check;
9use SqlSemantics\Platform\PostgreSql\Model\Rendering\Output;
10use SqlSemantics\Platform\PostgreSql\Model\Resolution\Environment;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Scalar;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Snapshot;
13use SqlSemantics\Platform\PostgreSql\Rules\Expression\Precedence;
14use SqlSemantics\Platform\PostgreSql\Statement\Clause;
15
16/**
17 * A key and its value in JSON_OBJECT or JSON_OBJECTAGG.
18 *
19 * Mirrors PostgreSQL's `JsonPair` node. With the VALUE spelling the key
20 * is a primary expression; a key that would need parentheses is rejected.
21 * Source: https://www.postgresql.org/docs/17/functions-json.html#FUNCTIONS-JSON-CREATION-TABLE.
22 *
23 * @visibility public
24 * @example Reading a key and value pair
25 *     $pair = new \SqlSemantics\Platform\PostgreSql\Statement\Invocation\Json\JsonPair(new \SqlSemantics\Platform\PostgreSql\Statement\Literal\NullLiteral(), new \SqlSemantics\Platform\PostgreSql\Statement\Invocation\Json\JsonValueExpression(new \SqlSemantics\Platform\PostgreSql\Statement\Literal\NullLiteral()));
26 *     $pair->spelling->value // => ':'
27 */
28final class JsonPair implements Clause
29{
30    use Snapshot;
31
32    /**
33     * @param Scalar $key The key
34     * @param JsonValueExpression $value The value
35     * @param KeyValueSpelling $spelling How the key joins the value
36     */
37    public function __construct(public readonly Scalar $key, public readonly JsonValueExpression $value, public readonly KeyValueSpelling $spelling = KeyValueSpelling::Colon)
38    {
39        Check::input($spelling === KeyValueSpelling::Colon || (new Precedence())->primary($key), 'A key before VALUE is a primary expression; group it.');
40    }
41
42    /**
43     * Derives the key and the value.
44     */
45    public function deriveClause(Derivation $derivation, Environment $environment): void
46    {
47        $derivation->scalar($this->key, $environment);
48        $this->value->deriveValue($derivation, $environment);
49    }
50
51    /**
52     * Writes the key, the joining word or symbol, and the value.
53     */
54    public function render(Output $out): void
55    {
56        $out->node($this->key);
57        if ($this->spelling === KeyValueSpelling::Value) {
58            $out->keyword('VALUE');
59        } else {
60            $out->symbol(':');
61        }
62        $out->node($this->value);
63    }
64}
65