connection.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package main
  2. import (
  3. "fmt"
  4. "gorm.io/gorm"
  5. "gorm.io/driver/mysql"
  6. )
  7. type ConnectionProperties struct {
  8. User string
  9. Pass string
  10. Host string
  11. Db string
  12. }
  13. type Connection struct {
  14. GormDb *gorm.DB
  15. DbOpenStr string
  16. ConnProperties ConnectionProperties
  17. }
  18. func (c *Connection) Init() {
  19. c.ConnProperties.User = appSettings.DbUser
  20. c.ConnProperties.Pass = appSettings.DbPassword
  21. c.ConnProperties.Host = appSettings.DbHost
  22. c.ConnProperties.Db = appSettings.DbName
  23. c.DbOpenStr = fmt.Sprintf("%s:%s@tcp(%s)/%s", c.ConnProperties.User, c.ConnProperties.Pass, c.ConnProperties.Host, c.ConnProperties.Db)
  24. LogInfo.Println("Connecting with:")
  25. LogInfo.Println(c.DbOpenStr)
  26. gormDb, err := gorm.Open(mysql.Open(c.DbOpenStr), &gorm.Config{})
  27. if err != nil {
  28. LogError.Println("failed to connect database")
  29. LogError.Println(err)
  30. } else {
  31. LogInfo.Println("Connected to database using gorm")
  32. }
  33. c.GormDb = gormDb
  34. }
  35. func (c *Connection) LatestWorkerRecord(worker string) (lastWorkerRecord Worker, err error) {
  36. result := c.GormDb.
  37. Where("worker = ?", worker).
  38. Order("time desc").
  39. Limit(1).
  40. Find(&lastWorkerRecord)
  41. return lastWorkerRecord, result.Error
  42. }
  43. func (c *Connection) LatestMinerRecord(wallet string) (lastMinerRecord Miner, err error) {
  44. result := c.GormDb.
  45. Where("wallet = ?", wallet).
  46. Order("time desc").
  47. Limit(1).
  48. Find(&lastMinerRecord)
  49. return lastMinerRecord, result.Error
  50. }
  51. func (c *Connection) ChatsWithWallet(wallet string) (ChatIds []int64, err error) {
  52. result := c.GormDb.Model(&User{}).
  53. Where("wallet = ?", wallet).
  54. Select("chat_id").
  55. Scan(&ChatIds)
  56. return ChatIds, result.Error
  57. }
  58. func (c *Connection) IsWorkerRowExists(worker string, time int64) (exists bool, err error) {
  59. var rowsCount int64
  60. result := c.GormDb.Model(&Worker{}).
  61. Where("worker = ? and time = ?", worker, time).
  62. Count(&rowsCount)
  63. if result.Error != nil {
  64. return false , result.Error
  65. }
  66. if rowsCount != 0 {
  67. return true, nil
  68. }
  69. return false, nil
  70. }
  71. // List of unique, not empty wallets in user table
  72. func (c *Connection) UniqueWallets() (wallets []string, err error) {
  73. result := c.GormDb.Model(&User{}).
  74. Not("wallet = ?", "").
  75. Select("DISTINCT(wallet)").
  76. Scan(&wallets)
  77. return wallets, result.Error
  78. }