I need help to complete the following requirements:
- [x]
Profile
table with columnsid
,username
, ... - [x]
Comment
table with columnsid
,content
, ... - [x]
CommentReference
table with columnsid
,profile_id
,comment_id
, ...
When a new comment is created, before inserting:
- [ ] Check if
NEW.content
have references to usernames, like@someusername
- [ ] Check if each reference exists in the profile table
- [ ] For references that exist, insert into
CommentReferences
the profile and comment
For now, what I have is the following code:
PS: the following code has errors, I need help to fix it. I'm using postgres version 12.
CREATE FUNCTION create_comment_usernames_references()
RETURNS trigger AS $$
DECLARE usernames TEXT[];
DECLARE username TEXT;
DECLARE profile_id TEXT; -- profile_id is of type uuid, is it correct to use TEXT here?
BEGIN
-- verify if there are usernames in the comment.content with the username regex
SELECT DISTINCT(
regexp_matches(
NEW.content,
'@(([a-z0-9]*((?<=[a-z0-9])[-|_|\.](?=[a-z0-9]))[a-z0-9]*)*|[a-z0-9]*)',
'g'
)
)[1]
INTO usernames;
FOREACH username IN ARRAY usernames LOOP
SELECT (SELECT id FROM "public"."Profile" WHERE "username" = username) INTO profile_id
INSERT INTO "public"."CommentReference" (comment_id, profile_id) VALUES (NEW.id, profile_id);
END LOOP;
-- return nothing
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER create_comment_usernames_references_trigger
BEFORE INSERT OR UPDATE ON "public"."Comment"
FOR EACH ROW
EXECUTE PROCEDURE create_comment_usernames_references();