packages/ztd-query-pdo-adapter/tests/Integration/PostgreSql/DoBlockTest.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 DoBlockTest extends TestCase
22{
23 public function testDoBlockPassesThroughAndLaterShadowDmlStillWorks(): void
24 {
25 $containerInstance = \Testcontainers\Testcontainers::run(PostgreSql16Container::class);
26 /** @var PDO $pdo */
27 $pdo = 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 $pdo->exec(sprintf('CREATE SCHEMA "%s"', $schemaName));
36 $pdo->exec(sprintf('SET search_path TO "%s"', $schemaName));
37
38
39 try {
40 $pdo->exec('CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)');
41 $ztdPdo = ZtdPdo::fromPdo($pdo);
42
43 self::assertSame(0, $ztdPdo->exec(
44 "DO \$block\$ BEGIN INSERT INTO items VALUES (1, 'physical'); END \$block\$",
45 ));
46 self::assertSame(1, $ztdPdo->exec("INSERT INTO items VALUES (2, 'shadow')"));
47
48 $shadow = $ztdPdo->query('SELECT id, name FROM items ORDER BY id');
49 self::assertNotFalse($shadow);
50 self::assertSame([['id' => 2, 'name' => 'shadow']], $shadow->fetchAll());
51
52 $physical = $pdo->query('SELECT id, name FROM items ORDER BY id');
53 self::assertNotFalse($physical);
54 self::assertSame([['id' => 1, 'name' => 'physical']], $physical->fetchAll());
55 } finally {
56 $pdo->exec(sprintf('DROP SCHEMA IF EXISTS "%s" CASCADE', $schemaName));
57 }
58 }
59}
60