packages/ztd-query-pdo-adapter/tests/Integration/Sqlite/NativeUpsertExpressionTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Integration\Sqlite;
6
7use PDO;
8use PHPUnit\Framework\Attributes\CoversNothing;
9use PHPUnit\Framework\Attributes\Large;
10use PHPUnit\Framework\TestCase;
11use ZtdQuery\Adapter\Pdo\ZtdPdo;
12
13/**
14 * @requires extension pdo_sqlite
15 */
16#[CoversNothing]
17#[Large]
18final class NativeUpsertExpressionTest extends TestCase
19{
20    public function testDatabaseEvaluatesJsonUpsertExpression(): void
21    {
22        $options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC];
23        $native = new PDO('sqlite::memory:', null, null, $options);
24        $underlying = new PDO('sqlite::memory:', null, null, $options);
25        $native->exec('CREATE TABLE items (id INTEGER PRIMARY KEY, meta TEXT)');
26        $underlying->exec('CREATE TABLE items (id INTEGER PRIMARY KEY, meta TEXT)');
27        $ztdPdo = ZtdPdo::fromPdo($underlying);
28        $seed = "INSERT INTO items VALUES (1, '{\"color\":\"red\"}')";
29        $native->exec($seed);
30        $ztdPdo->exec($seed);
31
32        $sql = "INSERT INTO items VALUES (1, '{\"color\":\"purple\"}') ON CONFLICT(id) DO UPDATE SET meta = json_set(items.meta, '$.color', 'purple')";
33        $native->exec($sql);
34        $ztdPdo->exec($sql);
35
36        $nativeStatement = $native->query('SELECT * FROM items');
37        $ztdStatement = $ztdPdo->query('SELECT * FROM items');
38        self::assertNotFalse($nativeStatement);
39        self::assertNotFalse($ztdStatement);
40        self::assertSame($nativeStatement->fetchAll(), $ztdStatement->fetchAll());
41    }
42}
43