github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/kv/kvserver/batcheval/cmd_conditional_put.go (about)

     1  // Copyright 2014 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package batcheval
    12  
    13  import (
    14  	"context"
    15  
    16  	"github.com/cockroachdb/cockroach/pkg/kv/kvserver/batcheval/result"
    17  	"github.com/cockroachdb/cockroach/pkg/roachpb"
    18  	"github.com/cockroachdb/cockroach/pkg/storage"
    19  )
    20  
    21  func init() {
    22  	RegisterReadWriteCommand(roachpb.ConditionalPut, DefaultDeclareIsolatedKeys, ConditionalPut)
    23  }
    24  
    25  // ConditionalPut sets the value for a specified key only if
    26  // the expected value matches. If not, the return value contains
    27  // the actual value.
    28  func ConditionalPut(
    29  	ctx context.Context, readWriter storage.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
    30  ) (result.Result, error) {
    31  	args := cArgs.Args.(*roachpb.ConditionalPutRequest)
    32  	h := cArgs.Header
    33  
    34  	if h.DistinctSpans {
    35  		if b, ok := readWriter.(storage.Batch); ok {
    36  			// Use the distinct batch for both blind and normal ops so that we don't
    37  			// accidentally flush mutations to make them visible to the distinct
    38  			// batch.
    39  			readWriter = b.Distinct()
    40  			defer readWriter.Close()
    41  		}
    42  	}
    43  	handleMissing := storage.CPutMissingBehavior(args.AllowIfDoesNotExist)
    44  	var err error
    45  	if args.Blind {
    46  		err = storage.MVCCBlindConditionalPut(ctx, readWriter, cArgs.Stats, args.Key, h.Timestamp, args.Value, args.ExpValue, handleMissing, h.Txn)
    47  	} else {
    48  		err = storage.MVCCConditionalPut(ctx, readWriter, cArgs.Stats, args.Key, h.Timestamp, args.Value, args.ExpValue, handleMissing, h.Txn)
    49  	}
    50  	// NB: even if MVCC returns an error, it may still have written an intent
    51  	// into the batch. This allows callers to consume errors like WriteTooOld
    52  	// without re-evaluating the batch. This behavior isn't particularly
    53  	// desirable, but while it remains, we need to assume that an intent could
    54  	// have been written even when an error is returned. This is harmless if the
    55  	// error is not consumed by the caller because the result will be discarded.
    56  	return result.FromAcquiredLocks(h.Txn, args.Key), err
    57  }