65 lines
1.7 KiB
Python
65 lines
1.7 KiB
Python
from typing import List, Optional, Union, Dict, Any
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.song import Song
|
|
from app.schemas.song import SongCreate, SongUpdate
|
|
|
|
|
|
def get_song(db: Session, song_id: int) -> Optional[Song]:
|
|
return db.query(Song).filter(Song.id == song_id).first()
|
|
|
|
|
|
def get_songs(
|
|
db: Session,
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
artist_id: Optional[int] = None,
|
|
album_id: Optional[int] = None,
|
|
search: Optional[str] = None
|
|
) -> List[Song]:
|
|
query = db.query(Song)
|
|
if artist_id:
|
|
query = query.filter(Song.artist_id == artist_id)
|
|
if album_id:
|
|
query = query.filter(Song.album_id == album_id)
|
|
if search:
|
|
query = query.filter(Song.title.ilike(f"%{search}%"))
|
|
return query.offset(skip).limit(limit).all()
|
|
|
|
|
|
def create_song(db: Session, obj_in: SongCreate) -> Song:
|
|
db_obj = Song(
|
|
title=obj_in.title,
|
|
duration=obj_in.duration,
|
|
file_path=obj_in.file_path,
|
|
track_number=obj_in.track_number,
|
|
artist_id=obj_in.artist_id,
|
|
album_id=obj_in.album_id,
|
|
)
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def update_song(
|
|
db: Session, *, db_obj: Song, obj_in: Union[SongUpdate, Dict[str, Any]]
|
|
) -> Song:
|
|
if isinstance(obj_in, dict):
|
|
update_data = obj_in
|
|
else:
|
|
update_data = obj_in.dict(exclude_unset=True)
|
|
for field in update_data:
|
|
if hasattr(db_obj, field):
|
|
setattr(db_obj, field, update_data[field])
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def delete_song(db: Session, *, id: int) -> None:
|
|
song = db.query(Song).get(id)
|
|
if song:
|
|
db.delete(song)
|
|
db.commit() |