forked from mtusi2026/mtusi2026lab5
48 lines
2.2 KiB
SQL
48 lines
2.2 KiB
SQL
ALTER TABLE messages
|
|
DROP CONSTRAINT messages_text_length,
|
|
DROP CONSTRAINT messages_text_not_blank;
|
|
|
|
ALTER TABLE messages
|
|
ADD CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 0 AND 4000),
|
|
ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id);
|
|
|
|
CREATE TABLE attachments (
|
|
id UUID PRIMARY KEY,
|
|
chat_id UUID NOT NULL,
|
|
owner_id UUID NOT NULL,
|
|
filename TEXT NOT NULL,
|
|
content_type TEXT NOT NULL,
|
|
size_bytes BIGINT NOT NULL,
|
|
sha256 TEXT NOT NULL,
|
|
object_key TEXT NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
|
CONSTRAINT attachments_id_chat_unique UNIQUE (id, chat_id),
|
|
CONSTRAINT attachments_object_key_unique UNIQUE (object_key),
|
|
CONSTRAINT attachments_owner_membership_fk FOREIGN KEY (chat_id, owner_id)
|
|
REFERENCES chat_members (chat_id, user_id) ON DELETE CASCADE,
|
|
CONSTRAINT attachments_filename_length 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_length CHECK (char_length(object_key) BETWEEN 1 AND 1024)
|
|
);
|
|
|
|
CREATE INDEX attachments_chat_id_created_at_id_idx ON attachments (chat_id, created_at, id);
|
|
|
|
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_unique UNIQUE (message_id, position),
|
|
CONSTRAINT message_attachments_position_range CHECK (position BETWEEN 0 AND 9),
|
|
CONSTRAINT message_attachments_message_chat_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
|
|
);
|
|
|
|
CREATE INDEX message_attachments_attachment_id_idx ON message_attachments (attachment_id);
|