Files
mtusi2026lab5/student-tests/fixtures/legacy/0003_attachments.sql
T

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);