-
Notifications
You must be signed in to change notification settings - Fork 0
/
updater.go
60 lines (53 loc) · 2.41 KB
/
updater.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
package dalgo2sql
import (
"context"
"fmt"
"github.com/dal-go/dalgo/dal"
)
func (dtb *database) Update(ctx context.Context, key *dal.Key, updates []dal.Update, preconditions ...dal.Precondition) error {
return updateSingle(ctx, dtb.options, dtb.db.ExecContext, key, updates, preconditions...)
}
func (t transaction) Update(ctx context.Context, key *dal.Key, updates []dal.Update, preconditions ...dal.Precondition) error {
return updateSingle(ctx, t.sqlOptions, t.tx.ExecContext, key, updates, preconditions...)
}
func (dtb *database) UpdateMulti(ctx context.Context, keys []*dal.Key, updates []dal.Update, preconditions ...dal.Precondition) error {
return updateMulti(ctx, dtb.options, dtb.db.ExecContext, keys, updates, preconditions...)
}
func (t transaction) UpdateMulti(ctx context.Context, keys []*dal.Key, updates []dal.Update, preconditions ...dal.Precondition) error {
return updateMulti(ctx, t.sqlOptions, t.tx.ExecContext, keys, updates, preconditions...)
}
func updateSingle(ctx context.Context, options Options, execStatement statementExecutor, key *dal.Key, updates []dal.Update, preconditions ...dal.Precondition) error {
qry := query{
text: fmt.Sprintf("UPDATE %v SET", key.Collection()),
}
for _, update := range updates {
qry.text += fmt.Sprintf("\n\t%v = ?", update.Field)
qry.args = append(qry.args, update.Value)
}
primaryKey := options.PrimaryKeyFieldNames(key)
switch len(primaryKey) {
case 0:
return fmt.Errorf("primary key is not defined for %s", getRecordsetName(key))
case 1:
qry.text += fmt.Sprintf("\n\tWHERE %v = ?", primaryKey[0])
default:
return fmt.Errorf("%w: update by composite primary key is not supported yet", dal.ErrNotImplementedYet)
}
qry.args = append(qry.args, key.ID)
result, err := execStatement(ctx, qry.text, qry.args...)
if err != nil {
return fmt.Errorf("failed to update a single record: %w", err)
}
if count, err := result.RowsAffected(); err == nil && count > 1 {
return fmt.Errorf("expected to update a single row, number of affected rows: %v", count)
}
return nil
}
func updateMulti(ctx context.Context, options Options, execStatement statementExecutor, keys []*dal.Key, updates []dal.Update, preconditions ...dal.Precondition) error {
for i, key := range keys {
if err := updateSingle(ctx, options, execStatement, key, updates, preconditions...); err != nil {
return fmt.Errorf("failed to update record #%d of %d: %w", i+1, len(keys), err)
}
}
return nil
}