packages/sql-semantics-sqlite/tests/Unit/Statement/Schema/CreateTableTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Schema;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\Sqlite\Model\Construction\Derivation;
11use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\Name;
12use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\QualifiedName;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Operation;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Column\ResolvedColumn;
15use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Table\DeclaredTable;
16use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Nullability;
17use SqlSemantics\Platform\Sqlite\Semantics;
18use SqlSemantics\Platform\Sqlite\Statement\Expression\Operator\Binary;
19use SqlSemantics\Platform\Sqlite\Statement\Lexical\Word;
20use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
21use SqlSemantics\Platform\Sqlite\Statement\Schema\Column\ColumnDefinition;
22use SqlSemantics\Platform\Sqlite\Statement\Schema\CreateTable;
23use SqlSemantics\Platform\Sqlite\Statement\Schema\Problem\PrimaryKeyProblem;
24use SqlSemantics\Platform\Sqlite\Statement\Schema\Table\TableOption;
25use SqlSemantics\Platform\Sqlite\Statement\Type\Affinity;
26use SqlSemantics\Platform\Sqlite\Statement\Type\ColumnDomain;
27
28#[CoversClass(CreateTable::class)]
29#[Medium]
30final class CreateTableTest extends TestCase
31{
32    public function testWithoutRowidAndStrictReadTheKnownOptions(): void
33    {
34        $plain = new CreateTable(new QualifiedName(new Name('t')), [new ColumnDefinition(new Name('a'))]);
35        $both = new CreateTable(new QualifiedName(new Name('t')), [new ColumnDefinition(new Name('a'))], [], [new TableOption(new Word(new Name('rowid')), true), new TableOption(new Word(new Name('STRICT')))]);
36
37        self::assertFalse($plain->withoutRowid());
38        self::assertFalse($plain->strict());
39        self::assertTrue($both->withoutRowid());
40        self::assertTrue($both->strict());
41    }
42
43    public function testStrictIgnoresAnOptionSqliteRejects(): void
44    {
45        $statement = (new Semantics())->inspect('CREATE TABLE t (a) "strict"')->statement;
46
47        self::assertInstanceOf(CreateTable::class, $statement);
48        self::assertFalse($statement->strict());
49    }
50
51    public function testDeriveStatementDeclaresTheColumnsInOrderWithTheirDeclaredTypes(): void
52    {
53        $table = (new Semantics())->inspect('CREATE TABLE t (id INTEGER, name VARCHAR(10), raw)')->declarations()[0];
54
55        self::assertSame(['id', 'name', 'raw'], array_map(static fn (object $column): string => $column->name->value, $table->columns));
56        self::assertSame(['INTEGER', 'VARCHAR(10)', ''], array_map(static fn (object $column): string => $column->type->name(), $table->columns));
57    }
58
59    public function testDeriveStatementBindsAQueryToTheVeryObjectsItDeclares(): void
60    {
61        $semantics = new Semantics();
62        $create = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)');
63        $table = $create->declarations()[0];
64        $query = $semantics->inspect('SELECT name, rowid FROM t WHERE t.id > 1', [$create]);
65        $input = $query->facts->relation($query->singleNamedInput())->table;
66
67        self::assertInstanceOf(DeclaredTable::class, $input);
68        self::assertSame($table, $input->table);
69        self::assertSame($table->columns[1], $query->field('name')->column());
70        self::assertSame($table->columns[0], $query->field(1)->column());
71        $select = $query->statement;
72        self::assertInstanceOf(Select::class, $select);
73        $where = $select->where;
74        self::assertInstanceOf(Binary::class, $where);
75        $resolution = $query->facts->scalar($where->left)->resolution;
76        self::assertInstanceOf(ResolvedColumn::class, $resolution);
77        self::assertSame($table->columns[0], $resolution->slot->column);
78    }
79
80    public function testDeriveStatementProvidesExactlyOneDeclaration(): void
81    {
82        $operation = (new Semantics())->inspect('CREATE TABLE IF NOT EXISTS t (a TEXT NOT NULL, b)', []);
83        $table = $operation->declarations()[0];
84
85        self::assertCount(1, $operation->declarations());
86        self::assertSame('t', $table->name->name->value);
87        self::assertNull($table->name->schema);
88        self::assertTrue($table->complete);
89        self::assertSame(Nullability::NotNull, $table->columns[0]->nullability);
90        self::assertSame(Nullability::Nullable, $table->columns[1]->nullability);
91        self::assertNull($operation->shape());
92        self::assertSame([], $operation->facts->diagnostics);
93    }
94
95    public function testDeriveStatementDeclaresATemporaryTableInTheTempSchema(): void
96    {
97        $operation = (new Semantics())->inspect('CREATE TEMP TABLE t (a)');
98
99        self::assertSame('temp', $operation->declarations()[0]->name->schema?->value);
100    }
101
102    public function testDeriveStatementDeclaresAnImplicitRowIdentifier(): void
103    {
104        $table = (new Semantics())->inspect('CREATE TABLE t (a TEXT)')->declarations()[0];
105
106        self::assertCount(1, $table->implicit);
107        self::assertSame(['rowid', 'oid', '_rowid_'], array_map(static fn (object $name): string => $name->value, $table->implicit[0]->names));
108        self::assertNotContains($table->implicit[0]->column, $table->columns);
109        self::assertSame(Nullability::NotNull, $table->implicit[0]->column->nullability);
110        self::assertInstanceOf(ColumnDomain::class, $table->implicit[0]->column->type);
111        self::assertSame(Affinity::Integer, $table->implicit[0]->column->type->affinity);
112    }
113
114    public function testDeriveStatementMakesAnIntegerPrimaryKeyTheRowIdentifier(): void
115    {
116        $table = (new Semantics())->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a)')->declarations()[0];
117
118        self::assertSame($table->columns[0], $table->implicit[0]->column);
119        self::assertSame(Nullability::NotNull, $table->columns[0]->nullability);
120    }
121
122    public function testDeriveStatementDeclaresNoRowIdentifierWithoutRowid(): void
123    {
124        $table = (new Semantics())->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a) WITHOUT ROWID')->declarations()[0];
125
126        self::assertSame([], $table->implicit);
127        self::assertSame(Nullability::NotNull, $table->columns[0]->nullability);
128    }
129
130    public function testDeriveStatementRecordsTheShapeOfTheNewTableForTheStatementNode(): void
131    {
132        $operation = (new Semantics())->inspect('CREATE TABLE t (a, b)');
133        $fact = $operation->facts->relation($operation->statement);
134
135        self::assertCount(2, $fact->shape->slots);
136        self::assertSame($operation->declarations()[0]->columns[1], $fact->shape->slots[1]->column);
137        self::assertInstanceOf(DeclaredTable::class, $fact->table);
138        self::assertSame($operation->declarations()[0], $fact->table->table);
139    }
140
141    public function testDeriveRelationDeclaresTheTableAndAnswersItsShape(): void
142    {
143        $semantics = new Semantics();
144        $statement = $semantics->inspect('CREATE TABLE t (a, b PRIMARY KEY, c PRIMARY KEY)')->statement;
145        $derivation = new Derivation($semantics->context());
146
147        self::assertInstanceOf(CreateTable::class, $statement);
148        $fact = $statement->deriveRelation($derivation, $derivation->environment());
149        self::assertSame(['a', 'b', 'c'], array_map(static fn (object $slot): ?string => $slot->name?->value, $fact->shape->slots));
150        self::assertTrue($fact->shape->complete());
151        self::assertInstanceOf(DeclaredTable::class, $fact->table);
152        self::assertSame([$fact->table->table], $derivation->facts()->declarations);
153        self::assertSame($fact->table->table->columns[0], $fact->shape->slots[0]->column);
154        self::assertInstanceOf(PrimaryKeyProblem::class, $derivation->facts()->diagnostics[0]);
155    }
156
157    public function testRenderKeepsACommaWrittenBeforeTheFirstOption(): void
158    {
159        $operation = (new Semantics())->inspect('CREATE TABLE t (a PRIMARY KEY) , WITHOUT ROWID , WITHOUT ROWID');
160
161        self::assertInstanceOf(CreateTable::class, $operation->statement);
162        self::assertTrue($operation->statement->optionsComma);
163        self::assertSame('CREATE TABLE t (a PRIMARY KEY), WITHOUT ROWID, WITHOUT ROWID', $operation->toString());
164    }
165
166    public function testRefusesACommaWithoutAnOptionAfterIt(): void
167    {
168        $this->expectExceptionMessage('A comma before the table options needs a table option after it.');
169
170        new CreateTable(new QualifiedName(new Name('t')), [new ColumnDefinition(new Name('a'))], [], [], false, false, true);
171    }
172
173    public function testRenderWritesEveryPartInGrammarOrder(): void
174    {
175        $operation = (new Semantics())->inspect('create temp table if not exists temp.t (id integer primary key, a text, unique (a)) strict, without rowid');
176
177        self::assertSame('CREATE TEMP TABLE IF NOT EXISTS `temp`.t (id integer PRIMARY KEY, a text, UNIQUE (a)) strict, WITHOUT rowid', $operation->toString());
178    }
179
180    public function testRenderWritesANewlyBuiltDefinition(): void
181    {
182        $semantics = new Semantics();
183        $operation = new Operation($semantics->context(), new CreateTable(new QualifiedName(new Name('t'), new Name('main')), [new ColumnDefinition(new Name('a')), new ColumnDefinition(new Name('b'))]));
184
185        self::assertSame('CREATE TABLE main.t (a, b)', $operation->toString());
186        self::assertCount(2, $operation->declarations()[0]->columns);
187    }
188}
189