packages/sql-semantics-mysql/tests/Unit/Statement/Relation/Hint/TableSampleTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Relation\Hint;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\MySql\Model\Statement\Type\Known;
11use SqlSemantics\Platform\MySql\Semantics;
12use SqlSemantics\Platform\MySql\Statement\Literal\NullLiteral;
13use SqlSemantics\Platform\MySql\Statement\Query\Select;
14use SqlSemantics\Platform\MySql\Statement\Relation\Hint\SamplingMethod;
15use SqlSemantics\Platform\MySql\Statement\Relation\Hint\TableSample;
16use SqlSemantics\Platform\MySql\Statement\Relation\TableReference;
17
18#[CoversClass(TableSample::class)]
19#[Medium]
20final class TableSampleTest extends TestCase
21{
22 public function testRenderWritesTheClause(): void
23 {
24 $semantics = new Semantics('mysql-9.1.0');
25
26 self::assertSame('SELECT a FROM t x TABLESAMPLE SYSTEM (@p)', $semantics->analyze('select a from t x tablesample system (@p)')->toString());
27 self::assertSame('SELECT a FROM t TABLESAMPLE BERNOULLI (?)', $semantics->analyze('select a from t tablesample bernoulli (?)')->toString());
28 }
29
30 public function testThePercentageIsDerivedWithoutColumns(): void
31 {
32 $operation = (new Semantics('mysql-9.1.0'))->analyze('SELECT a FROM t TABLESAMPLE BERNOULLI (10)');
33
34 self::assertInstanceOf(Select::class, $operation->statement);
35 self::assertInstanceOf(TableReference::class, $operation->statement->from);
36 self::assertNotNull($operation->statement->from->sample);
37 self::assertInstanceOf(Known::class, $operation->facts->scalar($operation->statement->from->sample->percentage)->type);
38 }
39
40 public function testAnExpressionAsThePercentageIsRejected(): void
41 {
42 $this->expectExceptionMessage('A sampling percentage is a number, a user variable or a parameter marker.');
43
44 new TableSample(SamplingMethod::System, new NullLiteral());
45 }
46}
47