|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Lagdo\DbAdmin\Db\Service\Admin; |
|
4
|
|
|
|
|
5
|
|
|
use Lagdo\DbAdmin\Db\Service\Audit\Options; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* SQL queries logging and storage. |
|
9
|
|
|
*/ |
|
10
|
|
|
class QueryHistory |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @var bool |
|
14
|
|
|
*/ |
|
15
|
|
|
private bool $historyEnabled; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var bool |
|
19
|
|
|
*/ |
|
20
|
|
|
private bool $historyDistinct; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @var int |
|
24
|
|
|
*/ |
|
25
|
|
|
private int $historyLimit; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* The constructor |
|
29
|
|
|
* |
|
30
|
|
|
* @param ConnectionProxy $proxy |
|
31
|
|
|
* @param array $options |
|
32
|
|
|
*/ |
|
33
|
|
|
public function __construct(private ConnectionProxy $proxy, array $options) |
|
34
|
|
|
{ |
|
35
|
|
|
$this->historyEnabled = (bool)($options['history']['enabled'] ?? false); |
|
36
|
|
|
$this->historyDistinct = (bool)($options['history']['distinct'] ?? false); |
|
37
|
|
|
$this->historyLimit = (int)($options['history']['limit'] ?? 15); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* @return array |
|
42
|
|
|
*/ |
|
43
|
|
|
public function getQueries(): array |
|
44
|
|
|
{ |
|
45
|
|
|
if (!$this->historyEnabled || |
|
46
|
|
|
($ownerId = $this->proxy->getOwnerId(false)) === 0) { |
|
47
|
|
|
return []; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
// PostgreSQL doesn't allow the use of distinct and order by |
|
51
|
|
|
// a field not in the select clause in the same SQL query. |
|
52
|
|
|
$category = Options::CAT_EDITOR; |
|
53
|
|
|
$select = $this->historyDistinct && $this->proxy->jush() !== 'pgsql' ? |
|
54
|
|
|
'SELECT DISTINCT' : 'SELECT'; |
|
55
|
|
|
$query = "$select driver,query FROM dbadmin_runned_commands c " . |
|
56
|
|
|
"WHERE c.owner_id=:owner_id AND c.category=:category " . |
|
57
|
|
|
"ORDER BY c.last_update DESC LIMIT {$this->historyLimit}"; |
|
58
|
|
|
$values = [ |
|
59
|
|
|
'owner_id' => $ownerId, |
|
60
|
|
|
'category' => $category, |
|
61
|
|
|
]; |
|
62
|
|
|
$statement = $this->proxy->executeQuery($query, $values); |
|
63
|
|
|
if ($statement !== false) { |
|
64
|
|
|
$commands = []; |
|
65
|
|
|
$id = 1; |
|
66
|
|
|
while (($row = $statement->fetchAssoc())) { |
|
67
|
|
|
$commands[$id++] = $row; |
|
68
|
|
|
} |
|
69
|
|
|
return $commands; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
$this->proxy->logWarning('Unable to read commands from the query audit database.'); |
|
73
|
|
|
return []; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|