44 lines
866 B
Go
44 lines
866 B
Go
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
|
|
}
|