From 2f57edd2773e5ea657862616efe13d21845302ae Mon Sep 17 00:00:00 2001 From: yanweidong Date: Tue, 23 Sep 2025 11:28:33 +0800 Subject: [PATCH] =?UTF-8?q?```=20refactor(database):=20=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E5=88=9D=E5=A7=8B=E5=8C=96=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 移除 NewDatabase 函数中的 Init 参数,改用 InitFunc 变量进行初始化操作。 更新 MigrateTables 附近的注释,明确说明 InitFunc 的用途。 删除函数内对 Init 参数的执行逻辑,确保代码简洁性。 ``` --- database/new.go | 9 +++------ with/init.go | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 6 deletions(-) create mode 100644 with/init.go diff --git a/database/new.go b/database/new.go index 1d0fd19..4baf740 100644 --- a/database/new.go +++ b/database/new.go @@ -15,11 +15,13 @@ import ( var ( // MigrateTables holds the tables that need to be auto-migrated on database initialization 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 // 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) switch driver { case "mysql": @@ -34,11 +36,6 @@ func NewDatabase(driver string, dsn []string, options *types.SqlOptions, Init *f return nil, err } - // Execute the Init function if it's not nil - if Init != nil { - (*Init)() - } - return db, nil } diff --git a/with/init.go b/with/init.go new file mode 100644 index 0000000..1b60b68 --- /dev/null +++ b/with/init.go @@ -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) + } + } +}