github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/kv/kvserver/batcheval/cmd_increment.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.Increment, DefaultDeclareIsolatedKeys, Increment)
    23  }
    24  
    25  // Increment increments the value (interpreted as varint64 encoded) and
    26  // returns the newly incremented value (encoded as varint64). If no value
    27  // exists for the key, zero is incremented.
    28  func Increment(
    29  	ctx context.Context, readWriter storage.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
    30  ) (result.Result, error) {
    31  	args := cArgs.Args.(*roachpb.IncrementRequest)
    32  	h := cArgs.Header
    33  	reply := resp.(*roachpb.IncrementResponse)
    34  
    35  	newVal, err := storage.MVCCIncrement(ctx, readWriter, cArgs.Stats, args.Key, h.Timestamp, h.Txn, args.Increment)
    36  	reply.NewValue = newVal
    37  	// NB: even if MVCC returns an error, it may still have written an intent
    38  	// into the batch. This allows callers to consume errors like WriteTooOld
    39  	// without re-evaluating the batch. This behavior isn't particularly
    40  	// desirable, but while it remains, we need to assume that an intent could
    41  	// have been written even when an error is returned. This is harmless if the
    42  	// error is not consumed by the caller because the result will be discarded.
    43  	return result.FromAcquiredLocks(h.Txn, args.Key), err
    44  }