// buildUpdatePlan builds the instructions for an UPDATE statement.
343909
func buildUpdatePlan(upd *sqlparser.Update, vschema ContextVSchema) (*engine.Update, error) {
	eupd := &engine.Update{
		ChangedVindexValues: make(map[string][]sqltypes.PlanValue),
	}
	pb := newPrimitiveBuilder(vschema, newJointab(sqlparser.GetBindvars(upd)))
	ro, err := pb.processDMLTable(upd.TableExprs)
	if err != nil {
		return nil, err
	}
	eupd.Keyspace = ro.eroute.Keyspace
	if !eupd.Keyspace.Sharded {
		// We only validate non-table subexpressions because the previous analysis has already validated them.
		if !pb.finalizeUnshardedDMLSubqueries(upd.Exprs, upd.Where, upd.OrderBy, upd.Limit) {
			return nil, errors.New("unsupported: sharded subqueries in DML")
		}
		eupd.Opcode = engine.UpdateUnsharded
		// Generate query after all the analysis. Otherwise table name substitutions for
		// routed tables won't happen.
		eupd.Query = generateQuery(upd)
		return eupd, nil
	}

	if hasSubquery(upd) {
		return nil, errors.New("unsupported: subqueries in sharded DML")
	}
	if len(pb.st.tables) != 1 {
		return nil, errors.New("unsupported: multi-table update statement in sharded keyspace")
	}

	// Generate query after all the analysis. Otherwise table name substitutions for
	// routed tables won't happen.
	eupd.Query = generateQuery(upd)

	directives := sqlparser.ExtractCommentDirectives(upd.Comments)
	if directives.IsSet(sqlparser.DirectiveMultiShardAutocommit) {
		eupd.MultiShardAutocommit = true
	}

	eupd.QueryTimeout = queryTimeout(directives)
	eupd.Table = ro.vschemaTable
	if eupd.Table == nil {
		return nil, errors.New("internal error: table.vindexTable is mysteriously nil")
	}

	if ro.eroute.TargetDestination != nil {
		if ro.eroute.TargetTabletType != topodatapb.TabletType_MASTER {
			return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unsupported: UPDATE statement with a replica target")
		}
		eupd.Opcode = engine.UpdateByDestination
		eupd.TargetDestination = ro.eroute.TargetDestination
		return eupd, nil
	}

	eupd.Vindex, eupd.Values, err = getDMLRouting(upd.Where, eupd.Table)
	if err != nil {
		eupd.Opcode = engine.UpdateScatter
	} else {
		eupd.Opcode = engine.UpdateEqual
	}

	if eupd.Opcode == engine.UpdateScatter {
		if len(eupd.Table.Owned) != 0 {
			return eupd, errors.New("unsupported: multi shard update on a table with owned lookup vindexes")
		}
		if upd.Limit != nil {
			return eupd, errors.New("unsupported: multi shard update with limit")
		}
	}

	if eupd.ChangedVindexValues, err = buildChangedVindexesValues(eupd, upd, eupd.Table.ColumnVindexes); err != nil {
		return nil, err
	}
	if len(eupd.ChangedVindexValues) != 0 {
		eupd.OwnedVindexQuery = generateUpdateSubquery(upd, eupd.Table)
	}
	return eupd, nil
}
503284
func (deploymentStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newDeployment := obj.(*apps.Deployment)
	oldDeployment := old.(*apps.Deployment)
	newDeployment.Status = oldDeployment.Status

	pod.DropDisabledTemplateFields(&newDeployment.Spec.Template, &oldDeployment.Spec.Template)

	// Spec updates bump the generation so that we can distinguish between
	// scaling events and template changes, annotation updates bump the generation
	// because annotations are copied from deployments to their replica sets.
	if !apiequality.Semantic.DeepEqual(newDeployment.Spec, oldDeployment.Spec) ||
		!apiequality.Semantic.DeepEqual(newDeployment.Annotations, oldDeployment.Annotations) {
		newDeployment.Generation = oldDeployment.Generation + 1
	}
}
585574
func buildActionPlan(desired, existing common.PinSliceBySubdir, needsRepair repairCB) (aMap ActionMap) {
	desiredSubdirs := stringset.New(len(desired))
	for desiredSubdir := range desired {
		desiredSubdirs.Add(desiredSubdir)
	}

	existingSubdirs := stringset.New(len(existing))
	for existingSubdir := range existing {
		existingSubdirs.Add(existingSubdir)
	}

	aMap = ActionMap{}

	// all newly added subdirs
	desiredSubdirs.Difference(existingSubdirs).Iter(func(subdir string) bool {
		if want := desired[subdir]; len(want) > 0 {
			aMap[subdir] = &Actions{ToInstall: want}
		}
		return true
	})

	// all removed subdirs
	existingSubdirs.Difference(desiredSubdirs).Iter(func(subdir string) bool {
		if have := existing[subdir]; len(have) > 0 {
			aMap[subdir] = &Actions{ToRemove: have}
		}
		return true
	})

	// all common subdirs
	desiredSubdirs.Intersect(existingSubdirs).Iter(func(subdir string) bool {
		a := Actions{}

		// Figure out what needs to be installed, updated or repaired.
		haveMap := existing[subdir].ToMap()
		for _, want := range desired[subdir] {
			if haveID, exists := haveMap[want.PackageName]; !exists {
				a.ToInstall = append(a.ToInstall, want)
			} else if haveID != want.InstanceID {
				a.ToUpdate = append(a.ToUpdate, UpdatedPin{
					From: common.Pin{PackageName: want.PackageName, InstanceID: haveID},
					To:   want,
				})
			} else if repairPlan := needsRepair(subdir, want); repairPlan != nil {
				a.ToRepair = append(a.ToRepair, BrokenPin{
					Pin:        want,
					RepairPlan: *repairPlan,
				})
			}
		}

		// Figure out what needs to be removed.
		wantMap := desired[subdir].ToMap()
		for _, have := range existing[subdir] {
			if wantMap[have.PackageName] == "" {
				a.ToRemove = append(a.ToRemove, have)
			}
		}

		if !a.Empty() {
			aMap[subdir] = &a
		}
		return true
	})

	if len(aMap) == 0 {
		return nil
	}
	return
}
113927
func (namespaceFinalizeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newNamespace := obj.(*api.Namespace)
	oldNamespace := old.(*api.Namespace)
	newNamespace.Status = oldNamespace.Status
}
391563
func (b *Builder) Update(updates ...Eq) *Builder {
	b.updates = make([]Eq, 0, len(updates))
	for _, update := range updates {
		if update.IsValid() {
			b.updates = append(b.updates, update)
		}
	}
	b.optype = updateType
	return b
}
1115666
func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newBuild := obj.(*buildapi.Build)
	oldBuild := old.(*buildapi.Build)
	// If the build is already in a failed state, do not allow an update
	// of the reason and message. This is to prevent the build controller from
	// overwriting the reason and message that was set by the builder pod
	// when it updated the build's details.
	// Only allow OOMKilled override because various processes in a container
	// can get OOMKilled and this confuses builder to prematurely populate
	// failure reason
	if oldBuild.Status.Phase == buildapi.BuildPhaseFailed &&
		newBuild.Status.Reason != buildapi.StatusReasonOutOfMemoryKilled {
		newBuild.Status.Reason = oldBuild.Status.Reason
		newBuild.Status.Message = oldBuild.Status.Message
	}
}
701786
func (builder *UpdateCounterCommandBuilder) Build() (Command, error) {
	var isLegacy = false
	var timeout time.Duration
	var protobuf proto.Message = nil
	if builder.bucketType == defaultBucketType && builder.returnBody == true {
		isLegacy = true
		rpbCounterUpdateReq := &rpbRiakKV.RpbCounterUpdateReq{
			Amount:      &builder.increment,
			W:           &builder.w,
			Dw:          &builder.dw,
			Pw:          &builder.pw,
			Returnvalue: &builder.returnBody,
		}
		// NB: strings must be handled this way to ensure that nil slices
		// are in the PB msg, rather than 0-len ones
		if builder.bucket != "" {
			rpbCounterUpdateReq.Bucket = []byte(builder.bucket)
		}
		if builder.key != "" {
			rpbCounterUpdateReq.Key = []byte(builder.key)
		}
		protobuf = rpbCounterUpdateReq
	} else {
		timeout = builder.timeout
		timeoutMilliseconds := uint32(builder.timeout / time.Millisecond)
		dtUpdateReq := &rpbRiakDT.DtUpdateReq{
			W:          &builder.w,
			Dw:         &builder.dw,
			Pw:         &builder.pw,
			ReturnBody: &builder.returnBody,
			Timeout:    &timeoutMilliseconds,
			Op: &rpbRiakDT.DtOp{
				CounterOp: &rpbRiakDT.CounterOp{
					Increment: &builder.increment,
				},
			},
		}
		// NB: strings must be handled this way to ensure that nil slices
		// are in the PB msg, rather than 0-len ones
		if builder.bucketType != "" {
			dtUpdateReq.Type = []byte(builder.bucketType)
		}
		if builder.bucket != "" {
			dtUpdateReq.Bucket = []byte(builder.bucket)
		}
		if builder.key != "" {
			dtUpdateReq.Key = []byte(builder.key)
		}
		protobuf = dtUpdateReq
	}

	if err := validateLocatable(protobuf); err != nil {
		return nil, err
	}

	return &UpdateCounterCommand{
		timeoutImpl: timeoutImpl{
			timeout: timeout,
		},
		protobuf: protobuf,
		isLegacy: isLegacy,
	}, nil
}
705481
func (detailsStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newBuild := obj.(*buildapi.Build)
	oldBuild := old.(*buildapi.Build)

	// ignore phase updates unless the caller is updating the build to
	// a completed phase.
	phase := oldBuild.Status.Phase
	stages := newBuild.Status.Stages
	if buildinternalhelpers.IsBuildComplete(newBuild) {
		phase = newBuild.Status.Phase
	}
	revision := newBuild.Spec.Revision
	message := newBuild.Status.Message
	reason := newBuild.Status.Reason
	outputTo := newBuild.Status.Output.To
	*newBuild = *oldBuild
	newBuild.Status.Phase = phase
	newBuild.Status.Stages = stages
	newBuild.Spec.Revision = revision
	newBuild.Status.Reason = reason
	newBuild.Status.Message = message
	newBuild.Status.Output.To = outputTo
}
416538
func (b *PlanBuilder) buildExplainFor(explainFor *ast.ExplainForStmt) (Plan, error) {
	processInfo, ok := b.ctx.GetSessionManager().GetProcessInfo(explainFor.ConnectionID)
	if !ok {
		return nil, ErrNoSuchThread.GenWithStackByArgs(explainFor.ConnectionID)
	}
	if b.ctx.GetSessionVars() != nil && b.ctx.GetSessionVars().User != nil {
		if b.ctx.GetSessionVars().User.Username != processInfo.User {
			err := ErrAccessDenied.GenWithStackByArgs(b.ctx.GetSessionVars().User.Username, b.ctx.GetSessionVars().User.Hostname)
			// Different from MySQL's behavior and document.
			b.visitInfo = appendVisitInfo(b.visitInfo, mysql.SuperPriv, "", "", "", err)
		}
	}

	targetPlan, ok := processInfo.Plan.(Plan)
	if !ok || targetPlan == nil {
		return &Explain{Format: explainFor.Format}, nil
	}

	return b.buildExplainPlan(targetPlan, explainFor.Format, false, nil)
}
127576
func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	newObj := obj.(*node.RuntimeClass)
	errorList := validation.ValidateRuntimeClass(newObj)
	return append(errorList, validation.ValidateRuntimeClassUpdate(newObj, old.(*node.RuntimeClass))...)
}
1174575
func buildControllerPlan(query string) (*controllerPlan, error) {
	stmt, err := sqlparser.Parse(query)
	if err != nil {
		return nil, err
	}
	switch stmt := stmt.(type) {
	case *sqlparser.Insert:
		return buildInsertPlan(stmt)
	case *sqlparser.Update:
		return buildUpdatePlan(stmt)
	case *sqlparser.Delete:
		return buildDeletePlan(stmt)
	case *sqlparser.Select:
		return buildSelectPlan(stmt)
	default:
		return nil, fmt.Errorf("unsupported construct: %s", sqlparser.String(stmt))
	}
}
642227
func (b *DiskBuilder) SetPlan(plan string) {
	switch plan {
	case "ssd":
		b.SetPlanID(sacloud.DiskPlanSSDID)
	case "hdd":
		b.SetPlanID(sacloud.DiskPlanHDDID)
	default:
		panic(fmt.Errorf("Invalid plan:%s", plan))
	}
}
577031
func NewUpdateSetCommandBuilder() *UpdateSetCommandBuilder {
	return &UpdateSetCommandBuilder{
		protobuf: &rpbRiakDT.DtUpdateReq{
			Op: &rpbRiakDT.DtOp{
				SetOp: &rpbRiakDT.SetOp{},
			},
		},
	}
}
283790
func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newDc := obj.(*appsapi.DeploymentConfig)
	oldDc := old.(*appsapi.DeploymentConfig)

	newVersion := newDc.Status.LatestVersion
	oldVersion := oldDc.Status.LatestVersion

	// Persist status
	newDc.Status = oldDc.Status

	// oc deploy --latest from old clients
	// TODO: Remove once we drop support for older clients
	if newVersion == oldVersion+1 {
		newDc.Status.LatestVersion = newVersion
	}

	// TODO: Disallow lastTriggeredImage updates from this update path.

	// Any changes to the spec or labels, increment the generation number, any changes
	// to the status should reflect the generation number of the corresponding object
	// (should be handled by the controller).
	if !reflect.DeepEqual(oldDc.Spec, newDc.Spec) || newDc.Status.LatestVersion != oldDc.Status.LatestVersion {
		newDc.Generation = oldDc.Generation + 1
	}
}
380841
func appsUpdate(db *gorm.DB, app *App) error {
	return db.Save(app).Error
}
1047355
func (bc *BuildController) patchBuild(build *buildv1.Build, update *buildUpdate) (*buildv1.Build, error) {
	// Create a patch using the buildUpdate object
	updatedBuild := build.DeepCopy()
	update.apply(updatedBuild)

	patch, err := createBuildPatch(build, updatedBuild)
	if err != nil {
		return nil, fmt.Errorf("failed to create a build patch: %v", err)
	}

	klog.V(5).Infof("Patching build %s with %v", buildDesc(build), update)
	return bc.buildPatcher.Patch(build.Namespace, build.Name, patch)
}
191208
func (auditSinkStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newIC := obj.(*audit.AuditSink)
	oldIC := old.(*audit.AuditSink)

	// Any changes to the policy or backend increment the generation number
	// See metav1.ObjectMeta description for more information on Generation.
	if !reflect.DeepEqual(oldIC.Spec, newIC.Spec) {
		newIC.Generation = oldIC.Generation + 1
	}
}