MySqlSchemaManager.php 10.2 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 25
use Doctrine\DBAL\Types\Type;

romanb's avatar
romanb committed
26
/**
27
 * Schema manager for the MySql RDBMS.
romanb's avatar
romanb committed
28
 *
Benjamin Morel's avatar
Benjamin Morel committed
29 30 31 32 33
 * @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
34
 */
35
class MySqlSchemaManager extends AbstractSchemaManager
36
{
Benjamin Morel's avatar
Benjamin Morel committed
37 38 39
    /**
     * {@inheritdoc}
     */
40 41
    protected function _getPortableViewDefinition($view)
    {
42
        return new View($view['TABLE_NAME'], $view['VIEW_DEFINITION']);
43 44
    }

Benjamin Morel's avatar
Benjamin Morel committed
45 46 47
    /**
     * {@inheritdoc}
     */
48 49
    protected function _getPortableTableDefinition($table)
    {
50
        return array_shift($table);
51 52
    }

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

Benjamin Morel's avatar
Benjamin Morel committed
64 65 66
    /**
     * {@inheritdoc}
     */
belgattitude's avatar
belgattitude committed
67
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
68
    {
Steve Müller's avatar
Steve Müller committed
69
        foreach ($tableIndexes as $k => $v) {
70
            $v = array_change_key_case($v, CASE_LOWER);
71
            if ($v['key_name'] === 'PRIMARY') {
72 73 74 75
                $v['primary'] = true;
            } else {
                $v['primary'] = false;
            }
76
            if (strpos($v['index_type'], 'FULLTEXT') !== false) {
77
                $v['flags'] = ['FULLTEXT'];
78
            } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
79
                $v['flags'] = ['SPATIAL'];
80
            }
81
            $tableIndexes[$k] = $v;
82
        }
83

84
        return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
85 86
    }

Benjamin Morel's avatar
Benjamin Morel committed
87 88 89
    /**
     * {@inheritdoc}
     */
90 91 92 93 94
    protected function _getPortableSequenceDefinition($sequence)
    {
        return end($sequence);
    }

Benjamin Morel's avatar
Benjamin Morel committed
95 96 97
    /**
     * {@inheritdoc}
     */
98 99
    protected function _getPortableDatabaseDefinition($database)
    {
100
        return $database['Database'];
101
    }
102

103
    /**
Benjamin Morel's avatar
Benjamin Morel committed
104
     * {@inheritdoc}
105
     */
106 107
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
108 109 110
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);

        $dbType = strtolower($tableColumn['type']);
111 112 113 114 115 116
        $dbType = strtok($dbType, '(), ');
        if (isset($tableColumn['length'])) {
            $length = $tableColumn['length'];
        } else {
            $length = strtok('(), ');
        }
Benjamin Morel's avatar
Benjamin Morel committed
117

118
        $fixed = null;
119 120 121 122

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

belgattitude's avatar
belgattitude committed
124
        $scale     = null;
125
        $precision = null;
126

127
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
128 129 130

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

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

180
        if ($this->_platform instanceof MariaDb1027Platform) {
181
            $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
182
        } else {
183
            $columnDefault = $tableColumn['default'];
184
        }
185

186
        $options = [
belgattitude's avatar
belgattitude committed
187
            'length'        => $length !== null ? (int) $length : null,
188
            'unsigned'      => strpos($tableColumn['type'], 'unsigned') !== false,
189
            'fixed'         => (bool) $fixed,
190
            'default'       => $columnDefault,
belgattitude's avatar
belgattitude committed
191
            'notnull'       => $tableColumn['null'] !== 'YES',
192 193
            'scale'         => null,
            'precision'     => null,
194
            'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
195 196 197
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
                ? $tableColumn['comment']
                : null,
198
        ];
199

200
        if ($scale !== null && $precision !== null) {
belgattitude's avatar
belgattitude committed
201
            $options['scale']     = (int) $scale;
202
            $options['precision'] = (int) $precision;
203 204
        }

205 206 207 208 209 210 211
        $column = new Column($tableColumn['field'], Type::getType($type), $options);

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

        return $column;
212 213
    }

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

Benjamin Morel's avatar
Benjamin Morel committed
253 254 255
    /**
     * {@inheritdoc}
     */
256
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
romanb's avatar
romanb committed
257
    {
258
        $list = [];
Benjamin Morel's avatar
Benjamin Morel committed
259
        foreach ($tableForeignKeys as $value) {
260
            $value = array_change_key_case($value, CASE_LOWER);
belgattitude's avatar
belgattitude committed
261 262
            if ( ! isset($list[$value['constraint_name']])) {
                if ( ! isset($value['delete_rule']) || $value['delete_rule'] === "RESTRICT") {
263 264
                    $value['delete_rule'] = null;
                }
belgattitude's avatar
belgattitude committed
265
                if ( ! isset($value['update_rule']) || $value['update_rule'] === "RESTRICT") {
266 267
                    $value['update_rule'] = null;
                }
268

269
                $list[$value['constraint_name']] = [
270
                    'name' => $value['constraint_name'],
271 272
                    'local' => [],
                    'foreign' => [],
273 274 275
                    'foreignTable' => $value['referenced_table_name'],
                    'onDelete' => $value['delete_rule'],
                    'onUpdate' => $value['update_rule'],
276
                ];
277
            }
belgattitude's avatar
belgattitude committed
278
            $list[$value['constraint_name']]['local'][]   = $value['column_name'];
279
            $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
280
        }
281

282
        $result = [];
Steve Müller's avatar
Steve Müller committed
283
        foreach ($list as $constraint) {
284
            $result[] = new ForeignKeyConstraint(
belgattitude's avatar
belgattitude committed
285 286 287 288
                array_values($constraint['local']),
                $constraint['foreignTable'],
                array_values($constraint['foreign']),
                $constraint['name'],
289
                [
290 291
                    'onDelete' => $constraint['onDelete'],
                    'onUpdate' => $constraint['onUpdate'],
292
                ]
293
            );
294
        }
295

296
        return $result;
romanb's avatar
romanb committed
297
    }
298
}