- Replace global variable pattern with proper dependency injection - Add uber-go/fx for automatic dependency resolution - Refactor all services and handlers to use constructor injection - Eliminate fragile initialization order dependencies - Improve testability and modularity - Add structured logging with zap Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
55 lines
1.1 KiB
Go
55 lines
1.1 KiB
Go
package database
|
|
|
|
import (
|
|
"CatsOfMastodonBotGo/internal/config"
|
|
"CatsOfMastodonBotGo/internal/domain"
|
|
"fmt"
|
|
"os"
|
|
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func Connect(cfg *config.Config) (*gorm.DB, error) {
|
|
var db *gorm.DB
|
|
var err error = nil
|
|
|
|
if cfg.DBEngine == "sqlite" {
|
|
_, err = os.ReadDir("data")
|
|
if err != nil {
|
|
err = os.Mkdir("data", 0755)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
db, err = gorm.Open(sqlite.Open("data/caom.db"), &gorm.Config{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
} else {
|
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
|
cfg.DBUser,
|
|
cfg.DBPassword,
|
|
cfg.DBHost,
|
|
cfg.DBPort,
|
|
cfg.DBName)
|
|
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sqlDB.SetMaxOpenConns(100)
|
|
sqlDB.SetMaxIdleConns(10)
|
|
}
|
|
|
|
// Migrate the schema
|
|
if err := db.AutoMigrate(&domain.Post{}, &domain.MediaAttachment{}, &domain.Account{}); err != nil {
|
|
return nil, err
|
|
}
|
|
return db, nil
|
|
} |