1// Copyright 2018 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package datastore
16
17import (
18	"fmt"
19
20	pb "google.golang.org/genproto/googleapis/datastore/v1"
21)
22
23// A Mutation represents a change to a Datastore entity.
24type Mutation struct {
25	key *Key // needed for transaction PendingKeys and to dedup deletions
26	mut *pb.Mutation
27
28	// err is set to a Datastore or gRPC error, if Mutation is not valid
29	// (see https://godoc.org/google.golang.org/grpc/codes).
30	err error
31}
32
33func (m *Mutation) isDelete() bool {
34	_, ok := m.mut.Operation.(*pb.Mutation_Delete)
35	return ok
36}
37
38// NewInsert creates a Mutation that will save the entity src into the
39// datastore with key k. If k already exists, calling Mutate with the
40// Mutation will lead to a gRPC codes.AlreadyExists error.
41func NewInsert(k *Key, src interface{}) *Mutation {
42	if !k.valid() {
43		return &Mutation{err: ErrInvalidKey}
44	}
45	p, err := saveEntity(k, src)
46	if err != nil {
47		return &Mutation{err: err}
48	}
49	return &Mutation{
50		key: k,
51		mut: &pb.Mutation{Operation: &pb.Mutation_Insert{Insert: p}},
52	}
53}
54
55// NewUpsert creates a Mutation that saves the entity src into the datastore with key
56// k, whether or not k exists. See Client.Put for valid values of src.
57func NewUpsert(k *Key, src interface{}) *Mutation {
58	if !k.valid() {
59		return &Mutation{err: ErrInvalidKey}
60	}
61	p, err := saveEntity(k, src)
62	if err != nil {
63		return &Mutation{err: err}
64	}
65	return &Mutation{
66		key: k,
67		mut: &pb.Mutation{Operation: &pb.Mutation_Upsert{Upsert: p}},
68	}
69}
70
71// NewUpdate creates a Mutation that replaces the entity in the datastore with
72// key k. If k does not exist, calling Mutate with the Mutation will lead to a
73// gRPC codes.NotFound error.
74// See Client.Put for valid values of src.
75func NewUpdate(k *Key, src interface{}) *Mutation {
76	if !k.valid() {
77		return &Mutation{err: ErrInvalidKey}
78	}
79	if k.Incomplete() {
80		return &Mutation{err: fmt.Errorf("datastore: can't update the incomplete key: %v", k)}
81	}
82	p, err := saveEntity(k, src)
83	if err != nil {
84		return &Mutation{err: err}
85	}
86	return &Mutation{
87		key: k,
88		mut: &pb.Mutation{Operation: &pb.Mutation_Update{Update: p}},
89	}
90}
91
92// NewDelete creates a Mutation that deletes the entity with key k.
93func NewDelete(k *Key) *Mutation {
94	if !k.valid() {
95		return &Mutation{err: ErrInvalidKey}
96	}
97	if k.Incomplete() {
98		return &Mutation{err: fmt.Errorf("datastore: can't delete the incomplete key: %v", k)}
99	}
100	return &Mutation{
101		key: k,
102		mut: &pb.Mutation{Operation: &pb.Mutation_Delete{Delete: keyToProto(k)}},
103	}
104}
105
106func mutationProtos(muts []*Mutation) ([]*pb.Mutation, error) {
107	// If any of the mutations have errors, collect and return them.
108	var merr MultiError
109	for i, m := range muts {
110		if m.err != nil {
111			if merr == nil {
112				merr = make(MultiError, len(muts))
113			}
114			merr[i] = m.err
115		}
116	}
117	if merr != nil {
118		return nil, merr
119	}
120	var protos []*pb.Mutation
121	// Collect protos. Remove duplicate deletions (see deleteMutations).
122	seen := map[string]bool{}
123	for _, m := range muts {
124		if m.isDelete() {
125			ks := m.key.String()
126			if seen[ks] {
127				continue
128			}
129			seen[ks] = true
130		}
131		protos = append(protos, m.mut)
132	}
133	return protos, nil
134}
135