Skip to content

Instantly share code, notes, and snippets.

View ericgross's full-sized avatar

Eric Gross ericgross

  • Whidbey Island, WA
View GitHub Profile
@ericgross
ericgross / 20230517213020_create_rls_functions.rb
Created May 20, 2023 23:07
Enabling multi-tenant Solidus using RLS on Postgres
class CreateRlsFunctions < ActiveRecord::Migration[7.0]
def self.up
connection.execute <<-SQL
-- This function returns the id of the current user or NULL if not set
-- this varaible is set on a connection basis before every action
-- If it is not set, it will return NULL and all non-public tables will seem empty.
CREATE FUNCTION current_user_id() RETURNS BIGINT AS $$
SELECT NULLIF(current_setting('rls.user_id', TRUE), '')::BIGINT;
$$ LANGUAGE sql SECURITY DEFINER STABLE COST 10;
-- This function returns the id of the current tenant or NULL if not set