47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
// Package database define database operation functions
|
|
package database
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
"time"
|
|
|
|
"modelRT/logger"
|
|
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var (
|
|
postgresOnce sync.Once
|
|
_globalPostgresClient *gorm.DB
|
|
_globalPostgresMu sync.RWMutex
|
|
)
|
|
|
|
// GetPostgresDBClient returns the global PostgresDB client.It's safe for concurrent use.
|
|
func GetPostgresDBClient() *gorm.DB {
|
|
_globalPostgresMu.RLock()
|
|
client := _globalPostgresClient
|
|
_globalPostgresMu.RUnlock()
|
|
return client
|
|
}
|
|
|
|
// InitPostgresDBInstance return instance of PostgresDB client
|
|
func InitPostgresDBInstance(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{Logger: logger.NewGormLogger()})
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return db
|
|
}
|