package Database import ( "log" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" "gorm.io/driver/postgres" "gorm.io/gorm" ) const ( dbURL = "postgres://postgres:@localhost:5432/envelope" dbTestURL = "postgres://postgres:@localhost:5432/envelope_test" ) // DB db var DB *gorm.DB func getModels() []interface{} { return []interface{}{ &Models.Session{}, &Models.Attachment{}, &Models.User{}, &Models.FriendRequest{}, &Models.MessageData{}, &Models.Message{}, &Models.ConversationDetail{}, &Models.ConversationDetailUser{}, &Models.UserConversation{}, } } // Init initializes the database connection func Init() { var ( model interface{} 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...") for _, model = range getModels() { err = DB.AutoMigrate(model) if err != nil { log.Fatalln(err) } } } // InitTest initializes the test datbase func InitTest() { var ( model interface{} err error ) DB, err = gorm.Open(postgres.Open(dbTestURL), &gorm.Config{}) if err != nil { log.Fatalln(err) } for _, model = range getModels() { DB.Migrator().DropTable(model) DB.AutoMigrate(model) } }