vitess.io/vitess@v0.16.2/go/sqlescape/ids.go (about) 1 /* 2 Copyright 2019 The Vitess Authors. 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 http://www.apache.org/licenses/LICENSE-2.0 7 Unless required by applicable law or agreed to in writing, software 8 distributed under the License is distributed on an "AS IS" BASIS, 9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 See the License for the specific language governing permissions and 11 limitations under the License. 12 */ 13 14 package sqlescape 15 16 import ( 17 "strings" 18 ) 19 20 // EscapeID returns a backticked identifier given an input string. 21 func EscapeID(in string) string { 22 var buf strings.Builder 23 WriteEscapeID(&buf, in) 24 return buf.String() 25 } 26 27 // WriteEscapeID writes a backticked identifier from an input string into buf. 28 func WriteEscapeID(buf *strings.Builder, in string) { 29 // growing by 4 more than the length, gives us room 30 // for guaranteed escaping with backticks on each end, 31 // plus a small amount of room just in case there are 32 // backticks within the symbol that needs to be double 33 // escaped. This is an unlikely edge case. 34 buf.Grow(4 + len(in)) 35 36 buf.WriteByte('`') 37 for i := 0; i < len(in); i++ { 38 buf.WriteByte(in[i]) 39 if in[i] == '`' { 40 buf.WriteByte('`') 41 } 42 } 43 buf.WriteByte('`') 44 } 45 46 // EscapeIDs runs sqlescape.EscapeID() for all entries in the slice. 47 func EscapeIDs(identifiers []string) []string { 48 result := make([]string, len(identifiers)) 49 for i := range identifiers { 50 result[i] = EscapeID(identifiers[i]) 51 } 52 return result 53 } 54 55 // UnescapeID reverses any backticking in the input string. 56 func UnescapeID(in string) string { 57 l := len(in) 58 if l >= 2 && in[0] == '`' && in[l-1] == '`' { 59 return in[1 : l-1] 60 } 61 return in 62 }