diff options
author | Simon Rettberg | 2017-05-10 17:34:18 +0200 |
---|---|---|
committer | Simon Rettberg | 2017-05-10 17:34:18 +0200 |
commit | c0878dbf4b226a097f6681e443159cccd16e07fe (patch) | |
tree | eca8c3713cc9c85bd5270813c94a707b9770453b /inc/database.inc.php | |
parent | Update config.php example (diff) | |
download | slx-admin-c0878dbf4b226a097f6681e443159cccd16e07fe.tar.gz slx-admin-c0878dbf4b226a097f6681e443159cccd16e07fe.tar.xz slx-admin-c0878dbf4b226a097f6681e443159cccd16e07fe.zip |
[inc/Database] Add slow query debugging output
Diffstat (limited to 'inc/database.inc.php')
-rw-r--r-- | inc/database.inc.php | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/inc/database.inc.php b/inc/database.inc.php index 9153c688..7adcf867 100644 --- a/inc/database.inc.php +++ b/inc/database.inc.php @@ -114,6 +114,9 @@ class Database public static function simpleQuery($query, $args = array(), $ignoreError = false) { self::init(); + if (CONFIG_DEBUG && preg_match('/^\s*SELECT/is', $query)) { + self::explainQuery($query, $args, $ignoreError); + } // Support passing nested arrays for IN statements, automagically refactor self::handleArrayArgument($query, $args); try { @@ -138,6 +141,51 @@ class Database return false; } + private static function explainQuery($query, $args, $ignoreError) + { + $res = self::simpleQuery('EXPLAIN ' . $query, $args, true); + if ($res === false) + return; + $rows = $res->fetchAll(PDO::FETCH_ASSOC); + if (empty($rows)) + return; + $log = false; + $lens = array(); + foreach (array_keys($rows[0]) as $key) { + $lens[$key] = strlen($key); + } + foreach ($rows as $row) { + if (!$log && preg_match('/filesort|temporary/i', $row['Extra'])) { + $log = true; + } + foreach ($row as $key => $col) { + $l = strlen($col); + if ($l > $lens[$key]) { + $lens[$key] = $l; + } + } + } + if (!$log) + return; + error_log('Possible slow query: ' . $query); + $border = $head = ''; + foreach ($lens as $key => $len) { + $border .= '+' . str_repeat('-', $len + 2); + $head .= '| ' . str_pad($key, $len) . ' '; + } + $border .= '+'; + $head .= '|'; + error_log("\n" . $border . "\n" . $head . "\n" . $border); + foreach ($rows as $row) { + $line = ''; + foreach ($lens as $key => $len) { + $line .= '| '. str_pad($row[$key], $len) . ' '; + } + error_log($line . "|"); + } + error_log($border); + } + /** * Convert nested array argument to multiple arguments. * If you have: |