packages/sql-fixture/tests/Unit/Platform/Sqlite/Schema/PragmaSchemaTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Platform\Sqlite\Schema;
6
7use PDO;
8use PHPUnit\Framework\Attributes\CoversClass;
9use PHPUnit\Framework\TestCase;
10use SqlFixture\Platform\Sqlite\Schema\PragmaSchema as Subject;
11
12#[CoversClass(Subject::class)]
13#[\PHPUnit\Framework\Attributes\UsesClass(\SqlFixture\Platform\Sqlite\Schema\PragmaColumn::class)]
14#[\PHPUnit\Framework\Attributes\UsesClass(\SqlFixture\Schema\ColumnDefinition::class)]
15#[\PHPUnit\Framework\Attributes\UsesClass(\SqlFixture\Schema\TableSchema::class)]
16final class PragmaSchemaTest extends TestCase
17{
18    public function testFetchSchemaViaPragmaReadsLiveTable(): void
19    {
20        $pdo = new PDO('sqlite::memory:');
21        $pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(30) NOT NULL DEFAULT \'ready\')');
22        $schema = (new Subject())->fetchSchemaViaPragma($pdo, 'users');
23        self::assertSame(['id'], $schema->primaryKeys);
24        self::assertSame(30, $schema->columns['name']->length);
25        self::assertSame('ready', $schema->columns['name']->default);
26    }
27
28    public function testParseDefaultValueDecodesQuotedAndNumericLiterals(): void
29    {
30        $parser = new Subject();
31        self::assertSame('ready', $parser->parseDefaultValue("'ready'"));
32        self::assertSame(12.5, $parser->parseDefaultValue('12.5'));
33        self::assertNull($parser->parseDefaultValue('NULL'));
34        self::assertSame('CURRENT_DATE', $parser->parseDefaultValue('CURRENT_DATE'));
35    }
36
37    #[\PHPUnit\Framework\Attributes\DataProvider('providerDefaultValues')]
38    public function testParseDefaultValuePreservesExpressionsAndDecodesLiterals(?string $input, int|float|string|null $expected): void
39    {
40        self::assertSame($expected, (new Subject())->parseDefaultValue($input));
41    }
42
43    /**
44     * @return list<array{?string, int|float|string|null}>
45     */
46    public static function providerDefaultValues(): array
47    {
48        return [
49            [null, null],
50            ['null', null],
51            ["'line\nbreak'", "line\nbreak"],
52            ["('part')", "('part')"],
53            ["CURRENT_DATE || 'tail'", "CURRENT_DATE || 'tail'"],
54            ["'head' || CURRENT_DATE", "'head' || CURRENT_DATE"],
55            ["strftime('%Y', 'now')", "strftime('%Y', 'now')"],
56            ['-3', -3],
57        ];
58    }
59}
60