41 lines
1.3 KiB
SQL
41 lines
1.3 KiB
SQL
-- Claims the key for this actor/chat and returns whether this request owns it.
|
|
-- A live record wins: the statement returns nothing and the caller replays the
|
|
-- stored message. An expired record is replaced in place.
|
|
-- name: ClaimMessageIdempotency :one
|
|
INSERT INTO message_idempotency (actor_id, chat_id, key, request_hash, expires_at)
|
|
VALUES (
|
|
sqlc.arg(actor_id),
|
|
sqlc.arg(chat_id),
|
|
sqlc.arg(key),
|
|
sqlc.arg(request_hash),
|
|
sqlc.arg(expires_at)
|
|
)
|
|
ON CONFLICT (actor_id, chat_id, key) DO UPDATE
|
|
SET request_hash = EXCLUDED.request_hash,
|
|
expires_at = EXCLUDED.expires_at,
|
|
message_id = NULL
|
|
WHERE message_idempotency.expires_at <= now()
|
|
RETURNING key;
|
|
|
|
-- Concurrent duplicates block here until the owner commits, then read the
|
|
-- result it stored in the same transaction.
|
|
-- name: GetMessageIdempotency :one
|
|
SELECT message_id, request_hash
|
|
FROM message_idempotency
|
|
WHERE actor_id = sqlc.arg(actor_id)
|
|
AND chat_id = sqlc.arg(chat_id)
|
|
AND key = sqlc.arg(key)
|
|
FOR UPDATE;
|
|
|
|
-- name: CompleteMessageIdempotency :exec
|
|
UPDATE message_idempotency
|
|
SET message_id = sqlc.arg(message_id)
|
|
WHERE actor_id = sqlc.arg(actor_id)
|
|
AND chat_id = sqlc.arg(chat_id)
|
|
AND key = sqlc.arg(key);
|
|
|
|
-- name: GetMessageByID :one
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM messages
|
|
WHERE id = sqlc.arg(id);
|