-
Notifications
You must be signed in to change notification settings - Fork 0
/
save.go
90 lines (78 loc) · 2.48 KB
/
save.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
package ldb
import (
"context"
"fmt"
"strings"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"admini.dev/admini/app/lib/database"
"admini.dev/admini/app/lib/schema/model"
"admini.dev/admini/app/util"
)
func Save(
ctx context.Context, db *database.Service, m *model.Model, ids []any, changes util.ValueMap, logger util.Logger,
) ([]any, error) {
cols, vals := changes.KeysAndValues()
pk := m.GetPK(logger)
where := make([]string, 0, len(pk))
for idx, x := range pk {
switch db.Placeholder() {
case "?":
where = append(where, fmt.Sprintf("%s = ?", x))
case "@":
where = append(where, fmt.Sprintf("%s = @p%d", x, len(vals)+idx+1))
default:
where = append(where, fmt.Sprintf("%s = $%d", x, len(vals)+idx+1))
}
}
if db.Type.SupportsReturning {
q := database.SQLUpdateReturning(m.Key, cols, strings.Join(where, " and "), pk, db.Placeholder())
out, err := db.QuerySingleRow(ctx, q, nil, logger, append(vals, ids...)...)
if err != nil {
return nil, errors.Wrapf(err, "unable to save [%s] with primary key [%s]", m.Name(), strings.Join(pk, "::"))
}
ret := make([]any, 0, len(out))
for _, p := range pk {
ret = append(ret, out[p])
}
return ret, nil
}
tx, err := db.StartTransaction(logger)
if err != nil {
return nil, err
}
uq := database.SQLUpdate(m.Key, cols, strings.Join(where, " and "), db.Placeholder())
_, err = db.Exec(ctx, uq, tx, -1, logger, append(vals, ids...)...)
if err != nil {
_ = tx.Rollback()
return nil, errors.Wrap(err, "unable to insert row")
}
return loadAfterEdit(ctx, pk, ids, m, tx, db, logger)
}
func loadAfterEdit(
ctx context.Context, pk []string, pkVals []any, m *model.Model, tx *sqlx.Tx, db *database.Service, logger util.Logger,
) ([]any, error) {
wc := make([]string, 0, len(pk))
for idx, x := range pk {
if db.Placeholder() == "?" {
wc = append(wc, fmt.Sprintf(`%s%s%s = ?`, db.Type.Quote, x, db.Type.Quote))
} else {
wc = append(wc, fmt.Sprintf(`%s%s%s = $%d`, db.Type.Quote, x, db.Type.Quote, idx+1))
}
}
sq := database.SQLSelectSimple(strings.Join(pk, ", "), m.Path().Quoted(db.Type.Quote), db.Placeholder(), wc...)
out, err := db.QuerySingleRow(ctx, sq, tx, logger, pkVals...)
if err != nil {
_ = tx.Rollback()
return nil, errors.Wrap(err, "unable to select newly-inserted row")
}
ret := make([]any, 0, len(pk))
for _, p := range pk {
ret = append(ret, out[p])
}
err = tx.Commit()
if err != nil {
return nil, errors.Wrap(err, "unable to commit insert transaction")
}
return ret, nil
}