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