-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Ruby: Query for N+1 queries problem #18317
base: main
Are you sure you want to change the base?
Conversation
QHelp previews: ruby/ql/src/queries/performance/ActiveRecordAssociationQueriedInLoop.qhelpActiveRecord association queried in loopPerforming database queries in a loop can be inefficient compared to performing a single query up front that retrieves all the data at once. ORMs such as ActiveRecord implicitly query the database when certain members of an object are being accessed. But if such a member is accessed in a loop, it can result in a separate query for each iteration. ActiveRecord provides a way to eagerly load associated data using the RecommendationIn ActiveRecord, use ExampleThe following example code gets the names of all podcasts followed by a user: def get_podcast_names(user):
user.podcasts.map do |podcast|
podcast.name
end
end However, the call to def get_podcast_names(user):
user.podcasts.includes(:name).map do |podcast|
podcast.name
end
end Now all the associated podcast names are loaded up front with a single SQL query, and the call to References
|
* @tags performance | ||
*/ | ||
|
||
// TODO: is a DB query executed as soon as the assocation is called, or when a field on the associated object is used? |
Check warning
Code scanning / CodeQL
Misspelling Warning
node1 = call.getReceiver() and | ||
node2 = call | ||
| | ||
call.getMethodName() = ["to_a"] and |
Check warning
Code scanning / CodeQL
Singleton set literal Warning
call.getMethodName() = queryBuilderMethodName() and | ||
// Block flow through a few methods: | ||
// - none: produces no output | ||
// - select: modelled more precisely below |
Check warning
Code scanning / CodeQL
Misspelling Warning
No description provided.