scan.go 1.4 KB

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