feat: Phase 8.1 — 定义 MessageRepository 接口和消息表迁移脚本
This commit is contained in:
40
backend/internal/store/message.go
Normal file
40
backend/internal/store/message.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/hhs/camtalk/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrMessageNotFound 消息不存在。
|
||||||
|
ErrMessageNotFound = errors.New("message not found")
|
||||||
|
)
|
||||||
|
|
||||||
|
// MessageRepository 消息持久化接口。
|
||||||
|
type MessageRepository interface {
|
||||||
|
// SaveMessage 保存一条消息。
|
||||||
|
SaveMessage(ctx context.Context, sessionID string, msg models.Message, tokensUsed int) error
|
||||||
|
|
||||||
|
// GetMessages 获取会话的消息列表(分页,按 created_at 升序)。
|
||||||
|
// beforeID 为 0 时从最新开始查询。
|
||||||
|
GetMessages(ctx context.Context, sessionID string, limit int, beforeID int64) ([]StoredMessage, error)
|
||||||
|
|
||||||
|
// GetLastMessage 获取会话的最后一条消息。
|
||||||
|
GetLastMessage(ctx context.Context, sessionID string) (*StoredMessage, error)
|
||||||
|
|
||||||
|
// GetMessageCount 获取会话的消息总数。
|
||||||
|
GetMessageCount(ctx context.Context, sessionID string) (int, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StoredMessage 持久化消息模型(store 层)。
|
||||||
|
type StoredMessage struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
SessionID string `json:"-"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
TokensUsed int `json:"tokens_used"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
1
backend/migrations/002_messages.down.sql
Normal file
1
backend/migrations/002_messages.down.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS messages;
|
||||||
17
backend/migrations/002_messages.up.sql
Normal file
17
backend/migrations/002_messages.up.sql
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
-- 消息表
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
session_id UUID NOT NULL,
|
||||||
|
role VARCHAR(16) NOT NULL, -- "user" | "assistant" | "system"
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
tokens_used INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 按会话查询消息(分页核心索引)
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_session_id_created_at
|
||||||
|
ON messages(session_id, created_at);
|
||||||
|
|
||||||
|
-- 按会话查询最后一条消息
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_session_id_id_desc
|
||||||
|
ON messages(session_id, id DESC);
|
||||||
Reference in New Issue
Block a user