Lines 96.15% 100 / 104
Functions and Methods 69.23% 9 / 13
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
SqliteSchemaGrammar 96.15% 100 / 104 69.23% 9 / 13 44 0.00% 0 / 1
 wrap 100.00% 1 / 1 100.00% 1 / 1 1
 type 100.00% 15 / 15 100.00% 1 / 1 16
 autoIncrement 100.00% 1 / 1 100.00% 1 / 1 1
 autoIncrementBeforePrimaryKey 100.00% 1 / 1 100.00% 1 / 1 1
 compilePartialIndexClause 100.00% 1 / 1 100.00% 1 / 1 1
 assertValidIdentifier 100.00% 1 / 1 100.00% 1 / 1 1
 compileDropIndex 100.00% 2 / 2 100.00% 1 / 1 1
 compileAddColumns 93.75% 15 / 16 0.00% 0 / 1 4.00
 addedNotNullWithoutDefault 75.00% 3 / 4 0.00% 0 / 1 4.25
 compileDropColumns 88.88% 8 / 9 0.00% 0 / 1 2.01
 compileDropColumn 100.00% 1 / 1 100.00% 1 / 1 1
 compileRebuildTable 97.43% 38 / 39 0.00% 0 / 1 8
 compileCopyTableWithBackfill 100.00% 13 / 13 100.00% 1 / 1 3
1<?php
2
3declare(strict_types=1);
4
5namespace BlueprintAU\Radiant\Database\Schema\Grammars;
6
7use BlueprintAU\Radiant\Database\Schema\Blueprint;
8use BlueprintAU\Radiant\Database\Schema\Enums\ColumnType;
9
10/**
11 * The SQLite dialect of the schema grammar.
12 *
13 * Identifiers are quoted with double quotes (embedded quotes doubled).
14 * Auto-increment renders as `AUTOINCREMENT` (only valid on an `INTEGER
15 * PRIMARY KEY` column). SQLite 3.35+ drops columns natively, and `ALTER
16 * TABLE` accepts a single `ADD COLUMN` clause per statement — a
17 * multi-column add compiles one statement per column.
18 */
19final class SqliteSchemaGrammar extends SchemaGrammar
20{
21    /**
22     * Wrap an identifier in SQLite double quotes.
23     *
24     * @param  string  $value
25     * @return string
26     */
27    protected function wrap(string $value): string
28    {
29        return '"' . str_replace('"', '""', $value) . '"';
30    }
31
32    /**
33     * Map a logical column type to SQLite's native type.
34     *
35     * Datetime types render declared precision (`datetime(3)`) for
36     * cross-dialect DDL parity; SQLite's type affinity ignores it, and the
37     * driver stores whatever textual precision the bound value carries.
38     *
39     * @param  ColumnType  $type
40     * @param  int|null  $length
41     * @param  int|null  $precision
42     * @param  int|null  $scale
43     * @return string
44     */
45    public function type(ColumnType $type, ?int $length = null, ?int $precision = null, ?int $scale = null): string
46    {
47        return match ($type) {
48            ColumnType::String => 'varchar' . $this->suffix($this->requireLength($length)),
49            ColumnType::Char => 'char' . $this->suffix($this->requireLength($length)),
50            ColumnType::Text => 'text',
51            ColumnType::BigInt => 'integer',
52            ColumnType::Int => 'int',
53            ColumnType::Decimal => 'numeric' . $this->suffix($precision, $scale),
54            ColumnType::Float => 'double',
55            ColumnType::Boolean => 'tinyint(1)',
56            ColumnType::Date => 'text',
57            ColumnType::DateTime => 'datetime' . $this->suffix($precision),
58            ColumnType::Timestamp => 'timestamp' . $this->suffix($precision),
59            ColumnType::Json => 'text',
60            ColumnType::Enum => 'varchar' . $this->suffix($this->requireLength($length)),
61            ColumnType::Binary => 'blob',
62            ColumnType::Uuid => 'text',
63        };
64    }
65
66    /**
67     * The SQLite auto-increment clause.
68     *
69     * @return string
70     */
71    protected function autoIncrement(): string
72    {
73        return 'AUTOINCREMENT';
74    }
75
76    /**
77     * Whether the auto-increment clause renders before `PRIMARY KEY`.
78     *
79     * @return bool
80     */
81    protected function autoIncrementBeforePrimaryKey(): bool
82    {
83        return false;
84    }
85
86    /**
87     * SQLite renders partial (filtered) indexes — `CREATE INDEX ... WHERE
88     * predicate`.
89     *
90     * @param  string  $predicate
91     * @return string
92     */
93    protected function compilePartialIndexClause(string $predicate): string
94    {
95        return 'WHERE ' . $predicate;
96    }
97
98    /**
99     * SQLite has no practical identifier length cap.
100     *
101     * @param  string  $name
102     * @return void
103     */
104    public function assertValidIdentifier(string $name): void
105    {
106    }
107
108    /**
109     * SQLite drops an index by name alone: `DROP INDEX name`.
110     *
111     * @param  string  $name
112     * @param  string  $table
113     * @return string
114     */
115    public function compileDropIndex(string $name, string $table): string
116    {
117        unset($table);
118
119        return 'DROP INDEX ' . $this->wrap($name);
120    }
121
122    /**
123     * Compile the `ALTER TABLE ... ADD COLUMN` statements.
124     *
125     * SQLite accepts a single `ADD COLUMN` clause per statement, so a
126     * multi-column add is one statement per column.
127     *
128     * @param  Blueprint  $blueprint
129     * @return list<string>
130     */
131    #[\Override]
132    public function compileAddColumns(Blueprint $blueprint): array
133    {
134        $table = $blueprint->getTable();
135        $columns = $blueprint->getColumns();
136        if ($columns === []) {
137            throw new \InvalidArgumentException('Cannot add columns with no columns defined.');
138        }
139
140        $backfills = $blueprint->getBackfills();
141
142        // A NOT NULL column without a default cannot be added to a
143        // non-empty table — its backfill renders as a temporary inline
144        // DEFAULT so the ADD succeeds and fills the existing rows (the
145        // rebuild, not this path, produces the no-final-default shape).
146        $statements = array_map(
147            fn (array $column): string => 'ALTER TABLE ' . $this->wrap($table)
148                . ' ADD COLUMN ' . $this->compileAddColumn($this->withTemporaryDefault($column, $backfills)),
149            $columns,
150        );
151
152        // SQLite cannot SET/DROP a column default in place, so a backfill
153        // on an in-place (nullable) add is an UPDATE of the existing rows.
154        // A NOT NULL-no-default column already got its backfill from the
155        // inline DEFAULT above — no UPDATE for it.
156        foreach ($backfills as $column => $value) {
157            if ($this->addedNotNullWithoutDefault($blueprint, $column)) {
158                continue;
159            }
160
161            $statements[] = 'UPDATE ' . $this->wrap($table) . ' SET ' . $this->wrap($column)
162                . ' = ' . $this->compileDefault($value) . ' WHERE ' . $this->wrap($column) . ' IS NULL';
163        }
164
165        return $statements;
166    }
167
168    /**
169     * Whether the named column is an added NOT NULL column without a
170     * declared default.
171     *
172     * @param  Blueprint  $blueprint
173     * @param  string  $name
174     * @return bool
175     */
176    private function addedNotNullWithoutDefault(Blueprint $blueprint, string $name): bool
177    {
178        foreach ($blueprint->getColumns() as $column) {
179            if ($column['name'] === $name) {
180                return $column['nullable'] !== true && $column['default'] === null;
181            }
182        }
183
184        return false;
185    }
186
187    /**
188     * Compile the `ALTER TABLE ... DROP COLUMN` statements.
189     *
190     * SQLite 3.35+ drops columns natively, one `DROP COLUMN` clause per
191     * statement.
192     *
193     * @param  Blueprint  $blueprint
194     * @return list<string>
195     */
196    #[\Override]
197    public function compileDropColumns(Blueprint $blueprint): array
198    {
199        $table = $blueprint->getTable();
200        $columns = $blueprint->getDropColumns();
201        if ($columns === []) {
202            throw new \InvalidArgumentException('Cannot drop columns with no columns defined.');
203        }
204
205        return array_map(
206            fn (string $column): string => 'ALTER TABLE ' . $this->wrap($table)
207                . ' DROP COLUMN ' . $this->compileDropColumn($column),
208            $columns,
209        );
210    }
211
212    /**
213     * Compile one column's `DROP COLUMN` clause.
214     *
215     * @param  string  $column
216     * @return string
217     */
218    #[\Override]
219    protected function compileDropColumn(string $column): string
220    {
221        return $this->wrap($column);
222    }
223
224    /**
225     * Compile the full table-rebuild sequence — SQLite's answer to every
226     * change it cannot make in place (content drift, FK/CHECK changes).
227     *
228     * The order is critical: create-new → copy → drop-old → rename. The
229     * copy projects the intersection of the live and desired column names.
230     *
231     * @param  Blueprint  $desired
232     * @param  string  $tempName
233     * @param  list<string>  $liveColumns
234     * @param  bool  $foreignKeyConstraintsEnabled  Whether the connection currently has `PRAGMA foreign_keys` ON.
235     * @return list<string>
236     * @throws \InvalidArgumentException
237     */
238    public function compileRebuildTable(
239        Blueprint $desired,
240        string $tempName,
241        array $liveColumns,
242        bool $foreignKeyConstraintsEnabled,
243    ): array {
244        $table = $desired->getTable();
245
246        // The copy projection: live ∩ desired — the data that survives.
247        $desiredNames = array_map(fn (array $column) => $column['name'], $desired->getColumns());
248        $copyColumns = array_values(array_intersect($liveColumns, $desiredNames));
249
250        if ($copyColumns === []) {
251            throw new \InvalidArgumentException(sprintf(
252                'A table rebuild of [%s] would copy no columns (live [%s] vs desired [%s]); '
253                . 'the rebuild is refused — drop and re-create the table explicitly instead.',
254                $table,
255                implode(', ', $liveColumns),
256                implode(', ', $desiredNames),
257            ));
258        }
259
260        // The temp blueprint: same desired shape, bound to the temp name,
261        // WITHOUT indexes (they are re-created from the original blueprint
262        // after the rename — derived names must carry the final table
263        // name, never the temp name).
264        $tempBlueprint = $desired->forTable($tempName);
265
266        // An added NOT NULL column has no source in the copy projection —
267        // the copy supplies its value for every surviving row: the
268        // blueprint's explicit backfill(), else the column's declared
269        // default — never a guessed zero value. A NOT NULL added column
270        // with neither fails fast at compile time. A column WITH a value
271        // keeps its NOT NULL in the temp definition (its copy projection
272        // can never produce NULL), so the rebuild lands the final shape in
273        // one apply; only a nullable added column copies as its natural
274        // NULL and needs no relaxation at all.
275        $declaredBackfills = $desired->getBackfills();
276        $backfills = [];
277
278        foreach ($desired->getColumns() as $column) {
279            if (in_array($column['name'], $liveColumns, true)) {
280                continue; // Not an added column — it has a copy source.
281            }
282
283            if ($column['nullable'] === true) {
284                continue; // Nullable added columns copy as their natural NULL.
285            }
286
287            $value = $declaredBackfills[$column['name']] ?? $column['default'] ?? null;
288
289            if ($value === null) {
290                throw new \InvalidArgumentException(sprintf(
291                    'A table rebuild of [%s] cannot add the NOT NULL column [%s]: it declares no '
292                    . 'default and no backfill() value to fill the existing rows with. Declare a '
293                    . 'default on the column, provide one with Blueprint::backfill(), or make the '
294                    . 'column nullable.',
295                    $table,
296                    $column['name'],
297                ));
298            }
299
300            $backfills[$column['name']] = $value;
301        }
302
303        $statements = array_values(array_filter([
304            $foreignKeyConstraintsEnabled ? 'PRAGMA foreign_keys = OFF' : null,
305            'CREATE TABLE ' . $this->wrap($tempName) . ' (' . $this->compileTableBody($tempBlueprint) . ')',
306            $this->compileCopyTableWithBackfill($table, $tempName, $copyColumns, $backfills),
307            $this->compileDrop($table),
308            $this->compileRenameTable($tempName, $table),
309            $foreignKeyConstraintsEnabled ? 'PRAGMA foreign_keys = ON' : null,
310        ]));
311
312        return $statements;
313    }
314
315    /**
316     * Compile the data-copy statement, backfilling the added NOT NULL
317     * columns with their values.
318     *
319     * @param  string  $from
320     * @param  string  $to
321     * @param  list<string>  $columns  The live ∩ desired projection.
322     * @param  array<string, mixed>  $backfills  Added column => backfill value.
323     * @return string
324     */
325    private function compileCopyTableWithBackfill(string $from, string $to, array $columns, array $backfills): string
326    {
327        if ($backfills === []) {
328            return $this->compileCopyTable($from, $to, $columns);
329        }
330
331        $targetColumns = [...$columns, ...array_keys($backfills)];
332
333        $selectExpressions = array_map(
334            fn (string $column): string => $this->wrap($column),
335            $columns,
336        );
337
338        foreach ($backfills as $default) {
339            $selectExpressions[] = $this->compileDefault($default);
340        }
341
342        return 'INSERT INTO ' . $this->wrap($to)
343            . ' (' . implode(', ', array_map(fn (string $column) => $this->wrap($column), $targetColumns)) . ')'
344            . ' SELECT ' . implode(', ', $selectExpressions)
345            . ' FROM ' . $this->wrap($from);
346    }
347}