3 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15 * This software consists of voluntary contributions made by many individuals
16 * and is licensed under the MIT license. For more information, see
17 * <http://www.doctrine-project.org>.
20 namespace Doctrine\DBAL\Schema;
22 use Doctrine\DBAL\Events;
23 use Doctrine\DBAL\Event\SchemaColumnDefinitionEventArgs;
24 use Doctrine\DBAL\Event\SchemaIndexDefinitionEventArgs;
25 use Doctrine\DBAL\Types;
26 use Doctrine\DBAL\DBALException;
27 use Doctrine\DBAL\Platforms\AbstractPlatform;
30 * Base class for schema managers. Schema managers are used to inspect and/or
31 * modify the database schema/structure.
33 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
34 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
35 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
36 * @author Roman Borschel <roman@code-factory.org>
37 * @author Jonathan H. Wage <jonwage@gmail.com>
38 * @author Benjamin Eberlei <kontakt@beberlei.de>
41 abstract class AbstractSchemaManager
44 * Holds instance of the Doctrine connection for this schema manager
46 * @var \Doctrine\DBAL\Connection
51 * Holds instance of the database platform used for this schema manager
53 * @var \Doctrine\DBAL\Platforms\AbstractPlatform
58 * Constructor. Accepts the Connection instance to manage the schema for
60 * @param \Doctrine\DBAL\Connection $conn
62 public function __construct(\Doctrine\DBAL\Connection $conn)
65 $this->_platform = $this->_conn->getDatabasePlatform();
69 * Return associated platform.
71 * @return \Doctrine\DBAL\Platforms\AbstractPlatform
73 public function getDatabasePlatform()
75 return $this->_platform;
79 * Try any method on the schema manager. Normally a method throws an
80 * exception when your DBMS doesn't support it or if an error occurs.
81 * This method allows you to try and method on your SchemaManager
82 * instance and will return false if it does not work or is not supported.
85 * $result = $sm->tryMethod('dropView', 'view_name');
90 public function tryMethod()
92 $args = func_get_args();
95 $args = array_values($args);
98 return call_user_func_array(array($this, $method), $args);
99 } catch (\Exception $e) {
105 * List the available databases for this connection
107 * @return array $databases
109 public function listDatabases()
111 $sql = $this->_platform->getListDatabasesSQL();
113 $databases = $this->_conn->fetchAll($sql);
115 return $this->_getPortableDatabasesList($databases);
119 * List the available sequences for this connection
123 public function listSequences($database = null)
125 if (is_null($database)) {
126 $database = $this->_conn->getDatabase();
128 $sql = $this->_platform->getListSequencesSQL($database);
130 $sequences = $this->_conn->fetchAll($sql);
132 return $this->filterAssetNames($this->_getPortableSequencesList($sequences));
136 * List the columns for a given table.
138 * In contrast to other libraries and to the old version of Doctrine,
139 * this column definition does try to contain the 'primary' field for
140 * the reason that it is not portable accross different RDBMS. Use
141 * {@see listTableIndexes($tableName)} to retrieve the primary key
142 * of a table. We're a RDBMS specifies more details these are held
143 * in the platformDetails array.
145 * @param string $table The name of the table.
146 * @param string $database
149 public function listTableColumns($table, $database = null)
152 $database = $this->_conn->getDatabase();
155 $sql = $this->_platform->getListTableColumnsSQL($table, $database);
157 $tableColumns = $this->_conn->fetchAll($sql);
159 return $this->_getPortableTableColumnList($table, $database, $tableColumns);
163 * List the indexes for a given table returning an array of Index instances.
165 * Keys of the portable indexes list are all lower-cased.
167 * @param string $table The name of the table
168 * @return Index[] $tableIndexes
170 public function listTableIndexes($table)
172 $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
174 $tableIndexes = $this->_conn->fetchAll($sql);
176 return $this->_getPortableTableIndexesList($tableIndexes, $table);
180 * Return true if all the given tables exist.
182 * @param array $tableNames
185 public function tablesExist($tableNames)
187 $tableNames = array_map('strtolower', (array)$tableNames);
188 return count($tableNames) == count(\array_intersect($tableNames, array_map('strtolower', $this->listTableNames())));
192 * Return a list of all tables in the current database
196 public function listTableNames()
198 $sql = $this->_platform->getListTablesSQL();
200 $tables = $this->_conn->fetchAll($sql);
201 $tableNames = $this->_getPortableTablesList($tables);
202 return $this->filterAssetNames($tableNames);
206 * Filter asset names if they are configured to return only a subset of all
207 * the found elements.
209 * @param array $assetNames
212 protected function filterAssetNames($assetNames)
214 $filterExpr = $this->getFilterSchemaAssetsExpression();
215 if ( ! $filterExpr) {
218 return array_values (
219 array_filter($assetNames, function ($assetName) use ($filterExpr) {
220 $assetName = ($assetName instanceof AbstractAsset) ? $assetName->getName() : $assetName;
221 return preg_match($filterExpr, $assetName);
226 protected function getFilterSchemaAssetsExpression()
228 return $this->_conn->getConfiguration()->getFilterSchemaAssetsExpression();
232 * List the tables for this connection
236 public function listTables()
238 $tableNames = $this->listTableNames();
241 foreach ($tableNames as $tableName) {
242 $tables[] = $this->listTableDetails($tableName);
249 * @param string $tableName
252 public function listTableDetails($tableName)
254 $columns = $this->listTableColumns($tableName);
255 $foreignKeys = array();
256 if ($this->_platform->supportsForeignKeyConstraints()) {
257 $foreignKeys = $this->listTableForeignKeys($tableName);
259 $indexes = $this->listTableIndexes($tableName);
261 return new Table($tableName, $columns, $indexes, $foreignKeys, false, array());
265 * List the views this connection has
269 public function listViews()
271 $database = $this->_conn->getDatabase();
272 $sql = $this->_platform->getListViewsSQL($database);
273 $views = $this->_conn->fetchAll($sql);
275 return $this->_getPortableViewsList($views);
279 * List the foreign keys for the given table
281 * @param string $table The name of the table
282 * @return ForeignKeyConstraint[]
284 public function listTableForeignKeys($table, $database = null)
286 if (is_null($database)) {
287 $database = $this->_conn->getDatabase();
289 $sql = $this->_platform->getListTableForeignKeysSQL($table, $database);
290 $tableForeignKeys = $this->_conn->fetchAll($sql);
292 return $this->_getPortableTableForeignKeysList($tableForeignKeys);
295 /* drop*() Methods */
300 * NOTE: You can not drop the database this SchemaManager is currently connected to.
302 * @param string $database The name of the database to drop
304 public function dropDatabase($database)
306 $this->_execSql($this->_platform->getDropDatabaseSQL($database));
310 * Drop the given table
312 * @param string $table The name of the table to drop
314 public function dropTable($table)
316 $this->_execSql($this->_platform->getDropTableSQL($table));
320 * Drop the index from the given table
322 * @param Index|string $index The name of the index
323 * @param string|Table $table The name of the table
325 public function dropIndex($index, $table)
327 if($index instanceof Index) {
328 $index = $index->getQuotedName($this->_platform);
331 $this->_execSql($this->_platform->getDropIndexSQL($index, $table));
335 * Drop the constraint from the given table
337 * @param Constraint $constraint
338 * @param string $table The name of the table
340 public function dropConstraint(Constraint $constraint, $table)
342 $this->_execSql($this->_platform->getDropConstraintSQL($constraint, $table));
346 * Drops a foreign key from a table.
348 * @param ForeignKeyConstraint|string $table The name of the table with the foreign key.
349 * @param Table|string $name The name of the foreign key.
350 * @return boolean $result
352 public function dropForeignKey($foreignKey, $table)
354 $this->_execSql($this->_platform->getDropForeignKeySQL($foreignKey, $table));
358 * Drops a sequence with a given name.
360 * @param string $name The name of the sequence to drop.
362 public function dropSequence($name)
364 $this->_execSql($this->_platform->getDropSequenceSQL($name));
370 * @param string $name The name of the view
371 * @return boolean $result
373 public function dropView($name)
375 $this->_execSql($this->_platform->getDropViewSQL($name));
378 /* create*() Methods */
381 * Creates a new database.
383 * @param string $database The name of the database to create.
385 public function createDatabase($database)
387 $this->_execSql($this->_platform->getCreateDatabaseSQL($database));
391 * Create a new table.
393 * @param Table $table
394 * @param int $createFlags
396 public function createTable(Table $table)
398 $createFlags = AbstractPlatform::CREATE_INDEXES|AbstractPlatform::CREATE_FOREIGNKEYS;
399 $this->_execSql($this->_platform->getCreateTableSQL($table, $createFlags));
403 * Create a new sequence
405 * @param Sequence $sequence
406 * @throws \Doctrine\DBAL\ConnectionException if something fails at database level
408 public function createSequence($sequence)
410 $this->_execSql($this->_platform->getCreateSequenceSQL($sequence));
414 * Create a constraint on a table
416 * @param Constraint $constraint
417 * @param string|Table $table
419 public function createConstraint(Constraint $constraint, $table)
421 $this->_execSql($this->_platform->getCreateConstraintSQL($constraint, $table));
425 * Create a new index on a table
427 * @param Index $index
428 * @param string $table name of the table on which the index is to be created
430 public function createIndex(Index $index, $table)
432 $this->_execSql($this->_platform->getCreateIndexSQL($index, $table));
436 * Create a new foreign key
438 * @param ForeignKeyConstraint $foreignKey ForeignKey instance
439 * @param string|Table $table name of the table on which the foreign key is to be created
441 public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
443 $this->_execSql($this->_platform->getCreateForeignKeySQL($foreignKey, $table));
451 public function createView(View $view)
453 $this->_execSql($this->_platform->getCreateViewSQL($view->getQuotedName($this->_platform), $view->getSql()));
456 /* dropAndCreate*() Methods */
459 * Drop and create a constraint
461 * @param Constraint $constraint
462 * @param string $table
463 * @see dropConstraint()
464 * @see createConstraint()
466 public function dropAndCreateConstraint(Constraint $constraint, $table)
468 $this->tryMethod('dropConstraint', $constraint, $table);
469 $this->createConstraint($constraint, $table);
473 * Drop and create a new index on a table
475 * @param string|Table $table name of the table on which the index is to be created
476 * @param Index $index
478 public function dropAndCreateIndex(Index $index, $table)
480 $this->tryMethod('dropIndex', $index->getQuotedName($this->_platform), $table);
481 $this->createIndex($index, $table);
485 * Drop and create a new foreign key
487 * @param ForeignKeyConstraint $foreignKey associative array that defines properties of the foreign key to be created.
488 * @param string|Table $table name of the table on which the foreign key is to be created
490 public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table)
492 $this->tryMethod('dropForeignKey', $foreignKey, $table);
493 $this->createForeignKey($foreignKey, $table);
497 * Drop and create a new sequence
499 * @param Sequence $sequence
500 * @throws \Doctrine\DBAL\ConnectionException if something fails at database level
502 public function dropAndCreateSequence(Sequence $sequence)
504 $this->tryMethod('dropSequence', $sequence->getQuotedName($this->_platform));
505 $this->createSequence($sequence);
509 * Drop and create a new table.
511 * @param Table $table
513 public function dropAndCreateTable(Table $table)
515 $this->tryMethod('dropTable', $table->getQuotedName($this->_platform));
516 $this->createTable($table);
520 * Drop and creates a new database.
522 * @param string $database The name of the database to create.
524 public function dropAndCreateDatabase($database)
526 $this->tryMethod('dropDatabase', $database);
527 $this->createDatabase($database);
531 * Drop and create a new view
535 public function dropAndCreateView(View $view)
537 $this->tryMethod('dropView', $view->getQuotedName($this->_platform));
538 $this->createView($view);
541 /* alterTable() Methods */
544 * Alter an existing tables schema
546 * @param TableDiff $tableDiff
548 public function alterTable(TableDiff $tableDiff)
550 $queries = $this->_platform->getAlterTableSQL($tableDiff);
551 if (is_array($queries) && count($queries)) {
552 foreach ($queries as $ddlQuery) {
553 $this->_execSql($ddlQuery);
559 * Rename a given table to another name
561 * @param string $name The current name of the table
562 * @param string $newName The new name of the table
564 public function renameTable($name, $newName)
566 $tableDiff = new TableDiff($name);
567 $tableDiff->newName = $newName;
568 $this->alterTable($tableDiff);
572 * Methods for filtering return values of list*() methods to convert
573 * the native DBMS data definition to a portable Doctrine definition
576 protected function _getPortableDatabasesList($databases)
579 foreach ($databases as $value) {
580 if ($value = $this->_getPortableDatabaseDefinition($value)) {
587 protected function _getPortableDatabaseDefinition($database)
592 protected function _getPortableFunctionsList($functions)
595 foreach ($functions as $value) {
596 if ($value = $this->_getPortableFunctionDefinition($value)) {
603 protected function _getPortableFunctionDefinition($function)
608 protected function _getPortableTriggersList($triggers)
611 foreach ($triggers as $value) {
612 if ($value = $this->_getPortableTriggerDefinition($value)) {
619 protected function _getPortableTriggerDefinition($trigger)
624 protected function _getPortableSequencesList($sequences)
627 foreach ($sequences as $value) {
628 if ($value = $this->_getPortableSequenceDefinition($value)) {
636 * @param array $sequence
639 protected function _getPortableSequenceDefinition($sequence)
641 throw DBALException::notSupported('Sequences');
645 * Independent of the database the keys of the column list result are lowercased.
647 * The name of the created column instance however is kept in its case.
649 * @param string $table The name of the table.
650 * @param string $database
651 * @param array $tableColumns
654 protected function _getPortableTableColumnList($table, $database, $tableColumns)
656 $eventManager = $this->_platform->getEventManager();
659 foreach ($tableColumns as $tableColumn) {
661 $defaultPrevented = false;
663 if (null !== $eventManager && $eventManager->hasListeners(Events::onSchemaColumnDefinition)) {
664 $eventArgs = new SchemaColumnDefinitionEventArgs($tableColumn, $table, $database, $this->_conn);
665 $eventManager->dispatchEvent(Events::onSchemaColumnDefinition, $eventArgs);
667 $defaultPrevented = $eventArgs->isDefaultPrevented();
668 $column = $eventArgs->getColumn();
671 if ( ! $defaultPrevented) {
672 $column = $this->_getPortableTableColumnDefinition($tableColumn);
676 $name = strtolower($column->getQuotedName($this->_platform));
677 $list[$name] = $column;
684 * Get Table Column Definition
686 * @param array $tableColumn
689 abstract protected function _getPortableTableColumnDefinition($tableColumn);
692 * Aggregate and group the index results according to the required data result.
694 * @param array $tableIndexRows
695 * @param string $tableName
698 protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null)
701 foreach($tableIndexRows as $tableIndex) {
702 $indexName = $keyName = $tableIndex['key_name'];
703 if($tableIndex['primary']) {
704 $keyName = 'primary';
706 $keyName = strtolower($keyName);
708 if(!isset($result[$keyName])) {
709 $result[$keyName] = array(
710 'name' => $indexName,
711 'columns' => array($tableIndex['column_name']),
712 'unique' => $tableIndex['non_unique'] ? false : true,
713 'primary' => $tableIndex['primary'],
714 'flags' => isset($tableIndex['flags']) ? $tableIndex['flags'] : array(),
717 $result[$keyName]['columns'][] = $tableIndex['column_name'];
721 $eventManager = $this->_platform->getEventManager();
724 foreach($result as $indexKey => $data) {
726 $defaultPrevented = false;
728 if (null !== $eventManager && $eventManager->hasListeners(Events::onSchemaIndexDefinition)) {
729 $eventArgs = new SchemaIndexDefinitionEventArgs($data, $tableName, $this->_conn);
730 $eventManager->dispatchEvent(Events::onSchemaIndexDefinition, $eventArgs);
732 $defaultPrevented = $eventArgs->isDefaultPrevented();
733 $index = $eventArgs->getIndex();
736 if ( ! $defaultPrevented) {
737 $index = new Index($data['name'], $data['columns'], $data['unique'], $data['primary'], $data['flags']);
741 $indexes[$indexKey] = $index;
748 protected function _getPortableTablesList($tables)
751 foreach ($tables as $value) {
752 if ($value = $this->_getPortableTableDefinition($value)) {
759 protected function _getPortableTableDefinition($table)
764 protected function _getPortableUsersList($users)
767 foreach ($users as $value) {
768 if ($value = $this->_getPortableUserDefinition($value)) {
775 protected function _getPortableUserDefinition($user)
780 protected function _getPortableViewsList($views)
783 foreach ($views as $value) {
784 if ($view = $this->_getPortableViewDefinition($value)) {
785 $viewName = strtolower($view->getQuotedName($this->_platform));
786 $list[$viewName] = $view;
792 protected function _getPortableViewDefinition($view)
797 protected function _getPortableTableForeignKeysList($tableForeignKeys)
800 foreach ($tableForeignKeys as $value) {
801 if ($value = $this->_getPortableTableForeignKeyDefinition($value)) {
808 protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
810 return $tableForeignKey;
813 protected function _execSql($sql)
815 foreach ((array) $sql as $query) {
816 $this->_conn->executeUpdate($query);
821 * Create a schema instance for the current database.
825 public function createSchema()
827 $sequences = array();
828 if($this->_platform->supportsSequences()) {
829 $sequences = $this->listSequences();
831 $tables = $this->listTables();
833 return new Schema($tables, $sequences, $this->createSchemaConfig());
837 * Create the configuration for this schema.
839 * @return SchemaConfig
841 public function createSchemaConfig()
843 $schemaConfig = new SchemaConfig();
844 $schemaConfig->setMaxIdentifierLength($this->_platform->getMaxIdentifierLength());
846 $searchPaths = $this->getSchemaSearchPaths();
847 if (isset($searchPaths[0])) {
848 $schemaConfig->setName($searchPaths[0]);
851 $params = $this->_conn->getParams();
852 if (isset($params['defaultTableOptions'])) {
853 $schemaConfig->setDefaultTableOptions($params['defautTableOptions']);
856 return $schemaConfig;
860 * The search path for namespaces in the currently connected database.
862 * The first entry is usually the default namespace in the Schema. All
863 * further namespaces contain tables/sequences which can also be addressed
864 * with a short, not full-qualified name.
866 * For databases that don't support subschema/namespaces this method
867 * returns the name of the currently connected database.
871 public function getSchemaSearchPaths()
873 return array($this->_conn->getDatabase());
877 * Given a table comment this method tries to extract a typehint for Doctrine Type, or returns
878 * the type given as default.
880 * @param string $comment
881 * @param string $currentType
884 public function extractDoctrineTypeFromComment($comment, $currentType)
886 if (preg_match("(\(DC2Type:([a-zA-Z0-9_]+)\))", $comment, $match)) {
887 $currentType = $match[1];
892 public function removeDoctrineTypeFromComment($comment, $type)
894 return str_replace('(DC2Type:'.$type.')', '', $comment);