Fixed race conditions in MySQL. Fixes #541. PLEASE TEST, BIG UPDATE