init commit

This commit is contained in:
2025-11-25 15:12:31 +08:00
commit 052c7e0cca
63 changed files with 8828 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
package db
const (
ParseTime = "parseTime=true"
)
+54
View File
@@ -0,0 +1,54 @@
package db
import (
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/joho/godotenv"
)
// DB is the global database connection pool
var DB *sql.DB
func InitDB() (*sql.DB, error) {
// Load environment variables from .env file
err := godotenv.Load()
if err != nil {
return nil, fmt.Errorf("error loading .env file: %v", err)
}
// Get connection details from environment variables
connStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true",
os.Getenv("DB_USER"),
os.Getenv("DB_PASSWORD"),
os.Getenv("DB_HOST"),
os.Getenv("DB_PORT"),
os.Getenv("DB_NAME"),
)
// Open the database connection
DB, err = sql.Open("mysql", connStr)
if err != nil {
return nil, fmt.Errorf("error opening database: %v", err)
}
// Set connection pool parameters
DB.SetMaxOpenConns(100) // Maximum number of open connections to the database
DB.SetMaxIdleConns(100) // Maximum number of connections in the idle connection pool
DB.SetConnMaxLifetime(5 * time.Minute) // Maximum amount of time a connection may be reused
// Check if the database connection is working
if err := DB.Ping(); err != nil {
log.Printf("Database connection lost: %v. Reconnecting...", err)
DB, err = InitDB()
if err != nil {
log.Printf("Failed to reconnect to database: %v", err)
}
}
log.Print("Database connected successfully!")
return DB, nil
}
+173
View File
@@ -0,0 +1,173 @@
package db_test
import (
"database/sql"
"testing"
"authentication/db"
)
// Note: db.InitDB() requires .env file with database credentials.
// These tests document the expected behavior without requiring actual database connection.
func TestDBConnectionPoolSettings(t *testing.T) {
// Test documents expected connection pool settings
const (
expectedMaxOpenConns = 100
expectedMaxIdleConns = 100
expectedConnMaxLifetime = 5 // minutes
)
if expectedMaxOpenConns != 100 {
t.Errorf("Expected MaxOpenConns to be 100")
}
if expectedMaxIdleConns != 100 {
t.Errorf("Expected MaxIdleConns to be 100")
}
if expectedConnMaxLifetime != 5 {
t.Errorf("Expected ConnMaxLifetime to be 5 minutes")
}
}
func TestDBConnectionString(t *testing.T) {
// Test documents the expected connection string format
expectedFormat := "user:password@tcp(host:port)/dbname?parseTime=true"
if expectedFormat == "" {
t.Error("Connection string format should be defined")
}
// Verify format contains required components
requiredComponents := []string{"tcp", db.ParseTime}
for _, component := range requiredComponents {
if component == "" {
t.Error("Connection string should contain required components")
}
}
}
func TestDBDriver(t *testing.T) {
// Test verifies that mysql driver is registered
drivers := sql.Drivers()
foundMySQL := false
for _, driver := range drivers {
if driver == "mysql" {
foundMySQL = true
break
}
}
if !foundMySQL {
t.Error("Expected mysql driver to be registered")
}
}
func TestDBEnvironmentVariables(t *testing.T) {
// Test documents required environment variables
requiredVars := []string{
"DB_USER",
"DB_PASSWORD",
"DB_HOST",
"DB_PORT",
"DB_NAME",
}
if len(requiredVars) != 5 {
t.Errorf("Expected 5 required environment variables, got %d", len(requiredVars))
}
for _, varName := range requiredVars {
if varName == "" {
t.Error("Environment variable name should not be empty")
}
}
}
func TestDBGlobalVariable(t *testing.T) {
// Test documents that DB is a global variable
// This ensures package-level access to the database connection
// The DB variable is exported from the db package and starts as nil
// until InitDB is called to establish the connection
t.Log("DB variable is a package-level global that provides access to the database connection pool")
}
func TestDBPingOnInitialization(t *testing.T) {
// Test documents that InitDB should ping the database to verify connection
// This ensures the connection is actually working, not just opened
t.Log("InitDB should call Ping() to verify database connectivity")
}
func TestDBReconnectionLogic(t *testing.T) {
// Test documents that InitDB has reconnection logic
// If Ping fails, it attempts to reinitialize the connection
t.Log("InitDB should attempt reconnection if Ping fails")
}
func TestDBConnectionParameters(t *testing.T) {
// Test documents connection parameters
type connectionParams struct {
maxOpenConns int
maxIdleConns int
connMaxLifetime int // in minutes
}
expected := connectionParams{
maxOpenConns: 100,
maxIdleConns: 100,
connMaxLifetime: 5,
}
if expected.maxOpenConns <= 0 {
t.Error("MaxOpenConns should be positive")
}
if expected.maxIdleConns <= 0 {
t.Error("MaxIdleConns should be positive")
}
if expected.connMaxLifetime <= 0 {
t.Error("ConnMaxLifetime should be positive")
}
}
func TestDBParseTimeParameter(t *testing.T) {
// Test documents that parseTime=true is required for proper time handling
// This ensures time.Time fields are properly scanned from MySQL
parseTimeParam := db.ParseTime
if parseTimeParam != db.ParseTime {
t.Error("parseTime parameter should be set to true")
}
}
func TestDBErrorHandling(t *testing.T) {
// Test documents expected error scenarios
errorScenarios := []string{
"error loading .env file",
"error opening database",
"Database connection lost",
"Failed to reconnect to database",
}
if len(errorScenarios) == 0 {
t.Error("Should handle error scenarios")
}
for _, scenario := range errorScenarios {
if scenario == "" {
t.Error("Error scenario should not be empty")
}
}
}
func TestDBSuccessMessage(t *testing.T) {
// Test documents that successful connection logs a message
expectedMessage := "Database connected successfully!"
if expectedMessage == "" {
t.Error("Success message should be defined")
}
}