From 7ef83d0a19ff1efcb647e25389f97be47cf295de Mon Sep 17 00:00:00 2001 From: Balaji Viswanathan Date: Tue, 7 Feb 2017 12:52:31 +0530 Subject: [PATCH] FAB-2085: Chaincode explicitly manages indices This chaincode example uses PartialCompositeKeyQuery using a composite key index color~name. On delete of a marble from state, the appropriate index entry also needs to be cleanedup Change-Id: I936b864ecf6902a45fa1a089224d674c419afa30 Signed-off-by: Balaji Viswanathan --- .../go/marbles02/marbles_chaincode.go | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/examples/chaincode/go/marbles02/marbles_chaincode.go b/examples/chaincode/go/marbles02/marbles_chaincode.go index baa6d960769..534fd70b58b 100644 --- a/examples/chaincode/go/marbles02/marbles_chaincode.go +++ b/examples/chaincode/go/marbles02/marbles_chaincode.go @@ -210,16 +210,46 @@ func (t *SimpleChaincode) readMarble(stub shim.ChaincodeStubInterface, args []st // delete - remove a marble key/value pair from state // ================================================== func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response { + var jsonResp string + var marbleJSON marble if len(args) != 1 { return shim.Error("Incorrect number of arguments. Expecting 1") } - marbleName := args[0] - err := stub.DelState(marbleName) //remove the marble from chaincode state + + // to maintain the color~name index, we need to read the marble first and get its color + valAsbytes, err := stub.GetState(marbleName) //get the marble from chaincode state + if err != nil { + jsonResp = "{\"Error\":\"Failed to get state for " + marbleName + "\"}" + return shim.Error(jsonResp) + } else if valAsbytes == nil { + jsonResp = "{\"Error\":\"Marble does not exist: " + marbleName + "\"}" + return shim.Error(jsonResp) + } + + err = json.Unmarshal([]byte(jsonResp), &marbleJSON) + if err != nil { + jsonResp = "{\"Error\":\"Failed to decode JSON of: " + marbleName + "\"}" + return shim.Error(jsonResp) + } + + err = stub.DelState(marbleName) //remove the marble from chaincode state if err != nil { return shim.Error("Failed to delete state:" + err.Error()) } + // maintain the index + indexName := "color~name" + colorNameIndexKey, err := stub.CreateCompositeKey(indexName, []string{marbleJSON.Color, marbleJSON.Name}) + if err != nil { + return shim.Error(err.Error()) + } + + // Delete index entry to state. + err = stub.DelState(colorNameIndexKey) + if err != nil { + return shim.Error("Failed to delete state:" + err.Error()) + } return shim.Success(nil) }