From 33cc9b3af85cd5a2db26ea933ae7fdcdcd267007 Mon Sep 17 00:00:00 2001 From: Sergei Morozov Date: Sun, 26 May 2019 08:46:14 -0700 Subject: [PATCH] Enforced parameter and return value types in Connection classes --- UPGRADE.md | 9 + lib/Doctrine/DBAL/Connection.php | 338 +++++++----------- .../Connections/MasterSlaveConnection.php | 52 ++- lib/Doctrine/DBAL/Driver.php | 2 +- lib/Doctrine/DBAL/Driver/Connection.php | 6 +- .../DBAL/Driver/IBMDB2/DB2Connection.php | 18 +- .../DBAL/Driver/Mysqli/MysqliConnection.php | 31 +- .../DBAL/Driver/OCI8/OCI8Connection.php | 33 +- lib/Doctrine/DBAL/Driver/PDOConnection.php | 15 +- .../DBAL/Driver/PDOSqlsrv/Connection.php | 2 +- .../SQLAnywhere/SQLAnywhereConnection.php | 8 +- .../DBAL/Driver/SQLSrv/LastInsertId.php | 12 +- .../DBAL/Driver/SQLSrv/SQLSrvConnection.php | 11 +- .../DBAL/Driver/ServerInfoAwareConnection.php | 6 +- lib/Doctrine/DBAL/Portability/Connection.php | 10 +- .../DBAL/Schema/AbstractSchemaManager.php | 8 +- lib/Doctrine/DBAL/Schema/DB2SchemaManager.php | 9 +- .../DBAL/Sharding/PoolingShardConnection.php | 67 +--- tests/Doctrine/Tests/DBAL/ConnectionTest.php | 24 +- .../Driver/OCI8/OCI8ConnectionTest.php | 2 +- .../Schema/OracleSchemaManagerTest.php | 2 +- .../Tests/DBAL/Functional/WriteTest.php | 3 +- .../DBAL/Schema/DB2SchemaManagerTest.php | 6 +- .../Sharding/PoolingShardConnectionTest.php | 76 ---- .../DBAL/Sharding/PoolingShardManagerTest.php | 9 +- 25 files changed, 255 insertions(+), 504 deletions(-) diff --git a/UPGRADE.md b/UPGRADE.md index 656239fddcc..24917ec6e71 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -1,5 +1,14 @@ # Upgrade to 3.0 +## BC BREAK: Changes in the `Doctrine\DBAL\Connection` API + +- The following methods have been removed as leaking internal implementation details: `::getHost()`, `::getPort()`, `::getUsername()`, `::getPassword()`. +- The `::getDatabase()` method can now return null which means that no database is currently selected. + +## BC BREAK: Changes in `Doctrine\DBAL\Driver\SQLSrv\LastInsertId` + +- The class stores the last inserted ID as a nullable string, not an integer, which is reflected in the method signatures. + ## BC BREAK: Changes in the `Doctrine\DBAL\Schema` API - Method `Doctrine\DBAL\Schema\AbstractSchemaManager::_getPortableViewDefinition()` no longer optionally returns false. It will always return a `Doctrine\DBAL\Schema\View` instance. diff --git a/lib/Doctrine/DBAL/Connection.php b/lib/Doctrine/DBAL/Connection.php index 40164cb1fb2..6966fca5468 100644 --- a/lib/Doctrine/DBAL/Connection.php +++ b/lib/Doctrine/DBAL/Connection.php @@ -114,7 +114,7 @@ class Connection implements DriverConnection /** * The parameters used during creation of the Connection instance. * - * @var mixed[] + * @var array */ private $params = []; @@ -153,10 +153,10 @@ class Connection implements DriverConnection /** * Initializes a new instance of the Connection class. * - * @param mixed[] $params The connection parameters. - * @param Driver $driver The driver to use. - * @param Configuration|null $config The configuration, optional. - * @param EventManager|null $eventManager The event manager, optional. + * @param array $params The connection parameters. + * @param Driver $driver The driver to use. + * @param Configuration|null $config The configuration, optional. + * @param EventManager|null $eventManager The event manager, optional. * * @throws DBALException */ @@ -197,89 +197,41 @@ public function __construct( /** * Gets the parameters used during instantiation. * - * @return mixed[] + * @return array */ - public function getParams() + public function getParams() : array { return $this->params; } /** * Gets the name of the database this Connection is connected to. - * - * @return string */ - public function getDatabase() + public function getDatabase() : ?string { return $this->_driver->getDatabase($this); } - /** - * Gets the hostname of the currently connected database. - * - * @return string|null - */ - public function getHost() - { - return $this->params['host'] ?? null; - } - - /** - * Gets the port of the currently connected database. - * - * @return mixed - */ - public function getPort() - { - return $this->params['port'] ?? null; - } - - /** - * Gets the username used by this connection. - * - * @return string|null - */ - public function getUsername() - { - return $this->params['user'] ?? null; - } - - /** - * Gets the password used by this connection. - * - * @return string|null - */ - public function getPassword() - { - return $this->params['password'] ?? null; - } - /** * Gets the DBAL driver instance. - * - * @return Driver */ - public function getDriver() + public function getDriver() : Driver { return $this->_driver; } /** * Gets the Configuration used by the Connection. - * - * @return Configuration */ - public function getConfiguration() + public function getConfiguration() : Configuration { return $this->_config; } /** * Gets the EventManager used by the Connection. - * - * @return EventManager */ - public function getEventManager() + public function getEventManager() : EventManager { return $this->_eventManager; } @@ -287,11 +239,9 @@ public function getEventManager() /** * Gets the DatabasePlatform for the connection. * - * @return AbstractPlatform - * * @throws DBALException */ - public function getDatabasePlatform() + public function getDatabasePlatform() : AbstractPlatform { if ($this->platform === null) { $this->detectDatabasePlatform(); @@ -302,10 +252,8 @@ public function getDatabasePlatform() /** * Gets the ExpressionBuilder for the connection. - * - * @return ExpressionBuilder */ - public function getExpressionBuilder() + public function getExpressionBuilder() : ExpressionBuilder { return $this->_expr; } @@ -347,7 +295,7 @@ public function connect() : void * * @throws DBALException If an invalid platform was specified for this connection. */ - private function detectDatabasePlatform() + private function detectDatabasePlatform() : void { $version = $this->getDatabasePlatformVersion(); @@ -370,11 +318,9 @@ private function detectDatabasePlatform() * or the underlying driver connection cannot determine the platform * version without having to query it (performance reasons). * - * @return string|null - * * @throws Exception */ - private function getDatabasePlatformVersion() + private function getDatabasePlatformVersion() : ?string { // Driver does not support version specific platforms. if (! $this->_driver instanceof VersionAwarePlatformDriver) { @@ -427,10 +373,8 @@ private function getDatabasePlatformVersion() /** * Returns the database server version if the underlying driver supports it. - * - * @return string|null */ - private function getServerVersion() + private function getServerVersion() : ?string { $connection = $this->getWrappedConnection(); @@ -450,9 +394,9 @@ private function getServerVersion() * * @return bool True if auto-commit mode is currently enabled for this connection, false otherwise. */ - public function isAutoCommit() + public function isAutoCommit() : bool { - return $this->autoCommit === true; + return $this->autoCommit; } /** @@ -465,7 +409,7 @@ public function isAutoCommit() * NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is * committed. If this method is called and the auto-commit mode is not changed, the call is a no-op. * - * @see isAutoCommit + * @see isAutoCommit * * @throws ConnectionException * @throws DriverException @@ -480,7 +424,7 @@ public function setAutoCommit(bool $autoCommit) : void $this->autoCommit = $autoCommit; // Commit all currently active transactions if any when switching auto-commit mode. - if ($this->isConnected !== true || $this->transactionNestingLevel === 0) { + if (! $this->isConnected || $this->transactionNestingLevel === 0) { return; } @@ -489,10 +433,8 @@ public function setAutoCommit(bool $autoCommit) : void /** * Sets the fetch mode. - * - * @param int $fetchMode */ - public function setFetchMode($fetchMode) : void + public function setFetchMode(int $fetchMode) : void { $this->defaultFetchMode = $fetchMode; } @@ -501,58 +443,58 @@ public function setFetchMode($fetchMode) : void * Prepares and executes an SQL query and returns the first row of the result * as an associative array. * - * @param string $statement The SQL query. - * @param mixed[] $params The query parameters. - * @param int[]|string[] $types The query parameter types. + * @param string $query The SQL query. + * @param array|array $params The prepared statement params. + * @param array|array $types The query parameter types. * - * @return mixed[]|false False is returned if no rows are found. + * @return array|false False is returned if no rows are found. * * @throws DBALException */ - public function fetchAssoc($statement, array $params = [], array $types = []) + public function fetchAssoc(string $query, array $params = [], array $types = []) { - return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::ASSOCIATIVE); + return $this->executeQuery($query, $params, $types)->fetch(FetchMode::ASSOCIATIVE); } /** * Prepares and executes an SQL query and returns the first row of the result * as a numerically indexed array. * - * @param string $statement The SQL query to be executed. - * @param mixed[] $params The prepared statement params. - * @param int[]|string[] $types The query parameter types. + * @param string $query The SQL query to be executed. + * @param array|array $params The prepared statement params. + * @param array|array $types The query parameter types. + * + * @return array|false False is returned if no rows are found. * - * @return mixed[]|false False is returned if no rows are found. + * @throws DBALException */ - public function fetchArray($statement, array $params = [], array $types = []) + public function fetchArray(string $query, array $params = [], array $types = []) { - return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::NUMERIC); + return $this->executeQuery($query, $params, $types)->fetch(FetchMode::NUMERIC); } /** * Prepares and executes an SQL query and returns the value of a single column * of the first row of the result. * - * @param string $statement The SQL query to be executed. - * @param mixed[] $params The prepared statement params. - * @param int $column The 0-indexed column number to retrieve. - * @param int[]|string[] $types The query parameter types. + * @param string $query The SQL query to be executed. + * @param array|array $params The prepared statement params. + * @param int $column The 0-indexed column number to retrieve. + * @param array|array $types The query parameter types. * * @return mixed|false False is returned if no rows are found. * * @throws DBALException */ - public function fetchColumn($statement, array $params = [], $column = 0, array $types = []) + public function fetchColumn(string $query, array $params = [], int $column = 0, array $types = []) { - return $this->executeQuery($statement, $params, $types)->fetchColumn($column); + return $this->executeQuery($query, $params, $types)->fetchColumn($column); } /** * Whether an actual connection to the database is established. - * - * @return bool */ - public function isConnected() + public function isConnected() : bool { return $this->isConnected; } @@ -562,7 +504,7 @@ public function isConnected() * * @return bool TRUE if a transaction is currently active, FALSE otherwise. */ - public function isTransactionActive() + public function isTransactionActive() : bool { return $this->transactionNestingLevel > 0; } @@ -570,10 +512,10 @@ public function isTransactionActive() /** * Adds identifier condition to the query components * - * @param mixed[] $identifier Map of key columns to their values - * @param string[] $columns Column names - * @param mixed[] $values Column values - * @param string[] $conditions Key conditions + * @param array $identifier Map of key columns to their values + * @param array $columns Column names + * @param array $values Column values + * @param array $conditions Key conditions * * @throws DBALException */ @@ -602,16 +544,16 @@ private function addIdentifierCondition( * * Table expression and columns are not escaped and are not safe for user-input. * - * @param string $tableExpression The expression of the table on which to delete. - * @param mixed[] $identifier The deletion criteria. An associative array containing column-value pairs. - * @param int[]|string[] $types The types of identifiers. + * @param string $table The SQL expression of the table on which to delete. + * @param array $identifier The deletion criteria. An associative array containing column-value pairs. + * @param array|array $types The query parameter types. * * @return int The number of affected rows. * * @throws DBALException * @throws InvalidArgumentException */ - public function delete($tableExpression, array $identifier, array $types = []) + public function delete(string $table, array $identifier, array $types = []) : int { if (empty($identifier)) { throw EmptyCriteriaNotAllowed::new(); @@ -622,7 +564,7 @@ public function delete($tableExpression, array $identifier, array $types = []) $this->addIdentifierCondition($identifier, $columns, $values, $conditions); return $this->executeUpdate( - 'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions), + 'DELETE FROM ' . $table . ' WHERE ' . implode(' AND ', $conditions), $values, is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types ); @@ -630,10 +572,8 @@ public function delete($tableExpression, array $identifier, array $types = []) /** * Closes the connection. - * - * @return void */ - public function close() + public function close() : void { $this->_conn = null; @@ -644,14 +584,12 @@ public function close() * Sets the transaction isolation level. * * @param int $level The level to set. - * - * @return int */ - public function setTransactionIsolation($level) + public function setTransactionIsolation(int $level) : void { $this->transactionIsolationLevel = $level; - return $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level)); + $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level)); } /** @@ -659,7 +597,7 @@ public function setTransactionIsolation($level) * * @return int The current transaction isolation level. */ - public function getTransactionIsolation() + public function getTransactionIsolation() : int { if ($this->transactionIsolationLevel === null) { $this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel(); @@ -673,16 +611,16 @@ public function getTransactionIsolation() * * Table expression and columns are not escaped and are not safe for user-input. * - * @param string $tableExpression The expression of the table to update quoted or unquoted. - * @param mixed[] $data An associative array containing column-value pairs. - * @param mixed[] $identifier The update criteria. An associative array containing column-value pairs. - * @param int[]|string[] $types Types of the merged $data and $identifier arrays in that order. + * @param string $table The SQL expression of the table to update quoted or unquoted. + * @param array $data An associative array containing column-value pairs. + * @param array $identifier The update criteria. An associative array containing column-value pairs. + * @param array|array $types The query parameter types. * * @return int The number of affected rows. * * @throws DBALException */ - public function update($tableExpression, array $data, array $identifier, array $types = []) + public function update(string $table, array $data, array $identifier, array $types = []) : int { $columns = $values = $conditions = $set = []; @@ -698,7 +636,7 @@ public function update($tableExpression, array $data, array $identifier, array $ $types = $this->extractTypeValues($columns, $types); } - $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set) + $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $set) . ' WHERE ' . implode(' AND ', $conditions); return $this->executeUpdate($sql, $values, $types); @@ -709,18 +647,18 @@ public function update($tableExpression, array $data, array $identifier, array $ * * Table expression and columns are not escaped and are not safe for user-input. * - * @param string $tableExpression The expression of the table to insert data into, quoted or unquoted. - * @param mixed[] $data An associative array containing column-value pairs. - * @param int[]|string[] $types Types of the inserted data. + * @param string $table The SQL expression of the table to insert data into, quoted or unquoted. + * @param array $data An associative array containing column-value pairs. + * @param array|array $types The query parameter types. * * @return int The number of affected rows. * * @throws DBALException */ - public function insert($tableExpression, array $data, array $types = []) + public function insert(string $table, array $data, array $types = []) : int { if (empty($data)) { - return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()'); + return $this->executeUpdate('INSERT INTO ' . $table . ' () VALUES ()'); } $columns = []; @@ -734,7 +672,7 @@ public function insert($tableExpression, array $data, array $types = []) } return $this->executeUpdate( - 'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' . + 'INSERT INTO ' . $table . ' (' . implode(', ', $columns) . ')' . ' VALUES (' . implode(', ', $set) . ')', $values, is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types @@ -744,16 +682,16 @@ public function insert($tableExpression, array $data, array $types = []) /** * Extract ordered type list from an ordered column list and type map. * - * @param int[]|string[] $columnList - * @param int[]|string[] $types + * @param array $columnList + * @param array $types The query parameter types. * - * @return int[]|string[] + * @return array|array */ private function extractTypeValues(array $columnList, array $types) { $typeValues = []; - foreach ($columnList as $columnIndex => $columnName) { + foreach ($columnList as $columnName) { $typeValues[] = $types[$columnName] ?? ParameterType::STRING; } @@ -770,13 +708,13 @@ private function extractTypeValues(array $columnList, array $types) * you SHOULD use them. In general, they end up causing way more * problems than they solve. * - * @param string $str The name to be quoted. + * @param string $identifier The identifier to be quoted. * - * @return string The quoted name. + * @return string The quoted identifier. */ - public function quoteIdentifier($str) + public function quoteIdentifier(string $identifier) : string { - return $this->getDatabasePlatform()->quoteIdentifier($str); + return $this->getDatabasePlatform()->quoteIdentifier($identifier); } /** @@ -790,15 +728,15 @@ public function quote(string $input) : string /** * Prepares and executes an SQL query and returns the result as an associative array. * - * @param string $sql The SQL query. - * @param mixed[] $params The query parameters. - * @param int[]|string[] $types The query parameter types. + * @param string $query The SQL query. + * @param array|array $params The query parameters. + * @param array|array $types The query parameter types. * - * @return mixed[] + * @return array */ - public function fetchAll($sql, array $params = [], $types = []) + public function fetchAll(string $query, array $params = [], array $types = []) : array { - return $this->executeQuery($sql, $params, $types)->fetchAll(); + return $this->executeQuery($query, $params, $types)->fetchAll(); } /** @@ -827,10 +765,10 @@ public function prepare(string $sql) : DriverStatement * If the query is parametrized, a prepared statement is used. * If an SQLLogger is configured, the execution is logged. * - * @param string $query The SQL query to execute. - * @param mixed[] $params The parameters to bind to the query, if any. - * @param int[]|string[] $types The types the previous parameters are in. - * @param QueryCacheProfile|null $qcp The query cache profile, optional. + * @param string $query The SQL query to execute. + * @param array|array $params The parameters to bind to the query, if any. + * @param array|array $types The query parameter types. + * @param QueryCacheProfile|null $qcp The query cache profile, optional. * * @return ResultStatement The executed statement. * @@ -875,14 +813,14 @@ public function executeQuery(string $query, array $params = [], $types = [], ?Qu /** * Executes a caching query. * - * @param string $query The SQL query to execute. - * @param mixed[] $params The parameters to bind to the query, if any. - * @param int[]|string[] $types The types the previous parameters are in. - * @param QueryCacheProfile $qcp The query cache profile. + * @param string $query The SQL query to execute. + * @param array|array $params The parameters to bind to the query, if any. + * @param array|array $types The query parameter types. + * @param QueryCacheProfile $qcp The query cache profile. * * @throws CacheException */ - public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp) : ResultStatement + public function executeCacheQuery(string $query, array $params, array $types, QueryCacheProfile $qcp) : ResultStatement { $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl(); @@ -920,15 +858,15 @@ public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qc * Executes an, optionally parametrized, SQL query and returns the result, * applying a given projection/transformation function on each row of the result. * - * @param string $query The SQL query to execute. - * @param mixed[] $params The parameters, if any. - * @param Closure $function The transformation function that is applied on each row. - * The function receives a single parameter, an array, that - * represents a row of the result set. + * @param string $query The SQL query to execute. + * @param array|array $params The parameters, if any. + * @param Closure $function The transformation function that is applied on each row. + * The function receives a single parameter, an array, that + * represents a row of the result set. * - * @return mixed[] The projected result of the query. + * @return array The projected result of the query. */ - public function project($query, array $params, Closure $function) + public function project(string $query, array $params, Closure $function) : array { $result = []; $stmt = $this->executeQuery($query, $params); @@ -971,9 +909,9 @@ public function query(string $sql) : ResultStatement * * This method supports PDO binding types as well as DBAL mapping types. * - * @param string $query The SQL query. - * @param mixed[] $params The query parameters. - * @param int[]|string[] $types The parameter types. + * @param string $query The SQL query. + * @param array|array $params The query parameters. + * @param array|array $types The query parameter types. * * @throws DBALException */ @@ -1035,7 +973,7 @@ public function exec(string $statement) : int * * @return int The nesting level. A value of 0 means there's no active transaction. */ - public function getTransactionNestingLevel() + public function getTransactionNestingLevel() : int { return $this->transactionNestingLevel; } @@ -1048,13 +986,13 @@ public function getTransactionNestingLevel() * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY * columns or sequences. * - * @param string|null $seqName Name of the sequence object from which the ID should be returned. + * @param string|null $name Name of the sequence object from which the ID should be returned. * * @return string A string representation of the last inserted ID. */ - public function lastInsertId($seqName = null) + public function lastInsertId(?string $name = null) : string { - return $this->getWrappedConnection()->lastInsertId($seqName); + return $this->getWrappedConnection()->lastInsertId($name); } /** @@ -1088,13 +1026,9 @@ public function transactional(Closure $func) /** * Sets if nested transactions should use savepoints. * - * @param bool $nestTransactionsWithSavepoints - * - * @return void - * * @throws ConnectionException */ - public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints) + public function setNestTransactionsWithSavepoints(bool $nestTransactionsWithSavepoints) : void { if ($this->transactionNestingLevel > 0) { throw MayNotAlterNestedTransactionWithSavepointsInTransaction::new(); @@ -1104,15 +1038,13 @@ public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoint throw SavepointsNotSupported::new(); } - $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints; + $this->nestTransactionsWithSavepoints = $nestTransactionsWithSavepoints; } /** * Gets if nested transactions should use savepoints. - * - * @return bool */ - public function getNestTransactionsWithSavepoints() + public function getNestTransactionsWithSavepoints() : bool { return $this->nestTransactionsWithSavepoints; } @@ -1264,11 +1196,9 @@ public function rollBack() : void * * @param string $savepoint The name of the savepoint to create. * - * @return void - * * @throws ConnectionException */ - public function createSavepoint($savepoint) + public function createSavepoint(string $savepoint) : void { if (! $this->getDatabasePlatform()->supportsSavepoints()) { throw SavepointsNotSupported::new(); @@ -1282,11 +1212,9 @@ public function createSavepoint($savepoint) * * @param string $savepoint The name of the savepoint to release. * - * @return void - * * @throws ConnectionException */ - public function releaseSavepoint($savepoint) + public function releaseSavepoint(string $savepoint) : void { if (! $this->getDatabasePlatform()->supportsSavepoints()) { throw SavepointsNotSupported::new(); @@ -1304,11 +1232,9 @@ public function releaseSavepoint($savepoint) * * @param string $savepoint The name of the savepoint to rollback to. * - * @return void - * * @throws ConnectionException */ - public function rollbackSavepoint($savepoint) + public function rollbackSavepoint(string $savepoint) : void { if (! $this->getDatabasePlatform()->supportsSavepoints()) { throw SavepointsNotSupported::new(); @@ -1319,10 +1245,8 @@ public function rollbackSavepoint($savepoint) /** * Gets the wrapped driver connection. - * - * @return DriverConnection */ - public function getWrappedConnection() + public function getWrappedConnection() : DriverConnection { $this->connect(); @@ -1332,10 +1256,8 @@ public function getWrappedConnection() /** * Gets the SchemaManager that can be used to inspect or change the * database schema through the connection. - * - * @return AbstractSchemaManager */ - public function getSchemaManager() + public function getSchemaManager() : AbstractSchemaManager { if ($this->_schemaManager === null) { $this->_schemaManager = $this->_driver->getSchemaManager($this); @@ -1348,11 +1270,9 @@ public function getSchemaManager() * Marks the current transaction so that the only possible * outcome for the transaction to be rolled back. * - * @return void - * * @throws ConnectionException If no transaction is active. */ - public function setRollbackOnly() + public function setRollbackOnly() : void { if ($this->transactionNestingLevel === 0) { throw NoActiveTransaction::new(); @@ -1363,11 +1283,9 @@ public function setRollbackOnly() /** * Checks whether the current transaction is marked for rollback only. * - * @return bool - * * @throws ConnectionException If no transaction is active. */ - public function isRollbackOnly() + public function isRollbackOnly() : bool { if ($this->transactionNestingLevel === 0) { throw NoActiveTransaction::new(); @@ -1385,7 +1303,7 @@ public function isRollbackOnly() * * @return mixed The converted value. */ - public function convertToDatabaseValue($value, $type) + public function convertToDatabaseValue($value, string $type) { return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform()); } @@ -1399,7 +1317,7 @@ public function convertToDatabaseValue($value, $type) * * @return mixed The converted type. */ - public function convertToPHPValue($value, $type) + public function convertToPHPValue($value, string $type) { return Type::getType($type)->convertToPHPValue($value, $this->getDatabasePlatform()); } @@ -1411,9 +1329,9 @@ public function convertToPHPValue($value, $type) * @internal Duck-typing used on the $stmt parameter to support driver statements as well as * raw PDOStatement instances. * - * @param DriverStatement $stmt The statement to bind the values to. - * @param mixed[] $params The map/list of named/positional parameters. - * @param int[]|string[] $types The parameter types. + * @param DriverStatement $stmt The statement to bind the values to. + * @param array|array $params The map/list of named/positional parameters. + * @param array|array $types The query parameter types. */ private function _bindTypedValues(DriverStatement $stmt, array $params, array $types) : void { @@ -1453,9 +1371,9 @@ private function _bindTypedValues(DriverStatement $stmt, array $params, array $t * @param mixed $value The value to bind. * @param int|string|null $type The type to bind (PDO or DBAL). * - * @return mixed[] [0] => the (escaped) value, [1] => the binding type. + * @return array [0] => the (escaped) value, [1] => the binding type. */ - private function getBindingInfo($value, $type) + private function getBindingInfo($value, $type) : array { if (is_string($type)) { $type = Type::getType($type); @@ -1476,12 +1394,12 @@ private function getBindingInfo($value, $type) * @internal This is a purely internal method. If you rely on this method, you are advised to * copy/paste the code as this method may change, or be removed without prior notice. * - * @param mixed[] $params - * @param int[]|string[] $types + * @param array|array $params + * @param array|array $types The query parameter types. * - * @return mixed[] + * @return array|array */ - public function resolveParams(array $params, array $types) + public function resolveParams(array $params, array $types) : array { $resolvedParams = []; @@ -1519,10 +1437,8 @@ public function resolveParams(array $params, array $types) /** * Creates a new instance of a SQL query builder. - * - * @return QueryBuilder */ - public function createQueryBuilder() + public function createQueryBuilder() : QueryBuilder { return new Query\QueryBuilder($this); } diff --git a/lib/Doctrine/DBAL/Connections/MasterSlaveConnection.php b/lib/Doctrine/DBAL/Connections/MasterSlaveConnection.php index 9ed48ae6c9c..b1da13c90f7 100644 --- a/lib/Doctrine/DBAL/Connections/MasterSlaveConnection.php +++ b/lib/Doctrine/DBAL/Connections/MasterSlaveConnection.php @@ -67,14 +67,15 @@ * ) * )); * - * You can also pass 'driverOptions' and any other documented option to each of this drivers to pass additional information. + * You can also pass 'driverOptions' and any other documented option to each of this drivers + * to pass additional information. */ class MasterSlaveConnection extends Connection { /** * Master and slave connection (one of the randomly picked slaves). * - * @var DriverConnection[]|null[] + * @var array */ protected $connections = ['master' => null, 'slave' => null]; @@ -89,12 +90,16 @@ class MasterSlaveConnection extends Connection /** * Creates Master Slave Connection. * - * @param mixed[] $params + * @param array $params * * @throws InvalidArgumentException */ - public function __construct(array $params, Driver $driver, ?Configuration $config = null, ?EventManager $eventManager = null) - { + public function __construct( + array $params, + Driver $driver, + ?Configuration $config = null, + ?EventManager $eventManager = null + ) { if (! isset($params['slaves'], $params['master'])) { throw new InvalidArgumentException('master or slaves configuration missing'); } @@ -114,10 +119,8 @@ public function __construct(array $params, Driver $driver, ?Configuration $confi /** * Checks if the connection is currently towards the master or not. - * - * @return bool */ - public function isConnectedToMaster() + public function isConnectedToMaster() : bool { return $this->_conn !== null && $this->_conn === $this->connections['master']; } @@ -179,12 +182,8 @@ public function connect($connectionName = null) : void /** * Connects to a specific connection. - * - * @param string $connectionName - * - * @return DriverConnection */ - protected function connectTo($connectionName) + protected function connectTo(string $connectionName) : DriverConnection { $params = $this->getParams(); @@ -199,12 +198,11 @@ protected function connectTo($connectionName) } /** - * @param string $connectionName - * @param mixed[] $params + * @param array $params * - * @return mixed + * @return array */ - protected function chooseConnectionConfiguration($connectionName, $params) + protected function chooseConnectionConfiguration(string $connectionName, array $params) : array { if ($connectionName === 'master') { return $params['master']; @@ -262,17 +260,17 @@ public function rollBack() : void /** * {@inheritDoc} */ - public function delete($tableName, array $identifier, array $types = []) + public function delete(string $table, array $identifier, array $types = []) : int { $this->connect('master'); - return parent::delete($tableName, $identifier, $types); + return parent::delete($table, $identifier, $types); } /** * {@inheritDoc} */ - public function close() + public function close() : void { unset($this->connections['master'], $this->connections['slave']); @@ -285,21 +283,21 @@ public function close() /** * {@inheritDoc} */ - public function update($tableName, array $data, array $identifier, array $types = []) + public function update(string $table, array $data, array $identifier, array $types = []) : int { $this->connect('master'); - return parent::update($tableName, $data, $identifier, $types); + return parent::update($table, $data, $identifier, $types); } /** * {@inheritDoc} */ - public function insert($tableName, array $data, array $types = []) + public function insert(string $table, array $data, array $types = []) : int { $this->connect('master'); - return parent::insert($tableName, $data, $types); + return parent::insert($table, $data, $types); } /** @@ -315,7 +313,7 @@ public function exec(string $statement) : int /** * {@inheritDoc} */ - public function createSavepoint($savepoint) + public function createSavepoint(string $savepoint) : void { $this->connect('master'); @@ -325,7 +323,7 @@ public function createSavepoint($savepoint) /** * {@inheritDoc} */ - public function releaseSavepoint($savepoint) + public function releaseSavepoint(string $savepoint) : void { $this->connect('master'); @@ -335,7 +333,7 @@ public function releaseSavepoint($savepoint) /** * {@inheritDoc} */ - public function rollbackSavepoint($savepoint) + public function rollbackSavepoint(string $savepoint) : void { $this->connect('master'); diff --git a/lib/Doctrine/DBAL/Driver.php b/lib/Doctrine/DBAL/Driver.php index 10ef3488c77..0cfc18cbba1 100644 --- a/lib/Doctrine/DBAL/Driver.php +++ b/lib/Doctrine/DBAL/Driver.php @@ -48,7 +48,7 @@ public function getSchemaManager(Connection $conn) : AbstractSchemaManager; /** * Gets the name of the database connected to for this driver. * - * @return string The name of the database or NULL if no database is currently selected. + * @return string|null The name of the database or NULL if no database is currently selected. */ public function getDatabase(Connection $conn) : ?string; } diff --git a/lib/Doctrine/DBAL/Driver/Connection.php b/lib/Doctrine/DBAL/Driver/Connection.php index 8ee150ec4f7..89402cfd7f9 100644 --- a/lib/Doctrine/DBAL/Driver/Connection.php +++ b/lib/Doctrine/DBAL/Driver/Connection.php @@ -40,12 +40,8 @@ public function exec(string $statement) : int; /** * Returns the ID of the last inserted row or sequence value. - * - * @param string|null $name - * - * @return string */ - public function lastInsertId($name = null); + public function lastInsertId(?string $name = null) : string; /** * Initiates a transaction. diff --git a/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Connection.php b/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Connection.php index c5a41d335b3..3439e1b96e5 100644 --- a/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Connection.php +++ b/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Connection.php @@ -29,18 +29,14 @@ class DB2Connection implements Connection, ServerInfoAwareConnection private $conn = null; /** - * @param mixed[] $params - * @param string $username - * @param string $password - * @param mixed[] $driverOptions + * @param array $params + * @param array $driverOptions * * @throws DB2Exception */ - public function __construct(array $params, $username, $password, $driverOptions = []) + public function __construct(array $params, string $username, string $password, array $driverOptions = []) { - $isPersistent = (isset($params['persistent']) && $params['persistent'] === true); - - if ($isPersistent) { + if (isset($params['persistent']) && $params['persistent'] === true) { $conn = db2_pconnect($params['dbname'], $username, $password, $driverOptions); } else { $conn = db2_connect($params['dbname'], $username, $password, $driverOptions); @@ -56,7 +52,7 @@ public function __construct(array $params, $username, $password, $driverOptions /** * {@inheritdoc} */ - public function getServerVersion() + public function getServerVersion() : string { /** @var stdClass $serverInfo */ $serverInfo = db2_server_info($this->conn); @@ -67,7 +63,7 @@ public function getServerVersion() /** * {@inheritdoc} */ - public function requiresQueryForServerVersion() + public function requiresQueryForServerVersion() : bool { return false; } @@ -121,7 +117,7 @@ public function exec(string $statement) : int /** * {@inheritdoc} */ - public function lastInsertId($name = null) + public function lastInsertId(?string $name = null) : string { return db2_last_insert_id($this->conn); } diff --git a/lib/Doctrine/DBAL/Driver/Mysqli/MysqliConnection.php b/lib/Doctrine/DBAL/Driver/Mysqli/MysqliConnection.php index 2c62142a105..2be3121ca82 100644 --- a/lib/Doctrine/DBAL/Driver/Mysqli/MysqliConnection.php +++ b/lib/Doctrine/DBAL/Driver/Mysqli/MysqliConnection.php @@ -39,14 +39,12 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar private $conn; /** - * @param mixed[] $params - * @param string $username - * @param string $password - * @param mixed[] $driverOptions + * @param array $params + * @param array $driverOptions * * @throws MysqliException */ - public function __construct(array $params, $username, $password, array $driverOptions = []) + public function __construct(array $params, string $username, string $password, array $driverOptions = []) { $port = $params['port'] ?? (int) ini_get('mysqli.default_port'); @@ -70,7 +68,8 @@ public function __construct(array $params, $username, $password, array $driverOp $this->setSecureConnection($params); $this->setDriverOptions($driverOptions); - set_error_handler(static function () { + set_error_handler(static function () : bool { + return true; }); try { if (! $this->conn->real_connect($host, $username, $password, $dbname, $port, $socket, $flags)) { @@ -91,10 +90,8 @@ public function __construct(array $params, $username, $password, array $driverOp * Retrieves mysqli native resource handle. * * Could be used if part of your application is not using DBAL. - * - * @return mysqli */ - public function getWrappedResourceHandle() + public function getWrappedResourceHandle() : mysqli { return $this->conn; } @@ -107,7 +104,7 @@ public function getWrappedResourceHandle() * * @link https://jira.mariadb.org/browse/MDEV-4088 */ - public function getServerVersion() + public function getServerVersion() : string { $serverInfos = $this->conn->get_server_info(); if (stripos($serverInfos, 'mariadb') !== false) { @@ -124,7 +121,7 @@ public function getServerVersion() /** * {@inheritdoc} */ - public function requiresQueryForServerVersion() + public function requiresQueryForServerVersion() : bool { return false; } @@ -171,9 +168,9 @@ public function exec(string $statement) : int /** * {@inheritdoc} */ - public function lastInsertId($name = null) + public function lastInsertId(?string $name = null) : string { - return $this->conn->insert_id; + return (string) $this->conn->insert_id; } /** @@ -207,12 +204,12 @@ public function rollBack() : void /** * Apply the driver options to the connection. * - * @param mixed[] $driverOptions + * @param array $driverOptions * * @throws MysqliException When one of of the options is not supported. * @throws MysqliException When applying doesn't work - e.g. due to incorrect value. */ - private function setDriverOptions(array $driverOptions = []) + private function setDriverOptions(array $driverOptions = []) : void { $supportedDriverOptions = [ MYSQLI_OPT_CONNECT_TIMEOUT, @@ -262,11 +259,11 @@ public function ping() : void /** * Establish a secure connection * - * @param mixed[] $params + * @param array $params * * @throws MysqliException */ - private function setSecureConnection(array $params) + private function setSecureConnection(array $params) : void { if (! isset($params['ssl_key']) && ! isset($params['ssl_cert']) && diff --git a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php index d32ecd15317..c2eac6d92a5 100644 --- a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php +++ b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php @@ -37,22 +37,15 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection /** * Creates a Connection to an Oracle Database using oci8 extension. * - * @param string $username - * @param string $password - * @param string $db - * @param string $charset - * @param int $sessionMode - * @param bool $persistent - * * @throws OCI8Exception */ public function __construct( - $username, - $password, - $db, - $charset = '', - $sessionMode = OCI_DEFAULT, - $persistent = false + string $username, + string $password, + string $db, + string $charset = '', + int $sessionMode = OCI_DEFAULT, + bool $persistent = false ) { $dbh = $persistent ? @oci_pconnect($username, $password, $db, $charset, $sessionMode) @@ -71,7 +64,7 @@ public function __construct( * @throws UnexpectedValueException If the version string returned by the database server * does not contain a parsable version number. */ - public function getServerVersion() + public function getServerVersion() : string { $version = oci_server_version($this->dbh); @@ -95,7 +88,7 @@ public function getServerVersion() /** * {@inheritdoc} */ - public function requiresQueryForServerVersion() + public function requiresQueryForServerVersion() : bool { return false; } @@ -141,10 +134,10 @@ public function exec(string $statement) : int /** * {@inheritdoc} */ - public function lastInsertId($name = null) + public function lastInsertId(?string $name = null) : string { if ($name === null) { - return false; + throw new OCI8Exception('The driver does not support identity columns.'); } $sql = 'SELECT ' . $name . '.CURRVAL FROM DUAL'; @@ -155,15 +148,13 @@ public function lastInsertId($name = null) throw new OCI8Exception('lastInsertId failed: Query was executed but no result was returned.'); } - return (int) $result; + return $result; } /** * Returns the current execution mode. - * - * @return int */ - public function getExecuteMode() + public function getExecuteMode() : int { return $this->executeMode; } diff --git a/lib/Doctrine/DBAL/Driver/PDOConnection.php b/lib/Doctrine/DBAL/Driver/PDOConnection.php index d9b40e923c9..77704b77e81 100644 --- a/lib/Doctrine/DBAL/Driver/PDOConnection.php +++ b/lib/Doctrine/DBAL/Driver/PDOConnection.php @@ -18,17 +18,14 @@ class PDOConnection implements Connection, ServerInfoAwareConnection private $connection; /** - * @param string $dsn - * @param string|null $user - * @param string|null $password - * @param mixed[]|null $options + * @param array $options * * @throws PDOException In case of an error. */ - public function __construct($dsn, $user = null, $password = null, ?array $options = null) + public function __construct(string $dsn, string $username = '', string $password = '', array $options = []) { try { - $this->connection = new PDO($dsn, (string) $user, (string) $password, (array) $options); + $this->connection = new PDO($dsn, $username, $password, $options); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (\PDOException $exception) { throw new PDOException($exception); @@ -50,7 +47,7 @@ public function exec(string $statement) : int /** * {@inheritdoc} */ - public function getServerVersion() + public function getServerVersion() : string { return $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION); } @@ -95,7 +92,7 @@ public function quote(string $input) : string /** * {@inheritdoc} */ - public function lastInsertId($name = null) + public function lastInsertId(?string $name = null) : string { try { if ($name === null) { @@ -111,7 +108,7 @@ public function lastInsertId($name = null) /** * {@inheritdoc} */ - public function requiresQueryForServerVersion() + public function requiresQueryForServerVersion() : bool { return false; } diff --git a/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Connection.php b/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Connection.php index 34b7458133d..ae8c43b9d9b 100644 --- a/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Connection.php +++ b/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Connection.php @@ -17,7 +17,7 @@ class Connection extends PDOConnection /** * {@inheritDoc} */ - public function lastInsertId($name = null) + public function lastInsertId(?string $name = null) : string { if ($name === null) { return parent::lastInsertId($name); diff --git a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereConnection.php b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereConnection.php index 7b2161a2e68..e815f760bda 100644 --- a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereConnection.php +++ b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereConnection.php @@ -37,7 +37,7 @@ class SQLAnywhereConnection implements Connection, ServerInfoAwareConnection * * @throws SQLAnywhereException */ - public function __construct($dsn, $persistent = false) + public function __construct(string $dsn, bool $persistent = false) { $this->connection = $persistent ? @sasql_pconnect($dsn) : @sasql_connect($dsn); @@ -97,7 +97,7 @@ public function exec(string $statement) : int /** * {@inheritdoc} */ - public function getServerVersion() + public function getServerVersion() : string { $version = $this->query("SELECT PROPERTY('ProductVersion')")->fetchColumn(); @@ -109,7 +109,7 @@ public function getServerVersion() /** * {@inheritdoc} */ - public function lastInsertId($name = null) + public function lastInsertId(?string $name = null) : string { if ($name === null) { return sasql_insert_id($this->connection); @@ -148,7 +148,7 @@ public function quote(string $input) : string /** * {@inheritdoc} */ - public function requiresQueryForServerVersion() + public function requiresQueryForServerVersion() : bool { return true; } diff --git a/lib/Doctrine/DBAL/Driver/SQLSrv/LastInsertId.php b/lib/Doctrine/DBAL/Driver/SQLSrv/LastInsertId.php index c76e66ff52e..8e688fe34e3 100644 --- a/lib/Doctrine/DBAL/Driver/SQLSrv/LastInsertId.php +++ b/lib/Doctrine/DBAL/Driver/SQLSrv/LastInsertId.php @@ -9,21 +9,15 @@ */ class LastInsertId { - /** @var int */ + /** @var string|null */ private $id; - /** - * @param int $id - */ - public function setId($id) + public function setId(?string $id) : void { $this->id = $id; } - /** - * @return int - */ - public function getId() + public function getId() : ?string { return $this->id; } diff --git a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php index 4470c58cd6d..a6b09b02818 100644 --- a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php +++ b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php @@ -30,12 +30,11 @@ class SQLSrvConnection implements Connection, ServerInfoAwareConnection protected $lastInsertId; /** - * @param string $serverName - * @param mixed[] $connectionOptions + * @param array $connectionOptions * * @throws SQLSrvException */ - public function __construct($serverName, $connectionOptions) + public function __construct(string $serverName, array $connectionOptions) { if (! sqlsrv_configure('WarningsReturnAsErrors', 0)) { throw SQLSrvException::fromSqlSrvErrors(); @@ -54,7 +53,7 @@ public function __construct($serverName, $connectionOptions) /** * {@inheritdoc} */ - public function getServerVersion() + public function getServerVersion() : string { $serverInfo = sqlsrv_server_info($this->conn); @@ -64,7 +63,7 @@ public function getServerVersion() /** * {@inheritdoc} */ - public function requiresQueryForServerVersion() + public function requiresQueryForServerVersion() : bool { return false; } @@ -119,7 +118,7 @@ public function exec(string $statement) : int /** * {@inheritDoc} */ - public function lastInsertId($name = null) + public function lastInsertId(?string $name = null) : string { if ($name !== null) { $stmt = $this->prepare('SELECT CONVERT(VARCHAR(MAX), current_value) FROM sys.sequences WHERE name = ?'); diff --git a/lib/Doctrine/DBAL/Driver/ServerInfoAwareConnection.php b/lib/Doctrine/DBAL/Driver/ServerInfoAwareConnection.php index d17b46c3b74..e667dddaf92 100644 --- a/lib/Doctrine/DBAL/Driver/ServerInfoAwareConnection.php +++ b/lib/Doctrine/DBAL/Driver/ServerInfoAwareConnection.php @@ -11,15 +11,13 @@ interface ServerInfoAwareConnection { /** * Returns the version number of the database server connected to. - * - * @return string */ - public function getServerVersion(); + public function getServerVersion() : string; /** * Checks whether a query is required to retrieve the database server version. * * @return bool True if a query is required to retrieve the database server version, false otherwise. */ - public function requiresQueryForServerVersion(); + public function requiresQueryForServerVersion() : bool; } diff --git a/lib/Doctrine/DBAL/Portability/Connection.php b/lib/Doctrine/DBAL/Portability/Connection.php index 8c64822f9e0..db687b167b4 100644 --- a/lib/Doctrine/DBAL/Portability/Connection.php +++ b/lib/Doctrine/DBAL/Portability/Connection.php @@ -82,18 +82,12 @@ public function connect() : void } } - /** - * @return int - */ - public function getPortability() + public function getPortability() : int { return $this->portability; } - /** - * @return int - */ - public function getFetchCase() + public function getFetchCase() : ?int { return $this->case; } diff --git a/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php b/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php index 2261b9c5f24..0e59e607db3 100644 --- a/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php +++ b/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php @@ -957,7 +957,13 @@ public function createSchemaConfig() : SchemaConfig */ public function getSchemaSearchPaths() : array { - return [$this->_conn->getDatabase()]; + $database = $this->_conn->getDatabase(); + + if ($database !== null) { + return [$database]; + } + + return []; } /** diff --git a/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php b/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php index 7bec112e9b3..b490640d0e2 100644 --- a/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php +++ b/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php @@ -8,9 +8,7 @@ use Doctrine\DBAL\Types\Type; use const CASE_LOWER; use function array_change_key_case; -use function assert; use function is_resource; -use function is_string; use function preg_match; use function str_replace; use function strpos; @@ -30,12 +28,9 @@ class DB2SchemaManager extends AbstractSchemaManager */ public function listTableNames() : array { - $username = $this->_conn->getUsername(); - assert(is_string($username)); + $sql = $this->_platform->getListTablesSQL() . ' AND CREATOR = CURRENT_USER'; - $sql = $this->_platform->getListTablesSQL() . ' AND CREATOR = UPPER(?)'; - - $tables = $this->_conn->fetchAll($sql, [$username]); + $tables = $this->_conn->fetchAll($sql); return $this->filterAssetNames($this->_getPortableTablesList($tables)); } diff --git a/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php b/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php index 72744474cac..aa7823241b0 100644 --- a/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php +++ b/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php @@ -53,13 +53,13 @@ */ class PoolingShardConnection extends Connection { - /** @var DriverConnection[] */ + /** @var array|array */ private $activeConnections = []; /** @var string|int|null */ private $activeShardId; - /** @var mixed[] */ + /** @var array>|array> */ private $connectionParameters = []; /** @@ -67,8 +67,12 @@ class PoolingShardConnection extends Connection * * @throws InvalidArgumentException */ - public function __construct(array $params, Driver $driver, ?Configuration $config = null, ?EventManager $eventManager = null) - { + public function __construct( + array $params, + Driver $driver, + ?Configuration $config = null, + ?EventManager $eventManager = null + ) { if (! isset($params['global'], $params['shards'])) { throw new InvalidArgumentException('Connection Parameters require "global" and "shards" configurations.'); } @@ -119,51 +123,11 @@ public function getActiveShardId() /** * {@inheritdoc} */ - public function getParams() + public function getParams() : array { return $this->activeShardId ? $this->connectionParameters[$this->activeShardId] : $this->connectionParameters[0]; } - /** - * {@inheritdoc} - */ - public function getHost() - { - $params = $this->getParams(); - - return $params['host'] ?? parent::getHost(); - } - - /** - * {@inheritdoc} - */ - public function getPort() - { - $params = $this->getParams(); - - return $params['port'] ?? parent::getPort(); - } - - /** - * {@inheritdoc} - */ - public function getUsername() - { - $params = $this->getParams(); - - return $params['user'] ?? parent::getUsername(); - } - - /** - * {@inheritdoc} - */ - public function getPassword() - { - $params = $this->getParams(); - - return $params['password'] ?? parent::getPassword(); - } - /** * Connects to a given shard. * @@ -207,10 +171,8 @@ public function connect($shardId = null) : void * Connects to a specific connection. * * @param string|int $shardId - * - * @return \Doctrine\DBAL\Driver\Connection */ - protected function connectTo($shardId) + protected function connectTo($shardId) : DriverConnection { $params = $this->getParams(); @@ -226,10 +188,8 @@ protected function connectTo($shardId) /** * @param string|int|null $shardId - * - * @return bool */ - public function isConnected($shardId = null) + public function isConnected($shardId = null) : bool { if ($shardId === null) { return $this->_conn !== null; @@ -238,10 +198,7 @@ public function isConnected($shardId = null) return isset($this->activeConnections[$shardId]); } - /** - * @return void - */ - public function close() + public function close() : void { $this->_conn = null; $this->activeConnections = []; diff --git a/tests/Doctrine/Tests/DBAL/ConnectionTest.php b/tests/Doctrine/Tests/DBAL/ConnectionTest.php index a7578d84c5d..c507ced6ff8 100644 --- a/tests/Doctrine/Tests/DBAL/ConnectionTest.php +++ b/tests/Doctrine/Tests/DBAL/ConnectionTest.php @@ -38,13 +38,13 @@ class ConnectionTest extends DbalTestCase /** @var Connection */ private $connection; - /** @var string[] */ + /** @var array */ protected $params = [ 'driver' => 'pdo_mysql', 'host' => 'localhost', 'user' => 'root', 'password' => 'password', - 'port' => '1234', + 'port' => 1234, ]; protected function setUp() : void @@ -114,26 +114,6 @@ public function testGetConfiguration() : void self::assertInstanceOf(Configuration::class, $config); } - public function testGetHost() : void - { - self::assertEquals('localhost', $this->connection->getHost()); - } - - public function testGetPort() : void - { - self::assertEquals('1234', $this->connection->getPort()); - } - - public function testGetUsername() : void - { - self::assertEquals('root', $this->connection->getUsername()); - } - - public function testGetPassword() : void - { - self::assertEquals('password', $this->connection->getPassword()); - } - public function testGetDriver() : void { self::assertInstanceOf(\Doctrine\DBAL\Driver\PDOMySql\Driver::class, $this->connection->getDriver()); diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/OCI8ConnectionTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/OCI8ConnectionTest.php index 4aaa091dbe5..e76cac08b00 100644 --- a/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/OCI8ConnectionTest.php +++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/OCI8ConnectionTest.php @@ -49,6 +49,6 @@ public function testLastInsertIdAcceptsFqn() : void $schema = $this->connection->getDatabase(); $sequence = $platform->getIdentitySequenceName($schema . '.DBAL2595', 'id'); - self::assertSame(1, $this->driverConnection->lastInsertId($sequence)); + self::assertEquals(1, $this->driverConnection->lastInsertId($sequence)); } } diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/OracleSchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/OracleSchemaManagerTest.php index 01b76d2bcc9..58ba12c300f 100644 --- a/tests/Doctrine/Tests/DBAL/Functional/Schema/OracleSchemaManagerTest.php +++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/OracleSchemaManagerTest.php @@ -237,7 +237,7 @@ public function testListTableColumnsSameTableNamesInDifferentSchemas() : void $otherTable->addColumn('id', Types::STRING); TestUtil::getTempConnection()->getSchemaManager()->dropAndCreateTable($otherTable); - $columns = $this->schemaManager->listTableColumns($table->getName(), $this->connection->getUsername()); + $columns = $this->schemaManager->listTableColumns($table->getName(), $this->connection->getDatabase()); self::assertCount(7, $columns); } diff --git a/tests/Doctrine/Tests/DBAL/Functional/WriteTest.php b/tests/Doctrine/Tests/DBAL/Functional/WriteTest.php index bce41d82afc..fc784a4b608 100644 --- a/tests/Doctrine/Tests/DBAL/Functional/WriteTest.php +++ b/tests/Doctrine/Tests/DBAL/Functional/WriteTest.php @@ -190,7 +190,8 @@ public function testLastInsertIdNoSequenceGiven() : void $this->markTestSkipped("Test only works consistently on platforms that support sequences and don't support identity columns."); } - self::assertFalse($this->lastInsertId()); + $this->expectException(DriverException::class); + $this->lastInsertId(); } /** diff --git a/tests/Doctrine/Tests/DBAL/Schema/DB2SchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Schema/DB2SchemaManagerTest.php index 31c3d27969d..8a202cc061b 100644 --- a/tests/Doctrine/Tests/DBAL/Schema/DB2SchemaManagerTest.php +++ b/tests/Doctrine/Tests/DBAL/Schema/DB2SchemaManagerTest.php @@ -33,14 +33,10 @@ protected function setUp() : void $platform = $this->createMock(DB2Platform::class); $this->conn = $this ->getMockBuilder(Connection::class) - ->onlyMethods(['fetchAll', 'getUsername']) + ->onlyMethods(['fetchAll']) ->setConstructorArgs([['platform' => $platform], $driverMock, new Configuration(), $eventManager]) ->getMock(); - $this->conn->expects($this->any()) - ->method('getUsername') - ->willReturn('db2inst1'); - $this->manager = new DB2SchemaManager($this->conn); } diff --git a/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardConnectionTest.php b/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardConnectionTest.php index 9569ef55d6e..1f56361668d 100644 --- a/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardConnectionTest.php +++ b/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardConnectionTest.php @@ -243,80 +243,4 @@ public function testGetParamsOverride() : void 'host' => 'foo', ], $conn->getParams()); } - - public function testGetHostOverride() : void - { - $conn = DriverManager::getConnection([ - 'wrapperClass' => PoolingShardConnection::class, - 'driver' => 'pdo_sqlite', - 'host' => 'localhost', - 'global' => ['memory' => true], - 'shards' => [ - ['id' => 1, 'memory' => true, 'host' => 'foo'], - ], - 'shardChoser' => MultiTenantShardChoser::class, - ]); - - self::assertEquals('localhost', $conn->getHost()); - - $conn->connect(1); - self::assertEquals('foo', $conn->getHost()); - } - - public function testGetPortOverride() : void - { - $conn = DriverManager::getConnection([ - 'wrapperClass' => PoolingShardConnection::class, - 'driver' => 'pdo_sqlite', - 'port' => 3306, - 'global' => ['memory' => true], - 'shards' => [ - ['id' => 1, 'memory' => true, 'port' => 3307], - ], - 'shardChoser' => MultiTenantShardChoser::class, - ]); - - self::assertEquals(3306, $conn->getPort()); - - $conn->connect(1); - self::assertEquals(3307, $conn->getPort()); - } - - public function testGetUsernameOverride() : void - { - $conn = DriverManager::getConnection([ - 'wrapperClass' => PoolingShardConnection::class, - 'driver' => 'pdo_sqlite', - 'user' => 'foo', - 'global' => ['memory' => true], - 'shards' => [ - ['id' => 1, 'memory' => true, 'user' => 'bar'], - ], - 'shardChoser' => MultiTenantShardChoser::class, - ]); - - self::assertEquals('foo', $conn->getUsername()); - - $conn->connect(1); - self::assertEquals('bar', $conn->getUsername()); - } - - public function testGetPasswordOverride() : void - { - $conn = DriverManager::getConnection([ - 'wrapperClass' => PoolingShardConnection::class, - 'driver' => 'pdo_sqlite', - 'password' => 'foo', - 'global' => ['memory' => true], - 'shards' => [ - ['id' => 1, 'memory' => true, 'password' => 'bar'], - ], - 'shardChoser' => MultiTenantShardChoser::class, - ]); - - self::assertEquals('foo', $conn->getPassword()); - - $conn->connect(1); - self::assertEquals('bar', $conn->getPassword()); - } } diff --git a/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardManagerTest.php b/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardManagerTest.php index 5a8e0e669d0..47ef10824c9 100644 --- a/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardManagerTest.php +++ b/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardManagerTest.php @@ -48,7 +48,14 @@ private function createStaticShardChooser() : ShardChoser public function testSelectGlobal() : void { $conn = $this->createConnectionMock(); - $conn->expects($this->once())->method('connect')->with($this->equalTo(0)); + $conn->expects($this->at(0)) + ->method('getParams') + ->will( + $this->returnValue([ + 'shardChoser' => $this->createMock(ShardChoser::class), + ]) + ); + $conn->expects($this->at(1))->method('connect')->with($this->equalTo(0)); $conn->method('getParams') ->willReturn([ 'shardChoser' => $this->createMock(ShardChoser::class),