github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/store/sqlstore/utils.go (about) 1 package sqlstore 2 3 import ( 4 "database/sql" 5 "strconv" 6 "strings" 7 "unicode" 8 9 "github.com/mattermost/gorp" 10 11 "github.com/masterhung0112/hk_server/v5/shared/mlog" 12 ) 13 14 var escapeLikeSearchChar = []string{ 15 "%", 16 "_", 17 } 18 19 func sanitizeSearchTerm(term string, escapeChar string) string { 20 term = strings.Replace(term, escapeChar, "", -1) 21 22 for _, c := range escapeLikeSearchChar { 23 term = strings.Replace(term, c, escapeChar+c, -1) 24 } 25 26 return term 27 } 28 29 // Converts a list of strings into a list of query parameters and a named parameter map that can 30 // be used as part of a SQL query. 31 func MapStringsToQueryParams(list []string, paramPrefix string) (string, map[string]interface{}) { 32 var keys strings.Builder 33 params := make(map[string]interface{}, len(list)) 34 for i, entry := range list { 35 if keys.Len() > 0 { 36 keys.WriteString(",") 37 } 38 39 key := paramPrefix + strconv.Itoa(i) 40 keys.WriteString(":" + key) 41 params[key] = entry 42 } 43 44 return "(" + keys.String() + ")", params 45 } 46 47 // finalizeTransaction ensures a transaction is closed after use, rolling back if not already committed. 48 func finalizeTransaction(transaction *gorp.Transaction) { 49 // Rollback returns sql.ErrTxDone if the transaction was already closed. 50 if err := transaction.Rollback(); err != nil && err != sql.ErrTxDone { 51 mlog.Error("Failed to rollback transaction", mlog.Err(err)) 52 } 53 } 54 55 // removeNonAlphaNumericUnquotedTerms removes all unquoted words that only contain 56 // non-alphanumeric chars from given line 57 func removeNonAlphaNumericUnquotedTerms(line, separator string) string { 58 words := strings.Split(line, separator) 59 filteredResult := make([]string, 0, len(words)) 60 61 for _, w := range words { 62 if isQuotedWord(w) || containsAlphaNumericChar(w) { 63 filteredResult = append(filteredResult, strings.TrimSpace(w)) 64 } 65 } 66 return strings.Join(filteredResult, separator) 67 } 68 69 // containsAlphaNumericChar returns true in case any letter or digit is present, false otherwise 70 func containsAlphaNumericChar(s string) bool { 71 for _, r := range s { 72 if unicode.IsLetter(r) || unicode.IsDigit(r) { 73 return true 74 } 75 } 76 return false 77 } 78 79 // isQuotedWord return true if the input string is quoted, false otherwise. Ex :- 80 // "quoted string" - will return true 81 // unquoted string - will return false 82 func isQuotedWord(s string) bool { 83 if len(s) < 2 { 84 return false 85 } 86 87 return s[0] == '"' && s[len(s)-1] == '"' 88 }