Files
mtusi2026lab4/migrations/003_attachments.sql
T

31 lines
1.5 KiB
SQL

ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_check;
ALTER TABLE messages ADD CONSTRAINT messages_text_length_check CHECK (length(text) <= 4000);
ALTER TABLE messages ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id);
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
owner_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
object_key text NOT NULL UNIQUE,
filename varchar(255) NOT NULL CHECK (length(filename) BETWEEN 1 AND 255),
content_type varchar(20) NOT NULL CHECK (content_type IN ('image/png','image/jpeg')),
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
sha256 char(64) NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
status varchar(16) NOT NULL CHECK (status IN ('ready','failed')),
error_code varchar(64),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
UNIQUE (id, chat_id)
);
CREATE INDEX attachments_chat_created ON attachments(chat_id, created_at);
CREATE TABLE message_attachments (
message_id uuid NOT NULL,
attachment_id uuid NOT NULL,
chat_id uuid NOT NULL,
PRIMARY KEY (message_id, attachment_id),
FOREIGN KEY (message_id, chat_id) REFERENCES messages(id, chat_id) ON DELETE CASCADE,
FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments(id, chat_id) ON DELETE RESTRICT
);
CREATE INDEX message_attachments_by_attachment ON message_attachments(attachment_id);