From bc2cb532871187b352f4564a85af8a92b8564c53 Mon Sep 17 00:00:00 2001 From: yanweidong Date: Thu, 18 Sep 2025 13:56:58 +0800 Subject: [PATCH] =?UTF-8?q?=20database=20=E6=96=B0=E5=A2=9E=20new,MigrateT?= =?UTF-8?q?ables?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- database/new.go | 88 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 database/new.go diff --git a/database/new.go b/database/new.go new file mode 100644 index 0000000..191eae7 --- /dev/null +++ b/database/new.go @@ -0,0 +1,88 @@ +package database + +import ( + "git.apinb.com/bsm-sdk/core/database/sql" + "git.apinb.com/bsm-sdk/core/types" + "git.apinb.com/bsm-sdk/core/vars" + "gorm.io/driver/mysql" + "gorm.io/gorm" +) + +var ( + MigrateTables []any +) + +// NewMysql 创建MySQL数据库服务 +func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) { + //set connection default val. + if options == nil { + options = &types.SqlOptions{ + MaxIdleConns: vars.SqlOptionMaxIdleConns, + MaxOpenConns: vars.SqlOptionMaxIdleConns, + ConnMaxLifetime: vars.SqlOptionConnMaxLifetime, + LogStdout: false, + Debug: true, + } + } + + gormDb, err = gorm.Open(mysql.Open(dsn[0]), &gorm.Config{ + SkipDefaultTransaction: true, + }) + if err != nil { + return nil, err + } + + if options.Debug { + gormDb = gormDb.Debug() + } + + // 获取通用数据库对象 sql.DB ,然后使用其提供的功能 + sqlDB, _ := gormDb.DB() + // SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。 + sqlDB.SetMaxIdleConns(options.MaxIdleConns) + // SetMaxOpenConns 设置打开数据库连接的最大数量。 + sqlDB.SetMaxOpenConns(options.MaxOpenConns) + // SetConnMaxLifetime 设置了连接可复用的最大时间。 + sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime) + + if len(MigrateTables) > 0 { + err = gormDb.AutoMigrate(MigrateTables...) + if err != nil { + return nil, err + } + } + + return gormDb, nil +} + +// NewPostgres 创建PostgreSQL数据库服务 +func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) { + //set connection default val. + if options == nil { + options = &types.SqlOptions{ + MaxIdleConns: vars.SqlOptionMaxIdleConns, + MaxOpenConns: vars.SqlOptionMaxIdleConns, + ConnMaxLifetime: vars.SqlOptionConnMaxLifetime, + LogStdout: false, + Debug: true, + } + } + + gormDb, err = sql.NewPostgreSql(dsn[0], options) + if err != nil { + return nil, err + } + + if options.Debug { + gormDb = gormDb.Debug() + } + + if len(MigrateTables) > 0 { + err = gormDb.AutoMigrate(MigrateTables...) + if err != nil { + return nil, err + } + } + + return +}