in aws-datastore/src/main/java/com/amplifyframework/datastore/storage/sqlite/SQLiteStorageAdapter.java [461:541]
public <T extends Model> void delete(
@NonNull T item,
@NonNull StorageItemChange.Initiator initiator,
@NonNull QueryPredicate predicate,
@NonNull Consumer<StorageItemChange<T>> onSuccess,
@NonNull Consumer<DataStoreException> onError
) {
Objects.requireNonNull(item);
Objects.requireNonNull(initiator);
Objects.requireNonNull(predicate);
Objects.requireNonNull(onSuccess);
Objects.requireNonNull(onError);
threadPool.submit(() -> {
try {
final String modelName = item.getModelName();
final ModelSchema modelSchema = schemaRegistry.getModelSchemaForModelClass(modelName);
// Check if data being deleted exists; "Succeed" deletion in that case.
if (!sqlQueryProcessor.modelExists(item, QueryPredicates.all())) {
LOG.verbose(modelName + " model with id = " + item.getId() + " does not exist.");
// Pass back item change instance without publishing it.
onSuccess.accept(StorageItemChange.<T>builder()
.item(item)
.patchItem(SerializedModel.create(item, modelSchema))
.modelSchema(modelSchema)
.type(StorageItemChange.Type.DELETE)
.predicate(predicate)
.initiator(initiator)
.build());
return;
}
// Check if existing data meets the condition, only if a condition other than all() was provided.
if (!QueryPredicates.all().equals(predicate) && !sqlQueryProcessor.modelExists(item, predicate)) {
throw new DataStoreException(
"Deletion failed because condition did not match existing model instance.",
"The deletion will continue to fail until the model instance is updated."
);
}
// identify items affected by cascading delete before deleting them
List<Model> cascadedModels = sqliteModelTree.descendantsOf(Collections.singleton(item));
// execute local deletion
writeData(item, StorageItemChange.Type.DELETE);
// publish cascaded deletions
for (Model cascadedModel : cascadedModels) {
ModelSchema schema = schemaRegistry.getModelSchemaForModelClass(cascadedModel.getModelName());
itemChangeSubject.onNext(StorageItemChange.builder()
.item(cascadedModel)
.patchItem(SerializedModel.create(cascadedModel, schema))
.modelSchema(schema)
.type(StorageItemChange.Type.DELETE)
.predicate(QueryPredicates.all())
.initiator(initiator)
.build());
}
// publish successful deletion of top-level item
StorageItemChange<T> change = StorageItemChange.<T>builder()
.item(item)
.patchItem(SerializedModel.create(item, modelSchema))
.modelSchema(modelSchema)
.type(StorageItemChange.Type.DELETE)
.predicate(predicate)
.initiator(initiator)
.build();
itemChangeSubject.onNext(change);
onSuccess.accept(change);
} catch (DataStoreException dataStoreException) {
onError.accept(dataStoreException);
} catch (Exception someOtherTypeOfException) {
DataStoreException dataStoreException = new DataStoreException(
"Error in deleting the model.", someOtherTypeOfException,
"See attached exception for details."
);
onError.accept(dataStoreException);
}
});
}