Skip to content

Commit

Permalink
Improve CheckUsage query perf (#4650)
Browse files Browse the repository at this point in the history
  • Loading branch information
zoldar authored Oct 2, 2024
1 parent ec2a560 commit 35c8010
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions lib/workers/check_usage.ex
Original file line number Diff line number Diff line change
Expand Up @@ -40,29 +40,31 @@ defmodule Plausible.Workers.CheckUsage do
from(s in Subscription,
order_by: [desc: s.inserted_at],
where: s.user_id == parent_as(:user).id,
where:
s.status in [
^Subscription.Status.active(),
^Subscription.Status.past_due(),
^Subscription.Status.deleted()
],
where: not is_nil(s.last_bill_date),
# Accounts for situations like last_bill_date==2021-01-31 AND today==2021-03-01. Since February never reaches the 31st day, the account is checked on 2021-03-01.
where: s.next_bill_date >= ^today,
where:
least(day_of_month(s.last_bill_date), day_of_month(last_day_of_month(^yesterday))) ==
day_of_month(^yesterday),
limit: 1
)

active_subscribers =
Repo.all(
from(u in User,
as: :user,
inner_lateral_join: s in subquery(last_subscription_query),
on: true,
inner_join: s in Plausible.Billing.Subscription,
on: s.user_id == u.id,
inner_lateral_join: ls in subquery(last_subscription_query),
on: ls.id == s.id,
left_join: ep in Plausible.Billing.EnterprisePlan,
on: ep.user_id == u.id,
where:
s.status in [
^Subscription.Status.active(),
^Subscription.Status.past_due(),
^Subscription.Status.deleted()
],
where: not is_nil(s.last_bill_date),
# Accounts for situations like last_bill_date==2021-01-31 AND today==2021-03-01. Since February never reaches the 31st day, the account is checked on 2021-03-01.
where: s.next_bill_date >= ^today,
where:
least(day_of_month(s.last_bill_date), day_of_month(last_day_of_month(^yesterday))) ==
day_of_month(^yesterday),
order_by: u.id,
preload: [subscription: s, enterprise_plan: ep]
)
Expand Down

0 comments on commit 35c8010

Please sign in to comment.