MySqlSchemaManager.php 10.1 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
        $dbType = strtok($dbType, '(), ');
112
        $length = $tableColumn['length'] ?? strtok('(), ');
Benjamin Morel's avatar
Benjamin Morel committed
113

114
        $fixed = null;
115 116 117 118

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

belgattitude's avatar
belgattitude committed
120
        $scale     = null;
121
        $precision = null;
122

123
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
124 125 126

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

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

176
        if ($this->_platform instanceof MariaDb1027Platform) {
177
            $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
178
        } else {
179
            $columnDefault = $tableColumn['default'];
180
        }
181

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

196
        if ($scale !== null && $precision !== null) {
belgattitude's avatar
belgattitude committed
197
            $options['scale']     = (int) $scale;
198
            $options['precision'] = (int) $precision;
199 200
        }

201 202 203 204 205 206 207
        $column = new Column($tableColumn['field'], Type::getType($type), $options);

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

        return $column;
208 209
    }

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

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

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

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

292
        return $result;
romanb's avatar
romanb committed
293
    }
294
}