forked from jaekwon/go-modeldb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadapter.go
58 lines (52 loc) · 1.28 KB
/
adapter.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
/*
This package is responsible for converting ? placeholders into
$i placeholders, like MySQL to PostgesQL.
*/
package modeldb
import (
. "github.com/jaekwon/pego"
"fmt"
"strings"
)
var phConversions = map[string]string{}
var phGrammar = Grm("S", map[string]*Pattern{
"S": Seq(
Ref("OTHER"),
Seq(
Ref("PH").Or(Ref("STR")),
Ref("OTHER"),
).Rep(0, -1),
).Clist(),
"OTHER": NegSet("'?").Rep(0, -1).Csimple(),
"PH": Char('?').Csimple(),
"STR": Seq(
Char('\''),
Seq(
Seq(Char('\\'), Any(1)).Or(
NegSet("'")),
).Rep(0, -1),
Char('\''),
).Csimple(),
})
func ReplacePH(items []interface{}) string {
index := 1
parts := []string{}
for _, item := range items {
if item == "?" {
parts = append(parts, fmt.Sprintf("$%v", index))
index++
} else {
parts = append(parts, item.(string))
}
}
//fmt.Println(">> %v", strings.Join(parts, ""))
return strings.Join(parts, "")
}
func ConvertPH(q string) string {
if phConversions[q] != "" {
return phConversions[q]
}
r, err, _ := Match(phGrammar, q)
if err != nil { panic(err) }
return ReplacePH(r.([]interface{}))
}