/model/model.go

https://github.com/indes/flowerss-bot · Go · 64 lines · 49 code · 11 blank · 4 comment · 8 complexity · 65ea7e61c1f951958d5cc577569e4269 MD5 · raw file

  1. package model
  2. import (
  3. "github.com/indes/flowerss-bot/config"
  4. "github.com/indes/flowerss-bot/log"
  5. "github.com/jinzhu/gorm"
  6. "go.uber.org/zap"
  7. _ "github.com/jinzhu/gorm/dialects/mysql" //mysql driver
  8. _ "github.com/jinzhu/gorm/dialects/sqlite"
  9. "moul.io/zapgorm"
  10. "time"
  11. )
  12. var db *gorm.DB
  13. // ConnectDB connect to db and update table
  14. func ConnectDB() {
  15. if config.RunMode == config.TestMode {
  16. return
  17. }
  18. var err error
  19. if config.EnableMysql {
  20. db, err = gorm.Open("mysql", config.Mysql.GetMysqlConnectingString())
  21. } else {
  22. db, err = gorm.Open("sqlite3", config.SQLitePath)
  23. }
  24. if err != nil {
  25. log.Logger.Fatal(err.Error())
  26. }
  27. db.DB().SetMaxIdleConns(10)
  28. db.DB().SetMaxOpenConns(50)
  29. db.LogMode(true)
  30. db.SetLogger(zapgorm.New(log.Logger.WithOptions(zap.AddCallerSkip(7))))
  31. createOrUpdateTable(&Subscribe{})
  32. createOrUpdateTable(&User{})
  33. createOrUpdateTable(&Source{})
  34. createOrUpdateTable(&Option{})
  35. createOrUpdateTable(&Content{})
  36. }
  37. // Disconnect disconnects from the database.
  38. func Disconnect() {
  39. db.Close()
  40. }
  41. // createOrUpdateTable create table or Migrate table
  42. func createOrUpdateTable(model interface{}) {
  43. if !db.HasTable(model) {
  44. db.CreateTable(model)
  45. } else {
  46. db.AutoMigrate(model)
  47. }
  48. }
  49. //EditTime timestamp
  50. type EditTime struct {
  51. CreatedAt time.Time
  52. UpdatedAt time.Time
  53. }