Files
backend_v2/internal/repository/translate_repository.go
toom1996 1b06bd5bda update
2026-09-30 11:58:32 +08:00

58 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package repository
import (
"context"
"errors"
"time"
"gorm.io/gorm"
)
// TitleCnMemory 翻译记忆表行(title_cn_memory)。
type TitleCnMemory struct {
TitleEn string `gorm:"primaryKey;column:title_en"`
TitleCn string `gorm:"column:title_cn"`
UpdatedAt uint32 `gorm:"column:updated_at"`
}
// TableName 指定记忆表名。
func (TitleCnMemory) TableName() string { return "title_cn_memory" }
// TranslateRepository 标题翻译记忆的读写接口。
type TranslateRepository interface {
// GetTitleCnMemory 取某英文标题的人工中文翻译;不存在返回 (_, false, nil)。
GetTitleCnMemory(ctx context.Context, titleEn string) (string, bool, error)
// UpsertTitleCnMemory 幂等写入/更新一条映射。
UpsertTitleCnMemory(ctx context.Context, titleEn, titleCn string) error
}
type translateRepository struct {
db *gorm.DB
}
// NewTranslateRepository 创建翻译记忆仓储。
func NewTranslateRepository(db *gorm.DB) TranslateRepository {
return &translateRepository{db: db}
}
func (r *translateRepository) GetTitleCnMemory(ctx context.Context, titleEn string) (string, bool, error) {
var row TitleCnMemory
err := r.db.WithContext(ctx).Where("title_en = ?", titleEn).First(&row).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return "", false, nil
}
return "", false, err
}
return row.TitleCn, true, nil
}
func (r *translateRepository) UpsertTitleCnMemory(ctx context.Context, titleEn, titleCn string) error {
now := uint32(time.Now().Unix())
row := TitleCnMemory{TitleEn: titleEn, TitleCn: titleCn, UpdatedAt: now}
return r.db.WithContext(ctx).
Where("title_en = ?", titleEn).
Assign(TitleCnMemory{TitleCn: titleCn, UpdatedAt: now}).
FirstOrCreate(&row).Error
}