2024-11-22 16:41:04 +08:00
|
|
|
// Package database define database operation functions
|
|
|
|
|
package database
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"sync"
|
|
|
|
|
|
2025-06-23 16:00:48 +08:00
|
|
|
"modelRT/logger"
|
|
|
|
|
|
2024-11-22 16:41:04 +08:00
|
|
|
"gorm.io/driver/postgres"
|
|
|
|
|
"gorm.io/gorm"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var (
|
|
|
|
|
postgresOnce sync.Once
|
|
|
|
|
_globalPostgresClient *gorm.DB
|
|
|
|
|
)
|
|
|
|
|
|
2024-11-28 15:29:34 +08:00
|
|
|
// GetPostgresDBClient returns the global PostgresDB client.It's safe for concurrent use.
|
|
|
|
|
func GetPostgresDBClient() *gorm.DB {
|
2026-01-30 17:42:50 +08:00
|
|
|
return _globalPostgresClient
|
2024-11-22 16:41:04 +08:00
|
|
|
}
|
|
|
|
|
|
2024-11-28 15:29:34 +08:00
|
|
|
// InitPostgresDBInstance return instance of PostgresDB client
|
2026-01-29 17:00:20 +08:00
|
|
|
func InitPostgresDBInstance(PostgresDBURI string) *gorm.DB {
|
2024-11-22 16:41:04 +08:00
|
|
|
postgresOnce.Do(func() {
|
2026-01-29 17:00:20 +08:00
|
|
|
_globalPostgresClient = initPostgresDBClient(PostgresDBURI)
|
2024-11-22 16:41:04 +08:00
|
|
|
})
|
|
|
|
|
return _globalPostgresClient
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// initPostgresDBClient return successfully initialized PostgresDB client
|
2026-01-29 17:00:20 +08:00
|
|
|
func initPostgresDBClient(PostgresDBURI string) *gorm.DB {
|
2025-06-23 16:00:48 +08:00
|
|
|
db, err := gorm.Open(postgres.Open(PostgresDBURI), &gorm.Config{Logger: logger.NewGormLogger()})
|
2024-11-22 16:41:04 +08:00
|
|
|
if err != nil {
|
|
|
|
|
panic(err)
|
|
|
|
|
}
|
|
|
|
|
return db
|
|
|
|
|
}
|