Brijesh's Git Server — k3yst0n3 @ 47493b53290ea602660736c157d63e1fa708e704

database/database.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
package database

import (
	"fmt"
	"k3yst0n3/helpers"
	"k3yst0n3/models"
	"log"
	"os"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type DbinstanceType struct {
	DB *gorm.DB
}

var DBInstance DbinstanceType

func ConnectDb() {
	dsn := fmt.Sprintf(
		// "host=postgres user=%s password=%s dbname=%s port=5432 sslmode=disable TimeZone=Asia/Shanghai",
		"host=postgres user=%s password=%s dbname=%s port=5432 sslmode=disable TimeZone=UTC",
		helpers.GetEnv("POSTGRES_USER"),
		helpers.GetEnv("POSTGRES_PASSWORD"),
		helpers.GetEnv("POSTGRES_DB"),
	)

	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		log.Fatal("Failed to connect to database. \n", err)
		os.Exit(2)
	}

	log.Println("connected")
	db.Logger = logger.Default.LogMode(logger.Info)

	log.Println("running migrations")
	db.AutoMigrate(&models.User{})
	db.AutoMigrate(&models.Application{})
	db.AutoMigrate(&models.Event{})

	DBInstance = DbinstanceType{
		DB: db,
	}
}