Skip to content

Commit

Permalink
engine/ Improve Readability and Maintainability of Data Purge Functio…
Browse files Browse the repository at this point in the history
…n (purge()) (#2529)

* engine/#2528/improve readability of data purge function

* engine/#2528/spotless check

* Update engine/src/main/java/com/google/android/fhir/db/impl/DatabaseImpl.kt

* Run spotless

---------

Co-authored-by: Jing Tang <[email protected]>
  • Loading branch information
itstanany and jingtang10 committed Jun 6, 2024
1 parent 201a874 commit 4b1c1b2
Showing 1 changed file with 15 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -386,26 +386,22 @@ internal class DatabaseImpl(
override suspend fun purge(type: ResourceType, ids: Set<String>, forcePurge: Boolean) {
db.withTransaction {
ids.forEach { id ->
// To check resource is present in DB else throw ResourceNotFoundException()
// 1. Verify resource presence:
selectEntity(type, id)
val localChangeEntityList = localChangeDao.getLocalChanges(type, id)
// If local change is not available simply delete resource
if (localChangeEntityList.isEmpty()) {
resourceDao.deleteResource(resourceId = id, resourceType = type)
} else {
// local change is available with FORCE_PURGE the delete resource and discard changes from
// localChangeEntity table
if (forcePurge) {
resourceDao.deleteResource(resourceId = id, resourceType = type)
localChangeDao.discardLocalChanges(
token = LocalChangeToken(localChangeEntityList.map { it.id }),
)
} else {
// local change is available but FORCE_PURGE = false then throw exception
throw IllegalStateException(
"Resource with type $type and id $id has local changes, either sync with server or FORCE_PURGE required",
)
}

// 2. Check for local changes (which can only be cleared without syncing in FORCE_PURGE
// mode):
val localChanges = localChangeDao.getLocalChanges(type, id)
if (localChanges.isNotEmpty() && !forcePurge) {
throw IllegalStateException(
"Resource with type $type and id $id has local changes, either sync with server or FORCE_PURGE required",
)
}

// 3. Delete resource and discard local changes (if applicable):
resourceDao.deleteResource(id, type)
if (localChanges.isNotEmpty()) {
localChangeDao.discardLocalChanges(id, type)
}
}
}
Expand Down

0 comments on commit 4b1c1b2

Please sign in to comment.