Skip to content

Instantly share code, notes, and snippets.

@jon-whit
Created March 14, 2024 15:40
Show Gist options
  • Save jon-whit/95896469eb0af81731111cac04635471 to your computer and use it in GitHub Desktop.
Save jon-whit/95896469eb0af81731111cac04635471 to your computer and use it in GitHub Desktop.
fga index create \
--name group_member_user_index \
--user-type=user \
--relation=member \
--object-type=group \
--out views.sql
Output:
--- views.sql
-- group#member --> group#member (e.g. nested groups)
CREATE MATERIALIZED VIEW group_to_group AS
WITH MUTUALLY RECURSIVE
group_to_group(object_type TEXT, object_id TEXT, relation TEXT, subject_object_type TEXT, subject_object_id TEXT, subject_relation TEXT) AS (
SELECT DISTINCT object_type, object_id, relation, subject_object_type, subject_object_id, subject_relation FROM relationship_tuples WHERE object_type='group' AND relation='member' AND subject_object_type='group' AND subject_relation='member'
UNION ALL
SELECT DISTINCT a2.object_type, a2.object_id, a2.relation, a1.subject_object_type, a1.subject_object_id, a1.subject_relation FROM group_to_group a1 JOIN group_to_group a2 ON a1.object_id = a2.subject_object_id
)
SELECT object_type, object_id, relation, subject_object_type, subject_object_id, subject_relation FROM group_to_group;
-- composite materialized view
CREATE MATERIALIZED VIEW group_member_user_index AS (
SELECT object_id, subject_object_id FROM relationship_tuples
WHERE
object_type='group' AND relation='member' AND subject_object_type='user' AND subject_relation=''
UNION
SELECT gg.object_id, rt.subject_object_id FROM relationship_tuples as rt
LEFT JOIN group_to_group as gg ON gg.object_type=rt.object_type AND gg.relation=rt.relation AND gg.subject_object_id=rt.object_id WHERE rt.subject_object_type='user' AND rt.subject_relation=''
);
model
schema 1.1
type user
type group
relations
@index(user_type="user")
define member: [user, group#member]
@jon-whit
Copy link
Author

This is a sample of what an FGA index creation command may look like. This is not yet official or implemented in any ways. It is a concept.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment