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



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

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

.fetch!Object



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

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

.find_eachObject



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

def find_each(&)
  PgRls.main_model.find_each do |tenant|
    with_tenant!(tenant, &)
  end
end

.find_main_modelObject



56
57
58
59
60
61
62
63
# File 'lib/pg_rls/tenant.rb', line 56

def find_main_model
  PgRls.main_model.ignored_columns = []
  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



65
66
67
68
# File 'lib/pg_rls/tenant.rb', line 65

def reset_rls!
  @tenant = nil
  PgRls.connection_class.connection.execute('RESET rls.tenant_id')
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

.with_tenant!(resource, &block) ⇒ Object



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

def with_tenant!(resource, &block)
  tenant = switch_tenant!(resource)

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