diff --git a/src/lib/db/migrations/2023-09-30.ts b/src/lib/db/migrations/2023-09-30.ts new file mode 100644 index 0000000..4db6454 --- /dev/null +++ b/src/lib/db/migrations/2023-09-30.ts @@ -0,0 +1,21 @@ +import type { Kysely, Migration } from 'kysely'; +import { sql } from 'kysely'; + +export const Migration20230930: Migration = { + async up(db: Kysely) { + await db + .deleteFrom('tag') + .where('id', 'not in', ({ selectFrom }: any) => selectFrom('noteTag').select('tagId')) + .execute(); + + await sql` + CREATE TRIGGER noteTagDeleteUnusedTagTrigger AFTER DELETE ON noteTag + BEGIN + DELETE FROM tag WHERE id = old.tagId AND (SELECT COUNT(*) FROM noteTag WHERE tagId = old.tagId) = 0; + END; + `.execute(db); + }, + async down(db: Kysely) { + await sql`DROP TRIGGER noteTagDeleteUnusedTagTrigger`.execute(db); + }, +}; diff --git a/src/lib/db/migrations/index.ts b/src/lib/db/migrations/index.ts index b1473be..e72d12b 100644 --- a/src/lib/db/migrations/index.ts +++ b/src/lib/db/migrations/index.ts @@ -1,6 +1,8 @@ import type { Migration } from 'kysely'; import { Migration20230830 } from './2023-08-30'; +import { Migration20230930 } from './2023-09-30'; export const migrations: Record = { '2023-08-30': Migration20230830, + '2023-09-30': Migration20230930, }; diff --git a/src/lib/stores/note-tags.ts b/src/lib/stores/note-tags.ts index d8dc0be..21bfb3c 100644 --- a/src/lib/stores/note-tags.ts +++ b/src/lib/stores/note-tags.ts @@ -54,28 +54,18 @@ export class NoteTagsStore implements Readable { }; remove = async (tagId: Tag['id']) => { - const noteId = this.noteId; - - await db.transaction().execute(async (trx) => { - await trx - .deleteFrom('noteTag') - .where('noteId', '=', noteId) - .where('tagId', '=', tagId) - .executeTakeFirstOrThrow(); - const remainingTagUsage = await trx - .selectFrom('noteTag') - .where('tagId', '=', tagId) - .select('tagId') - .executeTakeFirst(); - - if (!remainingTagUsage) { - await trx.deleteFrom('tag').where('id', '=', tagId).executeTakeFirstOrThrow(); - } - }); + const [deletedNoteTag] = await db + .deleteFrom('noteTag') + .where('noteId', '=', this.noteId) + .where('tagId', '=', tagId) + .returningAll() + .execute(); this.refreshTags(); this.notes.refreshNotes(); this.tags.refreshTags(); + + return deletedNoteTag; }; search = async (searchString: string): Promise => {