scan.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package repository
  2. import (
  3. "fmt"
  4. "github.com/felamaslen/go-music-player/pkg/config"
  5. "github.com/felamaslen/go-music-player/pkg/database"
  6. "github.com/felamaslen/go-music-player/pkg/logger"
  7. "github.com/felamaslen/go-music-player/pkg/read"
  8. )
  9. func InsertMusicIntoDatabase(songs chan *read.Song) {
  10. var l = logger.CreateLogger(config.GetConfig().LogLevel)
  11. db := database.GetConnection()
  12. for {
  13. select {
  14. case song, more := <- songs:
  15. if !more {
  16. l.Verbose("Finished inserting songs\n")
  17. return
  18. }
  19. l.Debug("Adding song: %v\n", song)
  20. duration := "NULL"
  21. if song.DurationOk {
  22. duration = fmt.Sprintf("%d", song.Duration)
  23. }
  24. query, err := db.Query(
  25. `
  26. insert into songs (
  27. title
  28. ,track_number
  29. ,artist
  30. ,album
  31. ,duration
  32. ,base_path
  33. ,relative_path
  34. ,modified_date
  35. )
  36. values ($1, $2, $3, $4, $5, $6, $7, $8)
  37. on conflict (base_path, relative_path) do update
  38. set
  39. title = excluded.title
  40. ,track_number = excluded.track_number
  41. ,artist = excluded.artist
  42. ,album = excluded.album
  43. ,duration = excluded.duration
  44. ,modified_date = excluded.modified_date
  45. `,
  46. song.Title,
  47. song.TrackNumber,
  48. song.Artist,
  49. song.Album,
  50. duration,
  51. song.BasePath,
  52. song.RelativePath,
  53. song.ModifiedDate,
  54. )
  55. query.Close()
  56. if err == nil {
  57. l.Info("Added %s\n", song.RelativePath)
  58. } else {
  59. l.Error("Error inserting record: %s\n", err)
  60. }
  61. }
  62. }
  63. }