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

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Integration\PostgreSql;
6
7use Container\PostgreSql16Container;
8use PDO;
9use PHPUnit\Framework\Attributes\CoversNothing;
10use PHPUnit\Framework\Attributes\Large;
11use PHPUnit\Framework\TestCase;
12use ZtdQuery\Adapter\Pdo\ZtdPdo;
13
14/**
15 * @requires extension pdo_pgsql
16 * @group integration
17 * @group postgres
18 */
19#[CoversNothing]
20#[Large]
21final class NativeUpsertExpressionTest extends TestCase
22{
23    public function testDatabaseEvaluatesJsonUpsertExpression(): void
24    {
25        $containerInstance = \Testcontainers\Testcontainers::run(PostgreSql16Container::class);
26        /** @var PDO $rawPdo */
27        $rawPdo = new PDO(
28            sprintf('pgsql:host=%s;port=%d;dbname=test', str_replace('localhost', '127.0.0.1', $containerInstance->getHost()), $containerInstance->getMappedPort(5432)),
29            'test',
30            'test',
31            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC],
32        );
33
34        $schemaName = 'ztd_' . bin2hex(random_bytes(8));
35        $rawPdo->exec(sprintf('CREATE SCHEMA "%s"', $schemaName));
36        $rawPdo->exec(sprintf('SET search_path TO "%s"', $schemaName));
37
38
39        try {
40            $rawPdo->exec('CREATE TABLE items (id INT PRIMARY KEY, meta JSONB)');
41            $ztdPdo = ZtdPdo::fromPdo($rawPdo);
42            $seed = "INSERT INTO items VALUES (1, '{\"color\":\"red\"}')";
43            $rawPdo->exec($seed);
44            $ztdPdo->exec($seed);
45
46            $sql = "INSERT INTO items VALUES (1, '{\"color\":\"purple\"}') ON CONFLICT(id) DO UPDATE SET meta = jsonb_set(items.meta, '{color}', '\"purple\"')";
47            $rawPdo->exec($sql);
48            $ztdPdo->exec($sql);
49
50            $rawStatement = $rawPdo->query('SELECT id, meta::text FROM items');
51            $ztdStatement = $ztdPdo->query('SELECT id, meta::text FROM items');
52            self::assertNotFalse($rawStatement);
53            self::assertNotFalse($ztdStatement);
54            self::assertSame($rawStatement->fetchAll(), $ztdStatement->fetchAll());
55        } finally {
56            $rawPdo->exec(sprintf('DROP SCHEMA IF EXISTS "%s" CASCADE', $schemaName));
57        }
58    }
59}
60