package mysql import ( "fmt" _ "github.com/go-sql-driver/mysql" //加载mysql驱动 _ "github.com/joho/godotenv/autoload" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/schema" "hilo-socketCenter/common/config" "log" "net/url" "time" ) var Db *gorm.DB func init() { var err error mysqlConfigData := config.GetConfigMysql() options := "?charset=utf8mb4&parseTime=True&loc=Local&time_zone=" + url.QueryEscape("'+8:00'") dsn := "" + mysqlConfigData.MYSQL_USERNAME + ":" + mysqlConfigData.MYSQL_PASSWORD + "@(" + mysqlConfigData.MYSQL_HOST + ")/" + mysqlConfigData.MYSQL_DB + options //sqlLogger := logger.Default.LogMode(logger.Error) // 这个服务不需要 //if file := mylogrus.GetSqlLog(); file != nil { // //sqlLogger = logger.New(log.New(file, "\r\n", log.Ldate|log.Lmicroseconds), logger.Config{ // sqlLogger = MyNew(log.New(file, "", log.Ldate|log.Lmicroseconds), logger.Config{ // SlowThreshold: 200 * time.Millisecond, // LogLevel: logger.Info, // Colorful: false, // }) //} Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{ //Logger: sqlLogger, NamingStrategy: schema.NamingStrategy{ SingularTable: true, }, }) if err != nil { log.Fatalf("mysql connect error %v", err) } else { log.Println("mysql connect success") } if Db.Error != nil { fmt.Printf("database error %v", Db.Error) } if d, err := Db.DB(); err == nil { d.SetConnMaxLifetime(time.Minute * 30) // 连接可复用的最大时间。 d.SetMaxIdleConns(200) // 空闲连接数 } //移除entity的tableName /* gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string { return strings.Replace(defaultTableName, "_entities", "", 1) }*/ //Db.Callback().Create().Replace("gorm:update_time_stamp", updateTimeStampForCreateCallback) //Db.Callback().Update().Replace("gorm:update_time_stamp", updateTimeStampForUpdateCallback) /* Db.SingularTable(true) Db.DB().SetMaxIdleConns(10) Db.DB().SetMaxOpenConns(100) Db.LogMode(true) Db.SetLogger(log.New(os.Stdout, "\r\n", 0))*/ } /*func updateTimeStampForUpdateCallback(scope *gorm.Scope) { if _, ok := scope.Get("gorm:update_column"); !ok { _ = scope.SetColumn("UpdatedTime", time.Now().Unix()) } } func updateTimeStampForCreateCallback(scope *gorm.Scope) { if !scope.HasError() { nowTime := time.Now().Unix() if createTimeField, ok := scope.FieldByName("CreatedTime"); ok { if createTimeField.IsBlank { _ = createTimeField.Set(nowTime) } } if modifyTimeField, ok := scope.FieldByName("UpdatedTime"); ok { if modifyTimeField.IsBlank { _ = modifyTimeField.Set(nowTime) } } } }*/ func HasTable(tableName string) bool { //var num int //err := Db.Exec("SELECT COUNT(*) num FROM information_schema.TABLES WHERE table_name =%s;", tableName).Pluck("num", &num).Error //if err != nil { // mylogrus.MyLog.Errorf("HasTable err: %v, stack: %v", err, string(debug.Stack())) // return //} //if num > 0 { // has = true //} return Db.Migrator().HasTable(tableName) }