Files
mtusi2026lab4/migrations/011_attachments.sql

49 lines
1.8 KiB
SQL

ALTER TABLE messages
DROP CONSTRAINT messages_text_check;
ALTER TABLE messages
ADD CONSTRAINT messages_text_check
CHECK (char_length(text) BETWEEN 0 AND 4000 AND (text = '' OR btrim(text) <> ''));
ALTER TABLE messages
ADD CONSTRAINT messages_chat_id_id_unique UNIQUE (chat_id, id);
CREATE TABLE attachments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
chat_id UUID NOT NULL,
owner_id UUID NOT NULL,
filename TEXT NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
content_type TEXT 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 ~ '^[a-f0-9]{64}$'),
object_key TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT 'ready' CHECK (status = 'ready'),
variants JSONB NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(variants) = 'array'),
error_code TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (chat_id, id),
CHECK (error_code IS NULL),
FOREIGN KEY (chat_id, owner_id)
REFERENCES chat_members(chat_id, user_id) ON DELETE CASCADE
);
CREATE INDEX attachments_chat_created_idx
ON attachments (chat_id, created_at, id);
CREATE TABLE message_attachments (
chat_id UUID NOT NULL,
message_id UUID NOT NULL,
attachment_id UUID NOT NULL,
position SMALLINT NOT NULL CHECK (position BETWEEN 0 AND 9),
PRIMARY KEY (message_id, attachment_id),
UNIQUE (message_id, position),
FOREIGN KEY (chat_id, message_id)
REFERENCES messages(chat_id, id) ON DELETE CASCADE,
FOREIGN KEY (chat_id, attachment_id)
REFERENCES attachments(chat_id, id) ON DELETE CASCADE
);
CREATE INDEX message_attachments_chat_attachment_idx
ON message_attachments (chat_id, attachment_id);