-
-
Notifications
You must be signed in to change notification settings - Fork 39
Add lazy-load guard to detect N+1 relation queries #591
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
KalimeroMK
wants to merge
7
commits into
yiisoft:master
Choose a base branch
from
KalimeroMK:lazy-load-guard
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
27007b4
Add BeforeLazyRelationLoad event and LazyLoadGuard
KalimeroMK c1b49e7
Cover prevented BeforeLazyRelationLoad event
KalimeroMK 0a27a4f
Apply Rector suggestion in EventDispatcherProvider
KalimeroMK 37fc942
Fix double event dispatch in tests, count in strict mode, document event
KalimeroMK 174a71d
Drop Off mode and only/except from LazyLoadGuard
KalimeroMK 39f3a9d
Move lazy load guard to a separate trait without events
KalimeroMK c06c21e
Report lazy load starting from the second load of the same relation
KalimeroMK File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # LazyLoadGuardTrait | ||
|
|
||
| `LazyLoadGuardTrait` allows detecting N+1 queries caused by lazy loading of relations, i.e. reading a relation | ||
| that wasn't eager-loaded by `with()`. | ||
|
|
||
| ```php | ||
| use Yiisoft\ActiveRecord\ActiveRecord; | ||
| use Yiisoft\ActiveRecord\Trait\LazyLoadGuardTrait; | ||
|
|
||
| final class Customer extends ActiveRecord | ||
| { | ||
| use LazyLoadGuardTrait; | ||
| } | ||
| ``` | ||
|
|
||
| Every lazy load is registered by [LazyLoadGuard](../../src/LazyLoadGuard.php). Starting from the second lazy load | ||
| of the same relation it's reported according to the mode, since loading a relation once isn't an N+1 problem: | ||
|
|
||
| ```php | ||
| use Yiisoft\ActiveRecord\LazyLoadGuard; | ||
| use Yiisoft\ActiveRecord\LazyLoadGuardMode; | ||
|
|
||
| LazyLoadGuard::set(LazyLoadGuardMode::Log, $logger); | ||
| ``` | ||
|
|
||
| | Mode | Behavior | | ||
| |----------|---------------------------------------------------------------------------------------------------| | ||
| | `Log` | Default. Reports a PSR-3 warning with the relation name, the lazy load count and a stack trace | | ||
| | `Strict` | Throws `LogicException` | | ||
|
|
||
| In `Log` mode the logger is optional; when it's omitted the lazy loads are still counted and readable through | ||
| `LazyLoadGuard::getCounters()`, but nothing is written anywhere. `LazyLoadGuard::reset()` restores the defaults | ||
| and clears the counters. | ||
|
|
||
| The counters live until `LazyLoadGuard::reset()` is called. In long-running workers call it after each request. | ||
|
|
||
| The guard is meant for development and testing, e.g. `Strict` in the test suite and `Log` on staging. | ||
|
|
||
| > [!NOTE] | ||
| > The trait overrides `retrieveRelation()` method. If another trait of the model overrides it too, | ||
| > resolve the conflict using `insteadof` and `as` operators. | ||
|
|
||
| Back to [Extending Functionality With Traits](traits.md). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Yiisoft\ActiveRecord; | ||
|
|
||
| use Exception; | ||
| use LogicException; | ||
| use Psr\Log\LoggerInterface; | ||
| use Yiisoft\ActiveRecord\Trait\LazyLoadGuardTrait; | ||
|
|
||
| /** | ||
| * Detects N+1 queries caused by lazy loading of relations in models using {@see LazyLoadGuardTrait}. | ||
| */ | ||
| final class LazyLoadGuard | ||
| { | ||
| private static LazyLoadGuardMode $mode = LazyLoadGuardMode::Log; | ||
| private static ?LoggerInterface $logger = null; | ||
|
|
||
| /** | ||
| * @var int[] Number of detected lazy loads `[model_class::relation_name => count, ...]` | ||
| */ | ||
| private static array $counters = []; | ||
|
|
||
| /** | ||
| * Sets the mode of the guard and the logger used in the {@see LazyLoadGuardMode::Log} mode. | ||
| */ | ||
| public static function set(LazyLoadGuardMode $mode, ?LoggerInterface $logger = null): void | ||
| { | ||
| self::$mode = $mode; | ||
| self::$logger = $logger; | ||
| } | ||
|
|
||
| /** | ||
| * Registers a lazy load of the relation and reports it according to the mode, starting from the second lazy load | ||
| * of the same relation, since loading a relation once isn't an N+1 problem. | ||
| * | ||
| * @throws LogicException In the {@see LazyLoadGuardMode::Strict} mode. | ||
| */ | ||
| public static function check(ActiveRecordInterface $model, string $relationName): void | ||
| { | ||
| $modelClass = $model::class; | ||
| $relation = $modelClass . '::' . $relationName; | ||
|
|
||
| self::$counters[$relation] = (self::$counters[$relation] ?? 0) + 1; | ||
|
|
||
| if (self::$counters[$relation] === 1) { | ||
| return; | ||
| } | ||
|
|
||
| if (self::$mode === LazyLoadGuardMode::Strict) { | ||
| throw new LogicException("Relation \"$relation\" is lazy loaded."); | ||
| } | ||
|
|
||
| self::$logger?->warning( | ||
| "Relation \"$relation\" is lazy loaded.", | ||
| [ | ||
| 'model' => $modelClass, | ||
| 'relation' => $relationName, | ||
| 'count' => self::$counters[$relation], | ||
| 'trace' => (new Exception())->getTraceAsString(), | ||
| ], | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Returns the number of detected lazy loads `[model_class::relation_name => count, ...]`. | ||
| * | ||
| * @return int[] | ||
| */ | ||
| public static function getCounters(): array | ||
| { | ||
| return self::$counters; | ||
| } | ||
|
|
||
| /** | ||
| * Resets the mode, the logger and the counters to their defaults. | ||
| */ | ||
| public static function reset(): void | ||
| { | ||
| self::$mode = LazyLoadGuardMode::Log; | ||
| self::$logger = null; | ||
| self::$counters = []; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Yiisoft\ActiveRecord; | ||
|
|
||
| /** | ||
| * Modes of the {@see LazyLoadGuard}. | ||
| */ | ||
| enum LazyLoadGuardMode | ||
| { | ||
| /** Every lazy load is reported as a PSR-3 warning. */ | ||
| case Log; | ||
| /** Every lazy load throws a `LogicException`. */ | ||
| case Strict; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Yiisoft\ActiveRecord\Trait; | ||
|
|
||
| use Yiisoft\ActiveRecord\AbstractActiveRecord; | ||
| use Yiisoft\ActiveRecord\ActiveRecordInterface; | ||
| use Yiisoft\ActiveRecord\LazyLoadGuard; | ||
|
|
||
| /** | ||
| * Trait to detect N+1 queries caused by lazy loading of relations. | ||
| * | ||
| * @see LazyLoadGuard | ||
| * @see AbstractActiveRecord::retrieveRelation() | ||
| */ | ||
| trait LazyLoadGuardTrait | ||
| { | ||
| protected function retrieveRelation(string $name): ActiveRecordInterface|array|null | ||
| { | ||
| LazyLoadGuard::check($this, $name); | ||
|
|
||
| return parent::retrieveRelation($name); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Yiisoft\ActiveRecord\Tests\Driver\Mssql; | ||
|
|
||
| use Yiisoft\ActiveRecord\Tests\Support\MssqlHelper; | ||
| use Yiisoft\Db\Connection\ConnectionInterface; | ||
|
|
||
| final class LazyLoadGuardTest extends \Yiisoft\ActiveRecord\Tests\LazyLoadGuardTest | ||
| { | ||
| protected static function createConnection(): ConnectionInterface | ||
| { | ||
| return (new MssqlHelper())->createConnection(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Yiisoft\ActiveRecord\Tests\Driver\Mysql; | ||
|
|
||
| use Yiisoft\ActiveRecord\Tests\Support\MysqlHelper; | ||
| use Yiisoft\Db\Connection\ConnectionInterface; | ||
|
|
||
| final class LazyLoadGuardTest extends \Yiisoft\ActiveRecord\Tests\LazyLoadGuardTest | ||
| { | ||
| protected static function createConnection(): ConnectionInterface | ||
| { | ||
| return (new MysqlHelper())->createConnection(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Yiisoft\ActiveRecord\Tests\Driver\Oracle; | ||
|
|
||
| use Yiisoft\ActiveRecord\Tests\Support\OracleHelper; | ||
| use Yiisoft\Db\Connection\ConnectionInterface; | ||
|
|
||
| final class LazyLoadGuardTest extends \Yiisoft\ActiveRecord\Tests\LazyLoadGuardTest | ||
| { | ||
| protected static function createConnection(): ConnectionInterface | ||
| { | ||
| return (new OracleHelper())->createConnection(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Yiisoft\ActiveRecord\Tests\Driver\Pgsql; | ||
|
|
||
| use Yiisoft\ActiveRecord\Tests\Support\PgsqlHelper; | ||
| use Yiisoft\Db\Connection\ConnectionInterface; | ||
|
|
||
| final class LazyLoadGuardTest extends \Yiisoft\ActiveRecord\Tests\LazyLoadGuardTest | ||
| { | ||
| protected static function createConnection(): ConnectionInterface | ||
| { | ||
| return (new PgsqlHelper())->createConnection(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Yiisoft\ActiveRecord\Tests\Driver\Sqlite; | ||
|
|
||
| use Yiisoft\ActiveRecord\Tests\Support\SqliteHelper; | ||
| use Yiisoft\Db\Connection\ConnectionInterface; | ||
|
|
||
| final class LazyLoadGuardTest extends \Yiisoft\ActiveRecord\Tests\LazyLoadGuardTest | ||
| { | ||
| protected static function createConnection(): ConnectionInterface | ||
| { | ||
| return (new SqliteHelper())->createConnection(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.