shirakaba-audit-queries
Find and fix N+1 queries and other excess statements in a Shirakaba application using StatementLog, the shirakaba/phpstan query-in-loop check and ORM eager loading. Use when asked about slow endpoints
Files1
View on GitHubSKILL.mdpackages/docs/skills/shirakaba-audit-queries/SKILL.md
GitHubAudit database queries in a Shirakaba application
Read the testing chapter (vendor/shirakaba/docs/guide/09-testing.md) and the entities section
of vendor/shirakaba/docs/guide/06-database.md first.
- Find loops statically. Enable
reportQueriesInLoops: trueunderparameters.shirakabainphpstan.neonand runvendor/bin/phpstan analyse. Every database call inside a loop is reported. - Measure per request. In a test, add a
StatementLogobserver to the application ($app->observe($log)), call the endpoint withTestClient, and read$log->last()(the statements of the last request),$log->repeated()and$log->describe(). - Fix the shape, not the symptom.
- Related rows: request them with
with('user', 'files', 'reply.user')and read them through a projection withinto(). Each relation level is oneINquery, and leaf belongs-to and many-to-many relations share queries across paths. - Counts:
withCount('comments')and anint $commentsCountparameter. - Values from other tables: a
#[Computed]parameter filled by theinto()callback, which receives every loaded entity at once (nested ones as a second list) so one query serves the page. - Filters across relations:
whereHas()instead of loading and filtering in PHP.
- Related rows: request them with
- Pin the result. Assert the statement count in the test, with the reason:
self::assertLessThanOrEqual(5, count($log->last()), $log->describe()).
Verify
vendor/bin/phpstan analysereports no query in a loop- the test with the pinned statement count passes, and the rest of the suite still passes