packages/sql-semantics-postgres/tests/Unit/Statement/Expression/Operator/PatternMatchTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Expression\Operator;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Small;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
11use SqlSemantics\Platform\PostgreSql\Model\Contract\GrammarRelease;
12use SqlSemantics\Platform\PostgreSql\Model\Contract\LanguageProfile;
13use SqlSemantics\Platform\PostgreSql\Model\Rendering\Lexical;
14use SqlSemantics\Platform\PostgreSql\Model\Rendering\Output;
15use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Known;
16use SqlSemantics\Platform\PostgreSql\Platform;
17use SqlSemantics\Platform\PostgreSql\Rendering\Codec;
18use SqlSemantics\Platform\PostgreSql\Statement\Expression\Operator\Negation;
19use SqlSemantics\Platform\PostgreSql\Statement\Expression\Operator\PatternMatch;
20use SqlSemantics\Platform\PostgreSql\Statement\Expression\Operator\PatternOperator;
21use SqlSemantics\Platform\PostgreSql\Statement\Literal\Constant;
22use SqlSemantics\Platform\PostgreSql\Statement\Literal\NullLiteral;
23use SqlSemantics\Platform\PostgreSql\Statement\Literal\StringConstant;
24use SqlSemantics\Platform\PostgreSql\Statement\Type\Descriptor\Builtin;
25
26#[CoversClass(PatternMatch::class)]
27#[Small]
28final class PatternMatchTest extends TestCase
29{
30 public function testDeriveScalarIsBooleanForStrings(): void
31 {
32 $derivation = new Derivation((new Platform())->context(new LanguageProfile(GrammarRelease::PostgreSql172), null, [], true));
33 $fact = $derivation->scalar(new PatternMatch(new Constant(new StringConstant('a')), PatternOperator::SimilarTo, false, new Constant(new StringConstant('a'))), $derivation->environment());
34 self::assertEquals(new Known(Builtin::Bool), $fact->type);
35 }
36
37 public function testRenderWritesTheEscape(): void
38 {
39 $out = new Output(new Codec(GrammarRelease::PostgreSql172));
40 (new PatternMatch(new NullLiteral(), PatternOperator::ILike, true, new NullLiteral(), new NullLiteral()))->render($out);
41 self::assertSame('NULL NOT ILIKE NULL ESCAPE NULL', (new Lexical())->join($out->pieces()));
42 }
43
44 public function testAcceptsANegatedPatternBeforeTheEscape(): void
45 {
46 $pattern = new Negation(new NullLiteral());
47 self::assertSame($pattern, (new PatternMatch(new NullLiteral(), PatternOperator::Like, false, $pattern, new NullLiteral()))->right);
48 }
49
50 public function testRejectsAPatternThatWouldTakeTheEscape(): void
51 {
52 $inner = new Negation(new PatternMatch(new NullLiteral(), PatternOperator::Like, false, new NullLiteral()));
53 $this->expectExceptionMessage('The pattern or the escape needs parentheses to keep its place.');
54 new PatternMatch(new NullLiteral(), PatternOperator::Like, false, $inner, new NullLiteral());
55 }
56}
57