aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/migration/foreign_key_test.rb
blob: 8d152f2cf455f59e0bf381b4a58b2970cc8d48f7 (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# frozen_string_literal: true

require "cases/helper"
require "support/schema_dumping_helper"

if ActiveRecord::Base.connection.supports_foreign_keys_in_create?
  module ActiveRecord
    class Migration
      class ForeignKeyInCreateTest < ActiveRecord::TestCase
        def test_foreign_keys
          foreign_keys = ActiveRecord::Base.connection.foreign_keys("fk_test_has_fk")
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          assert_equal "fk_test_has_fk", fk.from_table
          assert_equal "fk_test_has_pk", fk.to_table
          assert_equal "fk_id", fk.column
          assert_equal "pk_id", fk.primary_key
          assert_equal "fk_name", fk.name unless current_adapter?(:SQLite3Adapter)
        end
      end

      module ForeignKeyChangeColumnSharedTest
        class Rocket < ActiveRecord::Base
          has_many :astronauts
        end

        class Astronaut < ActiveRecord::Base
          belongs_to :rocket
        end

        class CreateRocketsMigration < ActiveRecord::Migration::Current
          def up
            create_table :rockets do |t|
              t.string :name
            end

            create_table :astronauts do |t|
              t.string :name
              t.references :rocket, foreign_key: true
            end
          end

          def down
            drop_table :astronauts, if_exists: true
            drop_table :rockets, if_exists: true
          end
        end

        def setup
          @connection = ActiveRecord::Base.connection
          @migration = CreateRocketsMigration.new
          silence_stream($stdout) { @migration.migrate(:up) }
          Rocket.reset_table_name
          Rocket.reset_column_information
          Astronaut.reset_table_name
          Astronaut.reset_column_information
        end

        def teardown
          silence_stream($stdout) { @migration.migrate(:down) }
          Rocket.reset_table_name
          Rocket.reset_column_information
          Astronaut.reset_table_name
          Astronaut.reset_column_information
        end

        def test_change_column_of_parent_table
          rocket = Rocket.create!(name: "myrocket")
          rocket.astronauts << Astronaut.create!

          @connection.change_column_null Rocket.table_name, :name, false

          foreign_keys = @connection.foreign_keys(Astronaut.table_name)
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          assert_equal "myrocket", Rocket.first.name
          assert_equal Astronaut.table_name, fk.from_table
          assert_equal Rocket.table_name, fk.to_table
        end

        def test_rename_column_of_child_table
          rocket = Rocket.create!(name: "myrocket")
          rocket.astronauts << Astronaut.create!

          @connection.rename_column Astronaut.table_name, :name, :astronaut_name

          foreign_keys = @connection.foreign_keys(Astronaut.table_name)
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          assert_equal "myrocket", Rocket.first.name
          assert_equal Astronaut.table_name, fk.from_table
          assert_equal Rocket.table_name, fk.to_table
        end

        def test_rename_reference_column_of_child_table
          rocket = Rocket.create!(name: "myrocket")
          rocket.astronauts << Astronaut.create!

          @connection.rename_column Astronaut.table_name, :rocket_id, :new_rocket_id

          foreign_keys = @connection.foreign_keys(Astronaut.table_name)
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          assert_equal "myrocket", Rocket.first.name
          assert_equal Astronaut.table_name, fk.from_table
          assert_equal Rocket.table_name, fk.to_table
          assert_equal "new_rocket_id", fk.options[:column]
        end

        def test_remove_reference_column_of_child_table
          rocket = Rocket.create!(name: "myrocket")
          rocket.astronauts << Astronaut.create!

          @connection.remove_column Astronaut.table_name, :rocket_id

          assert_empty @connection.foreign_keys(Astronaut.table_name)
        end
      end

      class ForeignKeyChangeColumnTest < ActiveRecord::TestCase
        include ForeignKeyChangeColumnSharedTest

        self.use_transactional_tests = false
      end

      class ForeignKeyChangeColumnWithPrefixTest < ActiveRecord::TestCase
        include ForeignKeyChangeColumnSharedTest

        self.use_transactional_tests = false

        setup do
          ActiveRecord::Base.table_name_prefix = "p_"
        end

        teardown do
          ActiveRecord::Base.table_name_prefix = nil
        end
      end

      class ForeignKeyChangeColumnWithSuffixTest < ActiveRecord::TestCase
        include ForeignKeyChangeColumnSharedTest

        self.use_transactional_tests = false

        setup do
          ActiveRecord::Base.table_name_suffix = "_p"
        end

        teardown do
          ActiveRecord::Base.table_name_suffix = nil
        end
      end
    end
  end
end

if ActiveRecord::Base.connection.supports_foreign_keys?
  module ActiveRecord
    class Migration
      class ForeignKeyTest < ActiveRecord::TestCase
        include SchemaDumpingHelper
        include ActiveSupport::Testing::Stream

        class Rocket < ActiveRecord::Base
        end

        class Astronaut < ActiveRecord::Base
        end

        setup do
          @connection = ActiveRecord::Base.connection
          @connection.create_table "rockets", force: true do |t|
            t.string :name
          end

          @connection.create_table "astronauts", force: true do |t|
            t.string :name
            t.references :rocket
          end
        end

        teardown do
          @connection.drop_table "astronauts", if_exists: true
          @connection.drop_table "rockets", if_exists: true
        end

        def test_foreign_keys
          foreign_keys = @connection.foreign_keys("fk_test_has_fk")
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          assert_equal "fk_test_has_fk", fk.from_table
          assert_equal "fk_test_has_pk", fk.to_table
          assert_equal "fk_id", fk.column
          assert_equal "pk_id", fk.primary_key
          assert_equal "fk_name", fk.name
        end

        def test_add_foreign_key_inferes_column
          @connection.add_foreign_key :astronauts, :rockets

          foreign_keys = @connection.foreign_keys("astronauts")
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          assert_equal "astronauts", fk.from_table
          assert_equal "rockets", fk.to_table
          assert_equal "rocket_id", fk.column
          assert_equal "id", fk.primary_key
          assert_equal("fk_rails_78146ddd2e", fk.name)
        end

        def test_add_foreign_key_with_column
          @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id"

          foreign_keys = @connection.foreign_keys("astronauts")
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          assert_equal "astronauts", fk.from_table
          assert_equal "rockets", fk.to_table
          assert_equal "rocket_id", fk.column
          assert_equal "id", fk.primary_key
          assert_equal("fk_rails_78146ddd2e", fk.name)
        end

        def test_add_foreign_key_with_non_standard_primary_key
          @connection.create_table :space_shuttles, id: false, force: true do |t|
            t.bigint :pk, primary_key: true
          end

          @connection.add_foreign_key(:astronauts, :space_shuttles,
            column: "rocket_id", primary_key: "pk", name: "custom_pk")

          foreign_keys = @connection.foreign_keys("astronauts")
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          assert_equal "astronauts", fk.from_table
          assert_equal "space_shuttles", fk.to_table
          assert_equal "pk", fk.primary_key
        ensure
          @connection.remove_foreign_key :astronauts, name: "custom_pk"
          @connection.drop_table :space_shuttles
        end

        def test_add_on_delete_restrict_foreign_key
          @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :restrict

          foreign_keys = @connection.foreign_keys("astronauts")
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          if current_adapter?(:Mysql2Adapter)
            # ON DELETE RESTRICT is the default on MySQL
            assert_nil fk.on_delete
          else
            assert_equal :restrict, fk.on_delete
          end
        end

        def test_add_on_delete_cascade_foreign_key
          @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :cascade

          foreign_keys = @connection.foreign_keys("astronauts")
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          assert_equal :cascade, fk.on_delete
        end

        def test_add_on_delete_nullify_foreign_key
          @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify

          foreign_keys = @connection.foreign_keys("astronauts")
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          assert_equal :nullify, fk.on_delete
        end

        def test_on_update_and_on_delete_raises_with_invalid_values
          assert_raises ArgumentError do
            @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :invalid
          end

          assert_raises ArgumentError do
            @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :invalid
          end
        end

        def test_add_foreign_key_with_on_update
          @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :nullify

          foreign_keys = @connection.foreign_keys("astronauts")
          assert_equal 1, foreign_keys.size

          fk = foreign_keys.first
          assert_equal :nullify, fk.on_update
        end

        def test_foreign_key_exists
          @connection.add_foreign_key :astronauts, :rockets

          assert @connection.foreign_key_exists?(:astronauts, :rockets)
          assert_not @connection.foreign_key_exists?(:astronauts, :stars)
        end

        def test_foreign_key_exists_by_column
          @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id"

          assert @connection.foreign_key_exists?(:astronauts, column: "rocket_id")
          assert_not @connection.foreign_key_exists?(:astronauts, column: "star_id")
        end

        def test_foreign_key_exists_by_name
          @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk"

          assert @connection.foreign_key_exists?(:astronauts, name: "fancy_named_fk")
          assert_not @connection.foreign_key_exists?(:astronauts, name: "other_fancy_named_fk")
        end

        def test_remove_foreign_key_inferes_column
          @connection.add_foreign_key :astronauts, :rockets

          assert_equal 1, @connection.foreign_keys("astronauts").size
          @connection.remove_foreign_key :astronauts, :rockets
          assert_equal [], @connection.foreign_keys("astronauts")
        end

        def test_remove_foreign_key_by_column
          @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id"

          assert_equal 1, @connection.foreign_keys("astronauts").size
          @connection.remove_foreign_key :astronauts, column: "rocket_id"
          assert_equal [], @connection.foreign_keys("astronauts")
        end

        def test_remove_foreign_key_by_symbol_column
          @connection.add_foreign_key :astronauts, :rockets, column: :rocket_id

          assert_equal 1, @connection.foreign_keys("astronauts").size
          @connection.remove_foreign_key :astronauts, column: :rocket_id
          assert_equal [], @connection.foreign_keys("astronauts")
        end

        def test_remove_foreign_key_by_name
          @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk"

          assert_equal 1, @connection.foreign_keys("astronauts").size
          @connection.remove_foreign_key :astronauts, name: "fancy_named_fk"
          assert_equal [], @connection.foreign_keys("astronauts")
        end

        def test_remove_foreign_non_existing_foreign_key_raises
          assert_raises ArgumentError do
            @connection.remove_foreign_key :astronauts, :rockets
          end
        end

        if ActiveRecord::Base.connection.supports_validate_constraints?
          def test_add_invalid_foreign_key
            @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", validate: false

            foreign_keys = @connection.foreign_keys("astronauts")
            assert_equal 1, foreign_keys.size

            fk = foreign_keys.first
            assert_not_predicate fk, :validated?
          end

          def test_validate_foreign_key_infers_column
            @connection.add_foreign_key :astronauts, :rockets, validate: false
            assert_not_predicate @connection.foreign_keys("astronauts").first, :validated?

            @connection.validate_foreign_key :astronauts, :rockets
            assert_predicate @connection.foreign_keys("astronauts").first, :validated?
          end

          def test_validate_foreign_key_by_column
            @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", validate: false
            assert_not_predicate @connection.foreign_keys("astronauts").first, :validated?

            @connection.validate_foreign_key :astronauts, column: "rocket_id"
            assert_predicate @connection.foreign_keys("astronauts").first, :validated?
          end

          def test_validate_foreign_key_by_symbol_column
            @connection.add_foreign_key :astronauts, :rockets, column: :rocket_id, validate: false
            assert_not_predicate @connection.foreign_keys("astronauts").first, :validated?

            @connection.validate_foreign_key :astronauts, column: :rocket_id
            assert_predicate @connection.foreign_keys("astronauts").first, :validated?
          end

          def test_validate_foreign_key_by_name
            @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk", validate: false
            assert_not_predicate @connection.foreign_keys("astronauts").first, :validated?

            @connection.validate_foreign_key :astronauts, name: "fancy_named_fk"
            assert_predicate @connection.foreign_keys("astronauts").first, :validated?
          end

          def test_validate_foreign_non_existing_foreign_key_raises
            assert_raises ArgumentError do
              @connection.validate_foreign_key :astronauts, :rockets
            end
          end

          def test_validate_constraint_by_name
            @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk", validate: false

            @connection.validate_constraint :astronauts, "fancy_named_fk"
            assert_predicate @connection.foreign_keys("astronauts").first, :validated?
          end
        else
          # Foreign key should still be created, but should not be invalid
          def test_add_invalid_foreign_key
            @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", validate: false

            foreign_keys = @connection.foreign_keys("astronauts")
            assert_equal 1, foreign_keys.size

            fk = foreign_keys.first
            assert_predicate fk, :validated?
          end
        end

        def test_schema_dumping
          @connection.add_foreign_key :astronauts, :rockets
          output = dump_table_schema "astronauts"
          assert_match %r{\s+add_foreign_key "astronauts", "rockets"$}, output
        end

        def test_schema_dumping_with_options
          output = dump_table_schema "fk_test_has_fk"
          assert_match %r{\s+add_foreign_key "fk_test_has_fk", "fk_test_has_pk", column: "fk_id", primary_key: "pk_id", name: "fk_name"$}, output
        end

        def test_schema_dumping_with_custom_fk_ignore_pattern
          original_pattern = ActiveRecord::SchemaDumper.fk_ignore_pattern
          ActiveRecord::SchemaDumper.fk_ignore_pattern = /^ignored_/
          @connection.add_foreign_key :astronauts, :rockets, name: :ignored_fk_astronauts_rockets

          output = dump_table_schema "astronauts"
          assert_match %r{\s+add_foreign_key "astronauts", "rockets"$}, output

          ActiveRecord::SchemaDumper.fk_ignore_pattern = original_pattern
        end

        def test_schema_dumping_on_delete_and_on_update_options
          @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify, on_update: :cascade

          output = dump_table_schema "astronauts"
          assert_match %r{\s+add_foreign_key "astronauts",.+on_update: :cascade,.+on_delete: :nullify$}, output
        end

        class CreateCitiesAndHousesMigration < ActiveRecord::Migration::Current
          def change
            create_table("cities") { |t| }

            create_table("houses") do |t|
              t.references :city
            end
            add_foreign_key :houses, :cities, column: "city_id"

            # remove and re-add to test that schema is updated and not accidentally cached
            remove_foreign_key :houses, :cities
            add_foreign_key :houses, :cities, column: "city_id", on_delete: :cascade
          end
        end

        def test_add_foreign_key_is_reversible
          migration = CreateCitiesAndHousesMigration.new
          silence_stream($stdout) { migration.migrate(:up) }
          assert_equal 1, @connection.foreign_keys("houses").size
        ensure
          silence_stream($stdout) { migration.migrate(:down) }
        end

        def test_foreign_key_constraint_is_not_cached_incorrectly
          migration = CreateCitiesAndHousesMigration.new
          silence_stream($stdout) { migration.migrate(:up) }
          output = dump_table_schema "houses"
          assert_match %r{\s+add_foreign_key "houses",.+on_delete: :cascade$}, output
        ensure
          silence_stream($stdout) { migration.migrate(:down) }
        end

        class CreateSchoolsAndClassesMigration < ActiveRecord::Migration::Current
          def change
            create_table(:schools)

            create_table(:classes) do |t|
              t.references :school
            end
            add_foreign_key :classes, :schools
          end
        end

        def test_add_foreign_key_with_prefix
          ActiveRecord::Base.table_name_prefix = "p_"
          migration = CreateSchoolsAndClassesMigration.new
          silence_stream($stdout) { migration.migrate(:up) }
          assert_equal 1, @connection.foreign_keys("p_classes").size
        ensure
          silence_stream($stdout) { migration.migrate(:down) }
          ActiveRecord::Base.table_name_prefix = nil
        end

        def test_add_foreign_key_with_suffix
          ActiveRecord::Base.table_name_suffix = "_s"
          migration = CreateSchoolsAndClassesMigration.new
          silence_stream($stdout) { migration.migrate(:up) }
          assert_equal 1, @connection.foreign_keys("classes_s").size
        ensure
          silence_stream($stdout) { migration.migrate(:down) }
          ActiveRecord::Base.table_name_suffix = nil
        end
      end
    end
  end
else
  module ActiveRecord
    class Migration
      class NoForeignKeySupportTest < ActiveRecord::TestCase
        setup do
          @connection = ActiveRecord::Base.connection
        end

        def test_add_foreign_key_should_be_noop
          @connection.add_foreign_key :clubs, :categories
        end

        def test_remove_foreign_key_should_be_noop
          @connection.remove_foreign_key :clubs, :categories
        end

        unless current_adapter?(:SQLite3Adapter)
          def test_foreign_keys_should_raise_not_implemented
            assert_raises NotImplementedError do
              @connection.foreign_keys("clubs")
            end
          end
        end
      end
    end
  end
end