Unverified Commit f90c5001 authored by Sergei Morozov's avatar Sergei Morozov

Merge pull request #3568 from morozov/connection-types

Enforced parameter and return value types in Connection classes
parents ab8d709f 88f7feae
# Upgrade to 3.0 # 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 ## 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. - Method `Doctrine\DBAL\Schema\AbstractSchemaManager::_getPortableViewDefinition()` no longer optionally returns false. It will always return a `Doctrine\DBAL\Schema\View` instance.
......
...@@ -114,7 +114,7 @@ class Connection implements DriverConnection ...@@ -114,7 +114,7 @@ class Connection implements DriverConnection
/** /**
* The parameters used during creation of the Connection instance. * The parameters used during creation of the Connection instance.
* *
* @var mixed[] * @var array<string, mixed>
*/ */
private $params = []; private $params = [];
...@@ -153,7 +153,7 @@ class Connection implements DriverConnection ...@@ -153,7 +153,7 @@ class Connection implements DriverConnection
/** /**
* Initializes a new instance of the Connection class. * Initializes a new instance of the Connection class.
* *
* @param mixed[] $params The connection parameters. * @param array<string, mixed> $params The connection parameters.
* @param Driver $driver The driver to use. * @param Driver $driver The driver to use.
* @param Configuration|null $config The configuration, optional. * @param Configuration|null $config The configuration, optional.
* @param EventManager|null $eventManager The event manager, optional. * @param EventManager|null $eventManager The event manager, optional.
...@@ -197,97 +197,41 @@ class Connection implements DriverConnection ...@@ -197,97 +197,41 @@ class Connection implements DriverConnection
/** /**
* Gets the parameters used during instantiation. * Gets the parameters used during instantiation.
* *
* @return mixed[] * @return array<string, mixed>
*/ */
public function getParams() public function getParams() : array
{ {
return $this->params; return $this->params;
} }
/** /**
* Gets the name of the database this Connection is connected to. * 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); return $this->_driver->getDatabase($this);
} }
/**
* Gets the hostname of the currently connected database.
*
* @deprecated
*
* @return string|null
*/
public function getHost()
{
return $this->params['host'] ?? null;
}
/**
* Gets the port of the currently connected database.
*
* @deprecated
*
* @return mixed
*/
public function getPort()
{
return $this->params['port'] ?? null;
}
/**
* Gets the username used by this connection.
*
* @deprecated
*
* @return string|null
*/
public function getUsername()
{
return $this->params['user'] ?? null;
}
/**
* Gets the password used by this connection.
*
* @deprecated
*
* @return string|null
*/
public function getPassword()
{
return $this->params['password'] ?? null;
}
/** /**
* Gets the DBAL driver instance. * Gets the DBAL driver instance.
*
* @return Driver
*/ */
public function getDriver() public function getDriver() : Driver
{ {
return $this->_driver; return $this->_driver;
} }
/** /**
* Gets the Configuration used by the Connection. * Gets the Configuration used by the Connection.
*
* @return Configuration
*/ */
public function getConfiguration() public function getConfiguration() : Configuration
{ {
return $this->_config; return $this->_config;
} }
/** /**
* Gets the EventManager used by the Connection. * Gets the EventManager used by the Connection.
*
* @return EventManager
*/ */
public function getEventManager() public function getEventManager() : EventManager
{ {
return $this->_eventManager; return $this->_eventManager;
} }
...@@ -295,11 +239,9 @@ class Connection implements DriverConnection ...@@ -295,11 +239,9 @@ class Connection implements DriverConnection
/** /**
* Gets the DatabasePlatform for the connection. * Gets the DatabasePlatform for the connection.
* *
* @return AbstractPlatform
*
* @throws DBALException * @throws DBALException
*/ */
public function getDatabasePlatform() public function getDatabasePlatform() : AbstractPlatform
{ {
if ($this->platform === null) { if ($this->platform === null) {
$this->detectDatabasePlatform(); $this->detectDatabasePlatform();
...@@ -310,10 +252,8 @@ class Connection implements DriverConnection ...@@ -310,10 +252,8 @@ class Connection implements DriverConnection
/** /**
* Gets the ExpressionBuilder for the connection. * Gets the ExpressionBuilder for the connection.
*
* @return ExpressionBuilder
*/ */
public function getExpressionBuilder() public function getExpressionBuilder() : ExpressionBuilder
{ {
return $this->_expr; return $this->_expr;
} }
...@@ -357,7 +297,7 @@ class Connection implements DriverConnection ...@@ -357,7 +297,7 @@ class Connection implements DriverConnection
* *
* @throws DBALException If an invalid platform was specified for this connection. * @throws DBALException If an invalid platform was specified for this connection.
*/ */
private function detectDatabasePlatform() private function detectDatabasePlatform() : void
{ {
$version = $this->getDatabasePlatformVersion(); $version = $this->getDatabasePlatformVersion();
...@@ -380,11 +320,9 @@ class Connection implements DriverConnection ...@@ -380,11 +320,9 @@ class Connection implements DriverConnection
* or the underlying driver connection cannot determine the platform * or the underlying driver connection cannot determine the platform
* version without having to query it (performance reasons). * version without having to query it (performance reasons).
* *
* @return string|null
*
* @throws Exception * @throws Exception
*/ */
private function getDatabasePlatformVersion() private function getDatabasePlatformVersion() : ?string
{ {
// Driver does not support version specific platforms. // Driver does not support version specific platforms.
if (! $this->_driver instanceof VersionAwarePlatformDriver) { if (! $this->_driver instanceof VersionAwarePlatformDriver) {
...@@ -437,10 +375,8 @@ class Connection implements DriverConnection ...@@ -437,10 +375,8 @@ class Connection implements DriverConnection
/** /**
* Returns the database server version if the underlying driver supports it. * Returns the database server version if the underlying driver supports it.
*
* @return string|null
*/ */
private function getServerVersion() private function getServerVersion() : ?string
{ {
$connection = $this->getWrappedConnection(); $connection = $this->getWrappedConnection();
...@@ -460,9 +396,9 @@ class Connection implements DriverConnection ...@@ -460,9 +396,9 @@ class Connection implements DriverConnection
* *
* @return bool True if auto-commit mode is currently enabled for this connection, false otherwise. * @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;
} }
/** /**
...@@ -490,7 +426,7 @@ class Connection implements DriverConnection ...@@ -490,7 +426,7 @@ class Connection implements DriverConnection
$this->autoCommit = $autoCommit; $this->autoCommit = $autoCommit;
// Commit all currently active transactions if any when switching auto-commit mode. // 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; return;
} }
...@@ -499,10 +435,8 @@ class Connection implements DriverConnection ...@@ -499,10 +435,8 @@ class Connection implements DriverConnection
/** /**
* Sets the fetch mode. * Sets the fetch mode.
*
* @param int $fetchMode
*/ */
public function setFetchMode($fetchMode) : void public function setFetchMode(int $fetchMode) : void
{ {
$this->defaultFetchMode = $fetchMode; $this->defaultFetchMode = $fetchMode;
} }
...@@ -511,58 +445,58 @@ class Connection implements DriverConnection ...@@ -511,58 +445,58 @@ class Connection implements DriverConnection
* Prepares and executes an SQL query and returns the first row of the result * Prepares and executes an SQL query and returns the first row of the result
* as an associative array. * as an associative array.
* *
* @param string $statement The SQL query. * @param string $query The SQL query.
* @param mixed[] $params The query parameters. * @param array<int, mixed>|array<string, mixed> $params The prepared statement params.
* @param int[]|string[] $types The query parameter types. * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
* *
* @return mixed[]|false False is returned if no rows are found. * @return array<string, mixed>|false False is returned if no rows are found.
* *
* @throws DBALException * @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 * Prepares and executes an SQL query and returns the first row of the result
* as a numerically indexed array. * as a numerically indexed array.
* *
* @param string $statement The SQL query to be executed. * @param string $query The SQL query to be executed.
* @param mixed[] $params The prepared statement params. * @param array<int, mixed>|array<string, mixed> $params The prepared statement params.
* @param int[]|string[] $types The query parameter types. * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
*
* @return array<int, mixed>|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 * Prepares and executes an SQL query and returns the value of a single column
* of the first row of the result. * of the first row of the result.
* *
* @param string $statement The SQL query to be executed. * @param string $query The SQL query to be executed.
* @param mixed[] $params The prepared statement params. * @param array<int, mixed>|array<string, mixed> $params The prepared statement params.
* @param int $column The 0-indexed column number to retrieve. * @param int $column The 0-indexed column number to retrieve.
* @param int[]|string[] $types The query parameter types. * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
* *
* @return mixed|false False is returned if no rows are found. * @return mixed|false False is returned if no rows are found.
* *
* @throws DBALException * @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. * Whether an actual connection to the database is established.
*
* @return bool
*/ */
public function isConnected() public function isConnected() : bool
{ {
return $this->isConnected; return $this->isConnected;
} }
...@@ -572,7 +506,7 @@ class Connection implements DriverConnection ...@@ -572,7 +506,7 @@ class Connection implements DriverConnection
* *
* @return bool TRUE if a transaction is currently active, FALSE otherwise. * @return bool TRUE if a transaction is currently active, FALSE otherwise.
*/ */
public function isTransactionActive() public function isTransactionActive() : bool
{ {
return $this->transactionNestingLevel > 0; return $this->transactionNestingLevel > 0;
} }
...@@ -580,10 +514,10 @@ class Connection implements DriverConnection ...@@ -580,10 +514,10 @@ class Connection implements DriverConnection
/** /**
* Adds identifier condition to the query components * Adds identifier condition to the query components
* *
* @param mixed[] $identifier Map of key columns to their values * @param array<string, mixed> $identifier Map of key columns to their values
* @param string[] $columns Column names * @param array<int, string> $columns Column names
* @param mixed[] $values Column values * @param array<int, mixed> $values Column values
* @param string[] $conditions Key conditions * @param array<int, string> $conditions Key conditions
* *
* @throws DBALException * @throws DBALException
*/ */
...@@ -612,16 +546,16 @@ class Connection implements DriverConnection ...@@ -612,16 +546,16 @@ class Connection implements DriverConnection
* *
* Table expression and columns are not escaped and are not safe for user-input. * 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 string $table The SQL expression of the table on which to delete.
* @param mixed[] $identifier The deletion criteria. An associative array containing column-value pairs. * @param array<string, mixed> $identifier The deletion criteria. An associative array containing column-value pairs.
* @param int[]|string[] $types The types of identifiers. * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
* *
* @return int The number of affected rows. * @return int The number of affected rows.
* *
* @throws DBALException * @throws DBALException
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function delete($tableExpression, array $identifier, array $types = []) public function delete(string $table, array $identifier, array $types = []) : int
{ {
if (empty($identifier)) { if (empty($identifier)) {
throw EmptyCriteriaNotAllowed::new(); throw EmptyCriteriaNotAllowed::new();
...@@ -632,7 +566,7 @@ class Connection implements DriverConnection ...@@ -632,7 +566,7 @@ class Connection implements DriverConnection
$this->addIdentifierCondition($identifier, $columns, $values, $conditions); $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
return $this->executeUpdate( return $this->executeUpdate(
'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions), 'DELETE FROM ' . $table . ' WHERE ' . implode(' AND ', $conditions),
$values, $values,
is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
); );
...@@ -640,10 +574,8 @@ class Connection implements DriverConnection ...@@ -640,10 +574,8 @@ class Connection implements DriverConnection
/** /**
* Closes the connection. * Closes the connection.
*
* @return void
*/ */
public function close() public function close() : void
{ {
$this->_conn = null; $this->_conn = null;
...@@ -654,14 +586,12 @@ class Connection implements DriverConnection ...@@ -654,14 +586,12 @@ class Connection implements DriverConnection
* Sets the transaction isolation level. * Sets the transaction isolation level.
* *
* @param int $level The level to set. * @param int $level The level to set.
*
* @return int
*/ */
public function setTransactionIsolation($level) public function setTransactionIsolation(int $level) : void
{ {
$this->transactionIsolationLevel = $level; $this->transactionIsolationLevel = $level;
return $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level)); $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level));
} }
/** /**
...@@ -669,7 +599,7 @@ class Connection implements DriverConnection ...@@ -669,7 +599,7 @@ class Connection implements DriverConnection
* *
* @return int The current transaction isolation level. * @return int The current transaction isolation level.
*/ */
public function getTransactionIsolation() public function getTransactionIsolation() : int
{ {
if ($this->transactionIsolationLevel === null) { if ($this->transactionIsolationLevel === null) {
$this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel(); $this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel();
...@@ -683,16 +613,16 @@ class Connection implements DriverConnection ...@@ -683,16 +613,16 @@ class Connection implements DriverConnection
* *
* Table expression and columns are not escaped and are not safe for user-input. * 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 string $table The SQL expression of the table to update quoted or unquoted.
* @param mixed[] $data An associative array containing column-value pairs. * @param array<string, mixed> $data An associative array containing column-value pairs.
* @param mixed[] $identifier The update criteria. An associative array containing column-value pairs. * @param array<string, 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 array<int, int|string>|array<string, int|string> $types The query parameter types.
* *
* @return int The number of affected rows. * @return int The number of affected rows.
* *
* @throws DBALException * @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 = []; $columns = $values = $conditions = $set = [];
...@@ -708,7 +638,7 @@ class Connection implements DriverConnection ...@@ -708,7 +638,7 @@ class Connection implements DriverConnection
$types = $this->extractTypeValues($columns, $types); $types = $this->extractTypeValues($columns, $types);
} }
$sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set) $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $set)
. ' WHERE ' . implode(' AND ', $conditions); . ' WHERE ' . implode(' AND ', $conditions);
return $this->executeUpdate($sql, $values, $types); return $this->executeUpdate($sql, $values, $types);
...@@ -719,18 +649,18 @@ class Connection implements DriverConnection ...@@ -719,18 +649,18 @@ class Connection implements DriverConnection
* *
* Table expression and columns are not escaped and are not safe for user-input. * 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 string $table The SQL expression of the table to insert data into, quoted or unquoted.
* @param mixed[] $data An associative array containing column-value pairs. * @param array<string, mixed> $data An associative array containing column-value pairs.
* @param int[]|string[] $types Types of the inserted data. * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
* *
* @return int The number of affected rows. * @return int The number of affected rows.
* *
* @throws DBALException * @throws DBALException
*/ */
public function insert($tableExpression, array $data, array $types = []) public function insert(string $table, array $data, array $types = []) : int
{ {
if (empty($data)) { if (empty($data)) {
return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()'); return $this->executeUpdate('INSERT INTO ' . $table . ' () VALUES ()');
} }
$columns = []; $columns = [];
...@@ -744,7 +674,7 @@ class Connection implements DriverConnection ...@@ -744,7 +674,7 @@ class Connection implements DriverConnection
} }
return $this->executeUpdate( return $this->executeUpdate(
'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' . 'INSERT INTO ' . $table . ' (' . implode(', ', $columns) . ')' .
' VALUES (' . implode(', ', $set) . ')', ' VALUES (' . implode(', ', $set) . ')',
$values, $values,
is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
...@@ -754,16 +684,16 @@ class Connection implements DriverConnection ...@@ -754,16 +684,16 @@ class Connection implements DriverConnection
/** /**
* Extract ordered type list from an ordered column list and type map. * Extract ordered type list from an ordered column list and type map.
* *
* @param int[]|string[] $columnList * @param array<int, string> $columnList
* @param int[]|string[] $types * @param array<int, int|string> $types The query parameter types.
* *
* @return int[]|string[] * @return array<int, int>|array<int, string>
*/ */
private function extractTypeValues(array $columnList, array $types) private function extractTypeValues(array $columnList, array $types)
{ {
$typeValues = []; $typeValues = [];
foreach ($columnList as $columnIndex => $columnName) { foreach ($columnList as $columnName) {
$typeValues[] = $types[$columnName] ?? ParameterType::STRING; $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
} }
...@@ -780,13 +710,13 @@ class Connection implements DriverConnection ...@@ -780,13 +710,13 @@ class Connection implements DriverConnection
* you SHOULD use them. In general, they end up causing way more * you SHOULD use them. In general, they end up causing way more
* problems than they solve. * 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);
} }
/** /**
...@@ -800,15 +730,15 @@ class Connection implements DriverConnection ...@@ -800,15 +730,15 @@ class Connection implements DriverConnection
/** /**
* Prepares and executes an SQL query and returns the result as an associative array. * Prepares and executes an SQL query and returns the result as an associative array.
* *
* @param string $sql The SQL query. * @param string $query The SQL query.
* @param mixed[] $params The query parameters. * @param array<int, mixed>|array<string, mixed> $params The query parameters.
* @param int[]|string[] $types The query parameter types. * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
* *
* @return mixed[] * @return array<int, mixed>
*/ */
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();
} }
/** /**
...@@ -838,8 +768,8 @@ class Connection implements DriverConnection ...@@ -838,8 +768,8 @@ class Connection implements DriverConnection
* If an SQLLogger is configured, the execution is logged. * If an SQLLogger is configured, the execution is logged.
* *
* @param string $query The SQL query to execute. * @param string $query The SQL query to execute.
* @param mixed[] $params The parameters to bind to the query, if any. * @param array<int, mixed>|array<string, mixed> $params The parameters to bind to the query, if any.
* @param int[]|string[] $types The types the previous parameters are in. * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
* @param QueryCacheProfile|null $qcp The query cache profile, optional. * @param QueryCacheProfile|null $qcp The query cache profile, optional.
* *
* @return ResultStatement The executed statement. * @return ResultStatement The executed statement.
...@@ -886,13 +816,13 @@ class Connection implements DriverConnection ...@@ -886,13 +816,13 @@ class Connection implements DriverConnection
* Executes a caching query. * Executes a caching query.
* *
* @param string $query The SQL query to execute. * @param string $query The SQL query to execute.
* @param mixed[] $params The parameters to bind to the query, if any. * @param array<int, mixed>|array<string, mixed> $params The parameters to bind to the query, if any.
* @param int[]|string[] $types The types the previous parameters are in. * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
* @param QueryCacheProfile $qcp The query cache profile. * @param QueryCacheProfile $qcp The query cache profile.
* *
* @throws CacheException * @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(); $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();
...@@ -931,14 +861,14 @@ class Connection implements DriverConnection ...@@ -931,14 +861,14 @@ class Connection implements DriverConnection
* applying a given projection/transformation function on each row of the result. * applying a given projection/transformation function on each row of the result.
* *
* @param string $query The SQL query to execute. * @param string $query The SQL query to execute.
* @param mixed[] $params The parameters, if any. * @param array<int, mixed>|array<string, mixed> $params The parameters, if any.
* @param Closure $function The transformation function that is applied on each row. * @param Closure $function The transformation function that is applied on each row.
* The function receives a single parameter, an array, that * The function receives a single parameter, an array, that
* represents a row of the result set. * represents a row of the result set.
* *
* @return mixed[] The projected result of the query. * @return array<int, mixed> 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 = []; $result = [];
$stmt = $this->executeQuery($query, $params); $stmt = $this->executeQuery($query, $params);
...@@ -982,8 +912,8 @@ class Connection implements DriverConnection ...@@ -982,8 +912,8 @@ class Connection implements DriverConnection
* This method supports PDO binding types as well as DBAL mapping types. * This method supports PDO binding types as well as DBAL mapping types.
* *
* @param string $query The SQL query. * @param string $query The SQL query.
* @param mixed[] $params The query parameters. * @param array<int, mixed>|array<string, mixed> $params The query parameters.
* @param int[]|string[] $types The parameter types. * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
* *
* @throws DBALException * @throws DBALException
*/ */
...@@ -1045,7 +975,7 @@ class Connection implements DriverConnection ...@@ -1045,7 +975,7 @@ class Connection implements DriverConnection
* *
* @return int The nesting level. A value of 0 means there's no active transaction. * @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; return $this->transactionNestingLevel;
} }
...@@ -1058,13 +988,13 @@ class Connection implements DriverConnection ...@@ -1058,13 +988,13 @@ class Connection implements DriverConnection
* because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
* columns or sequences. * 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. * @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);
} }
/** /**
...@@ -1098,13 +1028,9 @@ class Connection implements DriverConnection ...@@ -1098,13 +1028,9 @@ class Connection implements DriverConnection
/** /**
* Sets if nested transactions should use savepoints. * Sets if nested transactions should use savepoints.
* *
* @param bool $nestTransactionsWithSavepoints
*
* @return void
*
* @throws ConnectionException * @throws ConnectionException
*/ */
public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints) public function setNestTransactionsWithSavepoints(bool $nestTransactionsWithSavepoints) : void
{ {
if ($this->transactionNestingLevel > 0) { if ($this->transactionNestingLevel > 0) {
throw MayNotAlterNestedTransactionWithSavepointsInTransaction::new(); throw MayNotAlterNestedTransactionWithSavepointsInTransaction::new();
...@@ -1114,15 +1040,13 @@ class Connection implements DriverConnection ...@@ -1114,15 +1040,13 @@ class Connection implements DriverConnection
throw SavepointsNotSupported::new(); throw SavepointsNotSupported::new();
} }
$this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints; $this->nestTransactionsWithSavepoints = $nestTransactionsWithSavepoints;
} }
/** /**
* Gets if nested transactions should use savepoints. * Gets if nested transactions should use savepoints.
*
* @return bool
*/ */
public function getNestTransactionsWithSavepoints() public function getNestTransactionsWithSavepoints() : bool
{ {
return $this->nestTransactionsWithSavepoints; return $this->nestTransactionsWithSavepoints;
} }
...@@ -1274,11 +1198,9 @@ class Connection implements DriverConnection ...@@ -1274,11 +1198,9 @@ class Connection implements DriverConnection
* *
* @param string $savepoint The name of the savepoint to create. * @param string $savepoint The name of the savepoint to create.
* *
* @return void
*
* @throws ConnectionException * @throws ConnectionException
*/ */
public function createSavepoint($savepoint) public function createSavepoint(string $savepoint) : void
{ {
if (! $this->getDatabasePlatform()->supportsSavepoints()) { if (! $this->getDatabasePlatform()->supportsSavepoints()) {
throw SavepointsNotSupported::new(); throw SavepointsNotSupported::new();
...@@ -1292,11 +1214,9 @@ class Connection implements DriverConnection ...@@ -1292,11 +1214,9 @@ class Connection implements DriverConnection
* *
* @param string $savepoint The name of the savepoint to release. * @param string $savepoint The name of the savepoint to release.
* *
* @return void
*
* @throws ConnectionException * @throws ConnectionException
*/ */
public function releaseSavepoint($savepoint) public function releaseSavepoint(string $savepoint) : void
{ {
if (! $this->getDatabasePlatform()->supportsSavepoints()) { if (! $this->getDatabasePlatform()->supportsSavepoints()) {
throw SavepointsNotSupported::new(); throw SavepointsNotSupported::new();
...@@ -1314,11 +1234,9 @@ class Connection implements DriverConnection ...@@ -1314,11 +1234,9 @@ class Connection implements DriverConnection
* *
* @param string $savepoint The name of the savepoint to rollback to. * @param string $savepoint The name of the savepoint to rollback to.
* *
* @return void
*
* @throws ConnectionException * @throws ConnectionException
*/ */
public function rollbackSavepoint($savepoint) public function rollbackSavepoint(string $savepoint) : void
{ {
if (! $this->getDatabasePlatform()->supportsSavepoints()) { if (! $this->getDatabasePlatform()->supportsSavepoints()) {
throw SavepointsNotSupported::new(); throw SavepointsNotSupported::new();
...@@ -1329,10 +1247,8 @@ class Connection implements DriverConnection ...@@ -1329,10 +1247,8 @@ class Connection implements DriverConnection
/** /**
* Gets the wrapped driver connection. * Gets the wrapped driver connection.
*
* @return DriverConnection
*/ */
public function getWrappedConnection() public function getWrappedConnection() : DriverConnection
{ {
$this->connect(); $this->connect();
...@@ -1342,10 +1258,8 @@ class Connection implements DriverConnection ...@@ -1342,10 +1258,8 @@ class Connection implements DriverConnection
/** /**
* Gets the SchemaManager that can be used to inspect or change the * Gets the SchemaManager that can be used to inspect or change the
* database schema through the connection. * database schema through the connection.
*
* @return AbstractSchemaManager
*/ */
public function getSchemaManager() public function getSchemaManager() : AbstractSchemaManager
{ {
if ($this->_schemaManager === null) { if ($this->_schemaManager === null) {
$this->_schemaManager = $this->_driver->getSchemaManager($this); $this->_schemaManager = $this->_driver->getSchemaManager($this);
...@@ -1358,11 +1272,9 @@ class Connection implements DriverConnection ...@@ -1358,11 +1272,9 @@ class Connection implements DriverConnection
* Marks the current transaction so that the only possible * Marks the current transaction so that the only possible
* outcome for the transaction to be rolled back. * outcome for the transaction to be rolled back.
* *
* @return void
*
* @throws ConnectionException If no transaction is active. * @throws ConnectionException If no transaction is active.
*/ */
public function setRollbackOnly() public function setRollbackOnly() : void
{ {
if ($this->transactionNestingLevel === 0) { if ($this->transactionNestingLevel === 0) {
throw NoActiveTransaction::new(); throw NoActiveTransaction::new();
...@@ -1373,11 +1285,9 @@ class Connection implements DriverConnection ...@@ -1373,11 +1285,9 @@ class Connection implements DriverConnection
/** /**
* Checks whether the current transaction is marked for rollback only. * Checks whether the current transaction is marked for rollback only.
* *
* @return bool
*
* @throws ConnectionException If no transaction is active. * @throws ConnectionException If no transaction is active.
*/ */
public function isRollbackOnly() public function isRollbackOnly() : bool
{ {
if ($this->transactionNestingLevel === 0) { if ($this->transactionNestingLevel === 0) {
throw NoActiveTransaction::new(); throw NoActiveTransaction::new();
...@@ -1395,7 +1305,7 @@ class Connection implements DriverConnection ...@@ -1395,7 +1305,7 @@ class Connection implements DriverConnection
* *
* @return mixed The converted value. * @return mixed The converted value.
*/ */
public function convertToDatabaseValue($value, $type) public function convertToDatabaseValue($value, string $type)
{ {
return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform()); return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform());
} }
...@@ -1409,7 +1319,7 @@ class Connection implements DriverConnection ...@@ -1409,7 +1319,7 @@ class Connection implements DriverConnection
* *
* @return mixed The converted 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()); return Type::getType($type)->convertToPHPValue($value, $this->getDatabasePlatform());
} }
...@@ -1422,8 +1332,8 @@ class Connection implements DriverConnection ...@@ -1422,8 +1332,8 @@ class Connection implements DriverConnection
* raw PDOStatement instances. * raw PDOStatement instances.
* *
* @param DriverStatement $stmt The statement to bind the values to. * @param DriverStatement $stmt The statement to bind the values to.
* @param mixed[] $params The map/list of named/positional parameters. * @param array<int, mixed>|array<string, mixed> $params The map/list of named/positional parameters.
* @param int[]|string[] $types The parameter types. * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
*/ */
private function _bindTypedValues(DriverStatement $stmt, array $params, array $types) : void private function _bindTypedValues(DriverStatement $stmt, array $params, array $types) : void
{ {
...@@ -1463,9 +1373,9 @@ class Connection implements DriverConnection ...@@ -1463,9 +1373,9 @@ class Connection implements DriverConnection
* @param mixed $value The value to bind. * @param mixed $value The value to bind.
* @param int|string|null $type The type to bind (PDO or DBAL). * @param int|string|null $type The type to bind (PDO or DBAL).
* *
* @return mixed[] [0] => the (escaped) value, [1] => the binding type. * @return array<int, mixed> [0] => the (escaped) value, [1] => the binding type.
*/ */
private function getBindingInfo($value, $type) private function getBindingInfo($value, $type) : array
{ {
if (is_string($type)) { if (is_string($type)) {
$type = Type::getType($type); $type = Type::getType($type);
...@@ -1486,12 +1396,12 @@ class Connection implements DriverConnection ...@@ -1486,12 +1396,12 @@ class Connection implements DriverConnection
* @internal This is a purely internal method. If you rely on this method, you are advised to * @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. * copy/paste the code as this method may change, or be removed without prior notice.
* *
* @param mixed[] $params * @param array<int, mixed>|array<string, mixed> $params
* @param int[]|string[] $types * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
* *
* @return mixed[] * @return array<int, mixed>|array<string, mixed>
*/ */
public function resolveParams(array $params, array $types) public function resolveParams(array $params, array $types) : array
{ {
$resolvedParams = []; $resolvedParams = [];
...@@ -1529,10 +1439,8 @@ class Connection implements DriverConnection ...@@ -1529,10 +1439,8 @@ class Connection implements DriverConnection
/** /**
* Creates a new instance of a SQL query builder. * Creates a new instance of a SQL query builder.
*
* @return QueryBuilder
*/ */
public function createQueryBuilder() public function createQueryBuilder() : QueryBuilder
{ {
return new Query\QueryBuilder($this); return new Query\QueryBuilder($this);
} }
......
...@@ -67,14 +67,15 @@ use function count; ...@@ -67,14 +67,15 @@ use function count;
* ) * )
* )); * ));
* *
* 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 class MasterSlaveConnection extends Connection
{ {
/** /**
* Master and slave connection (one of the randomly picked slaves). * Master and slave connection (one of the randomly picked slaves).
* *
* @var DriverConnection[]|null[] * @var array<string, DriverConnection|null>
*/ */
protected $connections = ['master' => null, 'slave' => null]; protected $connections = ['master' => null, 'slave' => null];
...@@ -89,12 +90,16 @@ class MasterSlaveConnection extends Connection ...@@ -89,12 +90,16 @@ class MasterSlaveConnection extends Connection
/** /**
* Creates Master Slave Connection. * Creates Master Slave Connection.
* *
* @param mixed[] $params * @param array<string, mixed> $params
* *
* @throws InvalidArgumentException * @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'])) { if (! isset($params['slaves'], $params['master'])) {
throw new InvalidArgumentException('master or slaves configuration missing'); throw new InvalidArgumentException('master or slaves configuration missing');
} }
...@@ -114,10 +119,8 @@ class MasterSlaveConnection extends Connection ...@@ -114,10 +119,8 @@ class MasterSlaveConnection extends Connection
/** /**
* Checks if the connection is currently towards the master or not. * 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']; return $this->_conn !== null && $this->_conn === $this->connections['master'];
} }
...@@ -179,12 +182,8 @@ class MasterSlaveConnection extends Connection ...@@ -179,12 +182,8 @@ class MasterSlaveConnection extends Connection
/** /**
* Connects to a specific connection. * Connects to a specific connection.
*
* @param string $connectionName
*
* @return DriverConnection
*/ */
protected function connectTo($connectionName) protected function connectTo(string $connectionName) : DriverConnection
{ {
$params = $this->getParams(); $params = $this->getParams();
...@@ -199,12 +198,11 @@ class MasterSlaveConnection extends Connection ...@@ -199,12 +198,11 @@ class MasterSlaveConnection extends Connection
} }
/** /**
* @param string $connectionName * @param array<string, mixed> $params
* @param mixed[] $params
* *
* @return mixed * @return array<string, mixed>
*/ */
protected function chooseConnectionConfiguration($connectionName, $params) protected function chooseConnectionConfiguration(string $connectionName, array $params) : array
{ {
if ($connectionName === 'master') { if ($connectionName === 'master') {
return $params['master']; return $params['master'];
...@@ -262,17 +260,17 @@ class MasterSlaveConnection extends Connection ...@@ -262,17 +260,17 @@ class MasterSlaveConnection extends Connection
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function delete($tableName, array $identifier, array $types = []) public function delete(string $table, array $identifier, array $types = []) : int
{ {
$this->connect('master'); $this->connect('master');
return parent::delete($tableName, $identifier, $types); return parent::delete($table, $identifier, $types);
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function close() public function close() : void
{ {
unset($this->connections['master'], $this->connections['slave']); unset($this->connections['master'], $this->connections['slave']);
...@@ -285,21 +283,21 @@ class MasterSlaveConnection extends Connection ...@@ -285,21 +283,21 @@ class MasterSlaveConnection extends Connection
/** /**
* {@inheritDoc} * {@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'); $this->connect('master');
return parent::update($tableName, $data, $identifier, $types); return parent::update($table, $data, $identifier, $types);
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function insert($tableName, array $data, array $types = []) public function insert(string $table, array $data, array $types = []) : int
{ {
$this->connect('master'); $this->connect('master');
return parent::insert($tableName, $data, $types); return parent::insert($table, $data, $types);
} }
/** /**
...@@ -315,7 +313,7 @@ class MasterSlaveConnection extends Connection ...@@ -315,7 +313,7 @@ class MasterSlaveConnection extends Connection
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function createSavepoint($savepoint) public function createSavepoint(string $savepoint) : void
{ {
$this->connect('master'); $this->connect('master');
...@@ -325,7 +323,7 @@ class MasterSlaveConnection extends Connection ...@@ -325,7 +323,7 @@ class MasterSlaveConnection extends Connection
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function releaseSavepoint($savepoint) public function releaseSavepoint(string $savepoint) : void
{ {
$this->connect('master'); $this->connect('master');
...@@ -335,7 +333,7 @@ class MasterSlaveConnection extends Connection ...@@ -335,7 +333,7 @@ class MasterSlaveConnection extends Connection
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function rollbackSavepoint($savepoint) public function rollbackSavepoint(string $savepoint) : void
{ {
$this->connect('master'); $this->connect('master');
......
...@@ -48,7 +48,7 @@ interface Driver ...@@ -48,7 +48,7 @@ interface Driver
/** /**
* Gets the name of the database connected to for this driver. * 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; public function getDatabase(Connection $conn) : ?string;
} }
...@@ -40,12 +40,8 @@ interface Connection ...@@ -40,12 +40,8 @@ interface Connection
/** /**
* Returns the ID of the last inserted row or sequence value. * 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. * Initiates a transaction.
......
...@@ -29,18 +29,14 @@ class DB2Connection implements Connection, ServerInfoAwareConnection ...@@ -29,18 +29,14 @@ class DB2Connection implements Connection, ServerInfoAwareConnection
private $conn = null; private $conn = null;
/** /**
* @param mixed[] $params * @param array<string, mixed> $params
* @param string $username * @param array<string, mixed> $driverOptions
* @param string $password
* @param mixed[] $driverOptions
* *
* @throws DB2Exception * @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 (isset($params['persistent']) && $params['persistent'] === true) {
if ($isPersistent) {
$conn = db2_pconnect($params['dbname'], $username, $password, $driverOptions); $conn = db2_pconnect($params['dbname'], $username, $password, $driverOptions);
} else { } else {
$conn = db2_connect($params['dbname'], $username, $password, $driverOptions); $conn = db2_connect($params['dbname'], $username, $password, $driverOptions);
...@@ -56,7 +52,7 @@ class DB2Connection implements Connection, ServerInfoAwareConnection ...@@ -56,7 +52,7 @@ class DB2Connection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getServerVersion() public function getServerVersion() : string
{ {
/** @var stdClass $serverInfo */ /** @var stdClass $serverInfo */
$serverInfo = db2_server_info($this->conn); $serverInfo = db2_server_info($this->conn);
...@@ -67,7 +63,7 @@ class DB2Connection implements Connection, ServerInfoAwareConnection ...@@ -67,7 +63,7 @@ class DB2Connection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function requiresQueryForServerVersion() public function requiresQueryForServerVersion() : bool
{ {
return false; return false;
} }
...@@ -121,7 +117,7 @@ class DB2Connection implements Connection, ServerInfoAwareConnection ...@@ -121,7 +117,7 @@ class DB2Connection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function lastInsertId($name = null) public function lastInsertId(?string $name = null) : string
{ {
return db2_last_insert_id($this->conn); return db2_last_insert_id($this->conn);
} }
......
...@@ -39,14 +39,12 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar ...@@ -39,14 +39,12 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar
private $conn; private $conn;
/** /**
* @param mixed[] $params * @param array<string, mixed> $params
* @param string $username * @param array<int, mixed> $driverOptions
* @param string $password
* @param mixed[] $driverOptions
* *
* @throws MysqliException * @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'); $port = $params['port'] ?? (int) ini_get('mysqli.default_port');
...@@ -70,7 +68,8 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar ...@@ -70,7 +68,8 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar
$this->setSecureConnection($params); $this->setSecureConnection($params);
$this->setDriverOptions($driverOptions); $this->setDriverOptions($driverOptions);
set_error_handler(static function () { set_error_handler(static function () : bool {
return true;
}); });
try { try {
if (! $this->conn->real_connect($host, $username, $password, $dbname, $port, $socket, $flags)) { if (! $this->conn->real_connect($host, $username, $password, $dbname, $port, $socket, $flags)) {
...@@ -91,10 +90,8 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar ...@@ -91,10 +90,8 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar
* Retrieves mysqli native resource handle. * Retrieves mysqli native resource handle.
* *
* Could be used if part of your application is not using DBAL. * Could be used if part of your application is not using DBAL.
*
* @return mysqli
*/ */
public function getWrappedResourceHandle() public function getWrappedResourceHandle() : mysqli
{ {
return $this->conn; return $this->conn;
} }
...@@ -107,7 +104,7 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar ...@@ -107,7 +104,7 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar
* *
* @link https://jira.mariadb.org/browse/MDEV-4088 * @link https://jira.mariadb.org/browse/MDEV-4088
*/ */
public function getServerVersion() public function getServerVersion() : string
{ {
$serverInfos = $this->conn->get_server_info(); $serverInfos = $this->conn->get_server_info();
if (stripos($serverInfos, 'mariadb') !== false) { if (stripos($serverInfos, 'mariadb') !== false) {
...@@ -124,7 +121,7 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar ...@@ -124,7 +121,7 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function requiresQueryForServerVersion() public function requiresQueryForServerVersion() : bool
{ {
return false; return false;
} }
...@@ -171,9 +168,9 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar ...@@ -171,9 +168,9 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar
/** /**
* {@inheritdoc} * {@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 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar ...@@ -207,12 +204,12 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar
/** /**
* Apply the driver options to the connection. * Apply the driver options to the connection.
* *
* @param mixed[] $driverOptions * @param array<int, mixed> $driverOptions
* *
* @throws MysqliException When one of of the options is not supported. * @throws MysqliException When one of of the options is not supported.
* @throws MysqliException When applying doesn't work - e.g. due to incorrect value. * @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 = [ $supportedDriverOptions = [
MYSQLI_OPT_CONNECT_TIMEOUT, MYSQLI_OPT_CONNECT_TIMEOUT,
...@@ -262,11 +259,11 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar ...@@ -262,11 +259,11 @@ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwar
/** /**
* Establish a secure connection * Establish a secure connection
* *
* @param mixed[] $params * @param array<string, mixed> $params
* *
* @throws MysqliException * @throws MysqliException
*/ */
private function setSecureConnection(array $params) private function setSecureConnection(array $params) : void
{ {
if (! isset($params['ssl_key']) && if (! isset($params['ssl_key']) &&
! isset($params['ssl_cert']) && ! isset($params['ssl_cert']) &&
......
...@@ -37,22 +37,15 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection ...@@ -37,22 +37,15 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection
/** /**
* Creates a Connection to an Oracle Database using oci8 extension. * 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 * @throws OCI8Exception
*/ */
public function __construct( public function __construct(
$username, string $username,
$password, string $password,
$db, string $db,
$charset = '', string $charset = '',
$sessionMode = OCI_DEFAULT, int $sessionMode = OCI_DEFAULT,
$persistent = false bool $persistent = false
) { ) {
$dbh = $persistent $dbh = $persistent
? @oci_pconnect($username, $password, $db, $charset, $sessionMode) ? @oci_pconnect($username, $password, $db, $charset, $sessionMode)
...@@ -71,7 +64,7 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection ...@@ -71,7 +64,7 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection
* @throws UnexpectedValueException If the version string returned by the database server * @throws UnexpectedValueException If the version string returned by the database server
* does not contain a parsable version number. * does not contain a parsable version number.
*/ */
public function getServerVersion() public function getServerVersion() : string
{ {
$version = oci_server_version($this->dbh); $version = oci_server_version($this->dbh);
...@@ -95,7 +88,7 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection ...@@ -95,7 +88,7 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function requiresQueryForServerVersion() public function requiresQueryForServerVersion() : bool
{ {
return false; return false;
} }
...@@ -141,10 +134,10 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection ...@@ -141,10 +134,10 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function lastInsertId($name = null) public function lastInsertId(?string $name = null) : string
{ {
if ($name === null) { if ($name === null) {
return false; throw new OCI8Exception('The driver does not support identity columns.');
} }
$sql = 'SELECT ' . $name . '.CURRVAL FROM DUAL'; $sql = 'SELECT ' . $name . '.CURRVAL FROM DUAL';
...@@ -155,15 +148,13 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection ...@@ -155,15 +148,13 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection
throw new OCI8Exception('lastInsertId failed: Query was executed but no result was returned.'); throw new OCI8Exception('lastInsertId failed: Query was executed but no result was returned.');
} }
return (int) $result; return $result;
} }
/** /**
* Returns the current execution mode. * Returns the current execution mode.
*
* @return int
*/ */
public function getExecuteMode() public function getExecuteMode() : int
{ {
return $this->executeMode; return $this->executeMode;
} }
......
...@@ -18,17 +18,14 @@ class PDOConnection implements Connection, ServerInfoAwareConnection ...@@ -18,17 +18,14 @@ class PDOConnection implements Connection, ServerInfoAwareConnection
private $connection; private $connection;
/** /**
* @param string $dsn * @param array<int, mixed> $options
* @param string|null $user
* @param string|null $password
* @param mixed[]|null $options
* *
* @throws PDOException In case of an error. * @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 { 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); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $exception) { } catch (\PDOException $exception) {
throw new PDOException($exception); throw new PDOException($exception);
...@@ -50,7 +47,7 @@ class PDOConnection implements Connection, ServerInfoAwareConnection ...@@ -50,7 +47,7 @@ class PDOConnection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getServerVersion() public function getServerVersion() : string
{ {
return $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION); return $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
} }
...@@ -95,7 +92,7 @@ class PDOConnection implements Connection, ServerInfoAwareConnection ...@@ -95,7 +92,7 @@ class PDOConnection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function lastInsertId($name = null) public function lastInsertId(?string $name = null) : string
{ {
try { try {
if ($name === null) { if ($name === null) {
...@@ -111,7 +108,7 @@ class PDOConnection implements Connection, ServerInfoAwareConnection ...@@ -111,7 +108,7 @@ class PDOConnection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function requiresQueryForServerVersion() public function requiresQueryForServerVersion() : bool
{ {
return false; return false;
} }
......
...@@ -17,7 +17,7 @@ class Connection extends PDOConnection ...@@ -17,7 +17,7 @@ class Connection extends PDOConnection
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function lastInsertId($name = null) public function lastInsertId(?string $name = null) : string
{ {
if ($name === null) { if ($name === null) {
return parent::lastInsertId($name); return parent::lastInsertId($name);
......
...@@ -37,7 +37,7 @@ class SQLAnywhereConnection implements Connection, ServerInfoAwareConnection ...@@ -37,7 +37,7 @@ class SQLAnywhereConnection implements Connection, ServerInfoAwareConnection
* *
* @throws SQLAnywhereException * @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); $this->connection = $persistent ? @sasql_pconnect($dsn) : @sasql_connect($dsn);
...@@ -97,7 +97,7 @@ class SQLAnywhereConnection implements Connection, ServerInfoAwareConnection ...@@ -97,7 +97,7 @@ class SQLAnywhereConnection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getServerVersion() public function getServerVersion() : string
{ {
$version = $this->query("SELECT PROPERTY('ProductVersion')")->fetchColumn(); $version = $this->query("SELECT PROPERTY('ProductVersion')")->fetchColumn();
...@@ -109,7 +109,7 @@ class SQLAnywhereConnection implements Connection, ServerInfoAwareConnection ...@@ -109,7 +109,7 @@ class SQLAnywhereConnection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function lastInsertId($name = null) public function lastInsertId(?string $name = null) : string
{ {
if ($name === null) { if ($name === null) {
return sasql_insert_id($this->connection); return sasql_insert_id($this->connection);
...@@ -148,7 +148,7 @@ class SQLAnywhereConnection implements Connection, ServerInfoAwareConnection ...@@ -148,7 +148,7 @@ class SQLAnywhereConnection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function requiresQueryForServerVersion() public function requiresQueryForServerVersion() : bool
{ {
return true; return true;
} }
......
...@@ -9,21 +9,15 @@ namespace Doctrine\DBAL\Driver\SQLSrv; ...@@ -9,21 +9,15 @@ namespace Doctrine\DBAL\Driver\SQLSrv;
*/ */
class LastInsertId class LastInsertId
{ {
/** @var int */ /** @var string|null */
private $id; private $id;
/** public function setId(?string $id) : void
* @param int $id
*/
public function setId($id)
{ {
$this->id = $id; $this->id = $id;
} }
/** public function getId() : ?string
* @return int
*/
public function getId()
{ {
return $this->id; return $this->id;
} }
......
...@@ -30,12 +30,11 @@ class SQLSrvConnection implements Connection, ServerInfoAwareConnection ...@@ -30,12 +30,11 @@ class SQLSrvConnection implements Connection, ServerInfoAwareConnection
protected $lastInsertId; protected $lastInsertId;
/** /**
* @param string $serverName * @param array<string, mixed> $connectionOptions
* @param mixed[] $connectionOptions
* *
* @throws SQLSrvException * @throws SQLSrvException
*/ */
public function __construct($serverName, $connectionOptions) public function __construct(string $serverName, array $connectionOptions)
{ {
if (! sqlsrv_configure('WarningsReturnAsErrors', 0)) { if (! sqlsrv_configure('WarningsReturnAsErrors', 0)) {
throw SQLSrvException::fromSqlSrvErrors(); throw SQLSrvException::fromSqlSrvErrors();
...@@ -54,7 +53,7 @@ class SQLSrvConnection implements Connection, ServerInfoAwareConnection ...@@ -54,7 +53,7 @@ class SQLSrvConnection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getServerVersion() public function getServerVersion() : string
{ {
$serverInfo = sqlsrv_server_info($this->conn); $serverInfo = sqlsrv_server_info($this->conn);
...@@ -64,7 +63,7 @@ class SQLSrvConnection implements Connection, ServerInfoAwareConnection ...@@ -64,7 +63,7 @@ class SQLSrvConnection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function requiresQueryForServerVersion() public function requiresQueryForServerVersion() : bool
{ {
return false; return false;
} }
...@@ -119,7 +118,7 @@ class SQLSrvConnection implements Connection, ServerInfoAwareConnection ...@@ -119,7 +118,7 @@ class SQLSrvConnection implements Connection, ServerInfoAwareConnection
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function lastInsertId($name = null) public function lastInsertId(?string $name = null) : string
{ {
if ($name !== null) { if ($name !== null) {
$stmt = $this->prepare('SELECT CONVERT(VARCHAR(MAX), current_value) FROM sys.sequences WHERE name = ?'); $stmt = $this->prepare('SELECT CONVERT(VARCHAR(MAX), current_value) FROM sys.sequences WHERE name = ?');
......
...@@ -11,15 +11,13 @@ interface ServerInfoAwareConnection ...@@ -11,15 +11,13 @@ interface ServerInfoAwareConnection
{ {
/** /**
* Returns the version number of the database server connected to. * 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. * 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. * @return bool True if a query is required to retrieve the database server version, false otherwise.
*/ */
public function requiresQueryForServerVersion(); public function requiresQueryForServerVersion() : bool;
} }
...@@ -82,18 +82,12 @@ class Connection extends \Doctrine\DBAL\Connection ...@@ -82,18 +82,12 @@ class Connection extends \Doctrine\DBAL\Connection
} }
} }
/** public function getPortability() : int
* @return int
*/
public function getPortability()
{ {
return $this->portability; return $this->portability;
} }
/** public function getFetchCase() : ?int
* @return int
*/
public function getFetchCase()
{ {
return $this->case; return $this->case;
} }
......
...@@ -957,7 +957,13 @@ abstract class AbstractSchemaManager ...@@ -957,7 +957,13 @@ abstract class AbstractSchemaManager
*/ */
public function getSchemaSearchPaths() : array public function getSchemaSearchPaths() : array
{ {
return [$this->_conn->getDatabase()]; $database = $this->_conn->getDatabase();
if ($database !== null) {
return [$database];
}
return [];
} }
/** /**
......
...@@ -8,9 +8,7 @@ use Doctrine\DBAL\Platforms\DB2Platform; ...@@ -8,9 +8,7 @@ use Doctrine\DBAL\Platforms\DB2Platform;
use Doctrine\DBAL\Types\Type; use Doctrine\DBAL\Types\Type;
use const CASE_LOWER; use const CASE_LOWER;
use function array_change_key_case; use function array_change_key_case;
use function assert;
use function is_resource; use function is_resource;
use function is_string;
use function preg_match; use function preg_match;
use function str_replace; use function str_replace;
use function strpos; use function strpos;
...@@ -30,12 +28,9 @@ class DB2SchemaManager extends AbstractSchemaManager ...@@ -30,12 +28,9 @@ class DB2SchemaManager extends AbstractSchemaManager
*/ */
public function listTableNames() : array public function listTableNames() : array
{ {
$username = $this->_conn->getUsername(); $sql = $this->_platform->getListTablesSQL() . ' AND CREATOR = CURRENT_USER';
assert(is_string($username));
$sql = $this->_platform->getListTablesSQL() . ' AND CREATOR = UPPER(?)'; $tables = $this->_conn->fetchAll($sql);
$tables = $this->_conn->fetchAll($sql, [$username]);
return $this->filterAssetNames($this->_getPortableTablesList($tables)); return $this->filterAssetNames($this->_getPortableTablesList($tables));
} }
......
...@@ -53,13 +53,13 @@ use function sprintf; ...@@ -53,13 +53,13 @@ use function sprintf;
*/ */
class PoolingShardConnection extends Connection class PoolingShardConnection extends Connection
{ {
/** @var DriverConnection[] */ /** @var array<int, DriverConnection>|array<string, DriverConnection> */
private $activeConnections = []; private $activeConnections = [];
/** @var string|int|null */ /** @var string|int|null */
private $activeShardId; private $activeShardId;
/** @var mixed[] */ /** @var array<int, array<string, mixed>>|array<string, array<string, mixed>> */
private $connectionParameters = []; private $connectionParameters = [];
/** /**
...@@ -67,8 +67,12 @@ class PoolingShardConnection extends Connection ...@@ -67,8 +67,12 @@ class PoolingShardConnection extends Connection
* *
* @throws InvalidArgumentException * @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'])) { if (! isset($params['global'], $params['shards'])) {
throw new InvalidArgumentException('Connection Parameters require "global" and "shards" configurations.'); throw new InvalidArgumentException('Connection Parameters require "global" and "shards" configurations.');
} }
...@@ -119,51 +123,11 @@ class PoolingShardConnection extends Connection ...@@ -119,51 +123,11 @@ class PoolingShardConnection extends Connection
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getParams() public function getParams() : array
{ {
return $this->activeShardId ? $this->connectionParameters[$this->activeShardId] : $this->connectionParameters[0]; 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. * Connects to a given shard.
* *
...@@ -207,10 +171,8 @@ class PoolingShardConnection extends Connection ...@@ -207,10 +171,8 @@ class PoolingShardConnection extends Connection
* Connects to a specific connection. * Connects to a specific connection.
* *
* @param string|int $shardId * @param string|int $shardId
*
* @return \Doctrine\DBAL\Driver\Connection
*/ */
protected function connectTo($shardId) protected function connectTo($shardId) : DriverConnection
{ {
$params = $this->getParams(); $params = $this->getParams();
...@@ -226,10 +188,8 @@ class PoolingShardConnection extends Connection ...@@ -226,10 +188,8 @@ class PoolingShardConnection extends Connection
/** /**
* @param string|int|null $shardId * @param string|int|null $shardId
*
* @return bool
*/ */
public function isConnected($shardId = null) public function isConnected($shardId = null) : bool
{ {
if ($shardId === null) { if ($shardId === null) {
return $this->_conn !== null; return $this->_conn !== null;
...@@ -238,10 +198,7 @@ class PoolingShardConnection extends Connection ...@@ -238,10 +198,7 @@ class PoolingShardConnection extends Connection
return isset($this->activeConnections[$shardId]); return isset($this->activeConnections[$shardId]);
} }
/** public function close() : void
* @return void
*/
public function close()
{ {
$this->_conn = null; $this->_conn = null;
$this->activeConnections = []; $this->activeConnections = [];
......
...@@ -38,13 +38,13 @@ class ConnectionTest extends DbalTestCase ...@@ -38,13 +38,13 @@ class ConnectionTest extends DbalTestCase
/** @var Connection */ /** @var Connection */
private $connection; private $connection;
/** @var string[] */ /** @var array<string, mixed> */
protected $params = [ protected $params = [
'driver' => 'pdo_mysql', 'driver' => 'pdo_mysql',
'host' => 'localhost', 'host' => 'localhost',
'user' => 'root', 'user' => 'root',
'password' => 'password', 'password' => 'password',
'port' => '1234', 'port' => 1234,
]; ];
protected function setUp() : void protected function setUp() : void
...@@ -114,26 +114,6 @@ class ConnectionTest extends DbalTestCase ...@@ -114,26 +114,6 @@ class ConnectionTest extends DbalTestCase
self::assertInstanceOf(Configuration::class, $config); 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 public function testGetDriver() : void
{ {
self::assertInstanceOf(\Doctrine\DBAL\Driver\PDOMySql\Driver::class, $this->connection->getDriver()); self::assertInstanceOf(\Doctrine\DBAL\Driver\PDOMySql\Driver::class, $this->connection->getDriver());
......
...@@ -49,6 +49,6 @@ class OCI8ConnectionTest extends DbalFunctionalTestCase ...@@ -49,6 +49,6 @@ class OCI8ConnectionTest extends DbalFunctionalTestCase
$schema = $this->connection->getDatabase(); $schema = $this->connection->getDatabase();
$sequence = $platform->getIdentitySequenceName($schema . '.DBAL2595', 'id'); $sequence = $platform->getIdentitySequenceName($schema . '.DBAL2595', 'id');
self::assertSame(1, $this->driverConnection->lastInsertId($sequence)); self::assertEquals(1, $this->driverConnection->lastInsertId($sequence));
} }
} }
...@@ -237,7 +237,7 @@ class OracleSchemaManagerTest extends SchemaManagerFunctionalTestCase ...@@ -237,7 +237,7 @@ class OracleSchemaManagerTest extends SchemaManagerFunctionalTestCase
$otherTable->addColumn('id', Types::STRING); $otherTable->addColumn('id', Types::STRING);
TestUtil::getTempConnection()->getSchemaManager()->dropAndCreateTable($otherTable); 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); self::assertCount(7, $columns);
} }
......
...@@ -190,7 +190,8 @@ class WriteTest extends DbalFunctionalTestCase ...@@ -190,7 +190,8 @@ class WriteTest extends DbalFunctionalTestCase
$this->markTestSkipped("Test only works consistently on platforms that support sequences and don't support identity columns."); $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();
} }
/** /**
......
...@@ -33,14 +33,10 @@ final class DB2SchemaManagerTest extends TestCase ...@@ -33,14 +33,10 @@ final class DB2SchemaManagerTest extends TestCase
$platform = $this->createMock(DB2Platform::class); $platform = $this->createMock(DB2Platform::class);
$this->conn = $this $this->conn = $this
->getMockBuilder(Connection::class) ->getMockBuilder(Connection::class)
->onlyMethods(['fetchAll', 'getUsername']) ->onlyMethods(['fetchAll'])
->setConstructorArgs([['platform' => $platform], $driverMock, new Configuration(), $eventManager]) ->setConstructorArgs([['platform' => $platform], $driverMock, new Configuration(), $eventManager])
->getMock(); ->getMock();
$this->conn->expects($this->any())
->method('getUsername')
->willReturn('db2inst1');
$this->manager = new DB2SchemaManager($this->conn); $this->manager = new DB2SchemaManager($this->conn);
} }
......
...@@ -243,80 +243,4 @@ class PoolingShardConnectionTest extends TestCase ...@@ -243,80 +243,4 @@ class PoolingShardConnectionTest extends TestCase
'host' => 'foo', 'host' => 'foo',
], $conn->getParams()); ], $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());
}
} }
...@@ -48,7 +48,14 @@ class PoolingShardManagerTest extends TestCase ...@@ -48,7 +48,14 @@ class PoolingShardManagerTest extends TestCase
public function testSelectGlobal() : void public function testSelectGlobal() : void
{ {
$conn = $this->createConnectionMock(); $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') $conn->method('getParams')
->willReturn([ ->willReturn([
'shardChoser' => $this->createMock(ShardChoser::class), 'shardChoser' => $this->createMock(ShardChoser::class),
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment