Files
mtusi2026lab3/migrations/002_lab3.sql
T

30 lines
1.3 KiB
SQL

-- Laboratory 3: shared idempotency for POST messages.
--
-- Scope is exactly (user_id, method, path, key): the same key may be reused by
-- another user or another chat independently. The message row and the stored
-- response are written in one transaction, so a transient failure never leaves
-- a "completed" key without its side effect (and vice versa).
CREATE TABLE IF NOT EXISTS idempotency_keys (
id bigserial PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
method text NOT NULL,
path text NOT NULL,
key text NOT NULL,
request_hash text NOT NULL,
status_code integer,
response_body jsonb,
message_id uuid REFERENCES messages(id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
expires_at timestamptz NOT NULL,
CONSTRAINT idempotency_keys_scope_key UNIQUE (user_id, method, path, key),
CONSTRAINT idempotency_keys_key_format
CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
CONSTRAINT idempotency_keys_method CHECK (method IN ('POST'))
);
-- Expired rows are removed opportunistically by the API. This index keeps the
-- cleanup and expiry checks cheap without scanning the whole table.
CREATE INDEX IF NOT EXISTS idempotency_keys_expires_at_idx
ON idempotency_keys (expires_at);