Friday, November 23, 2007

ActiveRecord Migrations - JRuby

I was goofing around a while back, wanted to use AR in a Java project... came up with this Rakefile. Comments welcome, didn't spend much time on it so I'm sure there may be some issues:

[sourcecode language="ruby"]
require 'active_record'
require 'active_support'
require 'yaml'
require 'ftools'

$mig_dir = 'db/migrate'
File.mkpath($mig_dir) if !File.exists?($mig_dir)

task :default do
Rake.application.options.show_task_pattern = //
Rake.application.display_tasks_and_comments
end

namespace :db do
task :environment do
ActiveRecord::Base.establish_connection(YAML::load(File.open('database.yml')))
ActiveRecord::Base.logger = Logger.new(File.open('.migrations.log', 'a'))
end

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

desc "Get the schema version number from DB"
task :version => :environment do
class SchemaInfo :environment do
abcs = YAML::load(File.open('database.yml'))

case abcs["adapter"]
when "mysql", "oci", "oracle"
ActiveRecord::Base.establish_connection(abcs)
File.open("db/schema_structure.sql", "w+") { |f| f db/schema_structure.sql"
else
raise "Task not supported by '#{abcs["test"]["adapter"]}'"
end

if ActiveRecord::Base.connection.supports_migrations?
File.open("db/schema_structure.sql", "a") { |f| f < max then n else max end
end
end

def next_migration_number
current_migration_number + 1
end

def next_migration_string(padding = 3)
"%.#{padding}d" % next_migration_number
end

def write_template(file_name, name)
contents = < :user_id do |t|
# t.primary_key :user_id
# t.column :user_id, :integer, :null => false
# t.column :first_name, :string, :null => false
# t.column :last_name, :string, :null => false
# end

# sample for self.down:
# drop_table :users

end
EOS

File.open("#{$mig_dir}/#{file_name}", 'w') do |file|
file.write(contents)
end

puts "Created migration file: #{$mig_dir}/#{file_name}"
end[/sourcecode]

No comments: