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

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Integration\PostgreSql;
6
7use Container\Endpoint;
8use Container\PostgreSqlRelease;
9use PDO;
10use PHPUnit\Framework\Attributes\CoversNothing;
11use PHPUnit\Framework\Attributes\Large;
12use PHPUnit\Framework\TestCase;
13use ZtdQuery\Adapter\Pdo\ZtdPdo;
14
15/**
16 * @requires extension pdo_pgsql
17 * @group integration
18 * @group postgres
19 */
20#[CoversNothing]
21#[Large]
22final class ReturningTest extends TestCase
23{
24    public function testReturningAndLastInsertIdMatchPostgresDml(): void
25    {
26        $endpoint = \Testcontainers\Testcontainers::run(PostgreSqlRelease::fromEnvironment())->getData(Endpoint::class);
27        /** @var PDO $rawPdo */
28        $rawPdo = new PDO(
29            $endpoint->dsn(),
30            $endpoint->username,
31            $endpoint->password,
32            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC],
33        );
34
35        $schemaName = 'ztd_' . bin2hex(random_bytes(8));
36        $rawPdo->exec(sprintf('CREATE SCHEMA "%s"', $schemaName));
37        $rawPdo->exec(sprintf('SET search_path TO "%s"', $schemaName));
38
39        $table = 'prefix_' . bin2hex(random_bytes(8));
40
41        try {
42            $rawPdo->exec("CREATE TABLE {$table} (id SERIAL PRIMARY KEY, name TEXT, score INTEGER)");
43            $ztdPdo = ZtdPdo::fromPdo($rawPdo);
44
45            $insert = "INSERT INTO {$table} (name, score) VALUES ('Alice', 90) RETURNING id, name";
46            $rawInsert = $rawPdo->query($insert);
47            $ztdInsert = $ztdPdo->query($insert);
48            self::assertNotFalse($rawInsert);
49            self::assertNotFalse($ztdInsert);
50            self::assertSame($rawInsert->fetchAll(), $ztdInsert->fetchAll());
51            self::assertSame('1', $ztdPdo->lastInsertId());
52
53            $update = "UPDATE {$table} SET score = 95 WHERE id = 1 RETURNING id, name, score";
54            $rawUpdate = $rawPdo->query($update);
55            $ztdUpdate = $ztdPdo->query($update);
56            self::assertNotFalse($rawUpdate);
57            self::assertNotFalse($ztdUpdate);
58            self::assertSame($rawUpdate->fetchAll(), $ztdUpdate->fetchAll());
59
60            $delete = "DELETE FROM {$table} WHERE id = 1 RETURNING *";
61            $rawDelete = $rawPdo->query($delete);
62            $ztdDelete = $ztdPdo->query($delete);
63            self::assertNotFalse($rawDelete);
64            self::assertNotFalse($ztdDelete);
65            self::assertSame($rawDelete->fetchAll(), $ztdDelete->fetchAll());
66        } finally {
67            $rawPdo->exec(sprintf('DROP SCHEMA IF EXISTS "%s" CASCADE', $schemaName));
68        }
69    }
70}
71