-- 0004 (lab4): метаданные вложений в PostgreSQL, байты — в приватном S3-бакете. -- Ключ объекта назначает сервер (att//original); filename — только отображаемое имя. CREATE TABLE attachments ( id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, 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, width integer NOT NULL, height integer NOT NULL, status text NOT NULL DEFAULT 'ready', error_code text, s3_key text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), 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_status CHECK (status IN ('queued', 'processing', 'ready', 'failed')), CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255) ); CREATE UNIQUE INDEX attachments_s3_key_key ON attachments (s3_key); CREATE INDEX attachments_chat ON attachments (chat_id); -- Связь сообщение <-> вложения (порядок сохраняется). Вложение может быть привязано к нескольким сообщениям чата. CREATE TABLE message_attachments ( message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE, attachment_id uuid NOT NULL REFERENCES attachments (id), position smallint NOT NULL, PRIMARY KEY (message_id, attachment_id) ); CREATE INDEX message_attachments_attachment ON message_attachments (attachment_id); -- Отправка сообщения с вложениями: заменяет функцию из 0003 (добавлен параметр p_atts и результат msg_atts). DROP FUNCTION send_message(uuid, uuid, text, bytea, text, double precision); CREATE FUNCTION send_message(p_chat uuid, p_user uuid, p_key text, p_hash bytea, p_text text, p_ttl double precision, p_atts uuid[]) RETURNS TABLE (outcome text, msg_id uuid, msg_chat uuid, msg_sender uuid, msg_text text, msg_created timestamptz, request_hash bytea, msg_atts uuid[]) LANGUAGE plpgsql AS $$ DECLARE v_new uuid := gen_random_uuid(); v_ins uuid; v_created timestamptz; v_found int; v_failed int; BEGIN IF NOT EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = p_chat AND m.user_id = p_user) THEN RETURN QUERY SELECT 'not_member'::text, NULL::uuid, NULL::uuid, NULL::uuid, NULL::text, NULL::timestamptz, NULL::bytea, NULL::uuid[]; RETURN; END IF; IF cardinality(p_atts) > 0 THEN SELECT count(*), count(*) FILTER (WHERE a.status = 'failed') INTO v_found, v_failed FROM attachments a WHERE a.id = ANY (p_atts) AND a.chat_id = p_chat; IF v_found <> cardinality(p_atts) THEN RETURN QUERY SELECT 'attachment_not_found'::text, NULL::uuid, NULL::uuid, NULL::uuid, NULL::text, NULL::timestamptz, NULL::bytea, NULL::uuid[]; RETURN; END IF; IF v_failed > 0 THEN RETURN QUERY SELECT 'attachment_failed'::text, NULL::uuid, NULL::uuid, NULL::uuid, NULL::text, NULL::timestamptz, NULL::bytea, NULL::uuid[]; RETURN; END IF; END IF; DELETE FROM idempotency_keys k WHERE k.user_id = p_user AND k.chat_id = p_chat AND k.idem_key = p_key AND k.created_at < now() - make_interval(secs => p_ttl); INSERT INTO idempotency_keys (user_id, chat_id, idem_key, request_hash, message_id) VALUES (p_user, p_chat, p_key, p_hash, v_new) ON CONFLICT DO NOTHING RETURNING message_id INTO v_ins; IF v_ins IS NOT NULL THEN INSERT INTO messages (id, chat_id, sender_id, text) VALUES (v_new, p_chat, p_user, p_text) RETURNING created_at INTO v_created; INSERT INTO message_attachments (message_id, attachment_id, position) SELECT v_new, a, (o - 1)::smallint FROM unnest(p_atts) WITH ORDINALITY AS t(a, o); RETURN QUERY SELECT 'created'::text, v_new, p_chat, p_user, p_text, v_created, p_hash, p_atts; ELSE RETURN QUERY SELECT 'replay'::text, m.id, m.chat_id, m.sender_id, m.text, m.created_at, k.request_hash, COALESCE((SELECT array_agg(ma.attachment_id ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id), '{}'::uuid[]) FROM idempotency_keys k JOIN messages m ON m.id = k.message_id WHERE k.user_id = p_user AND k.chat_id = p_chat AND k.idem_key = p_key; END IF; END; $$;