github.com/glide-im/glide@v1.6.0/internal/pkg/db/mysql.go (about)

     1  package db
     2  
     3  import (
     4  	"fmt"
     5  	"gorm.io/driver/mysql"
     6  	"gorm.io/gorm"
     7  	"gorm.io/gorm/schema"
     8  	"time"
     9  )
    10  
    11  var DB *gorm.DB
    12  
    13  type MySQLConfig struct {
    14  	Host           string
    15  	Port           int
    16  	User           string
    17  	Password       string
    18  	Database       string
    19  	Charset        string
    20  	MaxOpenConn    int
    21  	MaxIdleConn    int
    22  	MaxLifeTimeMin int
    23  }
    24  
    25  func Init(mysqlConf *MySQLConfig, redisConf *RedisConfig) error {
    26  
    27  	if mysqlConf != nil {
    28  		err := initMySQL(mysqlConf)
    29  		if err != nil {
    30  			return err
    31  		}
    32  	}
    33  	if redisConf != nil {
    34  		initRedis(redisConf)
    35  	}
    36  	return nil
    37  }
    38  
    39  func initMySQL(mysqlConf *MySQLConfig) error {
    40  
    41  	url := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=true",
    42  		mysqlConf.User, mysqlConf.Password, mysqlConf.Host, mysqlConf.Port, mysqlConf.Database, mysqlConf.Charset)
    43  
    44  	var err error
    45  	DB, err = gorm.Open(mysql.Open(url), &gorm.Config{
    46  		NamingStrategy: schema.NamingStrategy{
    47  			TablePrefix:   "im_",
    48  			SingularTable: true,
    49  			//NameReplacer:  nil,
    50  			//NoLowerCase:   false,
    51  		},
    52  	})
    53  	if err != nil {
    54  		return err
    55  	}
    56  	db, err := DB.DB()
    57  	if err != nil {
    58  		return err
    59  	}
    60  	if mysqlConf.MaxOpenConn > 0 {
    61  		db.SetMaxOpenConns(mysqlConf.MaxOpenConn)
    62  	}
    63  	if mysqlConf.MaxLifeTimeMin > 0 {
    64  		db.SetConnMaxLifetime(time.Duration(mysqlConf.MaxLifeTimeMin) * time.Minute)
    65  	}
    66  	if mysqlConf.MaxIdleConn > 0 {
    67  		db.SetMaxIdleConns(mysqlConf.MaxIdleConn)
    68  	}
    69  	return nil
    70  }