-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlescape.go
64 lines (61 loc) · 1.22 KB
/
sqlescape.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package textutil
import (
"fmt"
"strings"
)
func SQLEscape(tabLen int) func(string) (string, error) {
return func(text string) (string, error) {
sb := strings.Builder{}
sb.WriteRune('\'')
for _, r := range text {
switch r {
case '\'':
sb.WriteString("''")
default:
sb.WriteRune(r)
}
}
sb.WriteRune('\'')
return sb.String(), nil
}
}
func SQLUnescape(tabLen int) func(string) (string, error) {
return func(text string) (string, error) {
text = strings.TrimSuffix(strings.TrimPrefix(text, "'"), "'")
{
// avoid an allocation if we don't need it:
hasQuote := false
for _, c := range []byte(text) {
if c == '\'' {
hasQuote = true
break
}
}
if !hasQuote {
return text, nil
}
}
sb := strings.Builder{}
lastIsQuote := false
for i, r := range text {
switch r {
case '\'':
if !lastIsQuote {
lastIsQuote = true
continue
}
fallthrough
default:
if lastIsQuote && r != '\'' {
return "", fmt.Errorf(
"SQLUnscape:%d: Single quote not followed by another",
i+1,
)
}
sb.WriteRune(r)
lastIsQuote = false
}
}
return sb.String(), nil
}
}