1
2
3
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
29
30
namespace :converter do
  desc "Run the converter migrations"
  task :migrate => :environment do
    require 'tasks/converter'
    ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
    ConverterMigrator.migrate("db/converter/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
  end  
end

class ConverterMigrator < ActiveRecord::Migrator
  def self.ensure_extra_schema_info_exists
    begin
      cxn = ActiveRecord::Base.connection
      table_name = cxn.quote_table_name(ActiveRecord::Migrator.schema_info_table_name)
      int_type = cxn.type_to_sql(:integer)
      cxn.execute "ALTER TABLE #{table_name} ADD imported_data_version #{int_type}"
    rescue ActiveRecord::StatementInvalid
      # Schema has been initialized
    end
  end
  def self.current_version
    ensure_extra_schema_info_exists
    ActiveRecord::Base.connection.select_value("SELECT imported_data_version FROM #{schema_info_table_name}").to_i
  end
  
  def set_schema_version(version)
    self.class.ensure_extra_schema_info_exists
    ActiveRecord::Base.connection.update("UPDATE #{self.class.schema_info_table_name} SET imported_data_version = #{down? ? version.to_i - 1 : version.to_i}")
  end
end