remove Query Status Monitor, complete implementation

This commit is contained in:
Daniel Seifert 2020-05-01 01:08:23 +02:00
parent c3aa93e543
commit 07fcca498d
Signed by: DanielS
GPG Key ID: 6A513E13AEE66170
14 changed files with 40 additions and 351 deletions

View File

@ -1,16 +0,0 @@
language: php
php:
- 7.0
cache:
directories:
- $HOME/.composer/cache
before_script:
- composer install
script:
- php ./vendor/bin/phpspec run --format=pretty --stop-on-failure --no-code-generation

View File

@ -8,13 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
--- ---
## [1.2.0] - 2019-10-01 ## [1.2.0] - 2020-04-30
### Added ### Added
- SQL Query Monitor show at the Page how many SQL queries have been fired. - Format SQL query
- Measures the SQL execution time - Measures the SQL execution time
- Testing framework [phpspec](https://www.phpspec.net/en/stable/manual/introduction.html)
--- ---

View File

@ -1,8 +1,6 @@
Oxid eShop SQL Logger Oxid eShop SQL Logger
--------------------- ---------------------
[![Build Status](https://travis-ci.org/TumTum/oxid-sql-logger.svg?branch=master)](https://travis-ci.org/TumTum/oxid-sql-logger)
Returns all SQL queries into console of a Browser. Returns all SQL queries into console of a Browser.
## Install ## Install
@ -32,28 +30,6 @@ CLI:
![Example CLI](https://raw.githubusercontent.com/d3datadevelopment/oxid-sql-logger/master/img/screenshot-cli.jpg) ![Example CLI](https://raw.githubusercontent.com/d3datadevelopment/oxid-sql-logger/master/img/screenshot-cli.jpg)
## SQL Query Status Monitor
![Example CLI](https://raw.githubusercontent.com/TumTum/oxid-sql-logger/master/img/sql-query-status-monitor.jpg)
See how many queries and which types of queries have been added to the database.
To determine the amount.
#### Switch on
For this purpose, the parameter `$this->blSQLStatusBox = true;` must be stored in the file `config.inc.php`.
So you can turn it on and off temporarily.
Unique: Insert, at the end, the Smarty tag: `[{tm_sql_status}]` in the `base.tpl` file.
####### source/Application/views/flow/tpl/layout/base.tpl
```html
[{tm_sql_status}]
</body>
</html>
```
## Credits ## Credits
Many thanks to [Tobias Matthaiou](https://github.com/TumTum/oxid-sql-logger) for his inspiration. Many thanks to [Tobias Matthaiou](https://github.com/TumTum/oxid-sql-logger) for his inspiration.

View File

@ -6,19 +6,11 @@
"monolog/monolog": "^1", "monolog/monolog": "^1",
"nilportugues/sql-query-formatter": "^1.2.2" "nilportugues/sql-query-formatter": "^1.2.2"
}, },
"require-dev": {
"phpspec/phpspec": "^4",
"doctrine/dbal": "^2.5",
"bovigo/assert": "^2"
},
"license": "GPL-3.0", "license": "GPL-3.0",
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"D3\\OxidSqlLogger\\": "./src" "D3\\OxidSqlLogger\\": "./src"
}, }
"files": [
"./src/functions.php"
]
}, },
"authors": [ "authors": [
{ {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

View File

@ -1,4 +0,0 @@
suites:
default:
namespace: "tm\\oxid\\sql\\logger\\"
psr4_prefix: "tm\\oxid\\sql\\logger\\"

View File

@ -1,89 +0,0 @@
<?php
namespace spec\tm\oxid\sql\logger;
use PhpSpec\Exception\Example\FailureException;
use tm\oxid\sql\logger\OxidSQLLogger;
use PhpSpec\ObjectBehavior;
use Monolog;
use function bovigo\assert\predicate\hasKey;
use function bovigo\assert\predicate\isOfType;
use function bovigo\assert\predicate\isSameAs;
class OxidSQLLoggerSpec extends ObjectBehavior
{
/**
* @var Monolog\Handler\TestHandler
*/
private $testLogger = null;
public function let()
{
$this->testLogger = new Monolog\Handler\TestHandler();
Monolog\Registry::addLogger(
new Monolog\Logger('sql', [$this->testLogger]),
'sql',
true
);
}
public function it_is_initializable()
{
$this->shouldHaveType(OxidSQLLogger::class);
}
/**
* @throws FailureException
*/
public function it_should_log_the_sql_normally()
{
$this->startQuery('SELECT 1', ['param1'], ['master']);
for ($i = 0; $i <= 1000; $i++) @get_declared_classes();
$this->stopQuery();
$this->assertExpectLog();
$this->assertMatchMessage('/\[\d+ms\] SELECT 1/');
$this->assertContext('params', isSameAs(['param1']));
$this->assertContext('types', isSameAs(['master']));
$this->assertContext('time', isOfType('float'));
}
/**
* @throws FailureException
*/
public function it_should_log_without_time_specification()
{
$this->startQuery('SELECT 1');
$this->startQuery('SELECT 2');
$this->assertExpectLog();
$this->assertMatchMessage('/\[Statement canceled\] SELECT 1/');
$this->assertContext('time', isSameAs('Statement canceled'));
}
private function assertExpectLog()
{
if (!$this->testLogger->hasRecords(Monolog\Logger::DEBUG)) {
throw new FailureException("No log entry was made");
}
}
private function assertMatchMessage($regex)
{
if (!$this->testLogger->hasRecordThatMatches($regex, Monolog\Logger::DEBUG)) {
$message = $this->testLogger->getRecords()[0]['message'];
throw new FailureException("Expect message '{$regex}' got '{$message}'");
};
}
private function assertContext($param, $actual)
{
$record = $this->testLogger->getRecords()[0];
\bovigo\assert\assert($record['context'], hasKey($param), "Context '{$param}' not found");
\bovigo\assert\assert($record['context'][$param], $actual, "Context '{$param} is not same");
}
}

View File

@ -1,65 +0,0 @@
<?php
namespace spec\tm\oxid\sql\logger;
use tm\oxid\sql\logger\SQLQuery;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
/**
* Class SQLQuerySpec
* @package spec\tm\oxid\sql\logger
*/
class SQLQuerySpec extends ObjectBehavior
{
public function it_is_initializable()
{
$this->shouldHaveType(SQLQuery::class);
}
public function it_hat_sql_setter_getter()
{
$this->setSQL('SELECT NOW()')->shouldHaveType(SQLQuery::class);
$this->getSQL()->shouldBe('SELECT NOW()');
}
public function it_hat_params_setter_getter()
{
$this->setParams(['param1', 'param2'])->shouldHaveType(SQLQuery::class);
$this->getParams()->shouldBe(['param1', 'param2']);
}
public function it_hat_type_setter_getter()
{
$this->setTypes(['type1'])->shouldHaveType(SQLQuery::class);
$this->getTypes()->shouldBe(['type1']);
}
public function it_should_indicate_an_aborted_time()
{
$this->setSql('SELECT 1');
$this->setCanceled()->shouldHaveType(SQLQuery::class);
$this->getElapsedTime()->shouldBe('Statement canceled');
}
public function it_should_display_with_a_readable_time()
{
$this->setSql('SELECT 1');
sleep(1);
$this->getReadableElapsedTime()->shouldMatch('/^1\.\d\d\ds/');
}
public function it_should_display_with_a_readable_time_in_ms()
{
$this->setSql('SELECT 1');
for ($i = 0; $i <= 1000; $i++) @get_declared_classes();
$this->getReadableElapsedTime()->shouldMatch('/^\d{1,3}ms/');
}
public function it_should_display_a_time_in_float()
{
$this->setSql('SELECT 1');
for ($i = 0; $i <= 1000; $i++) @get_declared_classes();
$this->getElapsedTime()->shouldBeFloat();
}
}

View File

@ -1,57 +0,0 @@
<?php
/**
* Autor: Tobias Matthaiou <developer@tobimat.eu>
* Date: 2019-08-20
* Time: 21:33
*/
namespace D3\OxidSqlLogger;
/**
* Class AutoInstallSmaryPlugin
*/
class AutoInstallSmaryPlugin
{
public function runInstall()
{
$oxideshop_ce = new \SplFileInfo(__DIR__ . '/../../../oxid-esales/oxideshop-ce/source/Core/Smarty/Plugin');
$smartyPlugin = new \SplFileInfo(__DIR__ . '/Smarty/function.tm_sql_status.php');
if ($oxideshop_ce->isDir()) {
$target = new \SplFileInfo($oxideshop_ce->getRealPath() . '/' . $smartyPlugin->getBasename());
if ($target->isFile() && $this->isSameFile($target, $smartyPlugin)) {
return;
}
$this->createHardLink($smartyPlugin, $target);
OxidUtilsView::clearSmarty();
}
}
/**
* @param \SplFileInfo $target
* @param \SplFileInfo $
* @return bool
*/
protected function isSameFile(\SplFileInfo $target, \SplFileInfo $smartyPlugin)
{
return @md5_file($target->getPathname()) == @md5_file($smartyPlugin->getRealPath());
}
/**
* @param \SplFileInfo $smarty_func_tm_sql_status
* @param \SplFileInfo $target
*/
protected function createHardLink(\SplFileInfo $smartyPlugin, \SplFileInfo $target)
{
if ($target->isFile()) {
@unlink($target->getPathname());
}
link($smartyPlugin->getPathname(), $target->getPathname());
}
}

View File

@ -9,6 +9,7 @@ namespace D3\OxidSqlLogger;
use Doctrine\DBAL\Logging\SQLLogger; use Doctrine\DBAL\Logging\SQLLogger;
use Monolog; use Monolog;
use NilPortugues\Sql\QueryFormatter\Formatter;
/** /**
* Class OxidSQLLogger * Class OxidSQLLogger
@ -47,14 +48,12 @@ class OxidSQLLogger implements SQLLogger
*/ */
public function startQuery($sql, array $params = null, array $types = null) public function startQuery($sql, array $params = null, array $types = null)
{ {
$formatter = new Formatter();
if ($this->SQLQuery) { if ($this->SQLQuery) {
$this->SQLQuery->setCanceled(); $this->SQLQuery->setCanceled();
$this->stopQuery(); $this->stopQuery();
} }
$this->SQLQuery = (new SQLQuery()) ->setSql($formatter->format($sql)) $this->SQLQuery = (new SQLQuery()) ->setSql($sql)
->setParams($params) ->setParams($params)
->setTypes($types) ->setTypes($types)
->setLogStartingFile($this->logStartingFile) ->setLogStartingFile($this->logStartingFile)
@ -69,9 +68,12 @@ class OxidSQLLogger implements SQLLogger
public function stopQuery() public function stopQuery()
{ {
if ($this->SQLQuery) { if ($this->SQLQuery) {
$formatter = new Formatter();
Monolog\Registry::sql()->addDebug( Monolog\Registry::sql()->addDebug(
'['.$this->SQLQuery->getReadableElapsedTime().'] ' . ( $this->message ? $this->message : $this->SQLQuery->getSql() ), '['.$this->SQLQuery->getReadableElapsedTime().'] ' . ( $this->message ? $this->message : $this->SQLQuery->getSql() ),
[ [
'query' => $formatter->format($this->SQLQuery->getSql()),
'params' => $this->SQLQuery->getParams(), 'params' => $this->SQLQuery->getParams(),
'time' => $this->SQLQuery->getElapsedTime(), 'time' => $this->SQLQuery->getElapsedTime(),
'types' => $this->SQLQuery->getTypes(), 'types' => $this->SQLQuery->getTypes(),

View File

@ -1,24 +0,0 @@
<?php
/**
* Autor: Tobias Matthaiou <developer@tobimat.eu>
* Date: 2019-08-20
* Time: 21:33
*/
namespace D3\OxidSqlLogger;
/**
* Class OxidUtilsView
* @package tm\oxid\sql\logger
*/
class OxidUtilsView extends \OxidEsales\Eshop\Core\UtilsView
{
/**
* Removes existing Smarty instance
*/
public static function clearSmarty()
{
\OxidEsales\Eshop\Core\UtilsView::$_oSmarty = null;
}
}

View File

@ -108,6 +108,14 @@ class SQLQuery
return $this; return $this;
} }
/**
* @return string
*/
public function getLogStartingFile()
{
return $this->logStartingFile;
}
/** /**
* @param $file * @param $file
* @return SQLQuery * @return SQLQuery
@ -117,6 +125,14 @@ class SQLQuery
$this->logStartingFile = $file; $this->logStartingFile = $file;
return $this; return $this;
} }
/**
* @return string
*/
public function getLogStartingLine()
{
return $this->logStartingLine;
}
/** /**
* @param $line * @param $line
@ -127,6 +143,14 @@ class SQLQuery
$this->logStartingLine = $line; $this->logStartingLine = $line;
return $this; return $this;
} }
/**
* @return string
*/
public function getLogStartingClass()
{
return $this->logStartingClass;
}
/** /**
* @param $classname * @param $classname
@ -137,6 +161,14 @@ class SQLQuery
$this->logStartingClass = $classname; $this->logStartingClass = $classname;
return $this; return $this;
} }
/**
* @return string
*/
public function getLogStartingFunction()
{
return $this->logStartingFunction;
}
/** /**
* @param $functionname * @param $functionname

View File

@ -1,55 +0,0 @@
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: function.tm_sql_status.php
* Name: tm_sql_status
* Purpose: Output info on SQL dabase queries
*
* Enable: add in config.inc.php line $this->blSQLStatusBox = true
* -------------------------------------------------------------
*/
function smarty_function_tm_sql_status($aParams, &$smarty)
{
$myConfig = \OxidEsales\Eshop\Core\Registry::getConfig();
// muss in config.inc.php gesetzt sein
$box = $myConfig->getConfigParam('blSQLStatusBox');
if ($box == false) {
return '';
}
$db = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(\OxidEsales\Eshop\Core\DatabaseProvider::FETCH_MODE_ASSOC);
$query = "SHOW STATUS WHERE Variable_name IN ( 'Com_select', 'Com_update', 'Com_insert', 'Com_delete' )";
$iSelects = $iDeletes = $iInserts = $iUpdates = 0;
$rows = $db->getAll($query);
foreach ($rows as $row) {
switch ($row['Variable_name']) {
case 'Com_select':
$iSelects = (int)$row['Value'];
break;
case 'Com_update':
$iUpdates = (int)$row['Value'];
break;
case 'Com_insert':
$iInserts = (int)$row['Value'];
break;
case 'Com_delete':
$iDeletes = (int)$row['Value'];
break;
default:
break;
}
}
$iSum = $iSelects + $iDeletes + $iInserts + $iUpdates;
$sTable = '<style>table#tmqueries { border: 1px solid black; position: fixed; bottom: 15px; left: 0; background-color: aliceblue; z-index: 90009} table#tmqueries td { padding: 6px; text-aligb:center }</style>';
$sTable .= '<table id="tmqueries">';
$sTable .= "<tr><td> All: $iSum </td><td> SELECT: $iSelects </td><td> UPDATE: $iUpdates </td><td> INSERT: $iInserts </td><td> DELETE: $iDeletes </td></tr>";
$sTable .= '</table>';
return $sTable;
}

View File

@ -12,5 +12,3 @@ function D3StartSQLLog($message = null) {
function D3StopSQLLog() { function D3StopSQLLog() {
\D3\OxidSqlLogger\OxidEsalesDatabase::disableLogger(); \D3\OxidSqlLogger\OxidEsalesDatabase::disableLogger();
} }
// (new \D3\OxidSqlLogger\AutoInstallSmaryPlugin())->runInstall();