packages/sql-semantics-postgres/src/Statement/Expression/Subquery/UniquePredicate.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Statement\Expression\Subquery;
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\Fact\ScalarFact;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Query;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Scalar;
13use SqlSemantics\Platform\PostgreSql\Model\Statement\Snapshot;
14use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Invalid;
15use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Nullability;
16use SqlSemantics\Platform\PostgreSql\Statement\Expression\Problem\NotImplemented;
17
18/**
19 * The SQL-standard test of whether a query returns no duplicate rows: `UNIQUE [NULLS [NOT] DISTINCT] (SELECT …)`.
20 *
21 * The grammar accepts the predicate, and the server rejects it while parsing
22 * because it does not implement it.
23 *
24 * Rule: PG-UNIQUE-PREDICATE-001. The query is derived in the environment of
25 * the expression. Facts: the predicate is reported as not implemented, and
26 * its type is invalid.
27 * Source: https://www.postgresql.org/docs/17/features.html (feature F291), the grammar action of `a_expr: UNIQUE …`. Status: Implemented.
28 *
29 * @visibility public
30 * @example Reporting the predicate
31 * (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze('SELECT UNIQUE NULLS NOT DISTINCT (SELECT 1)') // throws \SqlSemantics\Platform\PostgreSql\Model\Diagnostic\SemanticException: UNIQUE predicate is not yet implemented.
32 */
33final class UniquePredicate implements Scalar
34{
35 use Snapshot;
36
37 /**
38 * @param bool|null $nullsDistinct Whether NULLS DISTINCT (true) or NULLS NOT DISTINCT (false) is written, or null when neither is
39 * @param Query $query The query inside the parentheses
40 */
41 public function __construct(public readonly ?bool $nullsDistinct, public readonly Query $query)
42 {
43 }
44
45 /**
46 * Derives the query and reports the predicate.
47 */
48 public function deriveScalar(Derivation $derivation, Environment $environment): ScalarFact
49 {
50 $derivation->query($this->query, $environment);
51 $problem = new NotImplemented('UNIQUE predicate');
52 $derivation->report($problem);
53
54 return new ScalarFact(new Invalid($problem), Nullability::Dependent);
55 }
56
57 /**
58 * Writes UNIQUE, the NULLS treatment and the query in parentheses.
59 */
60 public function render(Output $out): void
61 {
62 $out->keyword('UNIQUE');
63 if ($this->nullsDistinct !== null) {
64 $out->keyword(...($this->nullsDistinct ? ['NULLS', 'DISTINCT'] : ['NULLS', 'NOT', 'DISTINCT']));
65 }
66 $out->symbol('(')->node($this->query)->symbol(')');
67 }
68}
69