diff --git a/composer.json b/composer.json index ceafd91..680d021 100644 --- a/composer.json +++ b/composer.json @@ -17,11 +17,11 @@ ], "require": { "php": "^7.1 || ^8.0", - "illuminate/support": "^5.5 || ^6.0 || ^7.0 || ^8.0 || ^9.0" + "illuminate/support": "^5.5 || ^6.0 || ^7.0 || ^8.0 || ^9.0|^10.0 || ^11.0" }, "require-dev": { "laravel/legacy-factories": "^1.0", - "orchestra/testbench": "^3.0 || ^4.0 || ^5.0 || ^6.0", + "orchestra/testbench": "^3.0 || ^4.0 || ^5.0 || ^6.0|^8.0", "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" }, "autoload": { @@ -37,7 +37,6 @@ "scripts": { "test": "vendor/bin/phpunit", "test-coverage": "vendor/bin/phpunit --coverage-html coverage" - }, "config": { "sort-packages": true diff --git a/config/config.php b/config/config.php index 03f5ec7..84f1765 100644 --- a/config/config.php +++ b/config/config.php @@ -9,7 +9,7 @@ /* * Threshold level for the N+1 query detection. If a relation query will be - * executed more then this amount, the detector will notify you about it. + * executed more than this amount, the detector will notify you about it. */ 'threshold' => (int) env('QUERY_DETECTOR_THRESHOLD', 1), diff --git a/src/Outputs/Console.php b/src/Outputs/Console.php index 6b4680f..7a90366 100644 --- a/src/Outputs/Console.php +++ b/src/Outputs/Console.php @@ -42,10 +42,10 @@ protected function getOutputContent(Collection $detectedQueries) $output .= "console.warn('Found the following N+1 queries in this request:\\n\\n"; foreach ($detectedQueries as $detectedQuery) { $output .= "Model: ".addslashes($detectedQuery['model'])." => Relation: ".addslashes($detectedQuery['relation']); - $output .= " - You should add \"with(\'".$detectedQuery['relation']."\')\" to eager-load this relation."; + $output .= " - You should add \"with(\'".addslashes($detectedQuery['relation'])."\')\" to eager-load this relation."; $output .= "\\n\\n"; $output .= "Model: ".addslashes($detectedQuery['model'])."\\n"; - $output .= "Relation: ".$detectedQuery['relation']."\\n"; + $output .= "Relation: ".addslashes($detectedQuery['relation'])."\\n"; $output .= "Num-Called: ".$detectedQuery['count']."\\n"; $output .= "\\n"; $output .= 'Call-Stack:\\n'; diff --git a/src/QueryDetector.php b/src/QueryDetector.php index 0d3dcc6..70c3c7a 100755 --- a/src/QueryDetector.php +++ b/src/QueryDetector.php @@ -14,15 +14,29 @@ class QueryDetector { /** @var Collection */ private $queries; + /** + * @var bool + */ + private $booted = false; - public function __construct() + private function resetQueries() { $this->queries = Collection::make(); } + public function __construct() + { + $this->resetQueries(); + } + public function boot() { - DB::listen(function($query) { + if ($this->booted) { + $this->resetQueries(); + return; + } + + DB::listen(function ($query) { $backtrace = collect(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 50)); $this->logQuery($query, $backtrace); @@ -32,6 +46,8 @@ public function boot() app()->singleton($outputType); app($outputType)->boot(); } + + $this->booted = true; } public function isEnabled(): bool @@ -52,13 +68,13 @@ public function logQuery($query, Collection $backtrace) }); // The query is coming from an Eloquent model - if (! is_null($modelTrace)) { + if (!is_null($modelTrace)) { /* * Relations get resolved by either calling the "getRelationValue" method on the model, * or if the class itself is a Relation. */ $relation = $backtrace->first(function ($trace) { - return Arr::get($trace, 'function') === 'getRelationValue' || Arr::get($trace, 'class') === Relation::class ; + return Arr::get($trace, 'function') === 'getRelationValue' || Arr::get($trace, 'class') === Relation::class; }); // We try to access a relation @@ -74,11 +90,15 @@ public function logQuery($query, Collection $backtrace) } $sources = $this->findSource($backtrace); + + if (empty($sources)) { + return; + } $key = md5($query->sql . $model . $relationName . $sources[0]->name . $sources[0]->line); - $count = Arr::get($this->queries, $key.'.count', 0); - $time = Arr::get($this->queries, $key.'.time', 0); + $count = Arr::get($this->queries, $key . '.count', 0); + $time = Arr::get($this->queries, $key . '.time', 0); $this->queries[$key] = [ 'count' => ++$count, @@ -106,7 +126,7 @@ protected function findSource($stack) public function parseTrace($index, array $trace) { - $frame = (object) [ + $frame = (object)[ 'index' => $index, 'name' => null, 'line' => isset($trace['line']) ? $trace['line'] : '?', @@ -191,7 +211,7 @@ protected function getOutputTypes() { $outputTypes = config('querydetector.output'); - if (! is_array($outputTypes)) { + if (!is_array($outputTypes)) { $outputTypes = [$outputTypes]; } diff --git a/tests/QueryDetectorTest.php b/tests/QueryDetectorTest.php index b428e2a..b467d85 100644 --- a/tests/QueryDetectorTest.php +++ b/tests/QueryDetectorTest.php @@ -34,6 +34,54 @@ public function it_detects_n1_query_on_properties() $this->assertSame('profile', $queries[0]['relation']); } + /** @test */ + public function it_detects_n1_query_on_multiple_requests() + { + Route::get('/', function (){ + $authors = Author::get(); + + foreach ($authors as $author) { + $author->profile; + } + }); + + // first request + $this->get('/'); + $queries = app(QueryDetector::class)->getDetectedQueries(); + $this->assertCount(1, $queries); + $this->assertSame(Author::count(), $queries[0]['count']); + $this->assertSame(Author::class, $queries[0]['model']); + $this->assertSame('profile', $queries[0]['relation']); + + // second request + $this->get('/'); + $queries = app(QueryDetector::class)->getDetectedQueries(); + $this->assertCount(1, $queries); + $this->assertSame(Author::count(), $queries[0]['count']); + $this->assertSame(Author::class, $queries[0]['model']); + $this->assertSame('profile', $queries[0]['relation']); + } + + /** @test */ + public function it_does_not_detect_a_false_n1_query_on_multiple_requests() + { + Route::get('/', function (){ + $authors = Author::with("profile")->get(); + + foreach ($authors as $author) { + $author->profile; + } + }); + + // first request + $this->get('/'); + $this->assertCount(0, app(QueryDetector::class)->getDetectedQueries()); + + // second request + $this->get('/'); + $this->assertCount(0, app(QueryDetector::class)->getDetectedQueries()); + } + /** @test */ public function it_ignores_eager_loaded_relationships() {