Module: PgRls::Tenant

Defined in:
lib/pg_rls/tenant.rb

Overview

Tenant Controller

Class Method Summary collapse

Class Method Details

.fetchObject



33
34
35
36
37
# File 'lib/pg_rls/tenant.rb', line 33

def fetch
  fetch!
rescue ActiveRecord::StatementInvalid, ActiveRecord::RecordNotFound
  nil
end

.fetch!Object



39
40
41
42
43
44
45
# File 'lib/pg_rls/tenant.rb', line 39

def fetch!
  PgRls.main_model.find_by!(
    tenant_id: PgRls.connection_class.connection.execute(
      "SELECT current_setting('rls.tenant_id')"
    ).getvalue(0, 0)
  )
end

.reset_rls!Object



47
48
49
50
51
52
53
54
55
# File 'lib/pg_rls/tenant.rb', line 47

def reset_rls!
  PgRls.execute_rls_in_shards do |connection_class|
    connection_class.transaction do
      connection_class.connection.execute('RESET rls.tenant_id')
    end
  end

  nil
end

.switch(resource) ⇒ Object



7
8
9
10
11
# File 'lib/pg_rls/tenant.rb', line 7

def switch(resource)
  switch!(resource)
rescue PgRls::Errors::TenantNotFound
  nil
end

.switch!(resource) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/pg_rls/tenant.rb', line 13

def switch!(resource)
  tenant = switch_tenant!(resource)

  "RLS changed to '#{tenant.id}'"
rescue StandardError => e
  Rails.logger.info('connection was not made')
  raise PgRls::Errors::TenantNotFound
end

.with_tenant!(resource) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/pg_rls/tenant.rb', line 23

def with_tenant!(resource)
  PgRls.main_model.connection_pool.with_connection do
    tenant = switch_tenant!(resource)

    yield(tenant).presence if block_given?
  ensure
    reset_rls! unless PgRls.test_inline_tenant == true
  end
end