-
Notifications
You must be signed in to change notification settings - Fork 0
/
bind.go
85 lines (68 loc) · 1.83 KB
/
bind.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
82
83
84
85
package sqlx
import (
"strconv"
"strings"
"sync"
)
type Binder int
// Binder types supported by Rebind, BindMap and BindStruct.
const (
BindUnknown Binder = iota
BindQuestion
BindDollar
BindColon
BindAt
)
var binds sync.Map
func init() {
defaultBinds := map[Binder][]string{
BindDollar: {"postgres", "pgx", "pq-timeouts", "cloudsqlpostgres", "ql", "nrpostgres", "cockroach"},
BindQuestion: {"mysql", "sqlite3", "nrmysql", "nrsqlite3"},
BindColon: {"oci8", "ora", "goracle", "godror"},
BindAt: {"sqlserver"},
}
for bind, drivers := range defaultBinds {
for _, driver := range drivers {
BindDriver(driver, bind)
}
}
}
// GetBinder returns the binder for a given database given a drivername.
func GetBinder(driverName string) Binder {
itype, ok := binds.Load(driverName)
if !ok {
return BindUnknown
}
return itype.(Binder)
}
// BindDriver sets the Binder for driverName to binder.
func BindDriver(driverName string, binder Binder) {
binds.Store(driverName, binder)
}
// FIXME: this should be able to be tolerant of escaped ?'s in queries without
// losing much speed, and should be to avoid confusion.
// Rebind a query from the default binder (QUESTION) to the target binder.
func (binder Binder) Rebind(query string) string {
switch binder {
case BindQuestion, BindUnknown:
return query
}
// Add space enough for 10 params before we have to allocate
rqb := make([]byte, 0, len(query)+10)
var i, j int
for i = strings.Index(query, "?"); i != -1; i = strings.Index(query, "?") {
rqb = append(rqb, query[:i]...)
switch binder {
case BindDollar:
rqb = append(rqb, '$')
case BindColon:
rqb = append(rqb, ':', 'a', 'r', 'g')
case BindAt:
rqb = append(rqb, '@', 'p')
}
j++
rqb = strconv.AppendInt(rqb, int64(j), 10)
query = query[i+1:]
}
return string(append(rqb, query...))
}