Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails-like Database Migrations?

Is there any easy to install/use (on unix) database migration tools like Rails Migrations? I really like the idea, but installing ruby/rails purely to manage my database migrations seems overkill.

like image 755
Matthew Watson Avatar asked Sep 19 '08 13:09

Matthew Watson


People also ask

What is db migration in rails?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.

How do I migrate a database in Ruby on Rails?

Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor. The ID column will be created automatically, so don't do it here as well. The method self. up is used when migrating to a new version, self.

Where does rails store migration data?

Rails stores the most recent database schema in the file db/schema. rb . This file is the Ruby representation of all the migrations run on your database over the life of the application.


1 Answers

Just use ActiveRecord and a simple Rakefile. For example, if you put your migrations in a db/migrate directory and have a database.yml file that has your db config, this simple Rakefile should work:

Rakefile:

require 'active_record'
require 'yaml'

desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x"
task :migrate => :environment do
  ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
end

task :environment do
  ActiveRecord::Base.establish_connection(YAML::load(File.open('database.yml')))
  ActiveRecord::Base.logger = Logger.new(STDOUT)
end

database.yml:

adapter: mysql
encoding: utf8
database: test_database
username: root
password:
host: localhost

Afterwards, you'll be able to run rake migrate and have all the migration goodness without a surrounding rails app.

Alternatively, I have a set of bash scripts that perform a very similar function to ActiveRecord migrations, but they only work with Oracle. I used to use them before switching to Ruby and Rails. They are somewhat complicated and I provide no support for them, but if you are interested, feel free to contact me.

like image 101
Ryan McGeary Avatar answered Oct 02 '22 06:10

Ryan McGeary