Migration 0003 creates attachments with a pending or ready status, a server-assigned object key in byte order collation and a partial index for pending rows, and message_attachments that keeps the order of the attachments of a message. Foreign keys hold the links between zones: an attachment belongs to a member of its chat, and a message may only reference an attachment of its own chat, with RESTRICT so a referenced attachment can never be deleted. The text check is relaxed to at most 4000 code points because an empty text is legal next to an attachment; an empty message without attachments is still refused by the domain. The migration test covers the new version, a rerun without changes and both foreign keys. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
38 lines
1.7 KiB
SQL
38 lines
1.7 KiB
SQL
ALTER TABLE messages
|
|
DROP CONSTRAINT messages_text_check,
|
|
ADD CONSTRAINT messages_text_check CHECK (char_length(text) <= 4000);
|
|
|
|
CREATE TABLE attachments (
|
|
id uuid PRIMARY KEY,
|
|
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 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
|
|
width integer NOT NULL CHECK (width > 0),
|
|
height integer NOT NULL CHECK (height > 0),
|
|
object_key text COLLATE "C" NOT NULL CONSTRAINT attachments_object_key_key UNIQUE,
|
|
status text NOT NULL CHECK (status IN ('pending', 'ready')),
|
|
created_at timestamptz NOT NULL,
|
|
updated_at timestamptz NOT NULL,
|
|
CONSTRAINT attachments_chat_key UNIQUE (id, chat_id),
|
|
CONSTRAINT attachments_owner_fkey FOREIGN KEY (chat_id, owner_id)
|
|
REFERENCES chat_members (chat_id, user_id)
|
|
);
|
|
|
|
CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending';
|
|
|
|
CREATE TABLE message_attachments (
|
|
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
|
position smallint NOT NULL CHECK (position BETWEEN 0 AND 9),
|
|
chat_id uuid NOT NULL,
|
|
attachment_id uuid NOT NULL,
|
|
PRIMARY KEY (message_id, position),
|
|
UNIQUE (message_id, attachment_id),
|
|
CONSTRAINT message_attachments_attachment_fkey FOREIGN KEY (attachment_id, chat_id)
|
|
REFERENCES attachments (id, chat_id) ON DELETE RESTRICT
|
|
);
|
|
|
|
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
|