forked from mtusi2026/mtusi2026lab4
39 lines
1.7 KiB
SQL
39 lines
1.7 KiB
SQL
CREATE TABLE users (
|
|
id uuid PRIMARY KEY,
|
|
username text NOT NULL,
|
|
display_name text NOT NULL,
|
|
password_hash text NOT NULL,
|
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
|
CONSTRAINT users_username_key UNIQUE (username),
|
|
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
|
CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100)
|
|
);
|
|
|
|
CREATE TABLE chats (
|
|
id uuid PRIMARY KEY,
|
|
title text NOT NULL,
|
|
created_by uuid NOT NULL REFERENCES users (id),
|
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
|
CONSTRAINT chats_title_length CHECK (char_length(title) BETWEEN 1 AND 100)
|
|
);
|
|
CREATE INDEX chats_created_at_id_idx ON chats (created_at, id);
|
|
|
|
CREATE TABLE chat_members (
|
|
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
|
user_id uuid NOT NULL REFERENCES users (id),
|
|
added_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
|
PRIMARY KEY (chat_id, user_id)
|
|
);
|
|
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
|
|
|
|
CREATE TABLE messages (
|
|
id uuid PRIMARY KEY,
|
|
chat_id uuid NOT NULL,
|
|
sender_id uuid NOT NULL,
|
|
text text NOT NULL,
|
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
|
CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 1 AND 4000),
|
|
CONSTRAINT messages_sender_is_member FOREIGN KEY (chat_id, sender_id)
|
|
REFERENCES chat_members (chat_id, user_id)
|
|
);
|
|
CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id); |