.
This commit is contained in:
@@ -102,4 +102,62 @@ BEGIN
|
||||
RAISE NOTICE 'DM channel created with ID: %', new_channel_id;
|
||||
RETURN new_channel_id;
|
||||
END;
|
||||
$$;
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION create_group_channel(
|
||||
p_creator_id UUID, -- The user initiating the group creation (will be owner)
|
||||
p_recipient_user_ids UUID[], -- Array of all user IDs for the group (must include creator)
|
||||
p_group_channel_type INT2 -- The channel type identifier for groups (e.g., 1)
|
||||
)
|
||||
RETURNS UUID
|
||||
LANGUAGE plpgsql
|
||||
AS
|
||||
$$
|
||||
DECLARE
|
||||
new_channel_id UUID;
|
||||
existing_channel_id UUID;
|
||||
final_channel_name VARCHAR;
|
||||
unique_sorted_recipient_ids UUID[];
|
||||
num_recipients INT;
|
||||
uid UUID;
|
||||
-- Threshold for detailed name vs. summary name
|
||||
MAX_MEMBERS_FOR_DETAILED_NAME CONSTANT INT := 3;
|
||||
BEGIN
|
||||
-- Validate and process recipient IDs
|
||||
IF p_recipient_user_ids IS NULL OR array_length(p_recipient_user_ids, 1) IS NULL THEN
|
||||
RAISE EXCEPTION 'Recipient user IDs array must be provided and not empty.';
|
||||
END IF;
|
||||
|
||||
-- Get unique, sorted recipient IDs for consistent checking and to avoid duplicates.
|
||||
SELECT array_agg(DISTINCT u ORDER BY u) INTO unique_sorted_recipient_ids FROM unnest(p_recipient_user_ids) u;
|
||||
num_recipients := array_length(unique_sorted_recipient_ids, 1);
|
||||
|
||||
-- Validate minimum number of recipients for a group
|
||||
IF num_recipients < 1 THEN -- Groups typically have at least 2 members
|
||||
RAISE EXCEPTION 'Group channels (type %) must have at least 2 recipients. Found %.', p_group_channel_type, num_recipients;
|
||||
END IF;
|
||||
|
||||
-- Create new group channel
|
||||
INSERT INTO "channel" ("name", "type", "position", "owner_id", "server_id", "parent")
|
||||
VALUES ('Group',
|
||||
p_group_channel_type,
|
||||
0, -- Default position
|
||||
p_creator_id,
|
||||
NULL, -- Not a server channel
|
||||
NULL -- Not a nested server channel
|
||||
)
|
||||
RETURNING id INTO new_channel_id;
|
||||
|
||||
-- Add all recipients to the channel_recipient table
|
||||
INSERT INTO "channel_recipient" ("channel_id", "user_id")
|
||||
VALUES (new_channel_id, p_creator_id);
|
||||
|
||||
INSERT INTO "channel_recipient" ("channel_id", "user_id")
|
||||
SELECT new_channel_id, r_id
|
||||
FROM unnest(unique_sorted_recipient_ids) AS r_id;
|
||||
|
||||
RAISE NOTICE 'Group channel (type %) named "%" created with ID: % by owner % for recipients: %',
|
||||
p_group_channel_type, final_channel_name, new_channel_id, p_creator_id, unique_sorted_recipient_ids;
|
||||
RETURN new_channel_id;
|
||||
END;
|
||||
$$;
|
||||
|
||||
Reference in New Issue
Block a user