Module: PgRls::Tenant
- Defined in:
- lib/pg_rls/tenant.rb
Overview
Tenant Controller
Class Method Summary collapse
- .fetch ⇒ Object
- .fetch! ⇒ Object
- .reset_rls! ⇒ Object
- .set_rls!(tenant_id) ⇒ Object
- .switch(resource) ⇒ Object
- .switch!(resource) ⇒ Object
- .with_tenant!(resource) ⇒ Object
Class Method Details
.fetch ⇒ Object
32 33 34 35 36 |
# File 'lib/pg_rls/tenant.rb', line 32 def fetch fetch! rescue ActiveRecord::StatementInvalid, ActiveRecord::RecordNotFound nil end |
.fetch! ⇒ Object
38 39 40 41 42 43 44 |
# File 'lib/pg_rls/tenant.rb', line 38 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
46 47 48 49 50 51 52 53 54 |
# File 'lib/pg_rls/tenant.rb', line 46 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 |
.set_rls!(tenant_id) ⇒ Object
56 57 58 59 60 61 62 63 |
# File 'lib/pg_rls/tenant.rb', line 56 def set_rls!(tenant_id) PgRls.execute_rls_in_shards do |connection_class| connection_class.transaction do connection_class.connection.execute(format('SET rls.tenant_id = %s', connection_class.connection.quote(tenant_id))) end end 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 Rails.logger.info('connection was not made') raise PgRls::Errors::TenantNotFound end |
.with_tenant!(resource) ⇒ Object
22 23 24 25 26 27 28 29 30 |
# File 'lib/pg_rls/tenant.rb', line 22 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 |