实现数据库级联删除
All checks were successful
Go CI / test-and-build (push) Successful in 10s

This commit is contained in:
2026-04-06 16:32:10 +08:00
parent 744fa578f1
commit 3aa8057648
5 changed files with 189 additions and 14 deletions

View File

@@ -78,8 +78,41 @@ func (r *LibraryRepository) UpdatePath(id int, path string) error {
}
func (r *LibraryRepository) Delete(id int) error {
_, err := r.db.Exec("DELETE FROM libraries WHERE id = ?", id)
return err
tx, err := r.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
// Delete the library — CASCADE removes media_files and songs automatically
_, err = tx.Exec("DELETE FROM libraries WHERE id = ?", id)
if err != nil {
return err
}
// Clean up orphan albums (no songs reference them)
_, err = tx.Exec(`
DELETE FROM albums WHERE id NOT IN (
SELECT DISTINCT album_id FROM songs WHERE album_id IS NOT NULL
)
`)
if err != nil {
return err
}
// Clean up orphan artists (no songs and no albums reference them)
_, err = tx.Exec(`
DELETE FROM artists WHERE id NOT IN (
SELECT DISTINCT artist_id FROM songs WHERE artist_id IS NOT NULL
UNION
SELECT DISTINCT artist_id FROM albums WHERE artist_id IS NOT NULL
)
`)
if err != nil {
return err
}
return tx.Commit()
}
func (r *LibraryRepository) GetSongsByLibraryWithDetails(libraryID int) ([]SongDetail, error) {