Skip to content

Commit

Permalink
fix: Update chats.update_last_messages trigger to make sure it is onl…
Browse files Browse the repository at this point in the history
…y 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
  • Loading branch information
lazy-geek authored Dec 26, 2024
1 parent a42a74d commit 5cfe92c
Showing 1 changed file with 38 additions and 6 deletions.
44 changes: 38 additions & 6 deletions example/utils/sql/02_database_trigger.sql
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,46 @@ CREATE OR REPLACE FUNCTION chats.update_last_messages()
SET search_path = ''
AS $$
DECLARE
latest_message jsonb;
ts_in_milliseconds bigint;
BEGIN
SELECT EXTRACT(epoch FROM NOW()) * 1000 INTO ts_in_milliseconds;
UPDATE chats.rooms
SET "updatedAt" = ts_in_milliseconds,
"lastMessages" = jsonb_build_array(NEW)
WHERE id = NEW."roomId";
RETURN NEW;
SELECT jsonb_build_object(
'id', id,
'createdAt', "createdAt",
'metadata', metadata,
'duration', duration,
'mimeType', "mimeType",
'name', name,
'remoteId', "remoteId",
'repliedMessage', "repliedMessage",
'roomId', "roomId",
'showStatus', "showStatus",
'size', size,
'status', status,
'type', type,
'updatedAt', "updatedAt",
'uri', uri,
'waveForm', "waveForm",
'isLoading', "isLoading",
'height', height,
'width', width,
'previewData', "previewData",
'authorId', "authorId",
'text', text
)
INTO latest_message
FROM chats.messages
WHERE "roomId" = NEW."roomId"
ORDER BY "createdAt" DESC
LIMIT 1;
IF latest_message IS DISTINCT FROM (SELECT "lastMessages" FROM chats.rooms WHERE id = NEW."roomId") THEN
SELECT EXTRACT(epoch FROM NOW()) * 1000 INTO ts_in_milliseconds;
UPDATE chats.rooms
SET "updatedAt" = ts_in_milliseconds,
"lastMessages" = jsonb_build_array(latest_message)
WHERE id = NEW."roomId";
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

Expand Down

0 comments on commit 5cfe92c

Please sign in to comment.