Completed
Push — cache-closure ( 7d9053...380edd )
by Dmitry
35:54
created

Migration::printException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use yii\base\Component;
11
use yii\di\Instance;
12
13
/**
14
 * Migration is the base class for representing a database migration.
15
 *
16
 * Migration is designed to be used together with the "yii migrate" command.
17
 *
18
 * Each child class of Migration represents an individual database migration which
19
 * is identified by the child class name.
20
 *
21
 * Within each migration, the [[up()]] method should be overridden to contain the logic
22
 * for "upgrading" the database; while the [[down()]] method for the "downgrading"
23
 * logic. The "yii migrate" command manages all available migrations in an application.
24
 *
25
 * If the database supports transactions, you may also override [[safeUp()]] and
26
 * [[safeDown()]] so that if anything wrong happens during the upgrading or downgrading,
27
 * the whole migration can be reverted in a whole.
28
 *
29
 * Migration provides a set of convenient methods for manipulating database data and schema.
30
 * For example, the [[insert()]] method can be used to easily insert a row of data into
31
 * a database table; the [[createTable()]] method can be used to create a database table.
32
 * Compared with the same methods in [[Command]], these methods will display extra
33
 * information showing the method parameters and execution time, which may be useful when
34
 * applying migrations.
35
 *
36
 * For more details and usage information on Migration, see the [guide article on Migration](guide:db-migrations).
37
 *
38
 * @author Qiang Xue <[email protected]>
39
 * @since 2.0
40
 */
41
class Migration extends Component implements MigrationInterface
42
{
43
    use SchemaBuilderTrait;
44
45
    /**
46
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection
47
     * that this migration should work with. Starting from version 2.0.2, this can also be a configuration array
48
     * for creating the object.
49
     *
50
     * Note that when a Migration object is created by the `migrate` command, this property will be overwritten
51
     * by the command. If you do not want to use the DB connection provided by the command, you may override
52
     * the [[init()]] method like the following:
53
     *
54
     * ```php
55
     * public function init()
56
     * {
57
     *     $this->db = 'db2';
58
     *     parent::init();
59
     * }
60
     * ```
61
     */
62
    public $db = 'db';
63
64
65
    /**
66
     * Initializes the migration.
67
     * This method will set [[db]] to be the 'db' application component, if it is `null`.
68
     */
69 13
    public function init()
70
    {
71 13
        parent::init();
72 13
        $this->db = Instance::ensure($this->db, Connection::className());
73 13
        $this->db->getSchema()->refresh();
74 13
        $this->db->enableSlaves = false;
75 13
    }
76
77
    /**
78
     * @inheritdoc
79
     * @since 2.0.6
80
     */
81 1
    protected function getDb()
82
    {
83 1
        return $this->db;
84
    }
85
86
    /**
87
     * This method contains the logic to be executed when applying this migration.
88
     * Child classes may override this method to provide actual migration logic.
89
     * @return bool return a false value to indicate the migration fails
90
     * and should not proceed further. All other return values mean the migration succeeds.
91
     */
92
    public function up()
93
    {
94
        $transaction = $this->db->beginTransaction();
95
        try {
96
            if ($this->safeUp() === false) {
97
                $transaction->rollBack();
98
                return false;
99
            }
100
            $transaction->commit();
101
        } catch (\Exception $e) {
102
            $this->printException($e);
103
            $transaction->rollBack();
104
            return false;
105
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
106
            $this->printException($e);
107
            $transaction->rollBack();
108
            return false;
109
        }
110
111
        return null;
112
    }
113
114
    /**
115
     * This method contains the logic to be executed when removing this migration.
116
     * The default implementation throws an exception indicating the migration cannot be removed.
117
     * Child classes may override this method if the corresponding migrations can be removed.
118
     * @return bool return a false value to indicate the migration fails
119
     * and should not proceed further. All other return values mean the migration succeeds.
120
     */
121
    public function down()
122
    {
123
        $transaction = $this->db->beginTransaction();
124
        try {
125
            if ($this->safeDown() === false) {
126
                $transaction->rollBack();
127
                return false;
128
            }
129
            $transaction->commit();
130
        } catch (\Exception $e) {
131
            $this->printException($e);
132
            $transaction->rollBack();
133
            return false;
134
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
135
            $this->printException($e);
136
            $transaction->rollBack();
137
            return false;
138
        }
139
140
        return null;
141
    }
142
143
    /**
144
     * @param \Throwable|\Exception $e
145
     */
146
    private function printException($e)
147
    {
148
        echo 'Exception: ' . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
149
        echo $e->getTraceAsString() . "\n";
150
    }
151
152
    /**
153
     * This method contains the logic to be executed when applying this migration.
154
     * This method differs from [[up()]] in that the DB logic implemented here will
155
     * be enclosed within a DB transaction.
156
     * Child classes may implement this method instead of [[up()]] if the DB logic
157
     * needs to be within a transaction.
158
     * @return bool return a false value to indicate the migration fails
159
     * and should not proceed further. All other return values mean the migration succeeds.
160
     */
161
    public function safeUp()
162
    {
163
    }
164
165
    /**
166
     * This method contains the logic to be executed when removing this migration.
167
     * This method differs from [[down()]] in that the DB logic implemented here will
168
     * be enclosed within a DB transaction.
169
     * Child classes may implement this method instead of [[down()]] if the DB logic
170
     * needs to be within a transaction.
171
     * @return bool return a false value to indicate the migration fails
172
     * and should not proceed further. All other return values mean the migration succeeds.
173
     */
174
    public function safeDown()
175
    {
176
    }
177
178
    /**
179
     * Executes a SQL statement.
180
     * This method executes the specified SQL statement using [[db]].
181
     * @param string $sql the SQL statement to be executed
182
     * @param array $params input parameters (name => value) for the SQL execution.
183
     * See [[Command::execute()]] for more details.
184
     */
185
    public function execute($sql, $params = [])
186
    {
187
        echo "    > execute SQL: $sql ...";
188
        $time = microtime(true);
189
        $this->db->createCommand($sql)->bindValues($params)->execute();
190
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
191
    }
192
193
    /**
194
     * Creates and executes an INSERT SQL statement.
195
     * The method will properly escape the column names, and bind the values to be inserted.
196
     * @param string $table the table that new rows will be inserted into.
197
     * @param array $columns the column data (name => value) to be inserted into the table.
198
     */
199
    public function insert($table, $columns)
200
    {
201
        echo "    > insert into $table ...";
202
        $time = microtime(true);
203
        $this->db->createCommand()->insert($table, $columns)->execute();
204
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
205
    }
206
207
    /**
208
     * Creates and executes an batch INSERT SQL statement.
209
     * The method will properly escape the column names, and bind the values to be inserted.
210
     * @param string $table the table that new rows will be inserted into.
211
     * @param array $columns the column names.
212
     * @param array $rows the rows to be batch inserted into the table
213
     */
214
    public function batchInsert($table, $columns, $rows)
215
    {
216
        echo "    > insert into $table ...";
217
        $time = microtime(true);
218
        $this->db->createCommand()->batchInsert($table, $columns, $rows)->execute();
219
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
220
    }
221
222
    /**
223
     * Creates and executes an UPDATE SQL statement.
224
     * The method will properly escape the column names and bind the values to be updated.
225
     * @param string $table the table to be updated.
226
     * @param array $columns the column data (name => value) to be updated.
227
     * @param array|string $condition the conditions that will be put in the WHERE part. Please
228
     * refer to [[Query::where()]] on how to specify conditions.
229
     * @param array $params the parameters to be bound to the query.
230
     */
231
    public function update($table, $columns, $condition = '', $params = [])
232
    {
233
        echo "    > update $table ...";
234
        $time = microtime(true);
235
        $this->db->createCommand()->update($table, $columns, $condition, $params)->execute();
236
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
237
    }
238
239
    /**
240
     * Creates and executes a DELETE SQL statement.
241
     * @param string $table the table where the data will be deleted from.
242
     * @param array|string $condition the conditions that will be put in the WHERE part. Please
243
     * refer to [[Query::where()]] on how to specify conditions.
244
     * @param array $params the parameters to be bound to the query.
245
     */
246
    public function delete($table, $condition = '', $params = [])
247
    {
248
        echo "    > delete from $table ...";
249
        $time = microtime(true);
250
        $this->db->createCommand()->delete($table, $condition, $params)->execute();
251
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
252
    }
253
254
    /**
255
     * Builds and executes a SQL statement for creating a new DB table.
256
     *
257
     * The columns in the new  table should be specified as name-definition pairs (e.g. 'name' => 'string'),
258
     * where name stands for a column name which will be properly quoted by the method, and definition
259
     * stands for the column type which can contain an abstract DB type.
260
     *
261
     * The [[QueryBuilder::getColumnType()]] method will be invoked to convert any abstract type into a physical one.
262
     *
263
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
264
     * put into the generated SQL.
265
     *
266
     * @param string $table the name of the table to be created. The name will be properly quoted by the method.
267
     * @param array $columns the columns (name => definition) in the new table.
268
     * @param string $options additional SQL fragment that will be appended to the generated SQL.
269
     */
270 1
    public function createTable($table, $columns, $options = null)
271
    {
272 1
        echo "    > create table $table ...";
273 1
        $time = microtime(true);
274 1
        $this->db->createCommand()->createTable($table, $columns, $options)->execute();
275 1
        foreach ($columns as $column => $type) {
276 1
            if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
277
                $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
278
            }
279 1
        }
280 1
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
281 1
    }
282
283
    /**
284
     * Builds and executes a SQL statement for renaming a DB table.
285
     * @param string $table the table to be renamed. The name will be properly quoted by the method.
286
     * @param string $newName the new table name. The name will be properly quoted by the method.
287
     */
288
    public function renameTable($table, $newName)
289
    {
290
        echo "    > rename table $table to $newName ...";
291
        $time = microtime(true);
292
        $this->db->createCommand()->renameTable($table, $newName)->execute();
293
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
294
    }
295
296
    /**
297
     * Builds and executes a SQL statement for dropping a DB table.
298
     * @param string $table the table to be dropped. The name will be properly quoted by the method.
299
     */
300 1
    public function dropTable($table)
301
    {
302 1
        echo "    > drop table $table ...";
303 1
        $time = microtime(true);
304 1
        $this->db->createCommand()->dropTable($table)->execute();
305 1
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
306 1
    }
307
308
    /**
309
     * Builds and executes a SQL statement for truncating a DB table.
310
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
311
     */
312
    public function truncateTable($table)
313
    {
314
        echo "    > truncate table $table ...";
315
        $time = microtime(true);
316
        $this->db->createCommand()->truncateTable($table)->execute();
317
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
318
    }
319
320
    /**
321
     * Builds and executes a SQL statement for adding a new DB column.
322
     * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
323
     * @param string $column the name of the new column. The name will be properly quoted by the method.
324
     * @param string $type the column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
325
     * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
326
     * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
327
     */
328
    public function addColumn($table, $column, $type)
329
    {
330
        echo "    > add column $column $type to table $table ...";
331
        $time = microtime(true);
332
        $this->db->createCommand()->addColumn($table, $column, $type)->execute();
333
        if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
334
            $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
335
        }
336
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
337
    }
338
339
    /**
340
     * Builds and executes a SQL statement for dropping a DB column.
341
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
342
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
343
     */
344
    public function dropColumn($table, $column)
345
    {
346
        echo "    > drop column $column from table $table ...";
347
        $time = microtime(true);
348
        $this->db->createCommand()->dropColumn($table, $column)->execute();
349
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
350
    }
351
352
    /**
353
     * Builds and executes a SQL statement for renaming a column.
354
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
355
     * @param string $name the old name of the column. The name will be properly quoted by the method.
356
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
357
     */
358
    public function renameColumn($table, $name, $newName)
359
    {
360
        echo "    > rename column $name in table $table to $newName ...";
361
        $time = microtime(true);
362
        $this->db->createCommand()->renameColumn($table, $name, $newName)->execute();
363
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
364
    }
365
366
    /**
367
     * Builds and executes a SQL statement for changing the definition of a column.
368
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
369
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
370
     * @param string $type the new column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
371
     * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
372
     * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
373
     */
374
    public function alterColumn($table, $column, $type)
375
    {
376
        echo "    > alter column $column in table $table to $type ...";
377
        $time = microtime(true);
378
        $this->db->createCommand()->alterColumn($table, $column, $type)->execute();
379
        if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
380
            $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
381
        }
382
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
383
    }
384
385
    /**
386
     * Builds and executes a SQL statement for creating a primary key.
387
     * The method will properly quote the table and column names.
388
     * @param string $name the name of the primary key constraint.
389
     * @param string $table the table that the primary key constraint will be added to.
390
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
391
     */
392
    public function addPrimaryKey($name, $table, $columns)
393
    {
394
        echo "    > add primary key $name on $table (" . (is_array($columns) ? implode(',', $columns) : $columns) . ') ...';
395
        $time = microtime(true);
396
        $this->db->createCommand()->addPrimaryKey($name, $table, $columns)->execute();
397
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
398
    }
399
400
    /**
401
     * Builds and executes a SQL statement for dropping a primary key.
402
     * @param string $name the name of the primary key constraint to be removed.
403
     * @param string $table the table that the primary key constraint will be removed from.
404
     */
405
    public function dropPrimaryKey($name, $table)
406
    {
407
        echo "    > drop primary key $name ...";
408
        $time = microtime(true);
409
        $this->db->createCommand()->dropPrimaryKey($name, $table)->execute();
410
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
411
    }
412
413
    /**
414
     * Builds a SQL statement for adding a foreign key constraint to an existing table.
415
     * The method will properly quote the table and column names.
416
     * @param string $name the name of the foreign key constraint.
417
     * @param string $table the table that the foreign key constraint will be added to.
418
     * @param string|array $columns the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas or use an array.
419
     * @param string $refTable the table that the foreign key references to.
420
     * @param string|array $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas or use an array.
421
     * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
422
     * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
423
     */
424
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
425
    {
426
        echo "    > add foreign key $name: $table (" . implode(',', (array) $columns) . ") references $refTable (" . implode(',', (array) $refColumns) . ') ...';
427
        $time = microtime(true);
428
        $this->db->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update)->execute();
429
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
430
    }
431
432
    /**
433
     * Builds a SQL statement for dropping a foreign key constraint.
434
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
435
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
436
     */
437
    public function dropForeignKey($name, $table)
438
    {
439
        echo "    > drop foreign key $name from table $table ...";
440
        $time = microtime(true);
441
        $this->db->createCommand()->dropForeignKey($name, $table)->execute();
442
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
443
    }
444
445
    /**
446
     * Builds and executes a SQL statement for creating a new index.
447
     * @param string $name the name of the index. The name will be properly quoted by the method.
448
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
449
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
450
     * by commas or use an array. Each column name will be properly quoted by the method. Quoting will be skipped for column names that
451
     * include a left parenthesis "(".
452
     * @param bool $unique whether to add UNIQUE constraint on the created index.
453
     */
454
    public function createIndex($name, $table, $columns, $unique = false)
455
    {
456
        echo '    > create' . ($unique ? ' unique' : '') . " index $name on $table (" . implode(',', (array) $columns) . ') ...';
457
        $time = microtime(true);
458
        $this->db->createCommand()->createIndex($name, $table, $columns, $unique)->execute();
459
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
460
    }
461
462
    /**
463
     * Builds and executes a SQL statement for dropping an index.
464
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
465
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
466
     */
467
    public function dropIndex($name, $table)
468
    {
469
        echo "    > drop index $name on $table ...";
470
        $time = microtime(true);
471
        $this->db->createCommand()->dropIndex($name, $table)->execute();
472
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
473
    }
474
475
    /**
476
     * Builds and execute a SQL statement for adding comment to column
477
     *
478
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
479
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
480
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
481
     * @since 2.0.8
482
     */
483
    public function addCommentOnColumn($table, $column, $comment)
484
    {
485
        echo "    > add comment on column $column ...";
486
        $time = microtime(true);
487
        $this->db->createCommand()->addCommentOnColumn($table, $column, $comment)->execute();
488
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
489
    }
490
491
    /**
492
     * Builds a SQL statement for adding comment to table
493
     *
494
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
495
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
496
     * @since 2.0.8
497
     */
498
    public function addCommentOnTable($table, $comment)
499
    {
500
        echo "    > add comment on table $table ...";
501
        $time = microtime(true);
502
        $this->db->createCommand()->addCommentOnTable($table, $comment)->execute();
503
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
504
    }
505
506
    /**
507
     * Builds and execute a SQL statement for dropping comment from column
508
     *
509
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
510
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
511
     * @since 2.0.8
512
     */
513
    public function dropCommentFromColumn($table, $column)
514
    {
515
        echo "    > drop comment from column $column ...";
516
        $time = microtime(true);
517
        $this->db->createCommand()->dropCommentFromColumn($table, $column)->execute();
518
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
519
    }
520
521
    /**
522
     * Builds a SQL statement for dropping comment from table
523
     *
524
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
525
     * @since 2.0.8
526
     */
527
    public function dropCommentFromTable($table)
528
    {
529
        echo "    > drop comment from table $table ...";
530
        $time = microtime(true);
531
        $this->db->createCommand()->dropCommentFromTable($table)->execute();
532
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
533
    }
534
}
535