summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/database/postgres_foreign_key_spec.rb
blob: b0e08ca1e67e0758ce74719e65afbaaf950fb50a (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
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::Database::PostgresForeignKey, type: :model do
  # PostgresForeignKey does not `behaves_like 'a postgres model'` because it does not correspond 1-1 with a single entry
  # in pg_class

  before do
    ActiveRecord::Base.connection.execute(<<~SQL)
    CREATE TABLE public.referenced_table (
      id bigserial primary key not null
    );

    CREATE TABLE public.other_referenced_table (
      id bigserial primary key not null
    );

    CREATE TABLE public.constrained_table (
      id bigserial primary key not null,
      referenced_table_id bigint not null,
      other_referenced_table_id bigint not null,
      CONSTRAINT fk_constrained_to_referenced FOREIGN KEY(referenced_table_id) REFERENCES referenced_table(id),
      CONSTRAINT fk_constrained_to_other_referenced FOREIGN KEY(other_referenced_table_id)
         REFERENCES other_referenced_table(id)
    );
    SQL
  end

  describe '#by_referenced_table_identifier' do
    it 'throws an error when the identifier name is not fully qualified' do
      expect { described_class.by_referenced_table_identifier('referenced_table') }.to raise_error(ArgumentError, /not fully qualified/)
    end

    it 'finds the foreign keys for the referenced table' do
      expected = described_class.find_by!(name: 'fk_constrained_to_referenced')

      expect(described_class.by_referenced_table_identifier('public.referenced_table')).to contain_exactly(expected)
    end
  end

  describe '#by_constrained_table_identifier' do
    it 'throws an error when the identifier name is not fully qualified' do
      expect { described_class.by_constrained_table_identifier('constrained_table') }.to raise_error(ArgumentError, /not fully qualified/)
    end

    it 'finds the foreign keys for the constrained table' do
      expected = described_class.where(name: %w[fk_constrained_to_referenced fk_constrained_to_other_referenced]).to_a

      expect(described_class.by_constrained_table_identifier('public.constrained_table')).to match_array(expected)
    end
  end
end