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\Platforms;
22 use Doctrine\DBAL\DBALException,
23 Doctrine\DBAL\Schema\TableDiff,
24 Doctrine\DBAL\Schema\Index,
25 Doctrine\DBAL\Schema\Table;
28 * The MySqlPlatform provides the behavior, features and SQL dialect of the
29 * MySQL database platform. This platform represents a MySQL 5.0 or greater platform that
30 * uses the InnoDB storage engine.
33 * @author Roman Borschel <roman@code-factory.org>
34 * @author Benjamin Eberlei <kontakt@beberlei.de>
35 * @todo Rename: MySQLPlatform
37 class MySqlPlatform extends AbstractPlatform
42 public function getIdentifierQuoteCharacter()
50 public function getRegexpExpression()
58 public function getGuidExpression()
66 public function getLocateExpression($str, $substr, $startPos = false)
68 if ($startPos == false) {
69 return 'LOCATE(' . $substr . ', ' . $str . ')';
72 return 'LOCATE(' . $substr . ', ' . $str . ', '.$startPos.')';
78 public function getConcatExpression()
80 $args = func_get_args();
81 return 'CONCAT(' . join(', ', (array) $args) . ')';
87 public function getDateDiffExpression($date1, $date2)
89 return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
95 public function getDateAddDaysExpression($date, $days)
97 return 'DATE_ADD(' . $date . ', INTERVAL ' . $days . ' DAY)';
103 public function getDateSubDaysExpression($date, $days)
105 return 'DATE_SUB(' . $date . ', INTERVAL ' . $days . ' DAY)';
111 public function getDateAddMonthExpression($date, $months)
113 return 'DATE_ADD(' . $date . ', INTERVAL ' . $months . ' MONTH)';
119 public function getDateSubMonthExpression($date, $months)
121 return 'DATE_SUB(' . $date . ', INTERVAL ' . $months . ' MONTH)';
124 public function getListDatabasesSQL()
126 return 'SHOW DATABASES';
129 public function getListTableConstraintsSQL($table)
131 return 'SHOW INDEX FROM ' . $table;
137 * Two approaches to listing the table indexes. The information_schema is
138 * preferred, because it doesn't cause problems with SQL keywords such as "order" or "table".
140 * @param string $table
141 * @param string $currentDatabase
144 public function getListTableIndexesSQL($table, $currentDatabase = null)
146 if ($currentDatabase) {
147 return "SELECT TABLE_NAME AS `Table`, NON_UNIQUE AS Non_Unique, INDEX_NAME AS Key_name, ".
148 "SEQ_IN_INDEX AS Seq_in_index, COLUMN_NAME AS Column_Name, COLLATION AS Collation, ".
149 "CARDINALITY AS Cardinality, SUB_PART AS Sub_Part, PACKED AS Packed, " .
150 "NULLABLE AS `Null`, INDEX_TYPE AS Index_Type, COMMENT AS Comment " .
151 "FROM information_schema.STATISTICS WHERE TABLE_NAME = '" . $table . "' AND TABLE_SCHEMA = '" . $currentDatabase . "'";
154 return 'SHOW INDEX FROM ' . $table;
157 public function getListViewsSQL($database)
159 return "SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = '".$database."'";
162 public function getListTableForeignKeysSQL($table, $database = null)
164 $sql = "SELECT DISTINCT k.`CONSTRAINT_NAME`, k.`COLUMN_NAME`, k.`REFERENCED_TABLE_NAME`, ".
165 "k.`REFERENCED_COLUMN_NAME` /*!50116 , c.update_rule, c.delete_rule */ ".
166 "FROM information_schema.key_column_usage k /*!50116 ".
167 "INNER JOIN information_schema.referential_constraints c ON ".
168 " c.constraint_name = k.constraint_name AND ".
169 " c.table_name = '$table' */ WHERE k.table_name = '$table'";
172 $sql .= " AND k.table_schema = '$database' /*!50116 AND c.constraint_schema = '$database' */";
175 $sql .= " AND k.`REFERENCED_COLUMN_NAME` is not NULL";
180 public function getCreateViewSQL($name, $sql)
182 return 'CREATE VIEW ' . $name . ' AS ' . $sql;
185 public function getDropViewSQL($name)
187 return 'DROP VIEW '. $name;
193 protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
195 return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
196 : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
202 public function getClobTypeDeclarationSQL(array $field)
204 if ( ! empty($field['length']) && is_numeric($field['length'])) {
205 $length = $field['length'];
206 if ($length <= 255) {
210 if ($length <= 65532) {
214 if ($length <= 16777215) {
225 public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
227 if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] == true) {
237 public function getDateTypeDeclarationSQL(array $fieldDeclaration)
245 public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
253 public function getBooleanTypeDeclarationSQL(array $field)
259 * Obtain DBMS specific SQL code portion needed to set the COLLATION
260 * of a field declaration to be used in statements like CREATE TABLE.
262 * @param string $collation name of the collation
264 * @return string DBMS specific SQL code portion needed to set the COLLATION
265 * of a field declaration.
267 public function getCollationFieldDeclaration($collation)
269 return 'COLLATE ' . $collation;
275 * MySql prefers "autoincrement" identity columns since sequences can only
276 * be emulated with a table.
278 public function prefersIdentityColumns()
286 * MySql supports this through AUTO_INCREMENT columns.
288 public function supportsIdentityColumns()
296 public function supportsInlineColumnComments()
304 public function getShowDatabasesSQL()
306 return 'SHOW DATABASES';
309 public function getListTablesSQL()
311 return "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'";
314 public function getListTableColumnsSQL($table, $database = null)
317 return "SELECT COLUMN_NAME AS Field, COLUMN_TYPE AS Type, IS_NULLABLE AS `Null`, ".
318 "COLUMN_KEY AS `Key`, COLUMN_DEFAULT AS `Default`, EXTRA AS Extra, COLUMN_COMMENT AS Comment, " .
319 "CHARACTER_SET_NAME AS CharacterSet, COLLATION_NAME AS CollactionName ".
320 "FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '" . $database . "' AND TABLE_NAME = '" . $table . "'";
323 return 'DESCRIBE ' . $table;
329 public function getCreateDatabaseSQL($name)
331 return 'CREATE DATABASE ' . $name;
337 public function getDropDatabaseSQL($name)
339 return 'DROP DATABASE ' . $name;
345 protected function _getCreateTableSQL($tableName, array $columns, array $options = array())
347 $queryFields = $this->getColumnDeclarationListSQL($columns);
349 if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
350 foreach ($options['uniqueConstraints'] as $index => $definition) {
351 $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($index, $definition);
356 if (isset($options['indexes']) && ! empty($options['indexes'])) {
357 foreach($options['indexes'] as $index => $definition) {
358 $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
362 // attach all primary keys
363 if (isset($options['primary']) && ! empty($options['primary'])) {
364 $keyColumns = array_unique(array_values($options['primary']));
365 $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
369 if (!empty($options['temporary'])) {
370 $query .= 'TEMPORARY ';
372 $query .= 'TABLE ' . $tableName . ' (' . $queryFields . ') ';
374 if (isset($options['comment'])) {
375 $query .= 'COMMENT = ' . $options['comment'] . ' ';
378 if ( ! isset($options['charset'])) {
379 $options['charset'] = 'utf8';
382 if ( ! isset($options['collate'])) {
383 $options['collate'] = 'utf8_unicode_ci';
386 $query .= 'DEFAULT CHARACTER SET ' . $options['charset'];
387 $query .= ' COLLATE ' . $options['collate'];
389 if ( ! isset($options['engine'])) {
390 $options['engine'] = 'InnoDB';
392 $query .= ' ENGINE = ' . $options['engine'];
396 if (isset($options['foreignKeys'])) {
397 foreach ((array) $options['foreignKeys'] as $definition) {
398 $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
408 public function getAlterTableSQL(TableDiff $diff)
410 $columnSql = array();
411 $queryParts = array();
412 if ($diff->newName !== false) {
413 $queryParts[] = 'RENAME TO ' . $diff->newName;
416 foreach ($diff->addedColumns as $column) {
417 if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
421 $columnArray = $column->toArray();
422 $columnArray['comment'] = $this->getColumnComment($column);
423 $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
426 foreach ($diff->removedColumns as $column) {
427 if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
431 $queryParts[] = 'DROP ' . $column->getQuotedName($this);
434 foreach ($diff->changedColumns as $columnDiff) {
435 if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
439 /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
440 $column = $columnDiff->column;
441 $columnArray = $column->toArray();
442 $columnArray['comment'] = $this->getColumnComment($column);
443 $queryParts[] = 'CHANGE ' . ($columnDiff->oldColumnName) . ' '
444 . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
447 foreach ($diff->renamedColumns as $oldColumnName => $column) {
448 if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
452 $columnArray = $column->toArray();
453 $columnArray['comment'] = $this->getColumnComment($column);
454 $queryParts[] = 'CHANGE ' . $oldColumnName . ' '
455 . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
461 if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
462 if (count($queryParts) > 0) {
463 $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . implode(", ", $queryParts);
466 $this->getPreAlterTableIndexForeignKeySQL($diff),
468 $this->getPostAlterTableIndexForeignKeySQL($diff)
472 return array_merge($sql, $tableSql, $columnSql);
478 protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
481 $table = $diff->name;
483 foreach ($diff->removedIndexes as $remKey => $remIndex) {
485 foreach ($diff->addedIndexes as $addKey => $addIndex) {
486 if ($remIndex->getColumns() == $addIndex->getColumns()) {
488 $columns = $addIndex->getColumns();
490 if ($addIndex->isUnique()) {
494 $query = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', ';
495 $query .= 'ADD ' . $type . 'INDEX ' . $addIndex->getName();
496 $query .= ' (' . $this->getIndexFieldDeclarationListSQL($columns) . ')';
500 unset($diff->removedIndexes[$remKey]);
501 unset($diff->addedIndexes[$addKey]);
508 $sql = array_merge($sql, parent::getPreAlterTableIndexForeignKeySQL($diff));
516 protected function getCreateIndexSQLFlags(Index $index)
519 if ($index->isUnique()) {
521 } else if ($index->hasFlag('fulltext')) {
522 $type .= 'FULLTEXT ';
531 public function getIntegerTypeDeclarationSQL(array $field)
533 return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
539 public function getBigIntTypeDeclarationSQL(array $field)
541 return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
547 public function getSmallIntTypeDeclarationSQL(array $field)
549 return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
555 protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
558 if ( ! empty($columnDef['autoincrement'])) {
559 $autoinc = ' AUTO_INCREMENT';
561 $unsigned = (isset($columnDef['unsigned']) && $columnDef['unsigned']) ? ' UNSIGNED' : '';
563 return $unsigned . $autoinc;
569 public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey)
572 if ($foreignKey->hasOption('match')) {
573 $query .= ' MATCH ' . $foreignKey->getOption('match');
575 $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
582 public function getDropIndexSQL($index, $table=null)
584 if ($index instanceof Index) {
585 $indexName = $index->getQuotedName($this);
586 } else if(is_string($index)) {
589 throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
592 if ($table instanceof Table) {
593 $table = $table->getQuotedName($this);
594 } else if(!is_string($table)) {
595 throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
598 if ($index instanceof Index && $index->isPrimary()) {
599 // mysql primary keys are always named "PRIMARY",
600 // so we cannot use them in statements because of them being keyword.
601 return $this->getDropPrimaryKeySQL($table);
604 return 'DROP INDEX ' . $indexName . ' ON ' . $table;
608 * @param string $table
612 protected function getDropPrimaryKeySQL($table)
614 return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
620 public function getSetTransactionIsolationSQL($level)
622 return 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
628 public function getName()
636 public function getReadLockSQL()
638 return 'LOCK IN SHARE MODE';
644 protected function initializeDoctrineTypeMappings()
646 $this->doctrineTypeMapping = array(
647 'tinyint' => 'boolean',
648 'smallint' => 'smallint',
649 'mediumint' => 'integer',
651 'integer' => 'integer',
652 'bigint' => 'bigint',
653 'tinytext' => 'text',
654 'mediumtext' => 'text',
655 'longtext' => 'text',
657 'varchar' => 'string',
658 'string' => 'string',
661 'datetime' => 'datetime',
662 'timestamp' => 'datetime',
667 'decimal' => 'decimal',
668 'numeric' => 'decimal',
670 'longblob' => 'blob',
672 'mediumblob' => 'blob',
673 'tinyblob' => 'blob',
675 'varbinary' => 'blob',
676 'set' => 'simple_array',
683 public function getVarcharMaxLength()
691 protected function getReservedKeywordsClass()
693 return 'Doctrine\DBAL\Platforms\Keywords\MySQLKeywords';
699 * MySQL commits a transaction implicitly when DROP TABLE is executed, however not
700 * if DROP TEMPORARY TABLE is executed.
702 public function getDropTemporaryTableSQL($table)
704 if ($table instanceof Table) {
705 $table = $table->getQuotedName($this);
706 } else if(!is_string($table)) {
707 throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
710 return 'DROP TEMPORARY TABLE ' . $table;
716 public function getBlobTypeDeclarationSQL(array $field)