packages/sql-semantics-postgres/tests/Unit/Statement/Routine/Option/RoutineSourceTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Routine\Option;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\PostgreSql\Model\Contract\GrammarRelease;
11use SqlSemantics\Platform\PostgreSql\Model\Rendering\Lexical;
12use SqlSemantics\Platform\PostgreSql\Model\Rendering\Output;
13use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
14use SqlSemantics\Platform\PostgreSql\Rendering\Codec;
15use SqlSemantics\Platform\PostgreSql\Semantics;
16use SqlSemantics\Platform\PostgreSql\Statement\Literal\StringConstant;
17use SqlSemantics\Platform\PostgreSql\Statement\Routine\CreateFunction;
18use SqlSemantics\Platform\PostgreSql\Statement\Routine\Option\RoutineDefinition;
19use SqlSemantics\Platform\PostgreSql\Statement\Routine\Option\RoutineSource;
20
21#[CoversClass(RoutineSource::class)]
22#[Medium]
23final class RoutineSourceTest extends TestCase
24{
25    public function testRenderWritesTheTextAsAString(): void
26    {
27        $out = new Output(new Codec(GrammarRelease::PostgreSql172));
28        (new RoutineSource(new Name('sql'), new StringConstant('SELECT 1')))->render($out);
29        self::assertSame("'SELECT 1'", (new Lexical())->join($out->pieces()));
30    }
31
32    public function testAnalyzeKeepsAnSqlDefinitionUnanalysedWithItsLanguage(): void
33    {
34        $operation = (new Semantics())->inspect('CREATE FUNCTION f(a int4) RETURNS int4 AS $$ SELECT a FROM missing $$ LANGUAGE sql');
35        $function = $operation->statement;
36        self::assertInstanceOf(CreateFunction::class, $function);
37        $definition = $function->options[0];
38        self::assertInstanceOf(RoutineDefinition::class, $definition);
39        self::assertSame(['sql', ' SELECT a FROM missing ', []], [$definition->source->language?->value, $definition->source->text->value, $operation->facts->diagnostics]);
40    }
41
42    public function testAnalyzeNamesNoLanguageWithoutALanguageOption(): void
43    {
44        $operation = (new Semantics())->inspect("CREATE FUNCTION f() RETURNS int4 AS 'x'");
45        $function = $operation->statement;
46        self::assertInstanceOf(CreateFunction::class, $function);
47        $definition = $function->options[0];
48        self::assertInstanceOf(RoutineDefinition::class, $definition);
49        self::assertNull($definition->source->language);
50    }
51}
52