feat: Refactor database configuration loading and seeding logic for improved clarity and maintainability
This commit is contained in:
@@ -86,12 +86,6 @@ func main() {
|
||||
log.Fatalf("Error migrating database: %v", err)
|
||||
}
|
||||
|
||||
// Seed database with initial data if needed
|
||||
ctx := context.Background()
|
||||
if err := models.SeedDB(ctx); err != nil {
|
||||
log.Fatalf("Error seeding database: %v", err)
|
||||
}
|
||||
|
||||
// Create Gin router
|
||||
r := gin.Default()
|
||||
|
||||
|
||||
+66
-63
@@ -2,56 +2,28 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/timetracker/backend/internal/config"
|
||||
"github.com/timetracker/backend/internal/models"
|
||||
"gorm.io/gorm/logger"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Parse command line flags
|
||||
force := false
|
||||
for _, arg := range os.Args[1:] {
|
||||
if arg == "--force" || arg == "-f" {
|
||||
force = true
|
||||
}
|
||||
}
|
||||
// Parse CLI flags
|
||||
_ = flag.String("config", "", "Path to .env config file")
|
||||
flag.Parse()
|
||||
|
||||
// Get database configuration with sensible defaults
|
||||
dbConfig := models.DefaultDatabaseConfig()
|
||||
|
||||
// Override with environment variables if provided
|
||||
if host := os.Getenv("DB_HOST"); host != "" {
|
||||
dbConfig.Host = host
|
||||
// Load configuration
|
||||
cfg, err := config.LoadConfig()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to load config: %v", err)
|
||||
}
|
||||
if port := os.Getenv("DB_PORT"); port != "" {
|
||||
var portInt int
|
||||
if _, err := fmt.Sscanf(port, "%d", &portInt); err == nil && portInt > 0 {
|
||||
dbConfig.Port = portInt
|
||||
}
|
||||
}
|
||||
if user := os.Getenv("DB_USER"); user != "" {
|
||||
dbConfig.User = user
|
||||
}
|
||||
if password := os.Getenv("DB_PASSWORD"); password != "" {
|
||||
dbConfig.Password = password
|
||||
}
|
||||
if dbName := os.Getenv("DB_NAME"); dbName != "" {
|
||||
dbConfig.DBName = dbName
|
||||
}
|
||||
if sslMode := os.Getenv("DB_SSLMODE"); sslMode != "" {
|
||||
dbConfig.SSLMode = sslMode
|
||||
}
|
||||
|
||||
// Set log level
|
||||
dbConfig.LogLevel = logger.Info
|
||||
|
||||
// Initialize database
|
||||
fmt.Println("Connecting to database...")
|
||||
if err := models.InitDB(dbConfig); err != nil {
|
||||
if err := models.InitDB(cfg.Database); err != nil {
|
||||
log.Fatalf("Error initializing database: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
@@ -59,31 +31,62 @@ func main() {
|
||||
log.Printf("Error closing database connection: %v", err)
|
||||
}
|
||||
}()
|
||||
fmt.Println("✓ Database connection successful")
|
||||
|
||||
// Create context with timeout
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Check if we need to seed (e.g., no companies exist)
|
||||
if !force {
|
||||
var count int64
|
||||
db := models.GetEngine(ctx)
|
||||
if err := db.Model(&models.Company{}).Count(&count).Error; err != nil {
|
||||
log.Fatalf("Error checking if seeding is needed: %v", err)
|
||||
}
|
||||
|
||||
// If data already exists, skip seeding
|
||||
if count > 0 {
|
||||
fmt.Println("Database already contains data. Use --force to override.")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Seed the database
|
||||
fmt.Println("Seeding database with initial data...")
|
||||
if err := models.SeedDB(ctx); err != nil {
|
||||
// Execute seed operation
|
||||
if err := seedDatabase(context.Background()); err != nil {
|
||||
log.Fatalf("Error seeding database: %v", err)
|
||||
}
|
||||
fmt.Println("✓ Database seeding completed successfully")
|
||||
|
||||
log.Println("Database seeding completed successfully")
|
||||
}
|
||||
|
||||
// seedDatabase performs the database seeding operation
|
||||
func seedDatabase(ctx context.Context) error {
|
||||
// Check if seeding is needed
|
||||
var count int64
|
||||
if err := models.GetEngine(ctx).Model(&models.Company{}).Count(&count).Error; err != nil {
|
||||
return fmt.Errorf("error checking if seeding is needed: %w", err)
|
||||
}
|
||||
|
||||
// If data exists, skip seeding
|
||||
if count > 0 {
|
||||
log.Println("Database already contains data, skipping seeding")
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Println("Seeding database with initial data...")
|
||||
|
||||
// Start transaction
|
||||
return models.GetEngine(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// Create default company
|
||||
defaultCompany := models.Company{
|
||||
Name: "Default Company",
|
||||
}
|
||||
if err := tx.Create(&defaultCompany).Error; err != nil {
|
||||
return fmt.Errorf("error creating default company: %w", err)
|
||||
}
|
||||
|
||||
// Create admin user
|
||||
adminUser := models.User{
|
||||
Email: "admin@example.com",
|
||||
Role: models.RoleAdmin,
|
||||
CompanyID: defaultCompany.ID,
|
||||
HourlyRate: 100.0,
|
||||
}
|
||||
|
||||
// Hash password
|
||||
pwData, err := models.HashPassword("Admin@123456")
|
||||
if err != nil {
|
||||
return fmt.Errorf("error hashing password: %w", err)
|
||||
}
|
||||
|
||||
adminUser.Salt = pwData.Salt
|
||||
adminUser.Hash = pwData.Hash
|
||||
|
||||
if err := tx.Create(&adminUser).Error; err != nil {
|
||||
return fmt.Errorf("error creating admin user: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user