feat(database): 自动迁移表结构并优化数据库初始化函数

将 `AutoMigrate` 逻辑从各数据库初始化方法中提取至统一的 `NewDatabase` 方法内,
避免重复代码。同时修改 `Databases`、`Etcd`、`Memory` 和 `RedisCache` 函数签名,
使其返回实例而非通过参数传递,提高代码可读性和一致性。
```
This commit is contained in:
2025-09-23 16:17:03 +08:00
parent 518c237061
commit 21716c4340
5 changed files with 17 additions and 20 deletions

View File

@@ -34,6 +34,14 @@ func NewDatabase(driver string, dsn []string, options *types.SqlOptions) (db *go
return nil, err
}
// auto migrate table.
if len(MigrateTables) > 0 {
err = db.AutoMigrate(MigrateTables...)
if err != nil {
return nil, err
}
}
return db, nil
}
@@ -74,13 +82,6 @@ func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err err
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)
if len(MigrateTables) > 0 {
err = gormDb.AutoMigrate(MigrateTables...)
if err != nil {
return nil, err
}
}
return gormDb, nil
}
@@ -119,12 +120,5 @@ func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)
if len(MigrateTables) > 0 {
err = gormDb.AutoMigrate(MigrateTables...)
if err != nil {
return nil, err
}
}
return
}