Daniel Huckstep
Daniel Huckstep

Reputation: 5408

Rails with in memory database

Can I set rails to use mysql with MEMORY as the DB engine? I never restart mysql, and rebuild the db so often I'd rather have it be fast. Having the memory db for running tests would be nice too.

EDIT: I should have specified this is for dev/testing only, not production.

Upvotes: 13

Views: 10891

Answers (3)

Alexey
Alexey

Reputation: 9447

For testing purposes consider https://github.com/mvz/memory_test_fix plug-in. It's usage as easy as to update database.yml and to run

rails plugin install git://github.com/mvz/memory_test_fix.git

You may try also install memory_test_fix gem, but it's from different git branch and does not support Rails 3.

The gem helped me to reduce test cases execution time from 25 seconds to 19. On the other hand, it introduces 2 second overhead on database schema initialisation (and i don't have that much of them). So on small sets of tests it's not worth bothering.

Solution from Jason Stewart's answer is basically the same. And I used it instead of plugin, because it was easier to combine it with Spork plug-in.

Upvotes: 2

SFEley
SFEley

Reputation: 7766

I don't see why you couldn't; your choice of storage engine is a MySQL implementation detail. All you should need to do is set :options => "ENGINE=MEMORY" in your create_table declaration in your migrations.

Of course, I also don't see why you would -- especially in production. The MySQL documentation for the MEMORY engine is full of caveats, like fixed length field allocation, and the speed gain you'd realize has got to be trivial compared to the risk of losing everything. If your application is such that nothing needs to be persisted, ever, why not just skip ActiveRecord completely and layer your models on top of Memcached?

Upvotes: 7

Jason stewart
Jason stewart

Reputation: 1085

I use sqlite3 in memory database for testing. It's usually a little bit faster than file based, but not THAT much unless you have a ton of test data.

To set that up your database.yml will look like this:

test:
adapter: sqlite3
database: ":memory:"

You'll also have to load your schema into your in memory database in your test helper like so:

config = YAML::load(IO.read(File.dirname(__FILE__) + "/../config/database.yml"))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/../log/debug.log")
ActiveRecord::Base.establish_connection(config["test"])
load(File.dirname(__FILE__) + "/../db/schema.rb")

Upvotes: 3

Related Questions