Files
mtusi2026lab3/src/main/resources/migrations/V3__message_idempotency_keys.sql
T

20 lines
1.3 KiB
SQL

-- Idempotency-Key of POST /chats/{chat_id}/messages. Scope: user + chat (method and path are fixed) + key.
-- The row is inserted in the same transaction as the message, so a key exists only together with its message.
-- message_id is NULL only inside that transaction: the key is claimed first, the message is written next.
CREATE TABLE message_idempotency_keys (
user_id uuid NOT NULL,
chat_id uuid NOT NULL,
key varchar(128) NOT NULL,
request_hash varchar(64) NOT NULL,
message_id uuid NULL,
created_at timestamptz NOT NULL,
CONSTRAINT message_idempotency_keys_pkey PRIMARY KEY (user_id, chat_id, key),
CONSTRAINT message_idempotency_keys_user_id_fkey FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT message_idempotency_keys_chat_id_fkey FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE,
CONSTRAINT message_idempotency_keys_message_id_fkey FOREIGN KEY (message_id) REFERENCES messages (id) ON DELETE CASCADE
);
-- Foreign keys are not indexed automatically; the cascades from chats and messages need these.
CREATE INDEX message_idempotency_keys_chat_id_idx ON message_idempotency_keys (chat_id);
CREATE INDEX message_idempotency_keys_message_id_idx ON message_idempotency_keys (message_id);