Advertise here!

Rails, db_structure_dump, and Oracle

I use Ruby on Rails at work with an Oracle 10g database. The problem is that I have a couple new people who are supposed to begin helping with the project and would like to set up development databases. When I was using MySQL this was easy, I used the db_structure_dump task in rake and gave them the output file.

I tried to do the same with Oracle, but apparently the task and adapters aren’t set up for this. So after some looking around the web I came up with my own solution – to implement structure_dump in the oci_adapter. So if anyone needs this, here’s the quick and very dirty code. It could use some loving and cleaning before it gets submitted as a patch.

Add the following method to the OciAdapter class in active_record/connection_adapters/oci_adapter.rb:

def structure_dump
  select_all("select table_name from user_tables") .inject("") do |structure, table|
    string = "CREATE TABLE #{table.to_a.first.last} (\n "
    array = select_all("select column_name, data_type, data_length, data_precision,
       data_scale, data_default, nullable from all_tab_columns where table_name =
       '#{table.to_a.first.last}' order by column_id")
    
    array.collect! do |hash|
      tmp = "#{hash['column_name']} #{hash['data_type']}"	      
      if hash['data_type'] =='NUMBER' and !hash['data_precision'].nil?
        tmp << "(#{hash['data_precision'].to_i}"
        tmp << ",#{hash['data_scale'].to_i})" if !hash['data_scale'].nil?
        tmp << ')'
      elsif hash['data_type'].include?('CHAR')
        tmp << "(#{hash['data_length'].to_i})"  
      end	      
      tmp << " DEFAULT #{hash['data_default']}" if !hash['data_default'].nil?
      tmp << ' NOT NULL' if hash['nullable'] ="=" 'N'
      tmp	      
    end
    array.uniq!
    array.delete_if {|item| item.nil?}
    string << array.join(",\n ")
    string << ");\n\n"
    structure << string
  end
end

…And add “oci” to the case statement in the Rakefile:

desc "Dump the database structure to a SQL file"
task :db_structure_dump => :environment do
  abcs = ActiveRecord::Base.configurations
  case abcs[RAILS_ENV]["adapter"] 
    when "mysql", "oci"
      ActiveRecord::Base.establish_connection(abcs[RAILS_ENV])
Posted at 7pm on 06/30/05 | Posted in , , | 3 responses | read on