Completed
Pull Request — master (#1284)
by
unknown
01:44
created

SQLiteAdapter::migrateTriggers()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 12
nc 2
nop 2
crap 2
1
<?php
2
/**
3
 * Phinx
4
 *
5
 * (The MIT license)
6
 * Copyright (c) 2015 Rob Morgan
7
 *
8
 * Permission is hereby granted, free of charge, to any person obtaining a copy
9
 * of this software and associated * documentation files (the "Software"), to
10
 * deal in the Software without restriction, including without limitation the
11
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
12
 * sell copies of the Software, and to permit persons to whom the Software is
13
 * furnished to do so, subject to the following conditions:
14
 *
15
 * The above copyright notice and this permission notice shall be included in
16
 * all copies or substantial portions of the Software.
17
 *
18
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24
 * IN THE SOFTWARE.
25
 *
26
 * @package    Phinx
27
 * @subpackage Phinx\Db\Adapter
28
 */
29
namespace Phinx\Db\Adapter;
30
31
use Phinx\Db\Table;
32
use Phinx\Db\Table\Column;
33
use Phinx\Db\Table\ForeignKey;
34
use Phinx\Db\Table\Index;
35
36
/**
37
 * Phinx SQLite Adapter.
38
 *
39
 * @author Rob Morgan <[email protected]>
40
 * @author Richard McIntyre <[email protected]>
41
 */
42
class SQLiteAdapter extends PdoAdapter implements AdapterInterface
43
{
44
    protected $definitionsWithLimits = [
45
        'CHARACTER',
46
        'VARCHAR',
47
        'VARYING CHARACTER',
48
        'NCHAR',
49
        'NATIVE CHARACTER',
50
        'NVARCHAR'
51
    ];
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 42
    public function connect()
57
    {
58 42
        if ($this->connection === null) {
59 42
            if (!class_exists('PDO') || !in_array('sqlite', \PDO::getAvailableDrivers(), true)) {
60
                // @codeCoverageIgnoreStart
61
                throw new \RuntimeException('You need to enable the PDO_SQLITE extension for Phinx to run properly.');
62
                // @codeCoverageIgnoreEnd
63
            }
64
65 42
            $db = null;
66 42
            $options = $this->getOptions();
67
68
            // if port is specified use it, otherwise use the MySQL default
69 42
            if (isset($options['memory'])) {
70
                $dsn = 'sqlite::memory:';
71
            } else {
72 42
                $dsn = 'sqlite:' . $options['name'];
73 42
                if (file_exists($options['name'] . '.sqlite3')) {
74 42
                    $dsn = 'sqlite:' . $options['name'] . '.sqlite3';
75 42
                }
76
            }
77
78
            try {
79 42
                $db = new \PDO($dsn);
80 42
            } catch (\PDOException $exception) {
81
                throw new \InvalidArgumentException(sprintf(
82
                    'There was a problem connecting to the database: %s',
83
                    $exception->getMessage()
84
                ));
85
            }
86
87 42
            $this->setConnection($db);
88 42
        }
89 42
    }
90
91
    /**
92
     * {@inheritdoc}
93
     */
94 48
    public function disconnect()
95
    {
96 48
        $this->connection = null;
97 48
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function hasTransactions()
103
    {
104
        return true;
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110 1
    public function beginTransaction()
111
    {
112 1
        $this->execute('BEGIN TRANSACTION');
113 1
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118
    public function commitTransaction()
119
    {
120
        $this->execute('COMMIT');
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126
    public function rollbackTransaction()
127
    {
128
        $this->execute('ROLLBACK');
129
    }
130
131
    /**
132
     * {@inheritdoc}
133
     */
134 43
    public function quoteTableName($tableName)
135
    {
136 43
        return str_replace('.', '`.`', $this->quoteColumnName($tableName));
137
    }
138
139
    /**
140
     * {@inheritdoc}
141
     */
142 44
    public function quoteColumnName($columnName)
143
    {
144 44
        return '`' . str_replace('`', '``', $columnName) . '`';
145
    }
146
147
    /**
148
     * {@inheritdoc}
149
     */
150 42
    public function hasTable($tableName)
151
    {
152 42
        $tables = [];
153 42
        $rows = $this->fetchAll(sprintf('SELECT name FROM sqlite_master WHERE type=\'table\' AND name=\'%s\'', $tableName));
154 42
        foreach ($rows as $row) {
155 12
            $tables[] = strtolower($row[0]);
156 42
        }
157
158 42
        return in_array(strtolower($tableName), $tables);
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     */
164 42
    public function createTable(Table $table)
165
    {
166
        // Add the default primary key
167 42
        $columns = $table->getPendingColumns();
168 42
        $options = $table->getOptions();
169 42
        if (!isset($options['id']) || (isset($options['id']) && $options['id'] === true)) {
170 35
            $column = new Column();
171 35
            $column->setName('id')
172 35
                   ->setType('integer')
173 35
                   ->setIdentity(true);
174
175 35
            array_unshift($columns, $column);
176 42
        } elseif (isset($options['id']) && is_string($options['id'])) {
177
            // Handle id => "field_name" to support AUTO_INCREMENT
178 1
            $column = new Column();
179 1
            $column->setName($options['id'])
180 1
                   ->setType('integer')
181 1
                   ->setIdentity(true);
182
183 1
            array_unshift($columns, $column);
184 1
        }
185
186
        $sql = 'CREATE TABLE ';
187 42
        $sql .= $this->quoteTableName($table->getName()) . ' (';
188 42 View Code Duplication
        foreach ($columns as $column) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
189 42
            $sql .= $this->quoteColumnName($column->getName()) . ' ' . $this->getColumnSqlDefinition($column) . ', ';
190 42
        }
191 42
192
        // set the primary key(s)
193 View Code Duplication
        if (isset($options['primary_key'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
194 42
            $sql = rtrim($sql);
195 42
            $sql .= ' PRIMARY KEY (';
196 42
            if (is_string($options['primary_key'])) { // handle primary_key => 'id'
197 42
                $sql .= $this->quoteColumnName($options['primary_key']);
198 42
            } elseif (is_array($options['primary_key'])) { // handle primary_key => array('tag_id', 'resource_id')
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
199 42
                $sql .= implode(',', array_map([$this, 'quoteColumnName'], $options['primary_key']));
200
            }
201
            $sql .= ')';
202 1
        } else {
203 1
            $sql = substr(rtrim($sql), 0, -1); // no primary keys
204 1
        }
205
206 1
        // set the foreign keys
207 1
        $foreignKeys = $table->getForeignKeys();
208 1
        if (!empty($foreignKeys)) {
209 1
            foreach ($foreignKeys as $foreignKey) {
210 1
                $sql .= ', ' . $this->getForeignKeySqlDefinition($foreignKey);
211 1
            }
212 42
        }
213 42
214 37
        $sql = rtrim($sql) . ');';
215
        // execute the sql
216
        $this->execute($sql);
217
218 42
        foreach ($table->getIndexes() as $index) {
219 42
            $this->addIndex($table, $index);
220 1
        }
221 1
    }
222 1
223 1
    /**
224
     * {@inheritdoc}
225 42
     */
226
    public function renameTable($tableName, $newTableName)
227 42
    {
228
        $this->execute(sprintf('ALTER TABLE %s RENAME TO %s', $this->quoteTableName($tableName), $this->quoteTableName($newTableName)));
229 42
    }
230 6
231 42
    /**
232 42
     * {@inheritdoc}
233
     */
234
    public function dropTable($tableName)
235
    {
236
        $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tableName)));
237 1
    }
238
239 1
    /**
240 1
     * {@inheritdoc}
241
     */
242
    public function truncateTable($tableName)
243
    {
244
        $sql = sprintf(
245 1
            'DELETE FROM %s',
246
            $this->quoteTableName($tableName)
247 1
        );
248 1
249
        $this->execute($sql);
250
    }
251
252
    /**
253 1
     * {@inheritdoc}
254
     */
255 1
    public function getColumns($tableName)
256 1
    {
257 1
        $columns = [];
258 1
        $rows = $this->fetchAll(sprintf('pragma table_info(%s)', $this->quoteTableName($tableName)));
259
260 1
        foreach ($rows as $columnInfo) {
261 1
            $column = new Column();
262
            $type = strtolower($columnInfo['type']);
263
            $column->setName($columnInfo['name'])
264
                   ->setNull($columnInfo['notnull'] !== '1')
265
                   ->setDefault($columnInfo['dflt_value']);
266 1
267
            $phinxType = $this->getPhinxType($type);
268 1
            $column->setType($phinxType['name'])
269 1
                   ->setLimit($phinxType['limit']);
270
271 1
            if ($columnInfo['pk'] == 1) {
272 1
                $column->setIdentity(true);
273 1
            }
274 1
275 1
            $columns[] = $column;
276 1
        }
277
278 1
        return $columns;
279 1
    }
280 1
281
    /**
282 1
     * {@inheritdoc}
283 1
     */
284 1 View Code Duplication
    public function hasColumn($tableName, $columnName)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
285
    {
286 1
        $rows = $this->fetchAll(sprintf('pragma table_info(%s)', $this->quoteTableName($tableName)));
287 1
        foreach ($rows as $column) {
288
            if (strcasecmp($column['name'], $columnName) === 0) {
289 1
                return true;
290
            }
291
        }
292
293
        return false;
294
    }
295 8
296
    /**
297 8
     * {@inheritdoc}
298 8
     */
299 8 View Code Duplication
    public function addColumn(Table $table, Column $column)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
300 7
    {
301
        $sql = sprintf(
302 8
            'ALTER TABLE %s ADD COLUMN %s %s',
303
            $this->quoteTableName($table->getName()),
304 8
            $this->quoteColumnName($column->getName()),
305
            $this->getColumnSqlDefinition($column)
306
        );
307
308
        $this->execute($sql);
309
    }
310 4
311
    /**
312 4
     * {@inheritdoc}
313 4
     */
314 4
    public function renameColumn($tableName, $columnName, $newColumnName)
315 4
    {
316 4
        $tmpTableName = 'tmp_' . $tableName;
317 4
318
        $rows = $this->fetchAll('select * from sqlite_master where `type` = \'table\'');
319 4
320 4
        $sql = '';
321
        foreach ($rows as $table) {
322
            if ($table['tbl_name'] === $tableName) {
323
                $sql = $table['sql'];
324
            }
325 2
        }
326
327 2
        $columns = $this->fetchAll(sprintf('pragma table_info(%s)', $this->quoteTableName($tableName)));
328
        $selectColumns = [];
329 2
        $writeColumns = [];
330 View Code Duplication
        foreach ($columns as $column) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
331 2
            $selectName = $column['name'];
332 2
            $writeName = ($selectName == $columnName)? $newColumnName : $selectName;
333 2
            $selectColumns[] = $this->quoteColumnName($selectName);
334 2
            $writeColumns[] = $this->quoteColumnName($writeName);
335 2
        }
336 2
337 View Code Duplication
        if (!in_array($this->quoteColumnName($columnName), $selectColumns)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
338 2
            throw new \InvalidArgumentException(sprintf(
339 2
                'The specified column doesn\'t exist: ' . $columnName
340 2
            ));
341 2
        }
342 2
343 2
        $this->execute(sprintf('ALTER TABLE %s RENAME TO %s', $tableName, $tmpTableName));
344 2
345 2
        $sql = str_replace(
346 2
            $this->quoteColumnName($columnName),
347
            $this->quoteColumnName($newColumnName),
348 2
            $sql
349 1
        );
350
        $this->execute($sql);
351 1
352
        $sql = sprintf(
353
            'INSERT INTO %s(%s) SELECT %s FROM %s',
354 1
            $tableName,
355
            implode(', ', $writeColumns),
356 1
            implode(', ', $selectColumns),
357 1
            $tmpTableName
358 1
        );
359
360 1
        $this->execute($sql);
361 1
        $this->migrateTriggers($tmpTableName, $tableName);
362
        $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tmpTableName)));
363
    }
364 1
365 1
    /**
366 1
     * {@inheritdoc}
367 1
     */
368 1
    public function changeColumn($tableName, $columnName, Column $newColumn)
369
    {
370 1
        // TODO: DRY this up....
371
        $tmpTableName = 'tmp_' . $tableName;
372 1
373
        $rows = $this->fetchAll('select * from sqlite_master where `type` = \'table\'');
374 1
375 1
        $sql = '';
376
        foreach ($rows as $table) {
377
            if ($table['tbl_name'] === $tableName) {
378
                $sql = $table['sql'];
379
            }
380 6
        }
381
382
        $columns = $this->fetchAll(sprintf('pragma table_info(%s)', $this->quoteTableName($tableName)));
383
        $selectColumns = [];
384 6
        $writeColumns = [];
385 View Code Duplication
        foreach ($columns as $column) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
386 6
            $selectName = $column['name'];
387
            $writeName = ($selectName === $columnName)? $newColumn->getName() : $selectName;
388 6
            $selectColumns[] = $this->quoteColumnName($selectName);
389 6
            $writeColumns[] = $this->quoteColumnName($writeName);
390 6
        }
391 6
392 6 View Code Duplication
        if (!in_array($this->quoteColumnName($columnName), $selectColumns)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
393 6
            throw new \InvalidArgumentException(sprintf(
394
                'The specified column doesn\'t exist: ' . $columnName
395 6
            ));
396 6
        }
397 6
398 6
        $this->execute(sprintf('ALTER TABLE %s RENAME TO %s', $tableName, $tmpTableName));
399 6
400 6
        $sql = preg_replace(
401 6
            sprintf("/%s(?:\/\*.*?\*\/|\([^)]+\)|'[^']*?'|[^,])+([,)])/", $this->quoteColumnName($columnName)),
402 6
            sprintf('%s %s$1', $this->quoteColumnName($newColumn->getName()), $this->getColumnSqlDefinition($newColumn)),
403 6
            $sql,
404
            1
405 6
        );
406
407
        $this->execute($sql);
408
409
        $sql = sprintf(
410
            'INSERT INTO %s(%s) SELECT %s FROM %s',
411 6
            $tableName,
412
            implode(', ', $writeColumns),
413 6
            implode(', ', $selectColumns),
414 6
            $tmpTableName
415 6
        );
416 6
417
        $this->execute($sql);
418 6
        $this->migrateTriggers($tmpTableName, $tableName);
419
        $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tmpTableName)));
420 6
    }
421
422 6
    /**
423 6
     * {@inheritdoc}
424 6
     */
425 6
    public function dropColumn($tableName, $columnName)
426 6
    {
427
        // TODO: DRY this up....
428 6
        $tmpTableName = 'tmp_' . $tableName;
429
430 6
        $rows = $this->fetchAll('select * from sqlite_master where `type` = \'table\'');
431 6
432 6
        $sql = '';
433
        foreach ($rows as $table) {
434
            if ($table['tbl_name'] === $tableName) {
435
                $sql = $table['sql'];
436
            }
437 2
        }
438
439
        $rows = $this->fetchAll(sprintf('pragma table_info(%s)', $this->quoteTableName($tableName)));
440 2
        $columns = [];
441
        $columnType = null;
442 2
        foreach ($rows as $row) {
443
            if ($row['name'] !== $columnName) {
444 2
                $columns[] = $row['name'];
445 2
            } else {
446 2
                $found = true;
447 2
                $columnType = $row['type'];
448 2
            }
449 2
        }
450
451 2
        if (!isset($found)) {
452 2
            throw new \InvalidArgumentException(sprintf(
453 2
                'The specified column doesn\'t exist: ' . $columnName
454 2
            ));
455 2
        }
456 2
457 2
        $this->execute(sprintf('ALTER TABLE %s RENAME TO %s', $tableName, $tmpTableName));
458 2
459 2
        $sql = preg_replace(
460
            sprintf("/%s\s%s.*(,\s(?!')|\)$)/U", preg_quote($this->quoteColumnName($columnName)), preg_quote($columnType)),
461 2
            "",
462
            $sql
463 2
        );
464
465
        if (substr($sql, -2) === ', ') {
466
            $sql = substr($sql, 0, -2) . ')';
467
        }
468
469 2
        $this->execute($sql);
470
471 2
        $sql = sprintf(
472 2
            'INSERT INTO %s(%s) SELECT %s FROM %s',
473 2
            $tableName,
474
            implode(', ', $columns),
475 2
            implode(', ', $columns),
476
            $tmpTableName
477 2
        );
478 2
479 2
        $this->execute($sql);
480
        $this->migrateTriggers($tmpTableName, $tableName);
481 2
        $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tmpTableName)));
482
    }
483 2
484 2
    protected function migrateTriggers($oldTableName, $newTableName)
485 2
    {
486 2
        $rows = $this->fetchAll(sprintf(
487 2
            'select * from sqlite_master where type = "trigger" and tbl_name = "%s";',
488
            $oldTableName
489 2
        ));
490
491 2
        foreach ($rows as $row) {
492 2
            $newTrigger = preg_replace(
493 2
                sprintf('/%s/i', preg_quote($oldTableName)),
494
                $newTableName,
495
                $row['sql'],
496
                1
497
            );
498
499
            $this->execute(sprintf('DROP TRIGGER %s', $this->quoteTableName($row['name'])));
500
            $this->execute($newTrigger);
501 9
        }
502
    }
503 9
504 9
    /**
505
     * Get an array of indexes from a particular table.
506 9
     *
507 9
     * @param string $tableName Table Name
508 9
     * @return array
509 9
     */
510 9
    protected function getIndexes($tableName)
511 9
    {
512 9
        $indexes = [];
513 9
        $rows = $this->fetchAll(sprintf('pragma index_list(%s)', $tableName));
514 9
515 9
        foreach ($rows as $row) {
516
            $indexData = $this->fetchAll(sprintf('pragma index_info(%s)', $row['name']));
517
            if (!isset($indexes[$tableName])) {
518
                $indexes[$tableName] = ['index' => $row['name'], 'columns' => []];
519
            }
520
            foreach ($indexData as $indexItem) {
521 9
                $indexes[$tableName]['columns'][] = strtolower($indexItem['name']);
522
            }
523 9
        }
524 4
525 4
        return $indexes;
526
    }
527 9
528 9
    /**
529
     * {@inheritdoc}
530 9
     */
531 9 View Code Duplication
    public function hasIndex($tableName, $columns)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
532 9
    {
533 9
        if (is_string($columns)) {
534
            $columns = [$columns]; // str to array
535 8
        }
536
537 8
        $columns = array_map('strtolower', $columns);
538
        $indexes = $this->getIndexes($tableName);
539
540
        foreach ($indexes as $index) {
541
            $a = array_diff($columns, $index['columns']);
542
            if (empty($a)) {
543 1
                return true;
544
            }
545 1
        }
546
547 1
        return false;
548 1
    }
549 1
550
    /**
551
     * {@inheritdoc}
552
     */
553 View Code Duplication
    public function hasIndexByName($tableName, $indexName)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
554
    {
555
        $indexes = $this->getIndexes($tableName);
556
557
        foreach ($indexes as $index) {
558
            if ($indexName === $index['index']) {
559 8
                return true;
560
            }
561 8
        }
562 8
563 8
        return false;
564 8
    }
565 8
566 8
    /**
567 8
     * {@inheritdoc}
568 8
     */
569 8
    public function addIndex(Table $table, Index $index)
570 8
    {
571
        $indexColumnArray = [];
572 8
        foreach ($index->getColumns() as $column) {
573 8
            $indexColumnArray[] = sprintf('`%s` ASC', $column);
574 8
        }
575
        $indexColumns = implode(',', $indexColumnArray);
576
        $this->execute(
577
            sprintf(
578
                'CREATE %s ON %s (%s)',
579 1
                $this->getIndexSqlDefinition($table, $index),
580
                $this->quoteTableName($table->getName()),
581 1
                $indexColumns
582 1
            )
583 1
        );
584
    }
585 1
586 1
    /**
587
     * {@inheritdoc}
588 1
     */
589 1
    public function dropIndex($tableName, $columns)
590 1
    {
591 1
        if (is_string($columns)) {
592 1
            $columns = [$columns]; // str to array
593 1
        }
594 1
595 1
        $indexes = $this->getIndexes($tableName);
596 1
        $columns = array_map('strtolower', $columns);
597 1
598
        foreach ($indexes as $index) {
599
            $a = array_diff($columns, $index['columns']);
600
            if (empty($a)) {
601
                $this->execute(
602
                    sprintf(
603
                        'DROP INDEX %s',
604
                        $this->quoteColumnName($index['index'])
605 1
                    )
606
                );
607 1
608
                return;
609 1
            }
610 1
        }
611 1
    }
612 1
613 1
    /**
614 1
     * {@inheritdoc}
615 1
     */
616 1 View Code Duplication
    public function dropIndexByName($tableName, $indexName)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
617 1
    {
618
        $indexes = $this->getIndexes($tableName);
619
620
        foreach ($indexes as $index) {
621
            if ($indexName === $index['index']) {
622
                $this->execute(
623
                    sprintf(
624
                        'DROP INDEX %s',
625 5
                        $this->quoteColumnName($indexName)
626
                    )
627 5
                );
628
629
                return;
630 5
            }
631
        }
632 5
    }
633 5
634 5
    /**
635
     * {@inheritdoc}
636 1
     */
637
    public function hasForeignKey($tableName, $columns, $constraint = null)
638
    {
639
        if (is_string($columns)) {
640
            $columns = [$columns]; // str to array
641
        }
642
        $foreignKeys = $this->getForeignKeys($tableName);
643
644
        $a = array_diff($columns, $foreignKeys);
645 5
        if (empty($a)) {
646
            return true;
647 5
        }
648 5
649
        return false;
650
    }
651
652
    /**
653
     * Get an array of foreign keys from a particular table.
654
     *
655
     * @param string $tableName Table Name
656
     * @return array
657
     */
658
    protected function getForeignKeys($tableName)
659
    {
660
        $foreignKeys = [];
661 5
        $rows = $this->fetchAll(
662
            "SELECT sql, tbl_name
663 5
              FROM (
664 5
                    SELECT sql sql, type type, tbl_name tbl_name, name name
665 5
                      FROM sqlite_master
666 5
                     UNION ALL
667 5
                    SELECT sql, type, tbl_name, name
668 5
                      FROM sqlite_temp_master
669 5
                   )
670 5
             WHERE type != 'meta'
671 5
               AND sql NOTNULL
672 5
               AND name NOT LIKE 'sqlite_%'
673 5
             ORDER BY substr(type, 2, 1), name"
674
        );
675
676
        foreach ($rows as $row) {
677
            if ($row['tbl_name'] === $tableName) {
678
                if (strpos($row['sql'], 'REFERENCES') !== false) {
679 4
                    preg_match_all("/\(`([^`]*)`\) REFERENCES/", $row['sql'], $matches);
680
                    foreach ($matches[1] as $match) {
681
                        $foreignKeys[] = $match;
682 4
                    }
683
                }
684 4
            }
685 4
        }
686
687 4
        return $foreignKeys;
688 4
    }
689 4
690 4
    /**
691 4
     * {@inheritdoc}
692 4
     */
693
    public function addForeignKey(Table $table, ForeignKey $foreignKey)
694 4
    {
695 4
        // TODO: DRY this up....
696 4
        $this->execute('pragma foreign_keys = ON');
697 4
698 4
        $tmpTableName = 'tmp_' . $table->getName();
699
        $rows = $this->fetchAll('select * from sqlite_master where `type` = \'table\'');
700 4
701
        $sql = '';
702 4
        foreach ($rows as $row) {
703 4
            if ($row['tbl_name'] === $table->getName()) {
704
                $sql = $row['sql'];
705 4
            }
706 4
        }
707 4
708 4
        $rows = $this->fetchAll(sprintf('pragma table_info(%s)', $this->quoteTableName($table->getName())));
709 4
        $columns = [];
710 4
        foreach ($rows as $column) {
711 4
            $columns[] = $this->quoteColumnName($column['name']);
712
        }
713 4
714 4
        $this->execute(sprintf('ALTER TABLE %s RENAME TO %s', $this->quoteTableName($table->getName()), $tmpTableName));
715 4
716
        $sql = substr($sql, 0, -1) . ',' . $this->getForeignKeySqlDefinition($foreignKey) . ')';
717
        $this->execute($sql);
718
719
        $sql = sprintf(
720 1
            'INSERT INTO %s(%s) SELECT %s FROM %s',
721
            $this->quoteTableName($table->getName()),
722
            implode(', ', $columns),
723 1
            implode(', ', $columns),
724
            $this->quoteTableName($tmpTableName)
725
        );
726
727 1
        $this->execute($sql);
728
        $this->migrateTriggers($tmpTableName, $table->getName());
729 1
        $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tmpTableName)));
730
    }
731 1
732 1
    /**
733 1
     * {@inheritdoc}
734 1
     */
735 1
    public function dropForeignKey($tableName, $columns, $constraint = null)
736 1
    {
737
        // TODO: DRY this up....
738 1
        if (is_string($columns)) {
739 1
            $columns = [$columns]; // str to array
740 1
        }
741 1
742 1
        $tmpTableName = 'tmp_' . $tableName;
743 1
744 1
        $rows = $this->fetchAll('select * from sqlite_master where `type` = \'table\'');
745
746 1
        $sql = '';
747
        foreach ($rows as $table) {
748 1
            if ($table['tbl_name'] === $tableName) {
749
                $sql = $table['sql'];
750
            }
751
        }
752
753
        $rows = $this->fetchAll(sprintf('pragma table_info(%s)', $this->quoteTableName($tableName)));
754 1
        $replaceColumns = [];
755
        foreach ($rows as $row) {
756 1
            if (!in_array($row['name'], $columns)) {
757 1
                $replaceColumns[] = $row['name'];
758 1
            } else {
759 1
                $found = true;
760 1
            }
761 1
        }
762 1
763
        if (!isset($found)) {
764 1
            throw new \InvalidArgumentException(sprintf(
765
                'The specified column doesn\'t exist: '
766 1
            ));
767 1
        }
768 1
769 1
        $this->execute(sprintf('ALTER TABLE %s RENAME TO %s', $this->quoteTableName($tableName), $tmpTableName));
770 1
771
        foreach ($columns as $columnName) {
772 1
            $search = sprintf(
773
                "/,[^,]*\(%s(?:,`?(.*)`?)?\) REFERENCES[^,]*\([^\)]*\)[^,)]*/",
774 1
                $this->quoteColumnName($columnName)
775 1
            );
776 1
            $sql = preg_replace($search, '', $sql, 1);
777
        }
778
779
        $this->execute($sql);
780
781
        $sql = sprintf(
782
            'INSERT INTO %s(%s) SELECT %s FROM %s',
783
            $tableName,
784
            implode(', ', $columns),
785
            implode(', ', $columns),
786
            $tmpTableName
787
        );
788
789
        $this->execute($sql);
790
        $this->migrateTriggers($tmpTableName, $tableName);
791
        $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tmpTableName)));
792
    }
793
794
    /**
795
     * {@inheritdoc}
796
     */
797
    public function insert(Table $table, $row)
798
    {
799
        $sql = sprintf(
800
            "INSERT INTO %s ",
801
            $this->quoteTableName($table->getName())
802
        );
803
804
        $columns = array_keys($row);
805
        $sql .= "(" . implode(', ', array_map([$this, 'quoteColumnName'], $columns)) . ")";
806
        $sql .= " VALUES ";
807
808
        $sql .= "(" . implode(', ', array_map(function ($value) {
809
            if (is_numeric($value)) {
810 43
                return $value;
811
            }
812
813 43
            if ($value === null) {
814 42
                return 'null';
815
            }
816 43
817
                return $this->getConnection()->quote($value);
818
        }, $row)) . ")";
819 43
820 1
        $this->execute($sql);
821
    }
822 43
823 38
    /**
824
     * {@inheritdoc}
825 43
     */
826 42
    public function getSqlType($type, $limit = null)
827
    {
828 43
        switch ($type) {
829 2
            case static::PHINX_TYPE_STRING:
830
                return ['name' => 'varchar', 'limit' => 255];
831 43
            case static::PHINX_TYPE_CHAR:
832 1
                return ['name' => 'char', 'limit' => 255];
833
            case static::PHINX_TYPE_TEXT:
834 43
                return ['name' => 'text'];
835 1
            case static::PHINX_TYPE_INTEGER:
836
                return ['name' => 'integer'];
837 43
            case static::PHINX_TYPE_BIG_INTEGER:
838 42
                return ['name' => 'bigint'];
839
            case static::PHINX_TYPE_FLOAT:
840 43
                return ['name' => 'float'];
841 1
            case static::PHINX_TYPE_DECIMAL:
842
                return ['name' => 'decimal'];
843 43
            case static::PHINX_TYPE_DATETIME:
844 1
                return ['name' => 'datetime'];
845
            case static::PHINX_TYPE_TIMESTAMP:
846 43
                return ['name' => 'datetime'];
847 43
            case static::PHINX_TYPE_TIME:
848 1
                return ['name' => 'time'];
849
            case static::PHINX_TYPE_DATE:
850 43
                return ['name' => 'date'];
851 42
            case static::PHINX_TYPE_BLOB:
852
            case static::PHINX_TYPE_BINARY:
853 5
                return ['name' => 'blob'];
854
            case static::PHINX_TYPE_BOOLEAN:
855 5
                return ['name' => 'boolean'];
856 4
            case static::PHINX_TYPE_UUID:
857
                return ['name' => 'char', 'limit' => 36];
858
            case static::PHINX_TYPE_ENUM:
859
                return ['name' => 'enum'];
860 1
            // Geospatial database types
861 1
            // No specific data types exist in SQLite, instead all geospatial
862
            // functionality is handled in the client. See also: SpatiaLite.
863
            case static::PHINX_TYPE_GEOMETRY:
864 1
            case static::PHINX_TYPE_POLYGON:
865
                return ['name' => 'text'];
866
            case static::PHINX_TYPE_LINESTRING:
867 1
                return ['name' => 'varchar', 'limit' => 255];
868
            case static::PHINX_TYPE_POINT:
869 1
                return ['name' => 'float'];
870 1
            default:
871 1
                throw new \RuntimeException('The type: "' . $type . '" is not supported.');
872
        }
873
    }
874
875
    /**
876
     * Returns Phinx type by SQL type
877
     *
878
     * @param string $sqlTypeDef SQL type
879
     * @returns string Phinx type
880 3
     */
881
    public function getPhinxType($sqlTypeDef)
882 3
    {
883 1
        if (!preg_match('/^([\w]+)(\(([\d]+)*(,([\d]+))*\))*$/', $sqlTypeDef, $matches)) {
884
            throw new \RuntimeException('Column type ' . $sqlTypeDef . ' is not supported');
885 2
        } else {
886 2
            $limit = null;
887 2
            $precision = null;
888 2
            $type = $matches[1];
889 1
            if (count($matches) > 2) {
890 1
                $limit = $matches[3] ?: null;
891 2
            }
892
            if (count($matches) > 4) {
893
                $precision = $matches[5];
894 2
            }
895 2
            switch ($matches[1]) {
896 1
                case 'varchar':
897 1
                    $type = static::PHINX_TYPE_STRING;
898
                    if ($limit === 255) {
899
                        $limit = null;
900 1
                    }
901 2
                    break;
902 View Code Duplication
                case 'char':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
903
                    $type = static::PHINX_TYPE_CHAR;
904
                    if ($limit === 255) {
905
                        $limit = null;
906
                    }
907
                    if ($limit === 36) {
908
                        $type = static::PHINX_TYPE_UUID;
909
                    }
910 2
                    break;
911
                case 'int':
912
                    $type = static::PHINX_TYPE_INTEGER;
913
                    if ($limit === 11) {
914
                        $limit = null;
915
                    }
916 2
                    break;
917 1
                case 'bigint':
918
                    if ($limit === 11) {
919
                        $limit = null;
920 1
                    }
921 1
                    $type = static::PHINX_TYPE_BIG_INTEGER;
922 2
                    break;
923 1
                case 'blob':
924 1
                    $type = static::PHINX_TYPE_BINARY;
925 2
                    break;
926 2
            }
927 View Code Duplication
            if ($type === 'tinyint') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
928
                if ($matches[3] === 1) {
929
                    $type = static::PHINX_TYPE_BOOLEAN;
930
                    $limit = null;
931
                }
932
            }
933 2
934
            $this->getSqlType($type);
935
936 1
            return [
937 1
                'name' => $type,
938
                'limit' => $limit,
939 1
                'precision' => $precision
940
            ];
941
        }
942
    }
943
944
    /**
945
     * {@inheritdoc}
946 48
     */
947
    public function createDatabase($name, $options = [])
948 48
    {
949 48
        touch($name . '.sqlite3');
950
    }
951
952
    /**
953
     * {@inheritdoc}
954 2
     */
955
    public function hasDatabase($name)
956 2
    {
957
        return is_file($name . '.sqlite3');
958
    }
959
960
    /**
961
     * {@inheritdoc}
962 48
     */
963
    public function dropDatabase($name)
964 48
    {
965 47
        if (file_exists($name . '.sqlite3')) {
966 47
            unlink($name . '.sqlite3');
967 48
        }
968
    }
969
970
    /**
971
     * Get the definition for a `DEFAULT` statement.
972
     *
973
     * @param  mixed $default
974
     * @return string
975 42
     */
976 View Code Duplication
    protected function getDefaultValueDefinition($default)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
977 42
    {
978 8
        if (is_string($default) && 'CURRENT_TIMESTAMP' !== $default) {
979 42
            $default = $this->getConnection()->quote($default);
980 42
        } elseif (is_bool($default)) {
981 42
            $default = $this->castToBool($default);
982 42
        }
983
984
        return isset($default) ? ' DEFAULT ' . $default : '';
985
    }
986
987
    /**
988
     * Gets the SQLite Column Definition for a Column object.
989
     *
990
     * @param \Phinx\Db\Table\Column $column Column
991 42
     * @return string
992
     */
993 42
    protected function getColumnSqlDefinition(Column $column)
994 42
    {
995 42
        $sqlType = $this->getSqlType($column->getType());
996 42
        $def = '';
997
        $def .= strtoupper($sqlType['name']);
998 View Code Duplication
        if ($column->getPrecision() && $column->getScale()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
999 42
            $def .= '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
1000 42
        }
1001 42
        $limitable = in_array(strtoupper($sqlType['name']), $this->definitionsWithLimits);
1002 42
        if (($column->getLimit() || isset($sqlType['limit'])) && $limitable) {
1003 42
            $def .= '(' . ($column->getLimit() ?: $sqlType['limit']) . ')';
1004 4
        }
1005 4 View Code Duplication
        if (($values = $column->getValues()) && is_array($values)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1006
            $def .= " CHECK({$column->getName()} IN ('" . implode("', '", $values) . "'))";
1007 42
        }
1008
1009 42
        $default = $column->getDefault();
1010 42
1011 42
        $def .= ($column->isNull() || is_null($default)) ? ' NULL' : ' NOT NULL';
1012
        $def .= $this->getDefaultValueDefinition($default);
1013 42
        $def .= ($column->isIdentity()) ? ' PRIMARY KEY AUTOINCREMENT' : '';
1014
1015
        if ($column->getUpdate()) {
1016
            $def .= ' ON UPDATE ' . $column->getUpdate();
1017 42
        }
1018
1019 42
        $def .= $this->getCommentDefinition($column);
1020
1021
        return $def;
1022
    }
1023
1024
    /**
1025
     * Gets the comment Definition for a Column object.
1026
     *
1027
     * @param \Phinx\Db\Table\Column $column Column
1028 42
     * @return string
1029
     */
1030 42
    protected function getCommentDefinition(Column $column)
1031 2
    {
1032
        if ($column->getComment()) {
1033 42
            return ' /* ' . $column->getComment() . ' */ ';
1034
        }
1035
1036
        return '';
1037
    }
1038
1039
    /**
1040
     * Gets the SQLite Index Definition for an Index object.
1041
     *
1042 8
     * @param \Phinx\Db\Table $table Table
1043
     * @param \Phinx\Db\Table\Index $index Index
1044 8
     * @return string
1045 2
     */
1046 2
    protected function getIndexSqlDefinition(Table $table, Index $index)
1047 6
    {
1048
        if ($index->getType() === Index::UNIQUE) {
1049 8
            $def = 'UNIQUE INDEX';
1050 3
        } else {
1051 3
            $def = 'INDEX';
1052 6
        }
1053 6
        if (is_string($index->getName())) {
1054 6
            $indexName = $index->getName();
1055 6
        } else {
1056 6
            $indexName = $table->getName() . '_';
1057
            foreach ($index->getColumns() as $column) {
1058 8
                $indexName .= $column . '_';
1059 8
            }
1060
            $indexName .= 'index';
1061
        }
1062
        $def .= ' `' . $indexName . '`';
1063
1064
        return $def;
1065 47
    }
1066
1067 47
    /**
1068
     * {@inheritdoc}
1069
     */
1070
    public function getColumnTypes()
1071
    {
1072
        return array_merge(parent::getColumnTypes(), ['enum']);
1073
    }
1074
1075
    /**
1076 5
     * Gets the SQLite Foreign Key Definition for an ForeignKey object.
1077
     *
1078 5
     * @param \Phinx\Db\Table\ForeignKey $foreignKey
1079 5
     * @return string
1080
     */
1081 View Code Duplication
    protected function getForeignKeySqlDefinition(ForeignKey $foreignKey)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1082 5
    {
1083 5
        $def = '';
1084 5
        if ($foreignKey->getConstraint()) {
1085 5
            $def .= ' CONSTRAINT ' . $this->quoteColumnName($foreignKey->getConstraint());
0 ignored issues
show
Bug introduced by
It seems like $foreignKey->getConstraint() targeting Phinx\Db\Table\ForeignKey::getConstraint() can also be of type boolean; however, Phinx\Db\Adapter\SQLiteAdapter::quoteColumnName() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1086 5
        } else {
1087 5
            $columnNames = [];
1088 5
            foreach ($foreignKey->getColumns() as $column) {
1089 5
                $columnNames[] = $this->quoteColumnName($column);
1090 5
            }
1091 5
            $def .= ' FOREIGN KEY (' . implode(',', $columnNames) . ')';
1092 5
            $refColumnNames = [];
1093 1
            foreach ($foreignKey->getReferencedColumns() as $column) {
1094 1
                $refColumnNames[] = $this->quoteColumnName($column);
1095 5
            }
1096 1
            $def .= ' REFERENCES ' . $this->quoteTableName($foreignKey->getReferencedTable()->getName()) . ' (' . implode(',', $refColumnNames) . ')';
1097 1
            if ($foreignKey->getOnDelete()) {
1098
                $def .= ' ON DELETE ' . $foreignKey->getOnDelete();
1099 5
            }
1100
            if ($foreignKey->getOnUpdate()) {
1101
                $def .= ' ON UPDATE ' . $foreignKey->getOnUpdate();
1102
            }
1103
        }
1104
1105
        return $def;
1106
    }
1107
}
1108