Module: TenantLevelSecurity::SchemaStatements

Defined in:
lib/activerecord-tenant-level-security/schema_statements.rb

Instance Method Summary collapse

Instance Method Details

#create_policy(table_name, partition_key: TenantLevelSecurity::DEFAULT_PARTITION_KEY) ⇒ Object



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

#remove_policy(table_name, *args) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/activerecord-tenant-level-security/schema_statements.rb', line 21

def remove_policy(table_name, *args)
  quoted_table_name = quote_table_name(table_name)
  execute <<~SQL
    ALTER TABLE #{quoted_table_name} NO FORCE ROW LEVEL SECURITY;
    ALTER TABLE #{quoted_table_name} DISABLE ROW LEVEL SECURITY;
  SQL
  execute <<~SQL
    DROP POLICY tenant_policy ON #{quoted_table_name}
  SQL
end