|string>
+ * Binds parameters with known types previously bound to the statement
*/
- private function separateBoundValues()
+ private function bindTypedParameters()
{
$streams = $values = [];
$types = $this->types;
@@ -230,15 +225,19 @@ private function separateBoundValues()
$streams[$parameter] = $value;
$values[$parameter] = null;
continue;
- } else {
- $types[$parameter - 1] = static::$_paramTypeMap[ParameterType::STRING];
}
+
+ $types[$parameter - 1] = static::$_paramTypeMap[ParameterType::STRING];
}
$values[$parameter] = $value;
}
- return [$types, $values, $streams];
+ if (! $this->_stmt->bind_param($types, ...$values)) {
+ throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno);
+ }
+
+ $this->sendLongData($streams);
}
/**
@@ -270,7 +269,7 @@ private function sendLongData($streams)
*
* @return bool
*/
- private function _bindValues($values)
+ private function bindUntypedValues(array $values)
{
$params = [];
$types = str_repeat('s', count($values));
@@ -283,7 +282,7 @@ private function _bindValues($values)
}
/**
- * @return mixed[]|false
+ * @return mixed[]|false|null
*/
private function _fetch()
{
@@ -319,6 +318,7 @@ public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEX
}
$values = $this->_fetch();
+
if ($values === null) {
return false;
}
@@ -327,28 +327,23 @@ public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEX
throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno);
}
- switch ($fetchMode) {
- case FetchMode::NUMERIC:
- return $values;
+ if ($fetchMode === FetchMode::NUMERIC) {
+ return $values;
+ }
+
+ assert(is_array($this->_columnNames));
+ $assoc = array_combine($this->_columnNames, $values);
+ assert(is_array($assoc));
+ switch ($fetchMode) {
case FetchMode::ASSOCIATIVE:
- return array_combine($this->_columnNames, $values);
+ return $assoc;
case FetchMode::MIXED:
- $ret = array_combine($this->_columnNames, $values);
- $ret += $values;
-
- return $ret;
+ return $assoc + $values;
case FetchMode::STANDARD_OBJECT:
- $assoc = array_combine($this->_columnNames, $values);
- $ret = new stdClass();
-
- foreach ($assoc as $column => $value) {
- $ret->$column = $value;
- }
-
- return $ret;
+ return (object) $assoc;
default:
throw new MysqliException(sprintf("Unknown fetch type '%s'", $fetchMode));
diff --git a/lib/Doctrine/DBAL/Driver/OCI8/Driver.php b/lib/Doctrine/DBAL/Driver/OCI8/Driver.php
index 533db04dcfc..8d41098bba5 100644
--- a/lib/Doctrine/DBAL/Driver/OCI8/Driver.php
+++ b/lib/Doctrine/DBAL/Driver/OCI8/Driver.php
@@ -24,10 +24,10 @@ public function connect(array $params, $username = null, $password = null, array
{
try {
return new OCI8Connection(
- $username,
- $password,
+ (string) $username,
+ (string) $password,
$this->_constructDsn($params),
- $params['charset'] ?? null,
+ $params['charset'] ?? '',
$params['sessionMode'] ?? OCI_DEFAULT,
$params['persistent'] ?? false
);
@@ -50,6 +50,8 @@ protected function _constructDsn(array $params)
/**
* {@inheritdoc}
+ *
+ * @deprecated
*/
public function getName()
{
diff --git a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php
index 5ebc877a898..c1857936f5a 100644
--- a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php
+++ b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php
@@ -10,8 +10,6 @@
use const OCI_DEFAULT;
use const OCI_NO_AUTO_COMMIT;
use function addcslashes;
-use function define;
-use function defined;
use function func_get_args;
use function is_float;
use function is_int;
@@ -39,28 +37,32 @@ 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|null $charset
- * @param int $sessionMode
- * @param bool $persistent
+ * @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 = null, $sessionMode = OCI_DEFAULT, $persistent = false)
- {
- if (! defined('OCI_NO_AUTO_COMMIT')) {
- define('OCI_NO_AUTO_COMMIT', 0);
- }
-
- $this->dbh = $persistent
+ public function __construct(
+ $username,
+ $password,
+ $db,
+ $charset = '',
+ $sessionMode = OCI_DEFAULT,
+ $persistent = false
+ ) {
+ $dbh = $persistent
? @oci_pconnect($username, $password, $db, $charset, $sessionMode)
: @oci_connect($username, $password, $db, $charset, $sessionMode);
- if (! $this->dbh) {
+ if ($dbh === false) {
throw OCI8Exception::fromErrorInfo(oci_error());
}
+
+ $this->dbh = $dbh;
}
/**
@@ -71,17 +73,23 @@ public function __construct($username, $password, $db, $charset = null, $session
*/
public function getServerVersion()
{
- if (! preg_match('/\s+(\d+\.\d+\.\d+\.\d+\.\d+)\s+/', oci_server_version($this->dbh), $version)) {
+ $version = oci_server_version($this->dbh);
+
+ if ($version === false) {
+ throw OCI8Exception::fromErrorInfo(oci_error($this->dbh));
+ }
+
+ if (! preg_match('/\s+(\d+\.\d+\.\d+\.\d+\.\d+)\s+/', $version, $matches)) {
throw new UnexpectedValueException(
sprintf(
'Unexpected database version string "%s". Cannot parse an appropriate version number from it. ' .
'Please report this database version string to the Doctrine team.',
- oci_server_version($this->dbh)
+ $version
)
);
}
- return $version[1];
+ return $matches[1];
}
/**
@@ -222,6 +230,12 @@ public function errorCode()
*/
public function errorInfo()
{
- return oci_error($this->dbh);
+ $error = oci_error($this->dbh);
+
+ if ($error === false) {
+ return [];
+ }
+
+ return $error;
}
}
diff --git a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Statement.php b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Statement.php
index 8db54c86aa7..c974bf8fc7f 100644
--- a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Statement.php
+++ b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Statement.php
@@ -23,9 +23,11 @@
use const PREG_OFFSET_CAPTURE;
use const SQLT_CHR;
use function array_key_exists;
+use function assert;
use function count;
use function implode;
-use function is_numeric;
+use function is_int;
+use function is_resource;
use function oci_bind_by_name;
use function oci_cancel;
use function oci_error;
@@ -56,7 +58,11 @@ class OCI8Statement implements IteratorAggregate, Statement
/** @var OCI8Connection */
protected $_conn;
- /** @var string */
+ /**
+ * @deprecated
+ *
+ * @var string
+ */
protected static $_PARAM = ':param';
/** @var int[] */
@@ -92,16 +98,20 @@ class OCI8Statement implements IteratorAggregate, Statement
/**
* Creates a new OCI8Statement that uses the given connection handle and SQL statement.
*
- * @param resource $dbh The connection handle.
- * @param string $statement The SQL statement.
+ * @param resource $dbh The connection handle.
+ * @param string $query The SQL query.
*/
- public function __construct($dbh, $statement, OCI8Connection $conn)
+ public function __construct($dbh, $query, OCI8Connection $conn)
{
- [$statement, $paramMap] = self::convertPositionalToNamedPlaceholders($statement);
- $this->_sth = oci_parse($dbh, $statement);
- $this->_dbh = $dbh;
- $this->_paramMap = $paramMap;
- $this->_conn = $conn;
+ [$query, $paramMap] = self::convertPositionalToNamedPlaceholders($query);
+
+ $stmt = oci_parse($dbh, $query);
+ assert(is_resource($stmt));
+
+ $this->_sth = $stmt;
+ $this->_dbh = $dbh;
+ $this->_paramMap = $paramMap;
+ $this->_conn = $conn;
}
/**
@@ -207,10 +217,9 @@ private static function findPlaceholderOrOpeningQuote(
/**
* Finds closing quote
*
- * @param string $statement The SQL statement to parse
- * @param string $tokenOffset The offset to start searching from
- * @param string|null $currentLiteralDelimiter The delimiter of the current string literal
- * or NULL if not currently in a literal
+ * @param string $statement The SQL statement to parse
+ * @param string $tokenOffset The offset to start searching from
+ * @param string $currentLiteralDelimiter The delimiter of the current string literal
*
* @return bool Whether the token was found
*/
@@ -240,7 +249,7 @@ private static function findClosingQuote(
* where the token was found.
*
* @param string $statement The SQL statement to parse
- * @param string $offset The offset to start searching from
+ * @param int $offset The offset to start searching from
* @param string $regex The regex containing token pattern
*
* @return string|null Token or NULL if not found
@@ -249,6 +258,7 @@ private static function findToken($statement, &$offset, $regex)
{
if (preg_match($regex, $statement, $matches, PREG_OFFSET_CAPTURE, $offset)) {
$offset = $matches[0][1];
+
return $matches[0][0];
}
@@ -268,10 +278,14 @@ public function bindValue($param, $value, $type = ParameterType::STRING)
*/
public function bindParam($column, &$variable, $type = ParameterType::STRING, $length = null)
{
- $column = $this->_paramMap[$column] ?? $column;
+ $column = $this->_paramMap[$column];
if ($type === ParameterType::LARGE_OBJECT) {
$lob = oci_new_descriptor($this->_dbh, OCI_D_LOB);
+
+ $class = 'OCI-Lob';
+ assert($lob instanceof $class);
+
$lob->writeTemporary($variable, OCI_TEMP_BLOB);
$variable =& $lob;
@@ -327,7 +341,7 @@ public function closeCursor()
*/
public function columnCount()
{
- return oci_num_fields($this->_sth);
+ return oci_num_fields($this->_sth) ?: 0;
}
/**
@@ -348,7 +362,13 @@ public function errorCode()
*/
public function errorInfo()
{
- return oci_error($this->_sth);
+ $error = oci_error($this->_sth);
+
+ if ($error === false) {
+ return [];
+ }
+
+ return $error;
}
/**
@@ -358,8 +378,9 @@ public function execute($params = null)
{
if ($params) {
$hasZeroIndex = array_key_exists(0, $params);
+
foreach ($params as $key => $val) {
- if ($hasZeroIndex && is_numeric($key)) {
+ if ($hasZeroIndex && is_int($key)) {
$this->bindValue($key + 1, $val);
} else {
$this->bindValue($key, $val);
@@ -505,6 +526,6 @@ public function fetchColumn($columnIndex = 0)
*/
public function rowCount()
{
- return oci_num_rows($this->_sth);
+ return oci_num_rows($this->_sth) ?: 0;
}
}
diff --git a/lib/Doctrine/DBAL/Driver/PDOConnection.php b/lib/Doctrine/DBAL/Driver/PDOConnection.php
index 2155140b2a8..336542ea50a 100644
--- a/lib/Doctrine/DBAL/Driver/PDOConnection.php
+++ b/lib/Doctrine/DBAL/Driver/PDOConnection.php
@@ -4,7 +4,7 @@
use Doctrine\DBAL\ParameterType;
use PDO;
-use function count;
+use function assert;
use function func_get_args;
/**
@@ -24,7 +24,7 @@ class PDOConnection extends PDO implements Connection, ServerInfoAwareConnection
public function __construct($dsn, $user = null, $password = null, ?array $options = null)
{
try {
- parent::__construct($dsn, $user, $password, $options);
+ parent::__construct($dsn, (string) $user, (string) $password, (array) $options);
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class, []]);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $exception) {
@@ -69,23 +69,13 @@ public function prepare($prepareString, $driverOptions = [])
*/
public function query()
{
- $args = func_get_args();
- $argsCount = count($args);
+ $args = func_get_args();
try {
- if ($argsCount === 4) {
- return parent::query($args[0], $args[1], $args[2], $args[3]);
- }
-
- if ($argsCount === 3) {
- return parent::query($args[0], $args[1], $args[2]);
- }
+ $stmt = parent::query(...$args);
+ assert($stmt instanceof \PDOStatement);
- if ($argsCount === 2) {
- return parent::query($args[0], $args[1]);
- }
-
- return parent::query($args[0]);
+ return $stmt;
} catch (\PDOException $exception) {
throw new PDOException($exception);
}
@@ -105,6 +95,10 @@ public function quote($input, $type = ParameterType::STRING)
public function lastInsertId($name = null)
{
try {
+ if ($name === null) {
+ return parent::lastInsertId();
+ }
+
return parent::lastInsertId($name);
} catch (\PDOException $exception) {
throw new PDOException($exception);
diff --git a/lib/Doctrine/DBAL/Driver/PDOIbm/Driver.php b/lib/Doctrine/DBAL/Driver/PDOIbm/Driver.php
index 4291e1e17f0..12fb14ef5cb 100644
--- a/lib/Doctrine/DBAL/Driver/PDOIbm/Driver.php
+++ b/lib/Doctrine/DBAL/Driver/PDOIbm/Driver.php
@@ -49,6 +49,8 @@ private function _constructPdoDsn(array $params)
/**
* {@inheritdoc}
+ *
+ * @deprecated
*/
public function getName()
{
diff --git a/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php b/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php
index 59d27d3844f..dcd4ff51895 100644
--- a/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php
+++ b/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php
@@ -62,6 +62,8 @@ protected function constructPdoDsn(array $params)
/**
* {@inheritdoc}
+ *
+ * @deprecated
*/
public function getName()
{
diff --git a/lib/Doctrine/DBAL/Driver/PDOPgSql/Driver.php b/lib/Doctrine/DBAL/Driver/PDOPgSql/Driver.php
index 972dbadcd5d..f25cd5cded3 100644
--- a/lib/Doctrine/DBAL/Driver/PDOPgSql/Driver.php
+++ b/lib/Doctrine/DBAL/Driver/PDOPgSql/Driver.php
@@ -108,6 +108,8 @@ private function _constructPdoDsn(array $params)
/**
* {@inheritdoc}
+ *
+ * @deprecated
*/
public function getName()
{
diff --git a/lib/Doctrine/DBAL/Driver/PDOSqlite/Driver.php b/lib/Doctrine/DBAL/Driver/PDOSqlite/Driver.php
index 7a28b831027..d08c6a2c848 100644
--- a/lib/Doctrine/DBAL/Driver/PDOSqlite/Driver.php
+++ b/lib/Doctrine/DBAL/Driver/PDOSqlite/Driver.php
@@ -73,6 +73,8 @@ protected function _constructPdoDsn(array $params)
/**
* {@inheritdoc}
+ *
+ * @deprecated
*/
public function getName()
{
diff --git a/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Driver.php b/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Driver.php
index 6543e32392e..6d6c4844d57 100644
--- a/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Driver.php
+++ b/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Driver.php
@@ -16,13 +16,21 @@ class Driver extends AbstractSQLServerDriver
*/
public function connect(array $params, $username = null, $password = null, array $driverOptions = [])
{
- [$driverOptions, $connectionOptions] = $this->splitOptions($driverOptions);
+ $pdoOptions = $dsnOptions = [];
+
+ foreach ($driverOptions as $option => $value) {
+ if (is_int($option)) {
+ $pdoOptions[$option] = $value;
+ } else {
+ $dsnOptions[$option] = $value;
+ }
+ }
return new Connection(
- $this->_constructPdoDsn($params, $connectionOptions),
+ $this->_constructPdoDsn($params, $dsnOptions),
$username,
$password,
- $driverOptions
+ $pdoOptions
);
}
@@ -57,29 +65,6 @@ private function _constructPdoDsn(array $params, array $connectionOptions)
return $dsn . $this->getConnectionOptionsDsn($connectionOptions);
}
- /**
- * Separates a connection options from a driver options
- *
- * @param int[]|string[] $options
- *
- * @return int[][]|string[][]
- */
- private function splitOptions(array $options) : array
- {
- $driverOptions = [];
- $connectionOptions = [];
-
- foreach ($options as $optionKey => $optionValue) {
- if (is_int($optionKey)) {
- $driverOptions[$optionKey] = $optionValue;
- } else {
- $connectionOptions[$optionKey] = $optionValue;
- }
- }
-
- return [$driverOptions, $connectionOptions];
- }
-
/**
* Converts a connection options array to the DSN
*
@@ -98,6 +83,8 @@ private function getConnectionOptionsDsn(array $connectionOptions) : string
/**
* {@inheritdoc}
+ *
+ * @deprecated
*/
public function getName()
{
diff --git a/lib/Doctrine/DBAL/Driver/PDOStatement.php b/lib/Doctrine/DBAL/Driver/PDOStatement.php
index 2aed89fbf07..5be4f2c046d 100644
--- a/lib/Doctrine/DBAL/Driver/PDOStatement.php
+++ b/lib/Doctrine/DBAL/Driver/PDOStatement.php
@@ -6,6 +6,10 @@
use Doctrine\DBAL\ParameterType;
use PDO;
use const E_USER_DEPRECATED;
+use function array_slice;
+use function assert;
+use function func_get_args;
+use function is_array;
use function sprintf;
use function trigger_error;
@@ -88,7 +92,7 @@ public function bindParam($column, &$variable, $type = ParameterType::STRING, $l
$type = $this->convertParamType($type);
try {
- return parent::bindParam($column, $variable, $type, $length, $driverOptions);
+ return parent::bindParam($column, $variable, $type, ...array_slice(func_get_args(), 3));
} catch (\PDOException $exception) {
throw new PDOException($exception);
}
@@ -125,22 +129,14 @@ public function execute($params = null)
*/
public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
{
- $fetchMode = $this->convertFetchMode($fetchMode);
-
- try {
- if ($fetchMode === null && $cursorOrientation === PDO::FETCH_ORI_NEXT && $cursorOffset === 0) {
- return parent::fetch();
- }
-
- if ($cursorOrientation === PDO::FETCH_ORI_NEXT && $cursorOffset === 0) {
- return parent::fetch($fetchMode);
- }
+ $args = func_get_args();
- if ($cursorOffset === 0) {
- return parent::fetch($fetchMode, $cursorOrientation);
- }
+ if (isset($args[0])) {
+ $args[0] = $this->convertFetchMode($args[0]);
+ }
- return parent::fetch($fetchMode, $cursorOrientation, $cursorOffset);
+ try {
+ return parent::fetch(...$args);
} catch (\PDOException $exception) {
throw new PDOException($exception);
}
@@ -151,22 +147,27 @@ public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEX
*/
public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null)
{
- $fetchMode = $this->convertFetchMode($fetchMode);
+ $args = func_get_args();
- try {
- if ($fetchMode === null && $fetchArgument === null && $ctorArgs === null) {
- return parent::fetchAll();
- }
+ if (isset($args[0])) {
+ $args[0] = $this->convertFetchMode($args[0]);
+ }
- if ($fetchArgument === null && $ctorArgs === null) {
- return parent::fetchAll($fetchMode);
- }
+ if ($fetchMode === null && $fetchArgument === null && $ctorArgs === null) {
+ $args = [];
+ } elseif ($fetchArgument === null && $ctorArgs === null) {
+ $args = [$fetchMode];
+ } elseif ($ctorArgs === null) {
+ $args = [$fetchMode, $fetchArgument];
+ } else {
+ $args = [$fetchMode, $fetchArgument, $ctorArgs];
+ }
- if ($ctorArgs === null) {
- return parent::fetchAll($fetchMode, $fetchArgument);
- }
+ try {
+ $data = parent::fetchAll(...$args);
+ assert(is_array($data));
- return parent::fetchAll($fetchMode, $fetchArgument, $ctorArgs);
+ return $data;
} catch (\PDOException $exception) {
throw new PDOException($exception);
}
@@ -207,14 +208,10 @@ private function convertParamType(int $type) : int
/**
* Converts DBAL fetch mode to PDO fetch mode
*
- * @param int|null $fetchMode Fetch mode
+ * @param int $fetchMode Fetch mode
*/
- private function convertFetchMode(?int $fetchMode) : ?int
+ private function convertFetchMode(int $fetchMode) : int
{
- if ($fetchMode === null) {
- return null;
- }
-
if (! isset(self::FETCH_MODE_MAP[$fetchMode])) {
// TODO: next major: throw an exception
@trigger_error(sprintf(
diff --git a/lib/Doctrine/DBAL/Driver/SQLAnywhere/Driver.php b/lib/Doctrine/DBAL/Driver/SQLAnywhere/Driver.php
index 294d5c7a5e9..9564dc2981d 100644
--- a/lib/Doctrine/DBAL/Driver/SQLAnywhere/Driver.php
+++ b/lib/Doctrine/DBAL/Driver/SQLAnywhere/Driver.php
@@ -40,6 +40,8 @@ public function connect(array $params, $username = null, $password = null, array
/**
* {@inheritdoc}
+ *
+ * @deprecated
*/
public function getName()
{
diff --git a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereException.php b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereException.php
index 9f8aac0608d..0f8bc3e57e6 100644
--- a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereException.php
+++ b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereException.php
@@ -4,7 +4,6 @@
use Doctrine\DBAL\Driver\AbstractDriverException;
use InvalidArgumentException;
-use function is_resource;
use function sasql_error;
use function sasql_errorcode;
use function sasql_sqlstate;
@@ -28,14 +27,6 @@ class SQLAnywhereException extends AbstractDriverException
*/
public static function fromSQLAnywhereError($conn = null, $stmt = null)
{
- if ($conn !== null && ! is_resource($conn)) {
- throw new InvalidArgumentException('Invalid SQL Anywhere connection resource given: ' . $conn);
- }
-
- if ($stmt !== null && ! is_resource($stmt)) {
- throw new InvalidArgumentException('Invalid SQL Anywhere statement resource given: ' . $stmt);
- }
-
$state = $conn ? sasql_sqlstate($conn) : sasql_sqlstate();
$code = null;
$message = null;
diff --git a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereStatement.php b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereStatement.php
index 6354836a478..886bb245873 100644
--- a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereStatement.php
+++ b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereStatement.php
@@ -17,7 +17,7 @@
use function func_num_args;
use function gettype;
use function is_array;
-use function is_numeric;
+use function is_int;
use function is_object;
use function is_resource;
use function is_string;
@@ -177,9 +177,11 @@ public function execute($params = null)
$hasZeroIndex = array_key_exists(0, $params);
foreach ($params as $key => $val) {
- $key = $hasZeroIndex && is_numeric($key) ? $key + 1 : $key;
-
- $this->bindValue($key, $val);
+ if ($hasZeroIndex && is_int($key)) {
+ $this->bindValue($key + 1, $val);
+ } else {
+ $this->bindValue($key, $val);
+ }
}
}
diff --git a/lib/Doctrine/DBAL/Driver/SQLSrv/Driver.php b/lib/Doctrine/DBAL/Driver/SQLSrv/Driver.php
index a9be26e9dea..848ab5eef91 100644
--- a/lib/Doctrine/DBAL/Driver/SQLSrv/Driver.php
+++ b/lib/Doctrine/DBAL/Driver/SQLSrv/Driver.php
@@ -48,6 +48,8 @@ public function connect(array $params, $username = null, $password = null, array
/**
* {@inheritdoc}
+ *
+ * @deprecated
*/
public function getName()
{
diff --git a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php
index f1f9ddd1d79..35ad913ff5b 100644
--- a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php
+++ b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php
@@ -44,10 +44,13 @@ public function __construct($serverName, $connectionOptions)
throw SQLSrvException::fromSqlSrvErrors();
}
- $this->conn = sqlsrv_connect($serverName, $connectionOptions);
- if (! $this->conn) {
+ $conn = sqlsrv_connect($serverName, $connectionOptions);
+
+ if ($conn === false) {
throw SQLSrvException::fromSqlSrvErrors();
}
+
+ $this->conn = $conn;
$this->lastInsertId = new LastInsertId();
}
@@ -97,7 +100,9 @@ public function quote($value, $type = ParameterType::STRING)
{
if (is_int($value)) {
return $value;
- } elseif (is_float($value)) {
+ }
+
+ if (is_float($value)) {
return sprintf('%F', $value);
}
@@ -115,7 +120,13 @@ public function exec($statement)
throw SQLSrvException::fromSqlSrvErrors();
}
- return sqlsrv_rows_affected($stmt);
+ $rowsAffected = sqlsrv_rows_affected($stmt);
+
+ if ($rowsAffected === false) {
+ throw SQLSrvException::fromSqlSrvErrors();
+ }
+
+ return $rowsAffected;
}
/**
@@ -181,6 +192,6 @@ public function errorCode()
*/
public function errorInfo()
{
- return sqlsrv_errors(SQLSRV_ERR_ERRORS);
+ return (array) sqlsrv_errors(SQLSRV_ERR_ERRORS);
}
}
diff --git a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvException.php b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvException.php
index 796f5d129d4..1c1e8c472d7 100644
--- a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvException.php
+++ b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvException.php
@@ -16,12 +16,11 @@ class SQLSrvException extends AbstractDriverException
*/
public static function fromSqlSrvErrors()
{
- $errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
$message = '';
$sqlState = null;
$errorCode = null;
- foreach ($errors as $error) {
+ foreach ((array) sqlsrv_errors(SQLSRV_ERR_ERRORS) as $error) {
$message .= 'SQLSTATE [' . $error['SQLSTATE'] . ', ' . $error['code'] . ']: ' . $error['message'] . "\n";
if ($sqlState === null) {
@@ -34,6 +33,7 @@ public static function fromSqlSrvErrors()
$errorCode = $error['code'];
}
+
if (! $message) {
$message = 'SQL Server error occurred but no error message was retrieved from driver.';
}
diff --git a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvStatement.php b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvStatement.php
index 147ef76e1a0..5e7016c5a74 100644
--- a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvStatement.php
+++ b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvStatement.php
@@ -18,6 +18,7 @@
use function count;
use function func_get_args;
use function in_array;
+use function is_int;
use function is_numeric;
use function sqlsrv_errors;
use function sqlsrv_execute;
@@ -122,6 +123,8 @@ class SQLSrvStatement implements IteratorAggregate, Statement
/**
* Append to any INSERT query to retrieve the last insert id.
+ *
+ * @deprecated This constant has been deprecated and will be made private in 3.0
*/
public const LAST_INSERT_ID_SQL = ';SELECT SCOPE_IDENTITY() AS LastInsertId;';
@@ -179,7 +182,7 @@ public function bindParam($column, &$variable, $type = ParameterType::STRING, $l
public function closeCursor()
{
// not having the result means there's nothing to close
- if (! $this->result) {
+ if ($this->stmt === null || ! $this->result) {
return true;
}
@@ -200,7 +203,11 @@ public function closeCursor()
*/
public function columnCount()
{
- return sqlsrv_num_fields($this->stmt);
+ if ($this->stmt === null) {
+ return 0;
+ }
+
+ return sqlsrv_num_fields($this->stmt) ?: 0;
}
/**
@@ -221,7 +228,7 @@ public function errorCode()
*/
public function errorInfo()
{
- return sqlsrv_errors(SQLSRV_ERR_ERRORS);
+ return (array) sqlsrv_errors(SQLSRV_ERR_ERRORS);
}
/**
@@ -231,9 +238,13 @@ public function execute($params = null)
{
if ($params) {
$hasZeroIndex = array_key_exists(0, $params);
+
foreach ($params as $key => $val) {
- $key = $hasZeroIndex && is_numeric($key) ? $key + 1 : $key;
- $this->bindValue($key, $val);
+ if ($hasZeroIndex && is_int($key)) {
+ $this->bindValue($key + 1, $val);
+ } else {
+ $this->bindValue($key, $val);
+ }
}
}
@@ -328,7 +339,7 @@ public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEX
{
// do not try fetching from the statement if it's not expected to contain result
// in order to prevent exceptional situation
- if (! $this->result) {
+ if ($this->stmt === null || ! $this->result) {
return false;
}
@@ -406,6 +417,10 @@ public function fetchColumn($columnIndex = 0)
*/
public function rowCount()
{
- return sqlsrv_rows_affected($this->stmt);
+ if ($this->stmt === null) {
+ return 0;
+ }
+
+ return sqlsrv_rows_affected($this->stmt) ?: 0;
}
}
diff --git a/lib/Doctrine/DBAL/Driver/Statement.php b/lib/Doctrine/DBAL/Driver/Statement.php
index a3ea74a4df5..388983e46a6 100644
--- a/lib/Doctrine/DBAL/Driver/Statement.php
+++ b/lib/Doctrine/DBAL/Driver/Statement.php
@@ -48,7 +48,7 @@ public function bindValue($param, $value, $type = ParameterType::STRING);
* this will be a parameter name of the form :name. For a prepared statement using
* question mark placeholders, this will be the 1-indexed position of the parameter.
* @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter.
- * @param int|null $type Explicit data type for the parameter using the {@link \Doctrine\DBAL\ParameterType}
+ * @param int $type Explicit data type for the parameter using the {@link \Doctrine\DBAL\ParameterType}
* constants. To return an INOUT parameter from a stored procedure, use the bitwise
* OR operator to set the PDO::PARAM_INPUT_OUTPUT bits for the data_type parameter.
* @param int|null $length You must specify maxlength when using an OUT bind
diff --git a/lib/Doctrine/DBAL/Driver/StatementIterator.php b/lib/Doctrine/DBAL/Driver/StatementIterator.php
index 5246b38a448..6b3307da2af 100644
--- a/lib/Doctrine/DBAL/Driver/StatementIterator.php
+++ b/lib/Doctrine/DBAL/Driver/StatementIterator.php
@@ -6,10 +6,10 @@
class StatementIterator implements IteratorAggregate
{
- /** @var Statement */
+ /** @var ResultStatement */
private $statement;
- public function __construct(Statement $statement)
+ public function __construct(ResultStatement $statement)
{
$this->statement = $statement;
}
diff --git a/lib/Doctrine/DBAL/DriverManager.php b/lib/Doctrine/DBAL/DriverManager.php
index 658123199c0..6888d73b0c4 100644
--- a/lib/Doctrine/DBAL/DriverManager.php
+++ b/lib/Doctrine/DBAL/DriverManager.php
@@ -18,8 +18,10 @@
use function array_keys;
use function array_map;
use function array_merge;
+use function assert;
use function class_implements;
use function in_array;
+use function is_string;
use function is_subclass_of;
use function parse_str;
use function parse_url;
@@ -172,7 +174,9 @@ public static function getConnection(
// check for existing pdo object
if (isset($params['pdo']) && ! $params['pdo'] instanceof PDO) {
throw DBALException::invalidPdoInstance();
- } elseif (isset($params['pdo'])) {
+ }
+
+ if (isset($params['pdo'])) {
$params['pdo']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$params['driver'] = 'pdo_' . $params['pdo']->getAttribute(PDO::ATTR_DRIVER_NAME);
} else {
@@ -263,6 +267,8 @@ private static function parseDatabaseUrl(array $params) : array
// (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
$url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $params['url']);
+ assert(is_string($url));
+
$url = parse_url($url);
if ($url === false) {
@@ -414,6 +420,7 @@ private static function parseDatabaseUrlScheme(array $url, array $params) : arra
// URL schemes must not contain underscores, but dashes are ok
$driver = str_replace('-', '_', $url['scheme']);
+ assert(is_string($driver));
// The requested driver from the URL scheme takes precedence over the
// default driver from the connection parameters. If the driver is
diff --git a/lib/Doctrine/DBAL/Event/ConnectionEventArgs.php b/lib/Doctrine/DBAL/Event/ConnectionEventArgs.php
index bb0ca886d99..5c71992cc05 100644
--- a/lib/Doctrine/DBAL/Event/ConnectionEventArgs.php
+++ b/lib/Doctrine/DBAL/Event/ConnectionEventArgs.php
@@ -30,6 +30,8 @@ public function getConnection()
}
/**
+ * @deprecated Use ConnectionEventArgs::getConnection() and Connection::getDriver() instead.
+ *
* @return Driver
*/
public function getDriver()
@@ -38,6 +40,8 @@ public function getDriver()
}
/**
+ * @deprecated Use ConnectionEventArgs::getConnection() and Connection::getDatabasePlatform() instead.
+ *
* @return AbstractPlatform
*/
public function getDatabasePlatform()
@@ -46,6 +50,8 @@ public function getDatabasePlatform()
}
/**
+ * @deprecated Use ConnectionEventArgs::getConnection() and Connection::getSchemaManager() instead.
+ *
* @return AbstractSchemaManager
*/
public function getSchemaManager()
diff --git a/lib/Doctrine/DBAL/Event/SchemaAlterTableAddColumnEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaAlterTableAddColumnEventArgs.php
index 2f9edfea688..ff86a93d632 100644
--- a/lib/Doctrine/DBAL/Event/SchemaAlterTableAddColumnEventArgs.php
+++ b/lib/Doctrine/DBAL/Event/SchemaAlterTableAddColumnEventArgs.php
@@ -6,6 +6,7 @@
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\TableDiff;
use function array_merge;
+use function func_get_args;
use function is_array;
/**
@@ -57,17 +58,15 @@ public function getPlatform()
}
/**
+ * Passing multiple SQL statements as an array is deprecated. Pass each statement as an individual argument instead.
+ *
* @param string|string[] $sql
*
* @return \Doctrine\DBAL\Event\SchemaAlterTableAddColumnEventArgs
*/
public function addSql($sql)
{
- if (is_array($sql)) {
- $this->sql = array_merge($this->sql, $sql);
- } else {
- $this->sql[] = $sql;
- }
+ $this->sql = array_merge($this->sql, is_array($sql) ? $sql : func_get_args());
return $this;
}
diff --git a/lib/Doctrine/DBAL/Event/SchemaAlterTableChangeColumnEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaAlterTableChangeColumnEventArgs.php
index 55661d5d307..354eb68bc6b 100644
--- a/lib/Doctrine/DBAL/Event/SchemaAlterTableChangeColumnEventArgs.php
+++ b/lib/Doctrine/DBAL/Event/SchemaAlterTableChangeColumnEventArgs.php
@@ -6,6 +6,7 @@
use Doctrine\DBAL\Schema\ColumnDiff;
use Doctrine\DBAL\Schema\TableDiff;
use function array_merge;
+use function func_get_args;
use function is_array;
/**
@@ -57,17 +58,15 @@ public function getPlatform()
}
/**
+ * Passing multiple SQL statements as an array is deprecated. Pass each statement as an individual argument instead.
+ *
* @param string|string[] $sql
*
* @return \Doctrine\DBAL\Event\SchemaAlterTableChangeColumnEventArgs
*/
public function addSql($sql)
{
- if (is_array($sql)) {
- $this->sql = array_merge($this->sql, $sql);
- } else {
- $this->sql[] = $sql;
- }
+ $this->sql = array_merge($this->sql, is_array($sql) ? $sql : func_get_args());
return $this;
}
diff --git a/lib/Doctrine/DBAL/Event/SchemaAlterTableEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaAlterTableEventArgs.php
index 8f5f0ecf563..b10bc7a60a2 100644
--- a/lib/Doctrine/DBAL/Event/SchemaAlterTableEventArgs.php
+++ b/lib/Doctrine/DBAL/Event/SchemaAlterTableEventArgs.php
@@ -5,6 +5,7 @@
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\TableDiff;
use function array_merge;
+use function func_get_args;
use function is_array;
/**
@@ -44,17 +45,15 @@ public function getPlatform()
}
/**
+ * Passing multiple SQL statements as an array is deprecated. Pass each statement as an individual argument instead.
+ *
* @param string|string[] $sql
*
* @return \Doctrine\DBAL\Event\SchemaAlterTableEventArgs
*/
public function addSql($sql)
{
- if (is_array($sql)) {
- $this->sql = array_merge($this->sql, $sql);
- } else {
- $this->sql[] = $sql;
- }
+ $this->sql = array_merge($this->sql, is_array($sql) ? $sql : func_get_args());
return $this;
}
diff --git a/lib/Doctrine/DBAL/Event/SchemaAlterTableRemoveColumnEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaAlterTableRemoveColumnEventArgs.php
index 1bc9f590187..6e3d6a757c7 100644
--- a/lib/Doctrine/DBAL/Event/SchemaAlterTableRemoveColumnEventArgs.php
+++ b/lib/Doctrine/DBAL/Event/SchemaAlterTableRemoveColumnEventArgs.php
@@ -6,6 +6,7 @@
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\TableDiff;
use function array_merge;
+use function func_get_args;
use function is_array;
/**
@@ -57,17 +58,15 @@ public function getPlatform()
}
/**
+ * Passing multiple SQL statements as an array is deprecated. Pass each statement as an individual argument instead.
+ *
* @param string|string[] $sql
*
* @return \Doctrine\DBAL\Event\SchemaAlterTableRemoveColumnEventArgs
*/
public function addSql($sql)
{
- if (is_array($sql)) {
- $this->sql = array_merge($this->sql, $sql);
- } else {
- $this->sql[] = $sql;
- }
+ $this->sql = array_merge($this->sql, is_array($sql) ? $sql : func_get_args());
return $this;
}
diff --git a/lib/Doctrine/DBAL/Event/SchemaAlterTableRenameColumnEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaAlterTableRenameColumnEventArgs.php
index 911ea8b4ab6..27e2825314c 100644
--- a/lib/Doctrine/DBAL/Event/SchemaAlterTableRenameColumnEventArgs.php
+++ b/lib/Doctrine/DBAL/Event/SchemaAlterTableRenameColumnEventArgs.php
@@ -6,6 +6,7 @@
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\TableDiff;
use function array_merge;
+use function func_get_args;
use function is_array;
/**
@@ -72,17 +73,15 @@ public function getPlatform()
}
/**
+ * Passing multiple SQL statements as an array is deprecated. Pass each statement as an individual argument instead.
+ *
* @param string|string[] $sql
*
* @return \Doctrine\DBAL\Event\SchemaAlterTableRenameColumnEventArgs
*/
public function addSql($sql)
{
- if (is_array($sql)) {
- $this->sql = array_merge($this->sql, $sql);
- } else {
- $this->sql[] = $sql;
- }
+ $this->sql = array_merge($this->sql, is_array($sql) ? $sql : func_get_args());
return $this;
}
diff --git a/lib/Doctrine/DBAL/Event/SchemaColumnDefinitionEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaColumnDefinitionEventArgs.php
index 19d9f93a329..80d9abe73a5 100644
--- a/lib/Doctrine/DBAL/Event/SchemaColumnDefinitionEventArgs.php
+++ b/lib/Doctrine/DBAL/Event/SchemaColumnDefinitionEventArgs.php
@@ -97,6 +97,8 @@ public function getConnection()
}
/**
+ * @deprecated Use SchemaColumnDefinitionEventArgs::getConnection() and Connection::getDatabasePlatform() instead.
+ *
* @return AbstractPlatform
*/
public function getDatabasePlatform()
diff --git a/lib/Doctrine/DBAL/Event/SchemaCreateTableColumnEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaCreateTableColumnEventArgs.php
index 9d24b8b9049..6d78aae5c11 100644
--- a/lib/Doctrine/DBAL/Event/SchemaCreateTableColumnEventArgs.php
+++ b/lib/Doctrine/DBAL/Event/SchemaCreateTableColumnEventArgs.php
@@ -6,6 +6,7 @@
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\Table;
use function array_merge;
+use function func_get_args;
use function is_array;
/**
@@ -57,17 +58,15 @@ public function getPlatform()
}
/**
+ * Passing multiple SQL statements as an array is deprecated. Pass each statement as an individual argument instead.
+ *
* @param string|string[] $sql
*
* @return \Doctrine\DBAL\Event\SchemaCreateTableColumnEventArgs
*/
public function addSql($sql)
{
- if (is_array($sql)) {
- $this->sql = array_merge($this->sql, $sql);
- } else {
- $this->sql[] = $sql;
- }
+ $this->sql = array_merge($this->sql, is_array($sql) ? $sql : func_get_args());
return $this;
}
diff --git a/lib/Doctrine/DBAL/Event/SchemaCreateTableEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaCreateTableEventArgs.php
index 538617cc328..927a4e4efe1 100644
--- a/lib/Doctrine/DBAL/Event/SchemaCreateTableEventArgs.php
+++ b/lib/Doctrine/DBAL/Event/SchemaCreateTableEventArgs.php
@@ -3,9 +3,9 @@
namespace Doctrine\DBAL\Event;
use Doctrine\DBAL\Platforms\AbstractPlatform;
-use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\Table;
use function array_merge;
+use function func_get_args;
use function is_array;
/**
@@ -16,7 +16,7 @@ class SchemaCreateTableEventArgs extends SchemaEventArgs
/** @var Table */
private $table;
- /** @var Column[] */
+ /** @var mixed[][] */
private $columns;
/** @var mixed[] */
@@ -29,8 +29,8 @@ class SchemaCreateTableEventArgs extends SchemaEventArgs
private $sql = [];
/**
- * @param Column[] $columns
- * @param mixed[] $options
+ * @param mixed[][] $columns
+ * @param mixed[] $options
*/
public function __construct(Table $table, array $columns, array $options, AbstractPlatform $platform)
{
@@ -49,7 +49,7 @@ public function getTable()
}
/**
- * @return Column[]
+ * @return mixed[][]
*/
public function getColumns()
{
@@ -73,17 +73,15 @@ public function getPlatform()
}
/**
+ * Passing multiple SQL statements as an array is deprecated. Pass each statement as an individual argument instead.
+ *
* @param string|string[] $sql
*
* @return \Doctrine\DBAL\Event\SchemaCreateTableEventArgs
*/
public function addSql($sql)
{
- if (is_array($sql)) {
- $this->sql = array_merge($this->sql, $sql);
- } else {
- $this->sql[] = $sql;
- }
+ $this->sql = array_merge($this->sql, is_array($sql) ? $sql : func_get_args());
return $this;
}
diff --git a/lib/Doctrine/DBAL/Event/SchemaDropTableEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaDropTableEventArgs.php
index 900b9fbfd71..387049791d2 100644
--- a/lib/Doctrine/DBAL/Event/SchemaDropTableEventArgs.php
+++ b/lib/Doctrine/DBAL/Event/SchemaDropTableEventArgs.php
@@ -5,7 +5,6 @@
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\Table;
use InvalidArgumentException;
-use function is_string;
/**
* Event Arguments used when the SQL query for dropping tables are generated inside Doctrine\DBAL\Platform\AbstractPlatform.
@@ -28,10 +27,6 @@ class SchemaDropTableEventArgs extends SchemaEventArgs
*/
public function __construct($table, AbstractPlatform $platform)
{
- if (! $table instanceof Table && ! is_string($table)) {
- throw new InvalidArgumentException('SchemaDropTableEventArgs expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
- }
-
$this->table = $table;
$this->platform = $platform;
}
diff --git a/lib/Doctrine/DBAL/Logging/LoggerChain.php b/lib/Doctrine/DBAL/Logging/LoggerChain.php
index 2b5404b25c7..024afae283a 100644
--- a/lib/Doctrine/DBAL/Logging/LoggerChain.php
+++ b/lib/Doctrine/DBAL/Logging/LoggerChain.php
@@ -10,9 +10,19 @@ class LoggerChain implements SQLLogger
/** @var SQLLogger[] */
private $loggers = [];
+ /**
+ * @param SQLLogger[] $loggers
+ */
+ public function __construct(array $loggers = [])
+ {
+ $this->loggers = $loggers;
+ }
+
/**
* Adds a logger in the chain.
*
+ * @deprecated Inject list of loggers via constructor instead
+ *
* @return void
*/
public function addLogger(SQLLogger $logger)
diff --git a/lib/Doctrine/DBAL/Platforms/AbstractPlatform.php b/lib/Doctrine/DBAL/Platforms/AbstractPlatform.php
index 5e4537391ed..3d833dfaaeb 100644
--- a/lib/Doctrine/DBAL/Platforms/AbstractPlatform.php
+++ b/lib/Doctrine/DBAL/Platforms/AbstractPlatform.php
@@ -27,12 +27,14 @@
use Doctrine\DBAL\Types;
use Doctrine\DBAL\Types\Type;
use InvalidArgumentException;
+use UnexpectedValueException;
use const E_USER_DEPRECATED;
use function addcslashes;
use function array_map;
use function array_merge;
use function array_unique;
use function array_values;
+use function assert;
use function count;
use function explode;
use function func_get_arg;
@@ -144,7 +146,7 @@ abstract class AbstractPlatform
/**
* Holds the KeywordList instance for the current platform.
*
- * @var KeywordList
+ * @var KeywordList|null
*/
protected $_keywords;
@@ -486,6 +488,8 @@ public function isCommentedDoctrineType(Type $doctrineType)
$this->initializeCommentedDoctrineTypes();
}
+ assert(is_array($this->doctrineTypeComments));
+
return in_array($doctrineType->getName(), $this->doctrineTypeComments);
}
@@ -502,6 +506,8 @@ public function markDoctrineTypeCommented($doctrineType)
$this->initializeCommentedDoctrineTypes();
}
+ assert(is_array($this->doctrineTypeComments));
+
$this->doctrineTypeComments[] = $doctrineType instanceof Type ? $doctrineType->getName() : $doctrineType;
}
@@ -518,7 +524,7 @@ public function getDoctrineTypeComment(Type $doctrineType)
/**
* Gets the comment of a passed column modified by potential doctrine type comment hints.
*
- * @return string
+ * @return string|null
*/
protected function getColumnComment(Column $column)
{
@@ -864,9 +870,9 @@ public function getLowerExpression($str)
/**
* Returns the SQL snippet to get the position of the first occurrence of substring $substr in string $str.
*
- * @param string $str Literal string.
- * @param string $substr Literal string to find.
- * @param int|bool $startPos Position to start at, beginning of string by default.
+ * @param string $str Literal string.
+ * @param string $substr Literal string to find.
+ * @param int|false $startPos Position to start at, beginning of string by default.
*
* @return string
*
@@ -1419,7 +1425,13 @@ public function getDropTableSQL($table)
$this->_eventManager->dispatchEvent(Events::onSchemaDropTable, $eventArgs);
if ($eventArgs->isDefaultPrevented()) {
- return $eventArgs->getSql();
+ $sql = $eventArgs->getSql();
+
+ if ($sql === null) {
+ throw new UnexpectedValueException('Default implementation of DROP TABLE was overridden with NULL');
+ }
+
+ return $sql;
}
}
@@ -1595,6 +1607,9 @@ public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDE
$sql = $this->_getCreateTableSQL($tableName, $columns, $options);
if ($this->supportsCommentOnStatement()) {
+ if ($table->hasOption('comment')) {
+ $sql[] = $this->getCommentOnTableSQL($tableName, $table->getOption('comment'));
+ }
foreach ($table->getColumns() as $column) {
$comment = $this->getColumnComment($column);
@@ -1609,10 +1624,21 @@ public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDE
return array_merge($sql, $columnSql);
}
+ protected function getCommentOnTableSQL(string $tableName, ?string $comment) : string
+ {
+ $tableName = new Identifier($tableName);
+
+ return sprintf(
+ 'COMMENT ON TABLE %s IS %s',
+ $tableName->getQuotedName($this),
+ $this->quoteStringLiteral((string) $comment)
+ );
+ }
+
/**
- * @param string $tableName
- * @param string $columnName
- * @param string $comment
+ * @param string $tableName
+ * @param string $columnName
+ * @param string|null $comment
*
* @return string
*/
@@ -1620,13 +1646,12 @@ public function getCommentOnColumnSQL($tableName, $columnName, $comment)
{
$tableName = new Identifier($tableName);
$columnName = new Identifier($columnName);
- $comment = $this->quoteStringLiteral($comment);
return sprintf(
'COMMENT ON COLUMN %s.%s IS %s',
$tableName->getQuotedName($this),
$columnName->getQuotedName($this),
- $comment
+ $this->quoteStringLiteral((string) $comment)
);
}
@@ -1833,6 +1858,10 @@ protected function getCreateIndexSQLFlags(Index $index)
*/
public function getCreatePrimaryKeySQL(Index $index, $table)
{
+ if ($table instanceof Table) {
+ $table = $table->getQuotedName($this);
+ }
+
return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
}
@@ -2067,11 +2096,14 @@ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
*/
protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
{
- $tableName = $diff->newName !== false
- ? $diff->getNewName()->getQuotedName($this)
- : $diff->getName($this)->getQuotedName($this);
+ $sql = [];
+ $newName = $diff->getNewName();
- $sql = [];
+ if ($newName !== false) {
+ $tableName = $newName->getQuotedName($this);
+ } else {
+ $tableName = $diff->getName($this)->getQuotedName($this);
+ }
if ($this->supportsForeignKeyConstraints()) {
foreach ($diff->addedForeignKeys as $foreignKey) {
@@ -2122,6 +2154,8 @@ protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
/**
* Common code for alter table statement generation that updates the changed Index and Foreign Key definitions.
*
+ * @deprecated
+ *
* @return string[]
*/
protected function _getAlterTableIndexForeignKeySQL(TableDiff $diff)
@@ -2293,14 +2327,14 @@ public function getDefaultValueDeclarationSQL($field)
return " DEFAULT '" . $this->convertBooleans($default) . "'";
}
- return " DEFAULT '" . $default . "'";
+ return ' DEFAULT ' . $this->quoteStringLiteral($default);
}
/**
* Obtains DBMS specific SQL code portion needed to set a CHECK constraint
* declaration to be used in statements like CREATE TABLE.
*
- * @param mixed[][] $definition The check definition.
+ * @param string[]|mixed[][] $definition The check definition.
*
* @return string DBMS specific SQL code portion needed to set a CHECK constraint.
*/
@@ -2950,7 +2984,6 @@ public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
return $this->getDateTimeTypeDeclarationSQL($fieldDeclaration);
}
-
/**
* Obtains DBMS specific SQL to be used to create date fields in statements
* like CREATE TABLE.
@@ -3154,7 +3187,7 @@ public function supportsForeignKeyConstraints()
*/
public function supportsForeignKeyOnUpdate()
{
- return $this->supportsForeignKeyConstraints() && true;
+ return $this->supportsForeignKeyConstraints();
}
/**
diff --git a/lib/Doctrine/DBAL/Platforms/DB2Platform.php b/lib/Doctrine/DBAL/Platforms/DB2Platform.php
index 605122115d4..25d4163b6ec 100644
--- a/lib/Doctrine/DBAL/Platforms/DB2Platform.php
+++ b/lib/Doctrine/DBAL/Platforms/DB2Platform.php
@@ -6,9 +6,9 @@
use Doctrine\DBAL\Schema\ColumnDiff;
use Doctrine\DBAL\Schema\Identifier;
use Doctrine\DBAL\Schema\Index;
-use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use function array_merge;
use function count;
use function current;
@@ -97,7 +97,7 @@ public function initializeDoctrineTypeMappings()
*/
public function isCommentedDoctrineType(Type $doctrineType)
{
- if ($doctrineType->getName() === Type::BOOLEAN) {
+ if ($doctrineType->getName() === Types::BOOLEAN) {
// We require a commented boolean type in order to distinguish between boolean and smallint
// as both (have to) map to the same native type.
return true;
@@ -502,6 +502,7 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options
foreach ($indexes as $definition) {
$sqls[] = $this->getCreateIndexSQL($definition, $tableName);
}
+
return $sqls;
}
@@ -571,7 +572,7 @@ public function getAlterTableSQL(TableDiff $diff)
}
}
- $this->gatherAlterColumnSQL($diff->fromTable, $columnDiff, $sql, $queryParts);
+ $this->gatherAlterColumnSQL($diff->getName($this), $columnDiff, $sql, $queryParts);
}
foreach ($diff->renamedColumns as $oldColumnName => $column) {
@@ -599,8 +600,14 @@ public function getAlterTableSQL(TableDiff $diff)
$sql = array_merge($sql, $commentsSQL);
- if ($diff->newName !== false) {
- $sql[] = 'RENAME TABLE ' . $diff->getName($this)->getQuotedName($this) . ' TO ' . $diff->getNewName()->getQuotedName($this);
+ $newName = $diff->getNewName();
+
+ if ($newName !== false) {
+ $sql[] = sprintf(
+ 'RENAME TABLE %s TO %s',
+ $diff->getName($this)->getQuotedName($this),
+ $newName->getQuotedName($this)
+ );
}
$sql = array_merge(
@@ -616,12 +623,12 @@ public function getAlterTableSQL(TableDiff $diff)
/**
* Gathers the table alteration SQL for a given column diff.
*
- * @param Table $table The table to gather the SQL for.
+ * @param Identifier $table The table to gather the SQL for.
* @param ColumnDiff $columnDiff The column diff to evaluate.
* @param string[] $sql The sequence of table alteration statements to fill.
* @param mixed[] $queryParts The sequence of column alteration clauses to fill.
*/
- private function gatherAlterColumnSQL(Table $table, ColumnDiff $columnDiff, array &$sql, array &$queryParts)
+ private function gatherAlterColumnSQL(Identifier $table, ColumnDiff $columnDiff, array &$sql, array &$queryParts)
{
$alterColumnClauses = $this->getAlterColumnClausesSQL($columnDiff);
@@ -893,4 +900,17 @@ protected function getReservedKeywordsClass()
{
return Keywords\DB2Keywords::class;
}
+
+ public function getListTableCommentsSQL(string $table) : string
+ {
+ return sprintf(
+ <<<'SQL'
+SELECT REMARKS
+ FROM SYSIBM.SYSTABLES
+ WHERE NAME = UPPER( %s )
+SQL
+ ,
+ $this->quoteStringLiteral($table)
+ );
+ }
}
diff --git a/lib/Doctrine/DBAL/Platforms/DrizzlePlatform.php b/lib/Doctrine/DBAL/Platforms/DrizzlePlatform.php
index 27aacf42286..8f6f0966323 100644
--- a/lib/Doctrine/DBAL/Platforms/DrizzlePlatform.php
+++ b/lib/Doctrine/DBAL/Platforms/DrizzlePlatform.php
@@ -47,9 +47,7 @@ public function getIdentifierQuoteCharacter()
*/
public function getConcatExpression()
{
- $args = func_get_args();
-
- return 'CONCAT(' . implode(', ', (array) $args) . ')';
+ return 'CONCAT(' . implode(', ', func_get_args()) . ')';
}
/**
@@ -480,8 +478,10 @@ public function getAlterTableSQL(TableDiff $diff)
$columnSql = [];
$queryParts = [];
- if ($diff->newName !== false) {
- $queryParts[] = 'RENAME TO ' . $diff->getNewName()->getQuotedName($this);
+ $newName = $diff->getNewName();
+
+ if ($newName !== false) {
+ $queryParts[] = 'RENAME TO ' . $newName->getQuotedName($this);
}
foreach ($diff->addedColumns as $column) {
@@ -576,7 +576,7 @@ public function convertBooleans($item)
{
if (is_array($item)) {
foreach ($item as $key => $value) {
- if (! is_bool($value) && ! is_numeric($item)) {
+ if (! is_bool($value) && ! is_numeric($value)) {
continue;
}
diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/MySQL80Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/MySQL80Keywords.php
index 4b595d53a08..ec1562d2433 100644
--- a/lib/Doctrine/DBAL/Platforms/Keywords/MySQL80Keywords.php
+++ b/lib/Doctrine/DBAL/Platforms/Keywords/MySQL80Keywords.php
@@ -28,6 +28,7 @@ protected function getKeywords()
$keywords = array_merge($keywords, [
'ADMIN',
+ 'ARRAY',
'CUBE',
'CUME_DIST',
'DENSE_RANK',
@@ -40,7 +41,9 @@ protected function getKeywords()
'JSON_TABLE',
'LAG',
'LAST_VALUE',
+ 'LATERAL',
'LEAD',
+ 'MEMBER',
'NTH_VALUE',
'NTILE',
'OF',
diff --git a/lib/Doctrine/DBAL/Platforms/MariaDb1027Platform.php b/lib/Doctrine/DBAL/Platforms/MariaDb1027Platform.php
index 25420a0476e..6c57082c586 100644
--- a/lib/Doctrine/DBAL/Platforms/MariaDb1027Platform.php
+++ b/lib/Doctrine/DBAL/Platforms/MariaDb1027Platform.php
@@ -2,7 +2,7 @@
namespace Doctrine\DBAL\Platforms;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
/**
* Provides the behavior, features and SQL dialect of the MariaDB 10.2 (10.2.7 GA) database platform.
@@ -36,6 +36,6 @@ protected function initializeDoctrineTypeMappings() : void
{
parent::initializeDoctrineTypeMappings();
- $this->doctrineTypeMapping['json'] = Type::JSON;
+ $this->doctrineTypeMapping['json'] = Types::JSON;
}
}
diff --git a/lib/Doctrine/DBAL/Platforms/MySQL57Platform.php b/lib/Doctrine/DBAL/Platforms/MySQL57Platform.php
index 71ef6ca96c7..1db7d6689b7 100644
--- a/lib/Doctrine/DBAL/Platforms/MySQL57Platform.php
+++ b/lib/Doctrine/DBAL/Platforms/MySQL57Platform.php
@@ -4,7 +4,7 @@
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\TableDiff;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
/**
* Provides the behavior, features and SQL dialect of the MySQL 5.7 (5.7.9 GA) database platform.
@@ -66,6 +66,6 @@ protected function initializeDoctrineTypeMappings()
{
parent::initializeDoctrineTypeMappings();
- $this->doctrineTypeMapping['json'] = Type::JSON;
+ $this->doctrineTypeMapping['json'] = Types::JSON;
}
}
diff --git a/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php b/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php
index 98228fc50b3..57c448ce93e 100644
--- a/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php
+++ b/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php
@@ -154,11 +154,10 @@ public function getListTableIndexesSQL($table, $currentDatabase = null)
$currentDatabase = $this->quoteStringLiteral($currentDatabase);
$table = $this->quoteStringLiteral($table);
- return 'SELECT TABLE_NAME AS `Table`, NON_UNIQUE AS Non_Unique, INDEX_NAME AS Key_name, ' .
- 'SEQ_IN_INDEX AS Seq_in_index, COLUMN_NAME AS Column_Name, COLLATION AS Collation, ' .
- 'CARDINALITY AS Cardinality, SUB_PART AS Sub_Part, PACKED AS Packed, ' .
- 'NULLABLE AS `Null`, INDEX_TYPE AS Index_Type, COMMENT AS Comment ' .
- 'FROM information_schema.STATISTICS WHERE TABLE_NAME = ' . $table . ' AND TABLE_SCHEMA = ' . $currentDatabase .
+ return 'SELECT NON_UNIQUE AS Non_Unique, INDEX_NAME AS Key_name, COLUMN_NAME AS Column_Name,' .
+ ' SUB_PART AS Sub_Part, INDEX_TYPE AS Index_Type' .
+ ' FROM information_schema.STATISTICS WHERE TABLE_NAME = ' . $table .
+ ' AND TABLE_SCHEMA = ' . $currentDatabase .
' ORDER BY SEQ_IN_INDEX ASC';
}
@@ -504,7 +503,7 @@ private function buildTableOptions(array $options)
$options['collate'] = $options['charset'] . '_unicode_ci';
}
- $tableOptions[] = sprintf('COLLATE %s', $options['collate']);
+ $tableOptions[] = $this->getColumnCollationDeclarationSQL($options['collate']);
// Engine
if (! isset($options['engine'])) {
@@ -520,9 +519,7 @@ private function buildTableOptions(array $options)
// Comment
if (isset($options['comment'])) {
- $comment = trim($options['comment'], " '");
-
- $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($comment));
+ $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($options['comment']));
}
// Row format
@@ -554,8 +551,10 @@ public function getAlterTableSQL(TableDiff $diff)
{
$columnSql = [];
$queryParts = [];
- if ($diff->newName !== false) {
- $queryParts[] = 'RENAME TO ' . $diff->getNewName()->getQuotedName($this);
+ $newName = $diff->getNewName();
+
+ if ($newName !== false) {
+ $queryParts[] = 'RENAME TO ' . $newName->getQuotedName($this);
}
foreach ($diff->addedColumns as $column) {
@@ -613,6 +612,17 @@ public function getAlterTableSQL(TableDiff $diff)
$keyColumns = array_unique(array_values($diff->addedIndexes['primary']->getColumns()));
$queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
unset($diff->addedIndexes['primary']);
+ } elseif (isset($diff->changedIndexes['primary'])) {
+ // Necessary in case the new primary key includes a new auto_increment column
+ foreach ($diff->changedIndexes['primary']->getColumns() as $columnName) {
+ if (isset($diff->addedColumns[$columnName]) && $diff->addedColumns[$columnName]->getAutoincrement()) {
+ $keyColumns = array_unique(array_values($diff->changedIndexes['primary']->getColumns()));
+ $queryParts[] = 'DROP PRIMARY KEY';
+ $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
+ unset($diff->changedIndexes['primary']);
+ break;
+ }
+ }
}
$sql = [];
@@ -845,10 +855,14 @@ protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
*/
protected function getPostAlterTableRenameIndexForeignKeySQL(TableDiff $diff)
{
- $sql = [];
- $tableName = $diff->newName !== false
- ? $diff->getNewName()->getQuotedName($this)
- : $diff->getName($this)->getQuotedName($this);
+ $sql = [];
+ $newName = $diff->getNewName();
+
+ if ($newName !== false) {
+ $tableName = $newName->getQuotedName($this);
+ } else {
+ $tableName = $diff->getName($this)->getQuotedName($this);
+ }
foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
@@ -943,6 +957,22 @@ protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
return $this->getUnsignedDeclaration($columnDef) . $autoinc;
}
+ /**
+ * {@inheritDoc}
+ */
+ public function getColumnCharsetDeclarationSQL($charset)
+ {
+ return 'CHARACTER SET ' . $charset;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public function getColumnCollationDeclarationSQL($collation)
+ {
+ return 'COLLATE ' . $this->quoteSingleIdentifier($collation);
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/lib/Doctrine/DBAL/Platforms/OraclePlatform.php b/lib/Doctrine/DBAL/Platforms/OraclePlatform.php
index 537a566bada..21b13a2d691 100644
--- a/lib/Doctrine/DBAL/Platforms/OraclePlatform.php
+++ b/lib/Doctrine/DBAL/Platforms/OraclePlatform.php
@@ -201,9 +201,13 @@ private function getSequenceCacheSQL(Sequence $sequence)
{
if ($sequence->getCache() === 0) {
return ' NOCACHE';
- } elseif ($sequence->getCache() === 1) {
+ }
+
+ if ($sequence->getCache() === 1) {
return ' NOCACHE';
- } elseif ($sequence->getCache() > 1) {
+ }
+
+ if ($sequence->getCache() > 1) {
return ' CACHE ' . $sequence->getCache();
}
@@ -869,8 +873,14 @@ public function getAlterTableSQL(TableDiff $diff)
if (! $this->onSchemaAlterTable($diff, $tableSql)) {
$sql = array_merge($sql, $commentsSQL);
- if ($diff->newName !== false) {
- $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' RENAME TO ' . $diff->getNewName()->getQuotedName($this);
+ $newName = $diff->getNewName();
+
+ if ($newName !== false) {
+ $sql[] = sprintf(
+ 'ALTER TABLE %s RENAME TO %s',
+ $diff->getName($this)->getQuotedName($this),
+ $newName->getQuotedName($this)
+ );
}
$sql = array_merge(
@@ -1172,4 +1182,25 @@ public function getBlobTypeDeclarationSQL(array $field)
{
return 'BLOB';
}
+
+ public function getListTableCommentsSQL(string $table, ?string $database = null) : string
+ {
+ $tableCommentsName = 'user_tab_comments';
+ $ownerCondition = '';
+
+ if ($database !== null && $database !== '/') {
+ $tableCommentsName = 'all_tab_comments';
+ $ownerCondition = ' AND owner = ' . $this->quoteStringLiteral($this->normalizeIdentifier($database)->getName());
+ }
+
+ return sprintf(
+ <<<'SQL'
+SELECT comments FROM %s WHERE table_name = %s%s
+SQL
+ ,
+ $tableCommentsName,
+ $this->quoteStringLiteral($this->normalizeIdentifier($table)->getName()),
+ $ownerCondition
+ );
+ }
}
diff --git a/lib/Doctrine/DBAL/Platforms/PostgreSQL92Platform.php b/lib/Doctrine/DBAL/Platforms/PostgreSQL92Platform.php
index b302c0ceb83..1703056143f 100644
--- a/lib/Doctrine/DBAL/Platforms/PostgreSQL92Platform.php
+++ b/lib/Doctrine/DBAL/Platforms/PostgreSQL92Platform.php
@@ -2,7 +2,7 @@
namespace Doctrine\DBAL\Platforms;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use function sprintf;
/**
@@ -53,7 +53,7 @@ protected function initializeDoctrineTypeMappings()
{
parent::initializeDoctrineTypeMappings();
- $this->doctrineTypeMapping['json'] = Type::JSON;
+ $this->doctrineTypeMapping['json'] = Types::JSON;
}
/**
diff --git a/lib/Doctrine/DBAL/Platforms/PostgreSQL94Platform.php b/lib/Doctrine/DBAL/Platforms/PostgreSQL94Platform.php
index 9db0ecbbd2a..fb559dea2ac 100644
--- a/lib/Doctrine/DBAL/Platforms/PostgreSQL94Platform.php
+++ b/lib/Doctrine/DBAL/Platforms/PostgreSQL94Platform.php
@@ -2,7 +2,7 @@
namespace Doctrine\DBAL\Platforms;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
/**
* Provides the behavior, features and SQL dialect of the PostgreSQL 9.4 database platform.
@@ -36,6 +36,6 @@ protected function initializeDoctrineTypeMappings()
{
parent::initializeDoctrineTypeMappings();
- $this->doctrineTypeMapping['jsonb'] = Type::JSON;
+ $this->doctrineTypeMapping['jsonb'] = Types::JSON;
}
}
diff --git a/lib/Doctrine/DBAL/Platforms/PostgreSqlPlatform.php b/lib/Doctrine/DBAL/Platforms/PostgreSqlPlatform.php
index cb4603f5199..e570dc04ab0 100644
--- a/lib/Doctrine/DBAL/Platforms/PostgreSqlPlatform.php
+++ b/lib/Doctrine/DBAL/Platforms/PostgreSqlPlatform.php
@@ -614,8 +614,14 @@ public function getAlterTableSQL(TableDiff $diff)
if (! $this->onSchemaAlterTable($diff, $tableSql)) {
$sql = array_merge($sql, $commentsSQL);
- if ($diff->newName !== false) {
- $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' RENAME TO ' . $diff->getNewName()->getQuotedName($this);
+ $newName = $diff->getNewName();
+
+ if ($newName !== false) {
+ $sql[] = sprintf(
+ 'ALTER TABLE %s RENAME TO %s',
+ $diff->getName($this)->getQuotedName($this),
+ $newName->getQuotedName($this)
+ );
}
$sql = array_merge(
@@ -815,7 +821,7 @@ private function convertSingleBooleanValue($value, $callback)
}
if (is_bool($value) || is_numeric($value)) {
- return $callback($value ? true : false);
+ return $callback((bool) $value);
}
if (! is_string($value)) {
@@ -1215,7 +1221,8 @@ public function getDefaultValueDeclarationSQL($field)
*/
private function isSerialField(array $field) : bool
{
- return $field['autoincrement'] ?? false === true && isset($field['type'])
+ return isset($field['type'], $field['autoincrement'])
+ && $field['autoincrement'] === true
&& $this->isNumericType($field['type']);
}
@@ -1245,4 +1252,19 @@ private function getOldColumnComment(ColumnDiff $columnDiff) : ?string
{
return $columnDiff->fromColumn ? $this->getColumnComment($columnDiff->fromColumn) : null;
}
+
+ public function getListTableMetadataSQL(string $table, ?string $schema = null) : string
+ {
+ if ($schema !== null) {
+ $table = $schema . '.' . $table;
+ }
+
+ return sprintf(
+ <<<'SQL'
+SELECT obj_description(%s::regclass) AS table_comment;
+SQL
+ ,
+ $this->quoteStringLiteral($table)
+ );
+ }
}
diff --git a/lib/Doctrine/DBAL/Platforms/SQLAnywherePlatform.php b/lib/Doctrine/DBAL/Platforms/SQLAnywherePlatform.php
index ec3ef933441..6e3b2fcb958 100644
--- a/lib/Doctrine/DBAL/Platforms/SQLAnywherePlatform.php
+++ b/lib/Doctrine/DBAL/Platforms/SQLAnywherePlatform.php
@@ -23,7 +23,7 @@
use function get_class;
use function implode;
use function is_string;
-use function preg_replace;
+use function preg_match;
use function sprintf;
use function strlen;
use function strpos;
@@ -184,9 +184,11 @@ public function getAlterTableSQL(TableDiff $diff)
$sql = array_merge($sql, $commentsSQL);
- if ($diff->newName !== false) {
+ $newName = $diff->getNewName();
+
+ if ($newName !== false) {
$sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' .
- $this->getAlterTableRenameTableClause($diff->getNewName());
+ $this->getAlterTableRenameTableClause($newName);
}
$sql = array_merge(
@@ -625,12 +627,15 @@ public function getForeignKeyMatchClauseSQL($type)
switch ((int) $type) {
case self::FOREIGN_KEY_MATCH_SIMPLE:
return 'SIMPLE';
+
break;
case self::FOREIGN_KEY_MATCH_FULL:
return 'FULL';
+
break;
case self::FOREIGN_KEY_MATCH_SIMPLE_UNIQUE:
return 'UNIQUE SIMPLE';
+
break;
case self::FOREIGN_KEY_MATCH_FULL_UNIQUE:
return 'UNIQUE FULL';
@@ -1310,9 +1315,15 @@ protected function doModifyLimitQuery($query, $limit, $offset)
{
$limitOffsetClause = $this->getTopClauseSQL($limit, $offset);
- return $limitOffsetClause === ''
- ? $query
- : preg_replace('/^\s*(SELECT\s+(DISTINCT\s+)?)/i', '\1' . $limitOffsetClause . ' ', $query);
+ if ($limitOffsetClause === '') {
+ return $query;
+ }
+
+ if (! preg_match('/^\s*(SELECT\s+(DISTINCT\s+)?)(.*)/i', $query, $matches)) {
+ return $query;
+ }
+
+ return $matches[1] . $limitOffsetClause . ' ' . $matches[3];
}
private function getTopClauseSQL(?int $limit, ?int $offset) : string
diff --git a/lib/Doctrine/DBAL/Platforms/SQLServerPlatform.php b/lib/Doctrine/DBAL/Platforms/SQLServerPlatform.php
index 670b4596645..a37f7c9394a 100644
--- a/lib/Doctrine/DBAL/Platforms/SQLServerPlatform.php
+++ b/lib/Doctrine/DBAL/Platforms/SQLServerPlatform.php
@@ -25,7 +25,6 @@
use function is_numeric;
use function is_string;
use function preg_match;
-use function preg_replace;
use function sprintf;
use function str_replace;
use function stripos;
@@ -248,6 +247,11 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options
$defaultConstraintsSql = [];
$commentsSql = [];
+ $tableComment = $options['comment'] ?? null;
+ if ($tableComment !== null) {
+ $commentsSql[] = $this->getCommentOnTableSQL($tableName, $tableComment);
+ }
+
// @todo does other code breaks because of this?
// force primary keys to be not null
foreach ($columns as &$column) {
@@ -314,12 +318,19 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options
*/
public function getCreatePrimaryKeySQL(Index $index, $table)
{
- $flags = '';
+ if ($table instanceof Table) {
+ $identifier = $table->getQuotedName($this);
+ } else {
+ $identifier = $table;
+ }
+
+ $sql = 'ALTER TABLE ' . $identifier . ' ADD PRIMARY KEY';
+
if ($index->hasFlag('nonclustered')) {
- $flags = ' NONCLUSTERED';
+ $sql .= ' NONCLUSTERED';
}
- return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY' . $flags . ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
+ return $sql . ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
}
/**
@@ -333,9 +344,9 @@ public function getCreatePrimaryKeySQL(Index $index, $table)
* as column comments are stored in the same property there when
* specifying a column's "Description" attribute.
*
- * @param string $tableName The quoted table name to which the column belongs.
- * @param string $columnName The quoted column name to create the comment for.
- * @param string $comment The column's comment.
+ * @param string $tableName The quoted table name to which the column belongs.
+ * @param string $columnName The quoted column name to create the comment for.
+ * @param string|null $comment The column's comment.
*
* @return string
*/
@@ -583,8 +594,10 @@ public function getAlterTableSQL(TableDiff $diff)
$sql = array_merge($sql, $commentsSql);
- if ($diff->newName !== false) {
- $sql[] = "sp_RENAME '" . $diff->getName($this)->getQuotedName($this) . "', '" . $diff->getNewName()->getName() . "'";
+ $newName = $diff->getNewName();
+
+ if ($newName !== false) {
+ $sql[] = "sp_RENAME '" . $diff->getName($this)->getQuotedName($this) . "', '" . $newName->getName() . "'";
/**
* Rename table's default constraints names
@@ -597,10 +610,10 @@ public function getAlterTableSQL(TableDiff $diff)
$sql[] = "DECLARE @sql NVARCHAR(MAX) = N''; " .
"SELECT @sql += N'EXEC sp_rename N''' + dc.name + ''', N''' " .
"+ REPLACE(dc.name, '" . $this->generateIdentifierName($diff->name) . "', " .
- "'" . $this->generateIdentifierName($diff->newName) . "') + ''', ''OBJECT'';' " .
+ "'" . $this->generateIdentifierName($newName->getName()) . "') + ''', ''OBJECT'';' " .
'FROM sys.default_constraints dc ' .
'JOIN sys.tables tbl ON dc.parent_object_id = tbl.object_id ' .
- "WHERE tbl.name = '" . $diff->getNewName()->getName() . "';" .
+ "WHERE tbl.name = '" . $newName->getName() . "';" .
'EXEC sp_executesql @sql';
}
@@ -690,9 +703,9 @@ private function alterColumnRequiresDropDefaultConstraint(ColumnDiff $columnDiff
* as column comments are stored in the same property there when
* specifying a column's "Description" attribute.
*
- * @param string $tableName The quoted table name to which the column belongs.
- * @param string $columnName The quoted column name to alter the comment for.
- * @param string $comment The column's comment.
+ * @param string $tableName The quoted table name to which the column belongs.
+ * @param string $columnName The quoted column name to alter the comment for.
+ * @param string|null $comment The column's comment.
*
* @return string
*/
@@ -798,10 +811,10 @@ public function getAddExtendedPropertySQL(
$level2Name = null
) {
return 'EXEC sp_addextendedproperty ' .
- 'N' . $this->quoteStringLiteral($name) . ', N' . $this->quoteStringLiteral($value) . ', ' .
- 'N' . $this->quoteStringLiteral($level0Type) . ', ' . $level0Name . ', ' .
- 'N' . $this->quoteStringLiteral($level1Type) . ', ' . $level1Name . ', ' .
- 'N' . $this->quoteStringLiteral($level2Type) . ', ' . $level2Name;
+ 'N' . $this->quoteStringLiteral($name) . ', N' . $this->quoteStringLiteral((string) $value) . ', ' .
+ 'N' . $this->quoteStringLiteral((string) $level0Type) . ', ' . $level0Name . ', ' .
+ 'N' . $this->quoteStringLiteral((string) $level1Type) . ', ' . $level1Name . ', ' .
+ 'N' . $this->quoteStringLiteral((string) $level2Type) . ', ' . $level2Name;
}
/**
@@ -830,9 +843,9 @@ public function getDropExtendedPropertySQL(
) {
return 'EXEC sp_dropextendedproperty ' .
'N' . $this->quoteStringLiteral($name) . ', ' .
- 'N' . $this->quoteStringLiteral($level0Type) . ', ' . $level0Name . ', ' .
- 'N' . $this->quoteStringLiteral($level1Type) . ', ' . $level1Name . ', ' .
- 'N' . $this->quoteStringLiteral($level2Type) . ', ' . $level2Name;
+ 'N' . $this->quoteStringLiteral((string) $level0Type) . ', ' . $level0Name . ', ' .
+ 'N' . $this->quoteStringLiteral((string) $level1Type) . ', ' . $level1Name . ', ' .
+ 'N' . $this->quoteStringLiteral((string) $level2Type) . ', ' . $level2Name;
}
/**
@@ -862,10 +875,10 @@ public function getUpdateExtendedPropertySQL(
$level2Name = null
) {
return 'EXEC sp_updateextendedproperty ' .
- 'N' . $this->quoteStringLiteral($name) . ', N' . $this->quoteStringLiteral($value) . ', ' .
- 'N' . $this->quoteStringLiteral($level0Type) . ', ' . $level0Name . ', ' .
- 'N' . $this->quoteStringLiteral($level1Type) . ', ' . $level1Name . ', ' .
- 'N' . $this->quoteStringLiteral($level2Type) . ', ' . $level2Name;
+ 'N' . $this->quoteStringLiteral($name) . ', N' . $this->quoteStringLiteral((string) $value) . ', ' .
+ 'N' . $this->quoteStringLiteral((string) $level0Type) . ', ' . $level0Name . ', ' .
+ 'N' . $this->quoteStringLiteral((string) $level1Type) . ', ' . $level1Name . ', ' .
+ 'N' . $this->quoteStringLiteral((string) $level2Type) . ', ' . $level2Name;
}
/**
@@ -1269,9 +1282,11 @@ protected function doModifyLimitQuery($query, $limit, $offset = null)
// Even if the TOP n is very large, the use of a CTE will
// allow the SQL Server query planner to optimize it so it doesn't
// actually scan the entire range covered by the TOP clause.
- $selectPattern = '/^(\s*SELECT\s+(?:DISTINCT\s+)?)(.*)$/im';
- $replacePattern = sprintf('$1%s $2', $top);
- $query = preg_replace($selectPattern, $replacePattern, $query);
+ if (! preg_match('/^(\s*SELECT\s+(?:DISTINCT\s+)?)(.*)$/is', $query, $matches)) {
+ return $query;
+ }
+
+ $query = $matches[1] . $top . ' ' . $matches[2];
if (stristr($query, 'ORDER BY')) {
// Inner order by is not valid in SQL Server for our purposes
@@ -1338,6 +1353,7 @@ private function scrubInnerOrderBy($query)
$query = substr($query, 0, $orderByPos) . substr($query, $currentPosition - 1);
$offset = $orderByPos;
}
+
return $query;
}
@@ -1388,7 +1404,7 @@ public function convertBooleans($item)
{
if (is_array($item)) {
foreach ($item as $key => $value) {
- if (! is_bool($value) && ! is_numeric($item)) {
+ if (! is_bool($value) && ! is_numeric($value)) {
continue;
}
@@ -1645,4 +1661,35 @@ private function generateIdentifierName($identifier)
return strtoupper(dechex(crc32($identifier->getName())));
}
+
+ protected function getCommentOnTableSQL(string $tableName, ?string $comment) : string
+ {
+ return sprintf(
+ <<<'SQL'
+EXEC sys.sp_addextendedproperty @name=N'MS_Description',
+ @value=N%s, @level0type=N'SCHEMA', @level0name=N'dbo',
+ @level1type=N'TABLE', @level1name=N%s
+SQL
+ ,
+ $this->quoteStringLiteral((string) $comment),
+ $this->quoteStringLiteral($tableName)
+ );
+ }
+
+ public function getListTableMetadataSQL(string $table) : string
+ {
+ return sprintf(
+ <<<'SQL'
+SELECT
+ p.value AS [table_comment]
+FROM
+ sys.tables AS tbl
+ INNER JOIN sys.extended_properties AS p ON p.major_id=tbl.object_id AND p.minor_id=0 AND p.class=1
+WHERE
+ (tbl.name=N%s and SCHEMA_NAME(tbl.schema_id)=N'dbo' and p.name=N'MS_Description')
+SQL
+ ,
+ $this->quoteStringLiteral($table)
+ );
+ }
}
diff --git a/lib/Doctrine/DBAL/Platforms/SqlitePlatform.php b/lib/Doctrine/DBAL/Platforms/SqlitePlatform.php
index 819421d3469..02d2482c86e 100644
--- a/lib/Doctrine/DBAL/Platforms/SqlitePlatform.php
+++ b/lib/Doctrine/DBAL/Platforms/SqlitePlatform.php
@@ -23,6 +23,7 @@
use function strlen;
use function strpos;
use function strtolower;
+use function trim;
/**
* The SqlitePlatform class describes the specifics and dialects of the SQLite
@@ -332,7 +333,14 @@ protected function _getCreateTableSQL($name, array $columns, array $options = []
}
}
- $query = ['CREATE TABLE ' . $name . ' (' . $queryFields . ')'];
+ $tableComment = '';
+ if (isset($options['comment'])) {
+ $comment = trim($options['comment'], " '");
+
+ $tableComment = $this->getInlineTableCommentSQL($comment);
+ }
+
+ $query = ['CREATE TABLE ' . $name . ' ' . $tableComment . '(' . $queryFields . ')'];
if (isset($options['alter']) && $options['alter'] === true) {
return $query;
@@ -356,8 +364,8 @@ protected function _getCreateTableSQL($name, array $columns, array $options = []
/**
* Generate a PRIMARY KEY definition if no autoincrement value is used
*
- * @param string[] $columns
- * @param mixed[] $options
+ * @param mixed[][] $columns
+ * @param mixed[] $options
*/
private function getNonAutoincrementPrimaryKeyDefinition(array $columns, array $options) : string
{
@@ -368,7 +376,7 @@ private function getNonAutoincrementPrimaryKeyDefinition(array $columns, array $
$keyColumns = array_unique(array_values($options['primary']));
foreach ($keyColumns as $keyColumn) {
- if (isset($columns[$keyColumn]['autoincrement']) && ! empty($columns[$keyColumn]['autoincrement'])) {
+ if (! empty($columns[$keyColumn]['autoincrement'])) {
return '';
}
}
@@ -605,6 +613,11 @@ public function getInlineColumnCommentSQL($comment)
return '--' . str_replace("\n", "\n--", $comment) . "\n";
}
+ private function getInlineTableCommentSQL(string $comment) : string
+ {
+ return $this->getInlineColumnCommentSQL($comment);
+ }
+
/**
* {@inheritDoc}
*/
@@ -685,7 +698,12 @@ protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
}
$sql = [];
- $tableName = $diff->newName ? $diff->getNewName(): $diff->getName($this);
+ $tableName = $diff->getNewName();
+
+ if ($tableName === false) {
+ $tableName = $diff->getName($this);
+ }
+
foreach ($this->getIndexesInAlteredTable($diff) as $index) {
if ($index->isPrimary()) {
continue;
@@ -908,9 +926,14 @@ public function getAlterTableSQL(TableDiff $diff)
$sql[] = sprintf('INSERT INTO %s (%s) SELECT %s FROM %s', $newTable->getQuotedName($this), implode(', ', $newColumnNames), implode(', ', $oldColumnNames), $dataTable->getQuotedName($this));
$sql[] = $this->getDropTableSQL($dataTable);
- if ($diff->newName && $diff->newName !== $diff->name) {
- $renamedTable = $diff->getNewName();
- $sql[] = 'ALTER TABLE ' . $newTable->getQuotedName($this) . ' RENAME TO ' . $renamedTable->getQuotedName($this);
+ $newName = $diff->getNewName();
+
+ if ($newName !== false) {
+ $sql[] = sprintf(
+ 'ALTER TABLE %s RENAME TO %s',
+ $newTable->getQuotedName($this),
+ $newName->getQuotedName($this)
+ );
}
$sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
@@ -1028,7 +1051,8 @@ private function getColumnNamesInAlteredTable(TableDiff $diff)
$columns[strtolower($columnName)] = $columnName;
}
- foreach ($diff->addedColumns as $columnName => $column) {
+ foreach ($diff->addedColumns as $column) {
+ $columnName = $column->getName();
$columns[strtolower($columnName)] = $columnName;
}
@@ -1059,12 +1083,14 @@ private function getIndexesInAlteredTable(TableDiff $diff)
if (! isset($columnNames[$normalizedColumnName])) {
unset($indexes[$key]);
continue 2;
- } else {
- $indexColumns[] = $columnNames[$normalizedColumnName];
- if ($columnName !== $columnNames[$normalizedColumnName]) {
- $changed = true;
- }
}
+
+ $indexColumns[] = $columnNames[$normalizedColumnName];
+ if ($columnName === $columnNames[$normalizedColumnName]) {
+ continue;
+ }
+
+ $changed = true;
}
if (! $changed) {
@@ -1111,12 +1137,14 @@ private function getForeignKeysInAlteredTable(TableDiff $diff)
if (! isset($columnNames[$normalizedColumnName])) {
unset($foreignKeys[$key]);
continue 2;
- } else {
- $localColumns[] = $columnNames[$normalizedColumnName];
- if ($columnName !== $columnNames[$normalizedColumnName]) {
- $changed = true;
- }
}
+
+ $localColumns[] = $columnNames[$normalizedColumnName];
+ if ($columnName === $columnNames[$normalizedColumnName]) {
+ continue;
+ }
+
+ $changed = true;
}
if (! $changed) {
@@ -1127,6 +1155,10 @@ private function getForeignKeysInAlteredTable(TableDiff $diff)
}
foreach ($diff->removedForeignKeys as $constraint) {
+ if (! $constraint instanceof ForeignKeyConstraint) {
+ $constraint = new Identifier($constraint);
+ }
+
$constraintName = strtolower($constraint->getName());
if (! strlen($constraintName) || ! isset($foreignKeys[$constraintName])) {
continue;
diff --git a/lib/Doctrine/DBAL/Portability/Connection.php b/lib/Doctrine/DBAL/Portability/Connection.php
index 32186dcb0ec..7b4af8a8799 100644
--- a/lib/Doctrine/DBAL/Portability/Connection.php
+++ b/lib/Doctrine/DBAL/Portability/Connection.php
@@ -121,9 +121,9 @@ public function prepare($statement)
*/
public function query()
{
- $this->connect();
+ $connection = $this->getWrappedConnection();
- $stmt = $this->_conn->query(...func_get_args());
+ $stmt = $connection->query(...func_get_args());
$stmt = new Statement($stmt, $this);
$stmt->setFetchMode($this->defaultFetchMode);
diff --git a/lib/Doctrine/DBAL/Portability/Statement.php b/lib/Doctrine/DBAL/Portability/Statement.php
index 1499ff1bf48..514b3be2d74 100644
--- a/lib/Doctrine/DBAL/Portability/Statement.php
+++ b/lib/Doctrine/DBAL/Portability/Statement.php
@@ -2,6 +2,7 @@
namespace Doctrine\DBAL\Portability;
+use Doctrine\DBAL\Driver\ResultStatement;
use Doctrine\DBAL\Driver\Statement as DriverStatement;
use Doctrine\DBAL\Driver\StatementIterator;
use Doctrine\DBAL\FetchMode;
@@ -9,6 +10,7 @@
use IteratorAggregate;
use PDO;
use function array_change_key_case;
+use function assert;
use function is_string;
use function rtrim;
@@ -20,7 +22,7 @@ class Statement implements IteratorAggregate, DriverStatement
/** @var int */
private $portability;
- /** @var DriverStatement */
+ /** @var DriverStatement|ResultStatement */
private $stmt;
/** @var int */
@@ -32,7 +34,7 @@ class Statement implements IteratorAggregate, DriverStatement
/**
* Wraps Statement and applies portability measures.
*
- * @param DriverStatement $stmt
+ * @param DriverStatement|ResultStatement $stmt
*/
public function __construct($stmt, Connection $conn)
{
@@ -46,6 +48,8 @@ public function __construct($stmt, Connection $conn)
*/
public function bindParam($column, &$variable, $type = ParameterType::STRING, $length = null)
{
+ assert($this->stmt instanceof DriverStatement);
+
return $this->stmt->bindParam($column, $variable, $type, $length);
}
@@ -54,6 +58,8 @@ public function bindParam($column, &$variable, $type = ParameterType::STRING, $l
*/
public function bindValue($param, $value, $type = ParameterType::STRING)
{
+ assert($this->stmt instanceof DriverStatement);
+
return $this->stmt->bindValue($param, $value, $type);
}
@@ -78,6 +84,8 @@ public function columnCount()
*/
public function errorCode()
{
+ assert($this->stmt instanceof DriverStatement);
+
return $this->stmt->errorCode();
}
@@ -86,6 +94,8 @@ public function errorCode()
*/
public function errorInfo()
{
+ assert($this->stmt instanceof DriverStatement);
+
return $this->stmt->errorInfo();
}
@@ -94,6 +104,8 @@ public function errorInfo()
*/
public function execute($params = null)
{
+ assert($this->stmt instanceof DriverStatement);
+
return $this->stmt->execute($params);
}
@@ -228,6 +240,8 @@ public function fetchColumn($columnIndex = 0)
*/
public function rowCount()
{
+ assert($this->stmt instanceof DriverStatement);
+
return $this->stmt->rowCount();
}
}
diff --git a/lib/Doctrine/DBAL/Query/Expression/ExpressionBuilder.php b/lib/Doctrine/DBAL/Query/Expression/ExpressionBuilder.php
index 91f370aecb6..dfcc31ec709 100644
--- a/lib/Doctrine/DBAL/Query/Expression/ExpressionBuilder.php
+++ b/lib/Doctrine/DBAL/Query/Expression/ExpressionBuilder.php
@@ -286,8 +286,8 @@ public function notIn($x, $y)
/**
* Quotes a given input parameter.
*
- * @param mixed $input The parameter to be quoted.
- * @param string|null $type The type of the parameter.
+ * @param mixed $input The parameter to be quoted.
+ * @param int|null $type The type of the parameter.
*
* @return string
*/
diff --git a/lib/Doctrine/DBAL/Query/QueryBuilder.php b/lib/Doctrine/DBAL/Query/QueryBuilder.php
index 12584d960ab..587e26656ab 100644
--- a/lib/Doctrine/DBAL/Query/QueryBuilder.php
+++ b/lib/Doctrine/DBAL/Query/QueryBuilder.php
@@ -52,22 +52,28 @@ class QueryBuilder
*/
private $connection;
+ /*
+ * The default values of SQL parts collection
+ */
+ private const SQL_PARTS_DEFAULTS = [
+ 'select' => [],
+ 'distinct' => false,
+ 'from' => [],
+ 'join' => [],
+ 'set' => [],
+ 'where' => null,
+ 'groupBy' => [],
+ 'having' => null,
+ 'orderBy' => [],
+ 'values' => [],
+ ];
+
/**
* The array of SQL parts collected.
*
* @var mixed[]
*/
- private $sqlParts = [
- 'select' => [],
- 'from' => [],
- 'join' => [],
- 'set' => [],
- 'where' => null,
- 'groupBy' => [],
- 'having' => null,
- 'orderBy' => [],
- 'values' => [],
- ];
+ private $sqlParts = self::SQL_PARTS_DEFAULTS;
/**
* The complete SQL string for this query.
@@ -403,7 +409,7 @@ public function getMaxResults()
* 'groupBy', 'having' and 'orderBy'.
*
* @param string $sqlPartName
- * @param string $sqlPart
+ * @param mixed $sqlPart
* @param bool $append
*
* @return $this This QueryBuilder instance.
@@ -469,6 +475,25 @@ public function select($select = null)
return $this->add('select', $selects);
}
+ /**
+ * Adds DISTINCT to the query.
+ *
+ *
+ * $qb = $conn->createQueryBuilder()
+ * ->select('u.id')
+ * ->distinct()
+ * ->from('users', 'u')
+ *
+ *
+ * @return $this This QueryBuilder instance.
+ */
+ public function distinct() : self
+ {
+ $this->sqlParts['distinct'] = true;
+
+ return $this;
+ }
+
/**
* Adds an item that is to be returned in the query result.
*
@@ -504,7 +529,7 @@ public function addSelect($select = null)
*
* $qb = $conn->createQueryBuilder()
* ->delete('users', 'u')
- * ->where('u.id = :user_id');
+ * ->where('u.id = :user_id')
* ->setParameter(':user_id', 1);
*
*
@@ -866,7 +891,6 @@ public function groupBy($groupBy)
return $this->add('groupBy', $groupBy, false);
}
-
/**
* Adds a grouping expression to the query.
*
@@ -874,8 +898,8 @@ public function groupBy($groupBy)
* $qb = $conn->createQueryBuilder()
* ->select('u.name')
* ->from('users', 'u')
- * ->groupBy('u.lastLogin');
- * ->addGroupBy('u.createdAt')
+ * ->groupBy('u.lastLogin')
+ * ->addGroupBy('u.createdAt');
*
*
* @param mixed $groupBy The grouping expression.
@@ -1084,8 +1108,7 @@ public function resetQueryParts($queryPartNames = null)
*/
public function resetQueryPart($queryPartName)
{
- $this->sqlParts[$queryPartName] = is_array($this->sqlParts[$queryPartName])
- ? [] : null;
+ $this->sqlParts[$queryPartName] = self::SQL_PARTS_DEFAULTS[$queryPartName];
$this->state = self::STATE_DIRTY;
@@ -1099,7 +1122,8 @@ public function resetQueryPart($queryPartName)
*/
private function getSQLForSelect()
{
- $query = 'SELECT ' . implode(', ', $this->sqlParts['select']);
+ $query = 'SELECT ' . ($this->sqlParts['distinct'] ? 'DISTINCT ' : '') .
+ implode(', ', $this->sqlParts['select']);
$query .= ($this->sqlParts['from'] ? ' FROM ' . implode(', ', $this->getFromClauses()) : '')
. ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '')
@@ -1188,6 +1212,7 @@ private function getSQLForInsert()
private function getSQLForUpdate()
{
$table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
+
return 'UPDATE ' . $table
. ' SET ' . implode(', ', $this->sqlParts['set'])
. ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
@@ -1201,6 +1226,7 @@ private function getSQLForUpdate()
private function getSQLForDelete()
{
$table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
+
return 'DELETE FROM ' . $table . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
}
diff --git a/lib/Doctrine/DBAL/SQLParserUtils.php b/lib/Doctrine/DBAL/SQLParserUtils.php
index 537cd9e4884..9768883846e 100644
--- a/lib/Doctrine/DBAL/SQLParserUtils.php
+++ b/lib/Doctrine/DBAL/SQLParserUtils.php
@@ -24,49 +24,93 @@
*/
class SQLParserUtils
{
+ /**#@+
+ *
+ * @deprecated Will be removed as internal implementation details.
+ */
public const POSITIONAL_TOKEN = '\?';
public const NAMED_TOKEN = '(? integer pair (indexed from zero) for a positional statement
- * and a string => int[] pair for a named statement.
+ * For a statement with positional parameters, returns a zero-indexed list of placeholder position.
+ * For a statement with named parameters, returns a map of placeholder positions to their parameter names.
+ *
+ * @deprecated Will be removed as internal implementation detail.
*
* @param string $statement
* @param bool $isPositional
*
- * @return int[]
+ * @return int[]|string[]
*/
public static function getPlaceholderPositions($statement, $isPositional = true)
{
- $match = $isPositional ? '?' : ':';
+ return $isPositional
+ ? self::getPositionalPlaceholderPositions($statement)
+ : self::getNamedPlaceholderPositions($statement);
+ }
+
+ /**
+ * Returns a zero-indexed list of placeholder position.
+ *
+ * @return int[]
+ */
+ private static function getPositionalPlaceholderPositions(string $statement) : array
+ {
+ return self::collectPlaceholders(
+ $statement,
+ '?',
+ self::POSITIONAL_TOKEN,
+ static function (string $_, int $placeholderPosition, int $fragmentPosition, array &$carry) : void {
+ $carry[] = $placeholderPosition + $fragmentPosition;
+ }
+ );
+ }
+
+ /**
+ * Returns a map of placeholder positions to their parameter names.
+ *
+ * @return string[]
+ */
+ private static function getNamedPlaceholderPositions(string $statement) : array
+ {
+ return self::collectPlaceholders(
+ $statement,
+ ':',
+ self::NAMED_TOKEN,
+ static function (string $placeholder, int $placeholderPosition, int $fragmentPosition, array &$carry) : void {
+ $carry[$placeholderPosition + $fragmentPosition] = substr($placeholder, 1);
+ }
+ );
+ }
+
+ /**
+ * @return mixed[]
+ */
+ private static function collectPlaceholders(string $statement, string $match, string $token, callable $collector) : array
+ {
if (strpos($statement, $match) === false) {
return [];
}
- $token = $isPositional ? self::POSITIONAL_TOKEN : self::NAMED_TOKEN;
- $paramMap = [];
+ $carry = [];
foreach (self::getUnquotedStatementFragments($statement) as $fragment) {
preg_match_all('/' . $token . '/', $fragment[0], $matches, PREG_OFFSET_CAPTURE);
foreach ($matches[0] as $placeholder) {
- if ($isPositional) {
- $paramMap[] = $placeholder[1] + $fragment[1];
- } else {
- $pos = $placeholder[1] + $fragment[1];
- $paramMap[$pos] = substr($placeholder[0], 1, strlen($placeholder[0]));
- }
+ $collector($placeholder[0], $placeholder[1], $fragment[1], $carry);
}
}
- return $paramMap;
+ return $carry;
}
/**
@@ -109,14 +153,14 @@ public static function expandListParameters($query, $params, $types)
return [$query, $params, $types];
}
- $paramPos = self::getPlaceholderPositions($query, $isPositional);
-
if ($isPositional) {
$paramOffset = 0;
$queryOffset = 0;
$params = array_values($params);
$types = array_values($types);
+ $paramPos = self::getPositionalPlaceholderPositions($query);
+
foreach ($paramPos as $needle => $needlePos) {
if (! isset($arrayPositions[$needle])) {
continue;
@@ -156,6 +200,8 @@ public static function expandListParameters($query, $params, $types)
$typesOrd = [];
$paramsOrd = [];
+ $paramPos = self::getNamedPlaceholderPositions($query);
+
foreach ($paramPos as $pos => $paramName) {
$paramLen = strlen($paramName) + 1;
$value = static::extractParam($paramName, $params, true);
diff --git a/lib/Doctrine/DBAL/Schema/AbstractAsset.php b/lib/Doctrine/DBAL/Schema/AbstractAsset.php
index eb7262e32a6..45af02f5cc9 100644
--- a/lib/Doctrine/DBAL/Schema/AbstractAsset.php
+++ b/lib/Doctrine/DBAL/Schema/AbstractAsset.php
@@ -84,7 +84,7 @@ public function getNamespaceName()
* The shortest name is stripped of the default namespace. All other
* namespaced elements are returned as full-qualified names.
*
- * @param string $defaultNamespaceName
+ * @param string|null $defaultNamespaceName
*
* @return string
*/
diff --git a/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php b/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php
index 9b917427fd8..8e4ffa5f966 100644
--- a/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php
+++ b/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php
@@ -14,10 +14,12 @@
use function array_intersect;
use function array_map;
use function array_values;
+use function assert;
use function call_user_func_array;
use function count;
use function func_get_args;
use function is_array;
+use function is_callable;
use function preg_match;
use function str_replace;
use function strtolower;
@@ -80,8 +82,11 @@ public function tryMethod()
unset($args[0]);
$args = array_values($args);
+ $callback = [$this, $method];
+ assert(is_callable($callback));
+
try {
- return call_user_func_array([$this, $method], $args);
+ return call_user_func_array($callback, $args);
} catch (Throwable $e) {
return false;
}
@@ -141,7 +146,7 @@ public function listSequences($database = null)
* this column definition does try to contain the 'primary' field for
* the reason that it is not portable across different RDBMS. Use
* {@see listTableIndexes($tableName)} to retrieve the primary key
- * of a table. We're a RDBMS specifies more details these are held
+ * of a table. Where a RDBMS specifies more details, these are held
* in the platformDetails array.
*
* @param string $table The name of the table.
@@ -183,7 +188,9 @@ public function listTableIndexes($table)
/**
* Returns true if all the given tables exist.
*
- * @param string[] $tableNames
+ * The usage of a string $tableNames is deprecated. Pass a one-element array instead.
+ *
+ * @param string|string[] $tableNames
*
* @return bool
*/
@@ -268,7 +275,7 @@ public function listTableDetails($tableName)
}
$indexes = $this->listTableIndexes($tableName);
- return new Table($tableName, $columns, $indexes, $foreignKeys, false, []);
+ return new Table($tableName, $columns, $indexes, $foreignKeys);
}
/**
@@ -678,6 +685,8 @@ protected function getPortableNamespaceDefinition(array $namespace)
}
/**
+ * @deprecated
+ *
* @param mixed[][] $functions
*
* @return mixed[][]
@@ -699,6 +708,8 @@ protected function _getPortableFunctionsList($functions)
}
/**
+ * @deprecated
+ *
* @param mixed[] $function
*
* @return mixed
@@ -747,14 +758,9 @@ protected function _getPortableTriggerDefinition($trigger)
protected function _getPortableSequencesList($sequences)
{
$list = [];
- foreach ($sequences as $value) {
- $value = $this->_getPortableSequenceDefinition($value);
-
- if (! $value) {
- continue;
- }
- $list[] = $value;
+ foreach ($sequences as $value) {
+ $list[] = $this->_getPortableSequenceDefinition($value);
}
return $list;
@@ -854,7 +860,7 @@ protected function _getPortableTableIndexesList($tableIndexRows, $tableName = nu
$result[$keyName] = [
'name' => $indexName,
'columns' => [],
- 'unique' => $tableIndex['non_unique'] ? false : true,
+ 'unique' => ! $tableIndex['non_unique'],
'primary' => $tableIndex['primary'],
'flags' => $tableIndex['flags'] ?? [],
'options' => $options,
@@ -947,9 +953,9 @@ protected function _getPortableUsersList($users)
}
/**
- * @param mixed[] $user
+ * @param string[] $user
*
- * @return mixed[]
+ * @return string[]
*/
protected function _getPortableUserDefinition($user)
{
@@ -996,14 +1002,9 @@ protected function _getPortableViewDefinition($view)
protected function _getPortableTableForeignKeysList($tableForeignKeys)
{
$list = [];
- foreach ($tableForeignKeys as $value) {
- $value = $this->_getPortableTableForeignKeyDefinition($value);
-
- if (! $value) {
- continue;
- }
- $list[] = $value;
+ foreach ($tableForeignKeys as $value) {
+ $list[] = $this->_getPortableTableForeignKeyDefinition($value);
}
return $list;
@@ -1103,28 +1104,32 @@ public function getSchemaSearchPaths()
* Given a table comment this method tries to extract a typehint for Doctrine Type, or returns
* the type given as default.
*
- * @param string $comment
- * @param string $currentType
+ * @param string|null $comment
+ * @param string $currentType
*
* @return string
*/
public function extractDoctrineTypeFromComment($comment, $currentType)
{
- if (preg_match('(\(DC2Type:(((?!\)).)+)\))', $comment, $match)) {
- $currentType = $match[1];
+ if ($comment !== null && preg_match('(\(DC2Type:(((?!\)).)+)\))', $comment, $match)) {
+ return $match[1];
}
return $currentType;
}
/**
- * @param string $comment
- * @param string $type
+ * @param string|null $comment
+ * @param string|null $type
*
- * @return string
+ * @return string|null
*/
public function removeDoctrineTypeFromComment($comment, $type)
{
+ if ($comment === null) {
+ return null;
+ }
+
return str_replace('(DC2Type:' . $type . ')', '', $comment);
}
}
diff --git a/lib/Doctrine/DBAL/Schema/Column.php b/lib/Doctrine/DBAL/Schema/Column.php
index aef471e06fe..56c39c14994 100644
--- a/lib/Doctrine/DBAL/Schema/Column.php
+++ b/lib/Doctrine/DBAL/Schema/Column.php
@@ -356,7 +356,7 @@ public function setAutoincrement($flag)
}
/**
- * @param string $comment
+ * @param string|null $comment
*
* @return Column
*/
diff --git a/lib/Doctrine/DBAL/Schema/ColumnDiff.php b/lib/Doctrine/DBAL/Schema/ColumnDiff.php
index cb64592109b..1589f98d4a9 100644
--- a/lib/Doctrine/DBAL/Schema/ColumnDiff.php
+++ b/lib/Doctrine/DBAL/Schema/ColumnDiff.php
@@ -18,7 +18,7 @@ class ColumnDiff
/** @var string[] */
public $changedProperties = [];
- /** @var Column */
+ /** @var Column|null */
public $fromColumn;
/**
diff --git a/lib/Doctrine/DBAL/Schema/Comparator.php b/lib/Doctrine/DBAL/Schema/Comparator.php
index 2de65b11aa8..9ccaa9a1efa 100644
--- a/lib/Doctrine/DBAL/Schema/Comparator.php
+++ b/lib/Doctrine/DBAL/Schema/Comparator.php
@@ -10,6 +10,7 @@
use function array_merge;
use function array_shift;
use function array_unique;
+use function assert;
use function count;
use function get_class;
use function strtolower;
@@ -109,6 +110,8 @@ public function compare(Schema $fromSchema, Schema $toSchema)
}
foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
+ assert($removedForeignKey instanceof ForeignKeyConstraint);
+
// We check if the key is from the removed table if not we skip.
if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
continue;
@@ -251,6 +254,7 @@ public function diffTable(Table $table1, Table $table2)
// See if index has changed in table 2.
$table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
+ assert($table2Index instanceof Index);
if (! $this->diffIndex($index, $table2Index)) {
continue;
diff --git a/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php b/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php
index f5e225512ab..b1fe64afef4 100644
--- a/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php
+++ b/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php
@@ -2,14 +2,16 @@
namespace Doctrine\DBAL\Schema;
+use Doctrine\DBAL\Platforms\DB2Platform;
use Doctrine\DBAL\Types\Type;
use const CASE_LOWER;
use function array_change_key_case;
use function is_resource;
+use function preg_match;
+use function str_replace;
use function strpos;
use function strtolower;
use function substr;
-use function trim;
/**
* IBM Db2 Schema Manager.
@@ -41,14 +43,17 @@ protected function _getPortableTableColumnDefinition($tableColumn)
$length = null;
$fixed = null;
- $unsigned = false;
$scale = false;
$precision = false;
$default = null;
if ($tableColumn['default'] !== null && $tableColumn['default'] !== 'NULL') {
- $default = trim($tableColumn['default'], "'");
+ $default = $tableColumn['default'];
+
+ if (preg_match('/^\'(.*)\'$/s', $default, $matches)) {
+ $default = str_replace("''", "'", $matches[1]);
+ }
}
$type = $this->_platform->getDoctrineTypeMapping($tableColumn['typename']);
@@ -80,7 +85,7 @@ protected function _getPortableTableColumnDefinition($tableColumn)
$options = [
'length' => $length,
- 'unsigned' => (bool) $unsigned,
+ 'unsigned' => false,
'fixed' => (bool) $fixed,
'default' => $default,
'autoincrement' => (bool) $tableColumn['autoincrement'],
@@ -179,7 +184,9 @@ protected function _getPortableForeignKeyRuleDef($def)
{
if ($def === 'C') {
return 'CASCADE';
- } elseif ($def === 'N') {
+ }
+
+ if ($def === 'N') {
return 'SET NULL';
}
@@ -203,4 +210,18 @@ protected function _getPortableViewDefinition($view)
return new View($view['name'], $sql);
}
+
+ public function listTableDetails($tableName) : Table
+ {
+ $table = parent::listTableDetails($tableName);
+
+ /** @var DB2Platform $platform */
+ $platform = $this->_platform;
+ $sql = $platform->getListTableCommentsSQL($tableName);
+
+ $tableOptions = $this->_conn->fetchAssoc($sql);
+ $table->addOption('comment', $tableOptions['REMARKS']);
+
+ return $table;
+ }
}
diff --git a/lib/Doctrine/DBAL/Schema/ForeignKeyConstraint.php b/lib/Doctrine/DBAL/Schema/ForeignKeyConstraint.php
index 31850d7f23e..3c6585e4600 100644
--- a/lib/Doctrine/DBAL/Schema/ForeignKeyConstraint.php
+++ b/lib/Doctrine/DBAL/Schema/ForeignKeyConstraint.php
@@ -3,14 +3,13 @@
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Platforms\AbstractPlatform;
-use function array_combine;
use function array_keys;
use function array_map;
-use function end;
-use function explode;
use function in_array;
+use function strrpos;
use function strtolower;
use function strtoupper;
+use function substr;
/**
* An abstraction class for a foreign key constraint.
@@ -65,13 +64,11 @@ class ForeignKeyConstraint extends AbstractAsset implements Constraint
*/
public function __construct(array $localColumnNames, $foreignTableName, array $foreignColumnNames, $name = null, array $options = [])
{
- $this->_setName($name);
- $identifierConstructorCallback = static function ($column) {
- return new Identifier($column);
- };
- $this->_localColumnNames = $localColumnNames
- ? array_combine($localColumnNames, array_map($identifierConstructorCallback, $localColumnNames))
- : [];
+ if ($name !== null) {
+ $this->_setName($name);
+ }
+
+ $this->_localColumnNames = $this->createIdentifierMap($localColumnNames);
if ($foreignTableName instanceof Table) {
$this->_foreignTableName = $foreignTableName;
@@ -79,12 +76,26 @@ public function __construct(array $localColumnNames, $foreignTableName, array $f
$this->_foreignTableName = new Identifier($foreignTableName);
}
- $this->_foreignColumnNames = $foreignColumnNames
- ? array_combine($foreignColumnNames, array_map($identifierConstructorCallback, $foreignColumnNames))
- : [];
+ $this->_foreignColumnNames = $this->createIdentifierMap($foreignColumnNames);
$this->_options = $options;
}
+ /**
+ * @param string[] $names
+ *
+ * @return Identifier[]
+ */
+ private function createIdentifierMap(array $names) : array
+ {
+ $identifiers = [];
+
+ foreach ($names as $name) {
+ $identifiers[$name] = new Identifier($name);
+ }
+
+ return $identifiers;
+ }
+
/**
* Returns the name of the referencing table
* the foreign key constraint is associated with.
@@ -218,9 +229,14 @@ public function getForeignTableName()
*/
public function getUnqualifiedForeignTableName()
{
- $parts = explode('.', $this->_foreignTableName->getName());
+ $name = $this->_foreignTableName->getName();
+ $position = strrpos($name, '.');
+
+ if ($position !== false) {
+ $name = substr($name, $position);
+ }
- return strtolower(end($parts));
+ return strtolower($name);
}
/**
diff --git a/lib/Doctrine/DBAL/Schema/Index.php b/lib/Doctrine/DBAL/Schema/Index.php
index 91ffd472465..7a31c7824bf 100644
--- a/lib/Doctrine/DBAL/Schema/Index.php
+++ b/lib/Doctrine/DBAL/Schema/Index.php
@@ -243,7 +243,9 @@ public function overrules(Index $other)
{
if ($other->isPrimary()) {
return false;
- } elseif ($this->isSimpleIndex() && $other->isUnique()) {
+ }
+
+ if ($this->isSimpleIndex() && $other->isUnique()) {
return false;
}
diff --git a/lib/Doctrine/DBAL/Schema/MySqlSchemaManager.php b/lib/Doctrine/DBAL/Schema/MySqlSchemaManager.php
index c27e8308845..9522faf6a73 100644
--- a/lib/Doctrine/DBAL/Schema/MySqlSchemaManager.php
+++ b/lib/Doctrine/DBAL/Schema/MySqlSchemaManager.php
@@ -9,21 +9,40 @@
use function array_change_key_case;
use function array_shift;
use function array_values;
-use function end;
+use function assert;
use function explode;
+use function is_string;
use function preg_match;
-use function preg_replace;
-use function str_replace;
-use function stripslashes;
use function strpos;
use function strtok;
use function strtolower;
+use function strtr;
/**
* Schema manager for the MySql RDBMS.
*/
class MySqlSchemaManager extends AbstractSchemaManager
{
+ /**
+ * @see https://mariadb.com/kb/en/library/string-literals/#escape-sequences
+ */
+ private const MARIADB_ESCAPE_SEQUENCES = [
+ '\\0' => "\0",
+ "\\'" => "'",
+ '\\"' => '"',
+ '\\b' => "\b",
+ '\\n' => "\n",
+ '\\r' => "\r",
+ '\\t' => "\t",
+ '\\Z' => "\x1a",
+ '\\\\' => '\\',
+ '\\%' => '%',
+ '\\_' => '_',
+
+ // Internally, MariaDB escapes single quotes using the standard syntax
+ "''" => "'",
+ ];
+
/**
* {@inheritdoc}
*/
@@ -76,14 +95,6 @@ protected function _getPortableTableIndexesList($tableIndexes, $tableName = null
return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
}
- /**
- * {@inheritdoc}
- */
- protected function _getPortableSequenceDefinition($sequence)
- {
- return end($sequence);
- }
-
/**
* {@inheritdoc}
*/
@@ -101,6 +112,8 @@ protected function _getPortableTableColumnDefinition($tableColumn)
$dbType = strtolower($tableColumn['type']);
$dbType = strtok($dbType, '(), ');
+ assert(is_string($dbType));
+
$length = $tableColumn['length'] ?? strtok('(), ');
$fixed = null;
@@ -192,6 +205,9 @@ protected function _getPortableTableColumnDefinition($tableColumn)
$column = new Column($tableColumn['field'], Type::getType($type), $options);
+ if (isset($tableColumn['characterset'])) {
+ $column->setPlatformOption('charset', $tableColumn['characterset']);
+ }
if (isset($tableColumn['collation'])) {
$column->setPlatformOption('collation', $tableColumn['collation']);
}
@@ -220,15 +236,11 @@ private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?str
if ($columnDefault === 'NULL' || $columnDefault === null) {
return null;
}
- if ($columnDefault[0] === "'") {
- return stripslashes(
- str_replace(
- "''",
- "'",
- preg_replace('/^\'(.*)\'$/', '$1', $columnDefault)
- )
- );
+
+ if (preg_match('/^\'(.*)\'$/', $columnDefault, $matches)) {
+ return strtr($matches[1], self::MARIADB_ESCAPE_SEQUENCES);
}
+
switch ($columnDefault) {
case 'current_timestamp()':
return $platform->getCurrentTimestampSQL();
@@ -237,6 +249,7 @@ private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?str
case 'curtime()':
return $platform->getCurrentTimeSQL();
}
+
return $columnDefault;
}
diff --git a/lib/Doctrine/DBAL/Schema/OracleSchemaManager.php b/lib/Doctrine/DBAL/Schema/OracleSchemaManager.php
index b9919f58f14..af5a231a4a8 100644
--- a/lib/Doctrine/DBAL/Schema/OracleSchemaManager.php
+++ b/lib/Doctrine/DBAL/Schema/OracleSchemaManager.php
@@ -6,12 +6,14 @@
use Doctrine\DBAL\Driver\DriverException;
use Doctrine\DBAL\Platforms\OraclePlatform;
use Doctrine\DBAL\Types\Type;
+use Throwable;
use const CASE_LOWER;
use function array_change_key_case;
use function array_values;
use function assert;
use function preg_match;
use function sprintf;
+use function str_replace;
use function strpos;
use function strtolower;
use function strtoupper;
@@ -31,6 +33,7 @@ public function dropDatabase($database)
parent::dropDatabase($database);
} catch (DBALException $exception) {
$exception = $exception->getPrevious();
+ assert($exception instanceof Throwable);
if (! $exception instanceof DriverException) {
throw $exception;
@@ -142,8 +145,10 @@ protected function _getPortableTableColumnDefinition($tableColumn)
}
if ($tableColumn['data_default'] !== null) {
- // Default values returned from database are enclosed in single quotes.
- $tableColumn['data_default'] = trim($tableColumn['data_default'], "'");
+ // Default values returned from database are represented as literal expressions
+ if (preg_match('/^\'(.*)\'$/s', $tableColumn['data_default'], $matches)) {
+ $tableColumn['data_default'] = str_replace("''", "'", $matches[1]);
+ }
}
if ($tableColumn['data_precision'] !== null) {
@@ -259,6 +264,8 @@ protected function _getPortableSequenceDefinition($sequence)
/**
* {@inheritdoc}
+ *
+ * @deprecated
*/
protected function _getPortableFunctionDefinition($function)
{
@@ -279,6 +286,8 @@ protected function _getPortableDatabaseDefinition($database)
/**
* {@inheritdoc}
+ *
+ * Calling this method without an argument or by passing NULL is deprecated.
*/
public function createDatabase($database = null)
{
@@ -380,4 +389,18 @@ protected function killUserSessions($user)
);
}
}
+
+ public function listTableDetails($tableName) : Table
+ {
+ $table = parent::listTableDetails($tableName);
+
+ /** @var OraclePlatform $platform */
+ $platform = $this->_platform;
+ $sql = $platform->getListTableCommentsSQL($tableName);
+
+ $tableOptions = $this->_conn->fetchAssoc($sql);
+ $table->addOption('comment', $tableOptions['COMMENTS']);
+
+ return $table;
+ }
}
diff --git a/lib/Doctrine/DBAL/Schema/PostgreSqlSchemaManager.php b/lib/Doctrine/DBAL/Schema/PostgreSqlSchemaManager.php
index 168e74ea87f..e9608e7c193 100644
--- a/lib/Doctrine/DBAL/Schema/PostgreSqlSchemaManager.php
+++ b/lib/Doctrine/DBAL/Schema/PostgreSqlSchemaManager.php
@@ -6,6 +6,7 @@
use Doctrine\DBAL\FetchMode;
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use const CASE_LOWER;
use function array_change_key_case;
use function array_filter;
@@ -20,7 +21,6 @@
use function preg_replace;
use function sprintf;
use function str_replace;
-use function stripos;
use function strlen;
use function strpos;
use function strtolower;
@@ -134,8 +134,8 @@ protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
{
$onUpdate = null;
$onDelete = null;
- $localColumns = null;
- $foreignColumns = null;
+ $localColumns = [];
+ $foreignColumns = [];
$foreignTable = null;
if (preg_match('(ON UPDATE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
@@ -329,11 +329,9 @@ protected function _getPortableTableColumnDefinition($tableColumn)
$autoincrement = true;
}
- if (preg_match("/^['(](.*)[')]::.*$/", $tableColumn['default'], $matches)) {
+ if (preg_match("/^['(](.*)[')]::/", $tableColumn['default'], $matches)) {
$tableColumn['default'] = $matches[1];
- }
-
- if (stripos($tableColumn['default'], 'NULL') === 0) {
+ } elseif (preg_match('/^NULL::/', $tableColumn['default'])) {
$tableColumn['default'] = null;
}
@@ -394,11 +392,12 @@ protected function _getPortableTableColumnDefinition($tableColumn)
$length = null;
break;
case 'text':
- $fixed = false;
- break;
+ case '_varchar':
case 'varchar':
+ $tableColumn['default'] = $this->parseDefaultExpression($tableColumn['default']);
+ $fixed = false;
+ break;
case 'interval':
- case '_varchar':
$fixed = false;
break;
case 'char':
@@ -456,7 +455,7 @@ protected function _getPortableTableColumnDefinition($tableColumn)
$column->setPlatformOption('collation', $tableColumn['collation']);
}
- if (in_array($column->getType()->getName(), [Type::JSON_ARRAY, Type::JSON], true)) {
+ if (in_array($column->getType()->getName(), [Types::JSON_ARRAY, Types::JSON], true)) {
$column->setPlatformOption('jsonb', $jsonb);
}
@@ -478,4 +477,31 @@ private function fixVersion94NegativeNumericDefaultValue($defaultValue)
return $defaultValue;
}
+
+ /**
+ * Parses a default value expression as given by PostgreSQL
+ */
+ private function parseDefaultExpression(?string $default) : ?string
+ {
+ if ($default === null) {
+ return $default;
+ }
+
+ return str_replace("''", "'", $default);
+ }
+
+ public function listTableDetails($tableName) : Table
+ {
+ $table = parent::listTableDetails($tableName);
+
+ /** @var PostgreSqlPlatform $platform */
+ $platform = $this->_platform;
+ $sql = $platform->getListTableMetadataSQL($tableName);
+
+ $tableOptions = $this->_conn->fetchAssoc($sql);
+
+ $table->addOption('comment', $tableOptions['table_comment']);
+
+ return $table;
+ }
}
diff --git a/lib/Doctrine/DBAL/Schema/SQLAnywhereSchemaManager.php b/lib/Doctrine/DBAL/Schema/SQLAnywhereSchemaManager.php
index 62d5fa88e89..c169a6e0708 100644
--- a/lib/Doctrine/DBAL/Schema/SQLAnywhereSchemaManager.php
+++ b/lib/Doctrine/DBAL/Schema/SQLAnywhereSchemaManager.php
@@ -5,6 +5,7 @@
use Doctrine\DBAL\Platforms\SQLAnywherePlatform;
use Doctrine\DBAL\Types\Type;
use function assert;
+use function is_string;
use function preg_replace;
/**
@@ -222,9 +223,9 @@ protected function _getPortableTableIndexesList($tableIndexRows, $tableName = nu
*/
protected function _getPortableViewDefinition($view)
{
- return new View(
- $view['table_name'],
- preg_replace('/^.*\s+as\s+SELECT(.*)/i', 'SELECT$1', $view['view_def'])
- );
+ $definition = preg_replace('/^.*\s+as\s+SELECT(.*)/i', 'SELECT$1', $view['view_def']);
+ assert(is_string($definition));
+
+ return new View($view['table_name'], $definition);
}
}
diff --git a/lib/Doctrine/DBAL/Schema/SQLServerSchemaManager.php b/lib/Doctrine/DBAL/Schema/SQLServerSchemaManager.php
index 6cd82b2ffaf..35cdc45089a 100644
--- a/lib/Doctrine/DBAL/Schema/SQLServerSchemaManager.php
+++ b/lib/Doctrine/DBAL/Schema/SQLServerSchemaManager.php
@@ -4,16 +4,19 @@
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\DriverException;
+use Doctrine\DBAL\Platforms\SQLServerPlatform;
use Doctrine\DBAL\Types\Type;
use PDOException;
+use Throwable;
+use function assert;
use function count;
use function in_array;
-use function preg_replace;
+use function is_string;
+use function preg_match;
use function sprintf;
use function str_replace;
use function strpos;
use function strtok;
-use function trim;
/**
* SQL Server Schema Manager.
@@ -29,6 +32,7 @@ public function dropDatabase($database)
parent::dropDatabase($database);
} catch (DBALException $exception) {
$exception = $exception->getPrevious();
+ assert($exception instanceof Throwable);
if (! $exception instanceof DriverException) {
throw $exception;
@@ -61,7 +65,9 @@ protected function _getPortableSequenceDefinition($sequence)
*/
protected function _getPortableTableColumnDefinition($tableColumn)
{
- $dbType = strtok($tableColumn['type'], '(), ');
+ $dbType = strtok($tableColumn['type'], '(), ');
+ assert(is_string($dbType));
+
$fixed = null;
$length = (int) $tableColumn['length'];
$default = $tableColumn['default'];
@@ -71,15 +77,7 @@ protected function _getPortableTableColumnDefinition($tableColumn)
}
if ($default !== null) {
- while ($default !== ($default2 = preg_replace('/^\((.*)\)$/', '$1', $default))) {
- $default = trim($default2, "'");
-
- if ($default !== 'getdate()') {
- continue;
- }
-
- $default = $this->_platform->getCurrentTimestampSQL();
- }
+ $default = $this->parseDefaultExpression($default);
}
switch ($dbType) {
@@ -109,7 +107,7 @@ protected function _getPortableTableColumnDefinition($tableColumn)
'length' => $length === 0 || ! in_array($type, ['text', 'string']) ? null : $length,
'unsigned' => false,
'fixed' => (bool) $fixed,
- 'default' => $default !== 'NULL' ? $default : null,
+ 'default' => $default,
'notnull' => (bool) $tableColumn['notnull'],
'scale' => $tableColumn['scale'],
'precision' => $tableColumn['precision'],
@@ -126,6 +124,27 @@ protected function _getPortableTableColumnDefinition($tableColumn)
return $column;
}
+ private function parseDefaultExpression(string $value) : ?string
+ {
+ while (preg_match('/^\((.*)\)$/s', $value, $matches)) {
+ $value = $matches[1];
+ }
+
+ if ($value === 'NULL') {
+ return null;
+ }
+
+ if (preg_match('/^\'(.*)\'$/s', $value, $matches)) {
+ $value = str_replace("''", "'", $matches[1]);
+ }
+
+ if ($value === 'getdate()') {
+ return $this->_platform->getCurrentTimestampSQL();
+ }
+
+ return $value;
+ }
+
/**
* {@inheritdoc}
*/
@@ -216,7 +235,7 @@ protected function getPortableNamespaceDefinition(array $namespace)
protected function _getPortableViewDefinition($view)
{
// @todo
- return new View($view['name'], null);
+ return new View($view['name'], '');
}
/**
@@ -307,4 +326,24 @@ private function closeActiveDatabaseConnections($database)
)
);
}
+
+ /**
+ * @param string $tableName
+ */
+ public function listTableDetails($tableName) : Table
+ {
+ $table = parent::listTableDetails($tableName);
+
+ /** @var SQLServerPlatform $platform */
+ $platform = $this->_platform;
+ $sql = $platform->getListTableMetadataSQL($tableName);
+
+ $tableOptions = $this->_conn->fetchAssoc($sql);
+
+ if ($tableOptions !== false) {
+ $table->addOption('comment', $tableOptions['table_comment']);
+ }
+
+ return $table;
+ }
}
diff --git a/lib/Doctrine/DBAL/Schema/Schema.php b/lib/Doctrine/DBAL/Schema/Schema.php
index 7b75f4fb743..5d746654a40 100644
--- a/lib/Doctrine/DBAL/Schema/Schema.php
+++ b/lib/Doctrine/DBAL/Schema/Schema.php
@@ -105,7 +105,9 @@ protected function _addTable(Table $table)
throw SchemaException::tableAlreadyExists($tableName);
}
- if (! $table->isInDefaultNamespace($this->getName()) && ! $this->hasNamespace($namespaceName)) {
+ if ($namespaceName !== null
+ && ! $table->isInDefaultNamespace($this->getName())
+ && ! $this->hasNamespace($namespaceName)) {
$this->createNamespace($namespaceName);
}
@@ -127,7 +129,9 @@ protected function _addSequence(Sequence $sequence)
throw SchemaException::sequenceAlreadyExists($seqName);
}
- if (! $sequence->isInDefaultNamespace($this->getName()) && ! $this->hasNamespace($namespaceName)) {
+ if ($namespaceName !== null
+ && ! $sequence->isInDefaultNamespace($this->getName())
+ && ! $this->hasNamespace($namespaceName)) {
$this->createNamespace($namespaceName);
}
diff --git a/lib/Doctrine/DBAL/Schema/SchemaDiff.php b/lib/Doctrine/DBAL/Schema/SchemaDiff.php
index 0f2e25fb32b..69bf125a844 100644
--- a/lib/Doctrine/DBAL/Schema/SchemaDiff.php
+++ b/lib/Doctrine/DBAL/Schema/SchemaDiff.php
@@ -10,7 +10,7 @@
*/
class SchemaDiff
{
- /** @var Schema */
+ /** @var Schema|null */
public $fromSchema;
/**
diff --git a/lib/Doctrine/DBAL/Schema/Sequence.php b/lib/Doctrine/DBAL/Schema/Sequence.php
index 24cf4aae0b4..88891019bfd 100644
--- a/lib/Doctrine/DBAL/Schema/Sequence.php
+++ b/lib/Doctrine/DBAL/Schema/Sequence.php
@@ -4,7 +4,6 @@
use Doctrine\DBAL\Schema\Visitor\Visitor;
use function count;
-use function is_numeric;
use function sprintf;
/**
@@ -66,7 +65,7 @@ public function getCache()
*/
public function setAllocationSize($allocationSize)
{
- $this->allocationSize = is_numeric($allocationSize) ? (int) $allocationSize : 1;
+ $this->allocationSize = (int) $allocationSize ?: 1;
return $this;
}
@@ -78,7 +77,7 @@ public function setAllocationSize($allocationSize)
*/
public function setInitialValue($initialValue)
{
- $this->initialValue = is_numeric($initialValue) ? (int) $initialValue : 1;
+ $this->initialValue = (int) $initialValue ?: 1;
return $this;
}
@@ -105,11 +104,13 @@ public function setCache($cache)
*/
public function isAutoIncrementsFor(Table $table)
{
- if (! $table->hasPrimaryKey()) {
+ $primaryKey = $table->getPrimaryKey();
+
+ if ($primaryKey === null) {
return false;
}
- $pkColumns = $table->getPrimaryKey()->getColumns();
+ $pkColumns = $primaryKey->getColumns();
if (count($pkColumns) !== 1) {
return false;
diff --git a/lib/Doctrine/DBAL/Schema/SqliteSchemaManager.php b/lib/Doctrine/DBAL/Schema/SqliteSchemaManager.php
index 744acedabb5..ac758015a0f 100644
--- a/lib/Doctrine/DBAL/Schema/SqliteSchemaManager.php
+++ b/lib/Doctrine/DBAL/Schema/SqliteSchemaManager.php
@@ -77,7 +77,7 @@ public function renameTable($name, $newName)
*/
public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
{
- $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table);
+ $tableDiff = $this->getTableDiffForAlterForeignKey($table);
$tableDiff->addedForeignKeys[] = $foreignKey;
$this->alterTable($tableDiff);
@@ -88,7 +88,7 @@ public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
*/
public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table)
{
- $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table);
+ $tableDiff = $this->getTableDiffForAlterForeignKey($table);
$tableDiff->changedForeignKeys[] = $foreignKey;
$this->alterTable($tableDiff);
@@ -99,7 +99,7 @@ public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table
*/
public function dropForeignKey($foreignKey, $table)
{
- $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table);
+ $tableDiff = $this->getTableDiffForAlterForeignKey($table);
$tableDiff->removedForeignKeys[] = $foreignKey;
$this->alterTable($tableDiff);
@@ -205,7 +205,7 @@ protected function _getPortableTableIndexesList($tableIndexes, $tableName = null
$idx = [];
$idx['key_name'] = $keyName;
$idx['primary'] = false;
- $idx['non_unique'] = $tableIndex['unique']?false:true;
+ $idx['non_unique'] = ! $tableIndex['unique'];
$stmt = $this->_conn->executeQuery(sprintf(
'PRAGMA INDEX_INFO (%s)',
@@ -224,6 +224,8 @@ protected function _getPortableTableIndexesList($tableIndexes, $tableName = null
/**
* {@inheritdoc}
+ *
+ * @deprecated
*/
protected function _getPortableTableIndexDefinition($tableIndex)
{
@@ -283,9 +285,9 @@ protected function _getPortableTableColumnList($table, $database, $tableColumns)
continue;
}
- $type = $this->extractDoctrineTypeFromComment($comment, null);
+ $type = $this->extractDoctrineTypeFromComment($comment, '');
- if ($type !== null) {
+ if ($type !== '') {
$column->setType(Type::getType($type));
$comment = $this->removeDoctrineTypeFromComment($comment, $type);
@@ -324,10 +326,14 @@ protected function _getPortableTableColumnDefinition($tableColumn)
if ($default === 'NULL') {
$default = null;
}
+
if ($default !== null) {
- // SQLite returns strings wrapped in single quotes, so we need to strip them
- $default = preg_replace("/^'(.*)'$/", '\1', $default);
+ // SQLite returns the default value as a literal expression, so we need to parse it
+ if (preg_match('/^\'(.*)\'$/s', $default, $matches)) {
+ $default = str_replace("''", "'", $matches[1]);
+ }
}
+
$notnull = (bool) $tableColumn['notnull'];
if (! isset($tableColumn['name'])) {
@@ -436,11 +442,12 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys)
*
* @throws DBALException
*/
- private function getTableDiffForAlterForeignKey(ForeignKeyConstraint $foreignKey, $table)
+ private function getTableDiffForAlterForeignKey($table)
{
if (! $table instanceof Table) {
$tableDetails = $this->tryMethod('listTableDetails', $table);
- if ($table === false) {
+
+ if ($tableDetails === false) {
throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
}
@@ -465,6 +472,25 @@ private function parseColumnCollationFromSQL(string $column, string $sql) : ?str
return $match[1];
}
+ private function parseTableCommentFromSQL(string $table, string $sql) : ?string
+ {
+ $pattern = '/\s* # Allow whitespace characters at start of line
+CREATE\sTABLE # Match "CREATE TABLE"
+(?:\W"' . preg_quote($this->_platform->quoteSingleIdentifier($table), '/') . '"\W|\W' . preg_quote($table, '/')
+ . '\W) # Match table name (quoted and unquoted)
+( # Start capture
+ (?:\s*--[^\n]*\n?)+ # Capture anything that starts with whitespaces followed by -- until the end of the line(s)
+)/ix';
+
+ if (preg_match($pattern, $sql, $match) !== 1) {
+ return null;
+ }
+
+ $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
+
+ return $comment === '' ? null : $comment;
+ }
+
private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
{
$pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
@@ -498,4 +524,22 @@ private function getCreateTableSQL(string $table) : ?string
[$table]
) ?: null;
}
+
+ /**
+ * @param string $tableName
+ */
+ public function listTableDetails($tableName) : Table
+ {
+ $table = parent::listTableDetails($tableName);
+
+ $tableCreateSql = $this->getCreateTableSQL($tableName) ?? '';
+
+ $comment = $this->parseTableCommentFromSQL($tableName, $tableCreateSql);
+
+ if ($comment !== null) {
+ $table->addOption('comment', $comment);
+ }
+
+ return $table;
+ }
}
diff --git a/lib/Doctrine/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizer.php b/lib/Doctrine/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizer.php
index e51b27f3726..dd4b1ca5f40 100644
--- a/lib/Doctrine/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizer.php
+++ b/lib/Doctrine/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizer.php
@@ -31,7 +31,6 @@ public function getCreateSchema(Schema $createSchema)
return $createSchema->toSql($this->platform);
}
-
/**
* {@inheritdoc}
*/
@@ -87,11 +86,14 @@ public function getDropSchema(Schema $dropSchema)
}
foreach ($dropSchema->getTables() as $table) {
- if (! $table->hasPrimaryKey()) {
+ $primaryKey = $table->getPrimaryKey();
+
+ if ($primaryKey === null) {
continue;
}
- $columns = $table->getPrimaryKey()->getColumns();
+ $columns = $primaryKey->getColumns();
+
if (count($columns) > 1) {
continue;
}
diff --git a/lib/Doctrine/DBAL/Schema/Table.php b/lib/Doctrine/DBAL/Schema/Table.php
index c89298bb015..8e613320f79 100644
--- a/lib/Doctrine/DBAL/Schema/Table.php
+++ b/lib/Doctrine/DBAL/Schema/Table.php
@@ -18,9 +18,6 @@
*/
class Table extends AbstractAsset
{
- /** @var string */
- protected $_name = null;
-
/** @var Column[] */
protected $_columns = [];
@@ -100,8 +97,8 @@ protected function _getMaxIdentifierLength()
/**
* Sets the Primary Key.
*
- * @param string[] $columnNames
- * @param string|bool $indexName
+ * @param string[] $columnNames
+ * @param string|false $indexName
*
* @return self
*/
@@ -221,7 +218,7 @@ public function renameIndex($oldIndexName, $newIndexName = null)
if ($oldIndex->isPrimary()) {
$this->dropPrimaryKey();
- return $this->setPrimaryKey($oldIndex->getColumns(), $newIndexName);
+ return $this->setPrimaryKey($oldIndex->getColumns(), $newIndexName ?? false);
}
unset($this->_indexes[$oldIndexName]);
@@ -427,7 +424,7 @@ public function addNamedForeignKeyConstraint($name, $foreignTable, array $localC
/**
* @param string $name
- * @param string $value
+ * @param mixed $value
*
* @return self
*/
@@ -594,9 +591,11 @@ public function removeForeignKey($constraintName)
*/
public function getColumns()
{
+ $primaryKey = $this->getPrimaryKey();
$primaryKeyColumns = [];
- if ($this->hasPrimaryKey()) {
- $primaryKeyColumns = $this->filterColumns($this->getPrimaryKey()->getColumns());
+
+ if ($primaryKey !== null) {
+ $primaryKeyColumns = $this->filterColumns($primaryKey->getColumns());
}
return array_merge($primaryKeyColumns, $this->getForeignKeyColumns(), $this->_columns);
@@ -613,6 +612,7 @@ private function getForeignKeyColumns()
foreach ($this->getForeignKeys() as $foreignKey) {
$foreignKeyColumns = array_merge($foreignKeyColumns, $foreignKey->getColumns());
}
+
return $this->filterColumns($foreignKeyColumns);
}
@@ -686,10 +686,13 @@ public function getPrimaryKey()
*/
public function getPrimaryKeyColumns()
{
- if (! $this->hasPrimaryKey()) {
+ $primaryKey = $this->getPrimaryKey();
+
+ if ($primaryKey === null) {
throw new DBALException('Table ' . $this->getName() . ' has no primary key.');
}
- return $this->getPrimaryKey()->getColumns();
+
+ return $primaryKey->getColumns();
}
/**
@@ -825,12 +828,29 @@ public function __clone()
*
* Trims quotes and lowercases the given identifier.
*
- * @param string $identifier The identifier to normalize.
+ * @param string|null $identifier The identifier to normalize.
*
* @return string The normalized identifier.
*/
private function normalizeIdentifier($identifier)
{
+ if ($identifier === null) {
+ return '';
+ }
+
return $this->trimQuotes(strtolower($identifier));
}
+
+ public function setComment(?string $comment) : self
+ {
+ // For keeping backward compatibility with MySQL in previous releases, table comments are stored as options.
+ $this->addOption('comment', $comment);
+
+ return $this;
+ }
+
+ public function getComment() : ?string
+ {
+ return $this->_options['comment'] ?? null;
+ }
}
diff --git a/lib/Doctrine/DBAL/Schema/TableDiff.php b/lib/Doctrine/DBAL/Schema/TableDiff.php
index 457e1b6a963..1ff2c0ad105 100644
--- a/lib/Doctrine/DBAL/Schema/TableDiff.php
+++ b/lib/Doctrine/DBAL/Schema/TableDiff.php
@@ -12,7 +12,7 @@ class TableDiff
/** @var string */
public $name = null;
- /** @var string|bool */
+ /** @var string|false */
public $newName = false;
/**
@@ -92,7 +92,7 @@ class TableDiff
*/
public $removedForeignKeys = [];
- /** @var Table */
+ /** @var Table|null */
public $fromTable;
/**
@@ -139,10 +139,14 @@ public function getName(AbstractPlatform $platform)
}
/**
- * @return Identifier|string|bool
+ * @return Identifier|false
*/
public function getNewName()
{
- return $this->newName ? new Identifier($this->newName) : $this->newName;
+ if ($this->newName === false) {
+ return false;
+ }
+
+ return new Identifier($this->newName);
}
}
diff --git a/lib/Doctrine/DBAL/Schema/Visitor/CreateSchemaSqlCollector.php b/lib/Doctrine/DBAL/Schema/Visitor/CreateSchemaSqlCollector.php
index 318c8b26222..cc15bc0f655 100644
--- a/lib/Doctrine/DBAL/Schema/Visitor/CreateSchemaSqlCollector.php
+++ b/lib/Doctrine/DBAL/Schema/Visitor/CreateSchemaSqlCollector.php
@@ -47,7 +47,7 @@ public function acceptNamespace($namespaceName)
*/
public function acceptTable(Table $table)
{
- $this->createTableQueries = array_merge($this->createTableQueries, (array) $this->platform->getCreateTableSQL($table));
+ $this->createTableQueries = array_merge($this->createTableQueries, $this->platform->getCreateTableSQL($table));
}
/**
diff --git a/lib/Doctrine/DBAL/Schema/Visitor/DropSchemaSqlCollector.php b/lib/Doctrine/DBAL/Schema/Visitor/DropSchemaSqlCollector.php
index 44f5ea80af5..81e2023128b 100644
--- a/lib/Doctrine/DBAL/Schema/Visitor/DropSchemaSqlCollector.php
+++ b/lib/Doctrine/DBAL/Schema/Visitor/DropSchemaSqlCollector.php
@@ -78,15 +78,18 @@ public function getQueries()
{
$sql = [];
+ /** @var ForeignKeyConstraint $fkConstraint */
foreach ($this->constraints as $fkConstraint) {
$localTable = $this->constraints[$fkConstraint];
$sql[] = $this->platform->getDropForeignKeySQL($fkConstraint, $localTable);
}
+ /** @var Sequence $sequence */
foreach ($this->sequences as $sequence) {
$sql[] = $this->platform->getDropSequenceSQL($sequence);
}
+ /** @var Table $table */
foreach ($this->tables as $table) {
$sql[] = $this->platform->getDropTableSQL($table);
}
diff --git a/lib/Doctrine/DBAL/Schema/Visitor/Graphviz.php b/lib/Doctrine/DBAL/Schema/Visitor/Graphviz.php
index 889f9611254..d5e94cf6ea3 100644
--- a/lib/Doctrine/DBAL/Schema/Visitor/Graphviz.php
+++ b/lib/Doctrine/DBAL/Schema/Visitor/Graphviz.php
@@ -8,8 +8,6 @@
use function current;
use function file_put_contents;
use function in_array;
-use function mt_rand;
-use function sha1;
use function strtolower;
/**
@@ -41,7 +39,7 @@ public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkCons
*/
public function acceptSchema(Schema $schema)
{
- $this->output = 'digraph "' . sha1(mt_rand()) . '" {' . "\n";
+ $this->output = 'digraph "' . $schema->getName() . '" {' . "\n";
$this->output .= 'splines = true;' . "\n";
$this->output .= 'overlap = false;' . "\n";
$this->output .= 'outputorder=edgesfirst;' . "\n";
@@ -83,7 +81,10 @@ private function createTableLabel(Table $table)
$label .= '' . $columnLabel . '';
$label .= '' . strtolower($column->getType()) . ' | ';
$label .= '';
- if ($table->hasPrimaryKey() && in_array($column->getName(), $table->getPrimaryKey()->getColumns())) {
+
+ $primaryKey = $table->getPrimaryKey();
+
+ if ($primaryKey !== null && in_array($column->getName(), $primaryKey->getColumns())) {
$label .= "\xe2\x9c\xb7";
}
$label .= ' | ';
diff --git a/lib/Doctrine/DBAL/Schema/Visitor/RemoveNamespacedAssets.php b/lib/Doctrine/DBAL/Schema/Visitor/RemoveNamespacedAssets.php
index 9b23b395885..001ea2a0d70 100644
--- a/lib/Doctrine/DBAL/Schema/Visitor/RemoveNamespacedAssets.php
+++ b/lib/Doctrine/DBAL/Schema/Visitor/RemoveNamespacedAssets.php
@@ -65,6 +65,7 @@ public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkCons
// point to nowhere.
if (! $this->schema->hasTable($fkConstraint->getForeignTableName())) {
$localTable->removeForeignKey($fkConstraint->getName());
+
return;
}
diff --git a/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php b/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php
index abb5b4004e2..8d8134127d7 100644
--- a/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php
+++ b/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php
@@ -26,7 +26,7 @@
* - By default, the global shard is selected. If no global shard is configured
* an exception is thrown on access.
* - Selecting a shard by distribution value delegates the mapping
- * "distributionValue" => "client" to the ShardChooser interface.
+ * "distributionValue" => "client" to the ShardChoser interface.
* - An exception is thrown if trying to switch shards during an open
* transaction.
*
@@ -53,7 +53,7 @@ class PoolingShardConnection extends Connection
/** @var DriverConnection[] */
private $activeConnections = [];
- /** @var int|null */
+ /** @var string|int|null */
private $activeShardId;
/** @var mixed[] */
@@ -106,7 +106,7 @@ public function __construct(array $params, Driver $driver, ?Configuration $confi
/**
* Get active shard id.
*
- * @return int
+ * @return string|int|null
*/
public function getActiveShardId()
{
@@ -164,7 +164,7 @@ public function getPassword()
/**
* Connects to a given shard.
*
- * @param mixed $shardId
+ * @param string|int|null $shardId
*
* @return bool
*
@@ -184,15 +184,15 @@ public function connect($shardId = null)
throw new ShardingException('Cannot switch shard when transaction is active.');
}
- $this->activeShardId = (int) $shardId;
+ $activeShardId = $this->activeShardId = (int) $shardId;
- if (isset($this->activeConnections[$this->activeShardId])) {
- $this->_conn = $this->activeConnections[$this->activeShardId];
+ if (isset($this->activeConnections[$activeShardId])) {
+ $this->_conn = $this->activeConnections[$activeShardId];
return false;
}
- $this->_conn = $this->activeConnections[$this->activeShardId] = $this->connectTo($this->activeShardId);
+ $this->_conn = $this->activeConnections[$activeShardId] = $this->connectTo($activeShardId);
if ($this->_eventManager->hasListeners(Events::postConnect)) {
$eventArgs = new ConnectionEventArgs($this);
@@ -205,7 +205,7 @@ public function connect($shardId = null)
/**
* Connects to a specific connection.
*
- * @param string $shardId
+ * @param string|int $shardId
*
* @return \Doctrine\DBAL\Driver\Connection
*/
@@ -224,7 +224,7 @@ protected function connectTo($shardId)
}
/**
- * @param string|null $shardId
+ * @param string|int|null $shardId
*
* @return bool
*/
diff --git a/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizer.php b/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizer.php
index 32d642365b0..417f674a3e0 100644
--- a/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizer.php
+++ b/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizer.php
@@ -9,6 +9,7 @@
use Doctrine\DBAL\Schema\Synchronizer\SchemaSynchronizer;
use Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer;
use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use RuntimeException;
use function array_merge;
@@ -240,12 +241,12 @@ private function getFederationTypeDefaultValue()
$federationType = Type::getType($this->shardManager->getDistributionType());
switch ($federationType->getName()) {
- case Type::GUID:
+ case Types::GUID:
$defaultValue = '00000000-0000-0000-0000-000000000000';
break;
- case Type::INTEGER:
- case Type::SMALLINT:
- case Type::BIGINT:
+ case Types::INTEGER:
+ case Types::SMALLINT:
+ case Types::BIGINT:
$defaultValue = '0';
break;
default:
diff --git a/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureShardManager.php b/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureShardManager.php
index 7c5dfe5c4be..d8178ee07db 100644
--- a/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureShardManager.php
+++ b/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureShardManager.php
@@ -7,8 +7,6 @@
use Doctrine\DBAL\Sharding\ShardManager;
use Doctrine\DBAL\Types\Type;
use RuntimeException;
-use function is_bool;
-use function is_scalar;
use function sprintf;
/**
@@ -125,10 +123,6 @@ public function selectShard($distributionValue)
throw ShardingException::activeTransaction();
}
- if ($distributionValue === null || is_bool($distributionValue) || ! is_scalar($distributionValue)) {
- throw ShardingException::noShardDistributionValue();
- }
-
$platform = $this->conn->getDatabasePlatform();
$sql = sprintf(
'USE FEDERATION %s (%s = %s) WITH RESET, FILTERING = %s;',
diff --git a/lib/Doctrine/DBAL/Statement.php b/lib/Doctrine/DBAL/Statement.php
index b65fa95e33a..09913bb56ae 100644
--- a/lib/Doctrine/DBAL/Statement.php
+++ b/lib/Doctrine/DBAL/Statement.php
@@ -217,7 +217,9 @@ public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
{
if ($arg2 === null) {
return $this->stmt->setFetchMode($fetchMode);
- } elseif ($arg3 === null) {
+ }
+
+ if ($arg3 === null) {
return $this->stmt->setFetchMode($fetchMode, $arg2);
}
diff --git a/lib/Doctrine/DBAL/Tools/Console/Command/ImportCommand.php b/lib/Doctrine/DBAL/Tools/Console/Command/ImportCommand.php
index 0e815663786..0cd2999c97a 100644
--- a/lib/Doctrine/DBAL/Tools/Console/Command/ImportCommand.php
+++ b/lib/Doctrine/DBAL/Tools/Console/Command/ImportCommand.php
@@ -13,6 +13,7 @@
use Symfony\Component\Console\Output\OutputInterface;
use const PHP_EOL;
use function assert;
+use function error_get_last;
use function file_exists;
use function file_get_contents;
use function is_readable;
@@ -57,7 +58,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$fileNames = $input->getArgument('file');
if ($fileNames === null) {
- return null;
+ return 0;
}
foreach ((array) $fileNames as $fileName) {
@@ -72,14 +73,22 @@ protected function execute(InputInterface $input, OutputInterface $output)
throw new InvalidArgumentException(
sprintf("SQL file '%s' does not exist.", $filePath)
);
- } elseif (! is_readable($filePath)) {
+ }
+
+ if (! is_readable($filePath)) {
throw new InvalidArgumentException(
sprintf("SQL file '%s' does not have read permissions.", $filePath)
);
}
$output->write(sprintf("Processing file '%s'... ", $filePath));
- $sql = file_get_contents($filePath);
+ $sql = @file_get_contents($filePath);
+
+ if ($sql === false) {
+ throw new RuntimeException(
+ sprintf("Unable to read SQL file '%s': %s", $filePath, error_get_last()['message'])
+ );
+ }
if ($conn instanceof PDOConnection) {
// PDO Drivers
@@ -124,6 +133,6 @@ protected function execute(InputInterface $input, OutputInterface $output)
}
}
- return null;
+ return 0;
}
}
diff --git a/lib/Doctrine/DBAL/Tools/Console/Command/RunSqlCommand.php b/lib/Doctrine/DBAL/Tools/Console/Command/RunSqlCommand.php
index 8361219ad08..b479baec2ee 100644
--- a/lib/Doctrine/DBAL/Tools/Console/Command/RunSqlCommand.php
+++ b/lib/Doctrine/DBAL/Tools/Console/Command/RunSqlCommand.php
@@ -10,7 +10,9 @@
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
+use function assert;
use function is_numeric;
+use function is_string;
use function stripos;
/**
@@ -51,6 +53,8 @@ protected function execute(InputInterface $input, OutputInterface $output)
throw new RuntimeException("Argument 'SQL' is required in order to execute this command correctly.");
}
+ assert(is_string($sql));
+
$depth = $input->getOption('depth');
if (! is_numeric($depth)) {
@@ -64,5 +68,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
}
$output->write(Dumper::dump($resultSet, (int) $depth));
+
+ return 0;
}
}
diff --git a/lib/Doctrine/DBAL/Tools/Dumper.php b/lib/Doctrine/DBAL/Tools/Dumper.php
index d5086adee81..3668efbe4d1 100644
--- a/lib/Doctrine/DBAL/Tools/Dumper.php
+++ b/lib/Doctrine/DBAL/Tools/Dumper.php
@@ -9,6 +9,7 @@
use Doctrine\Common\Persistence\Proxy;
use stdClass;
use function array_keys;
+use function assert;
use function class_exists;
use function count;
use function end;
@@ -20,9 +21,11 @@
use function ini_set;
use function is_array;
use function is_object;
+use function is_string;
use function ob_get_clean;
use function ob_start;
use function strip_tags;
+use function strlen;
use function strrpos;
use function substr;
use function var_dump;
@@ -68,7 +71,10 @@ public static function dump($var, int $maxDepth = 2) : string
var_dump($var);
try {
- return strip_tags(html_entity_decode(ob_get_clean()));
+ $output = ob_get_clean();
+ assert(is_string($output));
+
+ return strip_tags(html_entity_decode($output));
} finally {
ini_set('html_errors', $html);
}
@@ -171,6 +177,6 @@ private static function getClass($object) : string
return $class;
}
- return substr($class, $pos + Proxy::MARKER_LENGTH + 2);
+ return substr($class, $pos + strlen(Proxy::MARKER) + 2);
}
}
diff --git a/lib/Doctrine/DBAL/Types/ArrayType.php b/lib/Doctrine/DBAL/Types/ArrayType.php
index 9bb8e578b23..78325ad95c9 100644
--- a/lib/Doctrine/DBAL/Types/ArrayType.php
+++ b/lib/Doctrine/DBAL/Types/ArrayType.php
@@ -43,7 +43,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
$value = is_resource($value) ? stream_get_contents($value) : $value;
- set_error_handler(function (int $code, string $message) : void {
+ set_error_handler(function (int $code, string $message) : bool {
throw ConversionException::conversionFailedUnserialization($this->getName(), $message);
});
@@ -59,7 +59,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
*/
public function getName()
{
- return Type::TARRAY;
+ return Types::ARRAY;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/BigIntType.php b/lib/Doctrine/DBAL/Types/BigIntType.php
index 1d320d624d4..69cd5341d84 100644
--- a/lib/Doctrine/DBAL/Types/BigIntType.php
+++ b/lib/Doctrine/DBAL/Types/BigIntType.php
@@ -15,7 +15,7 @@ class BigIntType extends Type implements PhpIntegerMappingType
*/
public function getName()
{
- return Type::BIGINT;
+ return Types::BIGINT;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/BinaryType.php b/lib/Doctrine/DBAL/Types/BinaryType.php
index 14362e840ae..d604b3bff69 100644
--- a/lib/Doctrine/DBAL/Types/BinaryType.php
+++ b/lib/Doctrine/DBAL/Types/BinaryType.php
@@ -4,6 +4,7 @@
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
+use function assert;
use function fopen;
use function fseek;
use function fwrite;
@@ -34,13 +35,14 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
if (is_string($value)) {
$fp = fopen('php://temp', 'rb+');
+ assert(is_resource($fp));
fwrite($fp, $value);
fseek($fp, 0);
$value = $fp;
}
if (! is_resource($value)) {
- throw ConversionException::conversionFailed($value, self::BINARY);
+ throw ConversionException::conversionFailed($value, Types::BINARY);
}
return $value;
@@ -51,7 +53,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
*/
public function getName()
{
- return Type::BINARY;
+ return Types::BINARY;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/BlobType.php b/lib/Doctrine/DBAL/Types/BlobType.php
index c309f0f0637..e4bb22f08d8 100644
--- a/lib/Doctrine/DBAL/Types/BlobType.php
+++ b/lib/Doctrine/DBAL/Types/BlobType.php
@@ -4,6 +4,7 @@
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
+use function assert;
use function fopen;
use function fseek;
use function fwrite;
@@ -34,13 +35,14 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
if (is_string($value)) {
$fp = fopen('php://temp', 'rb+');
+ assert(is_resource($fp));
fwrite($fp, $value);
fseek($fp, 0);
$value = $fp;
}
if (! is_resource($value)) {
- throw ConversionException::conversionFailed($value, self::BLOB);
+ throw ConversionException::conversionFailed($value, Types::BLOB);
}
return $value;
@@ -51,7 +53,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
*/
public function getName()
{
- return Type::BLOB;
+ return Types::BLOB;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/BooleanType.php b/lib/Doctrine/DBAL/Types/BooleanType.php
index 976f00e1fb7..bf9be9b19fe 100644
--- a/lib/Doctrine/DBAL/Types/BooleanType.php
+++ b/lib/Doctrine/DBAL/Types/BooleanType.php
@@ -39,7 +39,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
*/
public function getName()
{
- return Type::BOOLEAN;
+ return Types::BOOLEAN;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/DateImmutableType.php b/lib/Doctrine/DBAL/Types/DateImmutableType.php
index 196fc88c7b4..a4c5d266d92 100644
--- a/lib/Doctrine/DBAL/Types/DateImmutableType.php
+++ b/lib/Doctrine/DBAL/Types/DateImmutableType.php
@@ -15,7 +15,7 @@ class DateImmutableType extends DateType
*/
public function getName()
{
- return Type::DATE_IMMUTABLE;
+ return Types::DATE_IMMUTABLE;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/DateIntervalType.php b/lib/Doctrine/DBAL/Types/DateIntervalType.php
index 30e61c9eaa5..96a446e8607 100644
--- a/lib/Doctrine/DBAL/Types/DateIntervalType.php
+++ b/lib/Doctrine/DBAL/Types/DateIntervalType.php
@@ -19,7 +19,7 @@ class DateIntervalType extends Type
*/
public function getName()
{
- return Type::DATEINTERVAL;
+ return Types::DATEINTERVAL;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/DateTimeImmutableType.php b/lib/Doctrine/DBAL/Types/DateTimeImmutableType.php
index fdda50faa44..51960a8c344 100644
--- a/lib/Doctrine/DBAL/Types/DateTimeImmutableType.php
+++ b/lib/Doctrine/DBAL/Types/DateTimeImmutableType.php
@@ -16,7 +16,7 @@ class DateTimeImmutableType extends DateTimeType
*/
public function getName()
{
- return Type::DATETIME_IMMUTABLE;
+ return Types::DATETIME_IMMUTABLE;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/DateTimeType.php b/lib/Doctrine/DBAL/Types/DateTimeType.php
index 962d9d38da0..65071a6b188 100644
--- a/lib/Doctrine/DBAL/Types/DateTimeType.php
+++ b/lib/Doctrine/DBAL/Types/DateTimeType.php
@@ -17,7 +17,7 @@ class DateTimeType extends Type implements PhpDateTimeMappingType
*/
public function getName()
{
- return Type::DATETIME;
+ return Types::DATETIME_MUTABLE;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/DateTimeTzImmutableType.php b/lib/Doctrine/DBAL/Types/DateTimeTzImmutableType.php
index 253c02e002b..b888624796e 100644
--- a/lib/Doctrine/DBAL/Types/DateTimeTzImmutableType.php
+++ b/lib/Doctrine/DBAL/Types/DateTimeTzImmutableType.php
@@ -15,7 +15,7 @@ class DateTimeTzImmutableType extends DateTimeTzType
*/
public function getName()
{
- return Type::DATETIMETZ_IMMUTABLE;
+ return Types::DATETIMETZ_IMMUTABLE;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/DateTimeTzType.php b/lib/Doctrine/DBAL/Types/DateTimeTzType.php
index 0b78720ec3e..6240da8926c 100644
--- a/lib/Doctrine/DBAL/Types/DateTimeTzType.php
+++ b/lib/Doctrine/DBAL/Types/DateTimeTzType.php
@@ -29,7 +29,7 @@ class DateTimeTzType extends Type implements PhpDateTimeMappingType
*/
public function getName()
{
- return Type::DATETIMETZ;
+ return Types::DATETIMETZ_MUTABLE;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/DateType.php b/lib/Doctrine/DBAL/Types/DateType.php
index b5ad5356f69..15d9362f288 100644
--- a/lib/Doctrine/DBAL/Types/DateType.php
+++ b/lib/Doctrine/DBAL/Types/DateType.php
@@ -16,7 +16,7 @@ class DateType extends Type
*/
public function getName()
{
- return Type::DATE;
+ return Types::DATE_MUTABLE;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/DecimalType.php b/lib/Doctrine/DBAL/Types/DecimalType.php
index 318cb2476b7..b2d37f00b3e 100644
--- a/lib/Doctrine/DBAL/Types/DecimalType.php
+++ b/lib/Doctrine/DBAL/Types/DecimalType.php
@@ -14,7 +14,7 @@ class DecimalType extends Type
*/
public function getName()
{
- return Type::DECIMAL;
+ return Types::DECIMAL;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/FloatType.php b/lib/Doctrine/DBAL/Types/FloatType.php
index 3ad9aa737fa..4988d7253dc 100644
--- a/lib/Doctrine/DBAL/Types/FloatType.php
+++ b/lib/Doctrine/DBAL/Types/FloatType.php
@@ -11,7 +11,7 @@ class FloatType extends Type
*/
public function getName()
{
- return Type::FLOAT;
+ return Types::FLOAT;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/GuidType.php b/lib/Doctrine/DBAL/Types/GuidType.php
index a9ab21537c5..dd4516505ec 100644
--- a/lib/Doctrine/DBAL/Types/GuidType.php
+++ b/lib/Doctrine/DBAL/Types/GuidType.php
@@ -22,7 +22,7 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla
*/
public function getName()
{
- return Type::GUID;
+ return Types::GUID;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/IntegerType.php b/lib/Doctrine/DBAL/Types/IntegerType.php
index f04f3c7e008..d7ab8fd80f2 100644
--- a/lib/Doctrine/DBAL/Types/IntegerType.php
+++ b/lib/Doctrine/DBAL/Types/IntegerType.php
@@ -15,7 +15,7 @@ class IntegerType extends Type implements PhpIntegerMappingType
*/
public function getName()
{
- return Type::INTEGER;
+ return Types::INTEGER;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/JsonArrayType.php b/lib/Doctrine/DBAL/Types/JsonArrayType.php
index beae8038737..bc468fba0f3 100644
--- a/lib/Doctrine/DBAL/Types/JsonArrayType.php
+++ b/lib/Doctrine/DBAL/Types/JsonArrayType.php
@@ -33,7 +33,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
*/
public function getName()
{
- return Type::JSON_ARRAY;
+ return Types::JSON_ARRAY;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/JsonType.php b/lib/Doctrine/DBAL/Types/JsonType.php
index 00cd3f80fcf..127f3fa8ee1 100644
--- a/lib/Doctrine/DBAL/Types/JsonType.php
+++ b/lib/Doctrine/DBAL/Types/JsonType.php
@@ -69,7 +69,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
*/
public function getName()
{
- return Type::JSON;
+ return Types::JSON;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/ObjectType.php b/lib/Doctrine/DBAL/Types/ObjectType.php
index 081ec483b16..82b1a752ee1 100644
--- a/lib/Doctrine/DBAL/Types/ObjectType.php
+++ b/lib/Doctrine/DBAL/Types/ObjectType.php
@@ -42,7 +42,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
$value = is_resource($value) ? stream_get_contents($value) : $value;
- set_error_handler(function (int $code, string $message) : void {
+ set_error_handler(function (int $code, string $message) : bool {
throw ConversionException::conversionFailedUnserialization($this->getName(), $message);
});
@@ -58,7 +58,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
*/
public function getName()
{
- return Type::OBJECT;
+ return Types::OBJECT;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/SimpleArrayType.php b/lib/Doctrine/DBAL/Types/SimpleArrayType.php
index d23776f5f0a..31c22b8e6f6 100644
--- a/lib/Doctrine/DBAL/Types/SimpleArrayType.php
+++ b/lib/Doctrine/DBAL/Types/SimpleArrayType.php
@@ -54,7 +54,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
*/
public function getName()
{
- return Type::SIMPLE_ARRAY;
+ return Types::SIMPLE_ARRAY;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/SmallIntType.php b/lib/Doctrine/DBAL/Types/SmallIntType.php
index bca8a533f06..5fa3cb74bbc 100644
--- a/lib/Doctrine/DBAL/Types/SmallIntType.php
+++ b/lib/Doctrine/DBAL/Types/SmallIntType.php
@@ -15,7 +15,7 @@ class SmallIntType extends Type implements PhpIntegerMappingType
*/
public function getName()
{
- return Type::SMALLINT;
+ return Types::SMALLINT;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/StringType.php b/lib/Doctrine/DBAL/Types/StringType.php
index 879359a13d8..e0d1a552f5d 100644
--- a/lib/Doctrine/DBAL/Types/StringType.php
+++ b/lib/Doctrine/DBAL/Types/StringType.php
@@ -30,6 +30,6 @@ public function getDefaultLength(AbstractPlatform $platform)
*/
public function getName()
{
- return Type::STRING;
+ return Types::STRING;
}
}
diff --git a/lib/Doctrine/DBAL/Types/TextType.php b/lib/Doctrine/DBAL/Types/TextType.php
index 635d4f7de49..76dd7c48cf0 100644
--- a/lib/Doctrine/DBAL/Types/TextType.php
+++ b/lib/Doctrine/DBAL/Types/TextType.php
@@ -32,6 +32,6 @@ public function convertToPHPValue($value, AbstractPlatform $platform)
*/
public function getName()
{
- return Type::TEXT;
+ return Types::TEXT;
}
}
diff --git a/lib/Doctrine/DBAL/Types/TimeImmutableType.php b/lib/Doctrine/DBAL/Types/TimeImmutableType.php
index 8cb870fb393..cc437695564 100644
--- a/lib/Doctrine/DBAL/Types/TimeImmutableType.php
+++ b/lib/Doctrine/DBAL/Types/TimeImmutableType.php
@@ -15,7 +15,7 @@ class TimeImmutableType extends TimeType
*/
public function getName()
{
- return Type::TIME_IMMUTABLE;
+ return Types::TIME_IMMUTABLE;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/TimeType.php b/lib/Doctrine/DBAL/Types/TimeType.php
index c9895294e03..1eeb2c01d1f 100644
--- a/lib/Doctrine/DBAL/Types/TimeType.php
+++ b/lib/Doctrine/DBAL/Types/TimeType.php
@@ -16,7 +16,7 @@ class TimeType extends Type
*/
public function getName()
{
- return Type::TIME;
+ return Types::TIME_MUTABLE;
}
/**
diff --git a/lib/Doctrine/DBAL/Types/Type.php b/lib/Doctrine/DBAL/Types/Type.php
index ec1ab681356..ac7ab7bec13 100644
--- a/lib/Doctrine/DBAL/Types/Type.php
+++ b/lib/Doctrine/DBAL/Types/Type.php
@@ -5,9 +5,11 @@
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
-use function end;
-use function explode;
+use function array_map;
+use function get_class;
use function str_replace;
+use function strrpos;
+use function substr;
/**
* The base class for so-called Doctrine mapping types.
@@ -16,76 +18,119 @@
*/
abstract class Type
{
- public const TARRAY = 'array';
- public const SIMPLE_ARRAY = 'simple_array';
- public const JSON_ARRAY = 'json_array';
- public const JSON = 'json';
- public const BIGINT = 'bigint';
- public const BOOLEAN = 'boolean';
- public const DATETIME = 'datetime';
- public const DATETIME_IMMUTABLE = 'datetime_immutable';
- public const DATETIMETZ = 'datetimetz';
- public const DATETIMETZ_IMMUTABLE = 'datetimetz_immutable';
- public const DATE = 'date';
- public const DATE_IMMUTABLE = 'date_immutable';
- public const TIME = 'time';
- public const TIME_IMMUTABLE = 'time_immutable';
- public const DECIMAL = 'decimal';
- public const INTEGER = 'integer';
- public const OBJECT = 'object';
- public const SMALLINT = 'smallint';
- public const STRING = 'string';
- public const TEXT = 'text';
- public const BINARY = 'binary';
- public const BLOB = 'blob';
- public const FLOAT = 'float';
- public const GUID = 'guid';
- public const DATEINTERVAL = 'dateinterval';
+ /** @deprecated Use {@see DefaultTypes::BIGINT} instead. */
+ public const BIGINT = Types::BIGINT;
- /**
- * Map of already instantiated type objects. One instance per type (flyweight).
- *
- * @var self[]
- */
- private static $_typeObjects = [];
+ /** @deprecated Use {@see DefaultTypes::BINARY} instead. */
+ public const BINARY = Types::BINARY;
+
+ /** @deprecated Use {@see DefaultTypes::BLOB} instead. */
+ public const BLOB = Types::BLOB;
+
+ /** @deprecated Use {@see DefaultTypes::BOOLEAN} instead. */
+ public const BOOLEAN = Types::BOOLEAN;
+
+ /** @deprecated Use {@see DefaultTypes::DATE_MUTABLE} instead. */
+ public const DATE = Types::DATE_MUTABLE;
+
+ /** @deprecated Use {@see DefaultTypes::DATE_IMMUTABLE} instead. */
+ public const DATE_IMMUTABLE = Types::DATE_IMMUTABLE;
+
+ /** @deprecated Use {@see DefaultTypes::DATEINTERVAL} instead. */
+ public const DATEINTERVAL = Types::DATEINTERVAL;
+
+ /** @deprecated Use {@see DefaultTypes::DATETIME_MUTABLE} instead. */
+ public const DATETIME = Types::DATETIME_MUTABLE;
+
+ /** @deprecated Use {@see DefaultTypes::DATETIME_IMMUTABLE} instead. */
+ public const DATETIME_IMMUTABLE = Types::DATETIME_IMMUTABLE;
+
+ /** @deprecated Use {@see DefaultTypes::DATETIMETZ_MUTABLE} instead. */
+ public const DATETIMETZ = Types::DATETIMETZ_MUTABLE;
+
+ /** @deprecated Use {@see DefaultTypes::DATETIMETZ_IMMUTABLE} instead. */
+ public const DATETIMETZ_IMMUTABLE = Types::DATETIMETZ_IMMUTABLE;
+
+ /** @deprecated Use {@see DefaultTypes::DECIMAL} instead. */
+ public const DECIMAL = Types::DECIMAL;
+
+ /** @deprecated Use {@see DefaultTypes::FLOAT} instead. */
+ public const FLOAT = Types::FLOAT;
+
+ /** @deprecated Use {@see DefaultTypes::GUID} instead. */
+ public const GUID = Types::GUID;
+
+ /** @deprecated Use {@see DefaultTypes::INTEGER} instead. */
+ public const INTEGER = Types::INTEGER;
+
+ /** @deprecated Use {@see DefaultTypes::JSON} instead. */
+ public const JSON = Types::JSON;
+
+ /** @deprecated Use {@see DefaultTypes::JSON_ARRAY} instead. */
+ public const JSON_ARRAY = Types::JSON_ARRAY;
+
+ /** @deprecated Use {@see DefaultTypes::OBJECT} instead. */
+ public const OBJECT = Types::OBJECT;
+
+ /** @deprecated Use {@see DefaultTypes::SIMPLE_ARRAY} instead. */
+ public const SIMPLE_ARRAY = Types::SIMPLE_ARRAY;
+
+ /** @deprecated Use {@see DefaultTypes::SMALLINT} instead. */
+ public const SMALLINT = Types::SMALLINT;
+
+ /** @deprecated Use {@see DefaultTypes::STRING} instead. */
+ public const STRING = Types::STRING;
+
+ /** @deprecated Use {@see DefaultTypes::ARRAY} instead. */
+ public const TARRAY = Types::ARRAY;
+
+ /** @deprecated Use {@see DefaultTypes::TEXT} instead. */
+ public const TEXT = Types::TEXT;
+
+ /** @deprecated Use {@see DefaultTypes::TIME_MUTABLE} instead. */
+ public const TIME = Types::TIME_MUTABLE;
+
+ /** @deprecated Use {@see DefaultTypes::TIME_IMMUTABLE} instead. */
+ public const TIME_IMMUTABLE = Types::TIME_IMMUTABLE;
/**
* The map of supported doctrine mapping types.
- *
- * @var string[]
*/
- private static $_typesMap = [
- self::TARRAY => ArrayType::class,
- self::SIMPLE_ARRAY => SimpleArrayType::class,
- self::JSON_ARRAY => JsonArrayType::class,
- self::JSON => JsonType::class,
- self::OBJECT => ObjectType::class,
- self::BOOLEAN => BooleanType::class,
- self::INTEGER => IntegerType::class,
- self::SMALLINT => SmallIntType::class,
- self::BIGINT => BigIntType::class,
- self::STRING => StringType::class,
- self::TEXT => TextType::class,
- self::DATETIME => DateTimeType::class,
- self::DATETIME_IMMUTABLE => DateTimeImmutableType::class,
- self::DATETIMETZ => DateTimeTzType::class,
- self::DATETIMETZ_IMMUTABLE => DateTimeTzImmutableType::class,
- self::DATE => DateType::class,
- self::DATE_IMMUTABLE => DateImmutableType::class,
- self::TIME => TimeType::class,
- self::TIME_IMMUTABLE => TimeImmutableType::class,
- self::DECIMAL => DecimalType::class,
- self::FLOAT => FloatType::class,
- self::BINARY => BinaryType::class,
- self::BLOB => BlobType::class,
- self::GUID => GuidType::class,
- self::DATEINTERVAL => DateIntervalType::class,
+ private const BUILTIN_TYPES_MAP = [
+ Types::ARRAY => ArrayType::class,
+ Types::BIGINT => BigIntType::class,
+ Types::BINARY => BinaryType::class,
+ Types::BLOB => BlobType::class,
+ Types::BOOLEAN => BooleanType::class,
+ Types::DATE_MUTABLE => DateType::class,
+ Types::DATE_IMMUTABLE => DateImmutableType::class,
+ Types::DATEINTERVAL => DateIntervalType::class,
+ Types::DATETIME_MUTABLE => DateTimeType::class,
+ Types::DATETIME_IMMUTABLE => DateTimeImmutableType::class,
+ Types::DATETIMETZ_MUTABLE => DateTimeTzType::class,
+ Types::DATETIMETZ_IMMUTABLE => DateTimeTzImmutableType::class,
+ Types::DECIMAL => DecimalType::class,
+ Types::FLOAT => FloatType::class,
+ Types::GUID => GuidType::class,
+ Types::INTEGER => IntegerType::class,
+ Types::JSON => JsonType::class,
+ Types::JSON_ARRAY => JsonArrayType::class,
+ Types::OBJECT => ObjectType::class,
+ Types::SIMPLE_ARRAY => SimpleArrayType::class,
+ Types::SMALLINT => SmallIntType::class,
+ Types::STRING => StringType::class,
+ Types::TEXT => TextType::class,
+ Types::TIME_MUTABLE => TimeType::class,
+ Types::TIME_IMMUTABLE => TimeImmutableType::class,
];
+ /** @var TypeRegistry|null */
+ private static $typeRegistry;
+
/**
- * Prevents instantiation and forces use of the factory method.
+ * @internal Do not instantiate directly - use {@see Type::addType()} method instead.
*/
- final private function __construct()
+ final public function __construct()
{
}
@@ -148,6 +193,29 @@ abstract public function getSQLDeclaration(array $fieldDeclaration, AbstractPlat
*/
abstract public function getName();
+ /**
+ * @internal This method is only to be used within DBAL for forward compatibility purposes. Do not use directly.
+ */
+ final public static function getTypeRegistry() : TypeRegistry
+ {
+ if (self::$typeRegistry === null) {
+ self::$typeRegistry = self::createTypeRegistry();
+ }
+
+ return self::$typeRegistry;
+ }
+
+ private static function createTypeRegistry() : TypeRegistry
+ {
+ $registry = new TypeRegistry();
+
+ foreach (self::BUILTIN_TYPES_MAP as $name => $class) {
+ $registry->register($name, new $class());
+ }
+
+ return $registry;
+ }
+
/**
* Factory method to create type instances.
* Type instances are implemented as flyweights.
@@ -160,14 +228,7 @@ abstract public function getName();
*/
public static function getType($name)
{
- if (! isset(self::$_typeObjects[$name])) {
- if (! isset(self::$_typesMap[$name])) {
- throw DBALException::unknownColumnType($name);
- }
- self::$_typeObjects[$name] = new self::$_typesMap[$name]();
- }
-
- return self::$_typeObjects[$name];
+ return self::getTypeRegistry()->get($name);
}
/**
@@ -182,11 +243,7 @@ public static function getType($name)
*/
public static function addType($name, $className)
{
- if (isset(self::$_typesMap[$name])) {
- throw DBALException::typeExists($name);
- }
-
- self::$_typesMap[$name] = $className;
+ self::getTypeRegistry()->register($name, new $className());
}
/**
@@ -198,7 +255,7 @@ public static function addType($name, $className)
*/
public static function hasType($name)
{
- return isset(self::$_typesMap[$name]);
+ return self::getTypeRegistry()->has($name);
}
/**
@@ -213,15 +270,7 @@ public static function hasType($name)
*/
public static function overrideType($name, $className)
{
- if (! isset(self::$_typesMap[$name])) {
- throw DBALException::typeNotFound($name);
- }
-
- if (isset(self::$_typeObjects[$name])) {
- unset(self::$_typeObjects[$name]);
- }
-
- self::$_typesMap[$name] = $className;
+ self::getTypeRegistry()->override($name, new $className());
}
/**
@@ -245,7 +294,12 @@ public function getBindingType()
*/
public static function getTypesMap()
{
- return self::$_typesMap;
+ return array_map(
+ static function (Type $type) : string {
+ return get_class($type);
+ },
+ self::getTypeRegistry()->getMap()
+ );
}
/**
@@ -255,9 +309,14 @@ public static function getTypesMap()
*/
public function __toString()
{
- $e = explode('\\', static::class);
+ $type = static::class;
+ $position = strrpos($type, '\\');
+
+ if ($position !== false) {
+ $type = substr($type, $position);
+ }
- return str_replace('Type', '', end($e));
+ return str_replace('Type', '', $type);
}
/**
diff --git a/lib/Doctrine/DBAL/Types/TypeRegistry.php b/lib/Doctrine/DBAL/Types/TypeRegistry.php
new file mode 100644
index 00000000000..7e8093cf749
--- /dev/null
+++ b/lib/Doctrine/DBAL/Types/TypeRegistry.php
@@ -0,0 +1,118 @@
+ Map of type names and their corresponding flyweight objects. */
+ private $instances = [];
+
+ /**
+ * Finds a type by the given name.
+ *
+ * @throws DBALException
+ */
+ public function get(string $name) : Type
+ {
+ if (! isset($this->instances[$name])) {
+ throw DBALException::unknownColumnType($name);
+ }
+
+ return $this->instances[$name];
+ }
+
+ /**
+ * Finds a name for the given type.
+ *
+ * @throws DBALException
+ */
+ public function lookupName(Type $type) : string
+ {
+ $name = $this->findTypeName($type);
+
+ if ($name === null) {
+ throw DBALException::typeNotRegistered($type);
+ }
+
+ return $name;
+ }
+
+ /**
+ * Checks if there is a type of the given name.
+ */
+ public function has(string $name) : bool
+ {
+ return isset($this->instances[$name]);
+ }
+
+ /**
+ * Registers a custom type to the type map.
+ *
+ * @throws DBALException
+ */
+ public function register(string $name, Type $type) : void
+ {
+ if (isset($this->instances[$name])) {
+ throw DBALException::typeExists($name);
+ }
+
+ if ($this->findTypeName($type) !== null) {
+ throw DBALException::typeAlreadyRegistered($type);
+ }
+
+ $this->instances[$name] = $type;
+ }
+
+ /**
+ * Overrides an already defined type to use a different implementation.
+ *
+ * @throws DBALException
+ */
+ public function override(string $name, Type $type) : void
+ {
+ if (! isset($this->instances[$name])) {
+ throw DBALException::typeNotFound($name);
+ }
+
+ if (! in_array($this->findTypeName($type), [$name, null], true)) {
+ throw DBALException::typeAlreadyRegistered($type);
+ }
+
+ $this->instances[$name] = $type;
+ }
+
+ /**
+ * Gets the map of all registered types and their corresponding type instances.
+ *
+ * @internal
+ *
+ * @return array
+ */
+ public function getMap() : array
+ {
+ return $this->instances;
+ }
+
+ private function findTypeName(Type $type) : ?string
+ {
+ $name = array_search($type, $this->instances, true);
+
+ if ($name === false) {
+ return null;
+ }
+
+ return $name;
+ }
+}
diff --git a/lib/Doctrine/DBAL/Types/Types.php b/lib/Doctrine/DBAL/Types/Types.php
new file mode 100644
index 00000000000..f8d0cf913c3
--- /dev/null
+++ b/lib/Doctrine/DBAL/Types/Types.php
@@ -0,0 +1,43 @@
+
-
-
+
+
+
+
+
+ */lib/*
+
+
+
+ */lib/*
@@ -41,6 +49,7 @@
lib/Doctrine/DBAL/Platforms/AbstractPlatform.php
lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php
+ tests/Doctrine/Tests/DBAL/Platforms/AbstractPlatformTestCase.php
@@ -60,7 +69,14 @@
-
+
lib/Doctrine/DBAL/Schema/Comparator.php
+
+
+
+ lib/Doctrine/DBAL/Types/ArrayType.php
+ lib/Doctrine/DBAL/Types/ObjectType.php
+ tests/Doctrine/Tests/DBAL/Driver/Mysqli/MysqliConnectionTest.php
+
diff --git a/phpstan.neon.dist b/phpstan.neon.dist
index 406cc2a530e..4ae1fda3f8a 100644
--- a/phpstan.neon.dist
+++ b/phpstan.neon.dist
@@ -1,5 +1,5 @@
parameters:
- level: 3
+ level: 7
paths:
- %currentWorkingDirectory%/lib
autoload_files:
@@ -12,7 +12,12 @@ parameters:
# removing it would be BC break
- '~^Constructor of class Doctrine\\DBAL\\Schema\\Table has an unused parameter \$idGeneratorType\.\z~'
+ # declaring $tableName in AbstractSchemaManager::_getPortableTableIndexesList() non-optional will be a BC break
+ - '~^Parameter #2 \$table of class Doctrine\\DBAL\\Event\\SchemaIndexDefinitionEventArgs constructor expects string, string\|null given\.\z~'
+
# changing these would be a BC break, to be done in next major
+ - "~^Casting to bool something that's already bool.~"
+ - "~^Casting to int something that's already int.~"
- '~^Method Doctrine\\DBAL\\Driver\\IBMDB2\\DB2Connection::exec\(\) should return int but returns bool\.\z~'
- '~^Method Doctrine\\DBAL\\Query\\QueryBuilder::execute\(\) should return Doctrine\\DBAL\\Driver\\Statement\|int but returns Doctrine\\DBAL\\Driver\\ResultStatement\.\z~'
- '~^Property Doctrine\\DBAL\\Schema\\Table::\$_primaryKeyName \(string\) does not accept (default value of type )?false\.\z~'
@@ -23,11 +28,18 @@ parameters:
- '~^Method Doctrine\\DBAL\\Driver\\OCI8\\OCI8Connection::lastInsertId\(\) should return string but returns (int|false)\.\z~'
- '~^Method Doctrine\\DBAL\\Driver\\SQLSrv\\SQLSrvConnection::errorCode\(\) should return string\|null but returns false\.\z~'
- # http://php.net/manual/en/pdo.sqlitecreatefunction.php
+ # https://bugs.php.net/bug.php?id=78126
- '~^Call to an undefined method Doctrine\\DBAL\\Driver\\PDOConnection::sqliteCreateFunction\(\)\.\z~'
+ # https://github.com/phpstan/phpstan/issues/1847
+ - '~^Parameter #2 \$registeredAliases of static method Doctrine\\DBAL\\Query\\QueryException::unknownAlias\(\) expects array, array given\.\z~'
+ - '~^Parameter #2 \$registeredAliases of static method Doctrine\\DBAL\\Query\\QueryException::nonUniqueAlias\(\) expects array, array given\.\z~'
+
+ # PHPStan is too strict about preg_replace(): https://phpstan.org/r/993dc99f-0d43-4b51-868b-d01f982c1463
+ - '~^Method Doctrine\\DBAL\\Platforms\\AbstractPlatform::escapeStringForLike\(\) should return string but returns string|null\.\z~'
+
# legacy variadic-like signature
- - '~^Method Doctrine\\DBAL\\Driver\\Connection::query\(\) invoked with \d+ parameters?, 0 required\.\z~'
+ - '~^Method Doctrine\\DBAL(\\.*)?Connection::query\(\) invoked with \d+ parameters?, 0 required\.\z~'
# some drivers actually do accept 2nd parameter...
- '~^Method Doctrine\\DBAL\\Platforms\\AbstractPlatform::getListTableForeignKeysSQL\(\) invoked with \d+ parameters, 1 required\.\z~'
@@ -39,8 +51,8 @@ parameters:
# inheritance variance inference issue
- '~^Method Doctrine\\DBAL\\Driver\\PDOConnection::\w+\(\) should return Doctrine\\DBAL\\Driver\\Statement but returns PDOStatement\.\z~'
- # may not exist when pdo_sqlsrv is not loaded
+ # may not exist when pdo_sqlsrv is not loaded but PDO is
- '~^Access to undefined constant PDO::SQLSRV_ENCODING_BINARY\.\z~'
- # weird class name, doesn't exist in stubs either
+ # weird class name, represented in stubs as OCI_(Lob|Collection)
- '~unknown class OCI-(Lob|Collection)~'
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index b212ccf7e0d..f62532ed9f9 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -60,7 +60,6 @@
-
diff --git a/tests/Doctrine/Tests/DBAL/Cache/QueryCacheProfileTest.php b/tests/Doctrine/Tests/DBAL/Cache/QueryCacheProfileTest.php
index 1d500046260..217b27d1f2f 100644
--- a/tests/Doctrine/Tests/DBAL/Cache/QueryCacheProfileTest.php
+++ b/tests/Doctrine/Tests/DBAL/Cache/QueryCacheProfileTest.php
@@ -33,12 +33,12 @@ class QueryCacheProfileTest extends DbalTestCase
'driver' => 'database_driver',
];
- protected function setUp()
+ protected function setUp() : void
{
$this->queryCacheProfile = new QueryCacheProfile(self::LIFETIME, self::CACHE_KEY);
}
- public function testShouldUseTheGivenCacheKeyIfPresent()
+ public function testShouldUseTheGivenCacheKeyIfPresent() : void
{
[$cacheKey] = $this->queryCacheProfile->generateCacheKeys(
$this->query,
@@ -50,7 +50,7 @@ public function testShouldUseTheGivenCacheKeyIfPresent()
self::assertEquals(self::CACHE_KEY, $cacheKey, 'The returned cache key should match the given one');
}
- public function testShouldGenerateAnAutomaticKeyIfNoKeyHasBeenGiven()
+ public function testShouldGenerateAnAutomaticKeyIfNoKeyHasBeenGiven() : void
{
$this->queryCacheProfile = $this->queryCacheProfile->setCacheKey(null);
@@ -70,7 +70,7 @@ public function testShouldGenerateAnAutomaticKeyIfNoKeyHasBeenGiven()
self::assertNotEmpty($cacheKey, 'The generated cache key should not be empty');
}
- public function testShouldGenerateDifferentKeysForSameQueryAndParamsAndDifferentConnections()
+ public function testShouldGenerateDifferentKeysForSameQueryAndParamsAndDifferentConnections() : void
{
$this->queryCacheProfile = $this->queryCacheProfile->setCacheKey(null);
@@ -93,7 +93,7 @@ public function testShouldGenerateDifferentKeysForSameQueryAndParamsAndDifferent
self::assertNotEquals($firstCacheKey, $secondCacheKey, 'Cache keys should be different');
}
- public function testConnectionParamsShouldBeHashed()
+ public function testConnectionParamsShouldBeHashed() : void
{
$this->queryCacheProfile = $this->queryCacheProfile->setCacheKey(null);
@@ -110,11 +110,11 @@ public function testConnectionParamsShouldBeHashed()
self::assertArrayHasKey('connectionParams', $params);
foreach ($this->connectionParams as $param) {
- self::assertNotContains($param, $params['connectionParams']);
+ self::assertStringNotContainsString($param, $params['connectionParams']);
}
}
- public function testShouldGenerateSameKeysIfNoneOfTheParamsChanges()
+ public function testShouldGenerateSameKeysIfNoneOfTheParamsChanges() : void
{
$this->queryCacheProfile = $this->queryCacheProfile->setCacheKey(null);
diff --git a/tests/Doctrine/Tests/DBAL/ConfigurationTest.php b/tests/Doctrine/Tests/DBAL/ConfigurationTest.php
index 8310ea15c66..6b478e82b5e 100644
--- a/tests/Doctrine/Tests/DBAL/ConfigurationTest.php
+++ b/tests/Doctrine/Tests/DBAL/ConfigurationTest.php
@@ -20,7 +20,7 @@ class ConfigurationTest extends DbalTestCase
/**
* {@inheritdoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
$this->config = new Configuration();
}
@@ -30,7 +30,7 @@ protected function setUp()
*
* @group DBAL-81
*/
- public function testReturnsDefaultConnectionAutoCommitMode()
+ public function testReturnsDefaultConnectionAutoCommitMode() : void
{
self::assertTrue($this->config->getAutoCommit());
}
@@ -40,7 +40,7 @@ public function testReturnsDefaultConnectionAutoCommitMode()
*
* @group DBAL-81
*/
- public function testSetsDefaultConnectionAutoCommitMode()
+ public function testSetsDefaultConnectionAutoCommitMode() : void
{
$this->config->setAutoCommit(false);
diff --git a/tests/Doctrine/Tests/DBAL/ConnectionTest.php b/tests/Doctrine/Tests/DBAL/ConnectionTest.php
index 52e95cfc528..fb0157314d6 100644
--- a/tests/Doctrine/Tests/DBAL/ConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/ConnectionTest.php
@@ -12,6 +12,7 @@
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\Connection as DriverConnection;
+use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
use Doctrine\DBAL\Driver\Statement;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Events;
@@ -21,14 +22,10 @@
use Doctrine\DBAL\Logging\EchoSQLLogger;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
+use Doctrine\DBAL\VersionAwarePlatformDriver;
use Doctrine\Tests\DbalTestCase;
-use Doctrine\Tests\Mocks\DriverMock;
-use Doctrine\Tests\Mocks\DriverStatementMock;
-use Doctrine\Tests\Mocks\ServerInfoAwareConnectionMock;
-use Doctrine\Tests\Mocks\VersionAwarePlatformDriverMock;
use Exception;
-use PHPUnit_Framework_MockObject_MockObject;
-use ReflectionObject;
+use PHPUnit\Framework\MockObject\MockObject;
use stdClass;
use function call_user_func_array;
@@ -49,12 +46,15 @@ class ConnectionTest extends DbalTestCase
'port' => '1234',
];
- protected function setUp()
+ protected function setUp() : void
{
$this->connection = DriverManager::getConnection($this->params);
}
- public function getExecuteUpdateMockConnection()
+ /**
+ * @return Connection|MockObject
+ */
+ private function getExecuteUpdateMockConnection()
{
$driverMock = $this->createMock(Driver::class);
@@ -64,87 +64,89 @@ public function getExecuteUpdateMockConnection()
$this->createMock(DriverConnection::class)
));
+ $platform = $this->getMockForAbstractClass(AbstractPlatform::class);
+
return $this->getMockBuilder(Connection::class)
- ->setMethods(['executeUpdate'])
- ->setConstructorArgs([['platform' => new Mocks\MockPlatform()], $driverMock])
+ ->onlyMethods(['executeUpdate'])
+ ->setConstructorArgs([['platform' => $platform], $driverMock])
->getMock();
}
- public function testIsConnected()
+ public function testIsConnected() : void
{
self::assertFalse($this->connection->isConnected());
}
- public function testNoTransactionActiveByDefault()
+ public function testNoTransactionActiveByDefault() : void
{
self::assertFalse($this->connection->isTransactionActive());
}
- public function testCommitWithNoActiveTransactionThrowsException()
+ public function testCommitWithNoActiveTransactionThrowsException() : void
{
$this->expectException(ConnectionException::class);
$this->connection->commit();
}
- public function testRollbackWithNoActiveTransactionThrowsException()
+ public function testRollbackWithNoActiveTransactionThrowsException() : void
{
$this->expectException(ConnectionException::class);
$this->connection->rollBack();
}
- public function testSetRollbackOnlyNoActiveTransactionThrowsException()
+ public function testSetRollbackOnlyNoActiveTransactionThrowsException() : void
{
$this->expectException(ConnectionException::class);
$this->connection->setRollbackOnly();
}
- public function testIsRollbackOnlyNoActiveTransactionThrowsException()
+ public function testIsRollbackOnlyNoActiveTransactionThrowsException() : void
{
$this->expectException(ConnectionException::class);
$this->connection->isRollbackOnly();
}
- public function testGetConfiguration()
+ public function testGetConfiguration() : void
{
$config = $this->connection->getConfiguration();
self::assertInstanceOf(Configuration::class, $config);
}
- public function testGetHost()
+ public function testGetHost() : void
{
self::assertEquals('localhost', $this->connection->getHost());
}
- public function testGetPort()
+ public function testGetPort() : void
{
self::assertEquals('1234', $this->connection->getPort());
}
- public function testGetUsername()
+ public function testGetUsername() : void
{
self::assertEquals('root', $this->connection->getUsername());
}
- public function testGetPassword()
+ public function testGetPassword() : void
{
self::assertEquals('password', $this->connection->getPassword());
}
- public function testGetDriver()
+ public function testGetDriver() : void
{
self::assertInstanceOf(\Doctrine\DBAL\Driver\PDOMySql\Driver::class, $this->connection->getDriver());
}
- public function testGetEventManager()
+ public function testGetEventManager() : void
{
self::assertInstanceOf(EventManager::class, $this->connection->getEventManager());
}
- public function testConnectDispatchEvent()
+ public function testConnectDispatchEvent() : void
{
- $listenerMock = $this->getMockBuilder('ConnectDispatchEventListener')
- ->setMethods(['postConnect'])
+ $listenerMock = $this->getMockBuilder($this->getMockClass('ConnectDispatchEventListener'))
+ ->addMethods(['postConnect'])
->getMock();
$listenerMock->expects($this->once())->method('postConnect');
@@ -154,26 +156,36 @@ public function testConnectDispatchEvent()
$driverMock = $this->createMock(Driver::class);
$driverMock->expects($this->at(0))
->method('connect');
- $platform = new Mocks\MockPlatform();
- $conn = new Connection(['platform' => $platform], $driverMock, new Configuration(), $eventManager);
+ $conn = new Connection([], $driverMock, new Configuration(), $eventManager);
$conn->connect();
}
- public function testEventManagerPassedToPlatform()
+ public function testEventManagerPassedToPlatform() : void
{
- $driverMock = new DriverMock();
- $connection = new Connection($this->params, $driverMock);
- self::assertInstanceOf(EventManager::class, $connection->getDatabasePlatform()->getEventManager());
- self::assertSame($connection->getEventManager(), $connection->getDatabasePlatform()->getEventManager());
+ $eventManager = new EventManager();
+
+ /** @var AbstractPlatform|MockObject $driver */
+ $platform = $this->createMock(AbstractPlatform::class);
+ $platform->expects($this->once())
+ ->method('setEventManager')
+ ->with($eventManager);
+
+ /** @var Driver|MockObject $driver */
+ $driver = $this->createMock(Driver::class);
+ $driver->expects($this->any())
+ ->method('getDatabasePlatform')
+ ->willReturn($platform);
+
+ $connection = new Connection($this->params, $driver, null, $eventManager);
+ $connection->getDatabasePlatform();
}
/**
* @requires extension pdo_sqlite
- * @expectedException \Doctrine\DBAL\DBALException
* @dataProvider getQueryMethods
*/
- public function testDriverExceptionIsWrapped($method)
+ public function testDriverExceptionIsWrapped(string $method) : void
{
$this->expectException(DBALException::class);
$this->expectExceptionMessage("An exception occurred while executing 'MUUHAAAAHAAAA':\n\nSQLSTATE[HY000]: General error: 1 near \"MUUHAAAAHAAAA\"");
@@ -186,7 +198,10 @@ public function testDriverExceptionIsWrapped($method)
$connection->$method('MUUHAAAAHAAAA');
}
- public function getQueryMethods()
+ /**
+ * @return array>
+ */
+ public static function getQueryMethods() : iterable
{
return [
['exec'],
@@ -202,7 +217,7 @@ public function getQueryMethods()
*
* @group DBAL-11
*/
- public function testEchoSQLLogger()
+ public function testEchoSQLLogger() : void
{
$logger = new EchoSQLLogger();
$this->connection->getConfiguration()->setSQLLogger($logger);
@@ -214,7 +229,7 @@ public function testEchoSQLLogger()
*
* @group DBAL-11
*/
- public function testDebugSQLStack()
+ public function testDebugSQLStack() : void
{
$logger = new DebugStack();
$this->connection->getConfiguration()->setSQLLogger($logger);
@@ -224,7 +239,7 @@ public function testDebugSQLStack()
/**
* @group DBAL-81
*/
- public function testIsAutoCommit()
+ public function testIsAutoCommit() : void
{
self::assertTrue($this->connection->isAutoCommit());
}
@@ -232,7 +247,7 @@ public function testIsAutoCommit()
/**
* @group DBAL-81
*/
- public function testSetAutoCommit()
+ public function testSetAutoCommit() : void
{
$this->connection->setAutoCommit(false);
self::assertFalse($this->connection->isAutoCommit());
@@ -243,7 +258,7 @@ public function testSetAutoCommit()
/**
* @group DBAL-81
*/
- public function testConnectStartsTransactionInNoAutoCommitMode()
+ public function testConnectStartsTransactionInNoAutoCommitMode() : void
{
$driverMock = $this->createMock(Driver::class);
$driverMock->expects($this->any())
@@ -251,7 +266,7 @@ public function testConnectStartsTransactionInNoAutoCommitMode()
->will($this->returnValue(
$this->createMock(DriverConnection::class)
));
- $conn = new Connection(['platform' => new Mocks\MockPlatform()], $driverMock);
+ $conn = new Connection([], $driverMock);
$conn->setAutoCommit(false);
@@ -265,7 +280,7 @@ public function testConnectStartsTransactionInNoAutoCommitMode()
/**
* @group DBAL-81
*/
- public function testCommitStartsTransactionInNoAutoCommitMode()
+ public function testCommitStartsTransactionInNoAutoCommitMode() : void
{
$driverMock = $this->createMock(Driver::class);
$driverMock->expects($this->any())
@@ -273,7 +288,7 @@ public function testCommitStartsTransactionInNoAutoCommitMode()
->will($this->returnValue(
$this->createMock(DriverConnection::class)
));
- $conn = new Connection(['platform' => new Mocks\MockPlatform()], $driverMock);
+ $conn = new Connection([], $driverMock);
$conn->setAutoCommit(false);
$conn->connect();
@@ -282,10 +297,40 @@ public function testCommitStartsTransactionInNoAutoCommitMode()
self::assertTrue($conn->isTransactionActive());
}
+ /**
+ * @dataProvider resultProvider
+ */
+ public function testCommitReturn(bool $expectedResult) : void
+ {
+ $driverConnection = $this->createMock(DriverConnection::class);
+ $driverConnection->expects($this->once())
+ ->method('commit')->willReturn($expectedResult);
+
+ $driverMock = $this->createMock(Driver::class);
+ $driverMock->expects($this->any())
+ ->method('connect')
+ ->will($this->returnValue($driverConnection));
+
+ $conn = new Connection([], $driverMock);
+
+ $conn->connect();
+ $conn->beginTransaction();
+
+ self::assertSame($expectedResult, $conn->commit());
+ }
+
+ /**
+ * @return bool[][]
+ */
+ public function resultProvider() : array
+ {
+ return [[true], [false]];
+ }
+
/**
* @group DBAL-81
*/
- public function testRollBackStartsTransactionInNoAutoCommitMode()
+ public function testRollBackStartsTransactionInNoAutoCommitMode() : void
{
$driverMock = $this->createMock(Driver::class);
$driverMock->expects($this->any())
@@ -293,7 +338,7 @@ public function testRollBackStartsTransactionInNoAutoCommitMode()
->will($this->returnValue(
$this->createMock(DriverConnection::class)
));
- $conn = new Connection(['platform' => new Mocks\MockPlatform()], $driverMock);
+ $conn = new Connection([], $driverMock);
$conn->setAutoCommit(false);
$conn->connect();
@@ -305,7 +350,7 @@ public function testRollBackStartsTransactionInNoAutoCommitMode()
/**
* @group DBAL-81
*/
- public function testSwitchingAutoCommitModeCommitsAllCurrentTransactions()
+ public function testSwitchingAutoCommitModeCommitsAllCurrentTransactions() : void
{
$driverMock = $this->createMock(Driver::class);
$driverMock->expects($this->any())
@@ -313,7 +358,7 @@ public function testSwitchingAutoCommitModeCommitsAllCurrentTransactions()
->will($this->returnValue(
$this->createMock(DriverConnection::class)
));
- $conn = new Connection(['platform' => new Mocks\MockPlatform()], $driverMock);
+ $conn = new Connection([], $driverMock);
$conn->connect();
$conn->beginTransaction();
@@ -329,7 +374,7 @@ public function testSwitchingAutoCommitModeCommitsAllCurrentTransactions()
self::assertFalse($conn->isTransactionActive());
}
- public function testEmptyInsert()
+ public function testEmptyInsert() : void
{
$conn = $this->getExecuteUpdateMockConnection();
@@ -343,7 +388,7 @@ public function testEmptyInsert()
/**
* @group DBAL-2511
*/
- public function testUpdateWithDifferentColumnsInDataAndIdentifiers()
+ public function testUpdateWithDifferentColumnsInDataAndIdentifiers() : void
{
$conn = $this->getExecuteUpdateMockConnection();
@@ -387,7 +432,7 @@ public function testUpdateWithDifferentColumnsInDataAndIdentifiers()
/**
* @group DBAL-2511
*/
- public function testUpdateWithSameColumnInDataAndIdentifiers()
+ public function testUpdateWithSameColumnInDataAndIdentifiers() : void
{
$conn = $this->getExecuteUpdateMockConnection();
@@ -430,7 +475,7 @@ public function testUpdateWithSameColumnInDataAndIdentifiers()
/**
* @group DBAL-2688
*/
- public function testUpdateWithIsNull()
+ public function testUpdateWithIsNull() : void
{
$conn = $this->getExecuteUpdateMockConnection();
@@ -472,7 +517,7 @@ public function testUpdateWithIsNull()
/**
* @group DBAL-2688
*/
- public function testDeleteWithIsNull()
+ public function testDeleteWithIsNull() : void
{
$conn = $this->getExecuteUpdateMockConnection();
@@ -497,7 +542,7 @@ public function testDeleteWithIsNull()
);
}
- public function testFetchAssoc()
+ public function testFetchAssoc() : void
{
$statement = 'SELECT * FROM foo WHERE bar = ?';
$params = [666];
@@ -512,17 +557,17 @@ public function testFetchAssoc()
$this->createMock(DriverConnection::class)
));
- $driverStatementMock = $this->createMock(DriverStatementMock::class);
+ $driverStatementMock = $this->createMock(Statement::class);
$driverStatementMock->expects($this->once())
->method('fetch')
->with(FetchMode::ASSOCIATIVE)
->will($this->returnValue($result));
- /** @var PHPUnit_Framework_MockObject_MockObject|Connection $conn */
+ /** @var Connection|MockObject $conn */
$conn = $this->getMockBuilder(Connection::class)
- ->setMethods(['executeQuery'])
- ->setConstructorArgs([['platform' => new Mocks\MockPlatform()], $driverMock])
+ ->onlyMethods(['executeQuery'])
+ ->setConstructorArgs([[], $driverMock])
->getMock();
$conn->expects($this->once())
@@ -533,7 +578,7 @@ public function testFetchAssoc()
self::assertSame($result, $conn->fetchAssoc($statement, $params, $types));
}
- public function testFetchArray()
+ public function testFetchArray() : void
{
$statement = 'SELECT * FROM foo WHERE bar = ?';
$params = [666];
@@ -548,17 +593,17 @@ public function testFetchArray()
$this->createMock(DriverConnection::class)
));
- $driverStatementMock = $this->createMock(DriverStatementMock::class);
+ $driverStatementMock = $this->createMock(Statement::class);
$driverStatementMock->expects($this->once())
->method('fetch')
->with(FetchMode::NUMERIC)
->will($this->returnValue($result));
- /** @var PHPUnit_Framework_MockObject_MockObject|Connection $conn */
+ /** @var Connection|MockObject $conn */
$conn = $this->getMockBuilder(Connection::class)
- ->setMethods(['executeQuery'])
- ->setConstructorArgs([['platform' => new Mocks\MockPlatform()], $driverMock])
+ ->onlyMethods(['executeQuery'])
+ ->setConstructorArgs([[], $driverMock])
->getMock();
$conn->expects($this->once())
@@ -569,7 +614,7 @@ public function testFetchArray()
self::assertSame($result, $conn->fetchArray($statement, $params, $types));
}
- public function testFetchColumn()
+ public function testFetchColumn() : void
{
$statement = 'SELECT * FROM foo WHERE bar = ?';
$params = [666];
@@ -585,17 +630,17 @@ public function testFetchColumn()
$this->createMock(DriverConnection::class)
));
- $driverStatementMock = $this->createMock(DriverStatementMock::class);
+ $driverStatementMock = $this->createMock(Statement::class);
$driverStatementMock->expects($this->once())
->method('fetchColumn')
->with($column)
->will($this->returnValue($result));
- /** @var PHPUnit_Framework_MockObject_MockObject|Connection $conn */
+ /** @var Connection|MockObject $conn */
$conn = $this->getMockBuilder(Connection::class)
- ->setMethods(['executeQuery'])
- ->setConstructorArgs([['platform' => new Mocks\MockPlatform()], $driverMock])
+ ->onlyMethods(['executeQuery'])
+ ->setConstructorArgs([[], $driverMock])
->getMock();
$conn->expects($this->once())
@@ -606,30 +651,7 @@ public function testFetchColumn()
self::assertSame($result, $conn->fetchColumn($statement, $params, $column, $types));
}
- public function testConnectionIsClosedButNotUnset()
- {
- // mock Connection, and make connect() purposefully do nothing
- $connection = $this->getMockBuilder(Connection::class)
- ->disableOriginalConstructor()
- ->setMethods(['connect'])
- ->getMock();
-
- // artificially set the wrapped connection to non-null
- $reflection = new ReflectionObject($connection);
- $connProperty = $reflection->getProperty('_conn');
- $connProperty->setAccessible(true);
- $connProperty->setValue($connection, new stdClass());
-
- // close the connection (should nullify the wrapped connection)
- $connection->close();
-
- // the wrapped connection should be null
- // (and since connect() does nothing, this will not reconnect)
- // this will also fail if this _conn property was unset instead of set to null
- self::assertNull($connection->getWrappedConnection());
- }
-
- public function testFetchAll()
+ public function testFetchAll() : void
{
$statement = 'SELECT * FROM foo WHERE bar = ?';
$params = [666];
@@ -644,16 +666,16 @@ public function testFetchAll()
$this->createMock(DriverConnection::class)
));
- $driverStatementMock = $this->createMock(DriverStatementMock::class);
+ $driverStatementMock = $this->createMock(Statement::class);
$driverStatementMock->expects($this->once())
->method('fetchAll')
->will($this->returnValue($result));
- /** @var PHPUnit_Framework_MockObject_MockObject|Connection $conn */
+ /** @var Connection|MockObject $conn */
$conn = $this->getMockBuilder(Connection::class)
- ->setMethods(['executeQuery'])
- ->setConstructorArgs([['platform' => new Mocks\MockPlatform()], $driverMock])
+ ->onlyMethods(['executeQuery'])
+ ->setConstructorArgs([[], $driverMock])
->getMock();
$conn->expects($this->once())
@@ -664,7 +686,7 @@ public function testFetchAll()
self::assertSame($result, $conn->fetchAll($statement, $params, $types));
}
- public function testConnectionDoesNotMaintainTwoReferencesToExternalPDO()
+ public function testConnectionDoesNotMaintainTwoReferencesToExternalPDO() : void
{
$params['pdo'] = new stdClass();
@@ -675,7 +697,7 @@ public function testConnectionDoesNotMaintainTwoReferencesToExternalPDO()
self::assertArrayNotHasKey('pdo', $conn->getParams(), 'Connection is maintaining additional reference to the PDO connection');
}
- public function testPassingExternalPDOMeansConnectionIsConnected()
+ public function testPassingExternalPDOMeansConnectionIsConnected() : void
{
$params['pdo'] = new stdClass();
@@ -686,7 +708,7 @@ public function testPassingExternalPDOMeansConnectionIsConnected()
self::assertTrue($conn->isConnected(), 'Connection is not connected after passing external PDO');
}
- public function testCallingDeleteWithNoDeletionCriteriaResultsInInvalidArgumentException()
+ public function testCallingDeleteWithNoDeletionCriteriaResultsInInvalidArgumentException() : void
{
/** @var Driver $driver */
$driver = $this->createMock(Driver::class);
@@ -702,7 +724,10 @@ public function testCallingDeleteWithNoDeletionCriteriaResultsInInvalidArgumentE
$conn->delete('kittens', []);
}
- public function dataCallConnectOnce()
+ /**
+ * @return array>
+ */
+ public static function dataCallConnectOnce() : iterable
{
return [
['delete', ['tbl', ['id' => 12345]]],
@@ -714,13 +739,15 @@ public function dataCallConnectOnce()
}
/**
+ * @param array $params
+ *
* @dataProvider dataCallConnectOnce
*/
- public function testCallConnectOnce($method, $params)
+ public function testCallConnectOnce(string $method, array $params) : void
{
$driverMock = $this->createMock(Driver::class);
- $pdoMock = $this->createMock(\Doctrine\DBAL\Driver\Connection::class);
- $platformMock = new Mocks\MockPlatform();
+ $pdoMock = $this->createMock(Connection::class);
+ $platformMock = $this->createMock(AbstractPlatform::class);
$stmtMock = $this->createMock(Statement::class);
$pdoMock->expects($this->any())
@@ -729,7 +756,7 @@ public function testCallConnectOnce($method, $params)
$conn = $this->getMockBuilder(Connection::class)
->setConstructorArgs([['pdo' => $pdoMock, 'platform' => $platformMock], $driverMock])
- ->setMethods(['connect'])
+ ->onlyMethods(['connect'])
->getMock();
$conn->expects($this->once())->method('connect');
@@ -740,15 +767,15 @@ public function testCallConnectOnce($method, $params)
/**
* @group DBAL-1127
*/
- public function testPlatformDetectionIsTriggerOnlyOnceOnRetrievingPlatform()
+ public function testPlatformDetectionIsTriggerOnlyOnceOnRetrievingPlatform() : void
{
- /** @var VersionAwarePlatformDriverMock|PHPUnit_Framework_MockObject_MockObject $driverMock */
- $driverMock = $this->createMock(VersionAwarePlatformDriverMock::class);
+ /** @var Driver|VersionAwarePlatformDriver|MockObject $driverMock */
+ $driverMock = $this->createMock([Driver::class, VersionAwarePlatformDriver::class]);
- /** @var ServerInfoAwareConnectionMock|PHPUnit_Framework_MockObject_MockObject $driverConnectionMock */
- $driverConnectionMock = $this->createMock(ServerInfoAwareConnectionMock::class);
+ /** @var ServerInfoAwareConnection|MockObject $driverConnectionMock */
+ $driverConnectionMock = $this->createMock(ServerInfoAwareConnection::class);
- /** @var AbstractPlatform|PHPUnit_Framework_MockObject_MockObject $platformMock */
+ /** @var AbstractPlatform|MockObject $platformMock */
$platformMock = $this->getMockForAbstractClass(AbstractPlatform::class);
$connection = new Connection([], $driverMock);
@@ -773,7 +800,7 @@ public function testPlatformDetectionIsTriggerOnlyOnceOnRetrievingPlatform()
self::assertSame($platformMock, $connection->getDatabasePlatform());
}
- public function testConnectionParamsArePassedToTheQueryCacheProfileInExecuteCacheQuery()
+ public function testConnectionParamsArePassedToTheQueryCacheProfileInExecuteCacheQuery() : void
{
$resultCacheDriverMock = $this->createMock(Cache::class);
@@ -787,7 +814,7 @@ public function testConnectionParamsArePassedToTheQueryCacheProfileInExecuteCach
$params = [666];
$types = [ParameterType::INTEGER];
- /** @var QueryCacheProfile|PHPUnit_Framework_MockObject_MockObject $queryCacheProfileMock */
+ /** @var QueryCacheProfile|MockObject $queryCacheProfileMock */
$queryCacheProfileMock = $this->createMock(QueryCacheProfile::class);
$queryCacheProfileMock
@@ -824,7 +851,7 @@ public function testShouldNotPassPlatformInParamsToTheQueryCacheProfileInExecute
->with('cacheKey')
->will($this->returnValue(['realKey' => []]));
- /** @var QueryCacheProfile|PHPUnit_Framework_MockObject_MockObject $queryCacheProfileMock */
+ /** @var QueryCacheProfile|MockObject $queryCacheProfileMock */
$queryCacheProfileMock = $this->createMock(QueryCacheProfile::class);
$queryCacheProfileMock
@@ -869,10 +896,10 @@ public function testThrowsExceptionWhenInValidPlatformSpecified() : void
/**
* @group DBAL-990
*/
- public function testRethrowsOriginalExceptionOnDeterminingPlatformWhenConnectingToNonExistentDatabase()
+ public function testRethrowsOriginalExceptionOnDeterminingPlatformWhenConnectingToNonExistentDatabase() : void
{
- /** @var VersionAwarePlatformDriverMock|PHPUnit_Framework_MockObject_MockObject $driverMock */
- $driverMock = $this->createMock(VersionAwarePlatformDriverMock::class);
+ /** @var Driver|VersionAwarePlatformDriver|MockObject $driverMock */
+ $driverMock = $this->createMock([Driver::class, VersionAwarePlatformDriver::class]);
$connection = new Connection(['dbname' => 'foo'], $driverMock);
$originalException = new Exception('Original exception');
@@ -890,4 +917,55 @@ public function testRethrowsOriginalExceptionOnDeterminingPlatformWhenConnecting
$connection->getDatabasePlatform();
}
+
+ /**
+ * @group #3194
+ */
+ public function testExecuteCacheQueryStripsPlatformFromConnectionParamsBeforeGeneratingCacheKeys() : void
+ {
+ /** @var Driver|MockObject $driver */
+ $driver = $this->createMock(Driver::class);
+
+ /** @var AbstractPlatform|MockObject $platform */
+ $platform = $this->createMock(AbstractPlatform::class);
+
+ /** @var QueryCacheProfile|MockObject $queryCacheProfile */
+ $queryCacheProfile = $this->createMock(QueryCacheProfile::class);
+
+ /** @var Cache|MockObject $resultCacheDriver */
+ $resultCacheDriver = $this->createMock(Cache::class);
+
+ $queryCacheProfile
+ ->expects($this->any())
+ ->method('getResultCacheDriver')
+ ->will($this->returnValue($resultCacheDriver));
+
+ $resultCacheDriver
+ ->expects($this->atLeastOnce())
+ ->method('fetch')
+ ->with('cacheKey')
+ ->will($this->returnValue(['realKey' => []]));
+
+ $query = 'SELECT 1';
+
+ $params = [
+ 'dbname' => 'foo',
+ 'platform' => $platform,
+ ];
+
+ $paramsWithoutPlatform = $params;
+ unset($paramsWithoutPlatform['platform']);
+
+ $queryCacheProfile
+ ->expects($this->once())
+ ->method('generateCacheKeys')
+ ->with($query, [], [], $paramsWithoutPlatform)
+ ->will($this->returnValue(['cacheKey', 'realKey']));
+
+ $connection = new Connection($params, $driver);
+
+ self::assertSame($params, $connection->getParams());
+
+ $connection->executeCacheQuery($query, [], [], $queryCacheProfile);
+ }
}
diff --git a/tests/Doctrine/Tests/DBAL/DBALExceptionTest.php b/tests/Doctrine/Tests/DBAL/DBALExceptionTest.php
index 9c0cc18c0be..7db5921ba79 100644
--- a/tests/Doctrine/Tests/DBAL/DBALExceptionTest.php
+++ b/tests/Doctrine/Tests/DBAL/DBALExceptionTest.php
@@ -15,48 +15,36 @@
class DBALExceptionTest extends DbalTestCase
{
- public function testDriverExceptionDuringQueryAcceptsBinaryData()
+ public function testDriverExceptionDuringQueryAcceptsBinaryData() : void
{
/** @var Driver $driver */
$driver = $this->createMock(Driver::class);
$e = DBALException::driverExceptionDuringQuery($driver, new Exception(), '', ['ABC', chr(128)]);
- self::assertContains('with params ["ABC", "\x80"]', $e->getMessage());
+ self::assertStringContainsString('with params ["ABC", "\x80"]', $e->getMessage());
}
- public function testDriverExceptionDuringQueryAcceptsResource()
+ public function testDriverExceptionDuringQueryAcceptsResource() : void
{
/** @var Driver $driver */
$driver = $this->createMock(Driver::class);
$e = DBALException::driverExceptionDuringQuery($driver, new Exception(), 'INSERT INTO file (`content`) VALUES (?)', [1 => fopen(__FILE__, 'r')]);
- self::assertContains('Resource', $e->getMessage());
+ self::assertStringContainsString('Resource', $e->getMessage());
}
- public function testAvoidOverWrappingOnDriverException()
+ public function testAvoidOverWrappingOnDriverException() : void
{
/** @var Driver $driver */
$driver = $this->createMock(Driver::class);
- $inner = new class extends Exception implements InnerDriverException
- {
- /**
- * {@inheritDoc}
- */
- public function getErrorCode()
- {
- }
- /**
- * {@inheritDoc}
- */
- public function getSQLState()
- {
- }
- };
- $ex = new DriverException('', $inner);
- $e = DBALException::driverExceptionDuringQuery($driver, $ex, '');
+ /** @var InnerDriverException $inner */
+ $inner = $this->createMock(InnerDriverException::class);
+
+ $ex = new DriverException('', $inner);
+ $e = DBALException::driverExceptionDuringQuery($driver, $ex, '');
self::assertSame($ex, $e);
}
- public function testDriverRequiredWithUrl()
+ public function testDriverRequiredWithUrl() : void
{
$url = 'mysql://localhost';
$exception = DBALException::driverRequired($url);
diff --git a/tests/Doctrine/Tests/DBAL/Driver/AbstractDB2DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/AbstractDB2DriverTest.php
index e6a54060c71..7038f5f8340 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/AbstractDB2DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/AbstractDB2DriverTest.php
@@ -3,23 +3,26 @@
namespace Doctrine\Tests\DBAL\Driver;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\AbstractDB2Driver;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\DB2Platform;
+use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\DB2SchemaManager;
class AbstractDB2DriverTest extends AbstractDriverTest
{
- protected function createDriver()
+ protected function createDriver() : Driver
{
return $this->getMockForAbstractClass(AbstractDB2Driver::class);
}
- protected function createPlatform()
+ protected function createPlatform() : AbstractPlatform
{
return new DB2Platform();
}
- protected function createSchemaManager(Connection $connection)
+ protected function createSchemaManager(Connection $connection) : AbstractSchemaManager
{
return new DB2SchemaManager($connection);
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/AbstractDriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/AbstractDriverTest.php
index 0475ea11b89..d2a5422a179 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/AbstractDriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/AbstractDriverTest.php
@@ -3,6 +3,7 @@
namespace Doctrine\Tests\DBAL\Driver;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\DriverException as DriverExceptionInterface;
use Doctrine\DBAL\Driver\ExceptionConverterDriver;
@@ -27,7 +28,9 @@
use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\VersionAwarePlatformDriver;
use Doctrine\Tests\DbalTestCase;
-use Exception;
+use PHPUnit\Framework\MockObject\MockObject;
+use ReflectionProperty;
+use function array_merge;
use function get_class;
use function sprintf;
@@ -58,74 +61,45 @@ abstract class AbstractDriverTest extends DbalTestCase
*/
protected $driver;
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
$this->driver = $this->createDriver();
}
- public function testConvertsException()
+ /**
+ * @param int|string $errorCode
+ *
+ * @dataProvider exceptionConversionProvider
+ */
+ public function testConvertsException($errorCode, ?string $sqlState, ?string $message, string $expectedClass) : void
{
if (! $this->driver instanceof ExceptionConverterDriver) {
$this->markTestSkipped('This test is only intended for exception converter drivers.');
}
- $data = $this->getExceptionConversions();
-
- if (empty($data)) {
- $this->fail(
- sprintf(
- 'No test data found for test %s. You have to return test data from %s.',
- static::class . '::' . __FUNCTION__,
- static::class . '::getExceptionConversionData'
- )
- );
- }
-
- $driverException = new class extends Exception implements DriverExceptionInterface
- {
- public function __construct()
- {
- parent::__construct('baz');
- }
-
- /**
- * {@inheritDoc}
- */
- public function getErrorCode()
- {
- return 'foo';
- }
-
- /**
- * {@inheritDoc}
- */
- public function getSQLState()
- {
- return 'bar';
- }
- };
-
- $data[] = [$driverException, self::EXCEPTION_DRIVER];
-
- $message = 'DBAL exception message';
-
- foreach ($data as $item) {
- /** @var $driverException \Doctrine\DBAL\Driver\DriverException */
- [$driverException, $convertedExceptionClassName] = $item;
+ /** @var DriverExceptionInterface|MockObject $driverException */
+ $driverException = $this->getMockBuilder(DriverExceptionInterface::class)
+ ->setConstructorArgs([$message])
+ ->getMock();
+ $driverException->method('getErrorCode')
+ ->willReturn($errorCode);
+ $driverException->method('getSQLState')
+ ->willReturn($sqlState);
- $convertedException = $this->driver->convertException($message, $driverException);
+ $dbalMessage = 'DBAL exception message';
+ $dbalException = $this->driver->convertException($dbalMessage, $driverException);
- self::assertSame($convertedExceptionClassName, get_class($convertedException));
+ self::assertInstanceOf($expectedClass, $dbalException);
- self::assertSame($driverException->getErrorCode(), $convertedException->getErrorCode());
- self::assertSame($driverException->getSQLState(), $convertedException->getSQLState());
- self::assertSame($message, $convertedException->getMessage());
- }
+ self::assertSame($driverException->getErrorCode(), $dbalException->getErrorCode());
+ self::assertSame($driverException->getSQLState(), $dbalException->getSQLState());
+ self::assertSame($driverException, $dbalException->getPrevious());
+ self::assertSame($dbalMessage, $dbalException->getMessage());
}
- public function testCreatesDatabasePlatformForVersion()
+ public function testCreatesDatabasePlatformForVersion() : void
{
if (! $this->driver instanceof VersionAwarePlatformDriver) {
$this->markTestSkipped('This test is only intended for version aware platform drivers.');
@@ -158,19 +132,17 @@ public function testCreatesDatabasePlatformForVersion()
}
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testThrowsExceptionOnCreatingDatabasePlatformsForInvalidVersion()
+ public function testThrowsExceptionOnCreatingDatabasePlatformsForInvalidVersion() : void
{
if (! $this->driver instanceof VersionAwarePlatformDriver) {
$this->markTestSkipped('This test is only intended for version aware platform drivers.');
}
+ $this->expectException(DBALException::class);
$this->driver->createDatabasePlatformForVersion('foo');
}
- public function testReturnsDatabaseName()
+ public function testReturnsDatabaseName() : void
{
$params = [
'user' => 'foo',
@@ -187,36 +159,36 @@ public function testReturnsDatabaseName()
self::assertSame($params['dbname'], $this->driver->getDatabase($connection));
}
- public function testReturnsDatabasePlatform()
+ public function testReturnsDatabasePlatform() : void
{
self::assertEquals($this->createPlatform(), $this->driver->getDatabasePlatform());
}
- public function testReturnsSchemaManager()
+ public function testReturnsSchemaManager() : void
{
$connection = $this->getConnectionMock();
$schemaManager = $this->driver->getSchemaManager($connection);
self::assertEquals($this->createSchemaManager($connection), $schemaManager);
- self::assertAttributeSame($connection, '_conn', $schemaManager);
+
+ $re = new ReflectionProperty($schemaManager, '_conn');
+ $re->setAccessible(true);
+
+ self::assertSame($connection, $re->getValue($schemaManager));
}
/**
* Factory method for creating the driver instance under test.
- *
- * @return Driver
*/
- abstract protected function createDriver();
+ abstract protected function createDriver() : Driver;
/**
* Factory method for creating the the platform instance return by the driver under test.
*
* The platform instance returned by this method must be the same as returned by
* the driver's getDatabasePlatform() method.
- *
- * @return AbstractPlatform
*/
- abstract protected function createPlatform();
+ abstract protected function createPlatform() : AbstractPlatform;
/**
* Factory method for creating the the schema manager instance return by the driver under test.
@@ -225,73 +197,43 @@ abstract protected function createPlatform();
* the driver's getSchemaManager() method.
*
* @param Connection $connection The underlying connection to use.
- *
- * @return AbstractSchemaManager
*/
- abstract protected function createSchemaManager(Connection $connection);
+ abstract protected function createSchemaManager(Connection $connection) : AbstractSchemaManager;
- protected function getConnectionMock()
+ protected function getConnectionMock() : Connection
{
return $this->getMockBuilder(Connection::class)
->disableOriginalConstructor()
->getMock();
}
- protected function getDatabasePlatformsForVersions()
- {
- return [];
- }
-
- protected function getExceptionConversionData()
+ /**
+ * @return array>
+ */
+ protected function getDatabasePlatformsForVersions() : array
{
return [];
}
- private function getExceptionConversions()
+ /**
+ * @return mixed[][]
+ */
+ public static function exceptionConversionProvider() : iterable
{
- $data = [];
-
- foreach ($this->getExceptionConversionData() as $convertedExceptionClassName => $errors) {
- foreach ($errors as $error) {
- $driverException = new class ($error[0], $error[1], $error[2])
- extends Exception
- implements DriverExceptionInterface
- {
- /** @var mixed */
- private $errorCode;
-
- /** @var mixed */
- private $sqlState;
-
- public function __construct($errorCode, $sqlState, $message)
- {
- parent::__construct($message);
-
- $this->errorCode = $errorCode;
- $this->sqlState = $sqlState;
- }
-
- /**
- * {@inheritDoc}
- */
- public function getErrorCode()
- {
- return $this->errorCode;
- }
-
- /**
- * {@inheritDoc}
- */
- public function getSQLState()
- {
- return $this->sqlState;
- }
- };
-
- $data[] = [$driverException, $convertedExceptionClassName];
+ foreach (static::getExceptionConversionData() as $expectedClass => $items) {
+ foreach ($items as $item) {
+ yield array_merge($item, [$expectedClass]);
}
}
- return $data;
+ yield ['foo', 'bar', 'baz', self::EXCEPTION_DRIVER];
+ }
+
+ /**
+ * @return array
+ */
+ protected static function getExceptionConversionData() : array
+ {
+ return [];
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/AbstractMySQLDriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/AbstractMySQLDriverTest.php
index cde381653a9..4982a189e05 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/AbstractMySQLDriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/AbstractMySQLDriverTest.php
@@ -3,17 +3,20 @@
namespace Doctrine\Tests\DBAL\Driver;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\AbstractMySQLDriver;
+use Doctrine\DBAL\Driver\ResultStatement;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
use Doctrine\DBAL\Platforms\MySQL57Platform;
use Doctrine\DBAL\Platforms\MySQL80Platform;
use Doctrine\DBAL\Platforms\MySqlPlatform;
+use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\MySqlSchemaManager;
-use Doctrine\Tests\Mocks\DriverResultStatementMock;
class AbstractMySQLDriverTest extends AbstractDriverTest
{
- public function testReturnsDatabaseName()
+ public function testReturnsDatabaseName() : void
{
parent::testReturnsDatabaseName();
@@ -23,7 +26,7 @@ public function testReturnsDatabaseName()
'password' => 'bar',
];
- $statement = $this->createMock(DriverResultStatementMock::class);
+ $statement = $this->createMock(ResultStatement::class);
$statement->expects($this->once())
->method('fetchColumn')
@@ -42,23 +45,23 @@ public function testReturnsDatabaseName()
self::assertSame($database, $this->driver->getDatabase($connection));
}
- protected function createDriver()
+ protected function createDriver() : Driver
{
return $this->getMockForAbstractClass(AbstractMySQLDriver::class);
}
- protected function createPlatform()
+ protected function createPlatform() : AbstractPlatform
{
return new MySqlPlatform();
}
- protected function createSchemaManager(Connection $connection)
+ protected function createSchemaManager(Connection $connection) : AbstractSchemaManager
{
return new MySqlSchemaManager($connection);
}
/**
- * @return mixed[][]
+ * {@inheritDoc}
*/
protected function getDatabasePlatformsForVersions() : array
{
@@ -83,7 +86,10 @@ protected function getDatabasePlatformsForVersions() : array
];
}
- protected function getExceptionConversionData()
+ /**
+ * {@inheritDoc}
+ */
+ protected static function getExceptionConversionData() : array
{
return [
self::EXCEPTION_CONNECTION => [
diff --git a/tests/Doctrine/Tests/DBAL/Driver/AbstractOracleDriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/AbstractOracleDriverTest.php
index d88040e10a7..f95705a8a88 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/AbstractOracleDriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/AbstractOracleDriverTest.php
@@ -3,13 +3,16 @@
namespace Doctrine\Tests\DBAL\Driver;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\AbstractOracleDriver;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\OraclePlatform;
+use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\OracleSchemaManager;
class AbstractOracleDriverTest extends AbstractDriverTest
{
- public function testReturnsDatabaseName()
+ public function testReturnsDatabaseName() : void
{
$params = [
'user' => 'foo',
@@ -26,7 +29,7 @@ public function testReturnsDatabaseName()
self::assertSame($params['user'], $this->driver->getDatabase($connection));
}
- public function testReturnsDatabaseNameWithConnectDescriptor()
+ public function testReturnsDatabaseNameWithConnectDescriptor() : void
{
$params = [
'user' => 'foo',
@@ -45,22 +48,25 @@ public function testReturnsDatabaseNameWithConnectDescriptor()
self::assertSame($params['user'], $this->driver->getDatabase($connection));
}
- protected function createDriver()
+ protected function createDriver() : Driver
{
return $this->getMockForAbstractClass(AbstractOracleDriver::class);
}
- protected function createPlatform()
+ protected function createPlatform() : AbstractPlatform
{
return new OraclePlatform();
}
- protected function createSchemaManager(Connection $connection)
+ protected function createSchemaManager(Connection $connection) : AbstractSchemaManager
{
return new OracleSchemaManager($connection);
}
- protected function getExceptionConversionData()
+ /**
+ * {@inheritDoc}
+ */
+ protected static function getExceptionConversionData() : array
{
return [
self::EXCEPTION_CONNECTION => [
diff --git a/tests/Doctrine/Tests/DBAL/Driver/AbstractPostgreSQLDriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/AbstractPostgreSQLDriverTest.php
index d1159c80308..2ba6a732bd4 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/AbstractPostgreSQLDriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/AbstractPostgreSQLDriverTest.php
@@ -3,18 +3,21 @@
namespace Doctrine\Tests\DBAL\Driver;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\AbstractPostgreSQLDriver;
+use Doctrine\DBAL\Driver\ResultStatement;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\PostgreSQL100Platform;
use Doctrine\DBAL\Platforms\PostgreSQL91Platform;
use Doctrine\DBAL\Platforms\PostgreSQL92Platform;
use Doctrine\DBAL\Platforms\PostgreSQL94Platform;
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
+use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\PostgreSqlSchemaManager;
-use Doctrine\Tests\Mocks\DriverResultStatementMock;
class AbstractPostgreSQLDriverTest extends AbstractDriverTest
{
- public function testReturnsDatabaseName()
+ public function testReturnsDatabaseName() : void
{
parent::testReturnsDatabaseName();
@@ -24,7 +27,7 @@ public function testReturnsDatabaseName()
'password' => 'bar',
];
- $statement = $this->createMock(DriverResultStatementMock::class);
+ $statement = $this->createMock(ResultStatement::class);
$statement->expects($this->once())
->method('fetchColumn')
@@ -43,22 +46,25 @@ public function testReturnsDatabaseName()
self::assertSame($database, $this->driver->getDatabase($connection));
}
- protected function createDriver()
+ protected function createDriver() : Driver
{
return $this->getMockForAbstractClass(AbstractPostgreSQLDriver::class);
}
- protected function createPlatform()
+ protected function createPlatform() : AbstractPlatform
{
return new PostgreSqlPlatform();
}
- protected function createSchemaManager(Connection $connection)
+ protected function createSchemaManager(Connection $connection) : AbstractSchemaManager
{
return new PostgreSqlSchemaManager($connection);
}
- protected function getDatabasePlatformsForVersions()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getDatabasePlatformsForVersions() : array
{
return [
['9.0.9', PostgreSqlPlatform::class],
@@ -77,7 +83,10 @@ protected function getDatabasePlatformsForVersions()
];
}
- protected function getExceptionConversionData()
+ /**
+ * {@inheritDoc}
+ */
+ protected static function getExceptionConversionData() : array
{
return [
self::EXCEPTION_CONNECTION => [
diff --git a/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLAnywhereDriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLAnywhereDriverTest.php
index cbd23505bae..4c51e7cb35f 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLAnywhereDriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLAnywhereDriverTest.php
@@ -3,31 +3,37 @@
namespace Doctrine\Tests\DBAL\Driver;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\AbstractSQLAnywhereDriver;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SQLAnywhere11Platform;
use Doctrine\DBAL\Platforms\SQLAnywhere12Platform;
use Doctrine\DBAL\Platforms\SQLAnywhere16Platform;
use Doctrine\DBAL\Platforms\SQLAnywherePlatform;
+use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\SQLAnywhereSchemaManager;
class AbstractSQLAnywhereDriverTest extends AbstractDriverTest
{
- protected function createDriver()
+ protected function createDriver() : Driver
{
return $this->getMockForAbstractClass(AbstractSQLAnywhereDriver::class);
}
- protected function createPlatform()
+ protected function createPlatform() : AbstractPlatform
{
return new SQLAnywhere12Platform();
}
- protected function createSchemaManager(Connection $connection)
+ protected function createSchemaManager(Connection $connection) : AbstractSchemaManager
{
return new SQLAnywhereSchemaManager($connection);
}
- protected function getDatabasePlatformsForVersions()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getDatabasePlatformsForVersions() : array
{
return [
['10', SQLAnywherePlatform::class],
@@ -62,7 +68,10 @@ protected function getDatabasePlatformsForVersions()
];
}
- protected function getExceptionConversionData()
+ /**
+ * {@inheritDoc}
+ */
+ protected static function getExceptionConversionData() : array
{
return [
self::EXCEPTION_CONNECTION => [
diff --git a/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLServerDriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLServerDriverTest.php
index 48fb3b29f3e..0d34df8e81b 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLServerDriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLServerDriverTest.php
@@ -3,31 +3,37 @@
namespace Doctrine\Tests\DBAL\Driver;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\AbstractSQLServerDriver;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SQLServer2005Platform;
use Doctrine\DBAL\Platforms\SQLServer2008Platform;
use Doctrine\DBAL\Platforms\SQLServer2012Platform;
use Doctrine\DBAL\Platforms\SQLServerPlatform;
+use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\SQLServerSchemaManager;
class AbstractSQLServerDriverTest extends AbstractDriverTest
{
- protected function createDriver()
+ protected function createDriver() : Driver
{
return $this->getMockForAbstractClass(AbstractSQLServerDriver::class);
}
- protected function createPlatform()
+ protected function createPlatform() : AbstractPlatform
{
return new SQLServer2008Platform();
}
- protected function createSchemaManager(Connection $connection)
+ protected function createSchemaManager(Connection $connection) : AbstractSchemaManager
{
return new SQLServerSchemaManager($connection);
}
- protected function getDatabasePlatformsForVersions()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getDatabasePlatformsForVersions() : array
{
return [
['9', SQLServerPlatform::class],
diff --git a/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLiteDriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLiteDriverTest.php
index d92aa5d0d8d..338f9126077 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLiteDriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/AbstractSQLiteDriverTest.php
@@ -3,13 +3,16 @@
namespace Doctrine\Tests\DBAL\Driver;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\AbstractSQLiteDriver;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
+use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\SqliteSchemaManager;
class AbstractSQLiteDriverTest extends AbstractDriverTest
{
- public function testReturnsDatabaseName()
+ public function testReturnsDatabaseName() : void
{
$params = [
'user' => 'foo',
@@ -27,22 +30,25 @@ public function testReturnsDatabaseName()
self::assertSame($params['path'], $this->driver->getDatabase($connection));
}
- protected function createDriver()
+ protected function createDriver() : Driver
{
return $this->getMockForAbstractClass(AbstractSQLiteDriver::class);
}
- protected function createPlatform()
+ protected function createPlatform() : AbstractPlatform
{
return new SqlitePlatform();
}
- protected function createSchemaManager(Connection $connection)
+ protected function createSchemaManager(Connection $connection) : AbstractSchemaManager
{
return new SqliteSchemaManager($connection);
}
- protected function getExceptionConversionData()
+ /**
+ * {@inheritDoc}
+ */
+ protected static function getExceptionConversionData() : array
{
return [
self::EXCEPTION_CONNECTION => [
diff --git a/tests/Doctrine/Tests/DBAL/Driver/DrizzlePDOMySql/DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/DrizzlePDOMySql/DriverTest.php
index 520a732a0c3..5af24b8454a 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/DrizzlePDOMySql/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/DrizzlePDOMySql/DriverTest.php
@@ -3,34 +3,37 @@
namespace Doctrine\Tests\DBAL\Driver\DrizzlePDOMySql;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\DrizzlePDOMySql\Driver;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\DrizzlePlatform;
+use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\DrizzleSchemaManager;
use Doctrine\Tests\DBAL\Driver\PDOMySql\DriverTest as PDOMySQLDriverTest;
class DriverTest extends PDOMySQLDriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('drizzle_pdo_mysql', $this->driver->getName());
}
- public function testThrowsExceptionOnCreatingDatabasePlatformsForInvalidVersion()
+ public function testThrowsExceptionOnCreatingDatabasePlatformsForInvalidVersion() : void
{
$this->markTestSkipped('This test does not work on Drizzle as it is not version aware.');
}
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
- protected function createPlatform()
+ protected function createPlatform() : AbstractPlatform
{
return new DrizzlePlatform();
}
- protected function createSchemaManager(Connection $connection)
+ protected function createSchemaManager(Connection $connection) : AbstractSchemaManager
{
return new DrizzleSchemaManager($connection);
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/IBMDB2/DB2ConnectionTest.php b/tests/Doctrine/Tests/DBAL/Driver/IBMDB2/DB2ConnectionTest.php
index a60772295a6..cf2db940b33 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/IBMDB2/DB2ConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/IBMDB2/DB2ConnectionTest.php
@@ -4,7 +4,7 @@
use Doctrine\DBAL\Driver\IBMDB2\DB2Connection;
use Doctrine\Tests\DbalTestCase;
-use PHPUnit_Framework_MockObject_MockObject;
+use PHPUnit\Framework\MockObject\MockObject;
use function extension_loaded;
class DB2ConnectionTest extends DbalTestCase
@@ -12,11 +12,11 @@ class DB2ConnectionTest extends DbalTestCase
/**
* The ibm_db2 driver connection mock under test.
*
- * @var DB2Connection|PHPUnit_Framework_MockObject_MockObject
+ * @var DB2Connection|MockObject
*/
private $connectionMock;
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('ibm_db2')) {
$this->markTestSkipped('ibm_db2 is not installed.');
@@ -29,7 +29,7 @@ protected function setUp()
->getMockForAbstractClass();
}
- public function testDoesNotRequireQueryForServerVersion()
+ public function testDoesNotRequireQueryForServerVersion() : void
{
self::assertFalse($this->connectionMock->requiresQueryForServerVersion());
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/IBMDB2/DB2DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/IBMDB2/DB2DriverTest.php
index 93f390b628a..dcf9f6083e3 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/IBMDB2/DB2DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/IBMDB2/DB2DriverTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Driver\IBMDB2;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\IBMDB2\DB2Driver;
use Doctrine\Tests\DBAL\Driver\AbstractDB2DriverTest;
class DB2DriverTest extends AbstractDB2DriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('ibm_db2', $this->driver->getName());
}
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new DB2Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/Mysqli/DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/Mysqli/DriverTest.php
index f38ff8a5529..bbe16b34717 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/Mysqli/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/Mysqli/DriverTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Driver\Mysqli;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\Mysqli\Driver;
use Doctrine\Tests\DBAL\Driver\AbstractMySQLDriverTest;
class DriverTest extends AbstractMySQLDriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('mysqli', $this->driver->getName());
}
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/Mysqli/MysqliConnectionTest.php b/tests/Doctrine/Tests/DBAL/Driver/Mysqli/MysqliConnectionTest.php
index 9bd3172dd1d..37a5ab1a32f 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/Mysqli/MysqliConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/Mysqli/MysqliConnectionTest.php
@@ -6,7 +6,7 @@
use Doctrine\DBAL\Driver\Mysqli\MysqliException;
use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\Tests\DbalFunctionalTestCase;
-use PHPUnit_Framework_MockObject_MockObject;
+use PHPUnit\Framework\MockObject\MockObject;
use function extension_loaded;
use function restore_error_handler;
use function set_error_handler;
@@ -16,11 +16,11 @@ class MysqliConnectionTest extends DbalFunctionalTestCase
/**
* The mysqli driver connection mock under test.
*
- * @var MysqliConnection|PHPUnit_Framework_MockObject_MockObject
+ * @var MysqliConnection|MockObject
*/
private $connectionMock;
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('mysqli')) {
$this->markTestSkipped('mysqli is not installed.');
@@ -37,14 +37,14 @@ protected function setUp()
->getMockForAbstractClass();
}
- public function testDoesNotRequireQueryForServerVersion()
+ public function testDoesNotRequireQueryForServerVersion() : void
{
self::assertFalse($this->connectionMock->requiresQueryForServerVersion());
}
- public function testRestoresErrorHandlerOnException()
+ public function testRestoresErrorHandlerOnException() : void
{
- $handler = static function () {
+ $handler = static function () : bool {
self::fail('Never expected this to be called');
};
$default_handler = set_error_handler($handler);
diff --git a/tests/Doctrine/Tests/DBAL/Driver/OCI8/DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/OCI8/DriverTest.php
index 77e763a66bb..7b6ed1d5a55 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/OCI8/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/OCI8/DriverTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Driver\OCI8;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\OCI8\Driver;
use Doctrine\Tests\DBAL\Driver\AbstractOracleDriverTest;
class DriverTest extends AbstractOracleDriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('oci8', $this->driver->getName());
}
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/OCI8/OCI8ConnectionTest.php b/tests/Doctrine/Tests/DBAL/Driver/OCI8/OCI8ConnectionTest.php
index 0628738400e..4c3868f4a95 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/OCI8/OCI8ConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/OCI8/OCI8ConnectionTest.php
@@ -4,7 +4,7 @@
use Doctrine\DBAL\Driver\OCI8\OCI8Connection;
use Doctrine\Tests\DbalTestCase;
-use PHPUnit_Framework_MockObject_MockObject;
+use PHPUnit\Framework\MockObject\MockObject;
use function extension_loaded;
class OCI8ConnectionTest extends DbalTestCase
@@ -12,11 +12,11 @@ class OCI8ConnectionTest extends DbalTestCase
/**
* The oci8 driver connection mock under test.
*
- * @var OCI8Connection|PHPUnit_Framework_MockObject_MockObject
+ * @var OCI8Connection|MockObject
*/
private $connectionMock;
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('oci8')) {
$this->markTestSkipped('oci8 is not installed.');
@@ -29,7 +29,7 @@ protected function setUp()
->getMockForAbstractClass();
}
- public function testDoesNotRequireQueryForServerVersion()
+ public function testDoesNotRequireQueryForServerVersion() : void
{
self::assertFalse($this->connectionMock->requiresQueryForServerVersion());
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/OCI8/OCI8StatementTest.php b/tests/Doctrine/Tests/DBAL/Driver/OCI8/OCI8StatementTest.php
index d6e73f57412..f90f86d6eb3 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/OCI8/OCI8StatementTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/OCI8/OCI8StatementTest.php
@@ -11,7 +11,7 @@
class OCI8StatementTest extends DbalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('oci8')) {
$this->markTestSkipped('oci8 is not installed.');
@@ -32,12 +32,11 @@ protected function setUp()
* @param mixed[] $params
*
* @dataProvider executeDataProvider
- * @expectedException \Doctrine\DBAL\Driver\OCI8\OCI8Exception
*/
- public function testExecute(array $params)
+ public function testExecute(array $params) : void
{
$statement = $this->getMockBuilder(OCI8Statement::class)
- ->setMethods(['bindValue', 'errorInfo'])
+ ->onlyMethods(['bindValue', 'errorInfo'])
->disableOriginalConstructor()
->getMock();
@@ -68,7 +67,7 @@ public function testExecute(array $params)
// can't pass to constructor since we don't have a real database handle,
// but execute must check the connection for the executeMode
$conn = $this->getMockBuilder(OCI8Connection::class)
- ->setMethods(['getExecuteMode'])
+ ->onlyMethods(['getExecuteMode'])
->disableOriginalConstructor()
->getMock();
$conn->expects($this->once())
@@ -78,10 +77,14 @@ public function testExecute(array $params)
$reflProperty->setAccessible(true);
$reflProperty->setValue($statement, $conn);
+ $this->expectException(OCI8Exception::class);
$statement->execute($params);
}
- public static function executeDataProvider()
+ /**
+ * @return array>
+ */
+ public static function executeDataProvider() : iterable
{
return [
// $hasZeroIndex = isset($params[0]); == true
@@ -98,14 +101,17 @@ public static function executeDataProvider()
/**
* @dataProvider nonTerminatedLiteralProvider
*/
- public function testConvertNonTerminatedLiteral($sql, $message)
+ public function testConvertNonTerminatedLiteral(string $sql, string $message) : void
{
$this->expectException(OCI8Exception::class);
$this->expectExceptionMessageRegExp($message);
OCI8Statement::convertPositionalToNamedPlaceholders($sql);
}
- public static function nonTerminatedLiteralProvider()
+ /**
+ * @return array>
+ */
+ public static function nonTerminatedLiteralProvider() : iterable
{
return [
'no-matching-quote' => [
diff --git a/tests/Doctrine/Tests/DBAL/Driver/PDOExceptionTest.php b/tests/Doctrine/Tests/DBAL/Driver/PDOExceptionTest.php
index 593f04d203c..9ed9a06aa5b 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/PDOExceptionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/PDOExceptionTest.php
@@ -4,7 +4,7 @@
use Doctrine\DBAL\Driver\PDOException;
use Doctrine\Tests\DbalTestCase;
-use PHPUnit_Framework_MockObject_MockObject;
+use PHPUnit\Framework\MockObject\MockObject;
use function extension_loaded;
class PDOExceptionTest extends DbalTestCase
@@ -25,11 +25,11 @@ class PDOExceptionTest extends DbalTestCase
/**
* The wrapped PDO exception mock.
*
- * @var \PDOException|PHPUnit_Framework_MockObject_MockObject
+ * @var \PDOException|MockObject
*/
private $wrappedException;
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('PDO')) {
$this->markTestSkipped('PDO is not installed.');
@@ -44,27 +44,27 @@ protected function setUp()
$this->exception = new PDOException($this->wrappedException);
}
- public function testReturnsCode()
+ public function testReturnsCode() : void
{
self::assertSame(self::SQLSTATE, $this->exception->getCode());
}
- public function testReturnsErrorCode()
+ public function testReturnsErrorCode() : void
{
self::assertSame(self::ERROR_CODE, $this->exception->getErrorCode());
}
- public function testReturnsMessage()
+ public function testReturnsMessage() : void
{
self::assertSame(self::MESSAGE, $this->exception->getMessage());
}
- public function testReturnsSQLState()
+ public function testReturnsSQLState() : void
{
self::assertSame(self::SQLSTATE, $this->exception->getSQLState());
}
- public function testOriginalExceptionIsInChain()
+ public function testOriginalExceptionIsInChain() : void
{
self::assertSame($this->wrappedException, $this->exception->getPrevious());
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/PDOIbm/DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/PDOIbm/DriverTest.php
index 6361f05575c..9eeeafb78aa 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/PDOIbm/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/PDOIbm/DriverTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Driver\PDOIbm;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\PDOIbm\Driver;
use Doctrine\Tests\DBAL\Driver\AbstractDB2DriverTest;
class DriverTest extends AbstractDB2DriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('pdo_ibm', $this->driver->getName());
}
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/PDOMySql/DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/PDOMySql/DriverTest.php
index a965765780d..6e3ef7d5a03 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/PDOMySql/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/PDOMySql/DriverTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Driver\PDOMySql;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\PDOMySql\Driver;
use Doctrine\Tests\DBAL\Driver\AbstractMySQLDriverTest;
class DriverTest extends AbstractMySQLDriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('pdo_mysql', $this->driver->getName());
}
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/PDOOracle/DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/PDOOracle/DriverTest.php
index f9e0da70f1c..42353be376d 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/PDOOracle/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/PDOOracle/DriverTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Driver\PDOOracle;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\PDOOracle\Driver;
use Doctrine\Tests\DBAL\Driver\AbstractOracleDriverTest;
class DriverTest extends AbstractOracleDriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('pdo_oracle', $this->driver->getName());
}
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/PDOPgSql/DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/PDOPgSql/DriverTest.php
index a6ac2456b64..2b976233c27 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/PDOPgSql/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/PDOPgSql/DriverTest.php
@@ -2,17 +2,17 @@
namespace Doctrine\Tests\DBAL\Driver\PDOPgSql;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\PDOConnection;
use Doctrine\DBAL\Driver\PDOPgSql\Driver;
use Doctrine\Tests\DBAL\Driver\AbstractPostgreSQLDriverTest;
use PDO;
use PDOException;
-use PHPUnit_Framework_SkippedTestError;
use function defined;
class DriverTest extends AbstractPostgreSQLDriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('pdo_pgsql', $this->driver->getName());
}
@@ -20,7 +20,7 @@ public function testReturnsName()
/**
* @group DBAL-920
*/
- public function testConnectionDisablesPreparesOnPhp56()
+ public function testConnectionDisablesPreparesOnPhp56() : void
{
$this->skipWhenNotUsingPhp56AndPdoPgsql();
@@ -46,7 +46,7 @@ public function testConnectionDisablesPreparesOnPhp56()
/**
* @group DBAL-920
*/
- public function testConnectionDoesNotDisablePreparesOnPhp56WhenAttributeDefined()
+ public function testConnectionDoesNotDisablePreparesOnPhp56WhenAttributeDefined() : void
{
$this->skipWhenNotUsingPhp56AndPdoPgsql();
@@ -73,7 +73,7 @@ public function testConnectionDoesNotDisablePreparesOnPhp56WhenAttributeDefined(
/**
* @group DBAL-920
*/
- public function testConnectionDisablePreparesOnPhp56WhenDisablePreparesIsExplicitlyDefined()
+ public function testConnectionDisablePreparesOnPhp56WhenDisablePreparesIsExplicitlyDefined() : void
{
$this->skipWhenNotUsingPhp56AndPdoPgsql();
@@ -100,15 +100,12 @@ public function testConnectionDisablePreparesOnPhp56WhenDisablePreparesIsExplici
/**
* {@inheritDoc}
*/
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
- /**
- * @throws PHPUnit_Framework_SkippedTestError
- */
- private function skipWhenNotUsingPhp56AndPdoPgsql()
+ private function skipWhenNotUsingPhp56AndPdoPgsql() : void
{
if (! defined('PDO::PGSQL_ATTR_DISABLE_PREPARES')) {
$this->markTestSkipped('Test requires PHP 5.6+');
diff --git a/tests/Doctrine/Tests/DBAL/Driver/PDOSqlite/DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/PDOSqlite/DriverTest.php
index 49a604ccd07..9092b091e3a 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/PDOSqlite/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/PDOSqlite/DriverTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Driver\PDOSqlite;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\PDOSqlite\Driver;
use Doctrine\Tests\DBAL\Driver\AbstractSQLiteDriverTest;
class DriverTest extends AbstractSQLiteDriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('pdo_sqlite', $this->driver->getName());
}
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/PDOSqlsrv/DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/PDOSqlsrv/DriverTest.php
index bf060365838..c92dc86d5ba 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/PDOSqlsrv/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/PDOSqlsrv/DriverTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Driver\PDOSqlsrv;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\PDOSqlsrv\Driver;
use Doctrine\Tests\DBAL\Driver\AbstractSQLServerDriverTest;
class DriverTest extends AbstractSQLServerDriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('pdo_sqlsrv', $this->driver->getName());
}
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/SQLAnywhere/DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/SQLAnywhere/DriverTest.php
index 54b1912a911..d6f1595a45e 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/SQLAnywhere/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/SQLAnywhere/DriverTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Driver\SQLAnywhere;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\SQLAnywhere\Driver;
use Doctrine\Tests\DBAL\Driver\AbstractSQLAnywhereDriverTest;
class DriverTest extends AbstractSQLAnywhereDriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('sqlanywhere', $this->driver->getName());
}
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/SQLAnywhere/SQLAnywhereConnectionTest.php b/tests/Doctrine/Tests/DBAL/Driver/SQLAnywhere/SQLAnywhereConnectionTest.php
index d70d36396ba..effeb483362 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/SQLAnywhere/SQLAnywhereConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/SQLAnywhere/SQLAnywhereConnectionTest.php
@@ -4,7 +4,7 @@
use Doctrine\DBAL\Driver\SQLAnywhere\SQLAnywhereConnection;
use Doctrine\Tests\DbalTestCase;
-use PHPUnit_Framework_MockObject_MockObject;
+use PHPUnit\Framework\MockObject\MockObject;
use function extension_loaded;
class SQLAnywhereConnectionTest extends DbalTestCase
@@ -12,11 +12,11 @@ class SQLAnywhereConnectionTest extends DbalTestCase
/**
* The sqlanywhere driver connection mock under test.
*
- * @var SQLAnywhereConnection|PHPUnit_Framework_MockObject_MockObject
+ * @var SQLAnywhereConnection|MockObject
*/
private $connectionMock;
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('sqlanywhere')) {
$this->markTestSkipped('sqlanywhere is not installed.');
@@ -29,7 +29,7 @@ protected function setUp()
->getMockForAbstractClass();
}
- public function testRequiresQueryForServerVersion()
+ public function testRequiresQueryForServerVersion() : void
{
self::assertTrue($this->connectionMock->requiresQueryForServerVersion());
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/SQLSrv/DriverTest.php b/tests/Doctrine/Tests/DBAL/Driver/SQLSrv/DriverTest.php
index b99516f7048..9ab6635ecf4 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/SQLSrv/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/SQLSrv/DriverTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Driver\SQLSrv;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\SQLSrv\Driver;
use Doctrine\Tests\DBAL\Driver\AbstractSQLServerDriverTest;
class DriverTest extends AbstractSQLServerDriverTest
{
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('sqlsrv', $this->driver->getName());
}
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Driver/SQLSrv/SQLSrvConnectionTest.php b/tests/Doctrine/Tests/DBAL/Driver/SQLSrv/SQLSrvConnectionTest.php
index b0e32708428..8d457d8eb23 100644
--- a/tests/Doctrine/Tests/DBAL/Driver/SQLSrv/SQLSrvConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Driver/SQLSrv/SQLSrvConnectionTest.php
@@ -4,7 +4,7 @@
use Doctrine\DBAL\Driver\SQLSrv\SQLSrvConnection;
use Doctrine\Tests\DbalTestCase;
-use PHPUnit_Framework_MockObject_MockObject;
+use PHPUnit\Framework\MockObject\MockObject;
use function extension_loaded;
class SQLSrvConnectionTest extends DbalTestCase
@@ -12,11 +12,11 @@ class SQLSrvConnectionTest extends DbalTestCase
/**
* The sqlsrv driver connection mock under test.
*
- * @var SQLSrvConnection|PHPUnit_Framework_MockObject_MockObject
+ * @var SQLSrvConnection|MockObject
*/
private $connectionMock;
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('sqlsrv')) {
$this->markTestSkipped('sqlsrv is not installed.');
@@ -29,7 +29,7 @@ protected function setUp()
->getMockForAbstractClass();
}
- public function testDoesNotRequireQueryForServerVersion()
+ public function testDoesNotRequireQueryForServerVersion() : void
{
self::assertFalse($this->connectionMock->requiresQueryForServerVersion());
}
diff --git a/tests/Doctrine/Tests/DBAL/DriverManagerTest.php b/tests/Doctrine/Tests/DBAL/DriverManagerTest.php
index e5520afcf1e..ced3e5d993f 100644
--- a/tests/Doctrine/Tests/DBAL/DriverManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/DriverManagerTest.php
@@ -2,22 +2,23 @@
namespace Doctrine\Tests\DBAL;
+use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Connections\MasterSlaveConnection;
use Doctrine\DBAL\DBALException;
+use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\DrizzlePDOMySql\Driver as DrizzlePDOMySqlDriver;
use Doctrine\DBAL\Driver\PDOMySql\Driver as PDOMySQLDriver;
use Doctrine\DBAL\Driver\PDOSqlite\Driver as PDOSqliteDriver;
use Doctrine\DBAL\Driver\SQLSrv\Driver as SQLSrvDriver;
use Doctrine\DBAL\DriverManager;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Sharding\PoolingShardConnection;
use Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
-use Doctrine\Tests\Mocks\ConnectionMock;
-use Doctrine\Tests\Mocks\DriverMock;
use PDO;
use stdClass;
use function extension_loaded;
+use function get_class;
use function in_array;
use function is_array;
@@ -25,17 +26,17 @@ class DriverManagerTest extends DbalTestCase
{
/**
* @requires extension pdo_sqlite
- * @expectedException \Doctrine\DBAL\DBALException
*/
- public function testInvalidPdoInstance()
+ public function testInvalidPdoInstance() : void
{
+ $this->expectException(DBALException::class);
DriverManager::getConnection(['pdo' => 'test']);
}
/**
* @requires extension pdo_sqlite
*/
- public function testValidPdoInstance()
+ public function testValidPdoInstance() : void
{
$conn = DriverManager::getConnection([
'pdo' => new PDO('sqlite::memory:'),
@@ -48,7 +49,7 @@ public function testValidPdoInstance()
* @group DBAL-32
* @requires extension pdo_sqlite
*/
- public function testPdoInstanceSetErrorMode()
+ public function testPdoInstanceSetErrorMode() : void
{
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
@@ -58,43 +59,42 @@ public function testPdoInstanceSetErrorMode()
self::assertEquals(PDO::ERRMODE_EXCEPTION, $pdo->getAttribute(PDO::ATTR_ERRMODE));
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testCheckParams()
+ public function testCheckParams() : void
{
+ $this->expectException(DBALException::class);
+
DriverManager::getConnection([]);
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testInvalidDriver()
+ public function testInvalidDriver() : void
{
+ $this->expectException(DBALException::class);
+
DriverManager::getConnection(['driver' => 'invalid_driver']);
}
/**
* @requires extension pdo_sqlite
*/
- public function testCustomPlatform()
+ public function testCustomPlatform() : void
{
- $mockPlatform = new MockPlatform();
- $options = [
+ $platform = $this->createMock(AbstractPlatform::class);
+ $options = [
'pdo' => new PDO('sqlite::memory:'),
- 'platform' => $mockPlatform,
+ 'platform' => $platform,
];
$conn = DriverManager::getConnection($options);
- self::assertSame($mockPlatform, $conn->getDatabasePlatform());
+ self::assertSame($platform, $conn->getDatabasePlatform());
}
/**
* @requires extension pdo_sqlite
*/
- public function testCustomWrapper()
+ public function testCustomWrapper() : void
{
- $wrapperClass = ConnectionMock::class;
+ $wrapper = $this->createMock(Connection::class);
+ $wrapperClass = get_class($wrapper);
$options = [
'pdo' => new PDO('sqlite::memory:'),
@@ -108,7 +108,7 @@ public function testCustomWrapper()
/**
* @requires extension pdo_sqlite
*/
- public function testInvalidWrapperClass()
+ public function testInvalidWrapperClass() : void
{
$this->expectException(DBALException::class);
@@ -120,7 +120,7 @@ public function testInvalidWrapperClass()
DriverManager::getConnection($options);
}
- public function testInvalidDriverClass()
+ public function testInvalidDriverClass() : void
{
$this->expectException(DBALException::class);
@@ -129,7 +129,7 @@ public function testInvalidDriverClass()
DriverManager::getConnection($options);
}
- public function testValidDriverClass()
+ public function testValidDriverClass() : void
{
$options = ['driverClass' => PDOMySQLDriver::class];
@@ -137,7 +137,7 @@ public function testValidDriverClass()
self::assertInstanceOf(PDOMySQLDriver::class, $conn->getDriver());
}
- public function testDatabaseUrlMasterSlave()
+ public function testDatabaseUrlMasterSlave() : void
{
$options = [
'driver' => 'pdo_mysql',
@@ -169,7 +169,7 @@ public function testDatabaseUrlMasterSlave()
self::assertEquals('baz_slave', $params['slaves']['slave1']['dbname']);
}
- public function testDatabaseUrlShard()
+ public function testDatabaseUrlShard() : void
{
$options = [
'driver' => 'pdo_mysql',
@@ -206,9 +206,12 @@ public function testDatabaseUrlShard()
}
/**
+ * @param mixed $url
+ * @param mixed $expected
+ *
* @dataProvider databaseUrls
*/
- public function testDatabaseUrl($url, $expected)
+ public function testDatabaseUrl($url, $expected) : void
{
$options = is_array($url) ? $url : ['url' => $url];
@@ -238,8 +241,14 @@ public function testDatabaseUrl($url, $expected)
}
}
- public function databaseUrls()
+ /**
+ * @return array>
+ */
+ public function databaseUrls() : iterable
{
+ $driver = $this->createMock(Driver::class);
+ $driverClass = get_class($driver);
+
return [
'simple URL' => [
'mysql://foo:bar@localhost/baz',
@@ -408,14 +417,14 @@ public function databaseUrls()
'URL without scheme but custom driver' => [
[
'url' => '//foo:bar@localhost/baz',
- 'driverClass' => DriverMock::class,
+ 'driverClass' => $driverClass,
],
[
'user' => 'foo',
'password' => 'bar',
'host' => 'localhost',
'dbname' => 'baz',
- 'driverClass' => DriverMock::class,
+ 'driverClass' => $driverClass,
],
],
'URL without scheme but default PDO driver and default driver' => [
@@ -436,14 +445,14 @@ public function databaseUrls()
[
'url' => '//foo:bar@localhost/baz',
'driver' => 'pdo_mysql',
- 'driverClass' => DriverMock::class,
+ 'driverClass' => $driverClass,
],
[
'user' => 'foo',
'password' => 'bar',
'host' => 'localhost',
'dbname' => 'baz',
- 'driverClass' => DriverMock::class,
+ 'driverClass' => $driverClass,
],
],
'URL with default PDO driver' => [
@@ -475,7 +484,7 @@ public function databaseUrls()
'URL with default custom driver' => [
[
'url' => 'mysql://foo:bar@localhost/baz',
- 'driverClass' => DriverMock::class,
+ 'driverClass' => $driverClass,
],
[
'user' => 'foo',
@@ -503,7 +512,7 @@ public function databaseUrls()
[
'url' => 'mysql://foo:bar@localhost/baz',
'driver' => 'sqlite',
- 'driverClass' => DriverMock::class,
+ 'driverClass' => $driverClass,
],
[
'user' => 'foo',
@@ -518,7 +527,7 @@ public function databaseUrls()
'url' => 'mysql://foo:bar@localhost/baz',
'pdo' => true,
'driver' => 'sqlite',
- 'driverClass' => DriverMock::class,
+ 'driverClass' => $driverClass,
],
[
'user' => 'foo',
diff --git a/tests/Doctrine/Tests/DBAL/Events/MysqlSessionInitTest.php b/tests/Doctrine/Tests/DBAL/Events/MysqlSessionInitTest.php
index 0f9be11edda..daea3a754c6 100644
--- a/tests/Doctrine/Tests/DBAL/Events/MysqlSessionInitTest.php
+++ b/tests/Doctrine/Tests/DBAL/Events/MysqlSessionInitTest.php
@@ -10,7 +10,7 @@
class MysqlSessionInitTest extends DbalTestCase
{
- public function testPostConnect()
+ public function testPostConnect() : void
{
$connectionMock = $this->createMock(Connection::class);
$connectionMock->expects($this->once())
@@ -23,7 +23,7 @@ public function testPostConnect()
$listener->postConnect($eventArgs);
}
- public function testGetSubscribedEvents()
+ public function testGetSubscribedEvents() : void
{
$listener = new MysqlSessionInit();
self::assertEquals([Events::postConnect], $listener->getSubscribedEvents());
diff --git a/tests/Doctrine/Tests/DBAL/Events/OracleSessionInitTest.php b/tests/Doctrine/Tests/DBAL/Events/OracleSessionInitTest.php
index 2ea510a0543..998b1dc916e 100644
--- a/tests/Doctrine/Tests/DBAL/Events/OracleSessionInitTest.php
+++ b/tests/Doctrine/Tests/DBAL/Events/OracleSessionInitTest.php
@@ -11,7 +11,7 @@
class OracleSessionInitTest extends DbalTestCase
{
- public function testPostConnect()
+ public function testPostConnect() : void
{
$connectionMock = $this->createMock(Connection::class);
$connectionMock->expects($this->once())
@@ -28,7 +28,7 @@ public function testPostConnect()
* @group DBAL-1824
* @dataProvider getPostConnectWithSessionParameterValuesData
*/
- public function testPostConnectQuotesSessionParameterValues($name, $value)
+ public function testPostConnectQuotesSessionParameterValues(string $name, string $value) : void
{
$connectionMock = $this->getMockBuilder(Connection::class)
->disableOriginalConstructor()
@@ -43,14 +43,17 @@ public function testPostConnectQuotesSessionParameterValues($name, $value)
$listener->postConnect($eventArgs);
}
- public function getPostConnectWithSessionParameterValuesData()
+ /**
+ * @return array>
+ */
+ public static function getPostConnectWithSessionParameterValuesData() : iterable
{
return [
['CURRENT_SCHEMA', 'foo'],
];
}
- public function testGetSubscribedEvents()
+ public function testGetSubscribedEvents() : void
{
$listener = new OracleSessionInit();
self::assertEquals([Events::postConnect], $listener->getSubscribedEvents());
diff --git a/tests/Doctrine/Tests/DBAL/Events/SQLSessionInitTest.php b/tests/Doctrine/Tests/DBAL/Events/SQLSessionInitTest.php
index f42458de74d..c69b2996827 100644
--- a/tests/Doctrine/Tests/DBAL/Events/SQLSessionInitTest.php
+++ b/tests/Doctrine/Tests/DBAL/Events/SQLSessionInitTest.php
@@ -13,7 +13,7 @@
*/
class SQLSessionInitTest extends DbalTestCase
{
- public function testPostConnect()
+ public function testPostConnect() : void
{
$connectionMock = $this->createMock(Connection::class);
$connectionMock->expects($this->once())
@@ -26,7 +26,7 @@ public function testPostConnect()
$listener->postConnect($eventArgs);
}
- public function testGetSubscribedEvents()
+ public function testGetSubscribedEvents() : void
{
$listener = new SQLSessionInit("SET SEARCH_PATH TO foo, public, TIMEZONE TO 'Europe/Berlin'");
self::assertEquals([Events::postConnect], $listener->getSubscribedEvents());
diff --git a/tests/Doctrine/Tests/DBAL/Exception/InvalidArgumentExceptionTest.php b/tests/Doctrine/Tests/DBAL/Exception/InvalidArgumentExceptionTest.php
index 54cfea89596..7718a6bc9d8 100644
--- a/tests/Doctrine/Tests/DBAL/Exception/InvalidArgumentExceptionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Exception/InvalidArgumentExceptionTest.php
@@ -12,7 +12,7 @@
*/
class InvalidArgumentExceptionTest extends TestCase
{
- public function testFromEmptyCriteria()
+ public function testFromEmptyCriteria() : void
{
$exception = InvalidArgumentException::fromEmptyCriteria();
diff --git a/tests/Doctrine/Tests/DBAL/Functional/BlobTest.php b/tests/Doctrine/Tests/DBAL/Functional/BlobTest.php
index 7c6de8e3795..a12d0600201 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/BlobTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/BlobTest.php
@@ -18,7 +18,7 @@
*/
class BlobTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -38,7 +38,7 @@ protected function setUp()
$sm->dropAndCreateTable($table);
}
- public function testInsert()
+ public function testInsert() : void
{
$ret = $this->connection->insert('blob_table', [
'id' => 1,
@@ -53,7 +53,7 @@ public function testInsert()
self::assertEquals(1, $ret);
}
- public function testInsertProcessesStream()
+ public function testInsertProcessesStream() : void
{
// https://github.com/doctrine/dbal/issues/3290
if ($this->connection->getDriver() instanceof OCI8Driver) {
@@ -74,7 +74,7 @@ public function testInsertProcessesStream()
$this->assertBlobContains($longBlob);
}
- public function testSelect()
+ public function testSelect() : void
{
$this->connection->insert('blob_table', [
'id' => 1,
@@ -89,7 +89,7 @@ public function testSelect()
$this->assertBlobContains('test');
}
- public function testUpdate()
+ public function testUpdate() : void
{
$this->connection->insert('blob_table', [
'id' => 1,
@@ -109,7 +109,7 @@ public function testUpdate()
$this->assertBlobContains('test2');
}
- public function testUpdateProcessesStream()
+ public function testUpdateProcessesStream() : void
{
// https://github.com/doctrine/dbal/issues/3290
if ($this->connection->getDriver() instanceof OCI8Driver) {
@@ -137,7 +137,7 @@ public function testUpdateProcessesStream()
$this->assertBlobContains('test2');
}
- public function testBindParamProcessesStream()
+ public function testBindParamProcessesStream() : void
{
if ($this->connection->getDriver() instanceof OCI8Driver) {
$this->markTestIncomplete('The oci8 driver does not support stream resources as parameters');
@@ -156,7 +156,7 @@ public function testBindParamProcessesStream()
$this->assertBlobContains('test');
}
- private function assertBlobContains($text)
+ private function assertBlobContains(string $text) : void
{
$rows = $this->connection->query('SELECT blobfield FROM blob_table')->fetchAll(FetchMode::COLUMN);
@@ -164,7 +164,7 @@ private function assertBlobContains($text)
$blobValue = Type::getType('blob')->convertToPHPValue($rows[0], $this->connection->getDatabasePlatform());
- self::assertInternalType('resource', $blobValue);
+ self::assertIsResource($blobValue);
self::assertEquals($text, stream_get_contents($blobValue));
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/ConnectionTest.php b/tests/Doctrine/Tests/DBAL/Functional/ConnectionTest.php
index 6da314781b7..f9b067ad4a4 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/ConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/ConnectionTest.php
@@ -8,34 +8,35 @@
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use Doctrine\Tests\DbalFunctionalTestCase;
use Error;
use Exception;
+use PDO;
use RuntimeException;
use Throwable;
use function in_array;
class ConnectionTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
$this->resetSharedConn();
parent::setUp();
}
- protected function tearDown()
+ protected function tearDown() : void
{
parent::tearDown();
$this->resetSharedConn();
}
- public function testGetWrappedConnection()
+ public function testGetWrappedConnection() : void
{
self::assertInstanceOf(DriverConnection::class, $this->connection->getWrappedConnection());
}
- public function testCommitWithRollbackOnlyThrowsException()
+ public function testCommitWithRollbackOnlyThrowsException() : void
{
$this->connection->beginTransaction();
$this->connection->setRollbackOnly();
@@ -44,7 +45,7 @@ public function testCommitWithRollbackOnlyThrowsException()
$this->connection->commit();
}
- public function testTransactionNestingBehavior()
+ public function testTransactionNestingBehavior() : void
{
try {
$this->connection->beginTransaction();
@@ -105,7 +106,7 @@ public function testTransactionNestingLevelIsResetOnReconnect() : void
self::assertEquals(0, $connection->fetchColumn('select count(*) from test_nesting'));
}
- public function testTransactionNestingBehaviorWithSavepoints()
+ public function testTransactionNestingBehaviorWithSavepoints() : void
{
if (! $this->connection->getDatabasePlatform()->supportsSavepoints()) {
$this->markTestSkipped('This test requires the platform to support savepoints.');
@@ -121,7 +122,7 @@ public function testTransactionNestingBehaviorWithSavepoints()
self::assertEquals(2, $this->connection->getTransactionNestingLevel());
$this->connection->beginTransaction();
self::assertEquals(3, $this->connection->getTransactionNestingLevel());
- $this->connection->commit();
+ self::assertTrue($this->connection->commit());
self::assertEquals(2, $this->connection->getTransactionNestingLevel());
throw new Exception();
$this->connection->commit(); // never reached
@@ -144,7 +145,7 @@ public function testTransactionNestingBehaviorWithSavepoints()
}
}
- public function testTransactionNestingBehaviorCantBeChangedInActiveTransaction()
+ public function testTransactionNestingBehaviorCantBeChangedInActiveTransaction() : void
{
if (! $this->connection->getDatabasePlatform()->supportsSavepoints()) {
$this->markTestSkipped('This test requires the platform to support savepoints.');
@@ -155,7 +156,7 @@ public function testTransactionNestingBehaviorCantBeChangedInActiveTransaction()
$this->connection->setNestTransactionsWithSavepoints(true);
}
- public function testSetNestedTransactionsThroughSavepointsNotSupportedThrowsException()
+ public function testSetNestedTransactionsThroughSavepointsNotSupportedThrowsException() : void
{
if ($this->connection->getDatabasePlatform()->supportsSavepoints()) {
$this->markTestSkipped('This test requires the platform not to support savepoints.');
@@ -167,7 +168,7 @@ public function testSetNestedTransactionsThroughSavepointsNotSupportedThrowsExce
$this->connection->setNestTransactionsWithSavepoints(true);
}
- public function testCreateSavepointsNotSupportedThrowsException()
+ public function testCreateSavepointsNotSupportedThrowsException() : void
{
if ($this->connection->getDatabasePlatform()->supportsSavepoints()) {
$this->markTestSkipped('This test requires the platform not to support savepoints.');
@@ -179,7 +180,7 @@ public function testCreateSavepointsNotSupportedThrowsException()
$this->connection->createSavepoint('foo');
}
- public function testReleaseSavepointsNotSupportedThrowsException()
+ public function testReleaseSavepointsNotSupportedThrowsException() : void
{
if ($this->connection->getDatabasePlatform()->supportsSavepoints()) {
$this->markTestSkipped('This test requires the platform not to support savepoints.');
@@ -191,7 +192,7 @@ public function testReleaseSavepointsNotSupportedThrowsException()
$this->connection->releaseSavepoint('foo');
}
- public function testRollbackSavepointsNotSupportedThrowsException()
+ public function testRollbackSavepointsNotSupportedThrowsException() : void
{
if ($this->connection->getDatabasePlatform()->supportsSavepoints()) {
$this->markTestSkipped('This test requires the platform not to support savepoints.');
@@ -203,7 +204,7 @@ public function testRollbackSavepointsNotSupportedThrowsException()
$this->connection->rollbackSavepoint('foo');
}
- public function testTransactionBehaviorWithRollback()
+ public function testTransactionBehaviorWithRollback() : void
{
try {
$this->connection->beginTransaction();
@@ -219,7 +220,7 @@ public function testTransactionBehaviorWithRollback()
}
}
- public function testTransactionBehaviour()
+ public function testTransactionBehaviour() : void
{
try {
$this->connection->beginTransaction();
@@ -233,10 +234,10 @@ public function testTransactionBehaviour()
self::assertEquals(0, $this->connection->getTransactionNestingLevel());
}
- public function testTransactionalWithException()
+ public function testTransactionalWithException() : void
{
try {
- $this->connection->transactional(static function ($conn) {
+ $this->connection->transactional(static function ($conn) : void {
/** @var Connection $conn */
$conn->executeQuery($conn->getDatabasePlatform()->getDummySelectSQL());
throw new RuntimeException('Ooops!');
@@ -247,10 +248,10 @@ public function testTransactionalWithException()
}
}
- public function testTransactionalWithThrowable()
+ public function testTransactionalWithThrowable() : void
{
try {
- $this->connection->transactional(static function ($conn) {
+ $this->connection->transactional(static function ($conn) : void {
/** @var Connection $conn */
$conn->executeQuery($conn->getDatabasePlatform()->getDummySelectSQL());
throw new Error('Ooops!');
@@ -261,9 +262,9 @@ public function testTransactionalWithThrowable()
}
}
- public function testTransactional()
+ public function testTransactional() : void
{
- $res = $this->connection->transactional(static function ($conn) {
+ $res = $this->connection->transactional(static function ($conn) : void {
/** @var Connection $conn */
$conn->executeQuery($conn->getDatabasePlatform()->getDummySelectSQL());
});
@@ -271,7 +272,7 @@ public function testTransactional()
self::assertNull($res);
}
- public function testTransactionalReturnValue()
+ public function testTransactionalReturnValue() : void
{
$res = $this->connection->transactional(static function () {
return 42;
@@ -283,15 +284,15 @@ public function testTransactionalReturnValue()
/**
* Tests that the quote function accepts DBAL and PDO types.
*/
- public function testQuote()
+ public function testQuote() : void
{
self::assertEquals(
- $this->connection->quote('foo', Type::STRING),
+ $this->connection->quote('foo', Types::STRING),
$this->connection->quote('foo', ParameterType::STRING)
);
}
- public function testPingDoesTriggersConnect()
+ public function testPingDoesTriggersConnect() : void
{
self::assertTrue($this->connection->ping());
self::assertTrue($this->connection->isConnected());
@@ -300,7 +301,7 @@ public function testPingDoesTriggersConnect()
/**
* @group DBAL-1025
*/
- public function testConnectWithoutExplicitDatabaseName()
+ public function testConnectWithoutExplicitDatabaseName() : void
{
if (in_array($this->connection->getDatabasePlatform()->getName(), ['oracle', 'db2'], true)) {
$this->markTestSkipped('Platform does not support connecting without database name.');
@@ -323,7 +324,7 @@ public function testConnectWithoutExplicitDatabaseName()
/**
* @group DBAL-990
*/
- public function testDeterminesDatabasePlatformWhenConnectingToNonExistentDatabase()
+ public function testDeterminesDatabasePlatformWhenConnectingToNonExistentDatabase() : void
{
if (in_array($this->connection->getDatabasePlatform()->getName(), ['oracle', 'db2'], true)) {
$this->markTestSkipped('Platform does not support connecting without database name.');
@@ -345,4 +346,16 @@ public function testDeterminesDatabasePlatformWhenConnectingToNonExistentDatabas
$connection->close();
}
+
+ /**
+ * @requires extension pdo_sqlite
+ */
+ public function testUserProvidedPDOConnection() : void
+ {
+ self::assertTrue(
+ DriverManager::getConnection([
+ 'pdo' => new PDO('sqlite::memory:'),
+ ])->ping()
+ );
+ }
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/DataAccessTest.php b/tests/Doctrine/Tests/DBAL/Functional/DataAccessTest.php
index f6ad3cb6b22..b7d625c8600 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/DataAccessTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/DataAccessTest.php
@@ -4,6 +4,7 @@
use DateTime;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\Mysqli\Driver as MySQLiDriver;
use Doctrine\DBAL\Driver\OCI8\Driver as Oci8Driver;
use Doctrine\DBAL\Driver\PDOConnection;
@@ -15,7 +16,7 @@
use Doctrine\DBAL\Platforms\TrimMode;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Statement;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use Doctrine\Tests\DbalFunctionalTestCase;
use PDO;
use const CASE_LOWER;
@@ -35,9 +36,9 @@
class DataAccessTest extends DbalFunctionalTestCase
{
/** @var bool */
- static private $generated = false;
+ private static $generated = false;
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -58,7 +59,7 @@ protected function setUp()
self::$generated = true;
}
- public function testPrepareWithBindValue()
+ public function testPrepareWithBindValue() : void
{
$sql = 'SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?';
$stmt = $this->connection->prepare($sql);
@@ -73,7 +74,7 @@ public function testPrepareWithBindValue()
self::assertEquals(['test_int' => 1, 'test_string' => 'foo'], $row);
}
- public function testPrepareWithBindParam()
+ public function testPrepareWithBindParam() : void
{
$paramInt = 1;
$paramStr = 'foo';
@@ -91,7 +92,7 @@ public function testPrepareWithBindParam()
self::assertEquals(['test_int' => 1, 'test_string' => 'foo'], $row);
}
- public function testPrepareWithFetchAll()
+ public function testPrepareWithFetchAll() : void
{
$paramInt = 1;
$paramStr = 'foo';
@@ -112,7 +113,7 @@ public function testPrepareWithFetchAll()
/**
* @group DBAL-228
*/
- public function testPrepareWithFetchAllBoth()
+ public function testPrepareWithFetchAllBoth() : void
{
$paramInt = 1;
$paramStr = 'foo';
@@ -130,7 +131,7 @@ public function testPrepareWithFetchAllBoth()
self::assertEquals(['test_int' => 1, 'test_string' => 'foo', 0 => 1, 1 => 'foo'], $rows[0]);
}
- public function testPrepareWithFetchColumn()
+ public function testPrepareWithFetchColumn() : void
{
$paramInt = 1;
$paramStr = 'foo';
@@ -147,7 +148,7 @@ public function testPrepareWithFetchColumn()
self::assertEquals(1, $column);
}
- public function testPrepareWithIterator()
+ public function testPrepareWithIterator() : void
{
$paramInt = 1;
$paramStr = 'foo';
@@ -169,7 +170,7 @@ public function testPrepareWithIterator()
self::assertEquals(['test_int' => 1, 'test_string' => 'foo'], $rows[0]);
}
- public function testPrepareWithQuoted()
+ public function testPrepareWithQuoted() : void
{
$table = 'fetch_table';
$paramInt = 1;
@@ -184,7 +185,7 @@ public function testPrepareWithQuoted()
self::assertInstanceOf(Statement::class, $stmt);
}
- public function testPrepareWithExecuteParams()
+ public function testPrepareWithExecuteParams() : void
{
$paramInt = 1;
$paramStr = 'foo';
@@ -200,7 +201,7 @@ public function testPrepareWithExecuteParams()
self::assertEquals(['test_int' => 1, 'test_string' => 'foo'], $row);
}
- public function testFetchAll()
+ public function testFetchAll() : void
{
$sql = 'SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?';
$data = $this->connection->fetchAll($sql, [1, 'foo']);
@@ -218,13 +219,17 @@ public function testFetchAll()
/**
* @group DBAL-209
*/
- public function testFetchAllWithTypes()
+ public function testFetchAllWithTypes() : void
{
$datetimeString = '2010-01-01 10:10:10';
$datetime = new DateTime($datetimeString);
$sql = 'SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?';
- $data = $this->connection->fetchAll($sql, [1, $datetime], [ParameterType::STRING, Type::DATETIME]);
+ $data = $this->connection->fetchAll(
+ $sql,
+ [1, $datetime],
+ [ParameterType::STRING, Types::DATETIME_MUTABLE]
+ );
self::assertCount(1, $data);
@@ -238,9 +243,8 @@ public function testFetchAllWithTypes()
/**
* @group DBAL-209
- * @expectedException \Doctrine\DBAL\DBALException
*/
- public function testFetchAllWithMissingTypes()
+ public function testFetchAllWithMissingTypes() : void
{
if ($this->connection->getDriver() instanceof MySQLiDriver ||
$this->connection->getDriver() instanceof SQLSrvDriver) {
@@ -250,10 +254,13 @@ public function testFetchAllWithMissingTypes()
$datetimeString = '2010-01-01 10:10:10';
$datetime = new DateTime($datetimeString);
$sql = 'SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?';
+
+ $this->expectException(DBALException::class);
+
$this->connection->fetchAll($sql, [1, $datetime]);
}
- public function testFetchBoth()
+ public function testFetchBoth() : void
{
$sql = 'SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?';
$row = $this->connection->executeQuery($sql, [1, 'foo'])->fetch(FetchMode::MIXED);
@@ -268,14 +275,14 @@ public function testFetchBoth()
self::assertEquals('foo', $row[1]);
}
- public function testFetchNoResult()
+ public function testFetchNoResult() : void
{
self::assertFalse(
$this->connection->executeQuery('SELECT test_int FROM fetch_table WHERE test_int = ?', [-1])->fetch()
);
}
- public function testFetchAssoc()
+ public function testFetchAssoc() : void
{
$sql = 'SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?';
$row = $this->connection->fetchAssoc($sql, [1, 'foo']);
@@ -288,13 +295,17 @@ public function testFetchAssoc()
self::assertEquals('foo', $row['test_string']);
}
- public function testFetchAssocWithTypes()
+ public function testFetchAssocWithTypes() : void
{
$datetimeString = '2010-01-01 10:10:10';
$datetime = new DateTime($datetimeString);
$sql = 'SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?';
- $row = $this->connection->fetchAssoc($sql, [1, $datetime], [ParameterType::STRING, Type::DATETIME]);
+ $row = $this->connection->fetchAssoc(
+ $sql,
+ [1, $datetime],
+ [ParameterType::STRING, Types::DATETIME_MUTABLE]
+ );
self::assertNotFalse($row);
@@ -304,10 +315,7 @@ public function testFetchAssocWithTypes()
self::assertStringStartsWith($datetimeString, $row['test_datetime']);
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testFetchAssocWithMissingTypes()
+ public function testFetchAssocWithMissingTypes() : void
{
if ($this->connection->getDriver() instanceof MySQLiDriver ||
$this->connection->getDriver() instanceof SQLSrvDriver) {
@@ -317,10 +325,13 @@ public function testFetchAssocWithMissingTypes()
$datetimeString = '2010-01-01 10:10:10';
$datetime = new DateTime($datetimeString);
$sql = 'SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?';
+
+ $this->expectException(DBALException::class);
+
$this->connection->fetchAssoc($sql, [1, $datetime]);
}
- public function testFetchArray()
+ public function testFetchArray() : void
{
$sql = 'SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?';
$row = $this->connection->fetchArray($sql, [1, 'foo']);
@@ -329,13 +340,17 @@ public function testFetchArray()
self::assertEquals('foo', $row[1]);
}
- public function testFetchArrayWithTypes()
+ public function testFetchArrayWithTypes() : void
{
$datetimeString = '2010-01-01 10:10:10';
$datetime = new DateTime($datetimeString);
$sql = 'SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?';
- $row = $this->connection->fetchArray($sql, [1, $datetime], [ParameterType::STRING, Type::DATETIME]);
+ $row = $this->connection->fetchArray(
+ $sql,
+ [1, $datetime],
+ [ParameterType::STRING, Types::DATETIME_MUTABLE]
+ );
self::assertNotFalse($row);
@@ -345,10 +360,7 @@ public function testFetchArrayWithTypes()
self::assertStringStartsWith($datetimeString, $row[1]);
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testFetchArrayWithMissingTypes()
+ public function testFetchArrayWithMissingTypes() : void
{
if ($this->connection->getDriver() instanceof MySQLiDriver ||
$this->connection->getDriver() instanceof SQLSrvDriver) {
@@ -358,10 +370,13 @@ public function testFetchArrayWithMissingTypes()
$datetimeString = '2010-01-01 10:10:10';
$datetime = new DateTime($datetimeString);
$sql = 'SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?';
- $row = $this->connection->fetchArray($sql, [1, $datetime]);
+
+ $this->expectException(DBALException::class);
+
+ $this->connection->fetchArray($sql, [1, $datetime]);
}
- public function testFetchColumn()
+ public function testFetchColumn() : void
{
$sql = 'SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?';
$testInt = $this->connection->fetchColumn($sql, [1, 'foo'], 0);
@@ -374,23 +389,25 @@ public function testFetchColumn()
self::assertEquals('foo', $testString);
}
- public function testFetchColumnWithTypes()
+ public function testFetchColumnWithTypes() : void
{
$datetimeString = '2010-01-01 10:10:10';
$datetime = new DateTime($datetimeString);
$sql = 'SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?';
- $column = $this->connection->fetchColumn($sql, [1, $datetime], 1, [ParameterType::STRING, Type::DATETIME]);
+ $column = $this->connection->fetchColumn(
+ $sql,
+ [1, $datetime],
+ 1,
+ [ParameterType::STRING, Types::DATETIME_MUTABLE]
+ );
self::assertNotFalse($column);
self::assertStringStartsWith($datetimeString, $column);
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testFetchColumnWithMissingTypes()
+ public function testFetchColumnWithMissingTypes() : void
{
if ($this->connection->getDriver() instanceof MySQLiDriver ||
$this->connection->getDriver() instanceof SQLSrvDriver) {
@@ -400,19 +417,22 @@ public function testFetchColumnWithMissingTypes()
$datetimeString = '2010-01-01 10:10:10';
$datetime = new DateTime($datetimeString);
$sql = 'SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?';
- $column = $this->connection->fetchColumn($sql, [1, $datetime], 1);
+
+ $this->expectException(DBALException::class);
+
+ $this->connection->fetchColumn($sql, [1, $datetime], 1);
}
/**
* @group DDC-697
*/
- public function testExecuteQueryBindDateTimeType()
+ public function testExecuteQueryBindDateTimeType() : void
{
$sql = 'SELECT count(*) AS c FROM fetch_table WHERE test_datetime = ?';
$stmt = $this->connection->executeQuery(
$sql,
[1 => new DateTime('2010-01-01 10:10:10')],
- [1 => Type::DATETIME]
+ [1 => Types::DATETIME_MUTABLE]
);
self::assertEquals(1, $stmt->fetchColumn());
@@ -421,7 +441,7 @@ public function testExecuteQueryBindDateTimeType()
/**
* @group DDC-697
*/
- public function testExecuteUpdateBindDateTimeType()
+ public function testExecuteUpdateBindDateTimeType() : void
{
$datetime = new DateTime('2010-02-02 20:20:20');
@@ -433,25 +453,25 @@ public function testExecuteUpdateBindDateTimeType()
], [
1 => ParameterType::INTEGER,
2 => ParameterType::STRING,
- 3 => Type::DATETIME,
+ 3 => Types::DATETIME_MUTABLE,
]);
self::assertEquals(1, $affectedRows);
self::assertEquals(1, $this->connection->executeQuery(
'SELECT count(*) AS c FROM fetch_table WHERE test_datetime = ?',
[1 => $datetime],
- [1 => Type::DATETIME]
+ [1 => Types::DATETIME_MUTABLE]
)->fetchColumn());
}
/**
* @group DDC-697
*/
- public function testPrepareQueryBindValueDateTimeType()
+ public function testPrepareQueryBindValueDateTimeType() : void
{
$sql = 'SELECT count(*) AS c FROM fetch_table WHERE test_datetime = ?';
$stmt = $this->connection->prepare($sql);
- $stmt->bindValue(1, new DateTime('2010-01-01 10:10:10'), Type::DATETIME);
+ $stmt->bindValue(1, new DateTime('2010-01-01 10:10:10'), Types::DATETIME_MUTABLE);
$stmt->execute();
self::assertEquals(1, $stmt->fetchColumn());
@@ -460,7 +480,7 @@ public function testPrepareQueryBindValueDateTimeType()
/**
* @group DBAL-78
*/
- public function testNativeArrayListSupport()
+ public function testNativeArrayListSupport() : void
{
for ($i = 100; $i < 110; $i++) {
$this->connection->insert('fetch_table', ['test_int' => $i, 'test_string' => 'foo' . $i, 'test_datetime' => '2010-01-01 10:10:10']);
@@ -488,9 +508,11 @@ public function testNativeArrayListSupport()
}
/**
+ * @param string|false $char
+ *
* @dataProvider getTrimExpressionData
*/
- public function testTrimExpression($value, $position, $char, $expectedResult)
+ public function testTrimExpression(string $value, int $position, $char, string $expectedResult) : void
{
$sql = 'SELECT ' .
$this->connection->getDatabasePlatform()->getTrimExpression($value, $position, $char) . ' AS trimmed ' .
@@ -502,7 +524,10 @@ public function testTrimExpression($value, $position, $char, $expectedResult)
self::assertEquals($expectedResult, $row['trimmed']);
}
- public function getTrimExpressionData()
+ /**
+ * @return array>
+ */
+ public static function getTrimExpressionData() : iterable
{
return [
['test_string', TrimMode::UNSPECIFIED, false, 'foo'],
@@ -547,7 +572,7 @@ public function getTrimExpressionData()
/**
* @group DDC-1014
*/
- public function testDateArithmetics()
+ public function testDateArithmetics() : void
{
$p = $this->connection->getDatabasePlatform();
$sql = 'SELECT ';
@@ -590,7 +615,7 @@ public function testDateArithmetics()
self::assertEquals('2004-01-01', date('Y-m-d', strtotime($row['sub_years'])), 'Subtracting years should end up on 2004-01-01');
}
- public function testSqliteDateArithmeticWithDynamicInterval()
+ public function testSqliteDateArithmeticWithDynamicInterval() : void
{
$platform = $this->connection->getDatabasePlatform();
@@ -617,7 +642,7 @@ public function testSqliteDateArithmeticWithDynamicInterval()
$this->assertEquals(1, $rowCount);
}
- public function testLocateExpression()
+ public function testLocateExpression() : void
{
$platform = $this->connection->getDatabasePlatform();
@@ -647,7 +672,7 @@ public function testLocateExpression()
self::assertEquals(0, $row['locate9']);
}
- public function testQuoteSQLInjection()
+ public function testQuoteSQLInjection() : void
{
$sql = 'SELECT * FROM fetch_table WHERE test_string = ' . $this->connection->quote("bar' OR '1'='1");
$rows = $this->connection->fetchAll($sql);
@@ -658,7 +683,7 @@ public function testQuoteSQLInjection()
/**
* @group DDC-1213
*/
- public function testBitComparisonExpressionSupport()
+ public function testBitComparisonExpressionSupport() : void
{
$this->connection->exec('DELETE FROM fetch_table');
$platform = $this->connection->getDatabasePlatform();
@@ -706,7 +731,7 @@ public function testBitComparisonExpressionSupport()
}
}
- public function testSetDefaultFetchMode()
+ public function testSetDefaultFetchMode() : void
{
$stmt = $this->connection->query('SELECT * FROM fetch_table');
$stmt->setFetchMode(FetchMode::NUMERIC);
@@ -720,7 +745,7 @@ public function testSetDefaultFetchMode()
/**
* @group DBAL-1091
*/
- public function testFetchAllStyleObject()
+ public function testFetchAllStyleObject() : void
{
$this->setupFixture();
@@ -751,7 +776,7 @@ public function testFetchAllStyleObject()
/**
* @group DBAL-196
*/
- public function testFetchAllSupportFetchClass()
+ public function testFetchAllSupportFetchClass() : void
{
$this->beforeFetchClassTest();
$this->setupFixture();
@@ -776,7 +801,7 @@ public function testFetchAllSupportFetchClass()
/**
* @group DBAL-241
*/
- public function testFetchAllStyleColumn()
+ public function testFetchAllStyleColumn() : void
{
$sql = 'DELETE FROM fetch_table';
$this->connection->executeUpdate($sql);
@@ -793,7 +818,7 @@ public function testFetchAllStyleColumn()
/**
* @group DBAL-214
*/
- public function testSetFetchModeClassFetchAll()
+ public function testSetFetchModeClassFetchAll() : void
{
$this->beforeFetchClassTest();
$this->setupFixture();
@@ -815,7 +840,7 @@ public function testSetFetchModeClassFetchAll()
/**
* @group DBAL-214
*/
- public function testSetFetchModeClassFetch()
+ public function testSetFetchModeClassFetch() : void
{
$this->beforeFetchClassTest();
$this->setupFixture();
@@ -840,7 +865,7 @@ public function testSetFetchModeClassFetch()
/**
* @group DBAL-257
*/
- public function testEmptyFetchColumnReturnsFalse()
+ public function testEmptyFetchColumnReturnsFalse() : void
{
$this->connection->beginTransaction();
$this->connection->exec('DELETE FROM fetch_table');
@@ -852,7 +877,7 @@ public function testEmptyFetchColumnReturnsFalse()
/**
* @group DBAL-339
*/
- public function testSetFetchModeOnDbalStatement()
+ public function testSetFetchModeOnDbalStatement() : void
{
$sql = 'SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?';
$stmt = $this->connection->executeQuery($sql, [1, 'foo']);
@@ -868,7 +893,7 @@ public function testSetFetchModeOnDbalStatement()
/**
* @group DBAL-435
*/
- public function testEmptyParameters()
+ public function testEmptyParameters() : void
{
$sql = 'SELECT * FROM fetch_table WHERE test_int IN (?)';
$stmt = $this->connection->executeQuery($sql, [[]], [Connection::PARAM_INT_ARRAY]);
@@ -880,7 +905,7 @@ public function testEmptyParameters()
/**
* @group DBAL-1028
*/
- public function testFetchColumnNullValue()
+ public function testFetchColumnNullValue() : void
{
$this->connection->executeUpdate(
'INSERT INTO fetch_table (test_int, test_string) VALUES (?, ?)',
@@ -895,14 +920,14 @@ public function testFetchColumnNullValue()
/**
* @group DBAL-1028
*/
- public function testFetchColumnNoResult()
+ public function testFetchColumnNoResult() : void
{
self::assertFalse(
$this->connection->fetchColumn('SELECT test_int FROM fetch_table WHERE test_int = ?', [-1])
);
}
- private function setupFixture()
+ private function setupFixture() : void
{
$this->connection->exec('DELETE FROM fetch_table');
$this->connection->insert('fetch_table', [
@@ -912,7 +937,7 @@ private function setupFixture()
]);
}
- private function beforeFetchClassTest()
+ private function beforeFetchClassTest() : void
{
$driver = $this->connection->getDriver();
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/AbstractDriverTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/AbstractDriverTest.php
index 738c259d5c0..3adf3c2bb89 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/AbstractDriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/AbstractDriverTest.php
@@ -16,7 +16,7 @@ abstract class AbstractDriverTest extends DbalFunctionalTestCase
*/
protected $driver;
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -26,7 +26,7 @@ protected function setUp()
/**
* @group DBAL-1215
*/
- public function testConnectsWithoutDatabaseNameParameter()
+ public function testConnectsWithoutDatabaseNameParameter() : void
{
$params = $this->connection->getParams();
unset($params['dbname']);
@@ -42,7 +42,7 @@ public function testConnectsWithoutDatabaseNameParameter()
/**
* @group DBAL-1215
*/
- public function testReturnsDatabaseNameWithoutDatabaseNameParameter()
+ public function testReturnsDatabaseNameWithoutDatabaseNameParameter() : void
{
$params = $this->connection->getParams();
unset($params['dbname']);
@@ -55,20 +55,14 @@ public function testReturnsDatabaseNameWithoutDatabaseNameParameter()
);
self::assertSame(
- $this->getDatabaseNameForConnectionWithoutDatabaseNameParameter(),
+ static::getDatabaseNameForConnectionWithoutDatabaseNameParameter(),
$this->driver->getDatabase($connection)
);
}
- /**
- * @return Driver
- */
- abstract protected function createDriver();
+ abstract protected function createDriver() : Driver;
- /**
- * @return string|null
- */
- protected function getDatabaseNameForConnectionWithoutDatabaseNameParameter()
+ protected static function getDatabaseNameForConnectionWithoutDatabaseNameParameter() : ?string
{
return null;
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/IBMDB2/DB2DriverTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/IBMDB2/DB2DriverTest.php
index 82da6090b7e..4021bb2fff7 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/IBMDB2/DB2DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/IBMDB2/DB2DriverTest.php
@@ -2,13 +2,14 @@
namespace Doctrine\Tests\DBAL\Functional\Driver\IBMDB2;
+use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\IBMDB2\DB2Driver;
use Doctrine\Tests\DBAL\Functional\Driver\AbstractDriverTest;
use function extension_loaded;
class DB2DriverTest extends AbstractDriverTest
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('ibm_db2')) {
$this->markTestSkipped('ibm_db2 is not installed.');
@@ -26,7 +27,7 @@ protected function setUp()
/**
* {@inheritdoc}
*/
- public function testConnectsWithoutDatabaseNameParameter()
+ public function testConnectsWithoutDatabaseNameParameter() : void
{
$this->markTestSkipped('IBM DB2 does not support connecting without database name.');
}
@@ -34,7 +35,7 @@ public function testConnectsWithoutDatabaseNameParameter()
/**
* {@inheritdoc}
*/
- public function testReturnsDatabaseNameWithoutDatabaseNameParameter()
+ public function testReturnsDatabaseNameWithoutDatabaseNameParameter() : void
{
$this->markTestSkipped('IBM DB2 does not support connecting without database name.');
}
@@ -42,7 +43,7 @@ public function testReturnsDatabaseNameWithoutDatabaseNameParameter()
/**
* {@inheritdoc}
*/
- protected function createDriver()
+ protected function createDriver() : Driver
{
return new DB2Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/IBMDB2/DB2StatementTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/IBMDB2/DB2StatementTest.php
index 6c2ec6a9ca6..c839d20d916 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/IBMDB2/DB2StatementTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/IBMDB2/DB2StatementTest.php
@@ -11,7 +11,7 @@
class DB2StatementTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('ibm_db2')) {
$this->markTestSkipped('ibm_db2 is not installed.');
@@ -26,7 +26,7 @@ protected function setUp()
$this->markTestSkipped('ibm_db2 only test.');
}
- public function testExecutionErrorsAreNotSuppressed()
+ public function testExecutionErrorsAreNotSuppressed() : void
{
$stmt = $this->connection->prepare('SELECT * FROM SYSIBM.SYSDUMMY1 WHERE \'foo\' = ?');
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/Mysqli/ConnectionTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/Mysqli/ConnectionTest.php
index bbd8d5ebd09..4a3a315f296 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/Mysqli/ConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/Mysqli/ConnectionTest.php
@@ -4,13 +4,14 @@
use Doctrine\DBAL\Driver\Mysqli\Driver;
use Doctrine\DBAL\Driver\Mysqli\MysqliConnection;
+use Doctrine\DBAL\Driver\Mysqli\MysqliException;
use Doctrine\Tests\DbalFunctionalTestCase;
use const MYSQLI_OPT_CONNECT_TIMEOUT;
use function extension_loaded;
class ConnectionTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('mysqli')) {
$this->markTestSkipped('mysqli is not installed.');
@@ -25,12 +26,12 @@ protected function setUp()
$this->markTestSkipped('MySQLi only test.');
}
- protected function tearDown()
+ protected function tearDown() : void
{
parent::tearDown();
}
- public function testDriverOptions()
+ public function testDriverOptions() : void
{
$driverOptions = [MYSQLI_OPT_CONNECT_TIMEOUT => 1];
@@ -38,15 +39,14 @@ public function testDriverOptions()
self::assertInstanceOf(MysqliConnection::class, $connection);
}
- /**
- * @expectedException \Doctrine\DBAL\Driver\Mysqli\MysqliException
- */
- public function testUnsupportedDriverOption()
+ public function testUnsupportedDriverOption() : void
{
+ $this->expectException(MysqliException::class);
+
$this->getConnection(['hello' => 'world']); // use local infile
}
- public function testPing()
+ public function testPing() : void
{
$conn = $this->getConnection([]);
self::assertTrue($conn->ping());
@@ -55,7 +55,7 @@ public function testPing()
/**
* @param mixed[] $driverOptions
*/
- private function getConnection(array $driverOptions)
+ private function getConnection(array $driverOptions) : MysqliConnection
{
return new MysqliConnection(
[
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/Mysqli/DriverTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/Mysqli/DriverTest.php
index d7f02a40306..d4bbf9a1df7 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/Mysqli/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/Mysqli/DriverTest.php
@@ -2,13 +2,14 @@
namespace Doctrine\Tests\DBAL\Functional\Driver\Mysqli;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\Mysqli\Driver;
use Doctrine\Tests\DBAL\Functional\Driver\AbstractDriverTest;
use function extension_loaded;
class DriverTest extends AbstractDriverTest
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('mysqli')) {
$this->markTestSkipped('mysqli is not installed.');
@@ -26,7 +27,7 @@ protected function setUp()
/**
* {@inheritdoc}
*/
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/DriverTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/DriverTest.php
index a781b31007d..861ce650e76 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/DriverTest.php
@@ -2,13 +2,14 @@
namespace Doctrine\Tests\DBAL\Functional\Driver\OCI8;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\OCI8\Driver;
use Doctrine\Tests\DBAL\Functional\Driver\AbstractDriverTest;
use function extension_loaded;
class DriverTest extends AbstractDriverTest
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('oci8')) {
$this->markTestSkipped('oci8 is not installed.');
@@ -26,7 +27,7 @@ protected function setUp()
/**
* {@inheritdoc}
*/
- public function testConnectsWithoutDatabaseNameParameter()
+ public function testConnectsWithoutDatabaseNameParameter() : void
{
$this->markTestSkipped('Oracle does not support connecting without database name.');
}
@@ -34,7 +35,7 @@ public function testConnectsWithoutDatabaseNameParameter()
/**
* {@inheritdoc}
*/
- public function testReturnsDatabaseNameWithoutDatabaseNameParameter()
+ public function testReturnsDatabaseNameWithoutDatabaseNameParameter() : void
{
$this->markTestSkipped('Oracle does not support connecting without database name.');
}
@@ -42,7 +43,7 @@ public function testReturnsDatabaseNameWithoutDatabaseNameParameter()
/**
* {@inheritdoc}
*/
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/OCI8ConnectionTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/OCI8ConnectionTest.php
index 1c3226852d6..d6184316fac 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/OCI8ConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/OCI8ConnectionTest.php
@@ -13,7 +13,7 @@ class OCI8ConnectionTest extends DbalFunctionalTestCase
/** @var OCI8Connection */
protected $driverConnection;
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('oci8')) {
$this->markTestSkipped('oci8 is not installed.');
@@ -31,7 +31,7 @@ protected function setUp()
/**
* @group DBAL-2595
*/
- public function testLastInsertIdAcceptsFqn()
+ public function testLastInsertIdAcceptsFqn() : void
{
$platform = $this->connection->getDatabasePlatform();
$schemaManager = $this->connection->getSchemaManager();
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/StatementTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/StatementTest.php
index db6a4d552ca..8ecbed68082 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/StatementTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/OCI8/StatementTest.php
@@ -8,7 +8,7 @@
class StatementTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('oci8')) {
$this->markTestSkipped('oci8 is not installed.');
@@ -29,7 +29,7 @@ protected function setUp()
*
* @dataProvider queryConversionProvider
*/
- public function testQueryConversion($query, array $params, array $expected)
+ public function testQueryConversion(string $query, array $params, array $expected) : void
{
self::assertEquals(
$expected,
@@ -37,7 +37,10 @@ public function testQueryConversion($query, array $params, array $expected)
);
}
- public static function queryConversionProvider()
+ /**
+ * @return array>
+ */
+ public static function queryConversionProvider() : iterable
{
return [
'simple' => [
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOConnectionTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOConnectionTest.php
index 214f90700c1..6dfb1b85c3d 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOConnectionTest.php
@@ -3,9 +3,14 @@
namespace Doctrine\Tests\DBAL\Functional\Driver;
use Doctrine\DBAL\Driver\PDOConnection;
+use Doctrine\DBAL\Driver\PDOException;
+use Doctrine\DBAL\Driver\PDOOracle\Driver as PDOOracleDriver;
+use Doctrine\DBAL\Driver\PDOPgSql\Driver as PDOPgSQLDriver;
+use Doctrine\DBAL\Driver\PDOSqlsrv\Driver as PDOSQLSRVDriver;
use Doctrine\Tests\DbalFunctionalTestCase;
use PDO;
use function extension_loaded;
+use function get_class;
use function sprintf;
class PDOConnectionTest extends DbalFunctionalTestCase
@@ -17,7 +22,7 @@ class PDOConnectionTest extends DbalFunctionalTestCase
*/
protected $driverConnection;
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('PDO')) {
$this->markTestSkipped('PDO is not installed.');
@@ -34,68 +39,68 @@ protected function setUp()
$this->markTestSkipped('PDO connection only test.');
}
- protected function tearDown()
+ protected function tearDown() : void
{
$this->resetSharedConn();
parent::tearDown();
}
- public function testDoesNotRequireQueryForServerVersion()
+ public function testDoesNotRequireQueryForServerVersion() : void
{
self::assertFalse($this->driverConnection->requiresQueryForServerVersion());
}
- /**
- * @expectedException \Doctrine\DBAL\Driver\PDOException
- */
- public function testThrowsWrappedExceptionOnConstruct()
+ public function testThrowsWrappedExceptionOnConstruct() : void
{
+ $this->expectException(PDOException::class);
+
new PDOConnection('foo');
}
/**
* @group DBAL-1022
- * @expectedException \Doctrine\DBAL\Driver\PDOException
*/
- public function testThrowsWrappedExceptionOnExec()
+ public function testThrowsWrappedExceptionOnExec() : void
{
+ $this->expectException(PDOException::class);
+
$this->driverConnection->exec('foo');
}
- /**
- * @expectedException \Doctrine\DBAL\Driver\PDOException
- */
- public function testThrowsWrappedExceptionOnPrepare()
+ public function testThrowsWrappedExceptionOnPrepare() : void
{
- if ($this->connection->getDriver()->getName() === 'pdo_sqlsrv') {
+ $driver = $this->connection->getDriver();
+
+ if ($driver instanceof PDOSQLSRVDriver) {
$this->markTestSkipped('pdo_sqlsrv does not allow setting PDO::ATTR_EMULATE_PREPARES at connection level.');
}
+ // Some PDO adapters do not check the query server-side
+ // even though emulated prepared statements are disabled,
+ // so an exception is thrown only eventually.
+ if ($driver instanceof PDOOracleDriver
+ || $driver instanceof PDOPgSQLDriver
+ ) {
+ self::markTestSkipped(sprintf(
+ 'The underlying implementation of the %s driver does not check the query to be prepared server-side.',
+ get_class($driver)
+ ));
+ }
+
// Emulated prepared statements have to be disabled for this test
// so that PDO actually communicates with the database server to check the query.
$this->driverConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
- $this->driverConnection->prepare('foo');
+ $this->expectException(PDOException::class);
- // Some PDO adapters like PostgreSQL do not check the query server-side
- // even though emulated prepared statements are disabled,
- // so an exception is thrown only eventually.
- // Skip the test otherwise.
- $this->markTestSkipped(
- sprintf(
- 'The PDO adapter %s does not check the query to be prepared server-side, ' .
- 'so no assertions can be made.',
- $this->connection->getDriver()->getName()
- )
- );
+ $this->driverConnection->prepare('foo');
}
- /**
- * @expectedException \Doctrine\DBAL\Driver\PDOException
- */
- public function testThrowsWrappedExceptionOnQuery()
+ public function testThrowsWrappedExceptionOnQuery() : void
{
+ $this->expectException(PDOException::class);
+
$this->driverConnection->query('foo');
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOMySql/DriverTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOMySql/DriverTest.php
index cb0f9633201..7f77ea542f9 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOMySql/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOMySql/DriverTest.php
@@ -2,13 +2,14 @@
namespace Doctrine\Tests\DBAL\Functional\Driver\PDOMySql;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\PDOMySql\Driver;
use Doctrine\Tests\DBAL\Functional\Driver\AbstractDriverTest;
use function extension_loaded;
class DriverTest extends AbstractDriverTest
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('pdo_mysql')) {
$this->markTestSkipped('pdo_mysql is not installed.');
@@ -26,7 +27,7 @@ protected function setUp()
/**
* {@inheritdoc}
*/
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOOracle/DriverTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOOracle/DriverTest.php
index 604fbc8b123..b096fa47e94 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOOracle/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOOracle/DriverTest.php
@@ -2,13 +2,14 @@
namespace Doctrine\Tests\DBAL\Functional\Driver\PDOOracle;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\PDOOracle\Driver;
use Doctrine\Tests\DBAL\Functional\Driver\AbstractDriverTest;
use function extension_loaded;
class DriverTest extends AbstractDriverTest
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('PDO_OCI')) {
$this->markTestSkipped('PDO_OCI is not installed.');
@@ -26,7 +27,7 @@ protected function setUp()
/**
* {@inheritdoc}
*/
- public function testConnectsWithoutDatabaseNameParameter()
+ public function testConnectsWithoutDatabaseNameParameter() : void
{
$this->markTestSkipped('Oracle does not support connecting without database name.');
}
@@ -34,7 +35,7 @@ public function testConnectsWithoutDatabaseNameParameter()
/**
* {@inheritdoc}
*/
- public function testReturnsDatabaseNameWithoutDatabaseNameParameter()
+ public function testReturnsDatabaseNameWithoutDatabaseNameParameter() : void
{
$this->markTestSkipped('Oracle does not support connecting without database name.');
}
@@ -42,7 +43,7 @@ public function testReturnsDatabaseNameWithoutDatabaseNameParameter()
/**
* {@inheritdoc}
*/
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOPgSql/DriverTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOPgSql/DriverTest.php
index 289621c5eba..b5f9d3eda9d 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOPgSql/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOPgSql/DriverTest.php
@@ -3,6 +3,7 @@
namespace Doctrine\Tests\DBAL\Functional\Driver\PDOPgSql;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\PDOPgSql\Driver;
use Doctrine\Tests\DBAL\Functional\Driver\AbstractDriverTest;
use Doctrine\Tests\TestUtil;
@@ -13,7 +14,7 @@
class DriverTest extends AbstractDriverTest
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('pdo_pgsql')) {
$this->markTestSkipped('pdo_pgsql is not installed.');
@@ -31,7 +32,7 @@ protected function setUp()
/**
* @dataProvider getDatabaseParameter
*/
- public function testDatabaseParameters($databaseName, $defaultDatabaseName, $expectedDatabaseName)
+ public function testDatabaseParameters(?string $databaseName, ?string $defaultDatabaseName, ?string $expectedDatabaseName) : void
{
$params = $this->connection->getParams();
$params['dbname'] = $databaseName;
@@ -50,9 +51,12 @@ public function testDatabaseParameters($databaseName, $defaultDatabaseName, $exp
);
}
- public function getDatabaseParameter()
+ /**
+ * @return mixed[][]
+ */
+ public static function getDatabaseParameter() : iterable
{
- $params = TestUtil::getConnection()->getParams();
+ $params = TestUtil::getConnectionParams();
$realDatabaseName = $params['dbname'] ?? '';
$dummyDatabaseName = $realDatabaseName . 'a';
@@ -61,14 +65,14 @@ public function getDatabaseParameter()
[$realDatabaseName, null, $realDatabaseName],
[$realDatabaseName, $dummyDatabaseName, $realDatabaseName],
[null, $realDatabaseName, $realDatabaseName],
- [null, null, $this->getDatabaseNameForConnectionWithoutDatabaseNameParameter()],
+ [null, null, static::getDatabaseNameForConnectionWithoutDatabaseNameParameter()],
];
}
/**
* @group DBAL-1146
*/
- public function testConnectsWithApplicationNameParameter()
+ public function testConnectsWithApplicationNameParameter() : void
{
$parameters = $this->connection->getParams();
$parameters['application_name'] = 'doctrine';
@@ -100,7 +104,7 @@ public function testConnectsWithApplicationNameParameter()
/**
* {@inheritdoc}
*/
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
@@ -108,7 +112,7 @@ protected function createDriver()
/**
* {@inheritdoc}
*/
- protected function getDatabaseNameForConnectionWithoutDatabaseNameParameter()
+ protected static function getDatabaseNameForConnectionWithoutDatabaseNameParameter() : ?string
{
return 'postgres';
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOPgsqlConnectionTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOPgsqlConnectionTest.php
index 0893bed2e70..8336a3900d1 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOPgsqlConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOPgsqlConnectionTest.php
@@ -10,7 +10,7 @@
class PDOPgsqlConnectionTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('pdo_pgsql')) {
$this->markTestSkipped('pdo_pgsql is not loaded.');
@@ -26,13 +26,11 @@ protected function setUp()
}
/**
- * @param string $charset
- *
* @group DBAL-1183
* @group DBAL-1189
* @dataProvider getValidCharsets
*/
- public function testConnectsWithValidCharsetOption($charset)
+ public function testConnectsWithValidCharsetOption(string $charset) : void
{
$params = $this->connection->getParams();
$params['charset'] = $charset;
@@ -53,7 +51,7 @@ public function testConnectsWithValidCharsetOption($charset)
/**
* @return mixed[][]
*/
- public function getValidCharsets()
+ public static function getValidCharsets() : iterable
{
return [
['UTF8'],
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOSqlite/DriverTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOSqlite/DriverTest.php
index 36978d4b4fd..efc0382d85f 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOSqlite/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOSqlite/DriverTest.php
@@ -2,13 +2,14 @@
namespace Doctrine\Tests\DBAL\Functional\Driver\PDOSqlite;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\PDOSqlite\Driver;
use Doctrine\Tests\DBAL\Functional\Driver\AbstractDriverTest;
use function extension_loaded;
class DriverTest extends AbstractDriverTest
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('pdo_sqlite')) {
$this->markTestSkipped('pdo_sqlite is not installed.');
@@ -26,7 +27,7 @@ protected function setUp()
/**
* {@inheritdoc}
*/
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOSqlsrv/DriverTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOSqlsrv/DriverTest.php
index f125eab3515..d2dfd5925f5 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOSqlsrv/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/PDOSqlsrv/DriverTest.php
@@ -2,6 +2,7 @@
namespace Doctrine\Tests\DBAL\Functional\Driver\PDOSqlsrv;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\Driver\PDOSqlsrv\Driver;
use Doctrine\Tests\DBAL\Functional\Driver\AbstractDriverTest;
@@ -10,7 +11,7 @@
class DriverTest extends AbstractDriverTest
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('pdo_sqlsrv')) {
$this->markTestSkipped('pdo_sqlsrv is not installed.');
@@ -28,7 +29,7 @@ protected function setUp()
/**
* {@inheritdoc}
*/
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
@@ -36,7 +37,7 @@ protected function createDriver()
/**
* {@inheritdoc}
*/
- protected function getDatabaseNameForConnectionWithoutDatabaseNameParameter()
+ protected static function getDatabaseNameForConnectionWithoutDatabaseNameParameter() : ?string
{
return 'master';
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/ConnectionTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/ConnectionTest.php
index 63253a84408..4de7b7cde03 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/ConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/ConnectionTest.php
@@ -9,7 +9,7 @@
class ConnectionTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('sqlanywhere')) {
$this->markTestSkipped('sqlanywhere is not installed.');
@@ -24,7 +24,7 @@ protected function setUp()
$this->markTestSkipped('sqlanywhere only test.');
}
- public function testNonPersistentConnection()
+ public function testNonPersistentConnection() : void
{
$params = $this->connection->getParams();
$params['persistent'] = false;
@@ -36,7 +36,7 @@ public function testNonPersistentConnection()
self::assertTrue($conn->isConnected(), 'No SQLAnywhere-nonpersistent connection established');
}
- public function testPersistentConnection()
+ public function testPersistentConnection() : void
{
$params = $this->connection->getParams();
$params['persistent'] = true;
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/DriverTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/DriverTest.php
index 07d0189a88d..f2d54c62845 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/DriverTest.php
@@ -3,13 +3,14 @@
namespace Doctrine\Tests\DBAL\Functional\Driver\SQLAnywhere;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\SQLAnywhere\Driver;
use Doctrine\Tests\DBAL\Functional\Driver\AbstractDriverTest;
use function extension_loaded;
class DriverTest extends AbstractDriverTest
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('sqlanywhere')) {
$this->markTestSkipped('sqlanywhere is not installed.');
@@ -24,7 +25,7 @@ protected function setUp()
$this->markTestSkipped('sqlanywhere only test.');
}
- public function testReturnsDatabaseNameWithoutDatabaseNameParameter()
+ public function testReturnsDatabaseNameWithoutDatabaseNameParameter() : void
{
$params = $this->connection->getParams();
unset($params['dbname']);
@@ -38,13 +39,13 @@ public function testReturnsDatabaseNameWithoutDatabaseNameParameter()
// SQL Anywhere has no "default" database. The name of the default database
// is defined on server startup and therefore can be arbitrary.
- self::assertInternalType('string', $this->driver->getDatabase($connection));
+ self::assertIsString($this->driver->getDatabase($connection));
}
/**
* {@inheritdoc}
*/
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/StatementTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/StatementTest.php
index 3cf5c282ea0..c09eb0a5d56 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/StatementTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLAnywhere/StatementTest.php
@@ -9,7 +9,7 @@
class StatementTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('sqlanywhere')) {
$this->markTestSkipped('sqlanywhere is not installed.');
@@ -24,7 +24,7 @@ protected function setUp()
$this->markTestSkipped('sqlanywhere only test.');
}
- public function testNonPersistentStatement()
+ public function testNonPersistentStatement() : void
{
$params = $this->connection->getParams();
$params['persistent'] = false;
@@ -39,7 +39,7 @@ public function testNonPersistentStatement()
self::assertTrue($prepStmt->execute(), ' Statement non-persistent failed');
}
- public function testPersistentStatement()
+ public function testPersistentStatement() : void
{
$params = $this->connection->getParams();
$params['persistent'] = true;
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLSrv/DriverTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLSrv/DriverTest.php
index b09d7339fc9..eb9931a43dc 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLSrv/DriverTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLSrv/DriverTest.php
@@ -2,13 +2,14 @@
namespace Doctrine\Tests\DBAL\Functional\Driver\SQLSrv;
+use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\SQLSrv\Driver;
use Doctrine\Tests\DBAL\Functional\Driver\AbstractDriverTest;
use function extension_loaded;
class DriverTest extends AbstractDriverTest
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('sqlsrv')) {
$this->markTestSkipped('sqlsrv is not installed.');
@@ -26,7 +27,7 @@ protected function setUp()
/**
* {@inheritdoc}
*/
- protected function createDriver()
+ protected function createDriver() : DriverInterface
{
return new Driver();
}
@@ -34,7 +35,7 @@ protected function createDriver()
/**
* {@inheritdoc}
*/
- protected function getDatabaseNameForConnectionWithoutDatabaseNameParameter()
+ protected static function getDatabaseNameForConnectionWithoutDatabaseNameParameter() : ?string
{
return 'master';
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLSrv/StatementTest.php b/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLSrv/StatementTest.php
index 38df9cb5181..4e34f693c0c 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLSrv/StatementTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Driver/SQLSrv/StatementTest.php
@@ -9,7 +9,7 @@
class StatementTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('sqlsrv')) {
self::markTestSkipped('sqlsrv is not installed.');
@@ -24,7 +24,7 @@ protected function setUp()
self::markTestSkipped('sqlsrv only test');
}
- public function testFailureToPrepareResultsInException()
+ public function testFailureToPrepareResultsInException() : void
{
// use the driver connection directly to avoid having exception wrapped
$stmt = $this->connection->getWrappedConnection()->prepare(null);
diff --git a/tests/Doctrine/Tests/DBAL/Functional/ExceptionTest.php b/tests/Doctrine/Tests/DBAL/Functional/ExceptionTest.php
index 5ca5e95894f..3b9649d5595 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/ExceptionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/ExceptionTest.php
@@ -14,11 +14,14 @@
use Doctrine\DBAL\Schema\Table;
use Doctrine\Tests\DbalFunctionalTestCase;
use Throwable;
+use const PHP_OS;
use function array_merge;
use function assert;
use function chmod;
-use function defined;
+use function exec;
use function file_exists;
+use function posix_geteuid;
+use function posix_getpwuid;
use function sprintf;
use function sys_get_temp_dir;
use function touch;
@@ -27,7 +30,7 @@
class ExceptionTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -38,7 +41,7 @@ protected function setUp()
$this->markTestSkipped('Driver does not support special exception handling.');
}
- public function testPrimaryConstraintViolationException()
+ public function testPrimaryConstraintViolationException() : void
{
$table = new Table('duplicatekey_table');
$table->addColumn('id', 'integer', []);
@@ -52,7 +55,7 @@ public function testPrimaryConstraintViolationException()
$this->connection->insert('duplicatekey_table', ['id' => 1]);
}
- public function testTableNotFoundException()
+ public function testTableNotFoundException() : void
{
$sql = 'SELECT * FROM unknown_table';
@@ -60,7 +63,7 @@ public function testTableNotFoundException()
$this->connection->executeQuery($sql);
}
- public function testTableExistsException()
+ public function testTableExistsException() : void
{
$schemaManager = $this->connection->getSchemaManager();
$table = new Table('alreadyexist_table');
@@ -72,7 +75,7 @@ public function testTableExistsException()
$schemaManager->createTable($table);
}
- public function testForeignKeyConstraintViolationExceptionOnInsert()
+ public function testForeignKeyConstraintViolationExceptionOnInsert() : void
{
if (! $this->connection->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('Only fails on platforms with foreign key constraints.');
@@ -106,7 +109,7 @@ public function testForeignKeyConstraintViolationExceptionOnInsert()
$this->tearDownForeignKeyConstraintViolationExceptionTest();
}
- public function testForeignKeyConstraintViolationExceptionOnUpdate()
+ public function testForeignKeyConstraintViolationExceptionOnUpdate() : void
{
if (! $this->connection->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('Only fails on platforms with foreign key constraints.');
@@ -140,7 +143,7 @@ public function testForeignKeyConstraintViolationExceptionOnUpdate()
$this->tearDownForeignKeyConstraintViolationExceptionTest();
}
- public function testForeignKeyConstraintViolationExceptionOnDelete()
+ public function testForeignKeyConstraintViolationExceptionOnDelete() : void
{
if (! $this->connection->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('Only fails on platforms with foreign key constraints.');
@@ -174,7 +177,7 @@ public function testForeignKeyConstraintViolationExceptionOnDelete()
$this->tearDownForeignKeyConstraintViolationExceptionTest();
}
- public function testForeignKeyConstraintViolationExceptionOnTruncate()
+ public function testForeignKeyConstraintViolationExceptionOnTruncate() : void
{
$platform = $this->connection->getDatabasePlatform();
@@ -210,7 +213,7 @@ public function testForeignKeyConstraintViolationExceptionOnTruncate()
$this->tearDownForeignKeyConstraintViolationExceptionTest();
}
- public function testNotNullConstraintViolationException()
+ public function testNotNullConstraintViolationException() : void
{
$schema = new Schema();
@@ -227,7 +230,7 @@ public function testNotNullConstraintViolationException()
$this->connection->insert('notnull_table', ['id' => 1, 'value' => null]);
}
- public function testInvalidFieldNameException()
+ public function testInvalidFieldNameException() : void
{
$schema = new Schema();
@@ -242,7 +245,7 @@ public function testInvalidFieldNameException()
$this->connection->insert('bad_fieldname_table', ['name' => 5]);
}
- public function testNonUniqueFieldNameException()
+ public function testNonUniqueFieldNameException() : void
{
$schema = new Schema();
@@ -261,7 +264,7 @@ public function testNonUniqueFieldNameException()
$this->connection->executeQuery($sql);
}
- public function testUniqueConstraintViolationException()
+ public function testUniqueConstraintViolationException() : void
{
$schema = new Schema();
@@ -278,7 +281,7 @@ public function testUniqueConstraintViolationException()
$this->connection->insert('unique_field_table', ['id' => 5]);
}
- public function testSyntaxErrorException()
+ public function testSyntaxErrorException() : void
{
$table = new Table('syntax_error_table');
$table->addColumn('id', 'integer', []);
@@ -291,25 +294,28 @@ public function testSyntaxErrorException()
$this->connection->executeQuery($sql);
}
- /**
- * @dataProvider getSqLiteOpenConnection
- */
- public function testConnectionExceptionSqLite($mode, $exceptionClass)
+ public function testConnectionExceptionSqLite() : void
{
- if ($this->connection->getDatabasePlatform() instanceof SqlitePlatform) {
+ if (! ($this->connection->getDatabasePlatform() instanceof SqlitePlatform)) {
$this->markTestSkipped('Only fails this way on sqlite');
}
+ // mode 0 is considered read-only on Windows
+ $mode = PHP_OS === 'Linux' ? 0444 : 0000;
+
$filename = sprintf('%s/%s', sys_get_temp_dir(), 'doctrine_failed_connection_' . $mode . '.db');
if (file_exists($filename)) {
- chmod($filename, 0200); // make the file writable again, so it can be removed on Windows
- unlink($filename);
+ $this->cleanupReadOnlyFile($filename);
}
touch($filename);
chmod($filename, $mode);
+ if ($this->isLinuxRoot()) {
+ exec(sprintf('chattr +i %s', $filename));
+ }
+
$params = [
'driver' => 'pdo_sqlite',
'path' => $filename,
@@ -320,25 +326,30 @@ public function testConnectionExceptionSqLite($mode, $exceptionClass)
$table = $schema->createTable('no_connection');
$table->addColumn('id', 'integer');
- $this->expectException($exceptionClass);
- foreach ($schema->toSql($conn->getDatabasePlatform()) as $sql) {
- $conn->exec($sql);
- }
- }
+ $this->expectException(Exception\ReadOnlyException::class);
+ $this->expectExceptionMessage(
+ <<toSql($conn->getDatabasePlatform()) as $sql) {
+ $conn->exec($sql);
+ }
+ } finally {
+ $this->cleanupReadOnlyFile($filename);
+ }
}
/**
+ * @param array $params
+ *
* @dataProvider getConnectionParams
*/
- public function testConnectionException($params)
+ public function testConnectionException(array $params) : void
{
$platform = $this->connection->getDatabasePlatform();
@@ -379,7 +390,10 @@ public function testConnectionException($params)
}
}
- public function getConnectionParams()
+ /**
+ * @return array>
+ */
+ public static function getConnectionParams() : iterable
{
return [
[['user' => 'not_existing']],
@@ -388,7 +402,7 @@ public function getConnectionParams()
];
}
- private function setUpForeignKeyConstraintViolationExceptionTest()
+ private function setUpForeignKeyConstraintViolationExceptionTest() : void
{
$schemaManager = $this->connection->getSchemaManager();
@@ -406,11 +420,26 @@ private function setUpForeignKeyConstraintViolationExceptionTest()
$schemaManager->createTable($owningTable);
}
- private function tearDownForeignKeyConstraintViolationExceptionTest()
+ private function tearDownForeignKeyConstraintViolationExceptionTest() : void
{
$schemaManager = $this->connection->getSchemaManager();
$schemaManager->dropTable('owning_table');
$schemaManager->dropTable('constraint_error_table');
}
+
+ private function isLinuxRoot() : bool
+ {
+ return PHP_OS === 'Linux' && posix_getpwuid(posix_geteuid())['name'] === 'root';
+ }
+
+ private function cleanupReadOnlyFile(string $filename) : void
+ {
+ if ($this->isLinuxRoot()) {
+ exec(sprintf('chattr -i %s', $filename));
+ }
+
+ chmod($filename, 0200); // make the file writable again, so it can be removed on Windows
+ unlink($filename);
+ }
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/LoggingTest.php b/tests/Doctrine/Tests/DBAL/Functional/LoggingTest.php
index 99ca533e742..aa63af708df 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/LoggingTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/LoggingTest.php
@@ -7,7 +7,7 @@
class LoggingTest extends DbalFunctionalTestCase
{
- public function testLogExecuteQuery()
+ public function testLogExecuteQuery() : void
{
$sql = $this->connection->getDatabasePlatform()->getDummySelectSQL();
@@ -21,7 +21,7 @@ public function testLogExecuteQuery()
$this->connection->executeQuery($sql, []);
}
- public function testLogExecuteUpdate()
+ public function testLogExecuteUpdate() : void
{
$this->markTestSkipped('Test breaks MySQL but works on all other platforms (Unbuffered Queries stuff).');
@@ -37,7 +37,7 @@ public function testLogExecuteUpdate()
$this->connection->executeUpdate($sql, []);
}
- public function testLogPrepareExecute()
+ public function testLogPrepareExecute() : void
{
$sql = $this->connection->getDatabasePlatform()->getDummySelectSQL();
diff --git a/tests/Doctrine/Tests/DBAL/Functional/MasterSlaveConnectionTest.php b/tests/Doctrine/Tests/DBAL/Functional/MasterSlaveConnectionTest.php
index 00dc7e876eb..2731ac995b8 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/MasterSlaveConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/MasterSlaveConnectionTest.php
@@ -20,7 +20,7 @@
*/
class MasterSlaveConnectionTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -98,7 +98,7 @@ public function testInheritCharsetFromMaster() : void
}
}
- public function testMasterOnConnect()
+ public function testMasterOnConnect() : void
{
$conn = $this->createMasterSlaveConnection();
@@ -109,7 +109,7 @@ public function testMasterOnConnect()
self::assertTrue($conn->isConnectedToMaster());
}
- public function testNoMasterOnExecuteQuery()
+ public function testNoMasterOnExecuteQuery() : void
{
$conn = $this->createMasterSlaveConnection();
@@ -121,7 +121,7 @@ public function testNoMasterOnExecuteQuery()
self::assertFalse($conn->isConnectedToMaster());
}
- public function testMasterOnWriteOperation()
+ public function testMasterOnWriteOperation() : void
{
$conn = $this->createMasterSlaveConnection();
$conn->insert('master_slave_table', ['test_int' => 30]);
@@ -139,7 +139,7 @@ public function testMasterOnWriteOperation()
/**
* @group DBAL-335
*/
- public function testKeepSlaveBeginTransactionStaysOnMaster()
+ public function testKeepSlaveBeginTransactionStaysOnMaster() : void
{
$conn = $this->createMasterSlaveConnection($keepSlave = true);
$conn->connect('slave');
@@ -160,7 +160,7 @@ public function testKeepSlaveBeginTransactionStaysOnMaster()
/**
* @group DBAL-335
*/
- public function testKeepSlaveInsertStaysOnMaster()
+ public function testKeepSlaveInsertStaysOnMaster() : void
{
$conn = $this->createMasterSlaveConnection($keepSlave = true);
$conn->connect('slave');
@@ -176,7 +176,7 @@ public function testKeepSlaveInsertStaysOnMaster()
self::assertFalse($conn->isConnectedToMaster());
}
- public function testMasterSlaveConnectionCloseAndReconnect()
+ public function testMasterSlaveConnectionCloseAndReconnect() : void
{
$conn = $this->createMasterSlaveConnection();
$conn->connect('master');
@@ -189,7 +189,7 @@ public function testMasterSlaveConnectionCloseAndReconnect()
self::assertTrue($conn->isConnectedToMaster());
}
- public function testQueryOnMaster()
+ public function testQueryOnMaster() : void
{
$conn = $this->createMasterSlaveConnection();
@@ -213,7 +213,7 @@ public function testQueryOnMaster()
self::assertEquals(1, $data[0]['num']);
}
- public function testQueryOnSlave()
+ public function testQueryOnSlave() : void
{
$conn = $this->createMasterSlaveConnection();
$conn->connect('slave');
diff --git a/tests/Doctrine/Tests/DBAL/Functional/ModifyLimitQueryTest.php b/tests/Doctrine/Tests/DBAL/Functional/ModifyLimitQueryTest.php
index 94fb02da547..a14f9b17582 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/ModifyLimitQueryTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/ModifyLimitQueryTest.php
@@ -13,7 +13,7 @@ class ModifyLimitQueryTest extends DbalFunctionalTestCase
/** @var bool */
private static $tableCreated = false;
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -36,7 +36,7 @@ protected function setUp()
$this->connection->exec($this->connection->getDatabasePlatform()->getTruncateTableSQL('modify_limit_table2'));
}
- public function testModifyLimitQuerySimpleQuery()
+ public function testModifyLimitQuerySimpleQuery() : void
{
$this->connection->insert('modify_limit_table', ['test_int' => 1]);
$this->connection->insert('modify_limit_table', ['test_int' => 2]);
@@ -51,7 +51,7 @@ public function testModifyLimitQuerySimpleQuery()
$this->assertLimitResult([2, 3, 4], $sql, null, 1);
}
- public function testModifyLimitQueryJoinQuery()
+ public function testModifyLimitQueryJoinQuery() : void
{
$this->connection->insert('modify_limit_table', ['test_int' => 1]);
$this->connection->insert('modify_limit_table', ['test_int' => 2]);
@@ -69,7 +69,7 @@ public function testModifyLimitQueryJoinQuery()
$this->assertLimitResult([2, 2], $sql, 2, 0);
}
- public function testModifyLimitQueryNonDeterministic()
+ public function testModifyLimitQueryNonDeterministic() : void
{
$this->connection->insert('modify_limit_table', ['test_int' => 1]);
$this->connection->insert('modify_limit_table', ['test_int' => 2]);
@@ -83,7 +83,7 @@ public function testModifyLimitQueryNonDeterministic()
$this->assertLimitResult([2, 1], $sql, 2, 2, false);
}
- public function testModifyLimitQueryGroupBy()
+ public function testModifyLimitQueryGroupBy() : void
{
$this->connection->insert('modify_limit_table', ['test_int' => 1]);
$this->connection->insert('modify_limit_table', ['test_int' => 2]);
@@ -103,7 +103,7 @@ public function testModifyLimitQueryGroupBy()
$this->assertLimitResult([2], $sql, 1, 1);
}
- public function testModifyLimitQuerySubSelect()
+ public function testModifyLimitQuerySubSelect() : void
{
$this->connection->insert('modify_limit_table', ['test_int' => 1]);
$this->connection->insert('modify_limit_table', ['test_int' => 2]);
@@ -117,7 +117,7 @@ public function testModifyLimitQuerySubSelect()
$this->assertLimitResult([2, 1], $sql, 2, 2);
}
- public function testModifyLimitQueryFromSubSelect()
+ public function testModifyLimitQueryFromSubSelect() : void
{
$this->connection->insert('modify_limit_table', ['test_int' => 1]);
$this->connection->insert('modify_limit_table', ['test_int' => 2]);
@@ -131,7 +131,7 @@ public function testModifyLimitQueryFromSubSelect()
$this->assertLimitResult([2, 1], $sql, 2, 2);
}
- public function testModifyLimitQueryLineBreaks()
+ public function testModifyLimitQueryLineBreaks() : void
{
$this->connection->insert('modify_limit_table', ['test_int' => 1]);
$this->connection->insert('modify_limit_table', ['test_int' => 2]);
@@ -151,7 +151,7 @@ public function testModifyLimitQueryLineBreaks()
$this->assertLimitResult([2], $sql, 1, 1);
}
- public function testModifyLimitQueryZeroOffsetNoLimit()
+ public function testModifyLimitQueryZeroOffsetNoLimit() : void
{
$this->connection->insert('modify_limit_table', ['test_int' => 1]);
$this->connection->insert('modify_limit_table', ['test_int' => 2]);
@@ -161,7 +161,10 @@ public function testModifyLimitQueryZeroOffsetNoLimit()
$this->assertLimitResult([1, 2], $sql, null, 0);
}
- public function assertLimitResult($expectedResults, $sql, $limit, $offset, $deterministic = true)
+ /**
+ * @param array $expectedResults
+ */
+ private function assertLimitResult(array $expectedResults, string $sql, ?int $limit, int $offset, bool $deterministic = true) : void
{
$p = $this->connection->getDatabasePlatform();
$data = [];
diff --git a/tests/Doctrine/Tests/DBAL/Functional/NamedParametersTest.php b/tests/Doctrine/Tests/DBAL/Functional/NamedParametersTest.php
index fec2e5944d6..33e116ec368 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/NamedParametersTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/NamedParametersTest.php
@@ -16,7 +16,10 @@
*/
class NamedParametersTest extends DbalFunctionalTestCase
{
- public function ticketProvider()
+ /**
+ * @return iterable>
+ */
+ public static function ticketProvider() : iterable
{
return [
[
@@ -147,7 +150,7 @@ public function ticketProvider()
];
}
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -201,14 +204,13 @@ protected function setUp()
}
/**
- * @param string $query
* @param mixed[] $params
* @param int[] $types
* @param int[] $expected
*
* @dataProvider ticketProvider
*/
- public function testTicket($query, $params, $types, $expected)
+ public function testTicket(string $query, array $params, array $types, array $expected) : void
{
$stmt = $this->connection->executeQuery($query, $params, $types);
$result = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
diff --git a/tests/Doctrine/Tests/DBAL/Functional/PDOStatementTest.php b/tests/Doctrine/Tests/DBAL/Functional/PDOStatementTest.php
index f1e5c5a229a..42b8104a9e7 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/PDOStatementTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/PDOStatementTest.php
@@ -10,7 +10,7 @@
class PDOStatementTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
if (! extension_loaded('pdo')) {
$this->markTestSkipped('PDO is not installed');
@@ -32,7 +32,7 @@ protected function setUp()
* @group legacy
* @expectedDeprecation Using a PDO fetch mode or their combination (%d given) is deprecated and will cause an error in Doctrine 3.0
*/
- public function testPDOSpecificModeIsAccepted()
+ public function testPDOSpecificModeIsAccepted() : void
{
$this->connection->insert('stmt_test', [
'id' => 1,
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Platform/DefaultExpressionTest.php b/tests/Doctrine/Tests/DBAL/Functional/Platform/DefaultExpressionTest.php
index bddc884c105..5365693af43 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Platform/DefaultExpressionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Platform/DefaultExpressionTest.php
@@ -9,7 +9,7 @@
use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\DBAL\Platforms\OraclePlatform;
use Doctrine\DBAL\Schema\Table;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use Doctrine\Tests\DbalFunctionalTestCase;
use function sprintf;
@@ -23,7 +23,7 @@ public function testCurrentDate() : void
self::markTestSkipped('Not supported on MySQL');
}
- $this->assertDefaultExpression(Type::DATE, static function (AbstractPlatform $platform) : string {
+ $this->assertDefaultExpression(Types::DATE_MUTABLE, static function (AbstractPlatform $platform) : string {
return $platform->getCurrentDateSQL();
});
}
@@ -40,14 +40,14 @@ public function testCurrentTime() : void
self::markTestSkipped('Not supported on Oracle');
}
- $this->assertDefaultExpression(Type::TIME, static function (AbstractPlatform $platform) : string {
+ $this->assertDefaultExpression(Types::TIME_MUTABLE, static function (AbstractPlatform $platform) : string {
return $platform->getCurrentTimeSQL();
});
}
public function testCurrentTimestamp() : void
{
- $this->assertDefaultExpression(Type::DATETIME, static function (AbstractPlatform $platform) : string {
+ $this->assertDefaultExpression(Types::DATETIME_MUTABLE, static function (AbstractPlatform $platform) : string {
return $platform->getCurrentTimestampSQL();
});
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Platform/NewPrimaryKeyWithNewAutoIncrementColumnTest.php b/tests/Doctrine/Tests/DBAL/Functional/Platform/NewPrimaryKeyWithNewAutoIncrementColumnTest.php
new file mode 100644
index 00000000000..42e08f3f6d7
--- /dev/null
+++ b/tests/Doctrine/Tests/DBAL/Functional/Platform/NewPrimaryKeyWithNewAutoIncrementColumnTest.php
@@ -0,0 +1,70 @@
+getPlatform()->getName(), ['mysql'])) {
+ return;
+ }
+
+ $this->markTestSkipped('Restricted to MySQL.');
+ }
+
+ /**
+ * Ensures that the primary key is created within the same "alter table" statement that an auto-increment column
+ * is added to the table as part of the new primary key.
+ *
+ * Before the fix for this problem this resulted in a database error: (at least on mysql)
+ * SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto
+ * column and it must be defined as a key
+ */
+ public function testAlterPrimaryKeyToAutoIncrementColumn() : void
+ {
+ $schemaManager = $this->connection->getSchemaManager();
+ $schema = $schemaManager->createSchema();
+
+ $table = $schema->createTable('dbal2807');
+ $table->addColumn('initial_id', 'integer');
+ $table->setPrimaryKey(['initial_id']);
+
+ $schemaManager->dropAndCreateTable($table);
+
+ $newSchema = clone $schema;
+ $newTable = $newSchema->getTable($table->getName());
+ $newTable->addColumn('new_id', 'integer', ['autoincrement' => true]);
+ $newTable->dropPrimaryKey();
+ $newTable->setPrimaryKey(['new_id']);
+
+ $diff = (new Comparator())->compare($schema, $newSchema);
+
+ foreach ($diff->toSql($this->getPlatform()) as $sql) {
+ $this->connection->exec($sql);
+ }
+
+ $validationSchema = $schemaManager->createSchema();
+ $validationTable = $validationSchema->getTable($table->getName());
+
+ $this->assertTrue($validationTable->hasColumn('new_id'));
+ $this->assertTrue($validationTable->getColumn('new_id')->getAutoincrement());
+ $this->assertTrue($validationTable->hasPrimaryKey());
+ $this->assertSame(['new_id'], $validationTable->getPrimaryKeyColumns());
+ }
+
+ private function getPlatform() : AbstractPlatform
+ {
+ return $this->connection->getDatabasePlatform();
+ }
+}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/PortabilityTest.php b/tests/Doctrine/Tests/DBAL/Functional/PortabilityTest.php
index 33894dc55b8..72fb9dd2213 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/PortabilityTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/PortabilityTest.php
@@ -4,7 +4,6 @@
use Doctrine\DBAL\ColumnCase;
use Doctrine\DBAL\Connection;
-use Doctrine\DBAL\Driver\PDOSqlsrv\Driver;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\FetchMode;
use Doctrine\DBAL\Portability\Connection as ConnectionPortability;
@@ -21,7 +20,7 @@ class PortabilityTest extends DbalFunctionalTestCase
/** @var Connection */
private $portableConnection;
- protected function tearDown()
+ protected function tearDown() : void
{
if ($this->portableConnection) {
$this->portableConnection->close();
@@ -30,16 +29,10 @@ protected function tearDown()
parent::tearDown();
}
- /**
- * @param int $portabilityMode
- * @param int $case
- *
- * @return Connection
- */
private function getPortableConnection(
- $portabilityMode = ConnectionPortability::PORTABILITY_ALL,
- $case = ColumnCase::LOWER
- ) {
+ int $portabilityMode = ConnectionPortability::PORTABILITY_ALL,
+ int $case = ColumnCase::LOWER
+ ) : Connection {
if (! $this->portableConnection) {
$params = $this->connection->getParams();
@@ -68,7 +61,7 @@ private function getPortableConnection(
return $this->portableConnection;
}
- public function testFullFetchMode()
+ public function testFullFetchMode() : void
{
$rows = $this->getPortableConnection()->fetchAll('SELECT * FROM portability_table');
$this->assertFetchResultRows($rows);
@@ -94,7 +87,7 @@ public function testFullFetchMode()
}
}
- public function testConnFetchMode()
+ public function testConnFetchMode() : void
{
$conn = $this->getPortableConnection();
$conn->setFetchMode(FetchMode::ASSOCIATIVE);
@@ -119,7 +112,10 @@ public function testConnFetchMode()
}
}
- public function assertFetchResultRows($rows)
+ /**
+ * @param array> $rows
+ */
+ private function assertFetchResultRows(array $rows) : void
{
self::assertCount(2, $rows);
foreach ($rows as $row) {
@@ -127,7 +123,10 @@ public function assertFetchResultRows($rows)
}
}
- public function assertFetchResultRow($row)
+ /**
+ * @param array $row
+ */
+ public function assertFetchResultRow(array $row) : void
{
self::assertContains($row['test_int'], [1, 2], 'Primary key test_int should either be 1 or 2.');
self::assertArrayHasKey('test_string', $row, 'Case should be lowered.');
@@ -137,35 +136,11 @@ public function assertFetchResultRow($row)
}
/**
- * @requires extension pdo
- */
- public function testPortabilityPdoSqlServer()
- {
- $portability = ConnectionPortability::PORTABILITY_SQLSRV;
- $params = ['portability' => $portability];
-
- $driverMock = $this->getMockBuilder(Driver::class)
- ->setMethods(['connect'])
- ->getMock();
-
- $driverMock->expects($this->once())
- ->method('connect')
- ->will($this->returnValue(null));
-
- $connection = new ConnectionPortability($params, $driverMock);
-
- $connection->connect($params);
-
- self::assertEquals($portability, $connection->getPortability());
- }
-
- /**
- * @param string $field
* @param mixed[] $expected
*
* @dataProvider fetchAllColumnProvider
*/
- public function testFetchAllColumn($field, array $expected)
+ public function testFetchAllColumn(string $field, array $expected) : void
{
$conn = $this->getPortableConnection();
$stmt = $conn->query('SELECT ' . $field . ' FROM portability_table');
@@ -174,7 +149,10 @@ public function testFetchAllColumn($field, array $expected)
self::assertEquals($expected, $column);
}
- public static function fetchAllColumnProvider()
+ /**
+ * @return iterable>
+ */
+ public static function fetchAllColumnProvider() : iterable
{
return [
'int' => [
@@ -188,7 +166,7 @@ public static function fetchAllColumnProvider()
];
}
- public function testFetchAllNullColumn()
+ public function testFetchAllNullColumn() : void
{
$conn = $this->getPortableConnection();
$stmt = $conn->query('SELECT Test_Null FROM portability_table');
diff --git a/tests/Doctrine/Tests/DBAL/Functional/ResultCacheTest.php b/tests/Doctrine/Tests/DBAL/Functional/ResultCacheTest.php
index caf90927c3b..8d0a17c9b43 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/ResultCacheTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/ResultCacheTest.php
@@ -4,6 +4,7 @@
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\DBAL\Cache\QueryCacheProfile;
+use Doctrine\DBAL\Driver\ResultStatement;
use Doctrine\DBAL\FetchMode;
use Doctrine\DBAL\Logging\DebugStack;
use Doctrine\DBAL\Schema\Table;
@@ -20,13 +21,13 @@
*/
class ResultCacheTest extends DbalFunctionalTestCase
{
- /** @var int[][]|string[][] */
+ /** @var array> */
private $expectedResult = [['test_int' => 100, 'test_string' => 'foo'], ['test_int' => 200, 'test_string' => 'bar'], ['test_int' => 300, 'test_string' => 'baz']];
/** @var DebugStack */
private $sqlLogger;
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -49,52 +50,52 @@ protected function setUp()
$config->setResultCacheImpl($cache);
}
- protected function tearDown()
+ protected function tearDown() : void
{
$this->connection->getSchemaManager()->dropTable('caching');
parent::tearDown();
}
- public function testCacheFetchAssoc()
+ public function testCacheFetchAssoc() : void
{
- self::assertCacheNonCacheSelectSameFetchModeAreEqual(
+ $this->assertCacheNonCacheSelectSameFetchModeAreEqual(
$this->expectedResult,
FetchMode::ASSOCIATIVE
);
}
- public function testFetchNum()
+ public function testFetchNum() : void
{
$expectedResult = [];
foreach ($this->expectedResult as $v) {
$expectedResult[] = array_values($v);
}
- self::assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, FetchMode::NUMERIC);
+ $this->assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, FetchMode::NUMERIC);
}
- public function testFetchBoth()
+ public function testFetchBoth() : void
{
$expectedResult = [];
foreach ($this->expectedResult as $v) {
$expectedResult[] = array_merge($v, array_values($v));
}
- self::assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, FetchMode::MIXED);
+ $this->assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, FetchMode::MIXED);
}
- public function testFetchColumn()
+ public function testFetchColumn() : void
{
$expectedResult = [];
foreach ($this->expectedResult as $v) {
$expectedResult[] = array_shift($v);
}
- self::assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, FetchMode::COLUMN);
+ $this->assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, FetchMode::COLUMN);
}
- public function testMixingFetch()
+ public function testMixingFetch() : void
{
$numExpectedResult = [];
foreach ($this->expectedResult as $v) {
@@ -113,14 +114,14 @@ public function testMixingFetch()
self::assertEquals($numExpectedResult, $data);
}
- public function testIteratorFetch()
+ public function testIteratorFetch() : void
{
self::assertStandardAndIteratorFetchAreEqual(FetchMode::MIXED);
self::assertStandardAndIteratorFetchAreEqual(FetchMode::ASSOCIATIVE);
self::assertStandardAndIteratorFetchAreEqual(FetchMode::NUMERIC);
}
- public function assertStandardAndIteratorFetchAreEqual($fetchMode)
+ private function assertStandardAndIteratorFetchAreEqual(int $fetchMode) : void
{
$stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
$data = $this->hydrateStmt($stmt, $fetchMode);
@@ -131,7 +132,7 @@ public function assertStandardAndIteratorFetchAreEqual($fetchMode)
self::assertEquals($data, $data_iterator);
}
- public function testDontCloseNoCache()
+ public function testDontCloseNoCache() : void
{
$stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
@@ -152,7 +153,7 @@ public function testDontCloseNoCache()
self::assertCount(2, $this->sqlLogger->queries);
}
- public function testDontFinishNoCache()
+ public function testDontFinishNoCache() : void
{
$stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
@@ -166,7 +167,7 @@ public function testDontFinishNoCache()
self::assertCount(2, $this->sqlLogger->queries);
}
- public function testFetchAllAndFinishSavesCache()
+ public function testFetchAllAndFinishSavesCache() : void
{
$layerCache = new ArrayCache();
$stmt = $this->connection->executeQuery('SELECT * FROM caching WHERE test_int > 500', [], [], new QueryCacheProfile(10, 'testcachekey', $layerCache));
@@ -192,7 +193,10 @@ public function testFetchAllColumn() : void
self::assertEquals([1], $stmt->fetchAll(FetchMode::COLUMN));
}
- public function assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, $fetchMode)
+ /**
+ * @param array> $expectedResult
+ */
+ private function assertCacheNonCacheSelectSameFetchModeAreEqual(array $expectedResult, int $fetchMode) : void
{
$stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
@@ -208,7 +212,7 @@ public function assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult,
self::assertCount(1, $this->sqlLogger->queries, 'just one dbal hit');
}
- public function testEmptyResultCache()
+ public function testEmptyResultCache() : void
{
$stmt = $this->connection->executeQuery('SELECT * FROM caching WHERE test_int > 500', [], [], new QueryCacheProfile(10, 'emptycachekey'));
$data = $this->hydrateStmt($stmt);
@@ -219,7 +223,7 @@ public function testEmptyResultCache()
self::assertCount(1, $this->sqlLogger->queries, 'just one dbal hit');
}
- public function testChangeCacheImpl()
+ public function testChangeCacheImpl() : void
{
$stmt = $this->connection->executeQuery('SELECT * FROM caching WHERE test_int > 500', [], [], new QueryCacheProfile(10, 'emptycachekey'));
$data = $this->hydrateStmt($stmt);
@@ -232,17 +236,24 @@ public function testChangeCacheImpl()
self::assertCount(1, $secondCache->fetch('emptycachekey'));
}
- private function hydrateStmt($stmt, $fetchMode = FetchMode::ASSOCIATIVE)
+ /**
+ * @return array
+ */
+ private function hydrateStmt(ResultStatement $stmt, int $fetchMode = FetchMode::ASSOCIATIVE) : array
{
$data = [];
while ($row = $stmt->fetch($fetchMode)) {
$data[] = is_array($row) ? array_change_key_case($row, CASE_LOWER) : $row;
}
$stmt->closeCursor();
+
return $data;
}
- private function hydrateStmtIterator($stmt, $fetchMode = FetchMode::ASSOCIATIVE)
+ /**
+ * @return array
+ */
+ private function hydrateStmtIterator(ResultStatement $stmt, int $fetchMode = FetchMode::ASSOCIATIVE) : array
{
$data = [];
$stmt->setFetchMode($fetchMode);
@@ -250,6 +261,7 @@ private function hydrateStmtIterator($stmt, $fetchMode = FetchMode::ASSOCIATIVE)
$data[] = is_array($row) ? array_change_key_case($row, CASE_LOWER) : $row;
}
$stmt->closeCursor();
+
return $data;
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/ComparatorTest.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/ComparatorTest.php
index 0feb30fa5ba..13503e3187b 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Schema/ComparatorTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/ComparatorTest.php
@@ -17,7 +17,7 @@ class ComparatorTest extends DbalFunctionalTestCase
/** @var Comparator */
private $comparator;
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/Db2SchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/Db2SchemaManagerTest.php
index 102fd1bb495..330198e9ca9 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Schema/Db2SchemaManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/Db2SchemaManagerTest.php
@@ -10,7 +10,7 @@ class Db2SchemaManagerTest extends SchemaManagerFunctionalTestCase
/**
* @group DBAL-939
*/
- public function testGetBooleanColumn()
+ public function testGetBooleanColumn() : void
{
$table = new Table('boolean_column_test');
$table->addColumn('bool', 'boolean');
@@ -27,7 +27,7 @@ public function testGetBooleanColumn()
self::assertSame("That's a comment", $columns['bool_commented']->getComment());
}
- public function testListTableWithBinary()
+ public function testListTableWithBinary() : void
{
self::markTestSkipped('Binary data type is currently not supported on DB2 LUW');
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/DefaultValueTest.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/DefaultValueTest.php
new file mode 100644
index 00000000000..3dd362e2263
--- /dev/null
+++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/DefaultValueTest.php
@@ -0,0 +1,155 @@
+addColumn('id', 'integer');
+
+ foreach (self::columnProvider() as [$name, $default]) {
+ $table->addColumn($name, 'string', [
+ 'default' => $default,
+ 'notnull' => false,
+ ]);
+ }
+
+ $this->connection->getSchemaManager()
+ ->dropAndCreateTable($table);
+
+ $this->connection->insert('default_value', ['id' => 1]);
+ }
+
+ /**
+ * @param mixed $expectedDefault
+ *
+ * @dataProvider columnProvider
+ */
+ public function testEscapedDefaultValueCanBeIntrospected(string $name, ?string $expectedDefault) : void
+ {
+ self::assertSame(
+ $expectedDefault,
+ $this->connection
+ ->getSchemaManager()
+ ->listTableDetails('default_value')
+ ->getColumn($name)
+ ->getDefault()
+ );
+ }
+
+ /**
+ * @param mixed $expectedDefault
+ *
+ * @dataProvider columnProvider
+ */
+ public function testEscapedDefaultValueCanBeInserted(string $name, ?string $expectedDefault) : void
+ {
+ $value = $this->connection->fetchColumn(
+ sprintf('SELECT %s FROM default_value', $name)
+ );
+
+ self::assertSame($expectedDefault, $value);
+ }
+
+ /**
+ * Returns potential escaped literals from all platforms combined.
+ *
+ * @see https://dev.mysql.com/doc/refman/5.7/en/string-literals.html
+ * @see http://www.sqlite.org/lang_expr.html
+ * @see https://www.postgresql.org/docs/9.6/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-ESCAPE
+ *
+ * @return mixed[][]
+ */
+ public static function columnProvider() : iterable
+ {
+ return [
+ 'Single quote' => [
+ 'single_quote',
+ "foo'bar",
+ ],
+ 'Single quote, doubled' => [
+ 'single_quote_doubled',
+ "foo''bar",
+ ],
+ 'Double quote' => [
+ 'double_quote',
+ 'foo"bar',
+ ],
+ 'Double quote, doubled' => [
+ 'double_quote_doubled',
+ 'foo""bar',
+ ],
+ 'Backspace' => [
+ 'backspace',
+ "foo\x08bar",
+ ],
+ 'New line' => [
+ 'new_line',
+ "foo\nbar",
+ ],
+ 'Carriage return' => [
+ 'carriage_return',
+ "foo\rbar",
+ ],
+ 'Tab' => [
+ 'tab',
+ "foo\tbar",
+ ],
+ 'Substitute' => [
+ 'substitute',
+ "foo\x1abar",
+ ],
+ 'Backslash' => [
+ 'backslash',
+ 'foo\\bar',
+ ],
+ 'Backslash, doubled' => [
+ 'backslash_doubled',
+ 'foo\\\\bar',
+ ],
+ 'Percent' => [
+ 'percent_sign',
+ 'foo%bar',
+ ],
+ 'Underscore' => [
+ 'underscore',
+ 'foo_bar',
+ ],
+ 'NULL string' => [
+ 'null_string',
+ 'NULL',
+ ],
+ 'NULL value' => [
+ 'null_value',
+ null,
+ ],
+ 'SQL expression' => [
+ 'sql_expression',
+ "'; DROP DATABASE doctrine --",
+ ],
+ 'No double conversion' => [
+ 'no_double_conversion',
+ "\\'",
+ ],
+ ];
+ }
+}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/DrizzleSchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/DrizzleSchemaManagerTest.php
index 070e2173d63..422740476da 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Schema/DrizzleSchemaManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/DrizzleSchemaManagerTest.php
@@ -7,7 +7,7 @@
class DrizzleSchemaManagerTest extends SchemaManagerFunctionalTestCase
{
- public function testListTableWithBinary()
+ public function testListTableWithBinary() : void
{
$tableName = 'test_binary_table';
@@ -28,7 +28,7 @@ public function testListTableWithBinary()
self::assertFalse($table->getColumn('column_binary')->getFixed());
}
- public function testColumnCollation()
+ public function testColumnCollation() : void
{
$table = new Table('test_collation');
$table->addOption('collate', $collation = 'utf8_unicode_ci');
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/MySqlSchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/MySqlSchemaManagerTest.php
index 5bf0ad1712f..cf636a797ff 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Schema/MySqlSchemaManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/MySqlSchemaManagerTest.php
@@ -8,14 +8,14 @@
use Doctrine\DBAL\Schema\Comparator;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
+use Doctrine\DBAL\Types\BlobType;
use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use Doctrine\Tests\Types\MySqlPointType;
-use function implode;
-use function sprintf;
class MySqlSchemaManagerTest extends SchemaManagerFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -28,7 +28,7 @@ protected function setUp()
Type::addType('point', MySqlPointType::class);
}
- public function testSwitchPrimaryKeyColumns()
+ public function testSwitchPrimaryKeyColumns() : void
{
$tableOld = new Table('switch_primary_key_columns');
$tableOld->addColumn('foo_id', 'integer');
@@ -50,7 +50,7 @@ public function testSwitchPrimaryKeyColumns()
self::assertContains('foo_id', $primaryKey);
}
- public function testDiffTableBug()
+ public function testDiffTableBug() : void
{
$schema = new Schema();
$table = $schema->createTable('diffbug_routing_translations');
@@ -73,7 +73,7 @@ public function testDiffTableBug()
self::assertFalse($diff, 'no changes expected.');
}
- public function testFulltextIndex()
+ public function testFulltextIndex() : void
{
$table = new Table('fulltext_index');
$table->addColumn('text', 'text');
@@ -90,7 +90,7 @@ public function testFulltextIndex()
self::assertTrue($indexes['f_index']->hasFlag('fulltext'));
}
- public function testSpatialIndex()
+ public function testSpatialIndex() : void
{
$table = new Table('spatial_index');
$table->addColumn('point', 'point');
@@ -123,7 +123,7 @@ public function testIndexWithLength() : void
/**
* @group DBAL-400
*/
- public function testAlterTableAddPrimaryKey()
+ public function testAlterTableAddPrimaryKey() : void
{
$table = new Table('alter_table_add_pk');
$table->addColumn('id', 'integer');
@@ -149,7 +149,7 @@ public function testAlterTableAddPrimaryKey()
/**
* @group DBAL-464
*/
- public function testDropPrimaryKeyWithAutoincrementColumn()
+ public function testDropPrimaryKeyWithAutoincrementColumn() : void
{
$table = new Table('drop_primary_key');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -175,7 +175,7 @@ public function testDropPrimaryKeyWithAutoincrementColumn()
/**
* @group DBAL-789
*/
- public function testDoesNotPropagateDefaultValuesForUnsupportedColumnTypes()
+ public function testDoesNotPropagateDefaultValuesForUnsupportedColumnTypes() : void
{
if ($this->schemaManager->getDatabasePlatform() instanceof MariaDb1027Platform) {
$this->markTestSkipped(
@@ -214,7 +214,60 @@ public function testDoesNotPropagateDefaultValuesForUnsupportedColumnTypes()
self::assertFalse($onlineTable->getColumn('def_blob_null')->getNotnull());
}
- public function testColumnCollation()
+ public function testColumnCharset() : void
+ {
+ $table = new Table('test_column_charset');
+ $table->addColumn('id', 'integer');
+ $table->addColumn('no_charset', 'text');
+ $table->addColumn('foo', 'text')->setPlatformOption('charset', 'ascii');
+ $table->addColumn('bar', 'text')->setPlatformOption('charset', 'latin1');
+ $this->schemaManager->dropAndCreateTable($table);
+
+ $columns = $this->schemaManager->listTableColumns('test_column_charset');
+
+ self::assertFalse($columns['id']->hasPlatformOption('charset'));
+ self::assertEquals('utf8', $columns['no_charset']->getPlatformOption('charset'));
+ self::assertEquals('ascii', $columns['foo']->getPlatformOption('charset'));
+ self::assertEquals('latin1', $columns['bar']->getPlatformOption('charset'));
+ }
+
+ public function testAlterColumnCharset() : void
+ {
+ $tableName = 'test_alter_column_charset';
+
+ $table = new Table($tableName);
+ $table->addColumn('col_text', 'text')->setPlatformOption('charset', 'utf8');
+
+ $this->schemaManager->dropAndCreateTable($table);
+
+ $diffTable = clone $table;
+ $diffTable->getColumn('col_text')->setPlatformOption('charset', 'ascii');
+
+ $comparator = new Comparator();
+
+ $this->schemaManager->alterTable($comparator->diffTable($table, $diffTable));
+
+ $table = $this->schemaManager->listTableDetails($tableName);
+
+ self::assertEquals('ascii', $table->getColumn('col_text')->getPlatformOption('charset'));
+ }
+
+ public function testColumnCharsetChange() : void
+ {
+ $table = new Table('test_column_charset_change');
+ $table->addColumn('col_string', 'string')->setLength(100)->setNotnull(true)->setPlatformOption('charset', 'utf8');
+
+ $diffTable = clone $table;
+ $diffTable->getColumn('col_string')->setPlatformOption('charset', 'ascii');
+
+ $fromSchema = new Schema([$table]);
+ $toSchema = new Schema([$diffTable]);
+
+ $diff = $fromSchema->getMigrateToSql($toSchema, $this->connection->getDatabasePlatform());
+ self::assertContains('ALTER TABLE test_column_charset_change CHANGE col_string col_string VARCHAR(100) CHARACTER SET ascii NOT NULL', $diff);
+ }
+
+ public function testColumnCollation() : void
{
$table = new Table('test_collation');
$table->addOption('collate', $collation = 'latin1_swedish_ci');
@@ -223,6 +276,7 @@ public function testColumnCollation()
$table->addColumn('text', 'text');
$table->addColumn('foo', 'text')->setPlatformOption('collation', 'latin1_swedish_ci');
$table->addColumn('bar', 'text')->setPlatformOption('collation', 'utf8_general_ci');
+ $table->addColumn('baz', 'text')->setPlatformOption('collation', 'binary');
$this->schemaManager->dropAndCreateTable($table);
$columns = $this->schemaManager->listTableColumns('test_collation');
@@ -231,12 +285,13 @@ public function testColumnCollation()
self::assertEquals('latin1_swedish_ci', $columns['text']->getPlatformOption('collation'));
self::assertEquals('latin1_swedish_ci', $columns['foo']->getPlatformOption('collation'));
self::assertEquals('utf8_general_ci', $columns['bar']->getPlatformOption('collation'));
+ self::assertInstanceOf(BlobType::class, $columns['baz']->getType());
}
/**
* @group DBAL-843
*/
- public function testListLobTypeColumns()
+ public function testListLobTypeColumns() : void
{
$tableName = 'lob_type_columns';
$table = new Table($tableName);
@@ -295,7 +350,7 @@ public function testListLobTypeColumns()
/**
* @group DBAL-423
*/
- public function testDiffListGuidTableColumn()
+ public function testDiffListGuidTableColumn() : void
{
$offlineTable = new Table('list_guid_table_column');
$offlineTable->addColumn('col_guid', 'guid');
@@ -315,7 +370,7 @@ public function testDiffListGuidTableColumn()
/**
* @group DBAL-1082
*/
- public function testListDecimalTypeColumns()
+ public function testListDecimalTypeColumns() : void
{
$tableName = 'test_list_decimal_columns';
$table = new Table($tableName);
@@ -336,7 +391,7 @@ public function testListDecimalTypeColumns()
/**
* @group DBAL-1082
*/
- public function testListFloatTypeColumns()
+ public function testListFloatTypeColumns() : void
{
$tableName = 'test_list_float_columns';
$table = new Table($tableName);
@@ -362,7 +417,7 @@ public function testJsonColumnType() : void
$columns = $this->schemaManager->listTableColumns('test_mysql_json');
- self::assertSame(Type::JSON, $columns['col_json']->getType()->getName());
+ self::assertSame(Types::JSON, $columns['col_json']->getType()->getName());
}
public function testColumnDefaultCurrentTimestamp() : void
@@ -388,7 +443,7 @@ public function testColumnDefaultCurrentTimestamp() : void
self::assertFalse($diff, 'Tables should be identical with column defaults.');
}
- public function testColumnDefaultsAreValid()
+ public function testColumnDefaultsAreValid() : void
{
$table = new Table('test_column_defaults_are_valid');
@@ -463,45 +518,6 @@ public function testColumnDefaultValuesCurrentTimeAndDate() : void
self::assertFalse($diff, 'Tables should be identical with column defauts time and date.');
}
- /**
- * Ensure default values (un-)escaping is properly done by mysql platforms.
- * The test is voluntarily relying on schema introspection due to current
- * doctrine limitations. Once #2850 is landed, this test can be removed.
- *
- * @see https://dev.mysql.com/doc/refman/5.7/en/string-literals.html
- */
- public function testEnsureDefaultsAreUnescapedFromSchemaIntrospection() : void
- {
- $platform = $this->schemaManager->getDatabasePlatform();
- $this->connection->query('DROP TABLE IF EXISTS test_column_defaults_with_create');
-
- $escapeSequences = [
- "\\0", // An ASCII NUL (X'00') character
- "\\'",
- "''", // Single quote
- '\\"',
- '""', // Double quote
- '\\b', // A backspace character
- '\\n', // A new-line character
- '\\r', // A carriage return character
- '\\t', // A tab character
- '\\Z', // ASCII 26 (Control+Z)
- '\\\\', // A backslash (\) character
- '\\%', // A percent (%) character
- '\\_', // An underscore (_) character
- ];
-
- $default = implode('+', $escapeSequences);
-
- $sql = sprintf(
- 'CREATE TABLE test_column_defaults_with_create(col1 VARCHAR(255) NULL DEFAULT %s)',
- $platform->quoteStringLiteral($default)
- );
- $this->connection->query($sql);
- $onlineTable = $this->schemaManager->listTableDetails('test_column_defaults_with_create');
- self::assertSame($default, $onlineTable->getColumn('col1')->getDefault());
- }
-
public function testEnsureTableOptionsAreReflectedInMetadata() : void
{
$this->connection->query('DROP TABLE IF EXISTS test_table_metadata');
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/OracleSchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/OracleSchemaManagerTest.php
index b366cc9c002..b2363b639f0 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Schema/OracleSchemaManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/OracleSchemaManagerTest.php
@@ -5,7 +5,7 @@
use Doctrine\DBAL\Schema;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Types\BinaryType;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use Doctrine\Tests\TestUtil;
use function array_map;
@@ -14,7 +14,7 @@ class OracleSchemaManagerTest extends SchemaManagerFunctionalTestCase
/** @var bool */
private static $privilegesGranted = false;
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -32,7 +32,7 @@ protected function setUp()
self::$privilegesGranted = true;
}
- public function testRenameTable()
+ public function testRenameTable() : void
{
$this->schemaManager->tryMethod('DropTable', 'list_tables_test');
$this->schemaManager->tryMethod('DropTable', 'list_tables_test_new_name');
@@ -45,7 +45,7 @@ public function testRenameTable()
self::assertHasTable($tables, 'list_tables_test_new_name');
}
- public function testListTableWithBinary()
+ public function testListTableWithBinary() : void
{
$tableName = 'test_binary_table';
@@ -70,7 +70,7 @@ public function testListTableWithBinary()
* @group DBAL-472
* @group DBAL-1001
*/
- public function testAlterTableColumnNotNull()
+ public function testAlterTableColumnNotNull() : void
{
$comparator = new Schema\Comparator();
$tableName = 'list_table_column_notnull';
@@ -102,7 +102,7 @@ public function testAlterTableColumnNotNull()
self::assertTrue($columns['bar']->getNotnull());
}
- public function testListDatabases()
+ public function testListDatabases() : void
{
// We need the temp connection that has privileges to create a database.
$sm = TestUtil::getTempConnection()->getSchemaManager();
@@ -118,7 +118,7 @@ public function testListDatabases()
/**
* @group DBAL-831
*/
- public function testListTableDetailsWithDifferentIdentifierQuotingRequirements()
+ public function testListTableDetailsWithDifferentIdentifierQuotingRequirements() : void
{
$primaryTableName = '"Primary_Table"';
$offlinePrimaryTable = new Schema\Table($primaryTableName);
@@ -226,13 +226,13 @@ public function testListTableDetailsWithDifferentIdentifierQuotingRequirements()
);
}
- public function testListTableColumnsSameTableNamesInDifferentSchemas()
+ public function testListTableColumnsSameTableNamesInDifferentSchemas() : void
{
$table = $this->createListTableColumns();
$this->schemaManager->dropAndCreateTable($table);
$otherTable = new Table($table->getName());
- $otherTable->addColumn('id', Type::STRING);
+ $otherTable->addColumn('id', Types::STRING);
TestUtil::getTempConnection()->getSchemaManager()->dropAndCreateTable($otherTable);
$columns = $this->schemaManager->listTableColumns($table->getName(), $this->connection->getUsername());
@@ -242,7 +242,7 @@ public function testListTableColumnsSameTableNamesInDifferentSchemas()
/**
* @group DBAL-1234
*/
- public function testListTableIndexesPrimaryKeyConstraintNameDiffersFromIndexName()
+ public function testListTableIndexesPrimaryKeyConstraintNameDiffersFromIndexName() : void
{
$table = new Table('list_table_indexes_pk_id_test');
$table->setSchemaConfig($this->schemaManager->createSchemaConfig());
@@ -265,7 +265,7 @@ public function testListTableIndexesPrimaryKeyConstraintNameDiffersFromIndexName
/**
* @group DBAL-2555
*/
- public function testListTableDateTypeColumns()
+ public function testListTableDateTypeColumns() : void
{
$table = new Table('tbl_date');
$table->addColumn('col_date', 'date');
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/PostgreSqlSchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/PostgreSqlSchemaManagerTest.php
index 864820b595c..35326968798 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Schema/PostgreSqlSchemaManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/PostgreSqlSchemaManagerTest.php
@@ -12,6 +12,7 @@
use Doctrine\DBAL\Types\BlobType;
use Doctrine\DBAL\Types\DecimalType;
use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use function array_map;
use function array_pop;
use function count;
@@ -19,7 +20,7 @@
class PostgreSqlSchemaManagerTest extends SchemaManagerFunctionalTestCase
{
- protected function tearDown()
+ protected function tearDown() : void
{
parent::tearDown();
@@ -33,7 +34,7 @@ protected function tearDown()
/**
* @group DBAL-177
*/
- public function testGetSearchPath()
+ public function testGetSearchPath() : void
{
$params = $this->connection->getParams();
@@ -44,11 +45,11 @@ public function testGetSearchPath()
/**
* @group DBAL-244
*/
- public function testGetSchemaNames()
+ public function testGetSchemaNames() : void
{
$names = $this->schemaManager->getSchemaNames();
- self::assertInternalType('array', $names);
+ self::assertIsArray($names);
self::assertNotEmpty($names);
self::assertContains('public', $names, 'The public schema should be found.');
}
@@ -56,7 +57,7 @@ public function testGetSchemaNames()
/**
* @group DBAL-21
*/
- public function testSupportDomainTypeFallback()
+ public function testSupportDomainTypeFallback() : void
{
$createDomainTypeSQL = 'CREATE DOMAIN MyMoney AS DECIMAL(18,2)';
$this->connection->exec($createDomainTypeSQL);
@@ -77,7 +78,7 @@ public function testSupportDomainTypeFallback()
/**
* @group DBAL-37
*/
- public function testDetectsAutoIncrement()
+ public function testDetectsAutoIncrement() : void
{
$autoincTable = new Table('autoinc_table');
$column = $autoincTable->addColumn('id', 'integer');
@@ -91,7 +92,7 @@ public function testDetectsAutoIncrement()
/**
* @group DBAL-37
*/
- public function testAlterTableAutoIncrementAdd()
+ public function testAlterTableAutoIncrementAdd() : void
{
$tableFrom = new Table('autoinc_table_add');
$column = $tableFrom->addColumn('id', 'integer');
@@ -120,7 +121,7 @@ public function testAlterTableAutoIncrementAdd()
/**
* @group DBAL-37
*/
- public function testAlterTableAutoIncrementDrop()
+ public function testAlterTableAutoIncrementDrop() : void
{
$tableFrom = new Table('autoinc_table_drop');
$column = $tableFrom->addColumn('id', 'integer');
@@ -145,7 +146,7 @@ public function testAlterTableAutoIncrementDrop()
/**
* @group DBAL-75
*/
- public function testTableWithSchema()
+ public function testTableWithSchema() : void
{
$this->connection->exec('CREATE SCHEMA nested');
@@ -180,7 +181,7 @@ public function testTableWithSchema()
* @group DBAL-91
* @group DBAL-88
*/
- public function testReturnQuotedAssets()
+ public function testReturnQuotedAssets() : void
{
$sql = 'create table dbal91_something ( id integer CONSTRAINT id_something PRIMARY KEY NOT NULL ,"table" integer );';
$this->connection->exec($sql);
@@ -202,7 +203,7 @@ public function testReturnQuotedAssets()
/**
* @group DBAL-204
*/
- public function testFilterSchemaExpression()
+ public function testFilterSchemaExpression() : void
{
$testTable = new Table('dbal204_test_prefix');
$column = $testTable->addColumn('id', 'integer');
@@ -220,7 +221,7 @@ public function testFilterSchemaExpression()
self::assertCount(1, $names);
}
- public function testListForeignKeys()
+ public function testListForeignKeys() : void
{
if (! $this->connection->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('Does not support foreign key constraints.');
@@ -262,7 +263,7 @@ public function testListForeignKeys()
/**
* @group DBAL-511
*/
- public function testDefaultValueCharacterVarying()
+ public function testDefaultValueCharacterVarying() : void
{
$testTable = new Table('dbal511_default');
$testTable->addColumn('id', 'integer');
@@ -279,7 +280,7 @@ public function testDefaultValueCharacterVarying()
/**
* @group DDC-2843
*/
- public function testBooleanDefault()
+ public function testBooleanDefault() : void
{
$table = new Table('ddc2843_bools');
$table->addColumn('id', 'integer');
@@ -295,7 +296,7 @@ public function testBooleanDefault()
self::assertFalse($diff);
}
- public function testListTableWithBinary()
+ public function testListTableWithBinary() : void
{
$tableName = 'test_binary_table';
@@ -316,7 +317,7 @@ public function testListTableWithBinary()
self::assertFalse($table->getColumn('column_binary')->getFixed());
}
- public function testListQuotedTable()
+ public function testListQuotedTable() : void
{
$offlineTable = new Schema\Table('user');
$offlineTable->addColumn('id', 'integer');
@@ -334,7 +335,7 @@ public function testListQuotedTable()
self::assertFalse($comparator->diffTable($offlineTable, $onlineTable));
}
- public function testListTablesExcludesViews()
+ public function testListTablesExcludesViews() : void
{
$this->createTestTable('list_tables_excludes_views');
@@ -363,7 +364,7 @@ public function testListTablesExcludesViews()
/**
* @group DBAL-1033
*/
- public function testPartialIndexes()
+ public function testPartialIndexes() : void
{
$offlineTable = new Schema\Table('person');
$offlineTable->addColumn('id', 'integer');
@@ -390,6 +391,7 @@ public function testJsonbColumn(string $type) : void
{
if (! $this->schemaManager->getDatabasePlatform() instanceof PostgreSQL94Platform) {
$this->markTestSkipped('Requires PostgresSQL 9.4+');
+
return;
}
@@ -409,15 +411,15 @@ public function testJsonbColumn(string $type) : void
public function jsonbColumnTypeProvider() : array
{
return [
- [Type::JSON],
- [Type::JSON_ARRAY],
+ [Types::JSON],
+ [Types::JSON_ARRAY],
];
}
/**
* @group DBAL-2427
*/
- public function testListNegativeColumnDefaultValue()
+ public function testListNegativeColumnDefaultValue() : void
{
$table = new Schema\Table('test_default_negative');
$table->addColumn('col_smallint', 'smallint', ['default' => -1]);
@@ -442,7 +444,7 @@ public function testListNegativeColumnDefaultValue()
/**
* @return mixed[][]
*/
- public static function serialTypes() : array
+ public static function serialTypes() : iterable
{
return [
['integer'],
@@ -516,7 +518,7 @@ public function testAlterTableAutoIncrementIntToBigInt(string $from, string $to,
/**
* @return mixed[][]
*/
- public function autoIncrementTypeMigrations() : array
+ public static function autoIncrementTypeMigrations() : iterable
{
return [
'int->bigint' => ['integer', 'bigint', 'BIGINT'],
@@ -527,6 +529,9 @@ public function autoIncrementTypeMigrations() : array
class MoneyType extends Type
{
+ /**
+ * {@inheritDoc}
+ */
public function getName()
{
return 'MyMoney';
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/SQLAnywhereSchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/SQLAnywhereSchemaManagerTest.php
index f076a806a7a..ab5db98eff9 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Schema/SQLAnywhereSchemaManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/SQLAnywhereSchemaManagerTest.php
@@ -8,7 +8,7 @@
class SQLAnywhereSchemaManagerTest extends SchemaManagerFunctionalTestCase
{
- public function testCreateAndListViews()
+ public function testCreateAndListViews() : void
{
$this->createTestTable('view_test_table');
@@ -27,7 +27,7 @@ public function testCreateAndListViews()
self::assertRegExp('/^SELECT \* from "?DBA"?\."?view_test_table"?$/', $views[$name]->getSql());
}
- public function testDropAndCreateAdvancedIndex()
+ public function testDropAndCreateAdvancedIndex() : void
{
$table = $this->getTestTable('test_create_advanced_index');
$this->schemaManager->dropAndCreateTable($table);
@@ -37,7 +37,7 @@ public function testDropAndCreateAdvancedIndex()
);
$tableIndexes = $this->schemaManager->listTableIndexes('test_create_advanced_index');
- self::assertInternalType('array', $tableIndexes);
+ self::assertIsArray($tableIndexes);
self::assertEquals('test', $tableIndexes['test']->getName());
self::assertEquals(['test'], $tableIndexes['test']->getColumns());
self::assertTrue($tableIndexes['test']->isUnique());
@@ -47,7 +47,7 @@ public function testDropAndCreateAdvancedIndex()
self::assertTrue($tableIndexes['test']->hasFlag('for_olap_workload'));
}
- public function testListTableColumnsWithFixedStringTypeColumn()
+ public function testListTableColumnsWithFixedStringTypeColumn() : void
{
$table = new Table('list_table_columns_char');
$table->addColumn('id', 'integer', ['notnull' => true]);
@@ -61,4 +61,9 @@ public function testListTableColumnsWithFixedStringTypeColumn()
self::assertArrayHasKey('test', $columns);
self::assertTrue($columns['test']->getFixed());
}
+
+ public function testCommentInTable() : void
+ {
+ self::markTestSkipped('Table level comments are not supported on SQLAnywhere');
+ }
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/SQLServerSchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/SQLServerSchemaManagerTest.php
index d4598bccdb8..f8b3b66c15c 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Schema/SQLServerSchemaManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/SQLServerSchemaManagerTest.php
@@ -11,7 +11,7 @@
class SQLServerSchemaManagerTest extends SchemaManagerFunctionalTestCase
{
- protected function getPlatformName()
+ protected function getPlatformName() : string
{
return 'mssql';
}
@@ -19,7 +19,7 @@ protected function getPlatformName()
/**
* @group DBAL-255
*/
- public function testDropColumnConstraints()
+ public function testDropColumnConstraints() : void
{
$table = new Table('sqlsrv_drop_column');
$table->addColumn('id', 'integer');
@@ -34,7 +34,7 @@ public function testDropColumnConstraints()
self::assertCount(1, $columns);
}
- public function testColumnCollation()
+ public function testColumnCollation() : void
{
$table = new Table($tableName = 'test_collation');
$column = $table->addColumn($columnName = 'test', 'string');
@@ -52,7 +52,7 @@ public function testColumnCollation()
self::assertEquals($collation, $columns[$columnName]->getPlatformOption('collation'));
}
- public function testDefaultConstraints()
+ public function testDefaultConstraints() : void
{
$table = new Table('sqlsrv_default_constraints');
$table->addColumn('no_default', 'string');
@@ -157,7 +157,7 @@ public function testDefaultConstraints()
/**
* @group DBAL-543
*/
- public function testColumnComments()
+ public function testColumnComments() : void
{
$table = new Table('sqlsrv_column_comment');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -319,7 +319,7 @@ public function testColumnComments()
self::assertEquals('666', $columns['added_commented_type_with_comment']->getComment());
}
- public function testPkOrdering()
+ public function testPkOrdering() : void
{
// SQL Server stores index column information in a system table with two
// columns that almost always have the same value: index_column_id and key_ordinal.
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/SchemaManagerFunctionalTestCase.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/SchemaManagerFunctionalTestCase.php
index 1c0afc93e66..7b76f802612 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Schema/SchemaManagerFunctionalTestCase.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/SchemaManagerFunctionalTestCase.php
@@ -40,26 +40,28 @@
use function end;
use function explode;
use function in_array;
+use function sprintf;
use function str_replace;
use function strcasecmp;
use function strlen;
use function strtolower;
use function substr;
-class SchemaManagerFunctionalTestCase extends DbalFunctionalTestCase
+abstract class SchemaManagerFunctionalTestCase extends DbalFunctionalTestCase
{
/** @var AbstractSchemaManager */
protected $schemaManager;
- protected function getPlatformName()
+ protected function getPlatformName() : string
{
$class = static::class;
$e = explode('\\', $class);
$testClass = end($e);
+
return strtolower(str_replace('SchemaManagerTest', null, $testClass));
}
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -72,8 +74,7 @@ protected function setUp()
$this->schemaManager = $this->connection->getSchemaManager();
}
-
- protected function tearDown()
+ protected function tearDown() : void
{
parent::tearDown();
@@ -88,11 +89,10 @@ protected function tearDown()
}
}
-
/**
* @group DBAL-1220
*/
- public function testDropsDatabaseWithActiveConnections()
+ public function testDropsDatabaseWithActiveConnections() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsCreateDropDatabase()) {
$this->markTestSkipped('Cannot drop Database client side with this Driver.');
@@ -129,10 +129,14 @@ public function testDropsDatabaseWithActiveConnections()
/**
* @group DBAL-195
*/
- public function testDropAndCreateSequence()
+ public function testDropAndCreateSequence() : void
{
- if (! $this->connection->getDatabasePlatform()->supportsSequences()) {
- $this->markTestSkipped($this->connection->getDriver()->getName() . ' does not support sequences.');
+ $platform = $this->connection->getDatabasePlatform();
+
+ if (! $platform->supportsSequences()) {
+ $this->markTestSkipped(
+ sprintf('The "%s" platform does not support sequences.', $platform->getName())
+ );
}
$name = 'dropcreate_sequences_test_seq';
@@ -157,10 +161,14 @@ static function (AbstractAsset $item) use ($name) : bool {
return count($filteredList) === 1;
}
- public function testListSequences()
+ public function testListSequences() : void
{
- if (! $this->connection->getDatabasePlatform()->supportsSequences()) {
- $this->markTestSkipped($this->connection->getDriver()->getName() . ' does not support sequences.');
+ $platform = $this->connection->getDatabasePlatform();
+
+ if (! $platform->supportsSequences()) {
+ $this->markTestSkipped(
+ sprintf('The "%s" platform does not support sequences.', $platform->getName())
+ );
}
$sequence = new Sequence('list_sequences_test_seq', 20, 10);
@@ -168,7 +176,7 @@ public function testListSequences()
$sequences = $this->schemaManager->listSequences();
- self::assertInternalType('array', $sequences, 'listSequences() should return an array.');
+ self::assertIsArray($sequences, 'listSequences() should return an array.');
$foundSequence = null;
foreach ($sequences as $sequence) {
@@ -185,7 +193,7 @@ public function testListSequences()
self::assertSame(10, $foundSequence->getInitialValue(), 'Initial Value is expected to be 10.');
}
- public function testListDatabases()
+ public function testListDatabases() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsCreateDropDatabase()) {
$this->markTestSkipped('Cannot drop Database client side with this Driver.');
@@ -202,7 +210,7 @@ public function testListDatabases()
/**
* @group DBAL-1058
*/
- public function testListNamespaceNames()
+ public function testListNamespaceNames() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsSchemas()) {
$this->markTestSkipped('Platform does not support schemas.');
@@ -222,12 +230,12 @@ public function testListNamespaceNames()
self::assertContains('test_create_schema', $namespaces);
}
- public function testListTables()
+ public function testListTables() : void
{
$this->createTestTable('list_tables_test');
$tables = $this->schemaManager->listTables();
- self::assertInternalType('array', $tables);
+ self::assertIsArray($tables);
self::assertTrue(count($tables) > 0, "List Tables has to find at least one table named 'list_tables_test'.");
$foundTable = false;
@@ -247,7 +255,7 @@ public function testListTables()
self::assertTrue($foundTable, "The 'list_tables_test' table has to be found.");
}
- public function createListTableColumns()
+ public function createListTableColumns() : Table
{
$table = new Table('list_table_columns');
$table->addColumn('id', 'integer', ['notnull' => true]);
@@ -262,7 +270,7 @@ public function createListTableColumns()
return $table;
}
- public function testListTableColumns()
+ public function testListTableColumns() : void
{
$table = $this->createListTableColumns();
@@ -278,7 +286,7 @@ public function testListTableColumns()
self::assertEquals(false, $columns['id']->getunsigned());
self::assertEquals(true, $columns['id']->getnotnull());
self::assertEquals(null, $columns['id']->getdefault());
- self::assertInternalType('array', $columns['id']->getPlatformOptions());
+ self::assertIsArray($columns['id']->getPlatformOptions());
self::assertArrayHasKey('test', $columns);
self::assertEquals(1, array_search('test', $columnsKeys));
@@ -288,7 +296,7 @@ public function testListTableColumns()
self::assertEquals(false, $columns['test']->getfixed());
self::assertEquals(false, $columns['test']->getnotnull());
self::assertEquals('expected default', $columns['test']->getdefault());
- self::assertInternalType('array', $columns['test']->getPlatformOptions());
+ self::assertIsArray($columns['test']->getPlatformOptions());
self::assertEquals('foo', strtolower($columns['foo']->getname()));
self::assertEquals(2, array_search('foo', $columnsKeys));
@@ -297,7 +305,7 @@ public function testListTableColumns()
self::assertEquals(false, $columns['foo']->getfixed());
self::assertEquals(true, $columns['foo']->getnotnull());
self::assertEquals(null, $columns['foo']->getdefault());
- self::assertInternalType('array', $columns['foo']->getPlatformOptions());
+ self::assertIsArray($columns['foo']->getPlatformOptions());
self::assertEquals('bar', strtolower($columns['bar']->getname()));
self::assertEquals(3, array_search('bar', $columnsKeys));
@@ -309,34 +317,34 @@ public function testListTableColumns()
self::assertEquals(false, $columns['bar']->getfixed());
self::assertEquals(false, $columns['bar']->getnotnull());
self::assertEquals(null, $columns['bar']->getdefault());
- self::assertInternalType('array', $columns['bar']->getPlatformOptions());
+ self::assertIsArray($columns['bar']->getPlatformOptions());
self::assertEquals('baz1', strtolower($columns['baz1']->getname()));
self::assertEquals(4, array_search('baz1', $columnsKeys));
self::assertInstanceOf(DateTimeType::class, $columns['baz1']->gettype());
self::assertEquals(true, $columns['baz1']->getnotnull());
self::assertEquals(null, $columns['baz1']->getdefault());
- self::assertInternalType('array', $columns['baz1']->getPlatformOptions());
+ self::assertIsArray($columns['baz1']->getPlatformOptions());
self::assertEquals('baz2', strtolower($columns['baz2']->getname()));
self::assertEquals(5, array_search('baz2', $columnsKeys));
self::assertContains($columns['baz2']->gettype()->getName(), ['time', 'date', 'datetime']);
self::assertEquals(true, $columns['baz2']->getnotnull());
self::assertEquals(null, $columns['baz2']->getdefault());
- self::assertInternalType('array', $columns['baz2']->getPlatformOptions());
+ self::assertIsArray($columns['baz2']->getPlatformOptions());
self::assertEquals('baz3', strtolower($columns['baz3']->getname()));
self::assertEquals(6, array_search('baz3', $columnsKeys));
self::assertContains($columns['baz3']->gettype()->getName(), ['time', 'date', 'datetime']);
self::assertEquals(true, $columns['baz3']->getnotnull());
self::assertEquals(null, $columns['baz3']->getdefault());
- self::assertInternalType('array', $columns['baz3']->getPlatformOptions());
+ self::assertIsArray($columns['baz3']->getPlatformOptions());
}
/**
* @group DBAL-1078
*/
- public function testListTableColumnsWithFixedStringColumn()
+ public function testListTableColumnsWithFixedStringColumn() : void
{
$tableName = 'test_list_table_fixed_string';
@@ -353,16 +361,16 @@ public function testListTableColumnsWithFixedStringColumn()
self::assertSame(2, $columns['column_char']->getLength());
}
- public function testListTableColumnsDispatchEvent()
+ public function testListTableColumnsDispatchEvent() : void
{
$table = $this->createListTableColumns();
$this->schemaManager->dropAndCreateTable($table);
- $listenerMock = $this
- ->getMockBuilder('ListTableColumnsDispatchEventListener')
- ->setMethods(['onSchemaColumnDefinition'])
+ $listenerMock = $this->getMockBuilder($this->getMockClass('ListTableColumnsDispatchEventListener'))
+ ->addMethods(['onSchemaColumnDefinition'])
->getMock();
+
$listenerMock
->expects($this->exactly(7))
->method('onSchemaColumnDefinition');
@@ -379,7 +387,7 @@ public function testListTableColumnsDispatchEvent()
$this->schemaManager->getDatabasePlatform()->setEventManager($oldEventManager);
}
- public function testListTableIndexesDispatchEvent()
+ public function testListTableIndexesDispatchEvent() : void
{
$table = $this->getTestTable('list_table_indexes_test');
$table->addUniqueIndex(['test'], 'test_index_name');
@@ -387,9 +395,8 @@ public function testListTableIndexesDispatchEvent()
$this->schemaManager->dropAndCreateTable($table);
- $listenerMock = $this
- ->getMockBuilder('ListTableIndexesDispatchEventListener')
- ->setMethods(['onSchemaIndexDefinition'])
+ $listenerMock = $this->getMockBuilder($this->getMockClass('ListTableIndexesDispatchEventListener'))
+ ->addMethods(['onSchemaIndexDefinition'])
->getMock();
$listenerMock
->expects($this->exactly(3))
@@ -407,7 +414,7 @@ public function testListTableIndexesDispatchEvent()
$this->schemaManager->getDatabasePlatform()->setEventManager($oldEventManager);
}
- public function testDiffListTableColumns()
+ public function testDiffListTableColumns() : void
{
if ($this->schemaManager->getDatabasePlatform()->getName() === 'oracle') {
$this->markTestSkipped('Does not work with Oracle, since it cannot detect DateTime, Date and Time differenecs (at the moment).');
@@ -423,7 +430,7 @@ public function testDiffListTableColumns()
self::assertFalse($diff, 'No differences should be detected with the offline vs online schema.');
}
- public function testListTableIndexes()
+ public function testListTableIndexes() : void
{
$table = $this->getTestCompositeTable('list_table_indexes_test');
$table->addUniqueIndex(['test'], 'test_index_name');
@@ -451,7 +458,7 @@ public function testListTableIndexes()
self::assertFalse($tableIndexes['test_composite_idx']->isPrimary());
}
- public function testDropAndCreateIndex()
+ public function testDropAndCreateIndex() : void
{
$table = $this->getTestTable('test_create_index');
$table->addUniqueIndex(['test'], 'test');
@@ -459,7 +466,7 @@ public function testDropAndCreateIndex()
$this->schemaManager->dropAndCreateIndex($table->getIndex('test'), $table);
$tableIndexes = $this->schemaManager->listTableIndexes('test_create_index');
- self::assertInternalType('array', $tableIndexes);
+ self::assertIsArray($tableIndexes);
self::assertEquals('test', strtolower($tableIndexes['test']->getName()));
self::assertEquals(['test'], array_map('strtolower', $tableIndexes['test']->getColumns()));
@@ -467,7 +474,7 @@ public function testDropAndCreateIndex()
self::assertFalse($tableIndexes['test']->isPrimary());
}
- public function testCreateTableWithForeignKeys()
+ public function testCreateTableWithForeignKeys() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('Platform does not support foreign keys.');
@@ -495,7 +502,7 @@ public function testCreateTableWithForeignKeys()
self::assertTrue($fkTable->columnsAreIndexed($fkConstraint->getColumns()), 'The columns of a foreign key constraint should always be indexed.');
}
- public function testListForeignKeys()
+ public function testListForeignKeys() : void
{
if (! $this->connection->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('Does not support foreign key constraints.');
@@ -530,12 +537,12 @@ public function testListForeignKeys()
self::assertEquals('CASCADE', $fkeys[0]->getOption('onDelete'));
}
- protected function getCreateExampleViewSql()
+ protected function getCreateExampleViewSql() : void
{
$this->markTestSkipped('No Create Example View SQL was defined for this SchemaManager');
}
- public function testCreateSchema()
+ public function testCreateSchema() : void
{
$this->createTestTable('test_table');
@@ -543,7 +550,7 @@ public function testCreateSchema()
self::assertTrue($schema->hasTable('test_table'));
}
- public function testAlterTableScenario()
+ public function testAlterTableScenario() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsAlterTable()) {
$this->markTestSkipped('Alter Table is not supported by this platform.');
@@ -632,8 +639,7 @@ public function testAlterTableScenario()
self::assertEquals(['id'], array_map('strtolower', $foreignKey->getForeignColumns()));
}
-
- public function testTableInNamespace()
+ public function testTableInNamespace() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsSchemas()) {
$this->markTestSkipped('Schema definition is not supported by this platform.');
@@ -657,7 +663,7 @@ public function testTableInNamespace()
self::assertContains('my_table_not_in_namespace', $this->schemaManager->listTableNames());
}
- public function testCreateAndListViews()
+ public function testCreateAndListViews() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsViews()) {
$this->markTestSkipped('Views is not supported by this platform.');
@@ -675,7 +681,7 @@ public function testCreateAndListViews()
self::assertTrue($this->hasElementWithName($this->schemaManager->listViews(), $name));
}
- public function testAutoincrementDetection()
+ public function testAutoincrementDetection() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsIdentityColumns()) {
$this->markTestSkipped('This test is only supported on platforms that have autoincrement');
@@ -696,7 +702,7 @@ public function testAutoincrementDetection()
/**
* @group DBAL-792
*/
- public function testAutoincrementDetectionMulticolumns()
+ public function testAutoincrementDetectionMulticolumns() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsIdentityColumns()) {
$this->markTestSkipped('This test is only supported on platforms that have autoincrement');
@@ -718,7 +724,7 @@ public function testAutoincrementDetectionMulticolumns()
/**
* @group DDC-887
*/
- public function testUpdateSchemaWithForeignKeyRenaming()
+ public function testUpdateSchemaWithForeignKeyRenaming() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('This test is only supported on platforms that have foreign keys.');
@@ -763,7 +769,7 @@ public function testUpdateSchemaWithForeignKeyRenaming()
/**
* @group DBAL-1062
*/
- public function testRenameIndexUsedInForeignKeyConstraint()
+ public function testRenameIndexUsedInForeignKeyConstraint() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('This test is only supported on platforms that have foreign keys.');
@@ -804,7 +810,7 @@ public function testRenameIndexUsedInForeignKeyConstraint()
/**
* @group DBAL-42
*/
- public function testGetColumnComment()
+ public function testGetColumnComment() : void
{
if (! $this->connection->getDatabasePlatform()->supportsInlineColumnComments() &&
! $this->connection->getDatabasePlatform()->supportsCommentOnStatement() &&
@@ -848,7 +854,7 @@ public function testGetColumnComment()
/**
* @group DBAL-42
*/
- public function testAutomaticallyAppendCommentOnMarkedColumns()
+ public function testAutomaticallyAppendCommentOnMarkedColumns() : void
{
if (! $this->connection->getDatabasePlatform()->supportsInlineColumnComments() &&
! $this->connection->getDatabasePlatform()->supportsCommentOnStatement() &&
@@ -876,7 +882,7 @@ public function testAutomaticallyAppendCommentOnMarkedColumns()
/**
* @group DBAL-1228
*/
- public function testCommentHintOnDateIntervalTypeColumn()
+ public function testCommentHintOnDateIntervalTypeColumn() : void
{
if (! $this->connection->getDatabasePlatform()->supportsInlineColumnComments() &&
! $this->connection->getDatabasePlatform()->supportsCommentOnStatement() &&
@@ -901,7 +907,7 @@ public function testCommentHintOnDateIntervalTypeColumn()
/**
* @group DBAL-825
*/
- public function testChangeColumnsTypeWithDefaultValue()
+ public function testChangeColumnsTypeWithDefaultValue() : void
{
$tableName = 'column_def_change_type';
$table = new Table($tableName);
@@ -941,7 +947,7 @@ public function testChangeColumnsTypeWithDefaultValue()
/**
* @group DBAL-197
*/
- public function testListTableWithBlob()
+ public function testListTableWithBlob() : void
{
$table = new Table('test_blob_table');
$table->addColumn('id', 'integer', ['comment' => 'This is a comment']);
@@ -958,12 +964,9 @@ public function testListTableWithBlob()
}
/**
- * @param string $name
* @param mixed[] $data
- *
- * @return Table
*/
- protected function createTestTable($name = 'test_table', array $data = [])
+ protected function createTestTable(string $name = 'test_table', array $data = []) : Table
{
$options = $data['options'] ?? [];
@@ -974,7 +977,10 @@ protected function createTestTable($name = 'test_table', array $data = [])
return $table;
}
- protected function getTestTable($name, $options = [])
+ /**
+ * @param mixed[] $options
+ */
+ protected function getTestTable(string $name, array $options = []) : Table
{
$table = new Table($name, [], [], [], false, $options);
$table->setSchemaConfig($this->schemaManager->createSchemaConfig());
@@ -982,10 +988,11 @@ protected function getTestTable($name, $options = [])
$table->setPrimaryKey(['id']);
$table->addColumn('test', 'string', ['length' => 255]);
$table->addColumn('foreign_key_test', 'integer');
+
return $table;
}
- protected function getTestCompositeTable($name)
+ protected function getTestCompositeTable(string $name) : Table
{
$table = new Table($name, [], [], [], false, []);
$table->setSchemaConfig($this->schemaManager->createSchemaConfig());
@@ -993,10 +1000,14 @@ protected function getTestCompositeTable($name)
$table->addColumn('other_id', 'integer', ['notnull' => true]);
$table->setPrimaryKey(['id', 'other_id']);
$table->addColumn('test', 'string', ['length' => 255]);
+
return $table;
}
- protected function assertHasTable($tables, $tableName)
+ /**
+ * @param Table[] $tables
+ */
+ protected function assertHasTable(array $tables) : void
{
$foundTable = false;
foreach ($tables as $table) {
@@ -1010,7 +1021,7 @@ protected function assertHasTable($tables, $tableName)
self::assertTrue($foundTable, 'Could not find new table');
}
- public function testListForeignKeysComposite()
+ public function testListForeignKeysComposite() : void
{
if (! $this->connection->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('Does not support foreign key constraints.');
@@ -1040,7 +1051,7 @@ public function testListForeignKeysComposite()
/**
* @group DBAL-44
*/
- public function testColumnDefaultLifecycle()
+ public function testColumnDefaultLifecycle() : void
{
$table = new Table('col_def_lifecycle');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -1091,7 +1102,7 @@ public function testColumnDefaultLifecycle()
self::assertNull($columns['column7']->getDefault());
}
- public function testListTableWithBinary()
+ public function testListTableWithBinary() : void
{
$tableName = 'test_binary_table';
@@ -1112,7 +1123,7 @@ public function testListTableWithBinary()
self::assertTrue($table->getColumn('column_binary')->getFixed());
}
- public function testListTableDetailsWithFullQualifiedTableName()
+ public function testListTableDetailsWithFullQualifiedTableName() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsSchemas()) {
$this->markTestSkipped('Test only works on platforms that support schemas.');
@@ -1152,7 +1163,7 @@ public function testListTableDetailsWithFullQualifiedTableName()
);
}
- public function testCommentStringsAreQuoted()
+ public function testCommentStringsAreQuoted() : void
{
if (! $this->connection->getDatabasePlatform()->supportsInlineColumnComments() &&
! $this->connection->getDatabasePlatform()->supportsCommentOnStatement() &&
@@ -1170,7 +1181,7 @@ public function testCommentStringsAreQuoted()
self::assertEquals("It's a comment with a quote", $columns['id']->getComment());
}
- public function testCommentNotDuplicated()
+ public function testCommentNotDuplicated() : void
{
if (! $this->connection->getDatabasePlatform()->supportsInlineColumnComments()) {
$this->markTestSkipped('Database does not support column comments.');
@@ -1188,16 +1199,20 @@ public function testCommentNotDuplicated()
$table->addColumn('id', 'integer', ['columnDefinition' => $columnDefinition, 'comment' => 'unexpected_column_comment']);
$sql = $this->connection->getDatabasePlatform()->getCreateTableSQL($table);
- self::assertContains('expected+column+comment', $sql[0]);
- self::assertNotContains('unexpected_column_comment', $sql[0]);
+ self::assertStringContainsString('expected+column+comment', $sql[0]);
+ self::assertStringNotContainsString('unexpected_column_comment', $sql[0]);
}
/**
* @group DBAL-1009
* @dataProvider getAlterColumnComment
*/
- public function testAlterColumnComment($comment1, $expectedComment1, $comment2, $expectedComment2)
- {
+ public function testAlterColumnComment(
+ ?string $comment1,
+ ?string $expectedComment1,
+ ?string $comment2,
+ ?string $expectedComment2
+ ) : void {
if (! $this->connection->getDatabasePlatform()->supportsInlineColumnComments() &&
! $this->connection->getDatabasePlatform()->supportsCommentOnStatement() &&
$this->connection->getDatabasePlatform()->getName() !== 'mssql') {
@@ -1239,7 +1254,10 @@ public function testAlterColumnComment($comment1, $expectedComment1, $comment2,
self::assertSame($expectedComment2, $onlineTable->getColumn('no_comment2')->getComment());
}
- public function getAlterColumnComment()
+ /**
+ * @return mixed[][]
+ */
+ public static function getAlterColumnComment() : iterable
{
return [
[null, null, ' ', ' '],
@@ -1260,7 +1278,7 @@ public function getAlterColumnComment()
/**
* @group DBAL-1095
*/
- public function testDoesNotListIndexesImplicitlyCreatedByForeignKeys()
+ public function testDoesNotListIndexesImplicitlyCreatedByForeignKeys() : void
{
if (! $this->schemaManager->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('This test is only supported on platforms that have foreign keys.');
@@ -1531,7 +1549,7 @@ static function (Sequence $sequence) use ($sequenceName) : bool {
/**
* @group DBAL-2921
*/
- public function testPrimaryKeyAutoIncrement()
+ public function testPrimaryKeyAutoIncrement() : void
{
$table = new Table('test_pk_auto_increment');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -1575,4 +1593,15 @@ public function testGenerateAnIndexWithPartialColumnLength() : void
$onlineTable = $this->schemaManager->listTableDetails('test_partial_column_index');
self::assertEquals($expected, $onlineTable->getIndexes());
}
+
+ public function testCommentInTable() : void
+ {
+ $table = new Table('table_with_comment');
+ $table->addColumn('id', 'integer');
+ $table->setComment('Foo with control characters \'\\');
+ $this->schemaManager->dropAndCreateTable($table);
+
+ $table = $this->schemaManager->listTableDetails('table_with_comment');
+ self::assertSame('Foo with control characters \'\\', $table->getComment());
+ }
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Schema/SqliteSchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Functional/Schema/SqliteSchemaManagerTest.php
index 659e6d8dff2..cce8f92f72d 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Schema/SqliteSchemaManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Schema/SqliteSchemaManagerTest.php
@@ -2,11 +2,13 @@
namespace Doctrine\Tests\DBAL\Functional\Schema;
+use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\Schema;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Types\BlobType;
use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use SQLite3;
use function array_map;
use function dirname;
@@ -17,15 +19,15 @@ class SqliteSchemaManagerTest extends SchemaManagerFunctionalTestCase
{
/**
* SQLITE does not support databases.
- *
- * @expectedException \Doctrine\DBAL\DBALException
*/
- public function testListDatabases()
+ public function testListDatabases() : void
{
+ $this->expectException(DBALException::class);
+
$this->schemaManager->listDatabases();
}
- public function testCreateAndDropDatabase()
+ public function testCreateAndDropDatabase() : void
{
$path = dirname(__FILE__) . '/test_create_and_drop_sqlite_database.sqlite';
@@ -38,7 +40,7 @@ public function testCreateAndDropDatabase()
/**
* @group DBAL-1220
*/
- public function testDropsDatabaseWithActiveConnections()
+ public function testDropsDatabaseWithActiveConnections() : void
{
$this->schemaManager->dropAndCreateDatabase('test_drop_database');
@@ -61,7 +63,7 @@ public function testDropsDatabaseWithActiveConnections()
unset($connection);
}
- public function testRenameTable()
+ public function testRenameTable() : void
{
$this->createTestTable('oldname');
$this->schemaManager->renameTable('oldname', 'newname');
@@ -71,7 +73,7 @@ public function testRenameTable()
self::assertNotContains('oldname', $tables);
}
- public function createListTableColumns()
+ public function createListTableColumns() : Table
{
$table = parent::createListTableColumns();
$table->getColumn('id')->setAutoincrement(true);
@@ -79,7 +81,7 @@ public function createListTableColumns()
return $table;
}
- public function testListForeignKeysFromExistingDatabase()
+ public function testListForeignKeysFromExistingDatabase() : void
{
$this->connection->exec(<<schemaManager->listTableForeignKeys('user'));
}
- public function testColumnCollation()
+ public function testColumnCollation() : void
{
$table = new Schema\Table('test_collation');
$table->addColumn('id', 'integer');
@@ -136,7 +138,7 @@ public function testColumnCollation()
self::assertEquals('NOCASE', $columns['bar']->getPlatformOption('collation'));
}
- public function testListTableWithBinary()
+ public function testListTableWithBinary() : void
{
$tableName = 'test_binary_table';
@@ -157,7 +159,7 @@ public function testListTableWithBinary()
self::assertFalse($table->getColumn('column_binary')->getFixed());
}
- public function testNonDefaultPKOrder()
+ public function testNonDefaultPKOrder() : void
{
if (! extension_loaded('sqlite3')) {
$this->markTestSkipped('This test requires the SQLite3 extension.');
@@ -187,7 +189,7 @@ public function testNonDefaultPKOrder()
/**
* @group DBAL-1779
*/
- public function testListTableColumnsWithWhitespacesInTypeDeclarations()
+ public function testListTableColumnsWithWhitespacesInTypeDeclarations() : void
{
$sql = <<getType());
- self::assertSame(Type::getType(Type::TEXT), $columns['bar']->getType());
+ self::assertSame(Type::getType(Types::STRING), $columns['foo']->getType());
+ self::assertSame(Type::getType(Types::TEXT), $columns['bar']->getType());
self::assertSame(64, $columns['foo']->getLength());
self::assertSame(100, $columns['bar']->getLength());
@@ -216,7 +218,7 @@ public function testListTableColumnsWithWhitespacesInTypeDeclarations()
* @dataProvider getDiffListIntegerAutoincrementTableColumnsData
* @group DBAL-924
*/
- public function testDiffListIntegerAutoincrementTableColumns($integerType, $unsigned, $expectedComparatorDiff)
+ public function testDiffListIntegerAutoincrementTableColumns(string $integerType, bool $unsigned, bool $expectedComparatorDiff) : void
{
$tableName = 'test_int_autoincrement_table';
@@ -240,7 +242,7 @@ public function testDiffListIntegerAutoincrementTableColumns($integerType, $unsi
/**
* @return mixed[][]
*/
- public function getDiffListIntegerAutoincrementTableColumnsData()
+ public static function getDiffListIntegerAutoincrementTableColumnsData() : iterable
{
return [
['smallint', false, true],
@@ -255,7 +257,7 @@ public function getDiffListIntegerAutoincrementTableColumnsData()
/**
* @group DBAL-2921
*/
- public function testPrimaryKeyNoAutoIncrement()
+ public function testPrimaryKeyNoAutoIncrement() : void
{
$table = new Schema\Table('test_pk_auto_increment');
$table->addColumn('id', 'integer');
diff --git a/tests/Doctrine/Tests/DBAL/Functional/StatementTest.php b/tests/Doctrine/Tests/DBAL/Functional/StatementTest.php
index 7bd7009c788..392e6d756bc 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/StatementTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/StatementTest.php
@@ -14,7 +14,7 @@
class StatementTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -24,7 +24,7 @@ protected function setUp()
$this->connection->getSchemaManager()->dropAndCreateTable($table);
}
- public function testStatementIsReusableAfterClosingCursor()
+ public function testStatementIsReusableAfterClosingCursor() : void
{
if ($this->connection->getDriver() instanceof PDOOracleDriver) {
$this->markTestIncomplete('See https://bugs.php.net/bug.php?id=77181');
@@ -49,7 +49,7 @@ public function testStatementIsReusableAfterClosingCursor()
self::assertEquals(2, $id);
}
- public function testReuseStatementWithLongerResults()
+ public function testReuseStatementWithLongerResults() : void
{
if ($this->connection->getDriver() instanceof PDOOracleDriver) {
$this->markTestIncomplete('PDO_OCI doesn\'t support fetching blobs via PDOStatement::fetchAll()');
@@ -69,7 +69,7 @@ public function testReuseStatementWithLongerResults()
$stmt = $this->connection->prepare('SELECT param, val FROM stmt_longer_results ORDER BY param');
$stmt->execute();
- self::assertArraySubset([
+ self::assertEquals([
['param1', 'X'],
], $stmt->fetchAll(FetchMode::NUMERIC));
@@ -80,13 +80,13 @@ public function testReuseStatementWithLongerResults()
$this->connection->insert('stmt_longer_results', $row2);
$stmt->execute();
- self::assertArraySubset([
+ self::assertEquals([
['param1', 'X'],
['param2', 'A bit longer value'],
], $stmt->fetchAll(FetchMode::NUMERIC));
}
- public function testFetchLongBlob()
+ public function testFetchLongBlob() : void
{
if ($this->connection->getDriver() instanceof PDOOracleDriver) {
// inserting BLOBs as streams on Oracle requires Oracle-specific SQL syntax which is currently not supported
@@ -134,7 +134,7 @@ public function testFetchLongBlob()
self::assertSame($contents, stream_get_contents($stream));
}
- public function testIncompletelyFetchedStatementDoesNotBlockConnection()
+ public function testIncompletelyFetchedStatementDoesNotBlockConnection() : void
{
$this->connection->insert('stmt_test', ['id' => 1]);
$this->connection->insert('stmt_test', ['id' => 2]);
@@ -151,7 +151,7 @@ public function testIncompletelyFetchedStatementDoesNotBlockConnection()
self::assertEquals(1, $stmt2->fetchColumn());
}
- public function testReuseStatementAfterClosingCursor()
+ public function testReuseStatementAfterClosingCursor() : void
{
if ($this->connection->getDriver() instanceof PDOOracleDriver) {
$this->markTestIncomplete('See https://bugs.php.net/bug.php?id=77181');
@@ -173,7 +173,7 @@ public function testReuseStatementAfterClosingCursor()
self::assertEquals(2, $id);
}
- public function testReuseStatementWithParameterBoundByReference()
+ public function testReuseStatementWithParameterBoundByReference() : void
{
$this->connection->insert('stmt_test', ['id' => 1]);
$this->connection->insert('stmt_test', ['id' => 2]);
@@ -190,7 +190,7 @@ public function testReuseStatementWithParameterBoundByReference()
self::assertEquals(2, $stmt->fetchColumn());
}
- public function testReuseStatementWithReboundValue()
+ public function testReuseStatementWithReboundValue() : void
{
$this->connection->insert('stmt_test', ['id' => 1]);
$this->connection->insert('stmt_test', ['id' => 2]);
@@ -206,7 +206,7 @@ public function testReuseStatementWithReboundValue()
self::assertEquals(2, $stmt->fetchColumn());
}
- public function testReuseStatementWithReboundParam()
+ public function testReuseStatementWithReboundParam() : void
{
$this->connection->insert('stmt_test', ['id' => 1]);
$this->connection->insert('stmt_test', ['id' => 2]);
@@ -225,26 +225,27 @@ public function testReuseStatementWithReboundParam()
}
/**
+ * @param mixed $expected
+ *
* @dataProvider emptyFetchProvider
*/
- public function testFetchFromNonExecutedStatement(callable $fetch, $expected)
+ public function testFetchFromNonExecutedStatement(callable $fetch, $expected) : void
{
$stmt = $this->connection->prepare('SELECT id FROM stmt_test');
self::assertSame($expected, $fetch($stmt));
}
- public function testCloseCursorOnNonExecutedStatement()
+ public function testCloseCursorOnNonExecutedStatement() : void
{
$stmt = $this->connection->prepare('SELECT id FROM stmt_test');
-
self::assertTrue($stmt->closeCursor());
}
/**
* @group DBAL-2637
*/
- public function testCloseCursorAfterCursorEnd()
+ public function testCloseCursorAfterCursorEnd() : void
{
$stmt = $this->connection->prepare('SELECT name FROM stmt_test');
@@ -255,9 +256,11 @@ public function testCloseCursorAfterCursorEnd()
}
/**
+ * @param mixed $expected
+ *
* @dataProvider emptyFetchProvider
*/
- public function testFetchFromNonExecutedStatementWithClosedCursor(callable $fetch, $expected)
+ public function testFetchFromNonExecutedStatementWithClosedCursor(callable $fetch, $expected) : void
{
$stmt = $this->connection->prepare('SELECT id FROM stmt_test');
$stmt->closeCursor();
@@ -266,9 +269,11 @@ public function testFetchFromNonExecutedStatementWithClosedCursor(callable $fetc
}
/**
+ * @param mixed $expected
+ *
* @dataProvider emptyFetchProvider
*/
- public function testFetchFromExecutedStatementWithClosedCursor(callable $fetch, $expected)
+ public function testFetchFromExecutedStatementWithClosedCursor(callable $fetch, $expected) : void
{
$this->connection->insert('stmt_test', ['id' => 1]);
@@ -279,7 +284,10 @@ public function testFetchFromExecutedStatementWithClosedCursor(callable $fetch,
self::assertSame($expected, $fetch($stmt));
}
- public static function emptyFetchProvider()
+ /**
+ * @return mixed[][]
+ */
+ public static function emptyFetchProvider() : iterable
{
return [
'fetch' => [
diff --git a/tests/Doctrine/Tests/DBAL/Functional/TableGeneratorTest.php b/tests/Doctrine/Tests/DBAL/Functional/TableGeneratorTest.php
index f62b992015c..9846bf70fa1 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/TableGeneratorTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/TableGeneratorTest.php
@@ -16,7 +16,7 @@ class TableGeneratorTest extends DbalFunctionalTestCase
/** @var TableGenerator */
private $generator;
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -38,7 +38,7 @@ protected function setUp()
$this->generator = new TableGenerator($this->connection);
}
- public function testNextVal()
+ public function testNextVal() : void
{
$id1 = $this->generator->nextValue('tbl1');
$id2 = $this->generator->nextValue('tbl1');
@@ -49,7 +49,7 @@ public function testNextVal()
self::assertEquals($id1, $id3, 'First ids from different tables are equal.');
}
- public function testNextValNotAffectedByOuterTransactions()
+ public function testNextValNotAffectedByOuterTransactions() : void
{
$this->connection->beginTransaction();
$id1 = $this->generator->nextValue('tbl1');
diff --git a/tests/Doctrine/Tests/DBAL/Functional/TemporaryTableTest.php b/tests/Doctrine/Tests/DBAL/Functional/TemporaryTableTest.php
index 87a776c7e06..e96fd426b3a 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/TemporaryTableTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/TemporaryTableTest.php
@@ -9,7 +9,7 @@
class TemporaryTableTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
try {
@@ -18,7 +18,7 @@ protected function setUp()
}
}
- protected function tearDown()
+ protected function tearDown() : void
{
if ($this->connection) {
try {
@@ -32,11 +32,9 @@ protected function tearDown()
}
/**
- * @return void
- *
* @group DDC-1337
*/
- public function testDropTemporaryTableNotAutoCommitTransaction()
+ public function testDropTemporaryTableNotAutoCommitTransaction() : void
{
if ($this->connection->getDatabasePlatform()->getName() === 'sqlanywhere' ||
$this->connection->getDatabasePlatform()->getName() === 'oracle') {
@@ -69,11 +67,9 @@ public function testDropTemporaryTableNotAutoCommitTransaction()
}
/**
- * @return void
- *
* @group DDC-1337
*/
- public function testCreateTemporaryTableNotAutoCommitTransaction()
+ public function testCreateTemporaryTableNotAutoCommitTransaction() : void
{
if ($this->connection->getDatabasePlatform()->getName() === 'sqlanywhere' ||
$this->connection->getDatabasePlatform()->getName() === 'oracle') {
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL168Test.php b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL168Test.php
index b18b6cbdaf5..a3133635c0d 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL168Test.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL168Test.php
@@ -10,7 +10,7 @@
*/
class DBAL168Test extends DbalFunctionalTestCase
{
- public function testDomainsTable()
+ public function testDomainsTable() : void
{
if ($this->connection->getDatabasePlatform()->getName() !== 'postgresql') {
$this->markTestSkipped('PostgreSQL only test');
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL202Test.php b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL202Test.php
index 1adf993250f..da1fbcbd2f1 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL202Test.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL202Test.php
@@ -10,7 +10,7 @@
*/
class DBAL202Test extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -29,7 +29,7 @@ protected function setUp()
}
}
- public function testStatementRollback()
+ public function testStatementRollback() : void
{
$stmt = $this->connection->prepare('INSERT INTO DBAL202 VALUES (8)');
$this->connection->beginTransaction();
@@ -39,7 +39,7 @@ public function testStatementRollback()
self::assertEquals(0, $this->connection->query('SELECT COUNT(1) FROM DBAL202')->fetchColumn());
}
- public function testStatementCommit()
+ public function testStatementCommit() : void
{
$stmt = $this->connection->prepare('INSERT INTO DBAL202 VALUES (8)');
$this->connection->beginTransaction();
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL421Test.php b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL421Test.php
index af41670690a..3ebd3a62f1f 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL421Test.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL421Test.php
@@ -11,7 +11,7 @@
*/
class DBAL421Test extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -23,7 +23,7 @@ protected function setUp()
$this->markTestSkipped('Currently restricted to MySQL and SQLite.');
}
- public function testGuidShouldMatchPattern()
+ public function testGuidShouldMatchPattern() : void
{
$guid = $this->connection->query($this->getSelectGuidSql())->fetchColumn();
$pattern = '/[0-9A-F]{8}\-[0-9A-F]{4}\-[0-9A-F]{4}\-[8-9A-B][0-9A-F]{3}\-[0-9A-F]{12}/i';
@@ -34,7 +34,7 @@ public function testGuidShouldMatchPattern()
* This test does (of course) not proof that all generated GUIDs are
* random, it should however provide some basic confidence.
*/
- public function testGuidShouldBeRandom()
+ public function testGuidShouldBeRandom() : void
{
$statement = $this->connection->prepare($this->getSelectGuidSql());
$guids = [];
@@ -49,7 +49,7 @@ public function testGuidShouldBeRandom()
$statement->closeCursor();
}
- private function getSelectGuidSql()
+ private function getSelectGuidSql() : string
{
return 'SELECT ' . $this->connection->getDatabasePlatform()->getGuidExpression();
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL461Test.php b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL461Test.php
index a9dbdb1e109..e1c0927d852 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL461Test.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL461Test.php
@@ -14,7 +14,7 @@
*/
class DBAL461Test extends TestCase
{
- public function testIssue()
+ public function testIssue() : void
{
$conn = $this->createMock(Connection::class);
$platform = $this->getMockForAbstractClass(AbstractPlatform::class);
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL510Test.php b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL510Test.php
index fa98ecb3eca..1b3008db65d 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL510Test.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL510Test.php
@@ -11,7 +11,7 @@
*/
class DBAL510Test extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -22,7 +22,7 @@ protected function setUp()
$this->markTestSkipped('PostgreSQL Only test');
}
- public function testSearchPathSchemaChanges()
+ public function testSearchPathSchemaChanges() : void
{
$table = new Table('dbal510tbl');
$table->addColumn('id', 'integer');
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL630Test.php b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL630Test.php
index 827a9124277..687e6e834a0 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL630Test.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL630Test.php
@@ -16,7 +16,7 @@ class DBAL630Test extends DbalFunctionalTestCase
/** @var bool */
private $running = false;
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -34,7 +34,7 @@ protected function setUp()
$this->running = true;
}
- protected function tearDown()
+ protected function tearDown() : void
{
if ($this->running) {
$this->connection->getWrappedConnection()->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
@@ -43,7 +43,7 @@ protected function tearDown()
parent::tearDown();
}
- public function testBooleanConversionSqlLiteral()
+ public function testBooleanConversionSqlLiteral() : void
{
$this->connection->executeUpdate('INSERT INTO dbal630 (bool_col) VALUES(false)');
$id = $this->connection->lastInsertId('dbal630_id_seq');
@@ -54,7 +54,7 @@ public function testBooleanConversionSqlLiteral()
self::assertFalse($row['bool_col']);
}
- public function testBooleanConversionBoolParamRealPrepares()
+ public function testBooleanConversionBoolParamRealPrepares() : void
{
$this->connection->executeUpdate(
'INSERT INTO dbal630 (bool_col) VALUES(?)',
@@ -69,7 +69,7 @@ public function testBooleanConversionBoolParamRealPrepares()
self::assertFalse($row['bool_col']);
}
- public function testBooleanConversionBoolParamEmulatedPrepares()
+ public function testBooleanConversionBoolParamEmulatedPrepares() : void
{
$this->connection->getWrappedConnection()->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
@@ -92,9 +92,9 @@ public function testBooleanConversionBoolParamEmulatedPrepares()
* @dataProvider booleanTypeConversionWithoutPdoTypeProvider
*/
public function testBooleanConversionNullParamEmulatedPrepares(
- $statementValue,
- $databaseConvertedValue
- ) {
+ ?bool $statementValue,
+ ?bool $databaseConvertedValue
+ ) : void {
$this->connection->getWrappedConnection()->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$platform = $this->connection->getDatabasePlatform();
@@ -116,9 +116,9 @@ public function testBooleanConversionNullParamEmulatedPrepares(
* @dataProvider booleanTypeConversionUsingBooleanTypeProvider
*/
public function testBooleanConversionNullParamEmulatedPreparesWithBooleanTypeInBindValue(
- $statementValue,
- $databaseConvertedValue
- ) {
+ ?bool $statementValue,
+ bool $databaseConvertedValue
+ ) : void {
$this->connection->getWrappedConnection()->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$platform = $this->connection->getDatabasePlatform();
@@ -145,7 +145,7 @@ public function testBooleanConversionNullParamEmulatedPreparesWithBooleanTypeInB
*
* @return mixed[][]
*/
- public function booleanTypeConversionUsingBooleanTypeProvider()
+ public static function booleanTypeConversionUsingBooleanTypeProvider() : iterable
{
return [
// statement value, database converted value result
@@ -160,7 +160,7 @@ public function booleanTypeConversionUsingBooleanTypeProvider()
*
* @return mixed[][]
*/
- public function booleanTypeConversionWithoutPdoTypeProvider()
+ public static function booleanTypeConversionWithoutPdoTypeProvider() : iterable
{
return [
// statement value, database converted value result
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL752Test.php b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL752Test.php
index ee0bce44e08..47bc1c3e762 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL752Test.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL752Test.php
@@ -10,7 +10,7 @@
*/
class DBAL752Test extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -23,7 +23,7 @@ protected function setUp()
$this->markTestSkipped('Related to SQLite only');
}
- public function testUnsignedIntegerDetection()
+ public function testUnsignedIntegerDetection() : void
{
$this->connection->exec(<<connection->getDatabasePlatform() instanceof MySqlPlatform) {
+ return;
+ }
+
+ $this->markTestSkipped('Restricted to MySQL.');
+ }
+
+ protected function tearDown() : void
+ {
+ $this->resetSharedConn();
+
+ parent::tearDown();
+ }
+
+ public function testCommitFalse() : void
+ {
+ $this->connection->query('SET SESSION wait_timeout=1');
+
+ $this->assertTrue($this->connection->beginTransaction());
+
+ sleep(2); // during the sleep mysql will close the connection
+
+ $this->assertFalse(@$this->connection->commit()); // we will ignore `MySQL server has gone away` warnings
+ }
+}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/TypeConversionTest.php b/tests/Doctrine/Tests/DBAL/Functional/TypeConversionTest.php
index 0e086b598e4..0d034edada2 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/TypeConversionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/TypeConversionTest.php
@@ -8,15 +8,14 @@
use Doctrine\DBAL\Types\Type;
use Doctrine\Tests\DbalFunctionalTestCase;
use stdClass;
-use Throwable;
use function str_repeat;
class TypeConversionTest extends DbalFunctionalTestCase
{
/** @var int */
- static private $typeCounter = 0;
+ private static $typeCounter = 0;
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -38,45 +37,87 @@ protected function setUp()
$table->addColumn('test_decimal', 'decimal', ['notnull' => false, 'scale' => 2, 'precision' => 10]);
$table->setPrimaryKey(['id']);
- try {
- $this->connection->getSchemaManager()->createTable($table);
- } catch (Throwable $e) {
- }
+ $this->connection
+ ->getSchemaManager()
+ ->dropAndCreateTable($table);
}
- public static function dataIdempotentDataConversion()
+ /**
+ * @param mixed $originalValue
+ *
+ * @dataProvider booleanProvider
+ */
+ public function testIdempotentConversionToBoolean(string $type, $originalValue) : void
{
- $obj = new stdClass();
- $obj->foo = 'bar';
- $obj->bar = 'baz';
+ $dbValue = $this->processValue($type, $originalValue);
+
+ self::assertIsBool($dbValue);
+ self::assertEquals($originalValue, $dbValue);
+ }
+
+ /**
+ * @return mixed[][]
+ */
+ public static function booleanProvider() : iterable
+ {
+ return [
+ 'true' => ['boolean', true],
+ 'false' => ['boolean', false],
+ ];
+ }
+
+ /**
+ * @param mixed $originalValue
+ *
+ * @dataProvider integerProvider
+ */
+ public function testIdempotentConversionToInteger(string $type, $originalValue) : void
+ {
+ $dbValue = $this->processValue($type, $originalValue);
+
+ self::assertIsInt($dbValue);
+ self::assertEquals($originalValue, $dbValue);
+ }
+
+ /**
+ * @return mixed[][]
+ */
+ public static function integerProvider() : iterable
+ {
+ return [
+ 'smallint' => ['smallint', 123],
+ ];
+ }
+
+ /**
+ * @param mixed $originalValue
+ *
+ * @dataProvider floatProvider
+ */
+ public function testIdempotentConversionToFloat(string $type, $originalValue) : void
+ {
+ $dbValue = $this->processValue($type, $originalValue);
+
+ self::assertIsFloat($dbValue);
+ self::assertEquals($originalValue, $dbValue);
+ }
+ /**
+ * @return mixed[][]
+ */
+ public static function floatProvider() : iterable
+ {
return [
- ['string', 'ABCDEFGaaaBBB', 'string'],
- ['boolean', true, 'bool'],
- ['boolean', false, 'bool'],
- ['bigint', 12345678, 'string'],
- ['smallint', 123, 'int'],
- ['datetime', new DateTime('2010-04-05 10:10:10'), 'DateTime'],
- ['datetimetz', new DateTime('2010-04-05 10:10:10'), 'DateTime'],
- ['date', new DateTime('2010-04-05'), 'DateTime'],
- ['time', new DateTime('1970-01-01 10:10:10'), 'DateTime'],
- ['text', str_repeat('foo ', 1000), 'string'],
- ['array', ['foo' => 'bar'], 'array'],
- ['json_array', ['foo' => 'bar'], 'array'],
- ['object', $obj, 'object'],
- ['float', 1.5, 'float'],
- ['decimal', 1.55, 'string'],
+ 'float' => ['float', 1.5],
];
}
/**
- * @param string $type
- * @param mixed $originalValue
- * @param string $expectedPhpType
+ * @param mixed $originalValue
*
- * @dataProvider dataIdempotentDataConversion
+ * @dataProvider toStringProvider
*/
- public function testIdempotentDataConversion($type, $originalValue, $expectedPhpType)
+ public function testIdempotentConversionToString(string $type, $originalValue) : void
{
if ($type === 'text' && $this->connection->getDriver() instanceof PDOOracleDriver) {
// inserting BLOBs as streams on Oracle requires Oracle-specific SQL syntax which is currently not supported
@@ -84,31 +125,127 @@ public function testIdempotentDataConversion($type, $originalValue, $expectedPhp
$this->markTestSkipped('DBAL doesn\'t support storing LOBs represented as streams using PDO_OCI');
}
- $columnName = 'test_' . $type;
- $typeInstance = Type::getType($type);
- $insertionValue = $typeInstance->convertToDatabaseValue($originalValue, $this->connection->getDatabasePlatform());
+ $dbValue = $this->processValue($type, $originalValue);
- $this->connection->insert('type_conversion', ['id' => ++self::$typeCounter, $columnName => $insertionValue]);
+ self::assertIsString($dbValue);
+ self::assertEquals($originalValue, $dbValue);
+ }
- $sql = 'SELECT ' . $columnName . ' FROM type_conversion WHERE id = ' . self::$typeCounter;
- $actualDbValue = $typeInstance->convertToPHPValue($this->connection->fetchColumn($sql), $this->connection->getDatabasePlatform());
+ /**
+ * @return mixed[][]
+ */
+ public static function toStringProvider() : iterable
+ {
+ return [
+ 'string' => ['string', 'ABCDEFGabcdefg'],
+ 'bigint' => ['bigint', 12345678],
+ 'text' => ['text', str_repeat('foo ', 1000)],
+ 'decimal' => ['decimal', 1.55],
+ ];
+ }
- if ($originalValue instanceof DateTime) {
- self::assertInstanceOf($expectedPhpType, $actualDbValue, 'The expected type from the conversion to and back from the database should be ' . $expectedPhpType);
- } else {
- self::assertInternalType($expectedPhpType, $actualDbValue, 'The expected type from the conversion to and back from the database should be ' . $expectedPhpType);
- }
+ /**
+ * @param mixed $originalValue
+ *
+ * @dataProvider toArrayProvider
+ */
+ public function testIdempotentConversionToArray(string $type, $originalValue) : void
+ {
+ $dbValue = $this->processValue($type, $originalValue);
+
+ self::assertIsArray($dbValue);
+ self::assertEquals($originalValue, $dbValue);
+ }
+
+ /**
+ * @return mixed[][]
+ */
+ public static function toArrayProvider() : iterable
+ {
+ return [
+ 'array' => ['array', ['foo' => 'bar']],
+ 'json_array' => ['json_array', ['foo' => 'bar']],
+ ];
+ }
+
+ /**
+ * @param mixed $originalValue
+ *
+ * @dataProvider toObjectProvider
+ */
+ public function testIdempotentConversionToObject(string $type, $originalValue) : void
+ {
+ $dbValue = $this->processValue($type, $originalValue);
+
+ self::assertIsObject($dbValue);
+ self::assertEquals($originalValue, $dbValue);
+ }
+
+ /**
+ * @return mixed[][]
+ */
+ public static function toObjectProvider() : iterable
+ {
+ $obj = new stdClass();
+ $obj->foo = 'bar';
+ $obj->bar = 'baz';
+
+ return [
+ 'object' => ['object', $obj],
+ ];
+ }
+
+ /**
+ * @dataProvider toDateTimeProvider
+ */
+ public function testIdempotentConversionToDateTime(string $type, DateTime $originalValue) : void
+ {
+ $dbValue = $this->processValue($type, $originalValue);
+
+ self::assertInstanceOf(DateTime::class, $dbValue);
if ($type === 'datetimetz') {
return;
}
- self::assertEquals($originalValue, $actualDbValue, 'Conversion between values should produce the same out as in value, but doesnt!');
+ self::assertEquals($originalValue, $dbValue);
+ self::assertEquals(
+ $originalValue->getTimezone(),
+ $dbValue->getTimezone()
+ );
+ }
- if (! ($originalValue instanceof DateTime)) {
- return;
- }
+ /**
+ * @return mixed[][]
+ */
+ public static function toDateTimeProvider() : iterable
+ {
+ return [
+ 'datetime' => ['datetime', new DateTime('2010-04-05 10:10:10')],
+ 'datetimetz' => ['datetimetz', new DateTime('2010-04-05 10:10:10')],
+ 'date' => ['date', new DateTime('2010-04-05')],
+ 'time' => ['time', new DateTime('1970-01-01 10:10:10')],
+ ];
+ }
+
+ /**
+ * @param mixed $originalValue
+ *
+ * @return mixed
+ */
+ private function processValue(string $type, $originalValue)
+ {
+ $columnName = 'test_' . $type;
+ $typeInstance = Type::getType($type);
+ $insertionValue = $typeInstance->convertToDatabaseValue($originalValue, $this->connection->getDatabasePlatform());
+
+ $this->connection->insert('type_conversion', ['id' => ++self::$typeCounter, $columnName => $insertionValue]);
+
+ $sql = 'SELECT ' . $columnName . ' FROM type_conversion WHERE id = ' . self::$typeCounter;
- self::assertEquals($originalValue->getTimezone()->getName(), $actualDbValue->getTimezone()->getName(), 'Timezones should be the same.');
+ return $typeInstance->convertToPHPValue(
+ $this->connection->fetchColumn($sql),
+ $this->connection->getDatabasePlatform()
+ );
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Functional/Types/BinaryTest.php b/tests/Doctrine/Tests/DBAL/Functional/Types/BinaryTest.php
index 55b49156f87..76236acff0c 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/Types/BinaryTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/Types/BinaryTest.php
@@ -16,7 +16,7 @@
class BinaryTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -36,7 +36,7 @@ protected function setUp()
$sm->dropAndCreateTable($table);
}
- public function testInsertAndSelect()
+ public function testInsertAndSelect() : void
{
$id1 = random_bytes(16);
$id2 = random_bytes(16);
@@ -70,6 +70,9 @@ private function insert(string $id, string $value) : void
self::assertSame(1, $result);
}
+ /**
+ * @return mixed
+ */
private function select(string $id)
{
$value = $this->connection->fetchColumn(
diff --git a/tests/Doctrine/Tests/DBAL/Functional/WriteTest.php b/tests/Doctrine/Tests/DBAL/Functional/WriteTest.php
index e25de428aff..b08751d5ec3 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/WriteTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/WriteTest.php
@@ -15,7 +15,7 @@
class WriteTest extends DbalFunctionalTestCase
{
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
@@ -35,7 +35,7 @@ protected function setUp()
/**
* @group DBAL-80
*/
- public function testExecuteUpdateFirstTypeIsNull()
+ public function testExecuteUpdateFirstTypeIsNull() : void
{
$sql = 'INSERT INTO write_table (test_string, test_int) VALUES (?, ?)';
$this->connection->executeUpdate($sql, ['text', 1111], [null, ParameterType::INTEGER]);
@@ -44,7 +44,7 @@ public function testExecuteUpdateFirstTypeIsNull()
self::assertTrue((bool) $this->connection->fetchColumn($sql, ['text', 1111]));
}
- public function testExecuteUpdate()
+ public function testExecuteUpdate() : void
{
$sql = 'INSERT INTO write_table (test_int) VALUES ( ' . $this->connection->quote(1) . ')';
$affected = $this->connection->executeUpdate($sql);
@@ -52,7 +52,7 @@ public function testExecuteUpdate()
self::assertEquals(1, $affected, 'executeUpdate() should return the number of affected rows!');
}
- public function testExecuteUpdateWithTypes()
+ public function testExecuteUpdateWithTypes() : void
{
$sql = 'INSERT INTO write_table (test_int, test_string) VALUES (?, ?)';
$affected = $this->connection->executeUpdate(
@@ -64,7 +64,7 @@ public function testExecuteUpdateWithTypes()
self::assertEquals(1, $affected, 'executeUpdate() should return the number of affected rows!');
}
- public function testPrepareRowCountReturnsAffectedRows()
+ public function testPrepareRowCountReturnsAffectedRows() : void
{
$sql = 'INSERT INTO write_table (test_int, test_string) VALUES (?, ?)';
$stmt = $this->connection->prepare($sql);
@@ -76,7 +76,7 @@ public function testPrepareRowCountReturnsAffectedRows()
self::assertEquals(1, $stmt->rowCount());
}
- public function testPrepareWithPdoTypes()
+ public function testPrepareWithPdoTypes() : void
{
$sql = 'INSERT INTO write_table (test_int, test_string) VALUES (?, ?)';
$stmt = $this->connection->prepare($sql);
@@ -88,7 +88,7 @@ public function testPrepareWithPdoTypes()
self::assertEquals(1, $stmt->rowCount());
}
- public function testPrepareWithDbalTypes()
+ public function testPrepareWithDbalTypes() : void
{
$sql = 'INSERT INTO write_table (test_int, test_string) VALUES (?, ?)';
$stmt = $this->connection->prepare($sql);
@@ -100,7 +100,7 @@ public function testPrepareWithDbalTypes()
self::assertEquals(1, $stmt->rowCount());
}
- public function testPrepareWithDbalTypeNames()
+ public function testPrepareWithDbalTypeNames() : void
{
$sql = 'INSERT INTO write_table (test_int, test_string) VALUES (?, ?)';
$stmt = $this->connection->prepare($sql);
@@ -112,18 +112,18 @@ public function testPrepareWithDbalTypeNames()
self::assertEquals(1, $stmt->rowCount());
}
- public function insertRows()
+ public function insertRows() : void
{
self::assertEquals(1, $this->connection->insert('write_table', ['test_int' => 1, 'test_string' => 'foo']));
self::assertEquals(1, $this->connection->insert('write_table', ['test_int' => 2, 'test_string' => 'bar']));
}
- public function testInsert()
+ public function testInsert() : void
{
$this->insertRows();
}
- public function testDelete()
+ public function testDelete() : void
{
$this->insertRows();
@@ -134,7 +134,7 @@ public function testDelete()
self::assertCount(0, $this->connection->fetchAll('SELECT * FROM write_table'));
}
- public function testUpdate()
+ public function testUpdate() : void
{
$this->insertRows();
@@ -143,7 +143,7 @@ public function testUpdate()
self::assertEquals(0, $this->connection->update('write_table', ['test_string' => 'baz'], ['test_string' => 'bar']));
}
- public function testLastInsertId()
+ public function testLastInsertId() : void
{
if (! $this->connection->getDatabasePlatform()->prefersIdentityColumns()) {
$this->markTestSkipped('Test only works on platforms with identity columns.');
@@ -156,7 +156,7 @@ public function testLastInsertId()
self::assertGreaterThan(0, $num, 'LastInsertId() should be non-negative number.');
}
- public function testLastInsertIdSequence()
+ public function testLastInsertIdSequence() : void
{
if (! $this->connection->getDatabasePlatform()->supportsSequences()) {
$this->markTestSkipped('Test only works on platforms with sequences.');
@@ -182,7 +182,7 @@ public function testLastInsertIdSequence()
self::assertEquals($nextSequenceVal, $lastInsertId);
}
- public function testLastInsertIdNoSequenceGiven()
+ public function testLastInsertIdNoSequenceGiven() : void
{
if (! $this->connection->getDatabasePlatform()->supportsSequences() || $this->connection->getDatabasePlatform()->supportsIdentityColumns()) {
$this->markTestSkipped("Test only works consistently on platforms that support sequences and don't support identity columns.");
@@ -194,7 +194,7 @@ public function testLastInsertIdNoSequenceGiven()
/**
* @group DBAL-445
*/
- public function testInsertWithKeyValueTypes()
+ public function testInsertWithKeyValueTypes() : void
{
$testString = new DateTime('2013-04-14 10:10:10');
@@ -212,7 +212,7 @@ public function testInsertWithKeyValueTypes()
/**
* @group DBAL-445
*/
- public function testUpdateWithKeyValueTypes()
+ public function testUpdateWithKeyValueTypes() : void
{
$testString = new DateTime('2013-04-14 10:10:10');
@@ -239,7 +239,7 @@ public function testUpdateWithKeyValueTypes()
/**
* @group DBAL-445
*/
- public function testDeleteWithKeyValueTypes()
+ public function testDeleteWithKeyValueTypes() : void
{
$val = new DateTime('2013-04-14 10:10:10');
$this->connection->insert(
@@ -255,7 +255,7 @@ public function testDeleteWithKeyValueTypes()
self::assertFalse($data);
}
- public function testEmptyIdentityInsert()
+ public function testEmptyIdentityInsert() : void
{
$platform = $this->connection->getDatabasePlatform();
@@ -298,7 +298,7 @@ public function testEmptyIdentityInsert()
/**
* @group DBAL-2688
*/
- public function testUpdateWhereIsNull()
+ public function testUpdateWhereIsNull() : void
{
$this->connection->insert(
'write_table',
@@ -317,7 +317,7 @@ public function testUpdateWhereIsNull()
self::assertCount(0, $data);
}
- public function testDeleteWhereIsNull()
+ public function testDeleteWhereIsNull() : void
{
$this->connection->insert(
'write_table',
@@ -340,7 +340,7 @@ public function testDeleteWhereIsNull()
* Returns the ID of the last inserted row or skips the test if the currently used driver
* doesn't support this feature
*
- * @return string
+ * @return string|false
*
* @throws DriverException
*/
diff --git a/tests/Doctrine/Tests/DBAL/Logging/DebugStackTest.php b/tests/Doctrine/Tests/DBAL/Logging/DebugStackTest.php
index 914351c75dc..26b5a959350 100644
--- a/tests/Doctrine/Tests/DBAL/Logging/DebugStackTest.php
+++ b/tests/Doctrine/Tests/DBAL/Logging/DebugStackTest.php
@@ -10,17 +10,17 @@ class DebugStackTest extends DbalTestCase
/** @var DebugStack */
private $logger;
- protected function setUp()
+ protected function setUp() : void
{
$this->logger = new DebugStack();
}
- protected function tearDown()
+ protected function tearDown() : void
{
unset($this->logger);
}
- public function testLoggedQuery()
+ public function testLoggedQuery() : void
{
$this->logger->startQuery('SELECT column FROM table');
self::assertEquals(
@@ -39,7 +39,7 @@ public function testLoggedQuery()
self::assertGreaterThan(0, $this->logger->queries[1]['executionMS']);
}
- public function testLoggedQueryDisabled()
+ public function testLoggedQueryDisabled() : void
{
$this->logger->enabled = false;
$this->logger->startQuery('SELECT column FROM table');
diff --git a/tests/Doctrine/Tests/DBAL/Logging/LoggerChainTest.php b/tests/Doctrine/Tests/DBAL/Logging/LoggerChainTest.php
new file mode 100644
index 00000000000..60d9c669d13
--- /dev/null
+++ b/tests/Doctrine/Tests/DBAL/Logging/LoggerChainTest.php
@@ -0,0 +1,56 @@
+createChain('startQuery', $sql, $params, $types);
+ $listener->startQuery($sql, $params, $types);
+ }
+
+ public function testStopQuery() : void
+ {
+ $listener = $this->createChain('stopQuery');
+ $listener->stopQuery();
+ }
+
+ /**
+ * @param mixed ...$args
+ */
+ private function createChain(string $method, ...$args) : LoggerChain
+ {
+ $chain = new LoggerChain([
+ $this->createLogger($method, ...$args),
+ ]);
+
+ $chain->addLogger($this->createLogger($method, ...$args));
+
+ return $chain;
+ }
+
+ /**
+ * @param mixed ...$args
+ */
+ private function createLogger(string $method, ...$args) : SQLLogger
+ {
+ $logger = $this->createMock(SQLLogger::class);
+ $logger->expects($this->once())
+ ->method($method)
+ ->with(...$args);
+
+ return $logger;
+ }
+}
diff --git a/tests/Doctrine/Tests/DBAL/Mocks/MockPlatform.php b/tests/Doctrine/Tests/DBAL/Mocks/MockPlatform.php
deleted file mode 100644
index 6a3f3d8e376..00000000000
--- a/tests/Doctrine/Tests/DBAL/Mocks/MockPlatform.php
+++ /dev/null
@@ -1,100 +0,0 @@
-stopTiming();
}
- public function itemCountProvider()
+ /**
+ * @return mixed[][]
+ */
+ public static function itemCountProvider() : iterable
{
return [
'100 items' => [100],
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/AbstractMySQLPlatformTestCase.php b/tests/Doctrine/Tests/DBAL/Platforms/AbstractMySQLPlatformTestCase.php
index 63148215f22..bbae08c5b2c 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/AbstractMySQLPlatformTestCase.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/AbstractMySQLPlatformTestCase.php
@@ -13,44 +13,53 @@
abstract class AbstractMySQLPlatformTestCase extends AbstractPlatformTestCase
{
- public function testModifyLimitQueryWitoutLimit()
+ /** @var MySqlPlatform */
+ protected $platform;
+
+ public function testModifyLimitQueryWitoutLimit() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT n FROM Foo', null, 10);
self::assertEquals('SELECT n FROM Foo LIMIT 18446744073709551615 OFFSET 10', $sql);
}
- public function testGenerateMixedCaseTableCreate()
+ public function testGenerateMixedCaseTableCreate() : void
{
$table = new Table('Foo');
$table->addColumn('Bar', 'integer');
$sql = $this->platform->getCreateTableSQL($table);
- self::assertEquals('CREATE TABLE Foo (Bar INT NOT NULL) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB', array_shift($sql));
+ self::assertEquals('CREATE TABLE Foo (Bar INT NOT NULL) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB', array_shift($sql));
}
- public function getGenerateTableSql()
+ public function getGenerateTableSql() : string
{
- return 'CREATE TABLE test (id INT AUTO_INCREMENT NOT NULL, test VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB';
+ return 'CREATE TABLE test (id INT AUTO_INCREMENT NOT NULL, test VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB';
}
- public function getGenerateTableWithMultiColumnUniqueIndexSql()
+ /**
+ * @return string[]
+ */
+ public function getGenerateTableWithMultiColumnUniqueIndexSql() : array
{
- return ['CREATE TABLE test (foo VARCHAR(255) DEFAULT NULL, bar VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_D87F7E0C8C73652176FF8CAA (foo, bar)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'];
+ return ['CREATE TABLE test (foo VARCHAR(255) DEFAULT NULL, bar VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_D87F7E0C8C73652176FF8CAA (foo, bar)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB'];
}
- public function getGenerateAlterTableSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateAlterTableSql() : array
{
return ["ALTER TABLE mytable RENAME TO userlist, ADD quota INT DEFAULT NULL, DROP foo, CHANGE bar baz VARCHAR(255) DEFAULT 'def' NOT NULL, CHANGE bloo bloo TINYINT(1) DEFAULT '0' NOT NULL"];
}
- public function testGeneratesSqlSnippets()
+ public function testGeneratesSqlSnippets() : void
{
self::assertEquals('RLIKE', $this->platform->getRegexpExpression(), 'Regular expression operator is not correct');
self::assertEquals('`', $this->platform->getIdentifierQuoteCharacter(), 'Quote character is not correct');
self::assertEquals('CONCAT(column1, column2, column3)', $this->platform->getConcatExpression('column1', 'column2', 'column3'), 'Concatenation function is not correct');
}
- public function testGeneratesTransactionsCommands()
+ public function testGeneratesTransactionsCommands() : void
{
self::assertEquals(
'SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED',
@@ -71,8 +80,7 @@ public function testGeneratesTransactionsCommands()
);
}
-
- public function testGeneratesDDLSnippets()
+ public function testGeneratesDDLSnippets() : void
{
self::assertEquals('SHOW DATABASES', $this->platform->getListDatabasesSQL());
self::assertEquals('CREATE DATABASE foobar', $this->platform->getCreateDatabaseSQL('foobar'));
@@ -80,7 +88,7 @@ public function testGeneratesDDLSnippets()
self::assertEquals('DROP TABLE foobar', $this->platform->getDropTableSQL('foobar'));
}
- public function testGeneratesTypeDeclarationForIntegers()
+ public function testGeneratesTypeDeclarationForIntegers() : void
{
self::assertEquals(
'INT',
@@ -98,7 +106,7 @@ public function testGeneratesTypeDeclarationForIntegers()
);
}
- public function testGeneratesTypeDeclarationForStrings()
+ public function testGeneratesTypeDeclarationForStrings() : void
{
self::assertEquals(
'CHAR(10)',
@@ -118,32 +126,32 @@ public function testGeneratesTypeDeclarationForStrings()
);
}
- public function testPrefersIdentityColumns()
+ public function testPrefersIdentityColumns() : void
{
self::assertTrue($this->platform->prefersIdentityColumns());
}
- public function testSupportsIdentityColumns()
+ public function testSupportsIdentityColumns() : void
{
self::assertTrue($this->platform->supportsIdentityColumns());
}
- public function testDoesSupportSavePoints()
+ public function testDoesSupportSavePoints() : void
{
self::assertTrue($this->platform->supportsSavepoints());
}
- public function getGenerateIndexSql()
+ public function getGenerateIndexSql() : string
{
return 'CREATE INDEX my_idx ON mytable (user_name, last_login)';
}
- public function getGenerateUniqueIndexSql()
+ public function getGenerateUniqueIndexSql() : string
{
return 'CREATE UNIQUE INDEX index_name ON test (test, test2)';
}
- public function getGenerateForeignKeySql()
+ public function getGenerateForeignKeySql() : string
{
return 'ALTER TABLE test ADD FOREIGN KEY (fk_name_id) REFERENCES other_table (id)';
}
@@ -151,7 +159,7 @@ public function getGenerateForeignKeySql()
/**
* @group DBAL-126
*/
- public function testUniquePrimaryKey()
+ public function testUniquePrimaryKey() : void
{
$keyTable = new Table('foo');
$keyTable->addColumn('bar', 'integer');
@@ -174,13 +182,13 @@ public function testUniquePrimaryKey()
], $sql);
}
- public function testModifyLimitQuery()
+ public function testModifyLimitQuery() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', 10, 0);
self::assertEquals('SELECT * FROM user LIMIT 10', $sql);
}
- public function testModifyLimitQueryWithEmptyOffset()
+ public function testModifyLimitQueryWithEmptyOffset() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', 10);
self::assertEquals('SELECT * FROM user LIMIT 10', $sql);
@@ -189,32 +197,41 @@ public function testModifyLimitQueryWithEmptyOffset()
/**
* @group DDC-118
*/
- public function testGetDateTimeTypeDeclarationSql()
+ public function testGetDateTimeTypeDeclarationSql() : void
{
self::assertEquals('DATETIME', $this->platform->getDateTimeTypeDeclarationSQL(['version' => false]));
self::assertEquals('TIMESTAMP', $this->platform->getDateTimeTypeDeclarationSQL(['version' => true]));
self::assertEquals('DATETIME', $this->platform->getDateTimeTypeDeclarationSQL([]));
}
- public function getCreateTableColumnCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getCreateTableColumnCommentsSQL() : array
{
- return ["CREATE TABLE test (id INT NOT NULL COMMENT 'This is a comment', PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"];
+ return ["CREATE TABLE test (id INT NOT NULL COMMENT 'This is a comment', PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB"];
}
- public function getAlterTableColumnCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getAlterTableColumnCommentsSQL() : array
{
return ["ALTER TABLE mytable ADD quota INT NOT NULL COMMENT 'A comment', CHANGE foo foo VARCHAR(255) NOT NULL, CHANGE bar baz VARCHAR(255) NOT NULL COMMENT 'B comment'"];
}
- public function getCreateTableColumnTypeCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getCreateTableColumnTypeCommentsSQL() : array
{
- return ["CREATE TABLE test (id INT NOT NULL, data LONGTEXT NOT NULL COMMENT '(DC2Type:array)', PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"];
+ return ["CREATE TABLE test (id INT NOT NULL, data LONGTEXT NOT NULL COMMENT '(DC2Type:array)', PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB"];
}
/**
* @group DBAL-237
*/
- public function testChangeIndexWithForeignKeys()
+ public function testChangeIndexWithForeignKeys() : void
{
$index = new Index('idx', ['col'], false);
$unique = new Index('uniq', ['col'], true);
@@ -228,32 +245,44 @@ public function testChangeIndexWithForeignKeys()
self::assertEquals(['ALTER TABLE test DROP INDEX uniq, ADD INDEX idx (col)'], $sql);
}
- protected function getQuotedColumnInPrimaryKeySQL()
+ /**
+ * @return string[]
+ */
+ protected function getQuotedColumnInPrimaryKeySQL() : array
{
- return ['CREATE TABLE `quoted` (`create` VARCHAR(255) NOT NULL, PRIMARY KEY(`create`)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'];
+ return ['CREATE TABLE `quoted` (`create` VARCHAR(255) NOT NULL, PRIMARY KEY(`create`)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB'];
}
- protected function getQuotedColumnInIndexSQL()
+ /**
+ * @return string[]
+ */
+ protected function getQuotedColumnInIndexSQL() : array
{
- return ['CREATE TABLE `quoted` (`create` VARCHAR(255) NOT NULL, INDEX IDX_22660D028FD6E0FB (`create`)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'];
+ return ['CREATE TABLE `quoted` (`create` VARCHAR(255) NOT NULL, INDEX IDX_22660D028FD6E0FB (`create`)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB'];
}
- protected function getQuotedNameInIndexSQL()
+ /**
+ * @return string[]
+ */
+ protected function getQuotedNameInIndexSQL() : array
{
- return ['CREATE TABLE test (column1 VARCHAR(255) NOT NULL, INDEX `key` (column1)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'];
+ return ['CREATE TABLE test (column1 VARCHAR(255) NOT NULL, INDEX `key` (column1)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB'];
}
- protected function getQuotedColumnInForeignKeySQL()
+ /**
+ * @return string[]
+ */
+ protected function getQuotedColumnInForeignKeySQL() : array
{
return [
- 'CREATE TABLE `quoted` (`create` VARCHAR(255) NOT NULL, foo VARCHAR(255) NOT NULL, `bar` VARCHAR(255) NOT NULL) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB',
+ 'CREATE TABLE `quoted` (`create` VARCHAR(255) NOT NULL, foo VARCHAR(255) NOT NULL, `bar` VARCHAR(255) NOT NULL) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB',
'ALTER TABLE `quoted` ADD CONSTRAINT FK_WITH_RESERVED_KEYWORD FOREIGN KEY (`create`, foo, `bar`) REFERENCES `foreign` (`create`, bar, `foo-bar`)',
'ALTER TABLE `quoted` ADD CONSTRAINT FK_WITH_NON_RESERVED_KEYWORD FOREIGN KEY (`create`, foo, `bar`) REFERENCES foo (`create`, bar, `foo-bar`)',
'ALTER TABLE `quoted` ADD CONSTRAINT FK_WITH_INTENDED_QUOTATION FOREIGN KEY (`create`, foo, `bar`) REFERENCES `foo-bar` (`create`, bar, `foo-bar`)',
];
}
- public function testCreateTableWithFulltextIndex()
+ public function testCreateTableWithFulltextIndex() : void
{
$table = new Table('fulltext_table');
$table->addOption('engine', 'MyISAM');
@@ -264,10 +293,10 @@ public function testCreateTableWithFulltextIndex()
$index->addFlag('fulltext');
$sql = $this->platform->getCreateTableSQL($table);
- self::assertEquals(['CREATE TABLE fulltext_table (text LONGTEXT NOT NULL, FULLTEXT INDEX fulltext_text (text)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = MyISAM'], $sql);
+ self::assertEquals(['CREATE TABLE fulltext_table (text LONGTEXT NOT NULL, FULLTEXT INDEX fulltext_text (text)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = MyISAM'], $sql);
}
- public function testCreateTableWithSpatialIndex()
+ public function testCreateTableWithSpatialIndex() : void
{
$table = new Table('spatial_table');
$table->addOption('engine', 'MyISAM');
@@ -278,10 +307,10 @@ public function testCreateTableWithSpatialIndex()
$index->addFlag('spatial');
$sql = $this->platform->getCreateTableSQL($table);
- self::assertEquals(['CREATE TABLE spatial_table (point LONGTEXT NOT NULL, SPATIAL INDEX spatial_text (point)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = MyISAM'], $sql);
+ self::assertEquals(['CREATE TABLE spatial_table (point LONGTEXT NOT NULL, SPATIAL INDEX spatial_text (point)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = MyISAM'], $sql);
}
- public function testClobTypeDeclarationSQL()
+ public function testClobTypeDeclarationSQL() : void
{
self::assertEquals('TINYTEXT', $this->platform->getClobTypeDeclarationSQL(['length' => 1]));
self::assertEquals('TINYTEXT', $this->platform->getClobTypeDeclarationSQL(['length' => 255]));
@@ -293,7 +322,7 @@ public function testClobTypeDeclarationSQL()
self::assertEquals('LONGTEXT', $this->platform->getClobTypeDeclarationSQL([]));
}
- public function testBlobTypeDeclarationSQL()
+ public function testBlobTypeDeclarationSQL() : void
{
self::assertEquals('TINYBLOB', $this->platform->getBlobTypeDeclarationSQL(['length' => 1]));
self::assertEquals('TINYBLOB', $this->platform->getBlobTypeDeclarationSQL(['length' => 255]));
@@ -308,7 +337,7 @@ public function testBlobTypeDeclarationSQL()
/**
* @group DBAL-400
*/
- public function testAlterTableAddPrimaryKey()
+ public function testAlterTableAddPrimaryKey() : void
{
$table = new Table('alter_table_add_pk');
$table->addColumn('id', 'integer');
@@ -330,7 +359,7 @@ public function testAlterTableAddPrimaryKey()
/**
* @group DBAL-1132
*/
- public function testAlterPrimaryKeyWithAutoincrementColumn()
+ public function testAlterPrimaryKeyWithAutoincrementColumn() : void
{
$table = new Table('alter_primary_key');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -356,7 +385,7 @@ public function testAlterPrimaryKeyWithAutoincrementColumn()
/**
* @group DBAL-464
*/
- public function testDropPrimaryKeyWithAutoincrementColumn()
+ public function testDropPrimaryKeyWithAutoincrementColumn() : void
{
$table = new Table('drop_primary_key');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -381,7 +410,7 @@ public function testDropPrimaryKeyWithAutoincrementColumn()
/**
* @group DBAL-2302
*/
- public function testDropNonAutoincrementColumnFromCompositePrimaryKeyWithAutoincrementColumn()
+ public function testDropNonAutoincrementColumnFromCompositePrimaryKeyWithAutoincrementColumn() : void
{
$table = new Table('tbl');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -408,7 +437,7 @@ public function testDropNonAutoincrementColumnFromCompositePrimaryKeyWithAutoinc
/**
* @group DBAL-2302
*/
- public function testAddNonAutoincrementColumnToPrimaryKeyWithAutoincrementColumn()
+ public function testAddNonAutoincrementColumnToPrimaryKeyWithAutoincrementColumn() : void
{
$table = new Table('tbl');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -435,7 +464,7 @@ public function testAddNonAutoincrementColumnToPrimaryKeyWithAutoincrementColumn
/**
* @group DBAL-586
*/
- public function testAddAutoIncrementPrimaryKey()
+ public function testAddAutoIncrementPrimaryKey() : void
{
$keyTable = new Table('foo');
$keyTable->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -453,7 +482,7 @@ public function testAddAutoIncrementPrimaryKey()
self::assertEquals(['ALTER TABLE foo ADD id INT AUTO_INCREMENT NOT NULL, ADD PRIMARY KEY (id)'], $sql);
}
- public function testNamedPrimaryKey()
+ public function testNamedPrimaryKey() : void
{
$diff = new TableDiff('mytable');
$diff->changedIndexes['foo_index'] = new Index('foo_index', ['foo'], true, true);
@@ -466,7 +495,7 @@ public function testNamedPrimaryKey()
], $sql);
}
- public function testAlterPrimaryKeyWithNewColumn()
+ public function testAlterPrimaryKeyWithNewColumn() : void
{
$table = new Table('yolo');
$table->addColumn('pkc1', 'integer');
@@ -490,7 +519,7 @@ public function testAlterPrimaryKeyWithNewColumn()
);
}
- public function testInitializesDoctrineTypeMappings()
+ public function testInitializesDoctrineTypeMappings() : void
{
self::assertTrue($this->platform->hasDoctrineTypeMappingFor('binary'));
self::assertSame('binary', $this->platform->getDoctrineTypeMapping('binary'));
@@ -499,12 +528,12 @@ public function testInitializesDoctrineTypeMappings()
self::assertSame('binary', $this->platform->getDoctrineTypeMapping('varbinary'));
}
- protected function getBinaryMaxLength()
+ protected function getBinaryMaxLength() : int
{
return 65535;
}
- public function testReturnsBinaryTypeDeclarationSQL()
+ public function testReturnsBinaryTypeDeclarationSQL() : void
{
self::assertSame('VARBINARY(255)', $this->platform->getBinaryTypeDeclarationSQL([]));
self::assertSame('VARBINARY(255)', $this->platform->getBinaryTypeDeclarationSQL(['length' => 0]));
@@ -521,7 +550,7 @@ public function testReturnsBinaryTypeDeclarationSQL()
* @expectedDeprecation Binary field length 16777215 is greater than supported by the platform (65535). Reduce the field length or use a BLOB field instead.
* @expectedDeprecation Binary field length 16777216 is greater than supported by the platform (65535). Reduce the field length or use a BLOB field instead.
*/
- public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL()
+ public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL() : void
{
self::assertSame('MEDIUMBLOB', $this->platform->getBinaryTypeDeclarationSQL(['length' => 65536]));
self::assertSame('MEDIUMBLOB', $this->platform->getBinaryTypeDeclarationSQL(['length' => 16777215]));
@@ -532,7 +561,7 @@ public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL()
self::assertSame('LONGBLOB', $this->platform->getBinaryTypeDeclarationSQL(['fixed' => true, 'length' => 16777216]));
}
- public function testDoesNotPropagateForeignKeyCreationForNonSupportingEngines()
+ public function testDoesNotPropagateForeignKeyCreationForNonSupportingEngines() : void
{
$table = new Table('foreign_table');
$table->addColumn('id', 'integer');
@@ -542,7 +571,7 @@ public function testDoesNotPropagateForeignKeyCreationForNonSupportingEngines()
$table->addOption('engine', 'MyISAM');
self::assertSame(
- ['CREATE TABLE foreign_table (id INT NOT NULL, fk_id INT NOT NULL, INDEX IDX_5690FFE2A57719D0 (fk_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = MyISAM'],
+ ['CREATE TABLE foreign_table (id INT NOT NULL, fk_id INT NOT NULL, INDEX IDX_5690FFE2A57719D0 (fk_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = MyISAM'],
$this->platform->getCreateTableSQL(
$table,
AbstractPlatform::CREATE_INDEXES|AbstractPlatform::CREATE_FOREIGNKEYS
@@ -554,7 +583,7 @@ public function testDoesNotPropagateForeignKeyCreationForNonSupportingEngines()
self::assertSame(
[
- 'CREATE TABLE foreign_table (id INT NOT NULL, fk_id INT NOT NULL, INDEX IDX_5690FFE2A57719D0 (fk_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB',
+ 'CREATE TABLE foreign_table (id INT NOT NULL, fk_id INT NOT NULL, INDEX IDX_5690FFE2A57719D0 (fk_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB',
'ALTER TABLE foreign_table ADD CONSTRAINT FK_5690FFE2A57719D0 FOREIGN KEY (fk_id) REFERENCES foreign_table (id)',
],
$this->platform->getCreateTableSQL(
@@ -564,7 +593,7 @@ public function testDoesNotPropagateForeignKeyCreationForNonSupportingEngines()
);
}
- public function testDoesNotPropagateForeignKeyAlterationForNonSupportingEngines()
+ public function testDoesNotPropagateForeignKeyAlterationForNonSupportingEngines() : void
{
$table = new Table('foreign_table');
$table->addColumn('id', 'integer');
@@ -605,9 +634,11 @@ public function testDoesNotPropagateForeignKeyAlterationForNonSupportingEngines(
}
/**
+ * @return string[]
+ *
* @group DBAL-234
*/
- protected function getAlterTableRenameIndexSQL()
+ protected function getAlterTableRenameIndexSQL() : array
{
return [
'DROP INDEX idx_foo ON mytable',
@@ -616,9 +647,11 @@ protected function getAlterTableRenameIndexSQL()
}
/**
+ * @return string[]
+ *
* @group DBAL-234
*/
- protected function getQuotedAlterTableRenameIndexSQL()
+ protected function getQuotedAlterTableRenameIndexSQL() : array
{
return [
'DROP INDEX `create` ON `table`',
@@ -629,9 +662,11 @@ protected function getQuotedAlterTableRenameIndexSQL()
}
/**
+ * @return string[]
+ *
* @group DBAL-807
*/
- protected function getAlterTableRenameIndexInSchemaSQL()
+ protected function getAlterTableRenameIndexInSchemaSQL() : array
{
return [
'DROP INDEX idx_foo ON myschema.mytable',
@@ -640,9 +675,11 @@ protected function getAlterTableRenameIndexInSchemaSQL()
}
/**
+ * @return string[]
+ *
* @group DBAL-807
*/
- protected function getQuotedAlterTableRenameIndexInSchemaSQL()
+ protected function getQuotedAlterTableRenameIndexInSchemaSQL() : array
{
return [
'DROP INDEX `create` ON `schema`.`table`',
@@ -652,17 +689,17 @@ protected function getQuotedAlterTableRenameIndexInSchemaSQL()
];
}
- protected function getQuotesDropForeignKeySQL()
+ protected function getQuotesDropForeignKeySQL() : string
{
return 'ALTER TABLE `table` DROP FOREIGN KEY `select`';
}
- protected function getQuotesDropConstraintSQL()
+ protected function getQuotesDropConstraintSQL() : string
{
return 'ALTER TABLE `table` DROP CONSTRAINT `select`';
}
- public function testDoesNotPropagateDefaultValuesForUnsupportedColumnTypes()
+ public function testDoesNotPropagateDefaultValuesForUnsupportedColumnTypes() : void
{
$table = new Table('text_blob_default_value');
$table->addColumn('def_text', 'text', ['default' => 'def']);
@@ -671,7 +708,7 @@ public function testDoesNotPropagateDefaultValuesForUnsupportedColumnTypes()
$table->addColumn('def_blob_null', 'blob', ['notnull' => false, 'default' => 'def']);
self::assertSame(
- ['CREATE TABLE text_blob_default_value (def_text LONGTEXT NOT NULL, def_text_null LONGTEXT DEFAULT NULL, def_blob LONGBLOB NOT NULL, def_blob_null LONGBLOB DEFAULT NULL) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'],
+ ['CREATE TABLE text_blob_default_value (def_text LONGTEXT NOT NULL, def_text_null LONGTEXT DEFAULT NULL, def_blob LONGBLOB NOT NULL, def_blob_null LONGBLOB DEFAULT NULL) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB'],
$this->platform->getCreateTableSQL($table)
);
@@ -689,7 +726,7 @@ public function testDoesNotPropagateDefaultValuesForUnsupportedColumnTypes()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableRenameColumnSQL()
+ protected function getQuotedAlterTableRenameColumnSQL() : array
{
return ['ALTER TABLE mytable ' .
"CHANGE unquoted1 unquoted INT NOT NULL COMMENT 'Unquoted 1', " .
@@ -707,7 +744,7 @@ protected function getQuotedAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableChangeColumnLengthSQL()
+ protected function getQuotedAlterTableChangeColumnLengthSQL() : array
{
return ['ALTER TABLE mytable ' .
"CHANGE unquoted1 unquoted1 VARCHAR(255) NOT NULL COMMENT 'Unquoted 1', " .
@@ -722,7 +759,7 @@ protected function getQuotedAlterTableChangeColumnLengthSQL()
/**
* @group DBAL-423
*/
- public function testReturnsGuidTypeDeclarationSQL()
+ public function testReturnsGuidTypeDeclarationSQL() : void
{
self::assertSame('CHAR(36)', $this->platform->getGuidTypeDeclarationSQL([]));
}
@@ -730,7 +767,7 @@ public function testReturnsGuidTypeDeclarationSQL()
/**
* {@inheritdoc}
*/
- public function getAlterTableRenameColumnSQL()
+ public function getAlterTableRenameColumnSQL() : array
{
return ["ALTER TABLE foo CHANGE bar baz INT DEFAULT 666 NOT NULL COMMENT 'rename test'"];
}
@@ -738,7 +775,7 @@ public function getAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesTableIdentifiersInAlterTableSQL()
+ protected function getQuotesTableIdentifiersInAlterTableSQL() : array
{
return [
'ALTER TABLE `foo` DROP FOREIGN KEY fk1',
@@ -753,7 +790,7 @@ protected function getQuotesTableIdentifiersInAlterTableSQL()
/**
* {@inheritdoc}
*/
- protected function getCommentOnColumnSQL()
+ protected function getCommentOnColumnSQL() : array
{
return [
"COMMENT ON COLUMN foo.bar IS 'comment'",
@@ -765,7 +802,7 @@ protected function getCommentOnColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
+ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL() : string
{
return 'CONSTRAINT `select` UNIQUE (foo)';
}
@@ -773,7 +810,7 @@ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInIndexDeclarationSQL()
+ protected function getQuotesReservedKeywordInIndexDeclarationSQL() : string
{
return 'INDEX `select` (foo)';
}
@@ -781,7 +818,7 @@ protected function getQuotesReservedKeywordInIndexDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInTruncateTableSQL()
+ protected function getQuotesReservedKeywordInTruncateTableSQL() : string
{
return 'TRUNCATE `select`';
}
@@ -789,7 +826,7 @@ protected function getQuotesReservedKeywordInTruncateTableSQL()
/**
* {@inheritdoc}
*/
- protected function getAlterStringToFixedStringSQL()
+ protected function getAlterStringToFixedStringSQL() : array
{
return ['ALTER TABLE mytable CHANGE name name CHAR(2) NOT NULL'];
}
@@ -797,7 +834,7 @@ protected function getAlterStringToFixedStringSQL()
/**
* {@inheritdoc}
*/
- protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
+ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : array
{
return [
'ALTER TABLE mytable DROP FOREIGN KEY fk_foo',
@@ -810,7 +847,7 @@ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
/**
* {@inheritdoc}
*/
- public function getGeneratesDecimalTypeDeclarationSQL()
+ public static function getGeneratesDecimalTypeDeclarationSQL() : iterable
{
return [
[[], 'NUMERIC(10, 0)'],
@@ -825,7 +862,7 @@ public function getGeneratesDecimalTypeDeclarationSQL()
/**
* {@inheritdoc}
*/
- public function getGeneratesFloatDeclarationSQL()
+ public static function getGeneratesFloatDeclarationSQL() : iterable
{
return [
[[], 'DOUBLE PRECISION'],
@@ -840,69 +877,98 @@ public function getGeneratesFloatDeclarationSQL()
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableIndexesSQL()
+ public function testQuotesTableNameInListTableIndexesSQL() : void
{
- self::assertContains("'Foo''Bar\\\\'", $this->platform->getListTableIndexesSQL("Foo'Bar\\", 'foo_db'), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\\\'",
+ $this->platform->getListTableIndexesSQL("Foo'Bar\\", 'foo_db')
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesDatabaseNameInListTableIndexesSQL()
+ public function testQuotesDatabaseNameInListTableIndexesSQL() : void
{
- self::assertContains("'Foo''Bar\\\\'", $this->platform->getListTableIndexesSQL('foo_table', "Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\\\'",
+ $this->platform->getListTableIndexesSQL('foo_table', "Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesDatabaseNameInListViewsSQL()
+ public function testQuotesDatabaseNameInListViewsSQL() : void
{
- self::assertContains("'Foo''Bar\\\\'", $this->platform->getListViewsSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\\\'",
+ $this->platform->getListViewsSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableForeignKeysSQL()
+ public function testQuotesTableNameInListTableForeignKeysSQL() : void
{
- self::assertContains("'Foo''Bar\\\\'", $this->platform->getListTableForeignKeysSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\\\'",
+ $this->platform->getListTableForeignKeysSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesDatabaseNameInListTableForeignKeysSQL()
+ public function testQuotesDatabaseNameInListTableForeignKeysSQL() : void
{
- self::assertContains("'Foo''Bar\\\\'", $this->platform->getListTableForeignKeysSQL('foo_table', "Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\\\'",
+ $this->platform->getListTableForeignKeysSQL('foo_table', "Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableColumnsSQL()
+ public function testQuotesTableNameInListTableColumnsSQL() : void
{
- self::assertContains("'Foo''Bar\\\\'", $this->platform->getListTableColumnsSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\\\'",
+ $this->platform->getListTableColumnsSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesDatabaseNameInListTableColumnsSQL()
+ public function testQuotesDatabaseNameInListTableColumnsSQL() : void
{
- self::assertContains("'Foo''Bar\\\\'", $this->platform->getListTableColumnsSQL('foo_table', "Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\\\'",
+ $this->platform->getListTableColumnsSQL('foo_table', "Foo'Bar\\")
+ );
}
- public function testListTableForeignKeysSQLEvaluatesDatabase()
+ public function testListTableForeignKeysSQLEvaluatesDatabase() : void
{
$sql = $this->platform->getListTableForeignKeysSQL('foo');
- self::assertContains('DATABASE()', $sql);
+ self::assertStringContainsString('DATABASE()', $sql);
$sql = $this->platform->getListTableForeignKeysSQL('foo', 'bar');
- self::assertContains('bar', $sql);
- self::assertNotContains('DATABASE()', $sql);
+ self::assertStringContainsString('bar', $sql);
+ self::assertStringNotContainsString('DATABASE()', $sql);
+ }
+
+ public function testColumnCharsetDeclarationSQL() : void
+ {
+ self::assertSame(
+ 'CHARACTER SET ascii',
+ $this->platform->getColumnCharsetDeclarationSQL('ascii')
+ );
}
public function testSupportsColumnCollation() : void
@@ -913,7 +979,7 @@ public function testSupportsColumnCollation() : void
public function testColumnCollationDeclarationSQL() : void
{
self::assertSame(
- 'COLLATE ascii_general_ci',
+ 'COLLATE `ascii_general_ci`',
$this->platform->getColumnCollationDeclarationSQL('ascii_general_ci')
);
}
@@ -925,7 +991,7 @@ public function testGetCreateTableSQLWithColumnCollation() : void
$table->addColumn('column_collation', 'string')->setPlatformOption('collation', 'ascii_general_ci');
self::assertSame(
- ['CREATE TABLE foo (no_collation VARCHAR(255) NOT NULL, column_collation VARCHAR(255) NOT NULL COLLATE ascii_general_ci) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'],
+ ['CREATE TABLE foo (no_collation VARCHAR(255) NOT NULL, column_collation VARCHAR(255) NOT NULL COLLATE `ascii_general_ci`) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB'],
$this->platform->getCreateTableSQL($table),
'Column "no_collation" will use the default collation from the table/database and "column_collation" overwrites the collation on this column'
);
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/AbstractPlatformTestCase.php b/tests/Doctrine/Tests/DBAL/Platforms/AbstractPlatformTestCase.php
index 8fee20fede2..1ef4e65e322 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/AbstractPlatformTestCase.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/AbstractPlatformTestCase.php
@@ -27,9 +27,9 @@ abstract class AbstractPlatformTestCase extends DbalTestCase
/** @var AbstractPlatform */
protected $platform;
- abstract public function createPlatform();
+ abstract public function createPlatform() : AbstractPlatform;
- protected function setUp()
+ protected function setUp() : void
{
$this->platform = $this->createPlatform();
}
@@ -37,7 +37,7 @@ protected function setUp()
/**
* @group DDC-1360
*/
- public function testQuoteIdentifier()
+ public function testQuoteIdentifier() : void
{
if ($this->platform->getName() === 'mssql') {
$this->markTestSkipped('Not working this way on mssql.');
@@ -52,7 +52,7 @@ public function testQuoteIdentifier()
/**
* @group DDC-1360
*/
- public function testQuoteSingleIdentifier()
+ public function testQuoteSingleIdentifier() : void
{
if ($this->platform->getName() === 'mssql') {
$this->markTestSkipped('Not working this way on mssql.');
@@ -68,15 +68,15 @@ public function testQuoteSingleIdentifier()
* @group DBAL-1029
* @dataProvider getReturnsForeignKeyReferentialActionSQL
*/
- public function testReturnsForeignKeyReferentialActionSQL($action, $expectedSQL)
+ public function testReturnsForeignKeyReferentialActionSQL(string $action, string $expectedSQL) : void
{
self::assertSame($expectedSQL, $this->platform->getForeignKeyReferentialActionSQL($action));
}
/**
- * @return string[][]
+ * @return mixed[][]
*/
- public function getReturnsForeignKeyReferentialActionSQL()
+ public static function getReturnsForeignKeyReferentialActionSQL() : iterable
{
return [
['CASCADE', 'CASCADE'],
@@ -88,25 +88,25 @@ public function getReturnsForeignKeyReferentialActionSQL()
];
}
- public function testGetInvalidForeignKeyReferentialActionSQL()
+ public function testGetInvalidForeignKeyReferentialActionSQL() : void
{
$this->expectException('InvalidArgumentException');
$this->platform->getForeignKeyReferentialActionSQL('unknown');
}
- public function testGetUnknownDoctrineMappingType()
+ public function testGetUnknownDoctrineMappingType() : void
{
$this->expectException(DBALException::class);
$this->platform->getDoctrineTypeMapping('foobar');
}
- public function testRegisterDoctrineMappingType()
+ public function testRegisterDoctrineMappingType() : void
{
$this->platform->registerDoctrineTypeMapping('foo', 'integer');
self::assertEquals('integer', $this->platform->getDoctrineTypeMapping('foo'));
}
- public function testRegisterUnknownDoctrineMappingType()
+ public function testRegisterUnknownDoctrineMappingType() : void
{
$this->expectException(DBALException::class);
$this->platform->registerDoctrineTypeMapping('foo', 'bar');
@@ -115,7 +115,7 @@ public function testRegisterUnknownDoctrineMappingType()
/**
* @group DBAL-2594
*/
- public function testRegistersCommentedDoctrineMappingTypeImplicitly()
+ public function testRegistersCommentedDoctrineMappingTypeImplicitly() : void
{
if (! Type::hasType('my_commented')) {
Type::addType('my_commented', CommentedType::class);
@@ -131,12 +131,15 @@ public function testRegistersCommentedDoctrineMappingTypeImplicitly()
* @group DBAL-939
* @dataProvider getIsCommentedDoctrineType
*/
- public function testIsCommentedDoctrineType(Type $type, $commented)
+ public function testIsCommentedDoctrineType(Type $type, bool $commented) : void
{
self::assertSame($commented, $this->platform->isCommentedDoctrineType($type));
}
- public function getIsCommentedDoctrineType()
+ /**
+ * @return mixed[]
+ */
+ public function getIsCommentedDoctrineType() : iterable
{
$this->setUp();
@@ -154,7 +157,7 @@ public function getIsCommentedDoctrineType()
return $data;
}
- public function testCreateWithNoColumns()
+ public function testCreateWithNoColumns() : void
{
$table = new Table('test');
@@ -162,7 +165,7 @@ public function testCreateWithNoColumns()
$sql = $this->platform->getCreateTableSQL($table);
}
- public function testGeneratesTableCreationSql()
+ public function testGeneratesTableCreationSql() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer', ['notnull' => true, 'autoincrement' => true]);
@@ -173,9 +176,9 @@ public function testGeneratesTableCreationSql()
self::assertEquals($this->getGenerateTableSql(), $sql[0]);
}
- abstract public function getGenerateTableSql();
+ abstract public function getGenerateTableSql() : string;
- public function testGenerateTableWithMultiColumnUniqueIndex()
+ public function testGenerateTableWithMultiColumnUniqueIndex() : void
{
$table = new Table('test');
$table->addColumn('foo', 'string', ['notnull' => false, 'length' => 255]);
@@ -186,9 +189,12 @@ public function testGenerateTableWithMultiColumnUniqueIndex()
self::assertEquals($this->getGenerateTableWithMultiColumnUniqueIndexSql(), $sql);
}
- abstract public function getGenerateTableWithMultiColumnUniqueIndexSql();
+ /**
+ * @return string[]
+ */
+ abstract public function getGenerateTableWithMultiColumnUniqueIndexSql() : array;
- public function testGeneratesIndexCreationSql()
+ public function testGeneratesIndexCreationSql() : void
{
$indexDef = new Index('my_idx', ['user_name', 'last_login']);
@@ -198,9 +204,9 @@ public function testGeneratesIndexCreationSql()
);
}
- abstract public function getGenerateIndexSql();
+ abstract public function getGenerateIndexSql() : string;
- public function testGeneratesUniqueIndexCreationSql()
+ public function testGeneratesUniqueIndexCreationSql() : void
{
$indexDef = new Index('index_name', ['test', 'test2'], true);
@@ -208,9 +214,9 @@ public function testGeneratesUniqueIndexCreationSql()
self::assertEquals($this->getGenerateUniqueIndexSql(), $sql);
}
- abstract public function getGenerateUniqueIndexSql();
+ abstract public function getGenerateUniqueIndexSql() : string;
- public function testGeneratesPartialIndexesSqlOnlyWhenSupportingPartialIndexes()
+ public function testGeneratesPartialIndexesSqlOnlyWhenSupportingPartialIndexes() : void
{
$where = 'test IS NULL AND test2 IS NOT NULL';
$indexDef = new Index('name', ['test', 'test2'], false, false, [], ['where' => $where]);
@@ -236,7 +242,7 @@ public function testGeneratesPartialIndexesSqlOnlyWhenSupportingPartialIndexes()
}
}
- public function testGeneratesForeignKeyCreationSql()
+ public function testGeneratesForeignKeyCreationSql() : void
{
$fk = new ForeignKeyConstraint(['fk_name_id'], 'other_table', ['id'], '');
@@ -244,9 +250,9 @@ public function testGeneratesForeignKeyCreationSql()
self::assertEquals($sql, $this->getGenerateForeignKeySql());
}
- abstract public function getGenerateForeignKeySql();
+ abstract public function getGenerateForeignKeySql() : string;
- public function testGeneratesConstraintCreationSql()
+ public function testGeneratesConstraintCreationSql() : void
{
$idx = new Index('constraint_name', ['test'], true, false);
$sql = $this->platform->getCreateConstraintSQL($idx, 'test');
@@ -261,22 +267,19 @@ public function testGeneratesConstraintCreationSql()
self::assertEquals($this->getGenerateConstraintForeignKeySql($fk), $sql);
}
- public function testGeneratesForeignKeySqlOnlyWhenSupportingForeignKeys()
+ public function testGeneratesForeignKeySqlOnlyWhenSupportingForeignKeys() : void
{
$fk = new ForeignKeyConstraint(['fk_name'], 'foreign', ['id'], 'constraint_fk');
if ($this->platform->supportsForeignKeyConstraints()) {
- self::assertInternalType(
- 'string',
- $this->platform->getCreateForeignKeySQL($fk, 'test')
- );
+ self::assertIsString($this->platform->getCreateForeignKeySQL($fk, 'test'));
} else {
$this->expectException(DBALException::class);
$this->platform->getCreateForeignKeySQL($fk, 'test');
}
}
- protected function getBitAndComparisonExpressionSql($value1, $value2)
+ protected function getBitAndComparisonExpressionSql(string $value1, string $value2) : string
{
return '(' . $value1 . ' & ' . $value2 . ')';
}
@@ -284,13 +287,13 @@ protected function getBitAndComparisonExpressionSql($value1, $value2)
/**
* @group DDC-1213
*/
- public function testGeneratesBitAndComparisonExpressionSql()
+ public function testGeneratesBitAndComparisonExpressionSql() : void
{
$sql = $this->platform->getBitAndComparisonExpression(2, 4);
self::assertEquals($this->getBitAndComparisonExpressionSql(2, 4), $sql);
}
- protected function getBitOrComparisonExpressionSql($value1, $value2)
+ protected function getBitOrComparisonExpressionSql(string $value1, string $value2) : string
{
return '(' . $value1 . ' | ' . $value2 . ')';
}
@@ -298,23 +301,23 @@ protected function getBitOrComparisonExpressionSql($value1, $value2)
/**
* @group DDC-1213
*/
- public function testGeneratesBitOrComparisonExpressionSql()
+ public function testGeneratesBitOrComparisonExpressionSql() : void
{
$sql = $this->platform->getBitOrComparisonExpression(2, 4);
self::assertEquals($this->getBitOrComparisonExpressionSql(2, 4), $sql);
}
- public function getGenerateConstraintUniqueIndexSql()
+ public function getGenerateConstraintUniqueIndexSql() : string
{
return 'ALTER TABLE test ADD CONSTRAINT constraint_name UNIQUE (test)';
}
- public function getGenerateConstraintPrimaryIndexSql()
+ public function getGenerateConstraintPrimaryIndexSql() : string
{
return 'ALTER TABLE test ADD CONSTRAINT constraint_name PRIMARY KEY (test)';
}
- public function getGenerateConstraintForeignKeySql(ForeignKeyConstraint $fk)
+ public function getGenerateConstraintForeignKeySql(ForeignKeyConstraint $fk) : string
{
$quotedForeignTable = $fk->getQuotedForeignTableName($this->platform);
@@ -324,9 +327,12 @@ public function getGenerateConstraintForeignKeySql(ForeignKeyConstraint $fk)
);
}
- abstract public function getGenerateAlterTableSql();
+ /**
+ * @return string[]
+ */
+ abstract public function getGenerateAlterTableSql() : array;
- public function testGeneratesTableAlterationSql()
+ public function testGeneratesTableAlterationSql() : void
{
$expectedSql = $this->getGenerateAlterTableSql();
@@ -366,16 +372,16 @@ public function testGeneratesTableAlterationSql()
self::assertEquals($expectedSql, $sql);
}
- public function testGetCustomColumnDeclarationSql()
+ public function testGetCustomColumnDeclarationSql() : void
{
$field = ['columnDefinition' => 'MEDIUMINT(6) UNSIGNED'];
self::assertEquals('foo MEDIUMINT(6) UNSIGNED', $this->platform->getColumnDeclarationSQL('foo', $field));
}
- public function testGetCreateTableSqlDispatchEvent()
+ public function testGetCreateTableSqlDispatchEvent() : void
{
- $listenerMock = $this->getMockBuilder('GetCreateTableSqlDispatchEvenListener')
- ->setMethods(['onSchemaCreateTable', 'onSchemaCreateTableColumn'])
+ $listenerMock = $this->getMockBuilder($this->getMockClass('GetCreateTableSqlDispatchEvenListener'))
+ ->addMethods(['onSchemaCreateTable', 'onSchemaCreateTableColumn'])
->getMock();
$listenerMock
->expects($this->once())
@@ -396,10 +402,10 @@ public function testGetCreateTableSqlDispatchEvent()
$this->platform->getCreateTableSQL($table);
}
- public function testGetDropTableSqlDispatchEvent()
+ public function testGetDropTableSqlDispatchEvent() : void
{
- $listenerMock = $this->getMockBuilder('GetDropTableSqlDispatchEventListener')
- ->setMethods(['onSchemaDropTable'])
+ $listenerMock = $this->getMockBuilder($this->getMockClass('GetDropTableSqlDispatchEventListener'))
+ ->addMethods(['onSchemaDropTable'])
->getMock();
$listenerMock
->expects($this->once())
@@ -413,7 +419,7 @@ public function testGetDropTableSqlDispatchEvent()
$this->platform->getDropTableSQL('TABLE');
}
- public function testGetAlterTableSqlDispatchEvent()
+ public function testGetAlterTableSqlDispatchEvent() : void
{
$events = [
'onSchemaAlterTable',
@@ -423,8 +429,8 @@ public function testGetAlterTableSqlDispatchEvent()
'onSchemaAlterTableRenameColumn',
];
- $listenerMock = $this->getMockBuilder('GetAlterTableSqlDispatchEvenListener')
- ->setMethods($events)
+ $listenerMock = $this->getMockBuilder($this->getMockClass('GetAlterTableSqlDispatchEvenListener'))
+ ->addMethods($events)
->getMock();
$listenerMock
->expects($this->once())
@@ -480,7 +486,7 @@ public function testGetAlterTableSqlDispatchEvent()
/**
* @group DBAL-42
*/
- public function testCreateTableColumnComments()
+ public function testCreateTableColumnComments() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer', ['comment' => 'This is a comment']);
@@ -492,7 +498,7 @@ public function testCreateTableColumnComments()
/**
* @group DBAL-42
*/
- public function testAlterTableColumnComments()
+ public function testAlterTableColumnComments() : void
{
$tableDiff = new TableDiff('mytable');
$tableDiff->addedColumns['quota'] = new Column('quota', Type::getType('integer'), ['comment' => 'A comment']);
@@ -517,7 +523,7 @@ public function testAlterTableColumnComments()
self::assertEquals($this->getAlterTableColumnCommentsSQL(), $this->platform->getAlterTableSQL($tableDiff));
}
- public function testCreateTableColumnTypeComments()
+ public function testCreateTableColumnTypeComments() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
@@ -527,22 +533,31 @@ public function testCreateTableColumnTypeComments()
self::assertEquals($this->getCreateTableColumnTypeCommentsSQL(), $this->platform->getCreateTableSQL($table));
}
- public function getCreateTableColumnCommentsSQL()
+ /**
+ * @return string[]
+ */
+ public function getCreateTableColumnCommentsSQL() : array
{
$this->markTestSkipped('Platform does not support Column comments.');
}
- public function getAlterTableColumnCommentsSQL()
+ /**
+ * @return string[]
+ */
+ public function getAlterTableColumnCommentsSQL() : array
{
$this->markTestSkipped('Platform does not support Column comments.');
}
- public function getCreateTableColumnTypeCommentsSQL()
+ /**
+ * @return string[]
+ */
+ public function getCreateTableColumnTypeCommentsSQL() : array
{
$this->markTestSkipped('Platform does not support Column comments.');
}
- public function testGetDefaultValueDeclarationSQL()
+ public function testGetDefaultValueDeclarationSQL() : void
{
// non-timestamp value will get single quotes
$field = [
@@ -572,7 +587,7 @@ public function testGetDefaultValueDeclarationSQLDateTime() : void
}
}
- public function testGetDefaultValueDeclarationSQLForIntegerTypes()
+ public function testGetDefaultValueDeclarationSQLForIntegerTypes() : void
{
foreach (['bigint', 'integer', 'smallint'] as $type) {
$field = [
@@ -609,7 +624,7 @@ public function testGetDefaultValueDeclarationSQLForDateType() : void
/**
* @group DBAL-45
*/
- public function testKeywordList()
+ public function testKeywordList() : void
{
$keywordList = $this->platform->getReservedKeywordsList();
self::assertInstanceOf(KeywordList::class, $keywordList);
@@ -620,7 +635,7 @@ public function testKeywordList()
/**
* @group DBAL-374
*/
- public function testQuotedColumnInPrimaryKeyPropagation()
+ public function testQuotedColumnInPrimaryKeyPropagation() : void
{
$table = new Table('`quoted`');
$table->addColumn('create', 'string');
@@ -630,15 +645,30 @@ public function testQuotedColumnInPrimaryKeyPropagation()
self::assertEquals($this->getQuotedColumnInPrimaryKeySQL(), $sql);
}
- abstract protected function getQuotedColumnInPrimaryKeySQL();
- abstract protected function getQuotedColumnInIndexSQL();
- abstract protected function getQuotedNameInIndexSQL();
- abstract protected function getQuotedColumnInForeignKeySQL();
+ /**
+ * @return string[]
+ */
+ abstract protected function getQuotedColumnInPrimaryKeySQL() : array;
+
+ /**
+ * @return string[]
+ */
+ abstract protected function getQuotedColumnInIndexSQL() : array;
+
+ /**
+ * @return string[]
+ */
+ abstract protected function getQuotedNameInIndexSQL() : array;
+
+ /**
+ * @return string[]
+ */
+ abstract protected function getQuotedColumnInForeignKeySQL() : array;
/**
* @group DBAL-374
*/
- public function testQuotedColumnInIndexPropagation()
+ public function testQuotedColumnInIndexPropagation() : void
{
$table = new Table('`quoted`');
$table->addColumn('create', 'string');
@@ -648,7 +678,7 @@ public function testQuotedColumnInIndexPropagation()
self::assertEquals($this->getQuotedColumnInIndexSQL(), $sql);
}
- public function testQuotedNameInIndexSQL()
+ public function testQuotedNameInIndexSQL() : void
{
$table = new Table('test');
$table->addColumn('column1', 'string');
@@ -661,7 +691,7 @@ public function testQuotedNameInIndexSQL()
/**
* @group DBAL-374
*/
- public function testQuotedColumnInForeignKeyPropagation()
+ public function testQuotedColumnInForeignKeyPropagation() : void
{
$table = new Table('`quoted`');
$table->addColumn('create', 'string');
@@ -699,7 +729,7 @@ public function testQuotedColumnInForeignKeyPropagation()
/**
* @group DBAL-1051
*/
- public function testQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
+ public function testQuotesReservedKeywordInUniqueConstraintDeclarationSQL() : void
{
$index = new Index('select', ['foo'], true);
@@ -709,15 +739,12 @@ public function testQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
);
}
- /**
- * @return string
- */
- abstract protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL();
+ abstract protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL() : string;
/**
* @group DBAL-2270
*/
- public function testQuotesReservedKeywordInTruncateTableSQL()
+ public function testQuotesReservedKeywordInTruncateTableSQL() : void
{
self::assertSame(
$this->getQuotesReservedKeywordInTruncateTableSQL(),
@@ -725,15 +752,12 @@ public function testQuotesReservedKeywordInTruncateTableSQL()
);
}
- /**
- * @return string
- */
- abstract protected function getQuotesReservedKeywordInTruncateTableSQL();
+ abstract protected function getQuotesReservedKeywordInTruncateTableSQL() : string;
/**
* @group DBAL-1051
*/
- public function testQuotesReservedKeywordInIndexDeclarationSQL()
+ public function testQuotesReservedKeywordInIndexDeclarationSQL() : void
{
$index = new Index('select', ['foo']);
@@ -747,44 +771,34 @@ public function testQuotesReservedKeywordInIndexDeclarationSQL()
);
}
- /**
- * @return string
- */
- abstract protected function getQuotesReservedKeywordInIndexDeclarationSQL();
+ abstract protected function getQuotesReservedKeywordInIndexDeclarationSQL() : string;
- /**
- * @return bool
- */
- protected function supportsInlineIndexDeclaration()
+ protected function supportsInlineIndexDeclaration() : bool
{
return true;
}
- public function testSupportsCommentOnStatement()
+ public function testSupportsCommentOnStatement() : void
{
self::assertSame($this->supportsCommentOnStatement(), $this->platform->supportsCommentOnStatement());
}
- /**
- * @return bool
- */
- protected function supportsCommentOnStatement()
+ protected function supportsCommentOnStatement() : bool
{
return false;
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testGetCreateSchemaSQL()
+ public function testGetCreateSchemaSQL() : void
{
+ $this->expectException(DBALException::class);
+
$this->platform->getCreateSchemaSQL('schema');
}
/**
* @group DBAL-585
*/
- public function testAlterTableChangeQuotedColumn()
+ public function testAlterTableChangeQuotedColumn() : void
{
$tableDiff = new TableDiff('mytable');
$tableDiff->fromTable = new Table('mytable');
@@ -797,7 +811,7 @@ public function testAlterTableChangeQuotedColumn()
['type']
);
- self::assertContains(
+ self::assertStringContainsString(
$this->platform->quoteIdentifier('select'),
implode(';', $this->platform->getAlterTableSQL($tableDiff))
);
@@ -806,49 +820,49 @@ public function testAlterTableChangeQuotedColumn()
/**
* @group DBAL-563
*/
- public function testUsesSequenceEmulatedIdentityColumns()
+ public function testUsesSequenceEmulatedIdentityColumns() : void
{
self::assertFalse($this->platform->usesSequenceEmulatedIdentityColumns());
}
/**
* @group DBAL-563
- * @expectedException \Doctrine\DBAL\DBALException
*/
- public function testReturnsIdentitySequenceName()
+ public function testReturnsIdentitySequenceName() : void
{
+ $this->expectException(DBALException::class);
+
$this->platform->getIdentitySequenceName('mytable', 'mycolumn');
}
- public function testReturnsBinaryDefaultLength()
+ public function testReturnsBinaryDefaultLength() : void
{
self::assertSame($this->getBinaryDefaultLength(), $this->platform->getBinaryDefaultLength());
}
- protected function getBinaryDefaultLength()
+ protected function getBinaryDefaultLength() : int
{
return 255;
}
- public function testReturnsBinaryMaxLength()
+ public function testReturnsBinaryMaxLength() : void
{
self::assertSame($this->getBinaryMaxLength(), $this->platform->getBinaryMaxLength());
}
- protected function getBinaryMaxLength()
+ protected function getBinaryMaxLength() : int
{
return 4000;
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testReturnsBinaryTypeDeclarationSQL()
+ public function testReturnsBinaryTypeDeclarationSQL() : void
{
+ $this->expectException(DBALException::class);
+
$this->platform->getBinaryTypeDeclarationSQL([]);
}
- public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL()
+ public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL() : void
{
$this->markTestSkipped('Not applicable to the platform');
}
@@ -856,7 +870,7 @@ public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL()
/**
* @group DBAL-553
*/
- public function hasNativeJsonType()
+ public function hasNativeJsonType() : void
{
self::assertFalse($this->platform->hasNativeJsonType());
}
@@ -864,7 +878,7 @@ public function hasNativeJsonType()
/**
* @group DBAL-553
*/
- public function testReturnsJsonTypeDeclarationSQL()
+ public function testReturnsJsonTypeDeclarationSQL() : void
{
$column = [
'length' => 666,
@@ -881,7 +895,7 @@ public function testReturnsJsonTypeDeclarationSQL()
/**
* @group DBAL-234
*/
- public function testAlterTableRenameIndex()
+ public function testAlterTableRenameIndex() : void
{
$tableDiff = new TableDiff('mytable');
$tableDiff->fromTable = new Table('mytable');
@@ -898,9 +912,11 @@ public function testAlterTableRenameIndex()
}
/**
+ * @return string[]
+ *
* @group DBAL-234
*/
- protected function getAlterTableRenameIndexSQL()
+ protected function getAlterTableRenameIndexSQL() : array
{
return [
'DROP INDEX idx_foo',
@@ -911,7 +927,7 @@ protected function getAlterTableRenameIndexSQL()
/**
* @group DBAL-234
*/
- public function testQuotesAlterTableRenameIndex()
+ public function testQuotesAlterTableRenameIndex() : void
{
$tableDiff = new TableDiff('table');
$tableDiff->fromTable = new Table('table');
@@ -929,9 +945,11 @@ public function testQuotesAlterTableRenameIndex()
}
/**
+ * @return string[]
+ *
* @group DBAL-234
*/
- protected function getQuotedAlterTableRenameIndexSQL()
+ protected function getQuotedAlterTableRenameIndexSQL() : array
{
return [
'DROP INDEX "create"',
@@ -944,7 +962,7 @@ protected function getQuotedAlterTableRenameIndexSQL()
/**
* @group DBAL-835
*/
- public function testQuotesAlterTableRenameColumn()
+ public function testQuotesAlterTableRenameColumn() : void
{
$fromTable = new Table('mytable');
@@ -989,12 +1007,12 @@ public function testQuotesAlterTableRenameColumn()
*
* @group DBAL-835
*/
- abstract protected function getQuotedAlterTableRenameColumnSQL();
+ abstract protected function getQuotedAlterTableRenameColumnSQL() : array;
/**
* @group DBAL-835
*/
- public function testQuotesAlterTableChangeColumnLength()
+ public function testQuotesAlterTableChangeColumnLength() : void
{
$fromTable = new Table('mytable');
@@ -1031,12 +1049,12 @@ public function testQuotesAlterTableChangeColumnLength()
*
* @group DBAL-835
*/
- abstract protected function getQuotedAlterTableChangeColumnLengthSQL();
+ abstract protected function getQuotedAlterTableChangeColumnLengthSQL() : array;
/**
* @group DBAL-807
*/
- public function testAlterTableRenameIndexInSchema()
+ public function testAlterTableRenameIndexInSchema() : void
{
$tableDiff = new TableDiff('myschema.mytable');
$tableDiff->fromTable = new Table('myschema.mytable');
@@ -1053,9 +1071,11 @@ public function testAlterTableRenameIndexInSchema()
}
/**
+ * @return string[]
+ *
* @group DBAL-807
*/
- protected function getAlterTableRenameIndexInSchemaSQL()
+ protected function getAlterTableRenameIndexInSchemaSQL() : array
{
return [
'DROP INDEX idx_foo',
@@ -1066,7 +1086,7 @@ protected function getAlterTableRenameIndexInSchemaSQL()
/**
* @group DBAL-807
*/
- public function testQuotesAlterTableRenameIndexInSchema()
+ public function testQuotesAlterTableRenameIndexInSchema() : void
{
$tableDiff = new TableDiff('`schema`.table');
$tableDiff->fromTable = new Table('`schema`.table');
@@ -1084,9 +1104,11 @@ public function testQuotesAlterTableRenameIndexInSchema()
}
/**
+ * @return string[]
+ *
* @group DBAL-234
*/
- protected function getQuotedAlterTableRenameIndexInSchemaSQL()
+ protected function getQuotedAlterTableRenameIndexInSchemaSQL() : array
{
return [
'DROP INDEX "schema"."create"',
@@ -1099,7 +1121,7 @@ protected function getQuotedAlterTableRenameIndexInSchemaSQL()
/**
* @group DBAL-1237
*/
- public function testQuotesDropForeignKeySQL()
+ public function testQuotesDropForeignKeySQL() : void
{
if (! $this->platform->supportsForeignKeyConstraints()) {
$this->markTestSkipped(
@@ -1117,7 +1139,7 @@ public function testQuotesDropForeignKeySQL()
self::assertSame($expectedSql, $this->platform->getDropForeignKeySQL($foreignKey, $table));
}
- protected function getQuotesDropForeignKeySQL()
+ protected function getQuotesDropForeignKeySQL() : string
{
return 'ALTER TABLE "table" DROP FOREIGN KEY "select"';
}
@@ -1125,7 +1147,7 @@ protected function getQuotesDropForeignKeySQL()
/**
* @group DBAL-1237
*/
- public function testQuotesDropConstraintSQL()
+ public function testQuotesDropConstraintSQL() : void
{
$tableName = 'table';
$table = new Table($tableName);
@@ -1137,27 +1159,27 @@ public function testQuotesDropConstraintSQL()
self::assertSame($expectedSql, $this->platform->getDropConstraintSQL($constraint, $table));
}
- protected function getQuotesDropConstraintSQL()
+ protected function getQuotesDropConstraintSQL() : string
{
return 'ALTER TABLE "table" DROP CONSTRAINT "select"';
}
- protected function getStringLiteralQuoteCharacter()
+ protected function getStringLiteralQuoteCharacter() : string
{
return "'";
}
- public function testGetStringLiteralQuoteCharacter()
+ public function testGetStringLiteralQuoteCharacter() : void
{
self::assertSame($this->getStringLiteralQuoteCharacter(), $this->platform->getStringLiteralQuoteCharacter());
}
- protected function getQuotedCommentOnColumnSQLWithoutQuoteCharacter()
+ protected function getQuotedCommentOnColumnSQLWithoutQuoteCharacter() : string
{
return "COMMENT ON COLUMN mytable.id IS 'This is a comment'";
}
- public function testGetCommentOnColumnSQLWithoutQuoteCharacter()
+ public function testGetCommentOnColumnSQLWithoutQuoteCharacter() : void
{
self::assertEquals(
$this->getQuotedCommentOnColumnSQLWithoutQuoteCharacter(),
@@ -1165,12 +1187,12 @@ public function testGetCommentOnColumnSQLWithoutQuoteCharacter()
);
}
- protected function getQuotedCommentOnColumnSQLWithQuoteCharacter()
+ protected function getQuotedCommentOnColumnSQLWithQuoteCharacter() : string
{
return "COMMENT ON COLUMN mytable.id IS 'It''s a quote !'";
}
- public function testGetCommentOnColumnSQLWithQuoteCharacter()
+ public function testGetCommentOnColumnSQLWithQuoteCharacter() : void
{
$c = $this->getStringLiteralQuoteCharacter();
@@ -1185,12 +1207,12 @@ public function testGetCommentOnColumnSQLWithQuoteCharacter()
*
* @return string[]
*/
- abstract protected function getCommentOnColumnSQL();
+ abstract protected function getCommentOnColumnSQL() : array;
/**
* @group DBAL-1004
*/
- public function testGetCommentOnColumnSQL()
+ public function testGetCommentOnColumnSQL() : void
{
self::assertSame(
$this->getCommentOnColumnSQL(),
@@ -1206,7 +1228,7 @@ public function testGetCommentOnColumnSQL()
* @group DBAL-1176
* @dataProvider getGeneratesInlineColumnCommentSQL
*/
- public function testGeneratesInlineColumnCommentSQL($comment, $expectedSql)
+ public function testGeneratesInlineColumnCommentSQL(?string $comment, string $expectedSql) : void
{
if (! $this->platform->supportsInlineColumnComments()) {
$this->markTestSkipped(sprintf('%s does not support inline column comments.', get_class($this->platform)));
@@ -1215,52 +1237,55 @@ public function testGeneratesInlineColumnCommentSQL($comment, $expectedSql)
self::assertSame($expectedSql, $this->platform->getInlineColumnCommentSQL($comment));
}
- public function getGeneratesInlineColumnCommentSQL()
+ /**
+ * @return mixed[][]
+ */
+ public static function getGeneratesInlineColumnCommentSQL() : iterable
{
return [
- 'regular comment' => ['Regular comment', $this->getInlineColumnRegularCommentSQL()],
+ 'regular comment' => ['Regular comment', static::getInlineColumnRegularCommentSQL()],
'comment requiring escaping' => [
sprintf(
'Using inline comment delimiter %s works',
- $this->getInlineColumnCommentDelimiter()
+ static::getInlineColumnCommentDelimiter()
),
- $this->getInlineColumnCommentRequiringEscapingSQL(),
+ static::getInlineColumnCommentRequiringEscapingSQL(),
],
- 'empty comment' => ['', $this->getInlineColumnEmptyCommentSQL()],
+ 'empty comment' => ['', static::getInlineColumnEmptyCommentSQL()],
];
}
- protected function getInlineColumnCommentDelimiter()
+ protected static function getInlineColumnCommentDelimiter() : string
{
return "'";
}
- protected function getInlineColumnRegularCommentSQL()
+ protected static function getInlineColumnRegularCommentSQL() : string
{
return "COMMENT 'Regular comment'";
}
- protected function getInlineColumnCommentRequiringEscapingSQL()
+ protected static function getInlineColumnCommentRequiringEscapingSQL() : string
{
return "COMMENT 'Using inline comment delimiter '' works'";
}
- protected function getInlineColumnEmptyCommentSQL()
+ protected static function getInlineColumnEmptyCommentSQL() : string
{
return "COMMENT ''";
}
- protected function getQuotedStringLiteralWithoutQuoteCharacter()
+ protected function getQuotedStringLiteralWithoutQuoteCharacter() : string
{
return "'No quote'";
}
- protected function getQuotedStringLiteralWithQuoteCharacter()
+ protected function getQuotedStringLiteralWithQuoteCharacter() : string
{
return "'It''s a quote'";
}
- protected function getQuotedStringLiteralQuoteCharacter()
+ protected function getQuotedStringLiteralQuoteCharacter() : string
{
return "''''";
}
@@ -1268,7 +1293,7 @@ protected function getQuotedStringLiteralQuoteCharacter()
/**
* @group DBAL-1176
*/
- public function testThrowsExceptionOnGeneratingInlineColumnCommentSQLIfUnsupported()
+ public function testThrowsExceptionOnGeneratingInlineColumnCommentSQLIfUnsupported() : void
{
if ($this->platform->supportsInlineColumnComments()) {
$this->markTestSkipped(sprintf('%s supports inline column comments.', get_class($this->platform)));
@@ -1281,7 +1306,7 @@ public function testThrowsExceptionOnGeneratingInlineColumnCommentSQLIfUnsupport
$this->platform->getInlineColumnCommentSQL('unsupported');
}
- public function testQuoteStringLiteral()
+ public function testQuoteStringLiteral() : void
{
$c = $this->getStringLiteralQuoteCharacter();
@@ -1301,17 +1326,18 @@ public function testQuoteStringLiteral()
/**
* @group DBAL-423
- * @expectedException \Doctrine\DBAL\DBALException
*/
- public function testReturnsGuidTypeDeclarationSQL()
+ public function testReturnsGuidTypeDeclarationSQL() : void
{
+ $this->expectException(DBALException::class);
+
$this->platform->getGuidTypeDeclarationSQL([]);
}
/**
* @group DBAL-1010
*/
- public function testGeneratesAlterTableRenameColumnSQL()
+ public function testGeneratesAlterTableRenameColumnSQL() : void
{
$table = new Table('foo');
$table->addColumn(
@@ -1334,12 +1360,12 @@ public function testGeneratesAlterTableRenameColumnSQL()
/**
* @return string[]
*/
- abstract public function getAlterTableRenameColumnSQL();
+ abstract public function getAlterTableRenameColumnSQL() : array;
/**
* @group DBAL-1016
*/
- public function testQuotesTableIdentifiersInAlterTableSQL()
+ public function testQuotesTableIdentifiersInAlterTableSQL() : void
{
$table = new Table('"foo"');
$table->addColumn('id', 'integer');
@@ -1376,12 +1402,12 @@ public function testQuotesTableIdentifiersInAlterTableSQL()
/**
* @return string[]
*/
- abstract protected function getQuotesTableIdentifiersInAlterTableSQL();
+ abstract protected function getQuotesTableIdentifiersInAlterTableSQL() : array;
/**
* @group DBAL-1090
*/
- public function testAlterStringToFixedString()
+ public function testAlterStringToFixedString() : void
{
$table = new Table('mytable');
$table->addColumn('name', 'string', ['length' => 2]);
@@ -1409,12 +1435,12 @@ public function testAlterStringToFixedString()
/**
* @return string[]
*/
- abstract protected function getAlterStringToFixedStringSQL();
+ abstract protected function getAlterStringToFixedStringSQL() : array;
/**
* @group DBAL-1062
*/
- public function testGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
+ public function testGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : void
{
$foreignTable = new Table('foreign_table');
$foreignTable->addColumn('id', 'integer');
@@ -1442,7 +1468,7 @@ public function testGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
/**
* @return string[]
*/
- abstract protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL();
+ abstract protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : array;
/**
* @param mixed[] $column
@@ -1450,15 +1476,15 @@ abstract protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL
* @group DBAL-1082
* @dataProvider getGeneratesDecimalTypeDeclarationSQL
*/
- public function testGeneratesDecimalTypeDeclarationSQL(array $column, $expectedSql)
+ public function testGeneratesDecimalTypeDeclarationSQL(array $column, string $expectedSql) : void
{
self::assertSame($expectedSql, $this->platform->getDecimalTypeDeclarationSQL($column));
}
/**
- * @return mixed[]
+ * @return mixed[][]
*/
- public function getGeneratesDecimalTypeDeclarationSQL()
+ public static function getGeneratesDecimalTypeDeclarationSQL() : iterable
{
return [
[[], 'NUMERIC(10, 0)'],
@@ -1476,15 +1502,15 @@ public function getGeneratesDecimalTypeDeclarationSQL()
* @group DBAL-1082
* @dataProvider getGeneratesFloatDeclarationSQL
*/
- public function testGeneratesFloatDeclarationSQL(array $column, $expectedSql)
+ public function testGeneratesFloatDeclarationSQL(array $column, string $expectedSql) : void
{
self::assertSame($expectedSql, $this->platform->getFloatDeclarationSQL($column));
}
/**
- * @return mixed[]
+ * @return mixed[][]
*/
- public function getGeneratesFloatDeclarationSQL()
+ public static function getGeneratesFloatDeclarationSQL() : iterable
{
return [
[[], 'DOUBLE PRECISION'],
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/AbstractPostgreSqlPlatformTestCase.php b/tests/Doctrine/Tests/DBAL/Platforms/AbstractPostgreSqlPlatformTestCase.php
index 2624de8f71c..44c28018849 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/AbstractPostgreSqlPlatformTestCase.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/AbstractPostgreSqlPlatformTestCase.php
@@ -11,16 +11,20 @@
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\TransactionIsolationLevel;
use Doctrine\DBAL\Types\Type;
+use UnexpectedValueException;
use function sprintf;
abstract class AbstractPostgreSqlPlatformTestCase extends AbstractPlatformTestCase
{
- public function getGenerateTableSql()
+ public function getGenerateTableSql() : string
{
return 'CREATE TABLE test (id SERIAL NOT NULL, test VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id))';
}
- public function getGenerateTableWithMultiColumnUniqueIndexSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateTableWithMultiColumnUniqueIndexSql() : array
{
return [
'CREATE TABLE test (foo VARCHAR(255) DEFAULT NULL, bar VARCHAR(255) DEFAULT NULL)',
@@ -28,7 +32,10 @@ public function getGenerateTableWithMultiColumnUniqueIndexSql()
];
}
- public function getGenerateAlterTableSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateAlterTableSql() : array
{
return [
'ALTER TABLE mytable ADD quota INT DEFAULT NULL',
@@ -43,17 +50,17 @@ public function getGenerateAlterTableSql()
];
}
- public function getGenerateIndexSql()
+ public function getGenerateIndexSql() : string
{
return 'CREATE INDEX my_idx ON mytable (user_name, last_login)';
}
- public function getGenerateForeignKeySql()
+ public function getGenerateForeignKeySql() : string
{
return 'ALTER TABLE test ADD FOREIGN KEY (fk_name_id) REFERENCES other_table (id) NOT DEFERRABLE INITIALLY IMMEDIATE';
}
- public function testGeneratesForeignKeySqlForNonStandardOptions()
+ public function testGeneratesForeignKeySqlForNonStandardOptions() : void
{
$foreignKey = new ForeignKeyConstraint(
['foreign_id'],
@@ -128,7 +135,7 @@ public function testGeneratesForeignKeySqlForNonStandardOptions()
);
}
- public function testGeneratesSqlSnippets()
+ public function testGeneratesSqlSnippets() : void
{
self::assertEquals('SIMILAR TO', $this->platform->getRegexpExpression(), 'Regular expression operator is not correct');
self::assertEquals('"', $this->platform->getIdentifierQuoteCharacter(), 'Identifier quote character is not correct');
@@ -137,7 +144,7 @@ public function testGeneratesSqlSnippets()
self::assertEquals('SUBSTRING(column FROM 1 FOR 5)', $this->platform->getSubstringExpression('column', 1, 5), 'Substring expression with length is not correct');
}
- public function testGeneratesTransactionCommands()
+ public function testGeneratesTransactionCommands() : void
{
self::assertEquals(
'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED',
@@ -157,14 +164,14 @@ public function testGeneratesTransactionCommands()
);
}
- public function testGeneratesDDLSnippets()
+ public function testGeneratesDDLSnippets() : void
{
self::assertEquals('CREATE DATABASE foobar', $this->platform->getCreateDatabaseSQL('foobar'));
self::assertEquals('DROP DATABASE foobar', $this->platform->getDropDatabaseSQL('foobar'));
self::assertEquals('DROP TABLE foobar', $this->platform->getDropTableSQL('foobar'));
}
- public function testGenerateTableWithAutoincrement()
+ public function testGenerateTableWithAutoincrement() : void
{
$table = new Table('autoinc_table');
$column = $table->addColumn('id', 'integer');
@@ -174,9 +181,9 @@ public function testGenerateTableWithAutoincrement()
}
/**
- * @return string[][]
+ * @return mixed[][]
*/
- public static function serialTypes() : array
+ public static function serialTypes() : iterable
{
return [
['integer', 'SERIAL'],
@@ -233,7 +240,7 @@ public function testGetDefaultValueDeclarationSQLIgnoresTheDefaultKeyWhenTheFiel
self::assertSame('', $sql);
}
- public function testGeneratesTypeDeclarationForIntegers()
+ public function testGeneratesTypeDeclarationForIntegers() : void
{
self::assertEquals(
'INT',
@@ -251,7 +258,7 @@ public function testGeneratesTypeDeclarationForIntegers()
);
}
- public function testGeneratesTypeDeclarationForStrings()
+ public function testGeneratesTypeDeclarationForStrings() : void
{
self::assertEquals(
'CHAR(10)',
@@ -271,12 +278,12 @@ public function testGeneratesTypeDeclarationForStrings()
);
}
- public function getGenerateUniqueIndexSql()
+ public function getGenerateUniqueIndexSql() : string
{
return 'CREATE UNIQUE INDEX index_name ON test (test, test2)';
}
- public function testGeneratesSequenceSqlCommands()
+ public function testGeneratesSequenceSqlCommands() : void
{
$sequence = new Sequence('myseq', 20, 1);
self::assertEquals(
@@ -293,27 +300,27 @@ public function testGeneratesSequenceSqlCommands()
);
}
- public function testDoesNotPreferIdentityColumns()
+ public function testDoesNotPreferIdentityColumns() : void
{
self::assertFalse($this->platform->prefersIdentityColumns());
}
- public function testPrefersSequences()
+ public function testPrefersSequences() : void
{
self::assertTrue($this->platform->prefersSequences());
}
- public function testSupportsIdentityColumns()
+ public function testSupportsIdentityColumns() : void
{
self::assertTrue($this->platform->supportsIdentityColumns());
}
- public function testSupportsSavePoints()
+ public function testSupportsSavePoints() : void
{
self::assertTrue($this->platform->supportsSavepoints());
}
- public function testSupportsSequences()
+ public function testSupportsSequences() : void
{
self::assertTrue($this->platform->supportsSequences());
}
@@ -321,24 +328,27 @@ public function testSupportsSequences()
/**
* {@inheritdoc}
*/
- protected function supportsCommentOnStatement()
+ protected function supportsCommentOnStatement() : bool
{
return true;
}
- public function testModifyLimitQuery()
+ public function testModifyLimitQuery() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', 10, 0);
self::assertEquals('SELECT * FROM user LIMIT 10', $sql);
}
- public function testModifyLimitQueryWithEmptyOffset()
+ public function testModifyLimitQueryWithEmptyOffset() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', 10);
self::assertEquals('SELECT * FROM user LIMIT 10', $sql);
}
- public function getCreateTableColumnCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getCreateTableColumnCommentsSQL() : array
{
return [
'CREATE TABLE test (id INT NOT NULL, PRIMARY KEY(id))',
@@ -346,7 +356,10 @@ public function getCreateTableColumnCommentsSQL()
];
}
- public function getAlterTableColumnCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getAlterTableColumnCommentsSQL() : array
{
return [
'ALTER TABLE mytable ADD quota INT NOT NULL',
@@ -356,7 +369,10 @@ public function getAlterTableColumnCommentsSQL()
];
}
- public function getCreateTableColumnTypeCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getCreateTableColumnTypeCommentsSQL() : array
{
return [
'CREATE TABLE test (id INT NOT NULL, data TEXT NOT NULL, PRIMARY KEY(id))',
@@ -364,12 +380,18 @@ public function getCreateTableColumnTypeCommentsSQL()
];
}
- protected function getQuotedColumnInPrimaryKeySQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInPrimaryKeySQL() : array
{
return ['CREATE TABLE "quoted" ("create" VARCHAR(255) NOT NULL, PRIMARY KEY("create"))'];
}
- protected function getQuotedColumnInIndexSQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInIndexSQL() : array
{
return [
'CREATE TABLE "quoted" ("create" VARCHAR(255) NOT NULL)',
@@ -377,7 +399,10 @@ protected function getQuotedColumnInIndexSQL()
];
}
- protected function getQuotedNameInIndexSQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedNameInIndexSQL() : array
{
return [
'CREATE TABLE test (column1 VARCHAR(255) NOT NULL)',
@@ -385,7 +410,10 @@ protected function getQuotedNameInIndexSQL()
];
}
- protected function getQuotedColumnInForeignKeySQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInForeignKeySQL() : array
{
return [
'CREATE TABLE "quoted" ("create" VARCHAR(255) NOT NULL, foo VARCHAR(255) NOT NULL, "bar" VARCHAR(255) NOT NULL)',
@@ -396,20 +424,17 @@ protected function getQuotedColumnInForeignKeySQL()
}
/**
- * @param string $databaseValue
- * @param string $preparedStatementValue
- * @param int $integerValue
- * @param bool $booleanValue
+ * @param string|bool $databaseValue
*
* @group DBAL-457
* @dataProvider pgBooleanProvider
*/
public function testConvertBooleanAsLiteralStrings(
$databaseValue,
- $preparedStatementValue,
- $integerValue,
- $booleanValue
- ) {
+ string $preparedStatementValue,
+ ?int $integerValue,
+ ?bool $booleanValue
+ ) : void {
$platform = $this->createPlatform();
self::assertEquals($preparedStatementValue, $platform->convertBooleans($databaseValue));
@@ -418,7 +443,7 @@ public function testConvertBooleanAsLiteralStrings(
/**
* @group DBAL-457
*/
- public function testConvertBooleanAsLiteralIntegers()
+ public function testConvertBooleanAsLiteralIntegers() : void
{
$platform = $this->createPlatform();
$platform->setUseBooleanTrueFalseStrings(false);
@@ -431,20 +456,17 @@ public function testConvertBooleanAsLiteralIntegers()
}
/**
- * @param string $databaseValue
- * @param string $preparedStatementValue
- * @param int $integerValue
- * @param bool $booleanValue
+ * @param string|bool $databaseValue
*
* @group DBAL-630
* @dataProvider pgBooleanProvider
*/
public function testConvertBooleanAsDatabaseValueStrings(
$databaseValue,
- $preparedStatementValue,
- $integerValue,
- $booleanValue
- ) {
+ string $preparedStatementValue,
+ ?int $integerValue,
+ ?bool $booleanValue
+ ) : void {
$platform = $this->createPlatform();
self::assertSame($integerValue, $platform->convertBooleansToDatabaseValue($booleanValue));
@@ -453,7 +475,7 @@ public function testConvertBooleanAsDatabaseValueStrings(
/**
* @group DBAL-630
*/
- public function testConvertBooleanAsDatabaseValueIntegers()
+ public function testConvertBooleanAsDatabaseValueIntegers() : void
{
$platform = $this->createPlatform();
$platform->setUseBooleanTrueFalseStrings(false);
@@ -463,37 +485,35 @@ public function testConvertBooleanAsDatabaseValueIntegers()
}
/**
- * @param string $databaseValue
- * @param string $prepareStatementValue
- * @param int $integerValue
- * @param bool $booleanValue
+ * @param string|bool $databaseValue
*
* @dataProvider pgBooleanProvider
*/
- public function testConvertFromBoolean($databaseValue, $prepareStatementValue, $integerValue, $booleanValue)
+ public function testConvertFromBoolean($databaseValue, string $prepareStatementValue, ?int $integerValue, ?bool $booleanValue) : void
{
$platform = $this->createPlatform();
self::assertSame($booleanValue, $platform->convertFromBoolean($databaseValue));
}
- /**
- * @expectedException UnexpectedValueException
- * @expectedExceptionMessage Unrecognized boolean literal 'my-bool'
- */
- public function testThrowsExceptionWithInvalidBooleanLiteral()
+ public function testThrowsExceptionWithInvalidBooleanLiteral() : void
{
- $platform = $this->createPlatform()->convertBooleansToDatabaseValue('my-bool');
+ $platform = $this->createPlatform();
+
+ $this->expectException(UnexpectedValueException::class);
+ $this->expectExceptionMessage("Unrecognized boolean literal 'my-bool'");
+
+ $platform->convertBooleansToDatabaseValue('my-bool');
}
- public function testGetCreateSchemaSQL()
+ public function testGetCreateSchemaSQL() : void
{
$schemaName = 'schema';
$sql = $this->platform->getCreateSchemaSQL($schemaName);
self::assertEquals('CREATE SCHEMA ' . $schemaName, $sql);
}
- public function testAlterDecimalPrecisionScale()
+ public function testAlterDecimalPrecisionScale() : void
{
$table = new Table('mytable');
$table->addColumn('dfoo1', 'decimal');
@@ -555,7 +575,7 @@ public function testAlterDecimalPrecisionScale()
/**
* @group DBAL-365
*/
- public function testDroppingConstraintsBeforeColumns()
+ public function testDroppingConstraintsBeforeColumns() : void
{
$newTable = new Table('mytable');
$newTable->addColumn('id', 'integer');
@@ -582,7 +602,7 @@ public function testDroppingConstraintsBeforeColumns()
/**
* @group DBAL-563
*/
- public function testUsesSequenceEmulatedIdentityColumns()
+ public function testUsesSequenceEmulatedIdentityColumns() : void
{
self::assertTrue($this->platform->usesSequenceEmulatedIdentityColumns());
}
@@ -590,7 +610,7 @@ public function testUsesSequenceEmulatedIdentityColumns()
/**
* @group DBAL-563
*/
- public function testReturnsIdentitySequenceName()
+ public function testReturnsIdentitySequenceName() : void
{
self::assertSame('mytable_mycolumn_seq', $this->platform->getIdentitySequenceName('mytable', 'mycolumn'));
}
@@ -599,30 +619,33 @@ public function testReturnsIdentitySequenceName()
* @dataProvider dataCreateSequenceWithCache
* @group DBAL-139
*/
- public function testCreateSequenceWithCache($cacheSize, $expectedSql)
+ public function testCreateSequenceWithCache(int $cacheSize, string $expectedSql) : void
{
$sequence = new Sequence('foo', 1, 1, $cacheSize);
- self::assertContains($expectedSql, $this->platform->getCreateSequenceSQL($sequence));
+ self::assertStringContainsString($expectedSql, $this->platform->getCreateSequenceSQL($sequence));
}
- public function dataCreateSequenceWithCache()
+ /**
+ * @return mixed[][]
+ */
+ public static function dataCreateSequenceWithCache() : iterable
{
return [
[3, 'CACHE 3'],
];
}
- protected function getBinaryDefaultLength()
+ protected function getBinaryDefaultLength() : int
{
return 0;
}
- protected function getBinaryMaxLength()
+ protected function getBinaryMaxLength() : int
{
return 0;
}
- public function testReturnsBinaryTypeDeclarationSQL()
+ public function testReturnsBinaryTypeDeclarationSQL() : void
{
self::assertSame('BYTEA', $this->platform->getBinaryTypeDeclarationSQL([]));
self::assertSame('BYTEA', $this->platform->getBinaryTypeDeclarationSQL(['length' => 0]));
@@ -633,7 +656,7 @@ public function testReturnsBinaryTypeDeclarationSQL()
self::assertSame('BYTEA', $this->platform->getBinaryTypeDeclarationSQL(['fixed' => true, 'length' => 9999999]));
}
- public function testDoesNotPropagateUnnecessaryTableAlterationOnBinaryType()
+ public function testDoesNotPropagateUnnecessaryTableAlterationOnBinaryType() : void
{
$table1 = new Table('mytable');
$table1->addColumn('column_varbinary', 'binary');
@@ -674,17 +697,21 @@ public function testDoesNotPropagateUnnecessaryTableAlterationOnBinaryType()
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getAlterTableRenameIndexSQL()
+ protected function getAlterTableRenameIndexSQL() : array
{
return ['ALTER INDEX idx_foo RENAME TO idx_bar'];
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getQuotedAlterTableRenameIndexSQL()
+ protected function getQuotedAlterTableRenameIndexSQL() : array
{
return [
'ALTER INDEX "create" RENAME TO "select"',
@@ -695,9 +722,9 @@ protected function getQuotedAlterTableRenameIndexSQL()
/**
* PostgreSQL boolean strings provider
*
- * @return mixed[]
+ * @return mixed[][]
*/
- public function pgBooleanProvider()
+ public static function pgBooleanProvider() : iterable
{
return [
// Database value, prepared statement value, boolean integer value, boolean value.
@@ -724,7 +751,7 @@ public function pgBooleanProvider()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableRenameColumnSQL()
+ protected function getQuotedAlterTableRenameColumnSQL() : array
{
return [
'ALTER TABLE mytable RENAME COLUMN unquoted1 TO unquoted',
@@ -742,7 +769,7 @@ protected function getQuotedAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableChangeColumnLengthSQL()
+ protected function getQuotedAlterTableChangeColumnLengthSQL() : array
{
return [
'ALTER TABLE mytable ALTER unquoted1 TYPE VARCHAR(255)',
@@ -755,17 +782,21 @@ protected function getQuotedAlterTableChangeColumnLengthSQL()
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-807
*/
- protected function getAlterTableRenameIndexInSchemaSQL()
+ protected function getAlterTableRenameIndexInSchemaSQL() : array
{
return ['ALTER INDEX myschema.idx_foo RENAME TO idx_bar'];
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-807
*/
- protected function getQuotedAlterTableRenameIndexInSchemaSQL()
+ protected function getQuotedAlterTableRenameIndexInSchemaSQL() : array
{
return [
'ALTER INDEX "schema"."create" RENAME TO "select"',
@@ -773,12 +804,12 @@ protected function getQuotedAlterTableRenameIndexInSchemaSQL()
];
}
- protected function getQuotesDropForeignKeySQL()
+ protected function getQuotesDropForeignKeySQL() : string
{
return 'ALTER TABLE "table" DROP CONSTRAINT "select"';
}
- public function testGetNullCommentOnColumnSQL()
+ public function testGetNullCommentOnColumnSQL() : void
{
self::assertEquals(
'COMMENT ON COLUMN mytable.id IS NULL',
@@ -789,7 +820,7 @@ public function testGetNullCommentOnColumnSQL()
/**
* @group DBAL-423
*/
- public function testReturnsGuidTypeDeclarationSQL()
+ public function testReturnsGuidTypeDeclarationSQL() : void
{
self::assertSame('UUID', $this->platform->getGuidTypeDeclarationSQL([]));
}
@@ -797,7 +828,7 @@ public function testReturnsGuidTypeDeclarationSQL()
/**
* {@inheritdoc}
*/
- public function getAlterTableRenameColumnSQL()
+ public function getAlterTableRenameColumnSQL() : array
{
return ['ALTER TABLE foo RENAME COLUMN bar TO baz'];
}
@@ -805,7 +836,7 @@ public function getAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesTableIdentifiersInAlterTableSQL()
+ protected function getQuotesTableIdentifiersInAlterTableSQL() : array
{
return [
'ALTER TABLE "foo" DROP CONSTRAINT fk1',
@@ -825,7 +856,7 @@ protected function getQuotesTableIdentifiersInAlterTableSQL()
/**
* {@inheritdoc}
*/
- protected function getCommentOnColumnSQL()
+ protected function getCommentOnColumnSQL() : array
{
return [
'COMMENT ON COLUMN foo.bar IS \'comment\'',
@@ -837,7 +868,7 @@ protected function getCommentOnColumnSQL()
/**
* @group DBAL-1004
*/
- public function testAltersTableColumnCommentWithExplicitlyQuotedIdentifiers()
+ public function testAltersTableColumnCommentWithExplicitlyQuotedIdentifiers() : void
{
$table1 = new Table('"foo"', [new Column('"bar"', Type::getType('integer'))]);
$table2 = new Table('"foo"', [new Column('"bar"', Type::getType('integer'), ['comment' => 'baz'])]);
@@ -856,7 +887,7 @@ public function testAltersTableColumnCommentWithExplicitlyQuotedIdentifiers()
/**
* @group 3158
*/
- public function testAltersTableColumnCommentIfRequiredByType()
+ public function testAltersTableColumnCommentIfRequiredByType() : void
{
$table1 = new Table('"foo"', [new Column('"bar"', Type::getType('datetime'))]);
$table2 = new Table('"foo"', [new Column('"bar"', Type::getType('datetime_immutable'))]);
@@ -879,7 +910,7 @@ public function testAltersTableColumnCommentIfRequiredByType()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
+ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL() : string
{
return 'CONSTRAINT "select" UNIQUE (foo)';
}
@@ -887,7 +918,7 @@ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInIndexDeclarationSQL()
+ protected function getQuotesReservedKeywordInIndexDeclarationSQL() : string
{
return 'INDEX "select" (foo)';
}
@@ -895,7 +926,7 @@ protected function getQuotesReservedKeywordInIndexDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInTruncateTableSQL()
+ protected function getQuotesReservedKeywordInTruncateTableSQL() : string
{
return 'TRUNCATE "select"';
}
@@ -903,7 +934,7 @@ protected function getQuotesReservedKeywordInTruncateTableSQL()
/**
* {@inheritdoc}
*/
- protected function getAlterStringToFixedStringSQL()
+ protected function getAlterStringToFixedStringSQL() : array
{
return ['ALTER TABLE mytable ALTER name TYPE CHAR(2)'];
}
@@ -911,7 +942,7 @@ protected function getAlterStringToFixedStringSQL()
/**
* {@inheritdoc}
*/
- protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
+ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : array
{
return ['ALTER INDEX idx_foo RENAME TO idx_foo_renamed'];
}
@@ -919,7 +950,7 @@ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
/**
* @group DBAL-1142
*/
- public function testInitializesTsvectorTypeMapping()
+ public function testInitializesTsvectorTypeMapping() : void
{
self::assertTrue($this->platform->hasDoctrineTypeMappingFor('tsvector'));
self::assertEquals('text', $this->platform->getDoctrineTypeMapping('tsvector'));
@@ -928,7 +959,7 @@ public function testInitializesTsvectorTypeMapping()
/**
* @group DBAL-1220
*/
- public function testReturnsDisallowDatabaseConnectionsSQL()
+ public function testReturnsDisallowDatabaseConnectionsSQL() : void
{
self::assertSame(
"UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'foo'",
@@ -939,7 +970,7 @@ public function testReturnsDisallowDatabaseConnectionsSQL()
/**
* @group DBAL-1220
*/
- public function testReturnsCloseActiveDatabaseConnectionsSQL()
+ public function testReturnsCloseActiveDatabaseConnectionsSQL() : void
{
self::assertSame(
"SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname = 'foo'",
@@ -950,84 +981,88 @@ public function testReturnsCloseActiveDatabaseConnectionsSQL()
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableForeignKeysSQL()
+ public function testQuotesTableNameInListTableForeignKeysSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableForeignKeysSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableForeignKeysSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesSchemaNameInListTableForeignKeysSQL()
+ public function testQuotesSchemaNameInListTableForeignKeysSQL() : void
{
- self::assertContains(
+ self::assertStringContainsStringIgnoringCase(
"'Foo''Bar\\'",
- $this->platform->getListTableForeignKeysSQL("Foo'Bar\\.baz_table"),
- '',
- true
+ $this->platform->getListTableForeignKeysSQL("Foo'Bar\\.baz_table")
);
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableConstraintsSQL()
+ public function testQuotesTableNameInListTableConstraintsSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableConstraintsSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableConstraintsSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableIndexesSQL()
+ public function testQuotesTableNameInListTableIndexesSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableIndexesSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableIndexesSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesSchemaNameInListTableIndexesSQL()
+ public function testQuotesSchemaNameInListTableIndexesSQL() : void
{
- self::assertContains(
+ self::assertStringContainsStringIgnoringCase(
"'Foo''Bar\\'",
- $this->platform->getListTableIndexesSQL("Foo'Bar\\.baz_table"),
- '',
- true
+ $this->platform->getListTableIndexesSQL("Foo'Bar\\.baz_table")
);
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableColumnsSQL()
+ public function testQuotesTableNameInListTableColumnsSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableColumnsSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableColumnsSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesSchemaNameInListTableColumnsSQL()
+ public function testQuotesSchemaNameInListTableColumnsSQL() : void
{
- self::assertContains(
+ self::assertStringContainsStringIgnoringCase(
"'Foo''Bar\\'",
- $this->platform->getListTableColumnsSQL("Foo'Bar\\.baz_table"),
- '',
- true
+ $this->platform->getListTableColumnsSQL("Foo'Bar\\.baz_table")
);
}
/**
* @group DBAL-2436
*/
- public function testQuotesDatabaseNameInCloseActiveDatabaseConnectionsSQL()
+ public function testQuotesDatabaseNameInCloseActiveDatabaseConnectionsSQL() : void
{
- self::assertContains(
+ self::assertStringContainsStringIgnoringCase(
"'Foo''Bar\\'",
- $this->platform->getCloseActiveDatabaseConnectionsSQL("Foo'Bar\\"),
- '',
- true
+ $this->platform->getCloseActiveDatabaseConnectionsSQL("Foo'Bar\\")
);
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/AbstractSQLServerPlatformTestCase.php b/tests/Doctrine/Tests/DBAL/Platforms/AbstractSQLServerPlatformTestCase.php
index 00c941d6d09..46627bd8cf2 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/AbstractSQLServerPlatformTestCase.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/AbstractSQLServerPlatformTestCase.php
@@ -14,12 +14,15 @@
abstract class AbstractSQLServerPlatformTestCase extends AbstractPlatformTestCase
{
- public function getGenerateTableSql()
+ public function getGenerateTableSql() : string
{
return 'CREATE TABLE test (id INT IDENTITY NOT NULL, test NVARCHAR(255), PRIMARY KEY (id))';
}
- public function getGenerateTableWithMultiColumnUniqueIndexSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateTableWithMultiColumnUniqueIndexSql() : array
{
return [
'CREATE TABLE test (foo NVARCHAR(255), bar NVARCHAR(255))',
@@ -27,7 +30,10 @@ public function getGenerateTableWithMultiColumnUniqueIndexSql()
];
}
- public function getGenerateAlterTableSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateAlterTableSql() : array
{
return [
'ALTER TABLE mytable ADD quota INT',
@@ -47,15 +53,14 @@ public function getGenerateAlterTableSql()
];
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testDoesNotSupportRegexp()
+ public function testDoesNotSupportRegexp() : void
{
+ $this->expectException(DBALException::class);
+
$this->platform->getRegexpExpression();
}
- public function testGeneratesSqlSnippets()
+ public function testGeneratesSqlSnippets() : void
{
self::assertEquals('CONVERT(date, GETDATE())', $this->platform->getCurrentDateSQL());
self::assertEquals('CONVERT(time, GETDATE())', $this->platform->getCurrentTimeSQL());
@@ -64,7 +69,7 @@ public function testGeneratesSqlSnippets()
self::assertEquals('(column1 + column2 + column3)', $this->platform->getConcatExpression('column1', 'column2', 'column3'), 'Concatenation expression is not correct');
}
- public function testGeneratesTransactionsCommands()
+ public function testGeneratesTransactionsCommands() : void
{
self::assertEquals(
'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED',
@@ -84,7 +89,7 @@ public function testGeneratesTransactionsCommands()
);
}
- public function testGeneratesDDLSnippets()
+ public function testGeneratesDDLSnippets() : void
{
$dropDatabaseExpectation = 'DROP DATABASE foobar';
@@ -94,7 +99,7 @@ public function testGeneratesDDLSnippets()
self::assertEquals('DROP TABLE foobar', $this->platform->getDropTableSQL('foobar'));
}
- public function testGeneratesTypeDeclarationForIntegers()
+ public function testGeneratesTypeDeclarationForIntegers() : void
{
self::assertEquals(
'INT',
@@ -112,7 +117,7 @@ public function testGeneratesTypeDeclarationForIntegers()
);
}
- public function testGeneratesTypeDeclarationsForStrings()
+ public function testGeneratesTypeDeclarationsForStrings() : void
{
self::assertEquals(
'NCHAR(10)',
@@ -137,47 +142,47 @@ public function testGeneratesTypeDeclarationsForStrings()
);
}
- public function testPrefersIdentityColumns()
+ public function testPrefersIdentityColumns() : void
{
self::assertTrue($this->platform->prefersIdentityColumns());
}
- public function testSupportsIdentityColumns()
+ public function testSupportsIdentityColumns() : void
{
self::assertTrue($this->platform->supportsIdentityColumns());
}
- public function testSupportsCreateDropDatabase()
+ public function testSupportsCreateDropDatabase() : void
{
self::assertTrue($this->platform->supportsCreateDropDatabase());
}
- public function testSupportsSchemas()
+ public function testSupportsSchemas() : void
{
self::assertTrue($this->platform->supportsSchemas());
}
- public function testDoesNotSupportSavePoints()
+ public function testDoesNotSupportSavePoints() : void
{
self::assertTrue($this->platform->supportsSavepoints());
}
- public function getGenerateIndexSql()
+ public function getGenerateIndexSql() : string
{
return 'CREATE INDEX my_idx ON mytable (user_name, last_login)';
}
- public function getGenerateUniqueIndexSql()
+ public function getGenerateUniqueIndexSql() : string
{
return 'CREATE UNIQUE INDEX index_name ON test (test, test2) WHERE test IS NOT NULL AND test2 IS NOT NULL';
}
- public function getGenerateForeignKeySql()
+ public function getGenerateForeignKeySql() : string
{
return 'ALTER TABLE test ADD FOREIGN KEY (fk_name_id) REFERENCES other_table (id)';
}
- public function testModifyLimitQuery()
+ public function testModifyLimitQuery() : void
{
$querySql = 'SELECT * FROM user';
$alteredSql = 'SELECT TOP 10 * FROM user';
@@ -185,7 +190,7 @@ public function testModifyLimitQuery()
$this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
}
- public function testModifyLimitQueryWithEmptyOffset()
+ public function testModifyLimitQueryWithEmptyOffset() : void
{
$querySql = 'SELECT * FROM user';
$alteredSql = 'SELECT TOP 10 * FROM user';
@@ -193,7 +198,7 @@ public function testModifyLimitQueryWithEmptyOffset()
$this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
}
- public function testModifyLimitQueryWithOffset()
+ public function testModifyLimitQueryWithOffset() : void
{
if (! $this->platform->supportsLimitOffset()) {
$this->markTestSkipped(sprintf('Platform "%s" does not support offsets in result limiting.', $this->platform->getName()));
@@ -206,7 +211,7 @@ public function testModifyLimitQueryWithOffset()
$this->expectCteWithMinAndMaxRowNums($alteredSql, 6, 15, $sql);
}
- public function testModifyLimitQueryWithAscOrderBy()
+ public function testModifyLimitQueryWithAscOrderBy() : void
{
$querySql = 'SELECT * FROM user ORDER BY username ASC';
$alteredSql = 'SELECT TOP 10 * FROM user ORDER BY username ASC';
@@ -215,7 +220,7 @@ public function testModifyLimitQueryWithAscOrderBy()
$this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
}
- public function testModifyLimitQueryWithLowercaseOrderBy()
+ public function testModifyLimitQueryWithLowercaseOrderBy() : void
{
$querySql = 'SELECT * FROM user order by username';
$alteredSql = 'SELECT TOP 10 * FROM user order by username';
@@ -223,7 +228,7 @@ public function testModifyLimitQueryWithLowercaseOrderBy()
$this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
}
- public function testModifyLimitQueryWithDescOrderBy()
+ public function testModifyLimitQueryWithDescOrderBy() : void
{
$querySql = 'SELECT * FROM user ORDER BY username DESC';
$alteredSql = 'SELECT TOP 10 * FROM user ORDER BY username DESC';
@@ -231,7 +236,7 @@ public function testModifyLimitQueryWithDescOrderBy()
$this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
}
- public function testModifyLimitQueryWithMultipleOrderBy()
+ public function testModifyLimitQueryWithMultipleOrderBy() : void
{
$querySql = 'SELECT * FROM user ORDER BY username DESC, usereamil ASC';
$alteredSql = 'SELECT TOP 10 * FROM user ORDER BY username DESC, usereamil ASC';
@@ -239,7 +244,7 @@ public function testModifyLimitQueryWithMultipleOrderBy()
$this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
}
- public function testModifyLimitQueryWithSubSelect()
+ public function testModifyLimitQueryWithSubSelect() : void
{
$querySql = 'SELECT * FROM (SELECT u.id as uid, u.name as uname) dctrn_result';
$alteredSql = 'SELECT TOP 10 * FROM (SELECT u.id as uid, u.name as uname) dctrn_result';
@@ -247,7 +252,7 @@ public function testModifyLimitQueryWithSubSelect()
$this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
}
- public function testModifyLimitQueryWithSubSelectAndOrder()
+ public function testModifyLimitQueryWithSubSelectAndOrder() : void
{
$querySql = 'SELECT * FROM (SELECT u.id as uid, u.name as uname ORDER BY u.name DESC) dctrn_result';
$alteredSql = 'SELECT TOP 10 * FROM (SELECT u.id as uid, u.name as uname) dctrn_result';
@@ -260,7 +265,7 @@ public function testModifyLimitQueryWithSubSelectAndOrder()
$this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
}
- public function testModifyLimitQueryWithSubSelectAndMultipleOrder()
+ public function testModifyLimitQueryWithSubSelectAndMultipleOrder() : void
{
if (! $this->platform->supportsLimitOffset()) {
$this->markTestSkipped(sprintf('Platform "%s" does not support offsets in result limiting.', $this->platform->getName()));
@@ -282,7 +287,7 @@ public function testModifyLimitQueryWithSubSelectAndMultipleOrder()
$this->expectCteWithMinAndMaxRowNums($alteredSql, 6, 15, $sql);
}
- public function testModifyLimitQueryWithFromColumnNames()
+ public function testModifyLimitQueryWithFromColumnNames() : void
{
$querySql = 'SELECT a.fromFoo, fromBar FROM foo';
$alteredSql = 'SELECT TOP 10 a.fromFoo, fromBar FROM foo';
@@ -293,7 +298,7 @@ public function testModifyLimitQueryWithFromColumnNames()
/**
* @group DBAL-927
*/
- public function testModifyLimitQueryWithExtraLongQuery()
+ public function testModifyLimitQueryWithExtraLongQuery() : void
{
$query = 'SELECT table1.column1, table2.column2, table3.column3, table4.column4, table5.column5, table6.column6, table7.column7, table8.column8 FROM table1, table2, table3, table4, table5, table6, table7, table8 ';
$query .= 'WHERE (table1.column1 = table2.column2) AND (table1.column1 = table3.column3) AND (table1.column1 = table4.column4) AND (table1.column1 = table5.column5) AND (table1.column1 = table6.column6) AND (table1.column1 = table7.column7) AND (table1.column1 = table8.column8) AND (table2.column2 = table3.column3) AND (table2.column2 = table4.column4) AND (table2.column2 = table5.column5) AND (table2.column2 = table6.column6) ';
@@ -312,7 +317,7 @@ public function testModifyLimitQueryWithExtraLongQuery()
/**
* @group DDC-2470
*/
- public function testModifyLimitQueryWithOrderByClause()
+ public function testModifyLimitQueryWithOrderByClause() : void
{
if (! $this->platform->supportsLimitOffset()) {
$this->markTestSkipped(sprintf('Platform "%s" does not support offsets in result limiting.', $this->platform->getName()));
@@ -328,7 +333,7 @@ public function testModifyLimitQueryWithOrderByClause()
/**
* @group DBAL-713
*/
- public function testModifyLimitQueryWithSubSelectInSelectList()
+ public function testModifyLimitQueryWithSubSelectInSelectList() : void
{
$querySql = 'SELECT ' .
'u.id, ' .
@@ -352,7 +357,7 @@ public function testModifyLimitQueryWithSubSelectInSelectList()
/**
* @group DBAL-713
*/
- public function testModifyLimitQueryWithSubSelectInSelectListAndOrderByClause()
+ public function testModifyLimitQueryWithSubSelectInSelectListAndOrderByClause() : void
{
if (! $this->platform->supportsLimitOffset()) {
$this->markTestSkipped(sprintf('Platform "%s" does not support offsets in result limiting.', $this->platform->getName()));
@@ -381,7 +386,7 @@ public function testModifyLimitQueryWithSubSelectInSelectListAndOrderByClause()
/**
* @group DBAL-834
*/
- public function testModifyLimitQueryWithAggregateFunctionInOrderByClause()
+ public function testModifyLimitQueryWithAggregateFunctionInOrderByClause() : void
{
$querySql = 'SELECT ' .
'MAX(heading_id) aliased, ' .
@@ -402,7 +407,7 @@ public function testModifyLimitQueryWithAggregateFunctionInOrderByClause()
/**
* @throws DBALException
*/
- public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromBaseTable()
+ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromBaseTable() : void
{
$querySql = 'SELECT DISTINCT id_0, name_1 '
. 'FROM ('
@@ -426,7 +431,7 @@ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromBas
/**
* @throws DBALException
*/
- public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromJoinTable()
+ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromJoinTable() : void
{
$querySql = 'SELECT DISTINCT id_0, name_1 '
. 'FROM ('
@@ -450,7 +455,7 @@ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromJoi
/**
* @throws DBALException
*/
- public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnsFromBothTables()
+ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnsFromBothTables() : void
{
$querySql = 'SELECT DISTINCT id_0, name_1, foo_2 '
. 'FROM ('
@@ -471,7 +476,7 @@ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnsFromBo
$this->expectCteWithMaxRowNum($alteredSql, 5, $sql);
}
- public function testModifyLimitSubquerySimple()
+ public function testModifyLimitSubquerySimple() : void
{
$querySql = 'SELECT DISTINCT id_0 FROM '
. '(SELECT k0_.id AS id_0, k0_.field AS field_1 '
@@ -485,7 +490,7 @@ public function testModifyLimitSubquerySimple()
/**
* @group DDC-1360
*/
- public function testQuoteIdentifier()
+ public function testQuoteIdentifier() : void
{
self::assertEquals('[fo][o]', $this->platform->quoteIdentifier('fo]o'));
self::assertEquals('[test]', $this->platform->quoteIdentifier('test'));
@@ -495,7 +500,7 @@ public function testQuoteIdentifier()
/**
* @group DDC-1360
*/
- public function testQuoteSingleIdentifier()
+ public function testQuoteSingleIdentifier() : void
{
self::assertEquals('[fo][o]', $this->platform->quoteSingleIdentifier('fo]o'));
self::assertEquals('[test]', $this->platform->quoteSingleIdentifier('test'));
@@ -505,7 +510,7 @@ public function testQuoteSingleIdentifier()
/**
* @group DBAL-220
*/
- public function testCreateClusteredIndex()
+ public function testCreateClusteredIndex() : void
{
$idx = new Index('idx', ['id']);
$idx->addFlag('clustered');
@@ -515,7 +520,7 @@ public function testCreateClusteredIndex()
/**
* @group DBAL-220
*/
- public function testCreateNonClusteredPrimaryKeyInTable()
+ public function testCreateNonClusteredPrimaryKeyInTable() : void
{
$table = new Table('tbl');
$table->addColumn('id', 'integer');
@@ -528,25 +533,31 @@ public function testCreateNonClusteredPrimaryKeyInTable()
/**
* @group DBAL-220
*/
- public function testCreateNonClusteredPrimaryKey()
+ public function testCreateNonClusteredPrimaryKey() : void
{
$idx = new Index('idx', ['id'], false, true);
$idx->addFlag('nonclustered');
self::assertEquals('ALTER TABLE tbl ADD PRIMARY KEY NONCLUSTERED (id)', $this->platform->getCreatePrimaryKeySQL($idx, 'tbl'));
}
- public function testAlterAddPrimaryKey()
+ public function testAlterAddPrimaryKey() : void
{
$idx = new Index('idx', ['id'], false, true);
self::assertEquals('ALTER TABLE tbl ADD PRIMARY KEY (id)', $this->platform->getCreateIndexSQL($idx, 'tbl'));
}
- protected function getQuotedColumnInPrimaryKeySQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInPrimaryKeySQL() : array
{
return ['CREATE TABLE [quoted] ([create] NVARCHAR(255) NOT NULL, PRIMARY KEY ([create]))'];
}
- protected function getQuotedColumnInIndexSQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInIndexSQL() : array
{
return [
'CREATE TABLE [quoted] ([create] NVARCHAR(255) NOT NULL)',
@@ -554,7 +565,10 @@ protected function getQuotedColumnInIndexSQL()
];
}
- protected function getQuotedNameInIndexSQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedNameInIndexSQL() : array
{
return [
'CREATE TABLE test (column1 NVARCHAR(255) NOT NULL)',
@@ -562,7 +576,10 @@ protected function getQuotedNameInIndexSQL()
];
}
- protected function getQuotedColumnInForeignKeySQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInForeignKeySQL() : array
{
return [
'CREATE TABLE [quoted] ([create] NVARCHAR(255) NOT NULL, foo NVARCHAR(255) NOT NULL, [bar] NVARCHAR(255) NOT NULL)',
@@ -572,14 +589,14 @@ protected function getQuotedColumnInForeignKeySQL()
];
}
- public function testGetCreateSchemaSQL()
+ public function testGetCreateSchemaSQL() : void
{
$schemaName = 'schema';
$sql = $this->platform->getCreateSchemaSQL($schemaName);
self::assertEquals('CREATE SCHEMA ' . $schemaName, $sql);
}
- public function testCreateTableWithSchemaColumnComments()
+ public function testCreateTableWithSchemaColumnComments() : void
{
$table = new Table('testschema.test');
$table->addColumn('id', 'integer', ['comment' => 'This is a comment']);
@@ -593,7 +610,7 @@ public function testCreateTableWithSchemaColumnComments()
self::assertEquals($expectedSql, $this->platform->getCreateTableSQL($table));
}
- public function testAlterTableWithSchemaColumnComments()
+ public function testAlterTableWithSchemaColumnComments() : void
{
$tableDiff = new TableDiff('testschema.mytable');
$tableDiff->addedColumns['quota'] = new Column('quota', Type::getType('integer'), ['comment' => 'A comment']);
@@ -606,7 +623,7 @@ public function testAlterTableWithSchemaColumnComments()
self::assertEquals($expectedSql, $this->platform->getAlterTableSQL($tableDiff));
}
- public function testAlterTableWithSchemaDropColumnComments()
+ public function testAlterTableWithSchemaDropColumnComments() : void
{
$tableDiff = new TableDiff('testschema.mytable');
$tableDiff->changedColumns['quota'] = new ColumnDiff(
@@ -621,7 +638,7 @@ public function testAlterTableWithSchemaDropColumnComments()
self::assertEquals($expectedSql, $this->platform->getAlterTableSQL($tableDiff));
}
- public function testAlterTableWithSchemaUpdateColumnComments()
+ public function testAlterTableWithSchemaUpdateColumnComments() : void
{
$tableDiff = new TableDiff('testschema.mytable');
$tableDiff->changedColumns['quota'] = new ColumnDiff(
@@ -637,9 +654,11 @@ public function testAlterTableWithSchemaUpdateColumnComments()
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-543
*/
- public function getCreateTableColumnCommentsSQL()
+ public function getCreateTableColumnCommentsSQL() : array
{
return [
'CREATE TABLE test (id INT NOT NULL, PRIMARY KEY (id))',
@@ -648,9 +667,11 @@ public function getCreateTableColumnCommentsSQL()
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-543
*/
- public function getAlterTableColumnCommentsSQL()
+ public function getAlterTableColumnCommentsSQL() : array
{
return [
'ALTER TABLE mytable ADD quota INT NOT NULL',
@@ -661,9 +682,11 @@ public function getAlterTableColumnCommentsSQL()
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-543
*/
- public function getCreateTableColumnTypeCommentsSQL()
+ public function getCreateTableColumnTypeCommentsSQL() : array
{
return [
'CREATE TABLE test (id INT NOT NULL, data VARCHAR(MAX) NOT NULL, PRIMARY KEY (id))',
@@ -674,7 +697,7 @@ public function getCreateTableColumnTypeCommentsSQL()
/**
* @group DBAL-543
*/
- public function testGeneratesCreateTableSQLWithColumnComments()
+ public function testGeneratesCreateTableSQLWithColumnComments() : void
{
$table = new Table('mytable');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -713,7 +736,7 @@ public function testGeneratesCreateTableSQLWithColumnComments()
* @group DBAL-543
* @group DBAL-1011
*/
- public function testGeneratesAlterTableSQLWithColumnComments()
+ public function testGeneratesAlterTableSQLWithColumnComments() : void
{
$table = new Table('mytable');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -895,7 +918,7 @@ public function testGeneratesAlterTableSQLWithColumnComments()
/**
* @group DBAL-122
*/
- public function testInitializesDoctrineTypeMappings()
+ public function testInitializesDoctrineTypeMappings() : void
{
self::assertTrue($this->platform->hasDoctrineTypeMappingFor('bigint'));
self::assertSame('bigint', $this->platform->getDoctrineTypeMapping('bigint'));
@@ -973,12 +996,12 @@ public function testInitializesDoctrineTypeMappings()
self::assertSame('guid', $this->platform->getDoctrineTypeMapping('uniqueidentifier'));
}
- protected function getBinaryMaxLength()
+ protected function getBinaryMaxLength() : int
{
return 8000;
}
- public function testReturnsBinaryTypeDeclarationSQL()
+ public function testReturnsBinaryTypeDeclarationSQL() : void
{
self::assertSame('VARBINARY(255)', $this->platform->getBinaryTypeDeclarationSQL([]));
self::assertSame('VARBINARY(255)', $this->platform->getBinaryTypeDeclarationSQL(['length' => 0]));
@@ -993,24 +1016,28 @@ public function testReturnsBinaryTypeDeclarationSQL()
* @group legacy
* @expectedDeprecation Binary field length 8001 is greater than supported by the platform (8000). Reduce the field length or use a BLOB field instead.
*/
- public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL()
+ public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL() : void
{
self::assertSame('VARBINARY(MAX)', $this->platform->getBinaryTypeDeclarationSQL(['length' => 8001]));
self::assertSame('VARBINARY(MAX)', $this->platform->getBinaryTypeDeclarationSQL(['fixed' => true, 'length' => 8001]));
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getAlterTableRenameIndexSQL()
+ protected function getAlterTableRenameIndexSQL() : array
{
return ["EXEC sp_RENAME N'mytable.idx_foo', N'idx_bar', N'INDEX'"];
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getQuotedAlterTableRenameIndexSQL()
+ protected function getQuotedAlterTableRenameIndexSQL() : array
{
return [
"EXEC sp_RENAME N'[table].[create]', N'[select]', N'INDEX'",
@@ -1021,7 +1048,7 @@ protected function getQuotedAlterTableRenameIndexSQL()
/**
* @group DBAL-825
*/
- public function testChangeColumnsTypeWithDefaultValue()
+ public function testChangeColumnsTypeWithDefaultValue() : void
{
$tableName = 'column_def_change_type';
$table = new Table($tableName);
@@ -1063,7 +1090,7 @@ public function testChangeColumnsTypeWithDefaultValue()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableRenameColumnSQL()
+ protected function getQuotedAlterTableRenameColumnSQL() : array
{
return [
"sp_RENAME 'mytable.unquoted1', 'unquoted', 'COLUMN'",
@@ -1081,23 +1108,27 @@ protected function getQuotedAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableChangeColumnLengthSQL()
+ protected function getQuotedAlterTableChangeColumnLengthSQL() : array
{
$this->markTestIncomplete('Not implemented yet');
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-807
*/
- protected function getAlterTableRenameIndexInSchemaSQL()
+ protected function getAlterTableRenameIndexInSchemaSQL() : array
{
return ["EXEC sp_RENAME N'myschema.mytable.idx_foo', N'idx_bar', N'INDEX'"];
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-807
*/
- protected function getQuotedAlterTableRenameIndexInSchemaSQL()
+ protected function getQuotedAlterTableRenameIndexInSchemaSQL() : array
{
return [
"EXEC sp_RENAME N'[schema].[table].[create]', N'[select]', N'INDEX'",
@@ -1105,26 +1136,31 @@ protected function getQuotedAlterTableRenameIndexInSchemaSQL()
];
}
- protected function getQuotesDropForeignKeySQL()
+ protected function getQuotesDropForeignKeySQL() : string
{
return 'ALTER TABLE [table] DROP CONSTRAINT [select]';
}
- protected function getQuotesDropConstraintSQL()
+ protected function getQuotesDropConstraintSQL() : string
{
return 'ALTER TABLE [table] DROP CONSTRAINT [select]';
}
/**
+ * @param mixed[] $column
+ *
* @dataProvider getGeneratesIdentifierNamesInDefaultConstraintDeclarationSQL
* @group DBAL-830
*/
- public function testGeneratesIdentifierNamesInDefaultConstraintDeclarationSQL($table, $column, $expectedSql)
+ public function testGeneratesIdentifierNamesInDefaultConstraintDeclarationSQL(string $table, array $column, string $expectedSql) : void
{
self::assertSame($expectedSql, $this->platform->getDefaultConstraintDeclarationSQL($table, $column));
}
- public function getGeneratesIdentifierNamesInDefaultConstraintDeclarationSQL()
+ /**
+ * @return mixed[][]
+ */
+ public static function getGeneratesIdentifierNamesInDefaultConstraintDeclarationSQL() : iterable
{
return [
// Unquoted identifiers non-reserved keywords.
@@ -1139,15 +1175,20 @@ public function getGeneratesIdentifierNamesInDefaultConstraintDeclarationSQL()
}
/**
+ * @param string[] $expectedSql
+ *
* @dataProvider getGeneratesIdentifierNamesInCreateTableSQL
* @group DBAL-830
*/
- public function testGeneratesIdentifierNamesInCreateTableSQL($table, $expectedSql)
+ public function testGeneratesIdentifierNamesInCreateTableSQL(Table $table, array $expectedSql) : void
{
self::assertSame($expectedSql, $this->platform->getCreateTableSQL($table));
}
- public function getGeneratesIdentifierNamesInCreateTableSQL()
+ /**
+ * @return mixed[][]
+ */
+ public static function getGeneratesIdentifierNamesInCreateTableSQL() : iterable
{
return [
// Unquoted identifiers non-reserved keywords.
@@ -1186,15 +1227,20 @@ public function getGeneratesIdentifierNamesInCreateTableSQL()
}
/**
+ * @param string[] $expectedSql
+ *
* @dataProvider getGeneratesIdentifierNamesInAlterTableSQL
* @group DBAL-830
*/
- public function testGeneratesIdentifierNamesInAlterTableSQL($tableDiff, $expectedSql)
+ public function testGeneratesIdentifierNamesInAlterTableSQL(TableDiff $tableDiff, array $expectedSql) : void
{
self::assertSame($expectedSql, $this->platform->getAlterTableSQL($tableDiff));
}
- public function getGeneratesIdentifierNamesInAlterTableSQL()
+ /**
+ * @return mixed[][]
+ */
+ public static function getGeneratesIdentifierNamesInAlterTableSQL() : iterable
{
return [
// Unquoted identifiers non-reserved keywords.
@@ -1299,7 +1345,7 @@ public function getGeneratesIdentifierNamesInAlterTableSQL()
/**
* @group DBAL-423
*/
- public function testReturnsGuidTypeDeclarationSQL()
+ public function testReturnsGuidTypeDeclarationSQL() : void
{
self::assertSame('UNIQUEIDENTIFIER', $this->platform->getGuidTypeDeclarationSQL([]));
}
@@ -1307,7 +1353,7 @@ public function testReturnsGuidTypeDeclarationSQL()
/**
* {@inheritdoc}
*/
- public function getAlterTableRenameColumnSQL()
+ public function getAlterTableRenameColumnSQL() : array
{
return [
"sp_RENAME 'foo.bar', 'baz', 'COLUMN'",
@@ -1319,7 +1365,7 @@ public function getAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesTableIdentifiersInAlterTableSQL()
+ protected function getQuotesTableIdentifiersInAlterTableSQL() : array
{
return [
'ALTER TABLE [foo] DROP CONSTRAINT fk1',
@@ -1341,7 +1387,7 @@ protected function getQuotesTableIdentifiersInAlterTableSQL()
/**
* {@inheritdoc}
*/
- protected function getCommentOnColumnSQL()
+ protected function getCommentOnColumnSQL() : array
{
return [
"COMMENT ON COLUMN foo.bar IS 'comment'",
@@ -1353,7 +1399,7 @@ protected function getCommentOnColumnSQL()
/**
* {@inheritdoc}
*/
- public function getReturnsForeignKeyReferentialActionSQL()
+ public static function getReturnsForeignKeyReferentialActionSQL() : iterable
{
return [
['CASCADE', 'CASCADE'],
@@ -1368,7 +1414,7 @@ public function getReturnsForeignKeyReferentialActionSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
+ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL() : string
{
return 'CONSTRAINT [select] UNIQUE (foo) WHERE foo IS NOT NULL';
}
@@ -1376,7 +1422,7 @@ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInIndexDeclarationSQL()
+ protected function getQuotesReservedKeywordInIndexDeclarationSQL() : string
{
return 'INDEX [select] (foo)';
}
@@ -1384,7 +1430,7 @@ protected function getQuotesReservedKeywordInIndexDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInTruncateTableSQL()
+ protected function getQuotesReservedKeywordInTruncateTableSQL() : string
{
return 'TRUNCATE TABLE [select]';
}
@@ -1392,7 +1438,7 @@ protected function getQuotesReservedKeywordInTruncateTableSQL()
/**
* {@inheritdoc}
*/
- protected function getAlterStringToFixedStringSQL()
+ protected function getAlterStringToFixedStringSQL() : array
{
return ['ALTER TABLE mytable ALTER COLUMN name NCHAR(2) NOT NULL'];
}
@@ -1400,12 +1446,12 @@ protected function getAlterStringToFixedStringSQL()
/**
* {@inheritdoc}
*/
- protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
+ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : array
{
return ["EXEC sp_RENAME N'mytable.idx_foo', N'idx_foo_renamed', N'INDEX'"];
}
- public function testModifyLimitQueryWithTopNSubQueryWithOrderBy()
+ public function testModifyLimitQueryWithTopNSubQueryWithOrderBy() : void
{
$querySql = 'SELECT * FROM test t WHERE t.id = (SELECT TOP 1 t2.id FROM test t2 ORDER BY t2.data DESC)';
$alteredSql = 'SELECT TOP 10 * FROM test t WHERE t.id = (SELECT TOP 1 t2.id FROM test t2 ORDER BY t2.data DESC)';
@@ -1421,63 +1467,66 @@ public function testModifyLimitQueryWithTopNSubQueryWithOrderBy()
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableColumnsSQL()
+ public function testQuotesTableNameInListTableColumnsSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableColumnsSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableColumnsSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesSchemaNameInListTableColumnsSQL()
+ public function testQuotesSchemaNameInListTableColumnsSQL() : void
{
- self::assertContains(
+ self::assertStringContainsStringIgnoringCase(
"'Foo''Bar\\'",
- $this->platform->getListTableColumnsSQL("Foo'Bar\\.baz_table"),
- '',
- true
+ $this->platform->getListTableColumnsSQL("Foo'Bar\\.baz_table")
);
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableForeignKeysSQL()
+ public function testQuotesTableNameInListTableForeignKeysSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableForeignKeysSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableForeignKeysSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesSchemaNameInListTableForeignKeysSQL()
+ public function testQuotesSchemaNameInListTableForeignKeysSQL() : void
{
- self::assertContains(
+ self::assertStringContainsStringIgnoringCase(
"'Foo''Bar\\'",
- $this->platform->getListTableForeignKeysSQL("Foo'Bar\\.baz_table"),
- '',
- true
+ $this->platform->getListTableForeignKeysSQL("Foo'Bar\\.baz_table")
);
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableIndexesSQL()
+ public function testQuotesTableNameInListTableIndexesSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableIndexesSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableIndexesSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesSchemaNameInListTableIndexesSQL()
+ public function testQuotesSchemaNameInListTableIndexesSQL() : void
{
- self::assertContains(
+ self::assertStringContainsStringIgnoringCase(
"'Foo''Bar\\'",
- $this->platform->getListTableIndexesSQL("Foo'Bar\\.baz_table"),
- '',
- true
+ $this->platform->getListTableIndexesSQL("Foo'Bar\\.baz_table")
);
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/DB2PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/DB2PlatformTest.php
index ce2b7df42a8..a0c1f1f4b4b 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/DB2PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/DB2PlatformTest.php
@@ -10,18 +10,22 @@
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
class DB2PlatformTest extends AbstractPlatformTestCase
{
/** @var DB2Platform */
protected $platform;
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new DB2Platform();
}
- public function getGenerateAlterTableSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateAlterTableSql() : array
{
return [
'ALTER TABLE mytable ALTER COLUMN baz SET DATA TYPE VARCHAR(255)',
@@ -38,22 +42,25 @@ public function getGenerateAlterTableSql()
];
}
- public function getGenerateForeignKeySql()
+ public function getGenerateForeignKeySql() : string
{
return 'ALTER TABLE test ADD FOREIGN KEY (fk_name_id) REFERENCES other_table (id)';
}
- public function getGenerateIndexSql()
+ public function getGenerateIndexSql() : string
{
return 'CREATE INDEX my_idx ON mytable (user_name, last_login)';
}
- public function getGenerateTableSql()
+ public function getGenerateTableSql() : string
{
return 'CREATE TABLE test (id INTEGER GENERATED BY DEFAULT AS IDENTITY NOT NULL, test VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id))';
}
- public function getGenerateTableWithMultiColumnUniqueIndexSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateTableWithMultiColumnUniqueIndexSql() : array
{
return [
'CREATE TABLE test (foo VARCHAR(255) DEFAULT NULL, bar VARCHAR(255) DEFAULT NULL)',
@@ -61,12 +68,15 @@ public function getGenerateTableWithMultiColumnUniqueIndexSql()
];
}
- public function getGenerateUniqueIndexSql()
+ public function getGenerateUniqueIndexSql() : string
{
return 'CREATE UNIQUE INDEX index_name ON test (test, test2)';
}
- protected function getQuotedColumnInForeignKeySQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInForeignKeySQL() : array
{
return [
'CREATE TABLE "quoted" ("create" VARCHAR(255) NOT NULL, foo VARCHAR(255) NOT NULL, "bar" VARCHAR(255) NOT NULL)',
@@ -76,7 +86,10 @@ protected function getQuotedColumnInForeignKeySQL()
];
}
- protected function getQuotedColumnInIndexSQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInIndexSQL() : array
{
return [
'CREATE TABLE "quoted" ("create" VARCHAR(255) NOT NULL)',
@@ -84,7 +97,10 @@ protected function getQuotedColumnInIndexSQL()
];
}
- protected function getQuotedNameInIndexSQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedNameInIndexSQL() : array
{
return [
'CREATE TABLE test (column1 VARCHAR(255) NOT NULL)',
@@ -92,22 +108,28 @@ protected function getQuotedNameInIndexSQL()
];
}
- protected function getQuotedColumnInPrimaryKeySQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInPrimaryKeySQL() : array
{
return ['CREATE TABLE "quoted" ("create" VARCHAR(255) NOT NULL, PRIMARY KEY("create"))'];
}
- protected function getBitAndComparisonExpressionSql($value1, $value2)
+ protected function getBitAndComparisonExpressionSql(string $value1, string $value2) : string
{
return 'BITAND(' . $value1 . ', ' . $value2 . ')';
}
- protected function getBitOrComparisonExpressionSql($value1, $value2)
+ protected function getBitOrComparisonExpressionSql(string $value1, string $value2) : string
{
return 'BITOR(' . $value1 . ', ' . $value2 . ')';
}
- public function getCreateTableColumnCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getCreateTableColumnCommentsSQL() : array
{
return [
'CREATE TABLE test (id INTEGER NOT NULL, PRIMARY KEY(id))',
@@ -115,7 +137,10 @@ public function getCreateTableColumnCommentsSQL()
];
}
- public function getAlterTableColumnCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getAlterTableColumnCommentsSQL() : array
{
return [
'ALTER TABLE mytable ' .
@@ -127,7 +152,10 @@ public function getAlterTableColumnCommentsSQL()
];
}
- public function getCreateTableColumnTypeCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getCreateTableColumnTypeCommentsSQL() : array
{
return [
'CREATE TABLE test (id INTEGER NOT NULL, "data" CLOB(1M) NOT NULL, PRIMARY KEY(id))',
@@ -135,12 +163,12 @@ public function getCreateTableColumnTypeCommentsSQL()
];
}
- public function testHasCorrectPlatformName()
+ public function testHasCorrectPlatformName() : void
{
self::assertEquals('db2', $this->platform->getName());
}
- public function testGeneratesCreateTableSQLWithCommonIndexes()
+ public function testGeneratesCreateTableSQLWithCommonIndexes() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
@@ -159,7 +187,7 @@ public function testGeneratesCreateTableSQLWithCommonIndexes()
);
}
- public function testGeneratesCreateTableSQLWithForeignKeyConstraints()
+ public function testGeneratesCreateTableSQLWithForeignKeyConstraints() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
@@ -185,7 +213,7 @@ public function testGeneratesCreateTableSQLWithForeignKeyConstraints()
);
}
- public function testGeneratesCreateTableSQLWithCheckConstraints()
+ public function testGeneratesCreateTableSQLWithCheckConstraints() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
@@ -199,7 +227,7 @@ public function testGeneratesCreateTableSQLWithCheckConstraints()
);
}
- public function testGeneratesColumnTypesDeclarationSQL()
+ public function testGeneratesColumnTypesDeclarationSQL() : void
{
$fullColumnDef = [
'length' => 10,
@@ -231,7 +259,7 @@ public function testGeneratesColumnTypesDeclarationSQL()
self::assertEquals('TIME', $this->platform->getTimeTypeDeclarationSQL($fullColumnDef));
}
- public function testInitializesDoctrineTypeMappings()
+ public function testInitializesDoctrineTypeMappings() : void
{
$this->platform->initializeDoctrineTypeMappings();
@@ -275,16 +303,19 @@ public function testInitializesDoctrineTypeMappings()
self::assertSame('datetime', $this->platform->getDoctrineTypeMapping('timestamp'));
}
- public function getIsCommentedDoctrineType()
+ /**
+ * {@inheritDoc}
+ */
+ public function getIsCommentedDoctrineType() : array
{
$data = parent::getIsCommentedDoctrineType();
- $data[Type::BOOLEAN] = [Type::getType(Type::BOOLEAN), true];
+ $data[Types::BOOLEAN] = [Type::getType(Types::BOOLEAN), true];
return $data;
}
- public function testGeneratesDDLSnippets()
+ public function testGeneratesDDLSnippets() : void
{
self::assertEquals('CREATE DATABASE foobar', $this->platform->getCreateDatabaseSQL('foobar'));
self::assertEquals('DROP DATABASE foobar', $this->platform->getDropDatabaseSQL('foobar'));
@@ -297,7 +328,7 @@ public function testGeneratesDDLSnippets()
self::assertEquals('DROP VIEW fooview', $this->platform->getDropViewSQL('fooview'));
}
- public function testGeneratesCreateUnnamedPrimaryKeySQL()
+ public function testGeneratesCreateUnnamedPrimaryKeySQL() : void
{
self::assertEquals(
'ALTER TABLE foo ADD PRIMARY KEY (a, b)',
@@ -308,7 +339,7 @@ public function testGeneratesCreateUnnamedPrimaryKeySQL()
);
}
- public function testGeneratesSQLSnippets()
+ public function testGeneratesSQLSnippets() : void
{
self::assertEquals('CURRENT DATE', $this->platform->getCurrentDateSQL());
self::assertEquals('CURRENT TIME', $this->platform->getCurrentTimeSQL());
@@ -338,7 +369,7 @@ public function testGeneratesSQLSnippets()
self::assertEquals('SUBSTR(column, 5, 2)', $this->platform->getSubstringExpression('column', 5, 2));
}
- public function testModifiesLimitQuery()
+ public function testModifiesLimitQuery() : void
{
self::assertEquals(
'SELECT * FROM user',
@@ -365,47 +396,47 @@ public function testModifiesLimitQuery()
);
}
- public function testPrefersIdentityColumns()
+ public function testPrefersIdentityColumns() : void
{
self::assertTrue($this->platform->prefersIdentityColumns());
}
- public function testSupportsIdentityColumns()
+ public function testSupportsIdentityColumns() : void
{
self::assertTrue($this->platform->supportsIdentityColumns());
}
- public function testDoesNotSupportSavePoints()
+ public function testDoesNotSupportSavePoints() : void
{
self::assertFalse($this->platform->supportsSavepoints());
}
- public function testDoesNotSupportReleasePoints()
+ public function testDoesNotSupportReleasePoints() : void
{
self::assertFalse($this->platform->supportsReleaseSavepoints());
}
- public function testDoesNotSupportCreateDropDatabase()
+ public function testDoesNotSupportCreateDropDatabase() : void
{
self::assertFalse($this->platform->supportsCreateDropDatabase());
}
- public function testReturnsSQLResultCasing()
+ public function testReturnsSQLResultCasing() : void
{
self::assertSame('COL', $this->platform->getSQLResultCasing('cOl'));
}
- protected function getBinaryDefaultLength()
+ protected function getBinaryDefaultLength() : int
{
return 1;
}
- protected function getBinaryMaxLength()
+ protected function getBinaryMaxLength() : int
{
return 32704;
}
- public function testReturnsBinaryTypeDeclarationSQL()
+ public function testReturnsBinaryTypeDeclarationSQL() : void
{
self::assertSame('VARCHAR(1) FOR BIT DATA', $this->platform->getBinaryTypeDeclarationSQL([]));
self::assertSame('VARCHAR(255) FOR BIT DATA', $this->platform->getBinaryTypeDeclarationSQL(['length' => 0]));
@@ -419,24 +450,28 @@ public function testReturnsBinaryTypeDeclarationSQL()
* @group legacy
* @expectedDeprecation Binary field length 32705 is greater than supported by the platform (32704). Reduce the field length or use a BLOB field instead.
*/
- public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL()
+ public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL() : void
{
self::assertSame('BLOB(1M)', $this->platform->getBinaryTypeDeclarationSQL(['length' => 32705]));
self::assertSame('BLOB(1M)', $this->platform->getBinaryTypeDeclarationSQL(['fixed' => true, 'length' => 32705]));
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getAlterTableRenameIndexSQL()
+ protected function getAlterTableRenameIndexSQL() : array
{
return ['RENAME INDEX idx_foo TO idx_bar'];
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getQuotedAlterTableRenameIndexSQL()
+ protected function getQuotedAlterTableRenameIndexSQL() : array
{
return [
'RENAME INDEX "create" TO "select"',
@@ -447,7 +482,7 @@ protected function getQuotedAlterTableRenameIndexSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableRenameColumnSQL()
+ protected function getQuotedAlterTableRenameColumnSQL() : array
{
return ['ALTER TABLE mytable ' .
'RENAME COLUMN unquoted1 TO unquoted ' .
@@ -465,23 +500,27 @@ protected function getQuotedAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableChangeColumnLengthSQL()
+ protected function getQuotedAlterTableChangeColumnLengthSQL() : array
{
$this->markTestIncomplete('Not implemented yet');
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-807
*/
- protected function getAlterTableRenameIndexInSchemaSQL()
+ protected function getAlterTableRenameIndexInSchemaSQL() : array
{
return ['RENAME INDEX myschema.idx_foo TO idx_bar'];
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-807
*/
- protected function getQuotedAlterTableRenameIndexInSchemaSQL()
+ protected function getQuotedAlterTableRenameIndexInSchemaSQL() : array
{
return [
'RENAME INDEX "schema"."create" TO "select"',
@@ -492,7 +531,7 @@ protected function getQuotedAlterTableRenameIndexInSchemaSQL()
/**
* @group DBAL-423
*/
- public function testReturnsGuidTypeDeclarationSQL()
+ public function testReturnsGuidTypeDeclarationSQL() : void
{
self::assertSame('CHAR(36)', $this->platform->getGuidTypeDeclarationSQL([]));
}
@@ -500,7 +539,7 @@ public function testReturnsGuidTypeDeclarationSQL()
/**
* {@inheritdoc}
*/
- public function getAlterTableRenameColumnSQL()
+ public function getAlterTableRenameColumnSQL() : array
{
return ['ALTER TABLE foo RENAME COLUMN bar TO baz'];
}
@@ -508,7 +547,7 @@ public function getAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesTableIdentifiersInAlterTableSQL()
+ protected function getQuotesTableIdentifiersInAlterTableSQL() : array
{
return [
'ALTER TABLE "foo" DROP FOREIGN KEY fk1',
@@ -528,7 +567,7 @@ protected function getQuotesTableIdentifiersInAlterTableSQL()
/**
* {@inheritdoc}
*/
- protected function getCommentOnColumnSQL()
+ protected function getCommentOnColumnSQL() : array
{
return [
'COMMENT ON COLUMN foo.bar IS \'comment\'',
@@ -541,7 +580,7 @@ protected function getCommentOnColumnSQL()
* @group DBAL-944
* @dataProvider getGeneratesAlterColumnSQL
*/
- public function testGeneratesAlterColumnSQL($changedProperty, Column $column, $expectedSQLClause = null)
+ public function testGeneratesAlterColumnSQL(string $changedProperty, Column $column, ?string $expectedSQLClause = null) : void
{
$tableDiff = new TableDiff('foo');
$tableDiff->fromTable = new Table('foo');
@@ -559,9 +598,9 @@ public function testGeneratesAlterColumnSQL($changedProperty, Column $column, $e
}
/**
- * @return mixed[]
+ * @return mixed[][]
*/
- public function getGeneratesAlterColumnSQL()
+ public static function getGeneratesAlterColumnSQL() : iterable
{
return [
[
@@ -625,7 +664,7 @@ public function getGeneratesAlterColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
+ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL() : string
{
return 'CONSTRAINT "select" UNIQUE (foo)';
}
@@ -633,7 +672,7 @@ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInIndexDeclarationSQL()
+ protected function getQuotesReservedKeywordInIndexDeclarationSQL() : string
{
return ''; // not supported by this platform
}
@@ -641,7 +680,7 @@ protected function getQuotesReservedKeywordInIndexDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInTruncateTableSQL()
+ protected function getQuotesReservedKeywordInTruncateTableSQL() : string
{
return 'TRUNCATE "select" IMMEDIATE';
}
@@ -649,7 +688,7 @@ protected function getQuotesReservedKeywordInTruncateTableSQL()
/**
* {@inheritdoc}
*/
- protected function supportsInlineIndexDeclaration()
+ protected function supportsInlineIndexDeclaration() : bool
{
return false;
}
@@ -657,7 +696,7 @@ protected function supportsInlineIndexDeclaration()
/**
* {@inheritdoc}
*/
- protected function supportsCommentOnStatement()
+ protected function supportsCommentOnStatement() : bool
{
return true;
}
@@ -665,7 +704,7 @@ protected function supportsCommentOnStatement()
/**
* {@inheritdoc}
*/
- protected function getAlterStringToFixedStringSQL()
+ protected function getAlterStringToFixedStringSQL() : array
{
return [
'ALTER TABLE mytable ALTER COLUMN name SET DATA TYPE CHAR(2)',
@@ -676,7 +715,7 @@ protected function getAlterStringToFixedStringSQL()
/**
* {@inheritdoc}
*/
- protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
+ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : array
{
return ['RENAME INDEX idx_foo TO idx_foo_renamed'];
}
@@ -684,24 +723,33 @@ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableColumnsSQL()
+ public function testQuotesTableNameInListTableColumnsSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableColumnsSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableColumnsSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableIndexesSQL()
+ public function testQuotesTableNameInListTableIndexesSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableIndexesSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableIndexesSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableForeignKeysSQL()
+ public function testQuotesTableNameInListTableForeignKeysSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableForeignKeysSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableForeignKeysSQL("Foo'Bar\\")
+ );
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/MariaDb1027PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/MariaDb1027PlatformTest.php
index 7171ad714d6..00b86088ad5 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/MariaDb1027PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/MariaDb1027PlatformTest.php
@@ -2,15 +2,16 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
class MariaDb1027PlatformTest extends AbstractMySQLPlatformTestCase
{
/**
* {@inheritdoc}
*/
- public function createPlatform() : MariaDb1027Platform
+ public function createPlatform() : AbstractPlatform
{
return new MariaDb1027Platform();
}
@@ -33,7 +34,7 @@ public function testReturnsJsonTypeDeclarationSQL() : void
public function testInitializesJsonTypeMapping() : void
{
self::assertTrue($this->platform->hasDoctrineTypeMappingFor('json'));
- self::assertSame(Type::JSON, $this->platform->getDoctrineTypeMapping('json'));
+ self::assertSame(Types::JSON, $this->platform->getDoctrineTypeMapping('json'));
}
/**
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/MySQL57PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/MySQL57PlatformTest.php
index 52d7ca0708b..2557562ab95 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/MySQL57PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/MySQL57PlatformTest.php
@@ -2,47 +2,52 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\MySQL57Platform;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
class MySQL57PlatformTest extends AbstractMySQLPlatformTestCase
{
/**
* {@inheritdoc}
*/
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new MySQL57Platform();
}
- public function testHasNativeJsonType()
+ public function testHasNativeJsonType() : void
{
self::assertTrue($this->platform->hasNativeJsonType());
}
- public function testReturnsJsonTypeDeclarationSQL()
+ public function testReturnsJsonTypeDeclarationSQL() : void
{
self::assertSame('JSON', $this->platform->getJsonTypeDeclarationSQL([]));
}
- public function testInitializesJsonTypeMapping()
+ public function testInitializesJsonTypeMapping() : void
{
self::assertTrue($this->platform->hasDoctrineTypeMappingFor('json'));
- self::assertSame(Type::JSON, $this->platform->getDoctrineTypeMapping('json'));
+ self::assertSame(Types::JSON, $this->platform->getDoctrineTypeMapping('json'));
}
/**
+ * @return string[]
+ *
* @group DBAL-234
*/
- protected function getAlterTableRenameIndexSQL()
+ protected function getAlterTableRenameIndexSQL() : array
{
return ['ALTER TABLE mytable RENAME INDEX idx_foo TO idx_bar'];
}
/**
+ * @return string[]
+ *
* @group DBAL-234
*/
- protected function getQuotedAlterTableRenameIndexSQL()
+ protected function getQuotedAlterTableRenameIndexSQL() : array
{
return [
'ALTER TABLE `table` RENAME INDEX `create` TO `select`',
@@ -51,17 +56,21 @@ protected function getQuotedAlterTableRenameIndexSQL()
}
/**
+ * @return string[]
+ *
* @group DBAL-807
*/
- protected function getAlterTableRenameIndexInSchemaSQL()
+ protected function getAlterTableRenameIndexInSchemaSQL() : array
{
return ['ALTER TABLE myschema.mytable RENAME INDEX idx_foo TO idx_bar'];
}
/**
+ * @return string[]
+ *
* @group DBAL-807
*/
- protected function getQuotedAlterTableRenameIndexInSchemaSQL()
+ protected function getQuotedAlterTableRenameIndexInSchemaSQL() : array
{
return [
'ALTER TABLE `schema`.`table` RENAME INDEX `create` TO `select`',
@@ -72,7 +81,7 @@ protected function getQuotedAlterTableRenameIndexInSchemaSQL()
/**
* {@inheritdoc}
*/
- protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
+ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : array
{
return ['ALTER TABLE mytable RENAME INDEX idx_foo TO idx_foo_renamed'];
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/MySqlPlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/MySqlPlatformTest.php
index ec1f3181581..e8007baf55f 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/MySqlPlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/MySqlPlatformTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\DBAL\TransactionIsolationLevel;
class MySqlPlatformTest extends AbstractMySQLPlatformTestCase
{
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new MySqlPlatform();
}
- public function testHasCorrectDefaultTransactionIsolationLevel()
+ public function testHasCorrectDefaultTransactionIsolationLevel() : void
{
self::assertEquals(
TransactionIsolationLevel::REPEATABLE_READ,
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/OraclePlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/OraclePlatformTest.php
index e8f8f0cdd7f..0dd4b304739 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/OraclePlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/OraclePlatformTest.php
@@ -3,6 +3,7 @@
namespace Doctrine\Tests\DBAL\Platforms;
use Doctrine\DBAL\DBALException;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\OraclePlatform;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\ColumnDiff;
@@ -21,7 +22,10 @@
class OraclePlatformTest extends AbstractPlatformTestCase
{
- public static function dataValidIdentifiers()
+ /**
+ * @return mixed[][]
+ */
+ public static function dataValidIdentifiers() : iterable
{
return [
['a'],
@@ -39,7 +43,7 @@ public static function dataValidIdentifiers()
/**
* @dataProvider dataValidIdentifiers
*/
- public function testValidIdentifiers($identifier)
+ public function testValidIdentifiers(string $identifier) : void
{
$platform = $this->createPlatform();
$platform->assertValidIdentifier($identifier);
@@ -47,7 +51,10 @@ public function testValidIdentifiers($identifier)
$this->addToAssertionCount(1);
}
- public static function dataInvalidIdentifiers()
+ /**
+ * @return mixed[][]
+ */
+ public static function dataInvalidIdentifiers() : iterable
{
return [
['1'],
@@ -61,7 +68,7 @@ public static function dataInvalidIdentifiers()
/**
* @dataProvider dataInvalidIdentifiers
*/
- public function testInvalidIdentifiers($identifier)
+ public function testInvalidIdentifiers(string $identifier) : void
{
$this->expectException(DBALException::class);
@@ -69,17 +76,20 @@ public function testInvalidIdentifiers($identifier)
$platform->assertValidIdentifier($identifier);
}
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new OraclePlatform();
}
- public function getGenerateTableSql()
+ public function getGenerateTableSql() : string
{
return 'CREATE TABLE test (id NUMBER(10) NOT NULL, test VARCHAR2(255) DEFAULT NULL NULL, PRIMARY KEY(id))';
}
- public function getGenerateTableWithMultiColumnUniqueIndexSql()
+ /**
+ * @return mixed[]
+ */
+ public function getGenerateTableWithMultiColumnUniqueIndexSql() : array
{
return [
'CREATE TABLE test (foo VARCHAR2(255) DEFAULT NULL NULL, bar VARCHAR2(255) DEFAULT NULL NULL)',
@@ -87,7 +97,10 @@ public function getGenerateTableWithMultiColumnUniqueIndexSql()
];
}
- public function getGenerateAlterTableSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateAlterTableSql() : array
{
return [
'ALTER TABLE mytable ADD (quota NUMBER(10) DEFAULT NULL NULL)',
@@ -97,21 +110,20 @@ public function getGenerateAlterTableSql()
];
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testRLike()
+ public function testRLike() : void
{
+ $this->expectException(DBALException::class);
+
self::assertEquals('RLIKE', $this->platform->getRegexpExpression(), 'Regular expression operator is not correct');
}
- public function testGeneratesSqlSnippets()
+ public function testGeneratesSqlSnippets() : void
{
self::assertEquals('"', $this->platform->getIdentifierQuoteCharacter(), 'Identifier quote character is not correct');
self::assertEquals('column1 || column2 || column3', $this->platform->getConcatExpression('column1', 'column2', 'column3'), 'Concatenation expression is not correct');
}
- public function testGeneratesTransactionsCommands()
+ public function testGeneratesTransactionsCommands() : void
{
self::assertEquals(
'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED',
@@ -131,25 +143,24 @@ public function testGeneratesTransactionsCommands()
);
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testCreateDatabaseThrowsException()
+ public function testCreateDatabaseThrowsException() : void
{
+ $this->expectException(DBALException::class);
+
self::assertEquals('CREATE DATABASE foobar', $this->platform->getCreateDatabaseSQL('foobar'));
}
- public function testDropDatabaseThrowsException()
+ public function testDropDatabaseThrowsException() : void
{
self::assertEquals('DROP USER foobar CASCADE', $this->platform->getDropDatabaseSQL('foobar'));
}
- public function testDropTable()
+ public function testDropTable() : void
{
self::assertEquals('DROP TABLE foobar', $this->platform->getDropTableSQL('foobar'));
}
- public function testGeneratesTypeDeclarationForIntegers()
+ public function testGeneratesTypeDeclarationForIntegers() : void
{
self::assertEquals(
'NUMBER(10)',
@@ -167,7 +178,7 @@ public function testGeneratesTypeDeclarationForIntegers()
);
}
- public function testGeneratesTypeDeclarationsForStrings()
+ public function testGeneratesTypeDeclarationsForStrings() : void
{
self::assertEquals(
'CHAR(10)',
@@ -187,17 +198,17 @@ public function testGeneratesTypeDeclarationsForStrings()
);
}
- public function testPrefersIdentityColumns()
+ public function testPrefersIdentityColumns() : void
{
self::assertFalse($this->platform->prefersIdentityColumns());
}
- public function testSupportsIdentityColumns()
+ public function testSupportsIdentityColumns() : void
{
self::assertFalse($this->platform->supportsIdentityColumns());
}
- public function testSupportsSavePoints()
+ public function testSupportsSavePoints() : void
{
self::assertTrue($this->platform->supportsSavepoints());
}
@@ -205,22 +216,22 @@ public function testSupportsSavePoints()
/**
* {@inheritdoc}
*/
- protected function supportsCommentOnStatement()
+ protected function supportsCommentOnStatement() : bool
{
return true;
}
- public function getGenerateIndexSql()
+ public function getGenerateIndexSql() : string
{
return 'CREATE INDEX my_idx ON mytable (user_name, last_login)';
}
- public function getGenerateUniqueIndexSql()
+ public function getGenerateUniqueIndexSql() : string
{
return 'CREATE UNIQUE INDEX index_name ON test (test, test2)';
}
- public function getGenerateForeignKeySql()
+ public function getGenerateForeignKeySql() : string
{
return 'ALTER TABLE test ADD FOREIGN KEY (fk_name_id) REFERENCES other_table (id)';
}
@@ -231,7 +242,7 @@ public function getGenerateForeignKeySql()
* @group DBAL-1097
* @dataProvider getGeneratesAdvancedForeignKeyOptionsSQLData
*/
- public function testGeneratesAdvancedForeignKeyOptionsSQL(array $options, $expectedSql)
+ public function testGeneratesAdvancedForeignKeyOptionsSQL(array $options, string $expectedSql) : void
{
$foreignKey = new ForeignKeyConstraint(['foo'], 'foreign_table', ['bar'], null, $options);
@@ -239,9 +250,9 @@ public function testGeneratesAdvancedForeignKeyOptionsSQL(array $options, $expec
}
/**
- * @return mixed[]
+ * @return mixed[][]
*/
- public function getGeneratesAdvancedForeignKeyOptionsSQLData()
+ public static function getGeneratesAdvancedForeignKeyOptionsSQLData() : iterable
{
return [
[[], ''],
@@ -256,7 +267,7 @@ public function getGeneratesAdvancedForeignKeyOptionsSQLData()
/**
* {@inheritdoc}
*/
- public function getReturnsForeignKeyReferentialActionSQL()
+ public static function getReturnsForeignKeyReferentialActionSQL() : iterable
{
return [
['CASCADE', 'CASCADE'],
@@ -267,43 +278,43 @@ public function getReturnsForeignKeyReferentialActionSQL()
];
}
- public function testModifyLimitQuery()
+ public function testModifyLimitQuery() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', 10, 0);
self::assertEquals('SELECT a.* FROM (SELECT * FROM user) a WHERE ROWNUM <= 10', $sql);
}
- public function testModifyLimitQueryWithEmptyOffset()
+ public function testModifyLimitQueryWithEmptyOffset() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', 10);
self::assertEquals('SELECT a.* FROM (SELECT * FROM user) a WHERE ROWNUM <= 10', $sql);
}
- public function testModifyLimitQueryWithNonEmptyOffset()
+ public function testModifyLimitQueryWithNonEmptyOffset() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', 10, 10);
self::assertEquals('SELECT * FROM (SELECT a.*, ROWNUM AS doctrine_rownum FROM (SELECT * FROM user) a WHERE ROWNUM <= 20) WHERE doctrine_rownum >= 11', $sql);
}
- public function testModifyLimitQueryWithEmptyLimit()
+ public function testModifyLimitQueryWithEmptyLimit() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', null, 10);
self::assertEquals('SELECT * FROM (SELECT a.*, ROWNUM AS doctrine_rownum FROM (SELECT * FROM user) a) WHERE doctrine_rownum >= 11', $sql);
}
- public function testModifyLimitQueryWithAscOrderBy()
+ public function testModifyLimitQueryWithAscOrderBy() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user ORDER BY username ASC', 10);
self::assertEquals('SELECT a.* FROM (SELECT * FROM user ORDER BY username ASC) a WHERE ROWNUM <= 10', $sql);
}
- public function testModifyLimitQueryWithDescOrderBy()
+ public function testModifyLimitQueryWithDescOrderBy() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user ORDER BY username DESC', 10);
self::assertEquals('SELECT a.* FROM (SELECT * FROM user ORDER BY username DESC) a WHERE ROWNUM <= 10', $sql);
}
- public function testGenerateTableWithAutoincrement()
+ public function testGenerateTableWithAutoincrement() : void
{
$columnName = strtoupper('id' . uniqid());
$tableName = strtoupper('table' . uniqid());
@@ -337,7 +348,7 @@ public function testGenerateTableWithAutoincrement()
];
$statements = $this->platform->getCreateTableSQL($table);
//strip all the whitespace from the statements
- array_walk($statements, static function (&$value) {
+ array_walk($statements, static function (&$value) : void {
$value = preg_replace('/\s+/', ' ', $value);
});
foreach ($targets as $key => $sql) {
@@ -346,7 +357,10 @@ public function testGenerateTableWithAutoincrement()
}
}
- public function getCreateTableColumnCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getCreateTableColumnCommentsSQL() : array
{
return [
'CREATE TABLE test (id NUMBER(10) NOT NULL, PRIMARY KEY(id))',
@@ -354,7 +368,10 @@ public function getCreateTableColumnCommentsSQL()
];
}
- public function getCreateTableColumnTypeCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getCreateTableColumnTypeCommentsSQL() : array
{
return [
'CREATE TABLE test (id NUMBER(10) NOT NULL, data CLOB NOT NULL, PRIMARY KEY(id))',
@@ -362,7 +379,10 @@ public function getCreateTableColumnTypeCommentsSQL()
];
}
- public function getAlterTableColumnCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getAlterTableColumnCommentsSQL() : array
{
return [
'ALTER TABLE mytable ADD (quota NUMBER(10) NOT NULL)',
@@ -372,24 +392,30 @@ public function getAlterTableColumnCommentsSQL()
];
}
- public function getBitAndComparisonExpressionSql($value1, $value2)
+ public function getBitAndComparisonExpressionSql(string $value1, string $value2) : string
{
return 'BITAND(' . $value1 . ', ' . $value2 . ')';
}
- public function getBitOrComparisonExpressionSql($value1, $value2)
+ public function getBitOrComparisonExpressionSql(string $value1, string $value2) : string
{
return '(' . $value1 . '-' .
$this->getBitAndComparisonExpressionSql($value1, $value2)
. '+' . $value2 . ')';
}
- protected function getQuotedColumnInPrimaryKeySQL()
+ /**
+ * @return mixed[]
+ */
+ protected function getQuotedColumnInPrimaryKeySQL() : array
{
return ['CREATE TABLE "quoted" ("create" VARCHAR2(255) NOT NULL, PRIMARY KEY("create"))'];
}
- protected function getQuotedColumnInIndexSQL()
+ /**
+ * @return mixed[]
+ */
+ protected function getQuotedColumnInIndexSQL() : array
{
return [
'CREATE TABLE "quoted" ("create" VARCHAR2(255) NOT NULL)',
@@ -397,7 +423,10 @@ protected function getQuotedColumnInIndexSQL()
];
}
- protected function getQuotedNameInIndexSQL()
+ /**
+ * @return mixed[]
+ */
+ protected function getQuotedNameInIndexSQL() : array
{
return [
'CREATE TABLE test (column1 VARCHAR2(255) NOT NULL)',
@@ -405,7 +434,10 @@ protected function getQuotedNameInIndexSQL()
];
}
- protected function getQuotedColumnInForeignKeySQL()
+ /**
+ * @return mixed[]
+ */
+ protected function getQuotedColumnInForeignKeySQL() : array
{
return [
'CREATE TABLE "quoted" ("create" VARCHAR2(255) NOT NULL, foo VARCHAR2(255) NOT NULL, "bar" VARCHAR2(255) NOT NULL)',
@@ -419,7 +451,7 @@ protected function getQuotedColumnInForeignKeySQL()
* @group DBAL-472
* @group DBAL-1001
*/
- public function testAlterTableNotNULL()
+ public function testAlterTableNotNULL() : void
{
$tableDiff = new TableDiff('mytable');
$tableDiff->changedColumns['foo'] = new ColumnDiff(
@@ -457,7 +489,7 @@ public function testAlterTableNotNULL()
/**
* @group DBAL-2555
*/
- public function testInitializesDoctrineTypeMappings()
+ public function testInitializesDoctrineTypeMappings() : void
{
self::assertTrue($this->platform->hasDoctrineTypeMappingFor('long raw'));
self::assertSame('blob', $this->platform->getDoctrineTypeMapping('long raw'));
@@ -469,12 +501,12 @@ public function testInitializesDoctrineTypeMappings()
self::assertSame('date', $this->platform->getDoctrineTypeMapping('date'));
}
- protected function getBinaryMaxLength()
+ protected function getBinaryMaxLength() : int
{
return 2000;
}
- public function testReturnsBinaryTypeDeclarationSQL()
+ public function testReturnsBinaryTypeDeclarationSQL() : void
{
self::assertSame('RAW(255)', $this->platform->getBinaryTypeDeclarationSQL([]));
self::assertSame('RAW(2000)', $this->platform->getBinaryTypeDeclarationSQL(['length' => 0]));
@@ -489,13 +521,13 @@ public function testReturnsBinaryTypeDeclarationSQL()
* @group legacy
* @expectedDeprecation Binary field length 2001 is greater than supported by the platform (2000). Reduce the field length or use a BLOB field instead.
*/
- public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL()
+ public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL() : void
{
self::assertSame('BLOB', $this->platform->getBinaryTypeDeclarationSQL(['length' => 2001]));
self::assertSame('BLOB', $this->platform->getBinaryTypeDeclarationSQL(['fixed' => true, 'length' => 2001]));
}
- public function testDoesNotPropagateUnnecessaryTableAlterationOnBinaryType()
+ public function testDoesNotPropagateUnnecessaryTableAlterationOnBinaryType() : void
{
$table1 = new Table('mytable');
$table1->addColumn('column_varbinary', 'binary');
@@ -515,7 +547,7 @@ public function testDoesNotPropagateUnnecessaryTableAlterationOnBinaryType()
/**
* @group DBAL-563
*/
- public function testUsesSequenceEmulatedIdentityColumns()
+ public function testUsesSequenceEmulatedIdentityColumns() : void
{
self::assertTrue($this->platform->usesSequenceEmulatedIdentityColumns());
}
@@ -524,7 +556,7 @@ public function testUsesSequenceEmulatedIdentityColumns()
* @group DBAL-563
* @group DBAL-831
*/
- public function testReturnsIdentitySequenceName()
+ public function testReturnsIdentitySequenceName() : void
{
self::assertSame('MYTABLE_SEQ', $this->platform->getIdentitySequenceName('mytable', 'mycolumn'));
self::assertSame('"mytable_SEQ"', $this->platform->getIdentitySequenceName('"mytable"', 'mycolumn'));
@@ -536,13 +568,16 @@ public function testReturnsIdentitySequenceName()
* @dataProvider dataCreateSequenceWithCache
* @group DBAL-139
*/
- public function testCreateSequenceWithCache($cacheSize, $expectedSql)
+ public function testCreateSequenceWithCache(int $cacheSize, string $expectedSql) : void
{
$sequence = new Sequence('foo', 1, 1, $cacheSize);
- self::assertContains($expectedSql, $this->platform->getCreateSequenceSQL($sequence));
+ self::assertStringContainsString($expectedSql, $this->platform->getCreateSequenceSQL($sequence));
}
- public function dataCreateSequenceWithCache()
+ /**
+ * @return mixed[][]
+ */
+ public static function dataCreateSequenceWithCache() : iterable
{
return [
[1, 'NOCACHE'],
@@ -552,17 +587,21 @@ public function dataCreateSequenceWithCache()
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getAlterTableRenameIndexSQL()
+ protected function getAlterTableRenameIndexSQL() : array
{
return ['ALTER INDEX idx_foo RENAME TO idx_bar'];
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getQuotedAlterTableRenameIndexSQL()
+ protected function getQuotedAlterTableRenameIndexSQL() : array
{
return [
'ALTER INDEX "create" RENAME TO "select"',
@@ -573,7 +612,7 @@ protected function getQuotedAlterTableRenameIndexSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableRenameColumnSQL()
+ protected function getQuotedAlterTableRenameColumnSQL() : array
{
return [
'ALTER TABLE mytable RENAME COLUMN unquoted1 TO unquoted',
@@ -591,23 +630,27 @@ protected function getQuotedAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableChangeColumnLengthSQL()
+ protected function getQuotedAlterTableChangeColumnLengthSQL() : array
{
$this->markTestIncomplete('Not implemented yet');
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-807
*/
- protected function getAlterTableRenameIndexInSchemaSQL()
+ protected function getAlterTableRenameIndexInSchemaSQL() : array
{
return ['ALTER INDEX myschema.idx_foo RENAME TO idx_bar'];
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-807
*/
- protected function getQuotedAlterTableRenameIndexInSchemaSQL()
+ protected function getQuotedAlterTableRenameIndexInSchemaSQL() : array
{
return [
'ALTER INDEX "schema"."create" RENAME TO "select"',
@@ -615,7 +658,7 @@ protected function getQuotedAlterTableRenameIndexInSchemaSQL()
];
}
- protected function getQuotesDropForeignKeySQL()
+ protected function getQuotesDropForeignKeySQL() : string
{
return 'ALTER TABLE "table" DROP CONSTRAINT "select"';
}
@@ -623,7 +666,7 @@ protected function getQuotesDropForeignKeySQL()
/**
* @group DBAL-423
*/
- public function testReturnsGuidTypeDeclarationSQL()
+ public function testReturnsGuidTypeDeclarationSQL() : void
{
self::assertSame('CHAR(36)', $this->platform->getGuidTypeDeclarationSQL([]));
}
@@ -631,21 +674,26 @@ public function testReturnsGuidTypeDeclarationSQL()
/**
* {@inheritdoc}
*/
- public function getAlterTableRenameColumnSQL()
+ public function getAlterTableRenameColumnSQL() : array
{
return ['ALTER TABLE foo RENAME COLUMN bar TO baz'];
}
/**
+ * @param string[] $expectedSql
+ *
* @dataProvider getReturnsDropAutoincrementSQL
* @group DBAL-831
*/
- public function testReturnsDropAutoincrementSQL($table, $expectedSql)
+ public function testReturnsDropAutoincrementSQL(string $table, array $expectedSql) : void
{
self::assertSame($expectedSql, $this->platform->getDropAutoincrementSql($table));
}
- public function getReturnsDropAutoincrementSQL()
+ /**
+ * @return mixed[][]
+ */
+ public static function getReturnsDropAutoincrementSQL() : iterable
{
return [
[
@@ -678,7 +726,7 @@ public function getReturnsDropAutoincrementSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesTableIdentifiersInAlterTableSQL()
+ protected function getQuotesTableIdentifiersInAlterTableSQL() : array
{
return [
'ALTER TABLE "foo" DROP CONSTRAINT fk1',
@@ -696,7 +744,7 @@ protected function getQuotesTableIdentifiersInAlterTableSQL()
/**
* {@inheritdoc}
*/
- protected function getCommentOnColumnSQL()
+ protected function getCommentOnColumnSQL() : array
{
return [
'COMMENT ON COLUMN foo.bar IS \'comment\'',
@@ -708,7 +756,7 @@ protected function getCommentOnColumnSQL()
/**
* @group DBAL-1004
*/
- public function testAltersTableColumnCommentWithExplicitlyQuotedIdentifiers()
+ public function testAltersTableColumnCommentWithExplicitlyQuotedIdentifiers() : void
{
$table1 = new Table('"foo"', [new Column('"bar"', Type::getType('integer'))]);
$table2 = new Table('"foo"', [new Column('"bar"', Type::getType('integer'), ['comment' => 'baz'])]);
@@ -724,7 +772,7 @@ public function testAltersTableColumnCommentWithExplicitlyQuotedIdentifiers()
);
}
- public function testQuotedTableNames()
+ public function testQuotedTableNames() : void
{
$table = new Table('"test"');
$table->addColumn('"id"', 'integer', ['autoincrement' => true]);
@@ -768,7 +816,7 @@ public function testQuotedTableNames()
* @dataProvider getReturnsGetListTableColumnsSQL
* @group DBAL-831
*/
- public function testReturnsGetListTableColumnsSQL($database, $expectedSql)
+ public function testReturnsGetListTableColumnsSQL(?string $database, string $expectedSql) : void
{
// note: this assertion is a bit strict, as it compares a full SQL string.
// Should this break in future, then please try to reduce the matching to substring matching while reworking
@@ -776,7 +824,10 @@ public function testReturnsGetListTableColumnsSQL($database, $expectedSql)
self::assertEquals($expectedSql, $this->platform->getListTableColumnsSQL('"test"', $database));
}
- public function getReturnsGetListTableColumnsSQL()
+ /**
+ * @return mixed[][]
+ */
+ public static function getReturnsGetListTableColumnsSQL() : iterable
{
return [
[
@@ -833,7 +884,7 @@ public function getReturnsGetListTableColumnsSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
+ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL() : string
{
return 'CONSTRAINT "select" UNIQUE (foo)';
}
@@ -841,7 +892,7 @@ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInIndexDeclarationSQL()
+ protected function getQuotesReservedKeywordInIndexDeclarationSQL() : string
{
return 'INDEX "select" (foo)';
}
@@ -849,7 +900,7 @@ protected function getQuotesReservedKeywordInIndexDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInTruncateTableSQL()
+ protected function getQuotesReservedKeywordInTruncateTableSQL() : string
{
return 'TRUNCATE TABLE "select"';
}
@@ -857,7 +908,7 @@ protected function getQuotesReservedKeywordInTruncateTableSQL()
/**
* {@inheritdoc}
*/
- protected function getAlterStringToFixedStringSQL()
+ protected function getAlterStringToFixedStringSQL() : array
{
return ['ALTER TABLE mytable MODIFY (name CHAR(2) DEFAULT NULL)'];
}
@@ -865,7 +916,7 @@ protected function getAlterStringToFixedStringSQL()
/**
* {@inheritdoc}
*/
- protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
+ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : array
{
return ['ALTER INDEX idx_foo RENAME TO idx_foo_renamed'];
}
@@ -873,48 +924,66 @@ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
/**
* @group DBAL-2436
*/
- public function testQuotesDatabaseNameInListSequencesSQL()
+ public function testQuotesDatabaseNameInListSequencesSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListSequencesSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListSequencesSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableIndexesSQL()
+ public function testQuotesTableNameInListTableIndexesSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableIndexesSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableIndexesSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableForeignKeysSQL()
+ public function testQuotesTableNameInListTableForeignKeysSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableForeignKeysSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableForeignKeysSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableConstraintsSQL()
+ public function testQuotesTableNameInListTableConstraintsSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableConstraintsSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableConstraintsSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableColumnsSQL()
+ public function testQuotesTableNameInListTableColumnsSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableColumnsSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableColumnsSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesDatabaseNameInListTableColumnsSQL()
+ public function testQuotesDatabaseNameInListTableColumnsSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableColumnsSQL('foo_table', "Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableColumnsSQL('foo_table', "Foo'Bar\\")
+ );
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL100PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL100PlatformTest.php
index df30fc471f0..8eb58c98e72 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL100PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL100PlatformTest.php
@@ -4,6 +4,7 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\PostgreSQL100Platform;
class PostgreSQL100PlatformTest extends PostgreSQL94PlatformTest
@@ -11,7 +12,7 @@ class PostgreSQL100PlatformTest extends PostgreSQL94PlatformTest
/**
* {@inheritdoc}
*/
- public function createPlatform() : PostgreSQL100Platform
+ public function createPlatform() : AbstractPlatform
{
return new PostgreSQL100Platform();
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL91PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL91PlatformTest.php
index ec62ac8b026..3ed82529e08 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL91PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL91PlatformTest.php
@@ -2,12 +2,13 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\PostgreSQL91Platform;
use Doctrine\DBAL\Schema\Table;
class PostgreSQL91PlatformTest extends PostgreSqlPlatformTest
{
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new PostgreSQL91Platform();
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL92PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL92PlatformTest.php
index fb36beb334a..7fbedd494be 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL92PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL92PlatformTest.php
@@ -2,15 +2,16 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\PostgreSQL92Platform;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
class PostgreSQL92PlatformTest extends AbstractPostgreSqlPlatformTestCase
{
/**
* {@inheritdoc}
*/
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new PostgreSQL92Platform();
}
@@ -18,7 +19,7 @@ public function createPlatform()
/**
* @group DBAL-553
*/
- public function testHasNativeJsonType()
+ public function testHasNativeJsonType() : void
{
self::assertTrue($this->platform->hasNativeJsonType());
}
@@ -26,12 +27,12 @@ public function testHasNativeJsonType()
/**
* @group DBAL-553
*/
- public function testReturnsJsonTypeDeclarationSQL()
+ public function testReturnsJsonTypeDeclarationSQL() : void
{
self::assertSame('JSON', $this->platform->getJsonTypeDeclarationSQL([]));
}
- public function testReturnsSmallIntTypeDeclarationSQL()
+ public function testReturnsSmallIntTypeDeclarationSQL() : void
{
self::assertSame(
'SMALLSERIAL',
@@ -52,16 +53,16 @@ public function testReturnsSmallIntTypeDeclarationSQL()
/**
* @group DBAL-553
*/
- public function testInitializesJsonTypeMapping()
+ public function testInitializesJsonTypeMapping() : void
{
self::assertTrue($this->platform->hasDoctrineTypeMappingFor('json'));
- self::assertEquals(Type::JSON, $this->platform->getDoctrineTypeMapping('json'));
+ self::assertEquals(Types::JSON, $this->platform->getDoctrineTypeMapping('json'));
}
/**
* @group DBAL-1220
*/
- public function testReturnsCloseActiveDatabaseConnectionsSQL()
+ public function testReturnsCloseActiveDatabaseConnectionsSQL() : void
{
self::assertSame(
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'foo'",
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL94PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL94PlatformTest.php
index ed118aec406..179e005b2f9 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL94PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/PostgreSQL94PlatformTest.php
@@ -2,30 +2,31 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\PostgreSQL94Platform;
-use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
class PostgreSQL94PlatformTest extends PostgreSQL92PlatformTest
{
/**
* {@inheritdoc}
*/
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new PostgreSQL94Platform();
}
- public function testReturnsJsonTypeDeclarationSQL()
+ public function testReturnsJsonTypeDeclarationSQL() : void
{
parent::testReturnsJsonTypeDeclarationSQL();
self::assertSame('JSON', $this->platform->getJsonTypeDeclarationSQL(['jsonb' => false]));
self::assertSame('JSONB', $this->platform->getJsonTypeDeclarationSQL(['jsonb' => true]));
}
- public function testInitializesJsonTypeMapping()
+ public function testInitializesJsonTypeMapping() : void
{
parent::testInitializesJsonTypeMapping();
self::assertTrue($this->platform->hasDoctrineTypeMappingFor('jsonb'));
- self::assertEquals(Type::JSON, $this->platform->getDoctrineTypeMapping('jsonb'));
+ self::assertEquals(Types::JSON, $this->platform->getDoctrineTypeMapping('jsonb'));
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/PostgreSqlPlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/PostgreSqlPlatformTest.php
index b45a152ab0a..0b029d3497d 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/PostgreSqlPlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/PostgreSqlPlatformTest.php
@@ -2,17 +2,34 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
+use Doctrine\DBAL\Schema\Table;
class PostgreSqlPlatformTest extends AbstractPostgreSqlPlatformTestCase
{
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new PostgreSqlPlatform();
}
- public function testSupportsPartialIndexes()
+ public function testSupportsPartialIndexes() : void
{
self::assertTrue($this->platform->supportsPartialIndexes());
}
+
+ public function testGetCreateTableSQLWithColumnCollation() : void
+ {
+ $table = new Table('foo');
+ $table->addColumn('id', 'string');
+ $table->addOption('comment', 'foo');
+ self::assertSame(
+ [
+ 'CREATE TABLE foo (id VARCHAR(255) NOT NULL)',
+ "COMMENT ON TABLE foo IS 'foo'",
+ ],
+ $this->platform->getCreateTableSQL($table),
+ 'Comments are added to table.'
+ );
+ }
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/ReservedKeywordsValidatorTest.php b/tests/Doctrine/Tests/DBAL/Platforms/ReservedKeywordsValidatorTest.php
index 22ab967fd7e..8d07f62274d 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/ReservedKeywordsValidatorTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/ReservedKeywordsValidatorTest.php
@@ -12,12 +12,12 @@ class ReservedKeywordsValidatorTest extends DbalTestCase
/** @var ReservedKeywordsValidator */
private $validator;
- protected function setUp()
+ protected function setUp() : void
{
$this->validator = new ReservedKeywordsValidator([new MySQLKeywords()]);
}
- public function testReservedTableName()
+ public function testReservedTableName() : void
{
$table = new Table('TABLE');
$this->validator->acceptTable($table);
@@ -28,7 +28,7 @@ public function testReservedTableName()
);
}
- public function testReservedColumnName()
+ public function testReservedColumnName() : void
{
$table = new Table('TABLE');
$column = $table->addColumn('table', 'string');
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere11PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere11PlatformTest.php
index 7e91777d6ef..bf3f7372df3 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere11PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere11PlatformTest.php
@@ -2,6 +2,7 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SQLAnywhere11Platform;
class SQLAnywhere11PlatformTest extends SQLAnywherePlatformTest
@@ -9,17 +10,17 @@ class SQLAnywhere11PlatformTest extends SQLAnywherePlatformTest
/** @var SQLAnywhere11Platform */
protected $platform;
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new SQLAnywhere11Platform();
}
- public function testDoesNotSupportRegexp()
+ public function testDoesNotSupportRegexp() : void
{
$this->markTestSkipped('This version of the platform now supports regular expressions.');
}
- public function testGeneratesRegularExpressionSQLSnippet()
+ public function testGeneratesRegularExpressionSQLSnippet() : void
{
self::assertEquals('REGEXP', $this->platform->getRegexpExpression());
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere12PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere12PlatformTest.php
index 7cbb2c69bb8..e60f6b1c7f1 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere12PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere12PlatformTest.php
@@ -2,6 +2,7 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SQLAnywhere12Platform;
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Sequence;
@@ -11,22 +12,22 @@ class SQLAnywhere12PlatformTest extends SQLAnywhere11PlatformTest
/** @var SQLAnywhere12Platform */
protected $platform;
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new SQLAnywhere12Platform();
}
- public function testDoesNotSupportSequences()
+ public function testDoesNotSupportSequences() : void
{
$this->markTestSkipped('This version of the platform now supports sequences.');
}
- public function testSupportsSequences()
+ public function testSupportsSequences() : void
{
self::assertTrue($this->platform->supportsSequences());
}
- public function testGeneratesSequenceSqlCommands()
+ public function testGeneratesSequenceSqlCommands() : void
{
$sequence = new Sequence('myseq', 20, 1);
self::assertEquals(
@@ -55,7 +56,7 @@ public function testGeneratesSequenceSqlCommands()
);
}
- public function testGeneratesDateTimeTzColumnTypeDeclarationSQL()
+ public function testGeneratesDateTimeTzColumnTypeDeclarationSQL() : void
{
self::assertEquals(
'TIMESTAMP WITH TIME ZONE',
@@ -68,18 +69,18 @@ public function testGeneratesDateTimeTzColumnTypeDeclarationSQL()
);
}
- public function testHasCorrectDateTimeTzFormatString()
+ public function testHasCorrectDateTimeTzFormatString() : void
{
self::assertEquals('Y-m-d H:i:s.uP', $this->platform->getDateTimeTzFormatString());
}
- public function testInitializesDateTimeTzTypeMapping()
+ public function testInitializesDateTimeTzTypeMapping() : void
{
self::assertTrue($this->platform->hasDoctrineTypeMappingFor('timestamp with time zone'));
self::assertEquals('datetime', $this->platform->getDoctrineTypeMapping('timestamp with time zone'));
}
- public function testGeneratesCreateIndexWithAdvancedPlatformOptionsSQL()
+ public function testGeneratesCreateIndexWithAdvancedPlatformOptionsSQL() : void
{
self::assertEquals(
'CREATE VIRTUAL UNIQUE CLUSTERED INDEX fooindex ON footable (a, b) WITH NULLS NOT DISTINCT FOR OLAP WORKLOAD',
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere16PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere16PlatformTest.php
index 9692ffb1f76..a6a0018a06e 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere16PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywhere16PlatformTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SQLAnywhere16Platform;
use Doctrine\DBAL\Schema\Index;
class SQLAnywhere16PlatformTest extends SQLAnywhere12PlatformTest
{
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new SQLAnywhere16Platform();
}
- public function testGeneratesCreateIndexWithAdvancedPlatformOptionsSQL()
+ public function testGeneratesCreateIndexWithAdvancedPlatformOptionsSQL() : void
{
self::assertEquals(
'CREATE UNIQUE INDEX fooindex ON footable (a, b) WITH NULLS DISTINCT',
@@ -61,7 +62,7 @@ public function testGeneratesCreateIndexWithAdvancedPlatformOptionsSQL()
parent::testGeneratesCreateIndexWithAdvancedPlatformOptionsSQL();
}
- public function testThrowsExceptionOnInvalidWithNullsNotDistinctIndexOptions()
+ public function testThrowsExceptionOnInvalidWithNullsNotDistinctIndexOptions() : void
{
$this->expectException('UnexpectedValueException');
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywherePlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywherePlatformTest.php
index 219119c2cc1..0efa23b19c6 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywherePlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/SQLAnywherePlatformTest.php
@@ -27,12 +27,15 @@ class SQLAnywherePlatformTest extends AbstractPlatformTestCase
/** @var SQLAnywherePlatform */
protected $platform;
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new SQLAnywherePlatform();
}
- public function getGenerateAlterTableSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateAlterTableSql() : array
{
return [
"ALTER TABLE mytable ADD quota INT DEFAULT NULL, DROP foo, ALTER baz VARCHAR(1) DEFAULT 'def' NOT NULL, ALTER bloo BIT DEFAULT '0' NOT NULL",
@@ -40,22 +43,25 @@ public function getGenerateAlterTableSql()
];
}
- public function getGenerateForeignKeySql()
+ public function getGenerateForeignKeySql() : string
{
return 'ALTER TABLE test ADD FOREIGN KEY (fk_name_id) REFERENCES other_table (id)';
}
- public function getGenerateIndexSql()
+ public function getGenerateIndexSql() : string
{
return 'CREATE INDEX my_idx ON mytable (user_name, last_login)';
}
- public function getGenerateTableSql()
+ public function getGenerateTableSql() : string
{
return 'CREATE TABLE test (id INT IDENTITY NOT NULL, test VARCHAR(255) DEFAULT NULL, PRIMARY KEY (id))';
}
- public function getGenerateTableWithMultiColumnUniqueIndexSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateTableWithMultiColumnUniqueIndexSql() : array
{
return [
'CREATE TABLE test (foo VARCHAR(255) DEFAULT NULL, bar VARCHAR(255) DEFAULT NULL)',
@@ -63,17 +69,23 @@ public function getGenerateTableWithMultiColumnUniqueIndexSql()
];
}
- public function getGenerateUniqueIndexSql()
+ public function getGenerateUniqueIndexSql() : string
{
return 'CREATE UNIQUE INDEX index_name ON test (test, test2)';
}
- protected function getQuotedColumnInForeignKeySQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInForeignKeySQL() : array
{
return ['CREATE TABLE "quoted" ("create" VARCHAR(255) NOT NULL, foo VARCHAR(255) NOT NULL, "bar" VARCHAR(255) NOT NULL, CONSTRAINT FK_WITH_RESERVED_KEYWORD FOREIGN KEY ("create", foo, "bar") REFERENCES "foreign" ("create", bar, "foo-bar"), CONSTRAINT FK_WITH_NON_RESERVED_KEYWORD FOREIGN KEY ("create", foo, "bar") REFERENCES foo ("create", bar, "foo-bar"), CONSTRAINT FK_WITH_INTENDED_QUOTATION FOREIGN KEY ("create", foo, "bar") REFERENCES "foo-bar" ("create", bar, "foo-bar"))'];
}
- protected function getQuotedColumnInIndexSQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInIndexSQL() : array
{
return [
'CREATE TABLE "quoted" ("create" VARCHAR(255) NOT NULL)',
@@ -81,7 +93,10 @@ protected function getQuotedColumnInIndexSQL()
];
}
- protected function getQuotedNameInIndexSQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedNameInIndexSQL() : array
{
return [
'CREATE TABLE test (column1 VARCHAR(255) NOT NULL)',
@@ -89,12 +104,18 @@ protected function getQuotedNameInIndexSQL()
];
}
- protected function getQuotedColumnInPrimaryKeySQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInPrimaryKeySQL() : array
{
return ['CREATE TABLE "quoted" ("create" VARCHAR(255) NOT NULL, PRIMARY KEY ("create"))'];
}
- public function getCreateTableColumnCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getCreateTableColumnCommentsSQL() : array
{
return [
'CREATE TABLE test (id INT NOT NULL, PRIMARY KEY (id))',
@@ -102,7 +123,10 @@ public function getCreateTableColumnCommentsSQL()
];
}
- public function getAlterTableColumnCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getAlterTableColumnCommentsSQL() : array
{
return [
'ALTER TABLE mytable ADD quota INT NOT NULL',
@@ -112,7 +136,10 @@ public function getAlterTableColumnCommentsSQL()
];
}
- public function getCreateTableColumnTypeCommentsSQL()
+ /**
+ * {@inheritDoc}
+ */
+ public function getCreateTableColumnTypeCommentsSQL() : array
{
return [
'CREATE TABLE test (id INT NOT NULL, data TEXT NOT NULL, PRIMARY KEY (id))',
@@ -120,12 +147,12 @@ public function getCreateTableColumnTypeCommentsSQL()
];
}
- public function testHasCorrectPlatformName()
+ public function testHasCorrectPlatformName() : void
{
self::assertEquals('sqlanywhere', $this->platform->getName());
}
- public function testGeneratesCreateTableSQLWithCommonIndexes()
+ public function testGeneratesCreateTableSQLWithCommonIndexes() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
@@ -144,7 +171,7 @@ public function testGeneratesCreateTableSQLWithCommonIndexes()
);
}
- public function testGeneratesCreateTableSQLWithForeignKeyConstraints()
+ public function testGeneratesCreateTableSQLWithForeignKeyConstraints() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
@@ -169,7 +196,7 @@ public function testGeneratesCreateTableSQLWithForeignKeyConstraints()
);
}
- public function testGeneratesCreateTableSQLWithCheckConstraints()
+ public function testGeneratesCreateTableSQLWithCheckConstraints() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
@@ -183,7 +210,7 @@ public function testGeneratesCreateTableSQLWithCheckConstraints()
);
}
- public function testGeneratesTableAlterationWithRemovedColumnCommentSql()
+ public function testGeneratesTableAlterationWithRemovedColumnCommentSql() : void
{
$table = new Table('mytable');
$table->addColumn('foo', 'string', ['comment' => 'foo comment']);
@@ -203,9 +230,11 @@ public function testGeneratesTableAlterationWithRemovedColumnCommentSql()
}
/**
+ * @param int|bool|null $lockMode
+ *
* @dataProvider getLockHints
*/
- public function testAppendsLockHint($lockMode, $lockHint)
+ public function testAppendsLockHint($lockMode, string $lockHint) : void
{
$fromClause = 'FROM users';
$expectedResult = $fromClause . $lockHint;
@@ -213,7 +242,10 @@ public function testAppendsLockHint($lockMode, $lockHint)
self::assertSame($expectedResult, $this->platform->appendLockHint($fromClause, $lockMode));
}
- public function getLockHints()
+ /**
+ * @return mixed[][]
+ */
+ public static function getLockHints() : iterable
{
return [
[null, ''],
@@ -226,12 +258,12 @@ public function getLockHints()
];
}
- public function testHasCorrectMaxIdentifierLength()
+ public function testHasCorrectMaxIdentifierLength() : void
{
self::assertEquals(128, $this->platform->getMaxIdentifierLength());
}
- public function testFixesSchemaElementNames()
+ public function testFixesSchemaElementNames() : void
{
$maxIdentifierLength = $this->platform->getMaxIdentifierLength();
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
@@ -253,7 +285,7 @@ public function testFixesSchemaElementNames()
);
}
- public function testGeneratesColumnTypesDeclarationSQL()
+ public function testGeneratesColumnTypesDeclarationSQL() : void
{
$fullColumnDef = [
'length' => 10,
@@ -283,12 +315,12 @@ public function testGeneratesColumnTypesDeclarationSQL()
self::assertEquals(32767, $this->platform->getVarcharMaxLength());
}
- public function testHasNativeGuidType()
+ public function testHasNativeGuidType() : void
{
self::assertTrue($this->platform->hasNativeGuidType());
}
- public function testGeneratesDDLSnippets()
+ public function testGeneratesDDLSnippets() : void
{
self::assertEquals("CREATE DATABASE 'foobar'", $this->platform->getCreateDatabaseSQL('foobar'));
self::assertEquals("CREATE DATABASE 'foobar'", $this->platform->getCreateDatabaseSQL('"foobar"'));
@@ -311,7 +343,7 @@ public function testGeneratesDDLSnippets()
self::assertEquals('DROP VIEW fooview', $this->platform->getDropViewSQL('fooview'));
}
- public function testGeneratesPrimaryKeyDeclarationSQL()
+ public function testGeneratesPrimaryKeyDeclarationSQL() : void
{
self::assertEquals(
'CONSTRAINT pk PRIMARY KEY CLUSTERED (a, b)',
@@ -328,14 +360,14 @@ public function testGeneratesPrimaryKeyDeclarationSQL()
);
}
- public function testCannotGeneratePrimaryKeyDeclarationSQLWithEmptyColumns()
+ public function testCannotGeneratePrimaryKeyDeclarationSQLWithEmptyColumns() : void
{
$this->expectException(InvalidArgumentException::class);
$this->platform->getPrimaryKeyDeclarationSQL(new Index('pk', [], true, true));
}
- public function testGeneratesCreateUnnamedPrimaryKeySQL()
+ public function testGeneratesCreateUnnamedPrimaryKeySQL() : void
{
self::assertEquals(
'ALTER TABLE foo ADD PRIMARY KEY CLUSTERED (a, b)',
@@ -353,7 +385,7 @@ public function testGeneratesCreateUnnamedPrimaryKeySQL()
);
}
- public function testGeneratesUniqueConstraintDeclarationSQL()
+ public function testGeneratesUniqueConstraintDeclarationSQL() : void
{
self::assertEquals(
'CONSTRAINT unique_constraint UNIQUE CLUSTERED (a, b)',
@@ -368,14 +400,14 @@ public function testGeneratesUniqueConstraintDeclarationSQL()
);
}
- public function testCannotGenerateUniqueConstraintDeclarationSQLWithEmptyColumns()
+ public function testCannotGenerateUniqueConstraintDeclarationSQLWithEmptyColumns() : void
{
$this->expectException(InvalidArgumentException::class);
$this->platform->getUniqueConstraintDeclarationSQL('constr', new Index('constr', [], true));
}
- public function testGeneratesForeignKeyConstraintsWithAdvancedPlatformOptionsSQL()
+ public function testGeneratesForeignKeyConstraintsWithAdvancedPlatformOptionsSQL() : void
{
self::assertEquals(
'CONSTRAINT fk ' .
@@ -402,7 +434,7 @@ public function testGeneratesForeignKeyConstraintsWithAdvancedPlatformOptionsSQL
);
}
- public function testGeneratesForeignKeyMatchClausesSQL()
+ public function testGeneratesForeignKeyMatchClausesSQL() : void
{
self::assertEquals('SIMPLE', $this->platform->getForeignKeyMatchClauseSQL(1));
self::assertEquals('FULL', $this->platform->getForeignKeyMatchClauseSQL(2));
@@ -410,46 +442,46 @@ public function testGeneratesForeignKeyMatchClausesSQL()
self::assertEquals('UNIQUE FULL', $this->platform->getForeignKeyMatchClauseSQL(130));
}
- public function testCannotGenerateInvalidForeignKeyMatchClauseSQL()
+ public function testCannotGenerateInvalidForeignKeyMatchClauseSQL() : void
{
$this->expectException(InvalidArgumentException::class);
$this->platform->getForeignKeyMatchCLauseSQL(3);
}
- public function testCannotGenerateForeignKeyConstraintSQLWithEmptyLocalColumns()
+ public function testCannotGenerateForeignKeyConstraintSQLWithEmptyLocalColumns() : void
{
$this->expectException(InvalidArgumentException::class);
$this->platform->getForeignKeyDeclarationSQL(new ForeignKeyConstraint([], 'foreign_tbl', ['c', 'd']));
}
- public function testCannotGenerateForeignKeyConstraintSQLWithEmptyForeignColumns()
+ public function testCannotGenerateForeignKeyConstraintSQLWithEmptyForeignColumns() : void
{
$this->expectException(InvalidArgumentException::class);
$this->platform->getForeignKeyDeclarationSQL(new ForeignKeyConstraint(['a', 'b'], 'foreign_tbl', []));
}
- public function testCannotGenerateForeignKeyConstraintSQLWithEmptyForeignTableName()
+ public function testCannotGenerateForeignKeyConstraintSQLWithEmptyForeignTableName() : void
{
$this->expectException(InvalidArgumentException::class);
$this->platform->getForeignKeyDeclarationSQL(new ForeignKeyConstraint(['a', 'b'], '', ['c', 'd']));
}
- public function testCannotGenerateCommonIndexWithCreateConstraintSQL()
+ public function testCannotGenerateCommonIndexWithCreateConstraintSQL() : void
{
$this->expectException(InvalidArgumentException::class);
$this->platform->getCreateConstraintSQL(new Index('fooindex', []), new Table('footable'));
}
- public function testCannotGenerateCustomConstraintWithCreateConstraintSQL()
+ public function testCannotGenerateCustomConstraintWithCreateConstraintSQL() : void
{
$this->expectException(InvalidArgumentException::class);
$this->platform->getCreateConstraintSQL($this->createMock(Constraint::class), 'footable');
}
- public function testGeneratesCreateIndexWithAdvancedPlatformOptionsSQL()
+ public function testGeneratesCreateIndexWithAdvancedPlatformOptionsSQL() : void
{
self::assertEquals(
'CREATE VIRTUAL UNIQUE CLUSTERED INDEX fooindex ON footable (a, b) FOR OLAP WORKLOAD',
@@ -466,14 +498,14 @@ public function testGeneratesCreateIndexWithAdvancedPlatformOptionsSQL()
);
}
- public function testDoesNotSupportIndexDeclarationInCreateAlterTableStatements()
+ public function testDoesNotSupportIndexDeclarationInCreateAlterTableStatements() : void
{
$this->expectException(DBALException::class);
$this->platform->getIndexDeclarationSQL('index', new Index('index', []));
}
- public function testGeneratesDropIndexSQL()
+ public function testGeneratesDropIndexSQL() : void
{
$index = new Index('fooindex', []);
@@ -485,21 +517,21 @@ public function testGeneratesDropIndexSQL()
));
}
- public function testCannotGenerateDropIndexSQLWithInvalidIndexParameter()
+ public function testCannotGenerateDropIndexSQLWithInvalidIndexParameter() : void
{
$this->expectException(InvalidArgumentException::class);
$this->platform->getDropIndexSQL(['index'], 'table');
}
- public function testCannotGenerateDropIndexSQLWithInvalidTableParameter()
+ public function testCannotGenerateDropIndexSQLWithInvalidTableParameter() : void
{
$this->expectException(InvalidArgumentException::class);
$this->platform->getDropIndexSQL('index', ['table']);
}
- public function testGeneratesSQLSnippets()
+ public function testGeneratesSQLSnippets() : void
{
self::assertEquals('STRING(column1, "string1", column2, "string2")', $this->platform->getConcatExpression(
'column1',
@@ -573,14 +605,14 @@ public function testGeneratesSQLSnippets()
);
}
- public function testDoesNotSupportRegexp()
+ public function testDoesNotSupportRegexp() : void
{
$this->expectException(DBALException::class);
$this->platform->getRegexpExpression();
}
- public function testHasCorrectDateTimeTzFormatString()
+ public function testHasCorrectDateTimeTzFormatString() : void
{
// Date time type with timezone is not supported before version 12.
// For versions before we have to ensure that the date time with timezone format
@@ -588,7 +620,7 @@ public function testHasCorrectDateTimeTzFormatString()
self::assertEquals($this->platform->getDateTimeFormatString(), $this->platform->getDateTimeTzFormatString());
}
- public function testHasCorrectDefaultTransactionIsolationLevel()
+ public function testHasCorrectDefaultTransactionIsolationLevel() : void
{
self::assertEquals(
TransactionIsolationLevel::READ_UNCOMMITTED,
@@ -596,7 +628,7 @@ public function testHasCorrectDefaultTransactionIsolationLevel()
);
}
- public function testGeneratesTransactionsCommands()
+ public function testGeneratesTransactionsCommands() : void
{
self::assertEquals(
'SET TEMPORARY OPTION isolation_level = 0',
@@ -616,14 +648,14 @@ public function testGeneratesTransactionsCommands()
);
}
- public function testCannotGenerateTransactionCommandWithInvalidIsolationLevel()
+ public function testCannotGenerateTransactionCommandWithInvalidIsolationLevel() : void
{
$this->expectException(InvalidArgumentException::class);
$this->platform->getSetTransactionIsolationSQL('invalid_transaction_isolation_level');
}
- public function testModifiesLimitQuery()
+ public function testModifiesLimitQuery() : void
{
self::assertEquals(
'SELECT TOP 10 * FROM user',
@@ -631,7 +663,7 @@ public function testModifiesLimitQuery()
);
}
- public function testModifiesLimitQueryWithEmptyOffset()
+ public function testModifiesLimitQueryWithEmptyOffset() : void
{
self::assertEquals(
'SELECT TOP 10 * FROM user',
@@ -639,7 +671,7 @@ public function testModifiesLimitQueryWithEmptyOffset()
);
}
- public function testModifiesLimitQueryWithOffset()
+ public function testModifiesLimitQueryWithOffset() : void
{
self::assertEquals(
'SELECT TOP 10 START AT 6 * FROM user',
@@ -651,7 +683,7 @@ public function testModifiesLimitQueryWithOffset()
);
}
- public function testModifiesLimitQueryWithSubSelect()
+ public function testModifiesLimitQueryWithSubSelect() : void
{
self::assertEquals(
'SELECT TOP 10 * FROM (SELECT u.id as uid, u.name as uname FROM user) AS doctrine_tbl',
@@ -659,7 +691,7 @@ public function testModifiesLimitQueryWithSubSelect()
);
}
- public function testModifiesLimitQueryWithoutLimit()
+ public function testModifiesLimitQueryWithoutLimit() : void
{
self::assertEquals(
'SELECT TOP ALL START AT 11 n FROM Foo',
@@ -667,97 +699,97 @@ public function testModifiesLimitQueryWithoutLimit()
);
}
- public function testPrefersIdentityColumns()
+ public function testPrefersIdentityColumns() : void
{
self::assertTrue($this->platform->prefersIdentityColumns());
}
- public function testDoesNotPreferSequences()
+ public function testDoesNotPreferSequences() : void
{
self::assertFalse($this->platform->prefersSequences());
}
- public function testSupportsIdentityColumns()
+ public function testSupportsIdentityColumns() : void
{
self::assertTrue($this->platform->supportsIdentityColumns());
}
- public function testSupportsPrimaryConstraints()
+ public function testSupportsPrimaryConstraints() : void
{
self::assertTrue($this->platform->supportsPrimaryConstraints());
}
- public function testSupportsForeignKeyConstraints()
+ public function testSupportsForeignKeyConstraints() : void
{
self::assertTrue($this->platform->supportsForeignKeyConstraints());
}
- public function testSupportsForeignKeyOnUpdate()
+ public function testSupportsForeignKeyOnUpdate() : void
{
self::assertTrue($this->platform->supportsForeignKeyOnUpdate());
}
- public function testSupportsAlterTable()
+ public function testSupportsAlterTable() : void
{
self::assertTrue($this->platform->supportsAlterTable());
}
- public function testSupportsTransactions()
+ public function testSupportsTransactions() : void
{
self::assertTrue($this->platform->supportsTransactions());
}
- public function testSupportsSchemas()
+ public function testSupportsSchemas() : void
{
self::assertFalse($this->platform->supportsSchemas());
}
- public function testSupportsIndexes()
+ public function testSupportsIndexes() : void
{
self::assertTrue($this->platform->supportsIndexes());
}
- public function testSupportsCommentOnStatement()
+ public function testSupportsCommentOnStatement() : void
{
self::assertTrue($this->platform->supportsCommentOnStatement());
}
- public function testSupportsSavePoints()
+ public function testSupportsSavePoints() : void
{
self::assertTrue($this->platform->supportsSavepoints());
}
- public function testSupportsReleasePoints()
+ public function testSupportsReleasePoints() : void
{
self::assertTrue($this->platform->supportsReleaseSavepoints());
}
- public function testSupportsCreateDropDatabase()
+ public function testSupportsCreateDropDatabase() : void
{
self::assertTrue($this->platform->supportsCreateDropDatabase());
}
- public function testSupportsGettingAffectedRows()
+ public function testSupportsGettingAffectedRows() : void
{
self::assertTrue($this->platform->supportsGettingAffectedRows());
}
- public function testDoesNotSupportSequences()
+ public function testDoesNotSupportSequences() : void
{
self::assertFalse($this->platform->supportsSequences());
}
- public function testDoesNotSupportInlineColumnComments()
+ public function testDoesNotSupportInlineColumnComments() : void
{
self::assertFalse($this->platform->supportsInlineColumnComments());
}
- public function testCannotEmulateSchemas()
+ public function testCannotEmulateSchemas() : void
{
self::assertFalse($this->platform->canEmulateSchemas());
}
- public function testInitializesDoctrineTypeMappings()
+ public function testInitializesDoctrineTypeMappings() : void
{
self::assertTrue($this->platform->hasDoctrineTypeMappingFor('integer'));
self::assertSame('integer', $this->platform->getDoctrineTypeMapping('integer'));
@@ -769,17 +801,17 @@ public function testInitializesDoctrineTypeMappings()
self::assertSame('binary', $this->platform->getDoctrineTypeMapping('varbinary'));
}
- protected function getBinaryDefaultLength()
+ protected function getBinaryDefaultLength() : int
{
return 1;
}
- protected function getBinaryMaxLength()
+ protected function getBinaryMaxLength() : int
{
return 32767;
}
- public function testReturnsBinaryTypeDeclarationSQL()
+ public function testReturnsBinaryTypeDeclarationSQL() : void
{
self::assertSame('VARBINARY(1)', $this->platform->getBinaryTypeDeclarationSQL([]));
self::assertSame('VARBINARY(1)', $this->platform->getBinaryTypeDeclarationSQL(['length' => 0]));
@@ -794,24 +826,28 @@ public function testReturnsBinaryTypeDeclarationSQL()
* @group legacy
* @expectedDeprecation Binary field length 32768 is greater than supported by the platform (32767). Reduce the field length or use a BLOB field instead.
*/
- public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL()
+ public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL() : void
{
self::assertSame('LONG BINARY', $this->platform->getBinaryTypeDeclarationSQL(['length' => 32768]));
self::assertSame('LONG BINARY', $this->platform->getBinaryTypeDeclarationSQL(['fixed' => true, 'length' => 32768]));
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getAlterTableRenameIndexSQL()
+ protected function getAlterTableRenameIndexSQL() : array
{
return ['ALTER INDEX idx_foo ON mytable RENAME TO idx_bar'];
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getQuotedAlterTableRenameIndexSQL()
+ protected function getQuotedAlterTableRenameIndexSQL() : array
{
return [
'ALTER INDEX "create" ON "table" RENAME TO "select"',
@@ -822,7 +858,7 @@ protected function getQuotedAlterTableRenameIndexSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableRenameColumnSQL()
+ protected function getQuotedAlterTableRenameColumnSQL() : array
{
return [
'ALTER TABLE mytable RENAME unquoted1 TO unquoted',
@@ -840,23 +876,27 @@ protected function getQuotedAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableChangeColumnLengthSQL()
+ protected function getQuotedAlterTableChangeColumnLengthSQL() : array
{
$this->markTestIncomplete('Not implemented yet');
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-807
*/
- protected function getAlterTableRenameIndexInSchemaSQL()
+ protected function getAlterTableRenameIndexInSchemaSQL() : array
{
return ['ALTER INDEX idx_foo ON myschema.mytable RENAME TO idx_bar'];
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-807
*/
- protected function getQuotedAlterTableRenameIndexInSchemaSQL()
+ protected function getQuotedAlterTableRenameIndexInSchemaSQL() : array
{
return [
'ALTER INDEX "create" ON "schema"."table" RENAME TO "select"',
@@ -867,7 +907,7 @@ protected function getQuotedAlterTableRenameIndexInSchemaSQL()
/**
* @group DBAL-423
*/
- public function testReturnsGuidTypeDeclarationSQL()
+ public function testReturnsGuidTypeDeclarationSQL() : void
{
self::assertSame('UNIQUEIDENTIFIER', $this->platform->getGuidTypeDeclarationSQL([]));
}
@@ -875,7 +915,7 @@ public function testReturnsGuidTypeDeclarationSQL()
/**
* {@inheritdoc}
*/
- public function getAlterTableRenameColumnSQL()
+ public function getAlterTableRenameColumnSQL() : array
{
return ['ALTER TABLE foo RENAME bar TO baz'];
}
@@ -883,7 +923,7 @@ public function getAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesTableIdentifiersInAlterTableSQL()
+ protected function getQuotesTableIdentifiersInAlterTableSQL() : array
{
return [
'ALTER TABLE "foo" DROP FOREIGN KEY fk1',
@@ -899,7 +939,7 @@ protected function getQuotesTableIdentifiersInAlterTableSQL()
/**
* {@inheritdoc}
*/
- protected function getCommentOnColumnSQL()
+ protected function getCommentOnColumnSQL() : array
{
return [
'COMMENT ON COLUMN foo.bar IS \'comment\'',
@@ -911,7 +951,7 @@ protected function getCommentOnColumnSQL()
/**
* @group DBAL-1004
*/
- public function testAltersTableColumnCommentWithExplicitlyQuotedIdentifiers()
+ public function testAltersTableColumnCommentWithExplicitlyQuotedIdentifiers() : void
{
$table1 = new Table('"foo"', [new Column('"bar"', Type::getType('integer'))]);
$table2 = new Table('"foo"', [new Column('"bar"', Type::getType('integer'), ['comment' => 'baz'])]);
@@ -930,7 +970,7 @@ public function testAltersTableColumnCommentWithExplicitlyQuotedIdentifiers()
/**
* {@inheritdoc}
*/
- public function getReturnsForeignKeyReferentialActionSQL()
+ public static function getReturnsForeignKeyReferentialActionSQL() : iterable
{
return [
['CASCADE', 'CASCADE'],
@@ -945,7 +985,7 @@ public function getReturnsForeignKeyReferentialActionSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
+ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL() : string
{
return 'CONSTRAINT "select" UNIQUE (foo)';
}
@@ -953,7 +993,7 @@ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInIndexDeclarationSQL()
+ protected function getQuotesReservedKeywordInIndexDeclarationSQL() : string
{
return ''; // not supported by this platform
}
@@ -961,7 +1001,7 @@ protected function getQuotesReservedKeywordInIndexDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInTruncateTableSQL()
+ protected function getQuotesReservedKeywordInTruncateTableSQL() : string
{
return 'TRUNCATE TABLE "select"';
}
@@ -969,7 +1009,7 @@ protected function getQuotesReservedKeywordInTruncateTableSQL()
/**
* {@inheritdoc}
*/
- protected function supportsInlineIndexDeclaration()
+ protected function supportsInlineIndexDeclaration() : bool
{
return false;
}
@@ -977,7 +1017,7 @@ protected function supportsInlineIndexDeclaration()
/**
* {@inheritdoc}
*/
- protected function getAlterStringToFixedStringSQL()
+ protected function getAlterStringToFixedStringSQL() : array
{
return ['ALTER TABLE mytable ALTER name CHAR(2) NOT NULL'];
}
@@ -985,7 +1025,7 @@ protected function getAlterStringToFixedStringSQL()
/**
* {@inheritdoc}
*/
- protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
+ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : array
{
return ['ALTER INDEX idx_foo ON mytable RENAME TO idx_foo_renamed'];
}
@@ -993,76 +1033,74 @@ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
/**
* @group DBAL-2436
*/
- public function testQuotesSchemaNameInListTableColumnsSQL()
+ public function testQuotesSchemaNameInListTableColumnsSQL() : void
{
- self::assertContains(
+ self::assertStringContainsStringIgnoringCase(
"'Foo''Bar\\'",
- $this->platform->getListTableColumnsSQL("Foo'Bar\\.baz_table"),
- '',
- true
+ $this->platform->getListTableColumnsSQL("Foo'Bar\\.baz_table")
);
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableConstraintsSQL()
+ public function testQuotesTableNameInListTableConstraintsSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableConstraintsSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase("'Foo''Bar\\'", $this->platform->getListTableConstraintsSQL("Foo'Bar\\"), '', true);
}
/**
* @group DBAL-2436
*/
- public function testQuotesSchemaNameInListTableConstraintsSQL()
+ public function testQuotesSchemaNameInListTableConstraintsSQL() : void
{
- self::assertContains(
+ self::assertStringContainsStringIgnoringCase(
"'Foo''Bar\\'",
- $this->platform->getListTableConstraintsSQL("Foo'Bar\\.baz_table"),
- '',
- true
+ $this->platform->getListTableConstraintsSQL("Foo'Bar\\.baz_table")
);
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableForeignKeysSQL()
+ public function testQuotesTableNameInListTableForeignKeysSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableForeignKeysSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableForeignKeysSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesSchemaNameInListTableForeignKeysSQL()
+ public function testQuotesSchemaNameInListTableForeignKeysSQL() : void
{
- self::assertContains(
+ self::assertStringContainsStringIgnoringCase(
"'Foo''Bar\\'",
- $this->platform->getListTableForeignKeysSQL("Foo'Bar\\.baz_table"),
- '',
- true
+ $this->platform->getListTableForeignKeysSQL("Foo'Bar\\.baz_table")
);
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableIndexesSQL()
+ public function testQuotesTableNameInListTableIndexesSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableIndexesSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableIndexesSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesSchemaNameInListTableIndexesSQL()
+ public function testQuotesSchemaNameInListTableIndexesSQL() : void
{
- self::assertContains(
+ self::assertStringContainsStringIgnoringCase(
"'Foo''Bar\\'",
- $this->platform->getListTableIndexesSQL("Foo'Bar\\.baz_table"),
- '',
- true
+ $this->platform->getListTableIndexesSQL("Foo'Bar\\.baz_table")
);
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/SQLAzurePlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/SQLAzurePlatformTest.php
index e42aaeb8eaf..65b5e85f219 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/SQLAzurePlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/SQLAzurePlatformTest.php
@@ -14,12 +14,12 @@ class SQLAzurePlatformTest extends DbalTestCase
/** @var SQLAzurePlatform */
private $platform;
- protected function setUp()
+ protected function setUp() : void
{
$this->platform = new SQLAzurePlatform();
}
- public function testCreateFederatedOnTable()
+ public function testCreateFederatedOnTable() : void
{
$table = new Table('tbl');
$table->addColumn('id', 'integer');
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/SQLServer2008PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/SQLServer2008PlatformTest.php
index 3083ab7b606..60abcad7c06 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/SQLServer2008PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/SQLServer2008PlatformTest.php
@@ -2,16 +2,17 @@
namespace Doctrine\Tests\DBAL\Platforms;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SQLServer2008Platform;
class SQLServer2008PlatformTest extends AbstractSQLServerPlatformTestCase
{
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new SQLServer2008Platform();
}
- public function testGeneratesTypeDeclarationForDateTimeTz()
+ public function testGeneratesTypeDeclarationForDateTimeTz() : void
{
self::assertEquals('DATETIMEOFFSET(6)', $this->platform->getDateTimeTzTypeDeclarationSQL([]));
}
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/SQLServer2012PlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/SQLServer2012PlatformTest.php
index b908c427c28..18a8a0ef1d2 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/SQLServer2012PlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/SQLServer2012PlatformTest.php
@@ -3,27 +3,28 @@
namespace Doctrine\Tests\DBAL\Platforms;
use Doctrine\DBAL\DBALException;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SQLServer2012Platform;
use Doctrine\DBAL\Schema\Sequence;
class SQLServer2012PlatformTest extends AbstractSQLServerPlatformTestCase
{
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new SQLServer2012Platform();
}
- public function testSupportsSequences()
+ public function testSupportsSequences() : void
{
self::assertTrue($this->platform->supportsSequences());
}
- public function testDoesNotPreferSequences()
+ public function testDoesNotPreferSequences() : void
{
self::assertFalse($this->platform->prefersSequences());
}
- public function testGeneratesSequenceSqlCommands()
+ public function testGeneratesSequenceSqlCommands() : void
{
$sequence = new Sequence('myseq', 20, 1);
self::assertEquals(
@@ -44,56 +45,55 @@ public function testGeneratesSequenceSqlCommands()
);
}
-
- public function testModifyLimitQuery()
+ public function testModifyLimitQuery() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', 10, 0);
self::assertEquals('SELECT * FROM user ORDER BY (SELECT 0) OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
}
- public function testModifyLimitQueryWithEmptyOffset()
+ public function testModifyLimitQueryWithEmptyOffset() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', 10);
self::assertEquals('SELECT * FROM user ORDER BY (SELECT 0) OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
}
- public function testModifyLimitQueryWithOffset()
+ public function testModifyLimitQueryWithOffset() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user ORDER BY username DESC', 10, 5);
self::assertEquals('SELECT * FROM user ORDER BY username DESC OFFSET 5 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
}
- public function testModifyLimitQueryWithAscOrderBy()
+ public function testModifyLimitQueryWithAscOrderBy() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user ORDER BY username ASC', 10);
self::assertEquals('SELECT * FROM user ORDER BY username ASC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
}
- public function testModifyLimitQueryWithLowercaseOrderBy()
+ public function testModifyLimitQueryWithLowercaseOrderBy() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user order by username', 10);
self::assertEquals('SELECT * FROM user order by username OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
}
- public function testModifyLimitQueryWithDescOrderBy()
+ public function testModifyLimitQueryWithDescOrderBy() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user ORDER BY username DESC', 10);
self::assertEquals('SELECT * FROM user ORDER BY username DESC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
}
- public function testModifyLimitQueryWithMultipleOrderBy()
+ public function testModifyLimitQueryWithMultipleOrderBy() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user ORDER BY username DESC, usereamil ASC', 10);
self::assertEquals('SELECT * FROM user ORDER BY username DESC, usereamil ASC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
}
- public function testModifyLimitQueryWithSubSelect()
+ public function testModifyLimitQueryWithSubSelect() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM (SELECT u.id as uid, u.name as uname) dctrn_result', 10);
self::assertEquals('SELECT * FROM (SELECT u.id as uid, u.name as uname) dctrn_result ORDER BY (SELECT 0) OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
}
- public function testModifyLimitQueryWithSubSelectAndOrder()
+ public function testModifyLimitQueryWithSubSelectAndOrder() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM (SELECT u.id as uid, u.name as uname) dctrn_result ORDER BY uname DESC', 10);
self::assertEquals('SELECT * FROM (SELECT u.id as uid, u.name as uname) dctrn_result ORDER BY uname DESC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
@@ -102,7 +102,7 @@ public function testModifyLimitQueryWithSubSelectAndOrder()
self::assertEquals('SELECT * FROM (SELECT u.id, u.name) dctrn_result ORDER BY name DESC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
}
- public function testModifyLimitQueryWithSubSelectAndMultipleOrder()
+ public function testModifyLimitQueryWithSubSelectAndMultipleOrder() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM (SELECT u.id as uid, u.name as uname) dctrn_result ORDER BY uname DESC, uid ASC', 10, 5);
self::assertEquals('SELECT * FROM (SELECT u.id as uid, u.name as uname) dctrn_result ORDER BY uname DESC, uid ASC OFFSET 5 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
@@ -114,7 +114,7 @@ public function testModifyLimitQueryWithSubSelectAndMultipleOrder()
self::assertEquals('SELECT * FROM (SELECT u.id, u.name) dctrn_result ORDER BY name DESC, id ASC OFFSET 5 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
}
- public function testModifyLimitQueryWithFromColumnNames()
+ public function testModifyLimitQueryWithFromColumnNames() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT a.fromFoo, fromBar FROM foo', 10);
self::assertEquals('SELECT a.fromFoo, fromBar FROM foo ORDER BY (SELECT 0) OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', $sql);
@@ -123,7 +123,7 @@ public function testModifyLimitQueryWithFromColumnNames()
/**
* @group DBAL-927
*/
- public function testModifyLimitQueryWithExtraLongQuery()
+ public function testModifyLimitQueryWithExtraLongQuery() : void
{
$query = 'SELECT table1.column1, table2.column2, table3.column3, table4.column4, table5.column5, table6.column6, table7.column7, table8.column8 FROM table1, table2, table3, table4, table5, table6, table7, table8 ';
$query .= 'WHERE (table1.column1 = table2.column2) AND (table1.column1 = table3.column3) AND (table1.column1 = table4.column4) AND (table1.column1 = table5.column5) AND (table1.column1 = table6.column6) AND (table1.column1 = table7.column7) AND (table1.column1 = table8.column8) AND (table2.column2 = table3.column3) AND (table2.column2 = table4.column4) AND (table2.column2 = table5.column5) AND (table2.column2 = table6.column6) ';
@@ -144,7 +144,7 @@ public function testModifyLimitQueryWithExtraLongQuery()
/**
* @group DDC-2470
*/
- public function testModifyLimitQueryWithOrderByClause()
+ public function testModifyLimitQueryWithOrderByClause() : void
{
$sql = 'SELECT m0_.NOMBRE AS NOMBRE0, m0_.FECHAINICIO AS FECHAINICIO1, m0_.FECHAFIN AS FECHAFIN2 FROM MEDICION m0_ WITH (NOLOCK) INNER JOIN ESTUDIO e1_ ON m0_.ESTUDIO_ID = e1_.ID INNER JOIN CLIENTE c2_ ON e1_.CLIENTE_ID = c2_.ID INNER JOIN USUARIO u3_ ON c2_.ID = u3_.CLIENTE_ID WHERE u3_.ID = ? ORDER BY m0_.FECHAINICIO DESC';
$expected = 'SELECT m0_.NOMBRE AS NOMBRE0, m0_.FECHAINICIO AS FECHAINICIO1, m0_.FECHAFIN AS FECHAFIN2 FROM MEDICION m0_ WITH (NOLOCK) INNER JOIN ESTUDIO e1_ ON m0_.ESTUDIO_ID = e1_.ID INNER JOIN CLIENTE c2_ ON e1_.CLIENTE_ID = c2_.ID INNER JOIN USUARIO u3_ ON c2_.ID = u3_.CLIENTE_ID WHERE u3_.ID = ? ORDER BY m0_.FECHAINICIO DESC OFFSET 5 ROWS FETCH NEXT 10 ROWS ONLY';
@@ -156,7 +156,7 @@ public function testModifyLimitQueryWithOrderByClause()
/**
* @group DBAL-713
*/
- public function testModifyLimitQueryWithSubSelectInSelectList()
+ public function testModifyLimitQueryWithSubSelectInSelectList() : void
{
$sql = $this->platform->modifyLimitQuery(
'SELECT ' .
@@ -186,7 +186,7 @@ public function testModifyLimitQueryWithSubSelectInSelectList()
/**
* @group DBAL-713
*/
- public function testModifyLimitQueryWithSubSelectInSelectListAndOrderByClause()
+ public function testModifyLimitQueryWithSubSelectInSelectListAndOrderByClause() : void
{
$sql = $this->platform->modifyLimitQuery(
'SELECT ' .
@@ -218,7 +218,7 @@ public function testModifyLimitQueryWithSubSelectInSelectListAndOrderByClause()
/**
* @group DBAL-834
*/
- public function testModifyLimitQueryWithAggregateFunctionInOrderByClause()
+ public function testModifyLimitQueryWithAggregateFunctionInOrderByClause() : void
{
$sql = $this->platform->modifyLimitQuery(
'SELECT ' .
@@ -243,7 +243,7 @@ public function testModifyLimitQueryWithAggregateFunctionInOrderByClause()
);
}
- public function testModifyLimitQueryWithFromSubquery()
+ public function testModifyLimitQueryWithFromSubquery() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT DISTINCT id_0 FROM (SELECT k0_.id AS id_0 FROM key_measure k0_ WHERE (k0_.id_zone in(2))) dctrn_result', 10);
@@ -252,7 +252,7 @@ public function testModifyLimitQueryWithFromSubquery()
self::assertEquals($sql, $expected);
}
- public function testModifyLimitQueryWithFromSubqueryAndOrder()
+ public function testModifyLimitQueryWithFromSubqueryAndOrder() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT DISTINCT id_0, value_1 FROM (SELECT k0_.id AS id_0, k0_.value AS value_1 FROM key_measure k0_ WHERE (k0_.id_zone in(2))) dctrn_result ORDER BY value_1 DESC', 10);
@@ -261,7 +261,7 @@ public function testModifyLimitQueryWithFromSubqueryAndOrder()
self::assertEquals($sql, $expected);
}
- public function testModifyLimitQueryWithComplexOrderByExpression()
+ public function testModifyLimitQueryWithComplexOrderByExpression() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM table ORDER BY (table.x * table.y) DESC', 10);
@@ -270,11 +270,10 @@ public function testModifyLimitQueryWithComplexOrderByExpression()
self::assertEquals($sql, $expected);
}
-
/**
* @throws DBALException
*/
- public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromBaseTable()
+ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromBaseTable() : void
{
$querySql = 'SELECT DISTINCT id_0, name_1 '
. 'FROM ('
@@ -297,7 +296,7 @@ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromBas
/**
* @throws DBALException
*/
- public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromJoinTable()
+ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromJoinTable() : void
{
$querySql = 'SELECT DISTINCT id_0, name_1 '
. 'FROM ('
@@ -320,7 +319,7 @@ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromJoi
/**
* @throws DBALException
*/
- public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnsFromBothTables()
+ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnsFromBothTables() : void
{
$querySql = 'SELECT DISTINCT id_0, name_1, foo_2 '
. 'FROM ('
@@ -340,7 +339,7 @@ public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnsFromBo
self::assertEquals($alteredSql, $sql);
}
- public function testModifyLimitSubquerySimple()
+ public function testModifyLimitSubquerySimple() : void
{
$querySql = 'SELECT DISTINCT id_0 FROM '
. '(SELECT k0_.id AS id_0, k0_.field AS field_1 '
@@ -351,7 +350,7 @@ public function testModifyLimitSubquerySimple()
self::assertEquals($alteredSql, $sql);
}
- public function testModifyLimitQueryWithTopNSubQueryWithOrderBy()
+ public function testModifyLimitQueryWithTopNSubQueryWithOrderBy() : void
{
$querySql = 'SELECT * FROM test t WHERE t.id = (SELECT TOP 1 t2.id FROM test t2 ORDER BY t2.data DESC)';
$expectedSql = 'SELECT * FROM test t WHERE t.id = (SELECT TOP 1 t2.id FROM test t2 ORDER BY t2.data DESC) ORDER BY (SELECT 0) OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY';
@@ -364,7 +363,7 @@ public function testModifyLimitQueryWithTopNSubQueryWithOrderBy()
self::assertEquals($expectedSql, $sql);
}
- public function testModifyLimitQueryWithNewlineBeforeOrderBy()
+ public function testModifyLimitQueryWithNewlineBeforeOrderBy() : void
{
$querySql = "SELECT * FROM test\nORDER BY col DESC";
$expectedSql = "SELECT * FROM test\nORDER BY col DESC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY";
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/SQLServerPlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/SQLServerPlatformTest.php
index ed2842813aa..77cf7b17b41 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/SQLServerPlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/SQLServerPlatformTest.php
@@ -3,20 +3,23 @@
namespace Doctrine\Tests\DBAL\Platforms;
use Doctrine\DBAL\LockMode;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SQLServerPlatform;
class SQLServerPlatformTest extends AbstractSQLServerPlatformTestCase
{
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new SQLServerPlatform();
}
/**
+ * @param int|bool|null $lockMode
+ *
* @group DDC-2310
* @dataProvider getLockHints
*/
- public function testAppendsLockHint($lockMode, $lockHint)
+ public function testAppendsLockHint($lockMode, string $lockHint) : void
{
$fromClause = 'FROM users';
$expectedResult = $fromClause . $lockHint;
@@ -28,12 +31,15 @@ public function testAppendsLockHint($lockMode, $lockHint)
* @group DBAL-2408
* @dataProvider getModifyLimitQueries
*/
- public function testScrubInnerOrderBy($query, $limit, $offset, $expectedResult)
+ public function testScrubInnerOrderBy(string $query, int $limit, ?int $offset, string $expectedResult) : void
{
self::assertSame($expectedResult, $this->platform->modifyLimitQuery($query, $limit, $offset));
}
- public function getLockHints()
+ /**
+ * @return mixed[][]
+ */
+ public static function getLockHints() : iterable
{
return [
[null, ''],
@@ -46,7 +52,10 @@ public function getLockHints()
];
}
- public function getModifyLimitQueries()
+ /**
+ * @return mixed[][]
+ */
+ public static function getModifyLimitQueries() : iterable
{
return [
// Test re-ordered query with correctly-scrubbed ORDER BY clause
diff --git a/tests/Doctrine/Tests/DBAL/Platforms/SqlitePlatformTest.php b/tests/Doctrine/Tests/DBAL/Platforms/SqlitePlatformTest.php
index f2e12ae7b22..d645b218cb8 100644
--- a/tests/Doctrine/Tests/DBAL/Platforms/SqlitePlatformTest.php
+++ b/tests/Doctrine/Tests/DBAL/Platforms/SqlitePlatformTest.php
@@ -3,6 +3,7 @@
namespace Doctrine\Tests\DBAL\Platforms;
use Doctrine\DBAL\DBALException;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\Table;
@@ -12,17 +13,20 @@
class SqlitePlatformTest extends AbstractPlatformTestCase
{
- public function createPlatform()
+ public function createPlatform() : AbstractPlatform
{
return new SqlitePlatform();
}
- public function getGenerateTableSql()
+ public function getGenerateTableSql() : string
{
return 'CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, test VARCHAR(255) DEFAULT NULL)';
}
- public function getGenerateTableWithMultiColumnUniqueIndexSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateTableWithMultiColumnUniqueIndexSql() : array
{
return [
'CREATE TABLE test (foo VARCHAR(255) DEFAULT NULL, bar VARCHAR(255) DEFAULT NULL)',
@@ -30,14 +34,14 @@ public function getGenerateTableWithMultiColumnUniqueIndexSql()
];
}
- public function testGeneratesSqlSnippets()
+ public function testGeneratesSqlSnippets() : void
{
self::assertEquals('REGEXP', $this->platform->getRegexpExpression(), 'Regular expression operator is not correct');
self::assertEquals('SUBSTR(column, 5, LENGTH(column))', $this->platform->getSubstringExpression('column', 5), 'Substring expression without length is not correct');
self::assertEquals('SUBSTR(column, 0, 5)', $this->platform->getSubstringExpression('column', 0, 5), 'Substring expression with length is not correct');
}
- public function testGeneratesTransactionCommands()
+ public function testGeneratesTransactionCommands() : void
{
self::assertEquals(
'PRAGMA read_uncommitted = 0',
@@ -57,12 +61,12 @@ public function testGeneratesTransactionCommands()
);
}
- public function testPrefersIdentityColumns()
+ public function testPrefersIdentityColumns() : void
{
self::assertTrue($this->platform->prefersIdentityColumns());
}
- public function testIgnoresUnsignedIntegerDeclarationForAutoIncrementalIntegers()
+ public function testIgnoresUnsignedIntegerDeclarationForAutoIncrementalIntegers() : void
{
self::assertSame(
'INTEGER PRIMARY KEY AUTOINCREMENT',
@@ -74,7 +78,7 @@ public function testIgnoresUnsignedIntegerDeclarationForAutoIncrementalIntegers(
* @group DBAL-752
* @group DBAL-924
*/
- public function testGeneratesTypeDeclarationForTinyIntegers()
+ public function testGeneratesTypeDeclarationForTinyIntegers() : void
{
self::assertEquals(
'TINYINT',
@@ -104,7 +108,7 @@ public function testGeneratesTypeDeclarationForTinyIntegers()
* @group DBAL-752
* @group DBAL-924
*/
- public function testGeneratesTypeDeclarationForSmallIntegers()
+ public function testGeneratesTypeDeclarationForSmallIntegers() : void
{
self::assertEquals(
'SMALLINT',
@@ -138,7 +142,7 @@ public function testGeneratesTypeDeclarationForSmallIntegers()
* @group DBAL-752
* @group DBAL-924
*/
- public function testGeneratesTypeDeclarationForMediumIntegers()
+ public function testGeneratesTypeDeclarationForMediumIntegers() : void
{
self::assertEquals(
'MEDIUMINT',
@@ -168,7 +172,7 @@ public function testGeneratesTypeDeclarationForMediumIntegers()
);
}
- public function testGeneratesTypeDeclarationForIntegers()
+ public function testGeneratesTypeDeclarationForIntegers() : void
{
self::assertEquals(
'INTEGER',
@@ -202,7 +206,7 @@ public function testGeneratesTypeDeclarationForIntegers()
* @group DBAL-752
* @group DBAL-924
*/
- public function testGeneratesTypeDeclarationForBigIntegers()
+ public function testGeneratesTypeDeclarationForBigIntegers() : void
{
self::assertEquals(
'BIGINT',
@@ -232,7 +236,7 @@ public function testGeneratesTypeDeclarationForBigIntegers()
);
}
- public function testGeneratesTypeDeclarationForStrings()
+ public function testGeneratesTypeDeclarationForStrings() : void
{
self::assertEquals(
'CHAR(10)',
@@ -252,56 +256,57 @@ public function testGeneratesTypeDeclarationForStrings()
);
}
- public function getGenerateIndexSql()
+ public function getGenerateIndexSql() : string
{
return 'CREATE INDEX my_idx ON mytable (user_name, last_login)';
}
- public function getGenerateUniqueIndexSql()
+ public function getGenerateUniqueIndexSql() : string
{
return 'CREATE UNIQUE INDEX index_name ON test (test, test2)';
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testGeneratesForeignKeyCreationSql()
+ public function testGeneratesForeignKeyCreationSql() : void
{
+ $this->expectException(DBALException::class);
+
parent::testGeneratesForeignKeyCreationSql();
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testGeneratesConstraintCreationSql()
+ public function testGeneratesConstraintCreationSql() : void
{
+ $this->expectException(DBALException::class);
+
parent::testGeneratesConstraintCreationSql();
}
- public function getGenerateForeignKeySql()
+ public function getGenerateForeignKeySql() : string
{
return null;
}
- public function testModifyLimitQuery()
+ public function testModifyLimitQuery() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', 10, 0);
self::assertEquals('SELECT * FROM user LIMIT 10', $sql);
}
- public function testModifyLimitQueryWithEmptyOffset()
+ public function testModifyLimitQueryWithEmptyOffset() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', 10);
self::assertEquals('SELECT * FROM user LIMIT 10', $sql);
}
- public function testModifyLimitQueryWithOffsetAndEmptyLimit()
+ public function testModifyLimitQueryWithOffsetAndEmptyLimit() : void
{
$sql = $this->platform->modifyLimitQuery('SELECT * FROM user', null, 10);
self::assertEquals('SELECT * FROM user LIMIT -1 OFFSET 10', $sql);
}
- public function getGenerateAlterTableSql()
+ /**
+ * {@inheritDoc}
+ */
+ public function getGenerateAlterTableSql() : array
{
return [
'CREATE TEMPORARY TABLE __temp__mytable AS SELECT id, bar, bloo FROM mytable',
@@ -316,7 +321,7 @@ public function getGenerateAlterTableSql()
/**
* @group DDC-1845
*/
- public function testGenerateTableSqlShouldNotAutoQuotePrimaryKey()
+ public function testGenerateTableSqlShouldNotAutoQuotePrimaryKey() : void
{
$table = new Table('test');
$table->addColumn('"like"', 'integer', ['notnull' => true, 'autoincrement' => true]);
@@ -329,7 +334,7 @@ public function testGenerateTableSqlShouldNotAutoQuotePrimaryKey()
);
}
- public function testAlterTableAddColumns()
+ public function testAlterTableAddColumns() : void
{
$diff = new TableDiff('user');
$diff->addedColumns['foo'] = new Column('foo', Type::getType('string'));
@@ -353,8 +358,10 @@ public function testAlterTableAddComplexColumns(TableDiff $diff) : void
$this->platform->getAlterTableSQL($diff);
}
- /** @return mixed[] */
- public function complexDiffProvider() : array
+ /**
+ * @return mixed[][]
+ */
+ public static function complexDiffProvider() : iterable
{
$date = new TableDiff('user');
$date->addedColumns['time'] = new Column('time', Type::getType('date'), ['default' => 'CURRENT_DATE']);
@@ -368,7 +375,7 @@ public function complexDiffProvider() : array
];
}
- public function testCreateTableWithDeferredForeignKeys()
+ public function testCreateTableWithDeferredForeignKeys() : void
{
$table = new Table('user');
$table->addColumn('id', 'integer');
@@ -396,7 +403,7 @@ public function testCreateTableWithDeferredForeignKeys()
self::assertEquals($sql, $this->platform->getCreateTableSQL($table));
}
- public function testAlterTable()
+ public function testAlterTable() : void
{
$table = new Table('user');
$table->addColumn('id', 'integer');
@@ -440,12 +447,18 @@ public function testAlterTable()
self::assertEquals($sql, $this->platform->getAlterTableSQL($diff));
}
- protected function getQuotedColumnInPrimaryKeySQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInPrimaryKeySQL() : array
{
return ['CREATE TABLE "quoted" ("create" VARCHAR(255) NOT NULL, PRIMARY KEY("create"))'];
}
- protected function getQuotedColumnInIndexSQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInIndexSQL() : array
{
return [
'CREATE TABLE "quoted" ("create" VARCHAR(255) NOT NULL)',
@@ -453,7 +466,10 @@ protected function getQuotedColumnInIndexSQL()
];
}
- protected function getQuotedNameInIndexSQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedNameInIndexSQL() : array
{
return [
'CREATE TABLE test (column1 VARCHAR(255) NOT NULL)',
@@ -461,7 +477,10 @@ protected function getQuotedNameInIndexSQL()
];
}
- protected function getQuotedColumnInForeignKeySQL()
+ /**
+ * {@inheritDoc}
+ */
+ protected function getQuotedColumnInForeignKeySQL() : array
{
return [
'CREATE TABLE "quoted" (' .
@@ -472,17 +491,17 @@ protected function getQuotedColumnInForeignKeySQL()
];
}
- protected function getBinaryDefaultLength()
+ protected function getBinaryDefaultLength() : int
{
return 0;
}
- protected function getBinaryMaxLength()
+ protected function getBinaryMaxLength() : int
{
return 0;
}
- public function testReturnsBinaryTypeDeclarationSQL()
+ public function testReturnsBinaryTypeDeclarationSQL() : void
{
self::assertSame('BLOB', $this->platform->getBinaryTypeDeclarationSQL([]));
self::assertSame('BLOB', $this->platform->getBinaryTypeDeclarationSQL(['length' => 0]));
@@ -494,9 +513,11 @@ public function testReturnsBinaryTypeDeclarationSQL()
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getAlterTableRenameIndexSQL()
+ protected function getAlterTableRenameIndexSQL() : array
{
return [
'CREATE TEMPORARY TABLE __temp__mytable AS SELECT id FROM mytable',
@@ -509,9 +530,11 @@ protected function getAlterTableRenameIndexSQL()
}
/**
+ * {@inheritDoc}
+ *
* @group DBAL-234
*/
- protected function getQuotedAlterTableRenameIndexSQL()
+ protected function getQuotedAlterTableRenameIndexSQL() : array
{
return [
'CREATE TEMPORARY TABLE __temp__table AS SELECT id FROM "table"',
@@ -527,7 +550,7 @@ protected function getQuotedAlterTableRenameIndexSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableRenameColumnSQL()
+ protected function getQuotedAlterTableRenameColumnSQL() : array
{
return [
'CREATE TEMPORARY TABLE __temp__mytable AS SELECT unquoted1, unquoted2, unquoted3, "create", "table", "select", "quoted1", "quoted2", "quoted3" FROM mytable',
@@ -550,7 +573,7 @@ protected function getQuotedAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotedAlterTableChangeColumnLengthSQL()
+ protected function getQuotedAlterTableChangeColumnLengthSQL() : array
{
return [
'CREATE TEMPORARY TABLE __temp__mytable AS SELECT unquoted1, unquoted2, unquoted3, "create", "table", "select" FROM mytable',
@@ -570,7 +593,7 @@ protected function getQuotedAlterTableChangeColumnLengthSQL()
/**
* @group DBAL-807
*/
- public function testAlterTableRenameIndexInSchema()
+ public function testAlterTableRenameIndexInSchema() : void
{
$this->markTestIncomplete(
'Test currently produces broken SQL due to SQLLitePlatform::getAlterTable being broken ' .
@@ -581,7 +604,7 @@ public function testAlterTableRenameIndexInSchema()
/**
* @group DBAL-807
*/
- public function testQuotesAlterTableRenameIndexInSchema()
+ public function testQuotesAlterTableRenameIndexInSchema() : void
{
$this->markTestIncomplete(
'Test currently produces broken SQL due to SQLLitePlatform::getAlterTable being broken ' .
@@ -592,7 +615,7 @@ public function testQuotesAlterTableRenameIndexInSchema()
/**
* @group DBAL-423
*/
- public function testReturnsGuidTypeDeclarationSQL()
+ public function testReturnsGuidTypeDeclarationSQL() : void
{
self::assertSame('CHAR(36)', $this->platform->getGuidTypeDeclarationSQL([]));
}
@@ -600,7 +623,7 @@ public function testReturnsGuidTypeDeclarationSQL()
/**
* {@inheritdoc}
*/
- public function getAlterTableRenameColumnSQL()
+ public function getAlterTableRenameColumnSQL() : array
{
return [
'CREATE TEMPORARY TABLE __temp__foo AS SELECT bar FROM foo',
@@ -615,7 +638,7 @@ public function getAlterTableRenameColumnSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesTableIdentifiersInAlterTableSQL()
+ protected function getQuotesTableIdentifiersInAlterTableSQL() : array
{
return [
'DROP INDEX IDX_8C736521A81E660E',
@@ -637,7 +660,7 @@ protected function getQuotesTableIdentifiersInAlterTableSQL()
/**
* {@inheritdoc}
*/
- protected function getCommentOnColumnSQL()
+ protected function getCommentOnColumnSQL() : array
{
return [
'COMMENT ON COLUMN foo.bar IS \'comment\'',
@@ -646,22 +669,22 @@ protected function getCommentOnColumnSQL()
];
}
- protected function getInlineColumnCommentDelimiter()
+ protected static function getInlineColumnCommentDelimiter() : string
{
return "\n";
}
- protected function getInlineColumnRegularCommentSQL()
+ protected static function getInlineColumnRegularCommentSQL() : string
{
return "--Regular comment\n";
}
- protected function getInlineColumnCommentRequiringEscapingSQL()
+ protected static function getInlineColumnCommentRequiringEscapingSQL() : string
{
return "--Using inline comment delimiter \n-- works\n";
}
- protected function getInlineColumnEmptyCommentSQL()
+ protected static function getInlineColumnEmptyCommentSQL() : string
{
return "--\n";
}
@@ -669,7 +692,7 @@ protected function getInlineColumnEmptyCommentSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
+ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL() : string
{
return 'CONSTRAINT "select" UNIQUE (foo)';
}
@@ -677,7 +700,7 @@ protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInIndexDeclarationSQL()
+ protected function getQuotesReservedKeywordInIndexDeclarationSQL() : string
{
return 'INDEX "select" (foo)';
}
@@ -685,7 +708,7 @@ protected function getQuotesReservedKeywordInIndexDeclarationSQL()
/**
* {@inheritdoc}
*/
- protected function getQuotesReservedKeywordInTruncateTableSQL()
+ protected function getQuotesReservedKeywordInTruncateTableSQL() : string
{
return 'DELETE FROM "select"';
}
@@ -693,7 +716,7 @@ protected function getQuotesReservedKeywordInTruncateTableSQL()
/**
* {@inheritdoc}
*/
- protected function getAlterStringToFixedStringSQL()
+ protected function getAlterStringToFixedStringSQL() : array
{
return [
'CREATE TEMPORARY TABLE __temp__mytable AS SELECT name FROM mytable',
@@ -707,7 +730,7 @@ protected function getAlterStringToFixedStringSQL()
/**
* {@inheritdoc}
*/
- protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
+ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : array
{
return [
'DROP INDEX idx_foo',
@@ -725,41 +748,53 @@ protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL()
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableConstraintsSQL()
+ public function testQuotesTableNameInListTableConstraintsSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableConstraintsSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableConstraintsSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableColumnsSQL()
+ public function testQuotesTableNameInListTableColumnsSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableColumnsSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableColumnsSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableIndexesSQL()
+ public function testQuotesTableNameInListTableIndexesSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableIndexesSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableIndexesSQL("Foo'Bar\\")
+ );
}
/**
* @group DBAL-2436
*/
- public function testQuotesTableNameInListTableForeignKeysSQL()
+ public function testQuotesTableNameInListTableForeignKeysSQL() : void
{
- self::assertContains("'Foo''Bar\\'", $this->platform->getListTableForeignKeysSQL("Foo'Bar\\"), '', true);
+ self::assertStringContainsStringIgnoringCase(
+ "'Foo''Bar\\'",
+ $this->platform->getListTableForeignKeysSQL("Foo'Bar\\")
+ );
}
- public function testDateAddStaticNumberOfDays()
+ public function testDateAddStaticNumberOfDays() : void
{
self::assertSame("DATE(rentalBeginsOn,'+12 DAY')", $this->platform->getDateAddDaysExpression('rentalBeginsOn', 12));
}
- public function testDateAddNumberOfDaysFromColumn()
+ public function testDateAddNumberOfDaysFromColumn() : void
{
self::assertSame("DATE(rentalBeginsOn,'+' || duration || ' DAY')", $this->platform->getDateAddDaysExpression('rentalBeginsOn', 'duration'));
}
diff --git a/tests/Doctrine/Tests/DBAL/Portability/StatementTest.php b/tests/Doctrine/Tests/DBAL/Portability/StatementTest.php
index b4d5168d497..c8e40214eb0 100644
--- a/tests/Doctrine/Tests/DBAL/Portability/StatementTest.php
+++ b/tests/Doctrine/Tests/DBAL/Portability/StatementTest.php
@@ -8,27 +8,27 @@
use Doctrine\DBAL\Portability\Connection;
use Doctrine\DBAL\Portability\Statement;
use Doctrine\Tests\DbalTestCase;
-use Doctrine\Tests\Mocks\DriverStatementMock;
-use PHPUnit_Framework_MockObject_MockObject;
+use PHPUnit\Framework\MockObject\MockObject;
+use ReflectionProperty;
use function iterator_to_array;
class StatementTest extends DbalTestCase
{
- /** @var Connection|PHPUnit_Framework_MockObject_MockObject */
+ /** @var Connection|MockObject */
protected $conn;
/** @var Statement */
protected $stmt;
- /** @var DriverStatement|PHPUnit_Framework_MockObject_MockObject */
+ /** @var DriverStatement|MockObject */
protected $wrappedStmt;
/**
* {@inheritdoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
- $this->wrappedStmt = $this->createWrappedStatement();
+ $this->wrappedStmt = $this->createMock(DriverStatement::class);
$this->conn = $this->createConnection();
$this->stmt = $this->createStatement($this->wrappedStmt, $this->conn);
}
@@ -36,7 +36,7 @@ protected function setUp()
/**
* @group DBAL-726
*/
- public function testBindParam()
+ public function testBindParam() : void
{
$column = 'mycolumn';
$variable = 'myvalue';
@@ -51,7 +51,7 @@ public function testBindParam()
self::assertTrue($this->stmt->bindParam($column, $variable, $type, $length));
}
- public function testBindValue()
+ public function testBindValue() : void
{
$param = 'myparam';
$value = 'myvalue';
@@ -65,7 +65,7 @@ public function testBindValue()
self::assertTrue($this->stmt->bindValue($param, $value, $type));
}
- public function testCloseCursor()
+ public function testCloseCursor() : void
{
$this->wrappedStmt->expects($this->once())
->method('closeCursor')
@@ -74,7 +74,7 @@ public function testCloseCursor()
self::assertTrue($this->stmt->closeCursor());
}
- public function testColumnCount()
+ public function testColumnCount() : void
{
$columnCount = 666;
@@ -85,7 +85,7 @@ public function testColumnCount()
self::assertSame($columnCount, $this->stmt->columnCount());
}
- public function testErrorCode()
+ public function testErrorCode() : void
{
$errorCode = '666';
@@ -96,7 +96,7 @@ public function testErrorCode()
self::assertSame($errorCode, $this->stmt->errorCode());
}
- public function testErrorInfo()
+ public function testErrorInfo() : void
{
$errorInfo = ['666', 'Evil error.'];
@@ -107,7 +107,7 @@ public function testErrorInfo()
self::assertSame($errorInfo, $this->stmt->errorInfo());
}
- public function testExecute()
+ public function testExecute() : void
{
$params = [
'foo',
@@ -122,7 +122,7 @@ public function testExecute()
self::assertTrue($this->stmt->execute($params));
}
- public function testSetFetchMode()
+ public function testSetFetchMode() : void
{
$fetchMode = FetchMode::CUSTOM_OBJECT;
$arg1 = 'MyClass';
@@ -133,12 +133,15 @@ public function testSetFetchMode()
->with($fetchMode, $arg1, $arg2)
->will($this->returnValue(true));
- self::assertAttributeSame(FetchMode::MIXED, 'defaultFetchMode', $this->stmt);
+ $re = new ReflectionProperty($this->stmt, 'defaultFetchMode');
+ $re->setAccessible(true);
+
+ self::assertSame(FetchMode::MIXED, $re->getValue($this->stmt));
self::assertTrue($this->stmt->setFetchMode($fetchMode, $arg1, $arg2));
- self::assertAttributeSame($fetchMode, 'defaultFetchMode', $this->stmt);
+ self::assertSame($fetchMode, $re->getValue($this->stmt));
}
- public function testGetIterator()
+ public function testGetIterator() : void
{
$this->wrappedStmt->expects($this->exactly(3))
->method('fetch')
@@ -147,7 +150,7 @@ public function testGetIterator()
self::assertSame(['foo', 'bar'], iterator_to_array($this->stmt->getIterator()));
}
- public function testRowCount()
+ public function testRowCount() : void
{
$rowCount = 666;
@@ -159,7 +162,7 @@ public function testRowCount()
}
/**
- * @return Connection|PHPUnit_Framework_MockObject_MockObject
+ * @return Connection|MockObject
*/
protected function createConnection()
{
@@ -168,19 +171,8 @@ protected function createConnection()
->getMock();
}
- /**
- * @return Statement
- */
- protected function createStatement(DriverStatement $wrappedStatement, Connection $connection)
+ protected function createStatement(DriverStatement $wrappedStatement, Connection $connection) : Statement
{
return new Statement($wrappedStatement, $connection);
}
-
- /**
- * @return DriverStatement|PHPUnit_Framework_MockObject_MockObject
- */
- protected function createWrappedStatement()
- {
- return $this->createMock(DriverStatementMock::class);
- }
}
diff --git a/tests/Doctrine/Tests/DBAL/Query/Expression/CompositeExpressionTest.php b/tests/Doctrine/Tests/DBAL/Query/Expression/CompositeExpressionTest.php
index 512dfb08224..0a8492f795f 100644
--- a/tests/Doctrine/Tests/DBAL/Query/Expression/CompositeExpressionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Query/Expression/CompositeExpressionTest.php
@@ -10,7 +10,7 @@
*/
class CompositeExpressionTest extends DbalTestCase
{
- public function testCount()
+ public function testCount() : void
{
$expr = new CompositeExpression(CompositeExpression::TYPE_OR, ['u.group_id = 1']);
@@ -21,7 +21,7 @@ public function testCount()
self::assertCount(2, $expr);
}
- public function testAdd()
+ public function testAdd() : void
{
$expr = new CompositeExpression(CompositeExpression::TYPE_OR, ['u.group_id = 1']);
@@ -45,16 +45,21 @@ public function testAdd()
}
/**
+ * @param string[]|CompositeExpression[] $parts
+ *
* @dataProvider provideDataForConvertToString
*/
- public function testCompositeUsageAndGeneration($type, $parts, $expects)
+ public function testCompositeUsageAndGeneration(string $type, array $parts, string $expects) : void
{
$expr = new CompositeExpression($type, $parts);
self::assertEquals($expects, (string) $expr);
}
- public function provideDataForConvertToString()
+ /**
+ * @return mixed[][]
+ */
+ public static function provideDataForConvertToString() : iterable
{
return [
[
diff --git a/tests/Doctrine/Tests/DBAL/Query/Expression/ExpressionBuilderTest.php b/tests/Doctrine/Tests/DBAL/Query/Expression/ExpressionBuilderTest.php
index efa173829c3..817007d67d6 100644
--- a/tests/Doctrine/Tests/DBAL/Query/Expression/ExpressionBuilderTest.php
+++ b/tests/Doctrine/Tests/DBAL/Query/Expression/ExpressionBuilderTest.php
@@ -15,7 +15,7 @@ class ExpressionBuilderTest extends DbalTestCase
/** @var ExpressionBuilder */
protected $expr;
- protected function setUp()
+ protected function setUp() : void
{
$conn = $this->createMock(Connection::class);
@@ -27,9 +27,11 @@ protected function setUp()
}
/**
+ * @param string[]|CompositeExpression[] $parts
+ *
* @dataProvider provideDataForAndX
*/
- public function testAndX($parts, $expected)
+ public function testAndX(array $parts, string $expected) : void
{
$composite = $this->expr->andX();
@@ -40,7 +42,10 @@ public function testAndX($parts, $expected)
self::assertEquals($expected, (string) $composite);
}
- public function provideDataForAndX()
+ /**
+ * @return mixed[][]
+ */
+ public static function provideDataForAndX() : iterable
{
return [
[
@@ -83,9 +88,11 @@ public function provideDataForAndX()
}
/**
+ * @param string[]|CompositeExpression[] $parts
+ *
* @dataProvider provideDataForOrX
*/
- public function testOrX($parts, $expected)
+ public function testOrX(array $parts, string $expected) : void
{
$composite = $this->expr->orX();
@@ -96,7 +103,10 @@ public function testOrX($parts, $expected)
self::assertEquals($expected, (string) $composite);
}
- public function provideDataForOrX()
+ /**
+ * @return mixed[][]
+ */
+ public static function provideDataForOrX() : iterable
{
return [
[
@@ -141,14 +151,17 @@ public function provideDataForOrX()
/**
* @dataProvider provideDataForComparison
*/
- public function testComparison($leftExpr, $operator, $rightExpr, $expected)
+ public function testComparison(string $leftExpr, string $operator, string $rightExpr, string $expected) : void
{
$part = $this->expr->comparison($leftExpr, $operator, $rightExpr);
self::assertEquals($expected, (string) $part);
}
- public function provideDataForComparison()
+ /**
+ * @return mixed[][]
+ */
+ public static function provideDataForComparison() : iterable
{
return [
['u.user_id', ExpressionBuilder::EQ, '1', 'u.user_id = 1'],
@@ -160,72 +173,72 @@ public function provideDataForComparison()
];
}
- public function testEq()
+ public function testEq() : void
{
self::assertEquals('u.user_id = 1', $this->expr->eq('u.user_id', '1'));
}
- public function testNeq()
+ public function testNeq() : void
{
self::assertEquals('u.user_id <> 1', $this->expr->neq('u.user_id', '1'));
}
- public function testLt()
+ public function testLt() : void
{
self::assertEquals('u.salary < 10000', $this->expr->lt('u.salary', '10000'));
}
- public function testLte()
+ public function testLte() : void
{
self::assertEquals('u.salary <= 10000', $this->expr->lte('u.salary', '10000'));
}
- public function testGt()
+ public function testGt() : void
{
self::assertEquals('u.salary > 10000', $this->expr->gt('u.salary', '10000'));
}
- public function testGte()
+ public function testGte() : void
{
self::assertEquals('u.salary >= 10000', $this->expr->gte('u.salary', '10000'));
}
- public function testIsNull()
+ public function testIsNull() : void
{
self::assertEquals('u.deleted IS NULL', $this->expr->isNull('u.deleted'));
}
- public function testIsNotNull()
+ public function testIsNotNull() : void
{
self::assertEquals('u.updated IS NOT NULL', $this->expr->isNotNull('u.updated'));
}
- public function testIn()
+ public function testIn() : void
{
self::assertEquals('u.groups IN (1, 3, 4, 7)', $this->expr->in('u.groups', [1, 3, 4, 7]));
}
- public function testInWithPlaceholder()
+ public function testInWithPlaceholder() : void
{
self::assertEquals('u.groups IN (?)', $this->expr->in('u.groups', '?'));
}
- public function testNotIn()
+ public function testNotIn() : void
{
self::assertEquals('u.groups NOT IN (1, 3, 4, 7)', $this->expr->notIn('u.groups', [1, 3, 4, 7]));
}
- public function testNotInWithPlaceholder()
+ public function testNotInWithPlaceholder() : void
{
self::assertEquals('u.groups NOT IN (:values)', $this->expr->notIn('u.groups', ':values'));
}
- public function testLikeWithoutEscape()
+ public function testLikeWithoutEscape() : void
{
self::assertEquals("a.song LIKE 'a virgin'", $this->expr->like('a.song', "'a virgin'"));
}
- public function testLikeWithEscape()
+ public function testLikeWithEscape() : void
{
self::assertEquals(
"a.song LIKE 'a virgin' ESCAPE '💩'",
@@ -233,7 +246,7 @@ public function testLikeWithEscape()
);
}
- public function testNotLikeWithoutEscape()
+ public function testNotLikeWithoutEscape() : void
{
self::assertEquals(
"s.last_words NOT LIKE 'this'",
@@ -241,7 +254,7 @@ public function testNotLikeWithoutEscape()
);
}
- public function testNotLikeWithEscape()
+ public function testNotLikeWithEscape() : void
{
self::assertEquals(
"p.description NOT LIKE '20💩%' ESCAPE '💩'",
diff --git a/tests/Doctrine/Tests/DBAL/Query/QueryBuilderTest.php b/tests/Doctrine/Tests/DBAL/Query/QueryBuilderTest.php
index fdd28d87847..a210ef2fe73 100644
--- a/tests/Doctrine/Tests/DBAL/Query/QueryBuilderTest.php
+++ b/tests/Doctrine/Tests/DBAL/Query/QueryBuilderTest.php
@@ -17,7 +17,7 @@ class QueryBuilderTest extends DbalTestCase
/** @var Connection */
protected $conn;
- protected function setUp()
+ protected function setUp() : void
{
$this->conn = $this->createMock(Connection::class);
@@ -31,7 +31,7 @@ protected function setUp()
/**
* @group DBAL-2291
*/
- public function testSimpleSelectWithoutFrom()
+ public function testSimpleSelectWithoutFrom() : void
{
$qb = new QueryBuilder($this->conn);
@@ -40,7 +40,7 @@ public function testSimpleSelectWithoutFrom()
self::assertEquals('SELECT some_function()', (string) $qb);
}
- public function testSimpleSelect()
+ public function testSimpleSelect() : void
{
$qb = new QueryBuilder($this->conn);
@@ -50,7 +50,18 @@ public function testSimpleSelect()
self::assertEquals('SELECT u.id FROM users u', (string) $qb);
}
- public function testSelectWithSimpleWhere()
+ public function testSimpleSelectWithDistinct() : void
+ {
+ $qb = new QueryBuilder($this->conn);
+
+ $qb->select('u.id')
+ ->distinct()
+ ->from('users', 'u');
+
+ self::assertEquals('SELECT DISTINCT u.id FROM users u', (string) $qb);
+ }
+
+ public function testSelectWithSimpleWhere() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -62,7 +73,7 @@ public function testSelectWithSimpleWhere()
self::assertEquals('SELECT u.id FROM users u WHERE u.nickname = ?', (string) $qb);
}
- public function testSelectWithLeftJoin()
+ public function testSelectWithLeftJoin() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -74,7 +85,7 @@ public function testSelectWithLeftJoin()
self::assertEquals('SELECT u.*, p.* FROM users u LEFT JOIN phones p ON p.user_id = u.id', (string) $qb);
}
- public function testSelectWithJoin()
+ public function testSelectWithJoin() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -86,7 +97,7 @@ public function testSelectWithJoin()
self::assertEquals('SELECT u.*, p.* FROM users u INNER JOIN phones p ON p.user_id = u.id', (string) $qb);
}
- public function testSelectWithInnerJoin()
+ public function testSelectWithInnerJoin() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -98,7 +109,7 @@ public function testSelectWithInnerJoin()
self::assertEquals('SELECT u.*, p.* FROM users u INNER JOIN phones p ON p.user_id = u.id', (string) $qb);
}
- public function testSelectWithRightJoin()
+ public function testSelectWithRightJoin() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -110,7 +121,7 @@ public function testSelectWithRightJoin()
self::assertEquals('SELECT u.*, p.* FROM users u RIGHT JOIN phones p ON p.user_id = u.id', (string) $qb);
}
- public function testSelectWithAndWhereConditions()
+ public function testSelectWithAndWhereConditions() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -123,7 +134,7 @@ public function testSelectWithAndWhereConditions()
self::assertEquals('SELECT u.*, p.* FROM users u WHERE (u.username = ?) AND (u.name = ?)', (string) $qb);
}
- public function testSelectWithOrWhereConditions()
+ public function testSelectWithOrWhereConditions() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -136,7 +147,7 @@ public function testSelectWithOrWhereConditions()
self::assertEquals('SELECT u.*, p.* FROM users u WHERE (u.username = ?) OR (u.name = ?)', (string) $qb);
}
- public function testSelectWithOrOrWhereConditions()
+ public function testSelectWithOrOrWhereConditions() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -149,7 +160,7 @@ public function testSelectWithOrOrWhereConditions()
self::assertEquals('SELECT u.*, p.* FROM users u WHERE (u.username = ?) OR (u.name = ?)', (string) $qb);
}
- public function testSelectWithAndOrWhereConditions()
+ public function testSelectWithAndOrWhereConditions() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -164,7 +175,7 @@ public function testSelectWithAndOrWhereConditions()
self::assertEquals('SELECT u.*, p.* FROM users u WHERE (((u.username = ?) AND (u.username = ?)) OR (u.name = ?)) AND (u.name = ?)', (string) $qb);
}
- public function testSelectGroupBy()
+ public function testSelectGroupBy() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -176,7 +187,7 @@ public function testSelectGroupBy()
self::assertEquals('SELECT u.*, p.* FROM users u GROUP BY u.id', (string) $qb);
}
- public function testSelectEmptyGroupBy()
+ public function testSelectEmptyGroupBy() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -188,7 +199,7 @@ public function testSelectEmptyGroupBy()
self::assertEquals('SELECT u.*, p.* FROM users u', (string) $qb);
}
- public function testSelectEmptyAddGroupBy()
+ public function testSelectEmptyAddGroupBy() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -200,7 +211,7 @@ public function testSelectEmptyAddGroupBy()
self::assertEquals('SELECT u.*, p.* FROM users u', (string) $qb);
}
- public function testSelectAddGroupBy()
+ public function testSelectAddGroupBy() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -213,7 +224,7 @@ public function testSelectAddGroupBy()
self::assertEquals('SELECT u.*, p.* FROM users u GROUP BY u.id, u.foo', (string) $qb);
}
- public function testSelectAddGroupBys()
+ public function testSelectAddGroupBys() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -226,7 +237,7 @@ public function testSelectAddGroupBys()
self::assertEquals('SELECT u.*, p.* FROM users u GROUP BY u.id, u.foo, u.bar', (string) $qb);
}
- public function testSelectHaving()
+ public function testSelectHaving() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -239,7 +250,7 @@ public function testSelectHaving()
self::assertEquals('SELECT u.*, p.* FROM users u GROUP BY u.id HAVING u.name = ?', (string) $qb);
}
- public function testSelectAndHaving()
+ public function testSelectAndHaving() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -252,7 +263,7 @@ public function testSelectAndHaving()
self::assertEquals('SELECT u.*, p.* FROM users u GROUP BY u.id HAVING u.name = ?', (string) $qb);
}
- public function testSelectHavingAndHaving()
+ public function testSelectHavingAndHaving() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -266,7 +277,7 @@ public function testSelectHavingAndHaving()
self::assertEquals('SELECT u.*, p.* FROM users u GROUP BY u.id HAVING (u.name = ?) AND (u.username = ?)', (string) $qb);
}
- public function testSelectHavingOrHaving()
+ public function testSelectHavingOrHaving() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -280,7 +291,7 @@ public function testSelectHavingOrHaving()
self::assertEquals('SELECT u.*, p.* FROM users u GROUP BY u.id HAVING (u.name = ?) OR (u.username = ?)', (string) $qb);
}
- public function testSelectOrHavingOrHaving()
+ public function testSelectOrHavingOrHaving() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -294,7 +305,7 @@ public function testSelectOrHavingOrHaving()
self::assertEquals('SELECT u.*, p.* FROM users u GROUP BY u.id HAVING (u.name = ?) OR (u.username = ?)', (string) $qb);
}
- public function testSelectHavingAndOrHaving()
+ public function testSelectHavingAndOrHaving() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -309,7 +320,7 @@ public function testSelectHavingAndOrHaving()
self::assertEquals('SELECT u.*, p.* FROM users u GROUP BY u.id HAVING ((u.name = ?) OR (u.username = ?)) AND (u.username = ?)', (string) $qb);
}
- public function testSelectOrderBy()
+ public function testSelectOrderBy() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -321,7 +332,7 @@ public function testSelectOrderBy()
self::assertEquals('SELECT u.*, p.* FROM users u ORDER BY u.name ASC', (string) $qb);
}
- public function testSelectAddOrderBy()
+ public function testSelectAddOrderBy() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -334,7 +345,7 @@ public function testSelectAddOrderBy()
self::assertEquals('SELECT u.*, p.* FROM users u ORDER BY u.name ASC, u.username DESC', (string) $qb);
}
- public function testSelectAddAddOrderBy()
+ public function testSelectAddAddOrderBy() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -347,7 +358,7 @@ public function testSelectAddAddOrderBy()
self::assertEquals('SELECT u.*, p.* FROM users u ORDER BY u.name ASC, u.username DESC', (string) $qb);
}
- public function testEmptySelect()
+ public function testEmptySelect() : void
{
$qb = new QueryBuilder($this->conn);
$qb2 = $qb->select();
@@ -356,7 +367,7 @@ public function testEmptySelect()
self::assertEquals(QueryBuilder::SELECT, $qb->getType());
}
- public function testSelectAddSelect()
+ public function testSelectAddSelect() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -368,7 +379,7 @@ public function testSelectAddSelect()
self::assertEquals('SELECT u.*, p.* FROM users u', (string) $qb);
}
- public function testEmptyAddSelect()
+ public function testEmptyAddSelect() : void
{
$qb = new QueryBuilder($this->conn);
$qb2 = $qb->addSelect();
@@ -377,7 +388,7 @@ public function testEmptyAddSelect()
self::assertEquals(QueryBuilder::SELECT, $qb->getType());
}
- public function testSelectMultipleFrom()
+ public function testSelectMultipleFrom() : void
{
$qb = new QueryBuilder($this->conn);
$expr = $qb->expr();
@@ -390,7 +401,7 @@ public function testSelectMultipleFrom()
self::assertEquals('SELECT u.*, p.* FROM users u, phonenumbers p', (string) $qb);
}
- public function testUpdate()
+ public function testUpdate() : void
{
$qb = new QueryBuilder($this->conn);
$qb->update('users', 'u')
@@ -401,7 +412,7 @@ public function testUpdate()
self::assertEquals('UPDATE users u SET u.foo = ?, u.bar = ?', (string) $qb);
}
- public function testUpdateWithoutAlias()
+ public function testUpdateWithoutAlias() : void
{
$qb = new QueryBuilder($this->conn);
$qb->update('users')
@@ -411,7 +422,7 @@ public function testUpdateWithoutAlias()
self::assertEquals('UPDATE users SET foo = ?, bar = ?', (string) $qb);
}
- public function testUpdateWhere()
+ public function testUpdateWhere() : void
{
$qb = new QueryBuilder($this->conn);
$qb->update('users', 'u')
@@ -421,7 +432,7 @@ public function testUpdateWhere()
self::assertEquals('UPDATE users u SET u.foo = ? WHERE u.foo = ?', (string) $qb);
}
- public function testEmptyUpdate()
+ public function testEmptyUpdate() : void
{
$qb = new QueryBuilder($this->conn);
$qb2 = $qb->update();
@@ -430,7 +441,7 @@ public function testEmptyUpdate()
self::assertSame($qb2, $qb);
}
- public function testDelete()
+ public function testDelete() : void
{
$qb = new QueryBuilder($this->conn);
$qb->delete('users', 'u');
@@ -439,7 +450,7 @@ public function testDelete()
self::assertEquals('DELETE FROM users u', (string) $qb);
}
- public function testDeleteWithoutAlias()
+ public function testDeleteWithoutAlias() : void
{
$qb = new QueryBuilder($this->conn);
$qb->delete('users');
@@ -448,7 +459,7 @@ public function testDeleteWithoutAlias()
self::assertEquals('DELETE FROM users', (string) $qb);
}
- public function testDeleteWhere()
+ public function testDeleteWhere() : void
{
$qb = new QueryBuilder($this->conn);
$qb->delete('users', 'u')
@@ -457,7 +468,7 @@ public function testDeleteWhere()
self::assertEquals('DELETE FROM users u WHERE u.foo = ?', (string) $qb);
}
- public function testEmptyDelete()
+ public function testEmptyDelete() : void
{
$qb = new QueryBuilder($this->conn);
$qb2 = $qb->delete();
@@ -466,7 +477,7 @@ public function testEmptyDelete()
self::assertSame($qb2, $qb);
}
- public function testInsertValues()
+ public function testInsertValues() : void
{
$qb = new QueryBuilder($this->conn);
$qb->insert('users')
@@ -481,7 +492,7 @@ public function testInsertValues()
self::assertEquals('INSERT INTO users (foo, bar) VALUES(?, ?)', (string) $qb);
}
- public function testInsertReplaceValues()
+ public function testInsertReplaceValues() : void
{
$qb = new QueryBuilder($this->conn);
$qb->insert('users')
@@ -502,7 +513,7 @@ public function testInsertReplaceValues()
self::assertEquals('INSERT INTO users (bar, foo) VALUES(?, ?)', (string) $qb);
}
- public function testInsertSetValue()
+ public function testInsertSetValue() : void
{
$qb = new QueryBuilder($this->conn);
$qb->insert('users')
@@ -514,7 +525,7 @@ public function testInsertSetValue()
self::assertEquals('INSERT INTO users (foo, bar) VALUES(?, ?)', (string) $qb);
}
- public function testInsertValuesSetValue()
+ public function testInsertValuesSetValue() : void
{
$qb = new QueryBuilder($this->conn);
$qb->insert('users')
@@ -527,7 +538,7 @@ public function testInsertValuesSetValue()
self::assertEquals('INSERT INTO users (foo, bar) VALUES(?, ?)', (string) $qb);
}
- public function testEmptyInsert()
+ public function testEmptyInsert() : void
{
$qb = new QueryBuilder($this->conn);
$qb2 = $qb->insert();
@@ -536,13 +547,13 @@ public function testEmptyInsert()
self::assertSame($qb2, $qb);
}
- public function testGetConnection()
+ public function testGetConnection() : void
{
$qb = new QueryBuilder($this->conn);
self::assertSame($this->conn, $qb->getConnection());
}
- public function testGetState()
+ public function testGetState() : void
{
$qb = new QueryBuilder($this->conn);
@@ -558,7 +569,7 @@ public function testGetState()
self::assertEquals($sql1, $qb->getSQL());
}
- public function testSetMaxResults()
+ public function testSetMaxResults() : void
{
$qb = new QueryBuilder($this->conn);
$qb->setMaxResults(10);
@@ -567,7 +578,7 @@ public function testSetMaxResults()
self::assertEquals(10, $qb->getMaxResults());
}
- public function testSetFirstResult()
+ public function testSetFirstResult() : void
{
$qb = new QueryBuilder($this->conn);
$qb->setFirstResult(10);
@@ -576,7 +587,7 @@ public function testSetFirstResult()
self::assertEquals(10, $qb->getFirstResult());
}
- public function testResetQueryPart()
+ public function testResetQueryPart() : void
{
$qb = new QueryBuilder($this->conn);
@@ -587,7 +598,7 @@ public function testResetQueryPart()
self::assertEquals('SELECT u.* FROM users u', (string) $qb);
}
- public function testResetQueryParts()
+ public function testResetQueryParts() : void
{
$qb = new QueryBuilder($this->conn);
@@ -598,7 +609,7 @@ public function testResetQueryParts()
self::assertEquals('SELECT u.* FROM users u', (string) $qb);
}
- public function testCreateNamedParameter()
+ public function testCreateNamedParameter() : void
{
$qb = new QueryBuilder($this->conn);
@@ -611,7 +622,7 @@ public function testCreateNamedParameter()
self::assertEquals(ParameterType::INTEGER, $qb->getParameterType('dcValue1'));
}
- public function testCreateNamedParameterCustomPlaceholder()
+ public function testCreateNamedParameterCustomPlaceholder() : void
{
$qb = new QueryBuilder($this->conn);
@@ -624,7 +635,7 @@ public function testCreateNamedParameterCustomPlaceholder()
self::assertEquals(ParameterType::INTEGER, $qb->getParameterType('test'));
}
- public function testCreatePositionalParameter()
+ public function testCreatePositionalParameter() : void
{
$qb = new QueryBuilder($this->conn);
@@ -640,7 +651,7 @@ public function testCreatePositionalParameter()
/**
* @group DBAL-172
*/
- public function testReferenceJoinFromJoin()
+ public function testReferenceJoinFromJoin() : void
{
$qb = new QueryBuilder($this->conn);
@@ -659,7 +670,7 @@ public function testReferenceJoinFromJoin()
/**
* @group DBAL-172
*/
- public function testSelectFromMasterWithWhereOnJoinedTables()
+ public function testSelectFromMasterWithWhereOnJoinedTables() : void
{
$qb = new QueryBuilder($this->conn);
@@ -677,7 +688,7 @@ public function testSelectFromMasterWithWhereOnJoinedTables()
/**
* @group DBAL-442
*/
- public function testSelectWithMultipleFromAndJoins()
+ public function testSelectWithMultipleFromAndJoins() : void
{
$qb = new QueryBuilder($this->conn);
@@ -695,7 +706,7 @@ public function testSelectWithMultipleFromAndJoins()
/**
* @group DBAL-774
*/
- public function testSelectWithJoinsWithMultipleOnConditionsParseOrder()
+ public function testSelectWithJoinsWithMultipleOnConditionsParseOrder() : void
{
$qb = new QueryBuilder($this->conn);
@@ -720,7 +731,7 @@ public function testSelectWithJoinsWithMultipleOnConditionsParseOrder()
/**
* @group DBAL-774
*/
- public function testSelectWithMultipleFromsAndJoinsWithMultipleOnConditionsParseOrder()
+ public function testSelectWithMultipleFromsAndJoinsWithMultipleOnConditionsParseOrder() : void
{
$qb = new QueryBuilder($this->conn);
@@ -746,7 +757,7 @@ public function testSelectWithMultipleFromsAndJoinsWithMultipleOnConditionsParse
);
}
- public function testClone()
+ public function testClone() : void
{
$qb = new QueryBuilder($this->conn);
@@ -766,7 +777,7 @@ public function testClone()
self::assertNotSame($qb->getParameters(), $qb_clone->getParameters());
}
- public function testSimpleSelectWithoutTableAlias()
+ public function testSimpleSelectWithoutTableAlias() : void
{
$qb = new QueryBuilder($this->conn);
@@ -776,7 +787,7 @@ public function testSimpleSelectWithoutTableAlias()
self::assertEquals('SELECT id FROM users', (string) $qb);
}
- public function testSelectWithSimpleWhereWithoutTableAlias()
+ public function testSelectWithSimpleWhereWithoutTableAlias() : void
{
$qb = new QueryBuilder($this->conn);
@@ -787,7 +798,7 @@ public function testSelectWithSimpleWhereWithoutTableAlias()
self::assertEquals('SELECT id, name FROM users WHERE awesome=9001', (string) $qb);
}
- public function testComplexSelectWithoutTableAliases()
+ public function testComplexSelectWithoutTableAliases() : void
{
$qb = new QueryBuilder($this->conn);
@@ -802,7 +813,7 @@ public function testComplexSelectWithoutTableAliases()
self::assertEquals('SELECT DISTINCT users.id FROM users INNER JOIN permissions p ON p.user_id = users.id, articles INNER JOIN comments c ON c.article_id = articles.id WHERE (users.id = articles.user_id) AND (p.read = 1)', $qb->getSQL());
}
- public function testComplexSelectWithSomeTableAliases()
+ public function testComplexSelectWithSomeTableAliases() : void
{
$qb = new QueryBuilder($this->conn);
@@ -815,7 +826,7 @@ public function testComplexSelectWithSomeTableAliases()
self::assertEquals('SELECT u.id FROM users u INNER JOIN permissions p ON p.user_id = u.id, articles INNER JOIN comments c ON c.article_id = articles.id', $qb->getSQL());
}
- public function testSelectAllFromTableWithoutTableAlias()
+ public function testSelectAllFromTableWithoutTableAlias() : void
{
$qb = new QueryBuilder($this->conn);
@@ -825,7 +836,7 @@ public function testSelectAllFromTableWithoutTableAlias()
self::assertEquals('SELECT users.* FROM users', (string) $qb);
}
- public function testSelectAllWithoutTableAlias()
+ public function testSelectAllWithoutTableAlias() : void
{
$qb = new QueryBuilder($this->conn);
@@ -838,7 +849,7 @@ public function testSelectAllWithoutTableAlias()
/**
* @group DBAL-959
*/
- public function testGetParameterType()
+ public function testGetParameterType() : void
{
$qb = new QueryBuilder($this->conn);
@@ -859,7 +870,7 @@ public function testGetParameterType()
/**
* @group DBAL-959
*/
- public function testGetParameterTypes()
+ public function testGetParameterTypes() : void
{
$qb = new QueryBuilder($this->conn);
@@ -886,7 +897,7 @@ public function testGetParameterTypes()
/**
* @group DBAL-1137
*/
- public function testJoinWithNonUniqueAliasThrowsException()
+ public function testJoinWithNonUniqueAliasThrowsException() : void
{
$qb = new QueryBuilder($this->conn);
diff --git a/tests/Doctrine/Tests/DBAL/SQLParserUtilsTest.php b/tests/Doctrine/Tests/DBAL/SQLParserUtilsTest.php
index 414f909f870..ea8d4dc0752 100644
--- a/tests/Doctrine/Tests/DBAL/SQLParserUtilsTest.php
+++ b/tests/Doctrine/Tests/DBAL/SQLParserUtilsTest.php
@@ -14,7 +14,10 @@
*/
class SQLParserUtilsTest extends DbalTestCase
{
- public function dataGetPlaceholderPositions()
+ /**
+ * @return mixed[][]
+ */
+ public static function dataGetPlaceholderPositions() : iterable
{
return [
// none
@@ -91,15 +94,20 @@ public function dataGetPlaceholderPositions()
}
/**
+ * @param int[] $expectedParamPos
+ *
* @dataProvider dataGetPlaceholderPositions
*/
- public function testGetPlaceholderPositions($query, $isPositional, $expectedParamPos)
+ public function testGetPlaceholderPositions(string $query, bool $isPositional, array $expectedParamPos) : void
{
$actualParamPos = SQLParserUtils::getPlaceholderPositions($query, $isPositional);
self::assertEquals($expectedParamPos, $actualParamPos);
}
- public function dataExpandListParameters()
+ /**
+ * @return mixed[][]
+ */
+ public static function dataExpandListParameters() : iterable
{
return [
// Positional: Very simple with one needle
@@ -413,18 +421,32 @@ public function dataExpandListParameters()
}
/**
+ * @param mixed[] $params
+ * @param mixed[] $types
+ * @param mixed[] $expectedParams
+ * @param mixed[] $expectedTypes
+ *
* @dataProvider dataExpandListParameters
*/
- public function testExpandListParameters($q, $p, $t, $expectedQuery, $expectedParams, $expectedTypes)
- {
- [$query, $params, $types] = SQLParserUtils::expandListParameters($q, $p, $t);
+ public function testExpandListParameters(
+ string $query,
+ array $params,
+ array $types,
+ string $expectedQuery,
+ array $expectedParams,
+ array $expectedTypes
+ ) : void {
+ [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
self::assertEquals($expectedQuery, $query, 'Query was not rewritten correctly.');
self::assertEquals($expectedParams, $params, 'Params dont match');
self::assertEquals($expectedTypes, $types, 'Types dont match');
}
- public function dataQueryWithMissingParameters()
+ /**
+ * @return mixed[][]
+ */
+ public static function dataQueryWithMissingParameters() : iterable
{
return [
[
@@ -461,9 +483,12 @@ public function dataQueryWithMissingParameters()
}
/**
+ * @param mixed[] $params
+ * @param mixed[] $types
+ *
* @dataProvider dataQueryWithMissingParameters
*/
- public function testExceptionIsThrownForMissingParam($query, $params, $types = [])
+ public function testExceptionIsThrownForMissingParam(string $query, array $params, array $types = []) : void
{
$this->expectException(SQLParserUtilsException::class);
$this->expectExceptionMessage('Value for :param not found in params array. Params array key should be "param"');
diff --git a/tests/Doctrine/Tests/DBAL/Schema/ColumnDiffTest.php b/tests/Doctrine/Tests/DBAL/Schema/ColumnDiffTest.php
index 046118f91fa..0bdaa85ef6d 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/ColumnDiffTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/ColumnDiffTest.php
@@ -5,6 +5,7 @@
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\ColumnDiff;
use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use PHPUnit\Framework\TestCase;
class ColumnDiffTest extends TestCase
@@ -12,10 +13,10 @@ class ColumnDiffTest extends TestCase
/**
* @group DBAL-1255
*/
- public function testPreservesOldColumnNameQuotation()
+ public function testPreservesOldColumnNameQuotation() : void
{
- $fromColumn = new Column('"foo"', Type::getType(Type::INTEGER));
- $toColumn = new Column('bar', Type::getType(Type::INTEGER));
+ $fromColumn = new Column('"foo"', Type::getType(Types::INTEGER));
+ $toColumn = new Column('bar', Type::getType(Types::INTEGER));
$columnDiff = new ColumnDiff('"foo"', $toColumn, []);
self::assertTrue($columnDiff->getOldColumnName()->isQuoted());
diff --git a/tests/Doctrine/Tests/DBAL/Schema/ColumnTest.php b/tests/Doctrine/Tests/DBAL/Schema/ColumnTest.php
index 51fe749e28e..32e4568ed03 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/ColumnTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/ColumnTest.php
@@ -7,11 +7,12 @@
use Doctrine\DBAL\Platforms\SQLServerPlatform;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Types\Type;
+use Doctrine\DBAL\Types\Types;
use PHPUnit\Framework\TestCase;
class ColumnTest extends TestCase
{
- public function testGet()
+ public function testGet() : void
{
$column = $this->createColumn();
@@ -37,7 +38,7 @@ public function testGet()
self::assertFalse($column->hasCustomSchemaOption('foo'));
}
- public function testToArray()
+ public function testToArray() : void
{
$expected = [
'name' => 'foo',
@@ -65,6 +66,8 @@ public function testToArray()
*/
public function testSettingUnknownOptionIsStillSupported() : void
{
+ $this->expectNotToPerformAssertions();
+
new Column('foo', $this->createMock(Type::class), ['unknown_option' => 'bar']);
}
@@ -74,17 +77,14 @@ public function testSettingUnknownOptionIsStillSupported() : void
*/
public function testOptionsShouldNotBeIgnored() : void
{
- $col1 = new Column('bar', Type::getType(Type::INTEGER), ['unknown_option' => 'bar', 'notnull' => true]);
+ $col1 = new Column('bar', Type::getType(Types::INTEGER), ['unknown_option' => 'bar', 'notnull' => true]);
self::assertTrue($col1->getNotnull());
- $col2 = new Column('bar', Type::getType(Type::INTEGER), ['unknown_option' => 'bar', 'notnull' => false]);
+ $col2 = new Column('bar', Type::getType(Types::INTEGER), ['unknown_option' => 'bar', 'notnull' => false]);
self::assertFalse($col2->getNotnull());
}
- /**
- * @return Column
- */
- public function createColumn()
+ public function createColumn() : Column
{
$options = [
'length' => 200,
@@ -99,6 +99,7 @@ public function createColumn()
];
$string = Type::getType('string');
+
return new Column('foo', $string, $options);
}
@@ -106,7 +107,7 @@ public function createColumn()
* @group DBAL-64
* @group DBAL-830
*/
- public function testQuotedColumnName()
+ public function testQuotedColumnName() : void
{
$string = Type::getType('string');
$column = new Column('`bar`', $string, []);
@@ -130,7 +131,7 @@ public function testQuotedColumnName()
* @dataProvider getIsQuoted
* @group DBAL-830
*/
- public function testIsQuoted($columnName, $isQuoted)
+ public function testIsQuoted(string $columnName, bool $isQuoted) : void
{
$type = Type::getType('string');
$column = new Column($columnName, $type);
@@ -138,7 +139,10 @@ public function testIsQuoted($columnName, $isQuoted)
self::assertSame($isQuoted, $column->isQuoted());
}
- public function getIsQuoted()
+ /**
+ * @return mixed[][]
+ */
+ public static function getIsQuoted() : iterable
{
return [
['bar', false],
@@ -151,7 +155,7 @@ public function getIsQuoted()
/**
* @group DBAL-42
*/
- public function testColumnComment()
+ public function testColumnComment() : void
{
$column = new Column('bar', Type::getType('string'));
self::assertNull($column->getComment());
diff --git a/tests/Doctrine/Tests/DBAL/Schema/ComparatorTest.php b/tests/Doctrine/Tests/DBAL/Schema/ComparatorTest.php
index 6113653d20c..f73d1c6d1f4 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/ComparatorTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/ComparatorTest.php
@@ -20,7 +20,7 @@
class ComparatorTest extends TestCase
{
- public function testCompareSame1()
+ public function testCompareSame1() : void
{
$schema1 = new Schema([
'bugdb' => new Table(
@@ -44,7 +44,7 @@ public function testCompareSame1()
self::assertEquals($expected, Comparator::compareSchemas($schema1, $schema2));
}
- public function testCompareSame2()
+ public function testCompareSame2() : void
{
$schema1 = new Schema([
'bugdb' => new Table(
@@ -70,7 +70,7 @@ public function testCompareSame2()
self::assertEquals($expected, Comparator::compareSchemas($schema1, $schema2));
}
- public function testCompareMissingTable()
+ public function testCompareMissingTable() : void
{
$schemaConfig = new SchemaConfig();
$table = new Table('bugdb', ['integerfield1' => new Column('integerfield1', Type::getType('integer'))]);
@@ -84,7 +84,7 @@ public function testCompareMissingTable()
self::assertEquals($expected, Comparator::compareSchemas($schema1, $schema2));
}
- public function testCompareNewTable()
+ public function testCompareNewTable() : void
{
$schemaConfig = new SchemaConfig();
$table = new Table('bugdb', ['integerfield1' => new Column('integerfield1', Type::getType('integer'))]);
@@ -98,7 +98,7 @@ public function testCompareNewTable()
self::assertEquals($expected, Comparator::compareSchemas($schema1, $schema2));
}
- public function testCompareOnlyAutoincrementChanged()
+ public function testCompareOnlyAutoincrementChanged() : void
{
$column1 = new Column('foo', Type::getType('integer'), ['autoincrement' => true]);
$column2 = new Column('foo', Type::getType('integer'), ['autoincrement' => false]);
@@ -109,7 +109,7 @@ public function testCompareOnlyAutoincrementChanged()
self::assertEquals(['autoincrement'], $changedProperties);
}
- public function testCompareMissingField()
+ public function testCompareMissingField() : void
{
$missingColumn = new Column('integerfield1', Type::getType('integer'));
$schema1 = new Schema([
@@ -147,7 +147,7 @@ public function testCompareMissingField()
self::assertEquals($expected, Comparator::compareSchemas($schema1, $schema2));
}
- public function testCompareNewField()
+ public function testCompareNewField() : void
{
$schema1 = new Schema([
'bugdb' => new Table(
@@ -184,7 +184,7 @@ public function testCompareNewField()
self::assertEquals($expected, Comparator::compareSchemas($schema1, $schema2));
}
- public function testCompareChangedColumnsChangeType()
+ public function testCompareChangedColumnsChangeType() : void
{
$column1 = new Column('charfield1', Type::getType('string'));
$column2 = new Column('charfield1', Type::getType('integer'));
@@ -224,7 +224,7 @@ public function testCompareColumnsOverriddenType() : void
self::assertEquals([], $c->diffColumn($column1, $column2));
}
- public function testCompareChangedColumnsChangeCustomSchemaOption()
+ public function testCompareChangedColumnsChangeCustomSchemaOption() : void
{
$column1 = new Column('charfield1', Type::getType('string'));
$column2 = new Column('charfield1', Type::getType('string'));
@@ -240,7 +240,7 @@ public function testCompareChangedColumnsChangeCustomSchemaOption()
self::assertEquals([], $c->diffColumn($column1, $column1));
}
- public function testCompareChangeColumnsMultipleNewColumnsRename()
+ public function testCompareChangeColumnsMultipleNewColumnsRename() : void
{
$tableA = new Table('foo');
$tableA->addColumn('datefield1', 'datetime');
@@ -260,7 +260,7 @@ public function testCompareChangeColumnsMultipleNewColumnsRename()
self::assertCount(0, $tableDiff->changedColumns, 'Nothing should be changed as all fields old & new have diff names.');
}
- public function testCompareRemovedIndex()
+ public function testCompareRemovedIndex() : void
{
$schema1 = new Schema([
'bugdb' => new Table(
@@ -314,7 +314,7 @@ public function testCompareRemovedIndex()
self::assertEquals($expected, Comparator::compareSchemas($schema1, $schema2));
}
- public function testCompareNewIndex()
+ public function testCompareNewIndex() : void
{
$schema1 = new Schema([
'bugdb' => new Table(
@@ -366,7 +366,7 @@ public function testCompareNewIndex()
self::assertEquals($expected, Comparator::compareSchemas($schema1, $schema2));
}
- public function testCompareChangedIndex()
+ public function testCompareChangedIndex() : void
{
$schema1 = new Schema([
'bugdb' => new Table(
@@ -429,7 +429,7 @@ public function testCompareChangedIndex()
self::assertEquals($expected, Comparator::compareSchemas($schema1, $schema2));
}
- public function testCompareChangedIndexFieldPositions()
+ public function testCompareChangedIndexFieldPositions() : void
{
$schema1 = new Schema([
'bugdb' => new Table(
@@ -477,7 +477,7 @@ public function testCompareChangedIndexFieldPositions()
self::assertEquals($expected, Comparator::compareSchemas($schema1, $schema2));
}
- public function testCompareSequences()
+ public function testCompareSequences() : void
{
$seq1 = new Sequence('foo', 1, 1);
$seq2 = new Sequence('foo', 1, 2);
@@ -491,7 +491,7 @@ public function testCompareSequences()
self::assertFalse($c->diffSequence($seq1, $seq4));
}
- public function testRemovedSequence()
+ public function testRemovedSequence() : void
{
$schema1 = new Schema();
$seq = $schema1->createSequence('foo');
@@ -505,7 +505,7 @@ public function testRemovedSequence()
self::assertSame($seq, $diffSchema->removedSequences[0]);
}
- public function testAddedSequence()
+ public function testAddedSequence() : void
{
$schema1 = new Schema();
@@ -519,7 +519,7 @@ public function testAddedSequence()
self::assertSame($seq, $diffSchema->newSequences[0]);
}
- public function testTableAddForeignKey()
+ public function testTableAddForeignKey() : void
{
$tableForeign = new Table('bar');
$tableForeign->addColumn('id', 'integer');
@@ -538,7 +538,7 @@ public function testTableAddForeignKey()
self::assertCount(1, $tableDiff->addedForeignKeys);
}
- public function testTableRemoveForeignKey()
+ public function testTableRemoveForeignKey() : void
{
$tableForeign = new Table('bar');
$tableForeign->addColumn('id', 'integer');
@@ -557,7 +557,7 @@ public function testTableRemoveForeignKey()
self::assertCount(1, $tableDiff->removedForeignKeys);
}
- public function testTableUpdateForeignKey()
+ public function testTableUpdateForeignKey() : void
{
$tableForeign = new Table('bar');
$tableForeign->addColumn('id', 'integer');
@@ -577,7 +577,7 @@ public function testTableUpdateForeignKey()
self::assertCount(1, $tableDiff->changedForeignKeys);
}
- public function testMovedForeignKeyForeignTable()
+ public function testMovedForeignKeyForeignTable() : void
{
$tableForeign = new Table('bar');
$tableForeign->addColumn('id', 'integer');
@@ -600,7 +600,7 @@ public function testMovedForeignKeyForeignTable()
self::assertCount(1, $tableDiff->changedForeignKeys);
}
- public function testTablesCaseInsensitive()
+ public function testTablesCaseInsensitive() : void
{
$schemaA = new Schema();
$schemaA->createTable('foo');
@@ -617,10 +617,10 @@ public function testTablesCaseInsensitive()
$c = new Comparator();
$diff = $c->compare($schemaA, $schemaB);
- self::assertSchemaTableChangeCount($diff, 1, 0, 1);
+ $this->assertSchemaTableChangeCount($diff, 1, 0, 1);
}
- public function testSequencesCaseInsensitive()
+ public function testSequencesCaseInsensitive() : void
{
$schemaA = new Schema();
$schemaA->createSequence('foo');
@@ -637,10 +637,10 @@ public function testSequencesCaseInsensitive()
$c = new Comparator();
$diff = $c->compare($schemaA, $schemaB);
- self::assertSchemaSequenceChangeCount($diff, 1, 0, 1);
+ $this->assertSchemaSequenceChangeCount($diff, 1, 0, 1);
}
- public function testCompareColumnCompareCaseInsensitive()
+ public function testCompareColumnCompareCaseInsensitive() : void
{
$tableA = new Table('foo');
$tableA->addColumn('id', 'integer');
@@ -654,7 +654,7 @@ public function testCompareColumnCompareCaseInsensitive()
self::assertFalse($tableDiff);
}
- public function testCompareIndexBasedOnPropertiesNotName()
+ public function testCompareIndexBasedOnPropertiesNotName() : void
{
$tableA = new Table('foo');
$tableA->addColumn('id', 'integer');
@@ -675,7 +675,7 @@ public function testCompareIndexBasedOnPropertiesNotName()
);
}
- public function testCompareForeignKeyBasedOnPropertiesNotName()
+ public function testCompareForeignKeyBasedOnPropertiesNotName() : void
{
$tableA = new Table('foo');
$tableA->addColumn('id', 'integer');
@@ -691,7 +691,7 @@ public function testCompareForeignKeyBasedOnPropertiesNotName()
self::assertFalse($tableDiff);
}
- public function testCompareForeignKeyRestrictNoActionAreTheSame()
+ public function testCompareForeignKeyRestrictNoActionAreTheSame() : void
{
$fk1 = new ForeignKeyConstraint(['foo'], 'bar', ['baz'], 'fk1', ['onDelete' => 'NO ACTION']);
$fk2 = new ForeignKeyConstraint(['foo'], 'bar', ['baz'], 'fk1', ['onDelete' => 'RESTRICT']);
@@ -703,7 +703,7 @@ public function testCompareForeignKeyRestrictNoActionAreTheSame()
/**
* @group DBAL-492
*/
- public function testCompareForeignKeyNamesUnqualifiedAsNoSchemaInformationIsAvailable()
+ public function testCompareForeignKeyNamesUnqualifiedAsNoSchemaInformationIsAvailable() : void
{
$fk1 = new ForeignKeyConstraint(['foo'], 'foo.bar', ['baz'], 'fk1');
$fk2 = new ForeignKeyConstraint(['foo'], 'baz.bar', ['baz'], 'fk1');
@@ -712,7 +712,7 @@ public function testCompareForeignKeyNamesUnqualifiedAsNoSchemaInformationIsAvai
self::assertFalse($c->diffForeignKey($fk1, $fk2));
}
- public function testDetectRenameColumn()
+ public function testDetectRenameColumn() : void
{
$tableA = new Table('foo');
$tableA->addColumn('foo', 'integer');
@@ -736,7 +736,7 @@ public function testDetectRenameColumn()
*
* @group DBAL-24
*/
- public function testDetectRenameColumnAmbiguous()
+ public function testDetectRenameColumnAmbiguous() : void
{
$tableA = new Table('foo');
$tableA->addColumn('foo', 'integer');
@@ -759,7 +759,7 @@ public function testDetectRenameColumnAmbiguous()
/**
* @group DBAL-1063
*/
- public function testDetectRenameIndex()
+ public function testDetectRenameIndex() : void
{
$table1 = new Table('foo');
$table1->addColumn('foo', 'integer');
@@ -786,7 +786,7 @@ public function testDetectRenameIndex()
*
* @group DBAL-1063
*/
- public function testDetectRenameIndexAmbiguous()
+ public function testDetectRenameIndexAmbiguous() : void
{
$table1 = new Table('foo');
$table1->addColumn('foo', 'integer');
@@ -809,7 +809,7 @@ public function testDetectRenameIndexAmbiguous()
self::assertCount(0, $tableDiff->renamedIndexes);
}
- public function testDetectChangeIdentifierType()
+ public function testDetectChangeIdentifierType() : void
{
$this->markTestSkipped('DBAL-2 was reopened, this test cannot work anymore.');
@@ -826,11 +826,10 @@ public function testDetectChangeIdentifierType()
self::assertArrayHasKey('id', $tableDiff->changedColumns);
}
-
/**
* @group DBAL-105
*/
- public function testDiff()
+ public function testDiff() : void
{
$table = new Table('twitter_users');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -854,11 +853,10 @@ public function testDiff()
self::assertCount(0, $tableDiff->removedColumns);
}
-
/**
* @group DBAL-112
*/
- public function testChangedSequence()
+ public function testChangedSequence() : void
{
$schema = new Schema();
$sequence = $schema->createSequence('baz');
@@ -875,7 +873,7 @@ public function testChangedSequence()
/**
* @group DBAL-106
*/
- public function testDiffDecimalWithNullPrecision()
+ public function testDiffDecimalWithNullPrecision() : void
{
$column = new Column('foo', Type::getType('decimal'));
$column->setPrecision(null);
@@ -889,7 +887,7 @@ public function testDiffDecimalWithNullPrecision()
/**
* @group DBAL-204
*/
- public function testFqnSchemaComparison()
+ public function testFqnSchemaComparison() : void
{
$config = new SchemaConfig();
$config->setName('foo');
@@ -909,7 +907,7 @@ public function testFqnSchemaComparison()
/**
* @group DBAL-669
*/
- public function testNamespacesComparison()
+ public function testNamespacesComparison() : void
{
$config = new SchemaConfig();
$config->setName('schemaName');
@@ -936,7 +934,7 @@ public function testNamespacesComparison()
/**
* @group DBAL-204
*/
- public function testFqnSchemaComparisonDifferentSchemaNameButSameTableNoDiff()
+ public function testFqnSchemaComparisonDifferentSchemaNameButSameTableNoDiff() : void
{
$config = new SchemaConfig();
$config->setName('foo');
@@ -956,7 +954,7 @@ public function testFqnSchemaComparisonDifferentSchemaNameButSameTableNoDiff()
/**
* @group DBAL-204
*/
- public function testFqnSchemaComparisonNoSchemaSame()
+ public function testFqnSchemaComparisonNoSchemaSame() : void
{
$config = new SchemaConfig();
$config->setName('foo');
@@ -975,7 +973,7 @@ public function testFqnSchemaComparisonNoSchemaSame()
/**
* @group DDC-1657
*/
- public function testAutoIncrementSequences()
+ public function testAutoIncrementSequences() : void
{
$oldSchema = new Schema();
$table = $oldSchema->createTable('foo');
@@ -994,13 +992,12 @@ public function testAutoIncrementSequences()
self::assertCount(0, $diff->removedSequences);
}
-
/**
* Check that added autoincrement sequence is not populated in newSequences
*
* @group DBAL-562
*/
- public function testAutoIncrementNoSequences()
+ public function testAutoIncrementNoSequences() : void
{
$oldSchema = new Schema();
$table = $oldSchema->createTable('foo');
@@ -1018,13 +1015,14 @@ public function testAutoIncrementNoSequences()
self::assertCount(0, $diff->newSequences);
}
+
/**
* You can get multiple drops for a FK when a table referenced by a foreign
* key is deleted, as this FK is referenced twice, once on the orphanedForeignKeys
* array because of the dropped table, and once on changedTables array. We
* now check that the key is present once.
*/
- public function testAvoidMultipleDropForeignKey()
+ public function testAvoidMultipleDropForeignKey() : void
{
$oldSchema = new Schema();
@@ -1057,7 +1055,7 @@ public function testAvoidMultipleDropForeignKey()
self::assertCount(1, $schemaDiff->orphanedForeignKeys);
}
- public function testCompareChangedColumn()
+ public function testCompareChangedColumn() : void
{
$oldSchema = new Schema();
@@ -1079,7 +1077,7 @@ public function testCompareChangedColumn()
self::assertEquals($expected, Comparator::compareSchemas($oldSchema, $newSchema));
}
- public function testCompareChangedBinaryColumn()
+ public function testCompareChangedBinaryColumn() : void
{
$oldSchema = new Schema();
@@ -1104,7 +1102,7 @@ public function testCompareChangedBinaryColumn()
/**
* @group DBAL-617
*/
- public function testCompareQuotedAndUnquotedForeignKeyColumns()
+ public function testCompareQuotedAndUnquotedForeignKeyColumns() : void
{
$fk1 = new ForeignKeyConstraint(['foo'], 'bar', ['baz'], 'fk1', ['onDelete' => 'NO ACTION']);
$fk2 = new ForeignKeyConstraint(['`foo`'], 'bar', ['`baz`'], 'fk1', ['onDelete' => 'NO ACTION']);
@@ -1115,33 +1113,25 @@ public function testCompareQuotedAndUnquotedForeignKeyColumns()
self::assertFalse($diff);
}
- /**
- * @param SchemaDiff $diff
- * @param int $newTableCount
- * @param int $changeTableCount
- * @param int $removeTableCount
- */
- public function assertSchemaTableChangeCount($diff, $newTableCount = 0, $changeTableCount = 0, $removeTableCount = 0)
+ public function assertSchemaTableChangeCount(SchemaDiff $diff, int $newTableCount = 0, int $changeTableCount = 0, int $removeTableCount = 0) : void
{
self::assertCount($newTableCount, $diff->newTables);
self::assertCount($changeTableCount, $diff->changedTables);
self::assertCount($removeTableCount, $diff->removedTables);
}
- /**
- * @param SchemaDiff $diff
- * @param int $newSequenceCount
- * @param int $changeSequenceCount
- * @param int $changeSequenceCount
- */
- public function assertSchemaSequenceChangeCount($diff, $newSequenceCount = 0, $changeSequenceCount = 0, $removeSequenceCount = 0)
- {
+ public function assertSchemaSequenceChangeCount(
+ SchemaDiff $diff,
+ int $newSequenceCount = 0,
+ int $changeSequenceCount = 0,
+ int $removeSequenceCount = 0
+ ) : void {
self::assertCount($newSequenceCount, $diff->newSequences, 'Expected number of new sequences is wrong.');
self::assertCount($changeSequenceCount, $diff->changedSequences, 'Expected number of changed sequences is wrong.');
self::assertCount($removeSequenceCount, $diff->removedSequences, 'Expected number of removed sequences is wrong.');
}
- public function testDiffColumnPlatformOptions()
+ public function testDiffColumnPlatformOptions() : void
{
$column1 = new Column('foo', Type::getType('string'), ['platformOptions' => ['foo' => 'foo', 'bar' => 'bar']]);
$column2 = new Column('foo', Type::getType('string'), ['platformOptions' => ['foo' => 'foo', 'foobar' => 'foobar']]);
@@ -1158,7 +1148,7 @@ public function testDiffColumnPlatformOptions()
self::assertEquals([], $comparator->diffColumn($column4, $column1));
}
- public function testComplexDiffColumn()
+ public function testComplexDiffColumn() : void
{
$column1 = new Column('foo', Type::getType('string'), [
'platformOptions' => ['foo' => 'foo'],
@@ -1178,14 +1168,14 @@ public function testComplexDiffColumn()
/**
* @group DBAL-669
*/
- public function testComparesNamespaces()
+ public function testComparesNamespaces() : void
{
$comparator = new Comparator();
$fromSchema = $this->getMockBuilder(Schema::class)
- ->setMethods(['getNamespaces', 'hasNamespace'])
+ ->onlyMethods(['getNamespaces', 'hasNamespace'])
->getMock();
$toSchema = $this->getMockBuilder(Schema::class)
- ->setMethods(['getNamespaces', 'hasNamespace'])
+ ->onlyMethods(['getNamespaces', 'hasNamespace'])
->getMock();
$fromSchema->expects($this->once())
@@ -1224,7 +1214,7 @@ public function testComparesNamespaces()
self::assertEquals($expected, $comparator->compare($fromSchema, $toSchema));
}
- public function testCompareGuidColumns()
+ public function testCompareGuidColumns() : void
{
$comparator = new Comparator();
@@ -1243,7 +1233,7 @@ public function testCompareGuidColumns()
* @group DBAL-1009
* @dataProvider getCompareColumnComments
*/
- public function testCompareColumnComments($comment1, $comment2, $equals)
+ public function testCompareColumnComments(?string $comment1, ?string $comment2, bool $equals) : void
{
$column1 = new Column('foo', Type::getType('integer'), ['comment' => $comment1]);
$column2 = new Column('foo', Type::getType('integer'), ['comment' => $comment2]);
@@ -1261,7 +1251,10 @@ public function testCompareColumnComments($comment1, $comment2, $equals)
self::assertSame($expectedDiff, $actualDiff);
}
- public function getCompareColumnComments()
+ /**
+ * @return mixed[][]
+ */
+ public static function getCompareColumnComments() : iterable
{
return [
[null, null, true],
@@ -1286,7 +1279,7 @@ public function getCompareColumnComments()
];
}
- public function testForeignKeyRemovalWithRenamedLocalColumn()
+ public function testForeignKeyRemovalWithRenamedLocalColumn() : void
{
$fromSchema = new Schema([
'table1' => new Table(
diff --git a/tests/Doctrine/Tests/DBAL/Schema/DB2SchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Schema/DB2SchemaManagerTest.php
index bdde3d4fbcb..53f9a41cbda 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/DB2SchemaManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/DB2SchemaManagerTest.php
@@ -8,8 +8,8 @@
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Platforms\DB2Platform;
use Doctrine\DBAL\Schema\DB2SchemaManager;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
-use PHPUnit_Framework_MockObject_MockObject;
use function in_array;
/**
@@ -17,20 +17,20 @@
*/
final class DB2SchemaManagerTest extends TestCase
{
- /** @var Connection|PHPUnit_Framework_MockObject_MockObject */
+ /** @var Connection|MockObject */
private $conn;
/** @var DB2SchemaManager */
private $manager;
- protected function setUp()
+ protected function setUp() : void
{
$eventManager = new EventManager();
$driverMock = $this->createMock(Driver::class);
$platform = $this->createMock(DB2Platform::class);
$this->conn = $this
->getMockBuilder(Connection::class)
- ->setMethods(['fetchAll', 'quote'])
+ ->onlyMethods(['fetchAll', 'quote'])
->setConstructorArgs([['platform' => $platform], $driverMock, new Configuration(), $eventManager])
->getMock();
$this->manager = new DB2SchemaManager($this->conn);
@@ -39,11 +39,9 @@ protected function setUp()
/**
* @see https://github.com/doctrine/dbal/issues/2701
*
- * @return void
- *
* @group DBAL-2701
*/
- public function testListTableNamesFiltersAssetNamesCorrectly()
+ public function testListTableNamesFiltersAssetNamesCorrectly() : void
{
$this->conn->getConfiguration()->setFilterSchemaAssetsExpression('/^(?!T_)/');
$this->conn->expects($this->once())->method('fetchAll')->will($this->returnValue([
@@ -63,11 +61,9 @@ public function testListTableNamesFiltersAssetNamesCorrectly()
}
/**
- * @return void
- *
* @group DBAL-2701
*/
- public function testAssetFilteringSetsACallable()
+ public function testAssetFilteringSetsACallable() : void
{
$filterExpression = '/^(?!T_)/';
$this->conn->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
@@ -87,16 +83,13 @@ public function testAssetFilteringSetsACallable()
);
$callable = $this->conn->getConfiguration()->getSchemaAssetsFilter();
- $this->assertInternalType('callable', $callable);
+ self::assertIsCallable($callable);
// BC check: Test that regexp expression is still preserved & accessible.
$this->assertEquals($filterExpression, $this->conn->getConfiguration()->getFilterSchemaAssetsExpression());
}
- /**
- * @return void
- */
- public function testListTableNamesFiltersAssetNamesCorrectlyWithCallable()
+ public function testListTableNamesFiltersAssetNamesCorrectlyWithCallable() : void
{
$accepted = ['T_FOO', 'T_BAR'];
$this->conn->getConfiguration()->setSchemaAssetsFilter(static function ($assetName) use ($accepted) {
@@ -121,10 +114,7 @@ public function testListTableNamesFiltersAssetNamesCorrectlyWithCallable()
$this->assertNull($this->conn->getConfiguration()->getFilterSchemaAssetsExpression());
}
- /**
- * @return void
- */
- public function testSettingNullExpressionWillResetCallable()
+ public function testSettingNullExpressionWillResetCallable() : void
{
$accepted = ['T_FOO', 'T_BAR'];
$this->conn->getConfiguration()->setSchemaAssetsFilter(static function ($assetName) use ($accepted) {
@@ -161,10 +151,7 @@ public function testSettingNullExpressionWillResetCallable()
$this->assertNull($this->conn->getConfiguration()->getSchemaAssetsFilter());
}
- /**
- * @return void
- */
- public function testSettingNullAsCallableClearsExpression()
+ public function testSettingNullAsCallableClearsExpression() : void
{
$filterExpression = '/^(?!T_)/';
$this->conn->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
diff --git a/tests/Doctrine/Tests/DBAL/Schema/ForeignKeyConstraintTest.php b/tests/Doctrine/Tests/DBAL/Schema/ForeignKeyConstraintTest.php
index 2c317fc5dea..f0b115ddc4f 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/ForeignKeyConstraintTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/ForeignKeyConstraintTest.php
@@ -14,7 +14,7 @@ class ForeignKeyConstraintTest extends TestCase
* @group DBAL-1062
* @dataProvider getIntersectsIndexColumnsData
*/
- public function testIntersectsIndexColumns(array $indexColumns, $expectedResult)
+ public function testIntersectsIndexColumns(array $indexColumns, bool $expectedResult) : void
{
$foreignKey = new ForeignKeyConstraint(['foo', 'bar'], 'foreign_table', ['fk_foo', 'fk_bar']);
@@ -29,9 +29,9 @@ public function testIntersectsIndexColumns(array $indexColumns, $expectedResult)
}
/**
- * @return mixed[]
+ * @return mixed[][]
*/
- public function getIntersectsIndexColumnsData()
+ public static function getIntersectsIndexColumnsData() : iterable
{
return [
[['baz'], false],
diff --git a/tests/Doctrine/Tests/DBAL/Schema/IndexTest.php b/tests/Doctrine/Tests/DBAL/Schema/IndexTest.php
index ad9e2bbbdb7..d21e676b273 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/IndexTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/IndexTest.php
@@ -7,12 +7,15 @@
class IndexTest extends TestCase
{
- public function createIndex($unique = false, $primary = false, $options = [])
+ /**
+ * @param mixed[] $options
+ */
+ private function createIndex(bool $unique = false, bool $primary = false, array $options = []) : Index
{
return new Index('foo', ['bar', 'baz'], $unique, $primary, [], $options);
}
- public function testCreateIndex()
+ public function testCreateIndex() : void
{
$idx = $this->createIndex();
self::assertEquals('foo', $idx->getName());
@@ -23,14 +26,14 @@ public function testCreateIndex()
self::assertFalse($idx->isPrimary());
}
- public function testCreatePrimary()
+ public function testCreatePrimary() : void
{
$idx = $this->createIndex(false, true);
self::assertTrue($idx->isUnique());
self::assertTrue($idx->isPrimary());
}
- public function testCreateUnique()
+ public function testCreateUnique() : void
{
$idx = $this->createIndex(true, false);
self::assertTrue($idx->isUnique());
@@ -40,7 +43,7 @@ public function testCreateUnique()
/**
* @group DBAL-50
*/
- public function testFulfilledByUnique()
+ public function testFulfilledByUnique() : void
{
$idx1 = $this->createIndex(true, false);
$idx2 = $this->createIndex(true, false);
@@ -53,7 +56,7 @@ public function testFulfilledByUnique()
/**
* @group DBAL-50
*/
- public function testFulfilledByPrimary()
+ public function testFulfilledByPrimary() : void
{
$idx1 = $this->createIndex(true, true);
$idx2 = $this->createIndex(true, true);
@@ -66,7 +69,7 @@ public function testFulfilledByPrimary()
/**
* @group DBAL-50
*/
- public function testFulfilledByIndex()
+ public function testFulfilledByIndex() : void
{
$idx1 = $this->createIndex();
$idx2 = $this->createIndex();
@@ -78,7 +81,7 @@ public function testFulfilledByIndex()
self::assertTrue($idx1->isFullfilledBy($uniq));
}
- public function testFulfilledWithPartial()
+ public function testFulfilledWithPartial() : void
{
$without = new Index('without', ['col1', 'col2'], true, false, [], []);
$partial = new Index('partial', ['col1', 'col2'], true, false, [], ['where' => 'col1 IS NULL']);
@@ -93,7 +96,7 @@ public function testFulfilledWithPartial()
self::assertTrue($another->isFullfilledBy($partial));
}
- public function testOverrulesWithPartial()
+ public function testOverrulesWithPartial() : void
{
$without = new Index('without', ['col1', 'col2'], true, false, [], []);
$partial = new Index('partial', ['col1', 'col2'], true, false, [], ['where' => 'col1 IS NULL']);
@@ -141,7 +144,7 @@ public static function indexLengthProvider() : iterable
/**
* @group DBAL-220
*/
- public function testFlags()
+ public function testFlags() : void
{
$idx1 = $this->createIndex();
self::assertFalse($idx1->hasFlag('clustered'));
@@ -160,7 +163,7 @@ public function testFlags()
/**
* @group DBAL-285
*/
- public function testIndexQuotes()
+ public function testIndexQuotes() : void
{
$index = new Index('foo', ['`bar`', '`baz`']);
@@ -172,7 +175,7 @@ public function testIndexQuotes()
self::assertFalse($index->hasColumnAtPosition('baz', 0));
}
- public function testOptions()
+ public function testOptions() : void
{
$idx1 = $this->createIndex();
self::assertFalse($idx1->hasOption('where'));
diff --git a/tests/Doctrine/Tests/DBAL/Schema/MySqlInheritCharsetTest.php b/tests/Doctrine/Tests/DBAL/Schema/MySqlInheritCharsetTest.php
index b9c0f1d73ec..e65507b7826 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/MySqlInheritCharsetTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/MySqlInheritCharsetTest.php
@@ -45,7 +45,7 @@ public function testTableOptions() : void
$table = new Table('foobar', [new Column('aa', Type::getType('integer'))]);
self::assertSame(
$platform->getCreateTableSQL($table),
- ['CREATE TABLE foobar (aa INT NOT NULL) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB']
+ ['CREATE TABLE foobar (aa INT NOT NULL) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB']
);
// explicit utf8
@@ -53,7 +53,7 @@ public function testTableOptions() : void
$table->addOption('charset', 'utf8');
self::assertSame(
$platform->getCreateTableSQL($table),
- ['CREATE TABLE foobar (aa INT NOT NULL) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB']
+ ['CREATE TABLE foobar (aa INT NOT NULL) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB']
);
// explicit utf8mb4
@@ -61,7 +61,7 @@ public function testTableOptions() : void
$table->addOption('charset', 'utf8mb4');
self::assertSame(
$platform->getCreateTableSQL($table),
- ['CREATE TABLE foobar (aa INT NOT NULL) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB']
+ ['CREATE TABLE foobar (aa INT NOT NULL) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB']
);
}
diff --git a/tests/Doctrine/Tests/DBAL/Schema/MySqlSchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Schema/MySqlSchemaManagerTest.php
index 737a8223812..934b3e97bef 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/MySqlSchemaManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/MySqlSchemaManagerTest.php
@@ -21,19 +21,19 @@ class MySqlSchemaManagerTest extends TestCase
/** @var Connection */
private $conn;
- protected function setUp()
+ protected function setUp() : void
{
$eventManager = new EventManager();
$driverMock = $this->createMock(Driver::class);
$platform = $this->createMock(MySqlPlatform::class);
$this->conn = $this->getMockBuilder(Connection::class)
- ->setMethods(['fetchAll'])
+ ->onlyMethods(['fetchAll'])
->setConstructorArgs([['platform' => $platform], $driverMock, new Configuration(), $eventManager])
->getMock();
$this->manager = new MySqlSchemaManager($this->conn);
}
- public function testCompositeForeignKeys()
+ public function testCompositeForeignKeys() : void
{
$this->conn->expects($this->once())->method('fetchAll')->will($this->returnValue($this->getFKDefinition()));
$fkeys = $this->manager->listTableForeignKeys('dummy');
@@ -44,7 +44,10 @@ public function testCompositeForeignKeys()
self::assertEquals(['column_1', 'column_2', 'column_3'], array_map('strtolower', $fkeys[0]->getForeignColumns()));
}
- public function getFKDefinition()
+ /**
+ * @return string[][]
+ */
+ public function getFKDefinition() : array
{
return [
[
diff --git a/tests/Doctrine/Tests/DBAL/Schema/Platforms/MySQLSchemaTest.php b/tests/Doctrine/Tests/DBAL/Schema/Platforms/MySQLSchemaTest.php
index 0d45a5ef5e5..4cf69f28f7c 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/Platforms/MySQLSchemaTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/Platforms/MySQLSchemaTest.php
@@ -16,13 +16,13 @@ class MySQLSchemaTest extends TestCase
/** @var AbstractPlatform */
private $platform;
- protected function setUp()
+ protected function setUp() : void
{
$this->comparator = new Comparator();
$this->platform = new MySqlPlatform();
}
- public function testSwitchPrimaryKeyOrder()
+ public function testSwitchPrimaryKeyOrder() : void
{
$tableOld = new Table('test');
$tableOld->addColumn('foo_id', 'integer');
@@ -47,7 +47,7 @@ public function testSwitchPrimaryKeyOrder()
/**
* @group DBAL-132
*/
- public function testGenerateForeignKeySQL()
+ public function testGenerateForeignKeySQL() : void
{
$tableOld = new Table('test');
$tableOld->addColumn('foo_id', 'integer');
@@ -64,7 +64,7 @@ public function testGenerateForeignKeySQL()
/**
* @group DDC-1737
*/
- public function testClobNoAlterTable()
+ public function testClobNoAlterTable() : void
{
$tableOld = new Table('test');
$tableOld->addColumn('id', 'integer');
diff --git a/tests/Doctrine/Tests/DBAL/Schema/SchemaDiffTest.php b/tests/Doctrine/Tests/DBAL/Schema/SchemaDiffTest.php
index 8a6d9575bce..87146c2f001 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/SchemaDiffTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/SchemaDiffTest.php
@@ -2,17 +2,18 @@
namespace Doctrine\Tests\DBAL\Schema;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\SchemaDiff;
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\TableDiff;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class SchemaDiffTest extends TestCase
{
- public function testSchemaDiffToSql()
+ public function testSchemaDiffToSql() : void
{
$diff = $this->createSchemaDiff();
$platform = $this->createPlatform(true);
@@ -24,7 +25,7 @@ public function testSchemaDiffToSql()
self::assertEquals($expected, $sql);
}
- public function testSchemaDiffToSaveSql()
+ public function testSchemaDiffToSaveSql() : void
{
$diff = $this->createSchemaDiff();
$platform = $this->createPlatform(false);
@@ -36,9 +37,13 @@ public function testSchemaDiffToSaveSql()
self::assertEquals($expected, $sql);
}
- public function createPlatform($unsafe = false)
+ /**
+ * @return AbstractPlatform|MockObject
+ */
+ private function createPlatform(bool $unsafe)
{
- $platform = $this->createMock(MockPlatform::class);
+ /** @var AbstractPlatform|MockObject $platform */
+ $platform = $this->createMock(AbstractPlatform::class);
$platform->expects($this->exactly(1))
->method('getCreateSchemaSQL')
->with('foo_ns')
@@ -93,10 +98,11 @@ public function createPlatform($unsafe = false)
$platform->expects($this->exactly(2))
->method('supportsForeignKeyConstraints')
->will($this->returnValue(true));
+
return $platform;
}
- public function createSchemaDiff()
+ public function createSchemaDiff() : SchemaDiff
{
$diff = new SchemaDiff();
$diff->newNamespaces['foo_ns'] = 'foo_ns';
@@ -112,6 +118,7 @@ public function createSchemaDiff()
$fk = new ForeignKeyConstraint(['id'], 'foreign_table', ['id']);
$fk->setLocalTable(new Table('local_table'));
$diff->orphanedForeignKeys[] = $fk;
+
return $diff;
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Schema/SchemaTest.php b/tests/Doctrine/Tests/DBAL/Schema/SchemaTest.php
index f7254c97cb7..69796236235 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/SchemaTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/SchemaTest.php
@@ -10,12 +10,13 @@
use Doctrine\DBAL\Schema\Visitor\AbstractVisitor;
use Doctrine\DBAL\Schema\Visitor\Visitor;
use PHPUnit\Framework\TestCase;
+use ReflectionProperty;
use function current;
use function strlen;
class SchemaTest extends TestCase
{
- public function testAddTable()
+ public function testAddTable() : void
{
$tableName = 'public.foo';
$table = new Table($tableName);
@@ -31,7 +32,7 @@ public function testAddTable()
self::assertTrue($schema->hasTable($tableName));
}
- public function testTableMatchingCaseInsensitive()
+ public function testTableMatchingCaseInsensitive() : void
{
$table = new Table('Foo');
@@ -44,7 +45,7 @@ public function testTableMatchingCaseInsensitive()
self::assertSame($table, $schema->getTable('Foo'));
}
- public function testGetUnknownTableThrowsException()
+ public function testGetUnknownTableThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -52,7 +53,7 @@ public function testGetUnknownTableThrowsException()
$schema->getTable('unknown');
}
- public function testCreateTableTwiceThrowsException()
+ public function testCreateTableTwiceThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -63,7 +64,7 @@ public function testCreateTableTwiceThrowsException()
$schema = new Schema($tables);
}
- public function testRenameTable()
+ public function testRenameTable() : void
{
$tableName = 'foo';
$table = new Table($tableName);
@@ -76,7 +77,7 @@ public function testRenameTable()
self::assertSame($table, $schema->getTable('bar'));
}
- public function testDropTable()
+ public function testDropTable() : void
{
$tableName = 'foo';
$table = new Table($tableName);
@@ -89,7 +90,7 @@ public function testDropTable()
self::assertFalse($schema->hasTable('foo'));
}
- public function testCreateTable()
+ public function testCreateTable() : void
{
$schema = new Schema();
@@ -102,7 +103,7 @@ public function testCreateTable()
self::assertTrue($schema->hasTable('foo'));
}
- public function testAddSequences()
+ public function testAddSequences() : void
{
$sequence = new Sequence('a_seq', 1, 1);
@@ -115,7 +116,7 @@ public function testAddSequences()
self::assertArrayHasKey('public.a_seq', $sequences);
}
- public function testSequenceAccessCaseInsensitive()
+ public function testSequenceAccessCaseInsensitive() : void
{
$sequence = new Sequence('a_Seq');
@@ -129,7 +130,7 @@ public function testSequenceAccessCaseInsensitive()
self::assertEquals($sequence, $schema->getSequence('A_SEQ'));
}
- public function testGetUnknownSequenceThrowsException()
+ public function testGetUnknownSequenceThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -137,7 +138,7 @@ public function testGetUnknownSequenceThrowsException()
$schema->getSequence('unknown');
}
- public function testCreateSequence()
+ public function testCreateSequence() : void
{
$schema = new Schema();
$sequence = $schema->createSequence('a_seq', 10, 20);
@@ -153,7 +154,7 @@ public function testCreateSequence()
self::assertArrayHasKey('public.a_seq', $sequences);
}
- public function testDropSequence()
+ public function testDropSequence() : void
{
$sequence = new Sequence('a_seq', 1, 1);
@@ -163,7 +164,7 @@ public function testDropSequence()
self::assertFalse($schema->hasSequence('a_seq'));
}
- public function testAddSequenceTwiceThrowsException()
+ public function testAddSequenceTwiceThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -172,7 +173,7 @@ public function testAddSequenceTwiceThrowsException()
$schema = new Schema([], [$sequence, $sequence]);
}
- public function testConfigMaxIdentifierLength()
+ public function testConfigMaxIdentifierLength() : void
{
$schemaConfig = new SchemaConfig();
$schemaConfig->setMaxIdentifierLength(5);
@@ -186,7 +187,7 @@ public function testConfigMaxIdentifierLength()
self::assertEquals(5, strlen($index->getName()));
}
- public function testDeepClone()
+ public function testDeepClone() : void
{
$schema = new Schema();
$sequence = $schema->createSequence('baz');
@@ -211,13 +212,17 @@ public function testDeepClone()
$fk = $schemaNew->getTable('bar')->getForeignKeys();
$fk = current($fk);
- self::assertSame($schemaNew->getTable('bar'), $this->readAttribute($fk, '_localTable'));
+
+ $re = new ReflectionProperty($fk, '_localTable');
+ $re->setAccessible(true);
+
+ self::assertSame($schemaNew->getTable('bar'), $re->getValue($fk));
}
/**
* @group DBAL-219
*/
- public function testHasTableForQuotedAsset()
+ public function testHasTableForQuotedAsset() : void
{
$schema = new Schema();
@@ -230,7 +235,7 @@ public function testHasTableForQuotedAsset()
/**
* @group DBAL-669
*/
- public function testHasNamespace()
+ public function testHasNamespace() : void
{
$schema = new Schema();
@@ -254,7 +259,7 @@ public function testHasNamespace()
/**
* @group DBAL-669
*/
- public function testCreatesNamespace()
+ public function testCreatesNamespace() : void
{
$schema = new Schema();
@@ -279,20 +284,22 @@ public function testCreatesNamespace()
/**
* @group DBAL-669
- * @expectedException \Doctrine\DBAL\Schema\SchemaException
*/
- public function testThrowsExceptionOnCreatingNamespaceTwice()
+ public function testThrowsExceptionOnCreatingNamespaceTwice() : void
{
$schema = new Schema();
$schema->createNamespace('foo');
+
+ $this->expectException(SchemaException::class);
+
$schema->createNamespace('foo');
}
/**
* @group DBAL-669
*/
- public function testCreatesNamespaceThroughAddingTableImplicitly()
+ public function testCreatesNamespaceThroughAddingTableImplicitly() : void
{
$schema = new Schema();
@@ -322,7 +329,7 @@ public function testCreatesNamespaceThroughAddingTableImplicitly()
/**
* @group DBAL-669
*/
- public function testCreatesNamespaceThroughAddingSequenceImplicitly()
+ public function testCreatesNamespaceThroughAddingSequenceImplicitly() : void
{
$schema = new Schema();
@@ -352,7 +359,7 @@ public function testCreatesNamespaceThroughAddingSequenceImplicitly()
/**
* @group DBAL-669
*/
- public function testVisitsVisitor()
+ public function testVisitsVisitor() : void
{
$schema = new Schema();
$visitor = $this->createMock(Visitor::class);
@@ -398,7 +405,7 @@ public function testVisitsVisitor()
/**
* @group DBAL-669
*/
- public function testVisitsNamespaceVisitor()
+ public function testVisitsNamespaceVisitor() : void
{
$schema = new Schema();
$visitor = $this->createMock(AbstractVisitor::class);
diff --git a/tests/Doctrine/Tests/DBAL/Schema/SequenceTest.php b/tests/Doctrine/Tests/DBAL/Schema/SequenceTest.php
index b3a72017c16..d13d0a908a6 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/SequenceTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/SequenceTest.php
@@ -11,7 +11,7 @@ class SequenceTest extends DbalTestCase
/**
* @group DDC-1657
*/
- public function testIsAutoincrementFor()
+ public function testIsAutoincrementFor() : void
{
$table = new Table('foo');
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -26,7 +26,7 @@ public function testIsAutoincrementFor()
self::assertFalse($sequence3->isAutoIncrementsFor($table));
}
- public function testIsAutoincrementForCaseInsensitive()
+ public function testIsAutoincrementForCaseInsensitive() : void
{
$table = new Table('foo');
$table->addColumn('ID', 'integer', ['autoincrement' => true]);
diff --git a/tests/Doctrine/Tests/DBAL/Schema/SqliteSchemaManagerTest.php b/tests/Doctrine/Tests/DBAL/Schema/SqliteSchemaManagerTest.php
index 7b3031624af..3677212f240 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/SqliteSchemaManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/SqliteSchemaManagerTest.php
@@ -26,7 +26,10 @@ public function testParseColumnCollation(?string $collation, string $column, str
self::assertSame($collation, $ref->invoke($manager, $column, $sql));
}
- public function getDataColumnCollation()
+ /**
+ * @return mixed[][]
+ */
+ public static function getDataColumnCollation() : iterable
{
return [
['RTRIM', 'a', 'CREATE TABLE "a" ("a" text DEFAULT "aa" COLLATE "RTRIM" NOT NULL)'],
@@ -64,7 +67,10 @@ public function testParseColumnCommentFromSQL(?string $comment, string $column,
self::assertSame($comment, $ref->invoke($manager, $column, $sql));
}
- public function getDataColumnComment()
+ /**
+ * @return mixed[][]
+ */
+ public static function getDataColumnComment() : iterable
{
return [
'Single column with no comment' => [
diff --git a/tests/Doctrine/Tests/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizerTest.php b/tests/Doctrine/Tests/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizerTest.php
index cedc3583137..ad24ca599a6 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizerTest.php
@@ -19,7 +19,7 @@ class SingleDatabaseSynchronizerTest extends TestCase
/** @var SingleDatabaseSynchronizer */
private $synchronizer;
- protected function setUp()
+ protected function setUp() : void
{
$this->conn = DriverManager::getConnection([
'driver' => 'pdo_sqlite',
@@ -28,7 +28,7 @@ protected function setUp()
$this->synchronizer = new SingleDatabaseSynchronizer($this->conn);
}
- public function testGetCreateSchema()
+ public function testGetCreateSchema() : void
{
$schema = new Schema();
$table = $schema->createTable('test');
@@ -39,7 +39,7 @@ public function testGetCreateSchema()
self::assertEquals(['CREATE TABLE test (id INTEGER NOT NULL, PRIMARY KEY(id))'], $sql);
}
- public function testGetUpdateSchema()
+ public function testGetUpdateSchema() : void
{
$schema = new Schema();
$table = $schema->createTable('test');
@@ -50,7 +50,7 @@ public function testGetUpdateSchema()
self::assertEquals(['CREATE TABLE test (id INTEGER NOT NULL, PRIMARY KEY(id))'], $sql);
}
- public function testGetDropSchema()
+ public function testGetDropSchema() : void
{
$schema = new Schema();
$table = $schema->createTable('test');
@@ -63,7 +63,7 @@ public function testGetDropSchema()
self::assertEquals(['DROP TABLE test'], $sql);
}
- public function testGetDropAllSchema()
+ public function testGetDropAllSchema() : void
{
$schema = new Schema();
$table = $schema->createTable('test');
diff --git a/tests/Doctrine/Tests/DBAL/Schema/TableDiffTest.php b/tests/Doctrine/Tests/DBAL/Schema/TableDiffTest.php
index 80b9ef7b2c2..7ae17019f83 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/TableDiffTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/TableDiffTest.php
@@ -2,31 +2,39 @@
namespace Doctrine\Tests\DBAL\Schema;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\Identifier;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\TableDiff;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class TableDiffTest extends TestCase
{
+ /** @var AbstractPlatform|MockObject */
+ private $platform;
+
+ public function setUp() : void
+ {
+ $this->platform = $this->createMock(AbstractPlatform::class);
+ }
+
/**
* @group DBAL-1013
*/
- public function testReturnsName()
+ public function testReturnsName() : void
{
$tableDiff = new TableDiff('foo');
- self::assertEquals(new Identifier('foo'), $tableDiff->getName(new MockPlatform()));
+ self::assertEquals(new Identifier('foo'), $tableDiff->getName($this->platform));
}
/**
* @group DBAL-1016
*/
- public function testPrefersNameFromTableObject()
+ public function testPrefersNameFromTableObject() : void
{
- $platformMock = new MockPlatform();
- $tableMock = $this->getMockBuilder(Table::class)
+ $tableMock = $this->getMockBuilder(Table::class)
->disableOriginalConstructor()
->getMock();
@@ -35,16 +43,16 @@ public function testPrefersNameFromTableObject()
$tableMock->expects($this->once())
->method('getQuotedName')
- ->with($platformMock)
+ ->with($this->platform)
->will($this->returnValue('foo'));
- self::assertEquals(new Identifier('foo'), $tableDiff->getName($platformMock));
+ self::assertEquals(new Identifier('foo'), $tableDiff->getName($this->platform));
}
/**
* @group DBAL-1013
*/
- public function testReturnsNewName()
+ public function testReturnsNewName() : void
{
$tableDiff = new TableDiff('foo');
diff --git a/tests/Doctrine/Tests/DBAL/Schema/TableTest.php b/tests/Doctrine/Tests/DBAL/Schema/TableTest.php
index ac5fead5bcf..d330e758184 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/TableTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/TableTest.php
@@ -17,20 +17,20 @@
class TableTest extends DbalTestCase
{
- public function testCreateWithInvalidTableName()
+ public function testCreateWithInvalidTableName() : void
{
$this->expectException(DBALException::class);
new Table('');
}
- public function testGetName()
+ public function testGetName() : void
{
$table = new Table('foo', [], [], []);
self::assertEquals('foo', $table->getName());
}
- public function testColumns()
+ public function testColumns() : void
{
$type = Type::getType('integer');
$columns = [];
@@ -48,7 +48,7 @@ public function testColumns()
self::assertCount(2, $table->getColumns());
}
- public function testColumnsCaseInsensitive()
+ public function testColumnsCaseInsensitive() : void
{
$table = new Table('foo');
$column = $table->addColumn('Foo', 'integer');
@@ -62,7 +62,7 @@ public function testColumnsCaseInsensitive()
self::assertSame($column, $table->getColumn('FOO'));
}
- public function testCreateColumn()
+ public function testCreateColumn() : void
{
$type = Type::getType('integer');
@@ -74,7 +74,7 @@ public function testCreateColumn()
self::assertSame($type, $table->getColumn('bar')->getType());
}
- public function testDropColumn()
+ public function testDropColumn() : void
{
$type = Type::getType('integer');
$columns = [];
@@ -91,7 +91,7 @@ public function testDropColumn()
self::assertFalse($table->hasColumn('bar'));
}
- public function testGetUnknownColumnThrowsException()
+ public function testGetUnknownColumnThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -99,7 +99,7 @@ public function testGetUnknownColumnThrowsException()
$table->getColumn('unknown');
}
- public function testAddColumnTwiceThrowsException()
+ public function testAddColumnTwiceThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -110,7 +110,7 @@ public function testAddColumnTwiceThrowsException()
$table = new Table('foo', $columns, [], []);
}
- public function testCreateIndex()
+ public function testCreateIndex() : void
{
$type = Type::getType('integer');
$columns = [new Column('foo', $type), new Column('bar', $type), new Column('baz', $type)];
@@ -123,7 +123,7 @@ public function testCreateIndex()
self::assertTrue($table->hasIndex('foo_bar_baz_uniq'));
}
- public function testIndexCaseInsensitive()
+ public function testIndexCaseInsensitive() : void
{
$type = Type::getType('integer');
$columns = [
@@ -140,7 +140,7 @@ public function testIndexCaseInsensitive()
self::assertTrue($table->hasIndex('FOO_IDX'));
}
- public function testAddIndexes()
+ public function testAddIndexes() : void
{
$type = Type::getType('integer');
$columns = [
@@ -162,7 +162,7 @@ public function testAddIndexes()
self::assertInstanceOf(Index::class, $table->getIndex('bar_idx'));
}
- public function testGetUnknownIndexThrowsException()
+ public function testGetUnknownIndexThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -170,7 +170,7 @@ public function testGetUnknownIndexThrowsException()
$table->getIndex('unknownIndex');
}
- public function testAddTwoPrimaryThrowsException()
+ public function testAddTwoPrimaryThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -183,7 +183,7 @@ public function testAddTwoPrimaryThrowsException()
$table = new Table('foo', $columns, $indexes, []);
}
- public function testAddTwoIndexesWithSameNameThrowsException()
+ public function testAddTwoIndexesWithSameNameThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -196,7 +196,7 @@ public function testAddTwoIndexesWithSameNameThrowsException()
$table = new Table('foo', $columns, $indexes, []);
}
- public function testConstraints()
+ public function testConstraints() : void
{
$constraint = new ForeignKeyConstraint([], 'foo', []);
@@ -207,7 +207,7 @@ public function testConstraints()
self::assertSame($constraint, array_shift($constraints));
}
- public function testOptions()
+ public function testOptions() : void
{
$table = new Table('foo', [], [], [], false, ['foo' => 'bar']);
@@ -215,7 +215,7 @@ public function testOptions()
self::assertEquals('bar', $table->getOption('foo'));
}
- public function testBuilderSetPrimaryKey()
+ public function testBuilderSetPrimaryKey() : void
{
$table = new Table('foo');
@@ -228,7 +228,7 @@ public function testBuilderSetPrimaryKey()
self::assertTrue($table->getIndex('primary')->isPrimary());
}
- public function testBuilderAddUniqueIndex()
+ public function testBuilderAddUniqueIndex() : void
{
$table = new Table('foo');
@@ -240,7 +240,7 @@ public function testBuilderAddUniqueIndex()
self::assertFalse($table->getIndex('my_idx')->isPrimary());
}
- public function testBuilderAddIndex()
+ public function testBuilderAddIndex() : void
{
$table = new Table('foo');
@@ -252,7 +252,7 @@ public function testBuilderAddIndex()
self::assertFalse($table->getIndex('my_idx')->isPrimary());
}
- public function testBuilderAddIndexWithInvalidNameThrowsException()
+ public function testBuilderAddIndexWithInvalidNameThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -261,7 +261,7 @@ public function testBuilderAddIndexWithInvalidNameThrowsException()
$table->addIndex(['bar'], 'invalid name %&/');
}
- public function testBuilderAddIndexWithUnknownColumnThrowsException()
+ public function testBuilderAddIndexWithUnknownColumnThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -269,7 +269,7 @@ public function testBuilderAddIndexWithUnknownColumnThrowsException()
$table->addIndex(['bar'], 'invalidName');
}
- public function testBuilderOptions()
+ public function testBuilderOptions() : void
{
$table = new Table('foo');
$table->addOption('foo', 'bar');
@@ -277,7 +277,7 @@ public function testBuilderOptions()
self::assertEquals('bar', $table->getOption('foo'));
}
- public function testAddForeignKeyConstraintUnknownLocalColumnThrowsException()
+ public function testAddForeignKeyConstraintUnknownLocalColumnThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -290,7 +290,7 @@ public function testAddForeignKeyConstraintUnknownLocalColumnThrowsException()
$table->addForeignKeyConstraint($foreignTable, ['foo'], ['id']);
}
- public function testAddForeignKeyConstraintUnknownForeignColumnThrowsException()
+ public function testAddForeignKeyConstraintUnknownForeignColumnThrowsException() : void
{
$this->expectException(SchemaException::class);
@@ -303,7 +303,7 @@ public function testAddForeignKeyConstraintUnknownForeignColumnThrowsException()
$table->addForeignKeyConstraint($foreignTable, ['id'], ['foo']);
}
- public function testAddForeignKeyConstraint()
+ public function testAddForeignKeyConstraint() : void
{
$table = new Table('foo');
$table->addColumn('id', 'integer');
@@ -323,7 +323,7 @@ public function testAddForeignKeyConstraint()
self::assertEquals('bar', $constraint->getOption('foo'));
}
- public function testAddIndexWithCaseSensitiveColumnProblem()
+ public function testAddIndexWithCaseSensitiveColumnProblem() : void
{
$table = new Table('foo');
$table->addColumn('id', 'integer');
@@ -335,7 +335,7 @@ public function testAddIndexWithCaseSensitiveColumnProblem()
self::assertTrue($table->getIndex('my_idx')->spansColumns(['id']));
}
- public function testAddPrimaryKeyColumnsAreExplicitlySetToNotNull()
+ public function testAddPrimaryKeyColumnsAreExplicitlySetToNotNull() : void
{
$table = new Table('foo');
$column = $table->addColumn('id', 'integer', ['notnull' => false]);
@@ -350,7 +350,7 @@ public function testAddPrimaryKeyColumnsAreExplicitlySetToNotNull()
/**
* @group DDC-133
*/
- public function testAllowImplicitSchemaTableInAutogeneratedIndexNames()
+ public function testAllowImplicitSchemaTableInAutogeneratedIndexNames() : void
{
$table = new Table('foo.bar');
$table->addColumn('baz', 'integer', []);
@@ -362,7 +362,7 @@ public function testAllowImplicitSchemaTableInAutogeneratedIndexNames()
/**
* @group DBAL-50
*/
- public function testAddForeignKeyIndexImplicitly()
+ public function testAddForeignKeyIndexImplicitly() : void
{
$table = new Table('foo');
$table->addColumn('id', 'integer');
@@ -383,7 +383,7 @@ public function testAddForeignKeyIndexImplicitly()
/**
* @group DBAL-1063
*/
- public function testAddForeignKeyDoesNotCreateDuplicateIndex()
+ public function testAddForeignKeyDoesNotCreateDuplicateIndex() : void
{
$table = new Table('foo');
$table->addColumn('bar', 'integer');
@@ -402,7 +402,7 @@ public function testAddForeignKeyDoesNotCreateDuplicateIndex()
/**
* @group DBAL-1063
*/
- public function testAddForeignKeyAddsImplicitIndexIfIndexColumnsDoNotSpan()
+ public function testAddForeignKeyAddsImplicitIndexIfIndexColumnsDoNotSpan() : void
{
$table = new Table('foo');
$table->addColumn('bar', 'integer');
@@ -430,7 +430,7 @@ public function testAddForeignKeyAddsImplicitIndexIfIndexColumnsDoNotSpan()
* @group DBAL-50
* @group DBAL-1063
*/
- public function testOverrulingIndexDoesNotDropOverruledIndex()
+ public function testOverrulingIndexDoesNotDropOverruledIndex() : void
{
$table = new Table('bar');
$table->addColumn('baz', 'integer', []);
@@ -448,7 +448,7 @@ public function testOverrulingIndexDoesNotDropOverruledIndex()
/**
* @group DBAL-1063
*/
- public function testAllowsAddingDuplicateIndexesBasedOnColumns()
+ public function testAllowsAddingDuplicateIndexesBasedOnColumns() : void
{
$table = new Table('foo');
$table->addColumn('bar', 'integer');
@@ -465,7 +465,7 @@ public function testAllowsAddingDuplicateIndexesBasedOnColumns()
/**
* @group DBAL-1063
*/
- public function testAllowsAddingFulfillingIndexesBasedOnColumns()
+ public function testAllowsAddingFulfillingIndexesBasedOnColumns() : void
{
$table = new Table('foo');
$table->addColumn('bar', 'integer');
@@ -484,7 +484,7 @@ public function testAllowsAddingFulfillingIndexesBasedOnColumns()
* @group DBAL-50
* @group DBAL-1063
*/
- public function testPrimaryKeyOverrulingUniqueIndexDoesNotDropUniqueIndex()
+ public function testPrimaryKeyOverrulingUniqueIndexDoesNotDropUniqueIndex() : void
{
$table = new Table('bar');
$table->addColumn('baz', 'integer', []);
@@ -499,7 +499,7 @@ public function testPrimaryKeyOverrulingUniqueIndexDoesNotDropUniqueIndex()
self::assertTrue($table->hasIndex('idx_unique'));
}
- public function testAddingFulfillingRegularIndexOverridesImplicitForeignKeyConstraintIndex()
+ public function testAddingFulfillingRegularIndexOverridesImplicitForeignKeyConstraintIndex() : void
{
$foreignTable = new Table('foreign');
$foreignTable->addColumn('id', 'integer');
@@ -516,7 +516,7 @@ public function testAddingFulfillingRegularIndexOverridesImplicitForeignKeyConst
self::assertTrue($localTable->hasIndex('explicit_idx'));
}
- public function testAddingFulfillingUniqueIndexOverridesImplicitForeignKeyConstraintIndex()
+ public function testAddingFulfillingUniqueIndexOverridesImplicitForeignKeyConstraintIndex() : void
{
$foreignTable = new Table('foreign');
$foreignTable->addColumn('id', 'integer');
@@ -533,7 +533,7 @@ public function testAddingFulfillingUniqueIndexOverridesImplicitForeignKeyConstr
self::assertTrue($localTable->hasIndex('explicit_idx'));
}
- public function testAddingFulfillingPrimaryKeyOverridesImplicitForeignKeyConstraintIndex()
+ public function testAddingFulfillingPrimaryKeyOverridesImplicitForeignKeyConstraintIndex() : void
{
$foreignTable = new Table('foreign');
$foreignTable->addColumn('id', 'integer');
@@ -550,7 +550,7 @@ public function testAddingFulfillingPrimaryKeyOverridesImplicitForeignKeyConstra
self::assertTrue($localTable->hasIndex('explicit_idx'));
}
- public function testAddingFulfillingExplicitIndexOverridingImplicitForeignKeyConstraintIndexWithSameNameDoesNotThrowException()
+ public function testAddingFulfillingExplicitIndexOverridingImplicitForeignKeyConstraintIndexWithSameNameDoesNotThrowException() : void
{
$foreignTable = new Table('foreign');
$foreignTable->addColumn('id', 'integer');
@@ -574,7 +574,7 @@ public function testAddingFulfillingExplicitIndexOverridingImplicitForeignKeyCon
/**
* @group DBAL-64
*/
- public function testQuotedTableName()
+ public function testQuotedTableName() : void
{
$table = new Table('`bar`');
@@ -589,7 +589,7 @@ public function testQuotedTableName()
/**
* @group DBAL-79
*/
- public function testTableHasPrimaryKey()
+ public function testTableHasPrimaryKey() : void
{
$table = new Table('test');
@@ -604,7 +604,7 @@ public function testTableHasPrimaryKey()
/**
* @group DBAL-91
*/
- public function testAddIndexWithQuotedColumns()
+ public function testAddIndexWithQuotedColumns() : void
{
$table = new Table('test');
$table->addColumn('"foo"', 'integer');
@@ -617,7 +617,7 @@ public function testAddIndexWithQuotedColumns()
/**
* @group DBAL-91
*/
- public function testAddForeignKeyWithQuotedColumnsAndTable()
+ public function testAddForeignKeyWithQuotedColumnsAndTable() : void
{
$table = new Table('test');
$table->addColumn('"foo"', 'integer');
@@ -630,7 +630,7 @@ public function testAddForeignKeyWithQuotedColumnsAndTable()
/**
* @group DBAL-177
*/
- public function testQuoteSchemaPrefixed()
+ public function testQuoteSchemaPrefixed() : void
{
$table = new Table('`test`.`test`');
self::assertEquals('test.test', $table->getName());
@@ -640,7 +640,7 @@ public function testQuoteSchemaPrefixed()
/**
* @group DBAL-204
*/
- public function testFullQualifiedTableName()
+ public function testFullQualifiedTableName() : void
{
$table = new Table('`test`.`test`');
self::assertEquals('test.test', $table->getFullQualifiedName('test'));
@@ -654,7 +654,7 @@ public function testFullQualifiedTableName()
/**
* @group DBAL-224
*/
- public function testDropIndex()
+ public function testDropIndex() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
@@ -669,7 +669,7 @@ public function testDropIndex()
/**
* @group DBAL-224
*/
- public function testDropPrimaryKey()
+ public function testDropPrimaryKey() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
@@ -684,7 +684,7 @@ public function testDropPrimaryKey()
/**
* @group DBAL-234
*/
- public function testRenameIndex()
+ public function testRenameIndex() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
@@ -756,7 +756,7 @@ public function testRenameIndex()
/**
* @group DBAL-2508
*/
- public function testKeepsIndexOptionsOnRenamingRegularIndex()
+ public function testKeepsIndexOptionsOnRenamingRegularIndex() : void
{
$table = new Table('foo');
$table->addColumn('id', 'integer');
@@ -770,7 +770,7 @@ public function testKeepsIndexOptionsOnRenamingRegularIndex()
/**
* @group DBAL-2508
*/
- public function testKeepsIndexOptionsOnRenamingUniqueIndex()
+ public function testKeepsIndexOptionsOnRenamingUniqueIndex() : void
{
$table = new Table('foo');
$table->addColumn('id', 'integer');
@@ -783,22 +783,22 @@ public function testKeepsIndexOptionsOnRenamingUniqueIndex()
/**
* @group DBAL-234
- * @expectedException \Doctrine\DBAL\Schema\SchemaException
*/
- public function testThrowsExceptionOnRenamingNonExistingIndex()
+ public function testThrowsExceptionOnRenamingNonExistingIndex() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
$table->addIndex(['id'], 'idx');
+ $this->expectException(SchemaException::class);
+
$table->renameIndex('foo', 'bar');
}
/**
* @group DBAL-234
- * @expectedException \Doctrine\DBAL\Schema\SchemaException
*/
- public function testThrowsExceptionOnRenamingToAlreadyExistingIndex()
+ public function testThrowsExceptionOnRenamingToAlreadyExistingIndex() : void
{
$table = new Table('test');
$table->addColumn('id', 'integer');
@@ -806,6 +806,8 @@ public function testThrowsExceptionOnRenamingToAlreadyExistingIndex()
$table->addIndex(['id'], 'idx_id');
$table->addIndex(['foo'], 'idx_foo');
+ $this->expectException(SchemaException::class);
+
$table->renameIndex('idx_id', 'idx_foo');
}
@@ -813,7 +815,7 @@ public function testThrowsExceptionOnRenamingToAlreadyExistingIndex()
* @dataProvider getNormalizesAssetNames
* @group DBAL-831
*/
- public function testNormalizesColumnNames($assetName)
+ public function testNormalizesColumnNames(string $assetName) : void
{
$table = new Table('test');
@@ -867,7 +869,10 @@ public function testNormalizesColumnNames($assetName)
self::assertFalse($table->hasForeignKey('foo'));
}
- public function getNormalizesAssetNames()
+ /**
+ * @return mixed[][]
+ */
+ public static function getNormalizesAssetNames() : iterable
{
return [
['foo'],
@@ -880,4 +885,13 @@ public function getNormalizesAssetNames()
['"FOO"'],
];
}
+
+ public function testTableComment() : void
+ {
+ $table = new Table('bar');
+ self::assertNull($table->getComment());
+
+ $table->setComment('foo');
+ self::assertEquals('foo', $table->getComment());
+ }
}
diff --git a/tests/Doctrine/Tests/DBAL/Schema/Visitor/CreateSchemaSqlCollectorTest.php b/tests/Doctrine/Tests/DBAL/Schema/Visitor/CreateSchemaSqlCollectorTest.php
index e64b4c523f3..88df92341ce 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/Visitor/CreateSchemaSqlCollectorTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/Visitor/CreateSchemaSqlCollectorTest.php
@@ -7,12 +7,12 @@
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\Visitor\CreateSchemaSqlCollector;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
-use PHPUnit_Framework_MockObject_MockObject;
class CreateSchemaSqlCollectorTest extends TestCase
{
- /** @var AbstractPlatform|PHPUnit_Framework_MockObject_MockObject */
+ /** @var AbstractPlatform|MockObject */
private $platformMock;
/** @var CreateSchemaSqlCollector */
@@ -21,12 +21,12 @@ class CreateSchemaSqlCollectorTest extends TestCase
/**
* {@inheritdoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
parent::setUp();
$this->platformMock = $this->getMockBuilder(AbstractPlatform::class)
- ->setMethods(
+ ->onlyMethods(
[
'getCreateForeignKeySQL',
'getCreateSchemaSQL',
@@ -39,14 +39,16 @@ protected function setUp()
->getMockForAbstractClass();
$this->visitor = new CreateSchemaSqlCollector($this->platformMock);
- foreach (['getCreateSchemaSQL', 'getCreateTableSQL', 'getCreateForeignKeySQL', 'getCreateSequenceSQL'] as $method) {
- $this->platformMock->expects($this->any())
- ->method($method)
- ->will($this->returnValue('foo'));
+ foreach (['getCreateSchemaSQL', 'getCreateForeignKeySQL', 'getCreateSequenceSQL'] as $method) {
+ $this->platformMock->method($method)
+ ->willReturn('foo');
}
+
+ $this->platformMock->method('getCreateTableSQL')
+ ->willReturn(['foo']);
}
- public function testAcceptsNamespace()
+ public function testAcceptsNamespace() : void
{
$this->platformMock->expects($this->at(0))
->method('supportsSchemas')
@@ -65,7 +67,7 @@ public function testAcceptsNamespace()
self::assertSame(['foo'], $this->visitor->getQueries());
}
- public function testAcceptsTable()
+ public function testAcceptsTable() : void
{
$table = $this->createTableMock();
@@ -74,7 +76,7 @@ public function testAcceptsTable()
self::assertSame(['foo'], $this->visitor->getQueries());
}
- public function testAcceptsForeignKey()
+ public function testAcceptsForeignKey() : void
{
$this->platformMock->expects($this->at(0))
->method('supportsForeignKeyConstraints')
@@ -96,7 +98,7 @@ public function testAcceptsForeignKey()
self::assertSame(['foo'], $this->visitor->getQueries());
}
- public function testAcceptsSequences()
+ public function testAcceptsSequences() : void
{
$sequence = $this->createSequenceMock();
@@ -105,7 +107,7 @@ public function testAcceptsSequences()
self::assertSame(['foo'], $this->visitor->getQueries());
}
- public function testResetsQueries()
+ public function testResetsQueries() : void
{
foreach (['supportsSchemas', 'supportsForeignKeyConstraints'] as $method) {
$this->platformMock->expects($this->any())
@@ -130,7 +132,7 @@ public function testResetsQueries()
}
/**
- * @return ForeignKeyConstraint|PHPUnit_Framework_MockObject_MockObject
+ * @return ForeignKeyConstraint|MockObject
*/
private function createForeignKeyConstraintMock()
{
@@ -140,7 +142,7 @@ private function createForeignKeyConstraintMock()
}
/**
- * @return Sequence|PHPUnit_Framework_MockObject_MockObject
+ * @return Sequence|MockObject
*/
private function createSequenceMock()
{
@@ -150,7 +152,7 @@ private function createSequenceMock()
}
/**
- * @return Table|PHPUnit_Framework_MockObject_MockObject
+ * @return Table|MockObject
*/
private function createTableMock()
{
diff --git a/tests/Doctrine/Tests/DBAL/Schema/Visitor/DropSchemaSqlCollectorTest.php b/tests/Doctrine/Tests/DBAL/Schema/Visitor/DropSchemaSqlCollectorTest.php
index b2aff283871..12e3678cbf6 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/Visitor/DropSchemaSqlCollectorTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/Visitor/DropSchemaSqlCollectorTest.php
@@ -10,20 +10,20 @@
use PHPUnit\Framework\TestCase;
/**
- * @covers Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector
+ * @covers \Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector
*/
class DropSchemaSqlCollectorTest extends TestCase
{
- public function testGetQueriesUsesAcceptedForeignKeys()
+ public function testGetQueriesUsesAcceptedForeignKeys() : void
{
- $tableOne = $this->getTableMock();
- $tableTwo = $this->getTableMock();
+ $tableOne = $this->createMock(Table::class);
+ $tableTwo = $this->createMock(Table::class);
$keyConstraintOne = $this->getStubKeyConstraint('first');
$keyConstraintTwo = $this->getStubKeyConstraint('second');
$platform = $this->getMockBuilder(AbstractPlatform::class)
- ->setMethods(['getDropForeignKeySQL'])
+ ->onlyMethods(['getDropForeignKeySQL'])
->getMockForAbstractClass();
$collector = new DropSchemaSqlCollector($platform);
@@ -45,19 +45,9 @@ public function testGetQueriesUsesAcceptedForeignKeys()
$collector->getQueries();
}
- private function getTableMock()
+ private function getStubKeyConstraint(string $name) : ForeignKeyConstraint
{
- return $this->getMockWithoutArguments(Table::class);
- }
-
- private function getMockWithoutArguments($className)
- {
- return $this->getMockBuilder($className)->disableOriginalConstructor()->getMock();
- }
-
- private function getStubKeyConstraint($name)
- {
- $constraint = $this->getMockWithoutArguments(ForeignKeyConstraint::class);
+ $constraint = $this->createMock(ForeignKeyConstraint::class);
$constraint->expects($this->any())
->method('getName')
@@ -74,13 +64,16 @@ private function getStubKeyConstraint($name)
return $constraint;
}
- public function testGivenForeignKeyWithZeroLengthAcceptForeignKeyThrowsException()
+ public function testGivenForeignKeyWithZeroLengthAcceptForeignKeyThrowsException() : void
{
$collector = new DropSchemaSqlCollector(
$this->getMockForAbstractClass(AbstractPlatform::class)
);
$this->expectException(SchemaException::class);
- $collector->acceptForeignKey($this->getTableMock(), $this->getStubKeyConstraint(''));
+ $collector->acceptForeignKey(
+ $this->createMock(Table::class),
+ $this->getStubKeyConstraint('')
+ );
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Schema/Visitor/RemoveNamespacedAssetsTest.php b/tests/Doctrine/Tests/DBAL/Schema/Visitor/RemoveNamespacedAssetsTest.php
index c3e52b0ffaf..982da52ec44 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/Visitor/RemoveNamespacedAssetsTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/Visitor/RemoveNamespacedAssetsTest.php
@@ -14,7 +14,7 @@ class RemoveNamespacedAssetsTest extends TestCase
/**
* @group DBAL-204
*/
- public function testRemoveNamespacedAssets()
+ public function testRemoveNamespacedAssets() : void
{
$config = new SchemaConfig();
$config->setName('test');
@@ -33,7 +33,7 @@ public function testRemoveNamespacedAssets()
/**
* @group DBAL-204
*/
- public function testCleanupForeignKeys()
+ public function testCleanupForeignKeys() : void
{
$config = new SchemaConfig();
$config->setName('test');
@@ -56,7 +56,7 @@ public function testCleanupForeignKeys()
/**
* @group DBAL-204
*/
- public function testCleanupForeignKeysDifferentOrder()
+ public function testCleanupForeignKeysDifferentOrder() : void
{
$config = new SchemaConfig();
$config->setName('test');
diff --git a/tests/Doctrine/Tests/DBAL/Schema/Visitor/SchemaSqlCollectorTest.php b/tests/Doctrine/Tests/DBAL/Schema/Visitor/SchemaSqlCollectorTest.php
index 4ebfd1cac54..60c7f2a1f5b 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/Visitor/SchemaSqlCollectorTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/Visitor/SchemaSqlCollectorTest.php
@@ -8,10 +8,10 @@
class SchemaSqlCollectorTest extends TestCase
{
- public function testCreateSchema()
+ public function testCreateSchema() : void
{
$platformMock = $this->getMockBuilder(MySqlPlatform::class)
- ->setMethods(['getCreateTableSql', 'getCreateSequenceSql', 'getCreateForeignKeySql'])
+ ->onlyMethods(['getCreateTableSql', 'getCreateSequenceSql', 'getCreateForeignKeySql'])
->getMock();
$platformMock->expects($this->exactly(2))
->method('getCreateTableSql')
@@ -30,10 +30,10 @@ public function testCreateSchema()
self::assertEquals(['foo', 'foo', 'bar', 'baz'], $sql);
}
- public function testDropSchema()
+ public function testDropSchema() : void
{
$platformMock = $this->getMockBuilder(MySqlPlatform::class)
- ->setMethods(['getDropTableSql', 'getDropSequenceSql', 'getDropForeignKeySql'])
+ ->onlyMethods(['getDropTableSql', 'getDropSequenceSql', 'getDropForeignKeySql'])
->getMock();
$platformMock->expects($this->exactly(2))
->method('getDropTableSql')
@@ -52,10 +52,7 @@ public function testDropSchema()
self::assertEquals(['fk', 'seq', 'tbl', 'tbl'], $sql);
}
- /**
- * @return Schema
- */
- public function createFixtureSchema()
+ public function createFixtureSchema() : Schema
{
$schema = new Schema();
$tableA = $schema->createTable('foo');
diff --git a/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardConnectionTest.php b/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardConnectionTest.php
index 4985605c60d..c782b06b919 100644
--- a/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardConnectionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardConnectionTest.php
@@ -14,7 +14,7 @@
*/
class PoolingShardConnectionTest extends TestCase
{
- public function testConnect()
+ public function testConnect() : void
{
$conn = DriverManager::getConnection([
'wrapperClass' => PoolingShardConnection::class,
@@ -48,7 +48,7 @@ public function testConnect()
self::assertFalse($conn->isConnected(2));
}
- public function testNoGlobalServerException()
+ public function testNoGlobalServerException() : void
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage("Connection Parameters require 'global' and 'shards' configurations.");
@@ -64,7 +64,7 @@ public function testNoGlobalServerException()
]);
}
- public function testNoShardsServersException()
+ public function testNoShardsServersException() : void
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage("Connection Parameters require 'global' and 'shards' configurations.");
@@ -77,7 +77,7 @@ public function testNoShardsServersException()
]);
}
- public function testNoShardsChoserException()
+ public function testNoShardsChoserException() : void
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage("Missing Shard Choser configuration 'shardChoser'");
@@ -93,7 +93,7 @@ public function testNoShardsChoserException()
]);
}
- public function testShardChoserWrongInstance()
+ public function testShardChoserWrongInstance() : void
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage("The 'shardChoser' configuration is not a valid instance of Doctrine\DBAL\Sharding\ShardChoser\ShardChoser");
@@ -110,7 +110,7 @@ public function testShardChoserWrongInstance()
]);
}
- public function testShardNonNumericId()
+ public function testShardNonNumericId() : void
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Shard Id has to be a non-negative number.');
@@ -126,7 +126,7 @@ public function testShardNonNumericId()
]);
}
- public function testShardMissingId()
+ public function testShardMissingId() : void
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage("Missing 'id' for one configured shard. Please specify a unique shard-id.");
@@ -142,7 +142,7 @@ public function testShardMissingId()
]);
}
- public function testDuplicateShardId()
+ public function testDuplicateShardId() : void
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Shard 1 is duplicated in the configuration.');
@@ -159,7 +159,7 @@ public function testDuplicateShardId()
]);
}
- public function testSwitchShardWithOpenTransactionException()
+ public function testSwitchShardWithOpenTransactionException() : void
{
$conn = DriverManager::getConnection([
'wrapperClass' => PoolingShardConnection::class,
@@ -178,7 +178,7 @@ public function testSwitchShardWithOpenTransactionException()
$conn->connect(1);
}
- public function testGetActiveShardId()
+ public function testGetActiveShardId() : void
{
$conn = DriverManager::getConnection([
'wrapperClass' => PoolingShardConnection::class,
@@ -202,7 +202,7 @@ public function testGetActiveShardId()
self::assertNull($conn->getActiveShardId());
}
- public function testGetParamsOverride()
+ public function testGetParamsOverride() : void
{
$conn = DriverManager::getConnection([
'wrapperClass' => PoolingShardConnection::class,
@@ -241,7 +241,7 @@ public function testGetParamsOverride()
], $conn->getParams());
}
- public function testGetHostOverride()
+ public function testGetHostOverride() : void
{
$conn = DriverManager::getConnection([
'wrapperClass' => PoolingShardConnection::class,
@@ -260,7 +260,7 @@ public function testGetHostOverride()
self::assertEquals('foo', $conn->getHost());
}
- public function testGetPortOverride()
+ public function testGetPortOverride() : void
{
$conn = DriverManager::getConnection([
'wrapperClass' => PoolingShardConnection::class,
@@ -279,7 +279,7 @@ public function testGetPortOverride()
self::assertEquals(3307, $conn->getPort());
}
- public function testGetUsernameOverride()
+ public function testGetUsernameOverride() : void
{
$conn = DriverManager::getConnection([
'wrapperClass' => PoolingShardConnection::class,
@@ -298,7 +298,7 @@ public function testGetUsernameOverride()
self::assertEquals('bar', $conn->getUsername());
}
- public function testGetPasswordOverride()
+ public function testGetPasswordOverride() : void
{
$conn = DriverManager::getConnection([
'wrapperClass' => PoolingShardConnection::class,
diff --git a/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardManagerTest.php b/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardManagerTest.php
index 8954459eb94..eafbd69cfcb 100644
--- a/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Sharding/PoolingShardManagerTest.php
@@ -5,19 +5,23 @@
use Doctrine\DBAL\Sharding\PoolingShardConnection;
use Doctrine\DBAL\Sharding\PoolingShardManager;
use Doctrine\DBAL\Sharding\ShardChoser\ShardChoser;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class PoolingShardManagerTest extends TestCase
{
- private function createConnectionMock()
+ /**
+ * @return PoolingShardConnection|MockObject
+ */
+ private function createConnectionMock() : PoolingShardConnection
{
return $this->getMockBuilder(PoolingShardConnection::class)
- ->setMethods(['connect', 'getParams', 'fetchAll'])
+ ->onlyMethods(['connect', 'getParams', 'fetchAll'])
->disableOriginalConstructor()
->getMock();
}
- private function createPassthroughShardChoser()
+ private function createPassthroughShardChoser() : ShardChoser
{
$mock = $this->createMock(ShardChoser::class);
$mock->expects($this->any())
@@ -25,19 +29,21 @@ private function createPassthroughShardChoser()
->will($this->returnCallback(static function ($value) {
return $value;
}));
+
return $mock;
}
- private function createStaticShardChooser()
+ private function createStaticShardChooser() : ShardChoser
{
$mock = $this->createMock(ShardChoser::class);
$mock->expects($this->any())
->method('pickShard')
->willReturn(1);
+
return $mock;
}
- public function testSelectGlobal()
+ public function testSelectGlobal() : void
{
$conn = $this->createConnectionMock();
$conn->expects($this->once())->method('connect')->with($this->equalTo(0));
@@ -52,7 +58,7 @@ public function testSelectGlobal()
self::assertNull($shardManager->getCurrentDistributionValue());
}
- public function testSelectShard()
+ public function testSelectShard() : void
{
$shardId = 10;
$conn = $this->createConnectionMock();
@@ -65,7 +71,7 @@ public function testSelectShard()
self::assertEquals($shardId, $shardManager->getCurrentDistributionValue());
}
- public function testGetShards()
+ public function testGetShards() : void
{
$conn = $this->createConnectionMock();
$conn->expects($this->any())->method('getParams')->will(
@@ -80,7 +86,7 @@ public function testGetShards()
self::assertEquals([['id' => 1], ['id' => 2]], $shards);
}
- public function testQueryAll()
+ public function testQueryAll() : void
{
$sql = 'SELECT * FROM table';
$params = [1];
@@ -110,7 +116,7 @@ public function testQueryAll()
self::assertEquals([['id' => 1], ['id' => 2]], $result);
}
- public function testQueryAllWithStaticShardChoser()
+ public function testQueryAllWithStaticShardChoser() : void
{
$sql = 'SELECT * FROM table';
$params = [1];
diff --git a/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/AbstractTestCase.php b/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/AbstractTestCase.php
index 2e67d0a023f..b0439d5dfe2 100644
--- a/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/AbstractTestCase.php
+++ b/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/AbstractTestCase.php
@@ -17,7 +17,7 @@ abstract class AbstractTestCase extends TestCase
/** @var SQLAzureShardManager */
protected $sm;
- protected function setUp()
+ protected function setUp() : void
{
if (! isset($GLOBALS['db_type']) || strpos($GLOBALS['db_type'], 'sqlsrv') === false) {
$this->markTestSkipped('No driver or sqlserver driver specified.');
@@ -52,7 +52,7 @@ protected function setUp()
$this->sm = new SQLAzureShardManager($this->conn);
}
- public function createShopSchema()
+ protected function createShopSchema() : Schema
{
$schema = new Schema();
diff --git a/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/FunctionalTest.php b/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/FunctionalTest.php
index 8a99ea70879..6e31d8716ed 100644
--- a/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/FunctionalTest.php
+++ b/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/FunctionalTest.php
@@ -7,7 +7,7 @@
class FunctionalTest extends AbstractTestCase
{
- public function testSharding()
+ public function testSharding() : void
{
$schema = $this->createShopSchema();
diff --git a/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/MultiTenantVisitorTest.php b/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/MultiTenantVisitorTest.php
index 94634dadb69..3549cf40b0e 100644
--- a/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/MultiTenantVisitorTest.php
+++ b/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/MultiTenantVisitorTest.php
@@ -9,7 +9,7 @@
class MultiTenantVisitorTest extends TestCase
{
- public function testMultiTenantPrimaryKey()
+ public function testMultiTenantPrimaryKey() : void
{
$platform = new SQLAzurePlatform();
$visitor = new MultiTenantVisitor();
@@ -24,7 +24,7 @@ public function testMultiTenantPrimaryKey()
self::assertTrue($foo->hasColumn('tenant_id'));
}
- public function testMultiTenantNonPrimaryKey()
+ public function testMultiTenantNonPrimaryKey() : void
{
$platform = new SQLAzurePlatform();
$visitor = new MultiTenantVisitor();
diff --git a/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizerTest.php b/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizerTest.php
index 20e479a3e00..2185a9fc8d1 100644
--- a/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizerTest.php
@@ -6,7 +6,7 @@
class SQLAzureFederationsSynchronizerTest extends AbstractTestCase
{
- public function testCreateSchema()
+ public function testCreateSchema() : void
{
$schema = $this->createShopSchema();
@@ -23,7 +23,7 @@ public function testCreateSchema()
], $sql);
}
- public function testUpdateSchema()
+ public function testUpdateSchema() : void
{
$schema = $this->createShopSchema();
@@ -35,7 +35,7 @@ public function testUpdateSchema()
self::assertEquals([], $sql);
}
- public function testDropSchema()
+ public function testDropSchema() : void
{
$schema = $this->createShopSchema();
diff --git a/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/SQLAzureShardManagerTest.php b/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/SQLAzureShardManagerTest.php
index edc88d376c9..78d6afe593c 100644
--- a/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/SQLAzureShardManagerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Sharding/SQLAzure/SQLAzureShardManagerTest.php
@@ -9,7 +9,7 @@
class SQLAzureShardManagerTest extends TestCase
{
- public function testNoFederationName()
+ public function testNoFederationName() : void
{
$this->expectException(ShardingException::class);
$this->expectExceptionMessage('SQLAzure requires a federation name to be set during sharding configuration.');
@@ -18,7 +18,7 @@ public function testNoFederationName()
new SQLAzureShardManager($conn);
}
- public function testNoDistributionKey()
+ public function testNoDistributionKey() : void
{
$this->expectException(ShardingException::class);
$this->expectExceptionMessage('SQLAzure requires a distribution key to be set during sharding configuration.');
@@ -27,7 +27,7 @@ public function testNoDistributionKey()
new SQLAzureShardManager($conn);
}
- public function testNoDistributionType()
+ public function testNoDistributionType() : void
{
$this->expectException(ShardingException::class);
@@ -35,7 +35,7 @@ public function testNoDistributionType()
new SQLAzureShardManager($conn);
}
- public function testGetDefaultDistributionValue()
+ public function testGetDefaultDistributionValue() : void
{
$conn = $this->createConnection(['sharding' => ['federationName' => 'abc', 'distributionKey' => 'foo', 'distributionType' => 'integer']]);
@@ -43,7 +43,7 @@ public function testGetDefaultDistributionValue()
self::assertNull($sm->getCurrentDistributionValue());
}
- public function testSelectGlobalTransactionActive()
+ public function testSelectGlobalTransactionActive() : void
{
$conn = $this->createConnection(['sharding' => ['federationName' => 'abc', 'distributionKey' => 'foo', 'distributionType' => 'integer']]);
$conn->expects($this->at(1))->method('isTransactionActive')->will($this->returnValue(true));
@@ -55,7 +55,7 @@ public function testSelectGlobalTransactionActive()
$sm->selectGlobal();
}
- public function testSelectGlobal()
+ public function testSelectGlobal() : void
{
$conn = $this->createConnection(['sharding' => ['federationName' => 'abc', 'distributionKey' => 'foo', 'distributionType' => 'integer']]);
$conn->expects($this->at(1))->method('isTransactionActive')->will($this->returnValue(false));
@@ -65,7 +65,7 @@ public function testSelectGlobal()
$sm->selectGlobal();
}
- public function testSelectShard()
+ public function testSelectShard() : void
{
$conn = $this->createConnection(['sharding' => ['federationName' => 'abc', 'distributionKey' => 'foo', 'distributionType' => 'integer']]);
$conn->expects($this->at(1))->method('isTransactionActive')->will($this->returnValue(true));
@@ -79,28 +79,17 @@ public function testSelectShard()
self::assertEquals(1234, $sm->getCurrentDistributionValue());
}
- public function testSelectShardNoDistributionValue()
- {
- $conn = $this->createConnection(['sharding' => ['federationName' => 'abc', 'distributionKey' => 'foo', 'distributionType' => 'integer']]);
- $conn->expects($this->at(1))->method('isTransactionActive')->will($this->returnValue(false));
-
- $this->expectException(ShardingException::class);
- $this->expectExceptionMessage('You have to specify a string or integer as shard distribution value.');
-
- $sm = new SQLAzureShardManager($conn);
- $sm->selectShard(null);
- }
-
/**
* @param mixed[] $params
*/
- private function createConnection(array $params)
+ private function createConnection(array $params) : Connection
{
$conn = $this->getMockBuilder(Connection::class)
- ->setMethods(['getParams', 'exec', 'isTransactionActive'])
+ ->onlyMethods(['getParams', 'exec', 'isTransactionActive'])
->disableOriginalConstructor()
->getMock();
$conn->expects($this->at(0))->method('getParams')->will($this->returnValue($params));
+
return $conn;
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Sharding/ShardChoser/MultiTenantShardChoserTest.php b/tests/Doctrine/Tests/DBAL/Sharding/ShardChoser/MultiTenantShardChoserTest.php
index 0c78b5c1771..5b65deecc77 100644
--- a/tests/Doctrine/Tests/DBAL/Sharding/ShardChoser/MultiTenantShardChoserTest.php
+++ b/tests/Doctrine/Tests/DBAL/Sharding/ShardChoser/MultiTenantShardChoserTest.php
@@ -8,7 +8,7 @@
class MultiTenantShardChoserTest extends TestCase
{
- public function testPickShard()
+ public function testPickShard() : void
{
$choser = new MultiTenantShardChoser();
$conn = $this->createConnectionMock();
@@ -17,10 +17,10 @@ public function testPickShard()
self::assertEquals(2, $choser->pickShard(2, $conn));
}
- private function createConnectionMock()
+ private function createConnectionMock() : PoolingShardConnection
{
return $this->getMockBuilder(PoolingShardConnection::class)
- ->setMethods(['connect', 'getParams', 'fetchAll'])
+ ->onlyMethods(['connect', 'getParams', 'fetchAll'])
->disableOriginalConstructor()
->getMock();
}
diff --git a/tests/Doctrine/Tests/DBAL/StatementTest.php b/tests/Doctrine/Tests/DBAL/StatementTest.php
index 7f18b20936a..bb86e9cab3c 100644
--- a/tests/Doctrine/Tests/DBAL/StatementTest.php
+++ b/tests/Doctrine/Tests/DBAL/StatementTest.php
@@ -4,12 +4,12 @@
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\Connection as DriverConnection;
use Doctrine\DBAL\Logging\SQLLogger;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Statement;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
use Exception;
use PDOStatement;
@@ -25,24 +25,21 @@ class StatementTest extends DbalTestCase
/** @var PDOStatement */
private $pdoStatement;
- protected function setUp()
+ protected function setUp() : void
{
$this->pdoStatement = $this->getMockBuilder(PDOStatement::class)
- ->setMethods(['execute', 'bindParam', 'bindValue'])
+ ->onlyMethods(['execute', 'bindParam', 'bindValue'])
->getMock();
- $platform = new MockPlatform();
- $driverConnection = $this->createMock(DriverConnection::class);
+
+ $driverConnection = $this->createMock(DriverConnection::class);
$driverConnection->expects($this->any())
->method('prepare')
->will($this->returnValue($this->pdoStatement));
- $driver = $this->createMock(Driver::class);
- $constructorArgs = [
- ['platform' => $platform],
- $driver,
- ];
- $this->conn = $this->getMockBuilder(Connection::class)
- ->setConstructorArgs($constructorArgs)
+ $driver = $this->createMock(Driver::class);
+
+ $this->conn = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([[], $driver])
->getMock();
$this->conn->expects($this->atLeastOnce())
->method('getWrappedConnection')
@@ -58,7 +55,7 @@ protected function setUp()
->will($this->returnValue($driver));
}
- public function testExecuteCallsLoggerStartQueryWithParametersWhenValuesBound()
+ public function testExecuteCallsLoggerStartQueryWithParametersWhenValuesBound() : void
{
$name = 'foo';
$var = 'bar';
@@ -81,7 +78,7 @@ public function testExecuteCallsLoggerStartQueryWithParametersWhenValuesBound()
$statement->execute();
}
- public function testExecuteCallsLoggerStartQueryWithParametersWhenParamsPassedToExecute()
+ public function testExecuteCallsLoggerStartQueryWithParametersWhenParamsPassedToExecute() : void
{
$name = 'foo';
$var = 'bar';
@@ -102,7 +99,7 @@ public function testExecuteCallsLoggerStartQueryWithParametersWhenParamsPassedTo
$statement->execute($values);
}
- public function testExecuteCallsStartQueryWithTheParametersBoundViaBindParam()
+ public function testExecuteCallsStartQueryWithTheParametersBoundViaBindParam() : void
{
$name = 'foo';
$var = 'bar';
@@ -124,10 +121,7 @@ public function testExecuteCallsStartQueryWithTheParametersBoundViaBindParam()
$statement->execute();
}
- /**
- * @expectedException \Doctrine\DBAL\DBALException
- */
- public function testExecuteCallsLoggerStopQueryOnException()
+ public function testExecuteCallsLoggerStopQueryOnException() : void
{
$logger = $this->createMock(SQLLogger::class);
@@ -151,6 +145,9 @@ public function testExecuteCallsLoggerStopQueryOnException()
->will($this->throwException(new Exception('Mock test exception')));
$statement = new Statement('', $this->conn);
+
+ $this->expectException(DBALException::class);
+
$statement->execute();
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Tools/Console/RunSqlCommandTest.php b/tests/Doctrine/Tests/DBAL/Tools/Console/RunSqlCommandTest.php
index a85efd0a88c..202748be6d8 100644
--- a/tests/Doctrine/Tests/DBAL/Tools/Console/RunSqlCommandTest.php
+++ b/tests/Doctrine/Tests/DBAL/Tools/Console/RunSqlCommandTest.php
@@ -21,7 +21,7 @@ class RunSqlCommandTest extends TestCase
/** @var Connection */
private $connectionMock;
- protected function setUp()
+ protected function setUp() : void
{
$application = new Application();
$application->add(new RunSqlCommand());
@@ -39,7 +39,7 @@ protected function setUp()
$this->command->setHelperSet($helperSet);
}
- public function testMissingSqlArgument()
+ public function testMissingSqlArgument() : void
{
try {
$this->commandTester->execute([
@@ -48,11 +48,11 @@ public function testMissingSqlArgument()
]);
$this->fail('Expected a runtime exception when omitting sql argument');
} catch (RuntimeException $e) {
- self::assertContains("Argument 'SQL", $e->getMessage());
+ self::assertStringContainsString("Argument 'SQL", $e->getMessage());
}
}
- public function testIncorrectDepthOption()
+ public function testIncorrectDepthOption() : void
{
try {
$this->commandTester->execute([
@@ -62,24 +62,25 @@ public function testIncorrectDepthOption()
]);
$this->fail('Expected a logic exception when executing with a stringy depth');
} catch (LogicException $e) {
- self::assertContains("Option 'depth'", $e->getMessage());
+ self::assertStringContainsString("Option 'depth'", $e->getMessage());
}
}
- public function testSelectStatementsPrintsResult()
+ public function testSelectStatementsPrintsResult() : void
{
$this->expectConnectionFetchAll();
- $this->commandTester->execute([
+ $exitCode = $this->commandTester->execute([
'command' => $this->command->getName(),
'sql' => 'SELECT 1',
]);
+ $this->assertSame(0, $exitCode);
self::assertRegExp('@int.*1.*@', $this->commandTester->getDisplay());
self::assertRegExp('@array.*1.*@', $this->commandTester->getDisplay());
}
- public function testUpdateStatementsPrintsAffectedLines()
+ public function testUpdateStatementsPrintsAffectedLines() : void
{
$this->expectConnectionExecuteUpdate();
@@ -92,7 +93,7 @@ public function testUpdateStatementsPrintsAffectedLines()
self::assertNotRegExp('@array.*1.*@', $this->commandTester->getDisplay());
}
- private function expectConnectionExecuteUpdate()
+ private function expectConnectionExecuteUpdate() : void
{
$this->connectionMock
->expects($this->exactly(1))
@@ -102,7 +103,7 @@ private function expectConnectionExecuteUpdate()
->method('fetchAll');
}
- private function expectConnectionFetchAll()
+ private function expectConnectionFetchAll() : void
{
$this->connectionMock
->expects($this->exactly(0))
@@ -112,7 +113,7 @@ private function expectConnectionFetchAll()
->method('fetchAll');
}
- public function testStatementsWithFetchResultPrintsResult()
+ public function testStatementsWithFetchResultPrintsResult() : void
{
$this->expectConnectionFetchAll();
diff --git a/tests/Doctrine/Tests/DBAL/Tools/DumperTest.php b/tests/Doctrine/Tests/DBAL/Tools/DumperTest.php
index 2aae261561f..ba99024231b 100644
--- a/tests/Doctrine/Tests/DBAL/Tools/DumperTest.php
+++ b/tests/Doctrine/Tests/DBAL/Tools/DumperTest.php
@@ -16,7 +16,7 @@
class DumperTest extends DbalTestCase
{
- public function testExportObject()
+ public function testExportObject() : void
{
$obj = new stdClass();
$obj->foo = 'bar';
@@ -26,7 +26,7 @@ public function testExportObject()
self::assertEquals('stdClass', $var->__CLASS__);
}
- public function testExportObjectWithReference()
+ public function testExportObjectWithReference() : void
{
$foo = 'bar';
$bar = ['foo' => & $foo];
@@ -39,7 +39,7 @@ public function testExportObjectWithReference()
self::assertEquals('tab', $bar['foo']);
}
- public function testExportArray()
+ public function testExportArray() : void
{
$array = ['a' => 'b', 'b' => ['c', 'd' => ['e', 'f']]];
$var = Dumper::export($array, 2);
@@ -48,7 +48,7 @@ public function testExportArray()
self::assertEquals($expected, $var);
}
- public function testExportDateTime()
+ public function testExportDateTime() : void
{
$obj = new DateTime('2010-10-10 10:10:10', new DateTimeZone('UTC'));
@@ -57,7 +57,7 @@ public function testExportDateTime()
self::assertEquals('2010-10-10T10:10:10+00:00', $var->date);
}
- public function testExportDateTimeImmutable()
+ public function testExportDateTimeImmutable() : void
{
$obj = new DateTimeImmutable('2010-10-10 10:10:10', new DateTimeZone('UTC'));
@@ -66,7 +66,7 @@ public function testExportDateTimeImmutable()
self::assertEquals('2010-10-10T10:10:10+00:00', $var->date);
}
- public function testExportDateTimeZone()
+ public function testExportDateTimeZone() : void
{
$obj = new DateTimeImmutable('2010-10-10 12:34:56', new DateTimeZone('Europe/Rome'));
@@ -75,7 +75,7 @@ public function testExportDateTimeZone()
self::assertEquals('2010-10-10T12:34:56+02:00', $var->date);
}
- public function testExportArrayTraversable()
+ public function testExportArrayTraversable() : void
{
$obj = new ArrayObject(['foobar']);
@@ -93,7 +93,7 @@ public function testExportArrayTraversable()
*
* @dataProvider provideAttributesCases
*/
- public function testExportParentAttributes(TestAsset\ParentClass $class, array $expected)
+ public function testExportParentAttributes(TestAsset\ParentClass $class, array $expected) : void
{
$print_r_class = print_r($class, true);
$print_r_expected = print_r($expected, true);
@@ -110,7 +110,10 @@ public function testExportParentAttributes(TestAsset\ParentClass $class, array $
self::assertSame($expected, $var);
}
- public function provideAttributesCases()
+ /**
+ * @return mixed[][]
+ */
+ public static function provideAttributesCases() : iterable
{
return [
'different-attributes' => [
diff --git a/tests/Doctrine/Tests/DBAL/Types/ArrayTest.php b/tests/Doctrine/Tests/DBAL/Types/ArrayTest.php
index ecb4155f74f..bc6ab4d413f 100644
--- a/tests/Doctrine/Tests/DBAL/Types/ArrayTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/ArrayTest.php
@@ -3,50 +3,45 @@
namespace Doctrine\Tests\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;
+use Doctrine\DBAL\Types\ArrayType;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
use function serialize;
class ArrayTest extends DbalTestCase
{
- /** @var AbstractPlatform */
+ /** @var AbstractPlatform|MockObject */
private $platform;
- /** @var Type */
+ /** @var ArrayType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('array');
}
- public function testArrayConvertsToDatabaseValue()
+ public function testArrayConvertsToDatabaseValue() : void
{
- self::assertInternalType(
- 'string',
- $this->type->convertToDatabaseValue([], $this->platform)
- );
+ self::assertIsString($this->type->convertToDatabaseValue([], $this->platform));
}
- public function testArrayConvertsToPHPValue()
+ public function testArrayConvertsToPHPValue() : void
{
- self::assertInternalType(
- 'array',
- $this->type->convertToPHPValue(serialize([]), $this->platform)
- );
+ self::assertIsArray($this->type->convertToPHPValue(serialize([]), $this->platform));
}
- public function testConversionFailure()
+ public function testConversionFailure() : void
{
$this->expectException(ConversionException::class);
$this->expectExceptionMessage("Could not convert database value to 'array' as an error was triggered by the unserialization: 'unserialize(): Error at offset 0 of 7 bytes'");
$this->type->convertToPHPValue('abcdefg', $this->platform);
}
- public function testNullConversion()
+ public function testNullConversion() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
@@ -54,7 +49,7 @@ public function testNullConversion()
/**
* @group DBAL-73
*/
- public function testFalseConversion()
+ public function testFalseConversion() : void
{
self::assertFalse($this->type->convertToPHPValue(serialize(false), $this->platform));
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/BaseDateTypeTestCase.php b/tests/Doctrine/Tests/DBAL/Types/BaseDateTypeTestCase.php
index 8140cf6d109..5f5b412e249 100644
--- a/tests/Doctrine/Tests/DBAL/Types/BaseDateTypeTestCase.php
+++ b/tests/Doctrine/Tests/DBAL/Types/BaseDateTypeTestCase.php
@@ -4,9 +4,10 @@
use DateTime;
use DateTimeImmutable;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use stdClass;
use function date_default_timezone_get;
@@ -14,7 +15,7 @@
abstract class BaseDateTypeTestCase extends TestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
protected $platform;
/** @var Type */
@@ -26,9 +27,9 @@ abstract class BaseDateTypeTestCase extends TestCase
/**
* {@inheritDoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->getMockForAbstractClass(AbstractPlatform::class);
$this->currentTimezone = date_default_timezone_get();
self::assertInstanceOf(Type::class, $this->type);
@@ -37,14 +38,14 @@ protected function setUp()
/**
* {@inheritDoc}
*/
- protected function tearDown()
+ protected function tearDown() : void
{
date_default_timezone_set($this->currentTimezone);
}
- public function testDateConvertsToDatabaseValue()
+ public function testDateConvertsToDatabaseValue() : void
{
- self::assertInternalType('string', $this->type->convertToDatabaseValue(new DateTime(), $this->platform));
+ self::assertIsString($this->type->convertToDatabaseValue(new DateTime(), $this->platform));
}
/**
@@ -52,19 +53,19 @@ public function testDateConvertsToDatabaseValue()
*
* @dataProvider invalidPHPValuesProvider
*/
- public function testInvalidTypeConversionToDatabaseValue($value)
+ public function testInvalidTypeConversionToDatabaseValue($value) : void
{
$this->expectException(ConversionException::class);
$this->type->convertToDatabaseValue($value, $this->platform);
}
- public function testNullConversion()
+ public function testNullConversion() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testConvertDateTimeToPHPValue()
+ public function testConvertDateTimeToPHPValue() : void
{
$date = new DateTime('now');
@@ -78,7 +79,7 @@ public function testConvertDateTimeToPHPValue()
* by @see \Doctrine\DBAL\Types\DateTimeImmutableType, previous DBAL versions handled it just fine.
* This test is just in place to prevent further regressions, even if the type is being misused
*/
- public function testConvertDateTimeImmutableToPHPValue()
+ public function testConvertDateTimeImmutableToPHPValue() : void
{
$date = new DateTimeImmutable('now');
@@ -92,18 +93,15 @@ public function testConvertDateTimeImmutableToPHPValue()
* by @see \Doctrine\DBAL\Types\DateTimeImmutableType, previous DBAL versions handled it just fine.
* This test is just in place to prevent further regressions, even if the type is being misused
*/
- public function testDateTimeImmutableConvertsToDatabaseValue()
+ public function testDateTimeImmutableConvertsToDatabaseValue() : void
{
- self::assertInternalType(
- 'string',
- $this->type->convertToDatabaseValue(new DateTimeImmutable(), $this->platform)
- );
+ self::assertIsString($this->type->convertToDatabaseValue(new DateTimeImmutable(), $this->platform));
}
/**
* @return mixed[][]
*/
- public function invalidPHPValuesProvider()
+ public static function invalidPHPValuesProvider() : iterable
{
return [
[0],
@@ -113,7 +111,6 @@ public function invalidPHPValuesProvider()
['2015-01-31'],
['2015-01-31 10:11:12'],
[new stdClass()],
- [$this],
[27],
[-1],
[1.2],
diff --git a/tests/Doctrine/Tests/DBAL/Types/BinaryTest.php b/tests/Doctrine/Tests/DBAL/Types/BinaryTest.php
index fbcf5fb9357..fceeee557b8 100644
--- a/tests/Doctrine/Tests/DBAL/Types/BinaryTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/BinaryTest.php
@@ -3,17 +3,20 @@
namespace Doctrine\Tests\DBAL\Types;
use Doctrine\DBAL\ParameterType;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\BinaryType;
+use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
+use Doctrine\DBAL\Types\Types;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
use function base64_encode;
use function fopen;
use function stream_get_contents;
class BinaryTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
protected $platform;
/** @var BinaryType */
@@ -22,42 +25,46 @@ class BinaryTest extends DbalTestCase
/**
* {@inheritdoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('binary');
}
- public function testReturnsBindingType()
+ public function testReturnsBindingType() : void
{
self::assertSame(ParameterType::BINARY, $this->type->getBindingType());
}
- public function testReturnsName()
+ public function testReturnsName() : void
{
- self::assertSame(Type::BINARY, $this->type->getName());
+ self::assertSame(Types::BINARY, $this->type->getName());
}
- public function testReturnsSQLDeclaration()
+ public function testReturnsSQLDeclaration() : void
{
- self::assertSame('DUMMYBINARY', $this->type->getSQLDeclaration([], $this->platform));
+ $this->platform->expects($this->once())
+ ->method('getBinaryTypeDeclarationSQL')
+ ->willReturn('TEST_BINARY');
+
+ self::assertSame('TEST_BINARY', $this->type->getSQLDeclaration([], $this->platform));
}
- public function testBinaryNullConvertsToPHPValue()
+ public function testBinaryNullConvertsToPHPValue() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testBinaryStringConvertsToPHPValue()
+ public function testBinaryStringConvertsToPHPValue() : void
{
$databaseValue = 'binary string';
$phpValue = $this->type->convertToPHPValue($databaseValue, $this->platform);
- self::assertInternalType('resource', $phpValue);
+ self::assertIsResource($phpValue);
self::assertEquals($databaseValue, stream_get_contents($phpValue));
}
- public function testBinaryResourceConvertsToPHPValue()
+ public function testBinaryResourceConvertsToPHPValue() : void
{
$databaseValue = fopen('data://text/plain;base64,' . base64_encode('binary string'), 'r');
$phpValue = $this->type->convertToPHPValue($databaseValue, $this->platform);
@@ -66,15 +73,21 @@ public function testBinaryResourceConvertsToPHPValue()
}
/**
+ * @param mixed $value
+ *
* @dataProvider getInvalidDatabaseValues
- * @expectedException \Doctrine\DBAL\Types\ConversionException
*/
- public function testThrowsConversionExceptionOnInvalidDatabaseValue($value)
+ public function testThrowsConversionExceptionOnInvalidDatabaseValue($value) : void
{
+ $this->expectException(ConversionException::class);
+
$this->type->convertToPHPValue($value, $this->platform);
}
- public function getInvalidDatabaseValues()
+ /**
+ * @return mixed[][]
+ */
+ public static function getInvalidDatabaseValues() : iterable
{
return [
[false],
diff --git a/tests/Doctrine/Tests/DBAL/Types/BlobTest.php b/tests/Doctrine/Tests/DBAL/Types/BlobTest.php
index 5500836cfdb..194d26af0b8 100644
--- a/tests/Doctrine/Tests/DBAL/Types/BlobTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/BlobTest.php
@@ -2,10 +2,11 @@
namespace Doctrine\Tests\DBAL\Types;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\BlobType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
use function base64_encode;
use function chr;
use function fopen;
@@ -13,7 +14,7 @@
class BlobTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
protected $platform;
/** @var BlobType */
@@ -22,27 +23,27 @@ class BlobTest extends DbalTestCase
/**
* {@inheritdoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('blob');
}
- public function testBlobNullConvertsToPHPValue()
+ public function testBlobNullConvertsToPHPValue() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testBinaryStringConvertsToPHPValue()
+ public function testBinaryStringConvertsToPHPValue() : void
{
$databaseValue = $this->getBinaryString();
$phpValue = $this->type->convertToPHPValue($databaseValue, $this->platform);
- self::assertInternalType('resource', $phpValue);
+ self::assertIsResource($phpValue);
self::assertSame($databaseValue, stream_get_contents($phpValue));
}
- public function testBinaryResourceConvertsToPHPValue()
+ public function testBinaryResourceConvertsToPHPValue() : void
{
$databaseValue = fopen('data://text/plain;base64,' . base64_encode($this->getBinaryString()), 'r');
$phpValue = $this->type->convertToPHPValue($databaseValue, $this->platform);
@@ -52,10 +53,8 @@ public function testBinaryResourceConvertsToPHPValue()
/**
* Creates a binary string containing all possible byte values.
- *
- * @return string
*/
- private function getBinaryString()
+ private function getBinaryString() : string
{
$string = '';
diff --git a/tests/Doctrine/Tests/DBAL/Types/BooleanTest.php b/tests/Doctrine/Tests/DBAL/Types/BooleanTest.php
index a7e3377107a..b5e25c2a77b 100644
--- a/tests/Doctrine/Tests/DBAL/Types/BooleanTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/BooleanTest.php
@@ -2,35 +2,37 @@
namespace Doctrine\Tests\DBAL\Types;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
+use Doctrine\DBAL\Types\BooleanType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
class BooleanTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
private $platform;
- /** @var Type */
+ /** @var BooleanType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->getMockForAbstractClass(AbstractPlatform::class);
$this->type = Type::getType('boolean');
}
- public function testBooleanConvertsToDatabaseValue()
+ public function testBooleanConvertsToDatabaseValue() : void
{
- self::assertInternalType('integer', $this->type->convertToDatabaseValue(1, $this->platform));
+ self::assertIsInt($this->type->convertToDatabaseValue(1, $this->platform));
}
- public function testBooleanConvertsToPHPValue()
+ public function testBooleanConvertsToPHPValue() : void
{
- self::assertInternalType('bool', $this->type->convertToPHPValue(0, $this->platform));
+ self::assertIsBool($this->type->convertToPHPValue(0, $this->platform));
}
- public function testBooleanNullConvertsToPHPValue()
+ public function testBooleanNullConvertsToPHPValue() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/ConversionExceptionTest.php b/tests/Doctrine/Tests/DBAL/Types/ConversionExceptionTest.php
index f0183ef854c..e7fa8a4be03 100644
--- a/tests/Doctrine/Tests/DBAL/Types/ConversionExceptionTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/ConversionExceptionTest.php
@@ -15,7 +15,7 @@ class ConversionExceptionTest extends TestCase
*
* @dataProvider scalarsProvider
*/
- public function testConversionFailedInvalidTypeWithScalar($scalarValue)
+ public function testConversionFailedInvalidTypeWithScalar($scalarValue) : void
{
$exception = ConversionException::conversionFailedInvalidType($scalarValue, 'foo', ['bar', 'baz']);
@@ -26,12 +26,13 @@ public function testConversionFailedInvalidTypeWithScalar($scalarValue)
$exception->getMessage()
);
}
+
/**
* @param mixed $nonScalar
*
* @dataProvider nonScalarsProvider
*/
- public function testConversionFailedInvalidTypeWithNonScalar($nonScalar)
+ public function testConversionFailedInvalidTypeWithNonScalar($nonScalar) : void
{
$exception = ConversionException::conversionFailedInvalidType($nonScalar, 'foo', ['bar', 'baz']);
@@ -43,7 +44,7 @@ public function testConversionFailedInvalidTypeWithNonScalar($nonScalar)
);
}
- public function testConversionFailedFormatPreservesPreviousException()
+ public function testConversionFailedFormatPreservesPreviousException() : void
{
$previous = new Exception();
@@ -56,13 +57,12 @@ public function testConversionFailedFormatPreservesPreviousException()
/**
* @return mixed[][]
*/
- public function nonScalarsProvider()
+ public static function nonScalarsProvider() : iterable
{
return [
[[]],
[['foo']],
[null],
- [$this],
[new stdClass()],
[tmpfile()],
];
@@ -71,7 +71,7 @@ public function nonScalarsProvider()
/**
* @return mixed[][]
*/
- public function scalarsProvider()
+ public static function scalarsProvider() : iterable
{
return [
[''],
diff --git a/tests/Doctrine/Tests/DBAL/Types/DateImmutableTypeTest.php b/tests/Doctrine/Tests/DBAL/Types/DateImmutableTypeTest.php
index 5fd15d812d3..d023e6bc1ba 100644
--- a/tests/Doctrine/Tests/DBAL/Types/DateImmutableTypeTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/DateImmutableTypeTest.php
@@ -9,104 +9,113 @@
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateImmutableType;
use Doctrine\DBAL\Types\Type;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
-use Prophecy\Prophecy\ObjectProphecy;
use function get_class;
class DateImmutableTypeTest extends TestCase
{
- /** @var AbstractPlatform|ObjectProphecy */
+ /** @var AbstractPlatform|MockObject */
private $platform;
/** @var DateImmutableType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
$this->type = Type::getType('date_immutable');
- $this->platform = $this->prophesize(AbstractPlatform::class);
+ $this->platform = $this->createMock(AbstractPlatform::class);
}
- public function testFactoryCreatesCorrectType()
+ public function testFactoryCreatesCorrectType() : void
{
self::assertSame(DateImmutableType::class, get_class($this->type));
}
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('date_immutable', $this->type->getName());
}
- public function testReturnsBindingType()
+ public function testReturnsBindingType() : void
{
self::assertSame(ParameterType::STRING, $this->type->getBindingType());
}
- public function testConvertsDateTimeImmutableInstanceToDatabaseValue()
+ public function testConvertsDateTimeImmutableInstanceToDatabaseValue() : void
{
- $date = $this->prophesize(DateTimeImmutable::class);
+ $date = $this->createMock(DateTimeImmutable::class);
- $this->platform->getDateFormatString()->willReturn('Y-m-d')->shouldBeCalled();
- $date->format('Y-m-d')->willReturn('2016-01-01')->shouldBeCalled();
+ $this->platform->expects($this->once())
+ ->method('getDateFormatString')
+ ->willReturn('Y-m-d');
+ $date->expects($this->once())
+ ->method('format')
+ ->with('Y-m-d')
+ ->willReturn('2016-01-01');
self::assertSame(
'2016-01-01',
- $this->type->convertToDatabaseValue($date->reveal(), $this->platform->reveal())
+ $this->type->convertToDatabaseValue($date, $this->platform)
);
}
- public function testConvertsNullToDatabaseValue()
+ public function testConvertsNullToDatabaseValue() : void
{
- self::assertNull($this->type->convertToDatabaseValue(null, $this->platform->reveal()));
+ self::assertNull($this->type->convertToDatabaseValue(null, $this->platform));
}
- public function testDoesNotSupportMutableDateTimeToDatabaseValueConversion()
+ public function testDoesNotSupportMutableDateTimeToDatabaseValueConversion() : void
{
$this->expectException(ConversionException::class);
- $this->type->convertToDatabaseValue(new DateTime(), $this->platform->reveal());
+ $this->type->convertToDatabaseValue(new DateTime(), $this->platform);
}
- public function testConvertsDateTimeImmutableInstanceToPHPValue()
+ public function testConvertsDateTimeImmutableInstanceToPHPValue() : void
{
$date = new DateTimeImmutable();
- self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform->reveal()));
+ self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform));
}
- public function testConvertsNullToPHPValue()
+ public function testConvertsNullToPHPValue() : void
{
- self::assertNull($this->type->convertToPHPValue(null, $this->platform->reveal()));
+ self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testConvertsDateStringToPHPValue()
+ public function testConvertsDateStringToPHPValue() : void
{
- $this->platform->getDateFormatString()->willReturn('Y-m-d')->shouldBeCalled();
+ $this->platform->expects($this->once())
+ ->method('getDateFormatString')
+ ->willReturn('Y-m-d');
- $date = $this->type->convertToPHPValue('2016-01-01', $this->platform->reveal());
+ $date = $this->type->convertToPHPValue('2016-01-01', $this->platform);
self::assertInstanceOf(DateTimeImmutable::class, $date);
self::assertSame('2016-01-01', $date->format('Y-m-d'));
}
- public function testResetTimeFractionsWhenConvertingToPHPValue()
+ public function testResetTimeFractionsWhenConvertingToPHPValue() : void
{
- $this->platform->getDateFormatString()->willReturn('Y-m-d');
+ $this->platform->expects($this->any())
+ ->method('getDateFormatString')
+ ->willReturn('Y-m-d');
- $date = $this->type->convertToPHPValue('2016-01-01', $this->platform->reveal());
+ $date = $this->type->convertToPHPValue('2016-01-01', $this->platform);
self::assertSame('2016-01-01 00:00:00.000000', $date->format('Y-m-d H:i:s.u'));
}
- public function testThrowsExceptionDuringConversionToPHPValueWithInvalidDateString()
+ public function testThrowsExceptionDuringConversionToPHPValueWithInvalidDateString() : void
{
$this->expectException(ConversionException::class);
- $this->type->convertToPHPValue('invalid date string', $this->platform->reveal());
+ $this->type->convertToPHPValue('invalid date string', $this->platform);
}
- public function testRequiresSQLCommentHint()
+ public function testRequiresSQLCommentHint() : void
{
- self::assertTrue($this->type->requiresSQLCommentHint($this->platform->reveal()));
+ self::assertTrue($this->type->requiresSQLCommentHint($this->platform));
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/DateIntervalTest.php b/tests/Doctrine/Tests/DBAL/Types/DateIntervalTest.php
index 27d83ae7df7..7b2c09aca9f 100644
--- a/tests/Doctrine/Tests/DBAL/Types/DateIntervalTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/DateIntervalTest.php
@@ -4,16 +4,17 @@
use DateInterval;
use DateTime;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateIntervalType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
use stdClass;
final class DateIntervalTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
private $platform;
/** @var DateIntervalType */
@@ -24,7 +25,7 @@ final class DateIntervalTest extends DbalTestCase
*/
protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('dateinterval');
self::assertInstanceOf(DateIntervalType::class, $this->type);
@@ -102,6 +103,8 @@ public function testRequiresSQLCommentHint() : void
}
/**
+ * @param mixed $value
+ *
* @dataProvider invalidPHPValuesProvider
*/
public function testInvalidTypeConversionToDatabaseValue($value) : void
@@ -114,7 +117,7 @@ public function testInvalidTypeConversionToDatabaseValue($value) : void
/**
* @return mixed[][]
*/
- public function invalidPHPValuesProvider() : array
+ public static function invalidPHPValuesProvider() : iterable
{
return [
[0],
@@ -124,7 +127,6 @@ public function invalidPHPValuesProvider() : array
['2015-01-31'],
['2015-01-31 10:11:12'],
[new stdClass()],
- [$this],
[27],
[-1],
[1.2],
diff --git a/tests/Doctrine/Tests/DBAL/Types/DateTest.php b/tests/Doctrine/Tests/DBAL/Types/DateTest.php
index a8c7327b337..73e426ea41c 100644
--- a/tests/Doctrine/Tests/DBAL/Types/DateTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/DateTest.php
@@ -12,14 +12,14 @@ class DateTest extends BaseDateTypeTestCase
/**
* {@inheritDoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
$this->type = Type::getType('date');
parent::setUp();
}
- public function testDateConvertsToPHPValue()
+ public function testDateConvertsToPHPValue() : void
{
// Birthday of jwage and also birthday of Doctrine. Send him a present ;)
self::assertInstanceOf(
@@ -28,14 +28,14 @@ public function testDateConvertsToPHPValue()
);
}
- public function testDateResetsNonDatePartsToZeroUnixTimeValues()
+ public function testDateResetsNonDatePartsToZeroUnixTimeValues() : void
{
$date = $this->type->convertToPHPValue('1985-09-01', $this->platform);
self::assertEquals('00:00:00', $date->format('H:i:s'));
}
- public function testDateRestsSummerTimeAffection()
+ public function testDateRestsSummerTimeAffection() : void
{
date_default_timezone_set('Europe/Berlin');
@@ -48,7 +48,7 @@ public function testDateRestsSummerTimeAffection()
self::assertEquals('2009-11-01', $date->format('Y-m-d'));
}
- public function testInvalidDateFormatConversion()
+ public function testInvalidDateFormatConversion() : void
{
$this->expectException(ConversionException::class);
$this->type->convertToPHPValue('abcdefg', $this->platform);
diff --git a/tests/Doctrine/Tests/DBAL/Types/DateTimeImmutableTypeTest.php b/tests/Doctrine/Tests/DBAL/Types/DateTimeImmutableTypeTest.php
index dfedcca32b1..6ace4b4c4e8 100644
--- a/tests/Doctrine/Tests/DBAL/Types/DateTimeImmutableTypeTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/DateTimeImmutableTypeTest.php
@@ -9,81 +9,88 @@
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeImmutableType;
use Doctrine\DBAL\Types\Type;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
-use Prophecy\Prophecy\ObjectProphecy;
use function get_class;
class DateTimeImmutableTypeTest extends TestCase
{
- /** @var AbstractPlatform|ObjectProphecy */
+ /** @var AbstractPlatform|MockObject */
private $platform;
/** @var DateTimeImmutableType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
$this->type = Type::getType('datetime_immutable');
- $this->platform = $this->prophesize(AbstractPlatform::class);
+ $this->platform = $this->getMockBuilder(AbstractPlatform::class)->getMock();
}
- public function testFactoryCreatesCorrectType()
+ public function testFactoryCreatesCorrectType() : void
{
self::assertSame(DateTimeImmutableType::class, get_class($this->type));
}
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('datetime_immutable', $this->type->getName());
}
- public function testReturnsBindingType()
+ public function testReturnsBindingType() : void
{
self::assertSame(ParameterType::STRING, $this->type->getBindingType());
}
- public function testConvertsDateTimeImmutableInstanceToDatabaseValue()
+ public function testConvertsDateTimeImmutableInstanceToDatabaseValue() : void
{
- $date = $this->prophesize(DateTimeImmutable::class);
+ $date = $this->getMockBuilder(DateTimeImmutable::class)->getMock();
- $this->platform->getDateTimeFormatString()->willReturn('Y-m-d H:i:s')->shouldBeCalled();
- $date->format('Y-m-d H:i:s')->willReturn('2016-01-01 15:58:59')->shouldBeCalled();
+ $this->platform->expects($this->once())
+ ->method('getDateTimeFormatString')
+ ->willReturn('Y-m-d H:i:s');
+ $date->expects($this->once())
+ ->method('format')
+ ->with('Y-m-d H:i:s')
+ ->willReturn('2016-01-01 15:58:59');
self::assertSame(
'2016-01-01 15:58:59',
- $this->type->convertToDatabaseValue($date->reveal(), $this->platform->reveal())
+ $this->type->convertToDatabaseValue($date, $this->platform)
);
}
- public function testConvertsNullToDatabaseValue()
+ public function testConvertsNullToDatabaseValue() : void
{
- self::assertNull($this->type->convertToDatabaseValue(null, $this->platform->reveal()));
+ self::assertNull($this->type->convertToDatabaseValue(null, $this->platform));
}
- public function testDoesNotSupportMutableDateTimeToDatabaseValueConversion()
+ public function testDoesNotSupportMutableDateTimeToDatabaseValueConversion() : void
{
$this->expectException(ConversionException::class);
- $this->type->convertToDatabaseValue(new DateTime(), $this->platform->reveal());
+ $this->type->convertToDatabaseValue(new DateTime(), $this->platform);
}
- public function testConvertsDateTimeImmutableInstanceToPHPValue()
+ public function testConvertsDateTimeImmutableInstanceToPHPValue() : void
{
$date = new DateTimeImmutable();
- self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform->reveal()));
+ self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform));
}
- public function testConvertsNullToPHPValue()
+ public function testConvertsNullToPHPValue() : void
{
- self::assertNull($this->type->convertToPHPValue(null, $this->platform->reveal()));
+ self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testConvertsDateTimeStringToPHPValue()
+ public function testConvertsDateTimeStringToPHPValue() : void
{
- $this->platform->getDateTimeFormatString()->willReturn('Y-m-d H:i:s')->shouldBeCalled();
+ $this->platform->expects($this->once())
+ ->method('getDateTimeFormatString')
+ ->willReturn('Y-m-d H:i:s');
- $date = $this->type->convertToPHPValue('2016-01-01 15:58:59', $this->platform->reveal());
+ $date = $this->type->convertToPHPValue('2016-01-01 15:58:59', $this->platform);
self::assertInstanceOf(DateTimeImmutable::class, $date);
self::assertSame('2016-01-01 15:58:59', $date->format('Y-m-d H:i:s'));
@@ -92,24 +99,30 @@ public function testConvertsDateTimeStringToPHPValue()
/**
* @group DBAL-415
*/
- public function testConvertsDateTimeStringWithMicrosecondsToPHPValue()
+ public function testConvertsDateTimeStringWithMicrosecondsToPHPValue() : void
{
- $this->platform->getDateTimeFormatString()->willReturn('Y-m-d H:i:s');
+ $this->platform->expects($this->any())
+ ->method('getDateTimeFormatString')
+ ->willReturn('Y-m-d H:i:s');
- $date = $this->type->convertToPHPValue('2016-01-01 15:58:59.123456', $this->platform->reveal());
+ $date = $this->type->convertToPHPValue('2016-01-01 15:58:59.123456', $this->platform);
self::assertSame('2016-01-01 15:58:59', $date->format('Y-m-d H:i:s'));
}
- public function testThrowsExceptionDuringConversionToPHPValueWithInvalidDateTimeString()
+ public function testThrowsExceptionDuringConversionToPHPValueWithInvalidDateTimeString() : void
{
+ $this->platform->expects($this->atLeastOnce())
+ ->method('getDateTimeFormatString')
+ ->willReturn('Y-m-d H:i:s');
+
$this->expectException(ConversionException::class);
- $this->type->convertToPHPValue('invalid datetime string', $this->platform->reveal());
+ $this->type->convertToPHPValue('invalid datetime string', $this->platform);
}
- public function testRequiresSQLCommentHint()
+ public function testRequiresSQLCommentHint() : void
{
- self::assertTrue($this->type->requiresSQLCommentHint($this->platform->reveal()));
+ self::assertTrue($this->type->requiresSQLCommentHint($this->platform));
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/DateTimeTest.php b/tests/Doctrine/Tests/DBAL/Types/DateTimeTest.php
index 7d571f80eb2..ba7a661c8d9 100644
--- a/tests/Doctrine/Tests/DBAL/Types/DateTimeTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/DateTimeTest.php
@@ -11,14 +11,14 @@ class DateTimeTest extends BaseDateTypeTestCase
/**
* {@inheritDoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
$this->type = Type::getType('datetime');
parent::setUp();
}
- public function testDateTimeConvertsToDatabaseValue()
+ public function testDateTimeConvertsToDatabaseValue() : void
{
$date = new DateTime('1985-09-01 10:10:10');
@@ -28,7 +28,7 @@ public function testDateTimeConvertsToDatabaseValue()
self::assertEquals($expected, $actual);
}
- public function testDateTimeConvertsToPHPValue()
+ public function testDateTimeConvertsToPHPValue() : void
{
// Birthday of jwage and also birthday of Doctrine. Send him a present ;)
$date = $this->type->convertToPHPValue('1985-09-01 00:00:00', $this->platform);
@@ -36,13 +36,13 @@ public function testDateTimeConvertsToPHPValue()
self::assertEquals('1985-09-01 00:00:00', $date->format('Y-m-d H:i:s'));
}
- public function testInvalidDateTimeFormatConversion()
+ public function testInvalidDateTimeFormatConversion() : void
{
$this->expectException(ConversionException::class);
$this->type->convertToPHPValue('abcdefg', $this->platform);
}
- public function testConvertsNonMatchingFormatToPhpValueWithParser()
+ public function testConvertsNonMatchingFormatToPhpValueWithParser() : void
{
$date = '1985/09/01 10:10:10.12345';
diff --git a/tests/Doctrine/Tests/DBAL/Types/DateTimeTzImmutableTypeTest.php b/tests/Doctrine/Tests/DBAL/Types/DateTimeTzImmutableTypeTest.php
index df47f7b3991..808dfaf50ed 100644
--- a/tests/Doctrine/Tests/DBAL/Types/DateTimeTzImmutableTypeTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/DateTimeTzImmutableTypeTest.php
@@ -9,95 +9,106 @@
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeTzImmutableType;
use Doctrine\DBAL\Types\Type;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
-use Prophecy\Prophecy\ObjectProphecy;
use function get_class;
class DateTimeTzImmutableTypeTest extends TestCase
{
- /** @var AbstractPlatform|ObjectProphecy */
+ /** @var AbstractPlatform|MockObject */
private $platform;
/** @var DateTimeTzImmutableType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
$this->type = Type::getType('datetimetz_immutable');
- $this->platform = $this->prophesize(AbstractPlatform::class);
+ $this->platform = $this->createMock(AbstractPlatform::class);
}
- public function testFactoryCreatesCorrectType()
+ public function testFactoryCreatesCorrectType() : void
{
self::assertSame(DateTimeTzImmutableType::class, get_class($this->type));
}
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('datetimetz_immutable', $this->type->getName());
}
- public function testReturnsBindingType()
+ public function testReturnsBindingType() : void
{
self::assertSame(ParameterType::STRING, $this->type->getBindingType());
}
- public function testConvertsDateTimeImmutableInstanceToDatabaseValue()
+ public function testConvertsDateTimeImmutableInstanceToDatabaseValue() : void
{
- $date = $this->prophesize(DateTimeImmutable::class);
+ $date = $this->createMock(DateTimeImmutable::class);
- $this->platform->getDateTimeTzFormatString()->willReturn('Y-m-d H:i:s T')->shouldBeCalled();
- $date->format('Y-m-d H:i:s T')->willReturn('2016-01-01 15:58:59 UTC')->shouldBeCalled();
+ $this->platform->expects($this->once())
+ ->method('getDateTimeTzFormatString')
+ ->willReturn('Y-m-d H:i:s T');
+ $date->expects($this->once())
+ ->method('format')
+ ->with('Y-m-d H:i:s T')
+ ->willReturn('2016-01-01 15:58:59 UTC');
self::assertSame(
'2016-01-01 15:58:59 UTC',
- $this->type->convertToDatabaseValue($date->reveal(), $this->platform->reveal())
+ $this->type->convertToDatabaseValue($date, $this->platform)
);
}
- public function testConvertsNullToDatabaseValue()
+ public function testConvertsNullToDatabaseValue() : void
{
- self::assertNull($this->type->convertToDatabaseValue(null, $this->platform->reveal()));
+ self::assertNull($this->type->convertToDatabaseValue(null, $this->platform));
}
- public function testDoesNotSupportMutableDateTimeToDatabaseValueConversion()
+ public function testDoesNotSupportMutableDateTimeToDatabaseValueConversion() : void
{
$this->expectException(ConversionException::class);
- $this->type->convertToDatabaseValue(new DateTime(), $this->platform->reveal());
+ $this->type->convertToDatabaseValue(new DateTime(), $this->platform);
}
- public function testConvertsDateTimeImmutableInstanceToPHPValue()
+ public function testConvertsDateTimeImmutableInstanceToPHPValue() : void
{
$date = new DateTimeImmutable();
- self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform->reveal()));
+ self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform));
}
- public function testConvertsNullToPHPValue()
+ public function testConvertsNullToPHPValue() : void
{
- self::assertNull($this->type->convertToPHPValue(null, $this->platform->reveal()));
+ self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testConvertsDateTimeWithTimezoneStringToPHPValue()
+ public function testConvertsDateTimeWithTimezoneStringToPHPValue() : void
{
- $this->platform->getDateTimeTzFormatString()->willReturn('Y-m-d H:i:s T')->shouldBeCalled();
+ $this->platform->expects($this->once())
+ ->method('getDateTimeTzFormatString')
+ ->willReturn('Y-m-d H:i:s T');
- $date = $this->type->convertToPHPValue('2016-01-01 15:58:59 UTC', $this->platform->reveal());
+ $date = $this->type->convertToPHPValue('2016-01-01 15:58:59 UTC', $this->platform);
self::assertInstanceOf(DateTimeImmutable::class, $date);
self::assertSame('2016-01-01 15:58:59 UTC', $date->format('Y-m-d H:i:s T'));
}
- public function testThrowsExceptionDuringConversionToPHPValueWithInvalidDateTimeWithTimezoneString()
+ public function testThrowsExceptionDuringConversionToPHPValueWithInvalidDateTimeWithTimezoneString() : void
{
+ $this->platform->expects($this->atLeastOnce())
+ ->method('getDateTimeTzFormatString')
+ ->willReturn('Y-m-d H:i:s T');
+
$this->expectException(ConversionException::class);
- $this->type->convertToPHPValue('invalid datetime with timezone string', $this->platform->reveal());
+ $this->type->convertToPHPValue('invalid datetime with timezone string', $this->platform);
}
- public function testRequiresSQLCommentHint()
+ public function testRequiresSQLCommentHint() : void
{
- self::assertTrue($this->type->requiresSQLCommentHint($this->platform->reveal()));
+ self::assertTrue($this->type->requiresSQLCommentHint($this->platform));
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/DateTimeTzTest.php b/tests/Doctrine/Tests/DBAL/Types/DateTimeTzTest.php
index 4b6c8fb208f..72ccaf87d05 100644
--- a/tests/Doctrine/Tests/DBAL/Types/DateTimeTzTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/DateTimeTzTest.php
@@ -11,14 +11,14 @@ class DateTimeTzTest extends BaseDateTypeTestCase
/**
* {@inheritDoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
$this->type = Type::getType('datetimetz');
parent::setUp();
}
- public function testDateTimeConvertsToDatabaseValue()
+ public function testDateTimeConvertsToDatabaseValue() : void
{
$date = new DateTime('1985-09-01 10:10:10');
@@ -28,7 +28,7 @@ public function testDateTimeConvertsToDatabaseValue()
self::assertEquals($expected, $actual);
}
- public function testDateTimeConvertsToPHPValue()
+ public function testDateTimeConvertsToPHPValue() : void
{
// Birthday of jwage and also birthday of Doctrine. Send him a present ;)
$date = $this->type->convertToPHPValue('1985-09-01 00:00:00', $this->platform);
@@ -36,7 +36,7 @@ public function testDateTimeConvertsToPHPValue()
self::assertEquals('1985-09-01 00:00:00', $date->format('Y-m-d H:i:s'));
}
- public function testInvalidDateFormatConversion()
+ public function testInvalidDateFormatConversion() : void
{
$this->expectException(ConversionException::class);
$this->type->convertToPHPValue('abcdefg', $this->platform);
diff --git a/tests/Doctrine/Tests/DBAL/Types/DecimalTest.php b/tests/Doctrine/Tests/DBAL/Types/DecimalTest.php
index 3d1164afbfb..1528dfd86d9 100644
--- a/tests/Doctrine/Tests/DBAL/Types/DecimalTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/DecimalTest.php
@@ -2,30 +2,32 @@
namespace Doctrine\Tests\DBAL\Types;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
+use Doctrine\DBAL\Types\DecimalType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
class DecimalTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
private $platform;
- /** @var Type */
+ /** @var DecimalType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('decimal');
}
- public function testDecimalConvertsToPHPValue()
+ public function testDecimalConvertsToPHPValue() : void
{
- self::assertInternalType('string', $this->type->convertToPHPValue('5.5', $this->platform));
+ self::assertIsString($this->type->convertToPHPValue('5.5', $this->platform));
}
- public function testDecimalNullConvertsToPHPValue()
+ public function testDecimalNullConvertsToPHPValue() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/FloatTest.php b/tests/Doctrine/Tests/DBAL/Types/FloatTest.php
index e68bf0bc46f..4934f716c0f 100644
--- a/tests/Doctrine/Tests/DBAL/Types/FloatTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/FloatTest.php
@@ -2,40 +2,42 @@
namespace Doctrine\Tests\DBAL\Types;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
+use Doctrine\DBAL\Types\FloatType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
class FloatTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
private $platform;
- /** @var Type */
+ /** @var FloatType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('float');
}
- public function testFloatConvertsToPHPValue()
+ public function testFloatConvertsToPHPValue() : void
{
- self::assertInternalType('float', $this->type->convertToPHPValue('5.5', $this->platform));
+ self::assertIsFloat($this->type->convertToPHPValue('5.5', $this->platform));
}
- public function testFloatNullConvertsToPHPValue()
+ public function testFloatNullConvertsToPHPValue() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testFloatConvertToDatabaseValue()
+ public function testFloatConvertToDatabaseValue() : void
{
- self::assertInternalType('float', $this->type->convertToDatabaseValue(5.5, $this->platform));
+ self::assertIsFloat($this->type->convertToDatabaseValue(5.5, $this->platform));
}
- public function testFloatNullConvertToDatabaseValue()
+ public function testFloatNullConvertToDatabaseValue() : void
{
self::assertNull($this->type->convertToDatabaseValue(null, $this->platform));
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/GuidTypeTest.php b/tests/Doctrine/Tests/DBAL/Types/GuidTypeTest.php
index 978cfd50fb7..df265d8541a 100644
--- a/tests/Doctrine/Tests/DBAL/Types/GuidTypeTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/GuidTypeTest.php
@@ -2,45 +2,45 @@
namespace Doctrine\Tests\DBAL\Types;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
+use Doctrine\DBAL\Types\GuidType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
-use function get_class;
+use PHPUnit\Framework\MockObject\MockObject;
class GuidTypeTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
private $platform;
- /** @var Type */
+ /** @var GuidType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('guid');
}
- public function testConvertToPHPValue()
+ public function testConvertToPHPValue() : void
{
- self::assertInternalType('string', $this->type->convertToPHPValue('foo', $this->platform));
- self::assertInternalType('string', $this->type->convertToPHPValue('', $this->platform));
+ self::assertIsString($this->type->convertToPHPValue('foo', $this->platform));
+ self::assertIsString($this->type->convertToPHPValue('', $this->platform));
}
- public function testNullConversion()
+ public function testNullConversion() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testNativeGuidSupport()
+ public function testNativeGuidSupport() : void
{
self::assertTrue($this->type->requiresSQLCommentHint($this->platform));
- $mock = $this->createMock(get_class($this->platform));
- $mock->expects($this->any())
+ $this->platform->expects($this->any())
->method('hasNativeGuidType')
->will($this->returnValue(true));
- self::assertFalse($this->type->requiresSQLCommentHint($mock));
+ self::assertFalse($this->type->requiresSQLCommentHint($this->platform));
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/IntegerTest.php b/tests/Doctrine/Tests/DBAL/Types/IntegerTest.php
index 848ff05dfc8..e4ac718c4ea 100644
--- a/tests/Doctrine/Tests/DBAL/Types/IntegerTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/IntegerTest.php
@@ -2,31 +2,33 @@
namespace Doctrine\Tests\DBAL\Types;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
+use Doctrine\DBAL\Types\IntegerType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
class IntegerTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
private $platform;
- /** @var Type */
+ /** @var IntegerType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('integer');
}
- public function testIntegerConvertsToPHPValue()
+ public function testIntegerConvertsToPHPValue() : void
{
- self::assertInternalType('integer', $this->type->convertToPHPValue('1', $this->platform));
- self::assertInternalType('integer', $this->type->convertToPHPValue('0', $this->platform));
+ self::assertIsInt($this->type->convertToPHPValue('1', $this->platform));
+ self::assertIsInt($this->type->convertToPHPValue('0', $this->platform));
}
- public function testIntegerNullConvertsToPHPValue()
+ public function testIntegerNullConvertsToPHPValue() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/JsonArrayTest.php b/tests/Doctrine/Tests/DBAL/Types/JsonArrayTest.php
index 564371a30b3..2ee5e9fc45e 100644
--- a/tests/Doctrine/Tests/DBAL/Types/JsonArrayTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/JsonArrayTest.php
@@ -3,17 +3,19 @@
namespace Doctrine\Tests\DBAL\Types;
use Doctrine\DBAL\ParameterType;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\JsonArrayType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
+use Doctrine\DBAL\Types\Types;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
use function base64_encode;
use function fopen;
use function json_encode;
class JsonArrayTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
protected $platform;
/** @var JsonArrayType */
@@ -22,38 +24,42 @@ class JsonArrayTest extends DbalTestCase
/**
* {@inheritdoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('json_array');
}
- public function testReturnsBindingType()
+ public function testReturnsBindingType() : void
{
self::assertSame(ParameterType::STRING, $this->type->getBindingType());
}
- public function testReturnsName()
+ public function testReturnsName() : void
{
- self::assertSame(Type::JSON_ARRAY, $this->type->getName());
+ self::assertSame(Types::JSON_ARRAY, $this->type->getName());
}
- public function testReturnsSQLDeclaration()
+ public function testReturnsSQLDeclaration() : void
{
- self::assertSame('DUMMYJSON', $this->type->getSQLDeclaration([], $this->platform));
+ $this->platform->expects($this->once())
+ ->method('getJsonTypeDeclarationSQL')
+ ->willReturn('TEST_JSON');
+
+ self::assertSame('TEST_JSON', $this->type->getSQLDeclaration([], $this->platform));
}
- public function testJsonNullConvertsToPHPValue()
+ public function testJsonNullConvertsToPHPValue() : void
{
self::assertSame([], $this->type->convertToPHPValue(null, $this->platform));
}
- public function testJsonEmptyStringConvertsToPHPValue()
+ public function testJsonEmptyStringConvertsToPHPValue() : void
{
self::assertSame([], $this->type->convertToPHPValue('', $this->platform));
}
- public function testJsonStringConvertsToPHPValue()
+ public function testJsonStringConvertsToPHPValue() : void
{
$value = ['foo' => 'bar', 'bar' => 'foo'];
$databaseValue = json_encode($value);
@@ -62,7 +68,7 @@ public function testJsonStringConvertsToPHPValue()
self::assertEquals($value, $phpValue);
}
- public function testJsonResourceConvertsToPHPValue()
+ public function testJsonResourceConvertsToPHPValue() : void
{
$value = ['foo' => 'bar', 'bar' => 'foo'];
$databaseValue = fopen('data://text/plain;base64,' . base64_encode(json_encode($value)), 'r');
@@ -71,7 +77,7 @@ public function testJsonResourceConvertsToPHPValue()
self::assertSame($value, $phpValue);
}
- public function testRequiresSQLCommentHint()
+ public function testRequiresSQLCommentHint() : void
{
self::assertTrue($this->type->requiresSQLCommentHint($this->platform));
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/JsonTest.php b/tests/Doctrine/Tests/DBAL/Types/JsonTest.php
index 4f204a8baec..4a5ff3c28c0 100644
--- a/tests/Doctrine/Tests/DBAL/Types/JsonTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/JsonTest.php
@@ -3,18 +3,20 @@
namespace Doctrine\Tests\DBAL\Types;
use Doctrine\DBAL\ParameterType;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\JsonType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
+use Doctrine\DBAL\Types\Types;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
use function base64_encode;
use function fopen;
use function json_encode;
class JsonTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
protected $platform;
/** @var JsonType */
@@ -23,38 +25,42 @@ class JsonTest extends DbalTestCase
/**
* {@inheritdoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('json');
}
- public function testReturnsBindingType()
+ public function testReturnsBindingType() : void
{
self::assertSame(ParameterType::STRING, $this->type->getBindingType());
}
- public function testReturnsName()
+ public function testReturnsName() : void
{
- self::assertSame(Type::JSON, $this->type->getName());
+ self::assertSame(Types::JSON, $this->type->getName());
}
- public function testReturnsSQLDeclaration()
+ public function testReturnsSQLDeclaration() : void
{
- self::assertSame('DUMMYJSON', $this->type->getSQLDeclaration([], $this->platform));
+ $this->platform->expects($this->once())
+ ->method('getJsonTypeDeclarationSQL')
+ ->willReturn('TEST_JSON');
+
+ self::assertSame('TEST_JSON', $this->type->getSQLDeclaration([], $this->platform));
}
- public function testJsonNullConvertsToPHPValue()
+ public function testJsonNullConvertsToPHPValue() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testJsonEmptyStringConvertsToPHPValue()
+ public function testJsonEmptyStringConvertsToPHPValue() : void
{
self::assertNull($this->type->convertToPHPValue('', $this->platform));
}
- public function testJsonStringConvertsToPHPValue()
+ public function testJsonStringConvertsToPHPValue() : void
{
$value = ['foo' => 'bar', 'bar' => 'foo'];
$databaseValue = json_encode($value);
@@ -64,18 +70,21 @@ public function testJsonStringConvertsToPHPValue()
}
/** @dataProvider providerFailure */
- public function testConversionFailure($data)
+ public function testConversionFailure(string $data) : void
{
$this->expectException(ConversionException::class);
$this->type->convertToPHPValue($data, $this->platform);
}
- public function providerFailure()
+ /**
+ * @return mixed[][]
+ */
+ public static function providerFailure() : iterable
{
return [['a'], ['{']];
}
- public function testJsonResourceConvertsToPHPValue()
+ public function testJsonResourceConvertsToPHPValue() : void
{
$value = ['foo' => 'bar', 'bar' => 'foo'];
$databaseValue = fopen('data://text/plain;base64,' . base64_encode(json_encode($value)), 'r');
@@ -84,7 +93,7 @@ public function testJsonResourceConvertsToPHPValue()
self::assertSame($value, $phpValue);
}
- public function testRequiresSQLCommentHint()
+ public function testRequiresSQLCommentHint() : void
{
self::assertTrue($this->type->requiresSQLCommentHint($this->platform));
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/ObjectTest.php b/tests/Doctrine/Tests/DBAL/Types/ObjectTest.php
index 858004b73f4..da9481d105a 100644
--- a/tests/Doctrine/Tests/DBAL/Types/ObjectTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/ObjectTest.php
@@ -2,45 +2,47 @@
namespace Doctrine\Tests\DBAL\Types;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
+use Doctrine\DBAL\Types\ObjectType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
use stdClass;
use function serialize;
class ObjectTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
private $platform;
- /** @var Type */
+ /** @var ObjectType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('object');
}
- public function testObjectConvertsToDatabaseValue()
+ public function testObjectConvertsToDatabaseValue() : void
{
- self::assertInternalType('string', $this->type->convertToDatabaseValue(new stdClass(), $this->platform));
+ self::assertIsString($this->type->convertToDatabaseValue(new stdClass(), $this->platform));
}
- public function testObjectConvertsToPHPValue()
+ public function testObjectConvertsToPHPValue() : void
{
- self::assertInternalType('object', $this->type->convertToPHPValue(serialize(new stdClass()), $this->platform));
+ self::assertIsObject($this->type->convertToPHPValue(serialize(new stdClass()), $this->platform));
}
- public function testConversionFailure()
+ public function testConversionFailure() : void
{
$this->expectException(ConversionException::class);
$this->expectExceptionMessage("Could not convert database value to 'object' as an error was triggered by the unserialization: 'unserialize(): Error at offset 0 of 7 bytes'");
$this->type->convertToPHPValue('abcdefg', $this->platform);
}
- public function testNullConversion()
+ public function testNullConversion() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
@@ -48,7 +50,7 @@ public function testNullConversion()
/**
* @group DBAL-73
*/
- public function testFalseConversion()
+ public function testFalseConversion() : void
{
self::assertFalse($this->type->convertToPHPValue(serialize(false), $this->platform));
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/SmallIntTest.php b/tests/Doctrine/Tests/DBAL/Types/SmallIntTest.php
index 4a453421b36..b1731a99578 100644
--- a/tests/Doctrine/Tests/DBAL/Types/SmallIntTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/SmallIntTest.php
@@ -2,31 +2,33 @@
namespace Doctrine\Tests\DBAL\Types;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
+use Doctrine\DBAL\Types\SmallIntType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
class SmallIntTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
private $platform;
- /** @var Type */
+ /** @var SmallIntType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('smallint');
}
- public function testSmallIntConvertsToPHPValue()
+ public function testSmallIntConvertsToPHPValue() : void
{
- self::assertInternalType('integer', $this->type->convertToPHPValue('1', $this->platform));
- self::assertInternalType('integer', $this->type->convertToPHPValue('0', $this->platform));
+ self::assertIsInt($this->type->convertToPHPValue('1', $this->platform));
+ self::assertIsInt($this->type->convertToPHPValue('0', $this->platform));
}
- public function testSmallIntNullConvertsToPHPValue()
+ public function testSmallIntNullConvertsToPHPValue() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/StringTest.php b/tests/Doctrine/Tests/DBAL/Types/StringTest.php
index 74716e4f23c..4548ff60943 100644
--- a/tests/Doctrine/Tests/DBAL/Types/StringTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/StringTest.php
@@ -2,46 +2,56 @@
namespace Doctrine\Tests\DBAL\Types;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
+use Doctrine\DBAL\Types\StringType;
use Doctrine\DBAL\Types\Type;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
class StringTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
private $platform;
- /** @var Type */
+ /** @var StringType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('string');
}
- public function testReturnsSqlDeclarationFromPlatformVarchar()
+ public function testReturnsSqlDeclarationFromPlatformVarchar() : void
{
- self::assertEquals('DUMMYVARCHAR()', $this->type->getSqlDeclaration([], $this->platform));
+ $this->platform->expects($this->once())
+ ->method('getVarcharTypeDeclarationSQL')
+ ->willReturn('TEST_VARCHAR');
+
+ self::assertEquals('TEST_VARCHAR', $this->type->getSqlDeclaration([], $this->platform));
}
- public function testReturnsDefaultLengthFromPlatformVarchar()
+ public function testReturnsDefaultLengthFromPlatformVarchar() : void
{
+ $this->platform->expects($this->once())
+ ->method('getVarcharDefaultLength')
+ ->willReturn(255);
+
self::assertEquals(255, $this->type->getDefaultLength($this->platform));
}
- public function testConvertToPHPValue()
+ public function testConvertToPHPValue() : void
{
- self::assertInternalType('string', $this->type->convertToPHPValue('foo', $this->platform));
- self::assertInternalType('string', $this->type->convertToPHPValue('', $this->platform));
+ self::assertIsString($this->type->convertToPHPValue('foo', $this->platform));
+ self::assertIsString($this->type->convertToPHPValue('', $this->platform));
}
- public function testNullConversion()
+ public function testNullConversion() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testSQLConversion()
+ public function testSQLConversion() : void
{
self::assertFalse($this->type->canRequireSQLConversion(), 'String type can never require SQL conversion to work.');
self::assertEquals('t.foo', $this->type->convertToDatabaseValueSQL('t.foo', $this->platform));
diff --git a/tests/Doctrine/Tests/DBAL/Types/TimeImmutableTypeTest.php b/tests/Doctrine/Tests/DBAL/Types/TimeImmutableTypeTest.php
index 0f7427df3ed..ba087f19f40 100644
--- a/tests/Doctrine/Tests/DBAL/Types/TimeImmutableTypeTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/TimeImmutableTypeTest.php
@@ -9,104 +9,113 @@
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\TimeImmutableType;
use Doctrine\DBAL\Types\Type;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
-use Prophecy\Prophecy\ObjectProphecy;
use function get_class;
class TimeImmutableTypeTest extends TestCase
{
- /** @var AbstractPlatform|ObjectProphecy */
+ /** @var AbstractPlatform|MockObject */
private $platform;
/** @var TimeImmutableType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
$this->type = Type::getType('time_immutable');
- $this->platform = $this->prophesize(AbstractPlatform::class);
+ $this->platform = $this->getMockBuilder(AbstractPlatform::class)->getMock();
}
- public function testFactoryCreatesCorrectType()
+ public function testFactoryCreatesCorrectType() : void
{
self::assertSame(TimeImmutableType::class, get_class($this->type));
}
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('time_immutable', $this->type->getName());
}
- public function testReturnsBindingType()
+ public function testReturnsBindingType() : void
{
self::assertSame(ParameterType::STRING, $this->type->getBindingType());
}
- public function testConvertsDateTimeImmutableInstanceToDatabaseValue()
+ public function testConvertsDateTimeImmutableInstanceToDatabaseValue() : void
{
- $date = $this->prophesize(DateTimeImmutable::class);
+ $date = $this->getMockBuilder(DateTimeImmutable::class)->getMock();
- $this->platform->getTimeFormatString()->willReturn('H:i:s')->shouldBeCalled();
- $date->format('H:i:s')->willReturn('15:58:59')->shouldBeCalled();
+ $this->platform->expects($this->once())
+ ->method('getTimeFormatString')
+ ->willReturn('H:i:s');
+ $date->expects($this->once())
+ ->method('format')
+ ->with('H:i:s')
+ ->willReturn('15:58:59');
self::assertSame(
'15:58:59',
- $this->type->convertToDatabaseValue($date->reveal(), $this->platform->reveal())
+ $this->type->convertToDatabaseValue($date, $this->platform)
);
}
- public function testConvertsNullToDatabaseValue()
+ public function testConvertsNullToDatabaseValue() : void
{
- self::assertNull($this->type->convertToDatabaseValue(null, $this->platform->reveal()));
+ self::assertNull($this->type->convertToDatabaseValue(null, $this->platform));
}
- public function testDoesNotSupportMutableDateTimeToDatabaseValueConversion()
+ public function testDoesNotSupportMutableDateTimeToDatabaseValueConversion() : void
{
$this->expectException(ConversionException::class);
- $this->type->convertToDatabaseValue(new DateTime(), $this->platform->reveal());
+ $this->type->convertToDatabaseValue(new DateTime(), $this->platform);
}
- public function testConvertsDateTimeImmutableInstanceToPHPValue()
+ public function testConvertsDateTimeImmutableInstanceToPHPValue() : void
{
$date = new DateTimeImmutable();
- self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform->reveal()));
+ self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform));
}
- public function testConvertsNullToPHPValue()
+ public function testConvertsNullToPHPValue() : void
{
- self::assertNull($this->type->convertToPHPValue(null, $this->platform->reveal()));
+ self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testConvertsTimeStringToPHPValue()
+ public function testConvertsTimeStringToPHPValue() : void
{
- $this->platform->getTimeFormatString()->willReturn('H:i:s')->shouldBeCalled();
+ $this->platform->expects($this->once())
+ ->method('getTimeFormatString')
+ ->willReturn('H:i:s');
- $date = $this->type->convertToPHPValue('15:58:59', $this->platform->reveal());
+ $date = $this->type->convertToPHPValue('15:58:59', $this->platform);
self::assertInstanceOf(DateTimeImmutable::class, $date);
self::assertSame('15:58:59', $date->format('H:i:s'));
}
- public function testResetDateFractionsWhenConvertingToPHPValue()
+ public function testResetDateFractionsWhenConvertingToPHPValue() : void
{
- $this->platform->getTimeFormatString()->willReturn('H:i:s');
+ $this->platform->expects($this->any())
+ ->method('getTimeFormatString')
+ ->willReturn('H:i:s');
- $date = $this->type->convertToPHPValue('15:58:59', $this->platform->reveal());
+ $date = $this->type->convertToPHPValue('15:58:59', $this->platform);
self::assertSame('1970-01-01 15:58:59', $date->format('Y-m-d H:i:s'));
}
- public function testThrowsExceptionDuringConversionToPHPValueWithInvalidTimeString()
+ public function testThrowsExceptionDuringConversionToPHPValueWithInvalidTimeString() : void
{
$this->expectException(ConversionException::class);
- $this->type->convertToPHPValue('invalid time string', $this->platform->reveal());
+ $this->type->convertToPHPValue('invalid time string', $this->platform);
}
- public function testRequiresSQLCommentHint()
+ public function testRequiresSQLCommentHint() : void
{
- self::assertTrue($this->type->requiresSQLCommentHint($this->platform->reveal()));
+ self::assertTrue($this->type->requiresSQLCommentHint($this->platform));
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/TimeTest.php b/tests/Doctrine/Tests/DBAL/Types/TimeTest.php
index c2cd766b1c3..a75544b650e 100644
--- a/tests/Doctrine/Tests/DBAL/Types/TimeTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/TimeTest.php
@@ -10,19 +10,19 @@ class TimeTest extends BaseDateTypeTestCase
/**
* {@inheritDoc}
*/
- protected function setUp()
+ protected function setUp() : void
{
$this->type = Type::getType('time');
parent::setUp();
}
- public function testTimeConvertsToPHPValue()
+ public function testTimeConvertsToPHPValue() : void
{
self::assertInstanceOf('DateTime', $this->type->convertToPHPValue('5:30:55', $this->platform));
}
- public function testDateFieldResetInPHPValue()
+ public function testDateFieldResetInPHPValue() : void
{
$time = $this->type->convertToPHPValue('01:23:34', $this->platform);
@@ -30,7 +30,7 @@ public function testDateFieldResetInPHPValue()
self::assertEquals('1970-01-01', $time->format('Y-m-d'));
}
- public function testInvalidTimeFormatConversion()
+ public function testInvalidTimeFormatConversion() : void
{
$this->expectException(ConversionException::class);
$this->type->convertToPHPValue('abcdefg', $this->platform);
diff --git a/tests/Doctrine/Tests/DBAL/Types/TypeRegistryTest.php b/tests/Doctrine/Tests/DBAL/Types/TypeRegistryTest.php
new file mode 100644
index 00000000000..14cd7497385
--- /dev/null
+++ b/tests/Doctrine/Tests/DBAL/Types/TypeRegistryTest.php
@@ -0,0 +1,154 @@
+testType = new BlobType();
+ $this->otherTestType = new BinaryType();
+
+ $this->registry = new TypeRegistry();
+ $this->registry->register(self::TEST_TYPE_NAME, $this->testType);
+ $this->registry->register(self::OTHER_TEST_TYPE_NAME, $this->otherTestType);
+ }
+
+ public function testGet() : void
+ {
+ self::assertSame($this->testType, $this->registry->get(self::TEST_TYPE_NAME));
+ self::assertSame($this->otherTestType, $this->registry->get(self::OTHER_TEST_TYPE_NAME));
+
+ $this->expectException(DBALException::class);
+ $this->registry->get('unknown');
+ }
+
+ public function testGetReturnsSameInstances() : void
+ {
+ self::assertSame(
+ $this->registry->get(self::TEST_TYPE_NAME),
+ $this->registry->get(self::TEST_TYPE_NAME)
+ );
+ }
+
+ public function testLookupName() : void
+ {
+ self::assertSame(
+ self::TEST_TYPE_NAME,
+ $this->registry->lookupName($this->testType)
+ );
+ self::assertSame(
+ self::OTHER_TEST_TYPE_NAME,
+ $this->registry->lookupName($this->otherTestType)
+ );
+
+ $this->expectException(DBALException::class);
+ $this->registry->lookupName(new TextType());
+ }
+
+ public function testHas() : void
+ {
+ self::assertTrue($this->registry->has(self::TEST_TYPE_NAME));
+ self::assertTrue($this->registry->has(self::OTHER_TEST_TYPE_NAME));
+ self::assertFalse($this->registry->has('unknown'));
+ }
+
+ public function testRegister() : void
+ {
+ $newType = new TextType();
+
+ $this->registry->register('some', $newType);
+
+ self::assertTrue($this->registry->has('some'));
+ self::assertSame($newType, $this->registry->get('some'));
+ }
+
+ public function testRegisterWithAlradyRegisteredName() : void
+ {
+ $this->registry->register('some', new TextType());
+
+ $this->expectException(DBALException::class);
+ $this->registry->register('some', new TextType());
+ }
+
+ public function testRegisterWithAlreadyRegisteredInstance() : void
+ {
+ $newType = new TextType();
+
+ $this->registry->register('some', $newType);
+
+ $this->expectException(DBALException::class);
+ $this->registry->register('other', $newType);
+ }
+
+ public function testOverride() : void
+ {
+ $baseType = new TextType();
+ $overrideType = new StringType();
+
+ $this->registry->register('some', $baseType);
+ $this->registry->override('some', $overrideType);
+
+ self::assertSame($overrideType, $this->registry->get('some'));
+ }
+
+ public function testOverrideAllowsExistingInstance() : void
+ {
+ $type = new TextType();
+
+ $this->registry->register('some', $type);
+ $this->registry->override('some', $type);
+
+ self::assertSame($type, $this->registry->get('some'));
+ }
+
+ public function testOverrideWithAlreadyRegisteredInstance() : void
+ {
+ $newType = new TextType();
+
+ $this->registry->register('first', $newType);
+ $this->registry->register('second', new StringType());
+
+ $this->expectException(DBALException::class);
+ $this->registry->override('second', $newType);
+ }
+
+ public function testOverrideWithUnknownType() : void
+ {
+ $this->expectException(DBALException::class);
+ $this->registry->override('unknown', new TextType());
+ }
+
+ public function testGetMap() : void
+ {
+ $registeredTypes = $this->registry->getMap();
+
+ self::assertCount(2, $registeredTypes);
+ self::assertArrayHasKey(self::TEST_TYPE_NAME, $registeredTypes);
+ self::assertArrayHasKey(self::OTHER_TEST_TYPE_NAME, $registeredTypes);
+ self::assertSame($this->testType, $registeredTypes[self::TEST_TYPE_NAME]);
+ self::assertSame($this->otherTestType, $registeredTypes[self::OTHER_TEST_TYPE_NAME]);
+ }
+}
diff --git a/tests/Doctrine/Tests/DBAL/Types/TypeTest.php b/tests/Doctrine/Tests/DBAL/Types/TypeTest.php
new file mode 100644
index 00000000000..59440f062c6
--- /dev/null
+++ b/tests/Doctrine/Tests/DBAL/Types/TypeTest.php
@@ -0,0 +1,34 @@
+getReflectionConstants() as $constant) {
+ if (! $constant->isPublic()) {
+ continue;
+ }
+
+ yield [$constant->getValue()];
+ }
+ }
+}
diff --git a/tests/Doctrine/Tests/DBAL/Types/VarDateTimeImmutableTypeTest.php b/tests/Doctrine/Tests/DBAL/Types/VarDateTimeImmutableTypeTest.php
index 870bb23cc98..d3609fe2bac 100644
--- a/tests/Doctrine/Tests/DBAL/Types/VarDateTimeImmutableTypeTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/VarDateTimeImmutableTypeTest.php
@@ -9,93 +9,93 @@
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\VarDateTimeImmutableType;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
-use Prophecy\Prophecy\ObjectProphecy;
class VarDateTimeImmutableTypeTest extends TestCase
{
- /** @var AbstractPlatform|ObjectProphecy */
+ /** @var AbstractPlatform|MockObject */
private $platform;
/** @var VarDateTimeImmutableType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
if (! Type::hasType('vardatetime_immutable')) {
Type::addType('vardatetime_immutable', VarDateTimeImmutableType::class);
}
$this->type = Type::getType('vardatetime_immutable');
- $this->platform = $this->prophesize(AbstractPlatform::class);
+ $this->platform = $this->getMockForAbstractClass(AbstractPlatform::class);
}
- public function testReturnsName()
+ public function testReturnsName() : void
{
self::assertSame('datetime_immutable', $this->type->getName());
}
- public function testReturnsBindingType()
+ public function testReturnsBindingType() : void
{
self::assertSame(ParameterType::STRING, $this->type->getBindingType());
}
- public function testConvertsDateTimeImmutableInstanceToDatabaseValue()
+ public function testConvertsDateTimeImmutableInstanceToDatabaseValue() : void
{
- $date = $this->prophesize(DateTimeImmutable::class);
+ $date = $this->getMockBuilder(DateTimeImmutable::class)->getMock();
- $this->platform->getDateTimeFormatString()->willReturn('Y-m-d H:i:s')->shouldBeCalled();
- $date->format('Y-m-d H:i:s')->willReturn('2016-01-01 15:58:59')->shouldBeCalled();
+ $date->expects($this->once())
+ ->method('format')
+ ->with('Y-m-d H:i:s')
+ ->willReturn('2016-01-01 15:58:59');
self::assertSame(
'2016-01-01 15:58:59',
- $this->type->convertToDatabaseValue($date->reveal(), $this->platform->reveal())
+ $this->type->convertToDatabaseValue($date, $this->platform)
);
}
- public function testConvertsNullToDatabaseValue()
+ public function testConvertsNullToDatabaseValue() : void
{
- self::assertNull($this->type->convertToDatabaseValue(null, $this->platform->reveal()));
+ self::assertNull($this->type->convertToDatabaseValue(null, $this->platform));
}
- public function testDoesNotSupportMutableDateTimeToDatabaseValueConversion()
+ public function testDoesNotSupportMutableDateTimeToDatabaseValueConversion() : void
{
$this->expectException(ConversionException::class);
- $this->type->convertToDatabaseValue(new DateTime(), $this->platform->reveal());
+ $this->type->convertToDatabaseValue(new DateTime(), $this->platform);
}
- public function testConvertsDateTimeImmutableInstanceToPHPValue()
+ public function testConvertsDateTimeImmutableInstanceToPHPValue() : void
{
$date = new DateTimeImmutable();
- self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform->reveal()));
+ self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform));
}
- public function testConvertsNullToPHPValue()
+ public function testConvertsNullToPHPValue() : void
{
- self::assertNull($this->type->convertToPHPValue(null, $this->platform->reveal()));
+ self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testConvertsDateishStringToPHPValue()
+ public function testConvertsDateishStringToPHPValue() : void
{
- $this->platform->getDateTimeFormatString()->shouldNotBeCalled();
-
- $date = $this->type->convertToPHPValue('2016-01-01 15:58:59.123456 UTC', $this->platform->reveal());
+ $date = $this->type->convertToPHPValue('2016-01-01 15:58:59.123456 UTC', $this->platform);
self::assertInstanceOf(DateTimeImmutable::class, $date);
self::assertSame('2016-01-01 15:58:59.123456 UTC', $date->format('Y-m-d H:i:s.u T'));
}
- public function testThrowsExceptionDuringConversionToPHPValueWithInvalidDateishString()
+ public function testThrowsExceptionDuringConversionToPHPValueWithInvalidDateishString() : void
{
$this->expectException(ConversionException::class);
- $this->type->convertToPHPValue('invalid date-ish string', $this->platform->reveal());
+ $this->type->convertToPHPValue('invalid date-ish string', $this->platform);
}
- public function testRequiresSQLCommentHint()
+ public function testRequiresSQLCommentHint() : void
{
- self::assertTrue($this->type->requiresSQLCommentHint($this->platform->reveal()));
+ self::assertTrue($this->type->requiresSQLCommentHint($this->platform));
}
}
diff --git a/tests/Doctrine/Tests/DBAL/Types/VarDateTimeTest.php b/tests/Doctrine/Tests/DBAL/Types/VarDateTimeTest.php
index 2322aa474fe..7fe10cb2ba3 100644
--- a/tests/Doctrine/Tests/DBAL/Types/VarDateTimeTest.php
+++ b/tests/Doctrine/Tests/DBAL/Types/VarDateTimeTest.php
@@ -3,30 +3,31 @@
namespace Doctrine\Tests\DBAL\Types;
use DateTime;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\VarDateTimeType;
-use Doctrine\Tests\DBAL\Mocks\MockPlatform;
use Doctrine\Tests\DbalTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
class VarDateTimeTest extends DbalTestCase
{
- /** @var MockPlatform */
+ /** @var AbstractPlatform|MockObject */
private $platform;
- /** @var Type */
+ /** @var VarDateTimeType */
private $type;
- protected function setUp()
+ protected function setUp() : void
{
- $this->platform = new MockPlatform();
+ $this->platform = $this->createMock(AbstractPlatform::class);
if (! Type::hasType('vardatetime')) {
Type::addType('vardatetime', VarDateTimeType::class);
}
$this->type = Type::getType('vardatetime');
}
- public function testDateTimeConvertsToDatabaseValue()
+ public function testDateTimeConvertsToDatabaseValue() : void
{
$date = new DateTime('1985-09-01 10:10:10');
@@ -36,7 +37,7 @@ public function testDateTimeConvertsToDatabaseValue()
self::assertEquals($expected, $actual);
}
- public function testDateTimeConvertsToPHPValue()
+ public function testDateTimeConvertsToPHPValue() : void
{
// Birthday of jwage and also birthday of Doctrine. Send him a present ;)
$date = $this->type->convertToPHPValue('1985-09-01 00:00:00', $this->platform);
@@ -45,13 +46,13 @@ public function testDateTimeConvertsToPHPValue()
self::assertEquals('000000', $date->format('u'));
}
- public function testInvalidDateTimeFormatConversion()
+ public function testInvalidDateTimeFormatConversion() : void
{
$this->expectException(ConversionException::class);
$this->type->convertToPHPValue('abcdefg', $this->platform);
}
- public function testConversionWithMicroseconds()
+ public function testConversionWithMicroseconds() : void
{
$date = $this->type->convertToPHPValue('1985-09-01 00:00:00.123456', $this->platform);
self::assertInstanceOf('DateTime', $date);
@@ -59,12 +60,12 @@ public function testConversionWithMicroseconds()
self::assertEquals('123456', $date->format('u'));
}
- public function testNullConversion()
+ public function testNullConversion() : void
{
self::assertNull($this->type->convertToPHPValue(null, $this->platform));
}
- public function testConvertDateTimeToPHPValue()
+ public function testConvertDateTimeToPHPValue() : void
{
$date = new DateTime('now');
self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform));
diff --git a/tests/Doctrine/Tests/DBAL/UtilTest.php b/tests/Doctrine/Tests/DBAL/UtilTest.php
index e7800fceba3..92f63872f15 100644
--- a/tests/Doctrine/Tests/DBAL/UtilTest.php
+++ b/tests/Doctrine/Tests/DBAL/UtilTest.php
@@ -7,7 +7,10 @@
class UtilTest extends DbalTestCase
{
- public static function dataConvertPositionalToNamedParameters()
+ /**
+ * @return mixed[][]
+ */
+ public static function dataConvertPositionalToNamedParameters() : iterable
{
return [
[
@@ -64,13 +67,11 @@ public static function dataConvertPositionalToNamedParameters()
}
/**
- * @param string $inputSQL
- * @param string $expectedOutputSQL
* @param mixed[] $expectedOutputParamsMap
*
* @dataProvider dataConvertPositionalToNamedParameters
*/
- public function testConvertPositionalToNamedParameters($inputSQL, $expectedOutputSQL, $expectedOutputParamsMap)
+ public function testConvertPositionalToNamedParameters(string $inputSQL, string $expectedOutputSQL, array $expectedOutputParamsMap) : void
{
[$statement, $params] = OCI8Statement::convertPositionalToNamedPlaceholders($inputSQL);
diff --git a/tests/Doctrine/Tests/DbalFunctionalTestCase.php b/tests/Doctrine/Tests/DbalFunctionalTestCase.php
index 77cfd8d6900..16aa747c20e 100644
--- a/tests/Doctrine/Tests/DbalFunctionalTestCase.php
+++ b/tests/Doctrine/Tests/DbalFunctionalTestCase.php
@@ -18,7 +18,7 @@
use function strpos;
use function var_export;
-class DbalFunctionalTestCase extends DbalTestCase
+abstract class DbalFunctionalTestCase extends DbalTestCase
{
/**
* Shared connection when a TestCase is run alone (outside of it's functional suite)
@@ -33,7 +33,7 @@ class DbalFunctionalTestCase extends DbalTestCase
/** @var DebugStack */
protected $sqlLoggerStack;
- protected function resetSharedConn()
+ protected function resetSharedConn() : void
{
if (! self::$sharedConnection) {
return;
@@ -43,7 +43,7 @@ protected function resetSharedConn()
self::$sharedConnection = null;
}
- protected function setUp()
+ protected function setUp() : void
{
if (! isset(self::$sharedConnection)) {
self::$sharedConnection = TestUtil::getConnection();
@@ -54,14 +54,14 @@ protected function setUp()
$this->connection->getConfiguration()->setSQLLogger($this->sqlLoggerStack);
}
- protected function tearDown()
+ protected function tearDown() : void
{
while ($this->connection->isTransactionActive()) {
$this->connection->rollBack();
}
}
- protected function onNotSuccessfulTest(Throwable $t)
+ protected function onNotSuccessfulTest(Throwable $t) : void
{
if ($t instanceof AssertionFailedError) {
throw $t;
@@ -74,7 +74,9 @@ protected function onNotSuccessfulTest(Throwable $t)
$params = array_map(static function ($p) {
if (is_object($p)) {
return get_class($p);
- } elseif (is_scalar($p)) {
+ }
+
+ if (is_scalar($p)) {
return "'" . $p . "'";
}
diff --git a/tests/Doctrine/Tests/DbalPerformanceTestCase.php b/tests/Doctrine/Tests/DbalPerformanceTestCase.php
index bfc60201bef..ac0beb3c5de 100644
--- a/tests/Doctrine/Tests/DbalPerformanceTestCase.php
+++ b/tests/Doctrine/Tests/DbalPerformanceTestCase.php
@@ -11,7 +11,7 @@
* and stopTiming at the end of all tests. Tests that do not start or stop
* timing will fail.
*/
-class DbalPerformanceTestCase extends DbalFunctionalTestCase
+abstract class DbalPerformanceTestCase extends DbalFunctionalTestCase
{
/**
* time the test started
@@ -30,7 +30,7 @@ class DbalPerformanceTestCase extends DbalFunctionalTestCase
/**
* {@inheritdoc}
*/
- protected function assertPostConditions()
+ protected function assertPostConditions() : void
{
// If a perf test doesn't start or stop, it fails.
self::assertNotNull($this->startTime, 'Test timing was started');
@@ -40,7 +40,7 @@ protected function assertPostConditions()
/**
* begin timing
*/
- protected function startTiming()
+ protected function startTiming() : void
{
$this->startTime = microtime(true);
}
@@ -48,7 +48,7 @@ protected function startTiming()
/**
* end timing
*/
- protected function stopTiming()
+ protected function stopTiming() : void
{
$this->runTime = microtime(true) - $this->startTime;
}
@@ -56,7 +56,7 @@ protected function stopTiming()
/**
* @return float elapsed test execution time
*/
- public function getTime()
+ public function getTime() : float
{
return $this->runTime;
}
diff --git a/tests/Doctrine/Tests/Mocks/ConnectionMock.php b/tests/Doctrine/Tests/Mocks/ConnectionMock.php
deleted file mode 100644
index 157584f09f7..00000000000
--- a/tests/Doctrine/Tests/Mocks/ConnectionMock.php
+++ /dev/null
@@ -1,70 +0,0 @@
-platformMock = new DatabasePlatformMock();
-
- parent::__construct($params, $driver, $config, $eventManager);
- }
-
- public function getDatabasePlatform()
- {
- return $this->platformMock;
- }
-
- /**
- * {@inheritDoc}
- */
- public function insert($tableName, array $data, array $types = [])
- {
- $this->inserts[$tableName][] = $data;
- }
-
- public function lastInsertId($seqName = null)
- {
- return $this->lastInsertId;
- }
-
- public function quote($input, $type = null)
- {
- if (is_string($input)) {
- return "'" . $input . "'";
- }
- return $input;
- }
-
- public function setLastInsertId($id)
- {
- $this->lastInsertId = $id;
- }
-
- public function getInserts()
- {
- return $this->inserts;
- }
-
- public function reset()
- {
- $this->inserts = [];
- $this->lastInsertId = 0;
- }
-}
diff --git a/tests/Doctrine/Tests/Mocks/DatabasePlatformMock.php b/tests/Doctrine/Tests/Mocks/DatabasePlatformMock.php
deleted file mode 100644
index 690809e308a..00000000000
--- a/tests/Doctrine/Tests/Mocks/DatabasePlatformMock.php
+++ /dev/null
@@ -1,121 +0,0 @@
-prefersIdentityColumns;
- }
-
- public function prefersSequences()
- {
- return $this->prefersSequences;
- }
-
- public function getSequenceNextValSQL($sequenceName)
- {
- return $this->sequenceNextValSql;
- }
-
- /**
- * {@inheritDoc}
- */
- public function getBooleanTypeDeclarationSQL(array $field)
- {
- }
-
- /**
- * {@inheritDoc}
- */
- public function getIntegerTypeDeclarationSQL(array $field)
- {
- }
-
- /**
- * {@inheritDoc}
- */
- public function getBigIntTypeDeclarationSQL(array $field)
- {
- }
-
- /**
- * {@inheritDoc}
- */
- public function getSmallIntTypeDeclarationSQL(array $field)
- {
- }
-
- /**
- * {@inheritDoc}
- */
- protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
- {
- }
-
- /**
- * {@inheritDoc}
- */
- public function getVarcharTypeDeclarationSQL(array $field)
- {
- }
-
- /**
- * {@inheritDoc}
- */
- public function getClobTypeDeclarationSQL(array $field)
- {
- }
-
- /* MOCK API */
-
- /**
- * @param bool $prefersIdentityColumns
- */
- public function setPrefersIdentityColumns($prefersIdentityColumns)
- {
- $this->prefersIdentityColumns = $prefersIdentityColumns;
- }
-
- public function setPrefersSequences($bool)
- {
- $this->prefersSequences = $bool;
- }
-
- public function setSequenceNextValSql($sql)
- {
- $this->sequenceNextValSql = $sql;
- }
-
- public function getName()
- {
- return 'mock';
- }
- protected function initializeDoctrineTypeMappings()
- {
- }
- protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
- {
- }
-
- /**
- * {@inheritDoc}
- */
- public function getBlobTypeDeclarationSQL(array $field)
- {
- throw DBALException::notSupported(__METHOD__);
- }
-}
diff --git a/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php b/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php
deleted file mode 100644
index 7b8872f2ea8..00000000000
--- a/tests/Doctrine/Tests/Mocks/DriverConnectionMock.php
+++ /dev/null
@@ -1,42 +0,0 @@
-platformMock) {
- $this->platformMock = new DatabasePlatformMock();
- }
- return $this->platformMock;
- }
-
- public function getSchemaManager(Connection $conn)
- {
- if ($this->schemaManagerMock === null) {
- return new SchemaManagerMock($conn);
- }
-
- return $this->schemaManagerMock;
- }
-
- public function setDatabasePlatform(AbstractPlatform $platform)
- {
- $this->platformMock = $platform;
- }
-
- public function setSchemaManager(AbstractSchemaManager $sm)
- {
- $this->schemaManagerMock = $sm;
- }
-
- public function getName()
- {
- return 'mock';
- }
-
- public function getDatabase(Connection $conn)
- {
- return;
- }
-
- public function convertExceptionCode(Throwable $exception)
- {
- return 0;
- }
-}
diff --git a/tests/Doctrine/Tests/Mocks/DriverResultStatementMock.php b/tests/Doctrine/Tests/Mocks/DriverResultStatementMock.php
deleted file mode 100644
index 46573c39494..00000000000
--- a/tests/Doctrine/Tests/Mocks/DriverResultStatementMock.php
+++ /dev/null
@@ -1,10 +0,0 @@
-getDatabasePlatform();
- if (! self::$initialized) {
- if ($platform->supportsCreateDropDatabase()) {
- $dbname = $realConn->getDatabase();
- $realConn->close();
+ if ($platform->supportsCreateDropDatabase()) {
+ $dbname = $realConn->getDatabase();
+ $realConn->close();
- $tmpConn->getSchemaManager()->dropAndCreateDatabase($dbname);
+ $tmpConn->getSchemaManager()->dropAndCreateDatabase($dbname);
- $tmpConn->close();
- } else {
- $sm = $realConn->getSchemaManager();
+ $tmpConn->close();
+ } else {
+ $sm = $realConn->getSchemaManager();
- $schema = $sm->createSchema();
- $stmts = $schema->toDropSql($realConn->getDatabasePlatform());
+ $schema = $sm->createSchema();
+ $stmts = $schema->toDropSql($realConn->getDatabasePlatform());
- foreach ($stmts as $stmt) {
- $realConn->exec($stmt);
- }
+ foreach ($stmts as $stmt) {
+ $realConn->exec($stmt);
}
-
- self::$initialized = true;
}
-
- return $realDbParams;
}
- private static function getFallbackConnectionParams()
+ /**
+ * @return mixed[]
+ */
+ private static function getFallbackConnectionParams() : array
{
if (! extension_loaded('pdo_sqlite')) {
Assert::markTestSkipped('PDO SQLite extension is not loaded');
@@ -131,7 +136,7 @@ private static function getFallbackConnectionParams()
return $params;
}
- private static function addDbEventSubscribers(Connection $conn)
+ private static function addDbEventSubscribers(Connection $conn) : void
{
if (! isset($GLOBALS['db_event_subscribers'])) {
return;
@@ -144,7 +149,10 @@ private static function addDbEventSubscribers(Connection $conn)
}
}
- private static function getParamsForTemporaryConnection()
+ /**
+ * @return mixed[]
+ */
+ private static function getParamsForTemporaryConnection() : array
{
$connectionParams = [
'driver' => $GLOBALS['tmpdb_type'],
@@ -170,7 +178,10 @@ private static function getParamsForTemporaryConnection()
return $connectionParams;
}
- private static function getParamsForMainConnection()
+ /**
+ * @return mixed[]
+ */
+ private static function getParamsForMainConnection() : array
{
$connectionParams = [
'driver' => $GLOBALS['db_type'],
@@ -192,10 +203,7 @@ private static function getParamsForMainConnection()
return $connectionParams;
}
- /**
- * @return Connection
- */
- public static function getTempConnection()
+ public static function getTempConnection() : Connection
{
return DriverManager::getConnection(self::getParamsForTemporaryConnection());
}
diff --git a/tests/appveyor/mssql.sql2008r2sp2.sqlsrv.appveyor.xml b/tests/appveyor/mssql.sql2008r2sp2.sqlsrv.appveyor.xml
index 712a8029ade..ef358c2d3be 100644
--- a/tests/appveyor/mssql.sql2008r2sp2.sqlsrv.appveyor.xml
+++ b/tests/appveyor/mssql.sql2008r2sp2.sqlsrv.appveyor.xml
@@ -37,10 +37,6 @@
-
-
-
-
performance
diff --git a/tests/appveyor/mssql.sql2012sp1.sqlsrv.appveyor.xml b/tests/appveyor/mssql.sql2012sp1.sqlsrv.appveyor.xml
index 9195c5aaa87..68b1f31daea 100644
--- a/tests/appveyor/mssql.sql2012sp1.sqlsrv.appveyor.xml
+++ b/tests/appveyor/mssql.sql2012sp1.sqlsrv.appveyor.xml
@@ -37,10 +37,6 @@
-
-
-
-
performance
diff --git a/tests/appveyor/mssql.sql2017.pdo_sqlsrv.appveyor.xml b/tests/appveyor/mssql.sql2017.pdo_sqlsrv.appveyor.xml
index 281955abb16..4ed53022628 100644
--- a/tests/appveyor/mssql.sql2017.pdo_sqlsrv.appveyor.xml
+++ b/tests/appveyor/mssql.sql2017.pdo_sqlsrv.appveyor.xml
@@ -37,10 +37,6 @@
-
-
-
-
performance
diff --git a/tests/appveyor/mssql.sql2017.sqlsrv.appveyor.xml b/tests/appveyor/mssql.sql2017.sqlsrv.appveyor.xml
index 6818a6320db..86702637719 100644
--- a/tests/appveyor/mssql.sql2017.sqlsrv.appveyor.xml
+++ b/tests/appveyor/mssql.sql2017.sqlsrv.appveyor.xml
@@ -37,10 +37,6 @@
-
-
-
-
performance
diff --git a/tests/continuousphp/oci8.phpunit.continuousphp.xml b/tests/continuousphp/oci8.phpunit.continuousphp.xml
index 4b3740936d0..4a2de468240 100644
--- a/tests/continuousphp/oci8.phpunit.continuousphp.xml
+++ b/tests/continuousphp/oci8.phpunit.continuousphp.xml
@@ -39,10 +39,6 @@
-
-
-
-
performance
diff --git a/tests/continuousphp/pdo-oci.phpunit.xml b/tests/continuousphp/pdo-oci.phpunit.xml
index ef145a990d5..b25e0c02745 100644
--- a/tests/continuousphp/pdo-oci.phpunit.xml
+++ b/tests/continuousphp/pdo-oci.phpunit.xml
@@ -37,8 +37,4 @@
-
-
-
-
diff --git a/tests/travis/ibm_db2.travis.xml b/tests/travis/ibm_db2.travis.xml
index b58f3451bc3..e841a8ce252 100644
--- a/tests/travis/ibm_db2.travis.xml
+++ b/tests/travis/ibm_db2.travis.xml
@@ -37,10 +37,6 @@
-
-
-
-
performance
diff --git a/tests/travis/install-mssql.sh b/tests/travis/install-mssql.sh
index 7a28b10065f..e4ce49b2c4a 100644
--- a/tests/travis/install-mssql.sh
+++ b/tests/travis/install-mssql.sh
@@ -2,12 +2,6 @@
set -ex
-echo Installing drivers
-curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
-curl https://packages.microsoft.com/config/ubuntu/14.04/prod.list | sudo tee /etc/apt/sources.list.d/mssql.list
-sudo apt-get update
-ACCEPT_EULA=Y sudo apt-get install -qy msodbcsql17 mssql-tools unixodbc libssl1.0.0
-
echo Setting up Microsoft SQL Server
sudo docker pull microsoft/mssql-server-linux:2017-latest
@@ -15,24 +9,10 @@ sudo docker run \
-e 'ACCEPT_EULA=Y' \
-e 'SA_PASSWORD=Doctrine2018' \
-p 127.0.0.1:1433:1433 \
- --name db \
+ --name mssql \
-d \
microsoft/mssql-server-linux:2017-latest
-
-retries=10
-until (echo quit | /opt/mssql-tools/bin/sqlcmd -S 127.0.0.1 -l 1 -U sa -P Doctrine2018 &> /dev/null)
-do
- if [[ "$retries" -le 0 ]]; then
- echo SQL Server did not start
- exit 1
- fi
-
- retries=$((retries - 1))
-
- echo Waiting for SQL Server to start...
-
- sleep 2s
-done
+sudo docker exec -i mssql bash <<< 'until echo quit | /opt/mssql-tools/bin/sqlcmd -S 127.0.0.1 -l 1 -U sa -P Doctrine2018 > /dev/null 2>&1 ; do sleep 1; done'
echo SQL Server started
diff --git a/tests/travis/install-mysql-8.0.sh b/tests/travis/install-mysql-8.0.sh
index 1a4092e3aae..952a4300ba7 100644
--- a/tests/travis/install-mysql-8.0.sh
+++ b/tests/travis/install-mysql-8.0.sh
@@ -2,15 +2,16 @@
set -ex
-echo "Installing MySQL 8.0..."
+echo "Starting MySQL 8.0..."
-echo mysql-apt-config mysql-apt-config/select-server select mysql-8.0 | sudo debconf-set-selections
-wget https://dev.mysql.com/get/mysql-apt-config_0.8.10-1_all.deb
-sudo dpkg --install mysql-apt-config_0.8.10-1_all.deb
-sudo apt-get update -q
-sudo apt-get install -q -y --force-yes -o Dpkg::Options::=--force-confnew mysql-server
-echo -e "[mysqld]\ndefault_authentication_plugin=mysql_native_password" | sudo tee --append /etc/mysql/my.cnf
-sudo /etc/init.d/mysql start
-sudo mysql_upgrade
+sudo docker pull mysql:8.0
+sudo docker run \
+ -d \
+ -e MYSQL_ALLOW_EMPTY_PASSWORD=yes \
+ -e MYSQL_DATABASE=doctrine_tests \
+ -p 33306:3306 \
+ --name mysql80 \
+ mysql:8.0 \
+ --default-authentication-plugin=mysql_native_password
-mysql --version
+sudo docker exec -i mysql80 bash <<< 'until echo \\q | mysql doctrine_tests > /dev/null 2>&1 ; do sleep 1; done'
diff --git a/tests/travis/install-sqlsrv-dependencies.sh b/tests/travis/install-sqlsrv-dependencies.sh
new file mode 100644
index 00000000000..137b2a95705
--- /dev/null
+++ b/tests/travis/install-sqlsrv-dependencies.sh
@@ -0,0 +1,10 @@
+#!/usr/bin/env bash
+
+set -ex
+
+echo Installing driver dependencies
+
+curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
+curl https://packages.microsoft.com/config/ubuntu/14.04/prod.list | sudo tee /etc/apt/sources.list.d/mssql.list
+sudo apt-get update
+ACCEPT_EULA=Y sudo apt-get install -qy msodbcsql17 unixodbc unixodbc-dev libssl1.0.0
diff --git a/tests/travis/mariadb.mysqli.travis.xml b/tests/travis/mariadb.mysqli.travis.xml
index 46e7ea4853a..dfc62d307c5 100644
--- a/tests/travis/mariadb.mysqli.travis.xml
+++ b/tests/travis/mariadb.mysqli.travis.xml
@@ -37,10 +37,6 @@
-
-
-
-
performance
diff --git a/tests/travis/mariadb.travis.xml b/tests/travis/mariadb.travis.xml
index 132c27f3dab..0d4e2c43c9e 100644
--- a/tests/travis/mariadb.travis.xml
+++ b/tests/travis/mariadb.travis.xml
@@ -36,10 +36,6 @@
-
-
-
-
performance
diff --git a/tests/travis/mysql.docker.travis.xml b/tests/travis/mysql.docker.travis.xml
index 21fae6f35e9..fa6617c0948 100644
--- a/tests/travis/mysql.docker.travis.xml
+++ b/tests/travis/mysql.docker.travis.xml
@@ -36,10 +36,6 @@
-
-
-
-
performance
diff --git a/tests/travis/mysql.travis.xml b/tests/travis/mysql.travis.xml
index 132c27f3dab..0d4e2c43c9e 100644
--- a/tests/travis/mysql.travis.xml
+++ b/tests/travis/mysql.travis.xml
@@ -36,10 +36,6 @@
-
-
-
-
performance
diff --git a/tests/travis/mysqli.docker.travis.xml b/tests/travis/mysqli.docker.travis.xml
index 935815e9cf4..679415d7a18 100644
--- a/tests/travis/mysqli.docker.travis.xml
+++ b/tests/travis/mysqli.docker.travis.xml
@@ -36,10 +36,6 @@
-
-
-
-
performance
diff --git a/tests/travis/mysqli.travis.xml b/tests/travis/mysqli.travis.xml
index 8348cab6343..b8bd9be01cd 100644
--- a/tests/travis/mysqli.travis.xml
+++ b/tests/travis/mysqli.travis.xml
@@ -36,10 +36,6 @@
-
-
-
-
performance
diff --git a/tests/travis/pdo_sqlsrv.travis.xml b/tests/travis/pdo_sqlsrv.travis.xml
index 31de675b016..07f947600ea 100644
--- a/tests/travis/pdo_sqlsrv.travis.xml
+++ b/tests/travis/pdo_sqlsrv.travis.xml
@@ -36,10 +36,6 @@
-
-
-
-
performance
diff --git a/tests/travis/pgsql.travis.xml b/tests/travis/pgsql.travis.xml
index 27a671b8b22..5215f2e6f1b 100644
--- a/tests/travis/pgsql.travis.xml
+++ b/tests/travis/pgsql.travis.xml
@@ -36,10 +36,6 @@
-
-
-
-
performance
diff --git a/tests/travis/sqlite.travis.xml b/tests/travis/sqlite.travis.xml
index bfc18433db7..c6e3e291fce 100644
--- a/tests/travis/sqlite.travis.xml
+++ b/tests/travis/sqlite.travis.xml
@@ -23,10 +23,6 @@
-
-
-
-
performance
diff --git a/tests/travis/sqlsrv.travis.xml b/tests/travis/sqlsrv.travis.xml
index f5ca622d3a7..6c642e58e9a 100644
--- a/tests/travis/sqlsrv.travis.xml
+++ b/tests/travis/sqlsrv.travis.xml
@@ -36,10 +36,6 @@
-
-
-
-
performance