Files
butterfliu/internal/repository/song_repo.go
lzw-723 3aa8057648
All checks were successful
Go CI / test-and-build (push) Successful in 10s
实现数据库级联删除
2026-04-06 16:32:10 +08:00

66 lines
1.6 KiB
Go

package repository
import "database/sql"
type SongRepository struct {
db *sql.DB
}
func NewSongRepository(db *sql.DB) *SongRepository {
return &SongRepository{db: db}
}
func (r *SongRepository) GetAll() ([]Song, error) {
rows, err := r.db.Query("SELECT id, title, artist_id, album_id, duration, media_file_id FROM songs")
if err != nil {
return nil, err
}
defer rows.Close()
songs := []Song{}
for rows.Next() {
var song Song
if err := rows.Scan(&song.ID, &song.Title, &song.ArtistID, &song.AlbumID, &song.Duration, &song.MediaFileID); err != nil {
return nil, err
}
songs = append(songs, song)
}
return songs, nil
}
func (r *SongRepository) GetAllWithDetails() ([]SongDetail, error) {
rows, err := r.db.Query(`
SELECT s.id, s.title, a.name as artist_name, al.title as album_title, s.duration, mf.path
FROM songs s
INNER JOIN media_files mf ON s.media_file_id = mf.id
INNER JOIN artists a ON s.artist_id = a.id
INNER JOIN albums al ON s.album_id = al.id
ORDER BY s.title
`)
if err != nil {
return nil, err
}
defer rows.Close()
songs := []SongDetail{}
for rows.Next() {
var song SongDetail
if err := rows.Scan(&song.ID, &song.Title, &song.Artist, &song.Album, &song.Duration, &song.Path); err != nil {
return nil, err
}
songs = append(songs, song)
}
return songs, nil
}
func (r *SongRepository) Get(id int) (Song, error) {
var song Song
err := r.db.QueryRow("SELECT id, title, artist_id, album_id, duration, media_file_id FROM songs WHERE id = ?", id).Scan(
&song.ID, &song.Title, &song.ArtistID, &song.AlbumID, &song.Duration, &song.MediaFileID,
)
if err != nil {
return Song{}, err
}
return song, nil
}