refactor(database): 重构数据库初始化逻辑

移除 NewDatabase 函数中的 Init 参数,改用 InitFunc 变量进行初始化操作。
更新 MigrateTables 附近的注释,明确说明 InitFunc 的用途。
删除函数内对 Init 参数的执行逻辑,确保代码简洁性。
```
This commit is contained in:
yanweidong 2025-09-23 11:28:33 +08:00
parent cf0ee224f7
commit 2f57edd277
2 changed files with 21 additions and 6 deletions

View File

@ -15,11 +15,13 @@ import (
var ( var (
// MigrateTables holds the tables that need to be auto-migrated on database initialization // MigrateTables holds the tables that need to be auto-migrated on database initialization
MigrateTables []any MigrateTables []any
// Init is an optional initialization function that can be executed after database connection is established
InitFunc *func() error = nil
) )
// NewDatabase creates a new database connection based on the provided driver type // NewDatabase creates a new database connection based on the provided driver type
// It supports both MySQL and PostgreSQL databases // It supports both MySQL and PostgreSQL databases
func NewDatabase(driver string, dsn []string, options *types.SqlOptions, Init *func()) (db *gorm.DB, err error) { func NewDatabase(driver string, dsn []string, options *types.SqlOptions) (db *gorm.DB, err error) {
driver = strings.ToLower(driver) driver = strings.ToLower(driver)
switch driver { switch driver {
case "mysql": case "mysql":
@ -34,11 +36,6 @@ func NewDatabase(driver string, dsn []string, options *types.SqlOptions, Init *f
return nil, err return nil, err
} }
// Execute the Init function if it's not nil
if Init != nil {
(*Init)()
}
return db, nil return db, nil
} }

18
with/init.go Normal file
View File

@ -0,0 +1,18 @@
package with
import (
"git.apinb.com/bsm-sdk/core/database"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/print"
)
func InitData() {
// Execute the Init function if it's not nil
if database.InitFunc != nil {
err := (*database.InitFunc)()
if err != nil {
print.Error(errcode.ErrEtcd.Error())
panic(err)
}
}
}