packages/sql-semantics-mysql/tests/Unit/Statement/Expression/Operator/BinaryCastTest.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\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\MySql\Mode;
11use SqlSemantics\Platform\MySql\Model\Construction\Derivation;
12use SqlSemantics\Platform\MySql\Model\Contract\ParameterStyle;
13use SqlSemantics\Platform\MySql\Model\Rendering\Lexical;
14use SqlSemantics\Platform\MySql\Model\Rendering\Output;
15use SqlSemantics\Platform\MySql\Model\Statement\Type\Known;
16use SqlSemantics\Platform\MySql\Model\Statement\Type\Nullability;
17use SqlSemantics\Platform\MySql\Platform;
18use SqlSemantics\Platform\MySql\Statement\Expression\Operator\BinaryCast;
19use SqlSemantics\Platform\MySql\Statement\Expression\Operator\Concatenation;
20use SqlSemantics\Platform\MySql\Statement\Expression\Operator\Unary;
21use SqlSemantics\Platform\MySql\Statement\Expression\Operator\UnaryOperator;
22use SqlSemantics\Platform\MySql\Statement\Literal\NumberLiteral;
23use SqlSemantics\Platform\MySql\Statement\Type\Binary;
24use SqlSemantics\Platform\MySql\Statement\Type\Kind\BinaryKind;
25
26#[CoversClass(BinaryCast::class)]
27#[Medium]
28final class BinaryCastTest extends TestCase
29{
30 public function testDeriveScalarIsABinaryString(): void
31 {
32 $platform = new Platform();
33 $derivation = new Derivation($platform->context($platform->profile('mysql-5.7.44', null, ParameterStyle::Native), null, [], true));
34 $fact = $derivation->scalar(new BinaryCast(new NumberLiteral('1')), $derivation->environment());
35
36 self::assertEquals([new Known(new Binary(BinaryKind::VarBinary)), Nullability::NotNull], [$fact->type, $fact->nullability]);
37 }
38
39 public function testRenderCastsAPrefixOperandWithoutParentheses(): void
40 {
41 $platform = new Platform();
42 $out = new Output($platform->codec($platform->profile('mysql-8.4.7', Mode::fromString('PIPES_AS_CONCAT'), ParameterStyle::Native)));
43 (new Concatenation(new BinaryCast(new Unary(UnaryOperator::Minus, new NumberLiteral('1'))), new NumberLiteral('2')))->render($out);
44
45 self::assertSame('BINARY - 1 || 2', (new Lexical())->join($out->pieces()));
46 }
47
48 public function testAConcatenationOperandIsRejected(): void
49 {
50 $this->expectExceptionMessage('The operand of BINARY needs a grouping to keep its place.');
51
52 new BinaryCast(new Concatenation(new NumberLiteral('1'), new NumberLiteral('2')));
53 }
54}
55