3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# File 'lib/activerecord-tenant-level-security/schema_statements.rb', line 3
def create_policy(table_name, partition_key: TenantLevelSecurity::DEFAULT_PARTITION_KEY)
quoted_table_name = quote_table_name(table_name)
quoted_partition_key = quote_column_name(partition_key)
execute <<~SQL
ALTER TABLE #{quoted_table_name} ENABLE ROW LEVEL SECURITY;
ALTER TABLE #{quoted_table_name} FORCE ROW LEVEL SECURITY;
SQL
tenant_id_data_type = get_tenant_id_data_type(table_name, partition_key)
execute <<~SQL
CREATE POLICY tenant_policy ON #{quoted_table_name}
AS PERMISSIVE
FOR ALL
TO PUBLIC
USING (#{quoted_partition_key} = NULLIF(current_setting('tenant_level_security.tenant_id'), '')::#{tenant_id_data_type})
WITH CHECK (#{quoted_partition_key} = NULLIF(current_setting('tenant_level_security.tenant_id'), '')::#{tenant_id_data_type})
SQL
end
|