packages/ztd-query-pdo-adapter/tests/Integration/PostgreSql/SelectDistinctTest.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 SelectDistinctTest extends TestCase
25{
26 public function testSelectDistinct(): 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, category TEXT NOT NULL, name TEXT NOT NULL)");
45 $rawPdo->exec("INSERT INTO {$table} (id, category, name) VALUES (1, 'A', 'x'), (2, 'B', 'y'), (3, 'A', 'z'), (4, 'B', 'w')");
46
47 $ztdPdo = ZtdPdo::fromPdo($rawPdo);
48
49 $ztdPdo->exec("INSERT INTO {$table} (id, category, name) VALUES (1, 'A', 'x'), (2, 'B', 'y'), (3, 'A', 'z'), (4, 'B', 'w')");
50
51 $stmt = $rawPdo->query("SELECT DISTINCT category FROM {$table} ORDER BY category");
52 self::assertNotFalse($stmt);
53 /** @var list<Row> */
54 $rawRows = $stmt->fetchAll();
55
56 $stmt = $ztdPdo->query("SELECT DISTINCT category FROM {$table} ORDER BY category");
57 self::assertNotFalse($stmt);
58 /** @var list<Row> */
59 $ztdRows = $stmt->fetchAll();
60
61 self::assertSame($rawRows, $ztdRows);
62 } finally {
63 $rawPdo->exec(sprintf('DROP SCHEMA IF EXISTS "%s" CASCADE', $schemaName));
64 }
65 }
66}
67