package Database
|
|
|
|
import (
|
|
"log"
|
|
|
|
"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"
|
|
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const (
|
|
dbURL = "postgres://postgres:password@postgres:5432/capsule"
|
|
dbTestURL = "postgres://postgres:password@postgres-testing:5432/capsule-testing"
|
|
)
|
|
|
|
// 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)
|
|
}
|
|
}
|