2026-05-02 13:02:38 +08:00

65 lines
1.7 KiB
Go
Raw Permalink 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.

// 本包保存 user-service MySQL 子存储之间复用的低层工具。
package shared
import (
"context"
"database/sql"
"errors"
"strings"
mysqldriver "github.com/go-sql-driver/mysql"
"hyapp/pkg/xerr"
)
// Queryer 抽象 *sql.DB 和 *sql.Tx 的单行查询能力,便于同一 helper 服务普通查询和事务查询。
type Queryer interface {
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
// NullableString 统一把空字符串写成 SQL NULL避免空值参与唯一性或审计语义。
func NullableString(value string) any {
if strings.TrimSpace(value) == "" {
return nil
}
return value
}
// NullableOperator 让系统修改短号或主数据时可以不携带操作者。
func NullableOperator(operatorUserID int64) any {
if operatorUserID <= 0 {
return nil
}
return operatorUserID
}
// NullableRegionID 统一把无区域归属写成 SQL NULL查询投影再转换回 0。
func NullableRegionID(regionID int64) any {
if regionID <= 0 {
return nil
}
return regionID
}
// MapDisplayDuplicateError 把通用 display_user_id 唯一冲突转换成稳定领域 reason。
func MapDisplayDuplicateError(err error) error {
var mysqlErr *mysqldriver.MySQLError
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
return xerr.New(xerr.DisplayUserIDExists, "display_user_id already exists")
}
return err
}
// MapPrettyDuplicateError 把靓号租约相关唯一冲突转换成靓号不可用。
func MapPrettyDuplicateError(err error) error {
var mysqlErr *mysqldriver.MySQLError
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
return xerr.New(xerr.DisplayUserIDPrettyNotAvailable, "pretty display_user_id is not available")
}
return err
}