File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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)
You can’t perform that action at this time.
0 commit comments