Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/rls_rails/helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,16 @@ def self.set_user user
end

def self.current_tenant_id
return if disabled?

execute_sql(<<-SQL.strip_heredoc).values[0][0].presence
SELECT current_setting('rls.tenant_id', TRUE);
SQL
end

def self.current_user_id
return if disabled?

execute_sql(<<-SQL.strip_heredoc).values[0][0].presence
SELECT current_setting('rls.user_id', TRUE);
SQL
Expand Down
14 changes: 14 additions & 0 deletions spec/helpers_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,25 @@

describe '.set_tenant_for_block' do
it 'works for threads' do
client = User.create name: 'A'
RLS.enable!
RLS.set_tenant(client)
expect(RLS.enabled?).to be_truthy
expect(RLS.current_tenant_id).to eq(client.id.to_s)

Thread.new do
RLS.disable!

expect(RLS.disabled?).to be_truthy
expect(RLS.current_tenant).to be_nil
end.run

expect(RLS.enabled?).to be_truthy
expect(RLS.current_tenant_id).to eq(client.id.to_s)

RLS.disable_for_block do
expect(RLS.enabled?).to be_falsey
expect(RLS.current_tenant_id).to be_nil
end
end

Expand Down Expand Up @@ -96,12 +103,19 @@
end

context 'currently enabled' do
let!(:client1) {User.create name: 'User 1'}

before { RLS.enable! }

it 'clears not query cache' do
User.count
expect{ RLS.disable! }.to change { ActiveRecord::Base.connection.query_cache.size }.to 0
end

it 'unsets current_tenant_id' do
RLS.set_tenant(client1)
expect { RLS.disable! }.to change { RLS.current_tenant_id }.from(client1.id.to_s).to(nil)
end
end
end

Expand Down