aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/aaa_create_tables_test.rb
blob: f1fae8a4694e8674d825210d27107787e1e635f8 (plain) (blame)
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
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
62
63
64
65
66
67
68
69
70
71
72
# The filename begins with "aaa" to ensure this is the first test.
require 'abstract_unit'

class AAACreateTablesTest < ActiveSupport::TestCase
  self.use_transactional_fixtures = false

  def setup
    @base_path = "#{File.dirname(__FILE__)}/../schema"
  end

  def test_drop_and_create_main_tables
    recreate ActiveRecord::Base unless use_migrations?
    assert true
  end

  def test_load_schema
    if ActiveRecord::Base.connection.supports_migrations?
      eval(File.read("#{File.dirname(__FILE__)}/../schema/schema.rb"))
    else
      recreate ActiveRecord::Base, '3'
    end
    assert true
  end

  def test_drop_and_create_courses_table
    if Course.connection.supports_migrations?
      eval(File.read("#{File.dirname(__FILE__)}/../schema/schema2.rb"))
    end
    recreate Course, '2' unless use_migrations_for_courses?
    assert true
  end

  private
    def use_migrations?
      unittest_sql_filename = ActiveRecord::Base.connection.adapter_name.downcase + ".sql"
      not File.exist? "#{@base_path}/#{unittest_sql_filename}"
    end

    def use_migrations_for_courses?
      unittest2_sql_filename = ActiveRecord::Base.connection.adapter_name.downcase + "2.sql"
      not File.exist? "#{@base_path}/#{unittest2_sql_filename}"
    end

    def recreate(base, suffix = nil)
      connection = base.connection
      adapter_name = connection.adapter_name.downcase + suffix.to_s
      execute_sql_file "#{@base_path}/#{adapter_name}.drop.sql", connection
      execute_sql_file "#{@base_path}/#{adapter_name}.sql", connection
    end

    def execute_sql_file(path, connection)
      # OpenBase has a different format for sql files
      if current_adapter?(:OpenBaseAdapter) then
          File.read(path).split("go").each_with_index do |sql, i|
            begin
              # OpenBase does not support comments embedded in sql
              connection.execute(sql,"SQL statement ##{i}") unless sql.blank?
            rescue ActiveRecord::StatementInvalid
              #$stderr.puts "warning: #{$!}"
            end
          end
      else
        File.read(path).split(';').each_with_index do |sql, i|
          begin
            connection.execute("\n\n-- statement ##{i}\n#{sql}\n") unless sql.blank?
          rescue ActiveRecord::StatementInvalid
            #$stderr.puts "warning: #{$!}"
          end
        end
      end
    end
end