Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent "options" from create_table in rails 5 schema

My Rails 5 schema.rb file has an options: section for each create_table that I do not want. What I have is:

  create_table "accounts", id: false, force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|

but what I want is:

  create_table "accounts", id: false, force: :cascade do |t|

Since this is a generate file, I don't want to edit it manually.

The reason I don't want the options section is because for a fast TDD loop, I want to use SQLite in memory when RAILS_ENV=test but MySQL in development and production.

How do I prevent DB adapter specific options from being generated and put into the schema?

like image 724
Peter Sankauskas Avatar asked Aug 10 '16 16:08

Peter Sankauskas


1 Answers

Rails 5 broke the Schema dump format

In Rails 5 the core team decided to change the schema dump format and there were basically two issues with the new schema format:

1) the create_table statements now have options which are specific for the adapter, e.g. MySQL as in the OP's example.

2) the dumped columns do not show :limit statements if the value is the default value for the column type.

Why is that bad?

1) ActiveRecord is supposed to be DB agnostic, and some people use the schema files to load them into a different kind of database, e.g. load the schema file into a SQLite DB for faster testing.

SQLite does not understand the MySQL specific options, and breaks miserably.

2) Limits between different versions of the same kind of database could change over time, and limits could definitely change when you go from one DB to another DB.

Therefore it is not a good idea to just not show the actual value of the "default" limit.

Work Around

It is a terrible idea to monkey patch ActiveRecord. I hate having to do this, but that was the easiest way to get our schema files back to a DB-agnostic state, so we could do testing with SQLite.

If you are dumping your schema FROM MySQL on Rails 5.0, then you can fix it by adding these two files to your Rails 5.0 project:

config/initializers/active_record/schema_dumper.rb

config/initializers/active_record/connection_adapters/abstract/schema_dumper.rb

These two files contain the original code form the 5-0-stable branch of Rails, slightly modified to not do (1) and (2).

It's not pretty, but it will keep you generating the same dump format as before.

Hopefully the core team will fix the issue soon.

If you have a better solution, which allows cross-DB usage of schema files, please comment or post a better solution. I'm really not a big fan of monkey-patching :-(

like image 72
Tilo Avatar answered Oct 22 '22 02:10

Tilo