Files
mtusi2026lab5/migrations/003_attachments.sql
T
2026-11-19 19:45:26 +03:00

35 lines
1.4 KiB
SQL

CREATE TABLE IF NOT EXISTS attachments (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
owner_id UUID NOT NULL REFERENCES users (id) ON DELETE CASCADE,
object_key TEXT NOT NULL UNIQUE,
filename TEXT NOT NULL,
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 CHAR(64) NOT NULL,
width INT NOT NULL CHECK (width > 0),
height INT NOT NULL CHECK (height > 0),
status TEXT NOT NULL CHECK (status IN ('processing', 'ready', 'failed')),
variants JSONB NOT NULL DEFAULT '[]'::jsonb,
error_code TEXT,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS attachments_chat_created_idx
ON attachments (chat_id, created_at, id);
CREATE INDEX IF NOT EXISTS attachments_processing_created_idx
ON attachments (created_at)
WHERE status = 'processing';
CREATE TABLE IF NOT EXISTS message_attachments (
message_id UUID NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
attachment_id UUID NOT NULL REFERENCES attachments (id) ON DELETE RESTRICT,
position INT NOT NULL CHECK (position >= 0),
PRIMARY KEY (message_id, attachment_id),
UNIQUE (message_id, position)
);
CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx
ON message_attachments (attachment_id);