···1+-- Function to create homepage infrastructure for new identities
2+-- Replicates the logic from createIdentity TypeScript function
3+-- Returns the permission token ID to be used as home_page
4+CREATE OR REPLACE FUNCTION create_identity_homepage()
5+RETURNS uuid AS $$
6+DECLARE
7+ new_entity_set_id uuid;
8+ new_entity_id uuid;
9+ new_permission_token_id uuid;
10+BEGIN
11+ -- Create a new entity set
12+ INSERT INTO entity_sets DEFAULT VALUES
13+ RETURNING id INTO new_entity_set_id;
14+15+ -- Create a root entity and add it to that entity set
16+ new_entity_id := gen_random_uuid();
17+ INSERT INTO entities (id, set)
18+ VALUES (new_entity_id, new_entity_set_id);
19+20+ -- Create a new permission token
21+ INSERT INTO permission_tokens (root_entity)
22+ VALUES (new_entity_id)
23+ RETURNING id INTO new_permission_token_id;
24+25+ -- Give the token full permissions on that entity set
26+ INSERT INTO permission_token_rights (token, entity_set, read, write, create_token, change_entity_set)
27+ VALUES (new_permission_token_id, new_entity_set_id, true, true, true, true);
28+29+ RETURN new_permission_token_id;
30+END;
31+$$ LANGUAGE plpgsql;
32+33+-- Set the function as the default value for home_page column
34+ALTER TABLE identities ALTER COLUMN home_page SET DEFAULT create_identity_homepage();