// upsert either inserts a new item into the bucket or updates an existing one
// if an item with a matching key is already present.
974625
func (s *Bucket) upsert(item *Item) error {
	if s == nil {
		return fmt.Errorf("nil storage bucket")
	}

	if item == nil {
		return fmt.Errorf("nil item")
	}

	if item.ID == "" {
		return fmt.Errorf("missing item ID")
	}

	// Look for an item with matching key and don't modify the collection
	// while iterating
	foundIdx := -1
	for itemIdx, bucketItems := range s.Items {
		if bucketItems.ID == item.ID {
			foundIdx = itemIdx
			break
		}
	}

	// If there is no match, append the item, otherwise update it
	if foundIdx == -1 {
		s.Items = append(s.Items, item)
	} else {
		s.Items[foundIdx] = item
	}

	return nil
}
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
}
1028567
func (b *Bucket) Put(ctx context.Context, path string, data []byte, contType string, perm ACL, options Options) error {
	body := bytes.NewBuffer(data)
	return b.PutReader(ctx, path, body, int64(len(data)), contType, perm, options)
}
586629
func (s *CombinedMapSlice) UpsertRemote(key MergeKeys, l interface{}) error {
	item, err := s.upsert(key, l)
	if err != nil {
		return err
	}
	item.SetRemote(l)
	return nil
}
1155196
func (svc *S3Accessor) Put(ctx context.Context, keyPath string, object interface{}) error {
	jsonBytes, jsonBytesErr := json.Marshal(object)
	if jsonBytesErr != nil {
		return jsonBytesErr
	}

	logger, _ := ctx.Value(sparta.ContextKeyLogger).(*logrus.Logger)
	logger.WithFields(logrus.Fields{
		"Bytes":   string(jsonBytes),
		"KeyPath": keyPath}).Debug("Saving S3 object")

	bytesReader := bytes.NewReader(jsonBytes)
	putObjectInput := &s3.PutObjectInput{
		Bucket: aws.String(svc.s3BucketName()),
		Key:    aws.String(keyPath),
		Body:   bytesReader,
	}
	putObjectResponse, putObjectRespErr := svc.
		s3Svc(ctx).
		PutObjectWithContext(ctx, putObjectInput)

	logger.WithFields(logrus.Fields{
		"Error":   putObjectRespErr,
		"Results": putObjectResponse}).Debug("Save object results")

	return putObjectRespErr
}
614475
func (f Index) Put(i Item) (err error) {
	key, err := f.encodeKeyFunc(i)
	if err != nil {
		return err
	}
	value, err := f.encodeValueFunc(i)
	if err != nil {
		return err
	}
	return f.db.Put(key, value)
}
13651
func (m *MockClient) Upsert(arg0 context.Context, arg1 []string, arg2 dosa.DomainObject) error {
	ret := m.ctrl.Call(m, "Upsert", arg0, arg1, arg2)
	ret0, _ := ret[0].(error)
	return ret0
}
444706
func (d *Datastore) Put(key ds.Key, value []byte) (err error) {
	return d.child.Put(d.ConvertKey(key), value)
}
834204
func (s *StoragePacker) PutItem(_ context.Context, item *Item) error {
	if item == nil {
		return fmt.Errorf("nil item")
	}

	if item.ID == "" {
		return fmt.Errorf("missing ID in item")
	}

	var err error
	bucketKey := s.BucketKey(item.ID)
	bucketPath := s.BucketPath(bucketKey)

	bucket := &Bucket{
		Key: bucketPath,
	}

	// In this case, we persist the storage entry regardless of the read
	// storageEntry below is nil or not. Hence, directly acquire write lock
	// even to read the entry.
	lock := locksutil.LockForKey(s.storageLocks, bucketPath)
	lock.Lock()
	defer lock.Unlock()

	// Check if there is an existing bucket for a given key
	storageEntry, err := s.view.Get(context.Background(), bucketPath)
	if err != nil {
		return errwrap.Wrapf("failed to read packed storage bucket entry: {{err}}", err)
	}

	if storageEntry == nil {
		// If the bucket entry does not exist, this will be the only item the
		// bucket that is going to be persisted.
		bucket.Items = []*Item{
			item,
		}
	} else {
		uncompressedData, notCompressed, err := compressutil.Decompress(storageEntry.Value)
		if err != nil {
			return errwrap.Wrapf("failed to decompress packed storage entry: {{err}}", err)
		}
		if notCompressed {
			uncompressedData = storageEntry.Value
		}

		err = proto.Unmarshal(uncompressedData, bucket)
		if err != nil {
			return errwrap.Wrapf("failed to decode packed storage entry: {{err}}", err)
		}

		err = bucket.upsert(item)
		if err != nil {
			return errwrap.Wrapf("failed to update entry in packed storage entry: {{err}}", err)
		}
	}

	// Persist the result
	return s.PutBucket(bucket)
}
56758
func (w *Wrapper) UpsertNode(s services.Server) (*services.KeepAlive, error) {
	return w.Write.UpsertNode(s)
}
1006460
func (k kvstoreImplementation) upsert(ctx context.Context, key string, value []byte, lease bool) error {
	_, err := kvstore.UpdateIfDifferent(ctx, key, value, lease)
	return err
}
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
}
1365905
func (a *SentinelPolicies) Upsert(policy *SentinelPolicy, q *WriteOptions) (*WriteMeta, error) {
	if policy == nil || policy.Name == "" {
		return nil, fmt.Errorf("missing policy name")
	}
	wm, err := a.client.write("/v1/sentinel/policy/"+policy.Name, policy, nil, q)
	if err != nil {
		return nil, err
	}
	return wm, nil
}
668691
func (c *Connector) Upsert(ctx context.Context, ei *dosa.EntityInfo, values map[string]dosa.FieldValue) error {
	if c.Next == nil {
		return NewErrNoMoreConnector()
	}
	return c.Next.Upsert(ctx, ei, values)
}
398158
func (b *Bucket) Put(key, value []byte) error {
	return b.PutFn(key, value)
}
553294
func (c *Container) Put(key, value interface{}) {

	for k := 0; k < c.length; k++ {
		if equal(c.items[k].Key, key) {
			c.items[k].Value = value
			return
		}
	}
	if c.length == num {
		if c.next == nil {
			if c.pool != nil {
				c.next = c.pool.Get().(*Container)
			} else {
				c.next = New()
			}

		}
		c.next.Put(key, value)
		return
	}
	c.items[c.length] = item{key, value}
	c.length++
	return
}
527283
func (rb *RingBuffer) Put(item interface{}) error {
	_, err := rb.put(item, false)
	return err
}