|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace Cspray\DatabaseTestCase; |
| 4 | + |
| 5 | +use Amp\Postgres\PostgresConfig; |
| 6 | +use Amp\Postgres\PostgresLink; |
| 7 | +use Cspray\DatabaseTestCase\Exception\MissingRequiredComposerPackage; |
| 8 | +use function Amp\Postgres\connect; |
| 9 | + |
| 10 | +if (! interface_exists(PostgresLink::class)) { |
| 11 | + throw new MissingRequiredComposerPackage('You must install amphp/postgres to use ' . AmpPostgresConnectionAdapter::class); |
| 12 | +} |
| 13 | + |
| 14 | +class AmpPostgresConnectionAdapter extends AbstractConnectionAdapter { |
| 15 | + |
| 16 | + private ?PostgresLink $connection = null; |
| 17 | + |
| 18 | + public function __construct( |
| 19 | + private readonly ConnectionAdapterConfig $adapterConfig |
| 20 | + ) {} |
| 21 | + |
| 22 | + public function establishConnection() : void { |
| 23 | + $this->connection = connect( |
| 24 | + PostgresConfig::fromString(sprintf( |
| 25 | + 'db=%s host=%s port=%d user=%s pass=%s', |
| 26 | + $this->adapterConfig->database, |
| 27 | + $this->adapterConfig->host, |
| 28 | + $this->adapterConfig->port, |
| 29 | + $this->adapterConfig->user, |
| 30 | + $this->adapterConfig->password |
| 31 | + )) |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + public function onTestStart() : void { |
| 36 | + $this->connection->query('START TRANSACTION'); |
| 37 | + } |
| 38 | + |
| 39 | + public function onTestStop() : void { |
| 40 | + $this->connection->query('ROLLBACK'); |
| 41 | + } |
| 42 | + |
| 43 | + public function closeConnection() : void { |
| 44 | + $this->connection->close(); |
| 45 | + $this->connection = null; |
| 46 | + } |
| 47 | + |
| 48 | + public function getUnderlyingConnection() : PostgresLink { |
| 49 | + return $this->connection; |
| 50 | + } |
| 51 | + |
| 52 | + protected function executeInsertSql(string $sql, array $parameters) : void { |
| 53 | + $statement = $this->connection->prepare($sql); |
| 54 | + $statement->execute($parameters); |
| 55 | + } |
| 56 | + |
| 57 | + protected function executeSelectAllSql(string $table) : array { |
| 58 | + $result = $this->connection->query(sprintf('SELECT * FROM %s', $table)); |
| 59 | + $rows = []; |
| 60 | + while ($row = $result->fetchRow()) { |
| 61 | + $rows[] = $row; |
| 62 | + } |
| 63 | + return $rows; |
| 64 | + } |
| 65 | +} |
0 commit comments