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 > 0 AND size_bytes <= 10485760), sha256 TEXT NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), width INTEGER NOT NULL CHECK (width > 0), height INTEGER NOT NULL CHECK (height > 0), status TEXT NOT NULL DEFAULT 'ready' CHECK (status IN ('pending','ready','failed')), error_code TEXT, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX IF NOT EXISTS idx_attachments_chat ON attachments (chat_id, created_at, id); CREATE INDEX IF NOT EXISTS idx_attachments_owner ON attachments (owner_id); -- Для reconciler/поиска «зависших» pending-записей: CREATE INDEX IF NOT EXISTS idx_attachments_pending ON attachments (created_at) WHERE status <> 'ready'; ALTER TABLE messages ADD COLUMN IF NOT EXISTS attachment_ids UUID[] NOT NULL DEFAULT '{}'; -- Журнал компенсации: объекты S3, которые могли остаться без метаданных. CREATE TABLE IF NOT EXISTS attachment_gc ( object_key TEXT PRIMARY KEY, reason TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() );