diff --git a/analyzer-baseline.toml b/analyzer-baseline.toml index f535850..36ee370 100644 --- a/analyzer-baseline.toml +++ b/analyzer-baseline.toml @@ -96,36 +96,18 @@ code = "docblock-type-mismatch" message = 'Docblock return type `null|resource` is incompatible with native return type `PgSql\Connection|null`.' count = 1 -[[issues]] -file = "src/Connection.php" -code = "impossible-condition" -message = "This condition (type `false`) will always evaluate to false." -count = 1 - [[issues]] file = "src/Connection.php" code = "imprecise-type" message = "Type `array` in parameter `$connectionInfo` is imprecise, equivalent to `array`." count = 1 -[[issues]] -file = "src/Connection.php" -code = "incompatible-property-type" -message = 'Property `PhpDb\Pgsql\Connection::$resource` has an incompatible type declaration from docblock.' -count = 1 - [[issues]] file = "src/Connection.php" code = "invalid-argument" message = 'Invalid argument type for argument #1 of `PhpDb\Adapter\Driver\DriverInterface::createResult`: expected `resource`, but found `PgSql\Result`.' count = 1 -[[issues]] -file = "src/Connection.php" -code = "invalid-property-assignment-value" -message = 'Invalid type for property `$resource`: expected `PgSql\Connection|null`, but got `PgSql\Connection|false`.' -count = 1 - [[issues]] file = "src/Connection.php" code = "invalid-return-statement" @@ -192,18 +174,6 @@ code = "possibly-null-argument" message = 'Argument #1 of function `pg_query` is possibly `null`, but parameter type `PgSql\Connection|string` does not accept it.' count = 6 -[[issues]] -file = "src/Connection.php" -code = "possibly-null-argument" -message = 'Argument #1 of function `pg_set_client_encoding` is possibly `null`, but parameter type `PgSql\Connection|string` does not accept it.' -count = 1 - -[[issues]] -file = "src/Connection.php" -code = "redundant-comparison" -message = "Redundant `===` comparison: left-hand side is never identical to right-hand side." -count = 1 - [[issues]] file = "src/Connection.php" code = "unhandled-thrown-type" @@ -234,12 +204,6 @@ code = "unhandled-thrown-type" message = 'Potentially unhandled exception `PhpDb\Adapter\Exception\RuntimeException` in `PhpDb\Pgsql\Connection::rollback`.' count = 1 -[[issues]] -file = "src/Connection.php" -code = "unhandled-thrown-type" -message = 'Potentially unhandled exception `PhpDb\Adapter\Exception\RuntimeException` in `{closure:src/Connection.php:106:27}`.' -count = 1 - [[issues]] file = "src/Connection.php" code = "uninitialized-property" @@ -504,12 +468,6 @@ code = "possibly-invalid-argument" message = 'Possible argument type mismatch for argument #1 of `PhpDb\Pgsql\Result::initialize`: expected `PgSql\Result`, but possibly received `PgSql\Result|resource`.' count = 1 -[[issues]] -file = "src/Driver.php" -code = "possibly-null-argument" -message = 'Argument #1 of method `PhpDb\Pgsql\Statement::initialize` is possibly `null`, but parameter type `PgSql\Connection` does not accept it.' -count = 1 - [[issues]] file = "src/Driver.php" code = "redundant-condition" @@ -556,13 +514,13 @@ count = 1 file = "src/Metadata/Source.php" code = "mixed-array-access" message = "Unsafe array access on type `mixed`." -count = 23 +count = 8 [[issues]] file = "src/Metadata/Source.php" code = "mixed-assignment" message = "Assigning `mixed` type to a variable may lead to unexpected behavior." -count = 6 +count = 2 [[issues]] file = "src/Metadata/Source.php" @@ -590,34 +548,22 @@ count = 1 [[issues]] file = "src/Metadata/Source.php" -code = "property-type-coercion" -message = "A value of a less specific type `array{'columns': non-empty-array, 'is_nullable': bool|null, 'numeric_precision': mixed, 'numeric_scale': mixed, 'numeric_unsigned': bool|null, 'ordinal_position': mixed}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints'?: array, 'constraint_type'?: string, 'delete_rule'?: string, 'match_option'?: string, 'referenced_columns'?: list, 'referenced_table_name'?: string, 'referenced_table_schema'?: string, 'update_rule'?: string}>>>, 'schemas'?: list, 'table_names'?: array>, 'triggers'?: array>}` is being assigned to property `$data` (array{'columns'?: array, 'is_nullable': bool|null, 'numeric_precision': int|null|string, 'numeric_scale': int|null|string, 'numeric_unsigned': bool|null, 'ordinal_position': int|null|string}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints'?: array, 'constraint_type'?: string, 'delete_rule'?: string, 'match_option'?: string, 'referenced_columns'?: list, 'referenced_table_name'?: string, 'referenced_table_schema'?: string, 'update_rule'?: string}>>>, 'schemas'?: list, 'table_names'?: array>, 'triggers'?: array>})." -count = 1 - -[[issues]] -file = "src/Metadata/Source.php" -code = "property-type-coercion" -message = "A value of a less specific type `array{'columns'?: array, 'is_nullable': bool|null, 'numeric_precision': int|null|string, 'numeric_scale': int|null|string, 'numeric_unsigned': bool|null, 'ordinal_position': int|null|string}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints': non-empty-array, 'constraint_name'?: mixed, 'constraint_type'?: mixed, 'delete_rule'?: mixed, 'match_option'?: mixed, 'referenced_columns'?: list, 'referenced_table_name'?: mixed, 'referenced_table_schema'?: mixed, 'table_name'?: mixed, 'update_rule'?: mixed}>>>, 'schemas'?: list, 'table_names'?: array>, 'triggers'?: array>}` is being assigned to property `$data` (array{'columns'?: array, 'is_nullable': bool|null, 'numeric_precision': int|null|string, 'numeric_scale': int|null|string, 'numeric_unsigned': bool|null, 'ordinal_position': int|null|string}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints'?: array, 'constraint_type'?: string, 'delete_rule'?: string, 'match_option'?: string, 'referenced_columns'?: list, 'referenced_table_name'?: string, 'referenced_table_schema'?: string, 'update_rule'?: string}>>>, 'schemas'?: list, 'table_names'?: array>, 'triggers'?: array>})." -count = 1 +code = "reference-constraint-violation" +message = "Invalid assignment to by-reference parameter `$c`." +count = 5 [[issues]] file = "src/Metadata/Source.php" -code = "property-type-coercion" -message = "A value of a less specific type `array{'columns'?: array, 'is_nullable': bool|null, 'numeric_precision': int|null|string, 'numeric_scale': int|null|string, 'numeric_unsigned': bool|null, 'ordinal_position': int|null|string}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints'?: array, 'constraint_type'?: string, 'delete_rule'?: string, 'match_option'?: string, 'referenced_columns'?: list, 'referenced_table_name'?: string, 'referenced_table_schema'?: string, 'update_rule'?: string}>>>, 'schemas'?: list, 'table_names': non-empty-array>, 'triggers'?: array>}` is being assigned to property `$data` (array{'columns'?: array, 'is_nullable': bool|null, 'numeric_precision': int|null|string, 'numeric_scale': int|null|string, 'numeric_unsigned': bool|null, 'ordinal_position': int|null|string}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints'?: array, 'constraint_type'?: string, 'delete_rule'?: string, 'match_option'?: string, 'referenced_columns'?: list, 'referenced_table_name'?: string, 'referenced_table_schema'?: string, 'update_rule'?: string}>>>, 'schemas'?: list, 'table_names'?: array>, 'triggers'?: array>})." +code = "mixed-property-type-coercion" +message = "A value with a less specific type `array{'columns'?: array, 'is_nullable': bool|null, 'numeric_precision': int|null|string, 'numeric_scale': int|null|string, 'numeric_unsigned': bool|null, 'ordinal_position': int|null|string}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints': non-empty-array, 'constraint_name'?: string, 'constraint_type'?: mixed, 'delete_rule'?: mixed, 'match_option'?: mixed, 'referenced_columns'?: list, 'referenced_table_name'?: mixed, 'referenced_table_schema'?: mixed, 'table_name'?: mixed, 'update_rule'?: mixed}>>>, 'schemas'?: list, 'table_names'?: array>, 'triggers'?: array>}` is being assigned to property `$data` (array{'columns'?: array, 'is_nullable': bool|null, 'numeric_precision': int|null|string, 'numeric_scale': int|null|string, 'numeric_unsigned': bool|null, 'ordinal_position': int|null|string}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints'?: array, 'constraint_type'?: string, 'delete_rule'?: string, 'match_option'?: string, 'referenced_columns'?: list, 'referenced_table_name'?: string, 'referenced_table_schema'?: string, 'update_rule'?: string}>>>, 'schemas'?: list, 'table_names'?: array>, 'triggers'?: array>})." count = 1 [[issues]] file = "src/Metadata/Source.php" -code = "property-type-coercion" -message = "A value of a less specific type `array{'columns'?: array, 'is_nullable': bool|null, 'numeric_precision': int|null|string, 'numeric_scale': int|null|string, 'numeric_unsigned': bool|null, 'ordinal_position': int|null|string}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints'?: array, 'constraint_type'?: string, 'delete_rule'?: string, 'match_option'?: string, 'referenced_columns'?: list, 'referenced_table_name'?: string, 'referenced_table_schema'?: string, 'update_rule'?: string}>>>, 'schemas'?: list, 'table_names'?: array>, 'triggers': non-empty-array}>>}` is being assigned to property `$data` (array{'columns'?: array, 'is_nullable': bool|null, 'numeric_precision': int|null|string, 'numeric_scale': int|null|string, 'numeric_unsigned': bool|null, 'ordinal_position': int|null|string}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints'?: array, 'constraint_type'?: string, 'delete_rule'?: string, 'match_option'?: string, 'referenced_columns'?: list, 'referenced_table_name'?: string, 'referenced_table_schema'?: string, 'update_rule'?: string}>>>, 'schemas'?: list, 'table_names'?: array>, 'triggers'?: array>})." +code = "mixed-property-type-coercion" +message = "A value with a less specific type `array{'columns'?: array, 'is_nullable': bool|null, 'numeric_precision': int|null|string, 'numeric_scale': int|null|string, 'numeric_unsigned': bool|null, 'ordinal_position': int|null|string}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints'?: array, 'constraint_type'?: string, 'delete_rule'?: string, 'match_option'?: string, 'referenced_columns'?: list, 'referenced_table_name'?: string, 'referenced_table_schema'?: string, 'update_rule'?: string}>>>, 'schemas'?: list, 'table_names'?: array>, 'triggers': non-empty-array}>>}` is being assigned to property `$data` (array{'columns'?: array, 'is_nullable': bool|null, 'numeric_precision': int|null|string, 'numeric_scale': int|null|string, 'numeric_unsigned': bool|null, 'ordinal_position': int|null|string}>>>, 'constraint_keys'?: array>, 'constraint_references'?: array>, 'constraints'?: array, 'constraint_type'?: string, 'delete_rule'?: string, 'match_option'?: string, 'referenced_columns'?: list, 'referenced_table_name'?: string, 'referenced_table_schema'?: string, 'update_rule'?: string}>>>, 'schemas'?: list, 'table_names'?: array>, 'triggers'?: array>})." count = 1 -[[issues]] -file = "src/Metadata/Source.php" -code = "reference-constraint-violation" -message = "Invalid assignment to by-reference parameter `$c`." -count = 7 - [[issues]] file = "src/Pdo/Connection.php" code = "class-must-be-final" diff --git a/lint-baseline.toml b/lint-baseline.toml index 8b2320a..2da7997 100644 --- a/lint-baseline.toml +++ b/lint-baseline.toml @@ -160,7 +160,7 @@ count = 1 file = "src/Metadata/Source.php" code = "no-else-clause" message = "Avoid `else` clauses." -count = 4 +count = 3 [[issues]] file = "src/Metadata/Source.php" diff --git a/mago.toml b/mago.toml index f7bb3dd..37e9f9f 100644 --- a/mago.toml +++ b/mago.toml @@ -6,6 +6,9 @@ php-version = "8.3.0" paths = ["src", "test"] includes = ["vendor"] +[formatter] +parentheses-around-new-in-member-access = true + [linter] baseline = "lint-baseline.toml" diff --git a/src/Connection.php b/src/Connection.php index 323a32b..6ef6f6b 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -35,9 +35,6 @@ class Connection extends AbstractConnection implements DriverAwareInterface { protected DriverInterface|Driver $driver; - /** @var ?PgSqlConnection */ - protected $resource; - /** PostgreSQL connection type */ protected ?int $type = null; @@ -64,7 +61,7 @@ public function beginTransaction(): static $this->connect(); } - pg_query($this->resource, 'BEGIN'); + pg_query($this->getResource(), 'BEGIN'); $this->inTransaction = true; return $this; @@ -84,7 +81,7 @@ public function commit(): static return $this; // We ignore attempts to commit non-existing transaction } - pg_query($this->resource, 'COMMIT'); + pg_query($this->getResource(), 'COMMIT'); $this->inTransaction = false; return $this; @@ -103,13 +100,16 @@ public function connect(): static } $connection = $this->getConnectionString(); - set_error_handler(static function ($number, $string) { - throw new Exception\RuntimeException( - self::class . '::connect: Unable to connect to database', - $number, - new Exception\ErrorException($string, $number), - ); - }); + set_error_handler( + /** @throws Exception\RuntimeException */ + static function ($number, $string) { + throw new Exception\RuntimeException( + self::class . '::connect: Unable to connect to database', + $number, + new Exception\ErrorException($string, $number), + ); + }, + ); try { $this->resource = pg_connect($connection); } finally { @@ -142,7 +142,7 @@ public function connect(): static #[Override] public function disconnect(): static { - pg_close($this->resource); + pg_close($this->getResource()); $this->resource = null; return $this; } @@ -161,13 +161,13 @@ public function execute($sql): ResultInterface $this->profiler?->profilerStart($sql); - $resultResource = pg_query($this->resource, $sql); + $resultResource = pg_query($this->getResource(), $sql); $this->profiler?->profilerFinish(); // if the returnValue is something other than a pg result resource, bypass wrapping it if (false === $resultResource) { - throw new Exception\InvalidQueryException(pg_last_error($this->resource)); + throw new Exception\InvalidQueryException(pg_last_error($this->getResource())); } /** @phpstan-ignore argument.type */ @@ -184,7 +184,7 @@ public function getCurrentSchema(): string|false $this->connect(); } - $result = pg_query($this->resource, 'SELECT CURRENT_SCHEMA AS "currentschema"'); + $result = pg_query($this->getResource(), 'SELECT CURRENT_SCHEMA AS "currentschema"'); if (false === $result) { return false; } @@ -202,7 +202,7 @@ public function getLastGeneratedValue(?string $name = null): string|int|false|nu return null; } $result = pg_query( - $this->resource, + $this->getResource(), 'SELECT CURRVAL(\'' . str_replace('\'', '\\\'', $name) . '\') as "currval"', ); @@ -213,6 +213,7 @@ public function getLastGeneratedValue(?string $name = null): string|int|false|nu #[Override] public function getResource(): ?PgSqlConnection { + /** @var PgSqlConnection|null */ return $this->resource; } @@ -239,7 +240,7 @@ public function rollback(): static throw new Exception\RuntimeException('Must call beginTransaction() before you can rollback'); } - pg_query($this->resource, 'ROLLBACK'); + pg_query($this->getResource(), 'ROLLBACK'); $this->inTransaction = false; return $this; diff --git a/src/Container/PdoConnectionInterfaceFactory.php b/src/Container/PdoConnectionInterfaceFactory.php index 37fd495..11ccca8 100644 --- a/src/Container/PdoConnectionInterfaceFactory.php +++ b/src/Container/PdoConnectionInterfaceFactory.php @@ -39,11 +39,11 @@ public function __invoke( $connectionInfo = $options['connection'] ?? $config[$requestedName]['connection'] ?? $config[AdapterInterface::class]['adapters'][$requestedName]['connection'] - ?? null; + ?? null; if (null === $connectionInfo || ! is_array($connectionInfo) || [] === $connectionInfo) { throw new InvalidConnectionParametersException( 'Connection configuration must be an array of parameters', - $connectionInfo, + is_array($connectionInfo) ? $connectionInfo : [], ); } return new Pdo\Connection($connectionInfo); diff --git a/src/Container/PdoDriverInterfaceFactory.php b/src/Container/PdoDriverInterfaceFactory.php index c0e9db5..96a9db7 100644 --- a/src/Container/PdoDriverInterfaceFactory.php +++ b/src/Container/PdoDriverInterfaceFactory.php @@ -35,7 +35,7 @@ public function __invoke( $connectionParameters = $options['connection'] ?? $config[$requestedName]['connection'] ?? $config[AdapterInterface::class]['adapters'][$requestedName]['connection'] - ?? null; + ?? null; $connection = $container->build(Pdo\Connection::class, ['connection' => $connectionParameters]); return new Pdo\Driver( connection: $connection, diff --git a/src/Driver.php b/src/Driver.php index ae3d676..43056bf 100644 --- a/src/Driver.php +++ b/src/Driver.php @@ -5,6 +5,7 @@ namespace PhpDb\Pgsql; use Override; +use PgSql\Connection as PgSqlConnection; use PgSql\Result as PgSqlResult; use PhpDb\Adapter\Driver\ConnectionInterface; use PhpDb\Adapter\Driver\DriverAwareInterface; @@ -91,7 +92,14 @@ public function createStatement($sqlOrResource = null): StatementInterface&State $this->connection->connect(); } - $statement->initialize($this->connection->getResource()); + $resource = $this->connection->getResource(); + if (! $resource instanceof PgSqlConnection) { + throw new Exception\RuntimeException( + 'Unable to create a statement without a PostgreSQL connection resource', + ); + } + + $statement->initialize($resource); return $statement; } diff --git a/src/Metadata/Source.php b/src/Metadata/Source.php index 11122fe..04022e5 100644 --- a/src/Metadata/Source.php +++ b/src/Metadata/Source.php @@ -13,7 +13,6 @@ use function array_change_key_case; use function array_walk; use function implode; -use function is_array; use function is_string; use function key; @@ -71,6 +70,7 @@ protected function loadColumnData(string $table, string $schema): void /** @var ResultSet\ResultSetInterface&ResultSet\ResultSet $results */ $results = $this->adapter->query($sql, AdapterInterface::QUERY_MODE_EXECUTE); $columns = []; + /** @var array{column_name: string, ordinal_position: int|string, column_default: ?string, is_nullable: string, data_type: string, character_maximum_length: int|string|null, character_octet_length: int|string|null, numeric_precision: int|string|null, numeric_scale: int|string|null} $row */ foreach ($results->toArray() as $row) { $columns[$row['column_name']] = [ 'ordinal_position' => $row['ordinal_position'], @@ -225,7 +225,7 @@ protected function loadConstraintData(string $table, string $schema): void $isFK = false; foreach ($results->toArray() as $row) { if ($row['constraint_name'] !== $name) { - $name = $row['constraint_name']; + $name = (string) $row['constraint_name']; $constraints[$name] = [ 'constraint_name' => $name, 'constraint_type' => $row['constraint_type'], @@ -246,9 +246,9 @@ protected function loadConstraintData(string $table, string $schema): void $constraints[$name]['delete_rule'] = $row['delete_rule']; } } - $constraints[$name]['columns'][] = $row['column_name']; + $constraints[(string) $name]['columns'][] = $row['column_name']; if ($isFK) { - $constraints[$name]['referenced_columns'][] = $row['referenced_column_name']; + $constraints[(string) $name]['referenced_columns'][] = $row['referenced_column_name']; } } @@ -283,6 +283,7 @@ protected function loadSchemaData(): void $results = $this->adapter->query($sql, AdapterInterface::QUERY_MODE_EXECUTE); $schemas = []; + /** @var array{schema_name: string} $row */ foreach ($results->toArray() as $row) { $schemas[] = $row['schema_name']; } @@ -346,6 +347,7 @@ protected function loadTableNameData(string $schema): void $results = $this->adapter->query($sql, AdapterInterface::QUERY_MODE_EXECUTE); $tables = []; + /** @var array{table_name: string, table_type: string, view_definition: ?string, check_option: ?string, is_updatable: ?string} $row */ foreach ($results->toArray() as $row) { $tables[$row['table_name']] = [ 'table_type' => $row['table_type'], @@ -379,22 +381,14 @@ protected function loadTriggerData(string $schema): void 'action_condition', 'action_statement', 'action_orientation', - ['action_timing' => 'condition_timing'], - ['action_reference_old_table' => 'condition_reference_old_table'], - ['action_reference_new_table' => 'condition_reference_new_table'], + 'action_timing', + 'action_reference_old_table', + 'action_reference_new_table', 'created', ]; array_walk($isColumns, static function (&$c) use ($p) { - if (is_array($c)) { - $alias = key($c); - $c = $p->quoteIdentifierChain($c); - if (is_string($alias)) { - $c .= " {$p->quoteIdentifier($alias)}"; - } - } else { - $c = $p->quoteIdentifier($c); - } + $c = $p->quoteIdentifier($c); }); $sql = @@ -423,7 +417,7 @@ protected function loadTriggerData(string $schema): void if (null !== $row['created']) { $row['created'] = new DateTime($row['created']); } - $data[$row['trigger_name']] = $row; + $data[(string) $row['trigger_name']] = $row; } $this->data['triggers'][$schema] = $data; diff --git a/src/Pdo/Driver.php b/src/Pdo/Driver.php index cd5e0ed..7b91c46 100644 --- a/src/Pdo/Driver.php +++ b/src/Pdo/Driver.php @@ -41,7 +41,7 @@ public function createResult($resource): ResultInterface { /** @var Result $result */ $result = clone $this->resultPrototype; - $result->initialize($resource, $this->connection->getLastGeneratedValue()); + $result->initialize($resource, $this->getLastGeneratedValue()); return $result; } diff --git a/test/integration/AdapterPlatformTest.php b/test/integration/AdapterPlatformTest.php index c54e6e2..8cf4f98 100644 --- a/test/integration/AdapterPlatformTest.php +++ b/test/integration/AdapterPlatformTest.php @@ -4,7 +4,7 @@ namespace PhpDbIntegrationTest\Pgsql; -use PhpDb\Adapter\Exception\VunerablePlatformQuoteException; +use PhpDb\Adapter\Exception\RuntimeException; use PhpDb\Pgsql\AdapterPlatform; use PhpDbTestAsset\Pgsql\SetupTrait; use PHPUnit\Framework\Attributes\CoversClass; @@ -23,8 +23,7 @@ public function quoteValueWithPdoPgsql(): void { $adapter = $this->getAdapter(self::PDO_ADAPTER); $pgsql = $adapter->getPlatform(); - //$this->expectException(VunerablePlatformQuoteException::class); - $value = $pgsql->quoteValue('value'); + $value = $pgsql->quoteValue('value'); static::assertSame('\'value\'', $value); } @@ -33,7 +32,8 @@ public function quoteValueWithPgsql(): void { $adapter = $this->getAdapter(self::NATIVE_ADAPTER); $pgsql = $adapter->getPlatform(); - $this->expectException(VunerablePlatformQuoteException::class); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('without extension/driver support can introduce security vulnerabilities'); $value = $pgsql->quoteValue('value'); static::assertSame('\'value\'', $value); diff --git a/test/integration/ConnectionTest.php b/test/integration/ConnectionTest.php new file mode 100644 index 0000000..b81088e --- /dev/null +++ b/test/integration/ConnectionTest.php @@ -0,0 +1,144 @@ +connection(); + + $connection->beginTransaction(); + $connection->execute("INSERT INTO test_connection (label) VALUES ('committed')"); + $connection->commit(); + + static::assertSame(1, $this->countRows( + $this->connection(), + "SELECT COUNT(*) AS n FROM test_connection WHERE label = 'committed'", + )); + } + + #[Test] + public function connectThrowsWhenTheServerRefusesTheConnection(): void + { + $connection = new Connection(['database' => 'phpdb_no_such_database'] + $this->conn); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage(Connection::class . '::connect: Unable to connect to database'); + + $connection->connect(); + } + + #[Test] + public function disconnectReleasesTheConnectionResource(): void + { + $connection = $this->connection(); + $connection->connect(); + + $connection->disconnect(); + + static::assertNull($connection->getResource()); + } + + #[Test] + public function executeThrowsTheServerErrorForInvalidSql(): void + { + $connection = $this->connection(); + $warnings = []; + $exception = null; + + set_error_handler(static function (int $number, string $message) use (&$warnings): bool { + $warnings[] = $message; + + return true; + }, E_WARNING); + try { + $connection->execute('SELECT * FROM no_such_table'); + } catch (InvalidQueryException $caught) { + $exception = $caught; + } finally { + restore_error_handler(); + } + + static::assertInstanceOf(InvalidQueryException::class, $exception); + static::assertStringContainsString('relation "no_such_table" does not exist', $exception->getMessage()); + static::assertCount(1, $warnings); + static::assertStringContainsString('pg_query(): Query failed', $warnings[0]); + } + + #[Test] + public function getCurrentSchemaReturnsTheSearchPathSchema(): void + { + static::assertSame('public', $this->connection()->getCurrentSchema()); + } + + #[Test] + public function getLastGeneratedValueReturnsTheSequenceValueOfTheLastInsert(): void + { + $connection = $this->connection(); + $inserted = $connection->execute("INSERT INTO test_connection (label) VALUES ('generated') RETURNING id") + ->current(); + + static::assertSame((string) $inserted['id'], $connection->getLastGeneratedValue('test_connection_id_seq')); + } + + #[Test] + public function rollbackDiscardsWhatTheTransactionWrote(): void + { + $connection = $this->connection(); + + $connection->beginTransaction(); + $connection->execute("INSERT INTO test_connection (label) VALUES ('rolled back')"); + $connection->rollback(); + + static::assertSame(0, $this->countRows($connection, 'SELECT COUNT(*) AS n FROM test_connection')); + } + + protected function tearDown(): void + { + $this->connection()->execute('TRUNCATE test_connection RESTART IDENTITY'); + } + + private function connection(): Connection + { + $connection = new Connection($this->conn); + $connection->setDriver(new Driver($connection)); + + return $connection; + } + + private function countRows(Connection $connection, string $sql): int + { + return (int) $connection->execute($sql)->current()['n']; + } +} diff --git a/test/integration/Container/PdoFactoriesTest.php b/test/integration/Container/PdoFactoriesTest.php new file mode 100644 index 0000000..a0f6ffb --- /dev/null +++ b/test/integration/Container/PdoFactoriesTest.php @@ -0,0 +1,75 @@ +getAdapter(self::PDO_ADAPTER); + + $connection = (new PdoConnectionInterfaceFactory())( + $this->serviceManager, + Connection::class, + ['connection' => $this->conn], + ); + + static::assertSame($this->conn, $connection->getConnectionParameters()); + } + + #[Test] + public function connectionFactoryRejectsAMissingConnectionConfiguration(): void + { + $this->getAdapter(self::PDO_ADAPTER); + + $this->expectException(InvalidConnectionParametersException::class); + $this->expectExceptionMessage('Connection configuration must be an array of parameters'); + + (new PdoConnectionInterfaceFactory())($this->serviceManager, Connection::class); + } + + #[Test] + public function driverFactoryBuildsADriverOnAConnectionFromTheGivenParameters(): void + { + $this->getAdapter(self::PDO_ADAPTER); + + $driver = (new PdoDriverInterfaceFactory())( + $this->serviceManager, + Driver::class, + ['connection' => $this->conn], + ); + + static::assertSame($this->conn, $driver->getConnection()->getConnectionParameters()); + } + + #[Test] + public function driverFactoryRejectsAMissingConnectionConfiguration(): void + { + $this->getAdapter(self::PDO_ADAPTER); + + $this->expectException(ServiceNotCreatedException::class); + $this->expectExceptionMessage('Connection configuration must be an array of parameters'); + + (new PdoDriverInterfaceFactory())($this->serviceManager, Driver::class); + } +} diff --git a/test/integration/DriverTest.php b/test/integration/DriverTest.php new file mode 100644 index 0000000..a9d83db --- /dev/null +++ b/test/integration/DriverTest.php @@ -0,0 +1,31 @@ +conn); + $driver = new Driver($connection); + + $statement = $driver->createStatement('SELECT name FROM test ORDER BY id'); + + static::assertSame('foo', $statement->execute()->current()['name']); + } +} diff --git a/test/integration/Metadata/SourceTest.php b/test/integration/Metadata/SourceTest.php new file mode 100644 index 0000000..a3c0ed3 --- /dev/null +++ b/test/integration/Metadata/SourceTest.php @@ -0,0 +1,91 @@ +constraintsByName('test_child')['test_child_test_id_fkey']; + + static::assertSame( + ['FOREIGN KEY', ['test_id'], 'test', ['id'], 'CASCADE'], + [ + $foreignKey->getType(), + $foreignKey->getColumns(), + $foreignKey->getReferencedTableName(), + $foreignKey->getReferencedColumns(), + $foreignKey->getDeleteRule(), + ], + ); + } + + #[Test] + public function getConstraintsDescribesPrimaryKeyAndCheckConstraints(): void + { + $constraints = $this->constraintsByName('test_child'); + + static::assertSame( + ['PRIMARY KEY', ['id'], 'CHECK', '(quantity > 0)'], + [ + $constraints['test_child_pkey']->getType(), + $constraints['test_child_pkey']->getColumns(), + $constraints['test_child_quantity_check']->getType(), + $constraints['test_child_quantity_check']->getCheckClause(), + ], + ); + } + + #[Test] + public function getTriggersListsTriggersByName(): void + { + $trigger = $this->source()->getTrigger('test_child_before_insert'); + + static::assertSame( + ['test_child_before_insert', 'INSERT', 'test_child', 'BEFORE'], + [ + $trigger->getName(), + $trigger->getEventManipulation(), + $trigger->getEventObjectTable(), + $trigger->getActionTiming(), + ], + ); + } + + /** + * @return array + */ + private function constraintsByName(string $table): array + { + $constraints = $this->source()->getConstraints($table); + + return array_combine(array_map(static fn($c) => $c->getName(), $constraints), $constraints); + } + + private function source(): Source + { + /** @var Adapter $adapter */ + $adapter = $this->getAdapter(); + + return new Source($adapter); + } +} diff --git a/test/integration/TestFixtures/pgsql.sql b/test/integration/TestFixtures/pgsql.sql index 3fe43cc..9c56db3 100644 --- a/test/integration/TestFixtures/pgsql.sql +++ b/test/integration/TestFixtures/pgsql.sql @@ -1,3 +1,4 @@ +DROP TABLE IF EXISTS test_child; DROP TABLE IF EXISTS test; CREATE TABLE IF NOT EXISTS test ( id SERIAL PRIMARY KEY, @@ -27,3 +28,27 @@ CREATE TABLE IF NOT EXISTS test_seq ( foo VARCHAR(255) NOT NULL, CONSTRAINT test_seq_pkey PRIMARY KEY (id) ); + +DROP TABLE IF EXISTS test_connection; +CREATE TABLE IF NOT EXISTS test_connection ( + id SERIAL PRIMARY KEY, + label VARCHAR(255) NOT NULL +); + +CREATE TABLE IF NOT EXISTS test_child ( + id SERIAL PRIMARY KEY, + test_id INTEGER NOT NULL, + quantity INTEGER NOT NULL, + CONSTRAINT test_child_test_id_fkey FOREIGN KEY (test_id) REFERENCES test (id) ON DELETE CASCADE, + CONSTRAINT test_child_quantity_check CHECK (quantity > 0) +); + +CREATE OR REPLACE FUNCTION test_child_touch() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + RETURN NEW; +END; +$$; + +CREATE TRIGGER test_child_before_insert + BEFORE INSERT ON test_child + FOR EACH ROW EXECUTE FUNCTION test_child_touch(); diff --git a/test/unit/DriverTest.php b/test/unit/DriverTest.php new file mode 100644 index 0000000..b5a3028 --- /dev/null +++ b/test/unit/DriverTest.php @@ -0,0 +1,33 @@ +createStub(Connection::class); + $connection->method('isConnected')->willReturn(true); + $connection->method('getResource')->willReturn(null); + + $driver = new Driver($connection); + + $this->expectException(Exception\RuntimeException::class); + $this->expectExceptionMessage('Unable to create a statement without a PostgreSQL connection resource'); + + $driver->createStatement('SELECT 1'); + } +} diff --git a/test/unit/Pdo/DriverTest.php b/test/unit/Pdo/DriverTest.php new file mode 100644 index 0000000..7bc75d6 --- /dev/null +++ b/test/unit/Pdo/DriverTest.php @@ -0,0 +1,32 @@ +createStub(Connection::class); + $connection->method('getLastGeneratedValue')->willReturn('42'); + + $driver = new Driver($connection); + $result = $driver->createResult($this->createStub(PDOStatement::class)); + + static::assertInstanceOf(Result::class, $result); + static::assertSame('42', $result->getGeneratedValue()); + } +}