// Upsert specifies the document to use for upserts. It will be used for
// create if the original document does not exist.
4071
func (r *BulkUpdateRequest) Upsert(doc interface{}) *BulkUpdateRequest {
	r.upsert = doc
	r.source = nil
	return r
}
186817
func (b *Bulk) Insert(docs ...interface{}) {
	action := b.action(bulkInsert)
	action.docs = append(action.docs, docs...)
}
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
}
1137338
func (c *Connector) MultiUpsert(ctx context.Context, ei *dosa.EntityInfo, multiValues []map[string]dosa.FieldValue) (result []error, err error) {
	if c.isCacheable(ei) {
		w := func() error {
			for _, values := range multiValues {
				_ = c.removeValueFromFallback(ctx, ei, createCacheKey(ei, values))
			}
			return nil
		}
		_ = c.cacheWrite(w)
	}
	return c.Next.MultiUpsert(ctx, ei, multiValues)
}
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
}
1234239
func (s *IdentityService) UpsertTOTP(user string, secretKey string) error {
	if user == "" {
		return trace.BadParameter("missing user name")
	}

	item := backend.Item{
		Key:   backend.Key(webPrefix, usersPrefix, user, totpPrefix),
		Value: []byte(secretKey),
	}

	_, err := s.Put(context.TODO(), item)
	if err != nil {
		return trace.Wrap(err)
	}

	return 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
}
1201751
func (t *Tr) walkupInsert(nodes map[string]*path) error {
	mapping := make(map[string]*Node, len(nodes))

	for len(nodes) > 0 {
		splitNodes := make(map[string]Keys)
		newNodes := make(map[string]*path)
		for id, path := range nodes {
			node := t.context.getNode(ID(id))

			parentPath := path.pop()
			if parentPath == nil {
				t.Root = node.ID
				continue
			}

			parent := parentPath.n
			newNode := mapping[string(parent.ID)]
			if newNode == nil {
				if !t.context.nodeExists(parent.ID) {
					cp := parent.copy()
					if string(t.Root) == string(parent.ID) {
						t.Root = cp.ID
					}

					t.context.addNode(cp)
					mapping[string(parent.ID)] = cp
					parent = cp
				} else {
					newNode = t.context.getNode(parent.ID)
					mapping[string(parent.ID)] = newNode
					parent = newNode
				}
			} else {
				parent = newNode
			}

			i := parentPath.i

			parent.replaceKeyAt(&Key{UUID: node.ID}, i)
			splitNodes[string(parent.ID)] = append(splitNodes[string(parent.ID)], t.iterativeSplit(node)...)
			newNodes[string(parent.ID)] = path
		}

		var wg sync.WaitGroup
		wg.Add(len(splitNodes))
		lerr := terr.New()

		for id, keys := range splitNodes {
			go func(id ID, keys Keys) {
				defer wg.Done()
				n, err := t.contextOrCachedNode(id, true)
				if err != nil {
					lerr.Set(err)
					return
				}
				for _, key := range keys {
					n.insert(t.config.Comparator, key)
				}
			}(ID(id), keys)
		}

		wg.Wait()

		if lerr.Get() != nil {
			return lerr.Get()
		}

		nodes = newNodes
	}

	n := t.context.getNode(t.Root)
	for n.needsSplit(t.config.NodeWidth) {
		root := newNode()
		t.Root = root.ID
		t.context.addNode(root)
		root.appendChild(&Key{UUID: n.ID})
		keys := t.iterativeSplit(n)
		for _, key := range keys {
			root.insert(t.config.Comparator, key)
		}
		n = root
	}

	return nil
}
892603
func (p *DocumentMatchPool) Put(d *DocumentMatch) {
	if d == nil {
		return
	}
	// reset DocumentMatch before returning it to available pool
	d.Reset()
	p.avail = append(p.avail, d)
}
373499
func (b *BulkDocument) Save(doc interface{}, id, rev string) error {
	if id == "" {
		return fmt.Errorf("No ID specified")
	}
	b.docs = append(b.docs, bulkDoc{id, rev, false, doc})
	return nil
}
1006460
func (k kvstoreImplementation) upsert(ctx context.Context, key string, value []byte, lease bool) error {
	_, err := kvstore.UpdateIfDifferent(ctx, key, value, lease)
	return err
}
202195
func (c *T) UpsertServer(beSrv backend.Srv) {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.beSrvRTMs[beSrv.URLKey()] = BeSrvEntry{beSrv.Cfg(), NewRTMetrics()}
}
672394
func (r *resourceRecordChangeset) Upsert(rrset dnsprovider.ResourceRecordSet) dnsprovider.ResourceRecordChangeset {
	r.upserts = append(r.upserts, rrset)
	return r
}
1272856
func (w *Wrapper) UpsertProxy(s services.Server) error {
	return w.Write.UpsertProxy(s)
}
450983
func (txops txOps) upsert(k compositeKey, val []byte) {
	keyops := txops.getOrCreateKeyEntry(k)
	keyops.flag += upsertVal
	keyops.value = val
}
1348284
function upsert(db, docId, diffFun) {
  return new Promise(function (fulfill, reject) {
    db.get(docId, function (err, doc) {
      if (err) {
        /* istanbul ignore next */
        if (err.status !== 404) {
          return reject(err);
        }
        doc = {};
      }

      // the user might change the _rev, so save it for posterity
      var docRev = doc._rev;
      var newDoc = diffFun(doc);

      if (!newDoc) {
        // if the diffFun returns falsy, we short-circuit as
        // an optimization
        return fulfill({updated: false, rev: docRev});
      }

      // users aren't allowed to modify these values,
      // so reset them here
      newDoc._id = docId;
      newDoc._rev = docRev;
      fulfill(tryAndPut(db, newDoc, diffFun));
    });
  });
}
97477
func (doc *Document) Update(newBody []byte) error {
	oldBody, err := doc.Exists()

	if err == nil {
		newData, err := doc.updateDocument(oldBody, newBody)
		if err != nil {
			return errors.New("Update document error " + err.Error())
		}
		_, err = doc.createOrUpdate(newData)
	}
	return err
}