// Upsert means update an existing object or create a new object
422437
func (c *Connector) Upsert(ctx context.Context, ei *dosa.EntityInfo, values map[string]dosa.FieldValue) error {
	err := validateSchema(ei)
	if err != nil {
		return err
	}

	keyName, valueName := nameOfKeyValue(ei)

	cacheValue, ok := values[valueName]
	if !ok || cacheValue == nil {
		return NewErrInvalidEntity("No value specified.")
	}

	cacheValueBytes := cacheValue.([]byte)
	if len(cacheValueBytes) == 0 {
		return NewErrInvalidEntity("No value specified.")
	}

	cacheKey, err := buildKey(c.keyPrefix, ei.Ref.Scope, ei.Ref.NamePrefix, ei.Def.Name, values[keyName])
	if err != nil {
		return err
	}

	err = c.client.SetEx(cacheKey, cacheValueBytes, c.ttl)
	c.logCallCount("Upsert", err)
	return err
}
398778
func (s *CombinedMapSlice) UpsertLocal(key MergeKeys, l interface{}) error {
	item, err := s.upsert(key, l)
	if err != nil {
		return err
	}
	item.SetLocal(l)
	return nil
}
1226591
func (b *AllocUpdateBatcher) CreateUpdate(allocs map[string]*structs.DesiredTransition, eval *structs.Evaluation) *BatchFuture {
	wrapper := &updateWrapper{
		allocs: allocs,
		e:      eval,
		f:      make(chan *BatchFuture, 1),
	}

	b.workCh <- wrapper
	return <-wrapper.f
}
551804
func (m *MongoDB) Upsert(key string, val Model) (bool, error) {
	sess := m.sess.Copy()
	defer sess.Close()
	coll := sess.DB(dbName).C(candiesColl)
	cInfo, err := coll.Upsert(bson.M{"key": key}, objWrapper{Key: key, Data: val})
	if err != nil {
		return false, err
	}
	// the Updated field is set when already existed, otherwise the UpsertedID field is set.
	// see the func at https://bazaar.launchpad.net/+branch/mgo/v2/view/head:/session.go#L1896
	return cInfo.UpsertedId != nil, nil
}
756062
func (c *FakeReplicaSets) Update(replicaSet *v1beta1.ReplicaSet) (result *v1beta1.ReplicaSet, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateAction(replicasetsResource, c.ns, replicaSet), &v1beta1.ReplicaSet{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.ReplicaSet), err
}
719953
func Update(mainObj interface{}, newData interface{}) bool {
	newDataVal, mainObjVal := reflect.ValueOf(newData).Elem(), reflect.ValueOf(mainObj).Elem()
	fieldCount := newDataVal.NumField()
	changed := false
	for i := 0; i < fieldCount; i++ {
		newField := newDataVal.Field(i)
		// They passed in a value for this field, update our DB user
		if newField.IsValid() && !IsEmpty(newField) {
			dbField := mainObjVal.Field(i)
			dbField.Set(newField)
			changed = true
		}
	}
	return changed
}
914446
func (c *Client) UpsertNode(s services.Server) (*services.KeepAlive, error) {
	if s.GetNamespace() == "" {
		return nil, trace.BadParameter("missing node namespace")
	}
	protoServer, ok := s.(*services.ServerV2)
	if !ok {
		return nil, trace.BadParameter("unsupported client")
	}
	clt, err := c.grpc()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	keepAlive, err := clt.UpsertNode(context.TODO(), protoServer)
	if err != nil {
		return nil, trail.FromGRPC(err)
	}
	return keepAlive, nil
}
570345
func (t *Tree) Upsert(ctx context.Context, kvp KeyValuePair, txinfo TxInfo) (err error) {
	t.Lock()
	defer t.Unlock()

	root, err := t.eng.LookupRoot(ctx)
	if err != nil {
		return err
	}

	prevRoot := root
	var last *Node

	var path path
	var level Level
	var curr *Node

	// Root might be nil if we're upserting into an empty tree
	if root != nil {
		_, curr, err = t.lookupNode(ctx, root)
		if err != nil {
			return err
		}
	}

	// Find the path from the key up to the root;
	// find by walking down from the root.
	for curr != nil {
		prefix, index := t.cfg.prefixAndIndexAtLevel(level, kvp.Key)
		path.push(step{p: prefix, n: curr, l: level, i: index})
		level++
		last = curr
		if curr.Type == nodeTypeLeaf {
			break
		}
		nxt, err := curr.findChildByIndex(index)
		if err != nil {
			return err
		}
		if nxt == nil {
			break
		}
		_, curr, err = t.lookupNode(ctx, nxt)
		if err != nil {
			return err
		}
	}

	// Figure out what to store at the node where we stopped going down the path.
	var sm *SortedMap
	if last == nil || last.Type == nodeTypeINode {
		sm = newSortedMapFromKeyAndValue(kvp)
		level = 0
	} else if val2 := last.findValueInLeaf(kvp.Key); val2 == nil || !deepEqual(val2, kvp.Value) {
		sm = newSortedMapFromNode(last).replace(kvp)
		level = path.len() - 1
	} else {
		return nil
	}

	// Make a new subtree out of our new node.
	hsh, err := t.hashTreeRecursive(ctx, level, sm, prevRoot)
	if err != nil {
		return err
	}

	path.reverse()

	for _, step := range path.steps {
		if step.n.Type != nodeTypeINode {
			continue
		}
		sm := newChildPointerMapFromNode(step.n).set(step.i, hsh)
		var nodeExported []byte
		hsh, _, nodeExported, err = sm.exportToNode(t.cfg.hasher, prevRoot, step.l)
		if err != nil {
			return err
		}
		err = t.eng.StoreNode(ctx, hsh, nodeExported)
		if err != nil {
			return err
		}
	}
	err = t.eng.CommitRoot(ctx, prevRoot, hsh, txinfo)

	return err
}
44296
func (c *cacheInternal) Upsert(token string, ms macaroon.Slice) {
	c.Lock()
	defer c.Unlock()

	var et *time.Time
	if expiryTime, ok := checkers.MacaroonsExpiryTime(ms); ok {
		et = &expiryTime
	}
	c.macaroons[token] = &macaroonEntry{
		ms:         ms,
		expiryTime: et,
	}
}
972694
func (s *StateStore) upsertDeploymentUpdates(index uint64, updates []*structs.DeploymentStatusUpdate, txn *memdb.Txn) error {
	for _, u := range updates {
		if err := s.updateDeploymentStatusImpl(index, u, txn); err != nil {
			return err
		}
	}

	return nil
}
654143
func (s *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, _ rest.ValidateObjectFunc, _ rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {
	obj, err := objInfo.UpdatedObject(ctx, nil)
	if err != nil {
		return nil, false, err
	}
	mapping, ok := obj.(*userinternal.UserIdentityMapping)
	if !ok {
		return nil, false, kerrs.NewBadRequest("invalid type")
	}
	Strategy.PrepareForUpdate(ctx, mapping, nil)
	return s.createOrUpdate(ctx, mapping, false)
}
142584
func (aug *AuthUserGroup) Upsert(db XODB) error {
	var err error

	// if already exist, bail
	if aug._exists {
		return errors.New("insert failed: already exists")
	}

	// sql query
	const sqlstr = `INSERT INTO public.auth_user_groups (` +
		`id, user_id, group_id` +
		`) VALUES (` +
		`$1, $2, $3` +
		`) ON CONFLICT (id) DO UPDATE SET (` +
		`id, user_id, group_id` +
		`) = (` +
		`EXCLUDED.id, EXCLUDED.user_id, EXCLUDED.group_id` +
		`)`

	// run query
	XOLog(sqlstr, aug.ID, aug.UserID, aug.GroupID)
	_, err = db.Exec(sqlstr, aug.ID, aug.UserID, aug.GroupID)
	if err != nil {
		return err
	}

	// set existence
	aug._exists = true

	return nil
}
9993
func (c *Client) UpsertNodes(namespace string, servers []services.Server) error {
	if namespace == "" {
		return trace.BadParameter("missing node namespace")
	}

	bytes, err := services.GetServerMarshaler().MarshalServers(servers)
	if err != nil {
		return trace.Wrap(err)
	}
	args := &upsertNodesReq{
		Namespace: namespace,
		Nodes:     bytes,
	}
	_, err = c.PutJSON(c.Endpoint("namespaces", namespace, "nodes"), args)
	return trace.Wrap(err)
}
1135684
func (o *Object) Update() {
	o.mut.Lock()
	o.checked = false
	o.mut.Unlock()
}
1266884
func (be *T) UpsertServer(beSrvCfg engine.Server) (bool, error) {
	be.mu.Lock()
	defer be.mu.Unlock()

	beSrv, err := NewServer(beSrvCfg)
	if err != nil {
		return false, errors.Wrapf(err, "bad config %v", beSrvCfg)
	}
	if i := be.indexOfServer(beSrvCfg.Id); i != -1 {
		if be.srvs[i].URLKey() == beSrv.URLKey() {
			return false, nil
		}
		be.cloneSrvCfgsIfSeen()
		be.srvs[i] = beSrv
		return true, nil
	}
	be.cloneSrvCfgsIfSeen()
	be.srvs = append(be.srvs, beSrv)
	return true, nil
}
813769
func (l Labels) upsertLabel(label Label) bool {
	oldLabel, found := l[label.Key]
	if found {
		// Key is the same, check if Value and Source are also the same
		if label.Value == oldLabel.Value && label.Source == oldLabel.Source {
			return false // No change
		}
	}
	// Insert or replace old label
	l[label.Key] = label
	return true
}
1223717
func (bk *Backend) UpsertItems(bucket []string, newItems []legacy.Item) error {
	// Open the bucket to work on the items.
	b, err := bk.openBucket(bk.flatten(bucket), os.O_CREATE|os.O_RDWR)
	if err != nil {
		return trace.Wrap(err)
	}
	defer b.Close()

	// Update items in bucket.
	for _, e := range newItems {
		b.updateItem(e.Key, e.Value, e.TTL)
	}

	return nil
}