forked from mtusi2026/mtusi2026lab5
43 lines
1.3 KiB
SQL
43 lines
1.3 KiB
SQL
-- +goose Up
|
|
CREATE TABLE users (
|
|
id uuid PRIMARY KEY,
|
|
username text NOT NULL CONSTRAINT users_username_key UNIQUE,
|
|
display_name text NOT NULL,
|
|
password_hash text NOT NULL,
|
|
created_at timestamptz NOT NULL
|
|
);
|
|
|
|
CREATE TABLE chats (
|
|
id uuid PRIMARY KEY,
|
|
title text NOT NULL,
|
|
created_at timestamptz NOT NULL
|
|
);
|
|
|
|
CREATE TABLE chat_members (
|
|
chat_id uuid NOT NULL REFERENCES chats (id),
|
|
user_id uuid NOT NULL REFERENCES users (id),
|
|
PRIMARY KEY (chat_id, user_id)
|
|
);
|
|
|
|
-- Lists the chats of one user in (created_at, id) order: chat ids are UUIDv7.
|
|
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
|
|
|
|
-- The key is (chat_id, id) and serves the history query directly:
|
|
-- WHERE chat_id = $1 AND id > $2 ORDER BY id LIMIT $3. Nothing looks a
|
|
-- message up by id alone, and a separate index on id would only cost writes
|
|
-- and tempt the planner into scanning every chat's messages in id order.
|
|
CREATE TABLE messages (
|
|
chat_id uuid NOT NULL REFERENCES chats (id),
|
|
id uuid NOT NULL,
|
|
sender_id uuid NOT NULL REFERENCES users (id),
|
|
text text NOT NULL,
|
|
created_at timestamptz NOT NULL,
|
|
PRIMARY KEY (chat_id, id)
|
|
);
|
|
|
|
-- +goose Down
|
|
DROP TABLE messages;
|
|
DROP TABLE chat_members;
|
|
DROP TABLE chats;
|
|
DROP TABLE users;
|