MySqlSchemaManager.php 10.6 KB
Newer Older
romanb's avatar
romanb committed
1 2
<?php

Michael Moravec's avatar
Michael Moravec committed
3 4
declare(strict_types=1);

5
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
6

7
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
8
use Doctrine\DBAL\Platforms\MySqlPlatform;
9
use Doctrine\DBAL\Types\Type;
10 11 12
use const CASE_LOWER;
use function array_change_key_case;
use function array_values;
Sergei Morozov's avatar
Sergei Morozov committed
13
use function assert;
14
use function explode;
Sergei Morozov's avatar
Sergei Morozov committed
15
use function is_string;
16 17 18 19
use function preg_match;
use function strpos;
use function strtok;
use function strtolower;
20
use function strtr;
21

romanb's avatar
romanb committed
22
/**
23
 * Schema manager for the MySql RDBMS.
romanb's avatar
romanb committed
24
 */
25
class MySqlSchemaManager extends AbstractSchemaManager
26
{
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
    /**
     * @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
        "''" => "'",
    ];

Benjamin Morel's avatar
Benjamin Morel committed
47 48 49
    /**
     * {@inheritdoc}
     */
50
    protected function _getPortableViewDefinition(array $view) : View
51
    {
52
        return new View($view['TABLE_NAME'], $view['VIEW_DEFINITION']);
53 54
    }

Benjamin Morel's avatar
Benjamin Morel committed
55 56 57
    /**
     * {@inheritdoc}
     */
58
    protected function _getPortableUserDefinition(array $user) : array
59
    {
60
        return [
61 62
            'user' => $user['User'],
            'password' => $user['Password'],
63
        ];
64 65
    }

Benjamin Morel's avatar
Benjamin Morel committed
66 67 68
    /**
     * {@inheritdoc}
     */
69
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
70
    {
71
        foreach ($tableIndexRows as $k => $v) {
72
            $v = array_change_key_case($v, CASE_LOWER);
73
            if ($v['key_name'] === 'PRIMARY') {
74 75 76 77
                $v['primary'] = true;
            } else {
                $v['primary'] = false;
            }
78
            if (strpos($v['index_type'], 'FULLTEXT') !== false) {
79
                $v['flags'] = ['FULLTEXT'];
80
            } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
81
                $v['flags'] = ['SPATIAL'];
82
            }
83
            $v['length'] = isset($v['sub_part']) ? (int) $v['sub_part'] : null;
84

85
            $tableIndexRows[$k] = $v;
86
        }
87

88
        return parent::_getPortableTableIndexesList($tableIndexRows, $tableName);
89 90
    }

Benjamin Morel's avatar
Benjamin Morel committed
91 92 93
    /**
     * {@inheritdoc}
     */
94
    protected function _getPortableDatabaseDefinition(array $database) : string
95
    {
96
        return $database['Database'];
97
    }
98

99
    /**
Benjamin Morel's avatar
Benjamin Morel committed
100
     * {@inheritdoc}
101
     */
102
    protected function _getPortableTableColumnDefinition(array $tableColumn) : Column
103
    {
104 105 106
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);

        $dbType = strtolower($tableColumn['type']);
107
        $dbType = strtok($dbType, '(), ');
Sergei Morozov's avatar
Sergei Morozov committed
108 109
        assert(is_string($dbType));

110
        $length = $tableColumn['length'] ?? strtok('(), ');
Benjamin Morel's avatar
Benjamin Morel committed
111

112
        $fixed = false;
113

114
        if (! isset($tableColumn['name'])) {
115 116
            $tableColumn['name'] = '';
        }
117

118
        $scale     = 0;
119
        $precision = null;
120

121 122
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'])
            ?? $this->_platform->getDoctrineTypeMapping($dbType);
123

124 125
        switch ($dbType) {
            case 'char':
Steve Müller's avatar
Steve Müller committed
126
            case 'binary':
127
                $fixed = true;
128
                break;
129 130 131 132
            case 'float':
            case 'double':
            case 'real':
            case 'numeric':
133
            case 'decimal':
Steve Müller's avatar
Steve Müller committed
134
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
135 136
                    $precision = (int) $match[1];
                    $scale     = (int) $match[2];
belgattitude's avatar
belgattitude committed
137
                    $length    = null;
138
                }
139
                break;
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
            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;
158 159 160 161 162 163
            case 'tinyint':
            case 'smallint':
            case 'mediumint':
            case 'int':
            case 'integer':
            case 'bigint':
164 165
            case 'year':
                $length = null;
166
                break;
167 168
        }

169
        if ($this->_platform instanceof MariaDb1027Platform) {
170
            $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
171
        } else {
172
            $columnDefault = $tableColumn['default'];
173
        }
174

175
        $options = [
belgattitude's avatar
belgattitude committed
176
            'length'        => $length !== null ? (int) $length : null,
177
            'unsigned'      => strpos($tableColumn['type'], 'unsigned') !== false,
178
            'fixed'         => $fixed,
179
            'default'       => $columnDefault,
belgattitude's avatar
belgattitude committed
180
            'notnull'       => $tableColumn['null'] !== 'YES',
181 182
            'scale'         => $scale,
            'precision'     => $precision,
183
            'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
184 185 186
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
                ? $tableColumn['comment']
                : null,
187
        ];
188

189 190
        $column = new Column($tableColumn['field'], Type::getType($type), $options);

191 192 193
        if (isset($tableColumn['characterset'])) {
            $column->setPlatformOption('charset', $tableColumn['characterset']);
        }
194 195 196 197 198
        if (isset($tableColumn['collation'])) {
            $column->setPlatformOption('collation', $tableColumn['collation']);
        }

        return $column;
199 200
    }

201
    /**
202
     * Return Doctrine/Mysql-compatible column default values for MariaDB 10.2.7+ servers.
203
     *
204
     * - Since MariaDb 10.2.7 column defaults stored in information_schema are now quoted
205
     *   to distinguish them from expressions (see MDEV-10134).
206 207
     * - CURRENT_TIMESTAMP, CURRENT_TIME, CURRENT_DATE are stored in information_schema
     *   as current_timestamp(), currdate(), currtime()
208
     * - Quoted 'NULL' is not enforced by Maria, it is technically possible to have
209
     *   null in some circumstances (see https://jira.mariadb.org/browse/MDEV-14053)
210
     * - \' is always stored as '' in information_schema (normalized)
211 212 213 214
     *
     * @link https://mariadb.com/kb/en/library/information-schema-columns-table/
     * @link https://jira.mariadb.org/browse/MDEV-13132
     *
215
     * @param string|null $columnDefault default value as stored in information_schema for MariaDB >= 10.2.7
216
     */
belgattitude's avatar
belgattitude committed
217 218
    private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault) : ?string
    {
219
        if ($columnDefault === 'NULL' || $columnDefault === null) {
220 221
            return null;
        }
Sergei Morozov's avatar
Sergei Morozov committed
222 223

        if (preg_match('/^\'(.*)\'$/', $columnDefault, $matches)) {
224
            return strtr($matches[1], self::MARIADB_ESCAPE_SEQUENCES);
225
        }
Sergei Morozov's avatar
Sergei Morozov committed
226

belgattitude's avatar
belgattitude committed
227
        switch ($columnDefault) {
228 229 230 231 232 233 234
            case 'current_timestamp()':
                return $platform->getCurrentTimestampSQL();
            case 'curdate()':
                return $platform->getCurrentDateSQL();
            case 'curtime()':
                return $platform->getCurrentTimeSQL();
        }
235

236
        return $columnDefault;
237 238
    }

Benjamin Morel's avatar
Benjamin Morel committed
239 240 241
    /**
     * {@inheritdoc}
     */
242
    protected function _getPortableTableForeignKeysList(array $tableForeignKeys) : array
romanb's avatar
romanb committed
243
    {
244
        $list = [];
Benjamin Morel's avatar
Benjamin Morel committed
245
        foreach ($tableForeignKeys as $value) {
246
            $value = array_change_key_case($value, CASE_LOWER);
247 248
            if (! isset($list[$value['constraint_name']])) {
                if (! isset($value['delete_rule']) || $value['delete_rule'] === 'RESTRICT') {
249 250
                    $value['delete_rule'] = null;
                }
251
                if (! isset($value['update_rule']) || $value['update_rule'] === 'RESTRICT') {
252 253
                    $value['update_rule'] = null;
                }
254

255
                $list[$value['constraint_name']] = [
256
                    'name' => $value['constraint_name'],
257 258
                    'local' => [],
                    'foreign' => [],
259 260 261
                    'foreignTable' => $value['referenced_table_name'],
                    'onDelete' => $value['delete_rule'],
                    'onUpdate' => $value['update_rule'],
262
                ];
263
            }
belgattitude's avatar
belgattitude committed
264
            $list[$value['constraint_name']]['local'][]   = $value['column_name'];
265
            $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
266
        }
267

268
        $result = [];
Steve Müller's avatar
Steve Müller committed
269
        foreach ($list as $constraint) {
270
            $result[] = new ForeignKeyConstraint(
belgattitude's avatar
belgattitude committed
271 272 273 274
                array_values($constraint['local']),
                $constraint['foreignTable'],
                array_values($constraint['foreign']),
                $constraint['name'],
275
                [
276 277
                    'onDelete' => $constraint['onDelete'],
                    'onUpdate' => $constraint['onUpdate'],
278
                ]
279
            );
280
        }
281

282
        return $result;
romanb's avatar
romanb committed
283
    }
284

285 286 287 288
    /**
     * {@inheritdoc}
     */
    public function listTableDetails(string $tableName) : Table
289 290 291 292 293 294 295 296 297
    {
        $table = parent::listTableDetails($tableName);

        /** @var MySqlPlatform $platform */
        $platform = $this->_platform;
        $sql      = $platform->getListTableMetadataSQL($tableName);

        $tableOptions = $this->_conn->fetchAssoc($sql);

298 299 300 301
        if ($tableOptions === false) {
            return $table;
        }

302
        $table->addOption('engine', $tableOptions['ENGINE']);
303

304 305 306
        if ($tableOptions['TABLE_COLLATION'] !== null) {
            $table->addOption('collation', $tableOptions['TABLE_COLLATION']);
        }
307

308 309 310
        if ($tableOptions['AUTO_INCREMENT'] !== null) {
            $table->addOption('autoincrement', $tableOptions['AUTO_INCREMENT']);
        }
311

312
        $table->addOption('comment', $tableOptions['TABLE_COMMENT']);
313
        $table->addOption('create_options', $this->parseCreateOptions($tableOptions['CREATE_OPTIONS']));
314

315 316
        return $table;
    }
317

318
    /**
319
     * @return array<string, string>|array<string, true>
320
     */
321
    private function parseCreateOptions(?string $string) : array
322 323
    {
        $options = [];
324

325
        if ($string === null || $string === '') {
326 327
            return $options;
        }
328

329 330
        foreach (explode(' ', $string) as $pair) {
            $parts = explode('=', $pair, 2);
331

332
            $options[$parts[0]] = $parts[1] ?? true;
333 334
        }

335
        return $options;
336
    }
337
}