From c92aec14d328ba58400699d6fab21f96e950e891 Mon Sep 17 00:00:00 2001 From: Thomas Richter Date: Sun, 1 Feb 2026 23:13:50 +0100 Subject: [PATCH] feat: auto-cleanup orphaned tags when removed from entries Tags that are no longer associated with any entry are automatically deleted from the database when a tag is removed from an entry. Co-Authored-By: Claude Opus 4.5 --- src/lib/server/db/repository.ts | 10 ++++++++++ src/routes/+page.server.ts | 3 +++ 2 files changed, 13 insertions(+) diff --git a/src/lib/server/db/repository.ts b/src/lib/server/db/repository.ts index e4dadee..c4715db 100644 --- a/src/lib/server/db/repository.ts +++ b/src/lib/server/db/repository.ts @@ -158,6 +158,7 @@ export interface TagRepository { getById(id: string): Tag | undefined; getByEntryId(entryId: string): Tag[]; updateEntryTags(entryId: string, tagNames: string[]): void; + cleanupOrphanedTags(): number; } class SQLiteTagRepository implements TagRepository { @@ -215,6 +216,15 @@ class SQLiteTagRepository implements TagRepository { db.insert(entryTags).values({ entryId, tagId: tag.id }).run(); } } + + cleanupOrphanedTags(): number { + // Delete tags that are not associated with any entry + const result = db.run(sql` + DELETE FROM tags + WHERE id NOT IN (SELECT DISTINCT tag_id FROM entry_tags) + `); + return result.changes; + } } export const tagRepository: TagRepository = new SQLiteTagRepository(); diff --git a/src/routes/+page.server.ts b/src/routes/+page.server.ts index 4539bb9..ea4f215 100644 --- a/src/routes/+page.server.ts +++ b/src/routes/+page.server.ts @@ -342,6 +342,9 @@ export const actions: Actions = { ); tagRepository.updateEntryTags(id, updatedTags); + // Clean up orphaned tags + tagRepository.cleanupOrphanedTags(); + return { success: true }; } };