init project

This commit is contained in:
2025-01-31 11:04:28 +07:00
parent 562c727ed6
commit 66c9f17dde
21 changed files with 725 additions and 57 deletions

View File

@@ -2,7 +2,6 @@ package database
import (
"context"
"database/sql"
"fmt"
"log"
"os"
@@ -11,31 +10,27 @@ import (
_ "github.com/jackc/pgx/v5/stdlib"
_ "github.com/joho/godotenv/autoload"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
// Service represents a service that interacts with a database.
type Service interface {
// Health returns a map of health status information.
// The keys and values in the map are service-specific.
Health() map[string]string
// Close terminates the database connection.
// It returns an error if the connection cannot be closed.
Close() error
GetDB() *gorm.DB
}
type service struct {
db *sql.DB
db *gorm.DB
}
var (
database = os.Getenv("BLUEPRINT_DB_DATABASE")
password = os.Getenv("BLUEPRINT_DB_PASSWORD")
username = os.Getenv("BLUEPRINT_DB_USERNAME")
port = os.Getenv("BLUEPRINT_DB_PORT")
host = os.Getenv("BLUEPRINT_DB_HOST")
schema = os.Getenv("BLUEPRINT_DB_SCHEMA")
dbInstance *service
hostSimrs = os.Getenv("POSTGRE_DB_HOST")
userNameSimrs = os.Getenv("POSTGRE_DB_USER")
passwordSimrs = os.Getenv("POSTGRE_DB_PASS")
dbNameSimrs = os.Getenv("POSTGRE_DB_NAME")
portSimrs = os.Getenv("POSTGRE_DB_PORT")
dbInstance *service
)
func New() Service {
@@ -43,13 +38,16 @@ func New() Service {
if dbInstance != nil {
return dbInstance
}
connStr := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable&search_path=%s", username, password, host, port, database, schema)
db, err := sql.Open("pgx", connStr)
simrs := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Jakarta", hostSimrs, userNameSimrs, passwordSimrs, dbNameSimrs, portSimrs)
SimrsDB, err := gorm.Open(postgres.Open(simrs), &gorm.Config{})
if err != nil {
log.Fatal(err)
log.Fatal("Failed to connect to SIM database: ", err)
} else {
log.Println("Successfully connected to the database")
}
dbInstance = &service{
db: db,
db: SimrsDB,
}
return dbInstance
}
@@ -57,17 +55,25 @@ func New() Service {
// Health checks the health of the database connection by pinging the database.
// It returns a map with keys indicating various health statistics.
func (s *service) Health() map[string]string {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stats := make(map[string]string)
// Ping the database
err := s.db.PingContext(ctx)
// Ping the database using GORM
db, err := s.db.DB() // Retrieve the underlying sql.DB instance from GORM
if err != nil {
stats["status"] = "down"
stats["error"] = fmt.Sprintf("failed to get sql.DB from GORM: %v", err)
log.Fatalf("failed to get sql.DB from GORM: %v", err) // Log the error and terminate the program
return stats
}
err = db.PingContext(ctx)
if err != nil {
stats["status"] = "down"
stats["error"] = fmt.Sprintf("db down: %v", err)
log.Fatalf(fmt.Sprintf("db down: %v", err)) // Log the error and terminate the program
log.Fatalf("db down: %v", err) // Log the error and terminate the program
return stats
}
@@ -75,8 +81,8 @@ func (s *service) Health() map[string]string {
stats["status"] = "up"
stats["message"] = "It's healthy"
// Get database stats (like open connections, in use, idle, etc.)
dbStats := s.db.Stats()
// Get database stats
dbStats := db.Stats()
stats["open_connections"] = strconv.Itoa(dbStats.OpenConnections)
stats["in_use"] = strconv.Itoa(dbStats.InUse)
stats["idle"] = strconv.Itoa(dbStats.Idle)
@@ -110,6 +116,22 @@ func (s *service) Health() map[string]string {
// If the connection is successfully closed, it returns nil.
// If an error occurs while closing the connection, it returns the error.
func (s *service) Close() error {
log.Printf("Disconnected from database: %s", database)
return s.db.Close()
db, err := s.db.DB() // Retrieve the underlying sql.DB instance from GORM
if err != nil {
log.Printf("Failed to retrieve sql.DB from GORM: %v", err)
return err
}
err = db.Close()
if err != nil {
log.Printf("Error closing the database connection: %v", err)
return err
}
log.Printf("Disconnected from database successfully")
return nil
}
func (s *service) GetDB() *gorm.DB {
return s.db
}