migration_helpers_spec.rb 35.8 KB
Newer Older
1 2
require 'spec_helper'

3
describe Gitlab::Database::MigrationHelpers do
4
  let(:model) do
5
    ActiveRecord::Migration.new.extend(described_class)
6 7
  end

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
  before do
    allow(model).to receive(:puts)
  end

  describe '#add_timestamps_with_timezone' do
    before do
      allow(model).to receive(:transaction_open?).and_return(false)
    end

    context 'using PostgreSQL' do
      before do
        allow(Gitlab::Database).to receive(:postgresql?).and_return(true)
        allow(model).to receive(:disable_statement_timeout)
      end

      it 'adds "created_at" and "updated_at" fields with the "datetime_with_timezone" data type' do
        expect(model).to receive(:add_column).with(:foo, :created_at, :datetime_with_timezone, { null: false })
        expect(model).to receive(:add_column).with(:foo, :updated_at, :datetime_with_timezone, { null: false })

        model.add_timestamps_with_timezone(:foo)
      end
    end

    context 'using MySQL' do
      before do
        allow(Gitlab::Database).to receive(:postgresql?).and_return(false)
      end

      it 'adds "created_at" and "updated_at" fields with "datetime_with_timezone" data type' do
        expect(model).to receive(:add_column).with(:foo, :created_at, :datetime_with_timezone, { null: false })
        expect(model).to receive(:add_column).with(:foo, :updated_at, :datetime_with_timezone, { null: false })

        model.add_timestamps_with_timezone(:foo)
      end
    end
  end
44

45 46 47
  describe '#add_concurrent_index' do
    context 'outside a transaction' do
      before do
48
        allow(model).to receive(:transaction_open?).and_return(false)
49 50 51
      end

      context 'using PostgreSQL' do
52 53 54 55
        before do
          allow(Gitlab::Database).to receive(:postgresql?).and_return(true)
          allow(model).to receive(:disable_statement_timeout)
        end
56

57
        it 'creates the index concurrently' do
58 59
          expect(model).to receive(:add_index)
            .with(:users, :foo, algorithm: :concurrently)
60 61 62

          model.add_concurrent_index(:users, :foo)
        end
63 64

        it 'creates unique index concurrently' do
65 66
          expect(model).to receive(:add_index)
            .with(:users, :foo, { algorithm: :concurrently, unique: true })
67 68 69

          model.add_concurrent_index(:users, :foo, unique: true)
        end
70 71 72 73 74 75
      end

      context 'using MySQL' do
        it 'creates a regular index' do
          expect(Gitlab::Database).to receive(:postgresql?).and_return(false)

76 77
          expect(model).to receive(:add_index)
            .with(:users, :foo, {})
78 79 80 81 82 83 84 85 86 87

          model.add_concurrent_index(:users, :foo)
        end
      end
    end

    context 'inside a transaction' do
      it 'raises RuntimeError' do
        expect(model).to receive(:transaction_open?).and_return(true)

88 89
        expect { model.add_concurrent_index(:users, :foo) }
          .to raise_error(RuntimeError)
90 91
      end
    end
92 93
  end

94 95 96 97 98 99 100 101
  describe '#remove_concurrent_index' do
    context 'outside a transaction' do
      before do
        allow(model).to receive(:transaction_open?).and_return(false)
      end

      context 'using PostgreSQL' do
        before do
102
          allow(model).to receive(:supports_drop_index_concurrently?).and_return(true)
103 104 105
          allow(model).to receive(:disable_statement_timeout)
        end

106
        it 'removes the index concurrently by column name' do
107 108
          expect(model).to receive(:remove_index)
            .with(:users, { algorithm: :concurrently, column: :foo })
109 110 111

          model.remove_concurrent_index(:users, :foo)
        end
112 113

        it 'removes the index concurrently by index name' do
114 115
          expect(model).to receive(:remove_index)
            .with(:users, { algorithm: :concurrently, name: "index_x_by_y" })
116 117 118

          model.remove_concurrent_index_by_name(:users, "index_x_by_y")
        end
119 120 121 122 123 124
      end

      context 'using MySQL' do
        it 'removes an index' do
          expect(Gitlab::Database).to receive(:postgresql?).and_return(false)

125 126
          expect(model).to receive(:remove_index)
            .with(:users, { column: :foo })
127 128 129 130 131 132 133 134 135 136

          model.remove_concurrent_index(:users, :foo)
        end
      end
    end

    context 'inside a transaction' do
      it 'raises RuntimeError' do
        expect(model).to receive(:transaction_open?).and_return(true)

137 138
        expect { model.remove_concurrent_index(:users, :foo) }
          .to raise_error(RuntimeError)
139 140 141 142
      end
    end
  end

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
  describe '#add_concurrent_foreign_key' do
    context 'inside a transaction' do
      it 'raises an error' do
        expect(model).to receive(:transaction_open?).and_return(true)

        expect do
          model.add_concurrent_foreign_key(:projects, :users, column: :user_id)
        end.to raise_error(RuntimeError)
      end
    end

    context 'outside a transaction' do
      before do
        allow(model).to receive(:transaction_open?).and_return(false)
      end

      context 'using MySQL' do
        it 'creates a regular foreign key' do
          allow(Gitlab::Database).to receive(:mysql?).and_return(true)

163 164
          expect(model).to receive(:add_foreign_key)
            .with(:projects, :users, column: :user_id, on_delete: :cascade)
165 166 167 168 169 170 171 172 173 174

          model.add_concurrent_foreign_key(:projects, :users, column: :user_id)
        end
      end

      context 'using PostgreSQL' do
        before do
          allow(Gitlab::Database).to receive(:mysql?).and_return(false)
        end

175
        it 'creates a concurrent foreign key and validates it' do
176 177 178 179 180 181
          expect(model).to receive(:disable_statement_timeout)
          expect(model).to receive(:execute).ordered.with(/NOT VALID/)
          expect(model).to receive(:execute).ordered.with(/VALIDATE CONSTRAINT/)

          model.add_concurrent_foreign_key(:projects, :users, column: :user_id)
        end
182 183 184 185 186 187 188 189 190 191

        it 'appends a valid ON DELETE statement' do
          expect(model).to receive(:disable_statement_timeout)
          expect(model).to receive(:execute).with(/ON DELETE SET NULL/)
          expect(model).to receive(:execute).ordered.with(/VALIDATE CONSTRAINT/)

          model.add_concurrent_foreign_key(:projects, :users,
                                           column: :user_id,
                                           on_delete: :nullify)
        end
192 193 194 195
      end
    end
  end

196 197 198 199 200 201 202 203 204 205
  describe '#concurrent_foreign_key_name' do
    it 'returns the name for a foreign key' do
      name = model.concurrent_foreign_key_name(:this_is_a_very_long_table_name,
                                               :with_a_very_long_column_name)

      expect(name).to be_an_instance_of(String)
      expect(name.length).to eq(13)
    end
  end

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
  describe '#disable_statement_timeout' do
    context 'using PostgreSQL' do
      it 'disables statement timeouts' do
        expect(Gitlab::Database).to receive(:postgresql?).and_return(true)

        expect(model).to receive(:execute).with('SET statement_timeout TO 0')

        model.disable_statement_timeout
      end
    end

    context 'using MySQL' do
      it 'does nothing' do
        expect(Gitlab::Database).to receive(:postgresql?).and_return(false)

        expect(model).not_to receive(:execute)

        model.disable_statement_timeout
      end
    end
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
  end

  describe '#true_value' do
    context 'using PostgreSQL' do
      before do
        expect(Gitlab::Database).to receive(:postgresql?).and_return(true)
      end

      it 'returns the appropriate value' do
        expect(model.true_value).to eq("'t'")
      end
    end

    context 'using MySQL' do
      before do
        expect(Gitlab::Database).to receive(:postgresql?).and_return(false)
      end

      it 'returns the appropriate value' do
        expect(model.true_value).to eq(1)
      end
    end
  end

  describe '#false_value' do
    context 'using PostgreSQL' do
      before do
        expect(Gitlab::Database).to receive(:postgresql?).and_return(true)
      end

      it 'returns the appropriate value' do
        expect(model.false_value).to eq("'f'")
      end
    end

    context 'using MySQL' do
      before do
        expect(Gitlab::Database).to receive(:postgresql?).and_return(false)
      end

      it 'returns the appropriate value' do
        expect(model.false_value).to eq(0)
      end
    end
270 271 272
  end

  describe '#update_column_in_batches' do
273 274 275
    context 'when running outside of a transaction' do
      before do
        expect(model).to receive(:transaction_open?).and_return(false)
276

277
        create_list(:project, 5)
278
      end
279

280 281
      it 'updates all the rows in a table' do
        model.update_column_in_batches(:projects, :import_error, 'foo')
282

283 284
        expect(Project.where(import_error: 'foo').count).to eq(5)
      end
285

286 287 288 289 290
      it 'updates boolean values correctly' do
        model.update_column_in_batches(:projects, :archived, true)

        expect(Project.where(archived: true).count).to eq(5)
      end
291

292 293 294
      context 'when a block is supplied' do
        it 'yields an Arel table and query object to the supplied block' do
          first_id = Project.first.id
295

296 297 298 299 300
          model.update_column_in_batches(:projects, :archived, true) do |t, query|
            query.where(t[:id].eq(first_id))
          end

          expect(Project.where(archived: true).count).to eq(1)
301
        end
302
      end
303

304 305 306 307 308 309
      context 'when the value is Arel.sql (Arel::Nodes::SqlLiteral)' do
        it 'updates the value as a SQL expression' do
          model.update_column_in_batches(:projects, :star_count, Arel.sql('1+1'))

          expect(Project.sum(:star_count)).to eq(2 * Project.count)
        end
310 311
      end
    end
312

313 314 315
    context 'when running inside the transaction' do
      it 'raises RuntimeError' do
        expect(model).to receive(:transaction_open?).and_return(true)
316

317 318 319
        expect do
          model.update_column_in_batches(:projects, :star_count, Arel.sql('1+1'))
        end.to raise_error(RuntimeError)
320 321
      end
    end
322 323 324 325
  end

  describe '#add_column_with_default' do
    context 'outside of a transaction' do
326 327
      context 'when a column limit is not set' do
        before do
328 329 330
          expect(model).to receive(:transaction_open?)
            .and_return(false)
            .at_least(:once)
331

332
          expect(model).to receive(:transaction).and_yield
333

334 335
          expect(model).to receive(:add_column)
            .with(:projects, :foo, :integer, default: nil)
336

337 338
          expect(model).to receive(:change_column_default)
            .with(:projects, :foo, 10)
339
        end
340

341
        it 'adds the column while allowing NULL values' do
342 343
          expect(model).to receive(:update_column_in_batches)
            .with(:projects, :foo, 10)
344

345
          expect(model).not_to receive(:change_column_null)
346

347 348 349 350
          model.add_column_with_default(:projects, :foo, :integer,
                                        default: 10,
                                        allow_null: true)
        end
351

352
        it 'adds the column while not allowing NULL values' do
353 354
          expect(model).to receive(:update_column_in_batches)
            .with(:projects, :foo, 10)
355

356 357
          expect(model).to receive(:change_column_null)
            .with(:projects, :foo, false)
358

359 360
          model.add_column_with_default(:projects, :foo, :integer, default: 10)
        end
361

362
        it 'removes the added column whenever updating the rows fails' do
363 364 365
          expect(model).to receive(:update_column_in_batches)
            .with(:projects, :foo, 10)
            .and_raise(RuntimeError)
366

367 368
          expect(model).to receive(:remove_column)
            .with(:projects, :foo)
369

370 371 372 373
          expect do
            model.add_column_with_default(:projects, :foo, :integer, default: 10)
          end.to raise_error(RuntimeError)
        end
374

375
        it 'removes the added column whenever changing a column NULL constraint fails' do
376 377 378
          expect(model).to receive(:change_column_null)
            .with(:projects, :foo, false)
            .and_raise(RuntimeError)
379

380 381
          expect(model).to receive(:remove_column)
            .with(:projects, :foo)
382

383 384 385 386 387 388 389 390 391 392
          expect do
            model.add_column_with_default(:projects, :foo, :integer, default: 10)
          end.to raise_error(RuntimeError)
        end
      end

      context 'when a column limit is set' do
        it 'adds the column with a limit' do
          allow(model).to receive(:transaction_open?).and_return(false)
          allow(model).to receive(:transaction).and_yield
Drew Blessing's avatar
fix  
Drew Blessing committed
393 394 395
          allow(model).to receive(:update_column_in_batches).with(:projects, :foo, 10)
          allow(model).to receive(:change_column_null).with(:projects, :foo, false)
          allow(model).to receive(:change_column_default).with(:projects, :foo, 10)
396

397 398
          expect(model).to receive(:add_column)
            .with(:projects, :foo, :integer, default: nil, limit: 8)
399 400 401

          model.add_column_with_default(:projects, :foo, :integer, default: 10, limit: 8)
        end
402
      end
403 404 405 406 407 408
    end

    context 'inside a transaction' do
      it 'raises RuntimeError' do
        expect(model).to receive(:transaction_open?).and_return(true)

409
        expect do
410
          model.add_column_with_default(:projects, :foo, :integer, default: 10)
411
        end.to raise_error(RuntimeError)
412 413 414
      end
    end
  end
415 416 417 418 419 420

  describe '#rename_column_concurrently' do
    context 'in a transaction' do
      it 'raises RuntimeError' do
        allow(model).to receive(:transaction_open?).and_return(true)

421 422
        expect { model.rename_column_concurrently(:users, :old, :new) }
          .to raise_error(RuntimeError)
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
      end
    end

    context 'outside a transaction' do
      let(:old_column) do
        double(:column,
               type: :integer,
               limit: 8,
               default: 0,
               null: false,
               precision: 5,
               scale: 1)
      end

      let(:trigger_name) { model.rename_trigger_name(:users, :old, :new) }

      before do
        allow(model).to receive(:transaction_open?).and_return(false)
        allow(model).to receive(:column_for).and_return(old_column)

        # Since MySQL and PostgreSQL use different quoting styles we'll just
        # stub the methods used for this to make testing easier.
        allow(model).to receive(:quote_column_name) { |name| name.to_s }
        allow(model).to receive(:quote_table_name) { |name| name.to_s }
      end

      context 'using MySQL' do
        it 'renames a column concurrently' do
          allow(Gitlab::Database).to receive(:postgresql?).and_return(false)

453 454
          expect(model).to receive(:check_trigger_permissions!).with(:users)

455 456
          expect(model).to receive(:install_rename_triggers_for_mysql)
            .with(trigger_name, 'users', 'old', 'new')
457

458 459
          expect(model).to receive(:add_column)
            .with(:users, :new, :integer,
460 461 462 463
                 limit: old_column.limit,
                 precision: old_column.precision,
                 scale: old_column.scale)

464 465
          expect(model).to receive(:change_column_default)
            .with(:users, :new, old_column.default)
466

467 468
          expect(model).to receive(:update_column_in_batches)

469 470
          expect(model).to receive(:change_column_null).with(:users, :new, false)

471 472 473 474 475 476 477 478 479 480 481
          expect(model).to receive(:copy_indexes).with(:users, :old, :new)
          expect(model).to receive(:copy_foreign_keys).with(:users, :old, :new)

          model.rename_column_concurrently(:users, :old, :new)
        end
      end

      context 'using PostgreSQL' do
        it 'renames a column concurrently' do
          allow(Gitlab::Database).to receive(:postgresql?).and_return(true)

482 483
          expect(model).to receive(:check_trigger_permissions!).with(:users)

484 485
          expect(model).to receive(:install_rename_triggers_for_postgresql)
            .with(trigger_name, 'users', 'old', 'new')
486

487 488
          expect(model).to receive(:add_column)
            .with(:users, :new, :integer,
489 490 491 492
                 limit: old_column.limit,
                 precision: old_column.precision,
                 scale: old_column.scale)

493 494
          expect(model).to receive(:change_column_default)
            .with(:users, :new, old_column.default)
495

496 497
          expect(model).to receive(:update_column_in_batches)

498 499
          expect(model).to receive(:change_column_null).with(:users, :new, false)

500 501 502 503 504 505 506 507 508 509 510 511 512
          expect(model).to receive(:copy_indexes).with(:users, :old, :new)
          expect(model).to receive(:copy_foreign_keys).with(:users, :old, :new)

          model.rename_column_concurrently(:users, :old, :new)
        end
      end
    end
  end

  describe '#cleanup_concurrent_column_rename' do
    it 'cleans up the renaming procedure for PostgreSQL' do
      allow(Gitlab::Database).to receive(:postgresql?).and_return(true)

513 514
      expect(model).to receive(:check_trigger_permissions!).with(:users)

515 516
      expect(model).to receive(:remove_rename_triggers_for_postgresql)
        .with(:users, /trigger_.{12}/)
517 518 519 520 521 522 523 524 525

      expect(model).to receive(:remove_column).with(:users, :old)

      model.cleanup_concurrent_column_rename(:users, :old, :new)
    end

    it 'cleans up the renaming procedure for MySQL' do
      allow(Gitlab::Database).to receive(:postgresql?).and_return(false)

526 527
      expect(model).to receive(:check_trigger_permissions!).with(:users)

528 529
      expect(model).to receive(:remove_rename_triggers_for_mysql)
        .with(/trigger_.{12}/)
530 531 532 533 534 535 536 537 538

      expect(model).to receive(:remove_column).with(:users, :old)

      model.cleanup_concurrent_column_rename(:users, :old, :new)
    end
  end

  describe '#change_column_type_concurrently' do
    it 'changes the column type' do
539 540
      expect(model).to receive(:rename_column_concurrently)
        .with('users', 'username', 'username_for_type_change', type: :text)
541 542 543 544 545 546 547

      model.change_column_type_concurrently('users', 'username', :text)
    end
  end

  describe '#cleanup_concurrent_column_type_change' do
    it 'cleans up the type changing procedure' do
548 549
      expect(model).to receive(:cleanup_concurrent_column_rename)
        .with('users', 'username', 'username_for_type_change')
550

551 552
      expect(model).to receive(:rename_column)
        .with('users', 'username_for_type_change', 'username')
553 554 555 556 557 558 559

      model.cleanup_concurrent_column_type_change('users', 'username')
    end
  end

  describe '#install_rename_triggers_for_postgresql' do
    it 'installs the triggers for PostgreSQL' do
560 561
      expect(model).to receive(:execute)
        .with(/CREATE OR REPLACE FUNCTION foo()/m)
562

563 564
      expect(model).to receive(:execute)
        .with(/CREATE TRIGGER foo/m)
565 566 567 568 569 570 571

      model.install_rename_triggers_for_postgresql('foo', :users, :old, :new)
    end
  end

  describe '#install_rename_triggers_for_mysql' do
    it 'installs the triggers for MySQL' do
572 573
      expect(model).to receive(:execute)
        .with(/CREATE TRIGGER foo_insert.+ON users/m)
574

575 576
      expect(model).to receive(:execute)
        .with(/CREATE TRIGGER foo_update.+ON users/m)
577 578 579 580 581 582 583

      model.install_rename_triggers_for_mysql('foo', :users, :old, :new)
    end
  end

  describe '#remove_rename_triggers_for_postgresql' do
    it 'removes the function and trigger' do
584 585
      expect(model).to receive(:execute).with('DROP TRIGGER IF EXISTS foo ON bar')
      expect(model).to receive(:execute).with('DROP FUNCTION IF EXISTS foo()')
586 587 588 589 590 591 592

      model.remove_rename_triggers_for_postgresql('bar', 'foo')
    end
  end

  describe '#remove_rename_triggers_for_mysql' do
    it 'removes the triggers' do
593 594
      expect(model).to receive(:execute).with('DROP TRIGGER IF EXISTS foo_insert')
      expect(model).to receive(:execute).with('DROP TRIGGER IF EXISTS foo_update')
595 596 597 598 599 600 601

      model.remove_rename_triggers_for_mysql('foo')
    end
  end

  describe '#rename_trigger_name' do
    it 'returns a String' do
602 603
      expect(model.rename_trigger_name(:users, :foo, :bar))
        .to match(/trigger_.{12}/)
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
    end
  end

  describe '#indexes_for' do
    it 'returns the indexes for a column' do
      idx1 = double(:idx, columns: %w(project_id))
      idx2 = double(:idx, columns: %w(user_id))

      allow(model).to receive(:indexes).with('table').and_return([idx1, idx2])

      expect(model.indexes_for('table', :user_id)).to eq([idx2])
    end
  end

  describe '#foreign_keys_for' do
    it 'returns the foreign keys for a column' do
      fk1 = double(:fk, column: 'project_id')
      fk2 = double(:fk, column: 'user_id')

      allow(model).to receive(:foreign_keys).with('table').and_return([fk1, fk2])

      expect(model.foreign_keys_for('table', :user_id)).to eq([fk2])
    end
  end

  describe '#copy_indexes' do
    context 'using a regular index using a single column' do
      it 'copies the index' do
        index = double(:index,
                       columns: %w(project_id),
                       name: 'index_on_issues_project_id',
                       using: nil,
                       where: nil,
                       opclasses: {},
                       unique: false,
                       lengths: [],
                       orders: [])

642 643
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
644

645 646
        expect(model).to receive(:add_concurrent_index)
          .with(:issues,
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
               %w(gl_project_id),
               unique: false,
               name: 'index_on_issues_gl_project_id',
               length: [],
               order: [])

        model.copy_indexes(:issues, :project_id, :gl_project_id)
      end
    end

    context 'using a regular index with multiple columns' do
      it 'copies the index' do
        index = double(:index,
                       columns: %w(project_id foobar),
                       name: 'index_on_issues_project_id_foobar',
                       using: nil,
                       where: nil,
                       opclasses: {},
                       unique: false,
                       lengths: [],
                       orders: [])

669 670
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
671

672 673
        expect(model).to receive(:add_concurrent_index)
          .with(:issues,
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
               %w(gl_project_id foobar),
               unique: false,
               name: 'index_on_issues_gl_project_id_foobar',
               length: [],
               order: [])

        model.copy_indexes(:issues, :project_id, :gl_project_id)
      end
    end

    context 'using an index with a WHERE clause' do
      it 'copies the index' do
        index = double(:index,
                       columns: %w(project_id),
                       name: 'index_on_issues_project_id',
                       using: nil,
                       where: 'foo',
                       opclasses: {},
                       unique: false,
                       lengths: [],
                       orders: [])

696 697
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
698

699 700
        expect(model).to receive(:add_concurrent_index)
          .with(:issues,
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
               %w(gl_project_id),
               unique: false,
               name: 'index_on_issues_gl_project_id',
               length: [],
               order: [],
               where: 'foo')

        model.copy_indexes(:issues, :project_id, :gl_project_id)
      end
    end

    context 'using an index with a USING clause' do
      it 'copies the index' do
        index = double(:index,
                       columns: %w(project_id),
                       name: 'index_on_issues_project_id',
                       where: nil,
                       using: 'foo',
                       opclasses: {},
                       unique: false,
                       lengths: [],
                       orders: [])

724 725
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
726

727 728
        expect(model).to receive(:add_concurrent_index)
          .with(:issues,
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
               %w(gl_project_id),
               unique: false,
               name: 'index_on_issues_gl_project_id',
               length: [],
               order: [],
               using: 'foo')

        model.copy_indexes(:issues, :project_id, :gl_project_id)
      end
    end

    context 'using an index with custom operator classes' do
      it 'copies the index' do
        index = double(:index,
                       columns: %w(project_id),
                       name: 'index_on_issues_project_id',
                       using: nil,
                       where: nil,
                       opclasses: { 'project_id' => 'bar' },
                       unique: false,
                       lengths: [],
                       orders: [])

752 753
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
754

755 756
        expect(model).to receive(:add_concurrent_index)
          .with(:issues,
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
               %w(gl_project_id),
               unique: false,
               name: 'index_on_issues_gl_project_id',
               length: [],
               order: [],
               opclasses: { 'gl_project_id' => 'bar' })

        model.copy_indexes(:issues, :project_id, :gl_project_id)
      end
    end

    describe 'using an index of which the name does not contain the source column' do
      it 'raises RuntimeError' do
        index = double(:index,
                       columns: %w(project_id),
                       name: 'index_foobar_index',
                       using: nil,
                       where: nil,
                       opclasses: {},
                       unique: false,
                       lengths: [],
                       orders: [])

780 781
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
782

783 784
        expect { model.copy_indexes(:issues, :project_id, :gl_project_id) }
          .to raise_error(RuntimeError)
785 786 787 788 789 790 791 792 793 794 795
      end
    end
  end

  describe '#copy_foreign_keys' do
    it 'copies foreign keys from one column to another' do
      fk = double(:fk,
                  from_table: 'issues',
                  to_table: 'projects',
                  on_delete: :cascade)

796 797
      allow(model).to receive(:foreign_keys_for).with(:issues, :project_id)
        .and_return([fk])
798

799 800
      expect(model).to receive(:add_concurrent_foreign_key)
        .with('issues', 'projects', column: :gl_project_id, on_delete: :cascade)
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816

      model.copy_foreign_keys(:issues, :project_id, :gl_project_id)
    end
  end

  describe '#column_for' do
    it 'returns a column object for an existing column' do
      column = model.column_for(:users, :id)

      expect(column.name).to eq('id')
    end

    it 'returns nil when a column does not exist' do
      expect(model.column_for(:users, :kittens)).to be_nil
    end
  end
817 818 819 820 821 822 823 824

  describe '#replace_sql' do
    context 'using postgres' do
      before do
        allow(Gitlab::Database).to receive(:mysql?).and_return(false)
      end

      it 'builds the sql with correct functions' do
825 826
        expect(model.replace_sql(Arel::Table.new(:users)[:first_name], "Alice", "Eve").to_s)
          .to include('regexp_replace')
827 828 829 830 831 832 833 834 835
      end
    end

    context 'using mysql' do
      before do
        allow(Gitlab::Database).to receive(:mysql?).and_return(true)
      end

      it 'builds the sql with the correct functions' do
836 837
        expect(model.replace_sql(Arel::Table.new(:users)[:first_name], "Alice", "Eve").to_s)
          .to include('locate', 'insert')
838 839 840 841 842 843 844
      end
    end

    describe 'results' do
      let!(:user) { create(:user, name: 'Kathy Alice Aliceson') }

      it 'replaces the correct part of the string' do
845
        allow(model).to receive(:transaction_open?).and_return(false)
846
        query = model.replace_sql(Arel::Table.new(:users)[:name], 'Alice', 'Eve')
847 848 849

        model.update_column_in_batches(:users, :name, query)

850 851 852 853
        expect(user.reload.name).to eq('Kathy Eve Aliceson')
      end
    end
  end
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885

  describe 'sidekiq migration helpers', :sidekiq, :redis do
    let(:worker) do
      Class.new do
        include Sidekiq::Worker
        sidekiq_options queue: 'test'
      end
    end

    describe '#sidekiq_queue_length' do
      context 'when queue is empty' do
        it 'returns zero' do
          Sidekiq::Testing.disable! do
            expect(model.sidekiq_queue_length('test')).to eq 0
          end
        end
      end

      context 'when queue contains jobs' do
        it 'returns correct size of the queue' do
          Sidekiq::Testing.disable! do
            worker.perform_async('Something', [1])
            worker.perform_async('Something', [2])

            expect(model.sidekiq_queue_length('test')).to eq 2
          end
        end
      end
    end

    describe '#migrate_sidekiq_queue' do
      it 'migrates jobs from one sidekiq queue to another' do
886 887 888
        Sidekiq::Testing.disable! do
          worker.perform_async('Something', [1])
          worker.perform_async('Something', [2])
889

890 891
          expect(model.sidekiq_queue_length('test')).to eq 2
          expect(model.sidekiq_queue_length('new_test')).to eq 0
892

893
          model.sidekiq_queue_migrate('test', to: 'new_test')
894

895 896 897
          expect(model.sidekiq_queue_length('test')).to eq 0
          expect(model.sidekiq_queue_length('new_test')).to eq 2
        end
898 899 900
      end
    end
  end
901 902 903 904

  describe '#check_trigger_permissions!' do
    it 'does nothing when the user has the correct permissions' do
      expect { model.check_trigger_permissions!('users') }
905
        .not_to raise_error
906 907 908 909 910 911 912 913 914 915 916
    end

    it 'raises RuntimeError when the user does not have the correct permissions' do
      allow(Gitlab::Database::Grant).to receive(:create_and_execute_trigger?)
        .with('kittens')
        .and_return(false)

      expect { model.check_trigger_permissions!('kittens') }
        .to raise_error(RuntimeError, /Your database user is not allowed/)
    end
  end
917

918
  describe '#bulk_queue_background_migration_jobs_by_range', :sidekiq do
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
    context 'when the model has an ID column' do
      let!(:id1) { create(:user).id }
      let!(:id2) { create(:user).id }
      let!(:id3) { create(:user).id }

      before do
        User.class_eval do
          include EachBatch
        end
      end

      context 'with enough rows to bulk queue jobs more than once' do
        before do
          stub_const('Gitlab::Database::MigrationHelpers::BACKGROUND_MIGRATION_JOB_BUFFER_SIZE', 1)
        end

        it 'queues jobs correctly' do
          Sidekiq::Testing.fake! do
937
            model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2)
938 939 940 941 942 943 944

            expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id2]])
            expect(BackgroundMigrationWorker.jobs[1]['args']).to eq(['FooJob', [id3, id3]])
          end
        end

        it 'queues jobs in groups of buffer size 1' do
945 946
          expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id1, id2]]])
          expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id3, id3]]])
947

948
          model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2)
949 950 951 952 953 954
        end
      end

      context 'with not enough rows to bulk queue jobs more than once' do
        it 'queues jobs correctly' do
          Sidekiq::Testing.fake! do
955
            model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2)
956 957 958 959 960 961 962

            expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id2]])
            expect(BackgroundMigrationWorker.jobs[1]['args']).to eq(['FooJob', [id3, id3]])
          end
        end

        it 'queues jobs in bulk all at once (big buffer size)' do
963 964
          expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id1, id2]],
                                                                                  ['FooJob', [id3, id3]]])
965

966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
          model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2)
        end
      end

      context 'without specifying batch_size' do
        it 'queues jobs correctly' do
          Sidekiq::Testing.fake! do
            model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob')

            expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id3]])
          end
        end
      end
    end

    context "when the model doesn't have an ID column" do
      it 'raises error (for now)' do
        expect do
          model.bulk_queue_background_migration_jobs_by_range(ProjectAuthorization, 'FooJob')
        end.to raise_error(StandardError, /does not have an ID/)
      end
    end
  end

  describe '#queue_background_migration_jobs_by_range_at_intervals', :sidekiq do
    context 'when the model has an ID column' do
      let!(:id1) { create(:user).id }
      let!(:id2) { create(:user).id }
      let!(:id3) { create(:user).id }

      around do |example|
        Timecop.freeze { example.run }
      end

      before do
        User.class_eval do
          include EachBatch
        end
      end

      context 'with batch_size option' do
        it 'queues jobs correctly' do
          Sidekiq::Testing.fake! do
            model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.seconds, batch_size: 2)

            expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id2]])
            expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(10.seconds.from_now.to_f)
            expect(BackgroundMigrationWorker.jobs[1]['args']).to eq(['FooJob', [id3, id3]])
            expect(BackgroundMigrationWorker.jobs[1]['at']).to eq(20.seconds.from_now.to_f)
          end
        end
      end

      context 'without batch_size option' do
        it 'queues jobs correctly' do
          Sidekiq::Testing.fake! do
            model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.seconds)

            expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id3]])
            expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(10.seconds.from_now.to_f)
          end
1027 1028 1029 1030 1031 1032 1033
        end
      end
    end

    context "when the model doesn't have an ID column" do
      it 'raises error (for now)' do
        expect do
1034
          model.queue_background_migration_jobs_by_range_at_intervals(ProjectAuthorization, 'FooJob', 10.seconds)
1035 1036 1037 1038
        end.to raise_error(StandardError, /does not have an ID/)
      end
    end
  end
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127

  describe '#change_column_type_using_background_migration' do
    let!(:issue) { create(:issue) }

    let(:issue_model) do
      Class.new(ActiveRecord::Base) do
        self.table_name = 'issues'
        include EachBatch
      end
    end

    it 'changes the type of a column using a background migration' do
      expect(model)
        .to receive(:add_column)
        .with('issues', 'closed_at_for_type_change', :datetime_with_timezone)

      expect(model)
        .to receive(:install_rename_triggers)
        .with('issues', :closed_at, 'closed_at_for_type_change')

      expect(BackgroundMigrationWorker)
        .to receive(:perform_in)
        .ordered
        .with(
          10.minutes,
          'CopyColumn',
          ['issues', :closed_at, 'closed_at_for_type_change', issue.id, issue.id]
        )

      expect(BackgroundMigrationWorker)
        .to receive(:perform_in)
        .ordered
        .with(
          1.hour + 10.minutes,
          'CleanupConcurrentTypeChange',
          ['issues', :closed_at, 'closed_at_for_type_change']
        )

      expect(Gitlab::BackgroundMigration)
        .to receive(:steal)
        .ordered
        .with('CopyColumn')

      expect(Gitlab::BackgroundMigration)
        .to receive(:steal)
        .ordered
        .with('CleanupConcurrentTypeChange')

      model.change_column_type_using_background_migration(
        issue_model.all,
        :closed_at,
        :datetime_with_timezone
      )
    end
  end

  describe '#perform_background_migration_inline?' do
    it 'returns true in a test environment' do
      allow(Rails.env)
        .to receive(:test?)
        .and_return(true)

      expect(model.perform_background_migration_inline?).to eq(true)
    end

    it 'returns true in a development environment' do
      allow(Rails.env)
        .to receive(:test?)
        .and_return(false)

      allow(Rails.env)
        .to receive(:development?)
        .and_return(true)

      expect(model.perform_background_migration_inline?).to eq(true)
    end

    it 'returns false in a production environment' do
      allow(Rails.env)
        .to receive(:test?)
        .and_return(false)

      allow(Rails.env)
        .to receive(:development?)
        .and_return(false)

      expect(model.perform_background_migration_inline?).to eq(false)
    end
  end
1128
end