58 lines
1.7 KiB
Go
58 lines
1.7 KiB
Go
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
|
||
}
|