count_spec.rb 2.59 KB
Newer Older
1
2
3
4
5
require 'spec_helper'

describe Gitlab::Database::Count do
  before do
    create_list(:project, 3)
6
    create(:identity)
7
8
  end

9
  let(:models) { [Project, Identity] }
10

11
12
13
14
15
  describe '.approximate_counts' do
    context 'with MySQL' do
      context 'when reltuples have not been updated' do
        it 'counts all models the normal way' do
          expect(Gitlab::Database).to receive(:postgresql?).and_return(false)
16

17
18
          expect(Project).to receive(:count).and_call_original
          expect(Identity).to receive(:count).and_call_original
19

20
21
          expect(described_class.approximate_counts(models)).to eq({ Project => 3, Identity => 1 })
        end
22
23
24
      end
    end

25
26
27
28
    context 'with PostgreSQL', :postgresql do
      describe 'when reltuples have not been updated' do
        it 'counts all models the normal way' do
          expect(described_class).to receive(:reltuples_from_recently_updated).with(%w(projects identities)).and_return({})
29

30
31
32
33
          expect(Project).to receive(:count).and_call_original
          expect(Identity).to receive(:count).and_call_original
          expect(described_class.approximate_counts(models)).to eq({ Project => 3, Identity => 1 })
        end
34
35
      end

36
37
      describe 'no permission' do
        it 'falls back to standard query' do
38
          allow(ActiveRecord::Base).to receive(:transaction).and_raise(PG::InsufficientPrivilege)
39

40
41
42
43
          expect(Project).to receive(:count).and_call_original
          expect(Identity).to receive(:count).and_call_original
          expect(described_class.approximate_counts(models)).to eq({ Project => 3, Identity => 1 })
        end
44
45
      end

46
47
48
49
50
51
52
53
      describe 'when some reltuples have been updated' do
        it 'counts projects in the fast way' do
          expect(described_class).to receive(:reltuples_from_recently_updated).with(%w(projects identities)).and_return({ 'projects' => 3 })

          expect(Project).not_to receive(:count).and_call_original
          expect(Identity).to receive(:count).and_call_original
          expect(described_class.approximate_counts(models)).to eq({ Project => 3, Identity => 1 })
        end
54
55
      end

56
57
58
59
60
61
62
63
64
      describe 'when all reltuples have been updated' do
        before do
          ActiveRecord::Base.connection.execute('ANALYZE projects')
          ActiveRecord::Base.connection.execute('ANALYZE identities')
        end

        it 'counts models with the standard way' do
          expect(Project).not_to receive(:count)
          expect(Identity).not_to receive(:count)
65

66
67
          expect(described_class.approximate_counts(models)).to eq({ Project => 3, Identity => 1 })
        end
68
69
70
71
      end
    end
  end
end