Files
nl-im-service/internal/utils/db.go
2026-08-24 15:29:53 +08:00

30 lines
788 B
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 utils
* 作用:数据库相关的通用工具函数
*/
package utils
import (
"errors"
"strings"
"gorm.io/gorm"
)
/**
* IsDuplicateEntryError
* 功能判断是否为唯一索引冲突错误MySQL 错误码 1062
* 为什么需要:依赖唯一索引做并发兜底的写入(如点赞、消息删除记录)
* 需要把"重复插入"当作幂等成功处理。GORM 的 ErrDuplicatedKey 依赖驱动
* Translate 支持,部分配置下返回的是原始 mysql 错误,需按错误文本兜底判断
*/
func IsDuplicateEntryError(err error) bool {
if err == nil {
return false
}
if errors.Is(err, gorm.ErrDuplicatedKey) {
return true
}
return strings.Contains(err.Error(), "Duplicate entry") || strings.Contains(err.Error(), "1062")
}