CREATE TABLE group_attachments ( group_id uuid NOT NULL, id uuid NOT NULL, epoch_id uuid NOT NULL, sender_device uuid NOT NULL, ciphertext bytea NOT NULL CHECK (octet_length(ciphertext) BETWEEN 16 AND 8388624), created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (group_id,id), UNIQUE (group_id,epoch_id,sender_device,id), FOREIGN KEY (group_id,epoch_id,sender_device) REFERENCES group_epoch_devices(group_id,epoch_id,device_id) ON DELETE CASCADE ); ALTER TABLE group_messages ADD COLUMN attachment_id uuid; ALTER TABLE group_messages ADD FOREIGN KEY (group_id,epoch_id,sender_device,attachment_id) REFERENCES group_attachments(group_id,epoch_id,sender_device,id); CREATE UNIQUE INDEX group_messages_attachment ON group_messages(group_id,attachment_id) WHERE attachment_id IS NOT NULL; CREATE INDEX group_attachments_expiry ON group_attachments(created_at);