1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-07-19 05:09:38 +02:00

Refactor syncing? method in Family model to optimize query performance. Moved visible scope to the beginning and adjusted joins and where conditions to leverage composite indexing for improved efficiency.

This commit is contained in:
Josh Pigford 2025-06-01 06:30:38 -05:00
parent 1f8a994b4e
commit 870b543640

View file

@ -37,10 +37,20 @@ class Family < ApplicationRecord
# If any accounts or plaid items are syncing, the family is also syncing, even if a formal "Family Sync" is not running. # If any accounts or plaid items are syncing, the family is also syncing, even if a formal "Family Sync" is not running.
def syncing? def syncing?
Sync.joins("LEFT JOIN plaid_items ON plaid_items.id = syncs.syncable_id AND syncs.syncable_type = 'PlaidItem'") # Check for any in-progress syncs that belong directly to the family, to one of the
# family's accounts, or to one of the family's Plaid items. By moving the `visible`
# scope to the beginning we narrow down the candidate rows **before** performing the
# joins and by explicitly constraining the `syncable_type` for the direct Family
# match we allow Postgres to use the composite index on `(syncable_type, syncable_id)`.
Sync.visible
.joins("LEFT JOIN accounts ON accounts.id = syncs.syncable_id AND syncs.syncable_type = 'Account'") .joins("LEFT JOIN accounts ON accounts.id = syncs.syncable_id AND syncs.syncable_type = 'Account'")
.where("syncs.syncable_id = ? OR accounts.family_id = ? OR plaid_items.family_id = ?", id, id, id) .joins("LEFT JOIN plaid_items ON plaid_items.id = syncs.syncable_id AND syncs.syncable_type = 'PlaidItem'")
.visible .where(
"(syncs.syncable_type = 'Family' AND syncs.syncable_id = :family_id) OR " \
"accounts.family_id = :family_id OR " \
"plaid_items.family_id = :family_id",
family_id: id
)
.exists? .exists?
end end