forked from houdiniproject/houdini
-
Notifications
You must be signed in to change notification settings - Fork 0
Event Metrics Query performance #1227
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
caseyhelbling
wants to merge
5
commits into
supporter_level_goal
Choose a base branch
from
feature/clh/increase-db-size-and-indexes
base: supporter_level_goal
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
42edea8
Attempt to get local event query performance to return results
caseyhelbling 6119bfd
Tweak UI to add number of each event and whitespace between each block
caseyhelbling 529b88b
Rewrite event metrics query so it actually returns
caseyhelbling 6e1d88f
Linter
caseyhelbling 3acd120
Remove redundant index
caseyhelbling File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,86 +1,148 @@ | ||
| # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later | ||
|
|
||
| module QueryEventMetrics | ||
| def self.expression(additional_selects = []) | ||
| selects = [ | ||
| "coalesce(tickets.total, 0) AS total_attendees", | ||
| "coalesce(tickets.checked_in_count, 0) AS checked_in_count", | ||
| "coalesce(ticket_payments.total_paid, 0) AS tickets_total_paid", | ||
| "coalesce(donations.payment_total, 0) AS donations_total_paid", | ||
| "coalesce(ticket_payments.total_paid, 0) + coalesce(donations.payment_total, 0) AS total_paid" | ||
| ] | ||
|
|
||
| tickets_sub = Qx.select("event_id", "SUM(quantity) AS total", "SUM(tickets.checked_in::int) AS checked_in_count") | ||
| .from("tickets") | ||
| .group_by("event_id") | ||
| .as("tickets") | ||
|
|
||
| ticket_payments_subquery = Qx.select("payment_id", "MAX(event_id) AS event_id").from("tickets").group_by("payment_id").as("tickets") | ||
|
|
||
| ticket_payments_sub = Qx.select("SUM(payments.gross_amount) AS total_paid", "tickets.event_id") | ||
| .from(:payments) | ||
| .join(ticket_payments_subquery, "payments.id=tickets.payment_id") | ||
| .group_by("tickets.event_id") | ||
| .as("ticket_payments") | ||
|
|
||
| donations_sub = Qx.select("event_id", "SUM(payments.gross_amount) as payment_total") | ||
| .from("donations") | ||
| .group_by("event_id") | ||
| .left_join("payments", "donations.id=payments.donation_id") | ||
| .as("donations") | ||
|
|
||
| selects = selects.concat(additional_selects) | ||
| Qx.select(*selects) | ||
| .from("events") | ||
| .left_join( | ||
| [tickets_sub, "tickets.event_id = events.id"], | ||
| [donations_sub, "donations.event_id = events.id"], | ||
| [ticket_payments_sub, "ticket_payments.event_id=events.id"] | ||
| ) | ||
| end | ||
| # For now limit to 1000 | ||
| QUERY_MAX_LIMIT = 1_000 | ||
|
|
||
| def self.with_event_ids(event_ids) | ||
| return [] if event_ids.empty? | ||
| QueryEventMetrics.expression.where("events.id in ($ids)", ids: event_ids).execute | ||
| return [] if event_ids.blank? | ||
|
|
||
| events = Event.select(:id, :name, :venue_name, :address, :city, :state_code, | ||
| :zip_code, :start_datetime, :end_datetime, :organizer_email) | ||
| .where(id: event_ids) | ||
| .limit(QUERY_MAX_LIMIT) | ||
|
|
||
| add_metrics_to_events(events) | ||
| end | ||
|
|
||
| def self.for_listings(id_type, id, params) | ||
| selects = [ | ||
| "events.id", | ||
| "events.name", | ||
| "events.venue_name", | ||
| "events.address", | ||
| "events.city", | ||
| "events.state_code", | ||
| "events.zip_code", | ||
| "events.start_datetime", | ||
| "events.end_datetime", | ||
| "events.organizer_email" | ||
| ] | ||
|
|
||
| exp = QueryEventMetrics.expression(selects) | ||
|
|
||
| if id_type == "profile" | ||
| exp = exp.and_where(["events.profile_id = $id", id: id]) | ||
| end | ||
| if id_type == "nonprofit" | ||
| exp = exp.and_where(["events.nonprofit_id = $id", id: id]) | ||
| def self.for_listings(id_type, profile_or_nonprofit_id, params) | ||
| events = base_events(id_type, profile_or_nonprofit_id, params) | ||
| return [] if events.blank? | ||
|
|
||
| # Add metrics to the events | ||
| add_metrics_to_events(events) | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def self.base_events(id_type, id, params) | ||
| query = Event.select(:id, :name, :venue_name, :address, :city, :state_code, | ||
| :zip_code, :start_datetime, :end_datetime, :organizer_email) | ||
|
|
||
| case id_type | ||
| when "profile" | ||
| query = query.where(profile_id: id) | ||
| when "nonprofit" | ||
| query = query.where(nonprofit_id: id) | ||
| else | ||
| raise "Unknown id_type #{id_type}" | ||
| end | ||
|
|
||
| if params["active"].present? | ||
| exp = exp | ||
| .and_where(["events.end_datetime >= $date", date: Time.now]) | ||
| .and_where(["events.published = TRUE AND coalesce(events.deleted, FALSE) = FALSE"]) | ||
| query = query | ||
| .where("end_datetime >= ?", Time.current) | ||
| .where(published: true) | ||
| .where("COALESCE(deleted, false) = false") | ||
| elsif params["past"].present? | ||
| query = query | ||
| .where("end_datetime < ?", Time.current) | ||
| .where(published: true) | ||
| .where("COALESCE(deleted, false) = false") | ||
| elsif params["unpublished"].present? | ||
| query = query | ||
| .where("COALESCE(published, false) = false") | ||
| .where("COALESCE(deleted, false) = false") | ||
| elsif params["deleted"].present? | ||
| query = query.where(deleted: true) | ||
| end | ||
| if params["past"].present? | ||
| exp = exp | ||
| .and_where(["events.end_datetime < $date", date: Time.now]) | ||
| .and_where(["events.published = TRUE AND coalesce(events.deleted, FALSE) = FALSE"]) | ||
|
|
||
| query = query.order(end_datetime: :desc) | ||
| query.limit(QUERY_MAX_LIMIT) | ||
| end | ||
|
|
||
| def self.add_metrics_to_events(events) | ||
| return [] if events.blank? | ||
|
|
||
| event_ids = events.pluck(:id) | ||
|
|
||
| ticket_metrics = ticket_metrics(event_ids) | ||
| donation_metrics = donation_metrics(event_ids) | ||
| payment_metrics = payment_metrics(event_ids) | ||
|
|
||
| events.map do |event| | ||
| build_event_result(event, | ||
| ticket_metrics[event.id], | ||
| donation_metrics[event.id], | ||
| payment_metrics[event.id]) | ||
| end | ||
| if params["unpublished"].present? | ||
| exp = exp.and_where(["coalesce(events.published, FALSE) = FALSE AND coalesce(events.deleted, FALSE) = FALSE"]) | ||
| end | ||
|
|
||
| def self.build_event_result(event, tickets, donations, payments) | ||
| tickets ||= {total: 0, checked_in_count: 0} | ||
| donations ||= {donation_total: 0} | ||
| payments ||= {payment_total: 0} | ||
|
|
||
| { | ||
| "id" => event.id, | ||
| "name" => event.name, | ||
| "venue_name" => event.venue_name, | ||
| "address" => event.address, | ||
| "city" => event.city, | ||
| "state_code" => event.state_code, | ||
| "zip_code" => event.zip_code, | ||
| "start_datetime" => event.start_datetime, | ||
| "end_datetime" => event.end_datetime, | ||
| "organizer_email" => event.organizer_email, | ||
| "total_attendees" => tickets[:total], | ||
| "checked_in_count" => tickets[:checked_in_count], | ||
| "tickets_total_paid" => payments[:payment_total], | ||
| "donations_total_paid" => donations[:donation_total], | ||
| "total_paid" => payments[:payment_total] + donations[:donation_total] | ||
| } | ||
| end | ||
|
|
||
| def self.ticket_metrics(event_ids) | ||
| return {} if event_ids.blank? | ||
|
|
||
| ticket_data = Ticket.where(event_id: event_ids) | ||
| .group(:event_id) | ||
| .pluck(:event_id, | ||
| Arel.sql("COALESCE(SUM(quantity), 0) as total"), | ||
| Arel.sql("COALESCE(SUM(CASE WHEN checked_in THEN 1 ELSE 0 END), 0) as checked_in_count")) | ||
|
|
||
| ticket_data.to_h do |event_id, total, checked_in_count| | ||
| [event_id, {total:, checked_in_count:}] | ||
| end | ||
| if params["deleted"].present? | ||
| exp = exp.and_where(["events.deleted = TRUE"]) | ||
| end | ||
|
|
||
| def self.donation_metrics(event_ids) | ||
| return {} if event_ids.blank? | ||
|
|
||
| donation_data = Donation.left_joins(:payments) | ||
| .where(event_id: event_ids) | ||
| .group(:event_id) | ||
| .pluck(:event_id, Arel.sql("COALESCE(SUM(payments.gross_amount), 0) as donation_total")) | ||
|
|
||
| donation_data.to_h do |event_id, donation_total| | ||
| [event_id, {donation_total:}] | ||
| end | ||
| end | ||
|
|
||
| def self.payment_metrics(event_ids) | ||
| return {} if event_ids.blank? | ||
|
|
||
| # TODO: consider deleted tickets too | ||
| payment_data = Payment.joins(:tickets) | ||
| .where(tickets: {event_id: event_ids}) | ||
| .group("tickets.event_id") | ||
| .pluck("tickets.event_id", Arel.sql("COALESCE(SUM(payments.gross_amount), 0) as payment_total")) | ||
|
|
||
| payment_data.to_h do |event_id, payment_total| | ||
| [event_id, {payment_total:}] | ||
| end | ||
| exp.execute | ||
| end | ||
|
|
||
| def self.execute(query) | ||
| Event.connection.execute query | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -16,27 +16,31 @@ module.exports = pathPrefix => { | |
| const init = _ => { | ||
| return { | ||
| active: get('active') | ||
| , past: get('past') | ||
| , unpublished: get('unpublished') | ||
| , deleted: get('deleted') | ||
| , past: get('past') | ||
| , unpublished: get('unpublished') | ||
| , deleted: get('deleted') | ||
| } | ||
| } | ||
|
|
||
| const listings = (key, state) => { | ||
| const resp$ = state[key] | ||
| const mixin = content => | ||
| h('section.u-marginBottom--30', [ | ||
| h('h5.u-centered.u-marginBottom--20', key.charAt(0).toUpperCase() + key.slice(1) + ' Events') | ||
| , h(`div.fundraiser--${key}`, content) | ||
| const mixin = (content, count) => | ||
| h('section.u-marginBottom--20.u-marginTop--30', [ | ||
| h('h4.u-marginBottom--0.u-paddingX--20', count + ' ' + key.charAt(0).toUpperCase() + key.slice(1) + ' Events') | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also, now display the count of events in the header/title: |
||
| , h(`div`, content) | ||
| ]) | ||
| if(!resp$()) | ||
| return mixin([h('p.u-padding--15', 'Loading...')]) | ||
| if(!resp$().body.length) | ||
| return mixin([h('p.u-padding--15', `No ${key} events`)]) | ||
| return mixin(resp$().body.map(listing)); | ||
|
|
||
| if(!resp$()) | ||
| return mixin([h(`p.u-padding--15.fundraiser--${key}`, 'Loading...')], 0) | ||
|
|
||
| const numberElems = resp$().body.length | ||
| if(!numberElems) | ||
| return mixin([h(`p.u-padding--15.fundraiser--${key}`, `No ${key} events`)], 0) | ||
|
|
||
| return mixin(resp$().body.map(item => listing(item, key)), numberElems); | ||
| } | ||
|
|
||
| const view = state => | ||
| const view = state => | ||
| h('div', [ | ||
| listings('active', state) | ||
| , listings('past', state) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| class AddIndexesEvents < ActiveRecord::Migration[7.1] | ||
| def change | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add missing indexes for performance. |
||
| add_index :tickets, [:event_id, :quantity, :checked_in], | ||
| name: 'idx_tickets_event_metrics' | ||
|
|
||
| add_index :payments, [:donation_id, :gross_amount], | ||
| name: 'idx_payments_donations' | ||
|
|
||
| add_index :tickets, [:payment_id, :event_id], | ||
| name: 'idx_tickets_payments' | ||
|
|
||
| add_index :payments, [:id, :gross_amount], | ||
| name: 'idx_payments_gross_amount' | ||
| end | ||
| end | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixes bug with divide by 0 (NaN)...