packages/sql-semantics-mysql/tests/Unit/Statement/Dml/Insert/InsertQueryTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Dml\Insert;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\MySql\Model\Statement\Declaration\Column;
11use SqlSemantics\Platform\MySql\Model\Statement\Declaration\Table;
12use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
13use SqlSemantics\Platform\MySql\Model\Statement\Identifier\QualifiedName;
14use SqlSemantics\Platform\MySql\Model\Statement\Type\Nullability;
15use SqlSemantics\Platform\MySql\Semantics;
16use SqlSemantics\Platform\MySql\Statement\Dml\Insert\InsertQuery;
17use SqlSemantics\Platform\MySql\Statement\Dml\Problem\ValueCountMismatch;
18use SqlSemantics\Platform\MySql\Statement\Type\Integral;
19use SqlSemantics\Platform\MySql\Statement\Type\Kind\IntegralKind;
20
21#[CoversClass(InsertQuery::class)]
22#[Medium]
23final class InsertQueryTest extends TestCase
24{
25 public function testDeriveStatementComparesTheQueryWidth(): void
26 {
27 $semantics = new Semantics();
28 $t = new Table(new QualifiedName(new Name('t'), new Name('(current)')), $semantics->profile(), [new Column(new Name('a'), new Integral(IntegralKind::Int), Nullability::NotNull), new Column(new Name('b'), new Integral(IntegralKind::BigInt))]);
29 $operation = $semantics->inspect('INSERT INTO t (a) SELECT 1, 2', [$t]);
30
31 self::assertCount(1, $operation->facts->diagnostics);
32 self::assertInstanceOf(ValueCountMismatch::class, $operation->facts->diagnostics[0]);
33 self::assertNull($operation->facts->diagnostics[0]->row);
34 }
35
36 public function testDeriveStatementLetsUpdatesSeeTheSourceTables(): void
37 {
38 $semantics = new Semantics();
39 $t = new Table(new QualifiedName(new Name('t'), new Name('(current)')), $semantics->profile(), [new Column(new Name('a'), new Integral(IntegralKind::Int), Nullability::NotNull), new Column(new Name('b'), new Integral(IntegralKind::BigInt))]);
40 $u = new Table(new QualifiedName(new Name('u'), new Name('(current)')), $semantics->profile(), [new Column(new Name('x'), new Integral(IntegralKind::Int)), new Column(new Name('y'), new Integral(IntegralKind::Int))]);
41 $operation = $semantics->inspect('INSERT INTO t (a) SELECT x FROM u ON DUPLICATE KEY UPDATE b = u.y + x', [$t, $u]);
42
43 self::assertSame([], $operation->facts->diagnostics);
44 }
45
46 public function testRenderWritesTheSource(): void
47 {
48 self::assertSame('INSERT INTO t (SELECT 1 LIMIT 1) UNION SELECT 2', (new Semantics('mysql-5.7.44'))->inspect('insert into t (select 1 limit 1) union select 2')->toString());
49 self::assertSame('INSERT INTO t TABLE u', (new Semantics())->inspect('insert t table u')->toString());
50 }
51}
52