avram icon indicating copy to clipboard operation
avram copied to clipboard

preloads for has_one associations don't always set limit 1

Open BrucePerens opened this issue 4 years ago • 1 comments

This is how a has_one association in my application is preloaded:

 ▸ Model URLPath. Query SELECT <lots of fields> FROM url_paths WHERE url_paths.manufacturer_id = ANY ($1). Args [["1"]]. Duration 1.93ms

Note that there is no LIMIT 1. Some of the query implementations for this association don't invoke first or first? and thus don't get the limit. If I manually add a limit(1) to my queries, at first glance it seems to run faster, which is what I would expect.

BrucePerens avatar Jan 08 '21 22:01 BrucePerens

That's a good idea. One issue to figure out is that when you call UserQuery.new.preload_has_one_assoc we only issue one sql request for loading all the has_one_assoc's. So if there are 20 User's there's only two sql queries (one for the users and another for the association) so limiting the preload query to one would mean only one user gets it's association loaded.

Here's the line where we add the specifics onto the preload query https://github.com/luckyframework/avram/blob/b44793857899a06b4c3b9d45cdd60f0164ec9fd9/src/avram/associations/has_one.cr#L88

matthewmcgarvey avatar Jan 08 '21 23:01 matthewmcgarvey