Module: DBStructure

Defined in:
lib/db_structure.rb

Class Method Summary collapse

Class Method Details

.db_helper(db) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/db_structure.rb', line 4

def self.db_helper(db)
  @db = db
  case db
  when 'postgresql'
    @pk = 'SERIAL PRIMARY KEY'
    @datetime = 'TIMESTAMP'
    @options = ''
  when 'sqlite'
    @pk = 'INTEGER PRIMARY KEY'
    @datetime = 'DATETIME'
    @options = ''
  when 'mysql'
    @pk = 'INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY'
    @datetime = 'DATETIME'
    @options = 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
  else
    raise "Unknown db type #{db}"
  end
  
  s = ''
  Dir['db/*.erbsql'].each do |filename|
    s += ERB.new(File.read(filename)).result(binding)
  end
  s
end

.db_structureObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/db_structure.rb', line 30

def self.db_structure
  config = ActiveRecord::Base.configurations
  
  ['production', 'test', 'development'].each do |target|
    begin
      ENV['RAILS_ENV'] = target
      begin
        puts "Recreating database #{config[target]['database']}"
        ActiveRecord::Base.connection.execute("DROP DATABASE #{config[target]['database']}")
      rescue
        puts "Database #{config[target]['database']} doesn't exist yet"
      ensure
        ActiveRecord::Base.connection.execute("CREATE DATABASE #{config[target]['database']}")
        ActiveRecord::Base.connection.execute("USE #{config[target]['database']}")
      end
      db_helper(config[target]['adapter']).split(/\s*;\s*/).each do |sql|
        if sql =~ /(create|CREATE).+?(table|TABLE).+?(\w+)/
          begin
            ActiveRecord::Base.connection.execute("DROP TABLE #{$3}")
          rescue
            puts "Table #{$3} does not exist"
          end
        end
        puts "Creating tables for #{config[target]['database']}..."
        ActiveRecord::Base.connection.execute(sql)
      end
      puts "done."
    rescue => e
      puts "failed: " + e.inspect
    end
  end
end