68 lines
2.1 KiB
SQL
68 lines
2.1 KiB
SQL
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 BIGINT NOT NULL,
|
|
sha256 TEXT NOT NULL,
|
|
object_key TEXT NOT NULL UNIQUE,
|
|
status TEXT NOT NULL DEFAULT 'ready',
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
|
|
|
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_bytes
|
|
CHECK (size_bytes BETWEEN 1 AND 10485760),
|
|
|
|
CONSTRAINT attachments_sha256_format
|
|
CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
|
|
|
CONSTRAINT attachments_status
|
|
CHECK (status = 'ready'),
|
|
|
|
CONSTRAINT attachments_owner_membership_fk
|
|
FOREIGN KEY (chat_id, owner_id)
|
|
REFERENCES chat_members (chat_id, user_id)
|
|
);
|
|
|
|
CREATE INDEX attachments_chat_created_id_idx
|
|
ON attachments (chat_id, created_at, id);
|
|
|
|
CREATE TABLE message_attachments (
|
|
message_id UUID NOT NULL REFERENCES messages(id),
|
|
attachment_id UUID NOT NULL REFERENCES attachments(id),
|
|
position SMALLINT NOT NULL,
|
|
|
|
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)
|
|
);
|
|
|
|
CREATE INDEX message_attachments_attachment_idx
|
|
ON message_attachments (attachment_id);
|
|
|
|
ALTER TABLE messages
|
|
DROP CONSTRAINT messages_text_length;
|
|
|
|
ALTER TABLE messages
|
|
ADD CONSTRAINT messages_text_length
|
|
CHECK (char_length(text) BETWEEN 0 AND 4000);
|
|
|
|
ALTER TABLE message_idempotency
|
|
ADD COLUMN request_attachment_ids UUID[] NOT NULL
|
|
DEFAULT ARRAY[]::UUID[];
|
|
|
|
ALTER TABLE message_idempotency
|
|
ADD CONSTRAINT message_idempotency_attachment_count
|
|
CHECK (cardinality(request_attachment_ids) <= 10);
|