schema_dumper_test.rb 16.3 KB
Newer Older
1
require "cases/helper"
2
require 'support/schema_dumping_helper'
3

4
class SchemaDumperTest < ActiveRecord::TestCase
5
  include SchemaDumpingHelper
6 7
  self.use_transactional_fixtures = false

S
Sean Griffin 已提交
8
  setup do
9
    ActiveRecord::SchemaMigration.create_table
10 11
  end

12
  def standard_dump
J
Jeremy Kemper 已提交
13 14 15 16 17
    @@standard_dump ||= perform_schema_dump
  end

  def perform_schema_dump
    dump_all_table_schema []
18 19
  end

20 21 22
  def test_dump_schema_information_outputs_lexically_ordered_versions
    versions = %w{ 20100101010101 20100201010101 20100301010101 }
    versions.reverse.each do |v|
23
      ActiveRecord::SchemaMigration.create!(:version => v)
24 25 26 27
    end

    schema_info = ActiveRecord::Base.connection.dump_schema_information
    assert_match(/20100201010101.*20100301010101/m, schema_info)
28 29
  ensure
    ActiveRecord::SchemaMigration.delete_all
30 31
  end

32
  def test_magic_comment
J
Jeremy Kemper 已提交
33
    assert_match "# encoding: #{Encoding.default_external.name}", standard_dump
34
  end
J
Jeremy Kemper 已提交
35

36 37 38 39 40 41
  def test_schema_dump
    output = standard_dump
    assert_match %r{create_table "accounts"}, output
    assert_match %r{create_table "authors"}, output
    assert_no_match %r{create_table "schema_migrations"}, output
  end
J
Jeremy Kemper 已提交
42

43 44 45 46
  def test_schema_dump_excludes_sqlite_sequence
    output = standard_dump
    assert_no_match %r{create_table "sqlite_sequence"}, output
  end
47

48 49 50 51 52
  def test_schema_dump_includes_camelcase_table_name
    output = standard_dump
    assert_match %r{create_table "CamelCase"}, output
  end

53 54 55 56 57 58 59 60
  def assert_line_up(lines, pattern, required = false)
    return assert(true) if lines.empty?
    matches = lines.map { |line| line.match(pattern) }
    assert matches.all? if required
    matches.compact!
    return assert(true) if matches.empty?
    assert_equal 1, matches.map{ |match| match.offset(0).first }.uniq.length
  end
61

62 63 64
  def column_definition_lines(output = standard_dump)
    output.scan(/^( *)create_table.*?\n(.*?)^\1end/m).map{ |m| m.last.split(/\n/) }
  end
65

66 67 68
  def test_types_line_up
    column_definition_lines.each do |column_set|
      next if column_set.empty?
69

70
      lengths = column_set.map do |column|
71
        if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean|uuid|point)\s+"/)
72
          match[0].length
73 74
        end
      end
J
Jeremy Kemper 已提交
75

76
      assert_equal 1, lengths.uniq.length
77
    end
78
  end
J
Jeremy Kemper 已提交
79

80 81
  def test_arguments_line_up
    column_definition_lines.each do |column_set|
82 83 84
      assert_line_up(column_set, /default: /)
      assert_line_up(column_set, /limit: /)
      assert_line_up(column_set, /null: /)
85
    end
86
  end
J
Jeremy Kemper 已提交
87

88 89 90 91
  def test_no_dump_errors
    output = standard_dump
    assert_no_match %r{\# Could not dump table}, output
  end
J
Jeremy Kemper 已提交
92

93
  def test_schema_dump_includes_not_null_columns
94
    output = dump_all_table_schema([/^[^r]/])
95
    assert_match %r{null: false}, output
96
  end
J
Jeremy Kemper 已提交
97

98
  def test_schema_dump_includes_limit_constraint_for_integer_columns
99
    output = dump_all_table_schema([/^(?!integer_limits)/])
100

101 102
    assert_match %r{c_int_without_limit}, output

103
    if current_adapter?(:PostgreSQLAdapter)
104 105
      assert_no_match %r{c_int_without_limit.*limit:}, output

106 107
      assert_match %r{c_int_1.*limit: 2}, output
      assert_match %r{c_int_2.*limit: 2}, output
108 109 110

      # int 3 is 4 bytes in postgresql
      assert_match %r{c_int_3.*}, output
111
      assert_no_match %r{c_int_3.*limit:}, output
112 113

      assert_match %r{c_int_4.*}, output
114
      assert_no_match %r{c_int_4.*limit:}, output
115
    elsif current_adapter?(:MysqlAdapter, :Mysql2Adapter)
116 117
      assert_match %r{c_int_without_limit.*limit: 4}, output

118 119 120
      assert_match %r{c_int_1.*limit: 1}, output
      assert_match %r{c_int_2.*limit: 2}, output
      assert_match %r{c_int_3.*limit: 3}, output
121 122 123

      assert_match %r{c_int_4.*}, output
      assert_no_match %r{c_int_4.*:limit}, output
124
    elsif current_adapter?(:SQLite3Adapter)
125 126
      assert_no_match %r{c_int_without_limit.*limit:}, output

127 128 129 130
      assert_match %r{c_int_1.*limit: 1}, output
      assert_match %r{c_int_2.*limit: 2}, output
      assert_match %r{c_int_3.*limit: 3}, output
      assert_match %r{c_int_4.*limit: 4}, output
131 132
    end

133
    if current_adapter?(:SQLite3Adapter)
134 135 136 137
      assert_match %r{c_int_5.*limit: 5}, output
      assert_match %r{c_int_6.*limit: 6}, output
      assert_match %r{c_int_7.*limit: 7}, output
      assert_match %r{c_int_8.*limit: 8}, output
138
    elsif current_adapter?(:OracleAdapter)
139 140 141 142
      assert_match %r{c_int_5.*limit: 5}, output
      assert_match %r{c_int_6.*limit: 6}, output
      assert_match %r{c_int_7.*limit: 7}, output
      assert_match %r{c_int_8.*limit: 8}, output
143
    else
144 145 146 147
      assert_match %r{c_int_5.*limit: 8}, output
      assert_match %r{c_int_6.*limit: 8}, output
      assert_match %r{c_int_7.*limit: 8}, output
      assert_match %r{c_int_8.*limit: 8}, output
148 149 150
    end
  end

151
  def test_schema_dump_with_string_ignored_table
152
    output = dump_all_table_schema(['accounts'])
153 154 155 156 157 158
    assert_no_match %r{create_table "accounts"}, output
    assert_match %r{create_table "authors"}, output
    assert_no_match %r{create_table "schema_migrations"}, output
  end

  def test_schema_dump_with_regexp_ignored_table
159
    output = dump_all_table_schema([/^account/])
160 161 162 163
    assert_no_match %r{create_table "accounts"}, output
    assert_match %r{create_table "authors"}, output
    assert_no_match %r{create_table "schema_migrations"}, output
  end
J
Jeremy Kemper 已提交
164

165 166
  def test_schema_dump_illegal_ignored_table_value
    stream = StringIO.new
167
    old_ignore_tables, ActiveRecord::SchemaDumper.ignore_tables = ActiveRecord::SchemaDumper.ignore_tables, [5]
168
    assert_raise(StandardError) do
169 170
      ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
    end
171 172
  ensure
    ActiveRecord::SchemaDumper.ignore_tables = old_ignore_tables
173
  end
174

175 176
  def test_schema_dumps_index_columns_in_right_order
    index_definition = standard_dump.split(/\n/).grep(/add_index.*companies/).first.strip
177
    if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
178 179 180
      assert_equal 'add_index "companies", ["firm_id", "type", "rating"], name: "company_index", using: :btree', index_definition
    else
      assert_equal 'add_index "companies", ["firm_id", "type", "rating"], name: "company_index"', index_definition
181
    end
182
  end
183

184 185 186
  def test_schema_dumps_partial_indices
    index_definition = standard_dump.split(/\n/).grep(/add_index.*company_partial_index/).first.strip
    if current_adapter?(:PostgreSQLAdapter)
187
      assert_equal 'add_index "companies", ["firm_id", "type"], name: "company_partial_index", where: "(rating > 10)", using: :btree', index_definition
188
    elsif current_adapter?(:MysqlAdapter, :Mysql2Adapter)
189
      assert_equal 'add_index "companies", ["firm_id", "type"], name: "company_partial_index", using: :btree', index_definition
190 191
    elsif current_adapter?(:SQLite3Adapter) && ActiveRecord::Base.connection.supports_partial_index?
      assert_equal 'add_index "companies", ["firm_id", "type"], name: "company_partial_index", where: "rating > 10"', index_definition
192
    else
193
      assert_equal 'add_index "companies", ["firm_id", "type"], name: "company_partial_index"', index_definition
194 195 196
    end
  end

197 198 199 200
  def test_schema_dump_should_honor_nonstandard_primary_keys
    output = standard_dump
    match = output.match(%r{create_table "movies"(.*)do})
    assert_not_nil(match, "nonstandardpk table not found")
201
    assert_match %r(primary_key: "movieid"), match[1], "non-standard primary key not preserved"
202
  end
203

204 205 206 207 208
  def test_schema_dump_should_use_false_as_default
    output = standard_dump
    assert_match %r{t\.boolean\s+"has_fun",.+default: false}, output
  end

209
  if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
210
    def test_schema_dump_should_add_default_value_for_mysql_text_field
211
      output = standard_dump
212
      assert_match %r{t.text\s+"body",\s+limit: 65535,\s+null: false$}, output
213
    end
214

215 216 217 218 219 220
    def test_schema_dump_includes_length_for_mysql_binary_fields
      output = standard_dump
      assert_match %r{t.binary\s+"var_binary",\s+limit: 255$}, output
      assert_match %r{t.binary\s+"var_binary_large",\s+limit: 4095$}, output
    end

221 222
    def test_schema_dump_includes_length_for_mysql_blob_and_text_fields
      output = standard_dump
223
      assert_match %r{t.binary\s+"tiny_blob",\s+limit: 255$}, output
224
      assert_match %r{t.binary\s+"normal_blob",\s+limit: 65535$}, output
225
      assert_match %r{t.binary\s+"medium_blob",\s+limit: 16777215$}, output
226
      assert_match %r{t.binary\s+"long_blob",\s+limit: 4294967295$}, output
227
      assert_match %r{t.text\s+"tiny_text",\s+limit: 255$}, output
228
      assert_match %r{t.text\s+"normal_text",\s+limit: 65535$}, output
229
      assert_match %r{t.text\s+"medium_text",\s+limit: 16777215$}, output
230
      assert_match %r{t.text\s+"long_text",\s+limit: 4294967295$}, output
231
    end
232 233 234 235 236 237

    def test_schema_dumps_index_type
      output = standard_dump
      assert_match %r{add_index "key_tests", \["awesome"\], name: "index_key_tests_on_awesome", type: :fulltext}, output
      assert_match %r{add_index "key_tests", \["pizza"\], name: "index_key_tests_on_pizza", using: :btree}, output
    end
238
  end
239

240
  def test_schema_dump_includes_decimal_options
241
    output = dump_all_table_schema([/^[^n]/])
242
    assert_match %r{precision: 3,[[:space:]]+scale: 2,[[:space:]]+default: 2.78}, output
243
  end
244

245
  if current_adapter?(:PostgreSQLAdapter)
246 247 248 249 250
    def test_schema_dump_includes_bigint_default
      output = standard_dump
      assert_match %r{t.integer\s+"bigint_default",\s+limit: 8,\s+default: 0}, output
    end

251 252 253 254 255
    if ActiveRecord::Base.connection.supports_extensions?
      def test_schema_dump_includes_extensions
        connection = ActiveRecord::Base.connection

        connection.stubs(:extensions).returns(['hstore'])
J
Jeremy Kemper 已提交
256
        output = perform_schema_dump
257 258 259 260
        assert_match "# These are extensions that must be enabled", output
        assert_match %r{enable_extension "hstore"}, output

        connection.stubs(:extensions).returns([])
J
Jeremy Kemper 已提交
261
        output = perform_schema_dump
262 263 264
        assert_no_match "# These are extensions that must be enabled", output
        assert_no_match %r{enable_extension}, output
      end
265 266
    end

267 268 269 270 271 272
    def test_schema_dump_includes_xml_shorthand_definition
      output = standard_dump
      if %r{create_table "postgresql_xml_data_type"} =~ output
        assert_match %r{t.xml "data"}, output
      end
    end
273

274 275 276
    def test_schema_dump_includes_json_shorthand_definition
      output = standard_dump
      if %r{create_table "postgresql_json_data_type"} =~ output
277
        assert_match %r|t.json "json_data", default: {}|, output
278 279 280
      end
    end

281 282
    def test_schema_dump_includes_inet_shorthand_definition
      output = standard_dump
283 284
      if %r{create_table "postgresql_network_addresses"} =~ output
        assert_match %r{t.inet\s+"inet_address",\s+default: "192.168.1.1"}, output
285 286 287 288 289
      end
    end

    def test_schema_dump_includes_cidr_shorthand_definition
      output = standard_dump
290 291
      if %r{create_table "postgresql_network_addresses"} =~ output
        assert_match %r{t.cidr\s+"cidr_address",\s+default: "192.168.1.0/24"}, output
292 293 294 295 296
      end
    end

    def test_schema_dump_includes_macaddr_shorthand_definition
      output = standard_dump
297 298
      if %r{create_table "postgresql_network_addresses"} =~ output
        assert_match %r{t.macaddr\s+"mac_address",\s+default: "ff:ff:ff:ff:ff:ff"}, output
299 300 301
      end
    end

302 303
    def test_schema_dump_includes_uuid_shorthand_definition
      output = standard_dump
304
      if %r{create_table "postgresql_uuids"} =~ output
305 306 307 308
        assert_match %r{t.uuid "guid"}, output
      end
    end

309
    def test_schema_dump_includes_hstores_shorthand_definition
J
Joel 已提交
310 311
      output = standard_dump
      if %r{create_table "postgresql_hstores"} =~ output
312
        assert_match %r[t.hstore "hash_store", default: {}], output
J
Joel 已提交
313 314 315
      end
    end

316 317 318 319 320 321 322
    def test_schema_dump_includes_citext_shorthand_definition
      output = standard_dump
      if %r{create_table "postgresql_citext"} =~ output
        assert_match %r[t.citext "text_citext"], output
      end
    end

323 324 325 326 327 328 329
    def test_schema_dump_includes_ltrees_shorthand_definition
      output = standard_dump
      if %r{create_table "postgresql_ltrees"} =~ output
        assert_match %r[t.ltree "path"], output
      end
    end

330 331 332 333 334 335 336 337
    def test_schema_dump_includes_arrays_shorthand_definition
      output = standard_dump
      if %r{create_table "postgresql_arrays"} =~ output
        assert_match %r[t.text\s+"nicknames",\s+array: true], output
        assert_match %r[t.integer\s+"commission_by_quarter",\s+array: true], output
      end
    end

338 339 340 341 342 343
    def test_schema_dump_includes_tsvector_shorthand_definition
      output = standard_dump
      if %r{create_table "postgresql_tsvectors"} =~ output
        assert_match %r{t.tsvector "text_vector"}, output
      end
    end
344 345
  end

346 347
  def test_schema_dump_keeps_large_precision_integer_columns_as_decimal
    output = standard_dump
348 349
    # Oracle supports precision up to 38 and it identifies decimals with scale 0 as integers
    if current_adapter?(:OracleAdapter)
350
      assert_match %r{t.integer\s+"atoms_in_universe",\s+precision: 38}, output
351
    else
352
      assert_match %r{t.decimal\s+"atoms_in_universe",\s+precision: 55}, output
353
    end
354
  end
355 356 357 358 359

  def test_schema_dump_keeps_id_column_when_id_is_false_and_id_column_added
    output = standard_dump
    match = output.match(%r{create_table "goofy_string_id"(.*)do.*\n(.*)\n})
    assert_not_nil(match, "goofy_string_id table not found")
360
    assert_match %r(id: false), match[1], "no table id not preserved"
361
    assert_match %r{t.string\s+"id",.*?null: false$}, match[2], "non-primary key id column not preserved"
362
  end
363 364 365

  def test_schema_dump_keeps_id_false_when_id_is_false_and_unique_not_null_column_added
    output = standard_dump
366
    assert_match %r{create_table "subscribers", id: false}, output
367
  end
368

369 370 371 372 373
  if ActiveRecord::Base.connection.supports_foreign_keys?
    def test_foreign_keys_are_dumped_at_the_bottom_to_circumvent_dependency_issues
      output = standard_dump
      assert_match(/^\s+add_foreign_key "fk_test_has_fk"[^\n]+\n\s+add_foreign_key "lessons_students"/, output)
    end
374 375 376 377 378

    def test_do_not_dump_foreign_keys_for_ignored_tables
      output = dump_table_schema "authors"
      assert_equal ["authors"], output.scan(/^\s*add_foreign_key "([^"]+)".+$/).flatten
    end
379 380
  end

381 382
  class CreateDogMigration < ActiveRecord::Migration
    def up
Y
Yves Senn 已提交
383 384 385
      create_table("dog_owners") do |t|
      end

386 387
      create_table("dogs") do |t|
        t.column :name, :string
Y
Yves Senn 已提交
388
        t.column :owner_id, :integer
389 390
      end
      add_index "dogs", [:name]
Y
Yves Senn 已提交
391
      add_foreign_key :dogs, :dog_owners, column: "owner_id" if supports_foreign_keys?
392 393 394
    end
    def down
      drop_table("dogs")
Y
Yves Senn 已提交
395
      drop_table("dog_owners")
396 397 398 399 400 401 402 403 404 405 406
    end
  end

  def test_schema_dump_with_table_name_prefix_and_suffix
    original, $stdout = $stdout, StringIO.new
    ActiveRecord::Base.table_name_prefix = 'foo_'
    ActiveRecord::Base.table_name_suffix = '_bar'

    migration = CreateDogMigration.new
    migration.migrate(:up)

J
Jeremy Kemper 已提交
407
    output = perform_schema_dump
408
    assert_no_match %r{create_table "foo_.+_bar"}, output
409
    assert_no_match %r{add_index "foo_.+_bar"}, output
410
    assert_no_match %r{create_table "schema_migrations"}, output
Y
Yves Senn 已提交
411 412 413 414 415

    if ActiveRecord::Base.connection.supports_foreign_keys?
      assert_no_match %r{add_foreign_key "foo_.+_bar"}, output
      assert_no_match %r{add_foreign_key "[^"]+", "foo_.+_bar"}, output
    end
416 417 418 419 420 421
  ensure
    migration.migrate(:down)

    ActiveRecord::Base.table_name_suffix = ActiveRecord::Base.table_name_prefix = ''
    $stdout = original
  end
422
end
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438

class SchemaDumperDefaultsTest < ActiveRecord::TestCase
  include SchemaDumpingHelper

  setup do
    @connection = ActiveRecord::Base.connection
    @connection.create_table :defaults, force: true do |t|
      t.string   :string_with_default,   default: "Hello!"
      t.date     :date_with_default,     default: '2014-06-05'
      t.datetime :datetime_with_default, default: "2014-06-05 07:17:04"
      t.time     :time_with_default,     default: "07:17:04"
    end
  end

  teardown do
    return unless @connection
439
    @connection.execute 'DROP TABLE defaults' if @connection.table_exists? 'defaults'
440 441 442 443 444
  end

  def test_schema_dump_defaults_with_universally_supported_types
    output = dump_table_schema('defaults')

445
    assert_match %r{t\.string\s+"string_with_default",.*?default: "Hello!"}, output
446 447 448 449 450
    assert_match %r{t\.date\s+"date_with_default",\s+default: '2014-06-05'}, output
    assert_match %r{t\.datetime\s+"datetime_with_default",\s+default: '2014-06-05 07:17:04'}, output
    assert_match %r{t\.time\s+"time_with_default",\s+default: '2000-01-01 07:17:04'}, output
  end
end