songs.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package repository
  2. import (
  3. "github.com/felamaslen/gmus-backend/pkg/read"
  4. "github.com/jmoiron/sqlx"
  5. "github.com/lib/pq"
  6. )
  7. const BATCH_SIZE = 100
  8. func SelectSong(db *sqlx.DB, ids []int) (songs *[]*read.Song, err error) {
  9. songs = &[]*read.Song{}
  10. var idsArray pq.Int64Array
  11. for _, id := range ids {
  12. idsArray = append(idsArray, int64(id))
  13. }
  14. err = db.Select(songs, querySelectSongById, idsArray)
  15. return
  16. }
  17. func SelectPagedArtists(db *sqlx.DB, limit int, offset int) (artists *[]string, err error) {
  18. artists = &[]string{}
  19. err = db.Select(artists, querySelectArtistsOrdered, limit, offset)
  20. return
  21. }
  22. type CountRow struct {
  23. Count int `db:"count"`
  24. }
  25. func SelectArtistCount(db *sqlx.DB) (count int, err error) {
  26. var countRow CountRow
  27. err = db.QueryRowx(queryCountArtists).StructScan(&countRow)
  28. count = countRow.Count
  29. return
  30. }
  31. func SelectAllArtists(db *sqlx.DB) (artists *[]string, err error) {
  32. artists = &[]string{}
  33. err = db.Select(artists, `select distinct artist from songs order by artist`)
  34. return
  35. }
  36. func SelectAlbumsByArtist(db *sqlx.DB, artist string) (albums *[]string, err error) {
  37. albums = &[]string{}
  38. err = db.Select(albums, querySelectAlbumsByArtist, artist)
  39. return
  40. }
  41. func SelectSongsByArtist(db *sqlx.DB, artist string) (songs *[]*read.SongExternal, err error) {
  42. songs = &[]*read.SongExternal{}
  43. err = db.Select(songs, querySelectSongsByArtist, artist)
  44. return
  45. }
  46. func BatchUpsertSongs(db *sqlx.DB, batch *[BATCH_SIZE]*read.Song, batchSize int) error {
  47. var trackNumbers pq.Int64Array
  48. var titles pq.StringArray
  49. var artists pq.StringArray
  50. var albums pq.StringArray
  51. var durations pq.Int64Array
  52. var modifiedDates pq.Int64Array
  53. var basePaths pq.StringArray
  54. var relativePaths pq.StringArray
  55. for i := 0; i < batchSize; i++ {
  56. trackNumbers = append(trackNumbers, int64((*batch)[i].TrackNumber))
  57. titles = append(titles, (*batch)[i].Title)
  58. artists = append(artists, (*batch)[i].Artist)
  59. albums = append(albums, (*batch)[i].Album)
  60. durations = append(durations, int64((*batch)[i].Duration))
  61. modifiedDates = append(modifiedDates, (*batch)[i].ModifiedDate)
  62. basePaths = append(basePaths, (*batch)[i].BasePath)
  63. relativePaths = append(relativePaths, (*batch)[i].RelativePath)
  64. }
  65. _, err := db.Exec(
  66. queryInsertSongs,
  67. trackNumbers,
  68. titles,
  69. artists,
  70. albums,
  71. durations,
  72. modifiedDates,
  73. basePaths,
  74. relativePaths,
  75. )
  76. return err
  77. }