PowerEngine/modelRT/database/postgres_init.go

45 lines
1.1 KiB
Go

// Package database define database operation functions
package database
import (
"context"
"sync"
"time"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var (
postgresOnce sync.Once
_globalPostgresClient *gorm.DB
_globalPostgresMu sync.RWMutex
)
// PostgresDBClient returns the global PostgresDB client.It's safe for concurrent use.
func PostgresDBClient() *gorm.DB {
_globalPostgresMu.RLock()
client := _globalPostgresClient
_globalPostgresMu.RUnlock()
return client
}
// GetPostgresDBInstance return instance of PostgresDB client
func GetPostgresDBInstance(ctx context.Context, PostgresDBURI string) *gorm.DB {
postgresOnce.Do(func() {
_globalPostgresClient = initPostgresDBClient(ctx, PostgresDBURI)
})
return _globalPostgresClient
}
// initPostgresDBClient return successfully initialized PostgresDB client
func initPostgresDBClient(ctx context.Context, PostgresDBURI string) *gorm.DB {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
db, err := gorm.Open(postgres.Open(PostgresDBURI), &gorm.Config{})
if err != nil {
panic(err)
}
return db
}