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\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 ReturningTest extends TestCase
22{
23 public function testReturningAndLastInsertIdMatchPostgresDml(): 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 $table = 'prefix_' . bin2hex(random_bytes(8));
39
40 try {
41 $rawPdo->exec("CREATE TABLE {$table} (id SERIAL PRIMARY KEY, name TEXT, score INTEGER)");
42 $ztdPdo = ZtdPdo::fromPdo($rawPdo);
43
44 $insert = "INSERT INTO {$table} (name, score) VALUES ('Alice', 90) RETURNING id, name";
45 $rawInsert = $rawPdo->query($insert);
46 $ztdInsert = $ztdPdo->query($insert);
47 self::assertNotFalse($rawInsert);
48 self::assertNotFalse($ztdInsert);
49 self::assertSame($rawInsert->fetchAll(), $ztdInsert->fetchAll());
50 self::assertSame('1', $ztdPdo->lastInsertId());
51
52 $update = "UPDATE {$table} SET score = 95 WHERE id = 1 RETURNING id, name, score";
53 $rawUpdate = $rawPdo->query($update);
54 $ztdUpdate = $ztdPdo->query($update);
55 self::assertNotFalse($rawUpdate);
56 self::assertNotFalse($ztdUpdate);
57 self::assertSame($rawUpdate->fetchAll(), $ztdUpdate->fetchAll());
58
59 $delete = "DELETE FROM {$table} WHERE id = 1 RETURNING *";
60 $rawDelete = $rawPdo->query($delete);
61 $ztdDelete = $ztdPdo->query($delete);
62 self::assertNotFalse($rawDelete);
63 self::assertNotFalse($ztdDelete);
64 self::assertSame($rawDelete->fetchAll(), $ztdDelete->fetchAll());
65 } finally {
66 $rawPdo->exec(sprintf('DROP SCHEMA IF EXISTS "%s" CASCADE', $schemaName));
67 }
68 }
69}
70