Use one query to check email uniqueness
What does this MR do and why?
Issue: https://gitlab.com/gitlab-org/modelops/anti-abuse/team-tasks/-/issues/503
Reduce the number of queries when checking if email is unique. This change aims to help improve the response time of sign-up requests.
Before
!emails.exists?(email: email) && Email.exists?(email: email)
-- code: !emails.exists?(email: email)
SELECT
1 AS one
FROM
"emails"
WHERE
"emails"."user_id" = 332
AND "emails"."email" = 'test+3@ex.com'
LIMIT 1
-- code: Email.exists?(email: email)
SELECT
1 AS one
FROM
"emails"
WHERE
"emails"."email" = 'test+3@ex.com'
LIMIT 1
After
Email.where.not(user: self).where(email: email).exists?
SELECT
1 AS one
FROM
"emails"
WHERE
"emails"."user_id" != 332
AND "emails"."email" = 'test+3@ex.com'
LIMIT 1
EXPLAIN
https://console.postgres.ai/shared/69d3df92-ee0d-454e-912d-ae8d8915bacb
Limit (cost=0.56..3.58 rows=1 width=4) (actual time=12.005..12.007 rows=0 loops=1)
Buffers: shared read=4
I/O Timings: read=11.935 write=0.000
-> Index Scan using index_emails_on_email on public.emails (cost=0.56..3.58 rows=1 width=4) (actual time=12.002..12.003 rows=0 loops=1)
Index Cond: ((emails.email)::text = 'eugie_new_email@gmail.com'::text)
Filter: (emails.user_id <> 9670031)
Rows Removed by Filter: 0
Buffers: shared read=4
I/O Timings: read=11.935 write=0.000
MR acceptance checklist
Please evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.
Screenshots or screen recordings
Screenshots are required for UI changes, and strongly recommended for all other merge requests.
Before | After |
---|---|
How to set up and validate locally
Numbered steps to set up and validate the change are strongly suggested.
Edited by Eugie Limpin