-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasy-pg-json.go
47 lines (44 loc) · 1 KB
/
easy-pg-json.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
package easypgjson
func FindClosingBrace(s []rune, pos int) int {
level := 0
for pos < len(s) {
if s[pos] == ')' {
if level == 0 {
return pos
} else {
level--
}
} else if s[pos] == '(' {
level++
}
pos = pos + 1
}
return -1
}
func ToSql(q string) string {
newString := ""
qR := []rune(q)
i := 0
for i < len(qR) {
if qR[i] == rune('$') && qR[i+1] == rune('$') && qR[i+2] == rune('(') {
pos := FindClosingBrace(qR, i+3)
if pos == -1 {
return q
}
newString = newString + "select json_build_object(" + string(qR[i+3:pos]) + ")"
// newString = newString + "( select json_agg(row_to_json(t)) from " + string(qR[i+3:pos]) + ") t )"
i = pos
} else if qR[i] == rune('$') && qR[i+1] == rune('(') {
pos := FindClosingBrace(qR, i+3)
if pos == -1 {
return q
}
newString = newString + "( select json_agg(row_to_json(t)) from (" + string(qR[i+3:pos]) + ") t )"
i = pos
} else {
newString = newString + string(qR[i])
}
i++
}
return newString
}