Commit a9df7147 authored by Yorick Peterse's avatar Yorick Peterse

Use a subquery with IDs only for find_by_any_email

This further improves performance of User.find_by_any_email and is
roughly twice as fast as the previous UNION setup.

Thanks again to @dlemstra for suggesting this.
parent bba46623
......@@ -235,15 +235,13 @@ class User < ActiveRecord::Base
# Find a User by their primary email or any associated secondary email
def find_by_any_email(email)
# Arel doesn't allow for chaining operations on union nodes, thus we have
# to write this query by hand. See the following issue for more info:
# https://github.com/rails/arel/issues/98.
sql = '(SELECT * FROM users WHERE email = :email)
sql = 'SELECT *
FROM users
WHERE id IN (
SELECT id FROM users WHERE email = :email
UNION
(SELECT users.*
FROM emails
INNER JOIN users ON users.id = emails.user_id
WHERE emails.email = :email)
SELECT emails.user_id FROM emails WHERE email = :email
)
LIMIT 1;'
User.find_by_sql([sql, { email: email }]).first
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment