forked from mtusi2026/mtusi2026lab5
52 lines
1.7 KiB
SQL
52 lines
1.7 KiB
SQL
-- +goose Up
|
|
CREATE TABLE users (
|
|
id uuid PRIMARY KEY,
|
|
username text NOT NULL UNIQUE
|
|
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
|
display_name text NOT NULL
|
|
CONSTRAINT users_display_name_not_blank CHECK (display_name ~ '\S'),
|
|
password_hash text NOT NULL,
|
|
created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
|
|
CREATE TABLE sessions (
|
|
token_hash text PRIMARY KEY,
|
|
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
|
created_at timestamptz NOT NULL DEFAULT now(),
|
|
expires_at timestamptz NOT NULL
|
|
);
|
|
|
|
CREATE INDEX idx_sessions_expires_at ON sessions (expires_at);
|
|
|
|
CREATE TABLE chats (
|
|
id uuid PRIMARY KEY,
|
|
title text NOT NULL
|
|
CONSTRAINT chats_title_not_blank CHECK (title ~ '\S'),
|
|
created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
|
|
CREATE TABLE chat_members (
|
|
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
|
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
|
PRIMARY KEY (chat_id, user_id)
|
|
);
|
|
|
|
CREATE INDEX idx_chat_members_user_id ON chat_members (user_id);
|
|
|
|
CREATE TABLE messages (
|
|
id uuid PRIMARY KEY,
|
|
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
|
sender_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
|
|
text text NOT NULL,
|
|
created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
|
|
CREATE INDEX idx_messages_chat_history ON messages (chat_id, created_at, id);
|
|
|
|
-- +goose Down
|
|
DROP TABLE messages;
|
|
DROP TABLE chat_members;
|
|
DROP TABLE chats;
|
|
DROP TABLE sessions;
|
|
DROP TABLE users;
|