modelRT/database/postgres_init.go

39 lines
918 B
Go

// Package database define database operation functions
package database
import (
"sync"
"modelRT/logger"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var (
postgresOnce sync.Once
_globalPostgresClient *gorm.DB
)
// GetPostgresDBClient returns the global PostgresDB client.It's safe for concurrent use.
func GetPostgresDBClient() *gorm.DB {
return _globalPostgresClient
}
// InitPostgresDBInstance return instance of PostgresDB client
func InitPostgresDBInstance(PostgresDBURI string) *gorm.DB {
postgresOnce.Do(func() {
_globalPostgresClient = initPostgresDBClient(PostgresDBURI)
})
return _globalPostgresClient
}
// initPostgresDBClient return successfully initialized PostgresDB client
func initPostgresDBClient(PostgresDBURI string) *gorm.DB {
db, err := gorm.Open(postgres.Open(PostgresDBURI), &gorm.Config{Logger: logger.NewGormLogger()})
if err != nil {
panic(err)
}
return db
}