DbPanel.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. namespace yii\debug\panels;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\debug\Panel;
  11. use yii\log\Logger;
  12. use yii\debug\models\search\Db;
  13. /**
  14. * Debugger panel that collects and displays database queries performed.
  15. *
  16. * @property array $profileLogs This property is read-only.
  17. * @property string $summaryName Short name of the panel, which will be use in summary. This property is
  18. * read-only.
  19. *
  20. * @author Qiang Xue <qiang.xue@gmail.com>
  21. * @since 2.0
  22. */
  23. class DbPanel extends Panel
  24. {
  25. /**
  26. * @var integer the threshold for determining whether the request has involved
  27. * critical number of DB queries. If the number of queries exceeds this number,
  28. * the execution is considered taking critical number of DB queries.
  29. */
  30. public $criticalQueryThreshold;
  31. /**
  32. * @var string the name of the database component to use for executing (explain) queries
  33. */
  34. public $db = 'db';
  35. /**
  36. * @var array the default ordering of the database queries. In the format of
  37. * [ property => sort direction ], for example: [ 'duration' => SORT_DESC ]
  38. * @since 2.0.7
  39. */
  40. public $defaultOrder = [
  41. 'seq' => SORT_ASC
  42. ];
  43. /**
  44. * @var array the default filter to apply to the database queries. In the format
  45. * of [ property => value ], for example: [ 'type' => 'SELECT' ]
  46. * @since 2.0.7
  47. */
  48. public $defaultFilter = [];
  49. /**
  50. * @var array db queries info extracted to array as models, to use with data provider.
  51. */
  52. private $_models;
  53. /**
  54. * @var array current database request timings
  55. */
  56. private $_timings;
  57. /**
  58. * @inheritdoc
  59. */
  60. public function init()
  61. {
  62. $this->actions['db-explain'] = [
  63. 'class' => 'yii\\debug\\actions\\db\\ExplainAction',
  64. 'panel' => $this,
  65. ];
  66. }
  67. /**
  68. * @inheritdoc
  69. */
  70. public function getName()
  71. {
  72. return 'Database';
  73. }
  74. /**
  75. * @return string short name of the panel, which will be use in summary.
  76. */
  77. public function getSummaryName()
  78. {
  79. return 'DB';
  80. }
  81. /**
  82. * @inheritdoc
  83. */
  84. public function getSummary()
  85. {
  86. $timings = $this->calculateTimings();
  87. $queryCount = count($timings);
  88. $queryTime = number_format($this->getTotalQueryTime($timings) * 1000) . ' ms';
  89. return Yii::$app->view->render('panels/db/summary', [
  90. 'timings' => $this->calculateTimings(),
  91. 'panel' => $this,
  92. 'queryCount' => $queryCount,
  93. 'queryTime' => $queryTime,
  94. ]);
  95. }
  96. /**
  97. * @inheritdoc
  98. */
  99. public function getDetail()
  100. {
  101. $searchModel = new Db();
  102. if (!$searchModel->load(Yii::$app->request->getQueryParams())) {
  103. $searchModel->load($this->defaultFilter, '');
  104. }
  105. $dataProvider = $searchModel->search($this->getModels());
  106. $dataProvider->getSort()->defaultOrder = $this->defaultOrder;
  107. return Yii::$app->view->render('panels/db/detail', [
  108. 'panel' => $this,
  109. 'dataProvider' => $dataProvider,
  110. 'searchModel' => $searchModel,
  111. 'hasExplain' => $this->hasExplain()
  112. ]);
  113. }
  114. /**
  115. * Calculates given request profile timings.
  116. *
  117. * @return array timings [token, category, timestamp, traces, nesting level, elapsed time]
  118. */
  119. public function calculateTimings()
  120. {
  121. if ($this->_timings === null) {
  122. $this->_timings = Yii::getLogger()->calculateTimings(isset($this->data['messages']) ? $this->data['messages'] : []);
  123. }
  124. return $this->_timings;
  125. }
  126. /**
  127. * @inheritdoc
  128. */
  129. public function save()
  130. {
  131. return ['messages' => $this->getProfileLogs()];
  132. }
  133. /**
  134. * Returns all profile logs of the current request for this panel. It includes categories such as:
  135. * 'yii\db\Command::query', 'yii\db\Command::execute'.
  136. * @return array
  137. */
  138. public function getProfileLogs()
  139. {
  140. $target = $this->module->logTarget;
  141. return $target->filterMessages($target->messages, Logger::LEVEL_PROFILE, ['yii\db\Command::query', 'yii\db\Command::execute']);
  142. }
  143. /**
  144. * Returns total query time.
  145. *
  146. * @param array $timings
  147. * @return int total time
  148. */
  149. protected function getTotalQueryTime($timings)
  150. {
  151. $queryTime = 0;
  152. foreach ($timings as $timing) {
  153. $queryTime += $timing['duration'];
  154. }
  155. return $queryTime;
  156. }
  157. /**
  158. * Returns an array of models that represents logs of the current request.
  159. * Can be used with data providers such as \yii\data\ArrayDataProvider.
  160. * @return array models
  161. */
  162. protected function getModels()
  163. {
  164. if ($this->_models === null) {
  165. $this->_models = [];
  166. $timings = $this->calculateTimings();
  167. foreach ($timings as $seq => $dbTiming) {
  168. $this->_models[] = [
  169. 'type' => $this->getQueryType($dbTiming['info']),
  170. 'query' => $dbTiming['info'],
  171. 'duration' => ($dbTiming['duration'] * 1000), // in milliseconds
  172. 'trace' => $dbTiming['trace'],
  173. 'timestamp' => ($dbTiming['timestamp'] * 1000), // in milliseconds
  174. 'seq' => $seq,
  175. ];
  176. }
  177. }
  178. return $this->_models;
  179. }
  180. /**
  181. * Returns database query type.
  182. *
  183. * @param string $timing timing procedure string
  184. * @return string query type such as select, insert, delete, etc.
  185. */
  186. protected function getQueryType($timing)
  187. {
  188. $timing = ltrim($timing);
  189. preg_match('/^([a-zA-z]*)/', $timing, $matches);
  190. return count($matches) ? mb_strtoupper($matches[0], 'utf8') : '';
  191. }
  192. /**
  193. * Check if given queries count is critical according settings.
  194. *
  195. * @param int $count queries count
  196. * @return bool
  197. */
  198. public function isQueryCountCritical($count)
  199. {
  200. return (($this->criticalQueryThreshold !== null) && ($count > $this->criticalQueryThreshold));
  201. }
  202. /**
  203. * Returns array query types
  204. *
  205. * @return array
  206. * @since 2.0.3
  207. */
  208. public function getTypes()
  209. {
  210. return array_reduce(
  211. $this->_models,
  212. function ($result, $item) {
  213. $result[$item['type']] = $item['type'];
  214. return $result;
  215. },
  216. []
  217. );
  218. }
  219. /**
  220. * @inheritdoc
  221. */
  222. public function isEnabled()
  223. {
  224. try {
  225. $this->getDb();
  226. } catch (InvalidConfigException $exception) {
  227. return false;
  228. }
  229. return true;
  230. }
  231. /**
  232. * @return bool Whether the DB component has support for EXPLAIN queries
  233. * @since 2.0.5
  234. */
  235. protected function hasExplain()
  236. {
  237. $db = $this->getDb();
  238. if (!($db instanceof \yii\db\Connection)) {
  239. return false;
  240. }
  241. switch ($db->getDriverName()) {
  242. case 'mysql':
  243. case 'sqlite':
  244. case 'pgsql':
  245. case 'cubrid':
  246. return true;
  247. default:
  248. return false;
  249. }
  250. }
  251. /**
  252. * Check if given query type can be explained.
  253. *
  254. * @param string $type query type
  255. * @return bool
  256. *
  257. * @since 2.0.5
  258. */
  259. public static function canBeExplained($type)
  260. {
  261. return $type !== 'SHOW';
  262. }
  263. /**
  264. * Returns a reference to the DB component associated with the panel
  265. *
  266. * @return \yii\db\Connection
  267. * @since 2.0.5
  268. */
  269. public function getDb()
  270. {
  271. return Yii::$app->get($this->db);
  272. }
  273. }