-
Notifications
You must be signed in to change notification settings - Fork 0
/
upsert.go
96 lines (82 loc) · 1.83 KB
/
upsert.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
86
87
88
89
90
91
92
93
94
95
96
package upsert
import (
"context"
"fmt"
"strings"
"github.com/jmoiron/sqlx"
)
func PrepareNamedQuery[T any](ctx context.Context, db *sqlx.DB, tableName string, val T, skipCols ...string) (*sqlx.NamedStmt, error) {
dcols, err := StructColumns(val)
if err != nil {
return nil, err
}
cols := columnsWithout(dcols.DBs(), skipCols...)
pkcols := columnsWithout(dcols.PKs(), skipCols...)
idcs := strings.Join(pkcols, ",")
colsnoids := columnsWithout(cols, append(pkcols, skipCols...)...)
var suffix string
suffixVals := []any{
strings.Join(colsnoids, ","),
strings.Join(excluded(colsnoids), ","),
}
switch {
case len(colsnoids) == 0:
suffix = "NOTHING"
suffixVals = nil
case len(colsnoids) == 1:
suffix = "UPDATE SET %s=%s"
case len(colsnoids) > 1:
suffix = "UPDATE SET (%s)=(%s)"
}
q := fmt.Sprintf(`INSERT INTO %s (%s) VALUES(%s)`,
tableName,
strings.Join(cols, ","),
replacers(cols),
)
if len(idcs) > 0 {
q = fmt.Sprintf(`%s ON CONFLICT(%s) DO %s`,
q,
idcs,
fmt.Sprintf(suffix, suffixVals...),
)
}
// slog.Debug("PrepareUpsertNamedQuery", "q", q)
return db.Unsafe().PrepareNamedContext(ctx, q)
}
func replacers(cols []string) string {
sb := &strings.Builder{}
sb.Grow(len(cols) * 10)
for i, col := range cols {
fmt.Fprintf(sb, ":%s", col)
if i < len(cols)-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
}