m141106_185632_log_init.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. use yii\base\InvalidConfigException;
  8. use yii\db\Migration;
  9. use yii\log\DbTarget;
  10. /**
  11. * Initializes log table.
  12. *
  13. * The indexes declared are not required. They are mainly used to improve the performance
  14. * of some queries about message levels and categories. Depending on your actual needs, you may
  15. * want to create additional indexes (e.g. index on `log_time`).
  16. *
  17. * @author Alexander Makarov <sam@rmcreative.ru>
  18. * @since 2.0.1
  19. */
  20. class m141106_185632_log_init extends Migration
  21. {
  22. /**
  23. * @var DbTarget[] Targets to create log table for
  24. */
  25. private $dbTargets = [];
  26. /**
  27. * @throws InvalidConfigException
  28. * @return DbTarget[]
  29. */
  30. protected function getDbTargets()
  31. {
  32. if ($this->dbTargets === []) {
  33. $log = Yii::$app->getLog();
  34. $usedTargets = [];
  35. foreach ($log->targets as $target) {
  36. if ($target instanceof DbTarget) {
  37. $currentTarget = [
  38. $target->db,
  39. $target->logTable,
  40. ];
  41. if (!in_array($currentTarget, $usedTargets, true)) {
  42. // do not create same table twice
  43. $usedTargets[] = $currentTarget;
  44. $this->dbTargets[] = $target;
  45. }
  46. }
  47. }
  48. if ($this->dbTargets === []) {
  49. throw new InvalidConfigException('You should configure "log" component to use one or more database targets before executing this migration.');
  50. }
  51. }
  52. return $this->dbTargets;
  53. }
  54. public function up()
  55. {
  56. $targets = $this->getDbTargets();
  57. foreach ($targets as $target) {
  58. $this->db = $target->db;
  59. $tableOptions = null;
  60. if ($this->db->driverName === 'mysql') {
  61. // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
  62. $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
  63. }
  64. $this->createTable($target->logTable, [
  65. 'id' => $this->bigPrimaryKey(),
  66. 'level' => $this->integer(),
  67. 'category' => $this->string(),
  68. 'log_time' => $this->double(),
  69. 'prefix' => $this->text(),
  70. 'message' => $this->text(),
  71. ], $tableOptions);
  72. $this->createIndex('idx_log_level', $target->logTable, 'level');
  73. $this->createIndex('idx_log_category', $target->logTable, 'category');
  74. }
  75. }
  76. public function down()
  77. {
  78. $targets = $this->getDbTargets();
  79. foreach ($targets as $target) {
  80. $this->db = $target->db;
  81. $this->dropTable($target->logTable);
  82. }
  83. }
  84. }