- package Database
-
- import (
- "log"
-
- "gorm.io/driver/postgres"
- "gorm.io/gorm"
- )
-
- const (
- dbURL = "postgres://postgres:password@postgres:5432/capsule"
- dbTestURL = "postgres://postgres:password@postgres-testing:5432/capsule-testing"
-
- PageSize = 20
- )
-
- // DB db
- var DB *gorm.DB
-
- var models = []interface{}{
- &Session{},
- &Attachment{},
- &User{},
- &FriendRequest{},
- &MessageData{},
- &Message{},
- &ConversationDetail{},
- &ConversationDetailUser{},
- &UserConversation{},
- }
-
- // Init initializes the database connection
- func Init() {
- var (
- err error
- )
-
- log.Println("Initializing database...")
-
- DB, err = gorm.Open(postgres.Open(dbURL), &gorm.Config{})
-
- if err != nil {
- log.Fatalln(err)
- }
-
- log.Println("Running AutoMigrate...")
-
- err = DB.AutoMigrate(models...)
- if err != nil {
- log.Fatalln(err)
- }
- }
-
- // InitTest initializes the test datbase
- func InitTest() {
- var (
- err error
- )
-
- DB, err = gorm.Open(postgres.Open(dbTestURL), &gorm.Config{})
-
- if err != nil {
- log.Fatalln(err)
- }
-
- err = DB.Migrator().DropTable(models...)
- if err != nil {
- panic(err)
- }
- err = DB.AutoMigrate(models...)
- if err != nil {
- panic(err)
- }
- }
|