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