JSONAPI-Resources / JSONAPI-Resources/jsonapi-resources

Reducing N+1 queries by eager loading

オープン
#485 コメント 10 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

Type: Maintenance
主要言語
Ruby
スター
2.3k
フォーク
546
PR マージ指標
30日以内にマージされた PR はありません

説明

I read through the documentation and couldn't find a built-in solution to this problem. When certain models are serialized we need to make sure that the query to retrieve that entity always adds an includes to avoid all the lazy loaded N+1 queries. We can do this via records as long as the request is on the resources controller. If it's not then I couldn't see a place to extend it.

Let me give an example

class ProjectResource
  has_one :company
end
class CompanyResource
  attribute :plan_start_at

  def plan_start_at
    @model.subscription.created_at
  end
end

As you'll notice each time a company is rendered it is going to retrieve a value out of it's subscription. However, the problem comes in when we request a URL like this

/api/projects?include=company

It's using the records method off of the projects resource and even when it goes to process the include on company it's not calling records on the company resource so we end up with a separate query for every companies subscription.

Now, from what I can tell maybe this is supposed to be taken care of by also requesting the subscription like this

/api/projects?include=company,company.subscription

However this doesn't completely work since I don't need the subscription object and requesting the subscription isn't a concern of the client (since we simply need the subscription in order to calculate a property on the company.)

コントリビューションガイド

このリポジトリのコントリビューションガイドは索引されていません

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、リソースコントローラー、recordsメソッド、および ProjectResource と CompanyResource について説明されている include 処理を追跡します。/api/projects?include=company のケースを再現し、company.subscription と比較します。computed 属性で使用される依存データが、クライアントにそのリレーションを要求させることなく eager load されれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
rails, ruby
領域
api, backend, performance
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。