|
| 1 | +package com.involutionhell.backend.chat.repository; |
| 2 | + |
| 3 | +import java.sql.Types; |
| 4 | +import java.util.UUID; |
| 5 | +import org.springframework.jdbc.core.JdbcTemplate; |
| 6 | +import org.springframework.stereotype.Repository; |
| 7 | +import org.springframework.transaction.annotation.Transactional; |
| 8 | + |
| 9 | +/** |
| 10 | + * 基于 Spring JDBC 的 Chat / Message 表读写实现。 |
| 11 | + * |
| 12 | + * 表结构由 Prisma 历史管理,列名是驼峰并加了双引号("userId"、"chatId"、 |
| 13 | + * "createdAt"),PostgreSQL 下这些名字都区分大小写,所有 SQL 里必须保留双 |
| 14 | + * 引号——漏一个就会报 column "userid" does not exist。 |
| 15 | + */ |
| 16 | +@Repository |
| 17 | +public class JdbcChatHistoryRepository implements ChatHistoryRepository { |
| 18 | + |
| 19 | + private final JdbcTemplate jdbc; |
| 20 | + |
| 21 | + public JdbcChatHistoryRepository(JdbcTemplate jdbc) { |
| 22 | + this.jdbc = jdbc; |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * 为什么用 ON CONFLICT 做 upsert 而不是先 select 再 insert: |
| 27 | + * 1. 单次 round-trip,少一次 SQL 调用 |
| 28 | + * 2. 并发两个 tab 同一 chatId 时不会先后撞主键冲突报 500 |
| 29 | + * |
| 30 | + * 为什么 userId 用 COALESCE:匿名请求 → 后续登录请求会复用同一个 chatId, |
| 31 | + * 第二次带着真实 userId 过来时应该把之前的 NULL 覆盖掉;但如果这次匿名、 |
| 32 | + * 上次已经登录了,不能把 userId 擦掉——所以用 COALESCE(EXCLUDED.userId, "Chat"."userId") |
| 33 | + * 的语义:新值优先,新值为 NULL 时保留旧值。 |
| 34 | + */ |
| 35 | + @Override |
| 36 | + @Transactional |
| 37 | + public void saveTurn(String chatId, Long userId, String userMessage, String assistantMessage) { |
| 38 | + jdbc.update( |
| 39 | + """ |
| 40 | + INSERT INTO "Chat" (id, "userId", "createdAt", "updatedAt") |
| 41 | + VALUES (?, ?, NOW(), NOW()) |
| 42 | + ON CONFLICT (id) DO UPDATE SET |
| 43 | + "userId" = COALESCE(EXCLUDED."userId", "Chat"."userId"), |
| 44 | + "updatedAt" = NOW() |
| 45 | + """, |
| 46 | + ps -> { |
| 47 | + ps.setString(1, chatId); |
| 48 | + if (userId == null) { |
| 49 | + ps.setNull(2, Types.INTEGER); |
| 50 | + } else { |
| 51 | + ps.setInt(2, userId.intValue()); |
| 52 | + } |
| 53 | + }); |
| 54 | + |
| 55 | + if (userMessage != null && !userMessage.isBlank()) { |
| 56 | + insertMessage(chatId, "user", userMessage); |
| 57 | + } |
| 58 | + if (assistantMessage != null && !assistantMessage.isBlank()) { |
| 59 | + insertMessage(chatId, "assistant", assistantMessage); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + private void insertMessage(String chatId, String role, String content) { |
| 64 | + jdbc.update( |
| 65 | + """ |
| 66 | + INSERT INTO "Message" (id, "chatId", role, content, "createdAt") |
| 67 | + VALUES (?, ?, ?, ?, NOW()) |
| 68 | + """, |
| 69 | + UUID.randomUUID().toString(), |
| 70 | + chatId, |
| 71 | + role, |
| 72 | + content); |
| 73 | + } |
| 74 | +} |
0 commit comments