// MultiUpsert upserts multiple entities at one time
761596
func (c *Connector) MultiUpsert(ctx context.Context, ei *dosa.EntityInfo, multiValues []map[string]dosa.FieldValue) ([]error, error) {
	values, err := fieldValueMapsFromClientMaps(multiValues)
	if err != nil {
		return nil, err
	}

	// ttl := dosa.NoTTL().Nanoseconds()
	// if ei.TTL != nil {
	// 	ttl = ei.TTL.Nanoseconds()
	// }

	// perform the multi upsert request
	request := &dosarpc.MultiUpsertRequest{
		Ref:      entityInfoToSchemaRef(ei),
		Entities: values,
		// TTL:      &ttl, mgode@ has not yet committed origin/ttl-for-multi-upsert
	}

	response, err := c.client.MultiUpsert(ctx, request, getHeaders(c.headers)...)
	if err != nil {
		if !dosarpc.Dosa_MultiUpsert_Helper.IsException(err) {
			return nil, errors.Wrap(err, "failed to MultiUpsert due to network issue")
		}

		return nil, errors.Wrap(err, "failed to MultiUpsert")
	}

	rpcErrors := response.Errors
	results := make([]error, len(rpcErrors))
	for i, rpcError := range rpcErrors {
		if rpcError != nil {
			results[i] = wrapIDLError(rpcError)
		}
	}

	return results, nil
}
370648
func (c *Client) UpsertProxy(s services.Server) error {
	data, err := services.GetServerMarshaler().MarshalServer(s)
	if err != nil {
		return trace.Wrap(err)
	}
	args := &upsertServerRawReq{
		Server: data,
	}
	_, err = c.PostJSON(c.Endpoint("proxies"), args)
	return trace.Wrap(err)
}
1006460
func (k kvstoreImplementation) upsert(ctx context.Context, key string, value []byte, lease bool) error {
	_, err := kvstore.UpdateIfDifferent(ctx, key, value, lease)
	return err
}
437497
func (s *CombinedPrimitiveSlice) UpsertRemote(l interface{}) {
	v := s.upsert(l)
	v.remote = l
	v.remoteSet = true
}
1169070
func (b *UpdateService) DocAsUpsert(docAsUpsert bool) *UpdateService {
	b.docAsUpsert = &docAsUpsert
	return b
}
920907
func (s *CompleteMultipartUploadInput) SetMultipartUpload(v *CompletedMultipartUpload) *CompleteMultipartUploadInput {
	s.MultipartUpload = v
	return s
}
1120688
func (self *Failure) UpsertFailure(req *request.Request) bool {
	self.RWMutex.Lock()
	defer self.RWMutex.Unlock()
	if self.list[req.Unique()] != nil {
		return false
	}
	self.list[req.Unique()] = req
	return true
}
1096826
func (p *RequestParams) Upsert(param string, paramType *reflect.StructField) {
	if p == nil {
		return
	}
	t := *p
	for i, reqparam := range t {
		if reqparam.FieldName == param {
			if paramType != nil {
				t[i].FieldType = *paramType
			}
			return
		}
	}
	reqparam := RequestParam{
		FieldName: param,
	}
	if paramType != nil {
		reqparam.FieldType = *paramType
	}
	*p = append(t, reqparam)
}
28118
func (r Resources) upsert(method string, route string, resource *Resource) error {
	currentNode := r

	parts := strings.Split(route, "/")
	if len(parts) > 0 {
		last := len(parts) - 1

		// Upsert route of the resource.
		for _, part := range parts[:last] {
			if part == "" {
				continue
			}
			part = "/" + part

			node, found := currentNode[part]
			if !found {
				node = &Resource{
					Resources: Resources{},
					Responses: Responses{},
				}

				currentNode[part] = node
			}
			currentNode = node.Resources
		}

		if parts[last] != "" {
			// Upsert resource into the very bottom of the node tree.
			part := "/" + parts[last]
			node, found := currentNode[part]
			if !found {
				node = &Resource{
					Resources: Resources{},
					Responses: Responses{},
				}
			}
			currentNode[part] = node
			currentNode = node.Resources
		}
	}

	method = strings.ToLower(method)
	if _, found := currentNode[method]; found {
		return nil
		// return fmt.Errorf("duplicated method route: %v %v", method, route)
	}

	currentNode[method] = resource

	return nil
}
1147652
func (a *AuthWithRoles) UpsertNodes(namespace string, servers []services.Server) error {
	if err := a.action(namespace, services.KindNode, services.VerbCreate); err != nil {
		return trace.Wrap(err)
	}
	if err := a.action(namespace, services.KindNode, services.VerbUpdate); err != nil {
		return trace.Wrap(err)
	}
	return a.authServer.UpsertNodes(namespace, servers)
}
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)
}
1169958
func (g *Goon) PutMulti(src interface{}) ([]*datastore.Key, error) {
	keys, err := g.extractKeys(src, true) // allow incomplete keys on a Put request
	if err != nil {
		return nil, err
	}

	v := reflect.Indirect(reflect.ValueOf(src))
	mu := new(sync.Mutex)
	multiErr, any := make(appengine.MultiError, len(keys)), false
	goroutines := (len(keys)-1)/putMultiLimit + 1
	var wg sync.WaitGroup
	wg.Add(goroutines)
	for i := 0; i < goroutines; i++ {
		go func(i int) {
			defer wg.Done()
			lo := i * putMultiLimit
			hi := (i + 1) * putMultiLimit
			if hi > len(keys) {
				hi = len(keys)
			}
			rkeys, pmerr := datastore.PutMulti(g.Context, keys[lo:hi], v.Slice(lo, hi).Interface())
			if pmerr != nil {
				mu.Lock()
				any = true // this flag tells PutMulti to return multiErr later
				mu.Unlock()
				merr, ok := pmerr.(appengine.MultiError)
				if !ok {
					g.error(pmerr)
					for j := lo; j < hi; j++ {
						multiErr[j] = pmerr
					}
					return
				}
				copy(multiErr[lo:hi], merr)
			}

			for i, key := range keys[lo:hi] {
				if multiErr[lo+i] != nil {
					continue // there was an error writing this value, go to next
				}
				vi := v.Index(lo + i).Interface()
				if key.Incomplete() {
					g.setStructKey(vi, rkeys[i])
					keys[lo+i] = rkeys[i]
				}
				if g.inTransaction {
					mk := MemcacheKey(rkeys[i])
					g.txnCacheLock.Lock()
					g.toDeleteMC[mk] = true
					g.txnCacheLock.Unlock()
				}
			}
		}(i)
	}
	wg.Wait()

	// Memcache needs to be updated after the datastore to prevent a common race condition,
	// where a concurrent request will fetch the not-yet-updated data from the datastore
	// and populate memcache with it.
	if !g.inTransaction {
		var memkeys []string
		for _, key := range keys {
			if !key.Incomplete() {
				memkeys = append(memkeys, MemcacheKey(key))
			}
		}
		memcache.DeleteMulti(g.Context, memkeys)
	}

	if any {
		return keys, realError(multiErr)
	}
	return keys, nil
}
672394
func (r *resourceRecordChangeset) Upsert(rrset dnsprovider.ResourceRecordSet) dnsprovider.ResourceRecordChangeset {
	r.upserts = append(r.upserts, rrset)
	return r
}
205058
func (l *s3EncObjects) NewMultipartUpload(ctx context.Context, bucket string, object string, o minio.ObjectOptions) (uploadID string, err error) {
	var sseOpts encrypt.ServerSide
	if o.ServerSideEncryption == nil {
		return l.s3Objects.NewMultipartUpload(ctx, bucket, object, minio.ObjectOptions{UserDefined: o.UserDefined})
	}
	// Decide if sse options needed to be passed to backend
	if (minio.GlobalGatewaySSE.SSEC() && o.ServerSideEncryption.Type() == encrypt.SSEC) ||
		(minio.GlobalGatewaySSE.SSES3() && o.ServerSideEncryption.Type() == encrypt.S3) {
		sseOpts = o.ServerSideEncryption
	}

	uploadID, err = l.s3Objects.NewMultipartUpload(ctx, bucket, getGWContentPath(object), minio.ObjectOptions{ServerSideEncryption: sseOpts})
	if err != nil {
		return
	}
	// Create uploadID and write a temporary dare.meta object under object/uploadID prefix
	gwmeta := newGWMetaV1()
	gwmeta.Meta = o.UserDefined
	gwmeta.Stat.ModTime = time.Now().UTC()
	err = l.writeGWMetadata(ctx, bucket, getTmpDareMetaPath(object, uploadID), gwmeta, minio.ObjectOptions{})
	if err != nil {
		return uploadID, minio.ErrorRespToObjectError(err)
	}
	return uploadID, nil
}
1055685
func (s *PresenceService) UpsertNodes(namespace string, servers []services.Server) error {
	batch, ok := s.Backend.(backend.Batch)
	if !ok {
		return trace.BadParameter("backend does not support batch interface")
	}
	if namespace == "" {
		return trace.BadParameter("missing node namespace")
	}

	start := time.Now()

	items := make([]backend.Item, len(servers))
	for i, server := range servers {
		value, err := services.GetServerMarshaler().MarshalServer(server)
		if err != nil {
			return trace.Wrap(err)
		}

		items[i] = backend.Item{
			Key:     backend.Key(nodesPrefix, server.GetNamespace(), server.GetName()),
			Value:   value,
			Expires: server.Expiry(),
			ID:      server.GetResourceID(),
		}
	}

	err := batch.PutRange(context.TODO(), items)
	if err != nil {
		return trace.Wrap(err)
	}

	s.log.Debugf("UpsertNodes(%v) in %v", len(servers), time.Now().Sub(start))

	return nil
}
1013844
func (tx *Tx) Upsert(list ...interface{}) error {
	return insertObjects(tx.Context(), tx.DB, tx, getUpsert, list, opUpsert)
}
259181
func (ap *AuthPermission) Upsert(db XODB) error {
	var err error

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

	// sql query
	const sqlstr = `INSERT INTO public.auth_permission (` +
		`id, name, content_type_id, codename` +
		`) VALUES (` +
		`$1, $2, $3, $4` +
		`) ON CONFLICT (id) DO UPDATE SET (` +
		`id, name, content_type_id, codename` +
		`) = (` +
		`EXCLUDED.id, EXCLUDED.name, EXCLUDED.content_type_id, EXCLUDED.codename` +
		`)`

	// run query
	XOLog(sqlstr, ap.ID, ap.Name, ap.ContentTypeID, ap.Codename)
	_, err = db.Exec(sqlstr, ap.ID, ap.Name, ap.ContentTypeID, ap.Codename)
	if err != nil {
		return err
	}

	// set existence
	ap._exists = true

	return nil
}