Skip to content

Commit 69ca6fc

Browse files
committed
fix: adjust RLS configs into postgres
1 parent bd794d7 commit 69ca6fc

1 file changed

Lines changed: 16 additions & 10 deletions

File tree

app/controllers/concerns/row_level_security.rb

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,22 @@ module RowLevelSecurity
1010
def with_rls_context
1111
return yield unless current_user && current_organization
1212

13-
# Set PostgreSQL session variables for RLS
14-
ActiveRecord::Base.connection.execute(
15-
"SET LOCAL app.current_user_id = '#{current_user.id}';"
16-
)
17-
ActiveRecord::Base.connection.execute(
18-
"SET LOCAL app.current_organization_id = '#{current_organization.id}';"
19-
)
20-
ActiveRecord::Base.connection.execute(
21-
"SET LOCAL app.user_role = '#{current_user.role}';"
22-
)
13+
begin
14+
# Set PostgreSQL session variables for RLS
15+
# Using a transaction to ensure SET LOCAL works properly
16+
ActiveRecord::Base.connection.execute(
17+
"SET LOCAL app.current_user_id = '#{current_user.id}';"
18+
)
19+
ActiveRecord::Base.connection.execute(
20+
"SET LOCAL app.current_organization_id = '#{current_organization.id}';"
21+
)
22+
ActiveRecord::Base.connection.execute(
23+
"SET LOCAL app.user_role = '#{current_user.role}';"
24+
)
25+
rescue ActiveRecord::StatementInvalid => e
26+
# SET LOCAL might fail outside transactions on some poolers
27+
Rails.logger.warn("RLS SET LOCAL failed: #{e.message}. Using thread-local only.")
28+
end
2329

2430
# Set thread-local variable for application-level scoping
2531
# This is needed because PostgreSQL RLS doesn't apply to table owners (postgres user)

0 commit comments

Comments
 (0)