package Database
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const (
|
|
PageSize = 20
|
|
)
|
|
|
|
var (
|
|
dbURL string
|
|
dbTestURL string
|
|
)
|
|
|
|
// DB db
|
|
var DB *gorm.DB
|
|
|
|
var models = []interface{}{
|
|
&Session{},
|
|
&Attachment{},
|
|
&User{},
|
|
&FriendRequest{},
|
|
&MessageData{},
|
|
&Message{},
|
|
&ConversationDetail{},
|
|
&ConversationDetailUser{},
|
|
&UserConversation{},
|
|
&DeviceToken{},
|
|
&FriendRequestDeviceToken{},
|
|
}
|
|
|
|
// Init initializes the database connection
|
|
func Init() {
|
|
var (
|
|
err error
|
|
)
|
|
|
|
log.Println("Initializing database...")
|
|
|
|
dbURL = fmt.Sprintf(
|
|
"postgres://%s:%s@%s:%s/%s",
|
|
os.Getenv("DB_USER"),
|
|
os.Getenv("DB_PASSWORD"),
|
|
os.Getenv("DB_HOST"),
|
|
os.Getenv("DB_PORT"),
|
|
os.Getenv("DB_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
|
|
)
|
|
|
|
dbTestURL = fmt.Sprintf(
|
|
"postgres://%s:%s@%s:%s/%s",
|
|
os.Getenv("DB_TESTING_USER"),
|
|
os.Getenv("DB_TESTING_PASSWORD"),
|
|
os.Getenv("DB_TESTING_HOST"),
|
|
os.Getenv("DB_TESTING_PORT"),
|
|
os.Getenv("DB_TESTING_DATABASE"),
|
|
)
|
|
|
|
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)
|
|
}
|
|
}
|