Module: PgRls::Tenant

Defined in:
lib/pg_rls/tenant.rb

Overview

Tenant Controller

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.tenantObject (readonly)

Returns the value of attribute tenant.



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

def tenant
  @tenant
end

Class Method Details

.fetchObject



36
37
38
39
40
# File 'lib/pg_rls/tenant.rb', line 36

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

.reset_rls!Object



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/pg_rls/tenant.rb', line 51

def reset_rls!
  return if @tenant.blank?

  @tenant = nil
  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



9
10
11
12
13
14
15
16
17
# File 'lib/pg_rls/tenant.rb', line 9

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

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

.switch!(resource) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/pg_rls/tenant.rb', line 19

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

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

.tenant!Object Also known as: fetch!



42
43
44
45
46
47
48
# File 'lib/pg_rls/tenant.rb', line 42

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

.with_tenant!(resource) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/pg_rls/tenant.rb', line 28

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

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