mysql.go 2.99 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
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/logger"
	"gorm.io/gorm/schema"
	"hilo-socketCenter/common/config"
	"hilo-socketCenter/common/mylogrus"
	"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.Info)
	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)
}