forked from mtusi2026/mtusi2026lab3
43 lines
1.4 KiB
SQL
43 lines
1.4 KiB
SQL
CREATE TABLE users (
|
|
id uuid PRIMARY KEY,
|
|
username text NOT NULL UNIQUE,
|
|
display_name text NOT NULL,
|
|
password_hash text NOT NULL,
|
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
|
);
|
|
CREATE TABLE sessions (
|
|
token_hash text PRIMARY KEY,
|
|
user_id uuid NOT NULL REFERENCES users(id),
|
|
expires_at timestamptz NOT NULL
|
|
);
|
|
CREATE INDEX sessions_expiry ON sessions(expires_at);
|
|
CREATE TABLE chats (
|
|
id uuid PRIMARY KEY,
|
|
title text NOT NULL,
|
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
|
);
|
|
CREATE TABLE memberships (
|
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
|
user_id uuid NOT NULL REFERENCES users(id),
|
|
PRIMARY KEY (chat_id, user_id)
|
|
);
|
|
CREATE INDEX memberships_user ON memberships(user_id, chat_id);
|
|
CREATE TABLE messages (
|
|
id uuid PRIMARY KEY,
|
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
|
sender_id uuid NOT NULL REFERENCES users(id),
|
|
text text NOT NULL,
|
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
|
);
|
|
CREATE INDEX messages_history ON messages(chat_id, created_at, id);
|
|
CREATE TABLE idempotency (
|
|
user_id uuid NOT NULL REFERENCES users(id),
|
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
|
key text NOT NULL,
|
|
body text NOT NULL,
|
|
message_id uuid NOT NULL REFERENCES messages(id),
|
|
expires_at timestamptz NOT NULL,
|
|
PRIMARY KEY (user_id, chat_id, key)
|
|
);
|
|
CREATE INDEX idempotency_expiry ON idempotency(expires_at);
|