Permalink
Browse files

ActiveRecord: autocreation of databases

  • Loading branch information...
1 parent d8be115 commit 6a80e36cf66b2e81d0c9a8aa15327d84a6b641a2 @stanislaw stanislaw committed with bmabey Aug 3, 2012
@@ -4,10 +4,27 @@
module MySQL2Helper
puts "Active Record #{ActiveRecord::VERSION::STRING}, mysql2"
+ # require 'logger'
# ActiveRecord::Base.logger = Logger.new(STDERR)
+ def config
+ db_config['mysql2']
+ end
+
+ def create_db
+ establish_connection(config.merge(:database => nil))
+
+ ActiveRecord::Base.connection.drop_database config['database'] rescue nil
+ ActiveRecord::Base.connection.create_database config['database']
+ end
+
+ def establish_connection config = config
+ ActiveRecord::Base.establish_connection config
+ end
+
def active_record_mysql2_setup
- ActiveRecord::Base.establish_connection db_config['mysql2']
+ create_db
+ establish_connection
load_schema
end
@@ -4,14 +4,31 @@
module MySQLHelper
puts "Active Record #{ActiveRecord::VERSION::STRING}, mysql"
+ # require 'logger'
# ActiveRecord::Base.logger = Logger.new(STDERR)
+ def config
+ db_config['mysql']
+ end
+
+ def create_db
+ establish_connection(config.merge(:database => nil))
+
+ ActiveRecord::Base.connection.drop_database config['database'] rescue nil
+ ActiveRecord::Base.connection.create_database config['database']
+ end
+
+ def establish_connection config = config
+ ActiveRecord::Base.establish_connection config
+ end
+
def active_record_mysql_setup
- ActiveRecord::Base.establish_connection db_config['mysql']
+ create_db
+ establish_connection
load_schema
end
- def active_record_mysql_connection
+ def active_record_mysql_connection
ActiveRecord::Base.connection
end
end
@@ -6,12 +6,32 @@ module PostgreSQLHelper
# ActiveRecord::Base.logger = Logger.new(STDERR)
+ def config
+ db_config['postgres']
+ end
+
+ def create_db
+ @encoding = config['encoding'] || ENV['CHARSET'] || 'utf8'
+ begin
+ establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
+ ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => @encoding))
+ rescue Exception => e
+ $stderr.puts e, *(e.backtrace)
+ $stderr.puts "Couldn't create database for #{config.inspect}"
+ end
+ end
+
+ def establish_connection config = config
+ ActiveRecord::Base.establish_connection(config)
+ end
+
def active_record_pg_setup
- ActiveRecord::Base.establish_connection db_config['postgres']
+ create_db
+ establish_connection
load_schema
end
- def active_record_pg_connection
+ def active_record_pg_connection
ActiveRecord::Base.connection
end
end

0 comments on commit 6a80e36

Please sign in to comment.