Files
mtusi2026lab4/migrations/001_initial.sql
T

28 lines
1.9 KiB
SQL

CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY, username text UNIQUE NOT NULL, display_name text NOT NULL,
password_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp());
CREATE TABLE IF NOT EXISTS sessions (
token_hash text PRIMARY KEY, user_id uuid NOT NULL REFERENCES users(id), expires_at timestamptz NOT NULL);
CREATE TABLE IF NOT EXISTS chats (
id uuid PRIMARY KEY, title text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp());
CREATE TABLE IF NOT EXISTS members (
chat_id uuid REFERENCES chats(id), user_id uuid REFERENCES users(id), PRIMARY KEY(chat_id,user_id));
CREATE TABLE IF NOT EXISTS attachments (
id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats(id), owner_id uuid NOT NULL REFERENCES users(id),
object_key text UNIQUE NOT NULL, filename text NOT NULL, content_type text NOT NULL,
size_bytes integer NOT NULL, sha256 text NOT NULL, width integer NOT NULL, height integer NOT NULL,
status text NOT NULL CHECK(status IN ('ready','failed')), error_code text,
created_at timestamptz NOT NULL DEFAULT clock_timestamp());
CREATE TABLE IF NOT EXISTS 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 IF NOT EXISTS messages_page ON messages(chat_id,created_at,id);
CREATE TABLE IF NOT EXISTS message_attachments (
message_id uuid REFERENCES messages(id), attachment_id uuid REFERENCES attachments(id),
position integer NOT NULL, PRIMARY KEY(message_id,attachment_id));
CREATE TABLE IF NOT EXISTS idempotency (
user_id uuid REFERENCES users(id), chat_id uuid REFERENCES chats(id), key text,
body_hash text NOT NULL, message_id uuid NOT NULL REFERENCES messages(id),
expires_at timestamptz NOT NULL, PRIMARY KEY(user_id,chat_id,key));
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS updated_at timestamptz NOT NULL DEFAULT clock_timestamp();