71 lines
2.5 KiB
Go
71 lines
2.5 KiB
Go
package dao
|
|
|
|
import (
|
|
"context"
|
|
"model-gateway/consts/public"
|
|
"model-gateway/model/entity"
|
|
|
|
"gitea.redpowerfuture.com/red-future/common/db/gfdb"
|
|
)
|
|
|
|
var ModelErrorMemory = &modelErrorMemoryDao{}
|
|
|
|
type modelErrorMemoryDao struct{}
|
|
|
|
// GetByKey 按记忆键查询(未命中返回 (nil, nil))
|
|
// 错误记忆为全局表:NoTenantId 绕过租户过滤,跨租户共享;r.IsEmpty() 兜底 miss 契约,
|
|
// 避免对空记录 r.Struct(&res) 上浮 sql.ErrNoRows 导致调用方 fail-closed。
|
|
func (d *modelErrorMemoryDao) GetByKey(ctx context.Context, key string) (res *entity.ModelErrorMemory, err error) {
|
|
r, err := gfdb.DB(ctx, public.DbNameModelGateway).Model(ctx, public.TableNameModelErrorMemory).
|
|
NoTenantId(ctx).
|
|
Where(entity.ModelErrorMemoryCol.MemoryKey, key).
|
|
One()
|
|
if err != nil {
|
|
return
|
|
}
|
|
if r.IsEmpty() {
|
|
return nil, nil
|
|
}
|
|
err = r.Struct(&res)
|
|
return
|
|
}
|
|
|
|
// Upsert 存在则更新 retryable/reason/analyzed_by,不存在则插入
|
|
func (d *modelErrorMemoryDao) Upsert(ctx context.Context, m *entity.ModelErrorMemory) (err error) {
|
|
model := gfdb.DB(ctx, public.DbNameModelGateway).Model(ctx, public.TableNameModelErrorMemory)
|
|
// Count 同样全局化:跨租户已存在的记忆键需命中更新分支,而非重复插入
|
|
n, err := model.NoTenantId(ctx).Where(entity.ModelErrorMemoryCol.MemoryKey, m.MemoryKey).Count()
|
|
if err != nil {
|
|
return
|
|
}
|
|
if n > 0 {
|
|
_, err = model.Where(entity.ModelErrorMemoryCol.MemoryKey, m.MemoryKey).Data(map[string]any{
|
|
entity.ModelErrorMemoryCol.Retryable: m.Retryable,
|
|
entity.ModelErrorMemoryCol.Reason: m.Reason,
|
|
entity.ModelErrorMemoryCol.AnalyzedBy: m.AnalyzedBy,
|
|
}).Update()
|
|
return
|
|
}
|
|
_, err = model.Insert(m)
|
|
return
|
|
}
|
|
|
|
// List 分页查询(按 id 倒序);全局表,管理端列表展示所有租户记忆
|
|
func (d *modelErrorMemoryDao) List(ctx context.Context, page, pageSize int) (list []entity.ModelErrorMemory, total int64, err error) {
|
|
model := gfdb.DB(ctx, public.DbNameModelGateway).Model(ctx, public.TableNameModelErrorMemory).NoTenantId(ctx)
|
|
n, err := model.Count()
|
|
if err != nil {
|
|
return
|
|
}
|
|
total = int64(n)
|
|
err = model.Page(page, pageSize).OrderDesc(entity.ModelErrorMemoryCol.Id).Scan(&list)
|
|
return
|
|
}
|
|
|
|
// Delete 按 id 删除(软删除)
|
|
func (d *modelErrorMemoryDao) Delete(ctx context.Context, id int64) (err error) {
|
|
_, err = gfdb.DB(ctx, public.DbNameModelGateway).Model(ctx, public.TableNameModelErrorMemory).
|
|
Where(entity.ModelErrorMemoryCol.Id, id).Delete()
|
|
return
|
|
}
|