new file structure & koneksi ke DB
This commit is contained in:
43
internal/database/database.go
Normal file
43
internal/database/database.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// DB is the database instance
|
||||
var DB *sqlx.DB
|
||||
|
||||
// Initialize creates and configures the database connection
|
||||
func Initialize(dsn string, maxOpenConns, maxIdleConns int, connMaxLifetime time.Duration) error {
|
||||
var err error
|
||||
|
||||
// Connect to the database
|
||||
DB, err = sqlx.Connect("mysql", dsn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to connect to database: %w", err)
|
||||
}
|
||||
|
||||
// Configure connection pool
|
||||
DB.SetMaxOpenConns(maxOpenConns)
|
||||
DB.SetMaxIdleConns(maxIdleConns)
|
||||
DB.SetConnMaxLifetime(connMaxLifetime)
|
||||
|
||||
// Check connection
|
||||
if err := DB.Ping(); err != nil {
|
||||
return fmt.Errorf("failed to ping database: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close closes the database connection
|
||||
func Close() error {
|
||||
if DB != nil {
|
||||
return DB.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user