-- Only completed, ready attachments are published in this table in lab4. -- Interrupted upload tracking/compensation is implemented separately. CREATE TABLE attachments ( id UUID PRIMARY KEY, chat_id UUID NOT NULL REFERENCES chats(id), owner_id UUID NOT NULL, object_key TEXT NOT NULL UNIQUE, filename TEXT NOT NULL, 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 TEXT NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), status TEXT NOT NULL DEFAULT 'ready' CHECK (status = 'ready'), created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT attachments_owner_membership_fk FOREIGN KEY (chat_id, owner_id) REFERENCES chat_members(chat_id, user_id), CONSTRAINT attachments_filename_valid CHECK ( char_length(filename) BETWEEN 1 AND 255 AND filename !~ '[[:cntrl:]]' AND position('/' IN filename) = 0 AND position(chr(92) IN filename) = 0 ), CONSTRAINT attachments_object_key_valid CHECK (object_key = 'attachments/' || id::text), CONSTRAINT attachments_updated_at_valid CHECK (updated_at >= created_at), CONSTRAINT attachments_id_chat_unique UNIQUE (id, chat_id) ); CREATE INDEX attachments_created_idx ON attachments (created_at, id); -- Composite FKs enforce that message and attachment share the same chat. ALTER TABLE messages ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id); CREATE TABLE message_attachments ( message_id UUID NOT NULL, attachment_id UUID NOT NULL, chat_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 (message_id, chat_id) REFERENCES messages(id, chat_id), FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments(id, chat_id) ); CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);