packages/sql-semantics-postgres/src/Statement/Object/Reference/CastPair.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Statement\Object\Reference;
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\Name\ObjectReference;
12use SqlSemantics\Platform\PostgreSql\Statement\Type\TypeName;
13
14/**
15 * A cast named by its source and target types: `( source AS target )`.
16 *
17 * Source: https://www.postgresql.org/docs/17/sql-dropcast.html.
18 *
19 * @visibility public
20 * @example Reading the target type
21 *     $text = new \SqlSemantics\Platform\PostgreSql\Statement\Type\TypeName(new \SqlSemantics\Platform\PostgreSql\Statement\Type\Designation\NamedDesignation(new \SqlSemantics\Platform\PostgreSql\Statement\Name\DottedName([new \SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name('text')])));
22 *     $mood = new \SqlSemantics\Platform\PostgreSql\Statement\Type\TypeName(new \SqlSemantics\Platform\PostgreSql\Statement\Type\Designation\NamedDesignation(new \SqlSemantics\Platform\PostgreSql\Statement\Name\DottedName([new \SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name('mood')])));
23 *     (new \SqlSemantics\Platform\PostgreSql\Statement\Object\Reference\CastPair($text, $mood))->target === $mood // => true
24 */
25final class CastPair implements ObjectReference
26{
27    use Snapshot;
28
29    /**
30     * @param TypeName $source The source type
31     * @param TypeName $target The target type
32     */
33    public function __construct(public readonly TypeName $source, public readonly TypeName $target)
34    {
35    }
36
37    /**
38     * Derives the type modifiers.
39     */
40    public function deriveClause(Derivation $derivation, Environment $environment): void
41    {
42        $this->source->deriveClause($derivation, $environment);
43        $this->target->deriveClause($derivation, $environment);
44    }
45
46    /**
47     * Writes the types in parentheses.
48     */
49    public function render(Output $out): void
50    {
51        $out->symbol('(')->node($this->source)->keyword('AS')->node($this->target)->symbol(')');
52    }
53}
54