-- Lab4: message may be text, attachments, or both. Empty text is stored only when -- an attachment is linked; the API rejects a blank message that has neither. ALTER TABLE messages DROP CONSTRAINT messages_text_len; ALTER TABLE messages ADD CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 0 AND 4000); -- filename is the display name only. object_key is assigned by the server and is never taken from filename. -- The original bytes live in the private S3 bucket under that key, not in this table. CREATE TABLE attachments ( id UUID PRIMARY KEY, chat_id UUID NOT NULL REFERENCES chats (id), owner_id UUID NOT NULL REFERENCES users (id), filename TEXT NOT NULL, content_type TEXT NOT NULL, size_bytes INTEGER NOT NULL, sha256 TEXT NOT NULL, object_key TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL, CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255), CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')), CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760), CONSTRAINT attachments_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$'), CONSTRAINT attachments_object_key_unique UNIQUE (object_key) ); CREATE INDEX attachments_chat_idx ON attachments (chat_id); CREATE TABLE message_attachments ( message_id UUID NOT NULL REFERENCES messages (id), attachment_id UUID NOT NULL REFERENCES attachments (id), position INTEGER NOT NULL, PRIMARY KEY (message_id, attachment_id), CONSTRAINT message_attachments_position CHECK (position >= 0 AND position < 10) ); CREATE INDEX message_attachments_message_idx ON message_attachments (message_id, position);