Skip to content
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

Optimize submission keys query #1141

Merged
merged 1 commit into from
May 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 14 additions & 14 deletions lib/model/query/keys.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,20 @@ const getById = (keyId) => ({ maybeOne }) =>
maybeOne(sql`select * from keys where id=${keyId}`).then(map(construct(Key)));

const getActiveByFormId = (formId, draft) => ({ all }) => all(sql`
select keys.* from keys
inner join
(select "keyId" from form_defs
inner join
(select "formDefId", "submissionId" from submission_defs
where current=true and "localKey" is not null) as submission_defs
inner join
(select submissions.id from submissions where draft=${draft}) as submissions
on submissions.id=submission_defs."submissionId"
on submission_defs."formDefId"=form_defs.id
where "formId"=${formId}
group by "keyId") as form_defs
on form_defs."keyId"=keys.id
order by id desc`)
SELECT keys.* FROM keys
INNER JOIN form_defs
ON form_defs."keyId" = keys.id
INNER JOIN submission_defs
ON submission_defs."formDefId" = form_defs.id
INNER JOIN submissions
ON submissions.id = submission_defs."submissionId"
WHERE submission_defs.current = true
AND submission_defs."localKey" IS NOT NULL
AND submissions.draft = ${draft}
AND form_defs."formId" = ${formId}
AND form_defs."keyId" IS NOT NULL
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this condition is already covered by the join between keys and form_defs. If a form def has a NULL keyId, then it won't join with a row from keys.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that while it seems redundant, it makes this query orders of magnitude faster. ~700ms -> 0.1 ms

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whoa, interesting!

GROUP BY keys.id
ORDER BY keys.id DESC`)
.then(map(construct(Key)));

const getManagedByIds = (ids) => ({ all }) =>
Expand Down