Skip to content

Commit

Permalink
Refactor old laravel query code (#1518)
Browse files Browse the repository at this point in the history
  • Loading branch information
erikn69 authored Feb 13, 2024
1 parent 9f00dcd commit 9ec8bbb
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 28 deletions.
29 changes: 13 additions & 16 deletions src/DataCollector/QueryCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,12 +139,9 @@ public function startMemoryUsage()

/**
*
* @param string $query
* @param array $bindings
* @param float $time
* @param \Illuminate\Database\Connection $connection
* @param \Illuminate\Database\Events\QueryExecuted $query
*/
public function addQuery($query, $bindings, $time, $connection)
public function addQuery($query)
{
$this->queryCount++;

Expand All @@ -154,24 +151,24 @@ public function addQuery($query, $bindings, $time, $connection)

$limited = $this->softLimit && $this->queryCount > $this->softLimit;


$sql = (string) $query->sql;
$explainResults = [];
$time = $time / 1000;
$time = $query->time / 1000;
$endTime = microtime(true);
$startTime = $endTime - $time;
$hints = $this->performQueryAnalysis($query);
$hints = $this->performQueryAnalysis($sql);

$pdo = null;
try {
$pdo = $connection->getPdo();
$pdo = $query->connection->getPdo();
} catch (\Throwable $e) {
// ignore error for non-pdo laravel drivers
}
$bindings = $connection->prepareBindings($bindings);
$bindings = $query->connection->prepareBindings($query->bindings);

// Run EXPLAIN on this query (if needed)
if (!$limited && $this->explainQuery && $pdo && preg_match('/^\s*(' . implode('|', $this->explainTypes) . ') /i', $query)) {
$statement = $pdo->prepare('EXPLAIN ' . $query);
if (!$limited && $this->explainQuery && $pdo && preg_match('/^\s*(' . implode('|', $this->explainTypes) . ') /i', $sql)) {
$statement = $pdo->prepare('EXPLAIN ' . $sql);
$statement->execute($bindings);
$explainResults = $statement->fetchAll(\PDO::FETCH_CLASS);
}
Expand Down Expand Up @@ -199,7 +196,7 @@ public function addQuery($query, $bindings, $time, $connection)
}
}

$query = preg_replace($regex, addcslashes($binding, '$'), $query, 1);
$sql = preg_replace($regex, addcslashes($binding, '$'), $sql, 1);
}
}

Expand All @@ -213,16 +210,16 @@ public function addQuery($query, $bindings, $time, $connection)
}

$this->queries[] = [
'query' => $query,
'query' => $sql,
'type' => 'query',
'bindings' => !$limited ? $this->getDataFormatter()->escapeBindings($bindings) : null,
'start' => $startTime,
'time' => $time,
'memory' => $this->lastMemoryUsage ? memory_get_usage(false) - $this->lastMemoryUsage : 0,
'source' => $source,
'explain' => $explainResults,
'connection' => $connection->getDatabaseName(),
'driver' => $connection->getConfig('driver'),
'connection' => $query->connection->getDatabaseName(),
'driver' => $query->connection->getConfig('driver'),
'hints' => ($this->showHints && !$limited) ? $hints : null,
'show_copy' => $this->showCopyButton,
];
Expand Down
11 changes: 3 additions & 8 deletions src/LaravelDebugbar.php
Original file line number Diff line number Diff line change
Expand Up @@ -371,20 +371,15 @@ function ($level, $message = null, $context = null) use ($logger) {

try {
$db->listen(
function (\Illuminate\Database\Events\QueryExecuted $query) use ($db, $queryCollector) {
function (\Illuminate\Database\Events\QueryExecuted $query) {
if (!app(static::class)->shouldCollect('db', true)) {
return; // Issue 776 : We've turned off collecting after the listener was attached
}

$bindings = $query->bindings;
$time = $query->time;
$connection = $query->connection;
$query = $query->sql;

//allow collecting only queries slower than a specified amount of milliseconds
$threshold = app('config')->get('debugbar.options.db.slow_threshold', false);
if (!$threshold || $time > $threshold) {
$queryCollector->addQuery((string)$query, $bindings, $time, $connection);
if (!$threshold || $query->time > $threshold) {
$this['queries']->addQuery($query);
}
}
);
Expand Down
9 changes: 5 additions & 4 deletions tests/DataCollector/QueryCollectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Barryvdh\Debugbar\Tests\DataCollector;

use Barryvdh\Debugbar\Tests\TestCase;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Arr;

Expand All @@ -18,12 +19,12 @@ public function testItReplacesQuestionMarksBindingsCorrectly()

/** @var \Barryvdh\Debugbar\DataCollector\QueryCollector $collector */
$collector = debugbar()->getCollector('queries');
$collector->addQuery(
$collector->addQuery(new QueryExecuted(
"SELECT ('[1, 2, 3]'::jsonb ?? ?) as a, ('[4, 5, 6]'::jsonb ??| ?) as b, 'hello world ? example ??' as c",
[3, '{4}'],
0,
$this->app['db']->connection()
);
));

tap($collector->collect(), function (array $collection) {
$this->assertEquals(1, $collection['nb_statements']);
Expand All @@ -44,12 +45,12 @@ public function testDollarBindingsArePresentedCorrectly()

/** @var \Barryvdh\Debugbar\DataCollector\QueryCollector $collector */
$collector = debugbar()->getCollector('queries');
$collector->addQuery(
$collector->addQuery(new QueryExecuted(
"SELECT a FROM b WHERE c = ? AND d = ? AND e = ?",
['$10', '$2y$10_DUMMY_BCRYPT_HASH', '$_$$_$$$_$2_$3'],
0,
$this->app['db']->connection()
);
));

tap(Arr::first($collector->collect()['statements']), function (array $statement) {
$this->assertEquals(
Expand Down

0 comments on commit 9ec8bbb

Please sign in to comment.