lab4 for lab5

This commit is contained in:
Матвей
2026-10-26 10:05:24 +03:00
parent 276dbdad8a
commit 3b67201e5e
40 changed files with 3522 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
CREATE TABLE users (
id uuid PRIMARY KEY,
username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name varchar(100) NOT NULL CHECK (char_length(btrim(display_name)) > 0),
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title varchar(100) NOT NULL CHECK (char_length(btrim(title)) > 0),
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 RESTRICT,
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 REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text varchar(4000) NOT NULL CHECK (char_length(btrim(text)) > 0),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id);
CREATE TABLE sessions (
token_hash char(64) PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
+1
View File
@@ -0,0 +1 @@
ALTER TABLE chats ADD COLUMN history_version bigint NOT NULL DEFAULT 0;
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE idempotency_records (
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
method varchar(8) NOT NULL,
path text NOT NULL,
idempotency_key varchar(128) NOT NULL,
request_hash char(64) NOT NULL,
message_id uuid REFERENCES messages(id) ON DELETE RESTRICT,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, method, path, idempotency_key)
);
CREATE INDEX idempotency_records_created_at_idx ON idempotency_records (created_at);
+18
View File
@@ -0,0 +1,18 @@
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id),
owner_id uuid NOT NULL REFERENCES users(id),
filename varchar(255) NOT NULL,
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
size_bytes integer NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
sha256 char(64) NOT NULL,
object_key text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (id, chat_id)
);
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}';
ALTER TABLE messages ADD CONSTRAINT messages_content_check
CHECK (char_length(btrim(text)) > 0 OR cardinality(attachment_ids) > 0);
CREATE INDEX attachments_chat_idx ON attachments(chat_id);