modelRT/database/postgres_init.go

43 lines
1.0 KiB
Go
Raw Normal View History

// 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
_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
2026-01-29 17:00:20 +08:00
func InitPostgresDBInstance(PostgresDBURI string) *gorm.DB {
postgresOnce.Do(func() {
2026-01-29 17:00:20 +08:00
_globalPostgresClient = initPostgresDBClient(PostgresDBURI)
})
return _globalPostgresClient
}
// initPostgresDBClient return successfully initialized PostgresDB client
2026-01-29 17:00:20 +08:00
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
}