scan.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package repository
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/felamaslen/go-music-player/pkg/config"
  6. "github.com/felamaslen/go-music-player/pkg/db"
  7. "github.com/felamaslen/go-music-player/pkg/logger"
  8. "github.com/felamaslen/go-music-player/pkg/read"
  9. )
  10. func InsertMusicIntoDatabase(songs chan *read.Song) {
  11. var l = logger.CreateLogger(config.GetConfig().LogLevel)
  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. conn := db.GetConnection()
  25. _, err := conn.Query(
  26. context.Background(),
  27. "insert into songs (title, artist, album, duration, base_path, relative_path) values ($1, $2, $3, $4, $5, $6)",
  28. song.Title,
  29. song.Artist,
  30. song.Album,
  31. duration,
  32. song.BasePath,
  33. song.RelativePath,
  34. )
  35. conn.Conn().Close(context.Background())
  36. if err != nil {
  37. l.Error("Error inserting record: %s\n", err)
  38. }
  39. }
  40. }
  41. }