Unverified Commit 61a06a5f authored by Sergei Morozov's avatar Sergei Morozov Committed by GitHub

Merge pull request #4082 from morozov/remove-deprecated

Backport removal of deprecated APIs from develop
parents d89cf163 6a7f6904
# Upgrade to 3.0
## BC BREAK: `Doctrine\DBAL\Types\Type::__toString()` removed
Relying on string representation was discouraged and has been removed.
## BC BREAK: Changes in the `Doctrine\DBAL\Schema` API
- Removed unused method `Doctrine\DBAL\Schema\AbstractSchemaManager::_getPortableFunctionsList()`
- Removed unused method `Doctrine\DBAL\Schema\AbstractSchemaManager::_getPortableFunctionDefinition()`
- Removed unused method `Doctrine\DBAL\Schema\OracleSchemaManager::_getPortableFunctionDefinition()`
- Removed unused method `Doctrine\DBAL\Schema\SqliteSchemaManager::_getPortableTableIndexDefinition()`
## BC BREAK: Removed support for DB-generated UUIDs
The support for DB-generated UUIDs was removed as non-portable.
Please generate UUIDs on the application side (e.g. using [ramsey/uuid](https://packagist.org/packages/ramsey/uuid)).
## BC BREAK: Changes in the `Doctrine\DBAL\Connection` API
- The following methods have been removed as leaking internal implementation details: `::getHost()`, `::getPort()`, `::getUsername()`, `::getPassword()`.
## BC BREAK: Changes in the `Doctrine\DBAL\Event` API
- `ConnectionEventArgs::getDriver()`, `::getDatabasePlatform()` and `::getSchemaManager()` methods have been removed. The connection information can be obtained from the connection which is available via `::getConnection()`.
- `SchemaColumnDefinitionEventArgs::getDatabasePlatform()` and `SchemaIndexDefinitionEventArgs::getDatabasePlatform()` have been removed for the same reason as above.
## BC BREAK: Changes in obtaining the currently selected database name
- The `Doctrine\DBAL\Driver::getDatabase()` method has been removed. Please use `Doctrine\DBAL\Connection::getDatabase()` instead.
- `Doctrine\DBAL\Connection::getDatabase()` will always return the name of the database currently connected to, regardless of the configuration parameters and will initialize a database connection if it's not yet established.
- A call to `Doctrine\DBAL\Connection::getDatabase()`, when connected to an SQLite database, will no longer return the database file path.
## BC BREAK: `Doctrine\DBAL\Driver::getName()` removed
The `Doctrine\DBAL\Driver::getName()` has been removed.
## BC BREAK Removed previously deprecated features
* Removed `json_array` type and all associated hacks.
* Removed `Connection::TRANSACTION_*` constants.
* Removed `AbstractPlatform::DATE_INTERVAL_UNIT_*` and `AbstractPlatform::TRIM_*` constants.
* Removed `MysqlSessionInit` listener.
* Removed `MysqlPlatform::getCollationFieldDeclaration()`.
* Removed `AbstractPlatform::getIdentityColumnNullInsertSQL()`.
* Removed `Table::addUnnamedForeignKeyConstraint()` and `Table::addNamedForeignKeyConstraint()`.
* Removed `Table::renameColumn()`.
* Removed `SQLParserUtils::getPlaceholderPositions()`.
* Removed `LoggerChain::addLogger`.
* Removed `AbstractSchemaManager::getFilterSchemaAssetsExpression()`, `Configuration::getFilterSchemaAssetsExpression()`
and `Configuration::getFilterSchemaAssetsExpression()`.
* `SQLParserUtils::*_TOKEN` constants made private.
## BC BREAK changes the `Driver::connect()` signature
The method no longer accepts the `$username`, `$password` and `$driverOptions` arguments. The corresponding values are expected to be passed as the "user", "password" and "driver_options" keys of the `$params` argument respectively.
......
......@@ -4,9 +4,6 @@ namespace Doctrine\DBAL;
use Doctrine\Common\Cache\Cache;
use Doctrine\DBAL\Logging\SQLLogger;
use Doctrine\DBAL\Schema\AbstractAsset;
use function preg_match;
/**
* Configuration container for the Doctrine DBAL.
......@@ -64,55 +61,6 @@ class Configuration
$this->_attributes['resultCacheImpl'] = $cacheImpl;
}
/**
* Sets the filter schema assets expression.
*
* Only include tables/sequences matching the filter expression regexp in
* schema instances generated for the active connection when calling
* {AbstractSchemaManager#createSchema()}.
*
* @deprecated Use Configuration::setSchemaAssetsFilter() instead
*
* @param string|null $filterExpression
*
* @return void
*/
public function setFilterSchemaAssetsExpression($filterExpression)
{
$this->_attributes['filterSchemaAssetsExpression'] = $filterExpression;
if ($filterExpression !== null) {
$this->_attributes['filterSchemaAssetsExpressionCallable'] = $this->buildSchemaAssetsFilterFromExpression($filterExpression);
} else {
$this->_attributes['filterSchemaAssetsExpressionCallable'] = null;
}
}
/**
* Returns filter schema assets expression.
*
* @deprecated Use Configuration::getSchemaAssetsFilter() instead
*
* @return string|null
*/
public function getFilterSchemaAssetsExpression()
{
return $this->_attributes['filterSchemaAssetsExpression'] ?? null;
}
/**
* @param string $filterExpression
*/
private function buildSchemaAssetsFilterFromExpression($filterExpression): callable
{
return static function ($assetName) use ($filterExpression) {
if ($assetName instanceof AbstractAsset) {
$assetName = $assetName->getName();
}
return preg_match($filterExpression, $assetName);
};
}
/**
* Sets the callable to use to filter schema assets.
*/
......
......@@ -40,34 +40,6 @@ use function key;
*/
class Connection implements DriverConnection
{
/**
* Constant for transaction isolation level READ UNCOMMITTED.
*
* @deprecated Use TransactionIsolationLevel::READ_UNCOMMITTED.
*/
public const TRANSACTION_READ_UNCOMMITTED = TransactionIsolationLevel::READ_UNCOMMITTED;
/**
* Constant for transaction isolation level READ COMMITTED.
*
* @deprecated Use TransactionIsolationLevel::READ_COMMITTED.
*/
public const TRANSACTION_READ_COMMITTED = TransactionIsolationLevel::READ_COMMITTED;
/**
* Constant for transaction isolation level REPEATABLE READ.
*
* @deprecated Use TransactionIsolationLevel::REPEATABLE_READ.
*/
public const TRANSACTION_REPEATABLE_READ = TransactionIsolationLevel::REPEATABLE_READ;
/**
* Constant for transaction isolation level SERIALIZABLE.
*
* @deprecated Use TransactionIsolationLevel::SERIALIZABLE.
*/
public const TRANSACTION_SERIALIZABLE = TransactionIsolationLevel::SERIALIZABLE;
/**
* Represents an array of ints to be expanded by Doctrine SQL parsing.
*/
......@@ -225,61 +197,23 @@ class Connection implements DriverConnection
}
/**
* Gets the name of the database this Connection is connected to.
*
* @return string
*/
public function getDatabase()
{
return $this->_driver->getDatabase($this);
}
/**
* Gets the hostname of the currently connected database.
*
* @deprecated
*
* @return string|null
*/
public function getHost()
{
return $this->params['host'] ?? null;
}
/**
* Gets the port of the currently connected database.
* Gets the name of the currently selected database.
*
* @deprecated
* @return string|null The name of the database or NULL if a database is not selected.
* The platforms which don't support the concept of a database (e.g. embedded databases)
* must always return a string as an indicator of an implicitly selected database.
*
* @return mixed
* @throws DBALException
*/
public function getPort()
public function getDatabase()
{
return $this->params['port'] ?? null;
}
$platform = $this->getDatabasePlatform();
$query = $platform->getDummySelectSQL($platform->getCurrentDatabaseExpression());
$database = $this->query($query)->fetchOne();
/**
* Gets the username used by this connection.
*
* @deprecated
*
* @return string|null
*/
public function getUsername()
{
return $this->params['user'] ?? null;
}
assert(is_string($database) || $database === null);
/**
* Gets the password used by this connection.
*
* @deprecated
*
* @return string|null
*/
public function getPassword()
{
return $this->params['password'] ?? null;
return $database;
}
/**
......
......@@ -39,22 +39,4 @@ interface Driver
* @return AbstractSchemaManager
*/
public function getSchemaManager(Connection $conn);
/**
* Gets the name of the driver.
*
* @deprecated
*
* @return string The name of the driver.
*/
public function getName();
/**
* Gets the name of the database connected to for this driver.
*
* @deprecated Use Connection::getDatabase() instead.
*
* @return string The name of the database.
*/
public function getDatabase(Connection $conn);
}
......@@ -12,18 +12,6 @@ use Doctrine\DBAL\Schema\DB2SchemaManager;
*/
abstract class AbstractDB2Driver implements Driver
{
/**
* {@inheritdoc}
*
* @deprecated Use Connection::getDatabase() instead.
*/
public function getDatabase(Connection $conn)
{
$params = $conn->getParams();
return $params['dbname'];
}
/**
* {@inheritdoc}
*/
......
......@@ -194,18 +194,6 @@ abstract class AbstractMySQLDriver implements ExceptionConverterDriver, VersionA
return $versionParts['major'] . '.' . $versionParts['minor'] . '.' . $versionParts['patch'];
}
/**
* {@inheritdoc}
*
* @deprecated Use Connection::getDatabase() instead.
*/
public function getDatabase(Connection $conn)
{
$params = $conn->getParams();
return $params['dbname'] ?? $conn->query('SELECT DATABASE()')->fetchOne();
}
/**
* {@inheritdoc}
*
......
......@@ -57,18 +57,6 @@ abstract class AbstractOracleDriver implements Driver, ExceptionConverterDriver
return new Exception\DriverException($message, $exception);
}
/**
* {@inheritdoc}
*
* @deprecated Use Connection::getDatabase() instead.
*/
public function getDatabase(Connection $conn)
{
$params = $conn->getParams();
return $params['user'];
}
/**
* {@inheritdoc}
*/
......
......@@ -102,18 +102,6 @@ abstract class AbstractPostgreSQLDriver implements ExceptionConverterDriver, Ver
return new PostgreSQL94Platform();
}
/**
* {@inheritdoc}
*
* @deprecated Use Connection::getDatabase() instead.
*/
public function getDatabase(Connection $conn)
{
$params = $conn->getParams();
return $params['dbname'] ?? $conn->query('SELECT CURRENT_DATABASE()')->fetchOne();
}
/**
* {@inheritdoc}
*/
......
......@@ -12,18 +12,6 @@ use Doctrine\DBAL\Schema\SQLServerSchemaManager;
*/
abstract class AbstractSQLServerDriver implements Driver
{
/**
* {@inheritdoc}
*
* @deprecated Use Connection::getDatabase() instead.
*/
public function getDatabase(Connection $conn)
{
$params = $conn->getParams();
return $params['dbname'] ?? $conn->query('SELECT DB_NAME()')->fetchOne();
}
/**
* {@inheritdoc}
*/
......
......@@ -77,18 +77,6 @@ abstract class AbstractSQLiteDriver implements Driver, ExceptionConverterDriver
return new Exception\DriverException($message, $exception);
}
/**
* {@inheritdoc}
*
* @deprecated Use Connection::getDatabase() instead.
*/
public function getDatabase(Connection $conn)
{
$params = $conn->getParams();
return $params['path'] ?? null;
}
/**
* {@inheritdoc}
*/
......
......@@ -22,14 +22,4 @@ class DB2Driver extends AbstractDB2Driver
$params['driver_options'] ?? []
);
}
/**
* {@inheritdoc}
*
* @deprecated
*/
public function getName()
{
return 'ibm_db2';
}
}
......@@ -113,12 +113,4 @@ class Driver extends AbstractMySQLDriver
return $initializers;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'mysqli';
}
}
......@@ -37,14 +37,4 @@ class Driver extends AbstractOracleDriver
{
return $this->getEasyConnectString($params);
}
/**
* {@inheritdoc}
*
* @deprecated
*/
public function getName()
{
return 'oci8';
}
}
......@@ -42,13 +42,6 @@ class OCI8Statement implements Statement
/** @var OCI8Connection */
protected $_conn;
/**
* @deprecated
*
* @var string
*/
protected static $_PARAM = ':param';
/** @var string[] */
protected $_paramMap = [];
......
......@@ -62,14 +62,4 @@ class Driver extends AbstractMySQLDriver
return $dsn;
}
/**
* {@inheritdoc}
*
* @deprecated
*/
public function getName()
{
return 'pdo_mysql';
}
}
......@@ -52,12 +52,4 @@ class Driver extends AbstractOracleDriver
return $dsn;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'pdo_oracle';
}
}
......@@ -107,14 +107,4 @@ class Driver extends AbstractPostgreSQLDriver
return $dsn;
}
/**
* {@inheritdoc}
*
* @deprecated
*/
public function getName()
{
return 'pdo_pgsql';
}
}
......@@ -69,14 +69,4 @@ class Driver extends AbstractSQLiteDriver
return $dsn;
}
/**
* {@inheritdoc}
*
* @deprecated
*/
public function getName()
{
return 'pdo_sqlite';
}
}
......@@ -88,14 +88,4 @@ class Driver extends AbstractSQLServerDriver
return $connectionOptionsDsn;
}
/**
* {@inheritdoc}
*
* @deprecated
*/
public function getName()
{
return 'pdo_sqlsrv';
}
}
......@@ -47,14 +47,4 @@ class Driver extends AbstractSQLServerDriver
return new SQLSrvConnection($serverName, $driverOptions);
}
/**
* {@inheritdoc}
*
* @deprecated
*/
public function getName()
{
return 'sqlsrv';
}
}
......@@ -70,10 +70,8 @@ final class SQLSrvStatement implements 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;';
private const LAST_INSERT_ID_SQL = ';SELECT SCOPE_IDENTITY() AS LastInsertId;';
/**
* @param resource $conn
......
......@@ -4,9 +4,6 @@ namespace Doctrine\DBAL\Event;
use Doctrine\Common\EventArgs;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\AbstractSchemaManager;
/**
* Event Arguments used when a Driver connection is established inside Doctrine\DBAL\Connection.
......@@ -28,34 +25,4 @@ class ConnectionEventArgs extends EventArgs
{
return $this->connection;
}
/**
* @deprecated Use ConnectionEventArgs::getConnection() and Connection::getDriver() instead.
*
* @return Driver
*/
public function getDriver()
{
return $this->connection->getDriver();
}
/**
* @deprecated Use ConnectionEventArgs::getConnection() and Connection::getDatabasePlatform() instead.
*
* @return AbstractPlatform
*/
public function getDatabasePlatform()
{
return $this->connection->getDatabasePlatform();
}
/**
* @deprecated Use ConnectionEventArgs::getConnection() and Connection::getSchemaManager() instead.
*
* @return AbstractSchemaManager
*/
public function getSchemaManager()
{
return $this->connection->getSchemaManager();
}
}
<?php
namespace Doctrine\DBAL\Event\Listeners;
use Doctrine\Common\EventSubscriber;
use Doctrine\DBAL\Event\ConnectionEventArgs;
use Doctrine\DBAL\Events;
/**
* MySQL Session Init Event Subscriber which allows to set the Client Encoding of the Connection.
*
* @deprecated Use "charset" option to PDO MySQL Connection instead.
*/
class MysqlSessionInit implements EventSubscriber
{
/**
* The charset.
*
* @var string
*/
private $charset;
/**
* The collation, or FALSE if no collation.
*
* @var string|bool
*/
private $collation;
/**
* Configure Charset and Collation options of MySQL Client for each Connection.
*
* @param string $charset The charset.
* @param string|bool $collation The collation, or FALSE if no collation.
*/
public function __construct($charset = 'utf8', $collation = false)
{
$this->charset = $charset;
$this->collation = $collation;
}
/**
* @return void
*/
public function postConnect(ConnectionEventArgs $args)
{
$statement = 'SET NAMES ' . $this->charset;
if ($this->collation !== false) {
$statement .= ' COLLATE ' . $this->collation;
}
$args->getConnection()->executeUpdate($statement);
}
/**
* {@inheritdoc}
*/
public function getSubscribedEvents()
{
return [Events::postConnect];
}
}
......@@ -3,7 +3,6 @@
namespace Doctrine\DBAL\Event;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\Column;
/**
......@@ -95,14 +94,4 @@ class SchemaColumnDefinitionEventArgs extends SchemaEventArgs
{
return $this->connection;
}
/**
* @deprecated Use SchemaColumnDefinitionEventArgs::getConnection() and Connection::getDatabasePlatform() instead.
*
* @return AbstractPlatform
*/
public function getDatabasePlatform()
{
return $this->connection->getDatabasePlatform();
}
}
......@@ -3,7 +3,6 @@
namespace Doctrine\DBAL\Event;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\Index;
/**
......@@ -81,12 +80,4 @@ class SchemaIndexDefinitionEventArgs extends SchemaEventArgs
{
return $this->connection;
}
/**
* @return AbstractPlatform
*/
public function getDatabasePlatform()
{
return $this->connection->getDatabasePlatform();
}
}
......@@ -7,29 +7,17 @@ namespace Doctrine\DBAL\Logging;
*/
class LoggerChain implements SQLLogger
{
/** @var SQLLogger[] */
/** @var iterable<SQLLogger> */
private $loggers = [];
/**
* @param SQLLogger[] $loggers
* @param iterable<SQLLogger> $loggers
*/
public function __construct(array $loggers = [])
public function __construct(iterable $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)
{
$this->loggers[] = $logger;
}
/**
* {@inheritdoc}
*/
......
......@@ -71,66 +71,6 @@ abstract class AbstractPlatform
public const CREATE_FOREIGNKEYS = 2;
/**
* @deprecated Use DateIntervalUnit::INTERVAL_UNIT_SECOND.
*/
public const DATE_INTERVAL_UNIT_SECOND = DateIntervalUnit::SECOND;
/**
* @deprecated Use DateIntervalUnit::MINUTE.
*/
public const DATE_INTERVAL_UNIT_MINUTE = DateIntervalUnit::MINUTE;
/**
* @deprecated Use DateIntervalUnit::HOUR.
*/
public const DATE_INTERVAL_UNIT_HOUR = DateIntervalUnit::HOUR;
/**
* @deprecated Use DateIntervalUnit::DAY.
*/
public const DATE_INTERVAL_UNIT_DAY = DateIntervalUnit::DAY;
/**
* @deprecated Use DateIntervalUnit::WEEK.
*/
public const DATE_INTERVAL_UNIT_WEEK = DateIntervalUnit::WEEK;
/**
* @deprecated Use DateIntervalUnit::MONTH.
*/
public const DATE_INTERVAL_UNIT_MONTH = DateIntervalUnit::MONTH;
/**
* @deprecated Use DateIntervalUnit::QUARTER.
*/
public const DATE_INTERVAL_UNIT_QUARTER = DateIntervalUnit::QUARTER;
/**
* @deprecated Use DateIntervalUnit::QUARTER.
*/
public const DATE_INTERVAL_UNIT_YEAR = DateIntervalUnit::YEAR;
/**
* @deprecated Use TrimMode::UNSPECIFIED.
*/
public const TRIM_UNSPECIFIED = TrimMode::UNSPECIFIED;
/**
* @deprecated Use TrimMode::LEADING.
*/
public const TRIM_LEADING = TrimMode::LEADING;
/**
* @deprecated Use TrimMode::TRAILING.
*/
public const TRIM_TRAILING = TrimMode::TRAILING;
/**
* @deprecated Use TrimMode::BOTH.
*/
public const TRIM_BOTH = TrimMode::BOTH;
/** @var string[]|null */
protected $doctrineTypeMapping = null;
......@@ -643,20 +583,6 @@ abstract class AbstractPlatform
throw DBALException::notSupported(__METHOD__);
}
/**
* Returns the global unique identifier expression.
*
* @deprecated Use application-generated UUIDs instead
*
* @return string
*
* @throws DBALException If not supported on this platform.
*/
public function getGuidExpression()
{
throw DBALException::notSupported(__METHOD__);
}
/**
* Returns the SQL snippet to get the average value of a column.
*
......@@ -1344,6 +1270,11 @@ abstract class AbstractPlatform
return '(' . $value1 . ' | ' . $value2 . ')';
}
/**
* Returns the SQL expression which represents the currently selected database.
*/
abstract public function getCurrentDatabaseExpression(): string;
/**
* Returns the FOR UPDATE expression.
*
......@@ -2162,18 +2093,6 @@ abstract class AbstractPlatform
];
}
/**
* Common code for alter table statement generation that updates the changed Index and Foreign Key definitions.
*
* @deprecated
*
* @return string[]
*/
protected function _getAlterTableIndexForeignKeySQL(TableDiff $diff)
{
return array_merge($this->getPreAlterTableIndexForeignKeySQL($diff), $this->getPostAlterTableIndexForeignKeySQL($diff));
}
/**
* Gets declaration of a number of fields in bulk.
*
......@@ -2389,7 +2308,7 @@ abstract class AbstractPlatform
}
return 'CONSTRAINT ' . $name->getQuotedName($this) . ' UNIQUE ('
. $this->getIndexFieldDeclarationListSQL($index)
. $this->getColumnsFieldDeclarationListSQL($columns)
. ')' . $this->getPartialIndexSQL($index);
}
......@@ -2435,22 +2354,23 @@ abstract class AbstractPlatform
/**
* Obtains DBMS specific SQL code portion needed to set an index
* declaration to be used in statements like CREATE TABLE.
*
* @param mixed[]|Index $columnsOrIndex array declaration is deprecated, prefer passing Index to this method
*/
public function getIndexFieldDeclarationListSQL($columnsOrIndex): string
public function getIndexFieldDeclarationListSQL(Index $index): string
{
if ($columnsOrIndex instanceof Index) {
return implode(', ', $columnsOrIndex->getQuotedColumns($this));
}
if (! is_array($columnsOrIndex)) {
throw new InvalidArgumentException('Fields argument should be an Index or array.');
return implode(', ', $index->getQuotedColumns($this));
}
/**
* Obtains DBMS specific SQL code portion needed to set an index
* declaration to be used in statements like CREATE TABLE.
*
* @param mixed[] $columns
*/
public function getColumnsFieldDeclarationListSQL(array $columns): string
{
$ret = [];
foreach ($columnsOrIndex as $column => $definition) {
foreach ($columns as $column => $definition) {
if (is_array($definition)) {
$ret[] = $column;
} else {
......@@ -3317,18 +3237,6 @@ abstract class AbstractPlatform
return false;
}
/**
* @deprecated
*
* @return string
*
* @todo Remove in 3.0
*/
public function getIdentityColumnNullInsertSQL()
{
return '';
}
/**
* Whether this platform supports views.
*
......
......@@ -840,6 +840,11 @@ class DB2Platform extends AbstractPlatform
return 'SUBSTR(' . $value . ', ' . $from . ', ' . $length . ')';
}
public function getCurrentDatabaseExpression(): string
{
return 'CURRENT_USER';
}
/**
* {@inheritDoc}
*/
......
......@@ -79,16 +79,6 @@ class MySqlPlatform extends AbstractPlatform
return 'RLIKE';
}
/**
* {@inheritDoc}
*
* @deprecated Use application-generated UUIDs instead
*/
public function getGuidExpression()
{
return 'UUID()';
}
/**
* {@inheritDoc}
*/
......@@ -127,6 +117,11 @@ class MySqlPlatform extends AbstractPlatform
return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
}
public function getCurrentDatabaseExpression(): string
{
return 'DATABASE()';
}
/**
* {@inheritDoc}
*/
......@@ -305,22 +300,6 @@ class MySqlPlatform extends AbstractPlatform
return 'TINYINT(1)';
}
/**
* Obtain DBMS specific SQL code portion needed to set the COLLATION
* of a field declaration to be used in statements like CREATE TABLE.
*
* @deprecated Deprecated since version 2.5, Use {@link self::getColumnCollationDeclarationSQL()} instead.
*
* @param string $collation name of the collation
*
* @return string DBMS specific SQL code portion needed to set the COLLATION
* of a field declaration.
*/
public function getCollationFieldDeclaration($collation)
{
return $this->getColumnCollationDeclarationSQL($collation);
}
/**
* {@inheritDoc}
*
......
......@@ -89,16 +89,6 @@ class OraclePlatform extends AbstractPlatform
return 'INSTR(' . $str . ', ' . $substr . ', ' . $startPos . ')';
}
/**
* {@inheritDoc}
*
* @deprecated Use application-generated UUIDs instead
*/
public function getGuidExpression()
{
return 'SYS_GUID()';
}
/**
* {@inheritdoc}
*/
......@@ -161,6 +151,11 @@ class OraclePlatform extends AbstractPlatform
return 'BITAND(' . $value1 . ', ' . $value2 . ')';
}
public function getCurrentDatabaseExpression(): string
{
return "SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')";
}
/**
* {@inheritDoc}
*/
......
......@@ -139,6 +139,11 @@ class PostgreSQL94Platform extends AbstractPlatform
return '(DATE(' . $date1 . ')-DATE(' . $date2 . '))';
}
public function getCurrentDatabaseExpression(): string
{
return 'CURRENT_DATABASE()';
}
/**
* {@inheritDoc}
*/
......@@ -1025,16 +1030,6 @@ SQL
return 'TIME(0) WITHOUT TIME ZONE';
}
/**
* {@inheritDoc}
*
* @deprecated Use application-generated UUIDs instead
*/
public function getGuidExpression()
{
return 'UUID_GENERATE_V4()';
}
/**
* {@inheritDoc}
*/
......@@ -1153,8 +1148,8 @@ SQL
'int8' => 'bigint',
'integer' => 'integer',
'interval' => 'string',
'json' => Type::JSON,
'jsonb' => Type::JSON,
'json' => 'json',
'jsonb' => 'json',
'money' => 'decimal',
'numeric' => 'decimal',
'serial' => 'integer',
......
......@@ -1083,16 +1083,6 @@ SQL
return 'DROP VIEW ' . $name;
}
/**
* {@inheritDoc}
*
* @deprecated Use application-generated UUIDs instead
*/
public function getGuidExpression()
{
return 'NEWID()';
}
/**
* {@inheritDoc}
*/
......@@ -1203,6 +1193,11 @@ SQL
return 'LEN(' . $column . ')';
}
public function getCurrentDatabaseExpression(): string
{
return 'DB_NAME()';
}
/**
* {@inheritDoc}
*/
......
......@@ -41,19 +41,6 @@ class SqlitePlatform extends AbstractPlatform
return 'REGEXP';
}
/**
* {@inheritDoc}
*
* @deprecated Use application-generated UUIDs instead
*/
public function getGuidExpression()
{
return "HEX(RANDOMBLOB(4)) || '-' || HEX(RANDOMBLOB(2)) || '-4' || "
. "SUBSTR(HEX(RANDOMBLOB(2)), 2) || '-' || "
. "SUBSTR('89AB', 1 + (ABS(RANDOM()) % 4), 1) || "
. "SUBSTR(HEX(RANDOMBLOB(2)), 2) || '-' || HEX(RANDOMBLOB(6))";
}
/**
* @param string $type
*
......@@ -162,6 +149,19 @@ class SqlitePlatform extends AbstractPlatform
return sprintf("JULIANDAY(%s, 'start of day') - JULIANDAY(%s, 'start of day')", $date1, $date2);
}
/**
* {@inheritDoc}
*
* The SQLite platform doesn't support the concept of a database, therefore, it always returns an empty string
* as an indicator of an implicitly selected database.
*
* @see \Doctrine\DBAL\Connection::getDatabase()
*/
public function getCurrentDatabaseExpression(): string
{
return "''";
}
/**
* {@inheritDoc}
*/
......
......@@ -27,39 +27,17 @@ use const PREG_OFFSET_CAPTURE;
*/
class SQLParserUtils
{
private const POSITIONAL_TOKEN = '\?';
private const NAMED_TOKEN = '(?<!:):[a-zA-Z_][a-zA-Z0-9_]*';
/**#@+
*
* @deprecated Will be removed as internal implementation details.
* Quote characters within string literals can be preceded by a backslash.
*/
public const POSITIONAL_TOKEN = '\?';
public const NAMED_TOKEN = '(?<!:):[a-zA-Z_][a-zA-Z0-9_]*';
// Quote characters within string literals can be preceded by a backslash.
public const ESCAPED_SINGLE_QUOTED_TEXT = "(?:'(?:\\\\)+'|'(?:[^'\\\\]|\\\\'?|'')*')";
public const ESCAPED_DOUBLE_QUOTED_TEXT = '(?:"(?:\\\\)+"|"(?:[^"\\\\]|\\\\"?)*")';
public const ESCAPED_BACKTICK_QUOTED_TEXT = '(?:`(?:\\\\)+`|`(?:[^`\\\\]|\\\\`?)*`)';
/**#@-*/
private const ESCAPED_SINGLE_QUOTED_TEXT = "(?:'(?:\\\\)+'|'(?:[^'\\\\]|\\\\'?|'')*')";
private const ESCAPED_DOUBLE_QUOTED_TEXT = '(?:"(?:\\\\)+"|"(?:[^"\\\\]|\\\\"?)*")';
private const ESCAPED_BACKTICK_QUOTED_TEXT = '(?:`(?:\\\\)+`|`(?:[^`\\\\]|\\\\`?)*`)';
private const ESCAPED_BRACKET_QUOTED_TEXT = '(?<!\b(?i:ARRAY))\[(?:[^\]])*\]';
/**
* Gets an array of the placeholders in an sql statements as keys and their positions in the query string.
*
* 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[]|string[]
*/
public static function getPlaceholderPositions($statement, $isPositional = true)
{
return $isPositional
? self::getPositionalPlaceholderPositions($statement)
: self::getNamedPlaceholderPositions($statement);
}
/**#@-*/
/**
* Returns a zero-indexed list of placeholder position.
......
......@@ -235,16 +235,6 @@ abstract class AbstractSchemaManager
return array_values(array_filter($assetNames, $filter));
}
/**
* @deprecated Use Configuration::getSchemaAssetsFilter() instead
*
* @return string|null
*/
protected function getFilterSchemaAssetsExpression()
{
return $this->_conn->getConfiguration()->getFilterSchemaAssetsExpression();
}
/**
* Lists the tables for this connection.
*
......@@ -678,41 +668,6 @@ abstract class AbstractSchemaManager
return $namespace;
}
/**
* @deprecated
*
* @param mixed[][] $functions
*
* @return mixed[][]
*/
protected function _getPortableFunctionsList($functions)
{
$list = [];
foreach ($functions as $value) {
$value = $this->_getPortableFunctionDefinition($value);
if (! $value) {
continue;
}
$list[] = $value;
}
return $list;
}
/**
* @deprecated
*
* @param mixed[] $function
*
* @return mixed
*/
protected function _getPortableFunctionDefinition($function)
{
return $function;
}
/**
* @param mixed[][] $triggers
*
......@@ -1082,7 +1037,13 @@ abstract class AbstractSchemaManager
*/
public function getSchemaSearchPaths()
{
return [$this->_conn->getDatabase()];
$database = $this->_conn->getDatabase();
if ($database !== null) {
return [$database];
}
return [];
}
/**
......
......@@ -2,15 +2,12 @@
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Schema\Exception\UnknownColumnOption;
use Doctrine\DBAL\Types\Type;
use function array_merge;
use function is_numeric;
use function method_exists;
use function sprintf;
use function trigger_error;
use const E_USER_DEPRECATED;
/**
* Object representation of a database column.
......@@ -78,15 +75,9 @@ class Column extends AbstractAsset
{
foreach ($options as $name => $value) {
$method = 'set' . $name;
if (! method_exists($this, $method)) {
// next major: throw an exception
@trigger_error(sprintf(
'The "%s" column option is not supported,' .
' setting it is deprecated and will cause an error in Doctrine DBAL 3.0',
$name
), E_USER_DEPRECATED);
continue;
throw UnknownColumnOption::new($name);
}
$this->$method($value);
......
......@@ -9,7 +9,6 @@ use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function array_shift;
use function array_unique;
use function assert;
use function count;
......@@ -440,13 +439,6 @@ class Comparator
$changedProperties[] = $property;
}
// This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
if ($this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
array_shift($changedProperties);
$changedProperties[] = 'comment';
}
// Null values need to be checked additionally as they tell whether to create or drop a default value.
// null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
if (
......@@ -514,21 +506,6 @@ class Comparator
return array_unique($changedProperties);
}
/**
* TODO: kill with fire on v3.0
*
* @deprecated
*/
private function isALegacyJsonComparison(Types\Type $one, Types\Type $other): bool
{
if (! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) {
return false;
}
return ( ! $one instanceof Types\JsonArrayType && $other instanceof Types\JsonArrayType)
|| ( ! $other instanceof Types\JsonArrayType && $one instanceof Types\JsonArrayType);
}
/**
* Finds the difference between the indexes $index1 and $index2.
*
......
......@@ -28,8 +28,7 @@ class DB2SchemaManager extends AbstractSchemaManager
*/
public function listTableNames()
{
$sql = $this->_platform->getListTablesSQL();
$sql .= ' AND CREATOR = UPPER(' . $this->_conn->quote($this->_conn->getUsername()) . ')';
$sql = $this->_platform->getListTablesSQL() . ' AND CREATOR = CURRENT_USER';
$tables = $this->_conn->fetchAllAssociative($sql);
......
<?php
declare(strict_types=1);
namespace Doctrine\DBAL\Schema\Exception;
use Doctrine\DBAL\Schema\SchemaException;
use function sprintf;
/**
* @psalm-immutable
*/
final class UnknownColumnOption extends SchemaException
{
public static function new(string $name): self
{
return new self(
sprintf('The "%s" column option is not supported.', $name)
);
}
}
......@@ -267,18 +267,6 @@ class OracleSchemaManager extends AbstractSchemaManager
);
}
/**
* {@inheritdoc}
*
* @deprecated
*/
protected function _getPortableFunctionDefinition($function)
{
$function = array_change_key_case($function, CASE_LOWER);
return $function['name'];
}
/**
* {@inheritdoc}
*/
......
......@@ -497,7 +497,7 @@ class PostgreSqlSchemaManager extends AbstractSchemaManager
$column->setPlatformOption('collation', $tableColumn['collation']);
}
if (in_array($column->getType()->getName(), [Types::JSON_ARRAY, Types::JSON], true)) {
if ($column->getType()->getName() === Types::JSON) {
$column->setPlatformOption('jsonb', $jsonb);
}
......
......@@ -224,21 +224,6 @@ class SqliteSchemaManager extends AbstractSchemaManager
return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
}
/**
* @deprecated
*
* @param array<string, mixed> $tableIndex
*
* @return array<string, bool|string>
*/
protected function _getPortableTableIndexDefinition($tableIndex)
{
return [
'name' => $tableIndex['name'],
'unique' => (bool) $tableIndex['unique'],
];
}
/**
* {@inheritdoc}
*/
......
......@@ -302,25 +302,6 @@ class Table extends AbstractAsset
return $column;
}
/**
* Renames a Column.
*
* @deprecated
*
* @param string $oldColumnName
* @param string $newColumnName
*
* @return void
*
* @throws DBALException
*/
public function renameColumn($oldColumnName, $newColumnName)
{
throw new DBALException('Table#renameColumn() was removed, because it drops and recreates ' .
'the column instead. There is no fix available, because a schema diff cannot reliably detect if a ' .
'column was renamed or one column was created and another one dropped.');
}
/**
* Change Column Details.
*
......@@ -361,55 +342,16 @@ class Table extends AbstractAsset
* @param string[] $localColumnNames
* @param string[] $foreignColumnNames
* @param mixed[] $options
* @param string|null $constraintName
*
* @return self
*/
public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [], $constraintName = null)
{
if ($constraintName === null) {
$constraintName = $this->_generateIdentifierName(array_merge((array) $this->getName(), $localColumnNames), 'fk', $this->_getMaxIdentifierLength());
}
return $this->addNamedForeignKeyConstraint($constraintName, $foreignTable, $localColumnNames, $foreignColumnNames, $options);
}
/**
* Adds a foreign key constraint.
*
* Name is to be generated by the database itself.
*
* @deprecated Use {@link addForeignKeyConstraint}
*
* @param Table|string $foreignTable Table schema instance or table name
* @param string[] $localColumnNames
* @param string[] $foreignColumnNames
* @param mixed[] $options
* @param string|null $name
*
* @return self
*/
public function addUnnamedForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [])
public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [], $name = null)
{
return $this->addForeignKeyConstraint($foreignTable, $localColumnNames, $foreignColumnNames, $options);
if ($name === null) {
$name = $this->_generateIdentifierName(array_merge((array) $this->getName(), $localColumnNames), 'fk', $this->_getMaxIdentifierLength());
}
/**
* Adds a foreign key constraint with a given name.
*
* @deprecated Use {@link addForeignKeyConstraint}
*
* @param string $name
* @param Table|string $foreignTable Table schema instance or table name
* @param string[] $localColumnNames
* @param string[] $foreignColumnNames
* @param mixed[] $options
*
* @return self
*
* @throws SchemaException
*/
public function addNamedForeignKeyConstraint($name, $foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [])
{
if ($foreignTable instanceof Table) {
foreach ($foreignColumnNames as $columnName) {
if (! $foreignTable->hasColumn($columnName)) {
......
......@@ -80,7 +80,7 @@ class Graphviz extends AbstractVisitor
$label .= '<TR>';
$label .= '<TD BORDER="0" ALIGN="LEFT" BGCOLOR="#eeeeec">';
$label .= '<FONT COLOR="#2e3436" FACE="Helvetica" POINT-SIZE="12">' . $columnLabel . '</FONT>';
$label .= '</TD><TD BORDER="0" ALIGN="LEFT" BGCOLOR="#eeeeec"><FONT COLOR="#2e3436" FACE="Helvetica" POINT-SIZE="10">' . strtolower($column->getType()) . '</FONT></TD>';
$label .= '</TD><TD BORDER="0" ALIGN="LEFT" BGCOLOR="#eeeeec"><FONT COLOR="#2e3436" FACE="Helvetica" POINT-SIZE="10">' . strtolower($column->getType()->getName()) . '</FONT></TD>';
$label .= '<TD BORDER="0" ALIGN="RIGHT" BGCOLOR="#eeeeec" PORT="col' . $column->getName() . '">';
$primaryKey = $table->getPrimaryKey();
......
<?php
namespace Doctrine\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use function is_resource;
use function json_decode;
use function stream_get_contents;
/**
* Array Type which can be used to generate json arrays.
*
* @deprecated Use JsonType instead
*/
class JsonArrayType extends JsonType
{
/**
* {@inheritdoc}
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ($value === null || $value === '') {
return [];
}
$value = is_resource($value) ? stream_get_contents($value) : $value;
return json_decode($value, true);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return Types::JSON_ARRAY;
}
/**
* {@inheritdoc}
*/
public function requiresSQLCommentHint(AbstractPlatform $platform)
{
return true;
}
}
......@@ -8,9 +8,6 @@ use Doctrine\DBAL\Platforms\AbstractPlatform;
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.
......@@ -19,81 +16,6 @@ use function substr;
*/
abstract class Type
{
/** @deprecated Use {@see Types::BIGINT} instead. */
public const BIGINT = Types::BIGINT;
/** @deprecated Use {@see Types::BINARY} instead. */
public const BINARY = Types::BINARY;
/** @deprecated Use {@see Types::BLOB} instead. */
public const BLOB = Types::BLOB;
/** @deprecated Use {@see Types::BOOLEAN} instead. */
public const BOOLEAN = Types::BOOLEAN;
/** @deprecated Use {@see Types::DATE_MUTABLE} instead. */
public const DATE = Types::DATE_MUTABLE;
/** @deprecated Use {@see Types::DATE_IMMUTABLE} instead. */
public const DATE_IMMUTABLE = Types::DATE_IMMUTABLE;
/** @deprecated Use {@see Types::DATEINTERVAL} instead. */
public const DATEINTERVAL = Types::DATEINTERVAL;
/** @deprecated Use {@see Types::DATETIME_MUTABLE} instead. */
public const DATETIME = Types::DATETIME_MUTABLE;
/** @deprecated Use {@see Types::DATETIME_IMMUTABLE} instead. */
public const DATETIME_IMMUTABLE = Types::DATETIME_IMMUTABLE;
/** @deprecated Use {@see Types::DATETIMETZ_MUTABLE} instead. */
public const DATETIMETZ = Types::DATETIMETZ_MUTABLE;
/** @deprecated Use {@see Types::DATETIMETZ_IMMUTABLE} instead. */
public const DATETIMETZ_IMMUTABLE = Types::DATETIMETZ_IMMUTABLE;
/** @deprecated Use {@see Types::DECIMAL} instead. */
public const DECIMAL = Types::DECIMAL;
/** @deprecated Use {@see Types::FLOAT} instead. */
public const FLOAT = Types::FLOAT;
/** @deprecated Use {@see Types::GUID} instead. */
public const GUID = Types::GUID;
/** @deprecated Use {@see Types::INTEGER} instead. */
public const INTEGER = Types::INTEGER;
/** @deprecated Use {@see Types::JSON} instead. */
public const JSON = Types::JSON;
/** @deprecated Use {@see Types::JSON_ARRAY} instead. */
public const JSON_ARRAY = Types::JSON_ARRAY;
/** @deprecated Use {@see Types::OBJECT} instead. */
public const OBJECT = Types::OBJECT;
/** @deprecated Use {@see Types::SIMPLE_ARRAY} instead. */
public const SIMPLE_ARRAY = Types::SIMPLE_ARRAY;
/** @deprecated Use {@see Types::SMALLINT} instead. */
public const SMALLINT = Types::SMALLINT;
/** @deprecated Use {@see Types::STRING} instead. */
public const STRING = Types::STRING;
/** @deprecated Use {@see Types::ARRAY} instead. */
public const TARRAY = Types::ARRAY;
/** @deprecated Use {@see Types::TEXT} instead. */
public const TEXT = Types::TEXT;
/** @deprecated Use {@see Types::TIME_MUTABLE} instead. */
public const TIME = Types::TIME_MUTABLE;
/** @deprecated Use {@see Types::TIME_IMMUTABLE} instead. */
public const TIME_IMMUTABLE = Types::TIME_IMMUTABLE;
/**
* The map of supported doctrine mapping types.
*/
......@@ -115,7 +37,6 @@ abstract class Type
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,
......@@ -303,23 +224,6 @@ abstract class Type
);
}
/**
* @deprecated Relying on string representation is discouraged and will be removed in DBAL 3.0.
*
* @return string
*/
public function __toString()
{
$type = static::class;
$position = strrpos($type, '\\');
if ($position !== false) {
$type = substr($type, $position);
}
return str_replace('Type', '', $type);
}
/**
* Does working with this column require SQL conversion functions?
*
......
......@@ -34,9 +34,6 @@ final class Types
public const TIME_MUTABLE = 'time';
public const TIME_IMMUTABLE = 'time_immutable';
/** @deprecated json_array type is deprecated, use {@see self::JSON} instead. */
public const JSON_ARRAY = 'json_array';
private function __construct()
{
}
......
......@@ -108,26 +108,6 @@ class ConnectionTest extends TestCase
self::assertInstanceOf(Configuration::class, $config);
}
public function testGetHost(): void
{
self::assertEquals('localhost', $this->connection->getHost());
}
public function testGetPort(): void
{
self::assertEquals('1234', $this->connection->getPort());
}
public function testGetUsername(): void
{
self::assertEquals('root', $this->connection->getUsername());
}
public function testGetPassword(): void
{
self::assertEquals('password', $this->connection->getPassword());
}
public function testGetDriver(): void
{
self::assertInstanceOf(\Doctrine\DBAL\Driver\PDOMySql\Driver::class, $this->connection->getDriver());
......
......@@ -142,23 +142,6 @@ abstract class AbstractDriverTest extends TestCase
$this->driver->createDatabasePlatformForVersion('foo');
}
public function testReturnsDatabaseName(): void
{
$params = [
'user' => 'foo',
'password' => 'bar',
'dbname' => 'baz',
];
$connection = $this->getConnectionMock();
$connection->expects(self::once())
->method('getParams')
->will(self::returnValue($params));
self::assertSame($params['dbname'], $this->driver->getDatabase($connection));
}
public function testReturnsDatabasePlatform(): void
{
self::assertEquals($this->createPlatform(), $this->driver->getDatabasePlatform());
......
......@@ -5,7 +5,6 @@ namespace Doctrine\DBAL\Tests\Driver;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\AbstractMySQLDriver;
use Doctrine\DBAL\Driver\Result;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
use Doctrine\DBAL\Platforms\MySQL57Platform;
......@@ -16,35 +15,6 @@ use Doctrine\DBAL\Schema\MySqlSchemaManager;
class AbstractMySQLDriverTest extends AbstractDriverTest
{
public function testReturnsDatabaseName(): void
{
parent::testReturnsDatabaseName();
$database = 'bloo';
$params = [
'user' => 'foo',
'password' => 'bar',
];
$result = $this->createMock(Result::class);
$result->expects(self::once())
->method('fetchOne')
->will(self::returnValue($database));
$connection = $this->getConnectionMock();
$connection->expects(self::once())
->method('getParams')
->will(self::returnValue($params));
$connection->expects(self::once())
->method('query')
->will(self::returnValue($result));
self::assertSame($database, $this->driver->getDatabase($connection));
}
protected function createDriver(): Driver
{
return $this->getMockForAbstractClass(AbstractMySQLDriver::class);
......
......@@ -12,42 +12,6 @@ use Doctrine\DBAL\Schema\OracleSchemaManager;
class AbstractOracleDriverTest extends AbstractDriverTest
{
public function testReturnsDatabaseName(): void
{
$params = [
'user' => 'foo',
'password' => 'bar',
'dbname' => 'baz',
];
$connection = $this->getConnectionMock();
$connection->expects(self::once())
->method('getParams')
->will(self::returnValue($params));
self::assertSame($params['user'], $this->driver->getDatabase($connection));
}
public function testReturnsDatabaseNameWithConnectDescriptor(): void
{
$params = [
'user' => 'foo',
'password' => 'bar',
'connectionstring' => '(DESCRIPTION=' .
'(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))' .
'(CONNECT_DATA=(SERVICE_NAME=baz)))',
];
$connection = $this->getConnectionMock();
$connection->expects(self::once())
->method('getParams')
->will(self::returnValue($params));
self::assertSame($params['user'], $this->driver->getDatabase($connection));
}
protected function createDriver(): Driver
{
return $this->getMockForAbstractClass(AbstractOracleDriver::class);
......
......@@ -5,7 +5,6 @@ namespace Doctrine\DBAL\Tests\Driver;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\AbstractPostgreSQLDriver;
use Doctrine\DBAL\Driver\Result;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\PostgreSQL100Platform;
use Doctrine\DBAL\Platforms\PostgreSQL94Platform;
......@@ -14,35 +13,6 @@ use Doctrine\DBAL\Schema\PostgreSqlSchemaManager;
class AbstractPostgreSQLDriverTest extends AbstractDriverTest
{
public function testReturnsDatabaseName(): void
{
parent::testReturnsDatabaseName();
$database = 'bloo';
$params = [
'user' => 'foo',
'password' => 'bar',
];
$result = $this->createMock(Result::class);
$result->expects(self::once())
->method('fetchOne')
->will(self::returnValue($database));
$connection = $this->getConnectionMock();
$connection->expects(self::once())
->method('getParams')
->will(self::returnValue($params));
$connection->expects(self::once())
->method('query')
->will(self::returnValue($result));
self::assertSame($database, $this->driver->getDatabase($connection));
}
protected function createDriver(): Driver
{
return $this->getMockForAbstractClass(AbstractPostgreSQLDriver::class);
......
......@@ -12,24 +12,6 @@ use Doctrine\DBAL\Schema\SqliteSchemaManager;
class AbstractSQLiteDriverTest extends AbstractDriverTest
{
public function testReturnsDatabaseName(): void
{
$params = [
'user' => 'foo',
'password' => 'bar',
'dbname' => 'baz',
'path' => 'bloo',
];
$connection = $this->getConnectionMock();
$connection->expects(self::once())
->method('getParams')
->will(self::returnValue($params));
self::assertSame($params['path'], $this->driver->getDatabase($connection));
}
protected function createDriver(): Driver
{
return $this->getMockForAbstractClass(AbstractSQLiteDriver::class);
......
......@@ -8,11 +8,6 @@ use Doctrine\DBAL\Tests\Driver\AbstractDB2DriverTest;
class DB2DriverTest extends AbstractDB2DriverTest
{
public function testReturnsName(): void
{
self::assertSame('ibm_db2', $this->driver->getName());
}
protected function createDriver(): DriverInterface
{
return new DB2Driver();
......
......@@ -8,11 +8,6 @@ use Doctrine\DBAL\Tests\Driver\AbstractMySQLDriverTest;
class DriverTest extends AbstractMySQLDriverTest
{
public function testReturnsName(): void
{
self::assertSame('mysqli', $this->driver->getName());
}
protected function createDriver(): DriverInterface
{
return new Driver();
......
......@@ -8,11 +8,6 @@ use Doctrine\DBAL\Tests\Driver\AbstractOracleDriverTest;
class DriverTest extends AbstractOracleDriverTest
{
public function testReturnsName(): void
{
self::assertSame('oci8', $this->driver->getName());
}
protected function createDriver(): DriverInterface
{
return new Driver();
......
......@@ -8,11 +8,6 @@ use Doctrine\DBAL\Tests\Driver\AbstractMySQLDriverTest;
class DriverTest extends AbstractMySQLDriverTest
{
public function testReturnsName(): void
{
self::assertSame('pdo_mysql', $this->driver->getName());
}
protected function createDriver(): DriverInterface
{
return new Driver();
......
......@@ -8,11 +8,6 @@ use Doctrine\DBAL\Tests\Driver\AbstractOracleDriverTest;
class DriverTest extends AbstractOracleDriverTest
{
public function testReturnsName(): void
{
self::assertSame('pdo_oracle', $this->driver->getName());
}
protected function createDriver(): DriverInterface
{
return new Driver();
......
......@@ -4,77 +4,68 @@ namespace Doctrine\DBAL\Tests\Driver\PDOPgSql;
use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\Driver\PDOConnection;
use Doctrine\DBAL\Driver\PDOPgSql\Driver;
use Doctrine\DBAL\Tests\Driver\AbstractPostgreSQLDriverTest;
use Doctrine\DBAL\Tests\TestUtil;
use PDO;
use PDOException;
use function array_merge;
class DriverTest extends AbstractPostgreSQLDriverTest
{
public function testReturnsName(): void
protected function setUp(): void
{
self::assertSame('pdo_pgsql', $this->driver->getName());
parent::setUp();
if (isset($GLOBALS['db_type']) && $GLOBALS['db_driver'] === 'pdo_pgsql') {
return;
}
$this->markTestSkipped('Test enabled only when using pdo_pgsql specific phpunit.xml');
}
/**
* @group DBAL-920
*/
public function testConnectionDisablesPreparesOnPhp56(): void
public function testConnectionDisablesPrepares(): void
{
$this->skipWhenNotUsingPdoPgsql();
$connection = $this->connect([]);
try {
self::assertTrue($connection->getWrappedConnection()->getAttribute(PDO::PGSQL_ATTR_DISABLE_PREPARES));
} catch (PDOException $ignored) {
/** @link https://bugs.php.net/bug.php?id=68371 */
$this->markTestIncomplete('See https://bugs.php.net/bug.php?id=68371');
}
self::assertInstanceOf(PDOConnection::class, $connection);
self::assertTrue(
$connection->getWrappedConnection()->getAttribute(PDO::PGSQL_ATTR_DISABLE_PREPARES)
);
}
/**
* @group DBAL-920
*/
public function testConnectionDoesNotDisablePreparesOnPhp56WhenAttributeDefined(): void
public function testConnectionDoesNotDisablePreparesWhenAttributeDefined(): void
{
$this->skipWhenNotUsingPdoPgsql();
$connection = $this->connect(
[PDO::PGSQL_ATTR_DISABLE_PREPARES => false]
);
try {
self::assertNotSame(
true,
self::assertInstanceOf(PDOConnection::class, $connection);
self::assertNotTrue(
$connection->getWrappedConnection()->getAttribute(PDO::PGSQL_ATTR_DISABLE_PREPARES)
);
} catch (PDOException $ignored) {
/** @link https://bugs.php.net/bug.php?id=68371 */
$this->markTestIncomplete('See https://bugs.php.net/bug.php?id=68371');
}
}
/**
* @group DBAL-920
*/
public function testConnectionDisablePreparesOnPhp56WhenDisablePreparesIsExplicitlyDefined(): void
public function testConnectionDisablePreparesWhenDisablePreparesIsExplicitlyDefined(): void
{
$this->skipWhenNotUsingPdoPgsql();
$connection = $this->connect(
[PDO::PGSQL_ATTR_DISABLE_PREPARES => true]
);
try {
self::assertTrue($connection->getWrappedConnection()->getAttribute(PDO::PGSQL_ATTR_DISABLE_PREPARES));
} catch (PDOException $ignored) {
/** @link https://bugs.php.net/bug.php?id=68371 */
$this->markTestIncomplete('See https://bugs.php.net/bug.php?id=68371');
}
self::assertInstanceOf(PDOConnection::class, $connection);
self::assertTrue(
$connection->getWrappedConnection()->getAttribute(PDO::PGSQL_ATTR_DISABLE_PREPARES)
);
}
protected function createDriver(): DriverInterface
......@@ -82,15 +73,6 @@ class DriverTest extends AbstractPostgreSQLDriverTest
return new Driver();
}
private function skipWhenNotUsingPdoPgsql(): void
{
if (isset($GLOBALS['db_driver']) && $GLOBALS['db_driver'] === 'pdo_pgsql') {
return;
}
$this->markTestSkipped('Test enabled only when using pdo_pgsql specific phpunit.xml');
}
/**
* @param array<int,mixed> $driverOptions
*/
......
......@@ -8,11 +8,6 @@ use Doctrine\DBAL\Tests\Driver\AbstractSQLiteDriverTest;
class DriverTest extends AbstractSQLiteDriverTest
{
public function testReturnsName(): void
{
self::assertSame('pdo_sqlite', $this->driver->getName());
}
protected function createDriver(): DriverInterface
{
return new Driver();
......
......@@ -8,11 +8,6 @@ use Doctrine\DBAL\Tests\Driver\AbstractSQLServerDriverTest;
class DriverTest extends AbstractSQLServerDriverTest
{
public function testReturnsName(): void
{
self::assertSame('pdo_sqlsrv', $this->driver->getName());
}
protected function createDriver(): DriverInterface
{
return new Driver();
......
......@@ -8,11 +8,6 @@ use Doctrine\DBAL\Tests\Driver\AbstractSQLServerDriverTest;
class DriverTest extends AbstractSQLServerDriverTest
{
public function testReturnsName(): void
{
self::assertSame('sqlsrv', $this->driver->getName());
}
protected function createDriver(): DriverInterface
{
return new Driver();
......
<?php
namespace Doctrine\DBAL\Tests\Events;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Event\ConnectionEventArgs;
use Doctrine\DBAL\Event\Listeners\MysqlSessionInit;
use Doctrine\DBAL\Events;
use PHPUnit\Framework\TestCase;
class MysqlSessionInitTest extends TestCase
{
public function testPostConnect(): void
{
$connectionMock = $this->createMock(Connection::class);
$connectionMock->expects(self::once())
->method('executeUpdate')
->with(self::equalTo('SET NAMES foo COLLATE bar'));
$eventArgs = new ConnectionEventArgs($connectionMock);
$listener = new MysqlSessionInit('foo', 'bar');
$listener->postConnect($eventArgs);
}
public function testGetSubscribedEvents(): void
{
$listener = new MysqlSessionInit();
self::assertEquals([Events::postConnect], $listener->getSubscribedEvents());
}
}
......@@ -53,7 +53,7 @@ abstract class AbstractDriverTest extends FunctionalTestCase
self::assertSame(
static::getDatabaseNameForConnectionWithoutDatabaseNameParameter(),
$this->driver->getDatabase($connection)
$connection->getDatabase()
);
}
......
......@@ -48,7 +48,7 @@ class DriverTest extends AbstractDriverTest
self::assertSame(
$expectedDatabaseName,
$this->driver->getDatabase($connection)
$connection->getDatabase()
);
}
......
......@@ -25,6 +25,11 @@ class DriverTest extends AbstractDriverTest
self::markTestSkipped('pdo_sqlite only test.');
}
public function testReturnsDatabaseNameWithoutDatabaseNameParameter(): void
{
self::markTestSkipped('SQLite does not support the concept of a database.');
}
protected function createDriver(): DriverInterface
{
return new Driver();
......
......@@ -236,7 +236,7 @@ class OracleSchemaManagerTest extends SchemaManagerFunctionalTestCase
$otherTable->addColumn('id', Types::STRING);
TestUtil::getPrivilegedConnection()->getSchemaManager()->dropAndCreateTable($otherTable);
$columns = $this->schemaManager->listTableColumns($table->getName(), $this->connection->getUsername());
$columns = $this->schemaManager->listTableColumns($table->getName(), $this->connection->getDatabase());
self::assertCount(7, $columns);
}
......
......@@ -18,6 +18,7 @@ use Doctrine\DBAL\Types\Types;
use function array_map;
use function array_pop;
use function count;
use function preg_match;
use function strtolower;
class PostgreSqlSchemaManagerTest extends SchemaManagerFunctionalTestCase
......@@ -164,7 +165,7 @@ class PostgreSqlSchemaManagerTest extends SchemaManagerFunctionalTestCase
$column = $nestedSchemaTable->addColumn('id', 'integer');
$column->setAutoincrement(true);
$nestedSchemaTable->setPrimaryKey(['id']);
$nestedSchemaTable->addUnnamedForeignKeyConstraint($nestedRelatedTable, ['id'], ['id']);
$nestedSchemaTable->addForeignKeyConstraint($nestedRelatedTable, ['id'], ['id']);
$this->schemaManager->createTable($nestedRelatedTable);
$this->schemaManager->createTable($nestedSchemaTable);
......@@ -217,11 +218,15 @@ class PostgreSqlSchemaManagerTest extends SchemaManagerFunctionalTestCase
$column = $testTable->addColumn('id', 'integer');
$this->schemaManager->createTable($testTable);
$this->connection->getConfiguration()->setFilterSchemaAssetsExpression('#^dbal204_#');
$this->connection->getConfiguration()->setSchemaAssetsFilter(static function (string $name): bool {
return preg_match('#^dbal204_#', $name) === 1;
});
$names = $this->schemaManager->listTableNames();
self::assertCount(2, $names);
$this->connection->getConfiguration()->setFilterSchemaAssetsExpression('#^dbal204_test#');
$this->connection->getConfiguration()->setSchemaAssetsFilter(static function (string $name): bool {
return preg_match('#^dbal204_test#', $name) === 1;
});
$names = $this->schemaManager->listTableNames();
self::assertCount(1, $names);
}
......@@ -403,10 +408,7 @@ class PostgreSqlSchemaManagerTest extends SchemaManagerFunctionalTestCase
self::assertSame('(id IS NULL)', $onlineTable->getIndex('simple_partial_index')->getOption('where'));
}
/**
* @dataProvider jsonbColumnTypeProvider
*/
public function testJsonbColumn(string $type): void
public function testJsonbColumn(): void
{
if (! $this->schemaManager->getDatabasePlatform() instanceof PostgreSQL94Platform) {
$this->markTestSkipped('Requires PostgresSQL 9.4+');
......@@ -415,26 +417,15 @@ class PostgreSqlSchemaManagerTest extends SchemaManagerFunctionalTestCase
}
$table = new Schema\Table('test_jsonb');
$table->addColumn('foo', $type)->setPlatformOption('jsonb', true);
$table->addColumn('foo', Types::JSON)->setPlatformOption('jsonb', true);
$this->schemaManager->dropAndCreateTable($table);
$columns = $this->schemaManager->listTableColumns('test_jsonb');
self::assertSame($type, $columns['foo']->getType()->getName());
self::assertSame(Types::JSON, $columns['foo']->getType()->getName());
self::assertTrue(true, $columns['foo']->getPlatformOption('jsonb'));
}
/**
* @return mixed[][]
*/
public function jsonbColumnTypeProvider(): array
{
return [
[Types::JSON],
[Types::JSON_ARRAY],
];
}
/**
* @group DBAL-2427
*/
......
......@@ -1309,129 +1309,6 @@ abstract class SchemaManagerFunctionalTestCase extends FunctionalTestCase
self::assertArrayHasKey('idx_3d6c147fdc58d6c', $indexes);
}
/**
* @after
*/
public function removeJsonArrayTable(): void
{
if (! $this->schemaManager->tablesExist(['json_array_test'])) {
return;
}
$this->schemaManager->dropTable('json_array_test');
}
/**
* @group 2782
* @group 6654
*/
public function testComparatorShouldReturnFalseWhenLegacyJsonArrayColumnHasComment(): void
{
$table = new Table('json_array_test');
$table->addColumn('parameters', 'json_array');
$this->schemaManager->createTable($table);
$comparator = new Comparator();
$tableDiff = $comparator->diffTable($this->schemaManager->listTableDetails('json_array_test'), $table);
self::assertFalse($tableDiff);
}
/**
* @group 2782
* @group 6654
*/
public function testComparatorShouldModifyOnlyTheCommentWhenUpdatingFromJsonArrayTypeOnLegacyPlatforms(): void
{
if ($this->schemaManager->getDatabasePlatform()->hasNativeJsonType()) {
$this->markTestSkipped('This test is only supported on platforms that do not have native JSON type.');
}
$table = new Table('json_array_test');
$table->addColumn('parameters', 'json_array');
$this->schemaManager->createTable($table);
$table = new Table('json_array_test');
$table->addColumn('parameters', 'json');
$comparator = new Comparator();
$tableDiff = $comparator->diffTable($this->schemaManager->listTableDetails('json_array_test'), $table);
self::assertInstanceOf(TableDiff::class, $tableDiff);
$changedColumn = $tableDiff->changedColumns['parameters'] ?? $tableDiff->changedColumns['PARAMETERS'];
self::assertSame(['comment'], $changedColumn->changedProperties);
}
/**
* @group 2782
* @group 6654
*/
public function testComparatorShouldAddCommentToLegacyJsonArrayTypeThatDoesNotHaveIt(): void
{
if (! $this->schemaManager->getDatabasePlatform()->hasNativeJsonType()) {
$this->markTestSkipped('This test is only supported on platforms that have native JSON type.');
}
$this->connection->executeQuery('CREATE TABLE json_array_test (parameters JSON NOT NULL)');
$table = new Table('json_array_test');
$table->addColumn('parameters', 'json_array');
$comparator = new Comparator();
$tableDiff = $comparator->diffTable($this->schemaManager->listTableDetails('json_array_test'), $table);
self::assertInstanceOf(TableDiff::class, $tableDiff);
self::assertSame(['comment'], $tableDiff->changedColumns['parameters']->changedProperties);
}
/**
* @group 2782
* @group 6654
*/
public function testComparatorShouldReturnAllChangesWhenUsingLegacyJsonArrayType(): void
{
if (! $this->schemaManager->getDatabasePlatform()->hasNativeJsonType()) {
$this->markTestSkipped('This test is only supported on platforms that have native JSON type.');
}
$this->connection->executeQuery('CREATE TABLE json_array_test (parameters JSON DEFAULT NULL)');
$table = new Table('json_array_test');
$table->addColumn('parameters', 'json_array');
$comparator = new Comparator();
$tableDiff = $comparator->diffTable($this->schemaManager->listTableDetails('json_array_test'), $table);
self::assertInstanceOf(TableDiff::class, $tableDiff);
self::assertSame(['notnull', 'comment'], $tableDiff->changedColumns['parameters']->changedProperties);
}
/**
* @group 2782
* @group 6654
*/
public function testComparatorShouldReturnAllChangesWhenUsingLegacyJsonArrayTypeEvenWhenPlatformHasJsonSupport(): void
{
if (! $this->schemaManager->getDatabasePlatform()->hasNativeJsonType()) {
$this->markTestSkipped('This test is only supported on platforms that have native JSON type.');
}
$this->connection->executeQuery('CREATE TABLE json_array_test (parameters JSON DEFAULT NULL)');
$table = new Table('json_array_test');
$table->addColumn('parameters', 'json_array');
$comparator = new Comparator();
$tableDiff = $comparator->diffTable($this->schemaManager->listTableDetails('json_array_test'), $table);
self::assertInstanceOf(TableDiff::class, $tableDiff);
self::assertSame(['notnull', 'comment'], $tableDiff->changedColumns['parameters']->changedProperties);
}
/**
* @group 2782
* @group 6654
......
<?php
namespace Doctrine\DBAL\Tests\Functional\Ticket;
use Doctrine\DBAL\Tests\FunctionalTestCase;
use function in_array;
use function preg_match;
/**
* @group DBAL-421
*/
class DBAL421Test extends FunctionalTestCase
{
protected function setUp(): void
{
parent::setUp();
$platform = $this->connection->getDatabasePlatform()->getName();
if (in_array($platform, ['mysql', 'sqlite'])) {
return;
}
$this->markTestSkipped('Currently restricted to MySQL and SQLite.');
}
public function testGuidShouldMatchPattern(): void
{
$guid = $this->connection->query($this->getSelectGuidSql())->fetchOne();
$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';
self::assertEquals(1, preg_match($pattern, $guid), 'GUID does not match pattern');
}
/**
* This test does (of course) not proof that all generated GUIDs are
* random, it should however provide some basic confidence.
*/
public function testGuidShouldBeRandom(): void
{
$statement = $this->connection->prepare($this->getSelectGuidSql());
$guids = [];
for ($i = 0; $i < 99; $i++) {
$guid = $statement->execute()->fetchFirstColumn();
self::assertNotContains($guid, $guids, 'Duplicate GUID detected');
$guids[] = $guid;
}
}
private function getSelectGuidSql(): string
{
return 'SELECT ' . $this->connection->getDatabasePlatform()->getGuidExpression();
}
}
......@@ -32,7 +32,7 @@ class TypeConversionTest extends FunctionalTestCase
$table->addColumn('test_time', 'time', ['notnull' => false]);
$table->addColumn('test_text', 'text', ['notnull' => false]);
$table->addColumn('test_array', 'array', ['notnull' => false]);
$table->addColumn('test_json_array', 'json_array', ['notnull' => false]);
$table->addColumn('test_json', 'json', ['notnull' => false]);
$table->addColumn('test_object', 'object', ['notnull' => false]);
$table->addColumn('test_float', 'float', ['notnull' => false]);
$table->addColumn('test_decimal', 'decimal', ['notnull' => false, 'scale' => 2, 'precision' => 10]);
......@@ -165,7 +165,7 @@ class TypeConversionTest extends FunctionalTestCase
{
return [
'array' => ['array', ['foo' => 'bar']],
'json_array' => ['json_array', ['foo' => 'bar']],
'json' => ['json', ['foo' => 'bar']],
];
}
......
......@@ -32,13 +32,10 @@ class LoggerChainTest extends TestCase
*/
private function createChain(string $method, ...$args): LoggerChain
{
$chain = new LoggerChain([
return new LoggerChain([
$this->createLogger($method, ...$args),
$this->createLogger($method, ...$args),
]);
$chain->addLogger($this->createLogger($method, ...$args));
return $chain;
}
/**
......
......@@ -857,7 +857,7 @@ abstract class AbstractPlatformTestCase extends TestCase
$column = [
'length' => 666,
'notnull' => true,
'type' => Type::getType('json_array'),
'type' => Type::getType('json'),
];
self::assertSame(
......
......@@ -589,7 +589,7 @@ abstract class AbstractPostgreSQLPlatformTestCase extends AbstractPlatformTestCa
$oldTable = clone $newTable;
$oldTable->addColumn('parent_id', 'integer');
$oldTable->addUnnamedForeignKeyConstraint('mytable', ['parent_id'], ['id']);
$oldTable->addForeignKeyConstraint('mytable', ['parent_id'], ['id']);
$comparator = new Comparator();
$tableDiff = $comparator->diffTable($oldTable, $newTable);
......
......@@ -5,7 +5,7 @@ namespace Doctrine\DBAL\Tests\Platforms;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\PostgreSQL94Platform;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\Types;
class PostgreSQL94PlatformTest extends AbstractPostgreSQLPlatformTestCase
{
......@@ -84,9 +84,9 @@ class PostgreSQL94PlatformTest extends AbstractPostgreSQLPlatformTestCase
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'));
self::assertTrue($this->platform->hasDoctrineTypeMappingFor('jsonb'));
self::assertEquals(Type::JSON, $this->platform->getDoctrineTypeMapping('jsonb'));
self::assertEquals(Types::JSON, $this->platform->getDoctrineTypeMapping('jsonb'));
}
/**
......
This diff is collapsed.
......@@ -6,6 +6,7 @@ use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Platforms\SQLServer2012Platform;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\Exception\UnknownColumnOption;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\Types;
use PHPUnit\Framework\TestCase;
......@@ -66,7 +67,8 @@ class ColumnTest extends TestCase
*/
public function testSettingUnknownOptionIsStillSupported(): void
{
$this->expectNotToPerformAssertions();
self::expectException(UnknownColumnOption::class);
self::expectExceptionMessage('The "unknown_option" column option is not supported.');
new Column('foo', $this->createMock(Type::class), ['unknown_option' => 'bar']);
}
......@@ -77,6 +79,9 @@ class ColumnTest extends TestCase
*/
public function testOptionsShouldNotBeIgnored(): void
{
self::expectException(UnknownColumnOption::class);
self::expectExceptionMessage('The "unknown_option" column option is not supported.');
$col1 = new Column('bar', Type::getType(Types::INTEGER), ['unknown_option' => 'bar', 'notnull' => true]);
self::assertTrue($col1->getNotnull());
......
......@@ -680,11 +680,11 @@ class ComparatorTest extends TestCase
{
$tableA = new Table('foo');
$tableA->addColumn('id', 'integer');
$tableA->addNamedForeignKeyConstraint('foo_constraint', 'bar', ['id'], ['id']);
$tableA->addForeignKeyConstraint('bar', ['id'], ['id'], [], 'foo_constraint');
$tableB = new Table('foo');
$tableB->addColumn('ID', 'integer');
$tableB->addNamedForeignKeyConstraint('bar_constraint', 'bar', ['id'], ['id']);
$tableB->addForeignKeyConstraint('bar', ['id'], ['id'], [], 'bar_constraint');
$c = new Comparator();
$tableDiff = $c->diffTable($tableA, $tableB);
......
......@@ -12,6 +12,7 @@ use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use function in_array;
use function preg_match;
/**
* @covers \Doctrine\DBAL\Schema\DB2SchemaManager
......@@ -44,8 +45,10 @@ final class DB2SchemaManagerTest extends TestCase
*/
public function testListTableNamesFiltersAssetNamesCorrectly(): void
{
$this->conn->getConfiguration()->setFilterSchemaAssetsExpression('/^(?!T_)/');
$this->conn->expects(self::once())->method('fetchAllAssociative')->will(self::returnValue([
$this->conn->getConfiguration()->setSchemaAssetsFilter(static function (string $name): bool {
return preg_match('/^(?!T_)/', $name) === 1;
});
$this->conn->expects(self::once())->method('fetchAllAssociative')->will($this->returnValue([
['name' => 'FOO'],
['name' => 'T_FOO'],
['name' => 'BAR'],
......@@ -61,35 +64,6 @@ final class DB2SchemaManagerTest extends TestCase
);
}
/**
* @group DBAL-2701
*/
public function testAssetFilteringSetsACallable(): void
{
$filterExpression = '/^(?!T_)/';
$this->conn->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
$this->conn->expects(self::once())->method('fetchAllAssociative')->will(self::returnValue([
['name' => 'FOO'],
['name' => 'T_FOO'],
['name' => 'BAR'],
['name' => 'T_BAR'],
]));
self::assertSame(
[
'FOO',
'BAR',
],
$this->manager->listTableNames()
);
$callable = $this->conn->getConfiguration()->getSchemaAssetsFilter();
self::assertIsCallable($callable);
// BC check: Test that regexp expression is still preserved & accessible.
self::assertEquals($filterExpression, $this->conn->getConfiguration()->getFilterSchemaAssetsExpression());
}
public function testListTableNamesFiltersAssetNamesCorrectlyWithCallable(): void
{
$accepted = ['T_FOO', 'T_BAR'];
......@@ -111,79 +85,5 @@ final class DB2SchemaManagerTest extends TestCase
],
$this->manager->listTableNames()
);
self::assertNull($this->conn->getConfiguration()->getFilterSchemaAssetsExpression());
}
public function testSettingNullExpressionWillResetCallable(): void
{
$accepted = ['T_FOO', 'T_BAR'];
$this->conn->getConfiguration()->setSchemaAssetsFilter(static function ($assetName) use ($accepted) {
return in_array($assetName, $accepted);
});
$this->conn->expects(self::any())->method('quote');
$this->conn->expects($this->atLeastOnce())->method('fetchAllAssociative')->will(self::returnValue([
['name' => 'FOO'],
['name' => 'T_FOO'],
['name' => 'BAR'],
['name' => 'T_BAR'],
]));
self::assertSame(
[
'T_FOO',
'T_BAR',
],
$this->manager->listTableNames()
);
$this->conn->getConfiguration()->setFilterSchemaAssetsExpression(null);
self::assertSame(
[
'FOO',
'T_FOO',
'BAR',
'T_BAR',
],
$this->manager->listTableNames()
);
self::assertNull($this->conn->getConfiguration()->getSchemaAssetsFilter());
}
public function testSettingNullAsCallableClearsExpression(): void
{
$filterExpression = '/^(?!T_)/';
$this->conn->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
$this->conn->expects(self::exactly(2))->method('fetchAllAssociative')->will(self::returnValue([
['name' => 'FOO'],
['name' => 'T_FOO'],
['name' => 'BAR'],
['name' => 'T_BAR'],
]));
self::assertSame(
[
'FOO',
'BAR',
],
$this->manager->listTableNames()
);
$this->conn->getConfiguration()->setSchemaAssetsFilter(null);
self::assertSame(
[
'FOO',
'T_FOO',
'BAR',
'T_BAR',
],
$this->manager->listTableNames()
);
$this->assertNull($this->conn->getConfiguration()->getFilterSchemaAssetsExpression());
}
}
......@@ -8,6 +8,7 @@ use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\Connection as DriverConnection;
use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\MySqlSchemaManager;
......@@ -74,7 +75,11 @@ class MySqlInheritCharsetTest extends TestCase
private function getTableOptionsForOverride(array $overrideOptions = []): array
{
$eventManager = new EventManager();
$driverMock = $this->createMock(Driver::class);
$driverMock->method('connect')
->willReturn($this->createMock(DriverConnection::class));
$platform = new MySqlPlatform();
$connOptions = array_merge(['platform' => $platform], $overrideOptions);
$conn = new Connection($connOptions, $driverMock, new Configuration(), $eventManager);
......
......@@ -42,7 +42,7 @@ class MySqlSchemaManagerTest extends TestCase
public function testCompositeForeignKeys(): void
{
$this->conn->expects(self::once())->method('fetchAllAssociative')->will(self::returnValue($this->getFKDefinition()));
$fkeys = $this->manager->listTableForeignKeys('dummy');
$fkeys = $this->manager->listTableForeignKeys('dummy', 'dummy');
self::assertCount(1, $fkeys, 'Table has to have one foreign key.');
self::assertInstanceOf(ForeignKeyConstraint::class, $fkeys[0]);
......
......@@ -51,7 +51,7 @@ class MySQLSchemaTest extends TestCase
{
$tableOld = new Table('test');
$tableOld->addColumn('foo_id', 'integer');
$tableOld->addUnnamedForeignKeyConstraint('test_foreign', ['foo_id'], ['foo_id']);
$tableOld->addForeignKeyConstraint('test_foreign', ['foo_id'], ['foo_id']);
$sqls = [];
foreach ($tableOld->getForeignKeys() as $fk) {
......
......@@ -5,6 +5,7 @@ namespace Doctrine\DBAL\Tests;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\OraclePlatform;
use PHPUnit\Framework\Assert;
use function array_keys;
......@@ -87,7 +88,12 @@ class TestUtil
$platform = $privConn->getDatabasePlatform();
if ($platform->supportsCreateDropDatabase()) {
$dbname = $testConn->getDatabase();
if (! $platform instanceof OraclePlatform) {
$dbname = $testConnParams['dbname'];
} else {
$dbname = $testConnParams['user'];
}
$testConn->close();
$privConn->getSchemaManager()->dropAndCreateDatabase($dbname);
......
<?php
namespace Doctrine\DBAL\Tests\Types;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\JsonArrayType;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\Types;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use function base64_encode;
use function fopen;
use function json_encode;
class JsonArrayTest extends TestCase
{
/** @var AbstractPlatform|MockObject */
protected $platform;
/** @var JsonArrayType */
protected $type;
protected function setUp(): void
{
$this->platform = $this->createMock(AbstractPlatform::class);
$this->type = Type::getType('json_array');
}
public function testReturnsBindingType(): void
{
self::assertSame(ParameterType::STRING, $this->type->getBindingType());
}
public function testReturnsName(): void
{
self::assertSame(Types::JSON_ARRAY, $this->type->getName());
}
public function testReturnsSQLDeclaration(): void
{
$this->platform->expects(self::once())
->method('getJsonTypeDeclarationSQL')
->willReturn('TEST_JSON');
self::assertSame('TEST_JSON', $this->type->getSQLDeclaration([], $this->platform));
}
public function testJsonNullConvertsToPHPValue(): void
{
self::assertSame([], $this->type->convertToPHPValue(null, $this->platform));
}
public function testJsonEmptyStringConvertsToPHPValue(): void
{
self::assertSame([], $this->type->convertToPHPValue('', $this->platform));
}
public function testJsonStringConvertsToPHPValue(): void
{
$value = ['foo' => 'bar', 'bar' => 'foo'];
$databaseValue = json_encode($value);
$phpValue = $this->type->convertToPHPValue($databaseValue, $this->platform);
self::assertEquals($value, $phpValue);
}
public function testJsonResourceConvertsToPHPValue(): void
{
$value = ['foo' => 'bar', 'bar' => 'foo'];
$databaseValue = fopen('data://text/plain;base64,' . base64_encode(json_encode($value)), 'r');
$phpValue = $this->type->convertToPHPValue($databaseValue, $this->platform);
self::assertSame($value, $phpValue);
}
public function testRequiresSQLCommentHint(): void
{
self::assertTrue($this->type->requiresSQLCommentHint($this->platform));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment