package initialize import ( "fmt" "os" "shop-api/global" "shop-api/initialize/internal" "shop-api/model" "go.uber.org/zap" "gorm.io/driver/mysql" "gorm.io/gorm" ) //@function: Gorm //@description: 初始化数据库并产生数据库全局变量 //@return: *gorm.DB func Gorm() *gorm.DB { switch global.MG_CONFIG.System.DbType { case "mysql": return GormMysql() default: return GormMysql() } } // MysqlTables //@function: MysqlTables //@description: 注册数据库表专用 //@param: db *gorm.DB func MysqlTables(db *gorm.DB) { err := db.AutoMigrate( model.Account{}, model.Address{}, model.Bill{}, //model.InfluencerUser{}, model.Order{}, model.OrderAddress{}, //model.OrderCommod{}, model.OrderGoods{}, model.OrderGoodsSpecs{}, //model.CustomerUser{}, model.TbGoods{}, model.TbGoodsSpecs{}, model.Wallet{}, model.JwtBlacklist{}, //model.SysDictionary{}, //model.SysDictionaryDetail{}, //model.ExaFileUploadAndDownload{}, //model.ExaFile{}, //model.ExaFileChunk{}, //model.ExaCustomer{}, //model.ExaSimpleUploader{}, // Code generated by pure Begin; DO NOT EDIT. // Code generated by pure End; DO NOT EDIT. model.Mission{}, model.MissionClaimAddress{}, model.CollectionMission{}, model.CollectionGoods{}, model.PaypalWebhook{}, model.MissionClaimWorks{}, model.MissionClaimOrder{}, model.MissionClaimOrderGoods{}, model.Internationalization{}, model.User{}, model.UserAppeal{}, model.OrderPostSale{}, model.DtStatisticOrder{}, ) if err != nil { global.MG_LOG.Error("register table failed", zap.Any("err", err)) os.Exit(0) } global.MG_LOG.Info("register table success") } // @function: GormMysql // @description: 初始化Mysql数据库 // @return: *gorm.DB func GormMysql() *gorm.DB { m := global.MG_CONFIG.Mysql if m.Dbname == "" { return nil } dsn := m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config mysqlConfig := mysql.Config{ DSN: dsn, // DSN data source name DefaultStringSize: 191, // string 类型字段的默认长度 DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持 DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引 DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列 SkipInitializeWithVersion: false, // 根据版本自动配置 } fmt.Println(m.LogMode) if db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config()); err != nil { // global.GVA_LOG.Error("MySQL启动异常", zap.Any("err", err)) // os.Exit(0) // return nil return nil } else { sqlDB, _ := db.DB() sqlDB.SetMaxIdleConns(m.MaxIdleConns) sqlDB.SetMaxOpenConns(m.MaxOpenConns) return db } }