Skip to content

Commit 5cfe92c

Browse files
authored
fix: Update chats.update_last_messages trigger to make sure it is only called for actual last message in case of update (#25)
it can be the case that a message got updated that is not the last message, in that case the `lastMessages` should not be updated
1 parent a42a74d commit 5cfe92c

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

example/utils/sql/02_database_trigger.sql

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,46 @@ CREATE OR REPLACE FUNCTION chats.update_last_messages()
2828
SET search_path = ''
2929
AS $$
3030
DECLARE
31+
latest_message jsonb;
3132
ts_in_milliseconds bigint;
3233
BEGIN
33-
SELECT EXTRACT(epoch FROM NOW()) * 1000 INTO ts_in_milliseconds;
34-
UPDATE chats.rooms
35-
SET "updatedAt" = ts_in_milliseconds,
36-
"lastMessages" = jsonb_build_array(NEW)
37-
WHERE id = NEW."roomId";
38-
RETURN NEW;
34+
SELECT jsonb_build_object(
35+
'id', id,
36+
'createdAt', "createdAt",
37+
'metadata', metadata,
38+
'duration', duration,
39+
'mimeType', "mimeType",
40+
'name', name,
41+
'remoteId', "remoteId",
42+
'repliedMessage', "repliedMessage",
43+
'roomId', "roomId",
44+
'showStatus', "showStatus",
45+
'size', size,
46+
'status', status,
47+
'type', type,
48+
'updatedAt', "updatedAt",
49+
'uri', uri,
50+
'waveForm', "waveForm",
51+
'isLoading', "isLoading",
52+
'height', height,
53+
'width', width,
54+
'previewData', "previewData",
55+
'authorId', "authorId",
56+
'text', text
57+
)
58+
INTO latest_message
59+
FROM chats.messages
60+
WHERE "roomId" = NEW."roomId"
61+
ORDER BY "createdAt" DESC
62+
LIMIT 1;
63+
IF latest_message IS DISTINCT FROM (SELECT "lastMessages" FROM chats.rooms WHERE id = NEW."roomId") THEN
64+
SELECT EXTRACT(epoch FROM NOW()) * 1000 INTO ts_in_milliseconds;
65+
UPDATE chats.rooms
66+
SET "updatedAt" = ts_in_milliseconds,
67+
"lastMessages" = jsonb_build_array(latest_message)
68+
WHERE id = NEW."roomId";
69+
END IF;
70+
RETURN NEW;
3971
END;
4072
$$ LANGUAGE plpgsql;
4173

0 commit comments

Comments
 (0)