nick.recoil.org

Rails DB migrations with clauses for SQLite or MySQL

When writing migrations, different databases have different syntaxes for certain aspects of table construction. SQLite doesn’t require you to specify the length of a key added to a column of type TEXT, but MySQL does.

If you’re using different databases for development and production, then writing one migration which copes with both databases is important. This can be done with the following code placed inside the migration file:

1
2
3
4
5
6

if ActiveRecord::Base.connection.adapter_name == "SQLite"
  add_index(:assets, :notes)
elsif ActiveRecord::Base.connection.adapter_name == "MySQL"
  execute "CREATE INDEX index_assets_on_notes ON assets (notes(50))"
end

Search

Sections

About Nick

I am a freelance technology consultant and developer working in London, with a particular interest in web development and video media.

This site contains my thoughts about technology, the universe and everything. If you would like to get in contact, have a look at the About me page.