diff --git a/core/src/main/groovy/com/jdbernard/wdiwtlt/db/DbApi.groovy b/core/src/main/groovy/com/jdbernard/wdiwtlt/db/DbApi.groovy index 230e284..ae74c06 100644 --- a/core/src/main/groovy/com/jdbernard/wdiwtlt/db/DbApi.groovy +++ b/core/src/main/groovy/com/jdbernard/wdiwtlt/db/DbApi.groovy @@ -560,7 +560,7 @@ public class DbApi { if (params.mediaFileId) { query.append(' AND mf.media_file_id = ? ') - sqlParam << params.mediaFileId } + sqlParams << params.mediaFileId } if (params.albumId) { query.append(' JOIN albums_media_files almf ON ') @@ -834,15 +834,30 @@ public class DbApi { def tagPlaceHolders = tags.collect { '?' }.join(', ') def tagIds = tags.collect { it.id } - String deleteQuery = """ + String unassociateTagQuery = """ DELETE FROM media_files_tags WHERE tag_id IN ($tagPlaceHolders) AND media_file_id = ?""" + String checkTagUseQuery = + 'SELECT * FROM media_files_tags WHERE tag_id = ?' + + String deleteTagQuery = 'DELETE FROM tags WHERE id = ?' + mediaFileIds.each { mfId -> def params = tagIds + mfId logger.debug('Removing tags.\n\tSQL: {}\n\tPARAMS: {}', - deleteQuery, params) - sql.execute(deleteQuery, params) } } } + unassociateTagQuery, params) + sql.execute(unassociateTagQuery, params) } + + tags.each { tag -> + def params = [tag.id] + logger.debug( + 'Checking if tag is still in use.\n\tSQL: {}\n\tPARAMS: {}', + checkTagUseQuery, params) + if (sql.rows(checkTagUseQuery, params).size() == 0) { + logger.debug('Deleting unused tag.\n\tSQL: {}, PARAMS: {}', + deleteTagQuery, params) + sql.execute(deleteTagQuery, params) } } } } /// ### Utility functions public def withTransaction(Closure c) {