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. foreach ($this->getDbTargets() as $target) {
  57. $this->db = $target->db;
  58. $tableOptions = null;
  59. if ($this->db->driverName === 'mysql') {
  60. // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
  61. $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
  62. }
  63. $this->createTable($target->logTable, [
  64. 'id' => $this->bigPrimaryKey(),
  65. 'level' => $this->integer(),
  66. 'category' => $this->string(),
  67. 'log_time' => $this->double(),
  68. 'prefix' => $this->text(),
  69. 'message' => $this->text(),
  70. ], $tableOptions);
  71. $this->createIndex('idx_log_level', $target->logTable, 'level');
  72. $this->createIndex('idx_log_category', $target->logTable, 'category');
  73. }
  74. }
  75. public function down()
  76. {
  77. foreach ($this->getDbTargets() as $target) {
  78. $this->db = $target->db;
  79. $this->dropTable($target->logTable);
  80. }
  81. }
  82. }