Skip to content

Instantly share code, notes, and snippets.

@afarber
Created March 6, 2018 12:07
Show Gist options
  • Save afarber/776fd772e71f44c96b7758916c6542cd to your computer and use it in GitHub Desktop.
Save afarber/776fd772e71f44c96b7758916c6542cd to your computer and use it in GitHub Desktop.
words_get_chat.sql
CREATE OR REPLACE FUNCTION words_get_chat(
in_gid integer,
in_social integer,
in_sid text
) RETURNS TABLE (
out_mine integer,
out_msg text
) AS
$func$
DECLARE
_uid integer;
BEGIN
_uid := (SELECT uid FROM words_social WHERE social = in_social AND sid = in_sid);
UPDATE words_games SET
chat2 = 0
WHERE gid = in_gid
AND player1 = _uid;
IF NOT FOUND THEN
UPDATE words_games SET
chat1 = 0
WHERE gid = in_gid
AND player2 = _uid;
END IF;
IF NOT FOUND THEN
RAISE EXCEPTION 'Game % not found for user % %', in_gid, in_social, in_sid;
END IF;
RETURN QUERY SELECT
CASE WHEN c.uid = s.uid THEN 1 ELSE 0 END,
c.msg
FROM words_chat c
JOIN words_games g USING (gid)
JOIN words_social s ON s.uid IN (g.player1, g.player2)
WHERE c.gid = in_gid
AND s.social = in_social
AND s.sid = in_sid
ORDER BY c.CREATED ASC;
END
$func$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment