May 15, 2007

Rails & MySQL gotcha

Just so you know, don't ever do this in MySQL:

SELECT * FROM foo WHERE id IS NULL;

Why you ask? Seems like a pretty normal thing to do.

MySQL has a known bug that will cause this to return the last row inserted into the DB, ie. something random, instead of what you are looking for. In reality, this was actually a design choice for MySQL. This was how they implemented the ability to figure out the ID for a row inserted with auto-increment. This is fixed in MySQL version 5.0.25 which will probably be in our next upgrade. If you have to use an older version of MySQL, do this:

def find_user_by_id(user_id)
return nil if user_id == nil

@user ||= User.find_by_id(user_id )
@user
end

not this:

def find_user_by_id(user_id)
@user ||= User.find_by_id(user_id )
@user
end

For more information, see...

http://bugs.mysql.com/bug.php?id=14553