Files
mtusi2026lab7/src/main/resources/db/migration/V4__add_attachments.sql
T

54 lines
2.2 KiB
SQL

ALTER TABLE messages DROP CONSTRAINT messages_text_length_chk;
ALTER TABLE messages ADD CONSTRAINT messages_text_length_chk
CHECK (char_length(text) BETWEEN 0 AND 4000);
ALTER TABLE messages ADD CONSTRAINT messages_id_chat_uk UNIQUE (id, chat_id);
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
owner_id uuid NOT NULL,
filename varchar(255) NOT NULL,
content_type varchar(32) NOT NULL,
size_bytes bigint NOT NULL,
sha256 char(64) NOT NULL,
object_key text NOT NULL,
status varchar(16) NOT NULL DEFAULT 'ready',
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT attachments_id_chat_uk UNIQUE (id, chat_id),
CONSTRAINT attachments_object_key_uk UNIQUE (object_key),
CONSTRAINT attachments_owner_membership_fk
FOREIGN KEY (chat_id, owner_id)
REFERENCES chat_members(chat_id, user_id) ON DELETE RESTRICT,
CONSTRAINT attachments_content_type_chk
CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_size_chk
CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha256_chk
CHECK (sha256 ~ '^[a-f0-9]{64}$'),
CONSTRAINT attachments_status_chk CHECK (status = 'ready'),
CONSTRAINT attachments_filename_chk
CHECK (char_length(filename) BETWEEN 1 AND 255)
);
CREATE TABLE message_attachments (
message_id uuid NOT NULL,
chat_id uuid NOT NULL,
attachment_id uuid NOT NULL,
position smallint NOT NULL,
CONSTRAINT message_attachments_pk PRIMARY KEY (message_id, attachment_id),
CONSTRAINT message_attachments_position_uk UNIQUE (message_id, position),
CONSTRAINT message_attachments_message_fk
FOREIGN KEY (message_id, chat_id)
REFERENCES messages(id, chat_id) ON DELETE CASCADE,
CONSTRAINT message_attachments_attachment_fk
FOREIGN KEY (attachment_id, chat_id)
REFERENCES attachments(id, chat_id) ON DELETE RESTRICT,
CONSTRAINT message_attachments_position_chk CHECK (position BETWEEN 0 AND 9)
);
CREATE INDEX attachments_chat_created_idx ON attachments (chat_id, created_at, id);
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);