android_catalogue1-7 Exercise 2: Delete Unused Tags ==================================================== DAO (TagDao): @Query("DELETE FROM tag WHERE id NOT IN (SELECT tagId FROM item_tag)") suspend fun deleteUnused() Repository: suspend fun deleteUnusedTags() = tagDao.deleteUnused() Where to call it: after something that can leave a tag unused: - after deleting an item (Chapter 5's delete), and - after saving an edit that removed a tag from an item. The simplest single place is inside the repository's own saveItemWithTagNames and deleteItem, after the writes. Inside the same transaction as the save, it is convenient because the clean-up is atomic with the change: no moment where the tag list is out of step with the links. The risk: the tag a user just typed but the item did not end up using would be deleted in the same step, and, more importantly, a bug in the query (for example a wrong table name, or NOT IN against a column containing NULL) would run on every save and could delete tags that are in use. NOT IN with a subquery returning NULL matches nothing, which here is safe; but in general test destructive queries on their own first. Design alternative: do not delete automatically, but offer "Delete unused tags" on a settings screen, so the user decides. For a personal catalogue, unused tags are harmless and may be useful as pre-planned categories, so many people would prefer that.