Skip to content

Commit 7ef83d0

Browse files
committed
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 <[email protected]>
1 parent ee1226d commit 7ef83d0

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

examples/chaincode/go/marbles02/marbles_chaincode.go

+32-2
Original file line numberDiff line numberDiff line change
@@ -210,16 +210,46 @@ func (t *SimpleChaincode) readMarble(stub shim.ChaincodeStubInterface, args []st
210210
// delete - remove a marble key/value pair from state
211211
// ==================================================
212212
func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response {
213+
var jsonResp string
214+
var marbleJSON marble
213215
if len(args) != 1 {
214216
return shim.Error("Incorrect number of arguments. Expecting 1")
215217
}
216-
217218
marbleName := args[0]
218-
err := stub.DelState(marbleName) //remove the marble from chaincode state
219+
220+
// to maintain the color~name index, we need to read the marble first and get its color
221+
valAsbytes, err := stub.GetState(marbleName) //get the marble from chaincode state
222+
if err != nil {
223+
jsonResp = "{\"Error\":\"Failed to get state for " + marbleName + "\"}"
224+
return shim.Error(jsonResp)
225+
} else if valAsbytes == nil {
226+
jsonResp = "{\"Error\":\"Marble does not exist: " + marbleName + "\"}"
227+
return shim.Error(jsonResp)
228+
}
229+
230+
err = json.Unmarshal([]byte(jsonResp), &marbleJSON)
231+
if err != nil {
232+
jsonResp = "{\"Error\":\"Failed to decode JSON of: " + marbleName + "\"}"
233+
return shim.Error(jsonResp)
234+
}
235+
236+
err = stub.DelState(marbleName) //remove the marble from chaincode state
219237
if err != nil {
220238
return shim.Error("Failed to delete state:" + err.Error())
221239
}
222240

241+
// maintain the index
242+
indexName := "color~name"
243+
colorNameIndexKey, err := stub.CreateCompositeKey(indexName, []string{marbleJSON.Color, marbleJSON.Name})
244+
if err != nil {
245+
return shim.Error(err.Error())
246+
}
247+
248+
// Delete index entry to state.
249+
err = stub.DelState(colorNameIndexKey)
250+
if err != nil {
251+
return shim.Error("Failed to delete state:" + err.Error())
252+
}
223253
return shim.Success(nil)
224254
}
225255

0 commit comments

Comments
 (0)