Passed
Push — master ( 52dcbe...46e258 )
by Aleksandr
02:20
created

MigrationTrait::_applyNewIndex()   C

Complexity

Conditions 11
Paths 66

Size

Total Lines 29
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 21
nc 66
nop 2
dl 0
loc 29
rs 5.2653
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
4
namespace carono\yii2migrate\traits;
5
6
use carono\yii2migrate\ForeignKeyColumn;
7
use carono\yii2migrate\PivotColumn;
8
use yii\db\ColumnSchema;
9
use yii\db\ColumnSchemaBuilder;
10
use yii\db\Migration;
11
use yii\db\Schema;
12
use yii\helpers\ArrayHelper;
13
use yii\helpers\StringHelper;
14
15
/**
16
 * Trait MigrationTrait
17
 *
18
 * @package carono\yii2migrate\traits
19
 * @mixin Migration
20
 */
21
trait MigrationTrait
22
{
23
24
    /**
25
     * @param      $refTable
26
     * @param null $refColumn
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $length is correct as it would always require null to be passed?
Loading history...
Documentation Bug introduced by
Are you sure the doc-type for parameter $refColumn is correct as it would always require null to be passed?
Loading history...
27
     *
28
     * @param string $type
29
     * @param null $length
30
     * @return ForeignKeyColumn
31
     */
32
    public function foreignKey($refTable = null, $refColumn = null, $type = Schema::TYPE_INTEGER, $length = null)
33
    {
34
        return (new ForeignKeyColumn($type, $length))->refTable($refTable)->refColumn($refColumn)->setMigrate($this);
35
    }
36
37
38
    /**
39
     * @param null $refTable
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $refTable is correct as it would always require null to be passed?
Loading history...
Documentation Bug introduced by
Are you sure the doc-type for parameter $refColumn is correct as it would always require null to be passed?
Loading history...
40
     * @param null $refColumn
41
     *
42
     * @return PivotColumn
43
     */
44
    public function pivot($refTable = null, $refColumn = null)
45
    {
46
        return (new PivotColumn())->refTable($refTable)->refColumn($refColumn)->setMigrate($this);
47
    }
48
49
    /**
50
     * @param string $name
51
     * @param string $table
52
     * @param array|string $columns
53
     * @param bool $unique
54
     */
55
    public function createIndex($name, $table, $columns, $unique = false)
56
    {
57
        $suffix = $unique ? "unq" : "idx";
58
        if (is_null($name)) {
0 ignored issues
show
introduced by
The condition is_null($name) can never be true.
Loading history...
59
            $name = self::formIndexName($table, $columns, $suffix);
60
            $name = $this->expandTablePrefix($name);
61
        }
62
        $name = self::truncateName($name, 64, '_' . $suffix);
63
        return parent::createIndex($name, $table, $columns, $unique);
64
    }
65
66
    /**
67
     * @param ColumnSchema $column
68
     * @return $this|ColumnSchemaBuilder
69
     * @throws \Exception
70
     */
71
    public function columnSchemaToBuilder(ColumnSchema $column)
72
    {
73
        $size = $column->size;
74
        $precision = $column->precision;
75
        $default = $column->defaultValue;
76
        $scale = $column->scale;
77
        if ($column->isPrimaryKey && $column->autoIncrement) {
78
            return $this->primaryKey();
0 ignored issues
show
Bug introduced by
It seems like primaryKey() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

78
            return $this->/** @scrutinizer ignore-call */ primaryKey();
Loading history...
79
        }
80
        switch ($column->type) {
81
            case "string":
82
                $builder = $this->string($size);
0 ignored issues
show
Bug introduced by
It seems like string() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

82
                /** @scrutinizer ignore-call */ 
83
                $builder = $this->string($size);
Loading history...
83
                break;
84
            case "integer":
85
                $builder = $this->integer($size);
0 ignored issues
show
Bug introduced by
It seems like integer() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

85
                /** @scrutinizer ignore-call */ 
86
                $builder = $this->integer($size);
Loading history...
86
                break;
87
            case "datetime":
88
                $builder = $this->dateTime($precision);
0 ignored issues
show
Bug introduced by
It seems like dateTime() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

88
                /** @scrutinizer ignore-call */ 
89
                $builder = $this->dateTime($precision);
Loading history...
89
                break;
90
            case "text":
91
                $builder = $this->text();
0 ignored issues
show
Bug introduced by
It seems like text() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

91
                /** @scrutinizer ignore-call */ 
92
                $builder = $this->text();
Loading history...
92
                break;
93
            case "smallint":
94
                if ($size === 1) {
95
                    $default = (boolean)$default;
96
                    $builder = $this->boolean();
0 ignored issues
show
Bug introduced by
It seems like boolean() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

96
                    /** @scrutinizer ignore-call */ 
97
                    $builder = $this->boolean();
Loading history...
97
                } else {
98
                    $builder = $this->smallInteger($size);
0 ignored issues
show
Bug introduced by
It seems like smallInteger() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

98
                    /** @scrutinizer ignore-call */ 
99
                    $builder = $this->smallInteger($size);
Loading history...
99
                }
100
                break;
101
            case "binary":
102
                $builder = $this->binary()->defaultValue($default);
0 ignored issues
show
Bug introduced by
It seems like binary() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

102
                $builder = $this->/** @scrutinizer ignore-call */ binary()->defaultValue($default);
Loading history...
103
                break;
104
            case "decimal":
105
                $builder = $this->decimal($precision, $scale);
0 ignored issues
show
Bug introduced by
It seems like decimal() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

105
                /** @scrutinizer ignore-call */ 
106
                $builder = $this->decimal($precision, $scale);
Loading history...
106
                break;
107
            case "double":
108
                $builder = $this->double($precision)->defaultValue($default);
0 ignored issues
show
Bug introduced by
It seems like double() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

108
                $builder = $this->/** @scrutinizer ignore-call */ double($precision)->defaultValue($default);
Loading history...
109
                break;
110
            default:
111
                throw new \Exception("Column ($column->name) type '$column->type' not recognized");
112
        }
113
        $builder->defaultValue($default);
114
        if (!$column->allowNull) {
115
            $builder->notNull();
116
        }
117
        $builder->comment($column->comment);
118
        return $builder;
119
    }
120
121
    /**
122
     * @param $name
123
     * @return mixed
124
     */
125
    public function expandTablePrefix($name)
126
    {
127
        return self::setTablePrefix($name, $this->db->tablePrefix);
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on carono\yii2migrate\traits\MigrationTrait. Did you maybe forget to declare it?
Loading history...
128
    }
129
130
    /**
131
     * @param $name
132
     * @param $prefix
133
     * @return mixed
134
     * @internal param $prefix
135
     */
136
    public static function setTablePrefix($name, $prefix)
137
    {
138
        return preg_replace('#{{%([\w\d\-_]+)}}#', $prefix . "$1", $name);
139
    }
140
141
    /**
142
     * @param string $table
143
     * @param array $columns
144
     * @param null $options
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $options is correct as it would always require null to be passed?
Loading history...
145
     */
146
    public function createTable($table, $columns, $options = null)
147
    {
148
        /**
149
         * @var PivotColumn[] $pvs
150
         * @var ForeignKeyColumn[] $fks
151
         */
152
        echo "    > create table $table ...";
153
        $time = microtime(true);
154
        $pvs = [];
155
        $fks = [];
156
        $pks = [];
157
        foreach ($columns as $column => &$type) {
158
            if ($type instanceof ColumnSchema) {
159
                $column = is_numeric($column) ? $type->name : $column;
160
                $type = $this->columnSchemaToBuilder($type);
161
            }
162
            if ((string)$type == (string)$this->primaryKey()) {
163
                $pks[] = $column;
164
            }
165
            if ($type instanceof ForeignKeyColumn) {
166
                $type->sourceTable($table)->sourceColumn($column);
167
                $fks[] = $type;
168
            }
169
170
            if ($type instanceof PivotColumn) {
171
                $type->setName($column)->sourceTable($table);
172
                $pvs[] = $type;
173
                unset($columns[$column]);
174
            }
175
        }
176
        if (count($pks) > 1) {
177
            foreach ($columns as $column => &$type) {
178
                $type = $this->integer();
179
            }
180
        }
181
        $this->db->createCommand()->createTable($table, $columns, $options)->execute();
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on carono\yii2migrate\traits\MigrationTrait. Did you maybe forget to declare it?
Loading history...
182
        foreach ($columns as $column => $type) {
183
            if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
184
                $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
185
            }
186
        }
187
        foreach ($fks as $fk) {
188
            $fk->apply();
189
        }
190
        if (count($pks) > 1) {
191
            $this->addPrimaryKey(null, $table, $pks);
192
        }
193
        foreach ($pvs as $pv) {
194
            $pv->apply();
195
        }
196
        echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
197
    }
198
199
    /**
200
     * @param string $name
201
     * @param string $table
202
     * @param array|string $columns
203
     * @param string $refTable
204
     * @param array|string $refColumns
205
     * @param null $delete
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $update is correct as it would always require null to be passed?
Loading history...
Documentation Bug introduced by
Are you sure the doc-type for parameter $delete is correct as it would always require null to be passed?
Loading history...
206
     * @param null $update
207
     */
208
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
209
    {
210
        if (is_null($name)) {
0 ignored issues
show
introduced by
The condition is_null($name) can never be true.
Loading history...
211
            $name = self::formFkName($table, $columns, $refTable, $refColumns);
212
            $name = $this->expandTablePrefix($name);
213
        }
214
        $name = self::truncateName($name, 64, '_fk');
215
        return parent::addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
216
    }
217
218
    /**
219
     * @inheritdoc
220
     */
221
    public function alterColumn($table, $column, $type)
222
    {
223
        if ($type instanceof ForeignKeyColumn) {
224
            $type->sourceTable($table);
225
            $type->sourceColumn($column);
226
            $type->apply();
227
        } else {
228
            return parent::alterColumn($table, $column, $type);
229
        }
230
    }
231
232
    /**
233
     * @param string $table
234
     * @param string $column
235
     * @param string $type
236
     * @return void
237
     */
238
    public function addColumn($table, $column, $type)
239
    {
240
        if ($type instanceof ForeignKeyColumn) {
0 ignored issues
show
introduced by
The condition $type instanceof carono\...igrate\ForeignKeyColumn can never be true since $type is never a sub-type of carono\yii2migrate\ForeignKeyColumn.
Loading history...
241
            parent::addColumn($table, $column, $type);
242
            $type->sourceTable($table);
243
            $type->sourceColumn($column);
244
            $type->apply();
245
        } else {
246
            parent::addColumn($table, $column, $type);
247
        }
248
    }
249
250
    /**
251
     * @param string $name
252
     * @param string $table
253
     * @param array|string $columns
254
     */
255
    public function addPrimaryKey($name, $table, $columns)
256
    {
257
        if (is_null($name)) {
0 ignored issues
show
introduced by
The condition is_null($name) can never be true.
Loading history...
258
            $name = self::formIndexName($table, $columns, 'pk');
259
            $name = $this->expandTablePrefix($name);
260
        }
261
        $name = self::truncateName($name, 64, '_pk');
262
        return parent::addPrimaryKey($name, $table, $columns);
263
    }
264
265
    /**
266
     * @return array
267
     */
268
    public function newColumns()
269
    {
270
        return [];
271
    }
272
273
    /**
274
     * @param array $array
275
     */
276
    public function downNewColumns($array = [])
277
    {
278
        $this->_applyNewColumns($array ? $array : $this->newColumns(), true);
279
    }
280
281
    /**
282
     * @param array $array
283
     */
284
    public function upNewColumns($array = [])
285
    {
286
        $this->_applyNewColumns($array ? $array : $this->newColumns(), false);
287
    }
288
289
    /**
290
     * @param array $columns
291
     * @param bool $revert
292
     */
293
    protected function _applyNewColumns($columns = [], $revert = false)
294
    {
295
        $columns = $revert ? array_reverse($columns) : $columns;
296
297
        $result = [];
298
        foreach ($columns as $key => $column) {
299
            if (is_numeric($key)) {
300
                $result[] = $column;
301
            } else {
302
                foreach ($column as $columnName => $value) {
303
                    $result[] = [$key, $columnName, $value];
304
                }
305
            }
306
        }
307
308
        foreach ($result as $column) {
309
            if ($column[2] instanceof PivotColumn) {
310
                $column[2]->setName($column[1])->sourceTable($column[0]);
311
            }
312
            if ($revert) {
313
                if ($column[2] instanceof PivotColumn) {
314
                    $column[2]->remove();
315
                    continue;
316
                }
317
                $this->dropColumn($column[0], $column[1], $column[2]);
318
            } else {
319
                if ($column[2] instanceof PivotColumn) {
320
                    $column[2]->apply();
321
                    continue;
322
                }
323
                $this->addColumn($column[0], $column[1], $column[2]);
324
            }
325
        }
326
    }
327
328
    /**
329
     * @param string $table
330
     * @param string $column
331
     * @param null $type
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $type is correct as it would always require null to be passed?
Loading history...
332
     */
333
    public function dropColumn($table, $column, $type = null)
334
    {
335
        if ($type instanceof ForeignKeyColumn) {
336
            $type->sourceTable($table);
337
            $type->sourceColumn($column);
338
            $type->remove();
339
        }
340
        return parent::dropColumn($table, $column);
341
    }
342
343
    /**
344
     * @return array
345
     */
346
    public function newTables()
347
    {
348
        return [];
349
    }
350
351
    /**
352
     * @param array $array
353
     * @param null $tableOptions
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $tableOptions is correct as it would always require null to be passed?
Loading history...
354
     */
355
    public function upNewTables($array = [], $tableOptions = null)
356
    {
357
        $this->_applyNewTables($array ? $array : $this->newTables(), false, $tableOptions);
358
    }
359
360
    /**
361
     * @param array $array
362
     */
363
    public function upNewIndex($array = [])
364
    {
365
        $this->_applyNewIndex($array ? $array : $this->newIndex());
366
    }
367
368
    /**
369
     * @param array $array
370
     */
371
    public function downNewIndex($array = [])
372
    {
373
        $this->_applyNewIndex($array ? $array : $this->newIndex(), true);
374
    }
375
376
    /**
377
     * @return array
378
     */
379
    public function newIndex()
380
    {
381
        return [];
382
    }
383
384
    /**
385
     * @param array $array
386
     */
387
    public function downNewTables($array = [])
388
    {
389
        $this->_applyNewTables($array ? $array : $this->newTables(), true);
390
    }
391
392
    /**
393
     * @param $indexes
394
     * @param bool $revert
395
     */
396
    protected function _applyNewIndex($indexes, $revert = false)
397
    {
398
        /**
399
         * @var ForeignKeyColumn $fk
400
         */
401
        $indexes = $revert ? array_reverse($indexes) : $indexes;
402
        foreach ($indexes as $key => $data) {
403
            $unq = isset($data[2]) && $data[2];
404
            $columns = is_array($data[1]) ? $data[1] : explode(',', $data[1]);
405
            $table = $data[0];
406
            $fk = null;
407
            if (isset($data[2]) && $data[2] instanceof ForeignKeyColumn) {
408
                $fk = $data[2];
409
                $fk->sourceTable($table);
410
                $fk->sourceColumn($columns[0]);
411
            }
412
413
            $name = self::expandTablePrefix(self::formIndexName($data[0], $columns, $unq ? "unq" : "idx"));
0 ignored issues
show
Bug Best Practice introduced by
The method carono\yii2migrate\trait...it::expandTablePrefix() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

413
            /** @scrutinizer ignore-call */ 
414
            $name = self::expandTablePrefix(self::formIndexName($data[0], $columns, $unq ? "unq" : "idx"));
Loading history...
414
            if ($revert) {
415
                if ($fk) {
416
                    $fk->remove();
417
                } else {
418
                    $this->dropIndex($name, $data[0]);
0 ignored issues
show
Bug introduced by
The method dropIndex() does not exist on carono\yii2migrate\traits\MigrationTrait. Did you maybe mean dropIndexByColumn()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

418
                    $this->/** @scrutinizer ignore-call */ 
419
                           dropIndex($name, $data[0]);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
419
                }
420
            } else {
421
                if ($fk) {
422
                    $fk->apply();
423
                } else {
424
                    $this->createIndex($name, $data[0], join(',', $columns), $unq);
425
                }
426
            }
427
        }
428
    }
429
430
    protected function _applyNewTables($tables, $revert = false, $tableOptions = null)
431
    {
432
        $tables = $revert ? array_reverse($tables) : $tables;
433
        foreach ($tables as $table => $columns) {
434
            if ($revert) {
435
                foreach ($columns as $column => $type) {
436
                    if ($type instanceof PivotColumn) {
437
                        $type->setName($column)->sourceTable($table);
438
                        $type->remove();
439
                    }
440
                }
441
                $this->dropTable($table);
0 ignored issues
show
Bug introduced by
It seems like dropTable() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

441
                $this->/** @scrutinizer ignore-call */ 
442
                       dropTable($table);
Loading history...
442
            } else {
443
                $tableOptions = ArrayHelper::remove($columns, 'tableOptions', $tableOptions);
444
                $this->createTable($table, $columns, $tableOptions);
445
            }
446
        }
447
    }
448
449
    public static function formFkName($table, $column, $refTable, $refColumn)
450
    {
451
        $table = count(($t = explode('.', $table))) > 1 ? $t[1] : $t[0];
452
        $refTable = count(($t = explode('.', $refTable))) > 1 ? $t[1] : $t[0];
453
        return "{$table}[{$column}]_{$refTable}[{$refColumn}]_fk";
454
    }
455
456
    public static function formPkIndexName($table, $columns, $suffix = "pk")
457
    {
458
        return self::formIndexName($table, $columns, $suffix);
459
    }
460
461
    public static function formIndexName($table, $columns, $suffix = "idx")
462
    {
463
        $table = self::removeSchema($table);
464
        $column = join(':', array_map('trim', (array)$columns));
465
        return "{$table}:{$column}_$suffix";
466
    }
467
468
    public function insertTo($table, $rows, $idStart = 1, $updateSeq = 'id')
469
    {
470
        $c = $idStart;
471
        foreach ($rows as $row) {
472
            if (!isset($row["id"]) && !is_null($idStart)) {
473
                $row += ["id" => $c++];
474
            }
475
            $this->insert($table, $row);
0 ignored issues
show
Bug introduced by
The method insert() does not exist on carono\yii2migrate\traits\MigrationTrait. Did you maybe mean insertTo()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

475
            $this->/** @scrutinizer ignore-call */ 
476
                   insert($table, $row);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
476
        }
477
        if ($updateSeq) {
478
            $c = (int)\Yii::$app->db->createCommand("SELECT count(*) FROM {{$table}}")->queryScalar() + 1;
479
            $this->execute("ALTER SEQUENCE {$table}_{$updateSeq}_seq RESTART WITH $c;");
0 ignored issues
show
Bug introduced by
It seems like execute() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

479
            $this->/** @scrutinizer ignore-call */ 
480
                   execute("ALTER SEQUENCE {$table}_{$updateSeq}_seq RESTART WITH $c;");
Loading history...
480
        }
481
    }
482
483
    public static function removeSchema($str)
484
    {
485
        if (strpos($str, '.') !== false) {
486
            $arr = explode('.', $str);
487
            return $arr[1];
488
        } else {
489
            return $str;
490
        }
491
    }
492
493
    /**
494
     * @param $table
495
     * @param $column
496
     * @return false|null|string
497
     */
498
    protected function getForeignKey($table, $column)
499
    {
500
        $condition = [':t' => $this->expandTablePrefix($table), ':c' => $column];
501
        $sql = "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME=:t AND COLUMN_NAME=:c";
502
        if ($this->db->driverName == 'mysql') {
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on carono\yii2migrate\traits\MigrationTrait. Did you maybe forget to declare it?
Loading history...
503
            $sql .= ' AND CONSTRAINT_SCHEMA=DATABASE()';
504
        }
505
        return $this->db->createCommand($sql, $condition)->queryScalar();
506
    }
507
508
    protected function getIndexName($table, $column)
509
    {
510
        $condition = [':t' => $this->expandTablePrefix($table), ':c' => $column];
511
512
        if ($this->db->driverName == 'pgsql') {
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on carono\yii2migrate\traits\MigrationTrait. Did you maybe forget to declare it?
Loading history...
513
            $sql = <<<SQL
514
SELECT
515
	i.relname
516
FROM
517
	pg_class T,
518
	pg_class i,
519
	pg_index ix,
520
	pg_attribute A
521
WHERE
522
	T .oid = ix.indrelid
523
AND i.oid = ix.indexrelid
524
AND A .attrelid = T .oid
525
AND A .attnum = ANY (ix.indkey)
526
AND T .relname = :t
527
AND A .attname = :c
528
SQL;
529
        } else {
530
            $sql = "SELECT DISTINCT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME=:t AND COLUMN_NAME=:c AND CONSTRAINT_SCHEMA=DATABASE()";
531
        }
532
        return $this->db->createCommand($sql, $condition)->queryScalar();
533
    }
534
535
    /**
536
     * @param $table
537
     * @param $column
538
     */
539
    public function dropIndexByColumn($table, $column)
540
    {
541
        if ($key = $this->getIndexName($table, $column)) {
542
            $this->dropIndex($key, $table);
543
        }
544
    }
545
546
    /**
547
     * @param $table
548
     * @param $column
549
     */
550
    public function dropForeignKeyByColumn($table, $column)
551
    {
552
        if ($key = $this->getForeignKey($table, $column)) {
553
            $this->dropForeignKey($key, $table);
0 ignored issues
show
Bug introduced by
The method dropForeignKey() does not exist on carono\yii2migrate\traits\MigrationTrait. Did you maybe mean dropForeignKeyByColumn()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

553
            $this->/** @scrutinizer ignore-call */ 
554
                   dropForeignKey($key, $table);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
554
        }
555
    }
556
557
    /**
558
     * Принудительно обрезаем названия ключей, если они получаются больше чем $length, т.к. базы могут вылететь с ошибкой
559
     *
560
     * @see https://dev.mysql.com/doc/refman/5.7/en/identifiers.html
561
     *
562
     * @param $name
563
     * @param int $length
564
     * @param null $suffix
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $suffix is correct as it would always require null to be passed?
Loading history...
565
     * @return bool|string
566
     */
567
    public static function truncateName($name, $length = 64, $suffix = null)
568
    {
569
        if (strlen($name) > $length) {
570
            if (StringHelper::endsWith($name, $suffix)) {
571
                $name = substr($name, 0, strlen($suffix) * -1);
572
            }
573
            return dechex(crc32($name)) . $suffix;
574
        } else {
575
            return $name;
576
        }
577
    }
578
}