Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Database migrations

  • Loading branch information...
commit daba80f8474d82785b6c34987110072957193e90 1 parent 8653f10
David Eisinger dce authored
2  .gitignore
@@ -9,3 +9,5 @@ tmp/*
9 9 tmp/**/*
10 10 config/settings.yml
11 11 config/deploy.rb
  12 +config/database.yml
  13 +db/*.sqlite3
3  Rakefile
@@ -10,6 +10,9 @@ end
10 10 task :environment do
11 11 $:.push(File.dirname(__FILE__))
12 12 require 'init'
  13 +
  14 + ActiveRecord::Base.logger = Logger.new('log/database.log')
  15 + RAILS_ROOT = File.dirname(__FILE__)
13 16 end
14 17
15 18 Dir['tasks/**/*.rake'].each do |rakefile|
27 app/models/site.rb
... ... @@ -1,7 +1,7 @@
1 1 require 'uri'
2 2 require 'fileutils'
3 3
4   -class Site < Ohm::Model
  4 +class Site < ActiveRecord::Base
5 5 module Regex
6 6 include URI::REGEXP::PATTERN
7 7 # A general email regular expression. It allows top level domains (TLD) to be from 2 - 4 in length, any
@@ -31,15 +31,6 @@ def save_with_monit_callback
31 31 private :save_with_monit_callback
32 32 alias_method_chain :save, :monit_callback
33 33
34   - attribute :name
35   - attribute :url
36   - attribute :match_text
37   - attribute :threshold
38   - attribute :email
39   - list :status_record
40   -
41   - index :url
42   -
43 34 def validate
44 35 assert_present :name
45 36 assert_present :url
@@ -61,13 +52,13 @@ def latest_status
61 52 end
62 53
63 54 private
64   - def create_monit_check
65   - @template = MonitCheck.new(self)
66   - File.open(root_path('monitrc', RACK_ENV, "#{self.id}.monitrc"), 'w') do |file|
67   - file << @template.render
68   - end
69   - FileUtils.chmod 0700, root_path('monitrc', RACK_ENV, "#{self.id}.monitrc")
70   - system "#{File.join(settings(:monit_bin_dir), 'monit')} #{settings(:monit_cli_options)} reload"
71   - end
72 55
  56 + def create_monit_check
  57 + @template = MonitCheck.new(self)
  58 + File.open(root_path('monitrc', RACK_ENV, "#{self.id}.monitrc"), 'w') do |file|
  59 + file << @template.render
  60 + end
  61 + FileUtils.chmod 0700, root_path('monitrc', RACK_ENV, "#{self.id}.monitrc")
  62 + system "#{File.join(settings(:monit_bin_dir), 'monit')} #{settings(:monit_cli_options)} reload"
  63 + end
73 64 end
17 config/database.example.yml
... ... @@ -0,0 +1,17 @@
  1 +development:
  2 + adapter: sqlite3
  3 + database: db/development.sqlite3
  4 + pool: 5
  5 + timeout: 5000
  6 +
  7 +test:
  8 + adapter: sqlite3
  9 + database: db/test.sqlite3
  10 + pool: 5
  11 + timeout: 5000
  12 +
  13 +production:
  14 + adapter: sqlite3
  15 + database: db/production.sqlite3
  16 + pool: 5
  17 + timeout: 5000
18 db/migrate/001_create_sites.rb
... ... @@ -0,0 +1,18 @@
  1 +class CreateSites < ActiveRecord::Migration
  2 + def self.up
  3 + create_table :sites do |t|
  4 + t.string :name
  5 + t.string :url
  6 + t.text :match_text
  7 + t.integer :threshold
  8 + t.string :email
  9 + t.string :status_record
  10 +
  11 + t.timestamps
  12 + end
  13 + end
  14 +
  15 + def self.down
  16 + drop_table :sites
  17 + end
  18 +end
25 db/schema.rb
... ... @@ -0,0 +1,25 @@
  1 +# This file is auto-generated from the current state of the database. Instead of editing this file,
  2 +# please use the migrations feature of Active Record to incrementally modify your database, and
  3 +# then regenerate this schema definition.
  4 +#
  5 +# Note that this schema.rb definition is the authoritative source for your database schema. If you need
  6 +# to create the application database on another system, you should be using db:schema:load, not running
  7 +# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
  8 +# you'll amass, the slower it'll run and the greater likelihood for issues).
  9 +#
  10 +# It's strongly recommended to check this file into your version control system.
  11 +
  12 +ActiveRecord::Schema.define(:version => 1) do
  13 +
  14 + create_table "sites", :force => true do |t|
  15 + t.string "name"
  16 + t.string "url"
  17 + t.text "match_text"
  18 + t.integer "threshold"
  19 + t.string "email"
  20 + t.string "status_record"
  21 + t.datetime "created_at"
  22 + t.datetime "updated_at"
  23 + end
  24 +
  25 +end
12 init.rb
@@ -10,8 +10,8 @@
10 10
11 11 require "monk/glue"
12 12 require 'active_support'
  13 +require 'active_record'
13 14 require 'mustache/sinatra'
14   -require 'ohm'
15 15
16 16 class Main < Monk::Glue
17 17 set :app_file, __FILE__
@@ -19,15 +19,17 @@ class Main < Monk::Glue
19 19 register Mustache::Sinatra
20 20 set :views, root_path('app', 'templates')
21 21 set :mustaches, root_path('app', 'views')
22   -
  22 +
23 23 configure do
24   - Ohm.connect
25   -
  24 + # Set up ActiveRecord
  25 + @db_config = YAML.load(File.open('config/database.yml'))
  26 + ActiveRecord::Base.establish_connection(@db_config[Main.environment.to_s])
  27 +
26 28 # Load all application files.
27 29 Dir[root_path("app/**/*.rb")].each do |file|
28 30 require file
29 31 end
30   - end
  32 + end
31 33 end
32 34
33 35 Main.run! if Main.run?
427 tasks/databases.rake
... ... @@ -0,0 +1,427 @@
  1 +namespace :db do
  2 + task :load_config => :environment do
  3 + require 'active_record'
  4 + ActiveRecord::Base.configurations = Main.db_config
  5 + end
  6 +
  7 + namespace :create do
  8 + desc 'Create all the local databases defined in config/database.yml'
  9 + task :all => :load_config do
  10 + ActiveRecord::Base.configurations.each_value do |config|
  11 + # Skip entries that don't have a database key, such as the first entry here:
  12 + #
  13 + # defaults: &defaults
  14 + # adapter: mysql
  15 + # username: root
  16 + # password:
  17 + # host: localhost
  18 + #
  19 + # development:
  20 + # database: blog_development
  21 + # <<: *defaults
  22 + next unless config['database']
  23 + # Only connect to local databases
  24 + local_database?(config) { create_database(config) }
  25 + end
  26 + end
  27 + end
  28 +
  29 + desc 'Create the database defined in config/database.yml for the current RAKE_ENV'
  30 + task :create => :load_config do
  31 + create_database(ActiveRecord::Base.configurations[RAKE_ENV])
  32 + end
  33 +
  34 + def create_database(config)
  35 + begin
  36 + if config['adapter'] =~ /sqlite/
  37 + if File.exist?(config['database'])
  38 + $stderr.puts "#{config['database']} already exists"
  39 + else
  40 + begin
  41 + # Create the SQLite database
  42 + ActiveRecord::Base.establish_connection(config)
  43 + ActiveRecord::Base.connection
  44 + rescue
  45 + $stderr.puts $!, *($!.backtrace)
  46 + $stderr.puts "Couldn't create database for #{config.inspect}"
  47 + end
  48 + end
  49 + return # Skip the else clause of begin/rescue
  50 + else
  51 + ActiveRecord::Base.establish_connection(config)
  52 + ActiveRecord::Base.connection
  53 + end
  54 + rescue
  55 + case config['adapter']
  56 + when 'mysql'
  57 + @charset = ENV['CHARSET'] || 'utf8'
  58 + @collation = ENV['COLLATION'] || 'utf8_unicode_ci'
  59 + begin
  60 + ActiveRecord::Base.establish_connection(config.merge('database' => nil))
  61 + ActiveRecord::Base.connection.create_database(config['database'], :charset => (config['charset'] || @charset), :collation => (config['collation'] || @collation))
  62 + ActiveRecord::Base.establish_connection(config)
  63 + rescue
  64 + $stderr.puts "Couldn't create database for #{config.inspect}, charset: #{config['charset'] || @charset}, collation: #{config['collation'] || @collation} (if you set the charset manually, make sure you have a matching collation)"
  65 + end
  66 + when 'postgresql'
  67 + @encoding = config[:encoding] || ENV['CHARSET'] || 'utf8'
  68 + begin
  69 + ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
  70 + ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => @encoding))
  71 + ActiveRecord::Base.establish_connection(config)
  72 + rescue
  73 + $stderr.puts $!, *($!.backtrace)
  74 + $stderr.puts "Couldn't create database for #{config.inspect}"
  75 + end
  76 + end
  77 + else
  78 + $stderr.puts "#{config['database']} already exists"
  79 + end
  80 + end
  81 +
  82 + namespace :drop do
  83 + desc 'Drops all the local databases defined in config/database.yml'
  84 + task :all => :load_config do
  85 + ActiveRecord::Base.configurations.each_value do |config|
  86 + # Skip entries that don't have a database key
  87 + next unless config['database']
  88 + # Only connect to local databases
  89 + local_database?(config) { drop_database(config) }
  90 + end
  91 + end
  92 + end
  93 +
  94 + desc 'Drops the database for the current RAKE_ENV'
  95 + task :drop => :load_config do
  96 + config = ActiveRecord::Base.configurations[RAKE_ENV || 'development']
  97 + begin
  98 + drop_database(config)
  99 + rescue Exception => e
  100 + puts "Couldn't drop #{config['database']} : #{e.inspect}"
  101 + end
  102 + end
  103 +
  104 + def local_database?(config, &block)
  105 + if %w( 127.0.0.1 localhost ).include?(config['host']) || config['host'].blank?
  106 + yield
  107 + else
  108 + puts "This task only modifies local databases. #{config['database']} is on a remote host."
  109 + end
  110 + end
  111 +
  112 +
  113 + desc "Migrate the database through scripts in db/migrate and update db/schema.rb by invoking db:schema:dump. Target specific version with VERSION=x. Turn off output with VERBOSE=false."
  114 + task :migrate => :environment do
  115 + ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
  116 + ActiveRecord::Migrator.migrate("db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
  117 + Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
  118 + end
  119 +
  120 + namespace :migrate do
  121 + desc 'Rollbacks the database one migration and re migrate up. If you want to rollback more than one step, define STEP=x. Target specific version with VERSION=x.'
  122 + task :redo => :environment do
  123 + if ENV["VERSION"]
  124 + Rake::Task["db:migrate:down"].invoke
  125 + Rake::Task["db:migrate:up"].invoke
  126 + else
  127 + Rake::Task["db:rollback"].invoke
  128 + Rake::Task["db:migrate"].invoke
  129 + end
  130 + end
  131 +
  132 + desc 'Resets your database using your migrations for the current environment'
  133 + task :reset => ["db:drop", "db:create", "db:migrate"]
  134 +
  135 + desc 'Runs the "up" for a given migration VERSION.'
  136 + task :up => :environment do
  137 + version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
  138 + raise "VERSION is required" unless version
  139 + ActiveRecord::Migrator.run(:up, "db/migrate/", version)
  140 + Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
  141 + end
  142 +
  143 + desc 'Runs the "down" for a given migration VERSION.'
  144 + task :down => :environment do
  145 + version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
  146 + raise "VERSION is required" unless version
  147 + ActiveRecord::Migrator.run(:down, "db/migrate/", version)
  148 + Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
  149 + end
  150 + end
  151 +
  152 + desc 'Rolls the schema back to the previous version. Specify the number of steps with STEP=n'
  153 + task :rollback => :environment do
  154 + step = ENV['STEP'] ? ENV['STEP'].to_i : 1
  155 + ActiveRecord::Migrator.rollback('db/migrate/', step)
  156 + Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
  157 + end
  158 +
  159 + desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
  160 + task :reset => [ 'db:drop', 'db:setup' ]
  161 +
  162 + desc "Retrieves the charset for the current environment's database"
  163 + task :charset => :environment do
  164 + config = ActiveRecord::Base.configurations[RAKE_ENV || 'development']
  165 + case config['adapter']
  166 + when 'mysql'
  167 + ActiveRecord::Base.establish_connection(config)
  168 + puts ActiveRecord::Base.connection.charset
  169 + when 'postgresql'
  170 + ActiveRecord::Base.establish_connection(config)
  171 + puts ActiveRecord::Base.connection.encoding
  172 + else
  173 + puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
  174 + end
  175 + end
  176 +
  177 + desc "Retrieves the collation for the current environment's database"
  178 + task :collation => :environment do
  179 + config = ActiveRecord::Base.configurations[RAKE_ENV || 'development']
  180 + case config['adapter']
  181 + when 'mysql'
  182 + ActiveRecord::Base.establish_connection(config)
  183 + puts ActiveRecord::Base.connection.collation
  184 + else
  185 + puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
  186 + end
  187 + end
  188 +
  189 + desc "Retrieves the current schema version number"
  190 + task :version => :environment do
  191 + puts "Current version: #{ActiveRecord::Migrator.current_version}"
  192 + end
  193 +
  194 + desc "Raises an error if there are pending migrations"
  195 + task :abort_if_pending_migrations => :environment do
  196 + if defined? ActiveRecord
  197 + pending_migrations = ActiveRecord::Migrator.new(:up, 'db/migrate').pending_migrations
  198 +
  199 + if pending_migrations.any?
  200 + puts "You have #{pending_migrations.size} pending migrations:"
  201 + pending_migrations.each do |pending_migration|
  202 + puts ' %4d %s' % [pending_migration.version, pending_migration.name]
  203 + end
  204 + abort %{Run "rake db:migrate" to update your database then try again.}
  205 + end
  206 + end
  207 + end
  208 +
  209 + desc 'Create the database, load the schema, and initialize with the seed data'
  210 + task :setup => [ 'db:create', 'db:schema:load', 'db:seed' ]
  211 +
  212 + desc 'Load the seed data from db/seeds.rb'
  213 + task :seed => :environment do
  214 + seed_file = File.join(Rails.root, 'db', 'seeds.rb')
  215 + load(seed_file) if File.exist?(seed_file)
  216 + end
  217 +
  218 + namespace :fixtures do
  219 + desc "Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
  220 + task :load => :environment do
  221 + require 'active_record/fixtures'
  222 + ActiveRecord::Base.establish_connection(Rails.env)
  223 + base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures')
  224 + fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir
  225 +
  226 + (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir.glob(File.join(fixtures_dir, '*.{yml,csv}'))).each do |fixture_file|
  227 + Fixtures.create_fixtures(File.dirname(fixture_file), File.basename(fixture_file, '.*'))
  228 + end
  229 + end
  230 +
  231 + desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
  232 + task :identify => :environment do
  233 + require "active_record/fixtures"
  234 +
  235 + label, id = ENV["LABEL"], ENV["ID"]
  236 + raise "LABEL or ID required" if label.blank? && id.blank?
  237 +
  238 + puts %Q(The fixture ID for "#{label}" is #{Fixtures.identify(label)}.) if label
  239 +
  240 + base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures')
  241 + Dir["#{base_dir}/**/*.yml"].each do |file|
  242 + if data = YAML::load(ERB.new(IO.read(file)).result)
  243 + data.keys.each do |key|
  244 + key_id = Fixtures.identify(key)
  245 +
  246 + if key == label || key_id == id.to_i
  247 + puts "#{file}: #{key} (#{key_id})"
  248 + end
  249 + end
  250 + end
  251 + end
  252 + end
  253 + end
  254 +
  255 + namespace :schema do
  256 + desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
  257 + task :dump => :environment do
  258 + require 'active_record/schema_dumper'
  259 + File.open(ENV['SCHEMA'] || "#{RAILS_ROOT}/db/schema.rb", "w") do |file|
  260 + ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
  261 + end
  262 + Rake::Task["db:schema:dump"].reenable
  263 + end
  264 +
  265 + desc "Load a schema.rb file into the database"
  266 + task :load => :environment do
  267 + file = ENV['SCHEMA'] || "#{RAILS_ROOT}/db/schema.rb"
  268 + if File.exists?(file)
  269 + load(file)
  270 + else
  271 + abort %{#{file} doesn't exist yet. Run "rake db:migrate" to create it then try again. If you do not intend to use a database, you should instead alter #{RAILS_ROOT}/config/environment.rb to prevent active_record from loading: config.frameworks -= [ :active_record ]}
  272 + end
  273 + end
  274 + end
  275 +
  276 + namespace :structure do
  277 + desc "Dump the database structure to a SQL file"
  278 + task :dump => :environment do
  279 + abcs = ActiveRecord::Base.configurations
  280 + case abcs[RAKE_ENV]["adapter"]
  281 + when "mysql", "oci", "oracle"
  282 + ActiveRecord::Base.establish_connection(abcs[RAKE_ENV])
  283 + File.open("#{RAILS_ROOT}/db/#{RAKE_ENV}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
  284 + when "postgresql"
  285 + ENV['PGHOST'] = abcs[RAKE_ENV]["host"] if abcs[RAKE_ENV]["host"]
  286 + ENV['PGPORT'] = abcs[RAKE_ENV]["port"].to_s if abcs[RAKE_ENV]["port"]
  287 + ENV['PGPASSWORD'] = abcs[RAKE_ENV]["password"].to_s if abcs[RAKE_ENV]["password"]
  288 + search_path = abcs[RAKE_ENV]["schema_search_path"]
  289 + search_path = "--schema=#{search_path}" if search_path
  290 + `pg_dump -i -U "#{abcs[RAKE_ENV]["username"]}" -s -x -O -f db/#{RAKE_ENV}_structure.sql #{search_path} #{abcs[RAKE_ENV]["database"]}`
  291 + raise "Error dumping database" if $?.exitstatus == 1
  292 + when "sqlite", "sqlite3"
  293 + dbfile = abcs[RAKE_ENV]["database"] || abcs[RAKE_ENV]["dbfile"]
  294 + `#{abcs[RAKE_ENV]["adapter"]} #{dbfile} .schema > db/#{RAKE_ENV}_structure.sql`
  295 + when "sqlserver"
  296 + `scptxfr /s #{abcs[RAKE_ENV]["host"]} /d #{abcs[RAKE_ENV]["database"]} /I /f db\\#{RAKE_ENV}_structure.sql /q /A /r`
  297 + `scptxfr /s #{abcs[RAKE_ENV]["host"]} /d #{abcs[RAKE_ENV]["database"]} /I /F db\ /q /A /r`
  298 + when "firebird"
  299 + set_firebird_env(abcs[RAKE_ENV])
  300 + db_string = firebird_db_string(abcs[RAKE_ENV])
  301 + sh "isql -a #{db_string} > #{RAILS_ROOT}/db/#{RAKE_ENV}_structure.sql"
  302 + else
  303 + raise "Task not supported by '#{abcs["test"]["adapter"]}'"
  304 + end
  305 +
  306 + if ActiveRecord::Base.connection.supports_migrations?
  307 + File.open("#{RAILS_ROOT}/db/#{RAKE_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
  308 + end
  309 + end
  310 + end
  311 +
  312 + namespace :test do
  313 + desc "Recreate the test database from the current schema.rb"
  314 + task :load => 'db:test:purge' do
  315 + ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
  316 + ActiveRecord::Schema.verbose = false
  317 + Rake::Task["db:schema:load"].invoke
  318 + end
  319 +
  320 + desc "Recreate the test database from the current environment's database schema"
  321 + task :clone => %w(db:schema:dump db:test:load)
  322 +
  323 + desc "Recreate the test databases from the development structure"
  324 + task :clone_structure => [ "db:structure:dump", "db:test:purge" ] do
  325 + abcs = ActiveRecord::Base.configurations
  326 + case abcs["test"]["adapter"]
  327 + when "mysql"
  328 + ActiveRecord::Base.establish_connection(:test)
  329 + ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0')
  330 + IO.readlines("#{RAILS_ROOT}/db/#{RAKE_ENV}_structure.sql").join.split("\n\n").each do |table|
  331 + ActiveRecord::Base.connection.execute(table)
  332 + end
  333 + when "postgresql"
  334 + ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"]
  335 + ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"]
  336 + ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"]
  337 + `psql -U "#{abcs["test"]["username"]}" -f #{RAILS_ROOT}/db/#{RAKE_ENV}_structure.sql #{abcs["test"]["database"]}`
  338 + when "sqlite", "sqlite3"
  339 + dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
  340 + `#{abcs["test"]["adapter"]} #{dbfile} < #{RAILS_ROOT}/db/#{RAKE_ENV}_structure.sql`
  341 + when "sqlserver"
  342 + `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAKE_ENV}_structure.sql`
  343 + when "oci", "oracle"
  344 + ActiveRecord::Base.establish_connection(:test)
  345 + IO.readlines("#{RAILS_ROOT}/db/#{RAKE_ENV}_structure.sql").join.split(";\n\n").each do |ddl|
  346 + ActiveRecord::Base.connection.execute(ddl)
  347 + end
  348 + when "firebird"
  349 + set_firebird_env(abcs["test"])
  350 + db_string = firebird_db_string(abcs["test"])
  351 + sh "isql -i #{RAILS_ROOT}/db/#{RAKE_ENV}_structure.sql #{db_string}"
  352 + else
  353 + raise "Task not supported by '#{abcs["test"]["adapter"]}'"
  354 + end
  355 + end
  356 +
  357 + desc "Empty the test database"
  358 + task :purge => :environment do
  359 + abcs = ActiveRecord::Base.configurations
  360 + case abcs["test"]["adapter"]
  361 + when "mysql"
  362 + ActiveRecord::Base.establish_connection(:test)
  363 + ActiveRecord::Base.connection.recreate_database(abcs["test"]["database"], abcs["test"])
  364 + when "postgresql"
  365 + ActiveRecord::Base.clear_active_connections!
  366 + drop_database(abcs['test'])
  367 + create_database(abcs['test'])
  368 + when "sqlite","sqlite3"
  369 + dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
  370 + File.delete(dbfile) if File.exist?(dbfile)
  371 + when "sqlserver"
  372 + dropfkscript = "#{abcs["test"]["host"]}.#{abcs["test"]["database"]}.DP1".gsub(/\\/,'-')
  373 + `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{dropfkscript}`
  374 + `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAKE_ENV}_structure.sql`
  375 + when "oci", "oracle"
  376 + ActiveRecord::Base.establish_connection(:test)
  377 + ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
  378 + ActiveRecord::Base.connection.execute(ddl)
  379 + end
  380 + when "firebird"
  381 + ActiveRecord::Base.establish_connection(:test)
  382 + ActiveRecord::Base.connection.recreate_database!
  383 + else
  384 + raise "Task not supported by '#{abcs["test"]["adapter"]}'"
  385 + end
  386 + end
  387 +
  388 + desc 'Check for pending migrations and load the test schema'
  389 + task :prepare => 'db:abort_if_pending_migrations' do
  390 + if defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
  391 + Rake::Task[{ :sql => "db:test:clone_structure", :ruby => "db:test:load" }[ActiveRecord::Base.schema_format]].invoke
  392 + end
  393 + end
  394 + end
  395 +
  396 + namespace :sessions do
  397 + desc "Creates a sessions migration for use with ActiveRecord::SessionStore"
  398 + task :create => :environment do
  399 + raise "Task unavailable to this database (no migration support)" unless ActiveRecord::Base.connection.supports_migrations?
  400 + require 'rails_generator'
  401 + require 'rails_generator/scripts/generate'
  402 + Rails::Generator::Scripts::Generate.new.run(["session_migration", ENV["MIGRATION"] || "CreateSessions"])
  403 + end
  404 +
  405 + desc "Clear the sessions table"
  406 + task :clear => :environment do
  407 + ActiveRecord::Base.connection.execute "DELETE FROM #{session_table_name}"
  408 + end
  409 + end
  410 +end
  411 +
  412 +def drop_database(config)
  413 + case config['adapter']
  414 + when 'mysql'
  415 + ActiveRecord::Base.establish_connection(config)
  416 + ActiveRecord::Base.connection.drop_database config['database']
  417 + when /^sqlite/
  418 + FileUtils.rm(File.join(RAILS_ROOT, config['database']))
  419 + when 'postgresql'
  420 + ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
  421 + ActiveRecord::Base.connection.drop_database config['database']
  422 + end
  423 +end
  424 +
  425 +def session_table_name
  426 + ActiveRecord::Base.pluralize_table_names ? :sessions : :session
  427 +end
4 test/test_helper.rb
@@ -8,8 +8,6 @@
8 8 require 'active_support/testing/assertions'
9 9 require 'mocha'
10 10
11   -Ohm.flush
12   -
13 11 Debugger.start
14 12 Debugger.settings[:autoeval] = true
15 13 Debugger.settings[:autolist] = 1
@@ -65,6 +63,4 @@ def factory(options = {}, &block)
65 63 end
66 64 end
67 65
68   -Ohm::Model.extend(Factory)
69   -
70 66 require "factories"

0 comments on commit daba80f

Please sign in to comment.
Something went wrong with that request. Please try again.