packages/ztd-query-pdo-adapter/tests/Integration/PostgreSql/SelectRecursiveCteTest.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 * @phpstan-type Row array<string, mixed>
21 */
22#[CoversNothing]
23#[Large]
24final class SelectRecursiveCteTest extends TestCase
25{
26 public function testRecursiveCte(): void
27 {
28 $endpoint = \Testcontainers\Testcontainers::run(PostgreSqlRelease::fromEnvironment())->getData(Endpoint::class);
29 /** @var PDO $rawPdo */
30 $rawPdo = new PDO(
31 $endpoint->dsn(),
32 $endpoint->username,
33 $endpoint->password,
34 [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC],
35 );
36
37 $schemaName = 'ztd_' . bin2hex(random_bytes(8));
38 $rawPdo->exec(sprintf('CREATE SCHEMA "%s"', $schemaName));
39 $rawPdo->exec(sprintf('SET search_path TO "%s"', $schemaName));
40
41 $table = 'prefix_' . bin2hex(random_bytes(8));
42
43 try {
44 $rawPdo->exec("CREATE TABLE {$table} (id INTEGER PRIMARY KEY, parent_id INTEGER, name TEXT NOT NULL)");
45 $rawPdo->exec("INSERT INTO {$table} (id, parent_id, name) VALUES (1, NULL, 'Root'), (2, 1, 'Child1'), (3, 1, 'Child2'), (4, 2, 'Grandchild1')");
46
47 $ztdPdo = ZtdPdo::fromPdo($rawPdo);
48
49 $ztdPdo->exec("INSERT INTO {$table} (id, parent_id, name) VALUES (1, NULL, 'Root'), (2, 1, 'Child1'), (3, 1, 'Child2'), (4, 2, 'Grandchild1')");
50
51 $sql = 'WITH RECURSIVE tree AS ('
52 . "SELECT id, parent_id, name, 0 AS depth FROM {$table} WHERE parent_id IS NULL "
53 . 'UNION ALL '
54 . "SELECT c.id, c.parent_id, c.name, t.depth + 1 FROM {$table} c INNER JOIN tree t ON c.parent_id = t.id"
55 . ') SELECT * FROM tree ORDER BY id';
56
57 $stmt = $rawPdo->query($sql);
58 self::assertNotFalse($stmt);
59 /** @var list<Row> */
60 $rawRows = $stmt->fetchAll();
61
62 $stmt = $ztdPdo->query($sql);
63 self::assertNotFalse($stmt);
64 /** @var list<Row> */
65 $ztdRows = $stmt->fetchAll();
66
67 self::assertSame($rawRows, $ztdRows);
68 } finally {
69 $rawPdo->exec(sprintf('DROP SCHEMA IF EXISTS "%s" CASCADE', $schemaName));
70 }
71 }
72}
73