forked from mtusi2026/mtusi2026lab4
21 lines
1.8 KiB
SQL
21 lines
1.8 KiB
SQL
CREATE TABLE users (
|
|
id uuid PRIMARY KEY, username text NOT NULL UNIQUE CHECK(username ~ '^[a-z0-9_]{3,32}$'),
|
|
display_name text NOT NULL CHECK(length(btrim(display_name))>0 AND length(display_name)<=100),
|
|
password_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
|
);
|
|
CREATE TABLE chats (id uuid PRIMARY KEY, title text NOT NULL CHECK(length(btrim(title))>0 AND length(title)<=100), created_at timestamptz NOT NULL DEFAULT clock_timestamp());
|
|
CREATE TABLE members (chat_id uuid REFERENCES chats ON DELETE CASCADE, user_id uuid REFERENCES users, PRIMARY KEY(chat_id,user_id));
|
|
CREATE INDEX members_user ON members(user_id,chat_id);
|
|
CREATE TABLE attachments (
|
|
id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats, owner_id uuid NOT NULL REFERENCES users,
|
|
object_key text NOT NULL UNIQUE, filename text NOT NULL, content_type text NOT NULL,
|
|
size_bytes bigint NOT NULL, sha256 char(64) NOT NULL, status text NOT NULL CHECK(status IN ('ready')),
|
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(), updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
|
);
|
|
CREATE INDEX attachments_chat ON attachments(chat_id,id);
|
|
CREATE TABLE messages (id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats, sender_id uuid NOT NULL REFERENCES users, text text NOT NULL CHECK(length(text)<=4000), created_at timestamptz NOT NULL DEFAULT clock_timestamp());
|
|
CREATE TABLE message_attachments (message_id uuid REFERENCES messages ON DELETE CASCADE, attachment_id uuid REFERENCES attachments, position smallint NOT NULL, PRIMARY KEY(message_id,attachment_id), UNIQUE(message_id,position));
|
|
CREATE INDEX messages_history ON messages(chat_id,created_at,id);
|
|
CREATE TABLE sessions (token_hash text PRIMARY KEY, user_id uuid NOT NULL REFERENCES users, expires_at timestamptz NOT NULL);
|
|
CREATE INDEX sessions_expiry ON sessions(expires_at);
|