summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/database/count_spec.rb
blob: 9d9caaabe16489ef847428516c44dc9e3e3c67b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
require 'spec_helper'

describe Gitlab::Database::Count do
  before do
    create_list(:project, 3)
  end

  describe '.execute_estimate_if_updated_recently', :postgresql do
    context 'when reltuples have not been updated' do
      before do
        expect(described_class).to receive(:reltuples_updated_recently?).and_return(false)
      end

      it 'returns nil' do
        expect(described_class.execute_estimate_if_updated_recently(Project)).to be nil
      end
    end

    context 'when reltuples have been updated' do
      before do
        ActiveRecord::Base.connection.execute('ANALYZE projects')
      end

      it 'calls postgresql_estimate_query' do
        expect(described_class).to receive(:postgresql_estimate_query).with(Project).and_call_original
        expect(described_class.execute_estimate_if_updated_recently(Project)).to eq(3)
      end
    end
  end

  describe '.approximate_count' do
    context 'when reltuples have not been updated' do
      it 'counts all projects the normal way' do
        allow(described_class).to receive(:reltuples_updated_recently?).and_return(false)

        expect(Project).to receive(:count).and_call_original
        expect(described_class.approximate_count(Project)).to eq(3)
      end
    end

    context 'no permission' do
      it 'falls back to standard query' do
        allow(described_class).to receive(:reltuples_updated_recently?).and_raise(PG::InsufficientPrivilege)

        expect(Project).to receive(:count).and_call_original
        expect(described_class.approximate_count(Project)).to eq(3)
      end
    end

    describe 'when reltuples have been updated', :postgresql do
      before do
        ActiveRecord::Base.connection.execute('ANALYZE projects')
      end

      it 'counts all projects in the fast way' do
        expect(described_class).to receive(:postgresql_estimate_query).with(Project).and_call_original

        expect(described_class.approximate_count(Project)).to eq(3)
      end
    end
  end
end