Documentation
¶
Index ¶
- Constants
- Variables
- func Abs[T Signed](a T) T
- func AbsFloat(a float64) float64
- func AbsInt(a int) int
- func AbsInt64(a int64) int64
- func ApplyFilters(rows []domain.Row, filters []domain.Filter) ([]domain.Row, error)
- func CaptureStackTrace(skip int) []string
- func CaptureStackTraceWithDepth(skip, maxDepth int) []string
- func Clamp[T Ordered](value, minVal, maxVal T) T
- func CompareValues(a, b interface{}, operator string) (bool, error)
- func CompareValuesForSort(a, b interface{}) int
- func CompareValuesForSortWithCollation(a, b interface{}, collation string) int
- func CompareValuesWithCollation(a, b interface{}, operator, collation string) (bool, error)
- func Contains(s, substr string) bool
- func ContainsSimple(s, substr string) bool
- func ContainsSlice[T comparable](slice []T, item T) bool
- func ContainsSubstring(s, substr string) bool
- func ContainsWord(str, word string) bool
- func ConvertBoolColumnsBasedOnSchema(row domain.Row, tableInfo *domain.TableInfo)
- func DeepCopy(value interface{}) interface{}
- func DefaultIfBlank(s, defaultValue string) string
- func DefaultIfEmpty(s, defaultValue string) string
- func EndsWith(s, suffix string) bool
- func FilterSlice[T any](slice []T, predicate func(T) bool) []T
- func FindSubstring(s, substr string) int
- func GenerateHashedPassword(password string) string
- func GeneratePasswordHash(password string, salt []byte) string
- func GetCallerFunction(skip int) string
- func GetCallerInfo(skip int) (function, file string, line int)
- func GetCharsetID(charsetName string) uint8
- func GetCharsetName(charsetID uint8) string
- func IndexOfSubstring(s, substr string) int
- func IsAcquireTimeout(err error) bool
- func IsBlank(s string) bool
- func IsEmpty(s string) bool
- func IsNotBlank(s string) bool
- func IsNotEmpty(s string) bool
- func IsPoolClosed(err error) bool
- func IsPoolEmpty(err error) bool
- func JoinWith(strs []string, sep string) string
- func MapErrorCode(err error) (uint16, string)
- func MapKeys[K comparable, V any](m map[K]V) []K
- func MapOperator(parserOp string) string
- func MapSlice[T, U any](slice []T, transform func(T) U) []U
- func MapValues[K comparable, V any](m map[K]V) []V
- func MatchesAllSubFilters(row domain.Row, subFilters []domain.Filter) (bool, error)
- func MatchesAnySubFilter(row domain.Row, subFilters []domain.Filter) (bool, error)
- func MatchesFilter(row domain.Row, filter domain.Filter) (bool, error)
- func MatchesLike(value, pattern string) bool
- func MatchesLikeWithCollation(value, pattern, collation string) bool
- func Max[T Ordered](a, b T) T
- func MaxInt(a, b int) int
- func MaxInt64(a, b int64) int64
- func Min[T Ordered](a, b T) T
- func MinInt(a, b int) int
- func MinInt64(a, b int64) int64
- func MustParseFloat64(s string) float64
- func MustParseInt(s string) int
- func MustParseInt64(s string) int64
- func Now() time.Time
- func PadLeft(s string, padChar rune, targetLen int) string
- func PadRight(s string, padChar rune, targetLen int) string
- func ParseBool(s string, defaultValue bool) bool
- func ParseBoolStrict(s string) (bool, error)
- func ParseFloat64(s string, defaultValue float64) float64
- func ParseFloat64Strict(s string) (float64, error)
- func ParseInt(s string, defaultValue int) int
- func ParseInt64(s string, defaultValue int64) int64
- func ParseInt64Strict(s string) (int64, error)
- func ParseIntStrict(s string) (int, error)
- func ParseRemoteAddr(remoteAddr string) (string, string)
- func ParseUint(s string, defaultValue uint) uint
- func ParseUint64(s string, defaultValue uint64) uint64
- func ReplaceAll(s, old, new string) string
- func ResetTimeProvider()
- func Reverse(s string) string
- func ReverseSlice[T any](slice []T)
- func SetTimeProvider(provider TimeProvider)
- func Since(t time.Time) time.Duration
- func Sleep(d time.Duration)
- func SortedKeys[K Ordered, V any](m map[K]V) []K
- func SortedStringKeys[V any](m map[string]V) []string
- func StartsWith(s, prefix string) bool
- func ToFloat64(arg interface{}) (float64, error)
- func ToInt(arg interface{}) (int, error)
- func ToInt64(arg interface{}) (int64, error)
- func ToLowerCase(s string) string
- func ToString(v interface{}) string
- func TrimPrefix(s, prefix string) string
- func TrimSpace(s string) string
- func TrimSuffix(s, suffix string) string
- func Truncate(s string, maxLen int) string
- func TruncateWithEllipsis(s string, maxLen int, ellipsis string) string
- func UniqueInt64s(slice []int64) []int64
- func UniqueInts(slice []int) []int
- func UniqueStrings(slice []string) []string
- func Until(t time.Time) time.Duration
- func VerifyPassword(storedHash string, password string, authResponse []byte, salt []byte) bool
- func VerifyPasswordWithHash(storedHash, password string) bool
- type CollationEngine
- func (e *CollationEngine) Compare(a, b string, collationName string) (int, error)
- func (e *CollationEngine) GetCollationInfo(name string) (*CollationInfo, bool)
- func (e *CollationEngine) IsAccentInsensitive(collationName string) bool
- func (e *CollationEngine) IsCaseInsensitive(collationName string) bool
- func (e *CollationEngine) ListCollations() []*CollationInfo
- func (e *CollationEngine) ResolveCollation(name string) string
- func (e *CollationEngine) SortKey(s string, collationName string) ([]byte, error)
- type CollationInfo
- type FixedTimeProvider
- func (p *FixedTimeProvider) Add(d time.Duration)
- func (p *FixedTimeProvider) Now() time.Time
- func (p *FixedTimeProvider) SetTime(t time.Time)
- func (p *FixedTimeProvider) Since(t time.Time) time.Duration
- func (p *FixedTimeProvider) Sleep(d time.Duration)
- func (p *FixedTimeProvider) Until(t time.Time) time.Duration
- type MockTimeProvider
- func (p *MockTimeProvider) Add(d time.Duration)
- func (p *MockTimeProvider) Now() time.Time
- func (p *MockTimeProvider) SetSleepHook(hook func(d time.Duration))
- func (p *MockTimeProvider) SetTime(t time.Time)
- func (p *MockTimeProvider) Since(t time.Time) time.Duration
- func (p *MockTimeProvider) Sleep(d time.Duration)
- func (p *MockTimeProvider) Until(t time.Time) time.Duration
- type Ordered
- type PoolError
- type Signed
- type SystemTimeProvider
- type TimeProvider
Examples ¶
Constants ¶
const ( // 常用字符集编号 CharsetBig5ChineseCI = 1 // big5_chinese_ci CharsetLatin2CzechCS = 2 // latin2_czech_cs CharsetDec8SwedishCI = 3 // dec8_swedish_ci CharsetCp850GeneralCI = 4 // cp850_general_ci CharsetLatin1German1CI = 5 // latin1_german1_ci CharsetHp8EnglishCI = 6 // hp8_english_ci CharsetKoi8rGeneralCI = 7 // koi8r_general_ci CharsetLatin1SwedishCI = 8 // latin1_swedish_ci CharsetLatin2GeneralCI = 9 // latin2_general_ci CharsetSwe7SwedishCI = 10 // swe7_swedish_ci CharsetAsciiGeneralCI = 11 // ascii_general_ci CharsetUjisJapaneseCI = 12 // ujis_japanese_ci CharsetSjisJapaneseCI = 13 // sjis_japanese_ci CharsetCp1251BulgarianCI = 14 // cp1251_bulgarian_ci CharsetLatin1DanishCI = 15 // latin1_danish_ci CharsetHebrewGeneralCI = 16 // hebrew_general_ci CharsetTis620ThaiCI = 18 // tis620_thai_ci CharsetEuckrKoreanCI = 19 // euckr_korean_ci CharsetLatin7EstonianCS = 20 // latin7_estonian_cs CharsetLatin2HungarianCI = 21 // latin2_hungarian_ci CharsetKoi8uGeneralCI = 22 // koi8u_general_ci CharsetCp1251UkrainianCI = 23 // cp1251_ukrainian_ci CharsetGb2312ChineseCI = 24 // gb2312_chinese_ci CharsetGreekGeneralCI = 25 // greek_general_ci CharsetCp1250GeneralCI = 26 // cp1250_general_ci CharsetLatin2CroatianCI = 27 // latin2_croatian_ci CharsetGbkChineseCI = 28 // gbk_chinese_ci CharsetCp1257LithuanianCI = 29 // cp1257_lithuanian_ci CharsetLatin5TurkishCI = 30 // latin5_turkish_ci CharsetLatin1German2CI = 31 // latin1_german2_ci CharsetArmscii8GeneralCI = 32 // armscii8_general_ci CharsetUtf8GeneralCI = 33 // utf8_general_ci (utf8) CharsetUtf8mb4GeneralCI = 45 // utf8mb4_general_ci (utf8mb4) CharsetUtf8mb4Bin = 46 // utf8mb4_bin CharsetLatin1SpanishCI = 47 // latin1_spanish_ci CharsetCp1256GeneralCI = 57 // cp1256_general_ci CharsetCp866GeneralCI = 58 // cp866_general_ci CharsetKeybcs2GeneralCI = 59 // keybcs2_general_ci CharsetMacceGeneralCI = 60 // macce_general_ci CharsetMacromanGeneralCI = 61 // macroman_general_ci CharsetCp852GeneralCI = 62 // cp852_general_ci CharsetLatin7GeneralCI = 63 // latin7_general_ci CharsetLatin7GeneralCS = 64 // latin7_general_cs CharsetMacceBin = 65 // macce_bin CharsetCp1250CroatianCI = 66 // cp1250_croatian_ci CharsetUtf8mb4UnicodeCI = 224 // utf8mb4_unicode_ci CharsetUtf8mb4IcelandicCI = 225 // utf8mb4_icelandic_ci CharsetUtf8mb4LatvianCI = 226 // utf8mb4_latvian_ci CharsetUtf8mb4RomanianCI = 227 // utf8mb4_romanian_ci CharsetUtf8mb4SlovenianCI = 228 // utf8mb4_slovenian_ci CharsetUtf8mb4PolishCI = 229 // utf8mb4_polish_ci CharsetUtf8mb4EstonianCI = 230 // utf8mb4_estonian_ci CharsetUtf8mb4SpanishCI = 231 // utf8mb4_spanish_ci CharsetUtf8mb4SwedishCI = 232 // utf8mb4_swedish_ci CharsetUtf8mb4TurkishCI = 233 // utf8mb4_turkish_ci CharsetUtf8mb4CzechCI = 234 // utf8mb4_czech_ci CharsetUtf8mb4DanishCI = 235 // utf8mb4_danish_ci CharsetUtf8mb4LithuanianCI = 236 // utf8mb4_lithuanian_ci CharsetUtf8mb4SlovakCI = 237 // utf8mb4_slovak_ci CharsetUtf8mb4Spanish2CI = 238 // utf8mb4_spanish2_ci CharsetUtf8mb4RomanCI = 239 // utf8mb4_roman_ci CharsetUtf8mb4PersianCI = 240 // utf8mb4_persian_ci CharsetUtf8mb4EsperantoCI = 241 // utf8mb4_esperanto_ci CharsetUtf8mb4HungarianCI = 242 // utf8mb4_hungarian_ci CharsetUtf8mb4SinhalaCI = 243 // utf8mb4_sinhala_ci CharsetUtf8mb4German2CI = 244 // utf8mb4_german2_ci CharsetUtf8mb4CroatianCI = 245 // utf8mb4_croatian_ci CharsetUtf8mb4Unicode520CI = 246 // utf8mb4_unicode_520_ci CharsetUtf8mb4VietnameseCI = 247 // utf8mb4_vietnamese_ci CharsetUtf8mb40900AICi = 255 // utf8mb4_0900_ai_ci (MySQL 8.0默认) )
const ( // UTF-8相关 CharsetUtf8 = CharsetUtf8GeneralCI // utf8 (3字节) CharsetUtf8mb4 = CharsetUtf8mb4GeneralCI // utf8mb4 (4字节,推荐) // 默认字符集 CharsetDefault = CharsetUtf8mb40900AICi // MySQL 8.0默认字符集 // 中文相关 CharsetGBK = CharsetGbkChineseCI // gbk CharsetGb2312 = CharsetGb2312ChineseCI // gb2312 CharsetBIG5 = CharsetBig5ChineseCI // big5 // 日文相关 CharsetSjis = CharsetSjisJapaneseCI // sjis CharsetUjis = CharsetUjisJapaneseCI // ujis // 韩文相关 CharsetEuckr = CharsetEuckrKoreanCI // euckr // 其他常用 CharsetLatin1 = CharsetLatin1SwedishCI // latin1 CharsetAscii = CharsetAsciiGeneralCI // ascii )
常用字符集别名
const ( // Table errors ErrNoSuchTable = 1146 // ER_NO_SUCH_TABLE ErrBadFieldError = 1054 // ER_BAD_FIELD_ERROR // Query errors ErrParseError = 1064 // ER_PARSE_ERROR ErrEmptyQuery = 1065 // ER_EMPTY_QUERY ErrInterrupted = 1317 // ER_QUERY_INTERRUPTED // SQL状态码 SqlStateNoSuchTable = "42S02" // Table does not exist SqlStateBadFieldError = "42S22" // Column does not exist SqlStateSyntaxError = "42000" // Syntax error or access violation SqlStateUnknownError = "HY000" // General error )
MySQL错误码常量定义
Variables ¶
var ( // ErrPoolClosed indicates that the pool has been closed ErrPoolClosed = errors.New("pool is closed") // ErrPoolEmpty indicates that the pool has no available resources ErrPoolEmpty = errors.New("pool is empty") // ErrPoolFull indicates that the pool has reached its maximum capacity ErrPoolFull = errors.New("pool is full") // ErrInvalidConfig indicates that the pool configuration is invalid ErrInvalidConfig = errors.New("invalid pool configuration") // ErrResourceClosed indicates that the resource has been closed ErrResourceClosed = errors.New("resource is closed") // ErrAcquireTimeout indicates that acquiring a resource timed out ErrAcquireTimeout = errors.New("acquire timeout") // ErrMaxRetries indicates that max retries have been exceeded ErrMaxRetries = errors.New("max retries exceeded") )
Common pool errors
Functions ¶
func ApplyFilters ¶
ApplyFilters applies filters to result rows
func CaptureStackTrace ¶
CaptureStackTrace captures the current call stack trace skip indicates how many callers to skip (0 = include CaptureStackTrace itself)
func CaptureStackTraceWithDepth ¶
CaptureStackTraceWithDepth captures the call stack with a custom maximum depth
func Clamp ¶
func Clamp[T Ordered](value, minVal, maxVal T) T
Clamp constrains a value to be within a range [min, max]
func CompareValues ¶
CompareValues compares two values with given operator Returns true if comparison matches, false otherwise
Example ¶
// 数值比较 result, _ := CompareValues(10, 5, ">") fmt.Println(result)
Output: true
func CompareValuesForSort ¶
func CompareValuesForSort(a, b interface{}) int
CompareValuesForSort compares two values for sorting Returns -1: a < b, 0: a == b, 1: a > b
func CompareValuesForSortWithCollation ¶
CompareValuesForSortWithCollation compares two values for sorting with collation. When collation is empty or binary, falls back to byte-level comparison.
func CompareValuesWithCollation ¶
CompareValuesWithCollation compares two values with given operator and collation. When collation is empty or "utf8mb4_bin", falls back to byte-level comparison.
func ContainsSlice ¶
func ContainsSlice[T comparable](slice []T, item T) bool
ContainsSlice checks if a slice contains a specific element
func ContainsSubstring ¶
ContainsSubstring 检查字符串是否包含子串
func ContainsWord ¶
ContainsWord checks if word exists in string as independent word
func ConvertBoolColumnsBasedOnSchema ¶ added in v0.3.0
ConvertBoolColumnsBasedOnSchema converts numeric values to bool for BOOL/BOOLEAN/TINYINT columns This is used for GORM compatibility as MySQL BOOLEAN is an alias for TINYINT(1) and TiDB parser converts BOOLEAN to tinyint
func DeepCopy ¶
func DeepCopy(value interface{}) interface{}
DeepCopy creates a deep copy of basic types (primitive values, slices, maps) For complex types, use json.Marshal/Unmarshal or implement custom copying
func DefaultIfBlank ¶
DefaultIfBlank returns the default value if the string is blank (empty or whitespace)
func DefaultIfEmpty ¶
DefaultIfEmpty returns the default value if the string is empty
func FilterSlice ¶
FilterSlice filters a slice based on a predicate function
func FindSubstring ¶
FindSubstring finds substring position (returns character index for Unicode support)
func GenerateHashedPassword ¶
GenerateHashedPassword 生成存储在数据库中的哈希密码 这是mysql.user表中的存储格式 格式: *SHA1(SHA1(password))
Example ¶
hash := GenerateHashedPassword("mypassword")
fmt.Println(len(hash))
fmt.Println(hash[:10])
Output: 41 *fabe5482d
func GeneratePasswordHash ¶
GeneratePasswordHash 生成MySQL native password hash Algorithm: SHA1(SHA1(password)) ^ SHA1(salt + SHA1(SHA1(password))) 用于MySQL认证协议
func GetCallerFunction ¶
GetCallerFunction returns the name of the calling function
func GetCallerInfo ¶
GetCallerInfo returns information about the caller at the specified skip level skip=0 returns the caller of GetCallerInfo
func GetCharsetID ¶
GetCharsetID 根据字符集名称获取字符集编号
Example ¶
id := GetCharsetID("utf8mb4_general_ci")
fmt.Println(id)
id2 := GetCharsetID("utf8")
fmt.Println(id2)
id3 := GetCharsetID("")
fmt.Println(id3)
Output: 45 33 255
func GetCharsetName ¶
GetCharsetName 根据字符集编号获取字符集名称
Example ¶
name := GetCharsetName(CharsetUtf8mb4) fmt.Println(name) name2 := GetCharsetName(CharsetUtf8) fmt.Println(name2) name3 := GetCharsetName(0) fmt.Println(name3)
Output: utf8mb4_general_ci utf8_general_ci unknown
func IndexOfSubstring ¶
IndexOfSubstring 查找子串位置(按字符索引,支持Unicode)
func IsAcquireTimeout ¶
IsAcquireTimeout checks if the error is ErrAcquireTimeout
func IsNotBlank ¶
IsNotBlank checks if a string is not empty and not just whitespace
func IsPoolClosed ¶
IsPoolClosed checks if the error is ErrPoolClosed
func MapErrorCode ¶
MapErrorCode 将错误映射到MySQL错误码和SQL状态码 返回 (errorCode, sqlState)
Example ¶
// 表不存在错误
err := errors.New("table 'users' not found")
code, state := MapErrorCode(err)
fmt.Printf("Code: %d, State: %s\n", code, state)
// 列不存在错误
err2 := errors.New("column 'name' not found")
code2, state2 := MapErrorCode(err2)
fmt.Printf("Code: %d, State: %s\n", code2, state2)
// 语法错误
err3 := errors.New("syntax error near 'from'")
code3, state3 := MapErrorCode(err3)
fmt.Printf("Code: %d, State: %s\n", code3, state3)
// 超时错误
code4, state4 := MapErrorCode(context.DeadlineExceeded)
fmt.Printf("Code: %d, State: %s\n", code4, state4)
Output: Code: 1146, State: 42S02 Code: 1054, State: 42S22 Code: 1064, State: 42000 Code: 1317, State: HY000
func MapKeys ¶
func MapKeys[K comparable, V any](m map[K]V) []K
MapKeys returns all keys of a map as a slice
func MapOperator ¶
MapOperator 映射parser操作符到标准操作符 支持的parser操作符: gt, gte, lt, lte, eq, ne, ===, !=, like, not like 返回标准SQL操作符: >, >=, <, <=, =, !=, LIKE, NOT LIKE
func MapSlice ¶
func MapSlice[T, U any](slice []T, transform func(T) U) []U
MapSlice transforms each element of a slice using a function
func MapValues ¶
func MapValues[K comparable, V any](m map[K]V) []V
MapValues returns all values of a map as a slice
func MatchesAllSubFilters ¶
MatchesAllSubFilters checks if a row matches all sub-filters (AND logic) Returns error immediately if any filter fails with an error
func MatchesAnySubFilter ¶
MatchesAnySubFilter checks if a row matches any sub-filter (OR logic) Returns the first error encountered, but continues matching
func MatchesFilter ¶
MatchesFilter checks if a row matches a filter
func MatchesLike ¶
MatchesLike implements SQL LIKE pattern matching. Supports: % (match any sequence of characters), _ (match any single character). Uses a segment-based algorithm: splits the pattern by '%', then matches each literal segment in order. O(n*k) where k = number of segments.
func MatchesLikeWithCollation ¶
MatchesLikeWithCollation performs LIKE matching with collation awareness. For _ci collations, folds both value and pattern to lowercase before matching. For _ai_ci collations, additionally strips accents via NFD decomposition.
func MustParseFloat64 ¶
MustParseFloat64 parses a string to float64, panics on error
func MustParseInt ¶
MustParseInt parses a string to int, panics on error
func MustParseInt64 ¶
MustParseInt64 parses a string to int64, panics on error
func PadLeft ¶
PadLeft pads a string on the left with a specified character to reach the target length
func PadRight ¶
PadRight pads a string on the right with a specified character to reach the target length
func ParseBool ¶
ParseBool parses a string to bool, returns default value on error Accepts "1", "t", "T", "true", "TRUE", "True" as true Accepts "0", "f", "F", "false", "FALSE", "False" as false
func ParseBoolStrict ¶
ParseBoolStrict parses a string to bool, returns error on failure
func ParseFloat64 ¶
ParseFloat64 parses a string to float64, returns default value on error
func ParseFloat64Strict ¶
ParseFloat64Strict parses a string to float64, returns error on failure
func ParseInt64 ¶
ParseInt64 parses a string to int64, returns default value on error
func ParseInt64Strict ¶
ParseInt64Strict parses a string to int64, returns error on failure
func ParseIntStrict ¶
ParseIntStrict parses a string to int, returns error on failure
func ParseRemoteAddr ¶
ParseRemoteAddr parses remote address in format "ip:port" or "[ipv6]:port" Returns (ip, port)
Example ¶
// IPv4 地址
ip, port := ParseRemoteAddr("192.168.1.1:3306")
fmt.Println("IP:", ip, "Port:", port)
// 域名地址
ip2, port2 := ParseRemoteAddr("localhost:3306")
fmt.Println("IP:", ip2, "Port:", port2)
Output: IP: 192.168.1.1 Port: 3306 IP: localhost Port: 3306
func ParseUint64 ¶
ParseUint64 parses a string to uint64, returns default value on error
func ReplaceAll ¶
ReplaceAll replaces all occurrences of old with new in string s
func ResetTimeProvider ¶
func ResetTimeProvider()
ResetTimeProvider resets to the system time provider
func SetTimeProvider ¶
func SetTimeProvider(provider TimeProvider)
SetTimeProvider sets the default time provider (useful for testing)
func SortedKeys ¶
SortedKeys returns the keys of a map sorted in ascending order
func SortedStringKeys ¶
SortedStringKeys returns the string keys of a map sorted in ascending order
func ToFloat64 ¶
ToFloat64 converts a value to float64
Example ¶
result, _ := ToFloat64(42)
fmt.Println(result)
result2, _ := ToFloat64("3.14")
fmt.Println(result2)
result3, _ := ToFloat64(int32(10))
fmt.Println(result3)
result4, err := ToFloat64("hello")
fmt.Println(result4, err)
Output: 42 3.14 10 0 cannot convert string to float64
func ToInt64 ¶
ToInt64 converts a value to int64
Example ¶
result, _ := ToInt64(42.7)
fmt.Println(result)
result2, _ := ToInt64(int32(100))
fmt.Println(result2)
result3, err := ToInt64("hello")
fmt.Println(result3, err)
Output: 42 100 0 cannot convert string to int64
func ToString ¶
func ToString(v interface{}) string
ToString converts any value to string
Example ¶
// 字符串转换
result := ToString("hello")
fmt.Println(result)
result2 := ToString(42)
fmt.Println(result2)
result3 := ToString(3.14)
fmt.Println(result3)
result4 := ToString(true)
fmt.Println(result4)
Output: hello 42 3.14 true
func TrimPrefix ¶
TrimPrefix removes a prefix from a string if present
func TrimSuffix ¶
TrimSuffix removes a suffix from a string if present
func Truncate ¶
Truncate truncates a string to the specified maximum length If the string is longer than maxLen, it returns the first maxLen characters with "..." appended If maxLen <= 3, returns the first maxLen characters without ellipsis
func TruncateWithEllipsis ¶
TruncateWithEllipsis truncates a string with custom ellipsis
func UniqueInt64s ¶
UniqueInt64s removes duplicate int64 from a slice
func UniqueInts ¶
UniqueInts removes duplicate integers from a slice
func UniqueStrings ¶
UniqueStrings removes duplicate strings from a slice
func VerifyPassword ¶
VerifyPassword 验证密码 参数:
- storedHash: 存储的密码哈希
- password: 待验证的明文密码
- authResponse: 客户端发送的认证响应
- salt: salt数据
返回: 密码是否匹配
func VerifyPasswordWithHash ¶
VerifyPasswordWithHash 仅验证密码是否匹配存储的哈希 用于测试和直接密码验证
Example ¶
hash := GenerateHashedPassword("mypassword")
result := VerifyPasswordWithHash(hash, "mypassword")
fmt.Println(result)
result2 := VerifyPasswordWithHash(hash, "wrongpassword")
fmt.Println(result2)
Output: true false
Types ¶
type CollationEngine ¶
type CollationEngine struct {
// contains filtered or unexported fields
}
CollationEngine provides locale-aware string comparison and sort key generation. It maps MySQL collation names to golang.org/x/text/collate configurations. Collator instances are created per-call because they are NOT goroutine-safe.
func GetGlobalCollationEngine ¶
func GetGlobalCollationEngine() *CollationEngine
GetGlobalCollationEngine returns the global CollationEngine singleton.
func NewCollationEngine ¶
func NewCollationEngine() *CollationEngine
NewCollationEngine creates a new CollationEngine with the supported collation registry.
func (*CollationEngine) Compare ¶
func (e *CollationEngine) Compare(a, b string, collationName string) (int, error)
Compare compares two strings using the specified collation. Returns -1, 0, or 1.
func (*CollationEngine) GetCollationInfo ¶
func (e *CollationEngine) GetCollationInfo(name string) (*CollationInfo, bool)
GetCollationInfo returns metadata for a collation, or (nil, false) if unknown.
func (*CollationEngine) IsAccentInsensitive ¶
func (e *CollationEngine) IsAccentInsensitive(collationName string) bool
IsAccentInsensitive returns true if the named collation is accent-insensitive.
func (*CollationEngine) IsCaseInsensitive ¶
func (e *CollationEngine) IsCaseInsensitive(collationName string) bool
IsCaseInsensitive returns true if the named collation is case-insensitive.
func (*CollationEngine) ListCollations ¶
func (e *CollationEngine) ListCollations() []*CollationInfo
ListCollations returns all registered collations.
func (*CollationEngine) ResolveCollation ¶
func (e *CollationEngine) ResolveCollation(name string) string
ResolveCollation normalizes a collation name, resolving aliases and case differences. Returns the canonical collation name.
type CollationInfo ¶
type CollationInfo struct {
Name string
ID uint8
Charset string
Tag language.Tag
CaseInsensitive bool
AccentInsensitive bool
IsBinary bool
// contains filtered or unexported fields
}
CollationInfo describes a collation's properties
type FixedTimeProvider ¶
type FixedTimeProvider struct {
// contains filtered or unexported fields
}
FixedTimeProvider returns a fixed time for testing purposes.
func NewFixedTimeProvider ¶
func NewFixedTimeProvider(fixedTime time.Time) *FixedTimeProvider
NewFixedTimeProvider creates a provider that always returns the given time
func (*FixedTimeProvider) Add ¶
func (p *FixedTimeProvider) Add(d time.Duration)
Add advances the fixed time by the given duration
func (*FixedTimeProvider) Now ¶
func (p *FixedTimeProvider) Now() time.Time
Now returns the fixed time
func (*FixedTimeProvider) SetTime ¶
func (p *FixedTimeProvider) SetTime(t time.Time)
SetTime allows updating the fixed time (useful for advancing time in tests)
func (*FixedTimeProvider) Since ¶
func (p *FixedTimeProvider) Since(t time.Time) time.Duration
Since returns the duration since the fixed time
func (*FixedTimeProvider) Sleep ¶
func (p *FixedTimeProvider) Sleep(d time.Duration)
Sleep does nothing in the fixed time provider
type MockTimeProvider ¶
type MockTimeProvider struct {
// contains filtered or unexported fields
}
MockTimeProvider allows full control over time for testing.
func NewMockTimeProvider ¶
func NewMockTimeProvider() *MockTimeProvider
NewMockTimeProvider creates a new mock time provider
func (*MockTimeProvider) Add ¶
func (p *MockTimeProvider) Add(d time.Duration)
Add advances the mock time by the given duration
func (*MockTimeProvider) Now ¶
func (p *MockTimeProvider) Now() time.Time
Now returns the mock current time
func (*MockTimeProvider) SetSleepHook ¶
func (p *MockTimeProvider) SetSleepHook(hook func(d time.Duration))
SetSleepHook sets a custom function to be called on Sleep
func (*MockTimeProvider) SetTime ¶
func (p *MockTimeProvider) SetTime(t time.Time)
SetTime sets the mock current time
func (*MockTimeProvider) Since ¶
func (p *MockTimeProvider) Since(t time.Time) time.Duration
Since returns the duration since t
func (*MockTimeProvider) Sleep ¶
func (p *MockTimeProvider) Sleep(d time.Duration)
Sleep calls the sleep hook if set, otherwise advances time
type Ordered ¶
type Ordered interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64 |
~string
}
Ordered is a constraint that permits any ordered type.
type PoolError ¶
PoolError represents a pool-related error with additional context
func NewPoolError ¶
NewPoolError creates a new PoolError
type SystemTimeProvider ¶
type SystemTimeProvider struct{}
SystemTimeProvider is the default implementation using real system time.
func NewSystemTimeProvider ¶
func NewSystemTimeProvider() *SystemTimeProvider
NewSystemTimeProvider creates a new SystemTimeProvider
func (*SystemTimeProvider) Now ¶
func (p *SystemTimeProvider) Now() time.Time
Now returns the current system time
func (*SystemTimeProvider) Since ¶
func (p *SystemTimeProvider) Since(t time.Time) time.Duration
Since returns the time elapsed since t
func (*SystemTimeProvider) Sleep ¶
func (p *SystemTimeProvider) Sleep(d time.Duration)
Sleep pauses the current goroutine for at least the duration d
type TimeProvider ¶
type TimeProvider interface {
// Now returns the current time
Now() time.Time
// Since returns the time elapsed since t
Since(t time.Time) time.Duration
// Until returns the duration until t
Until(t time.Time) time.Duration
// Sleep pauses the current goroutine for at least the duration d
Sleep(d time.Duration)
}
TimeProvider defines an interface for time-related operations. This abstraction allows for easier testing by enabling time injection.
func GetTimeProvider ¶
func GetTimeProvider() TimeProvider
GetTimeProvider returns the default time provider