Add current_organization_id database function

The RLS policies will toggle depending on the current organization id defined for the transaction. The policy will default to no isolation when the current organization id is null.

The current_organization_id function will look something close to:

-- Create a function to extract organization_id from application_name
CREATE OR REPLACE FUNCTION current_organization_id()
RETURNS INTEGER AS $$
BEGIN
  RETURN COALESCE(
    (regexp_match(current_setting('application_name'), 'org=(\d+):'))[1]::integer,
    0
  );
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Or via transaction setting
      CREATE OR REPLACE FUNCTION current_organization_id()
      RETURNS bigint AS $$
      BEGIN
        -- Return NULL if the setting doesn't exist or is empty
        RETURN nullif(current_setting('current_organization_id', TRUE), '')::bigint;
      END;
      $$ LANGUAGE plpgsql STABLE;
Edited by Alex Pooley