-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathreplace.go
66 lines (59 loc) · 1.2 KB
/
replace.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
package goerd
import (
"fmt"
"strings"
)
type Columner interface {
Table() string
Columns() []string
}
func ReplaceQuery(d Columner, idCols ...string) string {
idcs := strings.Join(idCols, ",")
cols := d.Columns()
colsnoids := ColumnsWithout(cols, append(idCols, "created_at")...)
return fmt.Sprintf(`INSERT INTO %s (%s) VALUES(%s) ON CONFLICT(%s) DO UPDATE SET (%s)=(%s)`,
d.Table(),
strings.Join(cols, ","),
Replacers(len(cols)),
idcs,
strings.Join(colsnoids, ","),
strings.Join(Excluded(colsnoids), ","),
)
}
func Replacers(cnt int) string {
sb := &strings.Builder{}
sb.Grow(cnt * 2)
for i := 0; i < cnt; i++ {
fmt.Fprintf(sb, "$%d", i+1)
if i < cnt-1 {
sb.WriteByte(',')
}
}
return sb.String()
}
func ColumnsWithout(cols []string, skip ...string) []string {
if len(skip) == 0 {
return cols
}
ret := make([]string, 0, len(cols))
for _, c := range cols {
fnd := false
for _, v := range skip {
if strings.EqualFold(c, v) {
fnd = true
break
}
}
if !fnd {
ret = append(ret, c)
}
}
return ret
}
func Excluded(cols []string) []string {
ret := make([]string, len(cols))
for i, v := range cols {
ret[i] = fmt.Sprintf("excluded.%s", v)
}
return ret
}