MySqlSchemaManager.php 10.4 KB
Newer Older
romanb's avatar
romanb committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
18 19
 */

20
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
21

22
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
23
use Doctrine\DBAL\Platforms\MySqlPlatform;
24
use Doctrine\DBAL\Types\Type;
25 26 27 28 29 30 31 32 33 34 35 36
use const CASE_LOWER;
use function array_change_key_case;
use function array_shift;
use function array_values;
use function end;
use function preg_match;
use function preg_replace;
use function str_replace;
use function stripslashes;
use function strpos;
use function strtok;
use function strtolower;
37

romanb's avatar
romanb committed
38
/**
39
 * Schema manager for the MySql RDBMS.
romanb's avatar
romanb committed
40
 *
Benjamin Morel's avatar
Benjamin Morel committed
41 42 43 44 45
 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
 * @author Roman Borschel <roman@code-factory.org>
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 * @since  2.0
romanb's avatar
romanb committed
46
 */
47
class MySqlSchemaManager extends AbstractSchemaManager
48
{
Benjamin Morel's avatar
Benjamin Morel committed
49 50 51
    /**
     * {@inheritdoc}
     */
52 53
    protected function _getPortableViewDefinition($view)
    {
54
        return new View($view['TABLE_NAME'], $view['VIEW_DEFINITION']);
55 56
    }

Benjamin Morel's avatar
Benjamin Morel committed
57 58 59
    /**
     * {@inheritdoc}
     */
60 61
    protected function _getPortableTableDefinition($table)
    {
62
        return array_shift($table);
63 64
    }

Benjamin Morel's avatar
Benjamin Morel committed
65 66 67
    /**
     * {@inheritdoc}
     */
68 69
    protected function _getPortableUserDefinition($user)
    {
70
        return [
71 72
            'user' => $user['User'],
            'password' => $user['Password'],
73
        ];
74 75
    }

Benjamin Morel's avatar
Benjamin Morel committed
76 77 78
    /**
     * {@inheritdoc}
     */
belgattitude's avatar
belgattitude committed
79
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
80
    {
Steve Müller's avatar
Steve Müller committed
81
        foreach ($tableIndexes as $k => $v) {
82
            $v = array_change_key_case($v, CASE_LOWER);
83
            if ($v['key_name'] === 'PRIMARY') {
84 85 86 87
                $v['primary'] = true;
            } else {
                $v['primary'] = false;
            }
88
            if (strpos($v['index_type'], 'FULLTEXT') !== false) {
89
                $v['flags'] = ['FULLTEXT'];
90
            } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
91
                $v['flags'] = ['SPATIAL'];
92
            }
93
            $tableIndexes[$k] = $v;
94
        }
95

96
        return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
97 98
    }

Benjamin Morel's avatar
Benjamin Morel committed
99 100 101
    /**
     * {@inheritdoc}
     */
102 103 104 105 106
    protected function _getPortableSequenceDefinition($sequence)
    {
        return end($sequence);
    }

Benjamin Morel's avatar
Benjamin Morel committed
107 108 109
    /**
     * {@inheritdoc}
     */
110 111
    protected function _getPortableDatabaseDefinition($database)
    {
112
        return $database['Database'];
113
    }
114

115
    /**
Benjamin Morel's avatar
Benjamin Morel committed
116
     * {@inheritdoc}
117
     */
118 119
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
120 121 122
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);

        $dbType = strtolower($tableColumn['type']);
123
        $dbType = strtok($dbType, '(), ');
124
        $length = $tableColumn['length'] ?? strtok('(), ');
Benjamin Morel's avatar
Benjamin Morel committed
125

126
        $fixed = null;
127 128 129 130

        if ( ! isset($tableColumn['name'])) {
            $tableColumn['name'] = '';
        }
131

belgattitude's avatar
belgattitude committed
132
        $scale     = null;
133
        $precision = null;
134

135
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
136 137 138

        // In cases where not connected to a database DESCRIBE $table does not return 'Comment'
        if (isset($tableColumn['comment'])) {
belgattitude's avatar
belgattitude committed
139
            $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
140 141
            $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
        }
142

143 144
        switch ($dbType) {
            case 'char':
Steve Müller's avatar
Steve Müller committed
145
            case 'binary':
146
                $fixed = true;
147
                break;
148 149 150 151
            case 'float':
            case 'double':
            case 'real':
            case 'numeric':
152
            case 'decimal':
Steve Müller's avatar
Steve Müller committed
153
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
154
                    $precision = $match[1];
belgattitude's avatar
belgattitude committed
155 156
                    $scale     = $match[2];
                    $length    = null;
157
                }
158
                break;
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
            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;
177 178 179 180 181 182
            case 'tinyint':
            case 'smallint':
            case 'mediumint':
            case 'int':
            case 'integer':
            case 'bigint':
183 184
            case 'year':
                $length = null;
185
                break;
186 187
        }

188
        if ($this->_platform instanceof MariaDb1027Platform) {
189
            $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
190
        } else {
191
            $columnDefault = $tableColumn['default'];
192
        }
193

194
        $options = [
belgattitude's avatar
belgattitude committed
195
            'length'        => $length !== null ? (int) $length : null,
196
            'unsigned'      => strpos($tableColumn['type'], 'unsigned') !== false,
197
            'fixed'         => (bool) $fixed,
198
            'default'       => $columnDefault,
belgattitude's avatar
belgattitude committed
199
            'notnull'       => $tableColumn['null'] !== 'YES',
200 201
            'scale'         => null,
            'precision'     => null,
202
            'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
203 204 205
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
                ? $tableColumn['comment']
                : null,
206
        ];
207

208
        if ($scale !== null && $precision !== null) {
belgattitude's avatar
belgattitude committed
209
            $options['scale']     = (int) $scale;
210
            $options['precision'] = (int) $precision;
211 212
        }

213 214 215 216 217 218 219
        $column = new Column($tableColumn['field'], Type::getType($type), $options);

        if (isset($tableColumn['collation'])) {
            $column->setPlatformOption('collation', $tableColumn['collation']);
        }

        return $column;
220 221
    }

222
    /**
223
     * Return Doctrine/Mysql-compatible column default values for MariaDB 10.2.7+ servers.
224
     *
225
     * - Since MariaDb 10.2.7 column defaults stored in information_schema are now quoted
226
     *   to distinguish them from expressions (see MDEV-10134).
227 228
     * - CURRENT_TIMESTAMP, CURRENT_TIME, CURRENT_DATE are stored in information_schema
     *   as current_timestamp(), currdate(), currtime()
229
     * - Quoted 'NULL' is not enforced by Maria, it is technically possible to have
230
     *   null in some circumstances (see https://jira.mariadb.org/browse/MDEV-14053)
231
     * - \' is always stored as '' in information_schema (normalized)
232 233 234 235 236 237
     *
     * @link https://mariadb.com/kb/en/library/information-schema-columns-table/
     * @link https://jira.mariadb.org/browse/MDEV-13132
     *
     * @param null|string $columnDefault default value as stored in information_schema for MariaDB >= 10.2.7
     */
belgattitude's avatar
belgattitude committed
238 239
    private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault) : ?string
    {
240
        if ($columnDefault === 'NULL' || $columnDefault === null) {
241 242
            return null;
        }
243
        if ($columnDefault[0] === "'") {
244 245 246 247 248
            return stripslashes(
                str_replace("''", "'",
                    preg_replace('/^\'(.*)\'$/', '$1', $columnDefault)
                )
            );
249
        }
belgattitude's avatar
belgattitude committed
250
        switch ($columnDefault) {
251 252 253 254 255 256 257 258
            case 'current_timestamp()':
                return $platform->getCurrentTimestampSQL();
            case 'curdate()':
                return $platform->getCurrentDateSQL();
            case 'curtime()':
                return $platform->getCurrentTimeSQL();
        }
        return $columnDefault;
259 260
    }

Benjamin Morel's avatar
Benjamin Morel committed
261 262 263
    /**
     * {@inheritdoc}
     */
264
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
romanb's avatar
romanb committed
265
    {
266
        $list = [];
Benjamin Morel's avatar
Benjamin Morel committed
267
        foreach ($tableForeignKeys as $value) {
268
            $value = array_change_key_case($value, CASE_LOWER);
belgattitude's avatar
belgattitude committed
269 270
            if ( ! isset($list[$value['constraint_name']])) {
                if ( ! isset($value['delete_rule']) || $value['delete_rule'] === "RESTRICT") {
271 272
                    $value['delete_rule'] = null;
                }
belgattitude's avatar
belgattitude committed
273
                if ( ! isset($value['update_rule']) || $value['update_rule'] === "RESTRICT") {
274 275
                    $value['update_rule'] = null;
                }
276

277
                $list[$value['constraint_name']] = [
278
                    'name' => $value['constraint_name'],
279 280
                    'local' => [],
                    'foreign' => [],
281 282 283
                    'foreignTable' => $value['referenced_table_name'],
                    'onDelete' => $value['delete_rule'],
                    'onUpdate' => $value['update_rule'],
284
                ];
285
            }
belgattitude's avatar
belgattitude committed
286
            $list[$value['constraint_name']]['local'][]   = $value['column_name'];
287
            $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
288
        }
289

290
        $result = [];
Steve Müller's avatar
Steve Müller committed
291
        foreach ($list as $constraint) {
292
            $result[] = new ForeignKeyConstraint(
belgattitude's avatar
belgattitude committed
293 294 295 296
                array_values($constraint['local']),
                $constraint['foreignTable'],
                array_values($constraint['foreign']),
                $constraint['name'],
297
                [
298 299
                    'onDelete' => $constraint['onDelete'],
                    'onUpdate' => $constraint['onUpdate'],
300
                ]
301
            );
302
        }
303

304
        return $result;
romanb's avatar
romanb committed
305
    }
306
}