|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace neon\core\db; |
|
4
|
|
|
|
|
5
|
|
|
class Command extends \yii\db\Command |
|
6
|
|
|
{ |
|
7
|
|
|
/** @var bool|string */ |
|
8
|
|
|
public static $logRawQueries = false; |
|
9
|
|
|
|
|
10
|
|
|
/** @var resource */ |
|
11
|
|
|
public static $sqlRawLogFileResource = null; |
|
12
|
|
|
|
|
13
|
|
|
/** @var bool */ |
|
14
|
|
|
private static bool $wasFileResource; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @param string $category |
|
18
|
|
|
* @return array |
|
19
|
|
|
*/ |
|
20
|
|
|
protected function logQuery($category) |
|
21
|
|
|
{ |
|
22
|
|
|
if ((self::$sqlRawLogFileResource!==null && get_resource_type(self::$sqlRawLogFileResource)==='stream') && |
|
23
|
|
|
(self::$logRawQueries===true || |
|
24
|
|
|
(self::$logRawQueries==='execute' && $category==='yii\\db\\Command::execute') || |
|
25
|
|
|
(self::$logRawQueries==='query' && $category==='yii\\db\\Command::query') |
|
26
|
|
|
) |
|
27
|
|
|
) { |
|
28
|
|
|
fwrite(self::$sqlRawLogFileResource, $this->getRawSql().";".PHP_EOL); |
|
29
|
|
|
} |
|
30
|
|
|
return parent::logQuery($category); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* start logging queries to a file or other stream |
|
35
|
|
|
* @param $fileOrStream |
|
36
|
|
|
* @param bool|string $logRawQueries |
|
37
|
|
|
* @throws \Exception |
|
38
|
|
|
*/ |
|
39
|
|
|
public static function startLogRawQueriesToFile($fileOrStream, $logRawQueries=true) |
|
40
|
|
|
{ |
|
41
|
|
|
if ($logRawQueries===false) return; |
|
42
|
|
|
if (is_string($fileOrStream)) { |
|
43
|
|
|
self::$sqlRawLogFileResource = fopen($fileOrStream, "w+"); |
|
44
|
|
|
self::$wasFileResource = false; |
|
45
|
|
|
} |
|
46
|
|
|
elseif (get_resource_type($fileOrStream)==='stream') { |
|
47
|
|
|
self::$sqlRawLogFileResource = $fileOrStream; |
|
48
|
|
|
self::$wasFileResource = true; |
|
49
|
|
|
} |
|
50
|
|
|
else { |
|
51
|
|
|
throw new \Exception('parameter fileOrSteam must be a filename or resource of type steam'); |
|
52
|
|
|
} |
|
53
|
|
|
if ($logRawQueries!==true && $logRawQueries!=='execute' && $logRawQueries!=='query') { |
|
54
|
|
|
throw new \Exception("parameter logRawQueries must boolean, 'execute' or 'query'"); |
|
55
|
|
|
} |
|
56
|
|
|
self::$logRawQueries = $logRawQueries; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* stop logging queries |
|
61
|
|
|
*/ |
|
62
|
|
|
public static function stopLogRawQueries() |
|
63
|
|
|
{ |
|
64
|
|
|
if (!self::$wasFileResource && get_resource_type(self::$sqlRawLogFileResource)==='stream') { |
|
65
|
|
|
// only auto-close if startLogRawQueriesToFile created the resource otherwise it's up to the user |
|
66
|
|
|
fclose(self::$sqlRawLogFileResource); |
|
67
|
|
|
} |
|
68
|
|
|
self::$sqlRawLogFileResource = null; |
|
69
|
|
|
} |
|
70
|
|
|
} |