···11+-- Function to create homepage infrastructure for new identities
22+-- Replicates the logic from createIdentity TypeScript function
33+-- Returns the permission token ID to be used as home_page
44+CREATE OR REPLACE FUNCTION create_identity_homepage()
55+RETURNS uuid AS $$
66+DECLARE
77+ new_entity_set_id uuid;
88+ new_entity_id uuid;
99+ new_permission_token_id uuid;
1010+BEGIN
1111+ -- Create a new entity set
1212+ INSERT INTO entity_sets DEFAULT VALUES
1313+ RETURNING id INTO new_entity_set_id;
1414+1515+ -- Create a root entity and add it to that entity set
1616+ new_entity_id := gen_random_uuid();
1717+ INSERT INTO entities (id, set)
1818+ VALUES (new_entity_id, new_entity_set_id);
1919+2020+ -- Create a new permission token
2121+ INSERT INTO permission_tokens (root_entity)
2222+ VALUES (new_entity_id)
2323+ RETURNING id INTO new_permission_token_id;
2424+2525+ -- Give the token full permissions on that entity set
2626+ INSERT INTO permission_token_rights (token, entity_set, read, write, create_token, change_entity_set)
2727+ VALUES (new_permission_token_id, new_entity_set_id, true, true, true, true);
2828+2929+ RETURN new_permission_token_id;
3030+END;
3131+$$ LANGUAGE plpgsql;
3232+3333+-- Set the function as the default value for home_page column
3434+ALTER TABLE identities ALTER COLUMN home_page SET DEFAULT create_identity_homepage();