-
Notifications
You must be signed in to change notification settings - Fork 0
/
escape.go
81 lines (72 loc) · 1.61 KB
/
escape.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package pgperms
import (
"bytes"
"fmt"
"regexp"
"strings"
"unicode"
"github.com/samber/lo"
)
// TODO: Write test
// Escape a string for use in a query.
// I don't fully guarantee this is correct, but it'll probably do for strings from the configuration.
func Escape(s string) string {
encodingType := ""
var buf bytes.Buffer
buf.WriteByte('\'')
buf.Grow(len(s) + 2)
for _, c := range s {
switch c {
case '\'':
buf.WriteByte('\'')
buf.WriteByte('\'')
case '\n':
buf.WriteByte('\\')
buf.WriteByte('n')
encodingType = "E"
case '\r':
buf.WriteByte('\\')
buf.WriteByte('r')
encodingType = "E"
case '\\':
buf.WriteByte('\\')
buf.WriteByte('\\')
encodingType = "E"
default:
if c > 128 {
fmt.Fprintf(&buf, `\u%04x`, c)
encodingType = "E"
} else if unicode.IsPrint(c) {
buf.WriteByte(byte(c))
} else {
fmt.Fprintf(&buf, `\x%x`, c)
encodingType = "E"
}
}
}
buf.WriteByte('\'')
return encodingType + buf.String()
}
func splitObjectName(name string) (string, string) {
sp := strings.SplitN(name, ".", 2)
if len(sp) == 1 {
return "", sp[0]
}
return sp[0], sp[1]
}
func joinTableName(database, schema, table string) string {
return database + "." + safeIdentifier(schema) + "." + safeIdentifier(table)
}
var safeCharactersRe = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
func identifierNeedsEscaping(s string) bool {
if lo.Contains(keywords, s) {
return true
}
return !safeCharactersRe.MatchString(s)
}
func safeIdentifier(s string) string {
if identifierNeedsEscaping(s) {
return `"` + strings.ReplaceAll(s, `"`, `""`) + `"`
}
return s
}