packages/sql-semantics-sqlite/tests/Unit/Statement/Query/ResultColumnTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Query;
6
7use PDO;
8use PDOStatement;
9use PHPUnit\Framework\Attributes\CoversClass;
10use PHPUnit\Framework\Attributes\Medium;
11use PHPUnit\Framework\Attributes\TestWith;
12use PHPUnit\Framework\TestCase;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\Name;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Operation;
15use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\Field;
16use SqlSemantics\Platform\Sqlite\Model\Statement\Spelling\Layout;
17use SqlSemantics\Platform\Sqlite\Model\Statement\Spelling\Spelled;
18use SqlSemantics\Platform\Sqlite\Semantics;
19use SqlSemantics\Platform\Sqlite\Statement\Expression\ColumnUse;
20use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\IntegerLiteral;
21use SqlSemantics\Platform\Sqlite\Statement\Expression\Operator\Binary;
22use SqlSemantics\Platform\Sqlite\Statement\Expression\Operator\BinaryOperator;
23use SqlSemantics\Platform\Sqlite\Statement\Query\ResultColumn;
24use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
25
26#[CoversClass(ResultColumn::class)]
27#[Medium]
28final class ResultColumnTest extends TestCase
29{
30    public function testRenderWritesTheAliasWithAsWhenItWasWritten(): void
31    {
32        $query = (new Semantics())->analyze('select 1 one, a as "x y", b from t');
33
34        self::assertInstanceOf(Select::class, $query->statement);
35        $columns = $query->statement->columns;
36        self::assertInstanceOf(ResultColumn::class, $columns[0]);
37        self::assertSame('one', $columns[0]->alias?->value);
38        self::assertInstanceOf(ResultColumn::class, $columns[1]);
39        self::assertSame('x y', $columns[1]->alias?->value);
40        self::assertInstanceOf(ResultColumn::class, $columns[2]);
41        self::assertNull($columns[2]->alias);
42        self::assertInstanceOf(ColumnUse::class, $columns[2]->expression);
43        self::assertSame('SELECT 1 one, a AS `x y`, b FROM t', $query->toString());
44        self::assertFalse($columns[0]->as);
45        self::assertTrue($columns[1]->as);
46    }
47
48    public function testRenderWritesANewlyBuiltColumn(): void
49    {
50        $semantics = new Semantics();
51        $operation = new Operation($semantics->context(), new Select([new ResultColumn(new IntegerLiteral('1'), new Name('n'), null, false), new ResultColumn(new IntegerLiteral('2')), new ResultColumn(new Binary(BinaryOperator::Add, new IntegerLiteral('1'), new IntegerLiteral('1')), null, new Layout([new Spelled('', '1'), new Spelled('', '+'), new Spelled('', '1')]))]));
52
53        self::assertSame('SELECT 1 n, 2, 1+1', $operation->toString());
54        self::assertSame(['n', '2', '1+1'], array_map(static fn (Field $field): ?string => $field->name?->value, $operation->fields()->items ?? []));
55    }
56
57    public function testRenderWritesTheExpressionInItsLayout(): void
58    {
59        $query = (new Semantics())->analyze("SELECT 1 + /* one */ 1, a  COLLATE  nocase, (select 2 x), 'y' AS y FROM t");
60        self::assertInstanceOf(Select::class, $query->statement);
61        $columns = $query->statement->columns;
62
63        self::assertInstanceOf(ResultColumn::class, $columns[0]);
64        self::assertSame('1 + /* one */ 1', $columns[0]->layout?->text());
65        self::assertInstanceOf(ResultColumn::class, $columns[2]);
66        self::assertSame('(select 2 x)', $columns[2]->layout?->text());
67        self::assertInstanceOf(ResultColumn::class, $columns[3]);
68        self::assertNull($columns[3]->layout);
69        self::assertSame("SELECT 1 + /* one */ 1, a  COLLATE  nocase, (select 2 x), 'y' AS y FROM t", $query->toString());
70    }
71
72    public function testRenderKeepsNoLayoutForTheCanonicalSpelling(): void
73    {
74        $query = (new Semantics())->analyze('SELECT 1 + 1, a FROM t');
75        self::assertInstanceOf(Select::class, $query->statement);
76        $columns = $query->statement->columns;
77
78        self::assertInstanceOf(ResultColumn::class, $columns[0]);
79        self::assertNull($columns[0]->layout);
80        self::assertSame('1 + 1', $query->field(0)->name?->value);
81    }
82
83    #[TestWith(['SELECT "1+1" FROM (SELECT 1+1)'])]
84    #[TestWith(["SELECT 1 + /* c */ 1, a  COLLATE  nocase, 'x', -a, a NOTNULL, a not null, b IS NOT NULL FROM t"])]
85    #[TestWith(['SELECT * FROM (SELECT A, a+1, true, "zz", (a), t.b, a COLLATE nocase FROM t)'])]
86    #[TestWith(["SELECT * FROM (SELECT 1000, 0X1f, 1.50E-3, x'0aff', 'text'.a, CROSS.b FROM t AS 'text', t AS CROSS)"])]
87    #[TestWith(['WITH w AS (SELECT a COLLATE nocase, likely(b), cast(a as text), max(a) OVER () FROM t) SELECT * FROM w'])]
88    #[TestWith(['SELECT * FROM (SELECT (SELECT 1 FROM t x), a  +  1 FROM t UNION SELECT 2, 3), (VALUES ("zz", 1))'])]
89    #[TestWith(['SELECT * FROM (SELECT a, a, a AS "a:1", true, 1 AS false FROM t)'])]
90    #[TestWith(["INSERT INTO t VALUES (2, 'y') RETURNING a+1, b  COLLATE nocase, rowid"])]
91    #[TestWith(['SELECT 1+1 /*c*/ ,2'])]
92    #[TestWith(["SELECT a+1 -- c\n , b /* d */ FROM t"])]
93    #[TestWith(['SELECT 1+1 -- c'])]
94    #[TestWith(["SELECT 1+1 /* c */ \n\t"])]
95    #[TestWith(['SELECT * FROM (SELECT a+1 /* x */ , b /* y */ FROM t)'])]
96    #[TestWith(['WITH w AS (SELECT a /* x */, a+1 /* y */ FROM t) SELECT * FROM w'])]
97    #[TestWith(['SELECT (SELECT 1+1 /* x */ ) /* y */ UNION SELECT 2'])]
98    #[TestWith(["INSERT INTO t VALUES (2, 'y') RETURNING a+1 /* c */ , b -- d"])]
99    public function testRenderKeepsTheNamesAndTheResultsSqliteGives(string $sql): void
100    {
101        $semantics = new Semantics();
102        $operation = $semantics->analyze($sql, [$semantics->analyze('CREATE TABLE t (a INTEGER, b TEXT)')]);
103        $source = new PDO('sqlite::memory:');
104        $rendered = new PDO('sqlite::memory:');
105        $source->exec("CREATE TABLE t (a INTEGER, b TEXT); INSERT INTO t VALUES (1, 'x')");
106        $rendered->exec("CREATE TABLE t (a INTEGER, b TEXT); INSERT INTO t VALUES (1, 'x')");
107        $original = $source->query($sql);
108        $rebuilt = $rendered->query($operation->toString());
109        self::assertInstanceOf(PDOStatement::class, $original);
110        self::assertInstanceOf(PDOStatement::class, $rebuilt);
111        $names = array_map(static fn (int $position): mixed => $original->getColumnMeta($position) === false ? null : $original->getColumnMeta($position)['name'], range(0, $original->columnCount() - 1));
112
113        self::assertSame($names, array_map(static fn (int $position): mixed => $rebuilt->getColumnMeta($position) === false ? null : $rebuilt->getColumnMeta($position)['name'], range(0, $rebuilt->columnCount() - 1)));
114        self::assertSame($names, array_map(static fn (Field $field): ?string => $field->name?->value, $operation->fields()->items ?? []));
115        self::assertSame($original->fetchAll(PDO::FETCH_NUM), $rebuilt->fetchAll(PDO::FETCH_NUM));
116    }
117
118    public function testRenderRefusesALayoutThatDoesNotSpellTheExpression(): void
119    {
120        $this->expectExceptionMessage('The layout of a result column spells one token per token its expression renders.');
121
122        new ResultColumn(new IntegerLiteral('1'), null, new Layout([new Spelled('', '1'), new Spelled('', '+')]));
123    }
124
125    public function testRenderKeepsTheCommentAfterTheExpression(): void
126    {
127        $query = (new Semantics())->analyze("SELECT 1+1 /*c*/ ,2, 3 -- d\n");
128        self::assertInstanceOf(Select::class, $query->statement);
129        $columns = $query->statement->columns;
130
131        self::assertInstanceOf(ResultColumn::class, $columns[0]);
132        self::assertSame(' /*c*/ ', $columns[0]->layout?->trail);
133        self::assertInstanceOf(ResultColumn::class, $columns[1]);
134        self::assertNull($columns[1]->layout);
135        self::assertInstanceOf(ResultColumn::class, $columns[2]);
136        self::assertSame(" -- d\n", $columns[2]->layout?->trail);
137        self::assertSame(['1+1 /*c*/', '2', '3 -- d'], array_map(static fn (Field $field): ?string => $field->name?->value, $query->fields()->items ?? []));
138        self::assertSame("SELECT 1+1 /*c*/ , 2, 3 -- d\n", $query->toString());
139    }
140
141    public function testRenderRefusesWhitespaceAloneAfterTheExpression(): void
142    {
143        $this->expectExceptionMessage('The layout of a result column keeps the trivia after its expression only when it holds a comment.');
144
145        new ResultColumn(new IntegerLiteral('1'), null, new Layout([new Spelled('', '1')], ' '));
146    }
147
148    public function testRenderRefusesTheCanonicalSpellingAsALayout(): void
149    {
150        $this->expectExceptionMessage('A result column written in the canonical spelling has no layout.');
151
152        new ResultColumn(new Binary(BinaryOperator::Add, new IntegerLiteral('1'), new IntegerLiteral('1')), null, new Layout([new Spelled('', '1'), new Spelled(' ', '+'), new Spelled(' ', '1')]));
153    }
154
155    public function testRenderRefusesALayoutOfAnAliasedColumn(): void
156    {
157        $this->expectExceptionMessage('An aliased result column is named by its alias and keeps no layout.');
158
159        new ResultColumn(new IntegerLiteral('1'), new Name('x'), new Layout([new Spelled('', '01')]));
160    }
161
162    public function testRenderRefusesToLeaveOutAsWithoutAnAlias(): void
163    {
164        $this->expectExceptionMessage('AS is left out only before an alias.');
165
166        new ResultColumn(new IntegerLiteral('1'), null, null, false);
167    }
168
169    public function testRenderRefusesALayoutThatChangesAToken(): void
170    {
171        $this->expectExceptionMessage('The spelled SQL is not the rendered SQL at token 1');
172
173        new Operation((new Semantics())->context(), new Select([new ResultColumn(new IntegerLiteral('1'), null, new Layout([new Spelled('', '2')]))]));
174    }
175
176    public function testRenderKeepsDigitSeparatorsThatNameAColumn(): void
177    {
178        $operation = (new Semantics())->analyze('SELECT * FROM (SELECT 1_000)');
179
180        self::assertSame('1_000', $operation->fields()?->at(0)->name?->value);
181        self::assertSame('SELECT * FROM (SELECT 1_000)', $operation->toString());
182    }
183}
184