-
Notifications
You must be signed in to change notification settings - Fork 0
/
add.go
56 lines (48 loc) · 1.42 KB
/
add.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
package ldb
import (
"context"
"github.com/pkg/errors"
"admini.dev/admini/app/lib/database"
"admini.dev/admini/app/lib/schema/model"
"admini.dev/admini/app/util"
)
func Add(ctx context.Context, db *database.Service, m *model.Model, changes util.ValueMap, logger util.Logger) ([]any, error) {
columns, data := changes.KeysAndValues()
pk := m.GetPK(logger)
if db.Type.SupportsReturning {
q := database.SQLInsertReturning(m.Path().Quoted(db.Type.Quote), columns, 1, pk, db.Placeholder())
out, err := db.QuerySingleRow(ctx, q, nil, logger, data...)
if err != nil {
return nil, errors.Wrap(err, "unable to insert row reurning primary key")
}
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, errors.Wrap(err, "unable to open transaction")
}
iq := database.SQLInsert(m.Path().Quoted(db.Type.Quote), columns, 1, db.Placeholder())
_, err = db.Exec(ctx, iq, tx, 1, logger, data...)
if err != nil {
return nil, errors.Wrap(err, "unable to insert row")
}
pkVals := make([]any, 0, len(pk))
for _, x := range pk {
hit := false
for idx, c := range columns {
if c == x {
hit = true
pkVals = append(pkVals, data[idx])
break
}
}
if !hit {
return nil, errors.Errorf("missing pk field [%s] for insert", x)
}
}
return loadAfterEdit(ctx, pk, pkVals, m, tx, db, logger)
}