John Joseph Bachir

How to use a RAM / memory disk for MySQL in Rails

I wanted to use a RAM disk for my MySQL data files when running my tests for a Rails project. I succeeded, but it only cut 2 seconds off of my ~30 second test suite for my functional tests, and didn’t cut any time off of my unit tests. But nevertheless, here is how I achieved this, in case it is useful to others. All of this is on OS X, using MySQL 5 from Macports.

What we are doing is creating a RAM disk, and then creating a seperate MySQL instance that stores its data on that RAM disk.

[bash]
# Create the RAM disk
hdid -nomount ram://52428800
newfs_hfs /dev/disk1
mkdir /tmp/ramdisk1
mount -t hfs /dev/disk1 /tmp/ramdisk1

# Initialize the MySQL environment
mysql_install_db5 –datadir=/tmp/ramdisk1

# Start the MySQL server
/opt/local/libexec/mysqld –basedir=/opt/local –datadir=/tmp/ramdisk1 –pid-file=/tmp/mysql_memory_localhost.pid –port=10000 –socket=/tmp/mysql_memory.sock

# Create your test database
mysqladmin5 –socket=/tmp/mysql_memory.sock -uroot create projectname_test
[/bash]

Now in your database.yml file, add socket: /tmp/mysql_memory.sock to the test database configuration.

(thanks to this tutorial for how-to create a RAM disk in OS X)


2 Comments

Another useful trick is the MEMORY engine:
http://dev.mysql.com/doc/refman/5.0/en/memory-storage-engine.html

(Not that “MEMORY tables cannot contain BLOB or TEXT columns.”). This may make them useless for you.

Posted by Anonymous on 29 September 2007 @ 9pm

Yep, I considered that too. There’s even a rails plugin to use sqlite3 memory tables. But i’d rather run my tests closer to the environment in which my application will be running, with transactions, etc. In fact, some of my tests test race conditions, so transactions are required.

Posted by John on 29 September 2007 @ 9pm

Leave a Comment