-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutation_delete.go
52 lines (47 loc) · 1.72 KB
/
mutation_delete.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
package spnr
import (
"context"
"time"
"cloud.google.com/go/spanner"
"github.com/pkg/errors"
)
// Delete build and execute delete operation using mutation API.
// You can pass either a struct or a slice of structs.
// If you pass a slice of structs, this method will build a mutation for each struct.
// This method requires spanner.ReadWriteTransaction, and will call spanner.ReadWriteTransaction.BufferWrite to save the mutation to transaction.
func (m *Mutation) Delete(tx *spanner.ReadWriteTransaction, target any) error {
isStruct, err := validateStructOrStructSliceType(target)
if err != nil {
return err
}
if isStruct {
return errors.WithStack(tx.BufferWrite(m.buildDelete([]any{target})))
}
return errors.WithStack(tx.BufferWrite(m.buildDelete(toStructSlice(target))))
}
// ApplyDelete is basically same as Delete, but it doesn't require transaction.
// This method directly calls mutation API without transaction by calling spanner.Client.Apply method.
func (m *Mutation) ApplyDelete(ctx context.Context, client *spanner.Client, target any) (time.Time, error) {
isStruct, err := validateStructOrStructSliceType(target)
if err != nil {
return time.Time{}, err
}
if isStruct {
t, err := client.Apply(ctx, m.buildDelete([]any{target}))
return t, errors.WithStack(err)
}
t, err := client.Apply(ctx, m.buildDelete(toStructSlice(target)))
return t, errors.WithStack(err)
}
func (m *Mutation) buildDelete(targets []any) []*spanner.Mutation {
var ms []*spanner.Mutation
for _, target := range targets {
var pks spanner.Key
for _, pk := range extractPks(toFields(target)) {
pks = append(pks, pk.value)
}
ms = append(ms, spanner.Delete(m.table, pks))
m.logf("Deleting from %s, key=%+v", m.table, pks)
}
return ms
}