Encrypted messaging app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.1 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. package Database
  2. import (
  3. "log"
  4. "gorm.io/driver/postgres"
  5. "gorm.io/gorm"
  6. )
  7. const (
  8. dbURL = "postgres://postgres:password@postgres:5432/capsule"
  9. dbTestURL = "postgres://postgres:password@postgres-testing:5432/capsule-testing"
  10. PageSize = 20
  11. )
  12. // DB db
  13. var DB *gorm.DB
  14. var models = []interface{}{
  15. &Session{},
  16. &Attachment{},
  17. &User{},
  18. &FriendRequest{},
  19. &MessageData{},
  20. &Message{},
  21. &ConversationDetail{},
  22. &ConversationDetailUser{},
  23. &UserConversation{},
  24. }
  25. // Init initializes the database connection
  26. func Init() {
  27. var (
  28. err error
  29. )
  30. log.Println("Initializing database...")
  31. DB, err = gorm.Open(postgres.Open(dbURL), &gorm.Config{})
  32. if err != nil {
  33. log.Fatalln(err)
  34. }
  35. log.Println("Running AutoMigrate...")
  36. err = DB.AutoMigrate(models...)
  37. if err != nil {
  38. log.Fatalln(err)
  39. }
  40. }
  41. // InitTest initializes the test datbase
  42. func InitTest() {
  43. var (
  44. err error
  45. )
  46. DB, err = gorm.Open(postgres.Open(dbTestURL), &gorm.Config{})
  47. if err != nil {
  48. log.Fatalln(err)
  49. }
  50. err = DB.Migrator().DropTable(models...)
  51. if err != nil {
  52. panic(err)
  53. }
  54. err = DB.AutoMigrate(models...)
  55. if err != nil {
  56. panic(err)
  57. }
  58. }