migration_helpers_spec.rb 45.1 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
      end

G
Gabriel Mazetto 已提交
51
      context 'using PostgreSQL', :postgresql do
52 53
        before do
          allow(Gitlab::Database).to receive(:postgresql?).and_return(true)
54
          allow(model).to receive(:disable_statement_timeout).and_call_original
55
        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 76 77

        it 'does nothing if the index exists already' do
          expect(model).to receive(:index_exists?)
            .with(:users, :foo, { algorithm: :concurrently, unique: true }).and_return(true)
          expect(model).not_to receive(:add_index)

          model.add_concurrent_index(:users, :foo, unique: true)
        end
78 79 80
      end

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

85
        it 'creates a regular index' do
86 87
          expect(model).to receive(:add_index)
            .with(:users, :foo, {})
88 89 90

          model.add_concurrent_index(:users, :foo)
        end
91 92 93 94 95 96 97 98

        it 'does nothing if the index exists already' do
          expect(model).to receive(:index_exists?)
            .with(:users, :foo, { unique: true }).and_return(true)
          expect(model).not_to receive(:add_index)

          model.add_concurrent_index(:users, :foo, unique: true)
        end
99 100 101 102 103 104 105
      end
    end

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

106 107
        expect { model.add_concurrent_index(:users, :foo) }
          .to raise_error(RuntimeError)
108 109
      end
    end
110 111
  end

112 113 114 115
  describe '#remove_concurrent_index' do
    context 'outside a transaction' do
      before do
        allow(model).to receive(:transaction_open?).and_return(false)
116
        allow(model).to receive(:index_exists?).and_return(true)
117
        allow(model).to receive(:disable_statement_timeout).and_call_original
118 119 120 121
      end

      context 'using PostgreSQL' do
        before do
122
          allow(model).to receive(:supports_drop_index_concurrently?).and_return(true)
123 124
        end

125 126 127 128 129 130 131
        describe 'by column name' do
          it 'removes the index concurrently' do
            expect(model).to receive(:remove_index)
              .with(:users, { algorithm: :concurrently, column: :foo })

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

133 134 135 136 137 138 139
          it 'does nothing if the index does not exist' do
            expect(model).to receive(:index_exists?)
              .with(:users, :foo, { algorithm: :concurrently, unique: true }).and_return(false)
            expect(model).not_to receive(:remove_index)

            model.remove_concurrent_index(:users, :foo, unique: true)
          end
140
        end
141

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        describe 'by index name' do
          before do
            allow(model).to receive(:index_exists_by_name?).with(:users, "index_x_by_y").and_return(true)
          end

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

            model.remove_concurrent_index_by_name(:users, "index_x_by_y")
          end

          it 'does nothing if the index does not exist' do
            expect(model).to receive(:index_exists_by_name?).with(:users, "index_x_by_y").and_return(false)
            expect(model).not_to receive(:remove_index)
157

158 159
            model.remove_concurrent_index_by_name(:users, "index_x_by_y")
          end
160
        end
161 162 163 164
      end

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

167 168
          expect(model).to receive(:remove_index)
            .with(:users, { column: :foo })
169 170 171 172 173 174 175 176 177 178

          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)

179 180
        expect { model.remove_concurrent_index(:users, :foo) }
          .to raise_error(RuntimeError)
181 182 183 184
      end
    end
  end

185
  describe '#add_concurrent_foreign_key' do
186 187 188 189
    before do
      allow(model).to receive(:foreign_key_exists?).and_return(false)
    end

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    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
206
        before do
207
          allow(Gitlab::Database).to receive(:mysql?).and_return(true)
208
        end
209

210
        it 'creates a regular foreign key' do
211 212
          expect(model).to receive(:add_foreign_key)
            .with(:projects, :users, column: :user_id, on_delete: :cascade)
213 214 215

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

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
        it 'allows the use of a custom key name' do
          expect(model).to receive(:add_foreign_key).with(
            :projects,
            :users,
            column: :user_id,
            on_delete: :cascade,
            name: :foo
          )

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

234 235 236 237 238 239
        it 'does not create a foreign key if it exists already' do
          expect(model).to receive(:foreign_key_exists?).with(:projects, :users, column: :user_id).and_return(true)
          expect(model).not_to receive(:add_foreign_key)

          model.add_concurrent_foreign_key(:projects, :users, column: :user_id)
        end
240 241 242 243
      end

      context 'using PostgreSQL' do
        before do
G
Gabriel Mazetto 已提交
244
          allow(Gitlab::Database).to receive(:postgresql?).and_return(true)
245 246 247
          allow(Gitlab::Database).to receive(:mysql?).and_return(false)
        end

248
        it 'creates a concurrent foreign key and validates it' do
249 250
          expect(model).to receive(:disable_statement_timeout).and_call_original
          expect(model).to receive(:execute).with(/statement_timeout/)
251 252
          expect(model).to receive(:execute).ordered.with(/NOT VALID/)
          expect(model).to receive(:execute).ordered.with(/VALIDATE CONSTRAINT/)
253
          expect(model).to receive(:execute).with(/RESET ALL/)
254 255 256

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

        it 'appends a valid ON DELETE statement' do
259 260
          expect(model).to receive(:disable_statement_timeout).and_call_original
          expect(model).to receive(:execute).with(/statement_timeout/)
261 262
          expect(model).to receive(:execute).with(/ON DELETE SET NULL/)
          expect(model).to receive(:execute).ordered.with(/VALIDATE CONSTRAINT/)
263
          expect(model).to receive(:execute).with(/RESET ALL/)
264 265 266 267 268

          model.add_concurrent_foreign_key(:projects, :users,
                                           column: :user_id,
                                           on_delete: :nullify)
        end
269 270 271 272 273 274 275 276

        it 'does not create a foreign key if it exists already' do
          expect(model).to receive(:foreign_key_exists?).with(:projects, :users, column: :user_id).and_return(true)
          expect(model).not_to receive(:execute).with(/ADD CONSTRAINT/)
          expect(model).to receive(:execute).with(/VALIDATE CONSTRAINT/)

          model.add_concurrent_foreign_key(:projects, :users, column: :user_id)
        end
277 278 279 280 281 282 283 284 285 286

        it 'allows the use of a custom key name' do
          expect(model).to receive(:disable_statement_timeout).and_call_original
          expect(model).to receive(:execute).with(/statement_timeout/)
          expect(model).to receive(:execute).ordered.with(/NOT VALID/)
          expect(model).to receive(:execute).ordered.with(/VALIDATE CONSTRAINT.+foo/)
          expect(model).to receive(:execute).with(/RESET ALL/)

          model.add_concurrent_foreign_key(:projects, :users, column: :user_id, name: :foo)
        end
287 288 289 290
      end
    end
  end

291 292 293 294 295 296 297 298 299 300
  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

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
  describe '#foreign_key_exists?' do
    before do
      key = ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(:projects, :users, { column: :non_standard_id })
      allow(model).to receive(:foreign_keys).with(:projects).and_return([key])
    end

    it 'finds existing foreign keys by column' do
      expect(model.foreign_key_exists?(:projects, :users, column: :non_standard_id)).to be_truthy
    end

    it 'finds existing foreign keys by target table only' do
      expect(model.foreign_key_exists?(:projects, :users)).to be_truthy
    end

    it 'compares by column name if given' do
      expect(model.foreign_key_exists?(:projects, :users, column: :user_id)).to be_falsey
    end

    it 'compares by target if no column given' do
      expect(model.foreign_key_exists?(:projects, :other_table)).to be_falsey
    end
  end

324 325
  describe '#disable_statement_timeout' do
    context 'using PostgreSQL' do
326 327
      it 'disables statement timeouts to current transaction only' do
        expect(Gitlab::Database).to receive(:postgresql?).and_return(true)
328

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

331 332
        model.disable_statement_timeout
      end
333

334 335 336 337 338
      # this specs runs without an enclosing transaction (:delete truncation method for db_cleaner)
      context 'with real environment', :postgresql, :delete do
        before do
          model.execute("SET statement_timeout TO '20000'")
        end
339

340 341 342
        after do
          model.execute('RESET ALL')
        end
343

344 345
        it 'defines statement to 0 only for current transaction' do
          expect(model.execute('SHOW statement_timeout').first['statement_timeout']).to eq('20s')
346

347 348 349
          model.connection.transaction do
            model.disable_statement_timeout
            expect(model.execute('SHOW statement_timeout').first['statement_timeout']).to eq('0')
350
          end
351 352

          expect(model.execute('SHOW statement_timeout').first['statement_timeout']).to eq('20s')
353 354 355
        end
      end

356 357
      context 'when passing a blocks' do
        it 'disables statement timeouts on session level and executes the block' do
358 359 360 361
          expect(Gitlab::Database).to receive(:postgresql?).and_return(true)
          expect(model).to receive(:execute).with('SET statement_timeout TO 0')
          expect(model).to receive(:execute).with('RESET ALL')

362
          expect { |block| model.disable_statement_timeout(&block) }.to yield_control
363 364 365 366 367 368 369 370 371 372 373 374
        end

        # this specs runs without an enclosing transaction (:delete truncation method for db_cleaner)
        context 'with real environment', :postgresql, :delete do
          before do
            model.execute("SET statement_timeout TO '20000'")
          end

          after do
            model.execute('RESET ALL')
          end

375
          it 'defines statement to 0 for any code run inside the block' do
376 377
            expect(model.execute('SHOW statement_timeout').first['statement_timeout']).to eq('20s')

378
            model.disable_statement_timeout do
379 380 381 382 383 384 385 386
              model.connection.transaction do
                expect(model.execute('SHOW statement_timeout').first['statement_timeout']).to eq('0')
              end

              expect(model.execute('SHOW statement_timeout').first['statement_timeout']).to eq('0')
            end
          end
        end
387 388 389 390
      end
    end

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

394
        expect(model).not_to receive(:execute)
395

396
        model.disable_statement_timeout
397
      end
398

399 400
      context 'when passing a blocks' do
        it 'executes the block of code' do
401 402 403 404
          expect(Gitlab::Database).to receive(:postgresql?).and_return(false)

          expect(model).not_to receive(:execute)

405
          expect { |block| model.disable_statement_timeout(&block) }.to yield_control
406
        end
407 408
      end
    end
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
  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
453 454 455
  end

  describe '#update_column_in_batches' do
456 457 458
    context 'when running outside of a transaction' do
      before do
        expect(model).to receive(:transaction_open?).and_return(false)
459

460
        create_list(:project, 5)
461
      end
462

463 464
      it 'updates all the rows in a table' do
        model.update_column_in_batches(:projects, :import_error, 'foo')
465

466 467
        expect(Project.where(import_error: 'foo').count).to eq(5)
      end
468

469 470 471 472 473
      it 'updates boolean values correctly' do
        model.update_column_in_batches(:projects, :archived, true)

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

475 476 477
      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
478

479 480 481 482 483
          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)
484
        end
485
      end
486

487 488 489 490 491 492
      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
493 494
      end
    end
495

496 497 498
    context 'when running inside the transaction' do
      it 'raises RuntimeError' do
        expect(model).to receive(:transaction_open?).and_return(true)
499

500 501 502
        expect do
          model.update_column_in_batches(:projects, :star_count, Arel.sql('1+1'))
        end.to raise_error(RuntimeError)
503 504
      end
    end
505 506 507 508
  end

  describe '#add_column_with_default' do
    context 'outside of a transaction' do
509 510
      context 'when a column limit is not set' do
        before do
511 512 513
          expect(model).to receive(:transaction_open?)
            .and_return(false)
            .at_least(:once)
514

515
          expect(model).to receive(:transaction).and_yield
516

517 518
          expect(model).to receive(:add_column)
            .with(:projects, :foo, :integer, default: nil)
519

520 521
          expect(model).to receive(:change_column_default)
            .with(:projects, :foo, 10)
522
        end
523

524
        it 'adds the column while allowing NULL values' do
525 526
          expect(model).to receive(:update_column_in_batches)
            .with(:projects, :foo, 10)
527

528
          expect(model).not_to receive(:change_column_null)
529

530 531 532 533
          model.add_column_with_default(:projects, :foo, :integer,
                                        default: 10,
                                        allow_null: true)
        end
534

535
        it 'adds the column while not allowing NULL values' do
536 537
          expect(model).to receive(:update_column_in_batches)
            .with(:projects, :foo, 10)
538

539 540
          expect(model).to receive(:change_column_null)
            .with(:projects, :foo, false)
541

542 543
          model.add_column_with_default(:projects, :foo, :integer, default: 10)
        end
544

545
        it 'removes the added column whenever updating the rows fails' do
546 547 548
          expect(model).to receive(:update_column_in_batches)
            .with(:projects, :foo, 10)
            .and_raise(RuntimeError)
549

550 551
          expect(model).to receive(:remove_column)
            .with(:projects, :foo)
552

553 554 555 556
          expect do
            model.add_column_with_default(:projects, :foo, :integer, default: 10)
          end.to raise_error(RuntimeError)
        end
557

558
        it 'removes the added column whenever changing a column NULL constraint fails' do
559 560 561
          expect(model).to receive(:change_column_null)
            .with(:projects, :foo, false)
            .and_raise(RuntimeError)
562

563 564
          expect(model).to receive(:remove_column)
            .with(:projects, :foo)
565

566 567 568 569 570 571 572 573 574 575
          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
D
fix  
Drew Blessing 已提交
576 577 578
          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)
579

580 581
          expect(model).to receive(:add_column)
            .with(:projects, :foo, :integer, default: nil, limit: 8)
582 583 584

          model.add_column_with_default(:projects, :foo, :integer, default: 10, limit: 8)
        end
585
      end
586 587 588 589 590 591
    end

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

592
        expect do
593
          model.add_column_with_default(:projects, :foo, :integer, default: 10)
594
        end.to raise_error(RuntimeError)
595 596 597
      end
    end
  end
598 599 600 601 602 603

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

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

636 637
          expect(model).to receive(:check_trigger_permissions!).with(:users)

638 639
          expect(model).to receive(:install_rename_triggers_for_mysql)
            .with(trigger_name, 'users', 'old', 'new')
640

641 642
          expect(model).to receive(:add_column)
            .with(:users, :new, :integer,
643 644 645 646
                 limit: old_column.limit,
                 precision: old_column.precision,
                 scale: old_column.scale)

647 648
          expect(model).to receive(:change_column_default)
            .with(:users, :new, old_column.default)
649

650 651
          expect(model).to receive(:update_column_in_batches)

652 653
          expect(model).to receive(:change_column_null).with(:users, :new, false)

654 655 656 657 658 659 660 661 662 663 664
          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)

665 666
          expect(model).to receive(:check_trigger_permissions!).with(:users)

667 668
          expect(model).to receive(:install_rename_triggers_for_postgresql)
            .with(trigger_name, 'users', 'old', 'new')
669

670 671
          expect(model).to receive(:add_column)
            .with(:users, :new, :integer,
672 673 674 675
                 limit: old_column.limit,
                 precision: old_column.precision,
                 scale: old_column.scale)

676 677
          expect(model).to receive(:change_column_default)
            .with(:users, :new, old_column.default)
678

679 680
          expect(model).to receive(:update_column_in_batches)

681 682
          expect(model).to receive(:change_column_null).with(:users, :new, false)

683 684 685 686 687 688 689 690 691 692 693 694 695
          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)

696 697
      expect(model).to receive(:check_trigger_permissions!).with(:users)

698 699
      expect(model).to receive(:remove_rename_triggers_for_postgresql)
        .with(:users, /trigger_.{12}/)
700 701 702 703 704 705 706 707 708

      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)

709 710
      expect(model).to receive(:check_trigger_permissions!).with(:users)

711 712
      expect(model).to receive(:remove_rename_triggers_for_mysql)
        .with(/trigger_.{12}/)
713 714 715 716 717 718 719 720 721

      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
722 723
      expect(model).to receive(:rename_column_concurrently)
        .with('users', 'username', 'username_for_type_change', type: :text)
724 725 726 727 728 729 730

      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
731 732
      expect(model).to receive(:cleanup_concurrent_column_rename)
        .with('users', 'username', 'username_for_type_change')
733

734 735
      expect(model).to receive(:rename_column)
        .with('users', 'username_for_type_change', 'username')
736 737 738 739 740 741 742

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

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

746 747
      expect(model).to receive(:execute)
        .with(/CREATE TRIGGER foo/m)
748 749 750 751 752 753 754

      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
755 756
      expect(model).to receive(:execute)
        .with(/CREATE TRIGGER foo_insert.+ON users/m)
757

758 759
      expect(model).to receive(:execute)
        .with(/CREATE TRIGGER foo_update.+ON users/m)
760 761 762 763 764 765 766

      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
767 768
      expect(model).to receive(:execute).with('DROP TRIGGER IF EXISTS foo ON bar')
      expect(model).to receive(:execute).with('DROP FUNCTION IF EXISTS foo()')
769 770 771 772 773 774 775

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

  describe '#remove_rename_triggers_for_mysql' do
    it 'removes the triggers' do
776 777
      expect(model).to receive(:execute).with('DROP TRIGGER IF EXISTS foo_insert')
      expect(model).to receive(:execute).with('DROP TRIGGER IF EXISTS foo_update')
778 779 780 781 782 783 784

      model.remove_rename_triggers_for_mysql('foo')
    end
  end

  describe '#rename_trigger_name' do
    it 'returns a String' do
785 786
      expect(model.rename_trigger_name(:users, :foo, :bar))
        .to match(/trigger_.{12}/)
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
    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: [])

825 826
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
827

828 829
        expect(model).to receive(:add_concurrent_index)
          .with(:issues,
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
               %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: [])

852 853
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
854

855 856
        expect(model).to receive(:add_concurrent_index)
          .with(:issues,
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
               %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: [])

879 880
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
881

882 883
        expect(model).to receive(:add_concurrent_index)
          .with(:issues,
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
               %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: [])

907 908
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
909

910 911
        expect(model).to receive(:add_concurrent_index)
          .with(:issues,
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
               %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: [])

935 936
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
937

938 939
        expect(model).to receive(:add_concurrent_index)
          .with(:issues,
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
               %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: [])

963 964
        allow(model).to receive(:indexes_for).with(:issues, 'project_id')
          .and_return([index])
965

966 967
        expect { model.copy_indexes(:issues, :project_id, :gl_project_id) }
          .to raise_error(RuntimeError)
968 969 970 971 972 973 974 975 976 977 978
      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)

979 980
      allow(model).to receive(:foreign_keys_for).with(:issues, :project_id)
        .and_return([fk])
981

982 983
      expect(model).to receive(:add_concurrent_foreign_key)
        .with('issues', 'projects', column: :gl_project_id, on_delete: :cascade)
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999

      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
1000 1001 1002 1003 1004 1005 1006 1007

  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
1008 1009
        expect(model.replace_sql(Arel::Table.new(:users)[:first_name], "Alice", "Eve").to_s)
          .to include('regexp_replace')
1010 1011 1012 1013 1014 1015 1016 1017 1018
      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
1019 1020
        expect(model.replace_sql(Arel::Table.new(:users)[:first_name], "Alice", "Eve").to_s)
          .to include('locate', 'insert')
1021 1022 1023 1024 1025 1026 1027
      end
    end

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

      it 'replaces the correct part of the string' do
1028
        allow(model).to receive(:transaction_open?).and_return(false)
1029
        query = model.replace_sql(Arel::Table.new(:users)[:name], 'Alice', 'Eve')
1030 1031 1032

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

1033 1034 1035 1036
        expect(user.reload.name).to eq('Kathy Eve Aliceson')
      end
    end
  end
1037 1038 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

  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
1069 1070 1071
        Sidekiq::Testing.disable! do
          worker.perform_async('Something', [1])
          worker.perform_async('Something', [2])
1072

1073 1074
          expect(model.sidekiq_queue_length('test')).to eq 2
          expect(model.sidekiq_queue_length('new_test')).to eq 0
1075

1076
          model.sidekiq_queue_migrate('test', to: 'new_test')
1077

1078 1079 1080
          expect(model.sidekiq_queue_length('test')).to eq 0
          expect(model.sidekiq_queue_length('new_test')).to eq 2
        end
1081 1082 1083
      end
    end
  end
1084 1085 1086 1087

  describe '#check_trigger_permissions!' do
    it 'does nothing when the user has the correct permissions' do
      expect { model.check_trigger_permissions!('users') }
1088
        .not_to raise_error
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
    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
1100

M
Michael Kozono 已提交
1101
  describe '#bulk_queue_background_migration_jobs_by_range', :sidekiq do
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
    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
M
Michael Kozono 已提交
1120
            model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2)
1121 1122 1123 1124 1125 1126 1127

            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
D
Douwe Maan 已提交
1128 1129
          expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id1, id2]]])
          expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id3, id3]]])
1130

M
Michael Kozono 已提交
1131
          model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2)
1132 1133 1134 1135 1136 1137
        end
      end

      context 'with not enough rows to bulk queue jobs more than once' do
        it 'queues jobs correctly' do
          Sidekiq::Testing.fake! do
M
Michael Kozono 已提交
1138
            model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2)
1139 1140 1141 1142 1143 1144 1145

            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
D
Douwe Maan 已提交
1146 1147
          expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id1, id2]],
                                                                                  ['FooJob', [id3, id3]]])
1148

M
Michael Kozono 已提交
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
          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
1192
            model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes, batch_size: 2)
M
Michael Kozono 已提交
1193 1194

            expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id2]])
1195
            expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(10.minutes.from_now.to_f)
M
Michael Kozono 已提交
1196
            expect(BackgroundMigrationWorker.jobs[1]['args']).to eq(['FooJob', [id3, id3]])
1197
            expect(BackgroundMigrationWorker.jobs[1]['at']).to eq(20.minutes.from_now.to_f)
M
Michael Kozono 已提交
1198 1199 1200 1201 1202 1203 1204
          end
        end
      end

      context 'without batch_size option' do
        it 'queues jobs correctly' do
          Sidekiq::Testing.fake! do
1205
            model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes)
M
Michael Kozono 已提交
1206 1207

            expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id3]])
1208
            expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(10.minutes.from_now.to_f)
M
Michael Kozono 已提交
1209
          end
1210 1211 1212 1213 1214 1215 1216
        end
      end
    end

    context "when the model doesn't have an ID column" do
      it 'raises error (for now)' do
        expect do
M
Michael Kozono 已提交
1217
          model.queue_background_migration_jobs_by_range_at_intervals(ProjectAuthorization, 'FooJob', 10.seconds)
1218 1219 1220 1221
        end.to raise_error(StandardError, /does not have an ID/)
      end
    end
  end
1222 1223

  describe '#change_column_type_using_background_migration' do
1224
    let!(:issue) { create(:issue, :closed, closed_at: Time.zone.now) }
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277

    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

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
  describe '#rename_column_using_background_migration' do
    let!(:issue) { create(:issue, :closed, closed_at: Time.zone.now) }

    it 'renames a column using a background migration' do
      expect(model)
        .to receive(:add_column)
        .with(
          'issues',
          :closed_at_timestamp,
          :datetime_with_timezone,
          limit: anything,
          precision: anything,
          scale: anything
        )

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

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

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

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

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

      model.rename_column_using_background_migration(
        'issues',
        :closed_at,
        :closed_at_timestamp
      )
    end
  end

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
  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
1366 1367

  describe '#index_exists_by_name?' do
1368
    it 'returns true if an index exists' do
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
      expect(model.index_exists_by_name?(:projects, 'index_projects_on_path'))
        .to be_truthy
    end

    it 'returns false if the index does not exist' do
      expect(model.index_exists_by_name?(:projects, 'this_does_not_exist'))
        .to be_falsy
    end

    context 'when an index with a function exists', :postgresql do
      before do
        ActiveRecord::Base.connection.execute(
          'CREATE INDEX test_index ON projects (LOWER(path));'
        )
      end

      after do
        'DROP INDEX IF EXISTS test_index;'
      end

      it 'returns true if an index exists' do
        expect(model.index_exists_by_name?(:projects, 'test_index'))
          .to be_truthy
      end
    end
  end
1395
end