packages/sql-semantics-postgres/src/Statement/Expression/Cast.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Statement\Expression;
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\Fact\ScalarFact;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
13use SqlSemantics\Platform\PostgreSql\Model\Statement\Scalar;
14use SqlSemantics\Platform\PostgreSql\Model\Statement\Snapshot;
15use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Invalid;
16use SqlSemantics\Platform\PostgreSql\Rules\Expression\ColumnNaming;
17use SqlSemantics\Platform\PostgreSql\Rules\Expression\Precedence;
18use SqlSemantics\Platform\PostgreSql\Statement\OutputNaming;
19use SqlSemantics\Platform\PostgreSql\Statement\Type\TypeName;
20
21/**
22 * A conversion of a value to a type: `x::t` or `CAST(x AS t)`.
23 *
24 * Mirrors PostgreSQL's `TypeCast` node. Both spellings are the same node;
25 * the spelling is kept because the token sequences differ.
26 *
27 * Rule: PG-CAST-001. Facts: the type the type name denotes; the NULL fact of
28 * the operand, since a cast of NULL is NULL and a cast of a value is a value.
29 * An unaliased result column is named after the operand when the operand
30 * names one firmly, and otherwise after the type. The operand of `::` must
31 * keep its place without parentheses (PG-PRECEDENCE-001).
32 * Source: https://www.postgresql.org/docs/17/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS,
33 * https://www.postgresql.org/docs/17/sql-createcast.html. Status: Implemented.
34 *
35 * @visibility public
36 * @example Reading the type of a cast
37 *     $query = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze("SELECT '1'::bigint");
38 *     [$query->field(0)->type->descriptor->name(), $query->field(0)->name->value] // => ['bigint', 'int8']
39 * @example Rejecting an operand that would need parentheses
40 *     $sum = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze('SELECT 1 + 2')->field(0)->expression;
41 *     $type = new \SqlSemantics\Platform\PostgreSql\Statement\Type\TypeName(new \SqlSemantics\Platform\PostgreSql\Statement\Type\Designation\KeywordDesignation(\SqlSemantics\Platform\PostgreSql\Statement\Type\Designation\TypeKeyword::Integer));
42 *     new \SqlSemantics\Platform\PostgreSql\Statement\Expression\Cast($sum, $type, \SqlSemantics\Platform\PostgreSql\Statement\Expression\CastSpelling::Operator) // throws \SqlSemantics\Platform\PostgreSql\Model\Diagnostic\InvalidConstruction
43 */
44final class Cast implements Scalar, OutputNaming
45{
46    use Snapshot;
47
48    /**
49     * @param Scalar $operand The converted value
50     * @param TypeName $type The target type
51     * @param CastSpelling $spelling How the cast is written
52     */
53    public function __construct(public readonly Scalar $operand, public readonly TypeName $type, public readonly CastSpelling $spelling)
54    {
55        Check::input($spelling === CastSpelling::Function || (new Precedence())->before($operand, Precedence::TYPECAST), 'The operand of :: needs parentheses to keep its place.');
56    }
57
58    /**
59     * Names an unaliased result column after the operand, or after the type.
60     */
61    public function outputName(): ?Name
62    {
63        return (new ColumnNaming())->name($this);
64    }
65
66    /**
67     * Derives the operand and the target type.
68     */
69    public function deriveScalar(Derivation $derivation, Environment $environment): ScalarFact
70    {
71        $operand = $derivation->scalar($this->operand, $environment);
72        $this->type->deriveClause($derivation, $environment);
73        $type = $this->type->typeFact($derivation->context);
74        if ($type instanceof Invalid) {
75            $derivation->report($type->cause);
76        }
77
78        return new ScalarFact($type, $operand->nullability);
79    }
80
81    /**
82     * Writes the operand, `::` and the type, or the CAST form.
83     */
84    public function render(Output $out): void
85    {
86        if ($this->spelling === CastSpelling::Operator) {
87            $out->node($this->operand)->symbol('::')->node($this->type);
88
89            return;
90        }
91        $out->keyword('CAST')->symbol('(')->node($this->operand)->keyword('AS')->node($this->type)->symbol(')');
92    }
93}
94