validates_uniqness_of + mysql == SLOW

ActiveRecord`s validate_uniqueness_of produces evil SQL that will not use your existing index!

Before:
SELECT `users`.id FROM `users` WHERE `users`.`email` = BINARY ‘my@email.com’ AND `users`.id 1234) LIMIT 1; –> 0.80s

After:
SELECT `users`.id FROM `users` WHERE `users`.`email` = ‘my@email.com’ AND `users`.id 1234) LIMIT 1; –> 0.00s

Hack to make AR use faster queries on the cost that no case-sensitive queries can be made anymore.

# validates_uniqueness_of produces "column = BINARY 'text'" queries
# which will not use existing indices, so we add this 
# EVIL HACK to make 
# ALL validates_uniqueness_of in-case-sensitive
class ActiveRecord::ConnectionAdapters::MysqlAdapter
  def case_sensitive_equality_operator
    "="
  end
end
Advertisements

One thought on “validates_uniqness_of + mysql == SLOW

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s