Actualización

This commit is contained in:
Xes
2025-04-10 12:24:57 +02:00
parent 8969cc929d
commit 45420b6f0d
39760 changed files with 4303286 additions and 0 deletions

View File

@@ -0,0 +1,213 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use function array_map;
use function crc32;
use function dechex;
use function explode;
use function implode;
use function str_replace;
use function strpos;
use function strtolower;
use function strtoupper;
use function substr;
/**
* The abstract asset allows to reset the name of all assets without publishing this to the public userland.
*
* This encapsulation hack is necessary to keep a consistent state of the database schema. Say we have a list of tables
* array($tableName => Table($tableName)); if you want to rename the table, you have to make sure
*/
abstract class AbstractAsset
{
/** @var string */
protected $_name = '';
/**
* Namespace of the asset. If none isset the default namespace is assumed.
*
* @var string|null
*/
protected $_namespace;
/** @var bool */
protected $_quoted = false;
/**
* Sets the name of this asset.
*
* @param string $name
*
* @return void
*/
protected function _setName($name)
{
if ($this->isIdentifierQuoted($name)) {
$this->_quoted = true;
$name = $this->trimQuotes($name);
}
if (strpos($name, '.') !== false) {
$parts = explode('.', $name);
$this->_namespace = $parts[0];
$name = $parts[1];
}
$this->_name = $name;
}
/**
* Is this asset in the default namespace?
*
* @param string $defaultNamespaceName
*
* @return bool
*/
public function isInDefaultNamespace($defaultNamespaceName)
{
return $this->_namespace === $defaultNamespaceName || $this->_namespace === null;
}
/**
* Gets the namespace name of this asset.
*
* If NULL is returned this means the default namespace is used.
*
* @return string|null
*/
public function getNamespaceName()
{
return $this->_namespace;
}
/**
* The shortest name is stripped of the default namespace. All other
* namespaced elements are returned as full-qualified names.
*
* @param string|null $defaultNamespaceName
*
* @return string
*/
public function getShortestName($defaultNamespaceName)
{
$shortestName = $this->getName();
if ($this->_namespace === $defaultNamespaceName) {
$shortestName = $this->_name;
}
return strtolower($shortestName);
}
/**
* The normalized name is full-qualified and lower-cased. Lower-casing is
* actually wrong, but we have to do it to keep our sanity. If you are
* using database objects that only differentiate in the casing (FOO vs
* Foo) then you will NOT be able to use Doctrine Schema abstraction.
*
* Every non-namespaced element is prefixed with the default namespace
* name which is passed as argument to this method.
*
* @param string $defaultNamespaceName
*
* @return string
*/
public function getFullQualifiedName($defaultNamespaceName)
{
$name = $this->getName();
if (! $this->_namespace) {
$name = $defaultNamespaceName . '.' . $name;
}
return strtolower($name);
}
/**
* Checks if this asset's name is quoted.
*
* @return bool
*/
public function isQuoted()
{
return $this->_quoted;
}
/**
* Checks if this identifier is quoted.
*
* @param string $identifier
*
* @return bool
*/
protected function isIdentifierQuoted($identifier)
{
return isset($identifier[0]) && ($identifier[0] === '`' || $identifier[0] === '"' || $identifier[0] === '[');
}
/**
* Trim quotes from the identifier.
*
* @param string $identifier
*
* @return string
*/
protected function trimQuotes($identifier)
{
return str_replace(['`', '"', '[', ']'], '', $identifier);
}
/**
* Returns the name of this schema asset.
*
* @return string
*/
public function getName()
{
if ($this->_namespace) {
return $this->_namespace . '.' . $this->_name;
}
return $this->_name;
}
/**
* Gets the quoted representation of this asset but only if it was defined with one. Otherwise
* return the plain unquoted value as inserted.
*
* @return string
*/
public function getQuotedName(AbstractPlatform $platform)
{
$keywords = $platform->getReservedKeywordsList();
$parts = explode('.', $this->getName());
foreach ($parts as $k => $v) {
$parts[$k] = $this->_quoted || $keywords->isKeyword($v) ? $platform->quoteIdentifier($v) : $v;
}
return implode('.', $parts);
}
/**
* Generates an identifier from a list of column names obeying a certain string length.
*
* This is especially important for Oracle, since it does not allow identifiers larger than 30 chars,
* however building idents automatically for foreign keys, composite keys or such can easily create
* very long names.
*
* @param string[] $columnNames
* @param string $prefix
* @param int $maxSize
*
* @return string
*/
protected function _generateIdentifierName($columnNames, $prefix = '', $maxSize = 30)
{
$hash = implode('', array_map(static function ($column) {
return dechex(crc32($column));
}, $columnNames));
return strtoupper(substr($prefix . '_' . $hash, 0, $maxSize));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,453 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Types\Type;
use Doctrine\Deprecations\Deprecation;
use function array_merge;
use function is_numeric;
use function method_exists;
/**
* Object representation of a database column.
*/
class Column extends AbstractAsset
{
/** @var Type */
protected $_type;
/** @var int|null */
protected $_length;
/** @var int */
protected $_precision = 10;
/** @var int */
protected $_scale = 0;
/** @var bool */
protected $_unsigned = false;
/** @var bool */
protected $_fixed = false;
/** @var bool */
protected $_notnull = true;
/** @var string|null */
protected $_default;
/** @var bool */
protected $_autoincrement = false;
/** @var mixed[] */
protected $_platformOptions = [];
/** @var string|null */
protected $_columnDefinition;
/** @var string|null */
protected $_comment;
/** @var mixed[] */
protected $_customSchemaOptions = [];
/**
* Creates a new Column.
*
* @param string $name
* @param mixed[] $options
*/
public function __construct($name, Type $type, array $options = [])
{
$this->_setName($name);
$this->setType($type);
$this->setOptions($options);
}
/**
* @param mixed[] $options
*
* @return Column
*/
public function setOptions(array $options)
{
foreach ($options as $name => $value) {
$method = 'set' . $name;
if (! method_exists($this, $method)) {
// next major: throw an exception
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/pull/2846',
'The "%s" column option is not supported,' .
' setting unknown options is deprecated and will cause an error in Doctrine DBAL 3.0',
$name
);
continue;
}
$this->$method($value);
}
return $this;
}
/**
* @return Column
*/
public function setType(Type $type)
{
$this->_type = $type;
return $this;
}
/**
* @param int|null $length
*
* @return Column
*/
public function setLength($length)
{
if ($length !== null) {
$this->_length = (int) $length;
} else {
$this->_length = null;
}
return $this;
}
/**
* @param int $precision
*
* @return Column
*/
public function setPrecision($precision)
{
if (! is_numeric($precision)) {
$precision = 10; // defaults to 10 when no valid precision is given.
}
$this->_precision = (int) $precision;
return $this;
}
/**
* @param int $scale
*
* @return Column
*/
public function setScale($scale)
{
if (! is_numeric($scale)) {
$scale = 0;
}
$this->_scale = (int) $scale;
return $this;
}
/**
* @param bool $unsigned
*
* @return Column
*/
public function setUnsigned($unsigned)
{
$this->_unsigned = (bool) $unsigned;
return $this;
}
/**
* @param bool $fixed
*
* @return Column
*/
public function setFixed($fixed)
{
$this->_fixed = (bool) $fixed;
return $this;
}
/**
* @param bool $notnull
*
* @return Column
*/
public function setNotnull($notnull)
{
$this->_notnull = (bool) $notnull;
return $this;
}
/**
* @param mixed $default
*
* @return Column
*/
public function setDefault($default)
{
$this->_default = $default;
return $this;
}
/**
* @param mixed[] $platformOptions
*
* @return Column
*/
public function setPlatformOptions(array $platformOptions)
{
$this->_platformOptions = $platformOptions;
return $this;
}
/**
* @param string $name
* @param mixed $value
*
* @return Column
*/
public function setPlatformOption($name, $value)
{
$this->_platformOptions[$name] = $value;
return $this;
}
/**
* @param string $value
*
* @return Column
*/
public function setColumnDefinition($value)
{
$this->_columnDefinition = $value;
return $this;
}
/**
* @return Type
*/
public function getType()
{
return $this->_type;
}
/**
* @return int|null
*/
public function getLength()
{
return $this->_length;
}
/**
* @return int
*/
public function getPrecision()
{
return $this->_precision;
}
/**
* @return int
*/
public function getScale()
{
return $this->_scale;
}
/**
* @return bool
*/
public function getUnsigned()
{
return $this->_unsigned;
}
/**
* @return bool
*/
public function getFixed()
{
return $this->_fixed;
}
/**
* @return bool
*/
public function getNotnull()
{
return $this->_notnull;
}
/**
* @return string|null
*/
public function getDefault()
{
return $this->_default;
}
/**
* @return mixed[]
*/
public function getPlatformOptions()
{
return $this->_platformOptions;
}
/**
* @param string $name
*
* @return bool
*/
public function hasPlatformOption($name)
{
return isset($this->_platformOptions[$name]);
}
/**
* @param string $name
*
* @return mixed
*/
public function getPlatformOption($name)
{
return $this->_platformOptions[$name];
}
/**
* @return string|null
*/
public function getColumnDefinition()
{
return $this->_columnDefinition;
}
/**
* @return bool
*/
public function getAutoincrement()
{
return $this->_autoincrement;
}
/**
* @param bool $flag
*
* @return Column
*/
public function setAutoincrement($flag)
{
$this->_autoincrement = $flag;
return $this;
}
/**
* @param string|null $comment
*
* @return Column
*/
public function setComment($comment)
{
$this->_comment = $comment;
return $this;
}
/**
* @return string|null
*/
public function getComment()
{
return $this->_comment;
}
/**
* @param string $name
* @param mixed $value
*
* @return Column
*/
public function setCustomSchemaOption($name, $value)
{
$this->_customSchemaOptions[$name] = $value;
return $this;
}
/**
* @param string $name
*
* @return bool
*/
public function hasCustomSchemaOption($name)
{
return isset($this->_customSchemaOptions[$name]);
}
/**
* @param string $name
*
* @return mixed
*/
public function getCustomSchemaOption($name)
{
return $this->_customSchemaOptions[$name];
}
/**
* @param mixed[] $customSchemaOptions
*
* @return Column
*/
public function setCustomSchemaOptions(array $customSchemaOptions)
{
$this->_customSchemaOptions = $customSchemaOptions;
return $this;
}
/**
* @return mixed[]
*/
public function getCustomSchemaOptions()
{
return $this->_customSchemaOptions;
}
/**
* @return mixed[]
*/
public function toArray()
{
return array_merge([
'name' => $this->_name,
'type' => $this->_type,
'default' => $this->_default,
'notnull' => $this->_notnull,
'length' => $this->_length,
'precision' => $this->_precision,
'scale' => $this->_scale,
'fixed' => $this->_fixed,
'unsigned' => $this->_unsigned,
'autoincrement' => $this->_autoincrement,
'columnDefinition' => $this->_columnDefinition,
'comment' => $this->_comment,
], $this->_platformOptions, $this->_customSchemaOptions);
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace Doctrine\DBAL\Schema;
use function in_array;
/**
* Represents the change of a column.
*/
class ColumnDiff
{
/** @var string */
public $oldColumnName;
/** @var Column */
public $column;
/** @var string[] */
public $changedProperties = [];
/** @var Column|null */
public $fromColumn;
/**
* @param string $oldColumnName
* @param string[] $changedProperties
*/
public function __construct(
$oldColumnName,
Column $column,
array $changedProperties = [],
?Column $fromColumn = null
) {
$this->oldColumnName = $oldColumnName;
$this->column = $column;
$this->changedProperties = $changedProperties;
$this->fromColumn = $fromColumn;
}
/**
* @param string $propertyName
*
* @return bool
*/
public function hasChanged($propertyName)
{
return in_array($propertyName, $this->changedProperties);
}
/**
* @return Identifier
*/
public function getOldColumnName()
{
$quote = $this->fromColumn && $this->fromColumn->isQuoted();
return new Identifier($this->oldColumnName, $quote);
}
}

View File

@@ -0,0 +1,556 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Types;
use function array_intersect_key;
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;
use function get_class;
use function strtolower;
/**
* Compares two Schemas and return an instance of SchemaDiff.
*/
class Comparator
{
/**
* @return SchemaDiff
*/
public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
{
$c = new self();
return $c->compare($fromSchema, $toSchema);
}
/**
* Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
*
* The returned differences are returned in such a way that they contain the
* operations to change the schema stored in $fromSchema to the schema that is
* stored in $toSchema.
*
* @return SchemaDiff
*/
public function compare(Schema $fromSchema, Schema $toSchema)
{
$diff = new SchemaDiff();
$diff->fromSchema = $fromSchema;
$foreignKeysToTable = [];
foreach ($toSchema->getNamespaces() as $namespace) {
if ($fromSchema->hasNamespace($namespace)) {
continue;
}
$diff->newNamespaces[$namespace] = $namespace;
}
foreach ($fromSchema->getNamespaces() as $namespace) {
if ($toSchema->hasNamespace($namespace)) {
continue;
}
$diff->removedNamespaces[$namespace] = $namespace;
}
foreach ($toSchema->getTables() as $table) {
$tableName = $table->getShortestName($toSchema->getName());
if (! $fromSchema->hasTable($tableName)) {
$diff->newTables[$tableName] = $toSchema->getTable($tableName);
} else {
$tableDifferences = $this->diffTable(
$fromSchema->getTable($tableName),
$toSchema->getTable($tableName)
);
if ($tableDifferences !== false) {
$diff->changedTables[$tableName] = $tableDifferences;
}
}
}
/* Check if there are tables removed */
foreach ($fromSchema->getTables() as $table) {
$tableName = $table->getShortestName($fromSchema->getName());
$table = $fromSchema->getTable($tableName);
if (! $toSchema->hasTable($tableName)) {
$diff->removedTables[$tableName] = $table;
}
// also remember all foreign keys that point to a specific table
foreach ($table->getForeignKeys() as $foreignKey) {
$foreignTable = strtolower($foreignKey->getForeignTableName());
if (! isset($foreignKeysToTable[$foreignTable])) {
$foreignKeysToTable[$foreignTable] = [];
}
$foreignKeysToTable[$foreignTable][] = $foreignKey;
}
}
foreach ($diff->removedTables as $tableName => $table) {
if (! isset($foreignKeysToTable[$tableName])) {
continue;
}
$diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
// deleting duplicated foreign keys present on both on the orphanedForeignKey
// and the removedForeignKeys from changedTables
foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
// strtolower the table name to make if compatible with getShortestName
$localTableName = strtolower($foreignKey->getLocalTableName());
if (! isset($diff->changedTables[$localTableName])) {
continue;
}
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;
}
unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
}
}
}
foreach ($toSchema->getSequences() as $sequence) {
$sequenceName = $sequence->getShortestName($toSchema->getName());
if (! $fromSchema->hasSequence($sequenceName)) {
if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
$diff->newSequences[] = $sequence;
}
} else {
if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
$diff->changedSequences[] = $toSchema->getSequence($sequenceName);
}
}
}
foreach ($fromSchema->getSequences() as $sequence) {
if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
continue;
}
$sequenceName = $sequence->getShortestName($fromSchema->getName());
if ($toSchema->hasSequence($sequenceName)) {
continue;
}
$diff->removedSequences[] = $sequence;
}
return $diff;
}
/**
* @param Schema $schema
* @param Sequence $sequence
*
* @return bool
*/
private function isAutoIncrementSequenceInSchema($schema, $sequence)
{
foreach ($schema->getTables() as $table) {
if ($sequence->isAutoIncrementsFor($table)) {
return true;
}
}
return false;
}
/**
* @return bool
*/
public function diffSequence(Sequence $sequence1, Sequence $sequence2)
{
if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
return true;
}
return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
}
/**
* Returns the difference between the tables $fromTable and $toTable.
*
* If there are no differences this method returns the boolean false.
*
* @return TableDiff|false
*/
public function diffTable(Table $fromTable, Table $toTable)
{
$changes = 0;
$tableDifferences = new TableDiff($fromTable->getName());
$tableDifferences->fromTable = $fromTable;
$fromTableColumns = $fromTable->getColumns();
$toTableColumns = $toTable->getColumns();
/* See if all the columns in "from" table exist in "to" table */
foreach ($toTableColumns as $columnName => $column) {
if ($fromTable->hasColumn($columnName)) {
continue;
}
$tableDifferences->addedColumns[$columnName] = $column;
$changes++;
}
/* See if there are any removed columns in "to" table */
foreach ($fromTableColumns as $columnName => $column) {
// See if column is removed in "to" table.
if (! $toTable->hasColumn($columnName)) {
$tableDifferences->removedColumns[$columnName] = $column;
$changes++;
continue;
}
// See if column has changed properties in "to" table.
$changedProperties = $this->diffColumn($column, $toTable->getColumn($columnName));
if (empty($changedProperties)) {
continue;
}
$columnDiff = new ColumnDiff($column->getName(), $toTable->getColumn($columnName), $changedProperties);
$columnDiff->fromColumn = $column;
$tableDifferences->changedColumns[$column->getName()] = $columnDiff;
$changes++;
}
$this->detectColumnRenamings($tableDifferences);
$fromTableIndexes = $fromTable->getIndexes();
$toTableIndexes = $toTable->getIndexes();
/* See if all the indexes in "from" table exist in "to" table */
foreach ($toTableIndexes as $indexName => $index) {
if (($index->isPrimary() && $fromTable->hasPrimaryKey()) || $fromTable->hasIndex($indexName)) {
continue;
}
$tableDifferences->addedIndexes[$indexName] = $index;
$changes++;
}
/* See if there are any removed indexes in "to" table */
foreach ($fromTableIndexes as $indexName => $index) {
// See if index is removed in "to" table.
if (
($index->isPrimary() && ! $toTable->hasPrimaryKey()) ||
! $index->isPrimary() && ! $toTable->hasIndex($indexName)
) {
$tableDifferences->removedIndexes[$indexName] = $index;
$changes++;
continue;
}
// See if index has changed in "to" table.
$toTableIndex = $index->isPrimary() ? $toTable->getPrimaryKey() : $toTable->getIndex($indexName);
assert($toTableIndex instanceof Index);
if (! $this->diffIndex($index, $toTableIndex)) {
continue;
}
$tableDifferences->changedIndexes[$indexName] = $toTableIndex;
$changes++;
}
$this->detectIndexRenamings($tableDifferences);
$fromForeignKeys = $fromTable->getForeignKeys();
$toForeignKeys = $toTable->getForeignKeys();
foreach ($fromForeignKeys as $fromKey => $fromConstraint) {
foreach ($toForeignKeys as $toKey => $toConstraint) {
if ($this->diffForeignKey($fromConstraint, $toConstraint) === false) {
unset($fromForeignKeys[$fromKey], $toForeignKeys[$toKey]);
} else {
if (strtolower($fromConstraint->getName()) === strtolower($toConstraint->getName())) {
$tableDifferences->changedForeignKeys[] = $toConstraint;
$changes++;
unset($fromForeignKeys[$fromKey], $toForeignKeys[$toKey]);
}
}
}
}
foreach ($fromForeignKeys as $fromConstraint) {
$tableDifferences->removedForeignKeys[] = $fromConstraint;
$changes++;
}
foreach ($toForeignKeys as $toConstraint) {
$tableDifferences->addedForeignKeys[] = $toConstraint;
$changes++;
}
return $changes ? $tableDifferences : false;
}
/**
* Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
* however ambiguities between different possibilities should not lead to renaming at all.
*
* @return void
*/
private function detectColumnRenamings(TableDiff $tableDifferences)
{
$renameCandidates = [];
foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
foreach ($tableDifferences->removedColumns as $removedColumn) {
if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
continue;
}
$renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
}
}
foreach ($renameCandidates as $candidateColumns) {
if (count($candidateColumns) !== 1) {
continue;
}
[$removedColumn, $addedColumn] = $candidateColumns[0];
$removedColumnName = strtolower($removedColumn->getName());
$addedColumnName = strtolower($addedColumn->getName());
if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
continue;
}
$tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
unset(
$tableDifferences->addedColumns[$addedColumnName],
$tableDifferences->removedColumns[$removedColumnName]
);
}
}
/**
* Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
* however ambiguities between different possibilities should not lead to renaming at all.
*
* @return void
*/
private function detectIndexRenamings(TableDiff $tableDifferences)
{
$renameCandidates = [];
// Gather possible rename candidates by comparing each added and removed index based on semantics.
foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
foreach ($tableDifferences->removedIndexes as $removedIndex) {
if ($this->diffIndex($addedIndex, $removedIndex)) {
continue;
}
$renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
}
}
foreach ($renameCandidates as $candidateIndexes) {
// If the current rename candidate contains exactly one semantically equal index,
// we can safely rename it.
// Otherwise it is unclear if a rename action is really intended,
// therefore we let those ambiguous indexes be added/dropped.
if (count($candidateIndexes) !== 1) {
continue;
}
[$removedIndex, $addedIndex] = $candidateIndexes[0];
$removedIndexName = strtolower($removedIndex->getName());
$addedIndexName = strtolower($addedIndex->getName());
if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
continue;
}
$tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
unset(
$tableDifferences->addedIndexes[$addedIndexName],
$tableDifferences->removedIndexes[$removedIndexName]
);
}
}
/**
* @return bool
*/
public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
{
if (
array_map('strtolower', $key1->getUnquotedLocalColumns())
!== array_map('strtolower', $key2->getUnquotedLocalColumns())
) {
return true;
}
if (
array_map('strtolower', $key1->getUnquotedForeignColumns())
!== array_map('strtolower', $key2->getUnquotedForeignColumns())
) {
return true;
}
if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
return true;
}
if ($key1->onUpdate() !== $key2->onUpdate()) {
return true;
}
return $key1->onDelete() !== $key2->onDelete();
}
/**
* Returns the difference between the columns
*
* If there are differences this method returns $field2, otherwise the
* boolean false.
*
* @return string[]
*/
public function diffColumn(Column $column1, Column $column2)
{
$properties1 = $column1->toArray();
$properties2 = $column2->toArray();
$changedProperties = [];
if (get_class($properties1['type']) !== get_class($properties2['type'])) {
$changedProperties[] = 'type';
}
foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
if ($properties1[$property] === $properties2[$property]) {
continue;
}
$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 (
($properties1['default'] === null) !== ($properties2['default'] === null)
|| $properties1['default'] != $properties2['default']
) {
$changedProperties[] = 'default';
}
if (
($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
$properties1['type'] instanceof Types\BinaryType
) {
// check if value of length is set at all, default value assumed otherwise.
$length1 = $properties1['length'] ?: 255;
$length2 = $properties2['length'] ?: 255;
if ($length1 !== $length2) {
$changedProperties[] = 'length';
}
if ($properties1['fixed'] !== $properties2['fixed']) {
$changedProperties[] = 'fixed';
}
} elseif ($properties1['type'] instanceof Types\DecimalType) {
if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
$changedProperties[] = 'precision';
}
if ($properties1['scale'] !== $properties2['scale']) {
$changedProperties[] = 'scale';
}
}
// A null value and an empty string are actually equal for a comment so they should not trigger a change.
if (
$properties1['comment'] !== $properties2['comment'] &&
! ($properties1['comment'] === null && $properties2['comment'] === '') &&
! ($properties2['comment'] === null && $properties1['comment'] === '')
) {
$changedProperties[] = 'comment';
}
$customOptions1 = $column1->getCustomSchemaOptions();
$customOptions2 = $column2->getCustomSchemaOptions();
foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
$changedProperties[] = $key;
} elseif ($properties1[$key] !== $properties2[$key]) {
$changedProperties[] = $key;
}
}
$platformOptions1 = $column1->getPlatformOptions();
$platformOptions2 = $column2->getPlatformOptions();
foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
if ($properties1[$key] === $properties2[$key]) {
continue;
}
$changedProperties[] = $key;
}
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.
*
* Compares $index1 with $index2 and returns $index2 if there are any
* differences or false in case there are no differences.
*
* @return bool
*/
public function diffIndex(Index $index1, Index $index2)
{
return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* Marker interface for constraints.
*/
interface Constraint
{
/**
* @return string
*/
public function getName();
/**
* @return string
*/
public function getQuotedName(AbstractPlatform $platform);
/**
* Returns the names of the referencing table columns
* the constraint is associated with.
*
* @return string[]
*/
public function getColumns();
/**
* Returns the quoted representation of the column names
* the constraint is associated with.
*
* But only if they were defined with one or a column name
* is a keyword reserved by the platform.
* Otherwise the plain unquoted value as inserted is returned.
*
* @param AbstractPlatform $platform The platform to use for quotation.
*
* @return string[]
*/
public function getQuotedColumns(AbstractPlatform $platform);
}

View File

@@ -0,0 +1,239 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Platforms\DB2Platform;
use Doctrine\DBAL\Types\Type;
use function array_change_key_case;
use function assert;
use function preg_match;
use function str_replace;
use function strpos;
use function strtolower;
use function substr;
use const CASE_LOWER;
/**
* IBM Db2 Schema Manager.
*/
class DB2SchemaManager extends AbstractSchemaManager
{
/**
* {@inheritdoc}
*
* Apparently creator is the schema not the user who created it:
* {@link http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.sqlref/db2z_sysibmsystablestable.htm}
*/
public function listTableNames()
{
$sql = $this->_platform->getListTablesSQL();
$sql .= ' AND CREATOR = UPPER(' . $this->_conn->quote($this->_conn->getUsername()) . ')';
$tables = $this->_conn->fetchAllAssociative($sql);
return $this->filterAssetNames($this->_getPortableTablesList($tables));
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableColumnDefinition($tableColumn)
{
$tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
$length = null;
$fixed = null;
$scale = false;
$precision = false;
$default = null;
if ($tableColumn['default'] !== null && $tableColumn['default'] !== 'NULL') {
$default = $tableColumn['default'];
if (preg_match('/^\'(.*)\'$/s', $default, $matches)) {
$default = str_replace("''", "'", $matches[1]);
}
}
$type = $this->_platform->getDoctrineTypeMapping($tableColumn['typename']);
if (isset($tableColumn['comment'])) {
$type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
$tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
}
switch (strtolower($tableColumn['typename'])) {
case 'varchar':
$length = $tableColumn['length'];
$fixed = false;
break;
case 'character':
$length = $tableColumn['length'];
$fixed = true;
break;
case 'clob':
$length = $tableColumn['length'];
break;
case 'decimal':
case 'double':
case 'real':
$scale = $tableColumn['scale'];
$precision = $tableColumn['length'];
break;
}
$options = [
'length' => $length,
'unsigned' => false,
'fixed' => (bool) $fixed,
'default' => $default,
'autoincrement' => (bool) $tableColumn['autoincrement'],
'notnull' => $tableColumn['nulls'] === 'N',
'scale' => null,
'precision' => null,
'comment' => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
? $tableColumn['comment']
: null,
'platformOptions' => [],
];
if ($scale !== null && $precision !== null) {
$options['scale'] = $scale;
$options['precision'] = $precision;
}
return new Column($tableColumn['colname'], Type::getType($type), $options);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTablesList($tables)
{
$tableNames = [];
foreach ($tables as $tableRow) {
$tableRow = array_change_key_case($tableRow, CASE_LOWER);
$tableNames[] = $tableRow['name'];
}
return $tableNames;
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
{
foreach ($tableIndexes as &$tableIndexRow) {
$tableIndexRow = array_change_key_case($tableIndexRow, CASE_LOWER);
$tableIndexRow['primary'] = (bool) $tableIndexRow['primary'];
}
return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
{
return new ForeignKeyConstraint(
$tableForeignKey['local_columns'],
$tableForeignKey['foreign_table'],
$tableForeignKey['foreign_columns'],
$tableForeignKey['name'],
$tableForeignKey['options']
);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableForeignKeysList($tableForeignKeys)
{
$foreignKeys = [];
foreach ($tableForeignKeys as $tableForeignKey) {
$tableForeignKey = array_change_key_case($tableForeignKey, CASE_LOWER);
if (! isset($foreignKeys[$tableForeignKey['index_name']])) {
$foreignKeys[$tableForeignKey['index_name']] = [
'local_columns' => [$tableForeignKey['local_column']],
'foreign_table' => $tableForeignKey['foreign_table'],
'foreign_columns' => [$tableForeignKey['foreign_column']],
'name' => $tableForeignKey['index_name'],
'options' => [
'onUpdate' => $tableForeignKey['on_update'],
'onDelete' => $tableForeignKey['on_delete'],
],
];
} else {
$foreignKeys[$tableForeignKey['index_name']]['local_columns'][] = $tableForeignKey['local_column'];
$foreignKeys[$tableForeignKey['index_name']]['foreign_columns'][] = $tableForeignKey['foreign_column'];
}
}
return parent::_getPortableTableForeignKeysList($foreignKeys);
}
/**
* @param string $def
*
* @return string|null
*/
protected function _getPortableForeignKeyRuleDef($def)
{
if ($def === 'C') {
return 'CASCADE';
}
if ($def === 'N') {
return 'SET NULL';
}
return null;
}
/**
* {@inheritdoc}
*/
protected function _getPortableViewDefinition($view)
{
$view = array_change_key_case($view, CASE_LOWER);
$sql = '';
$pos = strpos($view['text'], ' AS ');
if ($pos !== false) {
$sql = substr($view['text'], $pos + 4);
}
return new View($view['name'], $sql);
}
/**
* {@inheritdoc}
*/
public function listTableDetails($name): Table
{
$table = parent::listTableDetails($name);
$platform = $this->_platform;
assert($platform instanceof DB2Platform);
$sql = $platform->getListTableCommentsSQL($name);
$tableOptions = $this->_conn->fetchAssociative($sql);
if ($tableOptions !== false) {
$table->addOption('comment', $tableOptions['REMARKS']);
}
return $table;
}
}

View File

@@ -0,0 +1,104 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Types\Type;
use function explode;
use function strtolower;
use function trim;
/**
* Schema manager for the Drizzle RDBMS.
*/
class DrizzleSchemaManager extends AbstractSchemaManager
{
/**
* {@inheritdoc}
*/
protected function _getPortableTableColumnDefinition($tableColumn)
{
$dbType = strtolower($tableColumn['DATA_TYPE']);
$type = $this->_platform->getDoctrineTypeMapping($dbType);
$type = $this->extractDoctrineTypeFromComment($tableColumn['COLUMN_COMMENT'], $type);
$tableColumn['COLUMN_COMMENT'] = $this->removeDoctrineTypeFromComment($tableColumn['COLUMN_COMMENT'], $type);
$options = [
'notnull' => ! (bool) $tableColumn['IS_NULLABLE'],
'length' => (int) $tableColumn['CHARACTER_MAXIMUM_LENGTH'],
'default' => $tableColumn['COLUMN_DEFAULT'] ?? null,
'autoincrement' => (bool) $tableColumn['IS_AUTO_INCREMENT'],
'scale' => (int) $tableColumn['NUMERIC_SCALE'],
'precision' => (int) $tableColumn['NUMERIC_PRECISION'],
'comment' => isset($tableColumn['COLUMN_COMMENT']) && $tableColumn['COLUMN_COMMENT'] !== ''
? $tableColumn['COLUMN_COMMENT']
: null,
];
$column = new Column($tableColumn['COLUMN_NAME'], Type::getType($type), $options);
if (! empty($tableColumn['COLLATION_NAME'])) {
$column->setPlatformOption('collation', $tableColumn['COLLATION_NAME']);
}
return $column;
}
/**
* {@inheritdoc}
*/
protected function _getPortableDatabaseDefinition($database)
{
return $database['SCHEMA_NAME'];
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableDefinition($table)
{
return $table['TABLE_NAME'];
}
/**
* {@inheritdoc}
*/
public function _getPortableTableForeignKeyDefinition($tableForeignKey)
{
$columns = [];
foreach (explode(',', $tableForeignKey['CONSTRAINT_COLUMNS']) as $value) {
$columns[] = trim($value, ' `');
}
$refColumns = [];
foreach (explode(',', $tableForeignKey['REFERENCED_TABLE_COLUMNS']) as $value) {
$refColumns[] = trim($value, ' `');
}
return new ForeignKeyConstraint(
$columns,
$tableForeignKey['REFERENCED_TABLE_NAME'],
$refColumns,
$tableForeignKey['CONSTRAINT_NAME'],
[
'onUpdate' => $tableForeignKey['UPDATE_RULE'],
'onDelete' => $tableForeignKey['DELETE_RULE'],
]
);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
{
$indexes = [];
foreach ($tableIndexes as $k) {
$k['primary'] = (bool) $k['primary'];
$indexes[] = $k;
}
return parent::_getPortableTableIndexesList($indexes, $tableName);
}
}

View File

@@ -0,0 +1,399 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use function array_keys;
use function array_map;
use function in_array;
use function strrpos;
use function strtolower;
use function strtoupper;
use function substr;
/**
* An abstraction class for a foreign key constraint.
*/
class ForeignKeyConstraint extends AbstractAsset implements Constraint
{
/**
* Instance of the referencing table the foreign key constraint is associated with.
*
* @var Table
*/
protected $_localTable;
/**
* Asset identifier instances of the referencing table column names the foreign key constraint is associated with.
* array($columnName => Identifier)
*
* @var Identifier[]
*/
protected $_localColumnNames;
/**
* Table or asset identifier instance of the referenced table name the foreign key constraint is associated with.
*
* @var Table|Identifier
*/
protected $_foreignTableName;
/**
* Asset identifier instances of the referenced table column names the foreign key constraint is associated with.
* array($columnName => Identifier)
*
* @var Identifier[]
*/
protected $_foreignColumnNames;
/**
* Options associated with the foreign key constraint.
*
* @var mixed[]
*/
protected $_options;
/**
* Initializes the foreign key constraint.
*
* @param string[] $localColumnNames Names of the referencing table columns.
* @param Table|string $foreignTableName Referenced table.
* @param string[] $foreignColumnNames Names of the referenced table columns.
* @param string|null $name Name of the foreign key constraint.
* @param mixed[] $options Options associated with the foreign key constraint.
*/
public function __construct(
array $localColumnNames,
$foreignTableName,
array $foreignColumnNames,
$name = null,
array $options = []
) {
if ($name !== null) {
$this->_setName($name);
}
$this->_localColumnNames = $this->createIdentifierMap($localColumnNames);
if ($foreignTableName instanceof Table) {
$this->_foreignTableName = $foreignTableName;
} else {
$this->_foreignTableName = new Identifier($foreignTableName);
}
$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.
*
* @return string
*/
public function getLocalTableName()
{
return $this->_localTable->getName();
}
/**
* Sets the Table instance of the referencing table
* the foreign key constraint is associated with.
*
* @param Table $table Instance of the referencing table.
*
* @return void
*/
public function setLocalTable(Table $table)
{
$this->_localTable = $table;
}
/**
* @return Table
*/
public function getLocalTable()
{
return $this->_localTable;
}
/**
* Returns the names of the referencing table columns
* the foreign key constraint is associated with.
*
* @return string[]
*/
public function getLocalColumns()
{
return array_keys($this->_localColumnNames);
}
/**
* Returns the quoted representation of the referencing table column names
* the foreign key constraint is associated with.
*
* But only if they were defined with one or the referencing table column name
* is a keyword reserved by the platform.
* Otherwise the plain unquoted value as inserted is returned.
*
* @param AbstractPlatform $platform The platform to use for quotation.
*
* @return string[]
*/
public function getQuotedLocalColumns(AbstractPlatform $platform)
{
$columns = [];
foreach ($this->_localColumnNames as $column) {
$columns[] = $column->getQuotedName($platform);
}
return $columns;
}
/**
* Returns unquoted representation of local table column names for comparison with other FK
*
* @return string[]
*/
public function getUnquotedLocalColumns()
{
return array_map([$this, 'trimQuotes'], $this->getLocalColumns());
}
/**
* Returns unquoted representation of foreign table column names for comparison with other FK
*
* @return string[]
*/
public function getUnquotedForeignColumns()
{
return array_map([$this, 'trimQuotes'], $this->getForeignColumns());
}
/**
* {@inheritdoc}
*
* @see getLocalColumns
*/
public function getColumns()
{
return $this->getLocalColumns();
}
/**
* Returns the quoted representation of the referencing table column names
* the foreign key constraint is associated with.
*
* But only if they were defined with one or the referencing table column name
* is a keyword reserved by the platform.
* Otherwise the plain unquoted value as inserted is returned.
*
* @see getQuotedLocalColumns
*
* @param AbstractPlatform $platform The platform to use for quotation.
*
* @return string[]
*/
public function getQuotedColumns(AbstractPlatform $platform)
{
return $this->getQuotedLocalColumns($platform);
}
/**
* Returns the name of the referenced table
* the foreign key constraint is associated with.
*
* @return string
*/
public function getForeignTableName()
{
return $this->_foreignTableName->getName();
}
/**
* Returns the non-schema qualified foreign table name.
*
* @return string
*/
public function getUnqualifiedForeignTableName()
{
$name = $this->_foreignTableName->getName();
$position = strrpos($name, '.');
if ($position !== false) {
$name = substr($name, $position + 1);
}
return strtolower($name);
}
/**
* Returns the quoted representation of the referenced table name
* the foreign key constraint is associated with.
*
* But only if it was defined with one or the referenced table name
* is a keyword reserved by the platform.
* Otherwise the plain unquoted value as inserted is returned.
*
* @param AbstractPlatform $platform The platform to use for quotation.
*
* @return string
*/
public function getQuotedForeignTableName(AbstractPlatform $platform)
{
return $this->_foreignTableName->getQuotedName($platform);
}
/**
* Returns the names of the referenced table columns
* the foreign key constraint is associated with.
*
* @return string[]
*/
public function getForeignColumns()
{
return array_keys($this->_foreignColumnNames);
}
/**
* Returns the quoted representation of the referenced table column names
* the foreign key constraint is associated with.
*
* But only if they were defined with one or the referenced table column name
* is a keyword reserved by the platform.
* Otherwise the plain unquoted value as inserted is returned.
*
* @param AbstractPlatform $platform The platform to use for quotation.
*
* @return string[]
*/
public function getQuotedForeignColumns(AbstractPlatform $platform)
{
$columns = [];
foreach ($this->_foreignColumnNames as $column) {
$columns[] = $column->getQuotedName($platform);
}
return $columns;
}
/**
* Returns whether or not a given option
* is associated with the foreign key constraint.
*
* @param string $name Name of the option to check.
*
* @return bool
*/
public function hasOption($name)
{
return isset($this->_options[$name]);
}
/**
* Returns an option associated with the foreign key constraint.
*
* @param string $name Name of the option the foreign key constraint is associated with.
*
* @return mixed
*/
public function getOption($name)
{
return $this->_options[$name];
}
/**
* Returns the options associated with the foreign key constraint.
*
* @return mixed[]
*/
public function getOptions()
{
return $this->_options;
}
/**
* Returns the referential action for UPDATE operations
* on the referenced table the foreign key constraint is associated with.
*
* @return string|null
*/
public function onUpdate()
{
return $this->onEvent('onUpdate');
}
/**
* Returns the referential action for DELETE operations
* on the referenced table the foreign key constraint is associated with.
*
* @return string|null
*/
public function onDelete()
{
return $this->onEvent('onDelete');
}
/**
* Returns the referential action for a given database operation
* on the referenced table the foreign key constraint is associated with.
*
* @param string $event Name of the database operation/event to return the referential action for.
*
* @return string|null
*/
private function onEvent($event)
{
if (isset($this->_options[$event])) {
$onEvent = strtoupper($this->_options[$event]);
if (! in_array($onEvent, ['NO ACTION', 'RESTRICT'])) {
return $onEvent;
}
}
return null;
}
/**
* Checks whether this foreign key constraint intersects the given index columns.
*
* Returns `true` if at least one of this foreign key's local columns
* matches one of the given index's columns, `false` otherwise.
*
* @param Index $index The index to be checked against.
*
* @return bool
*/
public function intersectsIndexColumns(Index $index)
{
foreach ($index->getColumns() as $indexColumn) {
foreach ($this->_localColumnNames as $localColumn) {
if (strtolower($indexColumn) === strtolower($localColumn->getName())) {
return true;
}
}
}
return false;
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Doctrine\DBAL\Schema;
/**
* An abstraction class for an asset identifier.
*
* Wraps identifier names like column names in indexes / foreign keys
* in an abstract class for proper quotation capabilities.
*/
class Identifier extends AbstractAsset
{
/**
* @param string $identifier Identifier name to wrap.
* @param bool $quote Whether to force quoting the given identifier.
*/
public function __construct($identifier, $quote = false)
{
$this->_setName($identifier);
if (! $quote || $this->_quoted) {
return;
}
$this->_setName('"' . $this->getName() . '"');
}
}

View File

@@ -0,0 +1,376 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use InvalidArgumentException;
use function array_filter;
use function array_keys;
use function array_map;
use function array_search;
use function array_shift;
use function count;
use function is_string;
use function strtolower;
class Index extends AbstractAsset implements Constraint
{
/**
* Asset identifier instances of the column names the index is associated with.
* array($columnName => Identifier)
*
* @var Identifier[]
*/
protected $_columns = [];
/** @var bool */
protected $_isUnique = false;
/** @var bool */
protected $_isPrimary = false;
/**
* Platform specific flags for indexes.
* array($flagName => true)
*
* @var true[]
*/
protected $_flags = [];
/**
* Platform specific options
*
* @todo $_flags should eventually be refactored into options
* @var mixed[]
*/
private $options = [];
/**
* @param string $name
* @param string[] $columns
* @param bool $isUnique
* @param bool $isPrimary
* @param string[] $flags
* @param mixed[] $options
*/
public function __construct(
$name,
array $columns,
$isUnique = false,
$isPrimary = false,
array $flags = [],
array $options = []
) {
$isUnique = $isUnique || $isPrimary;
$this->_setName($name);
$this->_isUnique = $isUnique;
$this->_isPrimary = $isPrimary;
$this->options = $options;
foreach ($columns as $column) {
$this->_addColumn($column);
}
foreach ($flags as $flag) {
$this->addFlag($flag);
}
}
/**
* @param string $column
*
* @return void
*
* @throws InvalidArgumentException
*/
protected function _addColumn($column)
{
if (! is_string($column)) {
throw new InvalidArgumentException('Expecting a string as Index Column');
}
$this->_columns[$column] = new Identifier($column);
}
/**
* {@inheritdoc}
*/
public function getColumns()
{
return array_keys($this->_columns);
}
/**
* {@inheritdoc}
*/
public function getQuotedColumns(AbstractPlatform $platform)
{
$subParts = $platform->supportsColumnLengthIndexes() && $this->hasOption('lengths')
? $this->getOption('lengths') : [];
$columns = [];
foreach ($this->_columns as $column) {
$length = array_shift($subParts);
$quotedColumn = $column->getQuotedName($platform);
if ($length !== null) {
$quotedColumn .= '(' . $length . ')';
}
$columns[] = $quotedColumn;
}
return $columns;
}
/**
* @return string[]
*/
public function getUnquotedColumns()
{
return array_map([$this, 'trimQuotes'], $this->getColumns());
}
/**
* Is the index neither unique nor primary key?
*
* @return bool
*/
public function isSimpleIndex()
{
return ! $this->_isPrimary && ! $this->_isUnique;
}
/**
* @return bool
*/
public function isUnique()
{
return $this->_isUnique;
}
/**
* @return bool
*/
public function isPrimary()
{
return $this->_isPrimary;
}
/**
* @param string $name
* @param int $pos
*
* @return bool
*/
public function hasColumnAtPosition($name, $pos = 0)
{
$name = $this->trimQuotes(strtolower($name));
$indexColumns = array_map('strtolower', $this->getUnquotedColumns());
return array_search($name, $indexColumns) === $pos;
}
/**
* Checks if this index exactly spans the given column names in the correct order.
*
* @param string[] $columnNames
*
* @return bool
*/
public function spansColumns(array $columnNames)
{
$columns = $this->getColumns();
$numberOfColumns = count($columns);
$sameColumns = true;
for ($i = 0; $i < $numberOfColumns; $i++) {
if (
isset($columnNames[$i])
&& $this->trimQuotes(strtolower($columns[$i])) === $this->trimQuotes(strtolower($columnNames[$i]))
) {
continue;
}
$sameColumns = false;
}
return $sameColumns;
}
/**
* Checks if the other index already fulfills all the indexing and constraint needs of the current one.
*
* @return bool
*/
public function isFullfilledBy(Index $other)
{
// allow the other index to be equally large only. It being larger is an option
// but it creates a problem with scenarios of the kind PRIMARY KEY(foo,bar) UNIQUE(foo)
if (count($other->getColumns()) !== count($this->getColumns())) {
return false;
}
// Check if columns are the same, and even in the same order
$sameColumns = $this->spansColumns($other->getColumns());
if ($sameColumns) {
if (! $this->samePartialIndex($other)) {
return false;
}
if (! $this->hasSameColumnLengths($other)) {
return false;
}
if (! $this->isUnique() && ! $this->isPrimary()) {
// this is a special case: If the current key is neither primary or unique, any unique or
// primary key will always have the same effect for the index and there cannot be any constraint
// overlaps. This means a primary or unique index can always fulfill the requirements of just an
// index that has no constraints.
return true;
}
if ($other->isPrimary() !== $this->isPrimary()) {
return false;
}
return $other->isUnique() === $this->isUnique();
}
return false;
}
/**
* Detects if the other index is a non-unique, non primary index that can be overwritten by this one.
*
* @return bool
*/
public function overrules(Index $other)
{
if ($other->isPrimary()) {
return false;
}
if ($this->isSimpleIndex() && $other->isUnique()) {
return false;
}
return $this->spansColumns($other->getColumns())
&& ($this->isPrimary() || $this->isUnique())
&& $this->samePartialIndex($other);
}
/**
* Returns platform specific flags for indexes.
*
* @return string[]
*/
public function getFlags()
{
return array_keys($this->_flags);
}
/**
* Adds Flag for an index that translates to platform specific handling.
*
* @param string $flag
*
* @return Index
*
* @example $index->addFlag('CLUSTERED')
*/
public function addFlag($flag)
{
$this->_flags[strtolower($flag)] = true;
return $this;
}
/**
* Does this index have a specific flag?
*
* @param string $flag
*
* @return bool
*/
public function hasFlag($flag)
{
return isset($this->_flags[strtolower($flag)]);
}
/**
* Removes a flag.
*
* @param string $flag
*
* @return void
*/
public function removeFlag($flag)
{
unset($this->_flags[strtolower($flag)]);
}
/**
* @param string $name
*
* @return bool
*/
public function hasOption($name)
{
return isset($this->options[strtolower($name)]);
}
/**
* @param string $name
*
* @return mixed
*/
public function getOption($name)
{
return $this->options[strtolower($name)];
}
/**
* @return mixed[]
*/
public function getOptions()
{
return $this->options;
}
/**
* Return whether the two indexes have the same partial index
*
* @return bool
*/
private function samePartialIndex(Index $other)
{
if (
$this->hasOption('where')
&& $other->hasOption('where')
&& $this->getOption('where') === $other->getOption('where')
) {
return true;
}
return ! $this->hasOption('where') && ! $other->hasOption('where');
}
/**
* Returns whether the index has the same column lengths as the other
*/
private function hasSameColumnLengths(self $other): bool
{
$filter = static function (?int $length): bool {
return $length !== null;
};
return array_filter($this->options['lengths'] ?? [], $filter)
=== array_filter($other->options['lengths'] ?? [], $filter);
}
}

View File

@@ -0,0 +1,374 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\DBAL\Types\Type;
use function array_change_key_case;
use function array_shift;
use function assert;
use function explode;
use function is_string;
use function preg_match;
use function strpos;
use function strtok;
use function strtolower;
use function strtr;
use const CASE_LOWER;
/**
* 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}
*/
protected function _getPortableViewDefinition($view)
{
return new View($view['TABLE_NAME'], $view['VIEW_DEFINITION']);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableDefinition($table)
{
return array_shift($table);
}
/**
* {@inheritdoc}
*/
protected function _getPortableUserDefinition($user)
{
return [
'user' => $user['User'],
'password' => $user['Password'],
];
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
{
foreach ($tableIndexes as $k => $v) {
$v = array_change_key_case($v, CASE_LOWER);
if ($v['key_name'] === 'PRIMARY') {
$v['primary'] = true;
} else {
$v['primary'] = false;
}
if (strpos($v['index_type'], 'FULLTEXT') !== false) {
$v['flags'] = ['FULLTEXT'];
} elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
$v['flags'] = ['SPATIAL'];
}
// Ignore prohibited prefix `length` for spatial index
if (strpos($v['index_type'], 'SPATIAL') === false) {
$v['length'] = isset($v['sub_part']) ? (int) $v['sub_part'] : null;
}
$tableIndexes[$k] = $v;
}
return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
}
/**
* {@inheritdoc}
*/
protected function _getPortableDatabaseDefinition($database)
{
return $database['Database'];
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableColumnDefinition($tableColumn)
{
$tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
$dbType = strtolower($tableColumn['type']);
$dbType = strtok($dbType, '(), ');
assert(is_string($dbType));
$length = $tableColumn['length'] ?? strtok('(), ');
$fixed = null;
if (! isset($tableColumn['name'])) {
$tableColumn['name'] = '';
}
$scale = null;
$precision = null;
$type = $this->_platform->getDoctrineTypeMapping($dbType);
// In cases where not connected to a database DESCRIBE $table does not return 'Comment'
if (isset($tableColumn['comment'])) {
$type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
$tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
}
switch ($dbType) {
case 'char':
case 'binary':
$fixed = true;
break;
case 'float':
case 'double':
case 'real':
case 'numeric':
case 'decimal':
if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
$precision = $match[1];
$scale = $match[2];
$length = null;
}
break;
case 'tinytext':
$length = MySqlPlatform::LENGTH_LIMIT_TINYTEXT;
break;
case 'text':
$length = MySqlPlatform::LENGTH_LIMIT_TEXT;
break;
case 'mediumtext':
$length = MySqlPlatform::LENGTH_LIMIT_MEDIUMTEXT;
break;
case 'tinyblob':
$length = MySqlPlatform::LENGTH_LIMIT_TINYBLOB;
break;
case 'blob':
$length = MySqlPlatform::LENGTH_LIMIT_BLOB;
break;
case 'mediumblob':
$length = MySqlPlatform::LENGTH_LIMIT_MEDIUMBLOB;
break;
case 'tinyint':
case 'smallint':
case 'mediumint':
case 'int':
case 'integer':
case 'bigint':
case 'year':
$length = null;
break;
}
if ($this->_platform instanceof MariaDb1027Platform) {
$columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
} else {
$columnDefault = $tableColumn['default'];
}
$options = [
'length' => $length !== null ? (int) $length : null,
'unsigned' => strpos($tableColumn['type'], 'unsigned') !== false,
'fixed' => (bool) $fixed,
'default' => $columnDefault,
'notnull' => $tableColumn['null'] !== 'YES',
'scale' => null,
'precision' => null,
'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
'comment' => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
? $tableColumn['comment']
: null,
];
if ($scale !== null && $precision !== null) {
$options['scale'] = (int) $scale;
$options['precision'] = (int) $precision;
}
$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']);
}
return $column;
}
/**
* Return Doctrine/Mysql-compatible column default values for MariaDB 10.2.7+ servers.
*
* - Since MariaDb 10.2.7 column defaults stored in information_schema are now quoted
* to distinguish them from expressions (see MDEV-10134).
* - CURRENT_TIMESTAMP, CURRENT_TIME, CURRENT_DATE are stored in information_schema
* as current_timestamp(), currdate(), currtime()
* - Quoted 'NULL' is not enforced by Maria, it is technically possible to have
* null in some circumstances (see https://jira.mariadb.org/browse/MDEV-14053)
* - \' is always stored as '' in information_schema (normalized)
*
* @link https://mariadb.com/kb/en/library/information-schema-columns-table/
* @link https://jira.mariadb.org/browse/MDEV-13132
*
* @param string|null $columnDefault default value as stored in information_schema for MariaDB >= 10.2.7
*/
private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault): ?string
{
if ($columnDefault === 'NULL' || $columnDefault === null) {
return null;
}
if (preg_match('/^\'(.*)\'$/', $columnDefault, $matches)) {
return strtr($matches[1], self::MARIADB_ESCAPE_SEQUENCES);
}
switch ($columnDefault) {
case 'current_timestamp()':
return $platform->getCurrentTimestampSQL();
case 'curdate()':
return $platform->getCurrentDateSQL();
case 'curtime()':
return $platform->getCurrentTimeSQL();
}
return $columnDefault;
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableForeignKeysList($tableForeignKeys)
{
$list = [];
foreach ($tableForeignKeys as $value) {
$value = array_change_key_case($value, CASE_LOWER);
if (! isset($list[$value['constraint_name']])) {
if (! isset($value['delete_rule']) || $value['delete_rule'] === 'RESTRICT') {
$value['delete_rule'] = null;
}
if (! isset($value['update_rule']) || $value['update_rule'] === 'RESTRICT') {
$value['update_rule'] = null;
}
$list[$value['constraint_name']] = [
'name' => $value['constraint_name'],
'local' => [],
'foreign' => [],
'foreignTable' => $value['referenced_table_name'],
'onDelete' => $value['delete_rule'],
'onUpdate' => $value['update_rule'],
];
}
$list[$value['constraint_name']]['local'][] = $value['column_name'];
$list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
}
$result = [];
foreach ($list as $constraint) {
$result[] = new ForeignKeyConstraint(
$constraint['local'],
$constraint['foreignTable'],
$constraint['foreign'],
$constraint['name'],
[
'onDelete' => $constraint['onDelete'],
'onUpdate' => $constraint['onUpdate'],
]
);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function listTableDetails($name)
{
$table = parent::listTableDetails($name);
$platform = $this->_platform;
assert($platform instanceof MySqlPlatform);
$sql = $platform->getListTableMetadataSQL($name);
$tableOptions = $this->_conn->fetchAssociative($sql);
if ($tableOptions === false) {
return $table;
}
$table->addOption('engine', $tableOptions['ENGINE']);
if ($tableOptions['TABLE_COLLATION'] !== null) {
$table->addOption('collation', $tableOptions['TABLE_COLLATION']);
}
if ($tableOptions['AUTO_INCREMENT'] !== null) {
$table->addOption('autoincrement', $tableOptions['AUTO_INCREMENT']);
}
$table->addOption('comment', $tableOptions['TABLE_COMMENT']);
$table->addOption('create_options', $this->parseCreateOptions($tableOptions['CREATE_OPTIONS']));
return $table;
}
/**
* @return string[]|true[]
*/
private function parseCreateOptions(?string $string): array
{
$options = [];
if ($string === null || $string === '') {
return $options;
}
foreach (explode(' ', $string) as $pair) {
$parts = explode('=', $pair, 2);
$options[$parts[0]] = $parts[1] ?? true;
}
return $options;
}
}

View File

@@ -0,0 +1,425 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\Exception;
use Doctrine\DBAL\Platforms\OraclePlatform;
use Doctrine\DBAL\Types\Type;
use Throwable;
use function array_change_key_case;
use function array_values;
use function assert;
use function is_string;
use function preg_match;
use function sprintf;
use function str_replace;
use function strpos;
use function strtolower;
use function strtoupper;
use function trim;
use const CASE_LOWER;
/**
* Oracle Schema Manager.
*/
class OracleSchemaManager extends AbstractSchemaManager
{
/**
* {@inheritdoc}
*/
public function dropDatabase($database)
{
try {
parent::dropDatabase($database);
} catch (DBALException $exception) {
$exception = $exception->getPrevious();
assert($exception instanceof Throwable);
if (! $exception instanceof Exception) {
throw $exception;
}
// If we have a error code 1940 (ORA-01940), the drop database operation failed
// because of active connections on the database.
// To force dropping the database, we first have to close all active connections
// on that database and issue the drop database operation again.
if ($exception->getErrorCode() !== 1940) {
throw $exception;
}
$this->killUserSessions($database);
parent::dropDatabase($database);
}
}
/**
* {@inheritdoc}
*/
protected function _getPortableViewDefinition($view)
{
$view = array_change_key_case($view, CASE_LOWER);
return new View($this->getQuotedIdentifierName($view['view_name']), $view['text']);
}
/**
* {@inheritdoc}
*/
protected function _getPortableUserDefinition($user)
{
$user = array_change_key_case($user, CASE_LOWER);
return [
'user' => $user['username'],
];
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableDefinition($table)
{
$table = array_change_key_case($table, CASE_LOWER);
return $this->getQuotedIdentifierName($table['table_name']);
}
/**
* {@inheritdoc}
*
* @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
*/
protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
{
$indexBuffer = [];
foreach ($tableIndexes as $tableIndex) {
$tableIndex = array_change_key_case($tableIndex, CASE_LOWER);
$keyName = strtolower($tableIndex['name']);
$buffer = [];
if ($tableIndex['is_primary'] === 'P') {
$keyName = 'primary';
$buffer['primary'] = true;
$buffer['non_unique'] = false;
} else {
$buffer['primary'] = false;
$buffer['non_unique'] = ! $tableIndex['is_unique'];
}
$buffer['key_name'] = $keyName;
$buffer['column_name'] = $this->getQuotedIdentifierName($tableIndex['column_name']);
$indexBuffer[] = $buffer;
}
return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableColumnDefinition($tableColumn)
{
$tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
$dbType = strtolower($tableColumn['data_type']);
if (strpos($dbType, 'timestamp(') === 0) {
if (strpos($dbType, 'with time zone')) {
$dbType = 'timestamptz';
} else {
$dbType = 'timestamp';
}
}
$unsigned = $fixed = $precision = $scale = $length = null;
if (! isset($tableColumn['column_name'])) {
$tableColumn['column_name'] = '';
}
// Default values returned from database sometimes have trailing spaces.
if (is_string($tableColumn['data_default'])) {
$tableColumn['data_default'] = trim($tableColumn['data_default']);
}
if ($tableColumn['data_default'] === '' || $tableColumn['data_default'] === 'NULL') {
$tableColumn['data_default'] = null;
}
if ($tableColumn['data_default'] !== null) {
// 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) {
$precision = (int) $tableColumn['data_precision'];
}
if ($tableColumn['data_scale'] !== null) {
$scale = (int) $tableColumn['data_scale'];
}
$type = $this->_platform->getDoctrineTypeMapping($dbType);
$type = $this->extractDoctrineTypeFromComment($tableColumn['comments'], $type);
$tableColumn['comments'] = $this->removeDoctrineTypeFromComment($tableColumn['comments'], $type);
switch ($dbType) {
case 'number':
if ($precision === 20 && $scale === 0) {
$type = 'bigint';
} elseif ($precision === 5 && $scale === 0) {
$type = 'smallint';
} elseif ($precision === 1 && $scale === 0) {
$type = 'boolean';
} elseif ($scale > 0) {
$type = 'decimal';
}
break;
case 'varchar':
case 'varchar2':
case 'nvarchar2':
$length = $tableColumn['char_length'];
$fixed = false;
break;
case 'char':
case 'nchar':
$length = $tableColumn['char_length'];
$fixed = true;
break;
}
$options = [
'notnull' => $tableColumn['nullable'] === 'N',
'fixed' => (bool) $fixed,
'unsigned' => (bool) $unsigned,
'default' => $tableColumn['data_default'],
'length' => $length,
'precision' => $precision,
'scale' => $scale,
'comment' => isset($tableColumn['comments']) && $tableColumn['comments'] !== ''
? $tableColumn['comments']
: null,
];
return new Column($this->getQuotedIdentifierName($tableColumn['column_name']), Type::getType($type), $options);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableForeignKeysList($tableForeignKeys)
{
$list = [];
foreach ($tableForeignKeys as $value) {
$value = array_change_key_case($value, CASE_LOWER);
if (! isset($list[$value['constraint_name']])) {
if ($value['delete_rule'] === 'NO ACTION') {
$value['delete_rule'] = null;
}
$list[$value['constraint_name']] = [
'name' => $this->getQuotedIdentifierName($value['constraint_name']),
'local' => [],
'foreign' => [],
'foreignTable' => $value['references_table'],
'onDelete' => $value['delete_rule'],
];
}
$localColumn = $this->getQuotedIdentifierName($value['local_column']);
$foreignColumn = $this->getQuotedIdentifierName($value['foreign_column']);
$list[$value['constraint_name']]['local'][$value['position']] = $localColumn;
$list[$value['constraint_name']]['foreign'][$value['position']] = $foreignColumn;
}
$result = [];
foreach ($list as $constraint) {
$result[] = new ForeignKeyConstraint(
array_values($constraint['local']),
$this->getQuotedIdentifierName($constraint['foreignTable']),
array_values($constraint['foreign']),
$this->getQuotedIdentifierName($constraint['name']),
['onDelete' => $constraint['onDelete']]
);
}
return $result;
}
/**
* {@inheritdoc}
*/
protected function _getPortableSequenceDefinition($sequence)
{
$sequence = array_change_key_case($sequence, CASE_LOWER);
return new Sequence(
$this->getQuotedIdentifierName($sequence['sequence_name']),
(int) $sequence['increment_by'],
(int) $sequence['min_value']
);
}
/**
* {@inheritdoc}
*
* @deprecated
*/
protected function _getPortableFunctionDefinition($function)
{
$function = array_change_key_case($function, CASE_LOWER);
return $function['name'];
}
/**
* {@inheritdoc}
*/
protected function _getPortableDatabaseDefinition($database)
{
$database = array_change_key_case($database, CASE_LOWER);
return $database['username'];
}
/**
* {@inheritdoc}
*
* @param string|null $database
*
* Calling this method without an argument or by passing NULL is deprecated.
*/
public function createDatabase($database = null)
{
if ($database === null) {
$database = $this->_conn->getDatabase();
}
$statement = 'CREATE USER ' . $database;
$params = $this->_conn->getParams();
if (isset($params['password'])) {
$statement .= ' IDENTIFIED BY ' . $params['password'];
}
$this->_conn->executeStatement($statement);
$statement = 'GRANT DBA TO ' . $database;
$this->_conn->executeStatement($statement);
}
/**
* @param string $table
*
* @return bool
*/
public function dropAutoincrement($table)
{
assert($this->_platform instanceof OraclePlatform);
$sql = $this->_platform->getDropAutoincrementSql($table);
foreach ($sql as $query) {
$this->_conn->executeStatement($query);
}
return true;
}
/**
* {@inheritdoc}
*/
public function dropTable($name)
{
$this->tryMethod('dropAutoincrement', $name);
parent::dropTable($name);
}
/**
* Returns the quoted representation of the given identifier name.
*
* Quotes non-uppercase identifiers explicitly to preserve case
* and thus make references to the particular identifier work.
*
* @param string $identifier The identifier to quote.
*
* @return string The quoted identifier.
*/
private function getQuotedIdentifierName($identifier)
{
if (preg_match('/[a-z]/', $identifier)) {
return $this->_platform->quoteIdentifier($identifier);
}
return $identifier;
}
/**
* Kills sessions connected with the given user.
*
* This is useful to force DROP USER operations which could fail because of active user sessions.
*
* @param string $user The name of the user to kill sessions for.
*
* @return void
*/
private function killUserSessions($user)
{
$sql = <<<SQL
SELECT
s.sid,
s.serial#
FROM
gv\$session s,
gv\$process p
WHERE
s.username = ?
AND p.addr(+) = s.paddr
SQL;
$activeUserSessions = $this->_conn->fetchAllAssociative($sql, [strtoupper($user)]);
foreach ($activeUserSessions as $activeUserSession) {
$activeUserSession = array_change_key_case($activeUserSession, CASE_LOWER);
$this->_execSql(
sprintf(
"ALTER SYSTEM KILL SESSION '%s, %s' IMMEDIATE",
$activeUserSession['sid'],
$activeUserSession['serial#']
)
);
}
}
/**
* {@inheritdoc}
*/
public function listTableDetails($name): Table
{
$table = parent::listTableDetails($name);
$platform = $this->_platform;
assert($platform instanceof OraclePlatform);
$sql = $platform->getListTableCommentsSQL($name);
$tableOptions = $this->_conn->fetchAssociative($sql);
if ($tableOptions !== false) {
$table->addOption('comment', $tableOptions['COMMENTS']);
}
return $table;
}
}

View File

@@ -0,0 +1,544 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Exception\DriverException;
use Doctrine\DBAL\FetchMode;
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\Types;
use function array_change_key_case;
use function array_filter;
use function array_keys;
use function array_map;
use function array_shift;
use function assert;
use function explode;
use function implode;
use function in_array;
use function preg_match;
use function preg_replace;
use function sprintf;
use function str_replace;
use function strpos;
use function strtolower;
use function trim;
use const CASE_LOWER;
/**
* PostgreSQL Schema Manager.
*/
class PostgreSqlSchemaManager extends AbstractSchemaManager
{
/** @var string[]|null */
private $existingSchemaPaths;
/**
* Gets all the existing schema names.
*
* @return string[]
*/
public function getSchemaNames()
{
$statement = $this->_conn->executeQuery(
"SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_.*' AND nspname != 'information_schema'"
);
return $statement->fetchAll(FetchMode::COLUMN);
}
/**
* Returns an array of schema search paths.
*
* This is a PostgreSQL only function.
*
* @return string[]
*/
public function getSchemaSearchPaths()
{
$params = $this->_conn->getParams();
$searchPaths = $this->_conn->fetchColumn('SHOW search_path');
assert($searchPaths !== false);
$schema = explode(',', $searchPaths);
if (isset($params['user'])) {
$schema = str_replace('"$user"', $params['user'], $schema);
}
return array_map('trim', $schema);
}
/**
* Gets names of all existing schemas in the current users search path.
*
* This is a PostgreSQL only function.
*
* @return string[]
*/
public function getExistingSchemaSearchPaths()
{
if ($this->existingSchemaPaths === null) {
$this->determineExistingSchemaSearchPaths();
}
assert($this->existingSchemaPaths !== null);
return $this->existingSchemaPaths;
}
/**
* Sets or resets the order of the existing schemas in the current search path of the user.
*
* This is a PostgreSQL only function.
*
* @return void
*/
public function determineExistingSchemaSearchPaths()
{
$names = $this->getSchemaNames();
$paths = $this->getSchemaSearchPaths();
$this->existingSchemaPaths = array_filter($paths, static function ($v) use ($names) {
return in_array($v, $names);
});
}
/**
* {@inheritdoc}
*/
public function dropDatabase($database)
{
try {
parent::dropDatabase($database);
} catch (DriverException $exception) {
// If we have a SQLSTATE 55006, the drop database operation failed
// because of active connections on the database.
// To force dropping the database, we first have to close all active connections
// on that database and issue the drop database operation again.
if ($exception->getSQLState() !== '55006') {
throw $exception;
}
assert($this->_platform instanceof PostgreSqlPlatform);
$this->_execSql(
[
$this->_platform->getDisallowDatabaseConnectionsSQL($database),
$this->_platform->getCloseActiveDatabaseConnectionsSQL($database),
]
);
parent::dropDatabase($database);
}
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
{
$onUpdate = null;
$onDelete = null;
$localColumns = [];
$foreignColumns = [];
$foreignTable = null;
if (preg_match('(ON UPDATE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
$onUpdate = $match[1];
}
if (preg_match('(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
$onDelete = $match[1];
}
$result = preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $tableForeignKey['condef'], $values);
assert($result === 1);
// PostgreSQL returns identifiers that are keywords with quotes, we need them later, don't get
// the idea to trim them here.
$localColumns = array_map('trim', explode(',', $values[1]));
$foreignColumns = array_map('trim', explode(',', $values[3]));
$foreignTable = $values[2];
return new ForeignKeyConstraint(
$localColumns,
$foreignTable,
$foreignColumns,
$tableForeignKey['conname'],
['onUpdate' => $onUpdate, 'onDelete' => $onDelete]
);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTriggerDefinition($trigger)
{
return $trigger['trigger_name'];
}
/**
* {@inheritdoc}
*/
protected function _getPortableViewDefinition($view)
{
return new View($view['schemaname'] . '.' . $view['viewname'], $view['definition']);
}
/**
* {@inheritdoc}
*/
protected function _getPortableUserDefinition($user)
{
return [
'user' => $user['usename'],
'password' => $user['passwd'],
];
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableDefinition($table)
{
$schemas = $this->getExistingSchemaSearchPaths();
$firstSchema = array_shift($schemas);
if ($table['schema_name'] === $firstSchema) {
return $table['table_name'];
}
return $table['schema_name'] . '.' . $table['table_name'];
}
/**
* {@inheritdoc}
*
* @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
*/
protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
{
$buffer = [];
foreach ($tableIndexes as $row) {
$colNumbers = array_map('intval', explode(' ', $row['indkey']));
$columnNameSql = sprintf(
'SELECT attnum, attname FROM pg_attribute WHERE attrelid=%d AND attnum IN (%s) ORDER BY attnum ASC',
$row['indrelid'],
implode(' ,', $colNumbers)
);
$indexColumns = $this->_conn->fetchAllAssociative($columnNameSql);
// required for getting the order of the columns right.
foreach ($colNumbers as $colNum) {
foreach ($indexColumns as $colRow) {
if ($colNum !== $colRow['attnum']) {
continue;
}
$buffer[] = [
'key_name' => $row['relname'],
'column_name' => trim($colRow['attname']),
'non_unique' => ! $row['indisunique'],
'primary' => $row['indisprimary'],
'where' => $row['where'],
];
}
}
}
return parent::_getPortableTableIndexesList($buffer, $tableName);
}
/**
* {@inheritdoc}
*/
protected function _getPortableDatabaseDefinition($database)
{
return $database['datname'];
}
/**
* {@inheritdoc}
*/
protected function _getPortableSequencesList($sequences)
{
$sequenceDefinitions = [];
foreach ($sequences as $sequence) {
if ($sequence['schemaname'] !== 'public') {
$sequenceName = $sequence['schemaname'] . '.' . $sequence['relname'];
} else {
$sequenceName = $sequence['relname'];
}
$sequenceDefinitions[$sequenceName] = $sequence;
}
$list = [];
foreach ($this->filterAssetNames(array_keys($sequenceDefinitions)) as $sequenceName) {
$list[] = $this->_getPortableSequenceDefinition($sequenceDefinitions[$sequenceName]);
}
return $list;
}
/**
* {@inheritdoc}
*/
protected function getPortableNamespaceDefinition(array $namespace)
{
return $namespace['nspname'];
}
/**
* {@inheritdoc}
*/
protected function _getPortableSequenceDefinition($sequence)
{
if ($sequence['schemaname'] !== 'public') {
$sequenceName = $sequence['schemaname'] . '.' . $sequence['relname'];
} else {
$sequenceName = $sequence['relname'];
}
if (! isset($sequence['increment_by'], $sequence['min_value'])) {
/** @var string[] $data */
$data = $this->_conn->fetchAssoc(
'SELECT min_value, increment_by FROM ' . $this->_platform->quoteIdentifier($sequenceName)
);
$sequence += $data;
}
return new Sequence($sequenceName, (int) $sequence['increment_by'], (int) $sequence['min_value']);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableColumnDefinition($tableColumn)
{
$tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
if (strtolower($tableColumn['type']) === 'varchar' || strtolower($tableColumn['type']) === 'bpchar') {
// get length from varchar definition
$length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']);
$tableColumn['length'] = $length;
}
$matches = [];
$autoincrement = false;
if (
$tableColumn['default'] !== null
&& preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches) === 1
) {
$tableColumn['sequence'] = $matches[1];
$tableColumn['default'] = null;
$autoincrement = true;
}
if ($tableColumn['default'] !== null) {
if (preg_match("/^['(](.*)[')]::/", $tableColumn['default'], $matches) === 1) {
$tableColumn['default'] = $matches[1];
} elseif (preg_match('/^NULL::/', $tableColumn['default']) === 1) {
$tableColumn['default'] = null;
}
}
$length = $tableColumn['length'] ?? null;
if ($length === '-1' && isset($tableColumn['atttypmod'])) {
$length = $tableColumn['atttypmod'] - 4;
}
if ((int) $length <= 0) {
$length = null;
}
$fixed = null;
if (! isset($tableColumn['name'])) {
$tableColumn['name'] = '';
}
$precision = null;
$scale = null;
$jsonb = null;
$dbType = strtolower($tableColumn['type']);
if (
$tableColumn['domain_type'] !== null
&& $tableColumn['domain_type'] !== ''
&& ! $this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])
) {
$dbType = strtolower($tableColumn['domain_type']);
$tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
}
$type = $this->_platform->getDoctrineTypeMapping($dbType);
$type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
$tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
switch ($dbType) {
case 'smallint':
case 'int2':
$tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
$length = null;
break;
case 'int':
case 'int4':
case 'integer':
$tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
$length = null;
break;
case 'bigint':
case 'int8':
$tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
$length = null;
break;
case 'bool':
case 'boolean':
if ($tableColumn['default'] === 'true') {
$tableColumn['default'] = true;
}
if ($tableColumn['default'] === 'false') {
$tableColumn['default'] = false;
}
$length = null;
break;
case 'text':
case '_varchar':
case 'varchar':
$tableColumn['default'] = $this->parseDefaultExpression($tableColumn['default']);
$fixed = false;
break;
case 'interval':
$fixed = false;
break;
case 'char':
case 'bpchar':
$fixed = true;
break;
case 'float':
case 'float4':
case 'float8':
case 'double':
case 'double precision':
case 'real':
case 'decimal':
case 'money':
case 'numeric':
$tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']);
if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
$precision = $match[1];
$scale = $match[2];
$length = null;
}
break;
case 'year':
$length = null;
break;
// PostgreSQL 9.4+ only
case 'jsonb':
$jsonb = true;
break;
}
if ($tableColumn['default'] && preg_match("('([^']+)'::)", $tableColumn['default'], $match)) {
$tableColumn['default'] = $match[1];
}
$options = [
'length' => $length,
'notnull' => (bool) $tableColumn['isnotnull'],
'default' => $tableColumn['default'],
'precision' => $precision,
'scale' => $scale,
'fixed' => $fixed,
'unsigned' => false,
'autoincrement' => $autoincrement,
'comment' => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
? $tableColumn['comment']
: null,
];
$column = new Column($tableColumn['field'], Type::getType($type), $options);
if (isset($tableColumn['collation']) && ! empty($tableColumn['collation'])) {
$column->setPlatformOption('collation', $tableColumn['collation']);
}
if (in_array($column->getType()->getName(), [Types::JSON_ARRAY, Types::JSON], true)) {
$column->setPlatformOption('jsonb', $jsonb);
}
return $column;
}
/**
* PostgreSQL 9.4 puts parentheses around negative numeric default values that need to be stripped eventually.
*
* @param mixed $defaultValue
*
* @return mixed
*/
private function fixVersion94NegativeNumericDefaultValue($defaultValue)
{
if ($defaultValue !== null && strpos($defaultValue, '(') === 0) {
return trim($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);
}
/**
* {@inheritdoc}
*/
public function listTableDetails($name): Table
{
$table = parent::listTableDetails($name);
$platform = $this->_platform;
assert($platform instanceof PostgreSqlPlatform);
$sql = $platform->getListTableMetadataSQL($name);
$tableOptions = $this->_conn->fetchAssoc($sql);
if ($tableOptions !== false) {
$table->addOption('comment', $tableOptions['table_comment']);
}
return $table;
}
}

View File

@@ -0,0 +1,236 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Platforms\SQLAnywherePlatform;
use Doctrine\DBAL\Types\Type;
use function assert;
use function preg_replace;
/**
* SAP Sybase SQL Anywhere schema manager.
*/
class SQLAnywhereSchemaManager extends AbstractSchemaManager
{
/**
* {@inheritdoc}
*
* Starts a database after creation
* as SQL Anywhere needs a database to be started
* before it can be used.
*
* @see startDatabase
*/
public function createDatabase($database)
{
parent::createDatabase($database);
$this->startDatabase($database);
}
/**
* {@inheritdoc}
*
* Tries stopping a database before dropping
* as SQL Anywhere needs a database to be stopped
* before it can be dropped.
*
* @see stopDatabase
*/
public function dropDatabase($database)
{
$this->tryMethod('stopDatabase', $database);
parent::dropDatabase($database);
}
/**
* Starts a database.
*
* @param string $database The name of the database to start.
*
* @return void
*/
public function startDatabase($database)
{
assert($this->_platform instanceof SQLAnywherePlatform);
$this->_execSql($this->_platform->getStartDatabaseSQL($database));
}
/**
* Stops a database.
*
* @param string $database The name of the database to stop.
*
* @return void
*/
public function stopDatabase($database)
{
assert($this->_platform instanceof SQLAnywherePlatform);
$this->_execSql($this->_platform->getStopDatabaseSQL($database));
}
/**
* {@inheritdoc}
*/
protected function _getPortableDatabaseDefinition($database)
{
return $database['name'];
}
/**
* {@inheritdoc}
*/
protected function _getPortableSequenceDefinition($sequence)
{
return new Sequence($sequence['sequence_name'], $sequence['increment_by'], $sequence['start_with']);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableColumnDefinition($tableColumn)
{
$type = $this->_platform->getDoctrineTypeMapping($tableColumn['type']);
$type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
$tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
$precision = null;
$scale = null;
$fixed = false;
$default = null;
if ($tableColumn['default'] !== null) {
// Strip quotes from default value.
$default = preg_replace(["/^'(.*)'$/", "/''/"], ['$1', "'"], $tableColumn['default']);
if ($default === 'autoincrement') {
$default = null;
}
}
switch ($tableColumn['type']) {
case 'binary':
case 'char':
case 'nchar':
$fixed = true;
break;
}
switch ($type) {
case 'decimal':
case 'float':
$precision = $tableColumn['length'];
$scale = $tableColumn['scale'];
break;
}
return new Column(
$tableColumn['column_name'],
Type::getType($type),
[
'length' => $type === 'string' ? $tableColumn['length'] : null,
'precision' => $precision,
'scale' => $scale,
'unsigned' => (bool) $tableColumn['unsigned'],
'fixed' => $fixed,
'notnull' => (bool) $tableColumn['notnull'],
'default' => $default,
'autoincrement' => (bool) $tableColumn['autoincrement'],
'comment' => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
? $tableColumn['comment']
: null,
]
);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableDefinition($table)
{
return $table['table_name'];
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
{
return new ForeignKeyConstraint(
$tableForeignKey['local_columns'],
$tableForeignKey['foreign_table'],
$tableForeignKey['foreign_columns'],
$tableForeignKey['name'],
$tableForeignKey['options']
);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableForeignKeysList($tableForeignKeys)
{
$foreignKeys = [];
foreach ($tableForeignKeys as $tableForeignKey) {
if (! isset($foreignKeys[$tableForeignKey['index_name']])) {
$foreignKeys[$tableForeignKey['index_name']] = [
'local_columns' => [$tableForeignKey['local_column']],
'foreign_table' => $tableForeignKey['foreign_table'],
'foreign_columns' => [$tableForeignKey['foreign_column']],
'name' => $tableForeignKey['index_name'],
'options' => [
'notnull' => $tableForeignKey['notnull'],
'match' => $tableForeignKey['match'],
'onUpdate' => $tableForeignKey['on_update'],
'onDelete' => $tableForeignKey['on_delete'],
'check_on_commit' => $tableForeignKey['check_on_commit'],
'clustered' => $tableForeignKey['clustered'],
'for_olap_workload' => $tableForeignKey['for_olap_workload'],
],
];
} else {
$foreignKeys[$tableForeignKey['index_name']]['local_columns'][] = $tableForeignKey['local_column'];
$foreignKeys[$tableForeignKey['index_name']]['foreign_columns'][] = $tableForeignKey['foreign_column'];
}
}
return parent::_getPortableTableForeignKeysList($foreignKeys);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
{
foreach ($tableIndexes as &$tableIndex) {
$tableIndex['primary'] = (bool) $tableIndex['primary'];
$tableIndex['flags'] = [];
if ($tableIndex['clustered']) {
$tableIndex['flags'][] = 'clustered';
}
if ($tableIndex['with_nulls_not_distinct']) {
$tableIndex['flags'][] = 'with_nulls_not_distinct';
}
if (! $tableIndex['for_olap_workload']) {
continue;
}
$tableIndex['flags'][] = 'for_olap_workload';
}
return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
}
/**
* {@inheritdoc}
*/
protected function _getPortableViewDefinition($view)
{
$definition = preg_replace('/^.*\s+as\s+SELECT(.*)/i', 'SELECT$1', $view['view_def']);
return new View($view['table_name'], $definition);
}
}

View File

@@ -0,0 +1,347 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\Exception;
use Doctrine\DBAL\Platforms\SQLServerPlatform;
use Doctrine\DBAL\Types\Type;
use Throwable;
use function assert;
use function count;
use function in_array;
use function is_string;
use function preg_match;
use function sprintf;
use function str_replace;
use function strpos;
use function strtok;
/**
* SQL Server Schema Manager.
*/
class SQLServerSchemaManager extends AbstractSchemaManager
{
/**
* {@inheritdoc}
*/
public function dropDatabase($database)
{
try {
parent::dropDatabase($database);
} catch (DBALException $exception) {
$exception = $exception->getPrevious();
assert($exception instanceof Throwable);
if (! $exception instanceof Exception) {
throw $exception;
}
// If we have a error code 3702, the drop database operation failed
// because of active connections on the database.
// To force dropping the database, we first have to close all active connections
// on that database and issue the drop database operation again.
if ($exception->getErrorCode() !== 3702) {
throw $exception;
}
$this->closeActiveDatabaseConnections($database);
parent::dropDatabase($database);
}
}
/**
* {@inheritdoc}
*/
protected function _getPortableSequenceDefinition($sequence)
{
return new Sequence($sequence['name'], (int) $sequence['increment'], (int) $sequence['start_value']);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableColumnDefinition($tableColumn)
{
$dbType = strtok($tableColumn['type'], '(), ');
assert(is_string($dbType));
$fixed = null;
$length = (int) $tableColumn['length'];
$default = $tableColumn['default'];
if (! isset($tableColumn['name'])) {
$tableColumn['name'] = '';
}
if ($default !== null) {
$default = $this->parseDefaultExpression($default);
}
switch ($dbType) {
case 'nchar':
case 'nvarchar':
case 'ntext':
// Unicode data requires 2 bytes per character
$length /= 2;
break;
case 'varchar':
// TEXT type is returned as VARCHAR(MAX) with a length of -1
if ($length === -1) {
$dbType = 'text';
}
break;
}
if ($dbType === 'char' || $dbType === 'nchar' || $dbType === 'binary') {
$fixed = true;
}
$type = $this->_platform->getDoctrineTypeMapping($dbType);
$type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
$tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
$options = [
'length' => $length === 0 || ! in_array($type, ['text', 'string']) ? null : $length,
'unsigned' => false,
'fixed' => (bool) $fixed,
'default' => $default,
'notnull' => (bool) $tableColumn['notnull'],
'scale' => $tableColumn['scale'],
'precision' => $tableColumn['precision'],
'autoincrement' => (bool) $tableColumn['autoincrement'],
'comment' => $tableColumn['comment'] !== '' ? $tableColumn['comment'] : null,
];
$column = new Column($tableColumn['name'], Type::getType($type), $options);
if (isset($tableColumn['collation']) && $tableColumn['collation'] !== 'NULL') {
$column->setPlatformOption('collation', $tableColumn['collation']);
}
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}
*/
protected function _getPortableTableForeignKeysList($tableForeignKeys)
{
$foreignKeys = [];
foreach ($tableForeignKeys as $tableForeignKey) {
$name = $tableForeignKey['ForeignKey'];
if (! isset($foreignKeys[$name])) {
$foreignKeys[$name] = [
'local_columns' => [$tableForeignKey['ColumnName']],
'foreign_table' => $tableForeignKey['ReferenceTableName'],
'foreign_columns' => [$tableForeignKey['ReferenceColumnName']],
'name' => $name,
'options' => [
'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc']),
],
];
} else {
$foreignKeys[$name]['local_columns'][] = $tableForeignKey['ColumnName'];
$foreignKeys[$name]['foreign_columns'][] = $tableForeignKey['ReferenceColumnName'];
}
}
return parent::_getPortableTableForeignKeysList($foreignKeys);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
{
foreach ($tableIndexes as &$tableIndex) {
$tableIndex['non_unique'] = (bool) $tableIndex['non_unique'];
$tableIndex['primary'] = (bool) $tableIndex['primary'];
$tableIndex['flags'] = $tableIndex['flags'] ? [$tableIndex['flags']] : null;
}
return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
{
return new ForeignKeyConstraint(
$tableForeignKey['local_columns'],
$tableForeignKey['foreign_table'],
$tableForeignKey['foreign_columns'],
$tableForeignKey['name'],
$tableForeignKey['options']
);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableDefinition($table)
{
if (isset($table['schema_name']) && $table['schema_name'] !== 'dbo') {
return $table['schema_name'] . '.' . $table['name'];
}
return $table['name'];
}
/**
* {@inheritdoc}
*/
protected function _getPortableDatabaseDefinition($database)
{
return $database['name'];
}
/**
* {@inheritdoc}
*/
protected function getPortableNamespaceDefinition(array $namespace)
{
return $namespace['name'];
}
/**
* {@inheritdoc}
*/
protected function _getPortableViewDefinition($view)
{
// @todo
return new View($view['name'], '');
}
/**
* {@inheritdoc}
*/
public function listTableIndexes($table)
{
$sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
try {
$tableIndexes = $this->_conn->fetchAllAssociative($sql);
} catch (DBALException $e) {
if (strpos($e->getMessage(), 'SQLSTATE [01000, 15472]') === 0) {
return [];
}
throw $e;
}
return $this->_getPortableTableIndexesList($tableIndexes, $table);
}
/**
* {@inheritdoc}
*/
public function alterTable(TableDiff $tableDiff)
{
if (count($tableDiff->removedColumns) > 0) {
foreach ($tableDiff->removedColumns as $col) {
$columnConstraintSql = $this->getColumnConstraintSQL($tableDiff->name, $col->getName());
foreach ($this->_conn->fetchAllAssociative($columnConstraintSql) as $constraint) {
$this->_conn->exec(
sprintf(
'ALTER TABLE %s DROP CONSTRAINT %s',
$tableDiff->name,
$constraint['Name']
)
);
}
}
}
parent::alterTable($tableDiff);
}
/**
* Returns the SQL to retrieve the constraints for a given column.
*
* @param string $table
* @param string $column
*
* @return string
*/
private function getColumnConstraintSQL($table, $column)
{
return "SELECT sysobjects.[Name]
FROM sysobjects INNER JOIN (SELECT [Name],[ID] FROM sysobjects WHERE XType = 'U') AS Tab
ON Tab.[ID] = sysobjects.[Parent_Obj]
INNER JOIN sys.default_constraints DefCons ON DefCons.[object_id] = sysobjects.[ID]
INNER JOIN syscolumns Col ON Col.[ColID] = DefCons.[parent_column_id] AND Col.[ID] = Tab.[ID]
WHERE Col.[Name] = " . $this->_conn->quote($column) . ' AND Tab.[Name] = ' . $this->_conn->quote($table) . '
ORDER BY Col.[Name]';
}
/**
* Closes currently active connections on the given database.
*
* This is useful to force DROP DATABASE operations which could fail because of active connections.
*
* @param string $database The name of the database to close currently active connections for.
*
* @return void
*/
private function closeActiveDatabaseConnections($database)
{
$database = new Identifier($database);
$this->_execSql(
sprintf(
'ALTER DATABASE %s SET SINGLE_USER WITH ROLLBACK IMMEDIATE',
$database->getQuotedName($this->_platform)
)
);
}
/**
* @param string $name
*/
public function listTableDetails($name): Table
{
$table = parent::listTableDetails($name);
$platform = $this->_platform;
assert($platform instanceof SQLServerPlatform);
$sql = $platform->getListTableMetadataSQL($name);
$tableOptions = $this->_conn->fetchAssociative($sql);
if ($tableOptions !== false) {
$table->addOption('comment', $tableOptions['table_comment']);
}
return $table;
}
}

View File

@@ -0,0 +1,482 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\Visitor\CreateSchemaSqlCollector;
use Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector;
use Doctrine\DBAL\Schema\Visitor\NamespaceVisitor;
use Doctrine\DBAL\Schema\Visitor\Visitor;
use function array_keys;
use function strpos;
use function strtolower;
/**
* Object representation of a database schema.
*
* Different vendors have very inconsistent naming with regard to the concept
* of a "schema". Doctrine understands a schema as the entity that conceptually
* wraps a set of database objects such as tables, sequences, indexes and
* foreign keys that belong to each other into a namespace. A Doctrine Schema
* has nothing to do with the "SCHEMA" defined as in PostgreSQL, it is more
* related to the concept of "DATABASE" that exists in MySQL and PostgreSQL.
*
* Every asset in the doctrine schema has a name. A name consists of either a
* namespace.local name pair or just a local unqualified name.
*
* The abstraction layer that covers a PostgreSQL schema is the namespace of an
* database object (asset). A schema can have a name, which will be used as
* default namespace for the unqualified database objects that are created in
* the schema.
*
* In the case of MySQL where cross-database queries are allowed this leads to
* databases being "misinterpreted" as namespaces. This is intentional, however
* the CREATE/DROP SQL visitors will just filter this queries and do not
* execute them. Only the queries for the currently connected database are
* executed.
*/
class Schema extends AbstractAsset
{
/**
* The namespaces in this schema.
*
* @var string[]
*/
private $namespaces = [];
/** @var Table[] */
protected $_tables = [];
/** @var Sequence[] */
protected $_sequences = [];
/** @var SchemaConfig */
protected $_schemaConfig;
/**
* @param Table[] $tables
* @param Sequence[] $sequences
* @param string[] $namespaces
*/
public function __construct(
array $tables = [],
array $sequences = [],
?SchemaConfig $schemaConfig = null,
array $namespaces = []
) {
if ($schemaConfig === null) {
$schemaConfig = new SchemaConfig();
}
$this->_schemaConfig = $schemaConfig;
$this->_setName($schemaConfig->getName() ?: 'public');
foreach ($namespaces as $namespace) {
$this->createNamespace($namespace);
}
foreach ($tables as $table) {
$this->_addTable($table);
}
foreach ($sequences as $sequence) {
$this->_addSequence($sequence);
}
}
/**
* @return bool
*/
public function hasExplicitForeignKeyIndexes()
{
return $this->_schemaConfig->hasExplicitForeignKeyIndexes();
}
/**
* @return void
*
* @throws SchemaException
*/
protected function _addTable(Table $table)
{
$namespaceName = $table->getNamespaceName();
$tableName = $table->getFullQualifiedName($this->getName());
if (isset($this->_tables[$tableName])) {
throw SchemaException::tableAlreadyExists($tableName);
}
if (
$namespaceName !== null
&& ! $table->isInDefaultNamespace($this->getName())
&& ! $this->hasNamespace($namespaceName)
) {
$this->createNamespace($namespaceName);
}
$this->_tables[$tableName] = $table;
$table->setSchemaConfig($this->_schemaConfig);
}
/**
* @return void
*
* @throws SchemaException
*/
protected function _addSequence(Sequence $sequence)
{
$namespaceName = $sequence->getNamespaceName();
$seqName = $sequence->getFullQualifiedName($this->getName());
if (isset($this->_sequences[$seqName])) {
throw SchemaException::sequenceAlreadyExists($seqName);
}
if (
$namespaceName !== null
&& ! $sequence->isInDefaultNamespace($this->getName())
&& ! $this->hasNamespace($namespaceName)
) {
$this->createNamespace($namespaceName);
}
$this->_sequences[$seqName] = $sequence;
}
/**
* Returns the namespaces of this schema.
*
* @return string[] A list of namespace names.
*/
public function getNamespaces()
{
return $this->namespaces;
}
/**
* Gets all tables of this schema.
*
* @return Table[]
*/
public function getTables()
{
return $this->_tables;
}
/**
* @param string $name
*
* @return Table
*
* @throws SchemaException
*/
public function getTable($name)
{
$name = $this->getFullQualifiedAssetName($name);
if (! isset($this->_tables[$name])) {
throw SchemaException::tableDoesNotExist($name);
}
return $this->_tables[$name];
}
/**
* @param string $name
*
* @return string
*/
private function getFullQualifiedAssetName($name)
{
$name = $this->getUnquotedAssetName($name);
if (strpos($name, '.') === false) {
$name = $this->getName() . '.' . $name;
}
return strtolower($name);
}
/**
* Returns the unquoted representation of a given asset name.
*
* @param string $assetName Quoted or unquoted representation of an asset name.
*
* @return string
*/
private function getUnquotedAssetName($assetName)
{
if ($this->isIdentifierQuoted($assetName)) {
return $this->trimQuotes($assetName);
}
return $assetName;
}
/**
* Does this schema have a namespace with the given name?
*
* @param string $name
*
* @return bool
*/
public function hasNamespace($name)
{
$name = strtolower($this->getUnquotedAssetName($name));
return isset($this->namespaces[$name]);
}
/**
* Does this schema have a table with the given name?
*
* @param string $name
*
* @return bool
*/
public function hasTable($name)
{
$name = $this->getFullQualifiedAssetName($name);
return isset($this->_tables[$name]);
}
/**
* Gets all table names, prefixed with a schema name, even the default one if present.
*
* @return string[]
*/
public function getTableNames()
{
return array_keys($this->_tables);
}
/**
* @param string $name
*
* @return bool
*/
public function hasSequence($name)
{
$name = $this->getFullQualifiedAssetName($name);
return isset($this->_sequences[$name]);
}
/**
* @param string $name
*
* @return Sequence
*
* @throws SchemaException
*/
public function getSequence($name)
{
$name = $this->getFullQualifiedAssetName($name);
if (! $this->hasSequence($name)) {
throw SchemaException::sequenceDoesNotExist($name);
}
return $this->_sequences[$name];
}
/**
* @return Sequence[]
*/
public function getSequences()
{
return $this->_sequences;
}
/**
* Creates a new namespace.
*
* @param string $name The name of the namespace to create.
*
* @return Schema This schema instance.
*
* @throws SchemaException
*/
public function createNamespace($name)
{
$unquotedName = strtolower($this->getUnquotedAssetName($name));
if (isset($this->namespaces[$unquotedName])) {
throw SchemaException::namespaceAlreadyExists($unquotedName);
}
$this->namespaces[$unquotedName] = $name;
return $this;
}
/**
* Creates a new table.
*
* @param string $name
*
* @return Table
*/
public function createTable($name)
{
$table = new Table($name);
$this->_addTable($table);
foreach ($this->_schemaConfig->getDefaultTableOptions() as $option => $value) {
$table->addOption($option, $value);
}
return $table;
}
/**
* Renames a table.
*
* @param string $oldName
* @param string $newName
*
* @return Schema
*/
public function renameTable($oldName, $newName)
{
$table = $this->getTable($oldName);
$table->_setName($newName);
$this->dropTable($oldName);
$this->_addTable($table);
return $this;
}
/**
* Drops a table from the schema.
*
* @param string $name
*
* @return Schema
*/
public function dropTable($name)
{
$name = $this->getFullQualifiedAssetName($name);
$this->getTable($name);
unset($this->_tables[$name]);
return $this;
}
/**
* Creates a new sequence.
*
* @param string $name
* @param int $allocationSize
* @param int $initialValue
*
* @return Sequence
*/
public function createSequence($name, $allocationSize = 1, $initialValue = 1)
{
$seq = new Sequence($name, $allocationSize, $initialValue);
$this->_addSequence($seq);
return $seq;
}
/**
* @param string $name
*
* @return Schema
*/
public function dropSequence($name)
{
$name = $this->getFullQualifiedAssetName($name);
unset($this->_sequences[$name]);
return $this;
}
/**
* Returns an array of necessary SQL queries to create the schema on the given platform.
*
* @return string[]
*/
public function toSql(AbstractPlatform $platform)
{
$sqlCollector = new CreateSchemaSqlCollector($platform);
$this->visit($sqlCollector);
return $sqlCollector->getQueries();
}
/**
* Return an array of necessary SQL queries to drop the schema on the given platform.
*
* @return string[]
*/
public function toDropSql(AbstractPlatform $platform)
{
$dropSqlCollector = new DropSchemaSqlCollector($platform);
$this->visit($dropSqlCollector);
return $dropSqlCollector->getQueries();
}
/**
* @return string[]
*/
public function getMigrateToSql(Schema $toSchema, AbstractPlatform $platform)
{
$comparator = new Comparator();
$schemaDiff = $comparator->compare($this, $toSchema);
return $schemaDiff->toSql($platform);
}
/**
* @return string[]
*/
public function getMigrateFromSql(Schema $fromSchema, AbstractPlatform $platform)
{
$comparator = new Comparator();
$schemaDiff = $comparator->compare($fromSchema, $this);
return $schemaDiff->toSql($platform);
}
/**
* @return void
*/
public function visit(Visitor $visitor)
{
$visitor->acceptSchema($this);
if ($visitor instanceof NamespaceVisitor) {
foreach ($this->namespaces as $namespace) {
$visitor->acceptNamespace($namespace);
}
}
foreach ($this->_tables as $table) {
$table->visit($visitor);
}
foreach ($this->_sequences as $sequence) {
$sequence->visit($visitor);
}
}
/**
* Cloning a Schema triggers a deep clone of all related assets.
*
* @return void
*/
public function __clone()
{
foreach ($this->_tables as $k => $table) {
$this->_tables[$k] = clone $table;
}
foreach ($this->_sequences as $k => $sequence) {
$this->_sequences[$k] = clone $sequence;
}
}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace Doctrine\DBAL\Schema;
/**
* Configuration for a Schema.
*/
class SchemaConfig
{
/** @var bool */
protected $hasExplicitForeignKeyIndexes = false;
/** @var int */
protected $maxIdentifierLength = 63;
/** @var string */
protected $name;
/** @var mixed[] */
protected $defaultTableOptions = [];
/**
* @return bool
*/
public function hasExplicitForeignKeyIndexes()
{
return $this->hasExplicitForeignKeyIndexes;
}
/**
* @param bool $flag
*
* @return void
*/
public function setExplicitForeignKeyIndexes($flag)
{
$this->hasExplicitForeignKeyIndexes = (bool) $flag;
}
/**
* @param int $length
*
* @return void
*/
public function setMaxIdentifierLength($length)
{
$this->maxIdentifierLength = (int) $length;
}
/**
* @return int
*/
public function getMaxIdentifierLength()
{
return $this->maxIdentifierLength;
}
/**
* Gets the default namespace of schema objects.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Sets the default namespace name of schema objects.
*
* @param string $name The value to set.
*
* @return void
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Gets the default options that are passed to Table instances created with
* Schema#createTable().
*
* @return mixed[]
*/
public function getDefaultTableOptions()
{
return $this->defaultTableOptions;
}
/**
* @param mixed[] $defaultTableOptions
*
* @return void
*/
public function setDefaultTableOptions(array $defaultTableOptions)
{
$this->defaultTableOptions = $defaultTableOptions;
}
}

View File

@@ -0,0 +1,170 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use function array_merge;
/**
* Schema Diff.
*/
class SchemaDiff
{
/** @var Schema|null */
public $fromSchema;
/**
* All added namespaces.
*
* @var string[]
*/
public $newNamespaces = [];
/**
* All removed namespaces.
*
* @var string[]
*/
public $removedNamespaces = [];
/**
* All added tables.
*
* @var Table[]
*/
public $newTables = [];
/**
* All changed tables.
*
* @var TableDiff[]
*/
public $changedTables = [];
/**
* All removed tables.
*
* @var Table[]
*/
public $removedTables = [];
/** @var Sequence[] */
public $newSequences = [];
/** @var Sequence[] */
public $changedSequences = [];
/** @var Sequence[] */
public $removedSequences = [];
/** @var ForeignKeyConstraint[] */
public $orphanedForeignKeys = [];
/**
* Constructs an SchemaDiff object.
*
* @param Table[] $newTables
* @param TableDiff[] $changedTables
* @param Table[] $removedTables
*/
public function __construct($newTables = [], $changedTables = [], $removedTables = [], ?Schema $fromSchema = null)
{
$this->newTables = $newTables;
$this->changedTables = $changedTables;
$this->removedTables = $removedTables;
$this->fromSchema = $fromSchema;
}
/**
* The to save sql mode ensures that the following things don't happen:
*
* 1. Tables are deleted
* 2. Sequences are deleted
* 3. Foreign Keys which reference tables that would otherwise be deleted.
*
* This way it is ensured that assets are deleted which might not be relevant to the metadata schema at all.
*
* @return string[]
*/
public function toSaveSql(AbstractPlatform $platform)
{
return $this->_toSql($platform, true);
}
/**
* @return string[]
*/
public function toSql(AbstractPlatform $platform)
{
return $this->_toSql($platform, false);
}
/**
* @param bool $saveMode
*
* @return string[]
*/
protected function _toSql(AbstractPlatform $platform, $saveMode = false)
{
$sql = [];
if ($platform->supportsSchemas()) {
foreach ($this->newNamespaces as $newNamespace) {
$sql[] = $platform->getCreateSchemaSQL($newNamespace);
}
}
if ($platform->supportsForeignKeyConstraints() && $saveMode === false) {
foreach ($this->orphanedForeignKeys as $orphanedForeignKey) {
$sql[] = $platform->getDropForeignKeySQL($orphanedForeignKey, $orphanedForeignKey->getLocalTable());
}
}
if ($platform->supportsSequences() === true) {
foreach ($this->changedSequences as $sequence) {
$sql[] = $platform->getAlterSequenceSQL($sequence);
}
if ($saveMode === false) {
foreach ($this->removedSequences as $sequence) {
$sql[] = $platform->getDropSequenceSQL($sequence);
}
}
foreach ($this->newSequences as $sequence) {
$sql[] = $platform->getCreateSequenceSQL($sequence);
}
}
$foreignKeySql = [];
foreach ($this->newTables as $table) {
$sql = array_merge(
$sql,
$platform->getCreateTableSQL($table, AbstractPlatform::CREATE_INDEXES)
);
if (! $platform->supportsForeignKeyConstraints()) {
continue;
}
foreach ($table->getForeignKeys() as $foreignKey) {
$foreignKeySql[] = $platform->getCreateForeignKeySQL($foreignKey, $table);
}
}
$sql = array_merge($sql, $foreignKeySql);
if ($saveMode === false) {
foreach ($this->removedTables as $table) {
$sql[] = $platform->getDropTableSQL($table);
}
}
foreach ($this->changedTables as $tableDiff) {
$sql = array_merge($sql, $platform->getAlterTableSQL($tableDiff));
}
return $sql;
}
}

View File

@@ -0,0 +1,187 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Exception;
use function implode;
use function sprintf;
/**
* @psalm-immutable
*/
class SchemaException extends Exception
{
public const TABLE_DOESNT_EXIST = 10;
public const TABLE_ALREADY_EXISTS = 20;
public const COLUMN_DOESNT_EXIST = 30;
public const COLUMN_ALREADY_EXISTS = 40;
public const INDEX_DOESNT_EXIST = 50;
public const INDEX_ALREADY_EXISTS = 60;
public const SEQUENCE_DOENST_EXIST = 70;
public const SEQUENCE_ALREADY_EXISTS = 80;
public const INDEX_INVALID_NAME = 90;
public const FOREIGNKEY_DOESNT_EXIST = 100;
public const NAMESPACE_ALREADY_EXISTS = 110;
/**
* @param string $tableName
*
* @return SchemaException
*/
public static function tableDoesNotExist($tableName)
{
return new self("There is no table with name '" . $tableName . "' in the schema.", self::TABLE_DOESNT_EXIST);
}
/**
* @param string $indexName
*
* @return SchemaException
*/
public static function indexNameInvalid($indexName)
{
return new self(
sprintf('Invalid index-name %s given, has to be [a-zA-Z0-9_]', $indexName),
self::INDEX_INVALID_NAME
);
}
/**
* @param string $indexName
* @param string $table
*
* @return SchemaException
*/
public static function indexDoesNotExist($indexName, $table)
{
return new self(
sprintf("Index '%s' does not exist on table '%s'.", $indexName, $table),
self::INDEX_DOESNT_EXIST
);
}
/**
* @param string $indexName
* @param string $table
*
* @return SchemaException
*/
public static function indexAlreadyExists($indexName, $table)
{
return new self(
sprintf("An index with name '%s' was already defined on table '%s'.", $indexName, $table),
self::INDEX_ALREADY_EXISTS
);
}
/**
* @param string $columnName
* @param string $table
*
* @return SchemaException
*/
public static function columnDoesNotExist($columnName, $table)
{
return new self(
sprintf("There is no column with name '%s' on table '%s'.", $columnName, $table),
self::COLUMN_DOESNT_EXIST
);
}
/**
* @param string $namespaceName
*
* @return SchemaException
*/
public static function namespaceAlreadyExists($namespaceName)
{
return new self(
sprintf("The namespace with name '%s' already exists.", $namespaceName),
self::NAMESPACE_ALREADY_EXISTS
);
}
/**
* @param string $tableName
*
* @return SchemaException
*/
public static function tableAlreadyExists($tableName)
{
return new self("The table with name '" . $tableName . "' already exists.", self::TABLE_ALREADY_EXISTS);
}
/**
* @param string $tableName
* @param string $columnName
*
* @return SchemaException
*/
public static function columnAlreadyExists($tableName, $columnName)
{
return new self(
"The column '" . $columnName . "' on table '" . $tableName . "' already exists.",
self::COLUMN_ALREADY_EXISTS
);
}
/**
* @param string $name
*
* @return SchemaException
*/
public static function sequenceAlreadyExists($name)
{
return new self("The sequence '" . $name . "' already exists.", self::SEQUENCE_ALREADY_EXISTS);
}
/**
* @param string $name
*
* @return SchemaException
*/
public static function sequenceDoesNotExist($name)
{
return new self("There exists no sequence with the name '" . $name . "'.", self::SEQUENCE_DOENST_EXIST);
}
/**
* @param string $fkName
* @param string $table
*
* @return SchemaException
*/
public static function foreignKeyDoesNotExist($fkName, $table)
{
return new self(
sprintf("There exists no foreign key with the name '%s' on table '%s'.", $fkName, $table),
self::FOREIGNKEY_DOESNT_EXIST
);
}
/**
* @return SchemaException
*/
public static function namedForeignKeyRequired(Table $localTable, ForeignKeyConstraint $foreignKey)
{
return new self(
'The performed schema operation on ' . $localTable->getName() . ' requires a named foreign key, ' .
'but the given foreign key from (' . implode(', ', $foreignKey->getColumns()) . ') onto foreign table ' .
"'" . $foreignKey->getForeignTableName() . "' (" . implode(', ', $foreignKey->getForeignColumns()) . ')' .
' is currently unnamed.'
);
}
/**
* @param string $changeName
*
* @return SchemaException
*/
public static function alterTableChangeNotSupported($changeName)
{
return new self(
sprintf("Alter table change not supported, given '%s'", $changeName)
);
}
}

View File

@@ -0,0 +1,140 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Schema\Visitor\Visitor;
use function count;
use function sprintf;
/**
* Sequence structure.
*/
class Sequence extends AbstractAsset
{
/** @var int */
protected $allocationSize = 1;
/** @var int */
protected $initialValue = 1;
/** @var int|null */
protected $cache;
/**
* @param string $name
* @param int $allocationSize
* @param int $initialValue
* @param int|null $cache
*/
public function __construct($name, $allocationSize = 1, $initialValue = 1, $cache = null)
{
$this->_setName($name);
$this->setAllocationSize($allocationSize);
$this->setInitialValue($initialValue);
$this->cache = $cache;
}
/**
* @return int
*/
public function getAllocationSize()
{
return $this->allocationSize;
}
/**
* @return int
*/
public function getInitialValue()
{
return $this->initialValue;
}
/**
* @return int|null
*/
public function getCache()
{
return $this->cache;
}
/**
* @param int $allocationSize
*
* @return Sequence
*/
public function setAllocationSize($allocationSize)
{
$this->allocationSize = (int) $allocationSize ?: 1;
return $this;
}
/**
* @param int $initialValue
*
* @return Sequence
*/
public function setInitialValue($initialValue)
{
$this->initialValue = (int) $initialValue ?: 1;
return $this;
}
/**
* @param int $cache
*
* @return Sequence
*/
public function setCache($cache)
{
$this->cache = $cache;
return $this;
}
/**
* Checks if this sequence is an autoincrement sequence for a given table.
*
* This is used inside the comparator to not report sequences as missing,
* when the "from" schema implicitly creates the sequences.
*
* @return bool
*/
public function isAutoIncrementsFor(Table $table)
{
$primaryKey = $table->getPrimaryKey();
if ($primaryKey === null) {
return false;
}
$pkColumns = $primaryKey->getColumns();
if (count($pkColumns) !== 1) {
return false;
}
$column = $table->getColumn($pkColumns[0]);
if (! $column->getAutoincrement()) {
return false;
}
$sequenceName = $this->getShortestName($table->getNamespaceName());
$tableName = $table->getShortestName($table->getNamespaceName());
$tableSequenceName = sprintf('%s_%s_seq', $tableName, $column->getShortestName($table->getNamespaceName()));
return $tableSequenceName === $sequenceName;
}
/**
* @return void
*/
public function visit(Visitor $visitor)
{
$visitor->acceptSequence($this);
}
}

View File

@@ -0,0 +1,574 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Types\StringType;
use Doctrine\DBAL\Types\TextType;
use Doctrine\DBAL\Types\Type;
use function array_change_key_case;
use function array_map;
use function array_merge;
use function array_reverse;
use function explode;
use function file_exists;
use function preg_match;
use function preg_match_all;
use function preg_quote;
use function preg_replace;
use function rtrim;
use function sprintf;
use function str_replace;
use function strpos;
use function strtolower;
use function trim;
use function unlink;
use function usort;
use const CASE_LOWER;
/**
* Sqlite SchemaManager.
*/
class SqliteSchemaManager extends AbstractSchemaManager
{
/**
* {@inheritdoc}
*/
public function dropDatabase($database)
{
if (! file_exists($database)) {
return;
}
unlink($database);
}
/**
* {@inheritdoc}
*/
public function createDatabase($database)
{
$params = $this->_conn->getParams();
$params['path'] = $database;
unset($params['memory']);
$conn = DriverManager::getConnection($params);
$conn->connect();
$conn->close();
}
/**
* {@inheritdoc}
*/
public function renameTable($name, $newName)
{
$tableDiff = new TableDiff($name);
$tableDiff->fromTable = $this->listTableDetails($name);
$tableDiff->newName = $newName;
$this->alterTable($tableDiff);
}
/**
* {@inheritdoc}
*/
public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
{
$tableDiff = $this->getTableDiffForAlterForeignKey($table);
$tableDiff->addedForeignKeys[] = $foreignKey;
$this->alterTable($tableDiff);
}
/**
* {@inheritdoc}
*/
public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table)
{
$tableDiff = $this->getTableDiffForAlterForeignKey($table);
$tableDiff->changedForeignKeys[] = $foreignKey;
$this->alterTable($tableDiff);
}
/**
* {@inheritdoc}
*/
public function dropForeignKey($foreignKey, $table)
{
$tableDiff = $this->getTableDiffForAlterForeignKey($table);
$tableDiff->removedForeignKeys[] = $foreignKey;
$this->alterTable($tableDiff);
}
/**
* {@inheritdoc}
*/
public function listTableForeignKeys($table, $database = null)
{
if ($database === null) {
$database = $this->_conn->getDatabase();
}
$sql = $this->_platform->getListTableForeignKeysSQL($table, $database);
$tableForeignKeys = $this->_conn->fetchAllAssociative($sql);
if (! empty($tableForeignKeys)) {
$createSql = $this->getCreateTableSQL($table);
if (
$createSql !== null && preg_match_all(
'#
(?:CONSTRAINT\s+([^\s]+)\s+)?
(?:FOREIGN\s+KEY[^\)]+\)\s*)?
REFERENCES\s+[^\s]+\s+(?:\([^\)]+\))?
(?:
[^,]*?
(NOT\s+DEFERRABLE|DEFERRABLE)
(?:\s+INITIALLY\s+(DEFERRED|IMMEDIATE))?
)?#isx',
$createSql,
$match
)
) {
$names = array_reverse($match[1]);
$deferrable = array_reverse($match[2]);
$deferred = array_reverse($match[3]);
} else {
$names = $deferrable = $deferred = [];
}
foreach ($tableForeignKeys as $key => $value) {
$id = $value['id'];
$tableForeignKeys[$key] = array_merge($tableForeignKeys[$key], [
'constraint_name' => isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id,
'deferrable' => isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable',
'deferred' => isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred',
]);
}
}
return $this->_getPortableTableForeignKeysList($tableForeignKeys);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableDefinition($table)
{
return $table['name'];
}
/**
* {@inheritdoc}
*
* @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
*/
protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
{
$indexBuffer = [];
// fetch primary
$indexArray = $this->_conn->fetchAllAssociative(sprintf(
'PRAGMA TABLE_INFO (%s)',
$this->_conn->quote($tableName)
));
usort(
$indexArray,
/**
* @param array<string,mixed> $a
* @param array<string,mixed> $b
*/
static function (array $a, array $b): int {
if ($a['pk'] === $b['pk']) {
return $a['cid'] - $b['cid'];
}
return $a['pk'] - $b['pk'];
}
);
foreach ($indexArray as $indexColumnRow) {
if ($indexColumnRow['pk'] === 0 || $indexColumnRow['pk'] === '0') {
continue;
}
$indexBuffer[] = [
'key_name' => 'primary',
'primary' => true,
'non_unique' => false,
'column_name' => $indexColumnRow['name'],
];
}
// fetch regular indexes
foreach ($tableIndexes as $tableIndex) {
// Ignore indexes with reserved names, e.g. autoindexes
if (strpos($tableIndex['name'], 'sqlite_') === 0) {
continue;
}
$keyName = $tableIndex['name'];
$idx = [];
$idx['key_name'] = $keyName;
$idx['primary'] = false;
$idx['non_unique'] = ! $tableIndex['unique'];
$indexArray = $this->_conn->fetchAllAssociative(sprintf(
'PRAGMA INDEX_INFO (%s)',
$this->_conn->quote($keyName)
));
foreach ($indexArray as $indexColumnRow) {
$idx['column_name'] = $indexColumnRow['name'];
$indexBuffer[] = $idx;
}
}
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}
*/
protected function _getPortableTableColumnList($table, $database, $tableColumns)
{
$list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
// find column with autoincrement
$autoincrementColumn = null;
$autoincrementCount = 0;
foreach ($tableColumns as $tableColumn) {
if ($tableColumn['pk'] === 0 || $tableColumn['pk'] === '0') {
continue;
}
$autoincrementCount++;
if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
continue;
}
$autoincrementColumn = $tableColumn['name'];
}
if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
foreach ($list as $column) {
if ($autoincrementColumn !== $column->getName()) {
continue;
}
$column->setAutoincrement(true);
}
}
// inspect column collation and comments
$createSql = $this->getCreateTableSQL($table) ?? '';
foreach ($list as $columnName => $column) {
$type = $column->getType();
if ($type instanceof StringType || $type instanceof TextType) {
$column->setPlatformOption(
'collation',
$this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY'
);
}
$comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
if ($comment === null) {
continue;
}
$type = $this->extractDoctrineTypeFromComment($comment, '');
if ($type !== '') {
$column->setType(Type::getType($type));
$comment = $this->removeDoctrineTypeFromComment($comment, $type);
}
$column->setComment($comment);
}
return $list;
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableColumnDefinition($tableColumn)
{
$parts = explode('(', $tableColumn['type']);
$tableColumn['type'] = trim($parts[0]);
if (isset($parts[1])) {
$length = trim($parts[1], ')');
$tableColumn['length'] = $length;
}
$dbType = strtolower($tableColumn['type']);
$length = $tableColumn['length'] ?? null;
$unsigned = false;
if (strpos($dbType, ' unsigned') !== false) {
$dbType = str_replace(' unsigned', '', $dbType);
$unsigned = true;
}
$fixed = false;
$type = $this->_platform->getDoctrineTypeMapping($dbType);
$default = $tableColumn['dflt_value'];
if ($default === 'NULL') {
$default = null;
}
if ($default !== null) {
// 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'])) {
$tableColumn['name'] = '';
}
$precision = null;
$scale = null;
switch ($dbType) {
case 'char':
$fixed = true;
break;
case 'float':
case 'double':
case 'real':
case 'decimal':
case 'numeric':
if (isset($tableColumn['length'])) {
if (strpos($tableColumn['length'], ',') === false) {
$tableColumn['length'] .= ',0';
}
[$precision, $scale] = array_map('trim', explode(',', $tableColumn['length']));
}
$length = null;
break;
}
$options = [
'length' => $length,
'unsigned' => $unsigned,
'fixed' => $fixed,
'notnull' => $notnull,
'default' => $default,
'precision' => $precision,
'scale' => $scale,
'autoincrement' => false,
];
return new Column($tableColumn['name'], Type::getType($type), $options);
}
/**
* {@inheritdoc}
*/
protected function _getPortableViewDefinition($view)
{
return new View($view['name'], $view['sql']);
}
/**
* {@inheritdoc}
*/
protected function _getPortableTableForeignKeysList($tableForeignKeys)
{
$list = [];
foreach ($tableForeignKeys as $value) {
$value = array_change_key_case($value, CASE_LOWER);
$name = $value['constraint_name'];
if (! isset($list[$name])) {
if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
$value['on_delete'] = null;
}
if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
$value['on_update'] = null;
}
$list[$name] = [
'name' => $name,
'local' => [],
'foreign' => [],
'foreignTable' => $value['table'],
'onDelete' => $value['on_delete'],
'onUpdate' => $value['on_update'],
'deferrable' => $value['deferrable'],
'deferred' => $value['deferred'],
];
}
$list[$name]['local'][] = $value['from'];
if ($value['to'] === null) {
continue;
}
$list[$name]['foreign'][] = $value['to'];
}
$result = [];
foreach ($list as $constraint) {
$result[] = new ForeignKeyConstraint(
$constraint['local'],
$constraint['foreignTable'],
$constraint['foreign'],
$constraint['name'],
[
'onDelete' => $constraint['onDelete'],
'onUpdate' => $constraint['onUpdate'],
'deferrable' => $constraint['deferrable'],
'deferred' => $constraint['deferred'],
]
);
}
return $result;
}
/**
* @param Table|string $table
*
* @return TableDiff
*
* @throws Exception
*/
private function getTableDiffForAlterForeignKey($table)
{
if (! $table instanceof Table) {
$tableDetails = $this->tryMethod('listTableDetails', $table);
if ($tableDetails === false) {
throw new Exception(
sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table)
);
}
$table = $tableDetails;
}
$tableDiff = new TableDiff($table->getName());
$tableDiff->fromTable = $table;
return $tableDiff;
}
private function parseColumnCollationFromSQL(string $column, string $sql): ?string
{
$pattern = '{(?:\W' . preg_quote($column) . '\W|\W'
. preg_quote($this->_platform->quoteSingleIdentifier($column))
. '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
if (preg_match($pattern, $sql, $match) !== 1) {
return null;
}
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) . '\W)(?:\([^)]*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
if (preg_match($pattern, $sql, $match) !== 1) {
return null;
}
$comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
return $comment === '' ? null : $comment;
}
private function getCreateTableSQL(string $table): ?string
{
return $this->_conn->fetchColumn(
<<<'SQL'
SELECT sql
FROM (
SELECT *
FROM sqlite_master
UNION ALL
SELECT *
FROM sqlite_temp_master
)
WHERE type = 'table'
AND name = ?
SQL
,
[$table]
) ?: null;
}
/**
* @param string $name
*/
public function listTableDetails($name): Table
{
$table = parent::listTableDetails($name);
$tableCreateSql = $this->getCreateTableSQL($name) ?? '';
$comment = $this->parseTableCommentFromSQL($name, $tableCreateSql);
if ($comment !== null) {
$table->addOption('comment', $comment);
}
return $table;
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace Doctrine\DBAL\Schema\Synchronizer;
use Doctrine\DBAL\Connection;
use Doctrine\Deprecations\Deprecation;
use Throwable;
/**
* Abstract schema synchronizer with methods for executing batches of SQL.
*
* @deprecated
*/
abstract class AbstractSchemaSynchronizer implements SchemaSynchronizer
{
/** @var Connection */
protected $conn;
public function __construct(Connection $conn)
{
$this->conn = $conn;
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/pull/4213',
'SchemaSynchronizer API is deprecated without a replacement and will be removed in DBAL 3.0'
);
}
/**
* @param string[] $sql
*
* @return void
*/
protected function processSqlSafely(array $sql)
{
foreach ($sql as $s) {
try {
$this->conn->exec($s);
} catch (Throwable $e) {
}
}
}
/**
* @param string[] $sql
*
* @return void
*/
protected function processSql(array $sql)
{
foreach ($sql as $s) {
$this->conn->exec($s);
}
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Doctrine\DBAL\Schema\Synchronizer;
use Doctrine\DBAL\Schema\Schema;
/**
* The synchronizer knows how to synchronize a schema with the configured
* database.
*
* @deprecated
*/
interface SchemaSynchronizer
{
/**
* Gets the SQL statements that can be executed to create the schema.
*
* @return string[]
*/
public function getCreateSchema(Schema $createSchema);
/**
* Gets the SQL Statements to update given schema with the underlying db.
*
* @param bool $noDrops
*
* @return string[]
*/
public function getUpdateSchema(Schema $toSchema, $noDrops = false);
/**
* Gets the SQL Statements to drop the given schema from underlying db.
*
* @return string[]
*/
public function getDropSchema(Schema $dropSchema);
/**
* Gets the SQL statements to drop all schema assets from underlying db.
*
* @return string[]
*/
public function getDropAllSchema();
/**
* Creates the Schema.
*
* @return void
*/
public function createSchema(Schema $createSchema);
/**
* Updates the Schema to new schema version.
*
* @param bool $noDrops
*
* @return void
*/
public function updateSchema(Schema $toSchema, $noDrops = false);
/**
* Drops the given database schema from the underlying db.
*
* @return void
*/
public function dropSchema(Schema $dropSchema);
/**
* Drops all assets from the underlying db.
*
* @return void
*/
public function dropAllSchema();
}

View File

@@ -0,0 +1,160 @@
<?php
namespace Doctrine\DBAL\Schema\Synchronizer;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\Comparator;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector;
use function count;
/**
* Schema Synchronizer for Default DBAL Connection.
*
* @deprecated
*/
class SingleDatabaseSynchronizer extends AbstractSchemaSynchronizer
{
/** @var AbstractPlatform */
private $platform;
public function __construct(Connection $conn)
{
parent::__construct($conn);
$this->platform = $conn->getDatabasePlatform();
}
/**
* {@inheritdoc}
*/
public function getCreateSchema(Schema $createSchema)
{
return $createSchema->toSql($this->platform);
}
/**
* {@inheritdoc}
*/
public function getUpdateSchema(Schema $toSchema, $noDrops = false)
{
$comparator = new Comparator();
$sm = $this->conn->getSchemaManager();
$fromSchema = $sm->createSchema();
$schemaDiff = $comparator->compare($fromSchema, $toSchema);
if ($noDrops) {
return $schemaDiff->toSaveSql($this->platform);
}
return $schemaDiff->toSql($this->platform);
}
/**
* {@inheritdoc}
*/
public function getDropSchema(Schema $dropSchema)
{
$visitor = new DropSchemaSqlCollector($this->platform);
$sm = $this->conn->getSchemaManager();
$fullSchema = $sm->createSchema();
foreach ($fullSchema->getTables() as $table) {
if ($dropSchema->hasTable($table->getName())) {
$visitor->acceptTable($table);
}
foreach ($table->getForeignKeys() as $foreignKey) {
if (! $dropSchema->hasTable($table->getName())) {
continue;
}
if (! $dropSchema->hasTable($foreignKey->getForeignTableName())) {
continue;
}
$visitor->acceptForeignKey($table, $foreignKey);
}
}
if (! $this->platform->supportsSequences()) {
return $visitor->getQueries();
}
foreach ($dropSchema->getSequences() as $sequence) {
$visitor->acceptSequence($sequence);
}
foreach ($dropSchema->getTables() as $table) {
$primaryKey = $table->getPrimaryKey();
if ($primaryKey === null) {
continue;
}
$columns = $primaryKey->getColumns();
if (count($columns) > 1) {
continue;
}
$checkSequence = $table->getName() . '_' . $columns[0] . '_seq';
if (! $fullSchema->hasSequence($checkSequence)) {
continue;
}
$visitor->acceptSequence($fullSchema->getSequence($checkSequence));
}
return $visitor->getQueries();
}
/**
* {@inheritdoc}
*/
public function getDropAllSchema()
{
$sm = $this->conn->getSchemaManager();
$visitor = new DropSchemaSqlCollector($this->platform);
$schema = $sm->createSchema();
$schema->visit($visitor);
return $visitor->getQueries();
}
/**
* {@inheritdoc}
*/
public function createSchema(Schema $createSchema)
{
$this->processSql($this->getCreateSchema($createSchema));
}
/**
* {@inheritdoc}
*/
public function updateSchema(Schema $toSchema, $noDrops = false)
{
$this->processSql($this->getUpdateSchema($toSchema, $noDrops));
}
/**
* {@inheritdoc}
*/
public function dropSchema(Schema $dropSchema)
{
$this->processSqlSafely($this->getDropSchema($dropSchema));
}
/**
* {@inheritdoc}
*/
public function dropAllSchema()
{
$this->processSql($this->getDropAllSchema());
}
}

View File

@@ -0,0 +1,909 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Schema\Visitor\Visitor;
use Doctrine\DBAL\Types\Type;
use function array_filter;
use function array_merge;
use function in_array;
use function preg_match;
use function strlen;
use function strtolower;
use const ARRAY_FILTER_USE_KEY;
/**
* Object Representation of a table.
*/
class Table extends AbstractAsset
{
/** @var Column[] */
protected $_columns = [];
/** @var Index[] */
private $implicitIndexes = [];
/** @var Index[] */
protected $_indexes = [];
/** @var string|false */
protected $_primaryKeyName = false;
/** @var ForeignKeyConstraint[] */
protected $_fkConstraints = [];
/** @var mixed[] */
protected $_options = [
'create_options' => [],
];
/** @var SchemaConfig|null */
protected $_schemaConfig;
/**
* @param string $name
* @param Column[] $columns
* @param Index[] $indexes
* @param ForeignKeyConstraint[] $fkConstraints
* @param int $idGeneratorType
* @param mixed[] $options
*
* @throws Exception
*/
public function __construct(
$name,
array $columns = [],
array $indexes = [],
array $fkConstraints = [],
$idGeneratorType = 0,
array $options = []
) {
if (strlen($name) === 0) {
throw Exception::invalidTableName($name);
}
$this->_setName($name);
foreach ($columns as $column) {
$this->_addColumn($column);
}
foreach ($indexes as $idx) {
$this->_addIndex($idx);
}
foreach ($fkConstraints as $constraint) {
$this->_addForeignKeyConstraint($constraint);
}
$this->_options = array_merge($this->_options, $options);
}
/**
* @return void
*/
public function setSchemaConfig(SchemaConfig $schemaConfig)
{
$this->_schemaConfig = $schemaConfig;
}
/**
* @return int
*/
protected function _getMaxIdentifierLength()
{
if ($this->_schemaConfig instanceof SchemaConfig) {
return $this->_schemaConfig->getMaxIdentifierLength();
}
return 63;
}
/**
* Sets the Primary Key.
*
* @param string[] $columnNames
* @param string|false $indexName
*
* @return self
*/
public function setPrimaryKey(array $columnNames, $indexName = false)
{
$this->_addIndex($this->_createIndex($columnNames, $indexName ?: 'primary', true, true));
foreach ($columnNames as $columnName) {
$column = $this->getColumn($columnName);
$column->setNotnull(true);
}
return $this;
}
/**
* @param string[] $columnNames
* @param string|null $indexName
* @param string[] $flags
* @param mixed[] $options
*
* @return self
*/
public function addIndex(array $columnNames, $indexName = null, array $flags = [], array $options = [])
{
if ($indexName === null) {
$indexName = $this->_generateIdentifierName(
array_merge([$this->getName()], $columnNames),
'idx',
$this->_getMaxIdentifierLength()
);
}
return $this->_addIndex($this->_createIndex($columnNames, $indexName, false, false, $flags, $options));
}
/**
* Drops the primary key from this table.
*
* @return void
*/
public function dropPrimaryKey()
{
if ($this->_primaryKeyName === false) {
return;
}
$this->dropIndex($this->_primaryKeyName);
$this->_primaryKeyName = false;
}
/**
* Drops an index from this table.
*
* @param string $name The index name.
*
* @return void
*
* @throws SchemaException If the index does not exist.
*/
public function dropIndex($name)
{
$name = $this->normalizeIdentifier($name);
if (! $this->hasIndex($name)) {
throw SchemaException::indexDoesNotExist($name, $this->_name);
}
unset($this->_indexes[$name]);
}
/**
* @param string[] $columnNames
* @param string|null $indexName
* @param mixed[] $options
*
* @return self
*/
public function addUniqueIndex(array $columnNames, $indexName = null, array $options = [])
{
if ($indexName === null) {
$indexName = $this->_generateIdentifierName(
array_merge([$this->getName()], $columnNames),
'uniq',
$this->_getMaxIdentifierLength()
);
}
return $this->_addIndex($this->_createIndex($columnNames, $indexName, true, false, [], $options));
}
/**
* Renames an index.
*
* @param string $oldName The name of the index to rename from.
* @param string|null $newName The name of the index to rename to.
* If null is given, the index name will be auto-generated.
*
* @return self This table instance.
*
* @throws SchemaException If no index exists for the given current name
* or if an index with the given new name already exists on this table.
*/
public function renameIndex($oldName, $newName = null)
{
$oldName = $this->normalizeIdentifier($oldName);
$normalizedNewName = $this->normalizeIdentifier($newName);
if ($oldName === $normalizedNewName) {
return $this;
}
if (! $this->hasIndex($oldName)) {
throw SchemaException::indexDoesNotExist($oldName, $this->_name);
}
if ($this->hasIndex($normalizedNewName)) {
throw SchemaException::indexAlreadyExists($normalizedNewName, $this->_name);
}
$oldIndex = $this->_indexes[$oldName];
if ($oldIndex->isPrimary()) {
$this->dropPrimaryKey();
return $this->setPrimaryKey($oldIndex->getColumns(), $newName ?? false);
}
unset($this->_indexes[$oldName]);
if ($oldIndex->isUnique()) {
return $this->addUniqueIndex($oldIndex->getColumns(), $newName, $oldIndex->getOptions());
}
return $this->addIndex($oldIndex->getColumns(), $newName, $oldIndex->getFlags(), $oldIndex->getOptions());
}
/**
* Checks if an index begins in the order of the given columns.
*
* @param string[] $columnNames
*
* @return bool
*/
public function columnsAreIndexed(array $columnNames)
{
foreach ($this->getIndexes() as $index) {
if ($index->spansColumns($columnNames)) {
return true;
}
}
return false;
}
/**
* @param string[] $columnNames
* @param string $indexName
* @param bool $isUnique
* @param bool $isPrimary
* @param string[] $flags
* @param mixed[] $options
*
* @return Index
*
* @throws SchemaException
*/
private function _createIndex(
array $columnNames,
$indexName,
$isUnique,
$isPrimary,
array $flags = [],
array $options = []
) {
if (preg_match('(([^a-zA-Z0-9_]+))', $this->normalizeIdentifier($indexName))) {
throw SchemaException::indexNameInvalid($indexName);
}
foreach ($columnNames as $columnName) {
if (! $this->hasColumn($columnName)) {
throw SchemaException::columnDoesNotExist($columnName, $this->_name);
}
}
return new Index($indexName, $columnNames, $isUnique, $isPrimary, $flags, $options);
}
/**
* @param string $name
* @param string $typeName
* @param mixed[] $options
*
* @return Column
*/
public function addColumn($name, $typeName, array $options = [])
{
$column = new Column($name, Type::getType($typeName), $options);
$this->_addColumn($column);
return $column;
}
/**
* Renames a Column.
*
* @deprecated
*
* @param string $oldName
* @param string $name
*
* @return void
*
* @throws Exception
*/
public function renameColumn($oldName, $name)
{
throw new Exception('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.
*
* @param string $name
* @param mixed[] $options
*
* @return self
*/
public function changeColumn($name, array $options)
{
$column = $this->getColumn($name);
$column->setOptions($options);
return $this;
}
/**
* Drops a Column from the Table.
*
* @param string $name
*
* @return self
*/
public function dropColumn($name)
{
$name = $this->normalizeIdentifier($name);
unset($this->_columns[$name]);
return $this;
}
/**
* Adds a foreign key constraint.
*
* Name is inferred from the local columns.
*
* @param Table|string $foreignTable Table schema instance or table name
* @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
) {
$constraintName = $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
*
* @return self
*/
public function addUnnamedForeignKeyConstraint(
$foreignTable,
array $localColumnNames,
array $foreignColumnNames,
array $options = []
) {
return $this->addForeignKeyConstraint($foreignTable, $localColumnNames, $foreignColumnNames, $options);
}
/**
* 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)) {
throw SchemaException::columnDoesNotExist($columnName, $foreignTable->getName());
}
}
}
foreach ($localColumnNames as $columnName) {
if (! $this->hasColumn($columnName)) {
throw SchemaException::columnDoesNotExist($columnName, $this->_name);
}
}
$constraint = new ForeignKeyConstraint(
$localColumnNames,
$foreignTable,
$foreignColumnNames,
$name,
$options
);
$this->_addForeignKeyConstraint($constraint);
return $this;
}
/**
* @param string $name
* @param mixed $value
*
* @return self
*/
public function addOption($name, $value)
{
$this->_options[$name] = $value;
return $this;
}
/**
* @return void
*
* @throws SchemaException
*/
protected function _addColumn(Column $column)
{
$columnName = $column->getName();
$columnName = $this->normalizeIdentifier($columnName);
if (isset($this->_columns[$columnName])) {
throw SchemaException::columnAlreadyExists($this->getName(), $columnName);
}
$this->_columns[$columnName] = $column;
}
/**
* Adds an index to the table.
*
* @return self
*
* @throws SchemaException
*/
protected function _addIndex(Index $indexCandidate)
{
$indexName = $indexCandidate->getName();
$indexName = $this->normalizeIdentifier($indexName);
$replacedImplicitIndexes = [];
foreach ($this->implicitIndexes as $name => $implicitIndex) {
if (! $implicitIndex->isFullfilledBy($indexCandidate) || ! isset($this->_indexes[$name])) {
continue;
}
$replacedImplicitIndexes[] = $name;
}
if (
(isset($this->_indexes[$indexName]) && ! in_array($indexName, $replacedImplicitIndexes, true)) ||
($this->_primaryKeyName !== false && $indexCandidate->isPrimary())
) {
throw SchemaException::indexAlreadyExists($indexName, $this->_name);
}
foreach ($replacedImplicitIndexes as $name) {
unset($this->_indexes[$name], $this->implicitIndexes[$name]);
}
if ($indexCandidate->isPrimary()) {
$this->_primaryKeyName = $indexName;
}
$this->_indexes[$indexName] = $indexCandidate;
return $this;
}
/**
* @return void
*/
protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint)
{
$constraint->setLocalTable($this);
if (strlen($constraint->getName())) {
$name = $constraint->getName();
} else {
$name = $this->_generateIdentifierName(
array_merge((array) $this->getName(), $constraint->getLocalColumns()),
'fk',
$this->_getMaxIdentifierLength()
);
}
$name = $this->normalizeIdentifier($name);
$this->_fkConstraints[$name] = $constraint;
/* Add an implicit index (defined by the DBAL) on the foreign key
columns. If there is already a user-defined index that fulfills these
requirements drop the request. In the case of __construct() calling
this method during hydration from schema-details, all the explicitly
added indexes lead to duplicates. This creates computation overhead in
this case, however no duplicate indexes are ever added (based on
columns). */
$indexName = $this->_generateIdentifierName(
array_merge([$this->getName()], $constraint->getColumns()),
'idx',
$this->_getMaxIdentifierLength()
);
$indexCandidate = $this->_createIndex($constraint->getColumns(), $indexName, false, false);
foreach ($this->_indexes as $existingIndex) {
if ($indexCandidate->isFullfilledBy($existingIndex)) {
return;
}
}
$this->_addIndex($indexCandidate);
$this->implicitIndexes[$this->normalizeIdentifier($indexName)] = $indexCandidate;
}
/**
* Returns whether this table has a foreign key constraint with the given name.
*
* @param string $name
*
* @return bool
*/
public function hasForeignKey($name)
{
$name = $this->normalizeIdentifier($name);
return isset($this->_fkConstraints[$name]);
}
/**
* Returns the foreign key constraint with the given name.
*
* @param string $name The constraint name.
*
* @return ForeignKeyConstraint
*
* @throws SchemaException If the foreign key does not exist.
*/
public function getForeignKey($name)
{
$name = $this->normalizeIdentifier($name);
if (! $this->hasForeignKey($name)) {
throw SchemaException::foreignKeyDoesNotExist($name, $this->_name);
}
return $this->_fkConstraints[$name];
}
/**
* Removes the foreign key constraint with the given name.
*
* @param string $name The constraint name.
*
* @return void
*
* @throws SchemaException
*/
public function removeForeignKey($name)
{
$name = $this->normalizeIdentifier($name);
if (! $this->hasForeignKey($name)) {
throw SchemaException::foreignKeyDoesNotExist($name, $this->_name);
}
unset($this->_fkConstraints[$name]);
}
/**
* Returns ordered list of columns (primary keys are first, then foreign keys, then the rest)
*
* @return Column[]
*/
public function getColumns()
{
$primaryKey = $this->getPrimaryKey();
$primaryKeyColumns = [];
if ($primaryKey !== null) {
$primaryKeyColumns = $this->filterColumns($primaryKey->getColumns());
}
return array_merge($primaryKeyColumns, $this->getForeignKeyColumns(), $this->_columns);
}
/**
* Returns foreign key columns
*
* @return Column[]
*/
private function getForeignKeyColumns()
{
$foreignKeyColumns = [];
foreach ($this->getForeignKeys() as $foreignKey) {
$foreignKeyColumns = array_merge($foreignKeyColumns, $foreignKey->getColumns());
}
return $this->filterColumns($foreignKeyColumns);
}
/**
* Returns only columns that have specified names
*
* @param string[] $columnNames
*
* @return Column[]
*/
private function filterColumns(array $columnNames)
{
return array_filter($this->_columns, static function (string $columnName) use ($columnNames) {
return in_array($columnName, $columnNames, true);
}, ARRAY_FILTER_USE_KEY);
}
/**
* Returns whether this table has a Column with the given name.
*
* @param string $name The column name.
*
* @return bool
*/
public function hasColumn($name)
{
$name = $this->normalizeIdentifier($name);
return isset($this->_columns[$name]);
}
/**
* Returns the Column with the given name.
*
* @param string $name The column name.
*
* @return Column
*
* @throws SchemaException If the column does not exist.
*/
public function getColumn($name)
{
$name = $this->normalizeIdentifier($name);
if (! $this->hasColumn($name)) {
throw SchemaException::columnDoesNotExist($name, $this->_name);
}
return $this->_columns[$name];
}
/**
* Returns the primary key.
*
* @return Index|null The primary key, or null if this Table has no primary key.
*/
public function getPrimaryKey()
{
if ($this->_primaryKeyName !== false) {
return $this->getIndex($this->_primaryKeyName);
}
return null;
}
/**
* Returns the primary key columns.
*
* @return string[]
*
* @throws Exception
*/
public function getPrimaryKeyColumns()
{
$primaryKey = $this->getPrimaryKey();
if ($primaryKey === null) {
throw new Exception('Table ' . $this->getName() . ' has no primary key.');
}
return $primaryKey->getColumns();
}
/**
* Returns whether this table has a primary key.
*
* @return bool
*/
public function hasPrimaryKey()
{
return $this->_primaryKeyName && $this->hasIndex($this->_primaryKeyName);
}
/**
* Returns whether this table has an Index with the given name.
*
* @param string $name The index name.
*
* @return bool
*/
public function hasIndex($name)
{
$name = $this->normalizeIdentifier($name);
return isset($this->_indexes[$name]);
}
/**
* Returns the Index with the given name.
*
* @param string $name The index name.
*
* @return Index
*
* @throws SchemaException If the index does not exist.
*/
public function getIndex($name)
{
$name = $this->normalizeIdentifier($name);
if (! $this->hasIndex($name)) {
throw SchemaException::indexDoesNotExist($name, $this->_name);
}
return $this->_indexes[$name];
}
/**
* @return Index[]
*/
public function getIndexes()
{
return $this->_indexes;
}
/**
* Returns the foreign key constraints.
*
* @return ForeignKeyConstraint[]
*/
public function getForeignKeys()
{
return $this->_fkConstraints;
}
/**
* @param string $name
*
* @return bool
*/
public function hasOption($name)
{
return isset($this->_options[$name]);
}
/**
* @param string $name
*
* @return mixed
*/
public function getOption($name)
{
return $this->_options[$name];
}
/**
* @return mixed[]
*/
public function getOptions()
{
return $this->_options;
}
/**
* @return void
*/
public function visit(Visitor $visitor)
{
$visitor->acceptTable($this);
foreach ($this->getColumns() as $column) {
$visitor->acceptColumn($this, $column);
}
foreach ($this->getIndexes() as $index) {
$visitor->acceptIndex($this, $index);
}
foreach ($this->getForeignKeys() as $constraint) {
$visitor->acceptForeignKey($this, $constraint);
}
}
/**
* Clone of a Table triggers a deep clone of all affected assets.
*
* @return void
*/
public function __clone()
{
foreach ($this->_columns as $k => $column) {
$this->_columns[$k] = clone $column;
}
foreach ($this->_indexes as $k => $index) {
$this->_indexes[$k] = clone $index;
}
foreach ($this->_fkConstraints as $k => $fk) {
$this->_fkConstraints[$k] = clone $fk;
$this->_fkConstraints[$k]->setLocalTable($this);
}
}
/**
* Normalizes a given identifier.
*
* Trims quotes and lowercases the given identifier.
*
* @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;
}
}

View File

@@ -0,0 +1,152 @@
<?php
namespace Doctrine\DBAL\Schema;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* Table Diff.
*/
class TableDiff
{
/** @var string */
public $name;
/** @var string|false */
public $newName = false;
/**
* All added columns
*
* @var Column[]
*/
public $addedColumns;
/**
* All changed columns
*
* @var ColumnDiff[]
*/
public $changedColumns = [];
/**
* All removed columns
*
* @var Column[]
*/
public $removedColumns = [];
/**
* Columns that are only renamed from key to column instance name.
*
* @var Column[]
*/
public $renamedColumns = [];
/**
* All added indexes.
*
* @var Index[]
*/
public $addedIndexes = [];
/**
* All changed indexes.
*
* @var Index[]
*/
public $changedIndexes = [];
/**
* All removed indexes
*
* @var Index[]
*/
public $removedIndexes = [];
/**
* Indexes that are only renamed but are identical otherwise.
*
* @var Index[]
*/
public $renamedIndexes = [];
/**
* All added foreign key definitions
*
* @var ForeignKeyConstraint[]
*/
public $addedForeignKeys = [];
/**
* All changed foreign keys
*
* @var ForeignKeyConstraint[]
*/
public $changedForeignKeys = [];
/**
* All removed foreign keys
*
* @var ForeignKeyConstraint[]|string[]
*/
public $removedForeignKeys = [];
/** @var Table|null */
public $fromTable;
/**
* Constructs an TableDiff object.
*
* @param string $tableName
* @param Column[] $addedColumns
* @param ColumnDiff[] $changedColumns
* @param Column[] $removedColumns
* @param Index[] $addedIndexes
* @param Index[] $changedIndexes
* @param Index[] $removedIndexes
*/
public function __construct(
$tableName,
$addedColumns = [],
$changedColumns = [],
$removedColumns = [],
$addedIndexes = [],
$changedIndexes = [],
$removedIndexes = [],
?Table $fromTable = null
) {
$this->name = $tableName;
$this->addedColumns = $addedColumns;
$this->changedColumns = $changedColumns;
$this->removedColumns = $removedColumns;
$this->addedIndexes = $addedIndexes;
$this->changedIndexes = $changedIndexes;
$this->removedIndexes = $removedIndexes;
$this->fromTable = $fromTable;
}
/**
* @param AbstractPlatform $platform The platform to use for retrieving this table diff's name.
*
* @return Identifier
*/
public function getName(AbstractPlatform $platform)
{
return new Identifier(
$this->fromTable instanceof Table ? $this->fromTable->getQuotedName($platform) : $this->name
);
}
/**
* @return Identifier|false
*/
public function getNewName()
{
if ($this->newName === false) {
return false;
}
return new Identifier($this->newName);
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Doctrine\DBAL\Schema;
/**
* Representation of a Database View.
*/
class View extends AbstractAsset
{
/** @var string */
private $sql;
/**
* @param string $name
* @param string $sql
*/
public function __construct($name, $sql)
{
$this->_setName($name);
$this->sql = $sql;
}
/**
* @return string
*/
public function getSql()
{
return $this->sql;
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Doctrine\DBAL\Schema\Visitor;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
/**
* Abstract Visitor with empty methods for easy extension.
*/
class AbstractVisitor implements Visitor, NamespaceVisitor
{
public function acceptSchema(Schema $schema)
{
}
/**
* {@inheritdoc}
*/
public function acceptNamespace($namespaceName)
{
}
public function acceptTable(Table $table)
{
}
public function acceptColumn(Table $table, Column $column)
{
}
public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint)
{
}
public function acceptIndex(Table $table, Index $index)
{
}
public function acceptSequence(Sequence $sequence)
{
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace Doctrine\DBAL\Schema\Visitor;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
use function array_merge;
class CreateSchemaSqlCollector extends AbstractVisitor
{
/** @var string[] */
private $createNamespaceQueries = [];
/** @var string[] */
private $createTableQueries = [];
/** @var string[] */
private $createSequenceQueries = [];
/** @var string[] */
private $createFkConstraintQueries = [];
/** @var AbstractPlatform */
private $platform;
public function __construct(AbstractPlatform $platform)
{
$this->platform = $platform;
}
/**
* {@inheritdoc}
*/
public function acceptNamespace($namespaceName)
{
if (! $this->platform->supportsSchemas()) {
return;
}
$this->createNamespaceQueries[] = $this->platform->getCreateSchemaSQL($namespaceName);
}
/**
* {@inheritdoc}
*/
public function acceptTable(Table $table)
{
$this->createTableQueries = array_merge($this->createTableQueries, $this->platform->getCreateTableSQL($table));
}
/**
* {@inheritdoc}
*/
public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint)
{
if (! $this->platform->supportsForeignKeyConstraints()) {
return;
}
$this->createFkConstraintQueries[] = $this->platform->getCreateForeignKeySQL($fkConstraint, $localTable);
}
/**
* {@inheritdoc}
*/
public function acceptSequence(Sequence $sequence)
{
$this->createSequenceQueries[] = $this->platform->getCreateSequenceSQL($sequence);
}
/**
* @return void
*/
public function resetQueries()
{
$this->createNamespaceQueries = [];
$this->createTableQueries = [];
$this->createSequenceQueries = [];
$this->createFkConstraintQueries = [];
}
/**
* Gets all queries collected so far.
*
* @return string[]
*/
public function getQueries()
{
return array_merge(
$this->createNamespaceQueries,
$this->createTableQueries,
$this->createSequenceQueries,
$this->createFkConstraintQueries
);
}
}

View File

@@ -0,0 +1,106 @@
<?php
namespace Doctrine\DBAL\Schema\Visitor;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\SchemaException;
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
use SplObjectStorage;
use function assert;
use function strlen;
/**
* Gathers SQL statements that allow to completely drop the current schema.
*/
class DropSchemaSqlCollector extends AbstractVisitor
{
/** @var SplObjectStorage */
private $constraints;
/** @var SplObjectStorage */
private $sequences;
/** @var SplObjectStorage */
private $tables;
/** @var AbstractPlatform */
private $platform;
public function __construct(AbstractPlatform $platform)
{
$this->platform = $platform;
$this->initializeQueries();
}
/**
* {@inheritdoc}
*/
public function acceptTable(Table $table)
{
$this->tables->attach($table);
}
/**
* {@inheritdoc}
*/
public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint)
{
if (strlen($fkConstraint->getName()) === 0) {
throw SchemaException::namedForeignKeyRequired($localTable, $fkConstraint);
}
$this->constraints->attach($fkConstraint, $localTable);
}
/**
* {@inheritdoc}
*/
public function acceptSequence(Sequence $sequence)
{
$this->sequences->attach($sequence);
}
/**
* @return void
*/
public function clearQueries()
{
$this->initializeQueries();
}
/**
* @return string[]
*/
public function getQueries()
{
$sql = [];
foreach ($this->constraints as $fkConstraint) {
assert($fkConstraint instanceof ForeignKeyConstraint);
$localTable = $this->constraints[$fkConstraint];
$sql[] = $this->platform->getDropForeignKeySQL($fkConstraint, $localTable);
}
foreach ($this->sequences as $sequence) {
assert($sequence instanceof Sequence);
$sql[] = $this->platform->getDropSequenceSQL($sequence);
}
foreach ($this->tables as $table) {
assert($table instanceof Table);
$sql[] = $this->platform->getDropTableSQL($table);
}
return $sql;
}
private function initializeQueries(): void
{
$this->constraints = new SplObjectStorage();
$this->sequences = new SplObjectStorage();
$this->tables = new SplObjectStorage();
}
}

View File

@@ -0,0 +1,168 @@
<?php
namespace Doctrine\DBAL\Schema\Visitor;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
use function current;
use function file_put_contents;
use function in_array;
use function strtolower;
/**
* Create a Graphviz output of a Schema.
*/
class Graphviz extends AbstractVisitor
{
/** @var string */
private $output = '';
/**
* {@inheritdoc}
*/
public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint)
{
$this->output .= $this->createNodeRelation(
$fkConstraint->getLocalTableName() . ':col' . current($fkConstraint->getLocalColumns()) . ':se',
$fkConstraint->getForeignTableName() . ':col' . current($fkConstraint->getForeignColumns()) . ':se',
[
'dir' => 'back',
'arrowtail' => 'dot',
'arrowhead' => 'normal',
]
);
}
/**
* {@inheritdoc}
*/
public function acceptSchema(Schema $schema)
{
$this->output = 'digraph "' . $schema->getName() . '" {' . "\n";
$this->output .= 'splines = true;' . "\n";
$this->output .= 'overlap = false;' . "\n";
$this->output .= 'outputorder=edgesfirst;' . "\n";
$this->output .= 'mindist = 0.6;' . "\n";
$this->output .= 'sep = .2;' . "\n";
}
/**
* {@inheritdoc}
*/
public function acceptTable(Table $table)
{
$this->output .= $this->createNode(
$table->getName(),
[
'label' => $this->createTableLabel($table),
'shape' => 'plaintext',
]
);
}
/**
* @return string
*/
private function createTableLabel(Table $table)
{
// Start the table
$label = '<<TABLE CELLSPACING="0" BORDER="1" ALIGN="LEFT">';
// The title
$label .= '<TR><TD BORDER="1" COLSPAN="3" ALIGN="CENTER" BGCOLOR="#fcaf3e">'
. '<FONT COLOR="#2e3436" FACE="Helvetica" POINT-SIZE="12">' . $table->getName() . '</FONT></TD></TR>';
// The attributes block
foreach ($table->getColumns() as $column) {
$columnLabel = $column->getName();
$label .= '<TR>'
. '<TD BORDER="0" ALIGN="LEFT" BGCOLOR="#eeeeec">'
. '<FONT COLOR="#2e3436" FACE="Helvetica" POINT-SIZE="12">' . $columnLabel . '</FONT>'
. '</TD>'
. '<TD BORDER="0" ALIGN="LEFT" BGCOLOR="#eeeeec">'
. '<FONT COLOR="#2e3436" FACE="Helvetica" POINT-SIZE="10">' . strtolower($column->getType()) . '</FONT>'
. '</TD>'
. '<TD BORDER="0" ALIGN="RIGHT" BGCOLOR="#eeeeec" PORT="col' . $column->getName() . '">';
$primaryKey = $table->getPrimaryKey();
if ($primaryKey !== null && in_array($column->getName(), $primaryKey->getColumns())) {
$label .= "\xe2\x9c\xb7";
}
$label .= '</TD></TR>';
}
// End the table
$label .= '</TABLE>>';
return $label;
}
/**
* @param string $name
* @param string[] $options
*
* @return string
*/
private function createNode($name, $options)
{
$node = $name . ' [';
foreach ($options as $key => $value) {
$node .= $key . '=' . $value . ' ';
}
$node .= "]\n";
return $node;
}
/**
* @param string $node1
* @param string $node2
* @param string[] $options
*
* @return string
*/
private function createNodeRelation($node1, $node2, $options)
{
$relation = $node1 . ' -> ' . $node2 . ' [';
foreach ($options as $key => $value) {
$relation .= $key . '=' . $value . ' ';
}
$relation .= "]\n";
return $relation;
}
/**
* Get Graphviz Output
*
* @return string
*/
public function getOutput()
{
return $this->output . '}';
}
/**
* Writes dot language output to a file. This should usually be a *.dot file.
*
* You have to convert the output into a viewable format. For example use "neato" on linux systems
* and execute:
*
* neato -Tpng -o er.png er.dot
*
* @param string $filename
*
* @return void
*/
public function write($filename)
{
file_put_contents($filename, $this->getOutput());
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Doctrine\DBAL\Schema\Visitor;
/**
* Visitor that can visit schema namespaces.
*/
interface NamespaceVisitor
{
/**
* Accepts a schema namespace name.
*
* @param string $namespaceName The schema namespace name to accept.
*
* @return void
*/
public function acceptNamespace($namespaceName);
}

View File

@@ -0,0 +1,91 @@
<?php
namespace Doctrine\DBAL\Schema\Visitor;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
/**
* Removes assets from a schema that are not in the default namespace.
*
* Some databases such as MySQL support cross databases joins, but don't
* allow to call DDLs to a database from another connected database.
* Before a schema is serialized into SQL this visitor can cleanup schemas with
* non default namespaces.
*
* This visitor filters all these non-default namespaced tables and sequences
* and removes them from the SChema instance.
*/
class RemoveNamespacedAssets extends AbstractVisitor
{
/** @var Schema|null */
private $schema;
/**
* {@inheritdoc}
*/
public function acceptSchema(Schema $schema)
{
$this->schema = $schema;
}
/**
* {@inheritdoc}
*/
public function acceptTable(Table $table)
{
if ($this->schema === null) {
return;
}
if ($table->isInDefaultNamespace($this->schema->getName())) {
return;
}
$this->schema->dropTable($table->getName());
}
/**
* {@inheritdoc}
*/
public function acceptSequence(Sequence $sequence)
{
if ($this->schema === null) {
return;
}
if ($sequence->isInDefaultNamespace($this->schema->getName())) {
return;
}
$this->schema->dropSequence($sequence->getName());
}
/**
* {@inheritdoc}
*/
public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint)
{
if ($this->schema === null) {
return;
}
// The table may already be deleted in a previous
// RemoveNamespacedAssets#acceptTable call. Removing Foreign keys that
// point to nowhere.
if (! $this->schema->hasTable($fkConstraint->getForeignTableName())) {
$localTable->removeForeignKey($fkConstraint->getName());
return;
}
$foreignTable = $this->schema->getTable($fkConstraint->getForeignTableName());
if ($foreignTable->isInDefaultNamespace($this->schema->getName())) {
return;
}
$localTable->removeForeignKey($fkConstraint->getName());
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace Doctrine\DBAL\Schema\Visitor;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\TableDiff;
/**
* Visit a SchemaDiff.
*/
interface SchemaDiffVisitor
{
/**
* Visit an orphaned foreign key whose table was deleted.
*
* @return void
*/
public function visitOrphanedForeignKey(ForeignKeyConstraint $foreignKey);
/**
* Visit a sequence that has changed.
*
* @return void
*/
public function visitChangedSequence(Sequence $sequence);
/**
* Visit a sequence that has been removed.
*
* @return void
*/
public function visitRemovedSequence(Sequence $sequence);
/** @return void */
public function visitNewSequence(Sequence $sequence);
/** @return void */
public function visitNewTable(Table $table);
/** @return void */
public function visitNewTableForeignKey(Table $table, ForeignKeyConstraint $foreignKey);
/** @return void */
public function visitRemovedTable(Table $table);
/** @return void */
public function visitChangedTable(TableDiff $tableDiff);
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Doctrine\DBAL\Schema\Visitor;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
/**
* Schema Visitor used for Validation or Generation purposes.
*/
interface Visitor
{
/**
* @return void
*/
public function acceptSchema(Schema $schema);
/**
* @return void
*/
public function acceptTable(Table $table);
/**
* @return void
*/
public function acceptColumn(Table $table, Column $column);
/**
* @return void
*/
public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint);
/**
* @return void
*/
public function acceptIndex(Table $table, Index $index);
/**
* @return void
*/
public function acceptSequence(Sequence $sequence);
}