diff --git a/persistence/repositories/tag_repository.go b/persistence/repositories/tag_repository.go index 844ccc1..0906a5f 100644 --- a/persistence/repositories/tag_repository.go +++ b/persistence/repositories/tag_repository.go @@ -48,3 +48,36 @@ func (r *tagRepository) Upsert(names []string) error { return tx.Commit() } + +func (r *tagRepository) UpsertNoteTags(noteID int64, tagIDs []int64) error { + if len(tagIDs) == 0 { + return nil + } + + tx, err := r.db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + placeholders := make([]string, 0, len(tagIDs)) + args := make([]any, 0, len(tagIDs)) + + for _, tagID := range tagIDs { + placeholders = append(placeholders, "(?, ?)") + args = append(args, noteID, tagID) + } + + query := "WITH input(note_id, tag_id) AS (VALUES " + + strings.Join(placeholders, ",") + + ") INSERT INTO note_tags(note_id, tag_id) " + + "SELECT note_id, tag_id FROM input " + + "ON CONFLICT(note_id, tag_id) DO NOTHING" + + "SELECT note_id, tag_id FROM input;" + + if _, err := tx.Exec(query, args...); err != nil { + return err + } + + return tx.Commit() +}