Files
butterfliu/internal/repository/library.go
lzw-723 55c017f60d
All checks were successful
Go CI / test-and-build (push) Successful in 11s
拆分LibraryRepository
2026-04-08 14:42:52 +08:00

109 lines
2.7 KiB
Go

package repository
import (
"butterfliu/internal/model"
"database/sql"
)
type LibraryRepository struct {
db *sql.DB
}
func NewLibraryRepository(db *sql.DB) *LibraryRepository {
return &LibraryRepository{db: db}
}
func (r *LibraryRepository) GetAll() ([]model.Library, error) {
rows, err := r.db.Query("SELECT id, name, path, created_at, updated_at FROM libraries")
if err != nil {
return nil, err
}
defer rows.Close()
libraries := []model.Library{}
for rows.Next() {
var lib model.Library
if err := rows.Scan(&lib.ID, &lib.Name, &lib.Path, &lib.CreatedAt, &lib.UpdatedAt); err != nil {
return nil, err
}
libraries = append(libraries, lib)
}
return libraries, nil
}
func (r *LibraryRepository) GetByID(id int) (model.Library, error) {
row := r.db.QueryRow("SELECT id, name, path, COALESCE(created_at, '1970-01-01T00:00:00Z'), COALESCE(updated_at, '1970-01-01T00:00:00Z') FROM libraries WHERE id = ?", id)
var lib model.Library
if err := row.Scan(&lib.ID, &lib.Name, &lib.Path, &lib.CreatedAt, &lib.UpdatedAt); err != nil {
return model.Library{}, err
}
return lib, nil
}
func (r *LibraryRepository) Create(name, path string) (model.Library, error) {
result, err := r.db.Exec("INSERT INTO libraries (name, path) VALUES (?, ?)", name, path)
if err != nil {
return model.Library{}, err
}
id, err := result.LastInsertId()
if err != nil {
return model.Library{}, err
}
return model.Library{
ID: int(id),
Name: name,
Path: path,
}, nil
}
func (r *LibraryRepository) UpdateName(id int, name string) error {
_, err := r.db.Exec("UPDATE libraries SET name = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", name, id)
return err
}
func (r *LibraryRepository) UpdatePath(id int, path string) error {
_, err := r.db.Exec("UPDATE libraries SET path = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", path, id)
return err
}
func (r *LibraryRepository) Delete(id int) error {
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()
}