diff --git a/database/query/option.go b/database/query/option.go index 369069b..647d42c 100644 --- a/database/query/option.go +++ b/database/query/option.go @@ -287,19 +287,15 @@ func WithOR(orConditionList ...SetOption) SetOption { // 返回: // - 返回值 1:当前查询或协议操作的结果。 func WithOrder(orderRuleList ...string) SetOption { + order := append([]string(nil), orderRuleList...) + if len(order) == 2 && order[1] == "" { + order[1] = "DESC" + } return func(o *Option) { - if len(orderRuleList) != 2 { + if len(order) != 2 || order[0] == "" { return } - if len(orderRuleList[0]) == 0 { - - return - } - if len(orderRuleList[1]) == 0 { - - orderRuleList[1] = "DESC" - } - o.Order = orderRuleList + o.Order = append([]string(nil), order...) } } @@ -351,8 +347,8 @@ func WithBetween(field string, left any, right any) SetOption { // 返回: // - 返回值 1:当前查询或协议操作的结果。 func WithLockingStrength(lockingStrength string) SetOption { + lockingStrength = strings.ToUpper(lockingStrength) return func(o *Option) { - lockingStrength = strings.ToUpper(lockingStrength) if lockingStrength != clause.LockingStrengthUpdate && lockingStrength != clause.LockingStrengthShare && lockingStrength != clause.LockingOptionsSkipLocked && lockingStrength != clause.LockingOptionsNoWait { return diff --git a/database/query/reuse_test.go b/database/query/reuse_test.go new file mode 100644 index 0000000..6b2632a --- /dev/null +++ b/database/query/reuse_test.go @@ -0,0 +1,34 @@ +package query + +import ( + "sync" + "testing" +) + +func TestOptionsCanBeReusedWithoutChangingOrderInput(t *testing.T) { + input := []string{"id", ""} + order, lock := WithOrder(input...), WithLockingStrength("update") + var ( + wait sync.WaitGroup + ) + for range 20 { + wait.Go(func() { + option := &Option{} + order(option) + lock(option) + if len(option.Order) != 2 || option.Order[1] != "DESC" || option.LockingStrength != "UPDATE" { + t.Error("option behavior changed") + } + option.Order[0] = "only-this-call" + }) + } + wait.Wait() + if input[0] != "id" || input[1] != "" { + t.Fatalf("input mutated: %v", input) + } + option := &Option{} + order(option) + if option.Order[0] != "id" { + t.Fatal("option results share mutable slices") + } +} diff --git a/docs/getting-started.md b/docs/getting-started.md index eefaca7..3bf651e 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -479,9 +479,9 @@ server.Use(accesslog.New(accesslog.Config{RedactKeys: []string{"config_value"}}, config.Load(path, target, options) 读取文件;config.Decode(content, target, options) 解码应用已经读取的单份 YAML。两者共用目标检查和解码实现,默认展开现有环境变量、拒绝未知字段与多份文档。Decode 不修改或缓存输入字节、不读取文件、不设置环境;失败可能写入部分 target,调用方应丢弃结果。应用需要先宽松预读再严格解码时应重用同一字节快照、为每次解码提供新目标;已展开的内容需显式 DisableEnvExpansion:true,避免二次展开。未新增格式注册、文件缓存或热更新;.env 顺序、业务默认值和 JSON/TOML 适配仍由应用负责。 -可选 database/query 提供 BaseDao[T,C]、Model[C]、ListTarget[T]、NewListTarget 和 SetOption/Option。T 必须在编译期提供 TableName 与 Columns;调用方必须传入非 nil 的 *gorm.DB 或事务及有效结果接收指针;选项及其捕获的 map/slice 在执行期间不得并发修改。库不创建或关闭连接、不自动提交事务、不保存请求条件。List/Detail/Count/Update/Delete 使用独立派生会话,保留调用方 Context 与事务连接,隔离先前查询条件;Create 使用调用方会话创建,遵守原生 GORM 钩子。每个操作失败在源头分类为 CodeCreate/CodeUpdate/CodeList/CodeCount/CodeDelete/CodeDetail,保留 errors.Is/As 和原始 MySQL/GORM 原因,调用方不得用 == 比较包装错误或重复记录同一执行错误。对象不存在、权限与状态冲突的业务码由应用转换。可信诊断通过会话 Context 自动进入日志。 +可选 database/query 提供 BaseDao[T,C]、Model[C]、ListTarget[T]、NewListTarget 和 SetOption/Option。T 必须在编译期提供 TableName 与 Columns;调用方必须传入非 nil 的 *gorm.DB 或事务及有效结果接收指针;选项及其捕获的 map/slice 在执行期间不得并发修改。库不创建或关闭连接、不自动提交事务、不保存请求条件。List/Detail/Count/Update/Delete 使用独立派生会话,保留调用方 Context 与事务连接,隔离先前查询条件;Create 使用调用方会话创建,遵守原生 GORM 钩子。每个操作失败在源头分类为 CodeCreate/CodeUpdate/CodeList/CodeCount/CodeDelete/CodeDetail,保留 errors.Is/As 和原始 MySQL/GORM 原因,调用方不得用 == 比较包装错误或重复记录同一执行错误。对象不存在、权限与状态冲突的业务码由应用转换。GORM 钩子等应用扩展点返回的已分类错误(Code() int,或 Code() any 返回 int)原样传播,不重新包装、覆盖或记录;这类错误由应用源头负责日志。框架其他组件也遵循这一数字场景错误传播约定。可信诊断通过会话 Context 自动进入日志。 -WithSelect、WithModel、WithWhere、WithIn/WithNotIn/WithBatchNotIn、WithStart/WithEnd、WithLike/WithBatchLike、WithNotEqual、WithBetween、WithOR、WithOrder/WithOrderAsc/WithOrderDesc、WithForUpdate/WithLockingStrength、WithBatchSize、WithLimit、WithClearLimit 对应现有查询选项。字段、表名和排序必须由可信调用方通过 Columns 及白名单构造,值由 GORM 绑定;不会为传入的 SQL 片段自动提供安全保证。WithLike 保留包含匹配,不自动转义百分号/下划线;WithOR 的每个调用形成与公共条件相交的 OR 组,不推断复杂业务布尔树。WithForUpdate(false) 不添加锁,也不删除已显式设置的锁;锁语义须在真实事务中使用。 +WithSelect、WithModel、WithWhere、WithIn/WithNotIn/WithBatchNotIn、WithStart/WithEnd、WithLike/WithBatchLike、WithNotEqual、WithBetween、WithOR、WithOrder/WithOrderAsc/WithOrderDesc、WithForUpdate/WithLockingStrength、WithBatchSize、WithLimit、WithClearLimit 对应现有查询选项。字段、表名和排序必须由可信调用方通过 Columns 及白名单构造,值由 GORM 绑定;不会为传入的 SQL 片段自动提供安全保证。WithLike 保留包含匹配,不自动转义百分号/下划线;WithOR 的每个调用形成与公共条件相交的 OR 组,不推断复杂业务布尔树。WithOrder 复制排序切片并在构造时处理缺省方向,WithLockingStrength 在构造时规范化字符串;重复执行选项不改写捕获参数,也不修改传入排序切片。WithForUpdate(false) 不添加锁,也不删除已显式设置的锁;锁语义须在真实事务中使用。 新列表使用业务游标条件、确定性排序和 WithBatchSize;库不实现游标编码或自动分页策略。WithLimit 的原始 offset 仅用于消费方已有契约,库不提供页码换算方法。非正 Limit 不增加数量限制,WithBatchSize 不生成偏移;数量须在业务入口校验。ListAndTotal 不隐式开启事务;需一致快照时传入同一事务。DisableTotal=true 时 Total 是当次结果数量,不是额外全表计数。Update 保留普通指针零值、双指针 NULL 和 GORM 表达式;影响行数、更新范围、审计插件及 GORM 的批量/软删除语义仍由应用和原生模型决定。不得把 UpdateOne 的 LIMIT 当作唯一定位条件,应用必须提供受控定位或状态条件。 diff --git a/internal/failure/error.go b/internal/failure/error.go index c6c6b94..e3d32a8 100644 --- a/internal/failure/error.go +++ b/internal/failure/error.go @@ -3,6 +3,7 @@ package failure import ( "context" + "errors" "git.zhangdeman.cn/zhangdeman/ginframework/fault" "git.zhangdeman.cn/zhangdeman/ginframework/logger" @@ -22,6 +23,20 @@ func WrapContext(ctx context.Context, code int, message string, cause error) err if cause == nil || fault.Internal(cause) { return cause } + // 原生 GORM 钩子等扩展点可能返回应用已经分类的业务错误。 + // 只识别数字场景码,不依赖应用错误类型或把原始错误文案当作分类依据。 + var ( + numeric interface{ Code() int } + flexible interface{ Code() any } + ) + if errors.As(cause, &numeric) { + return cause + } + if errors.As(cause, &flexible) { + if _, ok := flexible.Code().(int); ok { + return cause + } + } result := fault.New(code, message, cause) logger.RecordErrorContext(ctx, message, result) return result diff --git a/internal/failure/error_test.go b/internal/failure/error_test.go new file mode 100644 index 0000000..2f815f1 --- /dev/null +++ b/internal/failure/error_test.go @@ -0,0 +1,33 @@ +package failure + +import ( + "errors" + "fmt" + "testing" + + "git.zhangdeman.cn/zhangdeman/ginframework/fault" +) + +type numericBusinessError struct{} + +func (*numericBusinessError) Error() string { return "private business message" } +func (*numericBusinessError) Code() int { return 1001 } + +type flexibleBusinessError struct{ code any } + +func (*flexibleBusinessError) Error() string { return "private business message" } +func (e *flexibleBusinessError) Code() any { return e.code } + +func TestClassifiedExtensionErrorsPreserveIdentity(t *testing.T) { + for _, cause := range []error{&numericBusinessError{}, &flexibleBusinessError{code: 1002}, fmt.Errorf("callback: %w", &numericBusinessError{}), fmt.Errorf("callback: %w", &flexibleBusinessError{code: 1003})} { + if got := Wrap(901106, "read database record failed", cause); got != cause { + t.Fatal("classified application error was wrapped") + } + } + for _, cause := range []error{&flexibleBusinessError{code: "1002"}, &flexibleBusinessError{}, errors.New("raw driver failure")} { + got := Wrap(901106, "read database record failed", cause) + if !fault.Internal(got) || !errors.Is(got, cause) { + t.Fatal("unclassified cause lost source classification") + } + } +}