package core import ( "strings" ) type LikeCondition struct { Field string Pattern string CaseSensitive bool } func Like(field string, pattern string) Condition { return LikeCondition{Field: field, Pattern: pattern, CaseSensitive: true} } func ILike(field string, pattern string) Condition { return LikeCondition{Field: field, Pattern: pattern, CaseSensitive: false} } func (c LikeCondition) Fields() []string { return []string{c.Field} } func (c LikeCondition) Match(row []byte, table *Table) bool { fieldIdx := table.findFieldIndex(c.Field) if fieldIdx < 0 { return false } offset, ok := table.getVersionedOffset(row, fieldIdx) if !ok { return false } fieldInfo := table.Field[fieldIdx] // 读取字符串值; 宽度取列声明的宽度 (含字符串宽度码), 否则宽字符串列会被切短 size := int(fieldInfo.Width()) if size <= 0 || int(offset)+size > len(row) { return false } stored := strings.TrimRight(string(row[offset:int(offset)+size]), "\x00") // 模式匹配 if !c.CaseSensitive { stored = strings.ToLower(stored) pattern := strings.ToLower(c.Pattern) return likeMatch(stored, pattern) } return likeMatch(stored, c.Pattern) } // likeMatch 简单的 LIKE 模式匹配(支持 % 和 _) func likeMatch(str, pattern string) bool { // 将 LIKE 模式转换为简单的通配符匹配 // % 匹配任意字符序列(包括空序列) // _ 匹配任意单个字符 // 简化实现:使用 strings.Contains 处理 % parts := strings.Split(pattern, "%") if len(parts) == 1 { // 没有 %,直接比较 return str == pattern } // 检查前缀 if parts[0] != "" && !strings.HasPrefix(str, parts[0]) { return false } // 检查后缀 if parts[len(parts)-1] != "" && !strings.HasSuffix(str, parts[len(parts)-1]) { return false } // 检查中间部分 current := str if parts[0] != "" { current = current[len(parts[0]):] } for i := 1; i < len(parts); i++ { idx := strings.Index(current, parts[i]) if idx == -1 { return false } current = current[idx+len(parts[i]):] } return true }