mobility icon indicating copy to clipboard operation
mobility copied to clipboard

eager_load and pluck builds the wrong query

Open elcuervo opened this issue 1 year ago • 0 comments

Context

First of all: Thank you for all your work on this gem. It's our core framework for translations here at Unsplash and it made our extensions easy to implement.

Debugging some performance issues on produce I noticed that we were returning extra records during some relation calls. Specifically n extra records as much as languages we have.

Plugins

Mobility.configure do
  # PLUGINS
  plugins do
    backend :key_value

    active_record

    reader
    writer

    column_fallback true

    backend_reader
    query
    cache

    presence
    fallthrough_accessors
  end
end
  • We use the default backend and we are using to improve the calls.
  • This bug affects calls with pluck.
  • We also use callback_column true and fallthrough_accessors
  • We add the i18n scope when the default locale is not in use.

Expected Behavior

We should be getting the same records on the english version as with the other languages.

Actual Behavior

When querying a relation with pluck we end up with extra records

I created this repo with a reproducible test https://github.com/elcuervo/mobility_bug/blob/main/test/models/post_test.rb

Possible Fix

I don't know if is purely Mobility related or it has some ties with ActiveRecord. I notice that the query being built as two LEFT OUTER JOIN instead of a secondary INNER JOIN.

From the documentation:

Executing the calls:

Post Load (0.5ms)  SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC LIMIT ?  [["LIMIT", 1]]
  Comment Pluck (0.5ms)  SELECT "Comment_text_es_string_translations"."value" FROM "comments" LEFT OUTER JOIN "mobility_string_translations" ON "mobility_string_translations"."translatable_type" = ? AND "mobility_string_translations"."key" = ? AND "mobility_string_translations"."translatable_id" = "comments"."id" LEFT OUTER JOIN "mobility_string_translations" "Comment_text_es_string_translations" ON "Comment_text_es_string_translations"."key" = 'text' AND "Comment_text_es_string_translations"."locale" = 'es' AND "Comment_text_es_string_translations"."translatable_type" = 'Comment' AND "Comment_text_es_string_translations"."translatable_id" = "comments"."id" WHERE "comments"."post_id" = ?  [["translatable_type", "Comment"], ["key", "text"], ["post_id", 2]]

elcuervo avatar Jun 07 '23 13:06 elcuervo