packages/ztd-query-pdo-adapter/tests/Integration/PostgreSql/SelectBitTypeTest.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#[CoversNothing]
21#[Large]
22final class SelectBitTypeTest extends TestCase
23{
24    public function testBitStringsPreserveWidthAndOperators(): void
25    {
26        $endpoint = \Testcontainers\Testcontainers::run(PostgreSqlRelease::fromEnvironment())->getData(Endpoint::class);
27        /** @var PDO $rawPdo */
28        $rawPdo = new PDO(
29            $endpoint->dsn(),
30            $endpoint->username,
31            $endpoint->password,
32            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC],
33        );
34
35        $schemaName = 'ztd_' . bin2hex(random_bytes(8));
36        $rawPdo->exec(sprintf('CREATE SCHEMA "%s"', $schemaName));
37        $rawPdo->exec(sprintf('SET search_path TO "%s"', $schemaName));
38
39        $table = 'prefix_' . bin2hex(random_bytes(8));
40
41        try {
42            $rawPdo->exec("CREATE TABLE {$table} (id INTEGER PRIMARY KEY, perms BIT(8) NOT NULL)");
43            $ztdPdo = ZtdPdo::fromPdo($rawPdo);
44            $ztdPdo->exec("INSERT INTO {$table} (id, perms) VALUES (1, B'11111111'), (2, B'00001111'), (3, B'00000001')");
45
46            $statement = $ztdPdo->query("SELECT perms::TEXT AS perms FROM {$table} WHERE (perms & B'11110000') <> B'00000000' ORDER BY id");
47
48            self::assertNotFalse($statement);
49            self::assertSame([['perms' => '11111111']], $statement->fetchAll());
50        } finally {
51            $rawPdo->exec(sprintf('DROP SCHEMA IF EXISTS "%s" CASCADE', $schemaName));
52        }
53    }
54}
55