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\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 SelectBitTypeTest extends TestCase
22{
23    public function testBitStringsPreserveWidthAndOperators(): void
24    {
25        $containerInstance = \Testcontainers\Testcontainers::run(PostgreSql16Container::class);
26        /** @var PDO $rawPdo */
27        $rawPdo = 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        $rawPdo->exec(sprintf('CREATE SCHEMA "%s"', $schemaName));
36        $rawPdo->exec(sprintf('SET search_path TO "%s"', $schemaName));
37
38        $table = 'prefix_' . bin2hex(random_bytes(8));
39
40        try {
41            $rawPdo->exec("CREATE TABLE {$table} (id INTEGER PRIMARY KEY, perms BIT(8) NOT NULL)");
42            $ztdPdo = ZtdPdo::fromPdo($rawPdo);
43            $ztdPdo->exec("INSERT INTO {$table} (id, perms) VALUES (1, B'11111111'), (2, B'00001111'), (3, B'00000001')");
44
45            $statement = $ztdPdo->query("SELECT perms::TEXT AS perms FROM {$table} WHERE (perms & B'11110000') <> B'00000000' ORDER BY id");
46
47            self::assertNotFalse($statement);
48            self::assertSame([['perms' => '11111111']], $statement->fetchAll());
49        } finally {
50            $rawPdo->exec(sprintf('DROP SCHEMA IF EXISTS "%s" CASCADE', $schemaName));
51        }
52    }
53}
54