go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/analysis/internal/span/util.go (about) 1 // Copyright 2022 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package span 16 17 import ( 18 "bytes" 19 "strings" 20 "text/template" 21 22 "cloud.google.com/go/spanner" 23 24 "go.chromium.org/luci/common/errors" 25 ) 26 27 // GenerateStatement generates a spanner statement from a text template. 28 func GenerateStatement(tmpl *template.Template, name string, input any) (spanner.Statement, error) { 29 sql := &bytes.Buffer{} 30 err := tmpl.ExecuteTemplate(sql, name, input) 31 if err != nil { 32 return spanner.Statement{}, errors.Annotate(err, "failed to generate statement: %s", name).Err() 33 } 34 return spanner.NewStatement(sql.String()), nil 35 } 36 37 // QuoteLike turns a literal string into an escaped like expression. 38 // This means strings like test_name will only match as expected, rather than 39 // also matching test3name. 40 func QuoteLike(value string) string { 41 value = strings.ReplaceAll(value, "\\", "\\\\") 42 value = strings.ReplaceAll(value, "%", "\\%") 43 value = strings.ReplaceAll(value, "_", "\\_") 44 return value 45 }