scan.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. ,artist
  29. ,album
  30. ,duration
  31. ,base_path
  32. ,relative_path
  33. ,modified_date
  34. )
  35. values ($1, $2, $3, $4, $5, $6, $7)
  36. on conflict (base_path, relative_path) do update
  37. set
  38. title = excluded.title
  39. ,artist = excluded.artist
  40. ,album = excluded.album
  41. ,duration = excluded.duration
  42. ,modified_date = excluded.modified_date
  43. `,
  44. song.Title,
  45. song.Artist,
  46. song.Album,
  47. duration,
  48. song.BasePath,
  49. song.RelativePath,
  50. song.ModifiedDate,
  51. )
  52. query.Close()
  53. if err == nil {
  54. l.Info("Added %s\n", song.RelativePath)
  55. } else {
  56. l.Error("Error inserting record: %s\n", err)
  57. }
  58. }
  59. }
  60. }